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 
514  width = (s->width - 1) / s->subsampling[0] + 1;
515  width = width * s->subsampling[0] * s->subsampling[1] + 2*width;
516  av_assert0(width <= bytes_per_row);
517  av_assert0(s->bpp == 24);
518  }
519 
520  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
521 #if CONFIG_ZLIB
522  return tiff_unpack_zlib(s, p, dst, stride, src, size, width, lines,
523  strip_start, is_yuv);
524 #else
526  "zlib support not enabled, "
527  "deflate compression not supported\n");
528  return AVERROR(ENOSYS);
529 #endif
530  }
531  if (s->compr == TIFF_LZMA) {
532 #if CONFIG_LZMA
533  return tiff_unpack_lzma(s, p, dst, stride, src, size, width, lines,
534  strip_start, is_yuv);
535 #else
537  "LZMA support not enabled\n");
538  return AVERROR(ENOSYS);
539 #endif
540  }
541  if (s->compr == TIFF_LZW) {
542  if (s->fill_order) {
543  if ((ret = deinvert_buffer(s, src, size)) < 0)
544  return ret;
545  ssrc = src = s->deinvert_buf;
546  }
547  if (size > 1 && !src[0] && (src[1]&1)) {
548  av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
549  }
550  if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
551  av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
552  return ret;
553  }
554  for (line = 0; line < lines; line++) {
555  pixels = ff_lzw_decode(s->lzw, dst, width);
556  if (pixels < width) {
557  av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
558  pixels, width);
559  return AVERROR_INVALIDDATA;
560  }
561  if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
562  horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
563  if (is_yuv) {
564  unpack_yuv(s, p, dst, strip_start + line);
565  line += s->subsampling[1] - 1;
566  }
567  dst += stride;
568  }
569  return 0;
570  }
571  if (s->compr == TIFF_CCITT_RLE ||
572  s->compr == TIFF_G3 ||
573  s->compr == TIFF_G4) {
574  if (is_yuv)
575  return AVERROR_INVALIDDATA;
576 
577  return tiff_unpack_fax(s, dst, stride, src, size, width, lines);
578  }
579 
580  bytestream2_init(&s->gb, src, size);
581  bytestream2_init_writer(&pb, dst, is_yuv ? s->yuv_line_size : (stride * lines));
582 
583  for (line = 0; line < lines; line++) {
584  if (src - ssrc > size) {
585  av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
586  return AVERROR_INVALIDDATA;
587  }
588 
589  if (bytestream2_get_bytes_left(&s->gb) == 0 || bytestream2_get_eof(&pb))
590  break;
591  bytestream2_seek_p(&pb, stride * line, SEEK_SET);
592  switch (s->compr) {
593  case TIFF_RAW:
594  if (ssrc + size - src < width)
595  return AVERROR_INVALIDDATA;
596 
597  if (!s->fill_order) {
599  dst, 1, src, 0, width, 0);
600  } else {
601  int i;
602  for (i = 0; i < width; i++)
603  dst[i] = ff_reverse[src[i]];
604  }
605  src += width;
606  break;
607  case TIFF_PACKBITS:
608  for (pixels = 0; pixels < width;) {
609  if (ssrc + size - src < 2) {
610  av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
611  return AVERROR_INVALIDDATA;
612  }
613  code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;
614  if (code >= 0) {
615  code++;
616  if (pixels + code > width ||
617  ssrc + size - src < code) {
619  "Copy went out of bounds\n");
620  return AVERROR_INVALIDDATA;
621  }
623  dst, 1, src, 0, code, pixels);
624  src += code;
625  pixels += code;
626  } else if (code != -128) { // -127..-1
627  code = (-code) + 1;
628  if (pixels + code > width) {
630  "Run went out of bounds\n");
631  return AVERROR_INVALIDDATA;
632  }
633  c = *src++;
635  dst, 0, NULL, c, code, pixels);
636  pixels += code;
637  }
638  }
639  if (s->fill_order) {
640  int i;
641  for (i = 0; i < width; i++)
642  dst[i] = ff_reverse[dst[i]];
643  }
644  break;
645  }
646  if (is_yuv) {
647  unpack_yuv(s, p, dst, strip_start + line);
648  line += s->subsampling[1] - 1;
649  }
650  dst += stride;
651  }
652  return 0;
653 }
654 
656 {
657  int ret;
658  int create_gray_palette = 0;
659 
660  switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
661  case 11:
662  if (!s->palette_is_set) {
664  break;
665  }
666  case 21:
667  case 41:
669  if (!s->palette_is_set) {
670  create_gray_palette = 1;
671  }
672  break;
673  case 81:
675  break;
676  case 243:
678  if (s->subsampling[0] == 1 && s->subsampling[1] == 1) {
680  } else if (s->subsampling[0] == 2 && s->subsampling[1] == 1) {
682  } else if (s->subsampling[0] == 4 && s->subsampling[1] == 1) {
684  } else if (s->subsampling[0] == 1 && s->subsampling[1] == 2) {
686  } else if (s->subsampling[0] == 2 && s->subsampling[1] == 2) {
688  } else if (s->subsampling[0] == 4 && s->subsampling[1] == 4) {
690  } else {
691  av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr subsampling\n");
692  return AVERROR_PATCHWELCOME;
693  }
694  } else
696  break;
697  case 161:
699  break;
700  case 162:
702  break;
703  case 322:
705  break;
706  case 324:
708  break;
709  case 483:
711  break;
712  case 644:
714  break;
715  case 1243:
717  break;
718  case 1324:
720  break;
721  case 1483:
723  break;
724  case 1644:
726  break;
727  default:
729  "This format is not supported (bpp=%d, bppcount=%d)\n",
730  s->bpp, s->bppcount);
731  return AVERROR_INVALIDDATA;
732  }
733 
736  if((desc->flags & AV_PIX_FMT_FLAG_RGB) ||
737  !(desc->flags & AV_PIX_FMT_FLAG_PLANAR) ||
738  desc->nb_components < 3) {
739  av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr variant\n");
740  return AVERROR_INVALIDDATA;
741  }
742  }
743 
744  if (s->width != s->avctx->width || s->height != s->avctx->height) {
745  ret = ff_set_dimensions(s->avctx, s->width, s->height);
746  if (ret < 0)
747  return ret;
748  }
749  if ((ret = ff_thread_get_buffer(s->avctx, frame, 0)) < 0)
750  return ret;
751  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
752  if (!create_gray_palette)
753  memcpy(frame->f->data[1], s->palette, sizeof(s->palette));
754  else {
755  /* make default grayscale pal */
756  int i;
757  uint32_t *pal = (uint32_t *)frame->f->data[1];
758  for (i = 0; i < 1<<s->bpp; i++)
759  pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
760  }
761  }
762  return 0;
763 }
764 
765 static void set_sar(TiffContext *s, unsigned tag, unsigned num, unsigned den)
766 {
767  int offset = tag == TIFF_YRES ? 2 : 0;
768  s->res[offset++] = num;
769  s->res[offset] = den;
770  if (s->res[0] && s->res[1] && s->res[2] && s->res[3])
772  s->res[2] * (uint64_t)s->res[1], s->res[0] * (uint64_t)s->res[3], INT32_MAX);
773 }
774 
776 {
777  unsigned tag, type, count, off, value = 0, value2 = 0;
778  int i, start;
779  int pos;
780  int ret;
781  double *dp;
782 
783  ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);
784  if (ret < 0) {
785  goto end;
786  }
787 
788  off = bytestream2_tell(&s->gb);
789  if (count == 1) {
790  switch (type) {
791  case TIFF_BYTE:
792  case TIFF_SHORT:
793  case TIFF_LONG:
794  value = ff_tget(&s->gb, type, s->le);
795  break;
796  case TIFF_RATIONAL:
797  value = ff_tget(&s->gb, TIFF_LONG, s->le);
798  value2 = ff_tget(&s->gb, TIFF_LONG, s->le);
799  break;
800  case TIFF_STRING:
801  if (count <= 4) {
802  break;
803  }
804  default:
805  value = UINT_MAX;
806  }
807  }
808 
809  switch (tag) {
810  case TIFF_WIDTH:
811  s->width = value;
812  break;
813  case TIFF_HEIGHT:
814  s->height = value;
815  break;
816  case TIFF_BPP:
817  if (count > 4U) {
819  "This format is not supported (bpp=%d, %d components)\n",
820  value, count);
821  return AVERROR_INVALIDDATA;
822  }
823  s->bppcount = count;
824  if (count == 1)
825  s->bpp = value;
826  else {
827  switch (type) {
828  case TIFF_BYTE:
829  case TIFF_SHORT:
830  case TIFF_LONG:
831  s->bpp = 0;
832  if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
833  return AVERROR_INVALIDDATA;
834  for (i = 0; i < count; i++)
835  s->bpp += ff_tget(&s->gb, type, s->le);
836  break;
837  default:
838  s->bpp = -1;
839  }
840  }
841  if (s->bpp > 64U) {
843  "This format is not supported (bpp=%d, %d components)\n",
844  s->bpp, count);
845  s->bpp = 0;
846  return AVERROR_INVALIDDATA;
847  }
848  break;
850  if (count != 1) {
852  "Samples per pixel requires a single value, many provided\n");
853  return AVERROR_INVALIDDATA;
854  }
855  if (value > 4U) {
857  "Samples per pixel %d is too large\n", value);
858  return AVERROR_INVALIDDATA;
859  }
860  if (s->bppcount == 1)
861  s->bpp *= value;
862  s->bppcount = value;
863  break;
864  case TIFF_COMPR:
865  s->compr = value;
866  s->predictor = 0;
867  switch (s->compr) {
868  case TIFF_RAW:
869  case TIFF_PACKBITS:
870  case TIFF_LZW:
871  case TIFF_CCITT_RLE:
872  break;
873  case TIFF_G3:
874  case TIFF_G4:
875  s->fax_opts = 0;
876  break;
877  case TIFF_DEFLATE:
878  case TIFF_ADOBE_DEFLATE:
879 #if CONFIG_ZLIB
880  break;
881 #else
882  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
883  return AVERROR(ENOSYS);
884 #endif
885  case TIFF_JPEG:
886  case TIFF_NEWJPEG:
887  avpriv_report_missing_feature(s->avctx, "JPEG compression");
888  return AVERROR_PATCHWELCOME;
889  case TIFF_LZMA:
890 #if CONFIG_LZMA
891  break;
892 #else
893  av_log(s->avctx, AV_LOG_ERROR, "LZMA not compiled in\n");
894  return AVERROR(ENOSYS);
895 #endif
896  default:
897  av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
898  s->compr);
899  return AVERROR_INVALIDDATA;
900  }
901  break;
902  case TIFF_ROWSPERSTRIP:
903  if (!value || (type == TIFF_LONG && value == UINT_MAX))
904  value = s->height;
905  s->rps = FFMIN(value, s->height);
906  break;
907  case TIFF_STRIP_OFFS:
908  if (count == 1) {
909  s->strippos = 0;
910  s->stripoff = value;
911  } else
912  s->strippos = off;
913  s->strips = count;
914  if (s->strips == 1)
915  s->rps = s->height;
916  s->sot = type;
917  break;
918  case TIFF_STRIP_SIZE:
919  if (count == 1) {
920  s->stripsizesoff = 0;
921  s->stripsize = value;
922  s->strips = 1;
923  } else {
924  s->stripsizesoff = off;
925  }
926  s->strips = count;
927  s->sstype = type;
928  break;
929  case TIFF_XRES:
930  case TIFF_YRES:
931  set_sar(s, tag, value, value2);
932  break;
934  case TIFF_TILE_LENGTH:
935  case TIFF_TILE_OFFSETS:
936  case TIFF_TILE_WIDTH:
937  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
938  return AVERROR_PATCHWELCOME;
939  break;
940  case TIFF_PREDICTOR:
941  s->predictor = value;
942  break;
943  case TIFF_PHOTOMETRIC:
944  switch (value) {
950  s->photometric = value;
951  break;
962  "PhotometricInterpretation 0x%04X",
963  value);
964  return AVERROR_PATCHWELCOME;
965  default:
966  av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "
967  "unknown\n", value);
968  return AVERROR_INVALIDDATA;
969  }
970  break;
971  case TIFF_FILL_ORDER:
972  if (value < 1 || value > 2) {
974  "Unknown FillOrder value %d, trying default one\n", value);
975  value = 1;
976  }
977  s->fill_order = value - 1;
978  break;
979  case TIFF_PAL: {
980  GetByteContext pal_gb[3];
981  off = type_sizes[type];
982  if (count / 3 > 256 ||
983  bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
984  return AVERROR_INVALIDDATA;
985 
986  pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
987  bytestream2_skip(&pal_gb[1], count / 3 * off);
988  bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
989 
990  off = (type_sizes[type] - 1) << 3;
991  for (i = 0; i < count / 3; i++) {
992  uint32_t p = 0xFF000000;
993  p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;
994  p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;
995  p |= ff_tget(&pal_gb[2], type, s->le) >> off;
996  s->palette[i] = p;
997  }
998  s->palette_is_set = 1;
999  break;
1000  }
1001  case TIFF_PLANAR:
1002  s->planar = value == 2;
1003  break;
1005  if (count != 2) {
1006  av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");
1007  return AVERROR_INVALIDDATA;
1008  }
1009  for (i = 0; i < count; i++)
1010  s->subsampling[i] = ff_tget(&s->gb, type, s->le);
1011  break;
1012  case TIFF_T4OPTIONS:
1013  if (s->compr == TIFF_G3)
1014  s->fax_opts = value;
1015  break;
1016  case TIFF_T6OPTIONS:
1017  if (s->compr == TIFF_G4)
1018  s->fax_opts = value;
1019  break;
1020 #define ADD_METADATA(count, name, sep)\
1021  if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
1022  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
1023  goto end;\
1024  }
1026  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
1027  break;
1029  ADD_METADATA(count, "ModelTransformationTag", NULL);
1030  break;
1031  case TIFF_MODEL_TIEPOINT:
1032  ADD_METADATA(count, "ModelTiepointTag", NULL);
1033  break;
1035  ADD_METADATA(1, "GeoTIFF_Version", NULL);
1036  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
1037  s->geotag_count = ff_tget_short(&s->gb, s->le);
1038  if (s->geotag_count > count / 4 - 1) {
1039  s->geotag_count = count / 4 - 1;
1040  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
1041  }
1042  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
1043  s->geotag_count = 0;
1044  return -1;
1045  }
1046  s->geotags = av_mallocz_array(s->geotag_count, sizeof(TiffGeoTag));
1047  if (!s->geotags) {
1048  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1049  s->geotag_count = 0;
1050  goto end;
1051  }
1052  for (i = 0; i < s->geotag_count; i++) {
1053  s->geotags[i].key = ff_tget_short(&s->gb, s->le);
1054  s->geotags[i].type = ff_tget_short(&s->gb, s->le);
1055  s->geotags[i].count = ff_tget_short(&s->gb, s->le);
1056 
1057  if (!s->geotags[i].type)
1058  s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
1059  else
1060  s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
1061  }
1062  break;
1064  if (count >= INT_MAX / sizeof(int64_t))
1065  return AVERROR_INVALIDDATA;
1066  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
1067  return AVERROR_INVALIDDATA;
1068  dp = av_malloc_array(count, sizeof(double));
1069  if (!dp) {
1070  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1071  goto end;
1072  }
1073  for (i = 0; i < count; i++)
1074  dp[i] = ff_tget_double(&s->gb, s->le);
1075  for (i = 0; i < s->geotag_count; i++) {
1076  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
1077  if (s->geotags[i].count == 0
1078  || s->geotags[i].offset + s->geotags[i].count > count) {
1079  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1080  } else {
1081  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
1082  if (!ap) {
1083  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1084  av_freep(&dp);
1085  return AVERROR(ENOMEM);
1086  }
1087  s->geotags[i].val = ap;
1088  }
1089  }
1090  }
1091  av_freep(&dp);
1092  break;
1093  case TIFF_GEO_ASCII_PARAMS:
1094  pos = bytestream2_tell(&s->gb);
1095  for (i = 0; i < s->geotag_count; i++) {
1096  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
1097  if (s->geotags[i].count == 0
1098  || s->geotags[i].offset + s->geotags[i].count > count) {
1099  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1100  } else {
1101  char *ap;
1102 
1103  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
1104  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
1105  return AVERROR_INVALIDDATA;
1106  ap = av_malloc(s->geotags[i].count);
1107  if (!ap) {
1108  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1109  return AVERROR(ENOMEM);
1110  }
1111  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
1112  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
1113  s->geotags[i].val = ap;
1114  }
1115  }
1116  }
1117  break;
1118  case TIFF_ARTIST:
1119  ADD_METADATA(count, "artist", NULL);
1120  break;
1121  case TIFF_COPYRIGHT:
1122  ADD_METADATA(count, "copyright", NULL);
1123  break;
1124  case TIFF_DATE:
1125  ADD_METADATA(count, "date", NULL);
1126  break;
1127  case TIFF_DOCUMENT_NAME:
1128  ADD_METADATA(count, "document_name", NULL);
1129  break;
1130  case TIFF_HOST_COMPUTER:
1131  ADD_METADATA(count, "computer", NULL);
1132  break;
1134  ADD_METADATA(count, "description", NULL);
1135  break;
1136  case TIFF_MAKE:
1137  ADD_METADATA(count, "make", NULL);
1138  break;
1139  case TIFF_MODEL:
1140  ADD_METADATA(count, "model", NULL);
1141  break;
1142  case TIFF_PAGE_NAME:
1143  ADD_METADATA(count, "page_name", NULL);
1144  break;
1145  case TIFF_PAGE_NUMBER:
1146  ADD_METADATA(count, "page_number", " / ");
1147  break;
1148  case TIFF_SOFTWARE_NAME:
1149  ADD_METADATA(count, "software", NULL);
1150  break;
1151  default:
1152  if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1154  "Unknown or unsupported tag %d/0X%0X\n",
1155  tag, tag);
1156  return AVERROR_INVALIDDATA;
1157  }
1158  }
1159 end:
1160  bytestream2_seek(&s->gb, start, SEEK_SET);
1161  return 0;
1162 }
1163 
1164 static int decode_frame(AVCodecContext *avctx,
1165  void *data, int *got_frame, AVPacket *avpkt)
1166 {
1167  TiffContext *const s = avctx->priv_data;
1168  AVFrame *const p = data;
1169  ThreadFrame frame = { .f = data };
1170  unsigned off;
1171  int le, ret, plane, planes;
1172  int i, j, entries, stride;
1173  unsigned soff, ssize;
1174  uint8_t *dst;
1175  GetByteContext stripsizes;
1176  GetByteContext stripdata;
1177 
1178  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1179 
1180  // parse image header
1181  if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
1182  av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
1183  return ret;
1184  } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1185  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1186  return AVERROR_INVALIDDATA;
1187  }
1188  s->le = le;
1189  // TIFF_BPP is not a required tag and defaults to 1
1190  s->bppcount = s->bpp = 1;
1192  s->compr = TIFF_RAW;
1193  s->fill_order = 0;
1194  free_geotags(s);
1195 
1196  // Reset these offsets so we can tell if they were set this frame
1197  s->stripsizesoff = s->strippos = 0;
1198  /* parse image file directory */
1199  bytestream2_seek(&s->gb, off, SEEK_SET);
1200  entries = ff_tget_short(&s->gb, le);
1201  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1202  return AVERROR_INVALIDDATA;
1203  for (i = 0; i < entries; i++) {
1204  if ((ret = tiff_decode_tag(s, p)) < 0)
1205  return ret;
1206  }
1207 
1208  for (i = 0; i<s->geotag_count; i++) {
1209  const char *keyname = get_geokey_name(s->geotags[i].key);
1210  if (!keyname) {
1211  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1212  continue;
1213  }
1214  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1215  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1216  continue;
1217  }
1218  ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
1219  if (ret<0) {
1220  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1221  return ret;
1222  }
1223  }
1224 
1225  if (!s->strippos && !s->stripoff) {
1226  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1227  return AVERROR_INVALIDDATA;
1228  }
1229  /* now we have the data and may start decoding */
1230  if ((ret = init_image(s, &frame)) < 0)
1231  return ret;
1232 
1233  if (s->strips == 1 && !s->stripsize) {
1234  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1235  s->stripsize = avpkt->size - s->stripoff;
1236  }
1237 
1238  if (s->stripsizesoff) {
1239  if (s->stripsizesoff >= (unsigned)avpkt->size)
1240  return AVERROR_INVALIDDATA;
1241  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
1242  avpkt->size - s->stripsizesoff);
1243  }
1244  if (s->strippos) {
1245  if (s->strippos >= (unsigned)avpkt->size)
1246  return AVERROR_INVALIDDATA;
1247  bytestream2_init(&stripdata, avpkt->data + s->strippos,
1248  avpkt->size - s->strippos);
1249  }
1250 
1251  if (s->rps <= 0) {
1252  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1253  return AVERROR_INVALIDDATA;
1254  }
1255 
1256  planes = s->planar ? s->bppcount : 1;
1257  for (plane = 0; plane < planes; plane++) {
1258  stride = p->linesize[plane];
1259  dst = p->data[plane];
1260  for (i = 0; i < s->height; i += s->rps) {
1261  if (s->stripsizesoff)
1262  ssize = ff_tget(&stripsizes, s->sstype, le);
1263  else
1264  ssize = s->stripsize;
1265 
1266  if (s->strippos)
1267  soff = ff_tget(&stripdata, s->sot, le);
1268  else
1269  soff = s->stripoff;
1270 
1271  if (soff > avpkt->size || ssize > avpkt->size - soff) {
1272  av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1273  return AVERROR_INVALIDDATA;
1274  }
1275  if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,
1276  FFMIN(s->rps, s->height - i))) < 0) {
1277  if (avctx->err_recognition & AV_EF_EXPLODE)
1278  return ret;
1279  break;
1280  }
1281  dst += s->rps * stride;
1282  }
1283  if (s->predictor == 2) {
1284  if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
1285  av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");
1286  return AVERROR_PATCHWELCOME;
1287  }
1288  dst = p->data[plane];
1289  soff = s->bpp >> 3;
1290  if (s->planar)
1291  soff = FFMAX(soff / s->bppcount, 1);
1292  ssize = s->width * soff;
1293  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1297  for (i = 0; i < s->height; i++) {
1298  for (j = soff; j < ssize; j += 2)
1299  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1300  dst += stride;
1301  }
1302  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1306  for (i = 0; i < s->height; i++) {
1307  for (j = soff; j < ssize; j += 2)
1308  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1309  dst += stride;
1310  }
1311  } else {
1312  for (i = 0; i < s->height; i++) {
1313  for (j = soff; j < ssize; j++)
1314  dst[j] += dst[j - soff];
1315  dst += stride;
1316  }
1317  }
1318  }
1319 
1321  dst = p->data[plane];
1322  for (i = 0; i < s->height; i++) {
1323  for (j = 0; j < p->linesize[plane]; j++)
1324  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1325  dst += stride;
1326  }
1327  }
1328  }
1329 
1330  if (s->planar && s->bppcount > 2) {
1331  FFSWAP(uint8_t*, p->data[0], p->data[2]);
1332  FFSWAP(int, p->linesize[0], p->linesize[2]);
1333  FFSWAP(uint8_t*, p->data[0], p->data[1]);
1334  FFSWAP(int, p->linesize[0], p->linesize[1]);
1335  }
1336 
1337  *got_frame = 1;
1338 
1339  return avpkt->size;
1340 }
1341 
1343 {
1344  TiffContext *s = avctx->priv_data;
1345 
1346  s->width = 0;
1347  s->height = 0;
1348  s->subsampling[0] =
1349  s->subsampling[1] = 1;
1350  s->avctx = avctx;
1351  ff_lzw_decode_open(&s->lzw);
1353 
1354  return 0;
1355 }
1356 
1357 static av_cold int tiff_end(AVCodecContext *avctx)
1358 {
1359  TiffContext *const s = avctx->priv_data;
1360 
1361  free_geotags(s);
1362 
1363  ff_lzw_decode_close(&s->lzw);
1364  av_freep(&s->deinvert_buf);
1365  return 0;
1366 }
1367 
1369  .name = "tiff",
1370  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1371  .type = AVMEDIA_TYPE_VIDEO,
1372  .id = AV_CODEC_ID_TIFF,
1373  .priv_data_size = sizeof(TiffContext),
1374  .init = tiff_init,
1375  .close = tiff_end,
1376  .decode = decode_frame,
1378  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1379 };