FFmpeg
 All Data Structures Namespaces 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 "config.h"
28 #if CONFIG_ZLIB
29 #include <zlib.h>
30 #endif
31 
32 #include "libavutil/attributes.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/imgutils.h"
36 #include "avcodec.h"
37 #include "bytestream.h"
38 #include "faxcompr.h"
39 #include "internal.h"
40 #include "lzw.h"
41 #include "mathops.h"
42 #include "tiff.h"
43 #include "tiff_data.h"
44 #include "thread.h"
45 
46 typedef struct TiffContext {
49 
50  int width, height;
51  unsigned int bpp, bppcount;
52  uint32_t palette[256];
54  int le;
56  int invert;
57  int planar;
58  int fax_opts;
59  int predictor;
61 
62  int strips, rps, sstype;
63  int sot;
66 
69 
72 } TiffContext;
73 
74 static void free_geotags(TiffContext *const s)
75 {
76  int i;
77  for (i = 0; i < s->geotag_count; i++) {
78  if (s->geotags[i].val)
79  av_freep(&s->geotags[i].val);
80  }
81  av_freep(&s->geotags);
82 }
83 
84 #define RET_GEOKEY(TYPE, array, element)\
85  if (key >= TIFF_##TYPE##_KEY_ID_OFFSET &&\
86  key - TIFF_##TYPE##_KEY_ID_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_name_type_map))\
87  return ff_tiff_##array##_name_type_map[key - TIFF_##TYPE##_KEY_ID_OFFSET].element;
88 
89 static const char *get_geokey_name(int key)
90 {
91  RET_GEOKEY(VERT, vert, name);
92  RET_GEOKEY(PROJ, proj, name);
93  RET_GEOKEY(GEOG, geog, name);
94  RET_GEOKEY(CONF, conf, name);
95 
96  return NULL;
97 }
98 
99 static int get_geokey_type(int key)
100 {
101  RET_GEOKEY(VERT, vert, type);
102  RET_GEOKEY(PROJ, proj, type);
103  RET_GEOKEY(GEOG, geog, type);
104  RET_GEOKEY(CONF, conf, type);
105 
106  return AVERROR_INVALIDDATA;
107 }
108 
109 static int cmp_id_key(const void *id, const void *k)
110 {
111  return *(const int*)id - ((const TiffGeoTagKeyName*)k)->key;
112 }
113 
114 static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)
115 {
116  TiffGeoTagKeyName *r = bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key);
117  if(r)
118  return r->name;
119 
120  return NULL;
121 }
122 
123 static char *get_geokey_val(int key, int val)
124 {
125  char *ap;
126 
127  if (val == TIFF_GEO_KEY_UNDEFINED)
128  return av_strdup("undefined");
129  if (val == TIFF_GEO_KEY_USER_DEFINED)
130  return av_strdup("User-Defined");
131 
132 #define RET_GEOKEY_VAL(TYPE, array)\
133  if (val >= TIFF_##TYPE##_OFFSET &&\
134  val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\
135  return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);
136 
137  switch (key) {
139  RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);
140  break;
142  RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);
143  break;
147  RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);
148  break;
151  RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);
152  break;
154  RET_GEOKEY_VAL(GCS_TYPE, gcs_type);
155  RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);
156  break;
158  RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);
159  RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);
160  break;
162  RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);
163  break;
165  RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);
166  break;
169  if(ap) return ap;
170  break;
173  if(ap) return ap;
174  break;
176  RET_GEOKEY_VAL(COORD_TRANS, coord_trans);
177  break;
179  RET_GEOKEY_VAL(VERT_CS, vert_cs);
180  RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);
181  break;
182 
183  }
184 
185  ap = av_malloc(14);
186  if (ap)
187  snprintf(ap, 14, "Unknown-%d", val);
188  return ap;
189 }
190 
191 static char *doubles2str(double *dp, int count, const char *sep)
192 {
193  int i;
194  char *ap, *ap0;
195  uint64_t component_len;
196  if (!sep) sep = ", ";
197  component_len = 15LL + strlen(sep);
198  if (count >= (INT_MAX - 1)/component_len)
199  return NULL;
200  ap = av_malloc(component_len * count + 1);
201  if (!ap)
202  return NULL;
203  ap0 = ap;
204  ap[0] = '\0';
205  for (i = 0; i < count; i++) {
206  unsigned l = snprintf(ap, component_len, "%f%s", dp[i], sep);
207  if(l >= component_len) {
208  av_free(ap0);
209  return NULL;
210  }
211  ap += l;
212  }
213  ap0[strlen(ap0) - strlen(sep)] = '\0';
214  return ap0;
215 }
216 
217 static int add_metadata(int count, int type,
218  const char *name, const char *sep, TiffContext *s, AVFrame *frame)
219 {
220  switch(type) {
221  case TIFF_DOUBLE: return ff_tadd_doubles_metadata(count, name, sep, &s->gb, s->le, avpriv_frame_get_metadatap(frame));
222  case TIFF_SHORT : return ff_tadd_shorts_metadata(count, name, sep, &s->gb, s->le, avpriv_frame_get_metadatap(frame));
223  case TIFF_STRING: return ff_tadd_string_metadata(count, name, &s->gb, s->le, avpriv_frame_get_metadatap(frame));
224  default : return AVERROR_INVALIDDATA;
225  };
226 }
227 
228 static void av_always_inline horizontal_fill(unsigned int bpp, uint8_t* dst,
229  int usePtr, const uint8_t *src,
230  uint8_t c, int width, int offset)
231 {
232  switch (bpp) {
233  case 1:
234  while (--width >= 0) {
235  dst[(width+offset)*8+7] = (usePtr ? src[width] : c) & 0x1;
236  dst[(width+offset)*8+6] = (usePtr ? src[width] : c) >> 1 & 0x1;
237  dst[(width+offset)*8+5] = (usePtr ? src[width] : c) >> 2 & 0x1;
238  dst[(width+offset)*8+4] = (usePtr ? src[width] : c) >> 3 & 0x1;
239  dst[(width+offset)*8+3] = (usePtr ? src[width] : c) >> 4 & 0x1;
240  dst[(width+offset)*8+2] = (usePtr ? src[width] : c) >> 5 & 0x1;
241  dst[(width+offset)*8+1] = (usePtr ? src[width] : c) >> 6 & 0x1;
242  dst[(width+offset)*8+0] = (usePtr ? src[width] : c) >> 7;
243  }
244  break;
245  case 2:
246  while (--width >= 0) {
247  dst[(width+offset)*4+3] = (usePtr ? src[width] : c) & 0x3;
248  dst[(width+offset)*4+2] = (usePtr ? src[width] : c) >> 2 & 0x3;
249  dst[(width+offset)*4+1] = (usePtr ? src[width] : c) >> 4 & 0x3;
250  dst[(width+offset)*4+0] = (usePtr ? src[width] : c) >> 6;
251  }
252  break;
253  case 4:
254  while (--width >= 0) {
255  dst[(width+offset)*2+1] = (usePtr ? src[width] : c) & 0xF;
256  dst[(width+offset)*2+0] = (usePtr ? src[width] : c) >> 4;
257  }
258  break;
259  default:
260  if (usePtr) {
261  memcpy(dst + offset, src, width);
262  } else {
263  memset(dst + offset, c, width);
264  }
265  }
266 }
267 
268 static int deinvert_buffer(TiffContext *s, const uint8_t *src, int size)
269 {
270  int i;
271 
273  if (!s->deinvert_buf)
274  return AVERROR(ENOMEM);
275  for (i = 0; i < size; i++)
276  s->deinvert_buf[i] = ff_reverse[src[i]];
277 
278  return 0;
279 }
280 
281 #if CONFIG_ZLIB
282 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
283  int size)
284 {
285  z_stream zstream = { 0 };
286  int zret;
287 
288  zstream.next_in = (uint8_t *)src;
289  zstream.avail_in = size;
290  zstream.next_out = dst;
291  zstream.avail_out = *len;
292  zret = inflateInit(&zstream);
293  if (zret != Z_OK) {
294  av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
295  return zret;
296  }
297  zret = inflate(&zstream, Z_SYNC_FLUSH);
298  inflateEnd(&zstream);
299  *len = zstream.total_out;
300  return zret == Z_STREAM_END ? Z_OK : zret;
301 }
302 
303 static int tiff_unpack_zlib(TiffContext *s, uint8_t *dst, int stride,
304  const uint8_t *src, int size,
305  int width, int lines)
306 {
307  uint8_t *zbuf;
308  unsigned long outlen;
309  int ret, line;
310  outlen = width * lines;
311  zbuf = av_malloc(outlen);
312  if (!zbuf)
313  return AVERROR(ENOMEM);
314  if (s->fill_order) {
315  if ((ret = deinvert_buffer(s, src, size)) < 0) {
316  av_free(zbuf);
317  return ret;
318  }
319  src = s->deinvert_buf;
320  }
321  ret = tiff_uncompress(zbuf, &outlen, src, size);
322  if (ret != Z_OK) {
324  "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
325  (unsigned long)width * lines, ret);
326  av_free(zbuf);
327  return AVERROR_UNKNOWN;
328  }
329  src = zbuf;
330  for (line = 0; line < lines; line++) {
331  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
332  horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
333  } else {
334  memcpy(dst, src, width);
335  }
336  dst += stride;
337  src += width;
338  }
339  av_free(zbuf);
340  return 0;
341 }
342 #endif
343 
344 
345 static int tiff_unpack_fax(TiffContext *s, uint8_t *dst, int stride,
346  const uint8_t *src, int size, int width, int lines)
347 {
348  int i, ret = 0;
349  int line;
350  uint8_t *src2 = av_malloc((unsigned)size +
352 
353  if (!src2) {
355  "Error allocating temporary buffer\n");
356  return AVERROR(ENOMEM);
357  }
358  if (s->fax_opts & 2) {
359  avpriv_request_sample(s->avctx, "Uncompressed fax mode");
360  av_free(src2);
361  return AVERROR_PATCHWELCOME;
362  }
363  if (!s->fill_order) {
364  memcpy(src2, src, size);
365  } else {
366  for (i = 0; i < size; i++)
367  src2[i] = ff_reverse[src[i]];
368  }
369  memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
370  ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
371  s->compr, s->fax_opts);
372  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
373  for (line = 0; line < lines; line++) {
374  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
375  dst += stride;
376  }
377  av_free(src2);
378  return ret;
379 }
380 
381 static int tiff_unpack_strip(TiffContext *s, uint8_t *dst, int stride,
382  const uint8_t *src, int size, int lines)
383 {
384  int c, line, pixels, code, ret;
385  const uint8_t *ssrc = src;
386  int width = ((s->width * s->bpp) + 7) >> 3;
387 
388  if (s->planar)
389  width /= s->bppcount;
390 
391  if (size <= 0)
392  return AVERROR_INVALIDDATA;
393 
394  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
395 #if CONFIG_ZLIB
396  return tiff_unpack_zlib(s, dst, stride, src, size, width, lines);
397 #else
399  "zlib support not enabled, "
400  "deflate compression not supported\n");
401  return AVERROR(ENOSYS);
402 #endif
403  }
404  if (s->compr == TIFF_LZW) {
405  if (s->fill_order) {
406  if ((ret = deinvert_buffer(s, src, size)) < 0)
407  return ret;
408  ssrc = src = s->deinvert_buf;
409  }
410  if (size > 1 && !src[0] && (src[1]&1)) {
411  av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
412  }
413  if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
414  av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
415  return ret;
416  }
417  }
418  if (s->compr == TIFF_CCITT_RLE ||
419  s->compr == TIFF_G3 ||
420  s->compr == TIFF_G4) {
421  return tiff_unpack_fax(s, dst, stride, src, size, width, lines);
422  }
423  for (line = 0; line < lines; line++) {
424  if (src - ssrc > size) {
425  av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
426  return AVERROR_INVALIDDATA;
427  }
428  switch (s->compr) {
429  case TIFF_RAW:
430  if (ssrc + size - src < width)
431  return AVERROR_INVALIDDATA;
432  if (!s->fill_order) {
434  dst, 1, src, 0, width, 0);
435  } else {
436  int i;
437  for (i = 0; i < width; i++)
438  dst[i] = ff_reverse[src[i]];
439  }
440  src += width;
441  break;
442  case TIFF_PACKBITS:
443  for (pixels = 0; pixels < width;) {
444  if (ssrc + size - src < 2) {
445  av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
446  return AVERROR_INVALIDDATA;
447  }
448  code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;
449  if (code >= 0) {
450  code++;
451  if (pixels + code > width ||
452  ssrc + size - src < code) {
454  "Copy went out of bounds\n");
455  return AVERROR_INVALIDDATA;
456  }
458  dst, 1, src, 0, code, pixels);
459  src += code;
460  pixels += code;
461  } else if (code != -128) { // -127..-1
462  code = (-code) + 1;
463  if (pixels + code > width) {
465  "Run went out of bounds\n");
466  return AVERROR_INVALIDDATA;
467  }
468  c = *src++;
470  dst, 0, NULL, c, code, pixels);
471  pixels += code;
472  }
473  }
474  if (s->fill_order) {
475  int i;
476  for (i = 0; i < width; i++)
477  dst[i] = ff_reverse[dst[i]];
478  }
479  break;
480  case TIFF_LZW:
481  pixels = ff_lzw_decode(s->lzw, dst, width);
482  if (pixels < width) {
483  av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
484  pixels, width);
485  return AVERROR_INVALIDDATA;
486  }
487  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
488  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
489  break;
490  }
491  dst += stride;
492  }
493  return 0;
494 }
495 
497 {
498  int i, ret;
499  uint32_t *pal;
500 
501  switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
502  case 11:
503  if (!s->palette_is_set) {
505  break;
506  }
507  case 21:
508  case 41:
509  case 81:
511  break;
512  case 243:
514  break;
515  case 161:
517  break;
518  case 162:
520  break;
521  case 324:
523  break;
524  case 483:
526  break;
527  case 644:
529  break;
530  case 1243:
532  break;
533  case 1324:
535  break;
536  case 1483:
538  break;
539  case 1644:
541  break;
542  default:
544  "This format is not supported (bpp=%d, bppcount=%d)\n",
545  s->bpp, s->bppcount);
546  return AVERROR_INVALIDDATA;
547  }
548  if (s->width != s->avctx->width || s->height != s->avctx->height) {
549  if ((ret = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)
550  return ret;
552  }
553  if ((ret = ff_thread_get_buffer(s->avctx, frame, 0)) < 0)
554  return ret;
555  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
556  if (s->palette_is_set) {
557  memcpy(frame->f->data[1], s->palette, sizeof(s->palette));
558  } else {
559  /* make default grayscale pal */
560  pal = (uint32_t *) frame->f->data[1];
561  for (i = 0; i < 1<<s->bpp; i++)
562  pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
563  }
564  }
565  return 0;
566 }
567 
569 {
570  unsigned tag, type, count, off, value = 0;
571  int i, j, k, pos, start;
572  int ret;
573  uint32_t *pal;
574  double *dp;
575 
576  ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);
577  if (ret < 0) {
578  goto end;
579  }
580 
581  off = bytestream2_tell(&s->gb);
582  if (count == 1) {
583  switch (type) {
584  case TIFF_BYTE:
585  case TIFF_SHORT:
586  case TIFF_LONG:
587  value = ff_tget(&s->gb, type, s->le);
588  break;
589  case TIFF_STRING:
590  if (count <= 4) {
591  break;
592  }
593  default:
594  value = UINT_MAX;
595  }
596  }
597 
598  switch (tag) {
599  case TIFF_WIDTH:
600  s->width = value;
601  break;
602  case TIFF_HEIGHT:
603  s->height = value;
604  break;
605  case TIFF_BPP:
606  s->bppcount = count;
607  if (count > 4) {
609  "This format is not supported (bpp=%d, %d components)\n",
610  s->bpp, count);
611  return AVERROR_INVALIDDATA;
612  }
613  if (count == 1)
614  s->bpp = value;
615  else {
616  switch (type) {
617  case TIFF_BYTE:
618  case TIFF_SHORT:
619  case TIFF_LONG:
620  s->bpp = 0;
621  if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
622  return AVERROR_INVALIDDATA;
623  for (i = 0; i < count; i++)
624  s->bpp += ff_tget(&s->gb, type, s->le);
625  break;
626  default:
627  s->bpp = -1;
628  }
629  }
630  break;
632  if (count != 1) {
634  "Samples per pixel requires a single value, many provided\n");
635  return AVERROR_INVALIDDATA;
636  }
637  if (value > 4U) {
639  "Samples per pixel %d is too large\n", value);
640  return AVERROR_INVALIDDATA;
641  }
642  if (s->bppcount == 1)
643  s->bpp *= value;
644  s->bppcount = value;
645  break;
646  case TIFF_COMPR:
647  s->compr = value;
648  s->predictor = 0;
649  switch (s->compr) {
650  case TIFF_RAW:
651  case TIFF_PACKBITS:
652  case TIFF_LZW:
653  case TIFF_CCITT_RLE:
654  break;
655  case TIFF_G3:
656  case TIFF_G4:
657  s->fax_opts = 0;
658  break;
659  case TIFF_DEFLATE:
660  case TIFF_ADOBE_DEFLATE:
661 #if CONFIG_ZLIB
662  break;
663 #else
664  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
665  return AVERROR(ENOSYS);
666 #endif
667  case TIFF_JPEG:
668  case TIFF_NEWJPEG:
669  avpriv_report_missing_feature(s->avctx, "JPEG compression");
670  return AVERROR_PATCHWELCOME;
671  default:
672  av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
673  s->compr);
674  return AVERROR_INVALIDDATA;
675  }
676  break;
677  case TIFF_ROWSPERSTRIP:
678  if (type == TIFF_LONG && value == UINT_MAX)
679  value = s->height;
680  if (value < 1) {
682  "Incorrect value of rows per strip\n");
683  return AVERROR_INVALIDDATA;
684  }
685  s->rps = value;
686  break;
687  case TIFF_STRIP_OFFS:
688  if (count == 1) {
689  s->strippos = 0;
690  s->stripoff = value;
691  } else
692  s->strippos = off;
693  s->strips = count;
694  if (s->strips == 1)
695  s->rps = s->height;
696  s->sot = type;
697  if (s->strippos > bytestream2_size(&s->gb)) {
699  "Tag referencing position outside the image\n");
700  return AVERROR_INVALIDDATA;
701  }
702  break;
703  case TIFF_STRIP_SIZE:
704  if (count == 1) {
705  s->stripsizesoff = 0;
706  s->stripsize = value;
707  s->strips = 1;
708  } else {
709  s->stripsizesoff = off;
710  }
711  s->strips = count;
712  s->sstype = type;
713  if (s->stripsizesoff > bytestream2_size(&s->gb)) {
715  "Tag referencing position outside the image\n");
716  return AVERROR_INVALIDDATA;
717  }
718  break;
720  case TIFF_TILE_LENGTH:
721  case TIFF_TILE_OFFSETS:
722  case TIFF_TILE_WIDTH:
723  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
724  return AVERROR_PATCHWELCOME;
725  break;
726  case TIFF_PREDICTOR:
727  s->predictor = value;
728  break;
729  case TIFF_INVERT:
730  switch (value) {
731  case 0:
732  s->invert = 1;
733  break;
734  case 1:
735  s->invert = 0;
736  break;
737  case 2:
738  case 3:
739  break;
740  default:
741  av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
742  value);
743  return AVERROR_INVALIDDATA;
744  }
745  break;
746  case TIFF_FILL_ORDER:
747  if (value < 1 || value > 2) {
749  "Unknown FillOrder value %d, trying default one\n", value);
750  value = 1;
751  }
752  s->fill_order = value - 1;
753  break;
754  case TIFF_PAL:
755  pal = (uint32_t *) s->palette;
756  off = type_sizes[type];
757  if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
758  return AVERROR_INVALIDDATA;
759  off = (type_sizes[type] - 1) << 3;
760  for (k = 2; k >= 0; k--) {
761  for (i = 0; i < count / 3; i++) {
762  if (k == 2)
763  pal[i] = 0xFFU << 24;
764  j = (ff_tget(&s->gb, type, s->le) >> off) << (k * 8);
765  pal[i] |= j;
766  }
767  }
768  s->palette_is_set = 1;
769  break;
770  case TIFF_PLANAR:
771  s->planar = value == 2;
772  break;
773  case TIFF_T4OPTIONS:
774  if (s->compr == TIFF_G3)
775  s->fax_opts = value;
776  break;
777  case TIFF_T6OPTIONS:
778  if (s->compr == TIFF_G4)
779  s->fax_opts = value;
780  break;
781 #define ADD_METADATA(count, name, sep)\
782  if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
783  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
784  goto end;\
785  }
787  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
788  break;
790  ADD_METADATA(count, "ModelTransformationTag", NULL);
791  break;
792  case TIFF_MODEL_TIEPOINT:
793  ADD_METADATA(count, "ModelTiepointTag", NULL);
794  break;
796  ADD_METADATA(1, "GeoTIFF_Version", NULL);
797  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
798  s->geotag_count = ff_tget_short(&s->gb, s->le);
799  if (s->geotag_count > count / 4 - 1) {
800  s->geotag_count = count / 4 - 1;
801  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
802  }
803  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
804  s->geotag_count = 0;
805  return -1;
806  }
807  s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);
808  if (!s->geotags) {
809  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
810  s->geotag_count = 0;
811  goto end;
812  }
813  for (i = 0; i < s->geotag_count; i++) {
814  s->geotags[i].key = ff_tget_short(&s->gb, s->le);
815  s->geotags[i].type = ff_tget_short(&s->gb, s->le);
816  s->geotags[i].count = ff_tget_short(&s->gb, s->le);
817 
818  if (!s->geotags[i].type)
819  s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
820  else
821  s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
822  }
823  break;
825  if (count >= INT_MAX / sizeof(int64_t))
826  return AVERROR_INVALIDDATA;
827  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
828  return AVERROR_INVALIDDATA;
829  dp = av_malloc(count * sizeof(double));
830  if (!dp) {
831  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
832  goto end;
833  }
834  for (i = 0; i < count; i++)
835  dp[i] = ff_tget_double(&s->gb, s->le);
836  for (i = 0; i < s->geotag_count; i++) {
837  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
838  if (s->geotags[i].count == 0
839  || s->geotags[i].offset + s->geotags[i].count > count) {
840  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
841  } else {
842  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
843  if (!ap) {
844  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
845  av_freep(&dp);
846  return AVERROR(ENOMEM);
847  }
848  s->geotags[i].val = ap;
849  }
850  }
851  }
852  av_freep(&dp);
853  break;
855  pos = bytestream2_tell(&s->gb);
856  for (i = 0; i < s->geotag_count; i++) {
857  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
858  if (s->geotags[i].count == 0
859  || s->geotags[i].offset + s->geotags[i].count > count) {
860  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
861  } else {
862  char *ap;
863 
864  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
865  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
866  return AVERROR_INVALIDDATA;
867  ap = av_malloc(s->geotags[i].count);
868  if (!ap) {
869  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
870  return AVERROR(ENOMEM);
871  }
872  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
873  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
874  s->geotags[i].val = ap;
875  }
876  }
877  }
878  break;
879  case TIFF_ARTIST:
880  ADD_METADATA(count, "artist", NULL);
881  break;
882  case TIFF_COPYRIGHT:
883  ADD_METADATA(count, "copyright", NULL);
884  break;
885  case TIFF_DATE:
886  ADD_METADATA(count, "date", NULL);
887  break;
888  case TIFF_DOCUMENT_NAME:
889  ADD_METADATA(count, "document_name", NULL);
890  break;
891  case TIFF_HOST_COMPUTER:
892  ADD_METADATA(count, "computer", NULL);
893  break;
895  ADD_METADATA(count, "description", NULL);
896  break;
897  case TIFF_MAKE:
898  ADD_METADATA(count, "make", NULL);
899  break;
900  case TIFF_MODEL:
901  ADD_METADATA(count, "model", NULL);
902  break;
903  case TIFF_PAGE_NAME:
904  ADD_METADATA(count, "page_name", NULL);
905  break;
906  case TIFF_PAGE_NUMBER:
907  ADD_METADATA(count, "page_number", " / ");
908  break;
909  case TIFF_SOFTWARE_NAME:
910  ADD_METADATA(count, "software", NULL);
911  break;
912  default:
913  if (s->avctx->err_recognition & AV_EF_EXPLODE) {
915  "Unknown or unsupported tag %d/0X%0X\n",
916  tag, tag);
917  return AVERROR_INVALIDDATA;
918  }
919  }
920 end:
921  bytestream2_seek(&s->gb, start, SEEK_SET);
922  return 0;
923 }
924 
925 static int decode_frame(AVCodecContext *avctx,
926  void *data, int *got_frame, AVPacket *avpkt)
927 {
928  TiffContext *const s = avctx->priv_data;
929  AVFrame *const p = data;
930  ThreadFrame frame = { .f = data };
931  unsigned off;
932  int le, ret, plane, planes;
933  int i, j, entries, stride;
934  unsigned soff, ssize;
935  uint8_t *dst;
936  GetByteContext stripsizes;
937  GetByteContext stripdata;
938 
939  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
940 
941  // parse image header
942  if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
943  av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
944  return ret;
945  } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
946  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
947  return AVERROR_INVALIDDATA;
948  }
949  s->le = le;
950  // TIFF_BPP is not a required tag and defaults to 1
951  s->bppcount = s->bpp = 1;
952  s->invert = 0;
953  s->compr = TIFF_RAW;
954  s->fill_order = 0;
955  free_geotags(s);
956 
957  // Reset these offsets so we can tell if they were set this frame
958  s->stripsizesoff = s->strippos = 0;
959  /* parse image file directory */
960  bytestream2_seek(&s->gb, off, SEEK_SET);
961  entries = ff_tget_short(&s->gb, le);
962  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
963  return AVERROR_INVALIDDATA;
964  for (i = 0; i < entries; i++) {
965  if ((ret = tiff_decode_tag(s, p)) < 0)
966  return ret;
967  }
968 
969  for (i = 0; i<s->geotag_count; i++) {
970  const char *keyname = get_geokey_name(s->geotags[i].key);
971  if (!keyname) {
972  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
973  continue;
974  }
975  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
976  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
977  continue;
978  }
979  ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
980  if (ret<0) {
981  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
982  return ret;
983  }
984  }
985 
986  if (!s->strippos && !s->stripoff) {
987  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
988  return AVERROR_INVALIDDATA;
989  }
990  /* now we have the data and may start decoding */
991  if ((ret = init_image(s, &frame)) < 0)
992  return ret;
993 
994  if (s->strips == 1 && !s->stripsize) {
995  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
996  s->stripsize = avpkt->size - s->stripoff;
997  }
998 
999  if (s->stripsizesoff) {
1000  if (s->stripsizesoff >= (unsigned)avpkt->size)
1001  return AVERROR_INVALIDDATA;
1002  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, avpkt->size - s->stripsizesoff);
1003  }
1004  if (s->strippos) {
1005  if (s->strippos >= (unsigned)avpkt->size)
1006  return AVERROR_INVALIDDATA;
1007  bytestream2_init(&stripdata, avpkt->data + s->strippos, avpkt->size - s->strippos);
1008  }
1009 
1010  if (s->rps <= 0) {
1011  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1012  return AVERROR_INVALIDDATA;
1013  }
1014 
1015  planes = s->planar ? s->bppcount : 1;
1016  for (plane = 0; plane < planes; plane++) {
1017  stride = p->linesize[plane];
1018  dst = p->data[plane];
1019  for (i = 0; i < s->height; i += s->rps) {
1020  if (s->stripsizesoff)
1021  ssize = ff_tget(&stripsizes, s->sstype, s->le);
1022  else
1023  ssize = s->stripsize;
1024 
1025  if (s->strippos)
1026  soff = ff_tget(&stripdata, s->sot, s->le);
1027  else
1028  soff = s->stripoff;
1029 
1030  if (soff > avpkt->size || ssize > avpkt->size - soff) {
1031  av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1032  return AVERROR_INVALIDDATA;
1033  }
1034  if ((ret = tiff_unpack_strip(s, dst, stride, avpkt->data + soff, ssize,
1035  FFMIN(s->rps, s->height - i))) < 0) {
1036  if (avctx->err_recognition & AV_EF_EXPLODE)
1037  return ret;
1038  break;
1039  }
1040  dst += s->rps * stride;
1041  }
1042  if (s->predictor == 2) {
1043  dst = p->data[plane];
1044  soff = s->bpp >> 3;
1045  if (s->planar)
1046  soff = FFMAX(soff / s->bppcount, 1);
1047  ssize = s->width * soff;
1048  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1052  for (i = 0; i < s->height; i++) {
1053  for (j = soff; j < ssize; j += 2)
1054  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1055  dst += stride;
1056  }
1057  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1061  for (i = 0; i < s->height; i++) {
1062  for (j = soff; j < ssize; j += 2)
1063  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1064  dst += stride;
1065  }
1066  } else {
1067  for (i = 0; i < s->height; i++) {
1068  for (j = soff; j < ssize; j++)
1069  dst[j] += dst[j - soff];
1070  dst += stride;
1071  }
1072  }
1073  }
1074 
1075  if (s->invert) {
1076  dst = p->data[plane];
1077  for (i = 0; i < s->height; i++) {
1078  for (j = 0; j < p->linesize[plane]; j++)
1079  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1080  dst += p->linesize[plane];
1081  }
1082  }
1083  }
1084 
1085  if (s->planar && s->bppcount > 2) {
1086  FFSWAP(uint8_t*, p->data[0], p->data[2]);
1087  FFSWAP(int, p->linesize[0], p->linesize[2]);
1088  FFSWAP(uint8_t*, p->data[0], p->data[1]);
1089  FFSWAP(int, p->linesize[0], p->linesize[1]);
1090  }
1091 
1092  *got_frame = 1;
1093 
1094  return avpkt->size;
1095 }
1096 
1098 {
1099  TiffContext *s = avctx->priv_data;
1100 
1101  s->width = 0;
1102  s->height = 0;
1103  s->avctx = avctx;
1104  ff_lzw_decode_open(&s->lzw);
1106 
1107  return 0;
1108 }
1109 
1110 static av_cold int tiff_end(AVCodecContext *avctx)
1111 {
1112  TiffContext *const s = avctx->priv_data;
1113 
1114  free_geotags(s);
1115 
1116  ff_lzw_decode_close(&s->lzw);
1117  av_freep(&s->deinvert_buf);
1118  return 0;
1119 }
1120 
1122  .name = "tiff",
1123  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1124  .type = AVMEDIA_TYPE_VIDEO,
1125  .id = AV_CODEC_ID_TIFF,
1126  .priv_data_size = sizeof(TiffContext),
1127  .init = tiff_init,
1128  .close = tiff_end,
1129  .decode = decode_frame,
1131  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1132 };