libavcodec/tiffenc.c
Go to the documentation of this file.
00001 /*
00002  * TIFF image encoder
00003  * Copyright (c) 2007 Bartlomiej Wolowiec
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 "libavutil/log.h"
00029 #include "libavutil/opt.h"
00030 
00031 #include "avcodec.h"
00032 #if CONFIG_ZLIB
00033 #include <zlib.h>
00034 #endif
00035 #include "bytestream.h"
00036 #include "tiff.h"
00037 #include "rle.h"
00038 #include "lzw.h"
00039 #include "put_bits.h"
00040 
00041 #define TIFF_MAX_ENTRY 32
00042 
00044 static const uint8_t type_sizes2[6] = {
00045     0, 1, 1, 2, 4, 8
00046 };
00047 
00048 typedef struct TiffEncoderContext {
00049     AVClass *class;                     
00050     AVCodecContext *avctx;
00051     AVFrame picture;
00052 
00053     int width;                          
00054     int height;                         
00055     unsigned int bpp;                   
00056     int compr;                          
00057     int bpp_tab_size;                   
00058     int photometric_interpretation;     
00059     int strips;                         
00060     int rps;                            
00061     uint8_t entries[TIFF_MAX_ENTRY*12]; 
00062     int num_entries;                    
00063     uint8_t **buf;                      
00064     uint8_t *buf_start;                 
00065     int buf_size;                       
00066     uint16_t subsampling[2];            
00067     struct LZWEncodeState *lzws;        
00068 } TiffEncoderContext;
00069 
00070 
00077 inline static int check_size(TiffEncoderContext * s, uint64_t need)
00078 {
00079     if (s->buf_size < *s->buf - s->buf_start + need) {
00080         *s->buf = s->buf_start + s->buf_size + 1;
00081         av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
00082         return 1;
00083     }
00084     return 0;
00085 }
00086 
00096 static void tnput(uint8_t ** p, int n, const uint8_t * val, enum TiffTypes type,
00097                   int flip)
00098 {
00099     int i;
00100 #if HAVE_BIGENDIAN
00101     flip ^= ((int[]) {0, 0, 0, 1, 3, 3})[type];
00102 #endif
00103     for (i = 0; i < n * type_sizes2[type]; i++)
00104         *(*p)++ = val[i ^ flip];
00105 }
00106 
00115 static void add_entry(TiffEncoderContext * s,
00116                       enum TiffTags tag, enum TiffTypes type, int count,
00117                       const void *ptr_val)
00118 {
00119     uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
00120 
00121     assert(s->num_entries < TIFF_MAX_ENTRY);
00122 
00123     bytestream_put_le16(&entries_ptr, tag);
00124     bytestream_put_le16(&entries_ptr, type);
00125     bytestream_put_le32(&entries_ptr, count);
00126 
00127     if (type_sizes[type] * count <= 4) {
00128         tnput(&entries_ptr, count, ptr_val, type, 0);
00129     } else {
00130         bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
00131         check_size(s, count * type_sizes2[type]);
00132         tnput(s->buf, count, ptr_val, type, 0);
00133     }
00134 
00135     s->num_entries++;
00136 }
00137 
00138 static void add_entry1(TiffEncoderContext * s,
00139                        enum TiffTags tag, enum TiffTypes type, int val){
00140     uint16_t w = val;
00141     uint32_t dw= val;
00142     add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
00143 }
00144 
00155 static int encode_strip(TiffEncoderContext * s, const int8_t * src,
00156                         uint8_t * dst, int n, int compr)
00157 {
00158 
00159     switch (compr) {
00160 #if CONFIG_ZLIB
00161     case TIFF_DEFLATE:
00162     case TIFF_ADOBE_DEFLATE:
00163         {
00164             unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
00165             if (compress(dst, &zlen, src, n) != Z_OK) {
00166                 av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
00167                 return -1;
00168             }
00169             return zlen;
00170         }
00171 #endif
00172     case TIFF_RAW:
00173         if (check_size(s, n))
00174             return -1;
00175         memcpy(dst, src, n);
00176         return n;
00177     case TIFF_PACKBITS:
00178         return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start), src, 1, n, 2, 0xff, -1, 0);
00179     case TIFF_LZW:
00180         return ff_lzw_encode(s->lzws, src, n);
00181     default:
00182         return -1;
00183     }
00184 }
00185 
00186 static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum)
00187 {
00188     AVFrame *p = &s->picture;
00189     int i, j, k;
00190     int w = (s->width - 1) / s->subsampling[0] + 1;
00191     uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
00192     uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
00193     for (i = 0; i < w; i++){
00194         for (j = 0; j < s->subsampling[1]; j++)
00195             for (k = 0; k < s->subsampling[0]; k++)
00196                 *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
00197                                     i * s->subsampling[0] + k];
00198         *dst++ = *pu++;
00199         *dst++ = *pv++;
00200     }
00201 }
00202 
00203 static int encode_frame(AVCodecContext * avctx, unsigned char *buf,
00204                         int buf_size, void *data)
00205 {
00206     TiffEncoderContext *s = avctx->priv_data;
00207     AVFrame *pict = data;
00208     AVFrame *const p = (AVFrame *) & s->picture;
00209     int i;
00210     int n;
00211     uint8_t *ptr = buf;
00212     uint8_t *offset;
00213     uint32_t strips;
00214     uint32_t *strip_sizes = NULL;
00215     uint32_t *strip_offsets = NULL;
00216     int bytes_per_row;
00217     uint32_t res[2] = { 72, 1 };        // image resolution (72/1)
00218     static const uint16_t bpp_tab[] = { 8, 8, 8, 8 };
00219     int ret = -1;
00220     int is_yuv = 0;
00221     uint8_t *yuv_line = NULL;
00222     int shift_h, shift_v;
00223 
00224     s->avctx = avctx;
00225     s->buf_start = buf;
00226     s->buf = &ptr;
00227     s->buf_size = buf_size;
00228 
00229     *p = *pict;
00230     p->pict_type = AV_PICTURE_TYPE_I;
00231     p->key_frame = 1;
00232     avctx->coded_frame= &s->picture;
00233 
00234 #if FF_API_TIFFENC_COMPLEVEL
00235     if (avctx->compression_level != FF_COMPRESSION_DEFAULT)
00236         av_log(avctx, AV_LOG_WARNING, "Using compression_level to set compression "
00237                "algorithm is deprecated. Please use the compression_algo private "
00238                "option instead.\n");
00239     if (avctx->compression_level == 0) {
00240         s->compr = TIFF_RAW;
00241     } else if(avctx->compression_level == 2) {
00242         s->compr = TIFF_LZW;
00243 #if CONFIG_ZLIB
00244     } else if ((avctx->compression_level >= 3)) {
00245         s->compr = TIFF_DEFLATE;
00246 #endif
00247     }
00248 #endif
00249 
00250     s->width = avctx->width;
00251     s->height = avctx->height;
00252     s->subsampling[0] = 1;
00253     s->subsampling[1] = 1;
00254 
00255     switch (avctx->pix_fmt) {
00256     case PIX_FMT_RGB24:
00257         s->bpp = 24;
00258         s->photometric_interpretation = 2;
00259         break;
00260     case PIX_FMT_GRAY8:
00261         s->bpp = 8;
00262         s->photometric_interpretation = 1;
00263         break;
00264     case PIX_FMT_PAL8:
00265         s->bpp = 8;
00266         s->photometric_interpretation = 3;
00267         break;
00268     case PIX_FMT_MONOBLACK:
00269         s->bpp = 1;
00270         s->photometric_interpretation = 1;
00271         break;
00272     case PIX_FMT_MONOWHITE:
00273         s->bpp = 1;
00274         s->photometric_interpretation = 0;
00275         break;
00276     case PIX_FMT_YUV420P:
00277     case PIX_FMT_YUV422P:
00278     case PIX_FMT_YUV444P:
00279     case PIX_FMT_YUV410P:
00280     case PIX_FMT_YUV411P:
00281         s->photometric_interpretation = 6;
00282         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
00283                 &shift_h, &shift_v);
00284         s->bpp = 8 + (16 >> (shift_h + shift_v));
00285         s->subsampling[0] = 1 << shift_h;
00286         s->subsampling[1] = 1 << shift_v;
00287         s->bpp_tab_size = 3;
00288         is_yuv = 1;
00289         break;
00290     default:
00291         av_log(s->avctx, AV_LOG_ERROR,
00292                "This colors format is not supported\n");
00293         return -1;
00294     }
00295     if (!is_yuv)
00296         s->bpp_tab_size = (s->bpp >> 3);
00297 
00298     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
00299         //best choose for DEFLATE
00300         s->rps = s->height;
00301     else
00302         s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);     // suggest size of strip
00303     s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
00304 
00305     strips = (s->height - 1) / s->rps + 1;
00306 
00307     if (check_size(s, 8))
00308         goto fail;
00309 
00310     // write header
00311     bytestream_put_le16(&ptr, 0x4949);
00312     bytestream_put_le16(&ptr, 42);
00313 
00314     offset = ptr;
00315     bytestream_put_le32(&ptr, 0);
00316 
00317     strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
00318     strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
00319     if (!strip_sizes || !strip_offsets) {
00320         ret = AVERROR(ENOMEM);
00321         goto fail;
00322     }
00323 
00324     bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
00325                     * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
00326     if (is_yuv){
00327         yuv_line = av_malloc(bytes_per_row);
00328         if (yuv_line == NULL){
00329             av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
00330             ret = AVERROR(ENOMEM);
00331             goto fail;
00332         }
00333     }
00334 
00335 #if CONFIG_ZLIB
00336     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
00337         uint8_t *zbuf;
00338         int zlen, zn;
00339         int j;
00340 
00341         zlen = bytes_per_row * s->rps;
00342         zbuf = av_malloc(zlen);
00343         if (!zbuf) {
00344             ret = AVERROR(ENOMEM);
00345             goto fail;
00346         }
00347         strip_offsets[0] = ptr - buf;
00348         zn = 0;
00349         for (j = 0; j < s->rps; j++) {
00350             if (is_yuv){
00351                 pack_yuv(s, yuv_line, j);
00352                 memcpy(zbuf + zn, yuv_line, bytes_per_row);
00353                 j += s->subsampling[1] - 1;
00354             }
00355             else
00356                 memcpy(zbuf + j * bytes_per_row,
00357                        p->data[0] + j * p->linesize[0], bytes_per_row);
00358             zn += bytes_per_row;
00359         }
00360         n = encode_strip(s, zbuf, ptr, zn, s->compr);
00361         av_free(zbuf);
00362         if (n<0) {
00363             av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
00364             goto fail;
00365         }
00366         ptr += n;
00367         strip_sizes[0] = ptr - buf - strip_offsets[0];
00368     } else
00369 #endif
00370     {
00371         if (s->compr == TIFF_LZW) {
00372             s->lzws = av_malloc(ff_lzw_encode_state_size);
00373             if (!s->lzws) {
00374                 ret = AVERROR(ENOMEM);
00375                 goto fail;
00376             }
00377         }
00378         for (i = 0; i < s->height; i++) {
00379             if (strip_sizes[i / s->rps] == 0) {
00380                 if(s->compr == TIFF_LZW){
00381                     ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
00382                                        12, FF_LZW_TIFF, put_bits);
00383                 }
00384                 strip_offsets[i / s->rps] = ptr - buf;
00385             }
00386             if (is_yuv){
00387                  pack_yuv(s, yuv_line, i);
00388                  n = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
00389                  i += s->subsampling[1] - 1;
00390             }
00391             else
00392                 n = encode_strip(s, p->data[0] + i * p->linesize[0],
00393                         ptr, bytes_per_row, s->compr);
00394             if (n < 0) {
00395                 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
00396                 goto fail;
00397             }
00398             strip_sizes[i / s->rps] += n;
00399             ptr += n;
00400             if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
00401                 int ret;
00402                 ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
00403                 strip_sizes[(i / s->rps )] += ret ;
00404                 ptr += ret;
00405             }
00406         }
00407         if(s->compr == TIFF_LZW)
00408             av_free(s->lzws);
00409     }
00410 
00411     s->num_entries = 0;
00412 
00413     add_entry1(s,TIFF_SUBFILE,           TIFF_LONG,             0);
00414     add_entry1(s,TIFF_WIDTH,             TIFF_LONG,             s->width);
00415     add_entry1(s,TIFF_HEIGHT,            TIFF_LONG,             s->height);
00416 
00417     if (s->bpp_tab_size)
00418     add_entry(s, TIFF_BPP,               TIFF_SHORT,    s->bpp_tab_size, bpp_tab);
00419 
00420     add_entry1(s,TIFF_COMPR,             TIFF_SHORT,            s->compr);
00421     add_entry1(s,TIFF_INVERT,            TIFF_SHORT,            s->photometric_interpretation);
00422     add_entry(s, TIFF_STRIP_OFFS,        TIFF_LONG,     strips, strip_offsets);
00423 
00424     if (s->bpp_tab_size)
00425     add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT,            s->bpp_tab_size);
00426 
00427     add_entry1(s,TIFF_ROWSPERSTRIP,      TIFF_LONG,             s->rps);
00428     add_entry(s, TIFF_STRIP_SIZE,        TIFF_LONG,     strips, strip_sizes);
00429     add_entry(s, TIFF_XRES,              TIFF_RATIONAL, 1,      res);
00430     add_entry(s, TIFF_YRES,              TIFF_RATIONAL, 1,      res);
00431     add_entry1(s,TIFF_RES_UNIT,          TIFF_SHORT,            2);
00432 
00433     if(!(avctx->flags & CODEC_FLAG_BITEXACT))
00434     add_entry(s, TIFF_SOFTWARE_NAME,     TIFF_STRING,
00435               strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
00436 
00437     if (avctx->pix_fmt == PIX_FMT_PAL8) {
00438         uint16_t pal[256 * 3];
00439         for (i = 0; i < 256; i++) {
00440             uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
00441             pal[i]       = ((rgb >> 16) & 0xff) * 257;
00442             pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
00443             pal[i + 512] = ( rgb        & 0xff) * 257;
00444         }
00445         add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
00446     }
00447     if (is_yuv){
00449         uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
00450         add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT,    2, s->subsampling);
00451         add_entry(s, TIFF_REFERENCE_BW,      TIFF_RATIONAL, 6, refbw);
00452     }
00453     bytestream_put_le32(&offset, ptr - buf);    // write offset to dir
00454 
00455     if (check_size(s, 6 + s->num_entries * 12))
00456         goto fail;
00457     bytestream_put_le16(&ptr, s->num_entries);  // write tag count
00458     bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
00459     bytestream_put_le32(&ptr, 0);
00460 
00461     ret = ptr - buf;
00462 
00463 fail:
00464     av_free(strip_sizes);
00465     av_free(strip_offsets);
00466     av_free(yuv_line);
00467     return ret;
00468 }
00469 
00470 #define OFFSET(x) offsetof(TiffEncoderContext, x)
00471 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
00472 static const AVOption options[] = {
00473     { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
00474     { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
00475     { "raw",      NULL, 0, AV_OPT_TYPE_CONST, {TIFF_RAW},      0, 0, VE, "compression_algo" },
00476     { "lzw",      NULL, 0, AV_OPT_TYPE_CONST, {TIFF_LZW},      0, 0, VE, "compression_algo" },
00477 #if CONFIG_ZLIB
00478     { "deflate",  NULL, 0, AV_OPT_TYPE_CONST, {TIFF_DEFLATE},  0, 0, VE, "compression_algo" },
00479 #endif
00480     { NULL },
00481 };
00482 
00483 static const AVClass tiffenc_class = {
00484     .class_name = "TIFF encoder",
00485     .item_name  = av_default_item_name,
00486     .option     = options,
00487     .version    = LIBAVUTIL_VERSION_INT,
00488 };
00489 
00490 AVCodec ff_tiff_encoder = {
00491     .name           = "tiff",
00492     .type           = AVMEDIA_TYPE_VIDEO,
00493     .id             = CODEC_ID_TIFF,
00494     .priv_data_size = sizeof(TiffEncoderContext),
00495     .encode         = encode_frame,
00496     .pix_fmts =
00497         (const enum PixelFormat[]) {PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8,
00498                               PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
00499                               PIX_FMT_YUV420P, PIX_FMT_YUV422P,
00500                               PIX_FMT_YUV444P, PIX_FMT_YUV410P,
00501                               PIX_FMT_YUV411P,
00502                               PIX_FMT_NONE},
00503     .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
00504     .priv_class     = &tiffenc_class,
00505 };