PageRenderTime 46ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/third_party/gofrontend/libgo/go/image/jpeg/reader.go

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