48ce5c1fada5418290018c9d145aa821d5c3379f
[libav.git] / libavcodec / tiff.c
1 /*
2 * TIFF image decoder
3 * Copyright (c) 2006 Konstantin Shishkov
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /**
23 * @file
24 * TIFF image decoder
25 * @author Konstantin Shishkov
26 */
27
28 #include "avcodec.h"
29 #include "config.h"
30 #if CONFIG_ZLIB
31 #include <zlib.h>
32 #endif
33 #include "lzw.h"
34 #include "tiff.h"
35 #include "faxcompr.h"
36 #include "mathops.h"
37 #include "libavutil/attributes.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/imgutils.h"
40
41 typedef struct TiffContext {
42 AVCodecContext *avctx;
43 AVFrame picture;
44
45 int width, height;
46 unsigned int bpp, bppcount;
47 uint32_t palette[256];
48 int palette_is_set;
49 int le;
50 enum TiffCompr compr;
51 int invert;
52 int fax_opts;
53 int predictor;
54 int fill_order;
55
56 int strips, rps, sstype;
57 int sot;
58 const uint8_t *stripdata;
59 const uint8_t *stripsizes;
60 int stripsize, stripoff;
61 LZWState *lzw;
62 } TiffContext;
63
64 static unsigned tget_short(const uint8_t **p, int le)
65 {
66 unsigned v = le ? AV_RL16(*p) : AV_RB16(*p);
67 *p += 2;
68 return v;
69 }
70
71 static unsigned tget_long(const uint8_t **p, int le)
72 {
73 unsigned v = le ? AV_RL32(*p) : AV_RB32(*p);
74 *p += 4;
75 return v;
76 }
77
78 static unsigned tget(const uint8_t **p, int type, int le)
79 {
80 switch (type) {
81 case TIFF_BYTE : return *(*p)++;
82 case TIFF_SHORT: return tget_short(p, le);
83 case TIFF_LONG : return tget_long(p, le);
84 default : return UINT_MAX;
85 }
86 }
87
88 #if CONFIG_ZLIB
89 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src,
90 int size)
91 {
92 z_stream zstream = { 0 };
93 int zret;
94
95 zstream.next_in = src;
96 zstream.avail_in = size;
97 zstream.next_out = dst;
98 zstream.avail_out = *len;
99 zret = inflateInit(&zstream);
100 if (zret != Z_OK) {
101 av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
102 return zret;
103 }
104 zret = inflate(&zstream, Z_SYNC_FLUSH);
105 inflateEnd(&zstream);
106 *len = zstream.total_out;
107 return zret == Z_STREAM_END ? Z_OK : zret;
108 }
109 #endif
110
111 static int tiff_unpack_strip(TiffContext *s, uint8_t *dst, int stride,
112 const uint8_t *src, int size, int lines)
113 {
114 int c, line, pixels, code;
115 const uint8_t *ssrc = src;
116 int width = ((s->width * s->bpp) + 7) >> 3;
117
118 if (size <= 0)
119 return AVERROR_INVALIDDATA;
120
121 #if CONFIG_ZLIB
122 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
123 uint8_t *zbuf;
124 unsigned long outlen;
125 int ret;
126 outlen = width * lines;
127 zbuf = av_malloc(outlen);
128 if (!zbuf)
129 return AVERROR(ENOMEM);
130 ret = tiff_uncompress(zbuf, &outlen, src, size);
131 if (ret != Z_OK) {
132 av_log(s->avctx, AV_LOG_ERROR,
133 "Uncompressing failed (%lu of %lu) with error %d\n", outlen,
134 (unsigned long)width * lines, ret);
135 av_free(zbuf);
136 return -1;
137 }
138 src = zbuf;
139 for (line = 0; line < lines; line++) {
140 memcpy(dst, src, width);
141 dst += stride;
142 src += width;
143 }
144 av_free(zbuf);
145 return 0;
146 }
147 #endif
148 if (s->compr == TIFF_LZW) {
149 if (ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF) < 0) {
150 av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
151 return -1;
152 }
153 }
154 if (s->compr == TIFF_CCITT_RLE || s->compr == TIFF_G3
155 || s->compr == TIFF_G4) {
156 int i, ret = 0;
157 uint8_t *src2 = av_malloc((unsigned)size +
158 FF_INPUT_BUFFER_PADDING_SIZE);
159
160 if (!src2) {
161 av_log(s->avctx, AV_LOG_ERROR,
162 "Error allocating temporary buffer\n");
163 return AVERROR(ENOMEM);
164 }
165 if (s->fax_opts & 2) {
166 av_log(s->avctx, AV_LOG_ERROR,
167 "Uncompressed fax mode is not supported (yet)\n");
168 av_free(src2);
169 return -1;
170 }
171 if (!s->fill_order) {
172 memcpy(src2, src, size);
173 } else {
174 for (i = 0; i < size; i++)
175 src2[i] = ff_reverse[src[i]];
176 }
177 memset(src2 + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
178 switch (s->compr) {
179 case TIFF_CCITT_RLE:
180 case TIFF_G3:
181 case TIFF_G4:
182 ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride,
183 s->compr, s->fax_opts);
184 break;
185 }
186 av_free(src2);
187 return ret;
188 }
189 for (line = 0; line < lines; line++) {
190 if (src - ssrc > size) {
191 av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");
192 return -1;
193 }
194 switch (s->compr) {
195 case TIFF_RAW:
196 if (ssrc + size - src < width)
197 return AVERROR_INVALIDDATA;
198 if (!s->fill_order) {
199 memcpy(dst, src, width);
200 } else {
201 int i;
202 for (i = 0; i < width; i++)
203 dst[i] = ff_reverse[src[i]];
204 }
205 src += width;
206 break;
207 case TIFF_PACKBITS:
208 for (pixels = 0; pixels < width;) {
209 code = (int8_t) * src++;
210 if (code >= 0) {
211 code++;
212 if (pixels + code > width) {
213 av_log(s->avctx, AV_LOG_ERROR,
214 "Copy went out of bounds\n");
215 return -1;
216 }
217 memcpy(dst + pixels, src, code);
218 src += code;
219 pixels += code;
220 } else if (code != -128) { // -127..-1
221 code = (-code) + 1;
222 if (pixels + code > width) {
223 av_log(s->avctx, AV_LOG_ERROR,
224 "Run went out of bounds\n");
225 return -1;
226 }
227 c = *src++;
228 memset(dst + pixels, c, code);
229 pixels += code;
230 }
231 }
232 break;
233 case TIFF_LZW:
234 pixels = ff_lzw_decode(s->lzw, dst, width);
235 if (pixels < width) {
236 av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
237 pixels, width);
238 return -1;
239 }
240 break;
241 }
242 dst += stride;
243 }
244 return 0;
245 }
246
247 static int init_image(TiffContext *s)
248 {
249 int i, ret;
250 uint32_t *pal;
251
252 switch (s->bpp * 10 + s->bppcount) {
253 case 11:
254 s->avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
255 break;
256 case 81:
257 s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
258 break;
259 case 243:
260 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
261 break;
262 case 161:
263 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GRAY16LE : AV_PIX_FMT_GRAY16BE;
264 break;
265 case 324:
266 s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
267 break;
268 case 483:
269 s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB48BE;
270 break;
271 default:
272 av_log(s->avctx, AV_LOG_ERROR,
273 "This format is not supported (bpp=%d, bppcount=%d)\n",
274 s->bpp, s->bppcount);
275 return AVERROR_INVALIDDATA;
276 }
277 if (s->width != s->avctx->width || s->height != s->avctx->height) {
278 if ((ret = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)
279 return ret;
280 avcodec_set_dimensions(s->avctx, s->width, s->height);
281 }
282 if (s->picture.data[0])
283 s->avctx->release_buffer(s->avctx, &s->picture);
284 if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0) {
285 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
286 return ret;
287 }
288 if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
289 if (s->palette_is_set) {
290 memcpy(s->picture.data[1], s->palette, sizeof(s->palette));
291 } else {
292 /* make default grayscale pal */
293 pal = (uint32_t *) s->picture.data[1];
294 for (i = 0; i < 256; i++)
295 pal[i] = i * 0x010101;
296 }
297 }
298 return 0;
299 }
300
301 static int tiff_decode_tag(TiffContext *s, const uint8_t *start,
302 const uint8_t *buf, const uint8_t *end_buf)
303 {
304 unsigned tag, type, count, off, value = 0;
305 int i, j;
306 uint32_t *pal;
307 const uint8_t *rp, *gp, *bp;
308
309 if (end_buf - buf < 12)
310 return -1;
311 tag = tget_short(&buf, s->le);
312 type = tget_short(&buf, s->le);
313 count = tget_long(&buf, s->le);
314 off = tget_long(&buf, s->le);
315
316 if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
317 av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
318 type);
319 return 0;
320 }
321
322 if (count == 1) {
323 switch (type) {
324 case TIFF_BYTE:
325 case TIFF_SHORT:
326 buf -= 4;
327 value = tget(&buf, type, s->le);
328 buf = NULL;
329 break;
330 case TIFF_LONG:
331 value = off;
332 buf = NULL;
333 break;
334 case TIFF_STRING:
335 if (count <= 4) {
336 buf -= 4;
337 break;
338 }
339 default:
340 value = UINT_MAX;
341 buf = start + off;
342 }
343 } else {
344 if (count <= 4 && type_sizes[type] * count <= 4) {
345 buf -= 4;
346 } else {
347 buf = start + off;
348 }
349 }
350
351 if (buf && (buf < start || buf > end_buf)) {
352 av_log(s->avctx, AV_LOG_ERROR,
353 "Tag referencing position outside the image\n");
354 return -1;
355 }
356
357 switch (tag) {
358 case TIFF_WIDTH:
359 s->width = value;
360 break;
361 case TIFF_HEIGHT:
362 s->height = value;
363 break;
364 case TIFF_BPP:
365 s->bppcount = count;
366 if (count > 4) {
367 av_log(s->avctx, AV_LOG_ERROR,
368 "This format is not supported (bpp=%d, %d components)\n",
369 s->bpp, count);
370 return -1;
371 }
372 if (count == 1)
373 s->bpp = value;
374 else {
375 switch (type) {
376 case TIFF_BYTE:
377 s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
378 ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
379 break;
380 case TIFF_SHORT:
381 case TIFF_LONG:
382 s->bpp = 0;
383 for (i = 0; i < count && buf < end_buf; i++)
384 s->bpp += tget(&buf, type, s->le);
385 break;
386 default:
387 s->bpp = -1;
388 }
389 }
390 break;
391 case TIFF_SAMPLES_PER_PIXEL:
392 if (count != 1) {
393 av_log(s->avctx, AV_LOG_ERROR,
394 "Samples per pixel requires a single value, many provided\n");
395 return AVERROR_INVALIDDATA;
396 }
397 if (s->bppcount == 1)
398 s->bpp *= value;
399 s->bppcount = value;
400 break;
401 case TIFF_COMPR:
402 s->compr = value;
403 s->predictor = 0;
404 switch (s->compr) {
405 case TIFF_RAW:
406 case TIFF_PACKBITS:
407 case TIFF_LZW:
408 case TIFF_CCITT_RLE:
409 break;
410 case TIFF_G3:
411 case TIFF_G4:
412 s->fax_opts = 0;
413 break;
414 case TIFF_DEFLATE:
415 case TIFF_ADOBE_DEFLATE:
416 #if CONFIG_ZLIB
417 break;
418 #else
419 av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
420 return -1;
421 #endif
422 case TIFF_JPEG:
423 case TIFF_NEWJPEG:
424 av_log(s->avctx, AV_LOG_ERROR,
425 "JPEG compression is not supported\n");
426 return -1;
427 default:
428 av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
429 s->compr);
430 return -1;
431 }
432 break;
433 case TIFF_ROWSPERSTRIP:
434 if (type == TIFF_LONG && value == UINT_MAX)
435 value = s->avctx->height;
436 if (value < 1) {
437 av_log(s->avctx, AV_LOG_ERROR,
438 "Incorrect value of rows per strip\n");
439 return -1;
440 }
441 s->rps = value;
442 break;
443 case TIFF_STRIP_OFFS:
444 if (count == 1) {
445 s->stripdata = NULL;
446 s->stripoff = value;
447 } else
448 s->stripdata = start + off;
449 s->strips = count;
450 if (s->strips == 1)
451 s->rps = s->height;
452 s->sot = type;
453 if (s->stripdata > end_buf) {
454 av_log(s->avctx, AV_LOG_ERROR,
455 "Tag referencing position outside the image\n");
456 return -1;
457 }
458 break;
459 case TIFF_STRIP_SIZE:
460 if (count == 1) {
461 s->stripsizes = NULL;
462 s->stripsize = value;
463 s->strips = 1;
464 } else {
465 s->stripsizes = start + off;
466 }
467 s->strips = count;
468 s->sstype = type;
469 if (s->stripsizes > end_buf) {
470 av_log(s->avctx, AV_LOG_ERROR,
471 "Tag referencing position outside the image\n");
472 return -1;
473 }
474 break;
475 case TIFF_PREDICTOR:
476 s->predictor = value;
477 break;
478 case TIFF_INVERT:
479 switch (value) {
480 case 0:
481 s->invert = 1;
482 break;
483 case 1:
484 s->invert = 0;
485 break;
486 case 2:
487 case 3:
488 break;
489 default:
490 av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
491 value);
492 return -1;
493 }
494 break;
495 case TIFF_FILL_ORDER:
496 if (value < 1 || value > 2) {
497 av_log(s->avctx, AV_LOG_ERROR,
498 "Unknown FillOrder value %d, trying default one\n", value);
499 value = 1;
500 }
501 s->fill_order = value - 1;
502 break;
503 case TIFF_PAL:
504 pal = (uint32_t *) s->palette;
505 off = type_sizes[type];
506 if (count / 3 > 256 || end_buf - buf < count / 3 * off * 3)
507 return -1;
508 rp = buf;
509 gp = buf + count / 3 * off;
510 bp = buf + count / 3 * off * 2;
511 off = (type_sizes[type] - 1) << 3;
512 for (i = 0; i < count / 3; i++) {
513 j = (tget(&rp, type, s->le) >> off) << 16;
514 j |= (tget(&gp, type, s->le) >> off) << 8;
515 j |= tget(&bp, type, s->le) >> off;
516 pal[i] = j;
517 }
518 s->palette_is_set = 1;
519 break;
520 case TIFF_PLANAR:
521 if (value == 2) {
522 av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
523 return -1;
524 }
525 break;
526 case TIFF_T4OPTIONS:
527 if (s->compr == TIFF_G3)
528 s->fax_opts = value;
529 break;
530 case TIFF_T6OPTIONS:
531 if (s->compr == TIFF_G4)
532 s->fax_opts = value;
533 break;
534 default:
535 av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
536 tag, tag);
537 }
538 return 0;
539 }
540
541 static int decode_frame(AVCodecContext *avctx,
542 void *data, int *data_size, AVPacket *avpkt)
543 {
544 const uint8_t *buf = avpkt->data;
545 int buf_size = avpkt->size;
546 TiffContext *const s = avctx->priv_data;
547 AVFrame *picture = data;
548 AVFrame *const p = &s->picture;
549 const uint8_t *orig_buf = buf, *end_buf = buf + buf_size;
550 unsigned off;
551 int id, le, ret;
552 int i, j, entries;
553 int stride;
554 unsigned soff, ssize;
555 uint8_t *dst;
556
557 //parse image header
558 if (end_buf - buf < 8)
559 return AVERROR_INVALIDDATA;
560 id = AV_RL16(buf);
561 buf += 2;
562 if (id == 0x4949)
563 le = 1;
564 else if (id == 0x4D4D)
565 le = 0;
566 else {
567 av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");
568 return -1;
569 }
570 s->le = le;
571 s->invert = 0;
572 s->compr = TIFF_RAW;
573 s->fill_order = 0;
574 // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
575 // that further identifies the file as a TIFF file"
576 if (tget_short(&buf, le) != 42) {
577 av_log(avctx, AV_LOG_ERROR,
578 "The answer to life, universe and everything is not correct!\n");
579 return -1;
580 }
581 // Reset these pointers so we can tell if they were set this frame
582 s->stripsizes = s->stripdata = NULL;
583 /* parse image file directory */
584 off = tget_long(&buf, le);
585 if (off >= UINT_MAX - 14 || end_buf - orig_buf < off + 14) {
586 av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
587 return AVERROR_INVALIDDATA;
588 }
589 buf = orig_buf + off;
590 entries = tget_short(&buf, le);
591 for (i = 0; i < entries; i++) {
592 if (tiff_decode_tag(s, orig_buf, buf, end_buf) < 0)
593 return -1;
594 buf += 12;
595 }
596 if (!s->stripdata && !s->stripoff) {
597 av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
598 return -1;
599 }
600 /* now we have the data and may start decoding */
601 if ((ret = init_image(s)) < 0)
602 return ret;
603
604 if (s->strips == 1 && !s->stripsize) {
605 av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
606 s->stripsize = buf_size - s->stripoff;
607 }
608 stride = p->linesize[0];
609 dst = p->data[0];
610 for (i = 0; i < s->height; i += s->rps) {
611 if (s->stripsizes) {
612 if (s->stripsizes >= end_buf)
613 return AVERROR_INVALIDDATA;
614 ssize = tget(&s->stripsizes, s->sstype, s->le);
615 } else
616 ssize = s->stripsize;
617
618 if (s->stripdata) {
619 if (s->stripdata >= end_buf)
620 return AVERROR_INVALIDDATA;
621 soff = tget(&s->stripdata, s->sot, s->le);
622 } else
623 soff = s->stripoff;
624
625 if (soff > buf_size || ssize > buf_size - soff) {
626 av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
627 return -1;
628 }
629 if (tiff_unpack_strip(s, dst, stride, orig_buf + soff, ssize,
630 FFMIN(s->rps, s->height - i)) < 0)
631 break;
632 dst += s->rps * stride;
633 }
634 if (s->predictor == 2) {
635 dst = p->data[0];
636 soff = s->bpp >> 3;
637 ssize = s->width * soff;
638 for (i = 0; i < s->height; i++) {
639 for (j = soff; j < ssize; j++)
640 dst[j] += dst[j - soff];
641 dst += stride;
642 }
643 }
644
645 if (s->invert) {
646 uint8_t *src;
647 int j;
648
649 src = s->picture.data[0];
650 for (j = 0; j < s->height; j++) {
651 for (i = 0; i < s->picture.linesize[0]; i++)
652 src[i] = 255 - src[i];
653 src += s->picture.linesize[0];
654 }
655 }
656 *picture = s->picture;
657 *data_size = sizeof(AVPicture);
658
659 return buf_size;
660 }
661
662 static av_cold int tiff_init(AVCodecContext *avctx)
663 {
664 TiffContext *s = avctx->priv_data;
665
666 s->width = 0;
667 s->height = 0;
668 s->avctx = avctx;
669 avcodec_get_frame_defaults(&s->picture);
670 avctx->coded_frame = &s->picture;
671 ff_lzw_decode_open(&s->lzw);
672 ff_ccitt_unpack_init();
673
674 return 0;
675 }
676
677 static av_cold int tiff_end(AVCodecContext *avctx)
678 {
679 TiffContext *const s = avctx->priv_data;
680
681 ff_lzw_decode_close(&s->lzw);
682 if (s->picture.data[0])
683 avctx->release_buffer(avctx, &s->picture);
684 return 0;
685 }
686
687 AVCodec ff_tiff_decoder = {
688 .name = "tiff",
689 .type = AVMEDIA_TYPE_VIDEO,
690 .id = AV_CODEC_ID_TIFF,
691 .priv_data_size = sizeof(TiffContext),
692 .init = tiff_init,
693 .close = tiff_end,
694 .decode = decode_frame,
695 .capabilities = CODEC_CAP_DR1,
696 .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
697 };