github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/image/jpeg/reader.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 implements a JPEG image decoder and encoder.
     6  //
     7  // JPEG is defined in ITU-T T.81: http://www.w3.org/Graphics/JPEG/itu-t81.pdf.
     8  package jpeg
     9  
    10  import (
    11  	"image"
    12  	"image/color"
    13  	"image/internal/imageutil"
    14  	"io"
    15  )
    16  
    17  // TODO(nigeltao): fix up the doc comment style so that sentences start with
    18  // the name of the type or function that they annotate.
    19  
    20  // A FormatError reports that the input is not a valid JPEG.
    21  type FormatError string
    22  
    23  func (e FormatError) Error() string { return "invalid JPEG format: " + string(e) }
    24  
    25  // An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.
    26  type UnsupportedError string
    27  
    28  func (e UnsupportedError) Error() string { return "unsupported JPEG feature: " + string(e) }
    29  
    30  var errUnsupportedSubsamplingRatio = UnsupportedError("luma/chroma subsampling ratio")
    31  
    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.
    38  }
    39  
    40  const (
    41  	dcTable = 0
    42  	acTable = 1
    43  	maxTc   = 1
    44  	maxTh   = 3
    45  	maxTq   = 3
    46  
    47  	maxComponents = 4
    48  )
    49  
    50  const (
    51  	sof0Marker = 0xc0 // Start Of Frame (Baseline).
    52  	sof1Marker = 0xc1 // Start Of Frame (Extended Sequential).
    53  	sof2Marker = 0xc2 // Start Of Frame (Progressive).
    54  	dhtMarker  = 0xc4 // Define Huffman Table.
    55  	rst0Marker = 0xd0 // ReSTart (0).
    56  	rst7Marker = 0xd7 // ReSTart (7).
    57  	soiMarker  = 0xd8 // Start Of Image.
    58  	eoiMarker  = 0xd9 // End Of Image.
    59  	sosMarker  = 0xda // Start Of Scan.
    60  	dqtMarker  = 0xdb // Define Quantization Table.
    61  	driMarker  = 0xdd // Define Restart Interval.
    62  	comMarker  = 0xfe // COMment.
    63  	// "APPlication specific" markers aren't part of the JPEG spec per se,
    64  	// but in practice, their use is described at
    65  	// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html
    66  	app0Marker  = 0xe0
    67  	app14Marker = 0xee
    68  	app15Marker = 0xef
    69  )
    70  
    71  // See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
    72  const (
    73  	adobeTransformUnknown = 0
    74  	adobeTransformYCbCr   = 1
    75  	adobeTransformYCbCrK  = 2
    76  )
    77  
    78  // unzig maps from the zig-zag ordering to the natural ordering. For example,
    79  // unzig[3] is the column and row of the fourth element in zig-zag order. The
    80  // value is 16, which means first column (16%8 == 0) and third row (16/8 == 2).
    81  var unzig = [blockSize]int{
    82  	0, 1, 8, 16, 9, 2, 3, 10,
    83  	17, 24, 32, 25, 18, 11, 4, 5,
    84  	12, 19, 26, 33, 40, 48, 41, 34,
    85  	27, 20, 13, 6, 7, 14, 21, 28,
    86  	35, 42, 49, 56, 57, 50, 43, 36,
    87  	29, 22, 15, 23, 30, 37, 44, 51,
    88  	58, 59, 52, 45, 38, 31, 39, 46,
    89  	53, 60, 61, 54, 47, 55, 62, 63,
    90  }
    91  
    92  // Reader is deprecated.
    93  type Reader interface {
    94  	io.ByteReader
    95  	io.Reader
    96  }
    97  
    98  // bits holds the unprocessed bits that have been taken from the byte-stream.
    99  // The n least significant bits of a form the unread bits, to be read in MSB to
   100  // LSB order.
   101  type bits struct {
   102  	a uint32 // accumulator.
   103  	m uint32 // mask. m==1<<(n-1) when n>0, with m==0 when n==0.
   104  	n int32  // the number of unread bits in a.
   105  }
   106  
   107  type decoder struct {
   108  	r    io.Reader
   109  	bits bits
   110  	// bytes is a byte buffer, similar to a bufio.Reader, except that it
   111  	// has to be able to unread more than 1 byte, due to byte stuffing.
   112  	// Byte stuffing is specified in section F.1.2.3.
   113  	bytes struct {
   114  		// buf[i:j] are the buffered bytes read from the underlying
   115  		// io.Reader that haven't yet been passed further on.
   116  		buf  [4096]byte
   117  		i, j int
   118  		// nUnreadable is the number of bytes to back up i after
   119  		// overshooting. It can be 0, 1 or 2.
   120  		nUnreadable int
   121  	}
   122  	width, height int
   123  
   124  	img1        *image.Gray
   125  	img3        *image.YCbCr
   126  	blackPix    []byte
   127  	blackStride int
   128  
   129  	ri                  int // Restart Interval.
   130  	nComp               int
   131  	progressive         bool
   132  	jfif                bool
   133  	adobeTransformValid bool
   134  	adobeTransform      uint8
   135  	eobRun              uint16 // End-of-Band run, specified in section G.1.2.2.
   136  
   137  	comp       [maxComponents]component
   138  	progCoeffs [maxComponents][]block // Saved state between progressive-mode scans.
   139  	huff       [maxTc + 1][maxTh + 1]huffman
   140  	quant      [maxTq + 1]block // Quantization tables, in zig-zag order.
   141  	tmp        [2 * blockSize]byte
   142  }
   143  
   144  // fill fills up the d.bytes.buf buffer from the underlying io.Reader. It
   145  // should only be called when there are no unread bytes in d.bytes.
   146  func (d *decoder) fill() error {
   147  	if d.bytes.i != d.bytes.j {
   148  		panic("jpeg: fill called when unread bytes exist")
   149  	}
   150  	// Move the last 2 bytes to the start of the buffer, in case we need
   151  	// to call unreadByteStuffedByte.
   152  	if d.bytes.j > 2 {
   153  		d.bytes.buf[0] = d.bytes.buf[d.bytes.j-2]
   154  		d.bytes.buf[1] = d.bytes.buf[d.bytes.j-1]
   155  		d.bytes.i, d.bytes.j = 2, 2
   156  	}
   157  	// Fill in the rest of the buffer.
   158  	n, err := d.r.Read(d.bytes.buf[d.bytes.j:])
   159  	d.bytes.j += n
   160  	if n > 0 {
   161  		err = nil
   162  	}
   163  	return err
   164  }
   165  
   166  // unreadByteStuffedByte undoes the most recent readByteStuffedByte call,
   167  // giving a byte of data back from d.bits to d.bytes. The Huffman look-up table
   168  // requires at least 8 bits for look-up, which means that Huffman decoding can
   169  // sometimes overshoot and read one or two too many bytes. Two-byte overshoot
   170  // can happen when expecting to read a 0xff 0x00 byte-stuffed byte.
   171  func (d *decoder) unreadByteStuffedByte() {
   172  	if d.bytes.nUnreadable == 0 {
   173  		return
   174  	}
   175  	d.bytes.i -= d.bytes.nUnreadable
   176  	d.bytes.nUnreadable = 0
   177  	if d.bits.n >= 8 {
   178  		d.bits.a >>= 8
   179  		d.bits.n -= 8
   180  		d.bits.m >>= 8
   181  	}
   182  }
   183  
   184  // readByte returns the next byte, whether buffered or not buffered. It does
   185  // not care about byte stuffing.
   186  func (d *decoder) readByte() (x byte, err error) {
   187  	for d.bytes.i == d.bytes.j {
   188  		if err = d.fill(); err != nil {
   189  			return 0, err
   190  		}
   191  	}
   192  	x = d.bytes.buf[d.bytes.i]
   193  	d.bytes.i++
   194  	d.bytes.nUnreadable = 0
   195  	return x, nil
   196  }
   197  
   198  // errMissingFF00 means that readByteStuffedByte encountered an 0xff byte (a
   199  // marker byte) that wasn't the expected byte-stuffed sequence 0xff, 0x00.
   200  var errMissingFF00 = FormatError("missing 0xff00 sequence")
   201  
   202  // readByteStuffedByte is like readByte but is for byte-stuffed Huffman data.
   203  func (d *decoder) readByteStuffedByte() (x byte, err error) {
   204  	// Take the fast path if d.bytes.buf contains at least two bytes.
   205  	if d.bytes.i+2 <= d.bytes.j {
   206  		x = d.bytes.buf[d.bytes.i]
   207  		d.bytes.i++
   208  		d.bytes.nUnreadable = 1
   209  		if x != 0xff {
   210  			return x, err
   211  		}
   212  		if d.bytes.buf[d.bytes.i] != 0x00 {
   213  			return 0, errMissingFF00
   214  		}
   215  		d.bytes.i++
   216  		d.bytes.nUnreadable = 2
   217  		return 0xff, nil
   218  	}
   219  
   220  	x, err = d.readByte()
   221  	if err != nil {
   222  		return 0, err
   223  	}
   224  	if x != 0xff {
   225  		d.bytes.nUnreadable = 1
   226  		return x, nil
   227  	}
   228  
   229  	x, err = d.readByte()
   230  	if err != nil {
   231  		d.bytes.nUnreadable = 1
   232  		return 0, err
   233  	}
   234  	d.bytes.nUnreadable = 2
   235  	if x != 0x00 {
   236  		return 0, errMissingFF00
   237  	}
   238  	return 0xff, nil
   239  }
   240  
   241  // readFull reads exactly len(p) bytes into p. It does not care about byte
   242  // stuffing.
   243  func (d *decoder) readFull(p []byte) error {
   244  	// Unread the overshot bytes, if any.
   245  	d.unreadByteStuffedByte()
   246  
   247  	for {
   248  		n := copy(p, d.bytes.buf[d.bytes.i:d.bytes.j])
   249  		p = p[n:]
   250  		d.bytes.i += n
   251  		if len(p) == 0 {
   252  			break
   253  		}
   254  		if err := d.fill(); err != nil {
   255  			if err == io.EOF {
   256  				err = io.ErrUnexpectedEOF
   257  			}
   258  			return err
   259  		}
   260  	}
   261  	return nil
   262  }
   263  
   264  // ignore ignores the next n bytes.
   265  func (d *decoder) ignore(n int) error {
   266  	// Unread the overshot bytes, if any.
   267  	d.unreadByteStuffedByte()
   268  
   269  	for {
   270  		m := d.bytes.j - d.bytes.i
   271  		if m > n {
   272  			m = n
   273  		}
   274  		d.bytes.i += m
   275  		n -= m
   276  		if n == 0 {
   277  			break
   278  		}
   279  		if err := d.fill(); err != nil {
   280  			if err == io.EOF {
   281  				err = io.ErrUnexpectedEOF
   282  			}
   283  			return err
   284  		}
   285  	}
   286  	return nil
   287  }
   288  
   289  // Specified in section B.2.2.
   290  func (d *decoder) processSOF(n int) error {
   291  	if d.nComp != 0 {
   292  		return FormatError("multiple SOF markers")
   293  	}
   294  	switch n {
   295  	case 6 + 3*1: // Grayscale image.
   296  		d.nComp = 1
   297  	case 6 + 3*3: // YCbCr or RGB image.
   298  		d.nComp = 3
   299  	case 6 + 3*4: // YCbCrK or CMYK image.
   300  		d.nComp = 4
   301  	default:
   302  		return UnsupportedError("number of components")
   303  	}
   304  	if err := d.readFull(d.tmp[:n]); err != nil {
   305  		return err
   306  	}
   307  	// We only support 8-bit precision.
   308  	if d.tmp[0] != 8 {
   309  		return UnsupportedError("precision")
   310  	}
   311  	d.height = int(d.tmp[1])<<8 + int(d.tmp[2])
   312  	d.width = int(d.tmp[3])<<8 + int(d.tmp[4])
   313  	if int(d.tmp[5]) != d.nComp {
   314  		return FormatError("SOF has wrong length")
   315  	}
   316  
   317  	for i := 0; i < d.nComp; i++ {
   318  		d.comp[i].c = d.tmp[6+3*i]
   319  		// Section B.2.2 states that "the value of C_i shall be different from
   320  		// the values of C_1 through C_(i-1)".
   321  		for j := 0; j < i; j++ {
   322  			if d.comp[i].c == d.comp[j].c {
   323  				return FormatError("repeated component identifier")
   324  			}
   325  		}
   326  
   327  		d.comp[i].tq = d.tmp[8+3*i]
   328  		if d.comp[i].tq > maxTq {
   329  			return FormatError("bad Tq value")
   330  		}
   331  
   332  		hv := d.tmp[7+3*i]
   333  		h, v := int(hv>>4), int(hv&0x0f)
   334  		if h < 1 || 4 < h || v < 1 || 4 < v {
   335  			return FormatError("luma/chroma subsampling ratio")
   336  		}
   337  		if h == 3 || v == 3 {
   338  			return errUnsupportedSubsamplingRatio
   339  		}
   340  		switch d.nComp {
   341  		case 1:
   342  			// If a JPEG image has only one component, section A.2 says "this data
   343  			// is non-interleaved by definition" and section A.2.2 says "[in this
   344  			// case...] the order of data units within a scan shall be left-to-right
   345  			// and top-to-bottom... regardless of the values of H_1 and V_1". Section
   346  			// 4.8.2 also says "[for non-interleaved data], the MCU is defined to be
   347  			// one data unit". Similarly, section A.1.1 explains that it is the ratio
   348  			// of H_i to max_j(H_j) that matters, and similarly for V. For grayscale
   349  			// images, H_1 is the maximum H_j for all components j, so that ratio is
   350  			// always 1. The component's (h, v) is effectively always (1, 1): even if
   351  			// the nominal (h, v) is (2, 1), a 20x5 image is encoded in three 8x8
   352  			// MCUs, not two 16x8 MCUs.
   353  			h, v = 1, 1
   354  
   355  		case 3:
   356  			// For YCbCr images, we only support 4:4:4, 4:4:0, 4:2:2, 4:2:0,
   357  			// 4:1:1 or 4:1:0 chroma subsampling ratios. This implies that the
   358  			// (h, v) values for the Y component are either (1, 1), (1, 2),
   359  			// (2, 1), (2, 2), (4, 1) or (4, 2), and the Y component's values
   360  			// must be a multiple of the Cb and Cr component's values. We also
   361  			// assume that the two chroma components have the same subsampling
   362  			// ratio.
   363  			switch i {
   364  			case 0: // Y.
   365  				// We have already verified, above, that h and v are both
   366  				// either 1, 2 or 4, so invalid (h, v) combinations are those
   367  				// with v == 4.
   368  				if v == 4 {
   369  					return errUnsupportedSubsamplingRatio
   370  				}
   371  			case 1: // Cb.
   372  				if d.comp[0].h%h != 0 || d.comp[0].v%v != 0 {
   373  					return errUnsupportedSubsamplingRatio
   374  				}
   375  			case 2: // Cr.
   376  				if d.comp[1].h != h || d.comp[1].v != v {
   377  					return errUnsupportedSubsamplingRatio
   378  				}
   379  			}
   380  
   381  		case 4:
   382  			// For 4-component images (either CMYK or YCbCrK), we only support two
   383  			// hv vectors: [0x11 0x11 0x11 0x11] and [0x22 0x11 0x11 0x22].
   384  			// Theoretically, 4-component JPEG images could mix and match hv values
   385  			// but in practice, those two combinations are the only ones in use,
   386  			// and it simplifies the applyBlack code below if we can assume that:
   387  			//	- for CMYK, the C and K channels have full samples, and if the M
   388  			//	  and Y channels subsample, they subsample both horizontally and
   389  			//	  vertically.
   390  			//	- for YCbCrK, the Y and K channels have full samples.
   391  			switch i {
   392  			case 0:
   393  				if hv != 0x11 && hv != 0x22 {
   394  					return errUnsupportedSubsamplingRatio
   395  				}
   396  			case 1, 2:
   397  				if hv != 0x11 {
   398  					return errUnsupportedSubsamplingRatio
   399  				}
   400  			case 3:
   401  				if d.comp[0].h != h || d.comp[0].v != v {
   402  					return errUnsupportedSubsamplingRatio
   403  				}
   404  			}
   405  		}
   406  
   407  		d.comp[i].h = h
   408  		d.comp[i].v = v
   409  	}
   410  	return nil
   411  }
   412  
   413  // Specified in section B.2.4.1.
   414  func (d *decoder) processDQT(n int) error {
   415  loop:
   416  	for n > 0 {
   417  		n--
   418  		x, err := d.readByte()
   419  		if err != nil {
   420  			return err
   421  		}
   422  		tq := x & 0x0f
   423  		if tq > maxTq {
   424  			return FormatError("bad Tq value")
   425  		}
   426  		switch x >> 4 {
   427  		default:
   428  			return FormatError("bad Pq value")
   429  		case 0:
   430  			if n < blockSize {
   431  				break loop
   432  			}
   433  			n -= blockSize
   434  			if err := d.readFull(d.tmp[:blockSize]); err != nil {
   435  				return err
   436  			}
   437  			for i := range d.quant[tq] {
   438  				d.quant[tq][i] = int32(d.tmp[i])
   439  			}
   440  		case 1:
   441  			if n < 2*blockSize {
   442  				break loop
   443  			}
   444  			n -= 2 * blockSize
   445  			if err := d.readFull(d.tmp[:2*blockSize]); err != nil {
   446  				return err
   447  			}
   448  			for i := range d.quant[tq] {
   449  				d.quant[tq][i] = int32(d.tmp[2*i])<<8 | int32(d.tmp[2*i+1])
   450  			}
   451  		}
   452  	}
   453  	if n != 0 {
   454  		return FormatError("DQT has wrong length")
   455  	}
   456  	return nil
   457  }
   458  
   459  // Specified in section B.2.4.4.
   460  func (d *decoder) processDRI(n int) error {
   461  	if n != 2 {
   462  		return FormatError("DRI has wrong length")
   463  	}
   464  	if err := d.readFull(d.tmp[:2]); err != nil {
   465  		return err
   466  	}
   467  	d.ri = int(d.tmp[0])<<8 + int(d.tmp[1])
   468  	return nil
   469  }
   470  
   471  func (d *decoder) processApp0Marker(n int) error {
   472  	if n < 5 {
   473  		return d.ignore(n)
   474  	}
   475  	if err := d.readFull(d.tmp[:5]); err != nil {
   476  		return err
   477  	}
   478  	n -= 5
   479  
   480  	d.jfif = d.tmp[0] == 'J' && d.tmp[1] == 'F' && d.tmp[2] == 'I' && d.tmp[3] == 'F' && d.tmp[4] == '\x00'
   481  
   482  	if n > 0 {
   483  		return d.ignore(n)
   484  	}
   485  	return nil
   486  }
   487  
   488  func (d *decoder) processApp14Marker(n int) error {
   489  	if n < 12 {
   490  		return d.ignore(n)
   491  	}
   492  	if err := d.readFull(d.tmp[:12]); err != nil {
   493  		return err
   494  	}
   495  	n -= 12
   496  
   497  	if d.tmp[0] == 'A' && d.tmp[1] == 'd' && d.tmp[2] == 'o' && d.tmp[3] == 'b' && d.tmp[4] == 'e' {
   498  		d.adobeTransformValid = true
   499  		d.adobeTransform = d.tmp[11]
   500  	}
   501  
   502  	if n > 0 {
   503  		return d.ignore(n)
   504  	}
   505  	return nil
   506  }
   507  
   508  // decode reads a JPEG image from r and returns it as an image.Image.
   509  func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, error) {
   510  	d.r = r
   511  
   512  	// Check for the Start Of Image marker.
   513  	if err := d.readFull(d.tmp[:2]); err != nil {
   514  		return nil, err
   515  	}
   516  	if d.tmp[0] != 0xff || d.tmp[1] != soiMarker {
   517  		return nil, FormatError("missing SOI marker")
   518  	}
   519  
   520  	// Process the remaining segments until the End Of Image marker.
   521  	for {
   522  		err := d.readFull(d.tmp[:2])
   523  		if err != nil {
   524  			return nil, err
   525  		}
   526  		for d.tmp[0] != 0xff {
   527  			// Strictly speaking, this is a format error. However, libjpeg is
   528  			// liberal in what it accepts. As of version 9, next_marker in
   529  			// jdmarker.c treats this as a warning (JWRN_EXTRANEOUS_DATA) and
   530  			// continues to decode the stream. Even before next_marker sees
   531  			// extraneous data, jpeg_fill_bit_buffer in jdhuff.c reads as many
   532  			// bytes as it can, possibly past the end of a scan's data. It
   533  			// effectively puts back any markers that it overscanned (e.g. an
   534  			// "\xff\xd9" EOI marker), but it does not put back non-marker data,
   535  			// and thus it can silently ignore a small number of extraneous
   536  			// non-marker bytes before next_marker has a chance to see them (and
   537  			// print a warning).
   538  			//
   539  			// We are therefore also liberal in what we accept. Extraneous data
   540  			// is silently ignored.
   541  			//
   542  			// This is similar to, but not exactly the same as, the restart
   543  			// mechanism within a scan (the RST[0-7] markers).
   544  			//
   545  			// Note that extraneous 0xff bytes in e.g. SOS data are escaped as
   546  			// "\xff\x00", and so are detected a little further down below.
   547  			d.tmp[0] = d.tmp[1]
   548  			d.tmp[1], err = d.readByte()
   549  			if err != nil {
   550  				return nil, err
   551  			}
   552  		}
   553  		marker := d.tmp[1]
   554  		if marker == 0 {
   555  			// Treat "\xff\x00" as extraneous data.
   556  			continue
   557  		}
   558  		for marker == 0xff {
   559  			// Section B.1.1.2 says, "Any marker may optionally be preceded by any
   560  			// number of fill bytes, which are bytes assigned code X'FF'".
   561  			marker, err = d.readByte()
   562  			if err != nil {
   563  				return nil, err
   564  			}
   565  		}
   566  		if marker == eoiMarker { // End Of Image.
   567  			break
   568  		}
   569  		if rst0Marker <= marker && marker <= rst7Marker {
   570  			// Figures B.2 and B.16 of the specification suggest that restart markers should
   571  			// only occur between Entropy Coded Segments and not after the final ECS.
   572  			// However, some encoders may generate incorrect JPEGs with a final restart
   573  			// marker. That restart marker will be seen here instead of inside the processSOS
   574  			// method, and is ignored as a harmless error. Restart markers have no extra data,
   575  			// so we check for this before we read the 16-bit length of the segment.
   576  			continue
   577  		}
   578  
   579  		// Read the 16-bit length of the segment. The value includes the 2 bytes for the
   580  		// length itself, so we subtract 2 to get the number of remaining bytes.
   581  		if err = d.readFull(d.tmp[:2]); err != nil {
   582  			return nil, err
   583  		}
   584  		n := int(d.tmp[0])<<8 + int(d.tmp[1]) - 2
   585  		if n < 0 {
   586  			return nil, FormatError("short segment length")
   587  		}
   588  
   589  		switch marker {
   590  		case sof0Marker, sof1Marker, sof2Marker:
   591  			d.progressive = marker == sof2Marker
   592  			err = d.processSOF(n)
   593  			if configOnly && d.jfif {
   594  				return nil, err
   595  			}
   596  		case dhtMarker:
   597  			if configOnly {
   598  				err = d.ignore(n)
   599  			} else {
   600  				err = d.processDHT(n)
   601  			}
   602  		case dqtMarker:
   603  			if configOnly {
   604  				err = d.ignore(n)
   605  			} else {
   606  				err = d.processDQT(n)
   607  			}
   608  		case sosMarker:
   609  			if configOnly {
   610  				return nil, nil
   611  			}
   612  			err = d.processSOS(n)
   613  		case driMarker:
   614  			if configOnly {
   615  				err = d.ignore(n)
   616  			} else {
   617  				err = d.processDRI(n)
   618  			}
   619  		case app0Marker:
   620  			err = d.processApp0Marker(n)
   621  		case app14Marker:
   622  			err = d.processApp14Marker(n)
   623  		default:
   624  			if app0Marker <= marker && marker <= app15Marker || marker == comMarker {
   625  				err = d.ignore(n)
   626  			} else if marker < 0xc0 { // See Table B.1 "Marker code assignments".
   627  				err = FormatError("unknown marker")
   628  			} else {
   629  				err = UnsupportedError("unknown marker")
   630  			}
   631  		}
   632  		if err != nil {
   633  			return nil, err
   634  		}
   635  	}
   636  	if d.img1 != nil {
   637  		return d.img1, nil
   638  	}
   639  	if d.img3 != nil {
   640  		if d.blackPix != nil {
   641  			return d.applyBlack()
   642  		} else if d.isRGB() {
   643  			return d.convertToRGB()
   644  		}
   645  		return d.img3, nil
   646  	}
   647  	return nil, FormatError("missing SOS marker")
   648  }
   649  
   650  // applyBlack combines d.img3 and d.blackPix into a CMYK image. The formula
   651  // used depends on whether the JPEG image is stored as CMYK or YCbCrK,
   652  // indicated by the APP14 (Adobe) metadata.
   653  //
   654  // Adobe CMYK JPEG images are inverted, where 255 means no ink instead of full
   655  // ink, so we apply "v = 255 - v" at various points. Note that a double
   656  // inversion is a no-op, so inversions might be implicit in the code below.
   657  func (d *decoder) applyBlack() (image.Image, error) {
   658  	if !d.adobeTransformValid {
   659  		return nil, UnsupportedError("unknown color model: 4-component JPEG doesn't have Adobe APP14 metadata")
   660  	}
   661  
   662  	// If the 4-component JPEG image isn't explicitly marked as "Unknown (RGB
   663  	// or CMYK)" as per
   664  	// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
   665  	// we assume that it is YCbCrK. This matches libjpeg's jdapimin.c.
   666  	if d.adobeTransform != adobeTransformUnknown {
   667  		// Convert the YCbCr part of the YCbCrK to RGB, invert the RGB to get
   668  		// CMY, and patch in the original K. The RGB to CMY inversion cancels
   669  		// out the 'Adobe inversion' described in the applyBlack doc comment
   670  		// above, so in practice, only the fourth channel (black) is inverted.
   671  		bounds := d.img3.Bounds()
   672  		img := image.NewRGBA(bounds)
   673  		imageutil.DrawYCbCr(img, bounds, d.img3, bounds.Min)
   674  		for iBase, y := 0, bounds.Min.Y; y < bounds.Max.Y; iBase, y = iBase+img.Stride, y+1 {
   675  			for i, x := iBase+3, bounds.Min.X; x < bounds.Max.X; i, x = i+4, x+1 {
   676  				img.Pix[i] = 255 - d.blackPix[(y-bounds.Min.Y)*d.blackStride+(x-bounds.Min.X)]
   677  			}
   678  		}
   679  		return &image.CMYK{
   680  			Pix:    img.Pix,
   681  			Stride: img.Stride,
   682  			Rect:   img.Rect,
   683  		}, nil
   684  	}
   685  
   686  	// The first three channels (cyan, magenta, yellow) of the CMYK
   687  	// were decoded into d.img3, but each channel was decoded into a separate
   688  	// []byte slice, and some channels may be subsampled. We interleave the
   689  	// separate channels into an image.CMYK's single []byte slice containing 4
   690  	// contiguous bytes per pixel.
   691  	bounds := d.img3.Bounds()
   692  	img := image.NewCMYK(bounds)
   693  
   694  	translations := [4]struct {
   695  		src    []byte
   696  		stride int
   697  	}{
   698  		{d.img3.Y, d.img3.YStride},
   699  		{d.img3.Cb, d.img3.CStride},
   700  		{d.img3.Cr, d.img3.CStride},
   701  		{d.blackPix, d.blackStride},
   702  	}
   703  	for t, translation := range translations {
   704  		subsample := d.comp[t].h != d.comp[0].h || d.comp[t].v != d.comp[0].v
   705  		for iBase, y := 0, bounds.Min.Y; y < bounds.Max.Y; iBase, y = iBase+img.Stride, y+1 {
   706  			sy := y - bounds.Min.Y
   707  			if subsample {
   708  				sy /= 2
   709  			}
   710  			for i, x := iBase+t, bounds.Min.X; x < bounds.Max.X; i, x = i+4, x+1 {
   711  				sx := x - bounds.Min.X
   712  				if subsample {
   713  					sx /= 2
   714  				}
   715  				img.Pix[i] = 255 - translation.src[sy*translation.stride+sx]
   716  			}
   717  		}
   718  	}
   719  	return img, nil
   720  }
   721  
   722  func (d *decoder) isRGB() bool {
   723  	if d.jfif {
   724  		return false
   725  	}
   726  	if d.adobeTransformValid && d.adobeTransform == adobeTransformUnknown {
   727  		// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
   728  		// says that 0 means Unknown (and in practice RGB) and 1 means YCbCr.
   729  		return true
   730  	}
   731  	return d.comp[0].c == 'R' && d.comp[1].c == 'G' && d.comp[2].c == 'B'
   732  }
   733  
   734  func (d *decoder) convertToRGB() (image.Image, error) {
   735  	cScale := d.comp[0].h / d.comp[1].h
   736  	bounds := d.img3.Bounds()
   737  	img := image.NewRGBA(bounds)
   738  	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
   739  		po := img.PixOffset(bounds.Min.X, y)
   740  		yo := d.img3.YOffset(bounds.Min.X, y)
   741  		co := d.img3.COffset(bounds.Min.X, y)
   742  		for i, iMax := 0, bounds.Max.X-bounds.Min.X; i < iMax; i++ {
   743  			img.Pix[po+4*i+0] = d.img3.Y[yo+i]
   744  			img.Pix[po+4*i+1] = d.img3.Cb[co+i/cScale]
   745  			img.Pix[po+4*i+2] = d.img3.Cr[co+i/cScale]
   746  			img.Pix[po+4*i+3] = 255
   747  		}
   748  	}
   749  	return img, nil
   750  }
   751  
   752  // Decode reads a JPEG image from r and returns it as an image.Image.
   753  func Decode(r io.Reader) (image.Image, error) {
   754  	var d decoder
   755  	return d.decode(r, false)
   756  }
   757  
   758  // DecodeConfig returns the color model and dimensions of a JPEG image without
   759  // decoding the entire image.
   760  func DecodeConfig(r io.Reader) (image.Config, error) {
   761  	var d decoder
   762  	if _, err := d.decode(r, true); err != nil {
   763  		return image.Config{}, err
   764  	}
   765  	switch d.nComp {
   766  	case 1:
   767  		return image.Config{
   768  			ColorModel: color.GrayModel,
   769  			Width:      d.width,
   770  			Height:     d.height,
   771  		}, nil
   772  	case 3:
   773  		cm := color.YCbCrModel
   774  		if d.isRGB() {
   775  			cm = color.RGBAModel
   776  		}
   777  		return image.Config{
   778  			ColorModel: cm,
   779  			Width:      d.width,
   780  			Height:     d.height,
   781  		}, nil
   782  	case 4:
   783  		return image.Config{
   784  			ColorModel: color.CMYKModel,
   785  			Width:      d.width,
   786  			Height:     d.height,
   787  		}, nil
   788  	}
   789  	return image.Config{}, FormatError("missing SOF marker")
   790  }
   791  
   792  func init() {
   793  	image.RegisterFormat("jpeg", "\xff\xd8", Decode, DecodeConfig)
   794  }