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