2 * Copyright (c) 2006 Konstantin Shishkov
4 * This file is part of FFmpeg.
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.
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.
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
24 * @author Konstantin Shishkov
32 #define LZMA_API_STATIC
36 #include "libavutil/attributes.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/imgutils.h"
41 #include "bytestream.h"
47 #include "tiff_data.h"
50 typedef struct TiffContext {
51 AVCodecContext *avctx;
55 unsigned int bpp, bppcount;
56 uint32_t palette[256];
60 enum TiffPhotometric photometric;
68 int strips, rps, sstype;
70 int stripsizesoff, stripsize, stripoff, strippos;
73 uint8_t *deinvert_buf;
74 int deinvert_buf_size;
76 unsigned int yuv_line_size;
78 unsigned int fax_buffer_size;
84 static void free_geotags(TiffContext *const s)
87 for (i = 0; i < s->geotag_count; i++) {
88 if (s->geotags[i].val)
89 av_freep(&s->geotags[i].val);
91 av_freep(&s->geotags);
95 #define RET_GEOKEY(TYPE, array, element)\
96 if (key >= TIFF_##TYPE##_KEY_ID_OFFSET &&\
97 key - TIFF_##TYPE##_KEY_ID_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_name_type_map))\
98 return ff_tiff_##array##_name_type_map[key - TIFF_##TYPE##_KEY_ID_OFFSET].element;
100 static const char *get_geokey_name(int key)
102 RET_GEOKEY(VERT, vert, name);
103 RET_GEOKEY(PROJ, proj, name);
104 RET_GEOKEY(GEOG, geog, name);
105 RET_GEOKEY(CONF, conf, name);
110 static int get_geokey_type(int key)
112 RET_GEOKEY(VERT, vert, type);
113 RET_GEOKEY(PROJ, proj, type);
114 RET_GEOKEY(GEOG, geog, type);
115 RET_GEOKEY(CONF, conf, type);
117 return AVERROR_INVALIDDATA;
120 static int cmp_id_key(const void *id, const void *k)
122 return *(const int*)id - ((const TiffGeoTagKeyName*)k)->key;
125 static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)
127 TiffGeoTagKeyName *r = bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key);
134 static char *get_geokey_val(int key, int val)
138 if (val == TIFF_GEO_KEY_UNDEFINED)
139 return av_strdup("undefined");
140 if (val == TIFF_GEO_KEY_USER_DEFINED)
141 return av_strdup("User-Defined");
143 #define RET_GEOKEY_VAL(TYPE, array)\
144 if (val >= TIFF_##TYPE##_OFFSET &&\
145 val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\
146 return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);
149 case TIFF_GT_MODEL_TYPE_GEOKEY:
150 RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);
152 case TIFF_GT_RASTER_TYPE_GEOKEY:
153 RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);
155 case TIFF_GEOG_LINEAR_UNITS_GEOKEY:
156 case TIFF_PROJ_LINEAR_UNITS_GEOKEY:
157 case TIFF_VERTICAL_UNITS_GEOKEY:
158 RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);
160 case TIFF_GEOG_ANGULAR_UNITS_GEOKEY:
161 case TIFF_GEOG_AZIMUTH_UNITS_GEOKEY:
162 RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);
164 case TIFF_GEOGRAPHIC_TYPE_GEOKEY:
165 RET_GEOKEY_VAL(GCS_TYPE, gcs_type);
166 RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);
168 case TIFF_GEOG_GEODETIC_DATUM_GEOKEY:
169 RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);
170 RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);
172 case TIFF_GEOG_ELLIPSOID_GEOKEY:
173 RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);
175 case TIFF_GEOG_PRIME_MERIDIAN_GEOKEY:
176 RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);
178 case TIFF_PROJECTED_CS_TYPE_GEOKEY:
179 ap = av_strdup(search_keyval(ff_tiff_proj_cs_type_codes, FF_ARRAY_ELEMS(ff_tiff_proj_cs_type_codes), val));
182 case TIFF_PROJECTION_GEOKEY:
183 ap = av_strdup(search_keyval(ff_tiff_projection_codes, FF_ARRAY_ELEMS(ff_tiff_projection_codes), val));
186 case TIFF_PROJ_COORD_TRANS_GEOKEY:
187 RET_GEOKEY_VAL(COORD_TRANS, coord_trans);
189 case TIFF_VERTICAL_CS_TYPE_GEOKEY:
190 RET_GEOKEY_VAL(VERT_CS, vert_cs);
191 RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);
198 snprintf(ap, 14, "Unknown-%d", val);
202 static char *doubles2str(double *dp, int count, const char *sep)
206 uint64_t component_len;
207 if (!sep) sep = ", ";
208 component_len = 24LL + strlen(sep);
209 if (count >= (INT_MAX - 1)/component_len)
211 ap = av_malloc(component_len * count + 1);
216 for (i = 0; i < count; i++) {
217 unsigned l = snprintf(ap, component_len, "%.15g%s", dp[i], sep);
218 if(l >= component_len) {
224 ap0[strlen(ap0) - strlen(sep)] = '\0';
228 static int add_metadata(int count, int type,
229 const char *name, const char *sep, TiffContext *s, AVFrame *frame)
232 case TIFF_DOUBLE: return ff_tadd_doubles_metadata(count, name, sep, &s->gb, s->le, &frame->metadata);
233 case TIFF_SHORT : return ff_tadd_shorts_metadata(count, name, sep, &s->gb, s->le, 0, &frame->metadata);
234 case TIFF_STRING: return ff_tadd_string_metadata(count, name, &s->gb, s->le, &frame->metadata);
235 default : return AVERROR_INVALIDDATA;
239 static void av_always_inline horizontal_fill(unsigned int bpp, uint8_t* dst,
240 int usePtr, const uint8_t *src,
241 uint8_t c, int width, int offset)
245 while (--width >= 0) {
246 dst[(width+offset)*8+7] = (usePtr ? src[width] : c) & 0x1;
247 dst[(width+offset)*8+6] = (usePtr ? src[width] : c) >> 1 & 0x1;
248 dst[(width+offset)*8+5] = (usePtr ? src[width] : c) >> 2 & 0x1;
249 dst[(width+offset)*8+4] = (usePtr ? src[width] : c) >> 3 & 0x1;
250 dst[(width+offset)*8+3] = (usePtr ? src[width] : c) >> 4 & 0x1;
251 dst[(width+offset)*8+2] = (usePtr ? src[width] : c) >> 5 & 0x1;
252 dst[(width+offset)*8+1] = (usePtr ? src[width] : c) >> 6 & 0x1;
253 dst[(width+offset)*8+0] = (usePtr ? src[width] : c) >> 7;
257 while (--width >= 0) {
258 dst[(width+offset)*4+3] = (usePtr ? src[width] : c) & 0x3;
259 dst[(width+offset)*4+2] = (usePtr ? src[width] : c) >> 2 & 0x3;
260 dst[(width+offset)*4+1] = (usePtr ? src[width] : c) >> 4 & 0x3;
261 dst[(width+offset)*4+0] = (usePtr ? src[width] : c) >> 6;
265 while (--width >= 0) {
266 dst[(width+offset)*2+1] = (usePtr ? src[width] : c) & 0xF;
267 dst[(width+offset)*2+0] = (usePtr ? src[width] : c) >> 4;
272 memcpy(dst + offset, src, width);
274 memset(dst + offset, c, width);
279 static int deinvert_buffer(TiffContext *s, const uint8_t *src, int size)
283 av_fast_padded_malloc(&s->deinvert_buf, &s->deinvert_buf_size, size);
284 if (!s->deinvert_buf)
285 return AVERROR(ENOMEM);
286 for (i = 0; i < size; i++)
287 s->deinvert_buf[i] = ff_reverse[src[i]];
292 static void unpack_yuv(TiffContext *s, AVFrame *p,
293 const uint8_t *src, int lnum)
296 int w = (s->width - 1) / s->subsampling[0] + 1;
297 uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
298 uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
299 if (s->width % s->subsampling[0] || s->height % s->subsampling[1]) {
300 for (i = 0; i < w; i++) {
301 for (j = 0; j < s->subsampling[1]; j++)
302 for (k = 0; k < s->subsampling[0]; k++)
303 p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
304 FFMIN(i * s->subsampling[0] + k, s->width-1)] = *src++;
309 for (i = 0; i < w; i++) {
310 for (j = 0; j < s->subsampling[1]; j++)
311 for (k = 0; k < s->subsampling[0]; k++)
312 p->data[0][(lnum + j) * p->linesize[0] +
313 i * s->subsampling[0] + k] = *src++;
321 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
324 z_stream zstream = { 0 };
327 zstream.next_in = (uint8_t *)src;
328 zstream.avail_in = size;
329 zstream.next_out = dst;
330 zstream.avail_out = *len;
331 zret = inflateInit(&zstream);
333 av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
336 zret = inflate(&zstream, Z_SYNC_FLUSH);
337 inflateEnd(&zstream);
338 *len = zstream.total_out;
339 return zret == Z_STREAM_END ? Z_OK : zret;
342 static int tiff_unpack_zlib(TiffContext *s, AVFrame *p, uint8_t *dst, int stride,
343 const uint8_t *src, int size, int width, int lines,
344 int strip_start, int is_yuv)
347 unsigned long outlen;
349 outlen = width * lines;
350 zbuf = av_malloc(outlen);
352 return AVERROR(ENOMEM);
354 if ((ret = deinvert_buffer(s, src, size)) < 0) {
358 src = s->deinvert_buf;
360 ret = tiff_uncompress(zbuf, &outlen, src, size);
362 av_log(s->avctx, AV_LOG_ERROR,
363 "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
364 (unsigned long)width * lines, ret);
366 return AVERROR_UNKNOWN;
369 for (line = 0; line < lines; line++) {
370 if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
371 horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
373 memcpy(dst, src, width);
376 unpack_yuv(s, p, dst, strip_start + line);
377 line += s->subsampling[1] - 1;
388 static int tiff_uncompress_lzma(uint8_t *dst, uint64_t *len, const uint8_t *src,
391 lzma_stream stream = LZMA_STREAM_INIT;
394 stream.next_in = (uint8_t *)src;
395 stream.avail_in = size;
396 stream.next_out = dst;
397 stream.avail_out = *len;
398 ret = lzma_stream_decoder(&stream, UINT64_MAX, 0);
399 if (ret != LZMA_OK) {
400 av_log(NULL, AV_LOG_ERROR, "LZMA init error: %d\n", ret);
403 ret = lzma_code(&stream, LZMA_RUN);
405 *len = stream.total_out;
406 return ret == LZMA_STREAM_END ? LZMA_OK : ret;
409 static int tiff_unpack_lzma(TiffContext *s, AVFrame *p, uint8_t *dst, int stride,
410 const uint8_t *src, int size, int width, int lines,
411 int strip_start, int is_yuv)
413 uint64_t outlen = width * (uint64_t)lines;
415 uint8_t *buf = av_malloc(outlen);
417 return AVERROR(ENOMEM);
419 if ((ret = deinvert_buffer(s, src, size)) < 0) {
423 src = s->deinvert_buf;
425 ret = tiff_uncompress_lzma(buf, &outlen, src, size);
426 if (ret != LZMA_OK) {
427 av_log(s->avctx, AV_LOG_ERROR,
428 "Uncompressing failed (%"PRIu64" of %"PRIu64") with error %d\n", outlen,
429 (uint64_t)width * lines, ret);
431 return AVERROR_UNKNOWN;
434 for (line = 0; line < lines; line++) {
435 if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
436 horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
438 memcpy(dst, src, width);
441 unpack_yuv(s, p, dst, strip_start + line);
442 line += s->subsampling[1] - 1;
452 static int tiff_unpack_fax(TiffContext *s, uint8_t *dst, int stride,
453 const uint8_t *src, int size, int width, int lines)
459 av_fast_padded_malloc(&s->fax_buffer, &s->fax_buffer_size, size);
460 src2 = s->fax_buffer;
463 av_log(s->avctx, AV_LOG_ERROR,
464 "Error allocating temporary buffer\n");
465 return AVERROR(ENOMEM);
468 if (!s->fill_order) {
469 memcpy(src2, src, size);
471 for (i = 0; i < size; i++)
472 src2[i] = ff_reverse[src[i]];
474 memset(src2 + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
475 ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
476 s->compr, s->fax_opts);
477 if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
478 for (line = 0; line < lines; line++) {
479 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
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)
489 int c, line, pixels, code, ret;
490 const uint8_t *ssrc = src;
491 int width = ((s->width * s->bpp) + 7) >> 3;
492 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(p->format);
493 int is_yuv = !(desc->flags & AV_PIX_FMT_FLAG_RGB) &&
494 (desc->flags & AV_PIX_FMT_FLAG_PLANAR) &&
495 desc->nb_components >= 3;
498 width /= s->bppcount;
501 return AVERROR_INVALIDDATA;
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);
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);
520 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
522 return tiff_unpack_zlib(s, p, dst, stride, src, size, width, lines,
523 strip_start, is_yuv);
525 av_log(s->avctx, AV_LOG_ERROR,
526 "zlib support not enabled, "
527 "deflate compression not supported\n");
528 return AVERROR(ENOSYS);
531 if (s->compr == TIFF_LZMA) {
533 return tiff_unpack_lzma(s, p, dst, stride, src, size, width, lines,
534 strip_start, is_yuv);
536 av_log(s->avctx, AV_LOG_ERROR,
537 "LZMA support not enabled\n");
538 return AVERROR(ENOSYS);
541 if (s->compr == TIFF_LZW) {
543 if ((ret = deinvert_buffer(s, src, size)) < 0)
545 ssrc = src = s->deinvert_buf;
547 if (size > 1 && !src[0] && (src[1]&1)) {
548 av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
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");
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",
559 return AVERROR_INVALIDDATA;
561 if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
562 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
564 unpack_yuv(s, p, dst, strip_start + line);
565 line += s->subsampling[1] - 1;
571 if (s->compr == TIFF_CCITT_RLE ||
572 s->compr == TIFF_G3 ||
573 s->compr == TIFF_G4) {
575 return AVERROR_INVALIDDATA;
577 return tiff_unpack_fax(s, dst, stride, src, size, width, lines);
580 bytestream2_init(&s->gb, src, size);
581 bytestream2_init_writer(&pb, dst, is_yuv ? s->yuv_line_size : (stride * lines));
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;
589 if (bytestream2_get_bytes_left(&s->gb) == 0 || bytestream2_get_eof(&pb))
591 bytestream2_seek_p(&pb, stride * line, SEEK_SET);
594 if (ssrc + size - src < width)
595 return AVERROR_INVALIDDATA;
597 if (!s->fill_order) {
598 horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
599 dst, 1, src, 0, width, 0);
602 for (i = 0; i < width; i++)
603 dst[i] = ff_reverse[src[i]];
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;
613 code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;
616 if (pixels + code > width ||
617 ssrc + size - src < code) {
618 av_log(s->avctx, AV_LOG_ERROR,
619 "Copy went out of bounds\n");
620 return AVERROR_INVALIDDATA;
622 horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
623 dst, 1, src, 0, code, pixels);
626 } else if (code != -128) { // -127..-1
628 if (pixels + code > width) {
629 av_log(s->avctx, AV_LOG_ERROR,
630 "Run went out of bounds\n");
631 return AVERROR_INVALIDDATA;
634 horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
635 dst, 0, NULL, c, code, pixels);
641 for (i = 0; i < width; i++)
642 dst[i] = ff_reverse[dst[i]];
647 unpack_yuv(s, p, dst, strip_start + line);
648 line += s->subsampling[1] - 1;
655 static int init_image(TiffContext *s, ThreadFrame *frame)
658 int create_gray_palette = 0;
660 // make sure there is no aliasing in the following switch
661 if (s->bpp >= 100 || s->bppcount >= 10) {
662 av_log(s->avctx, AV_LOG_ERROR,
663 "Unsupported image parameters: bpp=%d, bppcount=%d\n",
664 s->bpp, s->bppcount);
665 return AVERROR_INVALIDDATA;
668 switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
670 if (!s->palette_is_set) {
671 s->avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
676 s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
677 if (!s->palette_is_set) {
678 create_gray_palette = 1;
682 s->avctx->pix_fmt = s->palette_is_set ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8;
685 if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
686 if (s->subsampling[0] == 1 && s->subsampling[1] == 1) {
687 s->avctx->pix_fmt = AV_PIX_FMT_YUV444P;
688 } else if (s->subsampling[0] == 2 && s->subsampling[1] == 1) {
689 s->avctx->pix_fmt = AV_PIX_FMT_YUV422P;
690 } else if (s->subsampling[0] == 4 && s->subsampling[1] == 1) {
691 s->avctx->pix_fmt = AV_PIX_FMT_YUV411P;
692 } else if (s->subsampling[0] == 1 && s->subsampling[1] == 2) {
693 s->avctx->pix_fmt = AV_PIX_FMT_YUV440P;
694 } else if (s->subsampling[0] == 2 && s->subsampling[1] == 2) {
695 s->avctx->pix_fmt = AV_PIX_FMT_YUV420P;
696 } else if (s->subsampling[0] == 4 && s->subsampling[1] == 4) {
697 s->avctx->pix_fmt = AV_PIX_FMT_YUV410P;
699 av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr subsampling\n");
700 return AVERROR_PATCHWELCOME;
703 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
706 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GRAY16LE : AV_PIX_FMT_GRAY16BE;
709 s->avctx->pix_fmt = AV_PIX_FMT_YA8;
712 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_YA16LE : AV_PIX_FMT_YA16BE;
715 s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
718 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB48BE;
721 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGBA64BE;
724 s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
727 s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
730 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GBRP16LE : AV_PIX_FMT_GBRP16BE;
733 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GBRAP16LE : AV_PIX_FMT_GBRAP16BE;
736 av_log(s->avctx, AV_LOG_ERROR,
737 "This format is not supported (bpp=%d, bppcount=%d)\n",
738 s->bpp, s->bppcount);
739 return AVERROR_INVALIDDATA;
742 if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
743 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
744 if((desc->flags & AV_PIX_FMT_FLAG_RGB) ||
745 !(desc->flags & AV_PIX_FMT_FLAG_PLANAR) ||
746 desc->nb_components < 3) {
747 av_log(s->avctx, AV_LOG_ERROR, "Unsupported YCbCr variant\n");
748 return AVERROR_INVALIDDATA;
752 if (s->width != s->avctx->width || s->height != s->avctx->height) {
753 ret = ff_set_dimensions(s->avctx, s->width, s->height);
757 if ((ret = ff_thread_get_buffer(s->avctx, frame, 0)) < 0)
759 if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
760 if (!create_gray_palette)
761 memcpy(frame->f->data[1], s->palette, sizeof(s->palette));
763 /* make default grayscale pal */
765 uint32_t *pal = (uint32_t *)frame->f->data[1];
766 for (i = 0; i < 1<<s->bpp; i++)
767 pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
773 static void set_sar(TiffContext *s, unsigned tag, unsigned num, unsigned den)
775 int offset = tag == TIFF_YRES ? 2 : 0;
776 s->res[offset++] = num;
777 s->res[offset] = den;
778 if (s->res[0] && s->res[1] && s->res[2] && s->res[3]) {
779 uint64_t num = s->res[2] * (uint64_t)s->res[1];
780 uint64_t den = s->res[0] * (uint64_t)s->res[3];
781 if (num > INT64_MAX || den > INT64_MAX) {
785 av_reduce(&s->avctx->sample_aspect_ratio.num, &s->avctx->sample_aspect_ratio.den,
786 num, den, INT32_MAX);
787 if (!s->avctx->sample_aspect_ratio.den)
788 s->avctx->sample_aspect_ratio = (AVRational) {0, 1};
792 static int tiff_decode_tag(TiffContext *s, AVFrame *frame)
794 unsigned tag, type, count, off, value = 0, value2 = 0;
800 ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);
805 off = bytestream2_tell(&s->gb);
811 value = ff_tget(&s->gb, type, s->le);
814 value = ff_tget(&s->gb, TIFF_LONG, s->le);
815 value2 = ff_tget(&s->gb, TIFF_LONG, s->le);
835 av_log(s->avctx, AV_LOG_ERROR,
836 "This format is not supported (bpp=%d, %d components)\n",
838 return AVERROR_INVALIDDATA;
849 if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
850 return AVERROR_INVALIDDATA;
851 for (i = 0; i < count; i++)
852 s->bpp += ff_tget(&s->gb, type, s->le);
859 case TIFF_SAMPLES_PER_PIXEL:
861 av_log(s->avctx, AV_LOG_ERROR,
862 "Samples per pixel requires a single value, many provided\n");
863 return AVERROR_INVALIDDATA;
866 av_log(s->avctx, AV_LOG_ERROR,
867 "Samples per pixel %d is too large\n", value);
868 return AVERROR_INVALIDDATA;
870 if (s->bppcount == 1)
876 av_log(s->avctx, AV_LOG_DEBUG, "compression: %d\n", s->compr);
889 case TIFF_ADOBE_DEFLATE:
893 av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
894 return AVERROR(ENOSYS);
898 avpriv_report_missing_feature(s->avctx, "JPEG compression");
899 return AVERROR_PATCHWELCOME;
904 av_log(s->avctx, AV_LOG_ERROR, "LZMA not compiled in\n");
905 return AVERROR(ENOSYS);
908 av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
910 return AVERROR_INVALIDDATA;
913 case TIFF_ROWSPERSTRIP:
914 if (!value || (type == TIFF_LONG && value == UINT_MAX))
916 s->rps = FFMIN(value, s->height);
918 case TIFF_STRIP_OFFS:
920 if (value > INT_MAX) {
921 av_log(s->avctx, AV_LOG_ERROR,
922 "strippos %u too large\n", value);
923 return AVERROR_INVALIDDATA;
934 case TIFF_STRIP_SIZE:
936 if (value > INT_MAX) {
937 av_log(s->avctx, AV_LOG_ERROR,
938 "stripsize %u too large\n", value);
939 return AVERROR_INVALIDDATA;
941 s->stripsizesoff = 0;
942 s->stripsize = value;
945 s->stripsizesoff = off;
952 set_sar(s, tag, value, value2);
954 case TIFF_TILE_BYTE_COUNTS:
955 case TIFF_TILE_LENGTH:
956 case TIFF_TILE_OFFSETS:
957 case TIFF_TILE_WIDTH:
958 av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
959 return AVERROR_PATCHWELCOME;
962 s->predictor = value;
964 case TIFF_PHOTOMETRIC:
966 case TIFF_PHOTOMETRIC_WHITE_IS_ZERO:
967 case TIFF_PHOTOMETRIC_BLACK_IS_ZERO:
968 case TIFF_PHOTOMETRIC_RGB:
969 case TIFF_PHOTOMETRIC_PALETTE:
970 case TIFF_PHOTOMETRIC_YCBCR:
971 s->photometric = value;
973 case TIFF_PHOTOMETRIC_ALPHA_MASK:
974 case TIFF_PHOTOMETRIC_SEPARATED:
975 case TIFF_PHOTOMETRIC_CIE_LAB:
976 case TIFF_PHOTOMETRIC_ICC_LAB:
977 case TIFF_PHOTOMETRIC_ITU_LAB:
978 case TIFF_PHOTOMETRIC_CFA:
979 case TIFF_PHOTOMETRIC_LOG_L:
980 case TIFF_PHOTOMETRIC_LOG_LUV:
981 case TIFF_PHOTOMETRIC_LINEAR_RAW:
982 avpriv_report_missing_feature(s->avctx,
983 "PhotometricInterpretation 0x%04X",
985 return AVERROR_PATCHWELCOME;
987 av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "
989 return AVERROR_INVALIDDATA;
992 case TIFF_FILL_ORDER:
993 if (value < 1 || value > 2) {
994 av_log(s->avctx, AV_LOG_ERROR,
995 "Unknown FillOrder value %d, trying default one\n", value);
998 s->fill_order = value - 1;
1001 GetByteContext pal_gb[3];
1002 off = type_sizes[type];
1003 if (count / 3 > 256 ||
1004 bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
1005 return AVERROR_INVALIDDATA;
1007 pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
1008 bytestream2_skip(&pal_gb[1], count / 3 * off);
1009 bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
1011 off = (type_sizes[type] - 1) << 3;
1013 av_log(s->avctx, AV_LOG_ERROR, "palette shift %d is out of range\n", off);
1014 return AVERROR_INVALIDDATA;
1017 for (i = 0; i < count / 3; i++) {
1018 uint32_t p = 0xFF000000;
1019 p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;
1020 p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;
1021 p |= ff_tget(&pal_gb[2], type, s->le) >> off;
1024 s->palette_is_set = 1;
1028 s->planar = value == 2;
1030 case TIFF_YCBCR_SUBSAMPLING:
1032 av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");
1033 return AVERROR_INVALIDDATA;
1035 for (i = 0; i < count; i++) {
1036 s->subsampling[i] = ff_tget(&s->gb, type, s->le);
1037 if (s->subsampling[i] <= 0) {
1038 av_log(s->avctx, AV_LOG_ERROR, "subsampling %d is invalid\n", s->subsampling[i]);
1039 s->subsampling[i] = 1;
1040 return AVERROR_INVALIDDATA;
1044 case TIFF_T4OPTIONS:
1045 if (s->compr == TIFF_G3)
1046 s->fax_opts = value;
1048 case TIFF_T6OPTIONS:
1049 if (s->compr == TIFF_G4)
1050 s->fax_opts = value;
1052 #define ADD_METADATA(count, name, sep)\
1053 if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
1054 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
1057 case TIFF_MODEL_PIXEL_SCALE:
1058 ADD_METADATA(count, "ModelPixelScaleTag", NULL);
1060 case TIFF_MODEL_TRANSFORMATION:
1061 ADD_METADATA(count, "ModelTransformationTag", NULL);
1063 case TIFF_MODEL_TIEPOINT:
1064 ADD_METADATA(count, "ModelTiepointTag", NULL);
1066 case TIFF_GEO_KEY_DIRECTORY:
1067 if (s->geotag_count) {
1068 avpriv_request_sample(s->avctx, "Multiple geo key directories\n");
1069 return AVERROR_INVALIDDATA;
1071 ADD_METADATA(1, "GeoTIFF_Version", NULL);
1072 ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
1073 s->geotag_count = ff_tget_short(&s->gb, s->le);
1074 if (s->geotag_count > count / 4 - 1) {
1075 s->geotag_count = count / 4 - 1;
1076 av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
1078 if ( bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4
1079 || s->geotag_count == 0) {
1080 s->geotag_count = 0;
1083 s->geotags = av_mallocz_array(s->geotag_count, sizeof(TiffGeoTag));
1085 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1086 s->geotag_count = 0;
1089 for (i = 0; i < s->geotag_count; i++) {
1090 s->geotags[i].key = ff_tget_short(&s->gb, s->le);
1091 s->geotags[i].type = ff_tget_short(&s->gb, s->le);
1092 s->geotags[i].count = ff_tget_short(&s->gb, s->le);
1094 if (!s->geotags[i].type)
1095 s->geotags[i].val = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));
1097 s->geotags[i].offset = ff_tget_short(&s->gb, s->le);
1100 case TIFF_GEO_DOUBLE_PARAMS:
1101 if (count >= INT_MAX / sizeof(int64_t))
1102 return AVERROR_INVALIDDATA;
1103 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
1104 return AVERROR_INVALIDDATA;
1105 dp = av_malloc_array(count, sizeof(double));
1107 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1110 for (i = 0; i < count; i++)
1111 dp[i] = ff_tget_double(&s->gb, s->le);
1112 for (i = 0; i < s->geotag_count; i++) {
1113 if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
1114 if (s->geotags[i].count == 0
1115 || s->geotags[i].offset + s->geotags[i].count > count) {
1116 av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1117 } else if (s->geotags[i].val) {
1118 av_log(s->avctx, AV_LOG_WARNING, "Duplicate GeoTIFF key %d\n", s->geotags[i].key);
1120 char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
1122 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1124 return AVERROR(ENOMEM);
1126 s->geotags[i].val = ap;
1132 case TIFF_GEO_ASCII_PARAMS:
1133 pos = bytestream2_tell(&s->gb);
1134 for (i = 0; i < s->geotag_count; i++) {
1135 if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
1136 if (s->geotags[i].count == 0
1137 || s->geotags[i].offset + s->geotags[i].count > count) {
1138 av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1142 bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
1143 if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
1144 return AVERROR_INVALIDDATA;
1145 if (s->geotags[i].val)
1146 return AVERROR_INVALIDDATA;
1147 ap = av_malloc(s->geotags[i].count);
1149 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1150 return AVERROR(ENOMEM);
1152 bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
1153 ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
1154 s->geotags[i].val = ap;
1160 ADD_METADATA(count, "artist", NULL);
1162 case TIFF_COPYRIGHT:
1163 ADD_METADATA(count, "copyright", NULL);
1166 ADD_METADATA(count, "date", NULL);
1168 case TIFF_DOCUMENT_NAME:
1169 ADD_METADATA(count, "document_name", NULL);
1171 case TIFF_HOST_COMPUTER:
1172 ADD_METADATA(count, "computer", NULL);
1174 case TIFF_IMAGE_DESCRIPTION:
1175 ADD_METADATA(count, "description", NULL);
1178 ADD_METADATA(count, "make", NULL);
1181 ADD_METADATA(count, "model", NULL);
1183 case TIFF_PAGE_NAME:
1184 ADD_METADATA(count, "page_name", NULL);
1186 case TIFF_PAGE_NUMBER:
1187 ADD_METADATA(count, "page_number", " / ");
1189 case TIFF_SOFTWARE_NAME:
1190 ADD_METADATA(count, "software", NULL);
1193 if (s->avctx->err_recognition & AV_EF_EXPLODE) {
1194 av_log(s->avctx, AV_LOG_ERROR,
1195 "Unknown or unsupported tag %d/0X%0X\n",
1197 return AVERROR_INVALIDDATA;
1202 av_log(s->avctx, AV_LOG_ERROR,
1203 "This format is not supported (bpp=%d, %d components)\n",
1206 return AVERROR_INVALIDDATA;
1208 bytestream2_seek(&s->gb, start, SEEK_SET);
1212 static int decode_frame(AVCodecContext *avctx,
1213 void *data, int *got_frame, AVPacket *avpkt)
1215 TiffContext *const s = avctx->priv_data;
1216 AVFrame *const p = data;
1217 ThreadFrame frame = { .f = data };
1219 int le, ret, plane, planes;
1220 int i, j, entries, stride;
1221 unsigned soff, ssize;
1223 GetByteContext stripsizes;
1224 GetByteContext stripdata;
1226 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1228 // parse image header
1229 if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {
1230 av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");
1232 } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1233 av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1234 return AVERROR_INVALIDDATA;
1237 // TIFF_BPP is not a required tag and defaults to 1
1238 s->bppcount = s->bpp = 1;
1239 s->photometric = TIFF_PHOTOMETRIC_NONE;
1240 s->compr = TIFF_RAW;
1244 // Reset these offsets so we can tell if they were set this frame
1245 s->stripsizesoff = s->strippos = 0;
1246 /* parse image file directory */
1247 bytestream2_seek(&s->gb, off, SEEK_SET);
1248 entries = ff_tget_short(&s->gb, le);
1249 if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1250 return AVERROR_INVALIDDATA;
1251 for (i = 0; i < entries; i++) {
1252 if ((ret = tiff_decode_tag(s, p)) < 0)
1256 for (i = 0; i<s->geotag_count; i++) {
1257 const char *keyname = get_geokey_name(s->geotags[i].key);
1259 av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1262 if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1263 av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1266 ret = av_dict_set(&p->metadata, keyname, s->geotags[i].val, 0);
1268 av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1273 if (!s->strippos && !s->stripoff) {
1274 av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1275 return AVERROR_INVALIDDATA;
1277 /* now we have the data and may start decoding */
1278 if ((ret = init_image(s, &frame)) < 0)
1281 if (s->strips == 1 && !s->stripsize) {
1282 av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1283 s->stripsize = avpkt->size - s->stripoff;
1286 if (s->stripsizesoff) {
1287 if (s->stripsizesoff >= (unsigned)avpkt->size)
1288 return AVERROR_INVALIDDATA;
1289 bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
1290 avpkt->size - s->stripsizesoff);
1293 if (s->strippos >= (unsigned)avpkt->size)
1294 return AVERROR_INVALIDDATA;
1295 bytestream2_init(&stripdata, avpkt->data + s->strippos,
1296 avpkt->size - s->strippos);
1299 if (s->rps <= 0 || s->rps % s->subsampling[1]) {
1300 av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1301 return AVERROR_INVALIDDATA;
1304 planes = s->planar ? s->bppcount : 1;
1305 for (plane = 0; plane < planes; plane++) {
1306 stride = p->linesize[plane];
1307 dst = p->data[plane];
1308 for (i = 0; i < s->height; i += s->rps) {
1309 if (s->stripsizesoff)
1310 ssize = ff_tget(&stripsizes, s->sstype, le);
1312 ssize = s->stripsize;
1315 soff = ff_tget(&stripdata, s->sot, le);
1319 if (soff > avpkt->size || ssize > avpkt->size - soff) {
1320 av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1321 return AVERROR_INVALIDDATA;
1323 if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,
1324 FFMIN(s->rps, s->height - i))) < 0) {
1325 if (avctx->err_recognition & AV_EF_EXPLODE)
1329 dst += s->rps * stride;
1331 if (s->predictor == 2) {
1332 if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {
1333 av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");
1334 return AVERROR_PATCHWELCOME;
1336 dst = p->data[plane];
1339 soff = FFMAX(soff / s->bppcount, 1);
1340 ssize = s->width * soff;
1341 if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1342 s->avctx->pix_fmt == AV_PIX_FMT_RGBA64LE ||
1343 s->avctx->pix_fmt == AV_PIX_FMT_GRAY16LE ||
1344 s->avctx->pix_fmt == AV_PIX_FMT_YA16LE ||
1345 s->avctx->pix_fmt == AV_PIX_FMT_GBRP16LE ||
1346 s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16LE) {
1347 for (i = 0; i < s->height; i++) {
1348 for (j = soff; j < ssize; j += 2)
1349 AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1352 } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1353 s->avctx->pix_fmt == AV_PIX_FMT_RGBA64BE ||
1354 s->avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1355 s->avctx->pix_fmt == AV_PIX_FMT_YA16BE ||
1356 s->avctx->pix_fmt == AV_PIX_FMT_GBRP16BE ||
1357 s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16BE) {
1358 for (i = 0; i < s->height; i++) {
1359 for (j = soff; j < ssize; j += 2)
1360 AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1364 for (i = 0; i < s->height; i++) {
1365 for (j = soff; j < ssize; j++)
1366 dst[j] += dst[j - soff];
1372 if (s->photometric == TIFF_PHOTOMETRIC_WHITE_IS_ZERO) {
1373 int c = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255);
1374 dst = p->data[plane];
1375 for (i = 0; i < s->height; i++) {
1376 for (j = 0; j < stride; j++)
1377 dst[j] = c - dst[j];
1383 if (s->planar && s->bppcount > 2) {
1384 FFSWAP(uint8_t*, p->data[0], p->data[2]);
1385 FFSWAP(int, p->linesize[0], p->linesize[2]);
1386 FFSWAP(uint8_t*, p->data[0], p->data[1]);
1387 FFSWAP(int, p->linesize[0], p->linesize[1]);
1395 static av_cold int tiff_init(AVCodecContext *avctx)
1397 TiffContext *s = avctx->priv_data;
1402 s->subsampling[1] = 1;
1404 ff_lzw_decode_open(&s->lzw);
1405 ff_ccitt_unpack_init();
1410 static av_cold int tiff_end(AVCodecContext *avctx)
1412 TiffContext *const s = avctx->priv_data;
1416 ff_lzw_decode_close(&s->lzw);
1417 av_freep(&s->deinvert_buf);
1418 s->deinvert_buf_size = 0;
1419 av_freep(&s->fax_buffer);
1420 s->fax_buffer_size = 0;
1424 AVCodec ff_tiff_decoder = {
1426 .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1427 .type = AVMEDIA_TYPE_VIDEO,
1428 .id = AV_CODEC_ID_TIFF,
1429 .priv_data_size = sizeof(TiffContext),
1432 .decode = decode_frame,
1433 .init_thread_copy = ONLY_IF_THREADS_ENABLED(tiff_init),
1434 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,