Debian Codegraph @

tiff/tag.go

raw
1 package tiff
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "math/big"
10 "strings"
11 "unicode"
12 "unicode/utf8"
13 )
14
15 // Format specifies the Go type equivalent used to represent the basic
16 // tiff data types.
17 type Format int
18
19 const (
20 IntVal Format = iota
21 FloatVal
22 RatVal
23 StringVal
24 UndefVal
25 OtherVal
26 )
27
28 var ErrShortReadTagValue = errors.New("tiff: short read of tag value")
29
30 var formatNames = map[Format]string{
31 IntVal: "int",
32 FloatVal: "float",
33 RatVal: "rational",
34 StringVal: "string",
35 UndefVal: "undefined",
36 OtherVal: "other",
37 }
38
39 // DataType represents the basic tiff tag data types.
40 type DataType uint16
41
42 const (
43 DTByte DataType = 1
44 DTAscii DataType = 2
45 DTShort DataType = 3
46 DTLong DataType = 4
47 DTRational DataType = 5
48 DTSByte DataType = 6
49 DTUndefined DataType = 7
50 DTSShort DataType = 8
51 DTSLong DataType = 9
52 DTSRational DataType = 10
53 DTFloat DataType = 11
54 DTDouble DataType = 12
55 )
56
57 var typeNames = map[DataType]string{
58 DTByte: "byte",
59 DTAscii: "ascii",
60 DTShort: "short",
61 DTLong: "long",
62 DTRational: "rational",
63 DTSByte: "signed byte",
64 DTUndefined: "undefined",
65 DTSShort: "signed short",
66 DTSLong: "signed long",
67 DTSRational: "signed rational",
68 DTFloat: "float",
69 DTDouble: "double",
70 }
71
72 // typeSize specifies the size in bytes of each type.
73 var typeSize = map[DataType]uint32{
74 DTByte: 1,
75 DTAscii: 1,
76 DTShort: 2,
77 DTLong: 4,
78 DTRational: 8,
79 DTSByte: 1,
80 DTUndefined: 1,
81 DTSShort: 2,
82 DTSLong: 4,
83 DTSRational: 8,
84 DTFloat: 4,
85 DTDouble: 8,
86 }
87
88 // Tag reflects the parsed content of a tiff IFD tag.
89 type Tag struct {
90 // Id is the 2-byte tiff tag identifier.
91 Id uint16
92 // Type is an integer (1 through 12) indicating the tag value's data type.
93 Type DataType
94 // Count is the number of type Type stored in the tag's value (i.e. the
95 // tag's value is an array of type Type and length Count).
96 Count uint32
97 // Val holds the bytes that represent the tag's value.
98 Val []byte
99 // ValOffset holds byte offset of the tag value w.r.t. the beginning of the
100 // reader it was decoded from. Zero if the tag value fit inside the offset
101 // field.
102 ValOffset uint32
103
104 order binary.ByteOrder
105 intVals []int64
106 floatVals []float64
107 ratVals [][]int64
108 strVal string
109 format Format
110 }
111
112 // DecodeTag parses a tiff-encoded IFD tag from r and returns a Tag object. The
113 // first read from r should be the first byte of the tag. ReadAt offsets should
114 // generally be relative to the beginning of the tiff structure (not relative
115 // to the beginning of the tag).
116 func DecodeTag(r ReadAtReader, order binary.ByteOrder) (*Tag, error) {
117 t := new(Tag)
118 t.order = order
119
120 err := binary.Read(r, order, &t.Id)
121 if err != nil {
122 return nil, errors.New("tiff: tag id read failed: " + err.Error())
123 }
124
125 err = binary.Read(r, order, &t.Type)
126 if err != nil {
127 return nil, errors.New("tiff: tag type read failed: " + err.Error())
128 }
129
130 err = binary.Read(r, order, &t.Count)
131 if err != nil {
132 return nil, errors.New("tiff: tag component count read failed: " + err.Error())
133 }
134
135 // There seems to be a relatively common corrupt tag which has a Count of
136 // MaxUint32. This is probably not a valid value, so return early.
137 if t.Count == 1<<32-1 {
138 return t, errors.New("invalid Count offset in tag")
139 }
140
141 valLen := typeSize[t.Type] * t.Count
142 if valLen == 0 {
143 return t, errors.New("zero length tag value")
144 }
145
146 if valLen > 4 {
147 binary.Read(r, order, &t.ValOffset)
148
149 // Use a bytes.Buffer so we don't allocate a huge slice if the tag
150 // is corrupt.
151 var buff bytes.Buffer
152 sr := io.NewSectionReader(r, int64(t.ValOffset), int64(valLen))
153 n, err := io.Copy(&buff, sr)
154 if err != nil {
155 return t, errors.New("tiff: tag value read failed: " + err.Error())
156 } else if n != int64(valLen) {
157 return t, ErrShortReadTagValue
158 }
159 t.Val = buff.Bytes()
160
161 } else {
162 val := make([]byte, valLen)
163 if _, err = io.ReadFull(r, val); err != nil {
164 return t, errors.New("tiff: tag offset read failed: " + err.Error())
165 }
166 // ignore padding.
167 if _, err = io.ReadFull(r, make([]byte, 4-valLen)); err != nil {
168 return t, errors.New("tiff: tag offset read failed: " + err.Error())
169 }
170
171 t.Val = val
172 }
173
174 return t, t.convertVals()
175 }
176
177 func (t *Tag) convertVals() error {
178 r := bytes.NewReader(t.Val)
179
180 switch t.Type {
181 case DTAscii:
182 if len(t.Val) <= 0 {
183 break
184 }
185 nullPos := bytes.IndexByte(t.Val, 0)
186 if nullPos == -1 {
187 t.strVal = string(t.Val)
188 } else {
189 // ignore all trailing NULL bytes, in case of a broken t.Count
190 t.strVal = string(t.Val[:nullPos])
191 }
192 case DTByte:
193 var v uint8
194 t.intVals = make([]int64, int(t.Count))
195 for i := range t.intVals {
196 err := binary.Read(r, t.order, &v)
197 if err != nil {
198 return err
199 }
200 t.intVals[i] = int64(v)
201 }
202 case DTShort:
203 var v uint16
204 t.intVals = make([]int64, int(t.Count))
205 for i := range t.intVals {
206 err := binary.Read(r, t.order, &v)
207 if err != nil {
208 return err
209 }
210 t.intVals[i] = int64(v)
211 }
212 case DTLong:
213 var v uint32
214 t.intVals = make([]int64, int(t.Count))
215 for i := range t.intVals {
216 err := binary.Read(r, t.order, &v)
217 if err != nil {
218 return err
219 }
220 t.intVals[i] = int64(v)
221 }
222 case DTSByte:
223 var v int8
224 t.intVals = make([]int64, int(t.Count))
225 for i := range t.intVals {
226 err := binary.Read(r, t.order, &v)
227 if err != nil {
228 return err
229 }
230 t.intVals[i] = int64(v)
231 }
232 case DTSShort:
233 var v int16
234 t.intVals = make([]int64, int(t.Count))
235 for i := range t.intVals {
236 err := binary.Read(r, t.order, &v)
237 if err != nil {
238 return err
239 }
240 t.intVals[i] = int64(v)
241 }
242 case DTSLong:
243 var v int32
244 t.intVals = make([]int64, int(t.Count))
245 for i := range t.intVals {
246 err := binary.Read(r, t.order, &v)
247 if err != nil {
248 return err
249 }
250 t.intVals[i] = int64(v)
251 }
252 case DTRational:
253 t.ratVals = make([][]int64, int(t.Count))
254 for i := range t.ratVals {
255 var n, d uint32
256 err := binary.Read(r, t.order, &n)
257 if err != nil {
258 return err
259 }
260 err = binary.Read(r, t.order, &d)
261 if err != nil {
262 return err
263 }
264 t.ratVals[i] = []int64{int64(n), int64(d)}
265 }
266 case DTSRational:
267 t.ratVals = make([][]int64, int(t.Count))
268 for i := range t.ratVals {
269 var n, d int32
270 err := binary.Read(r, t.order, &n)
271 if err != nil {
272 return err
273 }
274 err = binary.Read(r, t.order, &d)
275 if err != nil {
276 return err
277 }
278 t.ratVals[i] = []int64{int64(n), int64(d)}
279 }
280 case DTFloat: // float32
281 t.floatVals = make([]float64, int(t.Count))
282 for i := range t.floatVals {
283 var v float32
284 err := binary.Read(r, t.order, &v)
285 if err != nil {
286 return err
287 }
288 t.floatVals[i] = float64(v)
289 }
290 case DTDouble:
291 t.floatVals = make([]float64, int(t.Count))
292 for i := range t.floatVals {
293 var u float64
294 err := binary.Read(r, t.order, &u)
295 if err != nil {
296 return err
297 }
298 t.floatVals[i] = u
299 }
300 }
301
302 switch t.Type {
303 case DTByte, DTShort, DTLong, DTSByte, DTSShort, DTSLong:
304 t.format = IntVal
305 case DTRational, DTSRational:
306 t.format = RatVal
307 case DTFloat, DTDouble:
308 t.format = FloatVal
309 case DTAscii:
310 t.format = StringVal
311 case DTUndefined:
312 t.format = UndefVal
313 default:
314 t.format = OtherVal
315 }
316
317 return nil
318 }
319
320 // Format returns a value indicating which method can be called to retrieve the
321 // tag's value properly typed (e.g. integer, rational, etc.).
322 func (t *Tag) Format() Format { return t.format }
323
324 func (t *Tag) typeErr(to Format) error {
325 return &wrongFmtErr{typeNames[t.Type], formatNames[to]}
326 }
327
328 // Rat returns the tag's i'th value as a rational number. It returns a nil and
329 // an error if this tag's Format is not RatVal. It panics for zero deminators
330 // or if i is out of range.
331 func (t *Tag) Rat(i int) (*big.Rat, error) {
332 n, d, err := t.Rat2(i)
333 if err != nil {
334 return nil, err
335 }
336 return big.NewRat(n, d), nil
337 }
338
339 // Rat2 returns the tag's i'th value as a rational number represented by a
340 // numerator-denominator pair. It returns an error if the tag's Format is not
341 // RatVal. It panics if i is out of range.
342 func (t *Tag) Rat2(i int) (num, den int64, err error) {
343 if t.format != RatVal {
344 return 0, 0, t.typeErr(RatVal)
345 }
346 return t.ratVals[i][0], t.ratVals[i][1], nil
347 }
348
349 // Int64 returns the tag's i'th value as an integer. It returns an error if the
350 // tag's Format is not IntVal. It panics if i is out of range.
351 func (t *Tag) Int64(i int) (int64, error) {
352 if t.format != IntVal {
353 return 0, t.typeErr(IntVal)
354 }
355 return t.intVals[i], nil
356 }
357
358 // Int returns the tag's i'th value as an integer. It returns an error if the
359 // tag's Format is not IntVal. It panics if i is out of range.
360 func (t *Tag) Int(i int) (int, error) {
361 if t.format != IntVal {
362 return 0, t.typeErr(IntVal)
363 }
364 return int(t.intVals[i]), nil
365 }
366
367 // Float returns the tag's i'th value as a float. It returns an error if the
368 // tag's Format is not IntVal. It panics if i is out of range.
369 func (t *Tag) Float(i int) (float64, error) {
370 if t.format != FloatVal {
371 return 0, t.typeErr(FloatVal)
372 }
373 return t.floatVals[i], nil
374 }
375
376 // StringVal returns the tag's value as a string. It returns an error if the
377 // tag's Format is not StringVal. It panics if i is out of range.
378 func (t *Tag) StringVal() (string, error) {
379 if t.format != StringVal {
380 return "", t.typeErr(StringVal)
381 }
382 return t.strVal, nil
383 }
384
385 // String returns a nicely formatted version of the tag.
386 func (t *Tag) String() string {
387 data, err := t.MarshalJSON()
388 if err != nil {
389 return "ERROR: " + err.Error()
390 }
391
392 if t.Count == 1 {
393 return strings.Trim(fmt.Sprintf("%s", data), "[]")
394 }
395 return fmt.Sprintf("%s", data)
396 }
397
398 func (t *Tag) MarshalJSON() ([]byte, error) {
399 switch t.format {
400 case StringVal, UndefVal:
401 return nullString(t.Val), nil
402 case OtherVal:
403 return []byte(fmt.Sprintf("unknown tag type '%v'", t.Type)), nil
404 }
405
406 rv := []string{}
407 for i := 0; i < int(t.Count); i++ {
408 switch t.format {
409 case RatVal:
410 n, d, _ := t.Rat2(i)
411 rv = append(rv, fmt.Sprintf(`"%v/%v"`, n, d))
412 case FloatVal:
413 v, _ := t.Float(i)
414 rv = append(rv, fmt.Sprintf("%v", v))
415 case IntVal:
416 v, _ := t.Int(i)
417 rv = append(rv, fmt.Sprintf("%v", v))
418 }
419 }
420 return []byte(fmt.Sprintf(`[%s]`, strings.Join(rv, ","))), nil
421 }
422
423 func nullString(in []byte) []byte {
424 rv := bytes.Buffer{}
425 rv.WriteByte('"')
426 for _, b := range in {
427 if unicode.IsPrint(rune(b)) {
428 rv.WriteByte(b)
429 }
430 }
431 rv.WriteByte('"')
432 rvb := rv.Bytes()
433 if utf8.Valid(rvb) {
434 return rvb
435 }
436 return []byte(`""`)
437 }
438
439 type wrongFmtErr struct {
440 From, To string
441 }
442
443 func (e *wrongFmtErr) Error() string {
444 return fmt.Sprintf("cannot convert tag type '%v' into '%v'", e.From, e.To)
445 }