github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/image/jpeg/huffman.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package jpeg
     6  
     7  import "io"
     8  
     9  // Each code is at most 16 bits long.
    10  const maxCodeLength = 16
    11  
    12  // Each decoded value is a uint8, so there are at most 256 such values.
    13  const maxNumValues = 256
    14  
    15  // Bit stream for the Huffman decoder.
    16  // The n least significant bits of a form the unread bits, to be read in MSB to LSB order.
    17  type bits struct {
    18  	a uint32 // accumulator.
    19  	m uint32 // mask. m==1<<(n-1) when n>0, with m==0 when n==0.
    20  	n int    // the number of unread bits in a.
    21  }
    22  
    23  // Huffman table decoder, specified in section C.
    24  type huffman struct {
    25  	l        [maxCodeLength]int
    26  	length   int                 // sum of l[i].
    27  	val      [maxNumValues]uint8 // the decoded values, as sorted by their encoding.
    28  	size     [maxNumValues]int   // size[i] is the number of bits to encode val[i].
    29  	code     [maxNumValues]int   // code[i] is the encoding of val[i].
    30  	minCode  [maxCodeLength]int  // min codes of length i, or -1 if no codes of that length.
    31  	maxCode  [maxCodeLength]int  // max codes of length i, or -1 if no codes of that length.
    32  	valIndex [maxCodeLength]int  // index into val of minCode[i].
    33  }
    34  
    35  // Reads bytes from the io.Reader to ensure that bits.n is at least n.
    36  func (d *decoder) ensureNBits(n int) error {
    37  	for d.b.n < n {
    38  		c, err := d.r.ReadByte()
    39  		if err != nil {
    40  			return err
    41  		}
    42  		d.b.a = d.b.a<<8 | uint32(c)
    43  		d.b.n += 8
    44  		if d.b.m == 0 {
    45  			d.b.m = 1 << 7
    46  		} else {
    47  			d.b.m <<= 8
    48  		}
    49  		// Byte stuffing, specified in section F.1.2.3.
    50  		if c == 0xff {
    51  			c, err = d.r.ReadByte()
    52  			if err != nil {
    53  				return err
    54  			}
    55  			if c != 0x00 {
    56  				return FormatError("missing 0xff00 sequence")
    57  			}
    58  		}
    59  	}
    60  	return nil
    61  }
    62  
    63  // The composition of RECEIVE and EXTEND, specified in section F.2.2.1.
    64  func (d *decoder) receiveExtend(t uint8) (int32, error) {
    65  	if d.b.n < int(t) {
    66  		if err := d.ensureNBits(int(t)); err != nil {
    67  			return 0, err
    68  		}
    69  	}
    70  	d.b.n -= int(t)
    71  	d.b.m >>= t
    72  	s := int32(1) << t
    73  	x := int32(d.b.a>>uint8(d.b.n)) & (s - 1)
    74  	if x < s>>1 {
    75  		x += ((-1) << t) + 1
    76  	}
    77  	return x, nil
    78  }
    79  
    80  // Processes a Define Huffman Table marker, and initializes a huffman struct from its contents.
    81  // Specified in section B.2.4.2.
    82  func (d *decoder) processDHT(n int) error {
    83  	for n > 0 {
    84  		if n < 17 {
    85  			return FormatError("DHT has wrong length")
    86  		}
    87  		_, err := io.ReadFull(d.r, d.tmp[0:17])
    88  		if err != nil {
    89  			return err
    90  		}
    91  		tc := d.tmp[0] >> 4
    92  		if tc > maxTc {
    93  			return FormatError("bad Tc value")
    94  		}
    95  		th := d.tmp[0] & 0x0f
    96  		if th > maxTh || !d.progressive && th > 1 {
    97  			return FormatError("bad Th value")
    98  		}
    99  		h := &d.huff[tc][th]
   100  
   101  		// Read l and val (and derive length).
   102  		h.length = 0
   103  		for i := 0; i < maxCodeLength; i++ {
   104  			h.l[i] = int(d.tmp[i+1])
   105  			h.length += h.l[i]
   106  		}
   107  		if h.length == 0 {
   108  			return FormatError("Huffman table has zero length")
   109  		}
   110  		if h.length > maxNumValues {
   111  			return FormatError("Huffman table has excessive length")
   112  		}
   113  		n -= h.length + 17
   114  		if n < 0 {
   115  			return FormatError("DHT has wrong length")
   116  		}
   117  		_, err = io.ReadFull(d.r, h.val[0:h.length])
   118  		if err != nil {
   119  			return err
   120  		}
   121  
   122  		// Derive size.
   123  		k := 0
   124  		for i := 0; i < maxCodeLength; i++ {
   125  			for j := 0; j < h.l[i]; j++ {
   126  				h.size[k] = i + 1
   127  				k++
   128  			}
   129  		}
   130  
   131  		// Derive code.
   132  		code := 0
   133  		size := h.size[0]
   134  		for i := 0; i < h.length; i++ {
   135  			if size != h.size[i] {
   136  				code <<= uint8(h.size[i] - size)
   137  				size = h.size[i]
   138  			}
   139  			h.code[i] = code
   140  			code++
   141  		}
   142  
   143  		// Derive minCode, maxCode, and valIndex.
   144  		k = 0
   145  		index := 0
   146  		for i := 0; i < maxCodeLength; i++ {
   147  			if h.l[i] == 0 {
   148  				h.minCode[i] = -1
   149  				h.maxCode[i] = -1
   150  				h.valIndex[i] = -1
   151  			} else {
   152  				h.minCode[i] = k
   153  				h.maxCode[i] = k + h.l[i] - 1
   154  				h.valIndex[i] = index
   155  				k += h.l[i]
   156  				index += h.l[i]
   157  			}
   158  			k <<= 1
   159  		}
   160  	}
   161  	return nil
   162  }
   163  
   164  // Returns the next Huffman-coded value from the bit stream, decoded according to h.
   165  // TODO(nigeltao): This decoding algorithm is simple, but slow. A lookahead table, instead of always
   166  // peeling off only 1 bit at time, ought to be faster.
   167  func (d *decoder) decodeHuffman(h *huffman) (uint8, error) {
   168  	if h.length == 0 {
   169  		return 0, FormatError("uninitialized Huffman table")
   170  	}
   171  	for i, code := 0, 0; i < maxCodeLength; i++ {
   172  		if d.b.n == 0 {
   173  			if err := d.ensureNBits(1); err != nil {
   174  				return 0, err
   175  			}
   176  		}
   177  		if d.b.a&d.b.m != 0 {
   178  			code |= 1
   179  		}
   180  		d.b.n--
   181  		d.b.m >>= 1
   182  		if code <= h.maxCode[i] {
   183  			return h.val[h.valIndex[i]+code-h.minCode[i]], nil
   184  		}
   185  		code <<= 1
   186  	}
   187  	return 0, FormatError("bad Huffman code")
   188  }
   189  
   190  func (d *decoder) decodeBit() (bool, error) {
   191  	if d.b.n == 0 {
   192  		if err := d.ensureNBits(1); err != nil {
   193  			return false, err
   194  		}
   195  	}
   196  	ret := d.b.a&d.b.m != 0
   197  	d.b.n--
   198  	d.b.m >>= 1
   199  	return ret, nil
   200  }
   201  
   202  func (d *decoder) decodeBits(n int) (uint32, error) {
   203  	if d.b.n < n {
   204  		if err := d.ensureNBits(n); err != nil {
   205  			return 0, err
   206  		}
   207  	}
   208  	ret := d.b.a >> uint(d.b.n-n)
   209  	ret &= (1 << uint(n)) - 1
   210  	d.b.n -= n
   211  	d.b.m >>= uint(n)
   212  	return ret, nil
   213  }