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