...

Source file src/image/jpeg/reader.go

     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		d.bytes.nUnreadable = 0
   221	
   222		x, err = d.readByte()
   223		if err != nil {
   224			return 0, err
   225		}
   226		d.bytes.nUnreadable = 1
   227		if x != 0xff {
   228			return x, nil
   229		}
   230	
   231		x, err = d.readByte()
   232		if err != nil {
   233			return 0, err
   234		}
   235		d.bytes.nUnreadable = 2
   236		if x != 0x00 {
   237			return 0, errMissingFF00
   238		}
   239		return 0xff, nil
   240	}
   241	
   242	// readFull reads exactly len(p) bytes into p. It does not care about byte
   243	// stuffing.
   244	func (d *decoder) readFull(p []byte) error {
   245		// Unread the overshot bytes, if any.
   246		d.unreadByteStuffedByte()
   247	
   248		for {
   249			n := copy(p, d.bytes.buf[d.bytes.i:d.bytes.j])
   250			p = p[n:]
   251			d.bytes.i += n
   252			if len(p) == 0 {
   253				break
   254			}
   255			if err := d.fill(); err != nil {
   256				if err == io.EOF {
   257					err = io.ErrUnexpectedEOF
   258				}
   259				return err
   260			}
   261		}
   262		return nil
   263	}
   264	
   265	// ignore ignores the next n bytes.
   266	func (d *decoder) ignore(n int) error {
   267		// Unread the overshot bytes, if any.
   268		d.unreadByteStuffedByte()
   269	
   270		for {
   271			m := d.bytes.j - d.bytes.i
   272			if m > n {
   273				m = n
   274			}
   275			d.bytes.i += m
   276			n -= m
   277			if n == 0 {
   278				break
   279			}
   280			if err := d.fill(); err != nil {
   281				if err == io.EOF {
   282					err = io.ErrUnexpectedEOF
   283				}
   284				return err
   285			}
   286		}
   287		return nil
   288	}
   289	
   290	// Specified in section B.2.2.
   291	func (d *decoder) processSOF(n int) error {
   292		if d.nComp != 0 {
   293			return FormatError("multiple SOF markers")
   294		}
   295		switch n {
   296		case 6 + 3*1: // Grayscale image.
   297			d.nComp = 1
   298		case 6 + 3*3: // YCbCr or RGB image.
   299			d.nComp = 3
   300		case 6 + 3*4: // YCbCrK or CMYK image.
   301			d.nComp = 4
   302		default:
   303			return UnsupportedError("number of components")
   304		}
   305		if err := d.readFull(d.tmp[:n]); err != nil {
   306			return err
   307		}
   308		// We only support 8-bit precision.
   309		if d.tmp[0] != 8 {
   310			return UnsupportedError("precision")
   311		}
   312		d.height = int(d.tmp[1])<<8 + int(d.tmp[2])
   313		d.width = int(d.tmp[3])<<8 + int(d.tmp[4])
   314		if int(d.tmp[5]) != d.nComp {
   315			return FormatError("SOF has wrong length")
   316		}
   317	
   318		for i := 0; i < d.nComp; i++ {
   319			d.comp[i].c = d.tmp[6+3*i]
   320			// Section B.2.2 states that "the value of C_i shall be different from
   321			// the values of C_1 through C_(i-1)".
   322			for j := 0; j < i; j++ {
   323				if d.comp[i].c == d.comp[j].c {
   324					return FormatError("repeated component identifier")
   325				}
   326			}
   327	
   328			d.comp[i].tq = d.tmp[8+3*i]
   329			if d.comp[i].tq > maxTq {
   330				return FormatError("bad Tq value")
   331			}
   332	
   333			hv := d.tmp[7+3*i]
   334			h, v := int(hv>>4), int(hv&0x0f)
   335			if h < 1 || 4 < h || v < 1 || 4 < v {
   336				return FormatError("luma/chroma subsampling ratio")
   337			}
   338			if h == 3 || v == 3 {
   339				return errUnsupportedSubsamplingRatio
   340			}
   341			switch d.nComp {
   342			case 1:
   343				// If a JPEG image has only one component, section A.2 says "this data
   344				// is non-interleaved by definition" and section A.2.2 says "[in this
   345				// case...] the order of data units within a scan shall be left-to-right
   346				// and top-to-bottom... regardless of the values of H_1 and V_1". Section
   347				// 4.8.2 also says "[for non-interleaved data], the MCU is defined to be
   348				// one data unit". Similarly, section A.1.1 explains that it is the ratio
   349				// of H_i to max_j(H_j) that matters, and similarly for V. For grayscale
   350				// images, H_1 is the maximum H_j for all components j, so that ratio is
   351				// always 1. The component's (h, v) is effectively always (1, 1): even if
   352				// the nominal (h, v) is (2, 1), a 20x5 image is encoded in three 8x8
   353				// MCUs, not two 16x8 MCUs.
   354				h, v = 1, 1
   355	
   356			case 3:
   357				// For YCbCr images, we only support 4:4:4, 4:4:0, 4:2:2, 4:2:0,
   358				// 4:1:1 or 4:1:0 chroma subsampling ratios. This implies that the
   359				// (h, v) values for the Y component are either (1, 1), (1, 2),
   360				// (2, 1), (2, 2), (4, 1) or (4, 2), and the Y component's values
   361				// must be a multiple of the Cb and Cr component's values. We also
   362				// assume that the two chroma components have the same subsampling
   363				// ratio.
   364				switch i {
   365				case 0: // Y.
   366					// We have already verified, above, that h and v are both
   367					// either 1, 2 or 4, so invalid (h, v) combinations are those
   368					// with v == 4.
   369					if v == 4 {
   370						return errUnsupportedSubsamplingRatio
   371					}
   372				case 1: // Cb.
   373					if d.comp[0].h%h != 0 || d.comp[0].v%v != 0 {
   374						return errUnsupportedSubsamplingRatio
   375					}
   376				case 2: // Cr.
   377					if d.comp[1].h != h || d.comp[1].v != v {
   378						return errUnsupportedSubsamplingRatio
   379					}
   380				}
   381	
   382			case 4:
   383				// For 4-component images (either CMYK or YCbCrK), we only support two
   384				// hv vectors: [0x11 0x11 0x11 0x11] and [0x22 0x11 0x11 0x22].
   385				// Theoretically, 4-component JPEG images could mix and match hv values
   386				// but in practice, those two combinations are the only ones in use,
   387				// and it simplifies the applyBlack code below if we can assume that:
   388				//	- for CMYK, the C and K channels have full samples, and if the M
   389				//	  and Y channels subsample, they subsample both horizontally and
   390				//	  vertically.
   391				//	- for YCbCrK, the Y and K channels have full samples.
   392				switch i {
   393				case 0:
   394					if hv != 0x11 && hv != 0x22 {
   395						return errUnsupportedSubsamplingRatio
   396					}
   397				case 1, 2:
   398					if hv != 0x11 {
   399						return errUnsupportedSubsamplingRatio
   400					}
   401				case 3:
   402					if d.comp[0].h != h || d.comp[0].v != v {
   403						return errUnsupportedSubsamplingRatio
   404					}
   405				}
   406			}
   407	
   408			d.comp[i].h = h
   409			d.comp[i].v = v
   410		}
   411		return nil
   412	}
   413	
   414	// Specified in section B.2.4.1.
   415	func (d *decoder) processDQT(n int) error {
   416	loop:
   417		for n > 0 {
   418			n--
   419			x, err := d.readByte()
   420			if err != nil {
   421				return err
   422			}
   423			tq := x & 0x0f
   424			if tq > maxTq {
   425				return FormatError("bad Tq value")
   426			}
   427			switch x >> 4 {
   428			default:
   429				return FormatError("bad Pq value")
   430			case 0:
   431				if n < blockSize {
   432					break loop
   433				}
   434				n -= blockSize
   435				if err := d.readFull(d.tmp[:blockSize]); err != nil {
   436					return err
   437				}
   438				for i := range d.quant[tq] {
   439					d.quant[tq][i] = int32(d.tmp[i])
   440				}
   441			case 1:
   442				if n < 2*blockSize {
   443					break loop
   444				}
   445				n -= 2 * blockSize
   446				if err := d.readFull(d.tmp[:2*blockSize]); err != nil {
   447					return err
   448				}
   449				for i := range d.quant[tq] {
   450					d.quant[tq][i] = int32(d.tmp[2*i])<<8 | int32(d.tmp[2*i+1])
   451				}
   452			}
   453		}
   454		if n != 0 {
   455			return FormatError("DQT has wrong length")
   456		}
   457		return nil
   458	}
   459	
   460	// Specified in section B.2.4.4.
   461	func (d *decoder) processDRI(n int) error {
   462		if n != 2 {
   463			return FormatError("DRI has wrong length")
   464		}
   465		if err := d.readFull(d.tmp[:2]); err != nil {
   466			return err
   467		}
   468		d.ri = int(d.tmp[0])<<8 + int(d.tmp[1])
   469		return nil
   470	}
   471	
   472	func (d *decoder) processApp0Marker(n int) error {
   473		if n < 5 {
   474			return d.ignore(n)
   475		}
   476		if err := d.readFull(d.tmp[:5]); err != nil {
   477			return err
   478		}
   479		n -= 5
   480	
   481		d.jfif = d.tmp[0] == 'J' && d.tmp[1] == 'F' && d.tmp[2] == 'I' && d.tmp[3] == 'F' && d.tmp[4] == '\x00'
   482	
   483		if n > 0 {
   484			return d.ignore(n)
   485		}
   486		return nil
   487	}
   488	
   489	func (d *decoder) processApp14Marker(n int) error {
   490		if n < 12 {
   491			return d.ignore(n)
   492		}
   493		if err := d.readFull(d.tmp[:12]); err != nil {
   494			return err
   495		}
   496		n -= 12
   497	
   498		if d.tmp[0] == 'A' && d.tmp[1] == 'd' && d.tmp[2] == 'o' && d.tmp[3] == 'b' && d.tmp[4] == 'e' {
   499			d.adobeTransformValid = true
   500			d.adobeTransform = d.tmp[11]
   501		}
   502	
   503		if n > 0 {
   504			return d.ignore(n)
   505		}
   506		return nil
   507	}
   508	
   509	// decode reads a JPEG image from r and returns it as an image.Image.
   510	func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, error) {
   511		d.r = r
   512	
   513		// Check for the Start Of Image marker.
   514		if err := d.readFull(d.tmp[:2]); err != nil {
   515			return nil, err
   516		}
   517		if d.tmp[0] != 0xff || d.tmp[1] != soiMarker {
   518			return nil, FormatError("missing SOI marker")
   519		}
   520	
   521		// Process the remaining segments until the End Of Image marker.
   522		for {
   523			err := d.readFull(d.tmp[:2])
   524			if err != nil {
   525				return nil, err
   526			}
   527			for d.tmp[0] != 0xff {
   528				// Strictly speaking, this is a format error. However, libjpeg is
   529				// liberal in what it accepts. As of version 9, next_marker in
   530				// jdmarker.c treats this as a warning (JWRN_EXTRANEOUS_DATA) and
   531				// continues to decode the stream. Even before next_marker sees
   532				// extraneous data, jpeg_fill_bit_buffer in jdhuff.c reads as many
   533				// bytes as it can, possibly past the end of a scan's data. It
   534				// effectively puts back any markers that it overscanned (e.g. an
   535				// "\xff\xd9" EOI marker), but it does not put back non-marker data,
   536				// and thus it can silently ignore a small number of extraneous
   537				// non-marker bytes before next_marker has a chance to see them (and
   538				// print a warning).
   539				//
   540				// We are therefore also liberal in what we accept. Extraneous data
   541				// is silently ignored.
   542				//
   543				// This is similar to, but not exactly the same as, the restart
   544				// mechanism within a scan (the RST[0-7] markers).
   545				//
   546				// Note that extraneous 0xff bytes in e.g. SOS data are escaped as
   547				// "\xff\x00", and so are detected a little further down below.
   548				d.tmp[0] = d.tmp[1]
   549				d.tmp[1], err = d.readByte()
   550				if err != nil {
   551					return nil, err
   552				}
   553			}
   554			marker := d.tmp[1]
   555			if marker == 0 {
   556				// Treat "\xff\x00" as extraneous data.
   557				continue
   558			}
   559			for marker == 0xff {
   560				// Section B.1.1.2 says, "Any marker may optionally be preceded by any
   561				// number of fill bytes, which are bytes assigned code X'FF'".
   562				marker, err = d.readByte()
   563				if err != nil {
   564					return nil, err
   565				}
   566			}
   567			if marker == eoiMarker { // End Of Image.
   568				break
   569			}
   570			if rst0Marker <= marker && marker <= rst7Marker {
   571				// Figures B.2 and B.16 of the specification suggest that restart markers should
   572				// only occur between Entropy Coded Segments and not after the final ECS.
   573				// However, some encoders may generate incorrect JPEGs with a final restart
   574				// marker. That restart marker will be seen here instead of inside the processSOS
   575				// method, and is ignored as a harmless error. Restart markers have no extra data,
   576				// so we check for this before we read the 16-bit length of the segment.
   577				continue
   578			}
   579	
   580			// Read the 16-bit length of the segment. The value includes the 2 bytes for the
   581			// length itself, so we subtract 2 to get the number of remaining bytes.
   582			if err = d.readFull(d.tmp[:2]); err != nil {
   583				return nil, err
   584			}
   585			n := int(d.tmp[0])<<8 + int(d.tmp[1]) - 2
   586			if n < 0 {
   587				return nil, FormatError("short segment length")
   588			}
   589	
   590			switch marker {
   591			case sof0Marker, sof1Marker, sof2Marker:
   592				d.progressive = marker == sof2Marker
   593				err = d.processSOF(n)
   594				if configOnly && d.jfif {
   595					return nil, err
   596				}
   597			case dhtMarker:
   598				if configOnly {
   599					err = d.ignore(n)
   600				} else {
   601					err = d.processDHT(n)
   602				}
   603			case dqtMarker:
   604				if configOnly {
   605					err = d.ignore(n)
   606				} else {
   607					err = d.processDQT(n)
   608				}
   609			case sosMarker:
   610				if configOnly {
   611					return nil, nil
   612				}
   613				err = d.processSOS(n)
   614			case driMarker:
   615				if configOnly {
   616					err = d.ignore(n)
   617				} else {
   618					err = d.processDRI(n)
   619				}
   620			case app0Marker:
   621				err = d.processApp0Marker(n)
   622			case app14Marker:
   623				err = d.processApp14Marker(n)
   624			default:
   625				if app0Marker <= marker && marker <= app15Marker || marker == comMarker {
   626					err = d.ignore(n)
   627				} else if marker < 0xc0 { // See Table B.1 "Marker code assignments".
   628					err = FormatError("unknown marker")
   629				} else {
   630					err = UnsupportedError("unknown marker")
   631				}
   632			}
   633			if err != nil {
   634				return nil, err
   635			}
   636		}
   637		if d.img1 != nil {
   638			return d.img1, nil
   639		}
   640		if d.img3 != nil {
   641			if d.blackPix != nil {
   642				return d.applyBlack()
   643			} else if d.isRGB() {
   644				return d.convertToRGB()
   645			}
   646			return d.img3, nil
   647		}
   648		return nil, FormatError("missing SOS marker")
   649	}
   650	
   651	// applyBlack combines d.img3 and d.blackPix into a CMYK image. The formula
   652	// used depends on whether the JPEG image is stored as CMYK or YCbCrK,
   653	// indicated by the APP14 (Adobe) metadata.
   654	//
   655	// Adobe CMYK JPEG images are inverted, where 255 means no ink instead of full
   656	// ink, so we apply "v = 255 - v" at various points. Note that a double
   657	// inversion is a no-op, so inversions might be implicit in the code below.
   658	func (d *decoder) applyBlack() (image.Image, error) {
   659		if !d.adobeTransformValid {
   660			return nil, UnsupportedError("unknown color model: 4-component JPEG doesn't have Adobe APP14 metadata")
   661		}
   662	
   663		// If the 4-component JPEG image isn't explicitly marked as "Unknown (RGB
   664		// or CMYK)" as per
   665		// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
   666		// we assume that it is YCbCrK. This matches libjpeg's jdapimin.c.
   667		if d.adobeTransform != adobeTransformUnknown {
   668			// Convert the YCbCr part of the YCbCrK to RGB, invert the RGB to get
   669			// CMY, and patch in the original K. The RGB to CMY inversion cancels
   670			// out the 'Adobe inversion' described in the applyBlack doc comment
   671			// above, so in practice, only the fourth channel (black) is inverted.
   672			bounds := d.img3.Bounds()
   673			img := image.NewRGBA(bounds)
   674			imageutil.DrawYCbCr(img, bounds, d.img3, bounds.Min)
   675			for iBase, y := 0, bounds.Min.Y; y < bounds.Max.Y; iBase, y = iBase+img.Stride, y+1 {
   676				for i, x := iBase+3, bounds.Min.X; x < bounds.Max.X; i, x = i+4, x+1 {
   677					img.Pix[i] = 255 - d.blackPix[(y-bounds.Min.Y)*d.blackStride+(x-bounds.Min.X)]
   678				}
   679			}
   680			return &image.CMYK{
   681				Pix:    img.Pix,
   682				Stride: img.Stride,
   683				Rect:   img.Rect,
   684			}, nil
   685		}
   686	
   687		// The first three channels (cyan, magenta, yellow) of the CMYK
   688		// were decoded into d.img3, but each channel was decoded into a separate
   689		// []byte slice, and some channels may be subsampled. We interleave the
   690		// separate channels into an image.CMYK's single []byte slice containing 4
   691		// contiguous bytes per pixel.
   692		bounds := d.img3.Bounds()
   693		img := image.NewCMYK(bounds)
   694	
   695		translations := [4]struct {
   696			src    []byte
   697			stride int
   698		}{
   699			{d.img3.Y, d.img3.YStride},
   700			{d.img3.Cb, d.img3.CStride},
   701			{d.img3.Cr, d.img3.CStride},
   702			{d.blackPix, d.blackStride},
   703		}
   704		for t, translation := range translations {
   705			subsample := d.comp[t].h != d.comp[0].h || d.comp[t].v != d.comp[0].v
   706			for iBase, y := 0, bounds.Min.Y; y < bounds.Max.Y; iBase, y = iBase+img.Stride, y+1 {
   707				sy := y - bounds.Min.Y
   708				if subsample {
   709					sy /= 2
   710				}
   711				for i, x := iBase+t, bounds.Min.X; x < bounds.Max.X; i, x = i+4, x+1 {
   712					sx := x - bounds.Min.X
   713					if subsample {
   714						sx /= 2
   715					}
   716					img.Pix[i] = 255 - translation.src[sy*translation.stride+sx]
   717				}
   718			}
   719		}
   720		return img, nil
   721	}
   722	
   723	func (d *decoder) isRGB() bool {
   724		if d.jfif {
   725			return false
   726		}
   727		if d.adobeTransformValid && d.adobeTransform == adobeTransformUnknown {
   728			// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
   729			// says that 0 means Unknown (and in practice RGB) and 1 means YCbCr.
   730			return true
   731		}
   732		return d.comp[0].c == 'R' && d.comp[1].c == 'G' && d.comp[2].c == 'B'
   733	}
   734	
   735	func (d *decoder) convertToRGB() (image.Image, error) {
   736		cScale := d.comp[0].h / d.comp[1].h
   737		bounds := d.img3.Bounds()
   738		img := image.NewRGBA(bounds)
   739		for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
   740			po := img.PixOffset(bounds.Min.X, y)
   741			yo := d.img3.YOffset(bounds.Min.X, y)
   742			co := d.img3.COffset(bounds.Min.X, y)
   743			for i, iMax := 0, bounds.Max.X-bounds.Min.X; i < iMax; i++ {
   744				img.Pix[po+4*i+0] = d.img3.Y[yo+i]
   745				img.Pix[po+4*i+1] = d.img3.Cb[co+i/cScale]
   746				img.Pix[po+4*i+2] = d.img3.Cr[co+i/cScale]
   747				img.Pix[po+4*i+3] = 255
   748			}
   749		}
   750		return img, nil
   751	}
   752	
   753	// Decode reads a JPEG image from r and returns it as an image.Image.
   754	func Decode(r io.Reader) (image.Image, error) {
   755		var d decoder
   756		return d.decode(r, false)
   757	}
   758	
   759	// DecodeConfig returns the color model and dimensions of a JPEG image without
   760	// decoding the entire image.
   761	func DecodeConfig(r io.Reader) (image.Config, error) {
   762		var d decoder
   763		if _, err := d.decode(r, true); err != nil {
   764			return image.Config{}, err
   765		}
   766		switch d.nComp {
   767		case 1:
   768			return image.Config{
   769				ColorModel: color.GrayModel,
   770				Width:      d.width,
   771				Height:     d.height,
   772			}, nil
   773		case 3:
   774			cm := color.YCbCrModel
   775			if d.isRGB() {
   776				cm = color.RGBAModel
   777			}
   778			return image.Config{
   779				ColorModel: cm,
   780				Width:      d.width,
   781				Height:     d.height,
   782			}, nil
   783		case 4:
   784			return image.Config{
   785				ColorModel: color.CMYKModel,
   786				Width:      d.width,
   787				Height:     d.height,
   788			}, nil
   789		}
   790		return image.Config{}, FormatError("missing SOF marker")
   791	}
   792	
   793	func init() {
   794		image.RegisterFormat("jpeg", "\xff\xd8", Decode, DecodeConfig)
   795	}
   796	

View as plain text