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.
5 // Package jpeg implements a JPEG image decoder and encoder.
7 // JPEG is defined in ITU-T T.81: http://www.w3.org/Graphics/JPEG/itu-t81.pdf.
19 // TODO(nigeltao): fix up the doc comment style so that sentences start with
20 // the name of the type or function that they annotate.
22 // A FormatError reports that the input is not a valid JPEG.
23 type FormatError string
25 func (e FormatError) String() string { return "invalid JPEG format: " + string(e) }
27 // An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.
28 type UnsupportedError string
30 func (e UnsupportedError) String() string { return "unsupported JPEG feature: " + string(e) }
32 // Component specification, specified in section B.2.2.
33 type component struct {
34 h int // Horizontal sampling factor.
35 v int // Vertical sampling factor.
36 c uint8 // Component identifier.
37 tq uint8 // Quantization table destination selector.
40 type block [blockSize]int
43 blockSize = 64 // A DCT block is 8x8.
51 // A grayscale JPEG image has only a Y component.
53 // A color JPEG image has Y, Cb and Cr components.
56 // We only support 4:4:4, 4:2:2 and 4:2:0 downsampling, and therefore the
57 // number of luma samples per chroma sample is at most 2 in the horizontal
58 // and 2 in the vertical direction.
64 soiMarker = 0xd8 // Start Of Image.
65 eoiMarker = 0xd9 // End Of Image.
66 sof0Marker = 0xc0 // Start Of Frame (Baseline).
67 sof2Marker = 0xc2 // Start Of Frame (Progressive).
68 dhtMarker = 0xc4 // Define Huffman Table.
69 dqtMarker = 0xdb // Define Quantization Table.
70 sosMarker = 0xda // Start Of Scan.
71 driMarker = 0xdd // Define Restart Interval.
72 rst0Marker = 0xd0 // ReSTart (0).
73 rst7Marker = 0xd7 // ReSTart (7).
74 app0Marker = 0xe0 // APPlication specific (0).
75 app15Marker = 0xef // APPlication specific (15).
76 comMarker = 0xfe // COMment.
79 // Maps from the zig-zag ordering to the natural ordering.
80 var unzig = [blockSize]int{
81 0, 1, 8, 16, 9, 2, 3, 10,
82 17, 24, 32, 25, 18, 11, 4, 5,
83 12, 19, 26, 33, 40, 48, 41, 34,
84 27, 20, 13, 6, 7, 14, 21, 28,
85 35, 42, 49, 56, 57, 50, 43, 36,
86 29, 22, 15, 23, 30, 37, 44, 51,
87 58, 59, 52, 45, 38, 31, 39, 46,
88 53, 60, 61, 54, 47, 55, 62, 63,
91 // If the passed in io.Reader does not also have ReadByte, then Decode will introduce its own buffering.
92 type Reader interface {
94 ReadByte() (c byte, err os.Error)
102 ri int // Restart Interval.
104 comp [nColorComponent]component
105 huff [maxTc + 1][maxTh + 1]huffman
106 quant [maxTq + 1]block
111 // Reads and ignores the next n bytes.
112 func (d *decoder) ignore(n int) os.Error {
118 _, err := io.ReadFull(d.r, d.tmp[0:m])
127 // Specified in section B.2.2.
128 func (d *decoder) processSOF(n int) os.Error {
130 case 6 + 3*nGrayComponent:
131 d.nComp = nGrayComponent
132 case 6 + 3*nColorComponent:
133 d.nComp = nColorComponent
135 return UnsupportedError("SOF has wrong length")
137 _, err := io.ReadFull(d.r, d.tmp[:n])
141 // We only support 8-bit precision.
143 return UnsupportedError("precision")
145 d.height = int(d.tmp[1])<<8 + int(d.tmp[2])
146 d.width = int(d.tmp[3])<<8 + int(d.tmp[4])
147 if int(d.tmp[5]) != d.nComp {
148 return UnsupportedError("SOF has wrong number of image components")
150 for i := 0; i < d.nComp; i++ {
152 d.comp[i].h = int(hv >> 4)
153 d.comp[i].v = int(hv & 0x0f)
154 d.comp[i].c = d.tmp[6+3*i]
155 d.comp[i].tq = d.tmp[8+3*i]
156 if d.nComp == nGrayComponent {
159 // For color images, we only support 4:4:4, 4:2:2 or 4:2:0 chroma
160 // downsampling ratios. This implies that the (h, v) values for the Y
161 // component are either (1, 1), (2, 1) or (2, 2), and the (h, v)
162 // values for the Cr and Cb components must be (1, 1).
164 if hv != 0x11 && hv != 0x21 && hv != 0x22 {
165 return UnsupportedError("luma downsample ratio")
167 } else if hv != 0x11 {
168 return UnsupportedError("chroma downsample ratio")
174 // Specified in section B.2.4.1.
175 func (d *decoder) processDQT(n int) os.Error {
176 const qtLength = 1 + blockSize
177 for ; n >= qtLength; n -= qtLength {
178 _, err := io.ReadFull(d.r, d.tmp[0:qtLength])
184 return UnsupportedError("bad Pq value")
186 tq := d.tmp[0] & 0x0f
188 return FormatError("bad Tq value")
190 for i := range d.quant[tq] {
191 d.quant[tq][i] = int(d.tmp[i+1])
195 return FormatError("DQT has wrong length")
200 // makeImg allocates and initializes the destination image.
201 func (d *decoder) makeImg(h0, v0, mxx, myy int) {
202 if d.nComp == nGrayComponent {
203 m := image.NewGray(image.Rect(0, 0, 8*mxx, 8*myy))
204 d.img1 = m.SubImage(image.Rect(0, 0, d.width, d.height)).(*image.Gray)
207 var subsampleRatio ycbcr.SubsampleRatio
211 subsampleRatio = ycbcr.SubsampleRatio444
213 subsampleRatio = ycbcr.SubsampleRatio422
215 subsampleRatio = ycbcr.SubsampleRatio420
219 b := make([]byte, mxx*myy*(1*8*8*n+2*8*8))
220 d.img3 = &ycbcr.YCbCr{
221 Y: b[mxx*myy*(0*8*8*n+0*8*8) : mxx*myy*(1*8*8*n+0*8*8)],
222 Cb: b[mxx*myy*(1*8*8*n+0*8*8) : mxx*myy*(1*8*8*n+1*8*8)],
223 Cr: b[mxx*myy*(1*8*8*n+1*8*8) : mxx*myy*(1*8*8*n+2*8*8)],
224 SubsampleRatio: subsampleRatio,
225 YStride: mxx * 8 * h0,
227 Rect: image.Rect(0, 0, d.width, d.height),
231 // Specified in section B.2.3.
232 func (d *decoder) processSOS(n int) os.Error {
234 return FormatError("missing SOF marker")
236 if n != 4+2*d.nComp {
237 return UnsupportedError("SOS has wrong length")
239 _, err := io.ReadFull(d.r, d.tmp[0:4+2*d.nComp])
243 if int(d.tmp[0]) != d.nComp {
244 return UnsupportedError("SOS has wrong number of image components")
246 var scan [nColorComponent]struct {
247 td uint8 // DC table selector.
248 ta uint8 // AC table selector.
250 for i := 0; i < d.nComp; i++ {
251 cs := d.tmp[1+2*i] // Component selector.
252 if cs != d.comp[i].c {
253 return UnsupportedError("scan components out of order")
255 scan[i].td = d.tmp[2+2*i] >> 4
256 scan[i].ta = d.tmp[2+2*i] & 0x0f
258 // mxx and myy are the number of MCUs (Minimum Coded Units) in the image.
259 h0, v0 := d.comp[0].h, d.comp[0].v // The h and v values from the Y components.
260 mxx := (d.width + 8*h0 - 1) / (8 * h0)
261 myy := (d.height + 8*v0 - 1) / (8 * v0)
262 if d.img1 == nil && d.img3 == nil {
263 d.makeImg(h0, v0, mxx, myy)
266 mcu, expectedRST := 0, uint8(rst0Marker)
269 dc [nColorComponent]int
271 for my := 0; my < myy; my++ {
272 for mx := 0; mx < mxx; mx++ {
273 for i := 0; i < d.nComp; i++ {
274 qt := &d.quant[d.comp[i].tq]
275 for j := 0; j < d.comp[i].h*d.comp[i].v; j++ {
276 // TODO(nigeltao): make this a "var b block" once the compiler's escape
277 // analysis is good enough to allocate it on the stack, not the heap.
280 // Decode the DC coefficient, as specified in section F.2.2.1.
281 value, err := d.decodeHuffman(&d.huff[dcTable][scan[i].td])
286 return UnsupportedError("excessive DC component")
288 dcDelta, err := d.receiveExtend(value)
295 // Decode the AC coefficients, as specified in section F.2.2.2.
296 for k := 1; k < blockSize; k++ {
297 value, err := d.decodeHuffman(&d.huff[acTable][scan[i].ta])
306 return FormatError("bad DCT index")
308 ac, err := d.receiveExtend(val1)
312 b[unzig[k]] = ac * qt[k]
321 // Perform the inverse DCT and store the MCU component to the image.
322 if d.nComp == nGrayComponent {
323 idct(d.img1.Pix[8*(my*d.img1.Stride+mx):], d.img1.Stride, &b)
327 mx0 := h0*mx + (j % 2)
328 my0 := v0*my + (j / 2)
329 idct(d.img3.Y[8*(my0*d.img3.YStride+mx0):], d.img3.YStride, &b)
331 idct(d.img3.Cb[8*(my*d.img3.CStride+mx):], d.img3.CStride, &b)
333 idct(d.img3.Cr[8*(my*d.img3.CStride+mx):], d.img3.CStride, &b)
339 if d.ri > 0 && mcu%d.ri == 0 && mcu < mxx*myy {
340 // A more sophisticated decoder could use RST[0-7] markers to resynchronize from corrupt input,
341 // but this one assumes well-formed input, and hence the restart marker follows immediately.
342 _, err := io.ReadFull(d.r, d.tmp[0:2])
346 if d.tmp[0] != 0xff || d.tmp[1] != expectedRST {
347 return FormatError("bad RST marker")
350 if expectedRST == rst7Marker+1 {
351 expectedRST = rst0Marker
353 // Reset the Huffman decoder.
355 // Reset the DC components, as per section F.2.1.3.1.
356 dc = [nColorComponent]int{}
364 // Specified in section B.2.4.4.
365 func (d *decoder) processDRI(n int) os.Error {
367 return FormatError("DRI has wrong length")
369 _, err := io.ReadFull(d.r, d.tmp[0:2])
373 d.ri = int(d.tmp[0])<<8 + int(d.tmp[1])
377 // decode reads a JPEG image from r and returns it as an image.Image.
378 func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, os.Error) {
379 if rr, ok := r.(Reader); ok {
382 d.r = bufio.NewReader(r)
385 // Check for the Start Of Image marker.
386 _, err := io.ReadFull(d.r, d.tmp[0:2])
390 if d.tmp[0] != 0xff || d.tmp[1] != soiMarker {
391 return nil, FormatError("missing SOI marker")
394 // Process the remaining segments until the End Of Image marker.
396 _, err := io.ReadFull(d.r, d.tmp[0:2])
400 if d.tmp[0] != 0xff {
401 return nil, FormatError("missing 0xff marker start")
404 if marker == eoiMarker { // End Of Image.
408 // Read the 16-bit length of the segment. The value includes the 2 bytes for the
409 // length itself, so we subtract 2 to get the number of remaining bytes.
410 _, err = io.ReadFull(d.r, d.tmp[0:2])
414 n := int(d.tmp[0])<<8 + int(d.tmp[1]) - 2
416 return nil, FormatError("short segment length")
420 case marker == sof0Marker: // Start Of Frame (Baseline).
421 err = d.processSOF(n)
425 case marker == sof2Marker: // Start Of Frame (Progressive).
426 err = UnsupportedError("progressive mode")
427 case marker == dhtMarker: // Define Huffman Table.
428 err = d.processDHT(n)
429 case marker == dqtMarker: // Define Quantization Table.
430 err = d.processDQT(n)
431 case marker == sosMarker: // Start Of Scan.
432 err = d.processSOS(n)
433 case marker == driMarker: // Define Restart Interval.
434 err = d.processDRI(n)
435 case marker >= app0Marker && marker <= app15Marker || marker == comMarker: // APPlication specific, or COMment.
438 err = UnsupportedError("unknown marker")
450 return nil, FormatError("missing SOS marker")
453 // Decode reads a JPEG image from r and returns it as an image.Image.
454 func Decode(r io.Reader) (image.Image, os.Error) {
456 return d.decode(r, false)
459 // DecodeConfig returns the color model and dimensions of a JPEG image without
460 // decoding the entire image.
461 func DecodeConfig(r io.Reader) (image.Config, os.Error) {
463 if _, err := d.decode(r, true); err != nil {
464 return image.Config{}, err
468 return image.Config{color.GrayModel, d.width, d.height}, nil
469 case nColorComponent:
470 return image.Config{ycbcr.YCbCrColorModel, d.width, d.height}, nil
472 return image.Config{}, FormatError("missing SOF marker")
476 image.RegisterFormat("jpeg", "\xff\xd8", Decode, DecodeConfig)