]> git.sesse.net Git - ffmpeg/blob - libavcodec/tiff.c
lavc: remove disabled FF_API_COLOR_TABLE_ID cruft
[ffmpeg] / 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 "internal.h"
37 #include "mathops.h"
38 #include "libavutil/attributes.h"
39 #include "libavutil/intreadwrite.h"
40 #include "libavutil/imgutils.h"
41
42 typedef struct TiffContext {
43     AVCodecContext *avctx;
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, ret;
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 AVERROR_UNKNOWN;
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 ((ret = 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 ret;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
239             }
240             break;
241         }
242         dst += stride;
243     }
244     return 0;
245 }
246
247 static int init_image(TiffContext *s, AVFrame *frame)
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 ((ret = ff_get_buffer(s->avctx, frame, 0)) < 0) {
283         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
284         return ret;
285     }
286     if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) {
287         if (s->palette_is_set) {
288             memcpy(frame->data[1], s->palette, sizeof(s->palette));
289         } else {
290             /* make default grayscale pal */
291             pal = (uint32_t *) frame->data[1];
292             for (i = 0; i < 256; i++)
293                 pal[i] = i * 0x010101;
294         }
295     }
296     return 0;
297 }
298
299 static int tiff_decode_tag(TiffContext *s, const uint8_t *start,
300                            const uint8_t *buf, const uint8_t *end_buf)
301 {
302     unsigned tag, type, count, off, value = 0;
303     int i, j;
304     uint32_t *pal;
305     const uint8_t *rp, *gp, *bp;
306
307     if (end_buf - buf < 12)
308         return AVERROR_INVALIDDATA;
309     tag = tget_short(&buf, s->le);
310     type = tget_short(&buf, s->le);
311     count = tget_long(&buf, s->le);
312     off = tget_long(&buf, s->le);
313
314     if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
315         av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
316                type);
317         return 0;
318     }
319
320     if (count == 1) {
321         switch (type) {
322         case TIFF_BYTE:
323         case TIFF_SHORT:
324             buf -= 4;
325             value = tget(&buf, type, s->le);
326             buf = NULL;
327             break;
328         case TIFF_LONG:
329             value = off;
330             buf = NULL;
331             break;
332         case TIFF_STRING:
333             if (count <= 4) {
334                 buf -= 4;
335                 break;
336             }
337         default:
338             value = UINT_MAX;
339             buf = start + off;
340         }
341     } else {
342         if (count <= 4 && type_sizes[type] * count <= 4) {
343             buf -= 4;
344         } else {
345             buf = start + off;
346         }
347     }
348
349     if (buf && (buf < start || buf > end_buf)) {
350         av_log(s->avctx, AV_LOG_ERROR,
351                "Tag referencing position outside the image\n");
352         return AVERROR_INVALIDDATA;
353     }
354
355     switch (tag) {
356     case TIFF_WIDTH:
357         s->width = value;
358         break;
359     case TIFF_HEIGHT:
360         s->height = value;
361         break;
362     case TIFF_BPP:
363         s->bppcount = count;
364         if (count > 4) {
365             av_log(s->avctx, AV_LOG_ERROR,
366                    "This format is not supported (bpp=%d, %d components)\n",
367                    s->bpp, count);
368             return AVERROR_INVALIDDATA;
369         }
370         if (count == 1)
371             s->bpp = value;
372         else {
373             switch (type) {
374             case TIFF_BYTE:
375                 s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
376                          ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
377                 break;
378             case TIFF_SHORT:
379             case TIFF_LONG:
380                 s->bpp = 0;
381                 for (i = 0; i < count && buf < end_buf; i++)
382                     s->bpp += tget(&buf, type, s->le);
383                 break;
384             default:
385                 s->bpp = -1;
386             }
387         }
388         break;
389     case TIFF_SAMPLES_PER_PIXEL:
390         if (count != 1) {
391             av_log(s->avctx, AV_LOG_ERROR,
392                    "Samples per pixel requires a single value, many provided\n");
393             return AVERROR_INVALIDDATA;
394         }
395         if (s->bppcount == 1)
396             s->bpp *= value;
397         s->bppcount = value;
398         break;
399     case TIFF_COMPR:
400         s->compr = value;
401         s->predictor = 0;
402         switch (s->compr) {
403         case TIFF_RAW:
404         case TIFF_PACKBITS:
405         case TIFF_LZW:
406         case TIFF_CCITT_RLE:
407             break;
408         case TIFF_G3:
409         case TIFF_G4:
410             s->fax_opts = 0;
411             break;
412         case TIFF_DEFLATE:
413         case TIFF_ADOBE_DEFLATE:
414 #if CONFIG_ZLIB
415             break;
416 #else
417             av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
418             return AVERROR(ENOSYS);
419 #endif
420         case TIFF_JPEG:
421         case TIFF_NEWJPEG:
422             av_log(s->avctx, AV_LOG_ERROR,
423                    "JPEG compression is not supported\n");
424             return AVERROR_PATCHWELCOME;
425         default:
426             av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
427                    s->compr);
428             return AVERROR_INVALIDDATA;
429         }
430         break;
431     case TIFF_ROWSPERSTRIP:
432         if (type == TIFF_LONG && value == UINT_MAX)
433             value = s->avctx->height;
434         if (value < 1) {
435             av_log(s->avctx, AV_LOG_ERROR,
436                    "Incorrect value of rows per strip\n");
437             return AVERROR_INVALIDDATA;
438         }
439         s->rps = value;
440         break;
441     case TIFF_STRIP_OFFS:
442         if (count == 1) {
443             s->stripdata = NULL;
444             s->stripoff = value;
445         } else
446             s->stripdata = start + off;
447         s->strips = count;
448         if (s->strips == 1)
449             s->rps = s->height;
450         s->sot = type;
451         if (s->stripdata > end_buf) {
452             av_log(s->avctx, AV_LOG_ERROR,
453                    "Tag referencing position outside the image\n");
454             return AVERROR_INVALIDDATA;
455         }
456         break;
457     case TIFF_STRIP_SIZE:
458         if (count == 1) {
459             s->stripsizes = NULL;
460             s->stripsize = value;
461             s->strips = 1;
462         } else {
463             s->stripsizes = start + off;
464         }
465         s->strips = count;
466         s->sstype = type;
467         if (s->stripsizes > end_buf) {
468             av_log(s->avctx, AV_LOG_ERROR,
469                    "Tag referencing position outside the image\n");
470             return AVERROR_INVALIDDATA;
471         }
472         break;
473     case TIFF_PREDICTOR:
474         s->predictor = value;
475         break;
476     case TIFF_INVERT:
477         switch (value) {
478         case 0:
479             s->invert = 1;
480             break;
481         case 1:
482             s->invert = 0;
483             break;
484         case 2:
485         case 3:
486             break;
487         default:
488             av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
489                    value);
490             return AVERROR_INVALIDDATA;
491         }
492         break;
493     case TIFF_FILL_ORDER:
494         if (value < 1 || value > 2) {
495             av_log(s->avctx, AV_LOG_ERROR,
496                    "Unknown FillOrder value %d, trying default one\n", value);
497             value = 1;
498         }
499         s->fill_order = value - 1;
500         break;
501     case TIFF_PAL:
502         pal = (uint32_t *) s->palette;
503         off = type_sizes[type];
504         if (count / 3 > 256 || end_buf - buf < count / 3 * off * 3)
505             return AVERROR_INVALIDDATA;
506         rp = buf;
507         gp = buf + count / 3 * off;
508         bp = buf + count / 3 * off * 2;
509         off = (type_sizes[type] - 1) << 3;
510         for (i = 0; i < count / 3; i++) {
511             j  = (tget(&rp, type, s->le) >> off) << 16;
512             j |= (tget(&gp, type, s->le) >> off) << 8;
513             j |=  tget(&bp, type, s->le) >> off;
514             pal[i] = j;
515         }
516         s->palette_is_set = 1;
517         break;
518     case TIFF_PLANAR:
519         if (value == 2) {
520             av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
521             return AVERROR_PATCHWELCOME;
522         }
523         break;
524     case TIFF_T4OPTIONS:
525         if (s->compr == TIFF_G3)
526             s->fax_opts = value;
527         break;
528     case TIFF_T6OPTIONS:
529         if (s->compr == TIFF_G4)
530             s->fax_opts = value;
531         break;
532     default:
533         av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
534                tag, tag);
535     }
536     return 0;
537 }
538
539 static int decode_frame(AVCodecContext *avctx,
540                         void *data, int *got_frame, AVPacket *avpkt)
541 {
542     const uint8_t *buf = avpkt->data;
543     int buf_size = avpkt->size;
544     TiffContext *const s = avctx->priv_data;
545     AVFrame *const p = data;
546     const uint8_t *orig_buf = buf, *end_buf = buf + buf_size;
547     unsigned off;
548     int id, le, ret;
549     int i, j, entries;
550     int stride;
551     unsigned soff, ssize;
552     uint8_t *dst;
553
554     //parse image header
555     if (end_buf - buf < 8)
556         return AVERROR_INVALIDDATA;
557     id = AV_RL16(buf);
558     buf += 2;
559     if (id == 0x4949)
560         le = 1;
561     else if (id == 0x4D4D)
562         le = 0;
563     else {
564         av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");
565         return AVERROR_INVALIDDATA;
566     }
567     s->le = le;
568     s->invert = 0;
569     s->compr = TIFF_RAW;
570     s->fill_order = 0;
571     // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
572     // that further identifies the file as a TIFF file"
573     if (tget_short(&buf, le) != 42) {
574         av_log(avctx, AV_LOG_ERROR,
575                "The answer to life, universe and everything is not correct!\n");
576         return AVERROR_INVALIDDATA;
577     }
578     // Reset these pointers so we can tell if they were set this frame
579     s->stripsizes = s->stripdata = NULL;
580     /* parse image file directory */
581     off = tget_long(&buf, le);
582     if (off >= UINT_MAX - 14 || end_buf - orig_buf < off + 14) {
583         av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
584         return AVERROR_INVALIDDATA;
585     }
586     buf = orig_buf + off;
587     entries = tget_short(&buf, le);
588     for (i = 0; i < entries; i++) {
589         if ((ret = tiff_decode_tag(s, orig_buf, buf, end_buf)) < 0)
590             return ret;
591         buf += 12;
592     }
593     if (!s->stripdata && !s->stripoff) {
594         av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
595         return AVERROR_INVALIDDATA;
596     }
597     /* now we have the data and may start decoding */
598     if ((ret = init_image(s, p)) < 0)
599         return ret;
600
601     if (s->strips == 1 && !s->stripsize) {
602         av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
603         s->stripsize = buf_size - s->stripoff;
604     }
605     stride = p->linesize[0];
606     dst = p->data[0];
607     for (i = 0; i < s->height; i += s->rps) {
608         if (s->stripsizes) {
609             if (s->stripsizes >= end_buf)
610                 return AVERROR_INVALIDDATA;
611             ssize = tget(&s->stripsizes, s->sstype, s->le);
612         } else
613             ssize = s->stripsize;
614
615         if (s->stripdata) {
616             if (s->stripdata >= end_buf)
617                 return AVERROR_INVALIDDATA;
618             soff = tget(&s->stripdata, s->sot, s->le);
619         } else
620             soff = s->stripoff;
621
622         if (soff > buf_size || ssize > buf_size - soff) {
623             av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
624             return AVERROR_INVALIDDATA;
625         }
626         if (tiff_unpack_strip(s, dst, stride, orig_buf + soff, ssize,
627                               FFMIN(s->rps, s->height - i)) < 0)
628             break;
629         dst += s->rps * stride;
630     }
631     if (s->predictor == 2) {
632         dst = p->data[0];
633         soff = s->bpp >> 3;
634         ssize = s->width * soff;
635         for (i = 0; i < s->height; i++) {
636             for (j = soff; j < ssize; j++)
637                 dst[j] += dst[j - soff];
638             dst += stride;
639         }
640     }
641
642     if (s->invert) {
643         uint8_t *src;
644         int j;
645
646         src = p->data[0];
647         for (j = 0; j < s->height; j++) {
648             for (i = 0; i < p->linesize[0]; i++)
649                 src[i] = 255 - src[i];
650             src += p->linesize[0];
651         }
652     }
653     *got_frame = 1;
654
655     return buf_size;
656 }
657
658 static av_cold int tiff_init(AVCodecContext *avctx)
659 {
660     TiffContext *s = avctx->priv_data;
661
662     s->width = 0;
663     s->height = 0;
664     s->avctx = avctx;
665     ff_lzw_decode_open(&s->lzw);
666     ff_ccitt_unpack_init();
667
668     return 0;
669 }
670
671 static av_cold int tiff_end(AVCodecContext *avctx)
672 {
673     TiffContext *const s = avctx->priv_data;
674
675     ff_lzw_decode_close(&s->lzw);
676     return 0;
677 }
678
679 AVCodec ff_tiff_decoder = {
680     .name           = "tiff",
681     .type           = AVMEDIA_TYPE_VIDEO,
682     .id             = AV_CODEC_ID_TIFF,
683     .priv_data_size = sizeof(TiffContext),
684     .init           = tiff_init,
685     .close          = tiff_end,
686     .decode         = decode_frame,
687     .capabilities   = CODEC_CAP_DR1,
688     .long_name      = NULL_IF_CONFIG_SMALL("TIFF image"),
689 };