FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
tiff.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2006 Konstantin Shishkov
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file
23  * TIFF image decoder
24  * @author Konstantin Shishkov
25  */
26 
27 #include "avcodec.h"
28 #include "bytestream.h"
29 #include "config.h"
30 #if CONFIG_ZLIB
31 #include <zlib.h>
32 #endif
33 #include "lzw.h"
34 #include "tiff.h"
35 #include "tiff_data.h"
36 #include "faxcompr.h"
37 #include "internal.h"
38 #include "mathops.h"
39 #include "libavutil/attributes.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/imgutils.h"
42 #include "libavutil/avstring.h"
43 
44 typedef struct TiffContext {
48 
49  int width, height;
50  unsigned int bpp, bppcount;
51  uint32_t palette[256];
53  int le;
55  int invert;
56  int fax_opts;
57  int predictor;
59 
60  int strips, rps, sstype;
61  int sot;
64 
67 
70 } TiffContext;
71 
72 static unsigned tget_short(GetByteContext *gb, int le)
73 {
74  unsigned v = le ? bytestream2_get_le16(gb) : bytestream2_get_be16(gb);
75  return v;
76 }
77 
78 static unsigned tget_long(GetByteContext *gb, int le)
79 {
80  unsigned v = le ? bytestream2_get_le32(gb) : bytestream2_get_be32(gb);
81  return v;
82 }
83 
84 static double tget_double(GetByteContext *gb, int le)
85 {
86  av_alias64 i = { .u64 = le ? bytestream2_get_le64(gb) : bytestream2_get_be64(gb)};
87  return i.f64;
88 }
89 
90 static unsigned tget(GetByteContext *gb, int type, int le)
91 {
92  switch (type) {
93  case TIFF_BYTE : return bytestream2_get_byte(gb);
94  case TIFF_SHORT: return tget_short(gb, le);
95  case TIFF_LONG : return tget_long(gb, le);
96  default : return UINT_MAX;
97  }
98 }
99 
100 static void free_geotags(TiffContext *const s)
101 {
102  int i;
103  for (i = 0; i < s->geotag_count; i++) {
104  if (s->geotags[i].val)
105  av_freep(&s->geotags[i].val);
106  }
107  av_freep(&s->geotags);
108 }
109 
110 #define RET_GEOKEY(TYPE, array, element)\
111  if (key >= TIFF_##TYPE##_KEY_ID_OFFSET &&\
112  key - TIFF_##TYPE##_KEY_ID_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_name_type_map))\
113  return ff_tiff_##array##_name_type_map[key - TIFF_##TYPE##_KEY_ID_OFFSET].element;
114 
115 static const char *get_geokey_name(int key)
116 {
117  RET_GEOKEY(VERT, vert, name);
118  RET_GEOKEY(PROJ, proj, name);
119  RET_GEOKEY(GEOG, geog, name);
120  RET_GEOKEY(CONF, conf, name);
121 
122  return NULL;
123 }
124 
125 static int get_geokey_type(int key)
126 {
127  RET_GEOKEY(VERT, vert, type);
128  RET_GEOKEY(PROJ, proj, type);
129  RET_GEOKEY(GEOG, geog, type);
130  RET_GEOKEY(CONF, conf, type);
131 
132  return AVERROR_INVALIDDATA;
133 }
134 
135 static int cmp_id_key(const void *id, const void *k)
136 {
137  return *(const int*)id - ((const TiffGeoTagKeyName*)k)->key;
138 }
139 
140 static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)
141 {
142  TiffGeoTagKeyName *r = bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key);
143  if(r)
144  return r->name;
145 
146  return NULL;
147 }
148 
149 static char *get_geokey_val(int key, int val)
150 {
151  char *ap;
152 
153  if (val == TIFF_GEO_KEY_UNDEFINED)
154  return av_strdup("undefined");
155  if (val == TIFF_GEO_KEY_USER_DEFINED)
156  return av_strdup("User-Defined");
157 
158 #define RET_GEOKEY_VAL(TYPE, array)\
159  if (val >= TIFF_##TYPE##_OFFSET &&\
160  val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\
161  return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);
162 
163  switch (key) {
165  RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);
166  break;
168  RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);
169  break;
173  RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);
174  break;
177  RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);
178  break;
180  RET_GEOKEY_VAL(GCS_TYPE, gcs_type);
181  RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);
182  break;
184  RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);
185  RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);
186  break;
188  RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);
189  break;
191  RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);
192  break;
195  if(ap) return ap;
196  break;
199  if(ap) return ap;
200  break;
202  RET_GEOKEY_VAL(COORD_TRANS, coord_trans);
203  break;
205  RET_GEOKEY_VAL(VERT_CS, vert_cs);
206  RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);
207  break;
208 
209  }
210 
211  ap = av_malloc(14);
212  if (ap)
213  snprintf(ap, 14, "Unknown-%d", val);
214  return ap;
215 }
216 
217 static char *doubles2str(double *dp, int count, const char *sep)
218 {
219  int i;
220  char *ap, *ap0;
221  uint64_t component_len;
222  if (!sep) sep = ", ";
223  component_len = 15LL + strlen(sep);
224  if (count >= (INT_MAX - 1)/component_len)
225  return NULL;
226  ap = av_malloc(component_len * count + 1);
227  if (!ap)
228  return NULL;
229  ap0 = ap;
230  ap[0] = '\0';
231  for (i = 0; i < count; i++) {
232  unsigned l = snprintf(ap, component_len, "%f%s", dp[i], sep);
233  if(l >= component_len) {
234  av_free(ap0);
235  return NULL;
236  }
237  ap += l;
238  }
239  ap0[strlen(ap0) - strlen(sep)] = '\0';
240  return ap0;
241 }
242 
243 static char *shorts2str(int16_t *sp, int count, const char *sep)
244 {
245  int i;
246  char *ap, *ap0;
247  uint64_t component_len;
248  if (!sep) sep = ", ";
249  component_len = 7LL + strlen(sep);
250  if (count >= (INT_MAX - 1)/component_len)
251  return NULL;
252  ap = av_malloc(component_len * count + 1);
253  if (!ap)
254  return NULL;
255  ap0 = ap;
256  ap[0] = '\0';
257  for (i = 0; i < count; i++) {
258  unsigned l = snprintf(ap, component_len, "%d%s", sp[i], sep);
259  if (l >= component_len) {
260  av_free(ap0);
261  return NULL;
262  }
263  ap += l;
264  }
265  ap0[strlen(ap0) - strlen(sep)] = '\0';
266  return ap0;
267 }
268 
269 static int add_doubles_metadata(int count,
270  const char *name, const char *sep,
271  TiffContext *s)
272 {
273  char *ap;
274  int i;
275  double *dp;
276 
277  if (count >= INT_MAX / sizeof(int64_t) || count <= 0)
278  return AVERROR_INVALIDDATA;
279  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
280  return AVERROR_INVALIDDATA;
281 
282  dp = av_malloc(count * sizeof(double));
283  if (!dp)
284  return AVERROR(ENOMEM);
285 
286  for (i = 0; i < count; i++)
287  dp[i] = tget_double(&s->gb, s->le);
288  ap = doubles2str(dp, count, sep);
289  av_freep(&dp);
290  if (!ap)
291  return AVERROR(ENOMEM);
293  return 0;
294 }
295 
296 static int add_shorts_metadata(int count, const char *name,
297  const char *sep, TiffContext *s)
298 {
299  char *ap;
300  int i;
301  int16_t *sp;
302 
303  if (count >= INT_MAX / sizeof(int16_t) || count <= 0)
304  return AVERROR_INVALIDDATA;
305  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int16_t))
306  return AVERROR_INVALIDDATA;
307 
308  sp = av_malloc(count * sizeof(int16_t));
309  if (!sp)
310  return AVERROR(ENOMEM);
311 
312  for (i = 0; i < count; i++)
313  sp[i] = tget_short(&s->gb, s->le);
314  ap = shorts2str(sp, count, sep);
315  av_freep(&sp);
316  if (!ap)
317  return AVERROR(ENOMEM);
319  return 0;
320 }
321 
322 static int add_string_metadata(int count, const char *name,
323  TiffContext *s)
324 {
325  char *value;
326 
327  if (bytestream2_get_bytes_left(&s->gb) < count || count < 0)
328  return AVERROR_INVALIDDATA;
329 
330  value = av_malloc(count + 1);
331  if (!value)
332  return AVERROR(ENOMEM);
333 
334  bytestream2_get_bufferu(&s->gb, value, count);
335  value[count] = 0;
336 
338  return 0;
339 }
340 
341 static int add_metadata(int count, int type,
342  const char *name, const char *sep, TiffContext *s)
343 {
344  switch(type) {
345  case TIFF_DOUBLE: return add_doubles_metadata(count, name, sep, s);
346  case TIFF_SHORT : return add_shorts_metadata(count, name, sep, s);
347  case TIFF_STRING: return add_string_metadata(count, name, s);
348  default : return AVERROR_INVALIDDATA;
349  };
350 }
351 
352 #if CONFIG_ZLIB
353 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
354  int size)
355 {
356  z_stream zstream = { 0 };
357  int zret;
358 
359  zstream.next_in = (uint8_t *)src;
360  zstream.avail_in = size;
361  zstream.next_out = dst;
362  zstream.avail_out = *len;
363  zret = inflateInit(&zstream);
364  if (zret != Z_OK) {
365  av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
366  return zret;
367  }
368  zret = inflate(&zstream, Z_SYNC_FLUSH);
369  inflateEnd(&zstream);
370  *len = zstream.total_out;
371  return zret == Z_STREAM_END ? Z_OK : zret;
372 }
373 #endif
374 
375 static void av_always_inline horizontal_fill(unsigned int bpp, uint8_t* dst,
376  int usePtr, const uint8_t *src,
377  uint8_t c, int width, int offset)
378 {
379  switch (bpp) {
380  case 1:
381  while (--width >= 0) {
382  dst[(width+offset)*8+7] = (usePtr ? src[width] : c) & 0x1;
383  dst[(width+offset)*8+6] = (usePtr ? src[width] : c) >> 1 & 0x1;
384  dst[(width+offset)*8+5] = (usePtr ? src[width] : c) >> 2 & 0x1;
385  dst[(width+offset)*8+4] = (usePtr ? src[width] : c) >> 3 & 0x1;
386  dst[(width+offset)*8+3] = (usePtr ? src[width] : c) >> 4 & 0x1;
387  dst[(width+offset)*8+2] = (usePtr ? src[width] : c) >> 5 & 0x1;
388  dst[(width+offset)*8+1] = (usePtr ? src[width] : c) >> 6 & 0x1;
389  dst[(width+offset)*8+0] = (usePtr ? src[width] : c) >> 7;
390  }
391  break;
392  case 2:
393  while (--width >= 0) {
394  dst[(width+offset)*4+3] = (usePtr ? src[width] : c) & 0x3;
395  dst[(width+offset)*4+2] = (usePtr ? src[width] : c) >> 2 & 0x3;
396  dst[(width+offset)*4+1] = (usePtr ? src[width] : c) >> 4 & 0x3;
397  dst[(width+offset)*4+0] = (usePtr ? src[width] : c) >> 6;
398  }
399  break;
400  case 4:
401  while (--width >= 0) {
402  dst[(width+offset)*2+1] = (usePtr ? src[width] : c) & 0xF;
403  dst[(width+offset)*2+0] = (usePtr ? src[width] : c) >> 4;
404  }
405  break;
406  default:
407  if (usePtr) {
408  memcpy(dst + offset, src, width);
409  } else {
410  memset(dst + offset, c, width);
411  }
412  }
413 }
414 
415 static int tiff_unpack_strip(TiffContext *s, uint8_t *dst, int stride,
416  const uint8_t *src, int size, int lines)
417 {
418  int c, line, pixels, code, ret;
419  const uint8_t *ssrc = src;
420  int width = ((s->width * s->bpp) + 7) >> 3;
421 
422  if (size <= 0)
423  return AVERROR_INVALIDDATA;
424 
425 #if CONFIG_ZLIB
426  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
427  uint8_t *src2 = NULL, *zbuf;
428  unsigned long outlen;
429  int i, ret;
430  outlen = width * lines;
431  zbuf = av_malloc(outlen);
432  if (!zbuf)
433  return AVERROR(ENOMEM);
434  if (s->fill_order) {
435  src2 = av_malloc((unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE);
436  if (!src2) {
437  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
438  av_free(zbuf);
439  return AVERROR(ENOMEM);
440  }
441  for (i = 0; i < size; i++)
442  src2[i] = ff_reverse[src[i]];
443  memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
444  src = src2;
445  }
446  ret = tiff_uncompress(zbuf, &outlen, src, size);
447  if (ret != Z_OK) {
449  "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
450  (unsigned long)width * lines, ret);
451  av_free(src2);
452  av_free(zbuf);
453  return AVERROR_UNKNOWN;
454  }
455  src = zbuf;
456  for (line = 0; line < lines; line++) {
457  if(s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8){
458  horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
459  }else{
460  memcpy(dst, src, width);
461  }
462  dst += stride;
463  src += width;
464  }
465  av_free(src2);
466  av_free(zbuf);
467  return 0;
468  }
469 #endif
470  if (s->compr == TIFF_LZW) {
471  if (s->fill_order) {
472  int i;
474  if (!s->deinvert_buf)
475  return AVERROR(ENOMEM);
476  for (i = 0; i < size; i++)
477  s->deinvert_buf[i] = ff_reverse[src[i]];
478  src = s->deinvert_buf;
479  ssrc = src;
480  }
481  if (size > 1 && !src[0] && (src[1]&1)) {
482  av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
483  }
484  if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
485  av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
486  return ret;
487  }
488  }
489  if (s->compr == TIFF_CCITT_RLE || s->compr == TIFF_G3
490  || s->compr == TIFF_G4) {
491  int i, ret = 0;
492  uint8_t *src2 = av_malloc((unsigned)size +
494 
495  if (!src2) {
497  "Error allocating temporary buffer\n");
498  return AVERROR(ENOMEM);
499  }
500  if (s->fax_opts & 2) {
502  "Uncompressed fax mode is not supported (yet)\n");
503  av_free(src2);
504  return AVERROR_INVALIDDATA;
505  }
506  if (!s->fill_order) {
507  memcpy(src2, src, size);
508  } else {
509  for (i = 0; i < size; i++)
510  src2[i] = ff_reverse[src[i]];
511  }
512  memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
513  switch (s->compr) {
514  case TIFF_CCITT_RLE:
515  case TIFF_G3:
516  case TIFF_G4:
517  ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
518  s->compr, s->fax_opts);
519  break;
520  }
521  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
522  for (line = 0; line < lines; line++) {
523  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
524  dst += stride;
525  }
526  av_free(src2);
527  return ret;
528  }
529  for (line = 0; line < lines; line++) {
530  if (src - ssrc > size) {
531  av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
532  return AVERROR_INVALIDDATA;
533  }
534  switch (s->compr) {
535  case TIFF_RAW:
536  if (ssrc + size - src < width)
537  return AVERROR_INVALIDDATA;
538  if (!s->fill_order) {
540  dst, 1, src, 0, width, 0);
541  } else {
542  int i;
543  for (i = 0; i < width; i++)
544  dst[i] = ff_reverse[src[i]];
545  }
546  src += width;
547  break;
548  case TIFF_PACKBITS:
549  for (pixels = 0; pixels < width;) {
550  if (ssrc + size - src < 2) {
551  av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
552  return AVERROR_INVALIDDATA;
553  }
554  code = (int8_t) * src++;
555  if (code >= 0) {
556  code++;
557  if (pixels + code > width) {
559  "Copy went out of bounds\n");
560  return AVERROR_INVALIDDATA;
561  }
562  if (ssrc + size - src < code) {
563  av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
564  return AVERROR_INVALIDDATA;
565  }
567  dst, 1, src, 0, code, pixels);
568  src += code;
569  pixels += code;
570  } else if (code != -128) { // -127..-1
571  code = (-code) + 1;
572  if (pixels + code > width) {
574  "Run went out of bounds\n");
575  return AVERROR_INVALIDDATA;
576  }
577  c = *src++;
579  dst, 0, NULL, c, code, pixels);
580  pixels += code;
581  }
582  }
583  break;
584  case TIFF_LZW:
585  pixels = ff_lzw_decode(s->lzw, dst, width);
586  if (pixels < width) {
587  av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
588  pixels, width);
589  return AVERROR_INVALIDDATA;
590  }
591  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
592  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
593  break;
594  }
595  dst += stride;
596  }
597  return 0;
598 }
599 
600 static int init_image(TiffContext *s)
601 {
602  int i, ret;
603  uint32_t *pal;
604 
605  switch (s->bpp * 10 + s->bppcount) {
606  case 11:
607  if (!s->palette_is_set) {
609  break;
610  }
611  case 21:
612  case 41:
613  case 81:
615  break;
616  case 243:
618  break;
619  case 161:
621  break;
622  case 162:
624  break;
625  case 324:
627  break;
628  case 483:
630  break;
631  case 644:
633  break;
634  default:
636  "This format is not supported (bpp=%d, bppcount=%d)\n",
637  s->bpp, s->bppcount);
638  return AVERROR_INVALIDDATA;
639  }
640  if (s->width != s->avctx->width || s->height != s->avctx->height) {
641  if ((ret = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)
642  return ret;
644  }
645  if (s->picture.data[0])
646  s->avctx->release_buffer(s->avctx, &s->picture);
647  if ((ret = ff_get_buffer(s->avctx, &s->picture)) < 0) {
648  av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
649  return ret;
650  }
651  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
652  if (s->palette_is_set) {
653  memcpy(s->picture.data[1], s->palette, sizeof(s->palette));
654  } else {
655  /* make default grayscale pal */
656  pal = (uint32_t *) s->picture.data[1];
657  for (i = 0; i < 1<<s->bpp; i++)
658  pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
659  }
660  }
661  return 0;
662 }
663 
665 {
666  unsigned tag, type, count, off, value = 0;
667  int i, j, k, pos, start;
668  int ret;
669  uint32_t *pal;
670  double *dp;
671 
672  tag = tget_short(&s->gb, s->le);
673  type = tget_short(&s->gb, s->le);
674  count = tget_long(&s->gb, s->le);
675  off = tget_long(&s->gb, s->le);
676  start = bytestream2_tell(&s->gb);
677 
678  if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
679  av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
680  type);
681  return 0;
682  }
683 
684  if (count == 1) {
685  switch (type) {
686  case TIFF_BYTE:
687  case TIFF_SHORT:
688  bytestream2_seek(&s->gb, -4, SEEK_CUR);
689  value = tget(&s->gb, type, s->le);
690  break;
691  case TIFF_LONG:
692  value = off;
693  break;
694  case TIFF_STRING:
695  if (count <= 4) {
696  bytestream2_seek(&s->gb, -4, SEEK_CUR);
697  break;
698  }
699  default:
700  value = UINT_MAX;
701  bytestream2_seek(&s->gb, off, SEEK_SET);
702  }
703  } else {
704  if (count <= 4 && type_sizes[type] * count <= 4) {
705  bytestream2_seek(&s->gb, -4, SEEK_CUR);
706  } else {
707  bytestream2_seek(&s->gb, off, SEEK_SET);
708  }
709  }
710 
711  switch (tag) {
712  case TIFF_WIDTH:
713  s->width = value;
714  break;
715  case TIFF_HEIGHT:
716  s->height = value;
717  break;
718  case TIFF_BPP:
719  s->bppcount = count;
720  if (count > 4) {
722  "This format is not supported (bpp=%d, %d components)\n",
723  s->bpp, count);
724  return AVERROR_INVALIDDATA;
725  }
726  if (count == 1)
727  s->bpp = value;
728  else {
729  switch (type) {
730  case TIFF_BYTE:
731  s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
732  ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
733  break;
734  case TIFF_SHORT:
735  case TIFF_LONG:
736  s->bpp = 0;
737  if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
738  return AVERROR_INVALIDDATA;
739  for (i = 0; i < count; i++)
740  s->bpp += tget(&s->gb, type, s->le);
741  break;
742  default:
743  s->bpp = -1;
744  }
745  }
746  break;
748  if (count != 1) {
750  "Samples per pixel requires a single value, many provided\n");
751  return AVERROR_INVALIDDATA;
752  }
753  if (value > 4U) {
755  "Samples per pixel %d is too large\n", value);
756  return AVERROR_INVALIDDATA;
757  }
758  if (s->bppcount == 1)
759  s->bpp *= value;
760  s->bppcount = value;
761  break;
762  case TIFF_COMPR:
763  s->compr = value;
764  s->predictor = 0;
765  switch (s->compr) {
766  case TIFF_RAW:
767  case TIFF_PACKBITS:
768  case TIFF_LZW:
769  case TIFF_CCITT_RLE:
770  break;
771  case TIFF_G3:
772  case TIFF_G4:
773  s->fax_opts = 0;
774  break;
775  case TIFF_DEFLATE:
776  case TIFF_ADOBE_DEFLATE:
777 #if CONFIG_ZLIB
778  break;
779 #else
780  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
781  return AVERROR(ENOSYS);
782 #endif
783  case TIFF_JPEG:
784  case TIFF_NEWJPEG:
786  "JPEG compression is not supported\n");
787  return AVERROR_PATCHWELCOME;
788  default:
789  av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
790  s->compr);
791  return AVERROR_INVALIDDATA;
792  }
793  break;
794  case TIFF_ROWSPERSTRIP:
795  if (type == TIFF_LONG && value == UINT_MAX)
796  value = s->height;
797  if (value < 1) {
799  "Incorrect value of rows per strip\n");
800  return AVERROR_INVALIDDATA;
801  }
802  s->rps = value;
803  break;
804  case TIFF_STRIP_OFFS:
805  if (count == 1) {
806  s->strippos = 0;
807  s->stripoff = value;
808  } else
809  s->strippos = off;
810  s->strips = count;
811  if (s->strips == 1)
812  s->rps = s->height;
813  s->sot = type;
814  if (s->strippos > bytestream2_size(&s->gb)) {
816  "Tag referencing position outside the image\n");
817  return AVERROR_INVALIDDATA;
818  }
819  break;
820  case TIFF_STRIP_SIZE:
821  if (count == 1) {
822  s->stripsizesoff = 0;
823  s->stripsize = value;
824  s->strips = 1;
825  } else {
826  s->stripsizesoff = off;
827  }
828  s->strips = count;
829  s->sstype = type;
830  if (s->stripsizesoff > bytestream2_size(&s->gb)) {
832  "Tag referencing position outside the image\n");
833  return AVERROR_INVALIDDATA;
834  }
835  break;
837  case TIFF_TILE_LENGTH:
838  case TIFF_TILE_OFFSETS:
839  case TIFF_TILE_WIDTH:
840  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
841  return AVERROR_PATCHWELCOME;
842  break;
843  case TIFF_PREDICTOR:
844  s->predictor = value;
845  break;
846  case TIFF_INVERT:
847  switch (value) {
848  case 0:
849  s->invert = 1;
850  break;
851  case 1:
852  s->invert = 0;
853  break;
854  case 2:
855  case 3:
856  break;
857  default:
858  av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
859  value);
860  return AVERROR_INVALIDDATA;
861  }
862  break;
863  case TIFF_FILL_ORDER:
864  if (value < 1 || value > 2) {
866  "Unknown FillOrder value %d, trying default one\n", value);
867  value = 1;
868  }
869  s->fill_order = value - 1;
870  break;
871  case TIFF_PAL:
872  pal = (uint32_t *) s->palette;
873  off = type_sizes[type];
874  if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
875  return AVERROR_INVALIDDATA;
876  off = (type_sizes[type] - 1) << 3;
877  for (k = 2; k >= 0; k--) {
878  for (i = 0; i < count / 3; i++) {
879  if (k == 2)
880  pal[i] = 0xFFU << 24;
881  j = (tget(&s->gb, type, s->le) >> off) << (k * 8);
882  pal[i] |= j;
883  }
884  }
885  s->palette_is_set = 1;
886  break;
887  case TIFF_PLANAR:
888  if (value == 2) {
889  av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
890  return AVERROR_PATCHWELCOME;
891  }
892  break;
893  case TIFF_T4OPTIONS:
894  if (s->compr == TIFF_G3)
895  s->fax_opts = value;
896  break;
897  case TIFF_T6OPTIONS:
898  if (s->compr == TIFF_G4)
899  s->fax_opts = value;
900  break;
901 #define ADD_METADATA(count, name, sep)\
902  if ((ret = add_metadata(count, type, name, sep, s)) < 0) {\
903  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
904  return ret;\
905  }
907  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
908  break;
910  ADD_METADATA(count, "ModelTransformationTag", NULL);
911  break;
912  case TIFF_MODEL_TIEPOINT:
913  ADD_METADATA(count, "ModelTiepointTag", NULL);
914  break;
916  ADD_METADATA(1, "GeoTIFF_Version", NULL);
917  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
918  s->geotag_count = tget_short(&s->gb, s->le);
919  if (s->geotag_count > count / 4 - 1) {
920  s->geotag_count = count / 4 - 1;
921  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
922  }
923  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
924  s->geotag_count = 0;
925  return -1;
926  }
927  s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);
928  if (!s->geotags) {
929  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
930  s->geotag_count = 0;
931  return AVERROR(ENOMEM);
932  }
933  for (i = 0; i < s->geotag_count; i++) {
934  s->geotags[i].key = tget_short(&s->gb, s->le);
935  s->geotags[i].type = tget_short(&s->gb, s->le);
936  s->geotags[i].count = tget_short(&s->gb, s->le);
937 
938  if (!s->geotags[i].type)
939  s->geotags[i].val = get_geokey_val(s->geotags[i].key, tget_short(&s->gb, s->le));
940  else
941  s->geotags[i].offset = tget_short(&s->gb, s->le);
942  }
943  break;
945  if (count >= INT_MAX / sizeof(int64_t))
946  return AVERROR_INVALIDDATA;
947  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
948  return AVERROR_INVALIDDATA;
949  dp = av_malloc(count * sizeof(double));
950  if (!dp) {
951  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
952  return AVERROR(ENOMEM);
953  }
954  for (i = 0; i < count; i++)
955  dp[i] = tget_double(&s->gb, s->le);
956  for (i = 0; i < s->geotag_count; i++) {
957  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
958  if (s->geotags[i].count == 0
959  || s->geotags[i].offset + s->geotags[i].count > count) {
960  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
961  } else {
962  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
963  if (!ap) {
964  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
965  av_freep(&dp);
966  return AVERROR(ENOMEM);
967  }
968  s->geotags[i].val = ap;
969  }
970  }
971  }
972  av_freep(&dp);
973  break;
975  pos = bytestream2_tell(&s->gb);
976  for (i = 0; i < s->geotag_count; i++) {
977  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
978  if (s->geotags[i].count == 0
979  || s->geotags[i].offset + s->geotags[i].count > count) {
980  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
981  } else {
982  char *ap;
983 
984  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
985  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
986  return AVERROR_INVALIDDATA;
987  ap = av_malloc(s->geotags[i].count);
988  if (!ap) {
989  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
990  return AVERROR(ENOMEM);
991  }
992  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
993  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
994  s->geotags[i].val = ap;
995  }
996  }
997  }
998  break;
999  case TIFF_ARTIST:
1000  ADD_METADATA(count, "artist", NULL);
1001  break;
1002  case TIFF_COPYRIGHT:
1003  ADD_METADATA(count, "copyright", NULL);
1004  break;
1005  case TIFF_DATE:
1006  ADD_METADATA(count, "date", NULL);
1007  break;
1008  case TIFF_DOCUMENT_NAME:
1009  ADD_METADATA(count, "document_name", NULL);
1010  break;
1011  case TIFF_HOST_COMPUTER:
1012  ADD_METADATA(count, "computer", NULL);
1013  break;
1015  ADD_METADATA(count, "description", NULL);
1016  break;
1017  case TIFF_MAKE:
1018  ADD_METADATA(count, "make", NULL);
1019  break;
1020  case TIFF_MODEL:
1021  ADD_METADATA(count, "model", NULL);
1022  break;
1023  case TIFF_PAGE_NAME:
1024  ADD_METADATA(count, "page_name", NULL);
1025  break;
1026  case TIFF_PAGE_NUMBER:
1027  ADD_METADATA(count, "page_number", " / ");
1028  break;
1029  case TIFF_SOFTWARE_NAME:
1030  ADD_METADATA(count, "software", NULL);
1031  break;
1032  default:
1033  av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
1034  tag, tag);
1035  }
1036  bytestream2_seek(&s->gb, start, SEEK_SET);
1037  return 0;
1038 }
1039 
1040 static int decode_frame(AVCodecContext *avctx,
1041  void *data, int *got_frame, AVPacket *avpkt)
1042 {
1043  TiffContext *const s = avctx->priv_data;
1044  AVFrame *picture = data;
1045  AVFrame *const p = &s->picture;
1046  unsigned off;
1047  int id, le, ret;
1048  int i, j, entries;
1049  int stride;
1050  unsigned soff, ssize;
1051  uint8_t *dst;
1052  GetByteContext stripsizes;
1053  GetByteContext stripdata;
1054 
1055  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1056 
1057  //parse image header
1058  if (avpkt->size < 8)
1059  return AVERROR_INVALIDDATA;
1060  id = bytestream2_get_le16u(&s->gb);
1061  if (id == 0x4949)
1062  le = 1;
1063  else if (id == 0x4D4D)
1064  le = 0;
1065  else {
1066  av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");
1067  return AVERROR_INVALIDDATA;
1068  }
1069  s->le = le;
1070  // TIFF_BPP is not a required tag and defaults to 1
1071  s->bppcount = s->bpp = 1;
1072  s->invert = 0;
1073  s->compr = TIFF_RAW;
1074  s->fill_order = 0;
1075  free_geotags(s);
1076  /* metadata has been destroyed from lavc internals, that pointer is not
1077  * valid anymore */
1079 
1080  // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
1081  // that further identifies the file as a TIFF file"
1082  if (tget_short(&s->gb, le) != 42) {
1083  av_log(avctx, AV_LOG_ERROR,
1084  "The answer to life, universe and everything is not correct!\n");
1085  return AVERROR_INVALIDDATA;
1086  }
1087  // Reset these offsets so we can tell if they were set this frame
1088  s->stripsizesoff = s->strippos = 0;
1089  /* parse image file directory */
1090  off = tget_long(&s->gb, le);
1091  if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1092  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1093  return AVERROR_INVALIDDATA;
1094  }
1095  bytestream2_seek(&s->gb, off, SEEK_SET);
1096  entries = tget_short(&s->gb, le);
1097  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1098  return AVERROR_INVALIDDATA;
1099  for (i = 0; i < entries; i++) {
1100  if ((ret = tiff_decode_tag(s)) < 0)
1101  return ret;
1102  }
1103 
1104  for (i = 0; i<s->geotag_count; i++) {
1105  const char *keyname = get_geokey_name(s->geotags[i].key);
1106  if (!keyname) {
1107  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1108  continue;
1109  }
1110  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1111  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1112  continue;
1113  }
1114  ret = av_dict_set(ff_frame_get_metadatap(&s->picture), keyname, s->geotags[i].val, 0);
1115  if (ret<0) {
1116  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1117  return ret;
1118  }
1119  }
1120 
1121  if (!s->strippos && !s->stripoff) {
1122  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1123  return AVERROR_INVALIDDATA;
1124  }
1125  /* now we have the data and may start decoding */
1126  if ((ret = init_image(s)) < 0)
1127  return ret;
1128 
1129  if (s->strips == 1 && !s->stripsize) {
1130  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1131  s->stripsize = avpkt->size - s->stripoff;
1132  }
1133  stride = p->linesize[0];
1134  dst = p->data[0];
1135 
1136  if (s->stripsizesoff) {
1137  if (s->stripsizesoff >= (unsigned)avpkt->size)
1138  return AVERROR_INVALIDDATA;
1139  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, avpkt->size - s->stripsizesoff);
1140  }
1141  if (s->strippos) {
1142  if (s->strippos >= (unsigned)avpkt->size)
1143  return AVERROR_INVALIDDATA;
1144  bytestream2_init(&stripdata, avpkt->data + s->strippos, avpkt->size - s->strippos);
1145  }
1146 
1147  if (s->rps <= 0) {
1148  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1149  return AVERROR_INVALIDDATA;
1150  }
1151 
1152  for (i = 0; i < s->height; i += s->rps) {
1153  if (s->stripsizesoff)
1154  ssize = tget(&stripsizes, s->sstype, s->le);
1155  else
1156  ssize = s->stripsize;
1157 
1158  if (s->strippos)
1159  soff = tget(&stripdata, s->sot, s->le);
1160  else
1161  soff = s->stripoff;
1162 
1163  if (soff > avpkt->size || ssize > avpkt->size - soff) {
1164  av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1165  return AVERROR_INVALIDDATA;
1166  }
1167  if (tiff_unpack_strip(s, dst, stride, avpkt->data + soff, ssize,
1168  FFMIN(s->rps, s->height - i)) < 0)
1169  break;
1170  dst += s->rps * stride;
1171  }
1172  if (s->predictor == 2) {
1173  dst = p->data[0];
1174  soff = s->bpp >> 3;
1175  ssize = s->width * soff;
1176  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1178  for (i = 0; i < s->height; i++) {
1179  for (j = soff; j < ssize; j += 2)
1180  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1181  dst += stride;
1182  }
1183  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1185  for (i = 0; i < s->height; i++) {
1186  for (j = soff; j < ssize; j += 2)
1187  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1188  dst += stride;
1189  }
1190  } else {
1191  for (i = 0; i < s->height; i++) {
1192  for (j = soff; j < ssize; j++)
1193  dst[j] += dst[j - soff];
1194  dst += stride;
1195  }
1196  }
1197  }
1198 
1199  if (s->invert) {
1200  dst = s->picture.data[0];
1201  for (i = 0; i < s->height; i++) {
1202  for (j = 0; j < s->picture.linesize[0]; j++)
1203  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1204  dst += s->picture.linesize[0];
1205  }
1206  }
1207  *picture = s->picture;
1208  *got_frame = 1;
1209 
1210  return avpkt->size;
1211 }
1212 
1214 {
1215  TiffContext *s = avctx->priv_data;
1216 
1217  s->width = 0;
1218  s->height = 0;
1219  s->avctx = avctx;
1221  avctx->coded_frame = &s->picture;
1222  ff_lzw_decode_open(&s->lzw);
1224 
1225  return 0;
1226 }
1227 
1228 static av_cold int tiff_end(AVCodecContext *avctx)
1229 {
1230  TiffContext *const s = avctx->priv_data;
1231 
1232  free_geotags(s);
1233 
1234  ff_lzw_decode_close(&s->lzw);
1235  av_freep(&s->deinvert_buf);
1236  if (s->picture.data[0])
1237  avctx->release_buffer(avctx, &s->picture);
1238  return 0;
1239 }
1240 
1242  .name = "tiff",
1243  .type = AVMEDIA_TYPE_VIDEO,
1244  .id = AV_CODEC_ID_TIFF,
1245  .priv_data_size = sizeof(TiffContext),
1246  .init = tiff_init,
1247  .close = tiff_end,
1248  .decode = decode_frame,
1249  .capabilities = CODEC_CAP_DR1,
1250  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1251 };