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 #if CONFIG_ZLIB
287 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
288  int size)
289 {
290  z_stream zstream = { 0 };
291  int zret;
292 
293  zstream.next_in = (uint8_t *)src;
294  zstream.avail_in = size;
295  zstream.next_out = dst;
296  zstream.avail_out = *len;
297  zret = inflateInit(&zstream);
298  if (zret != Z_OK) {
299  av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
300  return zret;
301  }
302  zret = inflate(&zstream, Z_SYNC_FLUSH);
303  inflateEnd(&zstream);
304  *len = zstream.total_out;
305  return zret == Z_STREAM_END ? Z_OK : zret;
306 }
307 
308 static int tiff_unpack_zlib(TiffContext *s, uint8_t *dst, int stride,
309  const uint8_t *src, int size,
310  int width, int lines)
311 {
312  uint8_t *zbuf;
313  unsigned long outlen;
314  int ret, line;
315  outlen = width * lines;
316  zbuf = av_malloc(outlen);
317  if (!zbuf)
318  return AVERROR(ENOMEM);
319  if (s->fill_order) {
320  if ((ret = deinvert_buffer(s, src, size)) < 0) {
321  av_free(zbuf);
322  return ret;
323  }
324  src = s->deinvert_buf;
325  }
326  ret = tiff_uncompress(zbuf, &outlen, src, size);
327  if (ret != Z_OK) {
329  "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
330  (unsigned long)width * lines, ret);
331  av_free(zbuf);
332  return AVERROR_UNKNOWN;
333  }
334  src = zbuf;
335  for (line = 0; line < lines; line++) {
336  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
337  horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
338  } else {
339  memcpy(dst, src, width);
340  }
341  dst += stride;
342  src += width;
343  }
344  av_free(zbuf);
345  return 0;
346 }
347 #endif
348 
349 
350 static int tiff_unpack_fax(TiffContext *s, uint8_t *dst, int stride,
351  const uint8_t *src, int size, int width, int lines)
352 {
353  int i, ret = 0;
354  int line;
355  uint8_t *src2 = av_malloc((unsigned)size +
357 
358  if (!src2) {
360  "Error allocating temporary buffer\n");
361  return AVERROR(ENOMEM);
362  }
363  if (s->fax_opts & 2) {
364  avpriv_request_sample(s->avctx, "Uncompressed fax mode");
365  av_free(src2);
366  return AVERROR_PATCHWELCOME;
367  }
368  if (!s->fill_order) {
369  memcpy(src2, src, size);
370  } else {
371  for (i = 0; i < size; i++)
372  src2[i] = ff_reverse[src[i]];
373  }
374  memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
375  ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
376  s->compr, s->fax_opts);
377  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
378  for (line = 0; line < lines; line++) {
379  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
380  dst += stride;
381  }
382  av_free(src2);
383  return ret;
384 }
385 
386 static void unpack_yuv(TiffContext *s, AVFrame *p,
387  const uint8_t *src, int lnum)
388 {
389  int i, j, k;
390  int w = (s->width - 1) / s->subsampling[0] + 1;
391  uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
392  uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
393  if (s->width % s->subsampling[0] || s->height % s->subsampling[1]) {
394  for (i = 0; i < w; i++) {
395  for (j = 0; j < s->subsampling[1]; j++)
396  for (k = 0; k < s->subsampling[0]; k++)
397  p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
398  FFMIN(i * s->subsampling[0] + k, s->width-1)] = *src++;
399  *pu++ = *src++;
400  *pv++ = *src++;
401  }
402  }else{
403  for (i = 0; i < w; i++) {
404  for (j = 0; j < s->subsampling[1]; j++)
405  for (k = 0; k < s->subsampling[0]; k++)
406  p->data[0][(lnum + j) * p->linesize[0] +
407  i * s->subsampling[0] + k] = *src++;
408  *pu++ = *src++;
409  *pv++ = *src++;
410  }
411  }
412 }
413 
414 
415 static int tiff_unpack_strip(TiffContext *s, AVFrame *p, uint8_t *dst, int stride,
416  const uint8_t *src, int size, int strip_start, int lines)
417 {
418  PutByteContext pb;
419  int c, line, pixels, code, ret;
420  const uint8_t *ssrc = src;
421  int width = ((s->width * s->bpp) + 7) >> 3;
422  int is_yuv = s->photometric == TIFF_PHOTOMETRIC_YCBCR;
423 
424  if (s->planar)
425  width /= s->bppcount;
426 
427  if (size <= 0)
428  return AVERROR_INVALIDDATA;
429 
430  if (is_yuv) {
431  int bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
432  s->subsampling[0] * s->subsampling[1] + 7) >> 3;
433  av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
434  if (s->yuv_line == NULL) {
435  av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
436  return AVERROR(ENOMEM);
437  }
438  dst = s->yuv_line;
439  stride = 0;
440  width = s->width * s->subsampling[1] + 2*(s->width / s->subsampling[0]);
441  av_assert0(width <= bytes_per_row);
442  av_assert0(s->bpp == 24);
443  }
444 
445  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
446  if (is_yuv) {
447  av_log(s->avctx, AV_LOG_ERROR, "YUV deflate is unsupported");
448  return AVERROR_PATCHWELCOME;
449  }
450 #if CONFIG_ZLIB
451  return tiff_unpack_zlib(s, dst, stride, src, size, width, lines);
452 #else
454  "zlib support not enabled, "
455  "deflate compression not supported\n");
456  return AVERROR(ENOSYS);
457 #endif
458  }
459  if (s->compr == TIFF_LZW) {
460  if (s->fill_order) {
461  if ((ret = deinvert_buffer(s, src, size)) < 0)
462  return ret;
463  ssrc = src = s->deinvert_buf;
464  }
465  if (size > 1 && !src[0] && (src[1]&1)) {
466  av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
467  }
468  if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
469  av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
470  return ret;
471  }
472  for (line = 0; line < lines; line++) {
473  pixels = ff_lzw_decode(s->lzw, dst, width);
474  if (pixels < width) {
475  av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
476  pixels, width);
477  return AVERROR_INVALIDDATA;
478  }
479  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
480  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
481  if (is_yuv) {
482  unpack_yuv(s, p, dst, strip_start + line);
483  line += s->subsampling[1] - 1;
484  }
485  dst += stride;
486  }
487  return 0;
488  }
489  if (s->compr == TIFF_CCITT_RLE ||
490  s->compr == TIFF_G3 ||
491  s->compr == TIFF_G4) {
492  if (is_yuv)
493  return AVERROR_INVALIDDATA;
494 
495  return tiff_unpack_fax(s, dst, stride, src, size, width, lines);
496  }
497 
498  bytestream2_init(&s->gb, src, size);
499  bytestream2_init_writer(&pb, dst, is_yuv ? s->yuv_line_size : (stride * lines));
500 
501  for (line = 0; line < lines; line++) {
502  if (src - ssrc > size) {
503  av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
504  return AVERROR_INVALIDDATA;
505  }
506 
507  if (bytestream2_get_bytes_left(&s->gb) == 0 || bytestream2_get_eof(&pb))
508  break;
509  bytestream2_seek_p(&pb, stride * line, SEEK_SET);
510  switch (s->compr) {
511  case TIFF_RAW:
512  if (ssrc + size - src < width)
513  return AVERROR_INVALIDDATA;
514 
515  if (!s->fill_order) {
517  dst, 1, src, 0, width, 0);
518  } else {
519  int i;
520  for (i = 0; i < width; i++)
521  dst[i] = ff_reverse[src[i]];
522  }
523  src += width;
524  break;
525  case TIFF_PACKBITS:
526  for (pixels = 0; pixels < width;) {
527  if (ssrc + size - src < 2) {
528  av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
529  return AVERROR_INVALIDDATA;
530  }
531  code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;
532  if (code >= 0) {
533  code++;
534  if (pixels + code > width ||
535  ssrc + size - src < code) {
537  "Copy went out of bounds\n");
538  return AVERROR_INVALIDDATA;
539  }
541  dst, 1, src, 0, code, pixels);
542  src += code;
543  pixels += code;
544  } else if (code != -128) { // -127..-1
545  code = (-code) + 1;
546  if (pixels + code > width) {
548  "Run went out of bounds\n");
549  return AVERROR_INVALIDDATA;
550  }
551  c = *src++;
553  dst, 0, NULL, c, code, pixels);
554  pixels += code;
555  }
556  }
557  if (s->fill_order) {
558  int i;
559  for (i = 0; i < width; i++)
560  dst[i] = ff_reverse[dst[i]];
561  }
562  break;
563  }
564  if (is_yuv) {
565  unpack_yuv(s, p, dst, strip_start + line);
566  line += s->subsampling[1] - 1;
567  }
568  dst += stride;
569  }
570  return 0;
571 }
572 
574 {
575  int i, ret;
576  uint32_t *pal;
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 324:
618  break;
619  case 483:
621  break;
622  case 644:
624  break;
625  case 1243:
627  break;
628  case 1324:
630  break;
631  case 1483:
633  break;
634  case 1644:
636  break;
637  default:
639  "This format is not supported (bpp=%d, bppcount=%d)\n",
640  s->bpp, s->bppcount);
641  return AVERROR_INVALIDDATA;
642  }
643  if (s->width != s->avctx->width || s->height != s->avctx->height) {
644  ret = ff_set_dimensions(s->avctx, s->width, s->height);
645  if (ret < 0)
646  return ret;
647  }
648  if ((ret = ff_thread_get_buffer(s->avctx, frame, 0)) < 0)
649  return ret;
650  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
651  if (s->palette_is_set) {
652  memcpy(frame->f->data[1], s->palette, sizeof(s->palette));
653  } else {
654  /* make default grayscale pal */
655  pal = (uint32_t *) frame->f->data[1];
656  for (i = 0; i < 1<<s->bpp; i++)
657  pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
658  }
659  }
660  return 0;
661 }
662 
663 static void set_sar(TiffContext *s, unsigned tag, unsigned num, unsigned den)
664 {
665  int offset = tag == TIFF_YRES ? 2 : 0;
666  s->res[offset++] = num;
667  s->res[offset] = den;
668  if (s->res[0] && s->res[1] && s->res[2] && s->res[3])
670  s->res[2] * (uint64_t)s->res[1], s->res[0] * (uint64_t)s->res[3], INT32_MAX);
671 }
672 
674 {
675  unsigned tag, type, count, off, value = 0, value2 = 0;
676  int i, start;
677  int pos;
678  int ret;
679  double *dp;
680 
681  ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);
682  if (ret < 0) {
683  goto end;
684  }
685 
686  off = bytestream2_tell(&s->gb);
687  if (count == 1) {
688  switch (type) {
689  case TIFF_BYTE:
690  case TIFF_SHORT:
691  case TIFF_LONG:
692  value = ff_tget(&s->gb, type, s->le);
693  break;
694  case TIFF_RATIONAL:
695  value = ff_tget(&s->gb, TIFF_LONG, s->le);
696  value2 = ff_tget(&s->gb, TIFF_LONG, s->le);
697  break;
698  case TIFF_STRING:
699  if (count <= 4) {
700  break;
701  }
702  default:
703  value = UINT_MAX;
704  }
705  }
706 
707  switch (tag) {
708  case TIFF_WIDTH:
709  s->width = value;
710  break;
711  case TIFF_HEIGHT:
712  s->height = value;
713  break;
714  case TIFF_BPP:
715  s->bppcount = count;
716  if (count > 4) {
718  "This format is not supported (bpp=%d, %d components)\n",
719  s->bpp, count);
720  return AVERROR_INVALIDDATA;
721  }
722  if (count == 1)
723  s->bpp = value;
724  else {
725  switch (type) {
726  case TIFF_BYTE:
727  case TIFF_SHORT:
728  case TIFF_LONG:
729  s->bpp = 0;
730  if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
731  return AVERROR_INVALIDDATA;
732  for (i = 0; i < count; i++)
733  s->bpp += ff_tget(&s->gb, type, s->le);
734  break;
735  default:
736  s->bpp = -1;
737  }
738  }
739  break;
741  if (count != 1) {
743  "Samples per pixel requires a single value, many provided\n");
744  return AVERROR_INVALIDDATA;
745  }
746  if (value > 4U) {
748  "Samples per pixel %d is too large\n", value);
749  return AVERROR_INVALIDDATA;
750  }
751  if (s->bppcount == 1)
752  s->bpp *= value;
753  s->bppcount = value;
754  break;
755  case TIFF_COMPR:
756  s->compr = value;
757  s->predictor = 0;
758  switch (s->compr) {
759  case TIFF_RAW:
760  case TIFF_PACKBITS:
761  case TIFF_LZW:
762  case TIFF_CCITT_RLE:
763  break;
764  case TIFF_G3:
765  case TIFF_G4:
766  s->fax_opts = 0;
767  break;
768  case TIFF_DEFLATE:
769  case TIFF_ADOBE_DEFLATE:
770 #if CONFIG_ZLIB
771  break;
772 #else
773  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
774  return AVERROR(ENOSYS);
775 #endif
776  case TIFF_JPEG:
777  case TIFF_NEWJPEG:
778  avpriv_report_missing_feature(s->avctx, "JPEG compression");
779  return AVERROR_PATCHWELCOME;
780  default:
781  av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
782  s->compr);
783  return AVERROR_INVALIDDATA;
784  }
785  break;
786  case TIFF_ROWSPERSTRIP:
787  if (!value || (type == TIFF_LONG && value == UINT_MAX))
788  value = s->height;
789  s->rps = FFMIN(value, s->height);
790  break;
791  case TIFF_STRIP_OFFS:
792  if (count == 1) {
793  s->strippos = 0;
794  s->stripoff = value;
795  } else
796  s->strippos = off;
797  s->strips = count;
798  if (s->strips == 1)
799  s->rps = s->height;
800  s->sot = type;
801  break;
802  case TIFF_STRIP_SIZE:
803  if (count == 1) {
804  s->stripsizesoff = 0;
805  s->stripsize = value;
806  s->strips = 1;
807  } else {
808  s->stripsizesoff = off;
809  }
810  s->strips = count;
811  s->sstype = type;
812  break;
813  case TIFF_XRES:
814  case TIFF_YRES:
815  set_sar(s, tag, value, value2);
816  break;
818  case TIFF_TILE_LENGTH:
819  case TIFF_TILE_OFFSETS:
820  case TIFF_TILE_WIDTH:
821  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
822  return AVERROR_PATCHWELCOME;
823  break;
824  case TIFF_PREDICTOR:
825  s->predictor = value;
826  break;
827  case TIFF_PHOTOMETRIC:
828  switch (value) {
834  s->photometric = value;
835  break;
846  "PhotometricInterpretation 0x%04X",
847  value);
848  return AVERROR_PATCHWELCOME;
849  default:
850  av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "
851  "unknown\n", value);
852  return AVERROR_INVALIDDATA;
853  }
854  break;
855  case TIFF_FILL_ORDER:
856  if (value < 1 || value > 2) {
858  "Unknown FillOrder value %d, trying default one\n", value);
859  value = 1;
860  }
861  s->fill_order = value - 1;
862  break;
863  case TIFF_PAL: {
864  GetByteContext pal_gb[3];
865  off = type_sizes[type];
866  if (count / 3 > 256 ||
867  bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
868  return AVERROR_INVALIDDATA;
869 
870  pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
871  bytestream2_skip(&pal_gb[1], count / 3 * off);
872  bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
873 
874  off = (type_sizes[type] - 1) << 3;
875  for (i = 0; i < count / 3; i++) {
876  uint32_t p = 0xFF000000;
877  p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;
878  p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;
879  p |= ff_tget(&pal_gb[2], type, s->le) >> off;
880  s->palette[i] = p;
881  }
882  s->palette_is_set = 1;
883  break;
884  }
885  case TIFF_PLANAR:
886  s->planar = value == 2;
887  break;
889  if (count != 2) {
890  av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");
891  return AVERROR_INVALIDDATA;
892  }
893  for (i = 0; i < count; i++)
894  s->subsampling[i] = ff_tget(&s->gb, type, s->le);
895  break;
896  case TIFF_T4OPTIONS:
897  if (s->compr == TIFF_G3)
898  s->fax_opts = value;
899  break;
900  case TIFF_T6OPTIONS:
901  if (s->compr == TIFF_G4)
902  s->fax_opts = value;
903  break;
904 #define ADD_METADATA(count, name, sep)\
905  if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
906  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
907  goto end;\
908  }
910  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
911  break;
913  ADD_METADATA(count, "ModelTransformationTag", NULL);
914  break;
915  case TIFF_MODEL_TIEPOINT:
916  ADD_METADATA(count, "ModelTiepointTag", NULL);
917  break;
919  ADD_METADATA(1, "GeoTIFF_Version", NULL);
920  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
921  s->geotag_count = ff_tget_short(&s->gb, s->le);
922  if (s->geotag_count > count / 4 - 1) {
923  s->geotag_count = count / 4 - 1;
924  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
925  }
926  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
927  s->geotag_count = 0;
928  return -1;
929  }
931  if (!s->geotags) {
932  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
933  s->geotag_count = 0;
934  goto end;
935  }
936  for (i = 0; i < s->geotag_count; i++) {
937  s->geotags[i].key = ff_tget_short(&s->gb, s->le);
938  s->geotags[i].type = ff_tget_short(&s->gb, s->le);
939  s->geotags[i].count = ff_tget_short(&s->gb, s->le);
940 
941  if (!s->geotags[i].type)
942  s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
943  else
944  s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
945  }
946  break;
948  if (count >= INT_MAX / sizeof(int64_t))
949  return AVERROR_INVALIDDATA;
950  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
951  return AVERROR_INVALIDDATA;
952  dp = av_malloc_array(count, sizeof(double));
953  if (!dp) {
954  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
955  goto end;
956  }
957  for (i = 0; i < count; i++)
958  dp[i] = ff_tget_double(&s->gb, s->le);
959  for (i = 0; i < s->geotag_count; i++) {
960  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
961  if (s->geotags[i].count == 0
962  || s->geotags[i].offset + s->geotags[i].count > count) {
963  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
964  } else {
965  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
966  if (!ap) {
967  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
968  av_freep(&dp);
969  return AVERROR(ENOMEM);
970  }
971  s->geotags[i].val = ap;
972  }
973  }
974  }
975  av_freep(&dp);
976  break;
978  pos = bytestream2_tell(&s->gb);
979  for (i = 0; i < s->geotag_count; i++) {
980  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
981  if (s->geotags[i].count == 0
982  || s->geotags[i].offset + s->geotags[i].count > count) {
983  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
984  } else {
985  char *ap;
986 
987  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
988  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
989  return AVERROR_INVALIDDATA;
990  ap = av_malloc(s->geotags[i].count);
991  if (!ap) {
992  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
993  return AVERROR(ENOMEM);
994  }
995  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
996  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
997  s->geotags[i].val = ap;
998  }
999  }
1000  }
1001  break;
1002  case TIFF_ARTIST:
1003  ADD_METADATA(count, "artist", NULL);
1004  break;
1005  case TIFF_COPYRIGHT:
1006  ADD_METADATA(count, "copyright", NULL);
1007  break;
1008  case TIFF_DATE:
1009  ADD_METADATA(count, "date", NULL);
1010  break;
1011  case TIFF_DOCUMENT_NAME:
1012  ADD_METADATA(count, "document_name", NULL);
1013  break;
1014  case TIFF_HOST_COMPUTER:
1015  ADD_METADATA(count, "computer", NULL);
1016  break;
1018  ADD_METADATA(count, "description", NULL);
1019  break;
1020  case TIFF_MAKE:
1021  ADD_METADATA(count, "make", NULL);
1022  break;
1023  case TIFF_MODEL:
1024  ADD_METADATA(count, "model", NULL);
1025  break;
1026  case TIFF_PAGE_NAME:
1027  ADD_METADATA(count, "page_name", NULL);
1028  break;
1029  case TIFF_PAGE_NUMBER:
1030  ADD_METADATA(count, "page_number", " / ");
1031  break;
1032  case TIFF_SOFTWARE_NAME:
1033  ADD_METADATA(count, "software", NULL);
1034  break;
1035  default:
1036  if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1038  "Unknown or unsupported tag %d/0X%0X\n",
1039  tag, tag);
1040  return AVERROR_INVALIDDATA;
1041  }
1042  }
1043 end:
1044  bytestream2_seek(&s->gb, start, SEEK_SET);
1045  return 0;
1046 }
1047 
1048 static int decode_frame(AVCodecContext *avctx,
1049  void *data, int *got_frame, AVPacket *avpkt)
1050 {
1051  TiffContext *const s = avctx->priv_data;
1052  AVFrame *const p = data;
1053  ThreadFrame frame = { .f = data };
1054  unsigned off;
1055  int le, ret, plane, planes;
1056  int i, j, entries, stride;
1057  unsigned soff, ssize;
1058  uint8_t *dst;
1059  GetByteContext stripsizes;
1060  GetByteContext stripdata;
1061 
1062  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1063 
1064  // parse image header
1065  if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
1066  av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
1067  return ret;
1068  } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1069  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1070  return AVERROR_INVALIDDATA;
1071  }
1072  s->le = le;
1073  // TIFF_BPP is not a required tag and defaults to 1
1074  s->bppcount = s->bpp = 1;
1076  s->compr = TIFF_RAW;
1077  s->fill_order = 0;
1078  free_geotags(s);
1079 
1080  // Reset these offsets so we can tell if they were set this frame
1081  s->stripsizesoff = s->strippos = 0;
1082  /* parse image file directory */
1083  bytestream2_seek(&s->gb, off, SEEK_SET);
1084  entries = ff_tget_short(&s->gb, le);
1085  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1086  return AVERROR_INVALIDDATA;
1087  for (i = 0; i < entries; i++) {
1088  if ((ret = tiff_decode_tag(s, p)) < 0)
1089  return ret;
1090  }
1091 
1092  for (i = 0; i<s->geotag_count; i++) {
1093  const char *keyname = get_geokey_name(s->geotags[i].key);
1094  if (!keyname) {
1095  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1096  continue;
1097  }
1098  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1099  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1100  continue;
1101  }
1102  ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
1103  if (ret<0) {
1104  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1105  return ret;
1106  }
1107  }
1108 
1109  if (!s->strippos && !s->stripoff) {
1110  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1111  return AVERROR_INVALIDDATA;
1112  }
1113  /* now we have the data and may start decoding */
1114  if ((ret = init_image(s, &frame)) < 0)
1115  return ret;
1116 
1117  if (s->strips == 1 && !s->stripsize) {
1118  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1119  s->stripsize = avpkt->size - s->stripoff;
1120  }
1121 
1122  if (s->stripsizesoff) {
1123  if (s->stripsizesoff >= (unsigned)avpkt->size)
1124  return AVERROR_INVALIDDATA;
1125  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
1126  avpkt->size - s->stripsizesoff);
1127  }
1128  if (s->strippos) {
1129  if (s->strippos >= (unsigned)avpkt->size)
1130  return AVERROR_INVALIDDATA;
1131  bytestream2_init(&stripdata, avpkt->data + s->strippos,
1132  avpkt->size - s->strippos);
1133  }
1134 
1135  if (s->rps <= 0) {
1136  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1137  return AVERROR_INVALIDDATA;
1138  }
1139 
1140  planes = s->planar ? s->bppcount : 1;
1141  for (plane = 0; plane < planes; plane++) {
1142  stride = p->linesize[plane];
1143  dst = p->data[plane];
1144  for (i = 0; i < s->height; i += s->rps) {
1145  if (s->stripsizesoff)
1146  ssize = ff_tget(&stripsizes, s->sstype, le);
1147  else
1148  ssize = s->stripsize;
1149 
1150  if (s->strippos)
1151  soff = ff_tget(&stripdata, s->sot, le);
1152  else
1153  soff = s->stripoff;
1154 
1155  if (soff > avpkt->size || ssize > avpkt->size - soff) {
1156  av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1157  return AVERROR_INVALIDDATA;
1158  }
1159  if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,
1160  FFMIN(s->rps, s->height - i))) < 0) {
1161  if (avctx->err_recognition & AV_EF_EXPLODE)
1162  return ret;
1163  break;
1164  }
1165  dst += s->rps * stride;
1166  }
1167  if (s->predictor == 2) {
1168  if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
1169  av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");
1170  return AVERROR_PATCHWELCOME;
1171  }
1172  dst = p->data[plane];
1173  soff = s->bpp >> 3;
1174  if (s->planar)
1175  soff = FFMAX(soff / s->bppcount, 1);
1176  ssize = s->width * soff;
1177  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1181  for (i = 0; i < s->height; i++) {
1182  for (j = soff; j < ssize; j += 2)
1183  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1184  dst += stride;
1185  }
1186  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1190  for (i = 0; i < s->height; i++) {
1191  for (j = soff; j < ssize; j += 2)
1192  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1193  dst += stride;
1194  }
1195  } else {
1196  for (i = 0; i < s->height; i++) {
1197  for (j = soff; j < ssize; j++)
1198  dst[j] += dst[j - soff];
1199  dst += stride;
1200  }
1201  }
1202  }
1203 
1205  dst = p->data[plane];
1206  for (i = 0; i < s->height; i++) {
1207  for (j = 0; j < p->linesize[plane]; j++)
1208  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1209  dst += stride;
1210  }
1211  }
1212  }
1213 
1214  if (s->planar && s->bppcount > 2) {
1215  FFSWAP(uint8_t*, p->data[0], p->data[2]);
1216  FFSWAP(int, p->linesize[0], p->linesize[2]);
1217  FFSWAP(uint8_t*, p->data[0], p->data[1]);
1218  FFSWAP(int, p->linesize[0], p->linesize[1]);
1219  }
1220 
1221  *got_frame = 1;
1222 
1223  return avpkt->size;
1224 }
1225 
1227 {
1228  TiffContext *s = avctx->priv_data;
1229 
1230  s->width = 0;
1231  s->height = 0;
1232  s->subsampling[0] =
1233  s->subsampling[1] = 1;
1234  s->avctx = avctx;
1235  ff_lzw_decode_open(&s->lzw);
1237 
1238  return 0;
1239 }
1240 
1241 static av_cold int tiff_end(AVCodecContext *avctx)
1242 {
1243  TiffContext *const s = avctx->priv_data;
1244 
1245  free_geotags(s);
1246 
1247  ff_lzw_decode_close(&s->lzw);
1248  av_freep(&s->deinvert_buf);
1249  return 0;
1250 }
1251 
1253  .name = "tiff",
1254  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1255  .type = AVMEDIA_TYPE_VIDEO,
1256  .id = AV_CODEC_ID_TIFF,
1257  .priv_data_size = sizeof(TiffContext),
1258  .init = tiff_init,
1259  .close = tiff_end,
1260  .decode = decode_frame,
1262  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1263 };