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  s->bppcount = count;
818  if (count > 4) {
820  "This format is not supported (bpp=%d, %d components)\n",
821  s->bpp, count);
822  return AVERROR_INVALIDDATA;
823  }
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  break;
843  if (count != 1) {
845  "Samples per pixel requires a single value, many provided\n");
846  return AVERROR_INVALIDDATA;
847  }
848  if (value > 4U) {
850  "Samples per pixel %d is too large\n", value);
851  return AVERROR_INVALIDDATA;
852  }
853  if (s->bppcount == 1)
854  s->bpp *= value;
855  s->bppcount = value;
856  break;
857  case TIFF_COMPR:
858  s->compr = value;
859  s->predictor = 0;
860  switch (s->compr) {
861  case TIFF_RAW:
862  case TIFF_PACKBITS:
863  case TIFF_LZW:
864  case TIFF_CCITT_RLE:
865  break;
866  case TIFF_G3:
867  case TIFF_G4:
868  s->fax_opts = 0;
869  break;
870  case TIFF_DEFLATE:
871  case TIFF_ADOBE_DEFLATE:
872 #if CONFIG_ZLIB
873  break;
874 #else
875  av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
876  return AVERROR(ENOSYS);
877 #endif
878  case TIFF_JPEG:
879  case TIFF_NEWJPEG:
880  avpriv_report_missing_feature(s->avctx, "JPEG compression");
881  return AVERROR_PATCHWELCOME;
882  case TIFF_LZMA:
883 #if CONFIG_LZMA
884  break;
885 #else
886  av_log(s->avctx, AV_LOG_ERROR, "LZMA not compiled in\n");
887  return AVERROR(ENOSYS);
888 #endif
889  default:
890  av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
891  s->compr);
892  return AVERROR_INVALIDDATA;
893  }
894  break;
895  case TIFF_ROWSPERSTRIP:
896  if (!value || (type == TIFF_LONG && value == UINT_MAX))
897  value = s->height;
898  s->rps = FFMIN(value, s->height);
899  break;
900  case TIFF_STRIP_OFFS:
901  if (count == 1) {
902  s->strippos = 0;
903  s->stripoff = value;
904  } else
905  s->strippos = off;
906  s->strips = count;
907  if (s->strips == 1)
908  s->rps = s->height;
909  s->sot = type;
910  break;
911  case TIFF_STRIP_SIZE:
912  if (count == 1) {
913  s->stripsizesoff = 0;
914  s->stripsize = value;
915  s->strips = 1;
916  } else {
917  s->stripsizesoff = off;
918  }
919  s->strips = count;
920  s->sstype = type;
921  break;
922  case TIFF_XRES:
923  case TIFF_YRES:
924  set_sar(s, tag, value, value2);
925  break;
927  case TIFF_TILE_LENGTH:
928  case TIFF_TILE_OFFSETS:
929  case TIFF_TILE_WIDTH:
930  av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
931  return AVERROR_PATCHWELCOME;
932  break;
933  case TIFF_PREDICTOR:
934  s->predictor = value;
935  break;
936  case TIFF_PHOTOMETRIC:
937  switch (value) {
943  s->photometric = value;
944  break;
955  "PhotometricInterpretation 0x%04X",
956  value);
957  return AVERROR_PATCHWELCOME;
958  default:
959  av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "
960  "unknown\n", value);
961  return AVERROR_INVALIDDATA;
962  }
963  break;
964  case TIFF_FILL_ORDER:
965  if (value < 1 || value > 2) {
967  "Unknown FillOrder value %d, trying default one\n", value);
968  value = 1;
969  }
970  s->fill_order = value - 1;
971  break;
972  case TIFF_PAL: {
973  GetByteContext pal_gb[3];
974  off = type_sizes[type];
975  if (count / 3 > 256 ||
976  bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
977  return AVERROR_INVALIDDATA;
978 
979  pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
980  bytestream2_skip(&pal_gb[1], count / 3 * off);
981  bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
982 
983  off = (type_sizes[type] - 1) << 3;
984  for (i = 0; i < count / 3; i++) {
985  uint32_t p = 0xFF000000;
986  p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;
987  p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;
988  p |= ff_tget(&pal_gb[2], type, s->le) >> off;
989  s->palette[i] = p;
990  }
991  s->palette_is_set = 1;
992  break;
993  }
994  case TIFF_PLANAR:
995  s->planar = value == 2;
996  break;
998  if (count != 2) {
999  av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");
1000  return AVERROR_INVALIDDATA;
1001  }
1002  for (i = 0; i < count; i++)
1003  s->subsampling[i] = ff_tget(&s->gb, type, s->le);
1004  break;
1005  case TIFF_T4OPTIONS:
1006  if (s->compr == TIFF_G3)
1007  s->fax_opts = value;
1008  break;
1009  case TIFF_T6OPTIONS:
1010  if (s->compr == TIFF_G4)
1011  s->fax_opts = value;
1012  break;
1013 #define ADD_METADATA(count, name, sep)\
1014  if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
1015  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
1016  goto end;\
1017  }
1019  ADD_METADATA(count, "ModelPixelScaleTag", NULL);
1020  break;
1022  ADD_METADATA(count, "ModelTransformationTag", NULL);
1023  break;
1024  case TIFF_MODEL_TIEPOINT:
1025  ADD_METADATA(count, "ModelTiepointTag", NULL);
1026  break;
1028  ADD_METADATA(1, "GeoTIFF_Version", NULL);
1029  ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
1030  s->geotag_count = ff_tget_short(&s->gb, s->le);
1031  if (s->geotag_count > count / 4 - 1) {
1032  s->geotag_count = count / 4 - 1;
1033  av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
1034  }
1035  if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
1036  s->geotag_count = 0;
1037  return -1;
1038  }
1039  s->geotags = av_mallocz_array(s->geotag_count, sizeof(TiffGeoTag));
1040  if (!s->geotags) {
1041  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1042  s->geotag_count = 0;
1043  goto end;
1044  }
1045  for (i = 0; i < s->geotag_count; i++) {
1046  s->geotags[i].key = ff_tget_short(&s->gb, s->le);
1047  s->geotags[i].type = ff_tget_short(&s->gb, s->le);
1048  s->geotags[i].count = ff_tget_short(&s->gb, s->le);
1049 
1050  if (!s->geotags[i].type)
1051  s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
1052  else
1053  s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
1054  }
1055  break;
1057  if (count >= INT_MAX / sizeof(int64_t))
1058  return AVERROR_INVALIDDATA;
1059  if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
1060  return AVERROR_INVALIDDATA;
1061  dp = av_malloc_array(count, sizeof(double));
1062  if (!dp) {
1063  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1064  goto end;
1065  }
1066  for (i = 0; i < count; i++)
1067  dp[i] = ff_tget_double(&s->gb, s->le);
1068  for (i = 0; i < s->geotag_count; i++) {
1069  if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
1070  if (s->geotags[i].count == 0
1071  || s->geotags[i].offset + s->geotags[i].count > count) {
1072  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1073  } else {
1074  char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
1075  if (!ap) {
1076  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1077  av_freep(&dp);
1078  return AVERROR(ENOMEM);
1079  }
1080  s->geotags[i].val = ap;
1081  }
1082  }
1083  }
1084  av_freep(&dp);
1085  break;
1086  case TIFF_GEO_ASCII_PARAMS:
1087  pos = bytestream2_tell(&s->gb);
1088  for (i = 0; i < s->geotag_count; i++) {
1089  if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
1090  if (s->geotags[i].count == 0
1091  || s->geotags[i].offset + s->geotags[i].count > count) {
1092  av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1093  } else {
1094  char *ap;
1095 
1096  bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
1097  if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
1098  return AVERROR_INVALIDDATA;
1099  ap = av_malloc(s->geotags[i].count);
1100  if (!ap) {
1101  av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1102  return AVERROR(ENOMEM);
1103  }
1104  bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
1105  ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
1106  s->geotags[i].val = ap;
1107  }
1108  }
1109  }
1110  break;
1111  case TIFF_ARTIST:
1112  ADD_METADATA(count, "artist", NULL);
1113  break;
1114  case TIFF_COPYRIGHT:
1115  ADD_METADATA(count, "copyright", NULL);
1116  break;
1117  case TIFF_DATE:
1118  ADD_METADATA(count, "date", NULL);
1119  break;
1120  case TIFF_DOCUMENT_NAME:
1121  ADD_METADATA(count, "document_name", NULL);
1122  break;
1123  case TIFF_HOST_COMPUTER:
1124  ADD_METADATA(count, "computer", NULL);
1125  break;
1127  ADD_METADATA(count, "description", NULL);
1128  break;
1129  case TIFF_MAKE:
1130  ADD_METADATA(count, "make", NULL);
1131  break;
1132  case TIFF_MODEL:
1133  ADD_METADATA(count, "model", NULL);
1134  break;
1135  case TIFF_PAGE_NAME:
1136  ADD_METADATA(count, "page_name", NULL);
1137  break;
1138  case TIFF_PAGE_NUMBER:
1139  ADD_METADATA(count, "page_number", " / ");
1140  break;
1141  case TIFF_SOFTWARE_NAME:
1142  ADD_METADATA(count, "software", NULL);
1143  break;
1144  default:
1145  if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1147  "Unknown or unsupported tag %d/0X%0X\n",
1148  tag, tag);
1149  return AVERROR_INVALIDDATA;
1150  }
1151  }
1152 end:
1153  bytestream2_seek(&s->gb, start, SEEK_SET);
1154  return 0;
1155 }
1156 
1157 static int decode_frame(AVCodecContext *avctx,
1158  void *data, int *got_frame, AVPacket *avpkt)
1159 {
1160  TiffContext *const s = avctx->priv_data;
1161  AVFrame *const p = data;
1162  ThreadFrame frame = { .f = data };
1163  unsigned off;
1164  int le, ret, plane, planes;
1165  int i, j, entries, stride;
1166  unsigned soff, ssize;
1167  uint8_t *dst;
1168  GetByteContext stripsizes;
1169  GetByteContext stripdata;
1170 
1171  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1172 
1173  // parse image header
1174  if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
1175  av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
1176  return ret;
1177  } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1178  av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1179  return AVERROR_INVALIDDATA;
1180  }
1181  s->le = le;
1182  // TIFF_BPP is not a required tag and defaults to 1
1183  s->bppcount = s->bpp = 1;
1185  s->compr = TIFF_RAW;
1186  s->fill_order = 0;
1187  free_geotags(s);
1188 
1189  // Reset these offsets so we can tell if they were set this frame
1190  s->stripsizesoff = s->strippos = 0;
1191  /* parse image file directory */
1192  bytestream2_seek(&s->gb, off, SEEK_SET);
1193  entries = ff_tget_short(&s->gb, le);
1194  if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1195  return AVERROR_INVALIDDATA;
1196  for (i = 0; i < entries; i++) {
1197  if ((ret = tiff_decode_tag(s, p)) < 0)
1198  return ret;
1199  }
1200 
1201  for (i = 0; i<s->geotag_count; i++) {
1202  const char *keyname = get_geokey_name(s->geotags[i].key);
1203  if (!keyname) {
1204  av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1205  continue;
1206  }
1207  if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1208  av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1209  continue;
1210  }
1211  ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
1212  if (ret<0) {
1213  av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1214  return ret;
1215  }
1216  }
1217 
1218  if (!s->strippos && !s->stripoff) {
1219  av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1220  return AVERROR_INVALIDDATA;
1221  }
1222  /* now we have the data and may start decoding */
1223  if ((ret = init_image(s, &frame)) < 0)
1224  return ret;
1225 
1226  if (s->strips == 1 && !s->stripsize) {
1227  av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1228  s->stripsize = avpkt->size - s->stripoff;
1229  }
1230 
1231  if (s->stripsizesoff) {
1232  if (s->stripsizesoff >= (unsigned)avpkt->size)
1233  return AVERROR_INVALIDDATA;
1234  bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
1235  avpkt->size - s->stripsizesoff);
1236  }
1237  if (s->strippos) {
1238  if (s->strippos >= (unsigned)avpkt->size)
1239  return AVERROR_INVALIDDATA;
1240  bytestream2_init(&stripdata, avpkt->data + s->strippos,
1241  avpkt->size - s->strippos);
1242  }
1243 
1244  if (s->rps <= 0) {
1245  av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1246  return AVERROR_INVALIDDATA;
1247  }
1248 
1249  planes = s->planar ? s->bppcount : 1;
1250  for (plane = 0; plane < planes; plane++) {
1251  stride = p->linesize[plane];
1252  dst = p->data[plane];
1253  for (i = 0; i < s->height; i += s->rps) {
1254  if (s->stripsizesoff)
1255  ssize = ff_tget(&stripsizes, s->sstype, le);
1256  else
1257  ssize = s->stripsize;
1258 
1259  if (s->strippos)
1260  soff = ff_tget(&stripdata, s->sot, le);
1261  else
1262  soff = s->stripoff;
1263 
1264  if (soff > avpkt->size || ssize > avpkt->size - soff) {
1265  av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1266  return AVERROR_INVALIDDATA;
1267  }
1268  if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,
1269  FFMIN(s->rps, s->height - i))) < 0) {
1270  if (avctx->err_recognition & AV_EF_EXPLODE)
1271  return ret;
1272  break;
1273  }
1274  dst += s->rps * stride;
1275  }
1276  if (s->predictor == 2) {
1277  if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
1278  av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");
1279  return AVERROR_PATCHWELCOME;
1280  }
1281  dst = p->data[plane];
1282  soff = s->bpp >> 3;
1283  if (s->planar)
1284  soff = FFMAX(soff / s->bppcount, 1);
1285  ssize = s->width * soff;
1286  if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1290  for (i = 0; i < s->height; i++) {
1291  for (j = soff; j < ssize; j += 2)
1292  AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1293  dst += stride;
1294  }
1295  } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1299  for (i = 0; i < s->height; i++) {
1300  for (j = soff; j < ssize; j += 2)
1301  AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1302  dst += stride;
1303  }
1304  } else {
1305  for (i = 0; i < s->height; i++) {
1306  for (j = soff; j < ssize; j++)
1307  dst[j] += dst[j - soff];
1308  dst += stride;
1309  }
1310  }
1311  }
1312 
1314  dst = p->data[plane];
1315  for (i = 0; i < s->height; i++) {
1316  for (j = 0; j < p->linesize[plane]; j++)
1317  dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1318  dst += stride;
1319  }
1320  }
1321  }
1322 
1323  if (s->planar && s->bppcount > 2) {
1324  FFSWAP(uint8_t*, p->data[0], p->data[2]);
1325  FFSWAP(int, p->linesize[0], p->linesize[2]);
1326  FFSWAP(uint8_t*, p->data[0], p->data[1]);
1327  FFSWAP(int, p->linesize[0], p->linesize[1]);
1328  }
1329 
1330  *got_frame = 1;
1331 
1332  return avpkt->size;
1333 }
1334 
1336 {
1337  TiffContext *s = avctx->priv_data;
1338 
1339  s->width = 0;
1340  s->height = 0;
1341  s->subsampling[0] =
1342  s->subsampling[1] = 1;
1343  s->avctx = avctx;
1344  ff_lzw_decode_open(&s->lzw);
1346 
1347  return 0;
1348 }
1349 
1350 static av_cold int tiff_end(AVCodecContext *avctx)
1351 {
1352  TiffContext *const s = avctx->priv_data;
1353 
1354  free_geotags(s);
1355 
1356  ff_lzw_decode_close(&s->lzw);
1357  av_freep(&s->deinvert_buf);
1358  return 0;
1359 }
1360 
1362  .name = "tiff",
1363  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1364  .type = AVMEDIA_TYPE_VIDEO,
1365  .id = AV_CODEC_ID_TIFF,
1366  .priv_data_size = sizeof(TiffContext),
1367  .init = tiff_init,
1368  .close = tiff_end,
1369  .decode = decode_frame,
1371  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1372 };