OSDN Git Service

Update Go library to r60.
[pf3gnuchains/gcc-fork.git] / libgo / go / image / tiff / reader.go
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.
6 //
7 // The TIFF specification is at http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
8 package tiff
9
10 import (
11         "compress/lzw"
12         "compress/zlib"
13         "encoding/binary"
14         "image"
15         "io"
16         "io/ioutil"
17         "os"
18 )
19
20 // A FormatError reports that the input is not a valid TIFF image.
21 type FormatError string
22
23 func (e FormatError) String() string {
24         return "tiff: invalid format: " + string(e)
25 }
26
27 // An UnsupportedError reports that the input uses a valid but
28 // unimplemented feature.
29 type UnsupportedError string
30
31 func (e UnsupportedError) String() string {
32         return "tiff: unsupported feature: " + string(e)
33 }
34
35 // An InternalError reports that an internal error was encountered.
36 type InternalError string
37
38 func (e InternalError) String() string {
39         return "tiff: internal error: " + string(e)
40 }
41
42 type decoder struct {
43         r         io.ReaderAt
44         byteOrder binary.ByteOrder
45         config    image.Config
46         mode      imageMode
47         features  map[int][]uint
48         palette   []image.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.
58 func (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.
68 func (d *decoder) ifdUint(p []byte) (u []uint, err os.Error) {
69         var raw []byte
70         datatype := d.byteOrder.Uint16(p[2:4])
71         count := d.byteOrder.Uint32(p[4:8])
72         if datalen := lengths[datatype] * count; datalen > 4 {
73                 // The IFD contains a pointer to the real value.
74                 raw = make([]byte, datalen)
75                 _, err = d.r.ReadAt(raw, int64(d.byteOrder.Uint32(p[8:12])))
76         } else {
77                 raw = p[8 : 8+datalen]
78         }
79         if err != nil {
80                 return nil, err
81         }
82
83         u = make([]uint, count)
84         switch datatype {
85         case dtByte:
86                 for i := uint32(0); i < count; i++ {
87                         u[i] = uint(raw[i])
88                 }
89         case dtShort:
90                 for i := uint32(0); i < count; i++ {
91                         u[i] = uint(d.byteOrder.Uint16(raw[2*i : 2*(i+1)]))
92                 }
93         case dtLong:
94                 for i := uint32(0); i < count; i++ {
95                         u[i] = uint(d.byteOrder.Uint32(raw[4*i : 4*(i+1)]))
96                 }
97         default:
98                 return nil, UnsupportedError("data type")
99         }
100         return u, nil
101 }
102
103 // parseIFD decides whether the the IFD entry in p is "interesting" and
104 // stows away the data in the decoder.
105 func (d *decoder) parseIFD(p []byte) os.Error {
106         tag := d.byteOrder.Uint16(p[0:2])
107         switch tag {
108         case tBitsPerSample,
109                 tExtraSamples,
110                 tPhotometricInterpretation,
111                 tCompression,
112                 tPredictor,
113                 tStripOffsets,
114                 tStripByteCounts,
115                 tRowsPerStrip,
116                 tImageLength,
117                 tImageWidth:
118                 val, err := d.ifdUint(p)
119                 if err != nil {
120                         return err
121                 }
122                 d.features[int(tag)] = val
123         case tColorMap:
124                 val, err := d.ifdUint(p)
125                 if err != nil {
126                         return err
127                 }
128                 numcolors := len(val) / 3
129                 if len(val)%3 != 0 || numcolors <= 0 || numcolors > 256 {
130                         return FormatError("bad ColorMap length")
131                 }
132                 d.palette = make([]image.Color, numcolors)
133                 for i := 0; i < numcolors; i++ {
134                         d.palette[i] = image.RGBA64Color{
135                                 uint16(val[i]),
136                                 uint16(val[i+numcolors]),
137                                 uint16(val[i+2*numcolors]),
138                                 0xffff,
139                         }
140                 }
141         case tSampleFormat:
142                 // Page 27 of the spec: If the SampleFormat is present and
143                 // the value is not 1 [= unsigned integer data], a Baseline
144                 // TIFF reader that cannot handle the SampleFormat value
145                 // must terminate the import process gracefully.
146                 val, err := d.ifdUint(p)
147                 if err != nil {
148                         return err
149                 }
150                 for _, v := range val {
151                         if v != 1 {
152                                 return UnsupportedError("sample format")
153                         }
154                 }
155         }
156         return nil
157 }
158
159 // readBits reads n bits from the internal buffer starting at the current offset.
160 func (d *decoder) readBits(n uint) uint32 {
161         for d.nbits < n {
162                 d.v <<= 8
163                 d.v |= uint32(d.buf[d.off])
164                 d.off++
165                 d.nbits += 8
166         }
167         d.nbits -= n
168         rv := d.v >> d.nbits
169         d.v &^= rv << d.nbits
170         return rv
171 }
172
173 // flushBits discards the unread bits in the buffer used by readBits.
174 // It is used at the end of a line.
175 func (d *decoder) flushBits() {
176         d.v = 0
177         d.nbits = 0
178 }
179
180 // decode decodes the raw data of an image.
181 // It reads from d.buf and writes the strip with ymin <= y < ymax into dst.
182 func (d *decoder) decode(dst image.Image, ymin, ymax int) os.Error {
183         spp := len(d.features[tBitsPerSample]) // samples per pixel
184         d.off = 0
185         width := dst.Bounds().Dx()
186
187         // Apply horizontal predictor if necessary.
188         // In this case, p contains the color difference to the preceding pixel.
189         // See page 64-65 of the spec.
190         if d.firstVal(tPredictor) == prHorizontal && d.firstVal(tBitsPerSample) == 8 {
191                 for y := ymin; y < ymax; y++ {
192                         d.off += spp
193                         for x := 0; x < (width-1)*spp; x++ {
194                                 d.buf[d.off] += d.buf[d.off-spp]
195                                 d.off++
196                         }
197                 }
198                 d.off = 0
199         }
200
201         switch d.mode {
202         case mGray, mGrayInvert:
203                 img := dst.(*image.Gray)
204                 bpp := d.firstVal(tBitsPerSample)
205                 max := uint32((1 << bpp) - 1)
206                 for y := ymin; y < ymax; y++ {
207                         for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
208                                 v := uint8(d.readBits(bpp) * 0xff / max)
209                                 if d.mode == mGrayInvert {
210                                         v = 0xff - v
211                                 }
212                                 img.SetGray(x, y, image.GrayColor{v})
213                         }
214                         d.flushBits()
215                 }
216         case mPaletted:
217                 img := dst.(*image.Paletted)
218                 bpp := d.firstVal(tBitsPerSample)
219                 for y := ymin; y < ymax; y++ {
220                         for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
221                                 img.SetColorIndex(x, y, uint8(d.readBits(bpp)))
222                         }
223                         d.flushBits()
224                 }
225         case mRGB:
226                 img := dst.(*image.RGBA)
227                 for y := ymin; y < ymax; y++ {
228                         for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
229                                 img.SetRGBA(x, y, image.RGBAColor{d.buf[d.off], d.buf[d.off+1], d.buf[d.off+2], 0xff})
230                                 d.off += spp
231                         }
232                 }
233         case mNRGBA:
234                 img := dst.(*image.NRGBA)
235                 for y := ymin; y < ymax; y++ {
236                         for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
237                                 img.SetNRGBA(x, y, image.NRGBAColor{d.buf[d.off], d.buf[d.off+1], d.buf[d.off+2], d.buf[d.off+3]})
238                                 d.off += spp
239                         }
240                 }
241         case mRGBA:
242                 img := dst.(*image.RGBA)
243                 for y := ymin; y < ymax; y++ {
244                         for x := img.Rect.Min.X; x < img.Rect.Max.X; x++ {
245                                 img.SetRGBA(x, y, image.RGBAColor{d.buf[d.off], d.buf[d.off+1], d.buf[d.off+2], d.buf[d.off+3]})
246                                 d.off += spp
247                         }
248                 }
249         }
250
251         return nil
252 }
253
254 func newDecoder(r io.Reader) (*decoder, os.Error) {
255         d := &decoder{
256                 r:        newReaderAt(r),
257                 features: make(map[int][]uint),
258         }
259
260         p := make([]byte, 8)
261         if _, err := d.r.ReadAt(p, 0); err != nil {
262                 return nil, err
263         }
264         switch string(p[0:4]) {
265         case leHeader:
266                 d.byteOrder = binary.LittleEndian
267         case beHeader:
268                 d.byteOrder = binary.BigEndian
269         default:
270                 return nil, FormatError("malformed header")
271         }
272
273         ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
274
275         // The first two bytes contain the number of entries (12 bytes each).
276         if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
277                 return nil, err
278         }
279         numItems := int(d.byteOrder.Uint16(p[0:2]))
280
281         // All IFD entries are read in one chunk.
282         p = make([]byte, ifdLen*numItems)
283         if _, err := d.r.ReadAt(p, ifdOffset+2); err != nil {
284                 return nil, err
285         }
286
287         for i := 0; i < len(p); i += ifdLen {
288                 if err := d.parseIFD(p[i : i+ifdLen]); err != nil {
289                         return nil, err
290                 }
291         }
292
293         d.config.Width = int(d.firstVal(tImageWidth))
294         d.config.Height = int(d.firstVal(tImageLength))
295
296         if _, ok := d.features[tBitsPerSample]; !ok {
297                 return nil, FormatError("BitsPerSample tag missing")
298         }
299
300         // Determine the image mode.
301         switch d.firstVal(tPhotometricInterpretation) {
302         case pRGB:
303                 for _, b := range d.features[tBitsPerSample] {
304                         if b != 8 {
305                                 return nil, UnsupportedError("non-8-bit RGB image")
306                         }
307                 }
308                 d.config.ColorModel = image.RGBAColorModel
309                 // RGB images normally have 3 samples per pixel.
310                 // If there are more, ExtraSamples (p. 31-32 of the spec)
311                 // gives their meaning (usually an alpha channel).
312                 switch len(d.features[tBitsPerSample]) {
313                 case 3:
314                         d.mode = mRGB
315                 case 4:
316                         switch d.firstVal(tExtraSamples) {
317                         case 1:
318                                 d.mode = mRGBA
319                         case 2:
320                                 d.mode = mNRGBA
321                                 d.config.ColorModel = image.NRGBAColorModel
322                         default:
323                                 // The extra sample is discarded.
324                                 d.mode = mRGB
325                         }
326                 default:
327                         return nil, FormatError("wrong number of samples for RGB")
328                 }
329         case pPaletted:
330                 d.mode = mPaletted
331                 d.config.ColorModel = image.PalettedColorModel(d.palette)
332         case pWhiteIsZero:
333                 d.mode = mGrayInvert
334                 d.config.ColorModel = image.GrayColorModel
335         case pBlackIsZero:
336                 d.mode = mGray
337                 d.config.ColorModel = image.GrayColorModel
338         default:
339                 return nil, UnsupportedError("color model")
340         }
341
342         return d, nil
343 }
344
345 // DecodeConfig returns the color model and dimensions of a TIFF image without
346 // decoding the entire image.
347 func DecodeConfig(r io.Reader) (image.Config, os.Error) {
348         d, err := newDecoder(r)
349         if err != nil {
350                 return image.Config{}, err
351         }
352         return d.config, nil
353 }
354
355 // Decode reads a TIFF image from r and returns it as an image.Image.
356 // The type of Image returned depends on the contents of the TIFF.
357 func Decode(r io.Reader) (img image.Image, err os.Error) {
358         d, err := newDecoder(r)
359         if err != nil {
360                 return
361         }
362
363         // Check if we have the right number of strips, offsets and counts.
364         rps := int(d.firstVal(tRowsPerStrip))
365         if rps == 0 {
366                 // Assume only one strip.
367                 rps = d.config.Height
368         }
369         numStrips := (d.config.Height + rps - 1) / rps
370         if rps == 0 || len(d.features[tStripOffsets]) < numStrips || len(d.features[tStripByteCounts]) < numStrips {
371                 return nil, FormatError("inconsistent header")
372         }
373
374         switch d.mode {
375         case mGray, mGrayInvert:
376                 img = image.NewGray(d.config.Width, d.config.Height)
377         case mPaletted:
378                 img = image.NewPaletted(d.config.Width, d.config.Height, d.palette)
379         case mNRGBA:
380                 img = image.NewNRGBA(d.config.Width, d.config.Height)
381         case mRGB, mRGBA:
382                 img = image.NewRGBA(d.config.Width, d.config.Height)
383         }
384
385         for i := 0; i < numStrips; i++ {
386                 ymin := i * rps
387                 // The last strip may be shorter.
388                 if i == numStrips-1 && d.config.Height%rps != 0 {
389                         rps = d.config.Height % rps
390                 }
391                 offset := int64(d.features[tStripOffsets][i])
392                 n := int64(d.features[tStripByteCounts][i])
393                 switch d.firstVal(tCompression) {
394                 case cNone:
395                         // TODO(bsiegert): Avoid copy if r is a tiff.buffer.
396                         d.buf = make([]byte, n)
397                         _, err = d.r.ReadAt(d.buf, offset)
398                 case cLZW:
399                         r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
400                         d.buf, err = ioutil.ReadAll(r)
401                         r.Close()
402                 case cDeflate, cDeflateOld:
403                         r, err := zlib.NewReader(io.NewSectionReader(d.r, offset, n))
404                         if err != nil {
405                                 return nil, err
406                         }
407                         d.buf, err = ioutil.ReadAll(r)
408                         r.Close()
409                 default:
410                         err = UnsupportedError("compression")
411                 }
412                 if err != nil {
413                         return
414                 }
415                 err = d.decode(img, ymin, ymin+rps)
416         }
417         return
418 }
419
420 func init() {
421         image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
422         image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)
423 }