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;
57  int planar;
58  int subsampling[2];
59  int fax_opts;
60  int predictor;
62  uint32_t res[4];
63 
64  int strips, rps, sstype;
65  int sot;
68 
72  unsigned int yuv_line_size;
73 
76 } TiffContext;
77 
78 static void free_geotags(TiffContext *const s)
79 {
80  int i;
81  for (i = 0; i < s->geotag_count; i++) {
82  if (s->geotags[i].val)
83  av_freep(&s->geotags[i].val);
84  }
85  av_freep(&s->geotags);
86  s->geotag_count = 0;
87 }
88 
89 #define RET_GEOKEY(TYPE, array, element)\
90  if (key >= TIFF_##TYPE##_KEY_ID_OFFSET &&\
91  key - TIFF_##TYPE##_KEY_ID_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_name_type_map))\
92  return ff_tiff_##array##_name_type_map[key - TIFF_##TYPE##_KEY_ID_OFFSET].element;
93 
94 static const char *get_geokey_name(int key)
95 {
96  RET_GEOKEY(VERT, vert, name);
97  RET_GEOKEY(PROJ, proj, name);
98  RET_GEOKEY(GEOG, geog, name);
99  RET_GEOKEY(CONF, conf, name);
100 
101  return NULL;
102 }
103 
104 static int get_geokey_type(int key)
105 {
106  RET_GEOKEY(VERT, vert, type);
107  RET_GEOKEY(PROJ, proj, type);
108  RET_GEOKEY(GEOG, geog, type);
109  RET_GEOKEY(CONF, conf, type);
110 
111  return AVERROR_INVALIDDATA;
112 }
113 
114 static int cmp_id_key(const void *id, const void *k)
115 {
116  return *(const int*)id - ((const TiffGeoTagKeyName*)k)->key;
117 }
118 
119 static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)
120 {
121  TiffGeoTagKeyName *r = bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key);
122  if(r)
123  return r->name;
124 
125  return NULL;
126 }
127 
128 static char *get_geokey_val(int key, int val)
129 {
130  char *ap;
131 
132  if (val == TIFF_GEO_KEY_UNDEFINED)
133  return av_strdup("undefined");
134  if (val == TIFF_GEO_KEY_USER_DEFINED)
135  return av_strdup("User-Defined");
136 
137 #define RET_GEOKEY_VAL(TYPE, array)\
138  if (val >= TIFF_##TYPE##_OFFSET &&\
139  val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\
140  return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);
141 
142  switch (key) {
144  RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);
145  break;
147  RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);
148  break;
152  RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);
153  break;
156  RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);
157  break;
159  RET_GEOKEY_VAL(GCS_TYPE, gcs_type);
160  RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);
161  break;
163  RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);
164  RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);
165  break;
167  RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);
168  break;
170  RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);
171  break;
174  if(ap) return ap;
175  break;
178  if(ap) return ap;
179  break;
181  RET_GEOKEY_VAL(COORD_TRANS, coord_trans);
182  break;
184  RET_GEOKEY_VAL(VERT_CS, vert_cs);
185  RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);
186  break;
187 
188  }
189 
190  ap = av_malloc(14);
191  if (ap)
192  snprintf(ap, 14, "Unknown-%d", val);
193  return ap;
194 }
195 
196 static char *doubles2str(double *dp, int count, const char *sep)
197 {
198  int i;
199  char *ap, *ap0;
200  uint64_t component_len;
201  if (!sep) sep = ", ";
202  component_len = 24LL + strlen(sep);
203  if (count >= (INT_MAX - 1)/component_len)
204  return NULL;
205  ap = av_malloc(component_len * count + 1);
206  if (!ap)
207  return NULL;
208  ap0 = ap;
209  ap[0] = '\0';
210  for (i = 0; i < count; i++) {
211  unsigned l = snprintf(ap, component_len, "%.15g%s", dp[i], sep);
212  if(l >= component_len) {
213  av_free(ap0);
214  return NULL;
215  }
216  ap += l;
217  }
218  ap0[strlen(ap0) - strlen(sep)] = '\0';
219  return ap0;
220 }
221 
222 static int add_metadata(int count, int type,
223  const char *name, const char *sep, TiffContext *s, AVFrame *frame)
224 {
225  switch(type) {
226  case TIFF_DOUBLE: return ff_tadd_doubles_metadata(count, name, sep, &s->gb, s->le, avpriv_frame_get_metadatap(frame));
227  case TIFF_SHORT : return ff_tadd_shorts_metadata(count, name, sep, &s->gb, s->le, 0, avpriv_frame_get_metadatap(frame));
228  case TIFF_STRING: return ff_tadd_string_metadata(count, name, &s->gb, s->le, avpriv_frame_get_metadatap(frame));
229  default : return AVERROR_INVALIDDATA;
230  };
231 }
232 
233 static void av_always_inline horizontal_fill(unsigned int bpp, uint8_t* dst,
234  int usePtr, const uint8_t *src,
235  uint8_t c, int width, int offset)
236 {
237  switch (bpp) {
238  case 1:
239  while (--width >= 0) {
240  dst[(width+offset)*8+7] = (usePtr ? src[width] : c) & 0x1;
241  dst[(width+offset)*8+6] = (usePtr ? src[width] : c) >> 1 & 0x1;
242  dst[(width+offset)*8+5] = (usePtr ? src[width] : c) >> 2 & 0x1;
243  dst[(width+offset)*8+4] = (usePtr ? src[width] : c) >> 3 & 0x1;
244  dst[(width+offset)*8+3] = (usePtr ? src[width] : c) >> 4 & 0x1;
245  dst[(width+offset)*8+2] = (usePtr ? src[width] : c) >> 5 & 0x1;
246  dst[(width+offset)*8+1] = (usePtr ? src[width] : c) >> 6 & 0x1;
247  dst[(width+offset)*8+0] = (usePtr ? src[width] : c) >> 7;
248  }
249  break;
250  case 2:
251  while (--width >= 0) {
252  dst[(width+offset)*4+3] = (usePtr ? src[width] : c) & 0x3;
253  dst[(width+offset)*4+2] = (usePtr ? src[width] : c) >> 2 & 0x3;
254  dst[(width+offset)*4+1] = (usePtr ? src[width] : c) >> 4 & 0x3;
255  dst[(width+offset)*4+0] = (usePtr ? src[width] : c) >> 6;
256  }
257  break;
258  case 4:
259  while (--width >= 0) {
260  dst[(width+offset)*2+1] = (usePtr ? src[width] : c) & 0xF;
261  dst[(width+offset)*2+0] = (usePtr ? src[width] : c) >> 4;
262  }
263  break;
264  default:
265  if (usePtr) {
266  memcpy(dst + offset, src, width);
267  } else {
268  memset(dst + offset, c, width);
269  }
270  }
271 }
272 
273 static int deinvert_buffer(TiffContext *s, const uint8_t *src, int size)
274 {
275  int i;
276 
278  if (!s->deinvert_buf)
279  return AVERROR(ENOMEM);
280  for (i = 0; i < size; i++)
281  s->deinvert_buf[i] = ff_reverse[src[i]];
282 
283  return 0;
284 }
285 
286 static void unpack_yuv(TiffContext *s, AVFrame *p,
287  const uint8_t *src, int lnum)
288 {
289  int i, j, k;
290  int w = (s->width - 1) / s->subsampling[0] + 1;
291  uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
292  uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
293  if (s->width % s->subsampling[0] || s->height % s->subsampling[1]) {
294  for (i = 0; i < w; i++) {
295  for (j = 0; j < s->subsampling[1]; j++)
296  for (k = 0; k < s->subsampling[0]; k++)
297  p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
298  FFMIN(i * s->subsampling[0] + k, s->width-1)] = *src++;
299  *pu++ = *src++;
300  *pv++ = *src++;
301  }
302  }else{
303  for (i = 0; i < w; i++) {
304  for (j = 0; j < s->subsampling[1]; j++)
305  for (k = 0; k < s->subsampling[0]; k++)
306  p->data[0][(lnum + j) * p->linesize[0] +
307  i * s->subsampling[0] + k] = *src++;
308  *pu++ = *src++;
309  *pv++ = *src++;
310  }
311  }
312 }
313 
314 #if CONFIG_ZLIB
315 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
316  int size)
317 {
318  z_stream zstream = { 0 };
319  int zret;
320 
321  zstream.next_in = (uint8_t *)src;
322  zstream.avail_in = size;
323  zstream.next_out = dst;
324  zstream.avail_out = *len;
325  zret = inflateInit(&zstream);
326  if (zret != Z_OK) {
327  av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
328  return zret;
329  }
330  zret = inflate(&zstream, Z_SYNC_FLUSH);
331  inflateEnd(&zstream);
332  *len = zstream.total_out;
333  return zret == Z_STREAM_END ? Z_OK : zret;
334 }
335 
336 static int tiff_unpack_zlib(TiffContext *s, AVFrame *p, uint8_t *dst, int stride,
337  const uint8_t *src, int size, int width, int lines,
338  int strip_start, int is_yuv)
339 {
340  uint8_t *zbuf;
341  unsigned long outlen;
342  int ret, line;
343  outlen = width * lines;
344  zbuf = av_malloc(outlen);
345  if (!zbuf)
346  return AVERROR(ENOMEM);
347  if (s->fill_order) {
348  if ((ret = deinvert_buffer(s, src, size)) < 0) {
349  av_free(zbuf);
350  return ret;
351  }
352  src = s->deinvert_buf;
353  }
354  ret = tiff_uncompress(zbuf, &outlen, src, size);
355  if (ret != Z_OK) {
357  "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
358  (unsigned long)width * lines, ret);
359  av_free(zbuf);
360  return AVERROR_UNKNOWN;
361  }
362  src = zbuf;
363  for (line = 0; line < lines; line++) {
364  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
365  horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
366  } else {
367  memcpy(dst, src, width);
368  }
369  if (is_yuv) {
370  unpack_yuv(s, p, dst, strip_start + line);
371  line += s->subsampling[1] - 1;
372  }
373  dst += stride;
374  src += width;
375  }
376  av_free(zbuf);
377  return 0;
378 }
379 #endif
380 
381 
382 static int tiff_unpack_fax(TiffContext *s, uint8_t *dst, int stride,
383  const uint8_t *src, int size, int width, int lines)
384 {
385  int i, ret = 0;
386  int line;
387  uint8_t *src2 = av_malloc((unsigned)size +
389 
390  if (!src2) {
392  "Error allocating temporary buffer\n");
393  return AVERROR(ENOMEM);
394  }
395  if (s->fax_opts & 2) {
396  avpriv_request_sample(s->avctx, "Uncompressed fax mode");
397  av_free(src2);
398  return AVERROR_PATCHWELCOME;
399  }
400  if (!s->fill_order) {
401  memcpy(src2, src, size);
402  } else {
403  for (i = 0; i < size; i++)
404  src2[i] = ff_reverse[src[i]];
405  }
406  memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
407  ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
408  s->compr, s->fax_opts);
409  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
410  for (line = 0; line < lines; line++) {
411  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
412  dst += stride;
413  }
414  av_free(src2);
415  return ret;
416 }
417 
418 static int tiff_unpack_strip(TiffContext *s, AVFrame *p, uint8_t *dst, int stride,
419  const uint8_t *src, int size, int strip_start, int lines)
420 {
421  PutByteContext pb;
422  int c, line, pixels, code, ret;
423  const uint8_t *ssrc = src;
424  int width = ((s->width * s->bpp) + 7) >> 3;
426  int is_yuv = !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components >= 2;
427 
428  if (s->planar)
429  width /= s->bppcount;
430 
431  if (size <= 0)
432  return AVERROR_INVALIDDATA;
433 
434  if (is_yuv) {
435  int bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
436  s->subsampling[0] * s->subsampling[1] + 7) >> 3;
437  av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
438  if (s->yuv_line == NULL) {
439  av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
440  return AVERROR(ENOMEM);
441  }
442  dst = s->yuv_line;
443  stride = 0;
444  width = s->width * s->subsampling[1] + 2*(s->width / s->subsampling[0]);
445  av_assert0(width <= bytes_per_row);
446  av_assert0(s->bpp == 24);
447  }
448 
449  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
450 #if CONFIG_ZLIB
451  return tiff_unpack_zlib(s, p, dst, stride, src, size, width, lines,
452  strip_start, is_yuv);
453 #else
455  "zlib support not enabled, "
456  "deflate compression not supported\n");
457  return AVERROR(ENOSYS);
458 #endif
459  }
460  if (s->compr == TIFF_LZW) {
461  if (s->fill_order) {
462  if ((ret = deinvert_buffer(s, src, size)) < 0)
463  return ret;
464  ssrc = src = s->deinvert_buf;
465  }
466  if (size > 1 && !src[0] && (src[1]&1)) {
467  av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
468  }
469  if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
470  av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
471  return ret;
472  }
473  for (line = 0; line < lines; line++) {
474  pixels = ff_lzw_decode(s->lzw, dst, width);
475  if (pixels < width) {
476  av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
477  pixels, width);
478  return AVERROR_INVALIDDATA;
479  }
480  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
481  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
482  if (is_yuv) {
483  unpack_yuv(s, p, dst, strip_start + line);
484  line += s->subsampling[1] - 1;
485  }
486  dst += stride;
487  }
488  return 0;
489  }
490  if (s->compr == TIFF_CCITT_RLE ||
491  s->compr == TIFF_G3 ||
492  s->compr == TIFF_G4) {
493  if (is_yuv)
494  return AVERROR_INVALIDDATA;
495 
496  return tiff_unpack_fax(s, dst, stride, src, size, width, lines);
497  }
498 
499  bytestream2_init(&s->gb, src, size);
500  bytestream2_init_writer(&pb, dst, is_yuv ? s->yuv_line_size : (stride * lines));
501 
502  for (line = 0; line < lines; line++) {
503  if (src - ssrc > size) {
504  av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
505  return AVERROR_INVALIDDATA;
506  }
507 
508  if (bytestream2_get_bytes_left(&s->gb) == 0 || bytestream2_get_eof(&pb))
509  break;
510  bytestream2_seek_p(&pb, stride * line, SEEK_SET);
511  switch (s->compr) {
512  case TIFF_RAW:
513  if (ssrc + size - src < width)
514  return AVERROR_INVALIDDATA;
515 
516  if (!s->fill_order) {
518  dst, 1, src, 0, width, 0);
519  } else {
520  int i;
521  for (i = 0; i < width; i++)
522  dst[i] = ff_reverse[src[i]];
523  }
524  src += width;
525  break;
526  case TIFF_PACKBITS:
527  for (pixels = 0; pixels < width;) {
528  if (ssrc + size - src < 2) {
529  av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
530  return AVERROR_INVALIDDATA;
531  }
532  code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;
533  if (code >= 0) {
534  code++;
535  if (pixels + code > width ||
536  ssrc + size - src < code) {
538  "Copy went out of bounds\n");
539  return AVERROR_INVALIDDATA;
540  }
542  dst, 1, src, 0, code, pixels);
543  src += code;
544  pixels += code;
545  } else if (code != -128) { // -127..-1
546  code = (-code) + 1;
547  if (pixels + code > width) {
549  "Run went out of bounds\n");
550  return AVERROR_INVALIDDATA;
551  }
552  c = *src++;
554  dst, 0, NULL, c, code, pixels);
555  pixels += code;
556  }
557  }
558  if (s->fill_order) {
559  int i;
560  for (i = 0; i < width; i++)
561  dst[i] = ff_reverse[dst[i]];
562  }
563  break;
564  }
565  if (is_yuv) {
566  unpack_yuv(s, p, dst, strip_start + line);
567  line += s->subsampling[1] - 1;
568  }
569  dst += stride;
570  }
571  return 0;
572 }
573 
575 {
576  int ret;
577 
578  switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
579  case 11:
580  if (!s->palette_is_set) {
582  break;
583  }
584  case 21:
585  case 41:
586  case 81:
588  break;
589  case 243:
591  if (s->subsampling[0] == 1 && s->subsampling[1] == 1) {
593  } else if (s->subsampling[0] == 2 && s->subsampling[1] == 1) {
595  } else if (s->subsampling[0] == 4 && s->subsampling[1] == 1) {
597  } else if (s->subsampling[0] == 1 && s->subsampling[1] == 2) {
599  } else if (s->subsampling[0] == 2 && s->subsampling[1] == 2) {
601  } else if (s->subsampling[0] == 4 && s->subsampling[1] == 4) {
603  } else {
604  av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr subsampling\n");
605  return AVERROR_PATCHWELCOME;
606  }
607  } else
609  break;
610  case 161:
612  break;
613  case 162:
615  break;
616  case 322:
618  break;
619  case 324:
621  break;
622  case 483:
624  break;
625  case 644:
627  break;
628  case 1243:
630  break;
631  case 1324:
633  break;
634  case 1483:
636  break;
637  case 1644:
639  break;
640  default:
642  "This format is not supported (bpp=%d, bppcount=%d)\n",
643  s->bpp, s->bppcount);
644  return AVERROR_INVALIDDATA;
645  }
646 
649  if((desc->flags & AV_PIX_FMT_FLAG_RGB) || desc->nb_components < 3) {
650  av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr variant\n");
651  return AVERROR_INVALIDDATA;
652  }
653  }
654 
655  if (s->width != s->avctx->width || s->height != s->avctx->height) {
656  ret = ff_set_dimensions(s->avctx, s->width, s->height);
657  if (ret < 0)
658  return ret;
659  }
660  if ((ret = ff_thread_get_buffer(s->avctx, frame, 0)) < 0)
661  return ret;
662  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
663  memcpy(frame->f->data[1], s->palette, sizeof(s->palette));
664  }
665  return 0;
666 }
667 
668 static void set_sar(TiffContext *s, unsigned tag, unsigned num, unsigned den)
669 {
670  int offset = tag == TIFF_YRES ? 2 : 0;
671  s->res[offset++] = num;
672  s->res[offset] = den;
673  if (s->res[0] && s->res[1] && s->res[2] && s->res[3])
675  s->res[2] * (uint64_t)s->res[1], s->res[0] * (uint64_t)s->res[3], INT32_MAX);
676 }
677 
679 {
680  unsigned tag, type, count, off, value = 0, value2 = 0;
681  int i, start;
682  int pos;
683  int ret;
684  double *dp;
685 
686  ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);
687  if (ret < 0) {
688  goto end;
689  }
690 
691  off = bytestream2_tell(&s->gb);
692  if (count == 1) {
693  switch (type) {
694  case TIFF_BYTE:
695  case TIFF_SHORT:
696  case TIFF_LONG:
697  value = ff_tget(&s->gb, type, s->le);
698  break;
699  case TIFF_RATIONAL:
700  value = ff_tget(&s->gb, TIFF_LONG, s->le);
701  value2 = ff_tget(&s->gb, TIFF_LONG, s->le);
702  break;
703  case TIFF_STRING:
704  if (count <= 4) {
705  break;
706  }
707  default:
708  value = UINT_MAX;
709  }
710  }
711 
712  switch (tag) {
713  case TIFF_WIDTH:
714  s->width = value;
715  break;
716  case TIFF_HEIGHT:
717  s->height = value;
718  break;
719  case TIFF_BPP:
720  s->bppcount = count;
721  if (count > 4) {
723  "This format is not supported (bpp=%d, %d components)\n",
724  s->bpp, count);
725  return AVERROR_INVALIDDATA;
726  }
727  if (count == 1)
728  s->bpp = value;
729  else {
730  switch (type) {
731  case TIFF_BYTE:
732  case TIFF_SHORT:
733  case TIFF_LONG:
734  s->bpp = 0;
735  if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
736  return AVERROR_INVALIDDATA;
737  for (i = 0; i < count; i++)
738  s->bpp += ff_tget(&s->gb, type, s->le);
739  break;
740  default:
741  s->bpp = -1;
742  }
743  }
744  break;
746  if (count != 1) {
748  "Samples per pixel requires a single value, many provided\n");
749  return AVERROR_INVALIDDATA;
750  }
751  if (value > 4U) {
753  "Samples per pixel %d is too large\n", value);
754  return AVERROR_INVALIDDATA;
755  }
756  if (s->bppcount == 1)
757  s->bpp *= value;
758  s->bppcount = value;
759  break;
760  case TIFF_COMPR:
761  s->compr = value;
762  s->predictor = 0;
763  switch (s->compr) {
764  case TIFF_RAW:
765  case TIFF_PACKBITS:
766  case TIFF_LZW:
767  case TIFF_CCITT_RLE:
768  break;
769  case TIFF_G3:
770  case TIFF_G4:
771  s->fax_opts = 0;
772  break;
773  case TIFF_DEFLATE:
774  case TIFF_ADOBE_DEFLATE:
775 #if CONFIG_ZLIB
776  break;
777 #else
778  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
779  return AVERROR(ENOSYS);
780 #endif
781  case TIFF_JPEG:
782  case TIFF_NEWJPEG:
783  avpriv_report_missing_feature(s->avctx, "JPEG compression");
784  return AVERROR_PATCHWELCOME;
785  case TIFF_LZMA:
786  avpriv_report_missing_feature(s->avctx, "LZMA compression");
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 (!value || (type == TIFF_LONG && value == UINT_MAX))
796  value = s->height;
797  s->rps = FFMIN(value, s->height);
798  break;
799  case TIFF_STRIP_OFFS:
800  if (count == 1) {
801  s->strippos = 0;
802  s->stripoff = value;
803  } else
804  s->strippos = off;
805  s->strips = count;
806  if (s->strips == 1)
807  s->rps = s->height;
808  s->sot = type;
809  break;
810  case TIFF_STRIP_SIZE:
811  if (count == 1) {
812  s->stripsizesoff = 0;
813  s->stripsize = value;
814  s->strips = 1;
815  } else {
816  s->stripsizesoff = off;
817  }
818  s->strips = count;
819  s->sstype = type;
820  break;
821  case TIFF_XRES:
822  case TIFF_YRES:
823  set_sar(s, tag, value, value2);
824  break;
826  case TIFF_TILE_LENGTH:
827  case TIFF_TILE_OFFSETS:
828  case TIFF_TILE_WIDTH:
829  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
830  return AVERROR_PATCHWELCOME;
831  break;
832  case TIFF_PREDICTOR:
833  s->predictor = value;
834  break;
835  case TIFF_PHOTOMETRIC:
836  switch (value) {
842  s->photometric = value;
843  break;
854  "PhotometricInterpretation 0x%04X",
855  value);
856  return AVERROR_PATCHWELCOME;
857  default:
858  av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "
859  "unknown\n", 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  GetByteContext pal_gb[3];
873  off = type_sizes[type];
874  if (count / 3 > 256 ||
875  bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
876  return AVERROR_INVALIDDATA;
877 
878  pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
879  bytestream2_skip(&pal_gb[1], count / 3 * off);
880  bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
881 
882  off = (type_sizes[type] - 1) << 3;
883  for (i = 0; i < count / 3; i++) {
884  uint32_t p = 0xFF000000;
885  p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;
886  p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;
887  p |= ff_tget(&pal_gb[2], type, s->le) >> off;
888  s->palette[i] = p;
889  }
890  s->palette_is_set = 1;
891  break;
892  }
893  case TIFF_PLANAR:
894  s->planar = value == 2;
895  break;
897  if (count != 2) {
898  av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");
899  return AVERROR_INVALIDDATA;
900  }
901  for (i = 0; i < count; i++)
902  s->subsampling[i] = ff_tget(&s->gb, type, s->le);
903  break;
904  case TIFF_T4OPTIONS:
905  if (s->compr == TIFF_G3)
906  s->fax_opts = value;
907  break;
908  case TIFF_T6OPTIONS:
909  if (s->compr == TIFF_G4)
910  s->fax_opts = value;
911  break;
912 #define ADD_METADATA(count, name, sep)\
913  if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
914  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
915  goto end;\
916  }
918  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
919  break;
921  ADD_METADATA(count, "ModelTransformationTag", NULL);
922  break;
923  case TIFF_MODEL_TIEPOINT:
924  ADD_METADATA(count, "ModelTiepointTag", NULL);
925  break;
927  ADD_METADATA(1, "GeoTIFF_Version", NULL);
928  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
929  s->geotag_count = ff_tget_short(&s->gb, s->le);
930  if (s->geotag_count > count / 4 - 1) {
931  s->geotag_count = count / 4 - 1;
932  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
933  }
934  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
935  s->geotag_count = 0;
936  return -1;
937  }
939  if (!s->geotags) {
940  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
941  s->geotag_count = 0;
942  goto end;
943  }
944  for (i = 0; i < s->geotag_count; i++) {
945  s->geotags[i].key = ff_tget_short(&s->gb, s->le);
946  s->geotags[i].type = ff_tget_short(&s->gb, s->le);
947  s->geotags[i].count = ff_tget_short(&s->gb, s->le);
948 
949  if (!s->geotags[i].type)
950  s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
951  else
952  s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
953  }
954  break;
956  if (count >= INT_MAX / sizeof(int64_t))
957  return AVERROR_INVALIDDATA;
958  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
959  return AVERROR_INVALIDDATA;
960  dp = av_malloc_array(count, sizeof(double));
961  if (!dp) {
962  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
963  goto end;
964  }
965  for (i = 0; i < count; i++)
966  dp[i] = ff_tget_double(&s->gb, s->le);
967  for (i = 0; i < s->geotag_count; i++) {
968  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
969  if (s->geotags[i].count == 0
970  || s->geotags[i].offset + s->geotags[i].count > count) {
971  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
972  } else {
973  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
974  if (!ap) {
975  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
976  av_freep(&dp);
977  return AVERROR(ENOMEM);
978  }
979  s->geotags[i].val = ap;
980  }
981  }
982  }
983  av_freep(&dp);
984  break;
986  pos = bytestream2_tell(&s->gb);
987  for (i = 0; i < s->geotag_count; i++) {
988  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
989  if (s->geotags[i].count == 0
990  || s->geotags[i].offset + s->geotags[i].count > count) {
991  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
992  } else {
993  char *ap;
994 
995  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
996  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
997  return AVERROR_INVALIDDATA;
998  ap = av_malloc(s->geotags[i].count);
999  if (!ap) {
1000  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1001  return AVERROR(ENOMEM);
1002  }
1003  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
1004  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
1005  s->geotags[i].val = ap;
1006  }
1007  }
1008  }
1009  break;
1010  case TIFF_ARTIST:
1011  ADD_METADATA(count, "artist", NULL);
1012  break;
1013  case TIFF_COPYRIGHT:
1014  ADD_METADATA(count, "copyright", NULL);
1015  break;
1016  case TIFF_DATE:
1017  ADD_METADATA(count, "date", NULL);
1018  break;
1019  case TIFF_DOCUMENT_NAME:
1020  ADD_METADATA(count, "document_name", NULL);
1021  break;
1022  case TIFF_HOST_COMPUTER:
1023  ADD_METADATA(count, "computer", NULL);
1024  break;
1026  ADD_METADATA(count, "description", NULL);
1027  break;
1028  case TIFF_MAKE:
1029  ADD_METADATA(count, "make", NULL);
1030  break;
1031  case TIFF_MODEL:
1032  ADD_METADATA(count, "model", NULL);
1033  break;
1034  case TIFF_PAGE_NAME:
1035  ADD_METADATA(count, "page_name", NULL);
1036  break;
1037  case TIFF_PAGE_NUMBER:
1038  ADD_METADATA(count, "page_number", " / ");
1039  break;
1040  case TIFF_SOFTWARE_NAME:
1041  ADD_METADATA(count, "software", NULL);
1042  break;
1043  default:
1044  if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1046  "Unknown or unsupported tag %d/0X%0X\n",
1047  tag, tag);
1048  return AVERROR_INVALIDDATA;
1049  }
1050  }
1051 end:
1052  bytestream2_seek(&s->gb, start, SEEK_SET);
1053  return 0;
1054 }
1055 
1056 static int decode_frame(AVCodecContext *avctx,
1057  void *data, int *got_frame, AVPacket *avpkt)
1058 {
1059  TiffContext *const s = avctx->priv_data;
1060  AVFrame *const p = data;
1061  ThreadFrame frame = { .f = data };
1062  unsigned off;
1063  int le, ret, plane, planes;
1064  int i, j, entries, stride;
1065  unsigned soff, ssize;
1066  uint8_t *dst;
1067  GetByteContext stripsizes;
1068  GetByteContext stripdata;
1069 
1070  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1071 
1072  // parse image header
1073  if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
1074  av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
1075  return ret;
1076  } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1077  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1078  return AVERROR_INVALIDDATA;
1079  }
1080  s->le = le;
1081  // TIFF_BPP is not a required tag and defaults to 1
1082  s->bppcount = s->bpp = 1;
1084  s->compr = TIFF_RAW;
1085  s->fill_order = 0;
1086  free_geotags(s);
1087 
1088  // Reset these offsets so we can tell if they were set this frame
1089  s->stripsizesoff = s->strippos = 0;
1090  /* parse image file directory */
1091  bytestream2_seek(&s->gb, off, SEEK_SET);
1092  entries = ff_tget_short(&s->gb, le);
1093  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1094  return AVERROR_INVALIDDATA;
1095  for (i = 0; i < entries; i++) {
1096  if ((ret = tiff_decode_tag(s, p)) < 0)
1097  return ret;
1098  }
1099 
1100  for (i = 0; i<s->geotag_count; i++) {
1101  const char *keyname = get_geokey_name(s->geotags[i].key);
1102  if (!keyname) {
1103  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1104  continue;
1105  }
1106  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1107  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1108  continue;
1109  }
1110  ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
1111  if (ret<0) {
1112  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1113  return ret;
1114  }
1115  }
1116 
1117  if (!s->strippos && !s->stripoff) {
1118  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1119  return AVERROR_INVALIDDATA;
1120  }
1121  /* now we have the data and may start decoding */
1122  if ((ret = init_image(s, &frame)) < 0)
1123  return ret;
1124 
1125  if (s->strips == 1 && !s->stripsize) {
1126  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1127  s->stripsize = avpkt->size - s->stripoff;
1128  }
1129 
1130  if (s->stripsizesoff) {
1131  if (s->stripsizesoff >= (unsigned)avpkt->size)
1132  return AVERROR_INVALIDDATA;
1133  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
1134  avpkt->size - s->stripsizesoff);
1135  }
1136  if (s->strippos) {
1137  if (s->strippos >= (unsigned)avpkt->size)
1138  return AVERROR_INVALIDDATA;
1139  bytestream2_init(&stripdata, avpkt->data + s->strippos,
1140  avpkt->size - s->strippos);
1141  }
1142 
1143  if (s->rps <= 0) {
1144  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1145  return AVERROR_INVALIDDATA;
1146  }
1147 
1148  planes = s->planar ? s->bppcount : 1;
1149  for (plane = 0; plane < planes; plane++) {
1150  stride = p->linesize[plane];
1151  dst = p->data[plane];
1152  for (i = 0; i < s->height; i += s->rps) {
1153  if (s->stripsizesoff)
1154  ssize = ff_tget(&stripsizes, s->sstype, le);
1155  else
1156  ssize = s->stripsize;
1157 
1158  if (s->strippos)
1159  soff = ff_tget(&stripdata, s->sot, 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 ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,
1168  FFMIN(s->rps, s->height - i))) < 0) {
1169  if (avctx->err_recognition & AV_EF_EXPLODE)
1170  return ret;
1171  break;
1172  }
1173  dst += s->rps * stride;
1174  }
1175  if (s->predictor == 2) {
1176  if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
1177  av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");
1178  return AVERROR_PATCHWELCOME;
1179  }
1180  dst = p->data[plane];
1181  soff = s->bpp >> 3;
1182  if (s->planar)
1183  soff = FFMAX(soff / s->bppcount, 1);
1184  ssize = s->width * soff;
1185  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1189  for (i = 0; i < s->height; i++) {
1190  for (j = soff; j < ssize; j += 2)
1191  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1192  dst += stride;
1193  }
1194  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1198  for (i = 0; i < s->height; i++) {
1199  for (j = soff; j < ssize; j += 2)
1200  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1201  dst += stride;
1202  }
1203  } else {
1204  for (i = 0; i < s->height; i++) {
1205  for (j = soff; j < ssize; j++)
1206  dst[j] += dst[j - soff];
1207  dst += stride;
1208  }
1209  }
1210  }
1211 
1213  dst = p->data[plane];
1214  for (i = 0; i < s->height; i++) {
1215  for (j = 0; j < p->linesize[plane]; j++)
1216  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1217  dst += stride;
1218  }
1219  }
1220  }
1221 
1222  if (s->planar && s->bppcount > 2) {
1223  FFSWAP(uint8_t*, p->data[0], p->data[2]);
1224  FFSWAP(int, p->linesize[0], p->linesize[2]);
1225  FFSWAP(uint8_t*, p->data[0], p->data[1]);
1226  FFSWAP(int, p->linesize[0], p->linesize[1]);
1227  }
1228 
1229  *got_frame = 1;
1230 
1231  return avpkt->size;
1232 }
1233 
1235 {
1236  TiffContext *s = avctx->priv_data;
1237 
1238  s->width = 0;
1239  s->height = 0;
1240  s->subsampling[0] =
1241  s->subsampling[1] = 1;
1242  s->avctx = avctx;
1243  ff_lzw_decode_open(&s->lzw);
1245 
1246  return 0;
1247 }
1248 
1249 static av_cold int tiff_end(AVCodecContext *avctx)
1250 {
1251  TiffContext *const s = avctx->priv_data;
1252 
1253  free_geotags(s);
1254 
1255  ff_lzw_decode_close(&s->lzw);
1256  av_freep(&s->deinvert_buf);
1257  return 0;
1258 }
1259 
1261  .name = "tiff",
1262  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1263  .type = AVMEDIA_TYPE_VIDEO,
1264  .id = AV_CODEC_ID_TIFF,
1265  .priv_data_size = sizeof(TiffContext),
1266  .init = tiff_init,
1267  .close = tiff_end,
1268  .decode = decode_frame,
1270  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1271 };