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