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