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 #include "libavutil/attributes.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/imgutils.h"
37 #include "bytestream.h"
43 #include "tiff_data.h"
45 typedef struct TiffContext {
46 AVCodecContext *avctx;
50 unsigned int bpp, bppcount;
51 uint32_t palette[256];
61 int strips, rps, sstype;
63 int stripsizesoff, stripsize, stripoff, strippos;
66 uint8_t *deinvert_buf;
67 int deinvert_buf_size;
73 static unsigned tget_short(GetByteContext *gb, int le)
75 unsigned v = le ? bytestream2_get_le16(gb) : bytestream2_get_be16(gb);
79 static unsigned tget_long(GetByteContext *gb, int le)
81 unsigned v = le ? bytestream2_get_le32(gb) : bytestream2_get_be32(gb);
85 static double tget_double(GetByteContext *gb, int le)
87 av_alias64 i = { .u64 = le ? bytestream2_get_le64(gb) : bytestream2_get_be64(gb)};
91 static unsigned tget(GetByteContext *gb, int type, int le)
95 return bytestream2_get_byte(gb);
97 return tget_short(gb, le);
99 return tget_long(gb, le);
105 static void free_geotags(TiffContext *const s)
108 for (i = 0; i < s->geotag_count; i++) {
109 if (s->geotags[i].val)
110 av_freep(&s->geotags[i].val);
112 av_freep(&s->geotags);
115 #define RET_GEOKEY(TYPE, array, element)\
116 if (key >= TIFF_##TYPE##_KEY_ID_OFFSET &&\
117 key - TIFF_##TYPE##_KEY_ID_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_name_type_map))\
118 return ff_tiff_##array##_name_type_map[key - TIFF_##TYPE##_KEY_ID_OFFSET].element;
120 static const char *get_geokey_name(int key)
122 RET_GEOKEY(VERT, vert, name);
123 RET_GEOKEY(PROJ, proj, name);
124 RET_GEOKEY(GEOG, geog, name);
125 RET_GEOKEY(CONF, conf, name);
130 static int get_geokey_type(int key)
132 RET_GEOKEY(VERT, vert, type);
133 RET_GEOKEY(PROJ, proj, type);
134 RET_GEOKEY(GEOG, geog, type);
135 RET_GEOKEY(CONF, conf, type);
137 return AVERROR_INVALIDDATA;
140 static int cmp_id_key(const void *id, const void *k)
142 return *(const int*)id - ((const TiffGeoTagKeyName*)k)->key;
145 static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)
147 TiffGeoTagKeyName *r = bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key);
154 static char *get_geokey_val(int key, int val)
158 if (val == TIFF_GEO_KEY_UNDEFINED)
159 return av_strdup("undefined");
160 if (val == TIFF_GEO_KEY_USER_DEFINED)
161 return av_strdup("User-Defined");
163 #define RET_GEOKEY_VAL(TYPE, array)\
164 if (val >= TIFF_##TYPE##_OFFSET &&\
165 val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\
166 return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);
169 case TIFF_GT_MODEL_TYPE_GEOKEY:
170 RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);
172 case TIFF_GT_RASTER_TYPE_GEOKEY:
173 RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);
175 case TIFF_GEOG_LINEAR_UNITS_GEOKEY:
176 case TIFF_PROJ_LINEAR_UNITS_GEOKEY:
177 case TIFF_VERTICAL_UNITS_GEOKEY:
178 RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);
180 case TIFF_GEOG_ANGULAR_UNITS_GEOKEY:
181 case TIFF_GEOG_AZIMUTH_UNITS_GEOKEY:
182 RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);
184 case TIFF_GEOGRAPHIC_TYPE_GEOKEY:
185 RET_GEOKEY_VAL(GCS_TYPE, gcs_type);
186 RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);
188 case TIFF_GEOG_GEODETIC_DATUM_GEOKEY:
189 RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);
190 RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);
192 case TIFF_GEOG_ELLIPSOID_GEOKEY:
193 RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);
195 case TIFF_GEOG_PRIME_MERIDIAN_GEOKEY:
196 RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);
198 case TIFF_PROJECTED_CS_TYPE_GEOKEY:
199 ap = av_strdup(search_keyval(ff_tiff_proj_cs_type_codes, FF_ARRAY_ELEMS(ff_tiff_proj_cs_type_codes), val));
202 case TIFF_PROJECTION_GEOKEY:
203 ap = av_strdup(search_keyval(ff_tiff_projection_codes, FF_ARRAY_ELEMS(ff_tiff_projection_codes), val));
206 case TIFF_PROJ_COORD_TRANS_GEOKEY:
207 RET_GEOKEY_VAL(COORD_TRANS, coord_trans);
209 case TIFF_VERTICAL_CS_TYPE_GEOKEY:
210 RET_GEOKEY_VAL(VERT_CS, vert_cs);
211 RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);
218 snprintf(ap, 14, "Unknown-%d", val);
222 static char *doubles2str(double *dp, int count, const char *sep)
226 uint64_t component_len;
227 if (!sep) sep = ", ";
228 component_len = 15LL + strlen(sep);
229 if (count >= (INT_MAX - 1)/component_len)
231 ap = av_malloc(component_len * count + 1);
236 for (i = 0; i < count; i++) {
237 unsigned l = snprintf(ap, component_len, "%f%s", dp[i], sep);
238 if(l >= component_len) {
244 ap0[strlen(ap0) - strlen(sep)] = '\0';
248 static char *shorts2str(int16_t *sp, int count, const char *sep)
252 uint64_t component_len;
253 if (!sep) sep = ", ";
254 component_len = 7LL + strlen(sep);
255 if (count >= (INT_MAX - 1)/component_len)
257 ap = av_malloc(component_len * count + 1);
262 for (i = 0; i < count; i++) {
263 unsigned l = snprintf(ap, component_len, "%d%s", sp[i], sep);
264 if (l >= component_len) {
270 ap0[strlen(ap0) - strlen(sep)] = '\0';
274 static int add_doubles_metadata(int count,
275 const char *name, const char *sep,
276 TiffContext *s, AVFrame *frame)
282 if (count >= INT_MAX / sizeof(int64_t) || count <= 0)
283 return AVERROR_INVALIDDATA;
284 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
285 return AVERROR_INVALIDDATA;
287 dp = av_malloc(count * sizeof(double));
289 return AVERROR(ENOMEM);
291 for (i = 0; i < count; i++)
292 dp[i] = tget_double(&s->gb, s->le);
293 ap = doubles2str(dp, count, sep);
296 return AVERROR(ENOMEM);
297 av_dict_set(avpriv_frame_get_metadatap(frame), name, ap, AV_DICT_DONT_STRDUP_VAL);
301 static int add_shorts_metadata(int count, const char *name,
302 const char *sep, TiffContext *s, AVFrame *frame)
308 if (count >= INT_MAX / sizeof(int16_t) || count <= 0)
309 return AVERROR_INVALIDDATA;
310 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int16_t))
311 return AVERROR_INVALIDDATA;
313 sp = av_malloc(count * sizeof(int16_t));
315 return AVERROR(ENOMEM);
317 for (i = 0; i < count; i++)
318 sp[i] = tget_short(&s->gb, s->le);
319 ap = shorts2str(sp, count, sep);
322 return AVERROR(ENOMEM);
323 av_dict_set(avpriv_frame_get_metadatap(frame), name, ap, AV_DICT_DONT_STRDUP_VAL);
327 static int add_string_metadata(int count, const char *name,
328 TiffContext *s, AVFrame *frame)
332 if (bytestream2_get_bytes_left(&s->gb) < count || count < 0)
333 return AVERROR_INVALIDDATA;
335 value = av_malloc(count + 1);
337 return AVERROR(ENOMEM);
339 bytestream2_get_bufferu(&s->gb, value, count);
342 av_dict_set(avpriv_frame_get_metadatap(frame), name, value, AV_DICT_DONT_STRDUP_VAL);
346 static int add_metadata(int count, int type,
347 const char *name, const char *sep, TiffContext *s, AVFrame *frame)
350 case TIFF_DOUBLE: return add_doubles_metadata(count, name, sep, s, frame);
351 case TIFF_SHORT : return add_shorts_metadata(count, name, sep, s, frame);
352 case TIFF_STRING: return add_string_metadata(count, name, s, frame);
353 default : return AVERROR_INVALIDDATA;
358 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
361 z_stream zstream = { 0 };
364 zstream.next_in = (uint8_t *)src;
365 zstream.avail_in = size;
366 zstream.next_out = dst;
367 zstream.avail_out = *len;
368 zret = inflateInit(&zstream);
370 av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
373 zret = inflate(&zstream, Z_SYNC_FLUSH);
374 inflateEnd(&zstream);
375 *len = zstream.total_out;
376 return zret == Z_STREAM_END ? Z_OK : zret;
380 static void av_always_inline horizontal_fill(unsigned int bpp, uint8_t* dst,
381 int usePtr, const uint8_t *src,
382 uint8_t c, int width, int offset)
386 while (--width >= 0) {
387 dst[(width+offset)*8+7] = (usePtr ? src[width] : c) & 0x1;
388 dst[(width+offset)*8+6] = (usePtr ? src[width] : c) >> 1 & 0x1;
389 dst[(width+offset)*8+5] = (usePtr ? src[width] : c) >> 2 & 0x1;
390 dst[(width+offset)*8+4] = (usePtr ? src[width] : c) >> 3 & 0x1;
391 dst[(width+offset)*8+3] = (usePtr ? src[width] : c) >> 4 & 0x1;
392 dst[(width+offset)*8+2] = (usePtr ? src[width] : c) >> 5 & 0x1;
393 dst[(width+offset)*8+1] = (usePtr ? src[width] : c) >> 6 & 0x1;
394 dst[(width+offset)*8+0] = (usePtr ? src[width] : c) >> 7;
398 while (--width >= 0) {
399 dst[(width+offset)*4+3] = (usePtr ? src[width] : c) & 0x3;
400 dst[(width+offset)*4+2] = (usePtr ? src[width] : c) >> 2 & 0x3;
401 dst[(width+offset)*4+1] = (usePtr ? src[width] : c) >> 4 & 0x3;
402 dst[(width+offset)*4+0] = (usePtr ? src[width] : c) >> 6;
406 while (--width >= 0) {
407 dst[(width+offset)*2+1] = (usePtr ? src[width] : c) & 0xF;
408 dst[(width+offset)*2+0] = (usePtr ? src[width] : c) >> 4;
413 memcpy(dst + offset, src, width);
415 memset(dst + offset, c, width);
420 static int deinvert_buffer(TiffContext *s, const uint8_t *src, int size)
424 av_fast_padded_malloc(&s->deinvert_buf, &s->deinvert_buf_size, size);
425 if (!s->deinvert_buf)
426 return AVERROR(ENOMEM);
427 for (i = 0; i < size; i++)
428 s->deinvert_buf[i] = ff_reverse[src[i]];
433 static int tiff_unpack_strip(TiffContext *s, uint8_t *dst, int stride,
434 const uint8_t *src, int size, int lines)
436 int c, line, pixels, code, ret;
437 const uint8_t *ssrc = src;
438 int width = ((s->width * s->bpp) + 7) >> 3;
441 width /= s->bppcount;
444 return AVERROR_INVALIDDATA;
447 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
449 unsigned long outlen;
451 outlen = width * lines;
452 zbuf = av_malloc(outlen);
454 return AVERROR(ENOMEM);
456 if ((ret = deinvert_buffer(s, src, size)) < 0) {
460 ssrc = src = s->deinvert_buf;
462 ret = tiff_uncompress(zbuf, &outlen, src, size);
464 av_log(s->avctx, AV_LOG_ERROR,
465 "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
466 (unsigned long)width * lines, ret);
468 return AVERROR_UNKNOWN;
471 for (line = 0; line < lines; line++) {
472 if(s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
473 horizontal_fill(s->bpp, dst, 1, src, 0, width, 0);
475 memcpy(dst, src, width);
484 if (s->compr == TIFF_LZW) {
486 if ((ret = deinvert_buffer(s, src, size)) < 0)
488 ssrc = src = s->deinvert_buf;
490 if (size > 1 && !src[0] && (src[1]&1)) {
491 av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");
493 if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {
494 av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
498 if (s->compr == TIFF_CCITT_RLE ||
499 s->compr == TIFF_G3 ||
500 s->compr == TIFF_G4) {
502 uint8_t *src2 = av_malloc((unsigned)size +
503 FF_INPUT_BUFFER_PADDING_SIZE);
506 av_log(s->avctx, AV_LOG_ERROR,
507 "Error allocating temporary buffer\n");
508 return AVERROR(ENOMEM);
510 if (s->fax_opts & 2) {
511 av_log(s->avctx, AV_LOG_ERROR,
512 "Uncompressed fax mode is not supported (yet)\n");
514 return AVERROR_INVALIDDATA;
516 if (!s->fill_order) {
517 memcpy(src2, src, size);
519 for (i = 0; i < size; i++)
520 src2[i] = ff_reverse[src[i]];
522 memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
527 ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
528 s->compr, s->fax_opts);
531 if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
532 for (line = 0; line < lines; line++) {
533 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
539 for (line = 0; line < lines; line++) {
540 if (src - ssrc > size) {
541 av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
542 return AVERROR_INVALIDDATA;
546 if (ssrc + size - src < width)
547 return AVERROR_INVALIDDATA;
548 if (!s->fill_order) {
549 horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
550 dst, 1, src, 0, width, 0);
553 for (i = 0; i < width; i++)
554 dst[i] = ff_reverse[src[i]];
559 for (pixels = 0; pixels < width;) {
560 if (ssrc + size - src < 2) {
561 av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
562 return AVERROR_INVALIDDATA;
564 code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;
567 if (pixels + code > width) {
568 av_log(s->avctx, AV_LOG_ERROR,
569 "Copy went out of bounds\n");
570 return AVERROR_INVALIDDATA;
572 if (ssrc + size - src < code) {
573 av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");
574 return AVERROR_INVALIDDATA;
576 horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
577 dst, 1, src, 0, code, pixels);
580 } else if (code != -128) { // -127..-1
582 if (pixels + code > width) {
583 av_log(s->avctx, AV_LOG_ERROR,
584 "Run went out of bounds\n");
585 return AVERROR_INVALIDDATA;
588 horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),
589 dst, 0, NULL, c, code, pixels);
595 for (i = 0; i < width; i++)
596 dst[i] = ff_reverse[dst[i]];
600 pixels = ff_lzw_decode(s->lzw, dst, width);
601 if (pixels < width) {
602 av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
604 return AVERROR_INVALIDDATA;
606 if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
607 horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);
615 static int init_image(TiffContext *s, AVFrame *frame)
620 switch (s->planar * 1000 + s->bpp * 10 + s->bppcount) {
622 if (!s->palette_is_set) {
623 s->avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
629 s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
632 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
635 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GRAY16LE : AV_PIX_FMT_GRAY16BE;
638 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8A;
641 s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
644 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB48BE;
647 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGBA64BE;
650 s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
653 s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
656 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GBRP16LE : AV_PIX_FMT_GBRP16BE;
659 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GBRAP16LE : AV_PIX_FMT_GBRAP16BE;
662 av_log(s->avctx, AV_LOG_ERROR,
663 "This format is not supported (bpp=%d, bppcount=%d)\n",
664 s->bpp, s->bppcount);
665 return AVERROR_INVALIDDATA;
667 if (s->width != s->avctx->width || s->height != s->avctx->height) {
668 if ((ret = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)
670 avcodec_set_dimensions(s->avctx, s->width, s->height);
672 if ((ret = ff_get_buffer(s->avctx, frame, 0)) < 0)
674 if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
675 if (s->palette_is_set) {
676 memcpy(frame->data[1], s->palette, sizeof(s->palette));
678 /* make default grayscale pal */
679 pal = (uint32_t *) frame->data[1];
680 for (i = 0; i < 1<<s->bpp; i++)
681 pal[i] = 0xFFU << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;
687 static int tiff_decode_tag(TiffContext *s, AVFrame *frame)
689 unsigned tag, type, count, off, value = 0;
690 int i, j, k, pos, start;
695 tag = tget_short(&s->gb, s->le);
696 type = tget_short(&s->gb, s->le);
697 count = tget_long(&s->gb, s->le);
698 off = tget_long(&s->gb, s->le);
699 start = bytestream2_tell(&s->gb);
701 if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
702 av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
711 bytestream2_seek(&s->gb, -4, SEEK_CUR);
712 value = tget(&s->gb, type, s->le);
719 bytestream2_seek(&s->gb, -4, SEEK_CUR);
724 bytestream2_seek(&s->gb, off, SEEK_SET);
727 if (count <= 4 && type_sizes[type] * count <= 4)
728 bytestream2_seek(&s->gb, -4, SEEK_CUR);
730 bytestream2_seek(&s->gb, off, SEEK_SET);
743 av_log(s->avctx, AV_LOG_ERROR,
744 "This format is not supported (bpp=%d, %d components)\n",
746 return AVERROR_INVALIDDATA;
753 s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
754 ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
759 if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)
760 return AVERROR_INVALIDDATA;
761 for (i = 0; i < count; i++)
762 s->bpp += tget(&s->gb, type, s->le);
769 case TIFF_SAMPLES_PER_PIXEL:
771 av_log(s->avctx, AV_LOG_ERROR,
772 "Samples per pixel requires a single value, many provided\n");
773 return AVERROR_INVALIDDATA;
776 av_log(s->avctx, AV_LOG_ERROR,
777 "Samples per pixel %d is too large\n", value);
778 return AVERROR_INVALIDDATA;
780 if (s->bppcount == 1)
798 case TIFF_ADOBE_DEFLATE:
802 av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
803 return AVERROR(ENOSYS);
807 av_log(s->avctx, AV_LOG_ERROR,
808 "JPEG compression is not supported\n");
809 return AVERROR_PATCHWELCOME;
811 av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
813 return AVERROR_INVALIDDATA;
816 case TIFF_ROWSPERSTRIP:
817 if (type == TIFF_LONG && value == UINT_MAX)
820 av_log(s->avctx, AV_LOG_ERROR,
821 "Incorrect value of rows per strip\n");
822 return AVERROR_INVALIDDATA;
826 case TIFF_STRIP_OFFS:
836 if (s->strippos > bytestream2_size(&s->gb)) {
837 av_log(s->avctx, AV_LOG_ERROR,
838 "Tag referencing position outside the image\n");
839 return AVERROR_INVALIDDATA;
842 case TIFF_STRIP_SIZE:
844 s->stripsizesoff = 0;
845 s->stripsize = value;
848 s->stripsizesoff = off;
852 if (s->stripsizesoff > bytestream2_size(&s->gb)) {
853 av_log(s->avctx, AV_LOG_ERROR,
854 "Tag referencing position outside the image\n");
855 return AVERROR_INVALIDDATA;
858 case TIFF_TILE_BYTE_COUNTS:
859 case TIFF_TILE_LENGTH:
860 case TIFF_TILE_OFFSETS:
861 case TIFF_TILE_WIDTH:
862 av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
863 return AVERROR_PATCHWELCOME;
866 s->predictor = value;
880 av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
882 return AVERROR_INVALIDDATA;
885 case TIFF_FILL_ORDER:
886 if (value < 1 || value > 2) {
887 av_log(s->avctx, AV_LOG_ERROR,
888 "Unknown FillOrder value %d, trying default one\n", value);
891 s->fill_order = value - 1;
894 pal = (uint32_t *) s->palette;
895 off = type_sizes[type];
896 if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
897 return AVERROR_INVALIDDATA;
898 off = (type_sizes[type] - 1) << 3;
899 for (k = 2; k >= 0; k--) {
900 for (i = 0; i < count / 3; i++) {
902 pal[i] = 0xFFU << 24;
903 j = (tget(&s->gb, type, s->le) >> off) << (k * 8);
907 s->palette_is_set = 1;
910 s->planar = value == 2;
913 if (s->compr == TIFF_G3)
917 if (s->compr == TIFF_G4)
920 #define ADD_METADATA(count, name, sep)\
921 if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\
922 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
925 case TIFF_MODEL_PIXEL_SCALE:
926 ADD_METADATA(count, "ModelPixelScaleTag", NULL);
928 case TIFF_MODEL_TRANSFORMATION:
929 ADD_METADATA(count, "ModelTransformationTag", NULL);
931 case TIFF_MODEL_TIEPOINT:
932 ADD_METADATA(count, "ModelTiepointTag", NULL);
934 case TIFF_GEO_KEY_DIRECTORY:
935 ADD_METADATA(1, "GeoTIFF_Version", NULL);
936 ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
937 s->geotag_count = tget_short(&s->gb, s->le);
938 if (s->geotag_count > count / 4 - 1) {
939 s->geotag_count = count / 4 - 1;
940 av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
942 if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {
946 s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);
948 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
950 return AVERROR(ENOMEM);
952 for (i = 0; i < s->geotag_count; i++) {
953 s->geotags[i].key = tget_short(&s->gb, s->le);
954 s->geotags[i].type = tget_short(&s->gb, s->le);
955 s->geotags[i].count = tget_short(&s->gb, s->le);
957 if (!s->geotags[i].type)
958 s->geotags[i].val = get_geokey_val(s->geotags[i].key, tget_short(&s->gb, s->le));
960 s->geotags[i].offset = tget_short(&s->gb, s->le);
963 case TIFF_GEO_DOUBLE_PARAMS:
964 if (count >= INT_MAX / sizeof(int64_t))
965 return AVERROR_INVALIDDATA;
966 if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))
967 return AVERROR_INVALIDDATA;
968 dp = av_malloc(count * sizeof(double));
970 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
971 return AVERROR(ENOMEM);
973 for (i = 0; i < count; i++)
974 dp[i] = tget_double(&s->gb, s->le);
975 for (i = 0; i < s->geotag_count; i++) {
976 if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
977 if (s->geotags[i].count == 0
978 || s->geotags[i].offset + s->geotags[i].count > count) {
979 av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
981 char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
983 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
985 return AVERROR(ENOMEM);
987 s->geotags[i].val = ap;
993 case TIFF_GEO_ASCII_PARAMS:
994 pos = bytestream2_tell(&s->gb);
995 for (i = 0; i < s->geotag_count; i++) {
996 if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
997 if (s->geotags[i].count == 0
998 || s->geotags[i].offset + s->geotags[i].count > count) {
999 av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
1003 bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);
1004 if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)
1005 return AVERROR_INVALIDDATA;
1006 ap = av_malloc(s->geotags[i].count);
1008 av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
1009 return AVERROR(ENOMEM);
1011 bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);
1012 ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte
1013 s->geotags[i].val = ap;
1019 ADD_METADATA(count, "artist", NULL);
1021 case TIFF_COPYRIGHT:
1022 ADD_METADATA(count, "copyright", NULL);
1025 ADD_METADATA(count, "date", NULL);
1027 case TIFF_DOCUMENT_NAME:
1028 ADD_METADATA(count, "document_name", NULL);
1030 case TIFF_HOST_COMPUTER:
1031 ADD_METADATA(count, "computer", NULL);
1033 case TIFF_IMAGE_DESCRIPTION:
1034 ADD_METADATA(count, "description", NULL);
1037 ADD_METADATA(count, "make", NULL);
1040 ADD_METADATA(count, "model", NULL);
1042 case TIFF_PAGE_NAME:
1043 ADD_METADATA(count, "page_name", NULL);
1045 case TIFF_PAGE_NUMBER:
1046 ADD_METADATA(count, "page_number", " / ");
1048 case TIFF_SOFTWARE_NAME:
1049 ADD_METADATA(count, "software", NULL);
1052 av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
1055 bytestream2_seek(&s->gb, start, SEEK_SET);
1059 static int decode_frame(AVCodecContext *avctx,
1060 void *data, int *got_frame, AVPacket *avpkt)
1062 TiffContext *const s = avctx->priv_data;
1063 AVFrame *const p = data;
1065 int id, le, ret, plane, planes;
1066 int i, j, entries, stride;
1067 unsigned soff, ssize;
1069 GetByteContext stripsizes;
1070 GetByteContext stripdata;
1072 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1074 // parse image header
1075 if (avpkt->size < 8)
1076 return AVERROR_INVALIDDATA;
1077 id = bytestream2_get_le16u(&s->gb);
1080 else if (id == 0x4D4D)
1083 av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");
1084 return AVERROR_INVALIDDATA;
1087 // TIFF_BPP is not a required tag and defaults to 1
1088 s->bppcount = s->bpp = 1;
1090 s->compr = TIFF_RAW;
1094 // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
1095 // that further identifies the file as a TIFF file"
1096 if (tget_short(&s->gb, le) != 42) {
1097 av_log(avctx, AV_LOG_ERROR,
1098 "The answer to life, universe and everything is not correct!\n");
1099 return AVERROR_INVALIDDATA;
1101 // Reset these offsets so we can tell if they were set this frame
1102 s->stripsizesoff = s->strippos = 0;
1103 /* parse image file directory */
1104 off = tget_long(&s->gb, le);
1105 if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
1106 av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
1107 return AVERROR_INVALIDDATA;
1109 bytestream2_seek(&s->gb, off, SEEK_SET);
1110 entries = tget_short(&s->gb, le);
1111 if (bytestream2_get_bytes_left(&s->gb) < entries * 12)
1112 return AVERROR_INVALIDDATA;
1113 for (i = 0; i < entries; i++) {
1114 if ((ret = tiff_decode_tag(s, p)) < 0)
1118 for (i = 0; i<s->geotag_count; i++) {
1119 const char *keyname = get_geokey_name(s->geotags[i].key);
1121 av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);
1124 if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {
1125 av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);
1128 ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);
1130 av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);
1135 if (!s->strippos && !s->stripoff) {
1136 av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
1137 return AVERROR_INVALIDDATA;
1139 /* now we have the data and may start decoding */
1140 if ((ret = init_image(s, p)) < 0)
1143 if (s->strips == 1 && !s->stripsize) {
1144 av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
1145 s->stripsize = avpkt->size - s->stripoff;
1148 if (s->stripsizesoff) {
1149 if (s->stripsizesoff >= (unsigned)avpkt->size)
1150 return AVERROR_INVALIDDATA;
1151 bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, avpkt->size - s->stripsizesoff);
1154 if (s->strippos >= (unsigned)avpkt->size)
1155 return AVERROR_INVALIDDATA;
1156 bytestream2_init(&stripdata, avpkt->data + s->strippos, avpkt->size - s->strippos);
1160 av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);
1161 return AVERROR_INVALIDDATA;
1164 planes = s->planar ? s->bppcount : 1;
1165 for (plane = 0; plane < planes; plane++) {
1166 stride = p->linesize[plane];
1167 dst = p->data[plane];
1168 for (i = 0; i < s->height; i += s->rps) {
1169 if (s->stripsizesoff)
1170 ssize = tget(&stripsizes, s->sstype, s->le);
1172 ssize = s->stripsize;
1175 soff = tget(&stripdata, s->sot, s->le);
1179 if (soff > avpkt->size || ssize > avpkt->size - soff) {
1180 av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
1181 return AVERROR_INVALIDDATA;
1183 if (tiff_unpack_strip(s, dst, stride, avpkt->data + soff, ssize,
1184 FFMIN(s->rps, s->height - i)) < 0)
1186 dst += s->rps * stride;
1188 if (s->predictor == 2) {
1189 dst = p->data[plane];
1192 soff = FFMAX(soff / s->bppcount, 1);
1193 ssize = s->width * soff;
1194 if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||
1195 s->avctx->pix_fmt == AV_PIX_FMT_RGBA64LE ||
1196 s->avctx->pix_fmt == AV_PIX_FMT_GBRP16LE ||
1197 s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16LE) {
1198 for (i = 0; i < s->height; i++) {
1199 for (j = soff; j < ssize; j += 2)
1200 AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));
1203 } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1204 s->avctx->pix_fmt == AV_PIX_FMT_RGBA64BE ||
1205 s->avctx->pix_fmt == AV_PIX_FMT_GBRP16BE ||
1206 s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16BE) {
1207 for (i = 0; i < s->height; i++) {
1208 for (j = soff; j < ssize; j += 2)
1209 AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));
1213 for (i = 0; i < s->height; i++) {
1214 for (j = soff; j < ssize; j++)
1215 dst[j] += dst[j - soff];
1222 dst = p->data[plane];
1223 for (i = 0; i < s->height; i++) {
1224 for (j = 0; j < p->linesize[plane]; j++)
1225 dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];
1226 dst += p->linesize[plane];
1231 if (s->planar && s->bppcount > 2) {
1232 FFSWAP(uint8_t*, p->data[0], p->data[2]);
1233 FFSWAP(int, p->linesize[0], p->linesize[2]);
1234 FFSWAP(uint8_t*, p->data[0], p->data[1]);
1235 FFSWAP(int, p->linesize[0], p->linesize[1]);
1243 static av_cold int tiff_init(AVCodecContext *avctx)
1245 TiffContext *s = avctx->priv_data;
1250 ff_lzw_decode_open(&s->lzw);
1251 ff_ccitt_unpack_init();
1256 static av_cold int tiff_end(AVCodecContext *avctx)
1258 TiffContext *const s = avctx->priv_data;
1262 ff_lzw_decode_close(&s->lzw);
1263 av_freep(&s->deinvert_buf);
1267 AVCodec ff_tiff_decoder = {
1269 .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
1270 .type = AVMEDIA_TYPE_VIDEO,
1271 .id = AV_CODEC_ID_TIFF,
1272 .priv_data_size = sizeof(TiffContext),
1275 .decode = decode_frame,
1276 .capabilities = CODEC_CAP_DR1,