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  int create_gray_palette = 0;
657 
658  switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
659  case 11:
660  if (!s->palette_is_set) {
662  break;
663  }
664  case 21:
665  case 41:
667  if (!s->palette_is_set) {
668  create_gray_palette = 1;
669  }
670  break;
671  case 81:
673  break;
674  case 243:
676  if (s->subsampling[0] == 1 && s->subsampling[1] == 1) {
678  } else if (s->subsampling[0] == 2 && s->subsampling[1] == 1) {
680  } else if (s->subsampling[0] == 4 && s->subsampling[1] == 1) {
682  } else if (s->subsampling[0] == 1 && s->subsampling[1] == 2) {
684  } else if (s->subsampling[0] == 2 && s->subsampling[1] == 2) {
686  } else if (s->subsampling[0] == 4 && s->subsampling[1] == 4) {
688  } else {
689  av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr subsampling\n");
690  return AVERROR_PATCHWELCOME;
691  }
692  } else
694  break;
695  case 161:
697  break;
698  case 162:
700  break;
701  case 322:
703  break;
704  case 324:
706  break;
707  case 483:
709  break;
710  case 644:
712  break;
713  case 1243:
715  break;
716  case 1324:
718  break;
719  case 1483:
721  break;
722  case 1644:
724  break;
725  default:
727  "This format is not supported (bpp=%d, bppcount=%d)\n",
728  s->bpp, s->bppcount);
729  return AVERROR_INVALIDDATA;
730  }
731 
734  if((desc->flags & AV_PIX_FMT_FLAG_RGB) ||
735  !(desc->flags & AV_PIX_FMT_FLAG_PLANAR) ||
736  desc->nb_components < 3) {
737  av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr variant\n");
738  return AVERROR_INVALIDDATA;
739  }
740  }
741 
742  if (s->width != s->avctx->width || s->height != s->avctx->height) {
743  ret = ff_set_dimensions(s->avctx, s->width, s->height);
744  if (ret < 0)
745  return ret;
746  }
747  if ((ret = ff_thread_get_buffer(s->avctx, frame, 0)) < 0)
748  return ret;
749  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
750  if (!create_gray_palette)
751  memcpy(frame->f->data[1], s->palette, sizeof(s->palette));
752  else {
753  /* make default grayscale pal */
754  int i;
755  uint32_t *pal = (uint32_t *)frame->f->data[1];
756  for (i = 0; i < 1<<s->bpp; i++)
757  pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
758  }
759  }
760  return 0;
761 }
762 
763 static void set_sar(TiffContext *s, unsigned tag, unsigned num, unsigned den)
764 {
765  int offset = tag == TIFF_YRES ? 2 : 0;
766  s->res[offset++] = num;
767  s->res[offset] = den;
768  if (s->res[0] && s->res[1] && s->res[2] && s->res[3])
770  s->res[2] * (uint64_t)s->res[1], s->res[0] * (uint64_t)s->res[3], INT32_MAX);
771 }
772 
774 {
775  unsigned tag, type, count, off, value = 0, value2 = 0;
776  int i, start;
777  int pos;
778  int ret;
779  double *dp;
780 
781  ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);
782  if (ret < 0) {
783  goto end;
784  }
785 
786  off = bytestream2_tell(&s->gb);
787  if (count == 1) {
788  switch (type) {
789  case TIFF_BYTE:
790  case TIFF_SHORT:
791  case TIFF_LONG:
792  value = ff_tget(&s->gb, type, s->le);
793  break;
794  case TIFF_RATIONAL:
795  value = ff_tget(&s->gb, TIFF_LONG, s->le);
796  value2 = ff_tget(&s->gb, TIFF_LONG, s->le);
797  break;
798  case TIFF_STRING:
799  if (count <= 4) {
800  break;
801  }
802  default:
803  value = UINT_MAX;
804  }
805  }
806 
807  switch (tag) {
808  case TIFF_WIDTH:
809  s->width = value;
810  break;
811  case TIFF_HEIGHT:
812  s->height = value;
813  break;
814  case TIFF_BPP:
815  s->bppcount = count;
816  if (count > 4) {
818  "This format is not supported (bpp=%d, %d components)\n",
819  s->bpp, count);
820  return AVERROR_INVALIDDATA;
821  }
822  if (count == 1)
823  s->bpp = value;
824  else {
825  switch (type) {
826  case TIFF_BYTE:
827  case TIFF_SHORT:
828  case TIFF_LONG:
829  s->bpp = 0;
830  if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
831  return AVERROR_INVALIDDATA;
832  for (i = 0; i < count; i++)
833  s->bpp += ff_tget(&s->gb, type, s->le);
834  break;
835  default:
836  s->bpp = -1;
837  }
838  }
839  break;
841  if (count != 1) {
843  "Samples per pixel requires a single value, many provided\n");
844  return AVERROR_INVALIDDATA;
845  }
846  if (value > 4U) {
848  "Samples per pixel %d is too large\n", value);
849  return AVERROR_INVALIDDATA;
850  }
851  if (s->bppcount == 1)
852  s->bpp *= value;
853  s->bppcount = value;
854  break;
855  case TIFF_COMPR:
856  s->compr = value;
857  s->predictor = 0;
858  switch (s->compr) {
859  case TIFF_RAW:
860  case TIFF_PACKBITS:
861  case TIFF_LZW:
862  case TIFF_CCITT_RLE:
863  break;
864  case TIFF_G3:
865  case TIFF_G4:
866  s->fax_opts = 0;
867  break;
868  case TIFF_DEFLATE:
869  case TIFF_ADOBE_DEFLATE:
870 #if CONFIG_ZLIB
871  break;
872 #else
873  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
874  return AVERROR(ENOSYS);
875 #endif
876  case TIFF_JPEG:
877  case TIFF_NEWJPEG:
878  avpriv_report_missing_feature(s->avctx, "JPEG compression");
879  return AVERROR_PATCHWELCOME;
880  case TIFF_LZMA:
881 #if CONFIG_LZMA
882  break;
883 #else
884  av_log(s->avctx, AV_LOG_ERROR, "LZMA not compiled in\n");
885  return AVERROR(ENOSYS);
886 #endif
887  default:
888  av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
889  s->compr);
890  return AVERROR_INVALIDDATA;
891  }
892  break;
893  case TIFF_ROWSPERSTRIP:
894  if (!value || (type == TIFF_LONG && value == UINT_MAX))
895  value = s->height;
896  s->rps = FFMIN(value, s->height);
897  break;
898  case TIFF_STRIP_OFFS:
899  if (count == 1) {
900  s->strippos = 0;
901  s->stripoff = value;
902  } else
903  s->strippos = off;
904  s->strips = count;
905  if (s->strips == 1)
906  s->rps = s->height;
907  s->sot = type;
908  break;
909  case TIFF_STRIP_SIZE:
910  if (count == 1) {
911  s->stripsizesoff = 0;
912  s->stripsize = value;
913  s->strips = 1;
914  } else {
915  s->stripsizesoff = off;
916  }
917  s->strips = count;
918  s->sstype = type;
919  break;
920  case TIFF_XRES:
921  case TIFF_YRES:
922  set_sar(s, tag, value, value2);
923  break;
925  case TIFF_TILE_LENGTH:
926  case TIFF_TILE_OFFSETS:
927  case TIFF_TILE_WIDTH:
928  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
929  return AVERROR_PATCHWELCOME;
930  break;
931  case TIFF_PREDICTOR:
932  s->predictor = value;
933  break;
934  case TIFF_PHOTOMETRIC:
935  switch (value) {
941  s->photometric = value;
942  break;
953  "PhotometricInterpretation 0x%04X",
954  value);
955  return AVERROR_PATCHWELCOME;
956  default:
957  av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "
958  "unknown\n", value);
959  return AVERROR_INVALIDDATA;
960  }
961  break;
962  case TIFF_FILL_ORDER:
963  if (value < 1 || value > 2) {
965  "Unknown FillOrder value %d, trying default one\n", value);
966  value = 1;
967  }
968  s->fill_order = value - 1;
969  break;
970  case TIFF_PAL: {
971  GetByteContext pal_gb[3];
972  off = type_sizes[type];
973  if (count / 3 > 256 ||
974  bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
975  return AVERROR_INVALIDDATA;
976 
977  pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
978  bytestream2_skip(&pal_gb[1], count / 3 * off);
979  bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
980 
981  off = (type_sizes[type] - 1) << 3;
982  for (i = 0; i < count / 3; i++) {
983  uint32_t p = 0xFF000000;
984  p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;
985  p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;
986  p |= ff_tget(&pal_gb[2], type, s->le) >> off;
987  s->palette[i] = p;
988  }
989  s->palette_is_set = 1;
990  break;
991  }
992  case TIFF_PLANAR:
993  s->planar = value == 2;
994  break;
996  if (count != 2) {
997  av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");
998  return AVERROR_INVALIDDATA;
999  }
1000  for (i = 0; i < count; i++)
1001  s->subsampling[i] = ff_tget(&s->gb, type, s->le);
1002  break;
1003  case TIFF_T4OPTIONS:
1004  if (s->compr == TIFF_G3)
1005  s->fax_opts = value;
1006  break;
1007  case TIFF_T6OPTIONS:
1008  if (s->compr == TIFF_G4)
1009  s->fax_opts = value;
1010  break;
1011 #define ADD_METADATA(count, name, sep)\
1012  if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
1013  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
1014  goto end;\
1015  }
1017  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
1018  break;
1020  ADD_METADATA(count, "ModelTransformationTag", NULL);
1021  break;
1022  case TIFF_MODEL_TIEPOINT:
1023  ADD_METADATA(count, "ModelTiepointTag", NULL);
1024  break;
1026  ADD_METADATA(1, "GeoTIFF_Version", NULL);
1027  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
1028  s->geotag_count = ff_tget_short(&s->gb, s->le);
1029  if (s->geotag_count > count / 4 - 1) {
1030  s->geotag_count = count / 4 - 1;
1031  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
1032  }
1033  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
1034  s->geotag_count = 0;
1035  return -1;
1036  }
1037  s->geotags = av_mallocz_array(s->geotag_count, sizeof(TiffGeoTag));
1038  if (!s->geotags) {
1039  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1040  s->geotag_count = 0;
1041  goto end;
1042  }
1043  for (i = 0; i < s->geotag_count; i++) {
1044  s->geotags[i].key = ff_tget_short(&s->gb, s->le);
1045  s->geotags[i].type = ff_tget_short(&s->gb, s->le);
1046  s->geotags[i].count = ff_tget_short(&s->gb, s->le);
1047 
1048  if (!s->geotags[i].type)
1049  s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
1050  else
1051  s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
1052  }
1053  break;
1055  if (count >= INT_MAX / sizeof(int64_t))
1056  return AVERROR_INVALIDDATA;
1057  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
1058  return AVERROR_INVALIDDATA;
1059  dp = av_malloc_array(count, sizeof(double));
1060  if (!dp) {
1061  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1062  goto end;
1063  }
1064  for (i = 0; i < count; i++)
1065  dp[i] = ff_tget_double(&s->gb, s->le);
1066  for (i = 0; i < s->geotag_count; i++) {
1067  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
1068  if (s->geotags[i].count == 0
1069  || s->geotags[i].offset + s->geotags[i].count > count) {
1070  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1071  } else {
1072  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
1073  if (!ap) {
1074  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1075  av_freep(&dp);
1076  return AVERROR(ENOMEM);
1077  }
1078  s->geotags[i].val = ap;
1079  }
1080  }
1081  }
1082  av_freep(&dp);
1083  break;
1084  case TIFF_GEO_ASCII_PARAMS:
1085  pos = bytestream2_tell(&s->gb);
1086  for (i = 0; i < s->geotag_count; i++) {
1087  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
1088  if (s->geotags[i].count == 0
1089  || s->geotags[i].offset + s->geotags[i].count > count) {
1090  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1091  } else {
1092  char *ap;
1093 
1094  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
1095  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
1096  return AVERROR_INVALIDDATA;
1097  ap = av_malloc(s->geotags[i].count);
1098  if (!ap) {
1099  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1100  return AVERROR(ENOMEM);
1101  }
1102  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
1103  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
1104  s->geotags[i].val = ap;
1105  }
1106  }
1107  }
1108  break;
1109  case TIFF_ARTIST:
1110  ADD_METADATA(count, "artist", NULL);
1111  break;
1112  case TIFF_COPYRIGHT:
1113  ADD_METADATA(count, "copyright", NULL);
1114  break;
1115  case TIFF_DATE:
1116  ADD_METADATA(count, "date", NULL);
1117  break;
1118  case TIFF_DOCUMENT_NAME:
1119  ADD_METADATA(count, "document_name", NULL);
1120  break;
1121  case TIFF_HOST_COMPUTER:
1122  ADD_METADATA(count, "computer", NULL);
1123  break;
1125  ADD_METADATA(count, "description", NULL);
1126  break;
1127  case TIFF_MAKE:
1128  ADD_METADATA(count, "make", NULL);
1129  break;
1130  case TIFF_MODEL:
1131  ADD_METADATA(count, "model", NULL);
1132  break;
1133  case TIFF_PAGE_NAME:
1134  ADD_METADATA(count, "page_name", NULL);
1135  break;
1136  case TIFF_PAGE_NUMBER:
1137  ADD_METADATA(count, "page_number", " / ");
1138  break;
1139  case TIFF_SOFTWARE_NAME:
1140  ADD_METADATA(count, "software", NULL);
1141  break;
1142  default:
1143  if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1145  "Unknown or unsupported tag %d/0X%0X\n",
1146  tag, tag);
1147  return AVERROR_INVALIDDATA;
1148  }
1149  }
1150 end:
1151  bytestream2_seek(&s->gb, start, SEEK_SET);
1152  return 0;
1153 }
1154 
1155 static int decode_frame(AVCodecContext *avctx,
1156  void *data, int *got_frame, AVPacket *avpkt)
1157 {
1158  TiffContext *const s = avctx->priv_data;
1159  AVFrame *const p = data;
1160  ThreadFrame frame = { .f = data };
1161  unsigned off;
1162  int le, ret, plane, planes;
1163  int i, j, entries, stride;
1164  unsigned soff, ssize;
1165  uint8_t *dst;
1166  GetByteContext stripsizes;
1167  GetByteContext stripdata;
1168 
1169  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1170 
1171  // parse image header
1172  if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
1173  av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
1174  return ret;
1175  } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1176  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1177  return AVERROR_INVALIDDATA;
1178  }
1179  s->le = le;
1180  // TIFF_BPP is not a required tag and defaults to 1
1181  s->bppcount = s->bpp = 1;
1183  s->compr = TIFF_RAW;
1184  s->fill_order = 0;
1185  free_geotags(s);
1186 
1187  // Reset these offsets so we can tell if they were set this frame
1188  s->stripsizesoff = s->strippos = 0;
1189  /* parse image file directory */
1190  bytestream2_seek(&s->gb, off, SEEK_SET);
1191  entries = ff_tget_short(&s->gb, le);
1192  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1193  return AVERROR_INVALIDDATA;
1194  for (i = 0; i < entries; i++) {
1195  if ((ret = tiff_decode_tag(s, p)) < 0)
1196  return ret;
1197  }
1198 
1199  for (i = 0; i<s->geotag_count; i++) {
1200  const char *keyname = get_geokey_name(s->geotags[i].key);
1201  if (!keyname) {
1202  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1203  continue;
1204  }
1205  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1206  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1207  continue;
1208  }
1209  ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
1210  if (ret<0) {
1211  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1212  return ret;
1213  }
1214  }
1215 
1216  if (!s->strippos && !s->stripoff) {
1217  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1218  return AVERROR_INVALIDDATA;
1219  }
1220  /* now we have the data and may start decoding */
1221  if ((ret = init_image(s, &frame)) < 0)
1222  return ret;
1223 
1224  if (s->strips == 1 && !s->stripsize) {
1225  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1226  s->stripsize = avpkt->size - s->stripoff;
1227  }
1228 
1229  if (s->stripsizesoff) {
1230  if (s->stripsizesoff >= (unsigned)avpkt->size)
1231  return AVERROR_INVALIDDATA;
1232  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
1233  avpkt->size - s->stripsizesoff);
1234  }
1235  if (s->strippos) {
1236  if (s->strippos >= (unsigned)avpkt->size)
1237  return AVERROR_INVALIDDATA;
1238  bytestream2_init(&stripdata, avpkt->data + s->strippos,
1239  avpkt->size - s->strippos);
1240  }
1241 
1242  if (s->rps <= 0) {
1243  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1244  return AVERROR_INVALIDDATA;
1245  }
1246 
1247  planes = s->planar ? s->bppcount : 1;
1248  for (plane = 0; plane < planes; plane++) {
1249  stride = p->linesize[plane];
1250  dst = p->data[plane];
1251  for (i = 0; i < s->height; i += s->rps) {
1252  if (s->stripsizesoff)
1253  ssize = ff_tget(&stripsizes, s->sstype, le);
1254  else
1255  ssize = s->stripsize;
1256 
1257  if (s->strippos)
1258  soff = ff_tget(&stripdata, s->sot, le);
1259  else
1260  soff = s->stripoff;
1261 
1262  if (soff > avpkt->size || ssize > avpkt->size - soff) {
1263  av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1264  return AVERROR_INVALIDDATA;
1265  }
1266  if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,
1267  FFMIN(s->rps, s->height - i))) < 0) {
1268  if (avctx->err_recognition & AV_EF_EXPLODE)
1269  return ret;
1270  break;
1271  }
1272  dst += s->rps * stride;
1273  }
1274  if (s->predictor == 2) {
1275  if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
1276  av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");
1277  return AVERROR_PATCHWELCOME;
1278  }
1279  dst = p->data[plane];
1280  soff = s->bpp >> 3;
1281  if (s->planar)
1282  soff = FFMAX(soff / s->bppcount, 1);
1283  ssize = s->width * soff;
1284  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1288  for (i = 0; i < s->height; i++) {
1289  for (j = soff; j < ssize; j += 2)
1290  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1291  dst += stride;
1292  }
1293  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1297  for (i = 0; i < s->height; i++) {
1298  for (j = soff; j < ssize; j += 2)
1299  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1300  dst += stride;
1301  }
1302  } else {
1303  for (i = 0; i < s->height; i++) {
1304  for (j = soff; j < ssize; j++)
1305  dst[j] += dst[j - soff];
1306  dst += stride;
1307  }
1308  }
1309  }
1310 
1312  dst = p->data[plane];
1313  for (i = 0; i < s->height; i++) {
1314  for (j = 0; j < p->linesize[plane]; j++)
1315  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1316  dst += stride;
1317  }
1318  }
1319  }
1320 
1321  if (s->planar && s->bppcount > 2) {
1322  FFSWAP(uint8_t*, p->data[0], p->data[2]);
1323  FFSWAP(int, p->linesize[0], p->linesize[2]);
1324  FFSWAP(uint8_t*, p->data[0], p->data[1]);
1325  FFSWAP(int, p->linesize[0], p->linesize[1]);
1326  }
1327 
1328  *got_frame = 1;
1329 
1330  return avpkt->size;
1331 }
1332 
1334 {
1335  TiffContext *s = avctx->priv_data;
1336 
1337  s->width = 0;
1338  s->height = 0;
1339  s->subsampling[0] =
1340  s->subsampling[1] = 1;
1341  s->avctx = avctx;
1342  ff_lzw_decode_open(&s->lzw);
1344 
1345  return 0;
1346 }
1347 
1348 static av_cold int tiff_end(AVCodecContext *avctx)
1349 {
1350  TiffContext *const s = avctx->priv_data;
1351 
1352  free_geotags(s);
1353 
1354  ff_lzw_decode_close(&s->lzw);
1355  av_freep(&s->deinvert_buf);
1356  return 0;
1357 }
1358 
1360  .name = "tiff",
1361  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1362  .type = AVMEDIA_TYPE_VIDEO,
1363  .id = AV_CODEC_ID_TIFF,
1364  .priv_data_size = sizeof(TiffContext),
1365  .init = tiff_init,
1366  .close = tiff_end,
1367  .decode = decode_frame,
1369  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1370 };