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