libavcodec/tiff.c
Go to the documentation of this file.
00001 /*
00002  * TIFF image decoder
00003  * Copyright (c) 2006 Konstantin Shishkov
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00028 #include "avcodec.h"
00029 #include "bytestream.h"
00030 #if CONFIG_ZLIB
00031 #include <zlib.h>
00032 #endif
00033 #include "lzw.h"
00034 #include "tiff.h"
00035 #include "faxcompr.h"
00036 #include "libavutil/common.h"
00037 #include "libavutil/intreadwrite.h"
00038 #include "libavutil/imgutils.h"
00039 
00040 typedef struct TiffContext {
00041     AVCodecContext *avctx;
00042     AVFrame picture;
00043     GetByteContext gb;
00044 
00045     int width, height;
00046     unsigned int bpp, bppcount;
00047     uint32_t palette[256];
00048     int palette_is_set;
00049     int le;
00050     enum TiffCompr compr;
00051     int invert;
00052     int fax_opts;
00053     int predictor;
00054     int fill_order;
00055 
00056     int strips, rps, sstype;
00057     int sot;
00058     int stripsizesoff, stripsize, stripoff, strippos;
00059     LZWState *lzw;
00060 } TiffContext;
00061 
00062 static unsigned tget_short(GetByteContext *gb, int le)
00063 {
00064     return le ? bytestream2_get_le16(gb) : bytestream2_get_be16(gb);
00065 }
00066 
00067 static unsigned tget_long(GetByteContext *gb, int le)
00068 {
00069     return le ? bytestream2_get_le32(gb) : bytestream2_get_be32(gb);
00070 }
00071 
00072 static unsigned tget(GetByteContext *gb, int type, int le)
00073 {
00074     switch(type){
00075     case TIFF_BYTE:  return bytestream2_get_byte(gb);
00076     case TIFF_SHORT: return tget_short(gb, le);
00077     case TIFF_LONG:  return tget_long(gb, le);
00078     default:         return UINT_MAX;
00079     }
00080 }
00081 
00082 #if CONFIG_ZLIB
00083 static int tiff_uncompress(uint8_t *dst, unsigned long *len, const uint8_t *src, int size)
00084 {
00085     z_stream zstream;
00086     int zret;
00087 
00088     memset(&zstream, 0, sizeof(zstream));
00089     zstream.next_in = src;
00090     zstream.avail_in = size;
00091     zstream.next_out = dst;
00092     zstream.avail_out = *len;
00093     zret = inflateInit(&zstream);
00094     if (zret != Z_OK) {
00095         av_log(NULL, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
00096         return zret;
00097     }
00098     zret = inflate(&zstream, Z_SYNC_FLUSH);
00099     inflateEnd(&zstream);
00100     *len = zstream.total_out;
00101     return zret == Z_STREAM_END ? Z_OK : zret;
00102 }
00103 #endif
00104 
00105 static int tiff_unpack_strip(TiffContext *s, uint8_t* dst, int stride, const uint8_t *src, int size, int lines){
00106     PutByteContext pb;
00107     int c, line, pixels, code;
00108     int width = ((s->width * s->bpp) + 7) >> 3;
00109 #if CONFIG_ZLIB
00110     uint8_t *zbuf; unsigned long outlen;
00111 
00112     if(s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE){
00113         int ret;
00114         outlen = width * lines;
00115         zbuf = av_malloc(outlen);
00116         ret = tiff_uncompress(zbuf, &outlen, src, size);
00117         if(ret != Z_OK){
00118             av_log(s->avctx, AV_LOG_ERROR, "Uncompressing failed (%lu of %lu) with error %d\n", outlen, (unsigned long)width * lines, ret);
00119             av_free(zbuf);
00120             return -1;
00121         }
00122         src = zbuf;
00123         for(line = 0; line < lines; line++){
00124             memcpy(dst, src, width);
00125             dst += stride;
00126             src += width;
00127         }
00128         av_free(zbuf);
00129         return 0;
00130     }
00131 #endif
00132     if(s->compr == TIFF_LZW){
00133         if(ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF) < 0){
00134             av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");
00135             return -1;
00136         }
00137         for (line = 0; line < lines; line++) {
00138             pixels = ff_lzw_decode(s->lzw, dst, width);
00139             if (pixels < width) {
00140                 av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",
00141                        pixels, width);
00142                 return AVERROR_INVALIDDATA;
00143             }
00144             dst += stride;
00145         }
00146         return 0;
00147     }
00148     if(s->compr == TIFF_CCITT_RLE || s->compr == TIFF_G3 || s->compr == TIFF_G4){
00149         int i, ret = 0;
00150         uint8_t *src2 = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
00151 
00152         if(!src2 || (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE < (unsigned)size){
00153             av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
00154             return -1;
00155         }
00156         if(s->fax_opts & 2){
00157             av_log(s->avctx, AV_LOG_ERROR, "Uncompressed fax mode is not supported (yet)\n");
00158             av_free(src2);
00159             return -1;
00160         }
00161         if(!s->fill_order){
00162             memcpy(src2, src, size);
00163         }else{
00164             for(i = 0; i < size; i++)
00165                 src2[i] = av_reverse[src[i]];
00166         }
00167         memset(src2+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
00168         switch(s->compr){
00169         case TIFF_CCITT_RLE:
00170         case TIFF_G3:
00171         case TIFF_G4:
00172             ret = ff_ccitt_unpack(s->avctx, src2, size, dst, lines, stride, s->compr, s->fax_opts);
00173             break;
00174         }
00175         av_free(src2);
00176         return ret;
00177     }
00178 
00179     bytestream2_init(&s->gb, src, size);
00180     bytestream2_init_writer(&pb, dst, stride * lines);
00181 
00182     for(line = 0; line < lines; line++){
00183         if (bytestream2_get_bytes_left(&s->gb) == 0 || bytestream2_get_eof(&pb))
00184             break;
00185         bytestream2_seek_p(&pb, stride * line, SEEK_SET);
00186         switch(s->compr){
00187         case TIFF_RAW:
00188             if (!s->fill_order) {
00189                 bytestream2_copy_buffer(&pb, &s->gb, width);
00190             } else {
00191                 int i;
00192                 for (i = 0; i < width; i++)
00193                     bytestream2_put_byte(&pb, av_reverse[bytestream2_get_byte(&s->gb)]);
00194             }
00195             break;
00196         case TIFF_PACKBITS:
00197             for(pixels = 0; pixels < width;){
00198                 code = (int8_t)bytestream2_get_byte(&s->gb);
00199                 if(code >= 0){
00200                     code++;
00201                     bytestream2_copy_buffer(&pb, &s->gb, code);
00202                     pixels += code;
00203                 }else if(code != -128){ // -127..-1
00204                     code = (-code) + 1;
00205                     c    = bytestream2_get_byte(&s->gb);
00206                     bytestream2_set_buffer(&pb, c, code);
00207                     pixels += code;
00208                 }
00209             }
00210             break;
00211         }
00212     }
00213     return 0;
00214 }
00215 
00216 static int init_image(TiffContext *s)
00217 {
00218     int i, ret;
00219     uint32_t *pal;
00220 
00221     switch (s->bpp * 10 + s->bppcount) {
00222     case 11:
00223         s->avctx->pix_fmt = PIX_FMT_MONOBLACK;
00224         break;
00225     case 81:
00226         s->avctx->pix_fmt = PIX_FMT_PAL8;
00227         break;
00228     case 243:
00229         s->avctx->pix_fmt = PIX_FMT_RGB24;
00230         break;
00231     case 161:
00232         s->avctx->pix_fmt = PIX_FMT_GRAY16BE;
00233         break;
00234     case 324:
00235         s->avctx->pix_fmt = PIX_FMT_RGBA;
00236         break;
00237     case 483:
00238         s->avctx->pix_fmt = s->le ? PIX_FMT_RGB48LE : PIX_FMT_RGB48BE;
00239         break;
00240     default:
00241         av_log(s->avctx, AV_LOG_ERROR,
00242                "This format is not supported (bpp=%d, bppcount=%d)\n",
00243                s->bpp, s->bppcount);
00244         return AVERROR_INVALIDDATA;
00245     }
00246     if (s->width != s->avctx->width || s->height != s->avctx->height) {
00247         if ((ret = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)
00248             return ret;
00249         avcodec_set_dimensions(s->avctx, s->width, s->height);
00250     }
00251     if (s->picture.data[0])
00252         s->avctx->release_buffer(s->avctx, &s->picture);
00253     if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0) {
00254         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00255         return ret;
00256     }
00257     if (s->avctx->pix_fmt == PIX_FMT_PAL8) {
00258         if (s->palette_is_set) {
00259             memcpy(s->picture.data[1], s->palette, sizeof(s->palette));
00260         } else {
00261             /* make default grayscale pal */
00262             pal = (uint32_t *) s->picture.data[1];
00263             for (i = 0; i < 256; i++)
00264                 pal[i] = i * 0x010101;
00265         }
00266     }
00267     return 0;
00268 }
00269 
00270 static int tiff_decode_tag(TiffContext *s)
00271 {
00272     unsigned tag, type, count, off, value = 0;
00273     int i, start;
00274     uint32_t *pal;
00275 
00276     if (bytestream2_get_bytes_left(&s->gb) < 12)
00277         return -1;
00278     tag   = tget_short(&s->gb, s->le);
00279     type  = tget_short(&s->gb, s->le);
00280     count = tget_long(&s->gb, s->le);
00281     off   = tget_long(&s->gb, s->le);
00282     start = bytestream2_tell(&s->gb);
00283 
00284     if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
00285         av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n", type);
00286         return 0;
00287     }
00288 
00289     if(count == 1){
00290         switch(type){
00291         case TIFF_BYTE:
00292         case TIFF_SHORT:
00293             bytestream2_seek(&s->gb, -4, SEEK_CUR);
00294             value = tget(&s->gb, type, s->le);
00295             break;
00296         case TIFF_LONG:
00297             value = off;
00298             break;
00299         case TIFF_STRING:
00300             if(count <= 4){
00301                 bytestream2_seek(&s->gb, -4, SEEK_CUR);
00302                 break;
00303             }
00304         default:
00305             value = UINT_MAX;
00306             bytestream2_seek(&s->gb, off, SEEK_SET);
00307         }
00308     } else {
00309         if (count <= 4 && type_sizes[type] * count <= 4)
00310             bytestream2_seek(&s->gb, -4, SEEK_CUR);
00311         else
00312             bytestream2_seek(&s->gb, off, SEEK_SET);
00313     }
00314 
00315     switch(tag){
00316     case TIFF_WIDTH:
00317         s->width = value;
00318         break;
00319     case TIFF_HEIGHT:
00320         s->height = value;
00321         break;
00322     case TIFF_BPP:
00323         s->bppcount = count;
00324         if(count > 4){
00325             av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);
00326             return -1;
00327         }
00328         if(count == 1) s->bpp = value;
00329         else{
00330             switch(type){
00331             case TIFF_BYTE:
00332                 s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) + ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
00333                 break;
00334             case TIFF_SHORT:
00335             case TIFF_LONG:
00336                 s->bpp = 0;
00337                 for (i = 0; i < count; i++)
00338                     s->bpp += tget(&s->gb, type, s->le);
00339                 break;
00340             default:
00341                 s->bpp = -1;
00342             }
00343         }
00344         break;
00345     case TIFF_SAMPLES_PER_PIXEL:
00346         if (count != 1) {
00347             av_log(s->avctx, AV_LOG_ERROR,
00348                    "Samples per pixel requires a single value, many provided\n");
00349             return AVERROR_INVALIDDATA;
00350         }
00351         if (s->bppcount == 1)
00352             s->bpp *= value;
00353         s->bppcount = value;
00354         break;
00355     case TIFF_COMPR:
00356         s->compr = value;
00357         s->predictor = 0;
00358         switch(s->compr){
00359         case TIFF_RAW:
00360         case TIFF_PACKBITS:
00361         case TIFF_LZW:
00362         case TIFF_CCITT_RLE:
00363             break;
00364         case TIFF_G3:
00365         case TIFF_G4:
00366             s->fax_opts = 0;
00367             break;
00368         case TIFF_DEFLATE:
00369         case TIFF_ADOBE_DEFLATE:
00370 #if CONFIG_ZLIB
00371             break;
00372 #else
00373             av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
00374             return -1;
00375 #endif
00376         case TIFF_JPEG:
00377         case TIFF_NEWJPEG:
00378             av_log(s->avctx, AV_LOG_ERROR, "JPEG compression is not supported\n");
00379             return -1;
00380         default:
00381             av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n", s->compr);
00382             return -1;
00383         }
00384         break;
00385     case TIFF_ROWSPERSTRIP:
00386         if (type == TIFF_LONG && value == UINT_MAX)
00387             value = s->avctx->height;
00388         if(value < 1){
00389             av_log(s->avctx, AV_LOG_ERROR, "Incorrect value of rows per strip\n");
00390             return -1;
00391         }
00392         s->rps = value;
00393         break;
00394     case TIFF_STRIP_OFFS:
00395         if(count == 1){
00396             s->strippos = 0;
00397             s->stripoff = value;
00398         }else
00399             s->strippos = off;
00400         s->strips = count;
00401         if(s->strips == 1) s->rps = s->height;
00402         s->sot = type;
00403         break;
00404     case TIFF_STRIP_SIZE:
00405         if(count == 1){
00406             s->stripsizesoff = 0;
00407             s->stripsize     = value;
00408             s->strips        = 1;
00409         }else{
00410             s->stripsizesoff = off;
00411         }
00412         s->strips = count;
00413         s->sstype = type;
00414         break;
00415     case TIFF_PREDICTOR:
00416         s->predictor = value;
00417         break;
00418     case TIFF_INVERT:
00419         switch(value){
00420         case 0:
00421             s->invert = 1;
00422             break;
00423         case 1:
00424             s->invert = 0;
00425             break;
00426         case 2:
00427         case 3:
00428             break;
00429         default:
00430             av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n", value);
00431             return -1;
00432         }
00433         break;
00434     case TIFF_FILL_ORDER:
00435         if(value < 1 || value > 2){
00436             av_log(s->avctx, AV_LOG_ERROR, "Unknown FillOrder value %d, trying default one\n", value);
00437             value = 1;
00438         }
00439         s->fill_order = value - 1;
00440         break;
00441     case TIFF_PAL: {
00442         GetByteContext pal_gb[3];
00443         pal = (uint32_t *) s->palette;
00444         off = type_sizes[type];
00445         if (count / 3 > 256 ||
00446             bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)
00447             return -1;
00448         pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;
00449         bytestream2_skip(&pal_gb[1], count / 3 * off);
00450         bytestream2_skip(&pal_gb[2], count / 3 * off * 2);
00451         off = (type_sizes[type] - 1) << 3;
00452         for(i = 0; i < count / 3; i++){
00453             uint32_t p = 0xFF000000;
00454             p |= (tget(&pal_gb[0], type, s->le) >> off) << 16;
00455             p |= (tget(&pal_gb[1], type, s->le) >> off) << 8;
00456             p |=  tget(&pal_gb[2], type, s->le) >> off;
00457             pal[i] = p;
00458         }
00459         s->palette_is_set = 1;
00460         break;
00461     }
00462     case TIFF_PLANAR:
00463         if(value == 2){
00464             av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
00465             return -1;
00466         }
00467         break;
00468     case TIFF_T4OPTIONS:
00469         if(s->compr == TIFF_G3)
00470             s->fax_opts = value;
00471         break;
00472     case TIFF_T6OPTIONS:
00473         if(s->compr == TIFF_G4)
00474             s->fax_opts = value;
00475         break;
00476     default:
00477         av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n", tag, tag);
00478     }
00479     bytestream2_seek(&s->gb, start, SEEK_SET);
00480     return 0;
00481 }
00482 
00483 static int decode_frame(AVCodecContext *avctx,
00484                         void *data, int *data_size,
00485                         AVPacket *avpkt)
00486 {
00487     TiffContext * const s = avctx->priv_data;
00488     AVFrame *picture = data;
00489     AVFrame * const p= (AVFrame*)&s->picture;
00490     unsigned off;
00491     int id, le, ret;
00492     int i, j, entries;
00493     int stride;
00494     unsigned soff, ssize;
00495     uint8_t *dst;
00496     GetByteContext stripsizes;
00497     GetByteContext stripdata;
00498 
00499     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
00500 
00501     //parse image header
00502     if (avpkt->size < 8)
00503         return AVERROR_INVALIDDATA;
00504     id = bytestream2_get_le16(&s->gb);
00505     if(id == 0x4949) le = 1;
00506     else if(id == 0x4D4D) le = 0;
00507     else{
00508         av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");
00509         return -1;
00510     }
00511     s->le = le;
00512     s->invert = 0;
00513     s->compr = TIFF_RAW;
00514     s->fill_order = 0;
00515     // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number
00516     // that further identifies the file as a TIFF file"
00517     if (tget_short(&s->gb, le) != 42) {
00518         av_log(avctx, AV_LOG_ERROR, "The answer to life, universe and everything is not correct!\n");
00519         return -1;
00520     }
00521     // Reset these offsets so we can tell if they were set this frame
00522     s->stripsizesoff = s->strippos = 0;
00523     /* parse image file directory */
00524     off = tget_long(&s->gb, le);
00525     if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {
00526         av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");
00527         return AVERROR_INVALIDDATA;
00528     }
00529     bytestream2_seek(&s->gb, off, SEEK_SET);
00530     entries = tget_short(&s->gb, le);
00531     for(i = 0; i < entries; i++){
00532         if (tiff_decode_tag(s) < 0)
00533             return -1;
00534     }
00535     if (!s->strippos && !s->stripoff) {
00536         av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");
00537         return -1;
00538     }
00539     /* now we have the data and may start decoding */
00540     if ((ret = init_image(s)) < 0)
00541         return ret;
00542 
00543     if(s->strips == 1 && !s->stripsize){
00544         av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");
00545         s->stripsize = avpkt->size - s->stripoff;
00546     }
00547     stride = p->linesize[0];
00548     dst = p->data[0];
00549 
00550     if (s->stripsizesoff) {
00551         if (s->stripsizesoff >= avpkt->size)
00552             return AVERROR_INVALIDDATA;
00553         bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,
00554                          avpkt->size - s->stripsizesoff);
00555     }
00556     if (s->strippos) {
00557         if (s->strippos >= avpkt->size)
00558             return AVERROR_INVALIDDATA;
00559         bytestream2_init(&stripdata, avpkt->data + s->strippos,
00560                          avpkt->size - s->strippos);
00561     }
00562 
00563     for(i = 0; i < s->height; i += s->rps){
00564         if (s->stripsizesoff)
00565             ssize = tget(&stripsizes, s->sstype, le);
00566         else
00567             ssize = s->stripsize;
00568 
00569         if (s->strippos)
00570             soff = tget(&stripdata, s->sot, le);
00571         else
00572             soff = s->stripoff;
00573 
00574         if (soff > avpkt->size || ssize > avpkt->size - soff) {
00575             av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");
00576             return -1;
00577         }
00578         if (tiff_unpack_strip(s, dst, stride, avpkt->data + soff, ssize,
00579                               FFMIN(s->rps, s->height - i)) < 0)
00580             break;
00581         dst += s->rps * stride;
00582     }
00583     if(s->predictor == 2){
00584         dst = p->data[0];
00585         soff = s->bpp >> 3;
00586         ssize = s->width * soff;
00587         for(i = 0; i < s->height; i++) {
00588             for(j = soff; j < ssize; j++)
00589                 dst[j] += dst[j - soff];
00590             dst += stride;
00591         }
00592     }
00593 
00594     if(s->invert){
00595         uint8_t *src;
00596         int j;
00597 
00598         src = s->picture.data[0];
00599         for(j = 0; j < s->height; j++){
00600             for(i = 0; i < s->picture.linesize[0]; i++)
00601                 src[i] = 255 - src[i];
00602             src += s->picture.linesize[0];
00603         }
00604     }
00605     *picture= *(AVFrame*)&s->picture;
00606     *data_size = sizeof(AVPicture);
00607 
00608     return avpkt->size;
00609 }
00610 
00611 static av_cold int tiff_init(AVCodecContext *avctx){
00612     TiffContext *s = avctx->priv_data;
00613 
00614     s->width = 0;
00615     s->height = 0;
00616     s->avctx = avctx;
00617     avcodec_get_frame_defaults((AVFrame*)&s->picture);
00618     avctx->coded_frame= (AVFrame*)&s->picture;
00619     ff_lzw_decode_open(&s->lzw);
00620     ff_ccitt_unpack_init();
00621 
00622     return 0;
00623 }
00624 
00625 static av_cold int tiff_end(AVCodecContext *avctx)
00626 {
00627     TiffContext * const s = avctx->priv_data;
00628 
00629     ff_lzw_decode_close(&s->lzw);
00630     if(s->picture.data[0])
00631         avctx->release_buffer(avctx, &s->picture);
00632     return 0;
00633 }
00634 
00635 AVCodec ff_tiff_decoder = {
00636     .name           = "tiff",
00637     .type           = AVMEDIA_TYPE_VIDEO,
00638     .id             = CODEC_ID_TIFF,
00639     .priv_data_size = sizeof(TiffContext),
00640     .init           = tiff_init,
00641     .close          = tiff_end,
00642     .decode         = decode_frame,
00643     .capabilities   = CODEC_CAP_DR1,
00644     .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
00645 };