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