github.com/bluenviron/mediacommon@v1.9.3/pkg/codecs/jpeg/define_quantization_table.go (about)

     1  package jpeg
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  // QuantizationTable is a DQT quantization table.
     8  type QuantizationTable struct {
     9  	ID        uint8
    10  	Precision uint8
    11  	Data      []byte
    12  }
    13  
    14  // DefineQuantizationTable is a DQT marker.
    15  type DefineQuantizationTable struct {
    16  	Tables []QuantizationTable
    17  }
    18  
    19  // Unmarshal decodes the marker.
    20  func (m *DefineQuantizationTable) Unmarshal(buf []byte) error {
    21  	for len(buf) != 0 {
    22  		id := buf[0] & 0x0F
    23  		precision := buf[0] >> 4
    24  		buf = buf[1:]
    25  		if precision != 0 {
    26  			return fmt.Errorf("Precision %d is not supported", precision)
    27  		}
    28  
    29  		if len(buf) < 64 {
    30  			return fmt.Errorf("image is too short")
    31  		}
    32  
    33  		m.Tables = append(m.Tables, QuantizationTable{
    34  			ID:        id,
    35  			Precision: precision,
    36  			Data:      buf[:64],
    37  		})
    38  		buf = buf[64:]
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  // Marshal encodes the marker.
    45  func (m DefineQuantizationTable) Marshal(buf []byte) []byte {
    46  	buf = append(buf, []byte{0xFF, MarkerDefineQuantizationTable}...)
    47  
    48  	// length
    49  	s := 2
    50  	for _, t := range m.Tables {
    51  		s += 1 + len(t.Data)
    52  	}
    53  	buf = append(buf, []byte{byte(s >> 8), byte(s)}...)
    54  
    55  	for _, t := range m.Tables {
    56  		buf = append(buf, []byte{(t.ID)}...)
    57  		buf = append(buf, t.Data...)
    58  	}
    59  
    60  	return buf
    61  }