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
28 #include "bytestream.h"
35 #include "tiff_data.h"
37 #include "libavutil/common.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/imgutils.h"
40 #include "libavutil/avstring.h"
42 typedef struct TiffContext {
43 AVCodecContext *avctx;
48 unsigned int bpp, bppcount;
49 uint32_t palette[256];
58 int strips, rps, sstype;
60 int stripsizesoff, stripsize, stripoff, strippos;
67 static unsigned tget_short(GetByteContext *gb, int le)
69 unsigned v = le ? bytestream2_get_le16u(gb) : bytestream2_get_be16u(gb);
73 static unsigned tget_long(GetByteContext *gb, int le)
75 unsigned v = le ? bytestream2_get_le32u(gb) : bytestream2_get_be32u(gb);
79 static double tget_double(GetByteContext *gb, int le)
81 av_alias64 i = { .u64 = le ? bytestream2_get_le64u(gb) : bytestream2_get_be64u(gb)};
85 static unsigned tget(GetByteContext *gb, int type, int le)
88 case TIFF_BYTE : return bytestream2_get_byteu(gb);
89 case TIFF_SHORT: return tget_short(gb, le);
90 case TIFF_LONG : return tget_long(gb, le);
91 default : return UINT_MAX;
95 static void free_geotags(TiffContext *const s)
98 for (i = 0; i < s->geotag_count; i++) {
99 if (s->geotags[i].val)
100 av_freep(&s->geotags[i].val);
102 av_freep(&s->geotags);
105 #define RET_GEOKEY(TYPE, array, element)\
106 if (key >= TIFF_##TYPE##_KEY_ID_OFFSET &&\
107 key - TIFF_##TYPE##_KEY_ID_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_name_type_map))\
108 return ff_tiff_##array##_name_type_map[key - TIFF_##TYPE##_KEY_ID_OFFSET].element;
110 static const char *get_geokey_name(int key)
112 RET_GEOKEY(VERT, vert, name);
113 RET_GEOKEY(PROJ, proj, name);
114 RET_GEOKEY(GEOG, geog, name);
115 RET_GEOKEY(CONF, conf, name);
120 static int get_geokey_type(int key)
122 RET_GEOKEY(VERT, vert, type);
123 RET_GEOKEY(PROJ, proj, type);
124 RET_GEOKEY(GEOG, geog, type);
125 RET_GEOKEY(CONF, conf, type);
127 return AVERROR_INVALIDDATA;
130 static int cmp_id_key(const void *id, const void *k)
132 return *(const int*)id - ((const TiffGeoTagKeyName*)k)->key;
135 static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)
137 return ((TiffGeoTagKeyName*)bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key))->name;
140 static char *get_geokey_val(int key, int val)
144 if (val == TIFF_GEO_KEY_UNDEFINED)
145 return av_strdup("undefined");
146 if (val == TIFF_GEO_KEY_USER_DEFINED)
147 return av_strdup("User-Defined");
149 #define RET_GEOKEY_VAL(TYPE, array)\
150 if (val >= TIFF_##TYPE##_OFFSET &&\
151 val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\
152 return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);
155 case TIFF_GT_MODEL_TYPE_GEOKEY:
156 RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);
158 case TIFF_GT_RASTER_TYPE_GEOKEY:
159 RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);
161 case TIFF_GEOG_LINEAR_UNITS_GEOKEY:
162 case TIFF_PROJ_LINEAR_UNITS_GEOKEY:
163 case TIFF_VERTICAL_UNITS_GEOKEY:
164 RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);
166 case TIFF_GEOG_ANGULAR_UNITS_GEOKEY:
167 case TIFF_GEOG_AZIMUTH_UNITS_GEOKEY:
168 RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);
170 case TIFF_GEOGRAPHIC_TYPE_GEOKEY:
171 RET_GEOKEY_VAL(GCS_TYPE, gcs_type);
172 RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);
174 case TIFF_GEOG_GEODETIC_DATUM_GEOKEY:
175 RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);
176 RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);
178 case TIFF_GEOG_ELLIPSOID_GEOKEY:
179 RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);
181 case TIFF_GEOG_PRIME_MERIDIAN_GEOKEY:
182 RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);
184 case TIFF_PROJECTED_CS_TYPE_GEOKEY:
185 return av_strdup(search_keyval(ff_tiff_proj_cs_type_codes, FF_ARRAY_ELEMS(ff_tiff_proj_cs_type_codes), val));
187 case TIFF_PROJECTION_GEOKEY:
188 return av_strdup(search_keyval(ff_tiff_projection_codes, FF_ARRAY_ELEMS(ff_tiff_projection_codes), val));
190 case TIFF_PROJ_COORD_TRANS_GEOKEY:
191 RET_GEOKEY_VAL(COORD_TRANS, coord_trans);
193 case TIFF_VERTICAL_CS_TYPE_GEOKEY:
194 RET_GEOKEY_VAL(VERT_CS, vert_cs);
195 RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);
202 snprintf(ap, 14, "Unknown-%d", val);
206 static char *doubles2str(double *dp, int count, const char *sep)
210 if (!sep) sep = ", ";
211 ap = av_malloc((15 + strlen(sep)) * count);
216 for (i = 0; i < count; i++) {
217 int l = snprintf(ap, 15 + strlen(sep), "%f%s", dp[i], sep);
220 ap0[strlen(ap0) - strlen(sep)] = '\0';
224 static char *shorts2str(int16_t *sp, int count, const char *sep)
228 if (!sep) sep = ", ";
229 ap = av_malloc((5 + strlen(sep)) * count);
234 for (i = 0; i < count; i++) {
235 int l = snprintf(ap, 5 + strlen(sep), "%d%s", sp[i], sep);
238 ap0[strlen(ap0) - strlen(sep)] = '\0';
242 static int add_doubles_metadata(int count,
243 const char *name, const char *sep,
250 if (count >= INT_MAX / sizeof(int64_t))
251 return AVERROR_INVALIDDATA;
252 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
253 return AVERROR_INVALIDDATA;
255 dp = av_malloc(count * sizeof(double));
257 return AVERROR(ENOMEM);
259 for (i = 0; i < count; i++)
260 dp[i] = tget_double(&s->gb, s->le);
261 ap = doubles2str(dp, count, sep);
264 return AVERROR(ENOMEM);
265 av_dict_set(&s->picture.metadata, name, ap, AV_DICT_DONT_STRDUP_VAL);
269 static int add_shorts_metadata(int count, const char *name,
270 const char *sep, TiffContext *s)
276 if (count >= INT_MAX / sizeof(int16_t))
277 return AVERROR_INVALIDDATA;
278 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int16_t))
279 return AVERROR_INVALIDDATA;
281 sp = av_malloc(count * sizeof(int16_t));
283 return AVERROR(ENOMEM);
285 for (i = 0; i < count; i++)
286 sp[i] = tget_short(&s->gb, s->le);
287 ap = shorts2str(sp, count, sep);
290 return AVERROR(ENOMEM);
291 av_dict_set(&s->picture.metadata, name, ap, AV_DICT_DONT_STRDUP_VAL);
295 static int add_string_metadata(int count, const char *name,
300 if (bytestream2_get_bytes_left(&s->gb) < count)
301 return AVERROR_INVALIDDATA;
303 value = av_malloc(count + 1);
305 return AVERROR(ENOMEM);
307 bytestream2_get_bufferu(&s->gb, value, count);
310 av_dict_set(&s->picture.metadata, name, value, AV_DICT_DONT_STRDUP_VAL);
314 static int add_metadata(int count, int type,
315 const char *name, const char *sep, TiffContext *s)
318 case TIFF_DOUBLE: return add_doubles_metadata(count, name, sep, s);
319 case TIFF_SHORT : return add_shorts_metadata(count, name, sep, s);
320 case TIFF_STRING: return add_string_metadata(count, name, s);
321 default : return AVERROR_INVALIDDATA;
326 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
329 z_stream zstream = { 0 };
332 zstream.next_in = src;
333 zstream.avail_in = size;
334 zstream.next_out = dst;
335 zstream.avail_out = *len;
336 zret = inflateInit(&zstream);
338 av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
341 zret = inflate(&zstream, Z_SYNC_FLUSH);
342 inflateEnd(&zstream);
343 *len = zstream.total_out;
344 return zret == Z_STREAM_END ? Z_OK : zret;
348 static void av_always_inline horizontal_fill(unsigned int bpp, uint8_t* dst,
349 int usePtr, const uint8_t *src,
350 uint8_t c, int width, int offset)
354 while (--width >= 0) {
355 dst[(width+offset)*8+7] = (usePtr ? src[width] : c) & 0x1;
356 dst[(width+offset)*8+6] = (usePtr ? src[width] : c) >> 1 & 0x1;
357 dst[(width+offset)*8+5] = (usePtr ? src[width] : c) >> 2 & 0x1;
358 dst[(width+offset)*8+4] = (usePtr ? src[width] : c) >> 3 & 0x1;
359 dst[(width+offset)*8+3] = (usePtr ? src[width] : c) >> 4 & 0x1;
360 dst[(width+offset)*8+2] = (usePtr ? src[width] : c) >> 5 & 0x1;
361 dst[(width+offset)*8+1] = (usePtr ? src[width] : c) >> 6 & 0x1;
362 dst[(width+offset)*8+0] = (usePtr ? src[width] : c) >> 7;
366 while (--width >= 0) {
367 dst[(width+offset)*4+3] = (usePtr ? src[width] : c) & 0x3;
368 dst[(width+offset)*4+2] = (usePtr ? src[width] : c) >> 2 & 0x3;
369 dst[(width+offset)*4+1] = (usePtr ? src[width] : c) >> 4 & 0x3;
370 dst[(width+offset)*4+0] = (usePtr ? src[width] : c) >> 6;
374 while (--width >= 0) {
375 dst[(width+offset)*2+1] = (usePtr ? src[width] : c) & 0xF;
376 dst[(width+offset)*2+0] = (usePtr ? src[width] : c) >> 4;
381 memcpy(dst + offset, src, width);
383 memset(dst + offset, c, width);
388 static int tiff_unpack_strip(TiffContext *s, uint8_t *dst, int stride,
389 const uint8_t *src, int size, int lines)
391 int c, line, pixels, code;
392 const uint8_t *ssrc = src;
393 int width = ((s->width * s->bpp) + 7) >> 3;
396 return AVERROR_INVALIDDATA;
399 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
401 unsigned long outlen;
403 outlen = width * lines;
404 zbuf = av_malloc(outlen);
406 return AVERROR(ENOMEM);
407 ret = tiff_uncompress(zbuf, &outlen, src, size);
409 av_log(s->avctx, AV_LOG_ERROR,
410 "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
411 (unsigned long)width * lines, ret);
416 for (line = 0; line < lines; line++) {
417 if(s->bpp < 8 && s->avctx->pix_fmt == PIX_FMT_PAL8){
418 horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
420 memcpy(dst, src, width);
429 if (s->compr == TIFF_LZW) {
430 if (ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF) < 0) {
431 av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
435 if (s->compr == TIFF_CCITT_RLE || s->compr == TIFF_G3
436 || s->compr == TIFF_G4) {
438 uint8_t *src2 = av_malloc((unsigned)size +
439 FF_INPUT_BUFFER_PADDING_SIZE);
442 av_log(s->avctx, AV_LOG_ERROR,
443 "Error allocating temporary buffer\n");
444 return AVERROR(ENOMEM);
446 if (s->fax_opts & 2) {
447 av_log(s->avctx, AV_LOG_ERROR,
448 "Uncompressed fax mode is not supported (yet)\n");
452 if (!s->fill_order) {
453 memcpy(src2, src, size);
455 for (i = 0; i < size; i++)
456 src2[i] = av_reverse[src[i]];
458 memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
463 ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
464 s->compr, s->fax_opts);
467 if (s->bpp < 8 && s->avctx->pix_fmt == PIX_FMT_PAL8)
468 for (line = 0; line < lines; line++) {
469 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
475 for (line = 0; line < lines; line++) {
476 if (src - ssrc > size) {
477 av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
482 if (ssrc + size - src < width)
483 return AVERROR_INVALIDDATA;
484 if (!s->fill_order) {
485 horizontal_fill(s->bpp * (s->avctx->pix_fmt == PIX_FMT_PAL8),
486 dst, 1, src, 0, width, 0);
489 for (i = 0; i < width; i++)
490 dst[i] = av_reverse[src[i]];
495 for (pixels = 0; pixels < width;) {
496 if (ssrc + size - src < 2) {
497 av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
498 return AVERROR_INVALIDDATA;
500 code = (int8_t) * src++;
503 if (pixels + code > width) {
504 av_log(s->avctx, AV_LOG_ERROR,
505 "Copy went out of bounds\n");
508 if (ssrc + size - src < code) {
509 av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
510 return AVERROR_INVALIDDATA;
512 horizontal_fill(s->bpp * (s->avctx->pix_fmt == PIX_FMT_PAL8),
513 dst, 1, src, 0, code, pixels);
516 } else if (code != -128) { // -127..-1
518 if (pixels + code > width) {
519 av_log(s->avctx, AV_LOG_ERROR,
520 "Run went out of bounds\n");
524 horizontal_fill(s->bpp * (s->avctx->pix_fmt == PIX_FMT_PAL8),
525 dst, 0, NULL, c, code, pixels);
531 pixels = ff_lzw_decode(s->lzw, dst, width);
532 if (pixels < width) {
533 av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
537 if (s->bpp < 8 && s->avctx->pix_fmt == PIX_FMT_PAL8)
538 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
546 static int init_image(TiffContext *s)
551 switch (s->bpp * 10 + s->bppcount) {
553 if (!s->palette_is_set) {
554 s->avctx->pix_fmt = PIX_FMT_MONOBLACK;
560 s->avctx->pix_fmt = PIX_FMT_PAL8;
563 s->avctx->pix_fmt = PIX_FMT_RGB24;
566 s->avctx->pix_fmt = s->le ? PIX_FMT_GRAY16LE : PIX_FMT_GRAY16BE;
569 s->avctx->pix_fmt = PIX_FMT_GRAY8A;
572 s->avctx->pix_fmt = PIX_FMT_RGBA;
575 s->avctx->pix_fmt = s->le ? PIX_FMT_RGB48LE : PIX_FMT_RGB48BE;
578 s->avctx->pix_fmt = s->le ? PIX_FMT_RGBA64LE : PIX_FMT_RGBA64BE;
581 av_log(s->avctx, AV_LOG_ERROR,
582 "This format is not supported (bpp=%d, bppcount=%d)\n",
583 s->bpp, s->bppcount);
584 return AVERROR_INVALIDDATA;
586 if (s->width != s->avctx->width || s->height != s->avctx->height) {
587 if ((ret = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)
589 avcodec_set_dimensions(s->avctx, s->width, s->height);
591 if (s->picture.data[0])
592 s->avctx->release_buffer(s->avctx, &s->picture);
593 if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0) {
594 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
597 if (s->avctx->pix_fmt == PIX_FMT_PAL8) {
598 if (s->palette_is_set) {
599 memcpy(s->picture.data[1], s->palette, sizeof(s->palette));
601 /* make default grayscale pal */
602 pal = (uint32_t *) s->picture.data[1];
603 for (i = 0; i < 1<<s->bpp; i++)
604 pal[i] = 0xFF << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
610 static int tiff_decode_tag(TiffContext *s)
612 unsigned tag, type, count, off, value = 0;
613 int i, j, k, pos, start;
618 tag = tget_short(&s->gb, s->le);
619 type = tget_short(&s->gb, s->le);
620 count = tget_long(&s->gb, s->le);
621 off = tget_long(&s->gb, s->le);
622 start = bytestream2_tell(&s->gb);
624 if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
625 av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
634 bytestream2_seek(&s->gb, -4, SEEK_CUR);
635 value = tget(&s->gb, type, s->le);
642 bytestream2_seek(&s->gb, -4, SEEK_CUR);
647 bytestream2_seek(&s->gb, off, SEEK_SET);
650 if (count <= 4 && type_sizes[type] * count <= 4) {
651 bytestream2_seek(&s->gb, -4, SEEK_CUR);
653 bytestream2_seek(&s->gb, off, SEEK_SET);
667 av_log(s->avctx, AV_LOG_ERROR,
668 "This format is not supported (bpp=%d, %d components)\n",
677 s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
678 ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
683 if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
685 for (i = 0; i < count; i++)
686 s->bpp += tget(&s->gb, type, s->le);
693 case TIFF_SAMPLES_PER_PIXEL:
695 av_log(s->avctx, AV_LOG_ERROR,
696 "Samples per pixel requires a single value, many provided\n");
697 return AVERROR_INVALIDDATA;
699 if (s->bppcount == 1)
717 case TIFF_ADOBE_DEFLATE:
721 av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
726 av_log(s->avctx, AV_LOG_ERROR,
727 "JPEG compression is not supported\n");
730 av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
735 case TIFF_ROWSPERSTRIP:
736 if (type == TIFF_LONG && value == UINT_MAX)
737 value = s->avctx->height;
739 av_log(s->avctx, AV_LOG_ERROR,
740 "Incorrect value of rows per strip\n");
745 case TIFF_STRIP_OFFS:
755 if (s->strippos > bytestream2_size(&s->gb)) {
756 av_log(s->avctx, AV_LOG_ERROR,
757 "Tag referencing position outside the image\n");
761 case TIFF_STRIP_SIZE:
763 s->stripsizesoff = 0;
764 s->stripsize = value;
767 s->stripsizesoff = off;
771 if (s->stripsizesoff > bytestream2_size(&s->gb)) {
772 av_log(s->avctx, AV_LOG_ERROR,
773 "Tag referencing position outside the image\n");
777 case TIFF_TILE_BYTE_COUNTS:
778 case TIFF_TILE_LENGTH:
779 case TIFF_TILE_OFFSETS:
780 case TIFF_TILE_WIDTH:
781 av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
782 return AVERROR_PATCHWELCOME;
785 s->predictor = value;
799 av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
804 case TIFF_FILL_ORDER:
805 if (value < 1 || value > 2) {
806 av_log(s->avctx, AV_LOG_ERROR,
807 "Unknown FillOrder value %d, trying default one\n", value);
810 s->fill_order = value - 1;
813 pal = (uint32_t *) s->palette;
814 off = type_sizes[type];
815 if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
817 off = (type_sizes[type] - 1) << 3;
818 for (k = 2; k >= 0; k--) {
819 for (i = 0; i < count / 3; i++) {
822 j = (tget(&s->gb, type, s->le) >> off) << (k * 8);
826 s->palette_is_set = 1;
830 av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
835 if (s->compr == TIFF_G3)
839 if (s->compr == TIFF_G4)
842 #define ADD_METADATA(count, name, sep)\
843 if (ret = add_metadata(count, type, name, sep, s) < 0) {\
844 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
847 case TIFF_MODEL_PIXEL_SCALE:
848 ADD_METADATA(count, "ModelPixelScaleTag", NULL);
850 case TIFF_MODEL_TRANSFORMATION:
851 ADD_METADATA(count, "ModelTransformationTag", NULL);
853 case TIFF_MODEL_TIEPOINT:
854 ADD_METADATA(count, "ModelTiepointTag", NULL);
856 case TIFF_GEO_KEY_DIRECTORY:
857 ADD_METADATA(1, "GeoTIFF_Version", NULL);
858 ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
859 s->geotag_count = tget_short(&s->gb, s->le);
860 if (s->geotag_count > count / 4 - 1) {
861 s->geotag_count = count / 4 - 1;
862 av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
864 if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4)
866 s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);
868 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
869 return AVERROR(ENOMEM);
871 for (i = 0; i < s->geotag_count; i++) {
872 s->geotags[i].key = tget_short(&s->gb, s->le);
873 s->geotags[i].type = tget_short(&s->gb, s->le);
874 s->geotags[i].count = tget_short(&s->gb, s->le);
876 if (!s->geotags[i].type)
877 s->geotags[i].val = get_geokey_val(s->geotags[i].key, tget_short(&s->gb, s->le));
879 s->geotags[i].offset = tget_short(&s->gb, s->le);
882 case TIFF_GEO_DOUBLE_PARAMS:
883 if (count >= INT_MAX / sizeof(int64_t))
884 return AVERROR_INVALIDDATA;
885 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
886 return AVERROR_INVALIDDATA;
887 dp = av_malloc(count * sizeof(double));
889 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
890 return AVERROR(ENOMEM);
892 for (i = 0; i < count; i++)
893 dp[i] = tget_double(&s->gb, s->le);
894 for (i = 0; i < s->geotag_count; i++) {
895 if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
896 if (s->geotags[i].count == 0
897 || s->geotags[i].offset + s->geotags[i].count > count) {
898 av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
900 char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
902 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
904 return AVERROR(ENOMEM);
906 s->geotags[i].val = ap;
912 case TIFF_GEO_ASCII_PARAMS:
913 pos = bytestream2_tell(&s->gb);
914 for (i = 0; i < s->geotag_count; i++) {
915 if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
916 if (s->geotags[i].count == 0
917 || s->geotags[i].offset + s->geotags[i].count > count) {
918 av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
922 bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
923 if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
925 ap = av_malloc(s->geotags[i].count);
927 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
928 return AVERROR(ENOMEM);
930 bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
931 ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
932 s->geotags[i].val = ap;
938 ADD_METADATA(count, "artist", NULL);
941 ADD_METADATA(count, "copyright", NULL);
944 ADD_METADATA(count, "date", NULL);
946 case TIFF_DOCUMENT_NAME:
947 ADD_METADATA(count, "document_name", NULL);
949 case TIFF_HOST_COMPUTER:
950 ADD_METADATA(count, "computer", NULL);
952 case TIFF_IMAGE_DESCRIPTION:
953 ADD_METADATA(count, "description", NULL);
956 ADD_METADATA(count, "make", NULL);
959 ADD_METADATA(count, "model", NULL);
962 ADD_METADATA(count, "page_name", NULL);
964 case TIFF_PAGE_NUMBER:
965 ADD_METADATA(count, "page_number", " / ");
967 case TIFF_SOFTWARE_NAME:
968 ADD_METADATA(count, "software", NULL);
971 av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
974 bytestream2_seek(&s->gb, start, SEEK_SET);
978 static int decode_frame(AVCodecContext *avctx,
979 void *data, int *data_size, AVPacket *avpkt)
981 TiffContext *const s = avctx->priv_data;
982 AVFrame *picture = data;
983 AVFrame *const p = &s->picture;
988 unsigned soff, ssize;
990 GetByteContext stripsizes;
991 GetByteContext stripdata;
993 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
997 return AVERROR_INVALIDDATA;
998 id = bytestream2_get_le16u(&s->gb);
1001 else if (id == 0x4D4D)
1004 av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");
1009 s->compr = TIFF_RAW;
1012 /* free existing metadata */
1013 av_dict_free(&s->picture.metadata);
1015 // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
1016 // that further identifies the file as a TIFF file"
1017 if (tget_short(&s->gb, le) != 42) {
1018 av_log(avctx, AV_LOG_ERROR,
1019 "The answer to life, universe and everything is not correct!\n");
1022 // Reset these offsets so we can tell if they were set this frame
1023 s->stripsizesoff = s->strippos = 0;
1024 /* parse image file directory */
1025 off = tget_long(&s->gb, le);
1026 if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1027 av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1028 return AVERROR_INVALIDDATA;
1030 bytestream2_seek(&s->gb, off, SEEK_SET);
1031 entries = tget_short(&s->gb, le);
1032 if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1033 return AVERROR_INVALIDDATA;
1034 for (i = 0; i < entries; i++) {
1035 if (tiff_decode_tag(s) < 0)
1039 for (i = 0; i<s->geotag_count; i++) {
1040 const char *keyname = get_geokey_name(s->geotags[i].key);
1042 av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1045 if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1046 av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1049 ret = av_dict_set(&s->picture.metadata, keyname, s->geotags[i].val, 0);
1051 av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1056 if (!s->strippos && !s->stripoff) {
1057 av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1060 /* now we have the data and may start decoding */
1061 if ((ret = init_image(s)) < 0)
1064 if (s->strips == 1 && !s->stripsize) {
1065 av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1066 s->stripsize = avpkt->size - s->stripoff;
1068 stride = p->linesize[0];
1071 if (s->stripsizesoff) {
1072 if (s->stripsizesoff >= avpkt->size)
1073 return AVERROR_INVALIDDATA;
1074 bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, avpkt->size - s->stripsizesoff);
1077 if (s->strippos >= avpkt->size)
1078 return AVERROR_INVALIDDATA;
1079 bytestream2_init(&stripdata, avpkt->data + s->strippos, avpkt->size - s->strippos);
1082 for (i = 0; i < s->height; i += s->rps) {
1083 if (s->stripsizesoff)
1084 ssize = tget(&stripsizes, s->sstype, s->le);
1086 ssize = s->stripsize;
1089 soff = tget(&stripdata, s->sot, s->le);
1093 if (soff > avpkt->size || ssize > avpkt->size - soff) {
1094 av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1097 if (tiff_unpack_strip(s, dst, stride, avpkt->data + soff, ssize,
1098 FFMIN(s->rps, s->height - i)) < 0)
1100 dst += s->rps * stride;
1102 if (s->predictor == 2) {
1105 ssize = s->width * soff;
1106 if (s->avctx->pix_fmt == PIX_FMT_RGB48LE ||
1107 s->avctx->pix_fmt == PIX_FMT_RGBA64LE) {
1108 for (i = 0; i < s->height; i++) {
1109 for (j = soff; j < ssize; j += 2)
1110 AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1113 } else if (s->avctx->pix_fmt == PIX_FMT_RGB48BE ||
1114 s->avctx->pix_fmt == PIX_FMT_RGBA64BE) {
1115 for (i = 0; i < s->height; i++) {
1116 for (j = soff; j < ssize; j += 2)
1117 AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1121 for (i = 0; i < s->height; i++) {
1122 for (j = soff; j < ssize; j++)
1123 dst[j] += dst[j - soff];
1130 dst = s->picture.data[0];
1131 for (i = 0; i < s->height; i++) {
1132 for (j = 0; j < s->picture.linesize[0]; j++)
1133 dst[j] = (s->avctx->pix_fmt == PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1134 dst += s->picture.linesize[0];
1137 *picture = s->picture;
1138 *data_size = sizeof(AVPicture);
1143 static av_cold int tiff_init(AVCodecContext *avctx)
1145 TiffContext *s = avctx->priv_data;
1150 avcodec_get_frame_defaults(&s->picture);
1151 avctx->coded_frame = &s->picture;
1152 ff_lzw_decode_open(&s->lzw);
1153 ff_ccitt_unpack_init();
1158 static av_cold int tiff_end(AVCodecContext *avctx)
1160 TiffContext *const s = avctx->priv_data;
1163 if (avctx->coded_frame && avctx->coded_frame->metadata)
1164 av_dict_free(&avctx->coded_frame->metadata);
1166 ff_lzw_decode_close(&s->lzw);
1167 if (s->picture.data[0])
1168 avctx->release_buffer(avctx, &s->picture);
1172 AVCodec ff_tiff_decoder = {
1174 .type = AVMEDIA_TYPE_VIDEO,
1175 .id = AV_CODEC_ID_TIFF,
1176 .priv_data_size = sizeof(TiffContext),
1179 .decode = decode_frame,
1180 .capabilities = CODEC_CAP_DR1,
1181 .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),