1// Copyright 2011 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 tiff implements a TIFF image decoder and encoder.
6//
7// The TIFF specification is at http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
8package tiff // import "golang.org/x/image/tiff"
9
10import (
11 "compress/zlib"
12 "encoding/binary"
13 "fmt"
14 "image"
15 "image/color"
16 "io"
17 "io/ioutil"
18 "math"
19
20 "golang.org/x/image/ccitt"
21 "golang.org/x/image/tiff/lzw"
22)
23
24// A FormatError reports that the input is not a valid TIFF image.
25type FormatError string
26
27func (e FormatError) Error() string {
28 return "tiff: invalid format: " + string(e)
29}
30
31// An UnsupportedError reports that the input uses a valid but
32// unimplemented feature.
33type UnsupportedError string
34
35func (e UnsupportedError) Error() string {
36 return "tiff: unsupported feature: " + string(e)
37}
38
39var errNoPixels = FormatError("not enough pixel data")
40
41type decoder struct {
42 r io.ReaderAt
43 byteOrder binary.ByteOrder
44 config image.Config
45 mode imageMode
46 bpp uint
47 features map[int][]uint
48 palette []color.Color
49
50 buf []byte
51 off int // Current offset in buf.
52 v uint32 // Buffer value for reading with arbitrary bit depths.
53 nbits uint // Remaining number of bits in v.
54}
55
56// firstVal returns the first uint of the features entry with the given tag,
57// or 0 if the tag does not exist.
58func (d *decoder) firstVal(tag int) uint {
59 f := d.features[tag]
60 if len(f) == 0 {
61 return 0
62 }
63 return f[0]
64}
65
66// ifdUint decodes the IFD entry in p, which must be of the Byte, Short
67// or Long type, and returns the decoded uint values.
68func (d *decoder) ifdUint(p []byte) (u []uint, err error) {
69 var raw []byte
70 if len(p) < ifdLen {
71 return nil, FormatError("bad IFD entry")
72 }
73
74 datatype := d.byteOrder.Uint16(p[2:4])
75 if dt := int(datatype); dt <= 0 || dt >= len(lengths) {
76 return nil, UnsupportedError("IFD entry datatype")
77 }
78
79 count := d.byteOrder.Uint32(p[4:8])
80 if count > math.MaxInt32/lengths[datatype] {
81 return nil, FormatError("IFD data too large")
82 }
83 if datalen := lengths[datatype] * count; datalen > 4 {
84 // The IFD contains a pointer to the real value.
85 raw = make([]byte, datalen)
86 _, err = d.r.ReadAt(raw, int64(d.byteOrder.Uint32(p[8:12])))
87 } else {
88 raw = p[8 : 8+datalen]
89 }
90 if err != nil {
91 return nil, err
92 }
93
94 u = make([]uint, count)
95 switch datatype {
96 case dtByte:
97 for i := uint32(0); i < count; i++ {
98 u[i] = uint(raw[i])
99 }
100 case dtShort:
101 for i := uint32(0); i < count; i++ {
102 u[i] = uint(d.byteOrder.Uint16(raw[2*i : 2*(i+1)]))
103 }
104 case dtLong:
105 for i := uint32(0); i < count; i++ {
106 u[i] = uint(d.byteOrder.Uint32(raw[4*i : 4*(i+1)]))
107 }
108 default:
109 return nil, UnsupportedError("data type")
110 }
111 return u, nil
112}
113
114// parseIFD decides whether the IFD entry in p is "interesting" and
115// stows away the data in the decoder. It returns the tag number of the
116// entry and an error, if any.
117func (d *decoder) parseIFD(p []byte) (int, error) {
118 tag := d.byteOrder.Uint16(p[0:2])
119 switch tag {
120 case tBitsPerSample,
121 tExtraSamples,
122 tPhotometricInterpretation,
123 tCompression,
124 tPredictor,
125 tStripOffsets,
126 tStripByteCounts,
127 tRowsPerStrip,
128 tTileWidth,
129 tTileLength,
130 tTileOffsets,
131 tTileByteCounts,
132 tImageLength,
133 tImageWidth,
134 tFillOrder,
135 tT4Options,
136 tT6Options:
137 val, err := d.ifdUint(p)
138 if err != nil {
139 return 0, err
140 }
141 d.features[int(tag)] = val
142 case tColorMap:
143 val, err := d.ifdUint(p)
144 if err != nil {
145 return 0, err
146 }
147 numcolors := len(val) / 3
148 if len(val)%3 != 0 || numcolors <= 0 || numcolors > 256 {
149 return 0, FormatError("bad ColorMap length")
150 }
151 d.palette = make([]color.Color, numcolors)
152 for i := 0; i < numcolors; i++ {
153 d.palette[i] = color.RGBA64{
154 uint16(val[i]),
155 uint16(val[i+numcolors]),
156 uint16(val[i+2*numcolors]),
157 0xffff,
158 }
159 }
160 case tSampleFormat:
161 // Page 27 of the spec: If the SampleFormat is present and
162 // the value is not 1 [= unsigned integer data], a Baseline
163 // TIFF reader that cannot handle the SampleFormat value
164 // must terminate the import process gracefully.
165 val, err := d.ifdUint(p)
166 if err != nil {
167 return 0, err
168 }
169 for _, v := range val {
170 if v != 1 {
171 return 0, UnsupportedError("sample format")
172 }
173 }
174 }
175 return int(tag), nil
176}
177
178// readBits reads n bits from the internal buffer starting at the current offset.
179func (d *decoder) readBits(n uint) (v uint32, ok bool) {
180 for d.nbits < n {
181 d.v <<= 8
182 if d.off >= len(d.buf) {
183 return 0, false
184 }
185 d.v |= uint32(d.buf[d.off])
186 d.off++
187 d.nbits += 8
188 }
189 d.nbits -= n
190 rv := d.v >> d.nbits
191 d.v &^= rv << d.nbits
192 return rv, true
193}
194
195// flushBits discards the unread bits in the buffer used by readBits.
196// It is used at the end of a line.
197func (d *decoder) flushBits() {
198 d.v = 0
199 d.nbits = 0
200}
201
202// minInt returns the smaller of x or y.
203func minInt(a, b int) int {
204 if a <= b {
205 return a
206 }
207 return b
208}
209
210// decode decodes the raw data of an image.
211// It reads from d.buf and writes the strip or tile into dst.
212func (d *decoder) decode(dst image.Image, xmin, ymin, xmax, ymax int) error {
213 d.off = 0
214
215 // Apply horizontal predictor if necessary.
216 // In this case, p contains the color difference to the preceding pixel.
217 // See page 64-65 of the spec.
218 if d.firstVal(tPredictor) == prHorizontal {
219 switch d.bpp {
220 case 16:
221 var off int
222 n := 2 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
223 for y := ymin; y < ymax; y++ {
224 off += n
225 for x := 0; x < (xmax-xmin-1)*n; x += 2 {
226 if off+2 > len(d.buf) {
227 return errNoPixels
228 }
229 v0 := d.byteOrder.Uint16(d.buf[off-n : off-n+2])
230 v1 := d.byteOrder.Uint16(d.buf[off : off+2])
231 d.byteOrder.PutUint16(d.buf[off:off+2], v1+v0)
232 off += 2
233 }
234 }
235 case 8:
236 var off int
237 n := 1 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
238 for y := ymin; y < ymax; y++ {
239 off += n
240 for x := 0; x < (xmax-xmin-1)*n; x++ {
241 if off >= len(d.buf) {
242 return errNoPixels
243 }
244 d.buf[off] += d.buf[off-n]
245 off++
246 }
247 }
248 case 1:
249 return UnsupportedError("horizontal predictor with 1 BitsPerSample")
250 }
251 }
252
253 rMaxX := minInt(xmax, dst.Bounds().Max.X)
254 rMaxY := minInt(ymax, dst.Bounds().Max.Y)
255 switch d.mode {
256 case mGray, mGrayInvert:
257 if d.bpp == 16 {
258 img := dst.(*image.Gray16)
259 for y := ymin; y < rMaxY; y++ {
260 for x := xmin; x < rMaxX; x++ {
261 if d.off+2 > len(d.buf) {
262 return errNoPixels
263 }
264 v := d.byteOrder.Uint16(d.buf[d.off : d.off+2])
265 d.off += 2
266 if d.mode == mGrayInvert {
267 v = 0xffff - v
268 }
269 img.SetGray16(x, y, color.Gray16{v})
270 }
271 if rMaxX == img.Bounds().Max.X {
272 d.off += 2 * (xmax - img.Bounds().Max.X)
273 }
274 }
275 } else {
276 img := dst.(*image.Gray)
277 max := uint32((1 << d.bpp) - 1)
278 for y := ymin; y < rMaxY; y++ {
279 for x := xmin; x < rMaxX; x++ {
280 v, ok := d.readBits(d.bpp)
281 if !ok {
282 return errNoPixels
283 }
284 v = v * 0xff / max
285 if d.mode == mGrayInvert {
286 v = 0xff - v
287 }
288 img.SetGray(x, y, color.Gray{uint8(v)})
289 }
290 d.flushBits()
291 }
292 }
293 case mPaletted:
294 img := dst.(*image.Paletted)
295 for y := ymin; y < rMaxY; y++ {
296 for x := xmin; x < rMaxX; x++ {
297 v, ok := d.readBits(d.bpp)
298 if !ok {
299 return errNoPixels
300 }
301 img.SetColorIndex(x, y, uint8(v))
302 }
303 d.flushBits()
304 }
305 case mRGB:
306 if d.bpp == 16 {
307 img := dst.(*image.RGBA64)
308 for y := ymin; y < rMaxY; y++ {
309 for x := xmin; x < rMaxX; x++ {
310 if d.off+6 > len(d.buf) {
311 return errNoPixels
312 }
313 r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
314 g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
315 b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
316 d.off += 6
317 img.SetRGBA64(x, y, color.RGBA64{r, g, b, 0xffff})
318 }
319 }
320 } else {
321 img := dst.(*image.RGBA)
322 for y := ymin; y < rMaxY; y++ {
323 min := img.PixOffset(xmin, y)
324 max := img.PixOffset(rMaxX, y)
325 off := (y - ymin) * (xmax - xmin) * 3
326 for i := min; i < max; i += 4 {
327 if off+3 > len(d.buf) {
328 return errNoPixels
329 }
330 img.Pix[i+0] = d.buf[off+0]
331 img.Pix[i+1] = d.buf[off+1]
332 img.Pix[i+2] = d.buf[off+2]
333 img.Pix[i+3] = 0xff
334 off += 3
335 }
336 }
337 }
338 case mNRGBA:
339 if d.bpp == 16 {
340 img := dst.(*image.NRGBA64)
341 for y := ymin; y < rMaxY; y++ {
342 for x := xmin; x < rMaxX; x++ {
343 if d.off+8 > len(d.buf) {
344 return errNoPixels
345 }
346 r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
347 g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
348 b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
349 a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
350 d.off += 8
351 img.SetNRGBA64(x, y, color.NRGBA64{r, g, b, a})
352 }
353 }
354 } else {
355 img := dst.(*image.NRGBA)
356 for y := ymin; y < rMaxY; y++ {
357 min := img.PixOffset(xmin, y)
358 max := img.PixOffset(rMaxX, y)
359 i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
360 if i1 > len(d.buf) {
361 return errNoPixels
362 }
363 copy(img.Pix[min:max], d.buf[i0:i1])
364 }
365 }
366 case mRGBA:
367 if d.bpp == 16 {
368 img := dst.(*image.RGBA64)
369 for y := ymin; y < rMaxY; y++ {
370 for x := xmin; x < rMaxX; x++ {
371 if d.off+8 > len(d.buf) {
372 return errNoPixels
373 }
374 r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
375 g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
376 b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
377 a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
378 d.off += 8
379 img.SetRGBA64(x, y, color.RGBA64{r, g, b, a})
380 }
381 }
382 } else {
383 img := dst.(*image.RGBA)
384 for y := ymin; y < rMaxY; y++ {
385 min := img.PixOffset(xmin, y)
386 max := img.PixOffset(rMaxX, y)
387 i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
388 if i1 > len(d.buf) {
389 return errNoPixels
390 }
391 copy(img.Pix[min:max], d.buf[i0:i1])
392 }
393 }
394 }
395
396 return nil
397}
398
399func newDecoder(r io.Reader) (*decoder, error) {
400 d := &decoder{
401 r: newReaderAt(r),
402 features: make(map[int][]uint),
403 }
404
405 p := make([]byte, 8)
406 if _, err := d.r.ReadAt(p, 0); err != nil {
407 return nil, err
408 }
409 switch string(p[0:4]) {
410 case leHeader:
411 d.byteOrder = binary.LittleEndian
412 case beHeader:
413 d.byteOrder = binary.BigEndian
414 default:
415 return nil, FormatError("malformed header")
416 }
417
418 ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
419
420 // The first two bytes contain the number of entries (12 bytes each).
421 if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
422 return nil, err
423 }
424 numItems := int(d.byteOrder.Uint16(p[0:2]))
425
426 // All IFD entries are read in one chunk.
427 p = make([]byte, ifdLen*numItems)
428 if _, err := d.r.ReadAt(p, ifdOffset+2); err != nil {
429 return nil, err
430 }
431
432 prevTag := -1
433 for i := 0; i < len(p); i += ifdLen {
434 tag, err := d.parseIFD(p[i : i+ifdLen])
435 if err != nil {
436 return nil, err
437 }
438 if tag <= prevTag {
439 return nil, FormatError("tags are not sorted in ascending order")
440 }
441 prevTag = tag
442 }
443
444 d.config.Width = int(d.firstVal(tImageWidth))
445 d.config.Height = int(d.firstVal(tImageLength))
446
447 if _, ok := d.features[tBitsPerSample]; !ok {
448 // Default is 1 per specification.
449 d.features[tBitsPerSample] = []uint{1}
450 }
451 d.bpp = d.firstVal(tBitsPerSample)
452 switch d.bpp {
453 case 0:
454 return nil, FormatError("BitsPerSample must not be 0")
455 case 1, 8, 16:
456 // Nothing to do, these are accepted by this implementation.
457 default:
458 return nil, UnsupportedError(fmt.Sprintf("BitsPerSample of %v", d.bpp))
459 }
460
461 // Determine the image mode.
462 switch d.firstVal(tPhotometricInterpretation) {
463 case pRGB:
464 if d.bpp == 16 {
465 for _, b := range d.features[tBitsPerSample] {
466 if b != 16 {
467 return nil, FormatError("wrong number of samples for 16bit RGB")
468 }
469 }
470 } else {
471 for _, b := range d.features[tBitsPerSample] {
472 if b != 8 {
473 return nil, FormatError("wrong number of samples for 8bit RGB")
474 }
475 }
476 }
477 // RGB images normally have 3 samples per pixel.
478 // If there are more, ExtraSamples (p. 31-32 of the spec)
479 // gives their meaning (usually an alpha channel).
480 //
481 // This implementation does not support extra samples
482 // of an unspecified type.
483 switch len(d.features[tBitsPerSample]) {
484 case 3:
485 d.mode = mRGB
486 if d.bpp == 16 {
487 d.config.ColorModel = color.RGBA64Model
488 } else {
489 d.config.ColorModel = color.RGBAModel
490 }
491 case 4:
492 switch d.firstVal(tExtraSamples) {
493 case 1:
494 d.mode = mRGBA
495 if d.bpp == 16 {
496 d.config.ColorModel = color.RGBA64Model
497 } else {
498 d.config.ColorModel = color.RGBAModel
499 }
500 case 2:
501 d.mode = mNRGBA
502 if d.bpp == 16 {
503 d.config.ColorModel = color.NRGBA64Model
504 } else {
505 d.config.ColorModel = color.NRGBAModel
506 }
507 default:
508 return nil, FormatError("wrong number of samples for RGB")
509 }
510 default:
511 return nil, FormatError("wrong number of samples for RGB")
512 }
513 case pPaletted:
514 d.mode = mPaletted
515 d.config.ColorModel = color.Palette(d.palette)
516 case pWhiteIsZero:
517 d.mode = mGrayInvert
518 if d.bpp == 16 {
519 d.config.ColorModel = color.Gray16Model
520 } else {
521 d.config.ColorModel = color.GrayModel
522 }
523 case pBlackIsZero:
524 d.mode = mGray
525 if d.bpp == 16 {
526 d.config.ColorModel = color.Gray16Model
527 } else {
528 d.config.ColorModel = color.GrayModel
529 }
530 default:
531 return nil, UnsupportedError("color model")
532 }
533
534 return d, nil
535}
536
537// DecodeConfig returns the color model and dimensions of a TIFF image without
538// decoding the entire image.
539func DecodeConfig(r io.Reader) (image.Config, error) {
540 d, err := newDecoder(r)
541 if err != nil {
542 return image.Config{}, err
543 }
544 return d.config, nil
545}
546
547func ccittFillOrder(tiffFillOrder uint) ccitt.Order {
548 if tiffFillOrder == 2 {
549 return ccitt.LSB
550 }
551 return ccitt.MSB
552}
553
554// Decode reads a TIFF image from r and returns it as an image.Image.
555// The type of Image returned depends on the contents of the TIFF.
556func Decode(r io.Reader) (img image.Image, err error) {
557 d, err := newDecoder(r)
558 if err != nil {
559 return
560 }
561
562 blockPadding := false
563 blockWidth := d.config.Width
564 blockHeight := d.config.Height
565 blocksAcross := 1
566 blocksDown := 1
567
568 if d.config.Width == 0 {
569 blocksAcross = 0
570 }
571 if d.config.Height == 0 {
572 blocksDown = 0
573 }
574
575 var blockOffsets, blockCounts []uint
576
577 if int(d.firstVal(tTileWidth)) != 0 {
578 blockPadding = true
579
580 blockWidth = int(d.firstVal(tTileWidth))
581 blockHeight = int(d.firstVal(tTileLength))
582
583 if blockWidth != 0 {
584 blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
585 }
586 if blockHeight != 0 {
587 blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
588 }
589
590 blockCounts = d.features[tTileByteCounts]
591 blockOffsets = d.features[tTileOffsets]
592
593 } else {
594 if int(d.firstVal(tRowsPerStrip)) != 0 {
595 blockHeight = int(d.firstVal(tRowsPerStrip))
596 }
597
598 if blockHeight != 0 {
599 blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
600 }
601
602 blockOffsets = d.features[tStripOffsets]
603 blockCounts = d.features[tStripByteCounts]
604 }
605
606 // Check if we have the right number of strips/tiles, offsets and counts.
607 if n := blocksAcross * blocksDown; len(blockOffsets) < n || len(blockCounts) < n {
608 return nil, FormatError("inconsistent header")
609 }
610
611 imgRect := image.Rect(0, 0, d.config.Width, d.config.Height)
612 switch d.mode {
613 case mGray, mGrayInvert:
614 if d.bpp == 16 {
615 img = image.NewGray16(imgRect)
616 } else {
617 img = image.NewGray(imgRect)
618 }
619 case mPaletted:
620 img = image.NewPaletted(imgRect, d.palette)
621 case mNRGBA:
622 if d.bpp == 16 {
623 img = image.NewNRGBA64(imgRect)
624 } else {
625 img = image.NewNRGBA(imgRect)
626 }
627 case mRGB, mRGBA:
628 if d.bpp == 16 {
629 img = image.NewRGBA64(imgRect)
630 } else {
631 img = image.NewRGBA(imgRect)
632 }
633 }
634
635 for i := 0; i < blocksAcross; i++ {
636 blkW := blockWidth
637 if !blockPadding && i == blocksAcross-1 && d.config.Width%blockWidth != 0 {
638 blkW = d.config.Width % blockWidth
639 }
640 for j := 0; j < blocksDown; j++ {
641 blkH := blockHeight
642 if !blockPadding && j == blocksDown-1 && d.config.Height%blockHeight != 0 {
643 blkH = d.config.Height % blockHeight
644 }
645 offset := int64(blockOffsets[j*blocksAcross+i])
646 n := int64(blockCounts[j*blocksAcross+i])
647 switch d.firstVal(tCompression) {
648
649 // According to the spec, Compression does not have a default value,
650 // but some tools interpret a missing Compression value as none so we do
651 // the same.
652 case cNone, 0:
653 if b, ok := d.r.(*buffer); ok {
654 d.buf, err = b.Slice(int(offset), int(n))
655 } else {
656 d.buf = make([]byte, n)
657 _, err = d.r.ReadAt(d.buf, offset)
658 }
659 case cG3:
660 inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
661 order := ccittFillOrder(d.firstVal(tFillOrder))
662 r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group3, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
663 d.buf, err = ioutil.ReadAll(r)
664 case cG4:
665 inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
666 order := ccittFillOrder(d.firstVal(tFillOrder))
667 r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group4, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
668 d.buf, err = ioutil.ReadAll(r)
669 case cLZW:
670 r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
671 d.buf, err = ioutil.ReadAll(r)
672 r.Close()
673 case cDeflate, cDeflateOld:
674 var r io.ReadCloser
675 r, err = zlib.NewReader(io.NewSectionReader(d.r, offset, n))
676 if err != nil {
677 return nil, err
678 }
679 d.buf, err = ioutil.ReadAll(r)
680 r.Close()
681 case cPackBits:
682 d.buf, err = unpackBits(io.NewSectionReader(d.r, offset, n))
683 default:
684 err = UnsupportedError(fmt.Sprintf("compression value %d", d.firstVal(tCompression)))
685 }
686 if err != nil {
687 return nil, err
688 }
689
690 xmin := i * blockWidth
691 ymin := j * blockHeight
692 xmax := xmin + blkW
693 ymax := ymin + blkH
694 err = d.decode(img, xmin, ymin, xmax, ymax)
695 if err != nil {
696 return nil, err
697 }
698 }
699 }
700 return
701}
702
703func init() {
704 image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
705 image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)
706}