]> git.sesse.net Git - ffmpeg/blob - libavcodec/tiffenc.c
c3d09805953254f8f43623091ed9febe2d0c90c7
[ffmpeg] / libavcodec / tiffenc.c
1 /*
2  * TIFF image encoder
3  * Copyright (c) 2007 Bartlomiej Wolowiec
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  * @file
24  * TIFF image encoder
25  * @author Bartlomiej Wolowiec
26  */
27
28 #include "libavutil/imgutils.h"
29 #include "libavutil/log.h"
30 #include "libavutil/opt.h"
31
32 #include "avcodec.h"
33 #include "config.h"
34 #if CONFIG_ZLIB
35 #include <zlib.h>
36 #endif
37 #include "bytestream.h"
38 #include "internal.h"
39 #include "tiff.h"
40 #include "rle.h"
41 #include "lzw.h"
42 #include "put_bits.h"
43
44 #define TIFF_MAX_ENTRY 32
45
46 /** sizes of various TIFF field types (string size = 1)*/
47 static const uint8_t type_sizes2[14] = {
48     0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4
49 };
50
51 typedef struct TiffEncoderContext {
52     AVClass *class;                     ///< for private options
53     AVCodecContext *avctx;
54     AVFrame picture;
55
56     int width;                          ///< picture width
57     int height;                         ///< picture height
58     unsigned int bpp;                   ///< bits per pixel
59     int compr;                          ///< compression level
60     int bpp_tab_size;                   ///< bpp_tab size
61     int photometric_interpretation;     ///< photometric interpretation
62     int strips;                         ///< number of strips
63     uint32_t *strip_sizes;
64     unsigned int strip_sizes_size;
65     uint32_t *strip_offsets;
66     unsigned int strip_offsets_size;
67     uint8_t *yuv_line;
68     unsigned int yuv_line_size;
69     int rps;                            ///< row per strip
70     uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
71     int num_entries;                    ///< number of entires
72     uint8_t **buf;                      ///< actual position in buffer
73     uint8_t *buf_start;                 ///< pointer to first byte in buffer
74     int buf_size;                       ///< buffer size
75     uint16_t subsampling[2];            ///< YUV subsampling factors
76     struct LZWEncodeState *lzws;        ///< LZW Encode state
77     uint32_t dpi;                       ///< image resolution in DPI
78 } TiffEncoderContext;
79
80
81 /**
82  * Check free space in buffer.
83  *
84  * @param s Tiff context
85  * @param need Needed bytes
86  * @return 0 - ok, 1 - no free space
87  */
88 static inline int check_size(TiffEncoderContext * s, uint64_t need)
89 {
90     if (s->buf_size < *s->buf - s->buf_start + need) {
91         *s->buf = s->buf_start + s->buf_size + 1;
92         av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
93         return 1;
94     }
95     return 0;
96 }
97
98 /**
99  * Put n values to buffer.
100  *
101  * @param p pointer to pointer to output buffer
102  * @param n number of values
103  * @param val pointer to values
104  * @param type type of values
105  * @param flip = 0 - normal copy, >0 - flip
106  */
107 static void tnput(uint8_t ** p, int n, const uint8_t * val, enum TiffTypes type,
108                   int flip)
109 {
110     int i;
111 #if HAVE_BIGENDIAN
112     flip ^= ((int[]) {0, 0, 0, 1, 3, 3})[type];
113 #endif
114     for (i = 0; i < n * type_sizes2[type]; i++)
115         *(*p)++ = val[i ^ flip];
116 }
117
118 /**
119  * Add entry to directory in tiff header.
120  *
121  * @param s Tiff context
122  * @param tag tag that identifies the entry
123  * @param type entry type
124  * @param count the number of values
125  * @param ptr_val pointer to values
126  */
127 static void add_entry(TiffEncoderContext * s,
128                       enum TiffTags tag, enum TiffTypes type, int count,
129                       const void *ptr_val)
130 {
131     uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
132
133     av_assert0(s->num_entries < TIFF_MAX_ENTRY);
134
135     bytestream_put_le16(&entries_ptr, tag);
136     bytestream_put_le16(&entries_ptr, type);
137     bytestream_put_le32(&entries_ptr, count);
138
139     if (type_sizes[type] * count <= 4) {
140         tnput(&entries_ptr, count, ptr_val, type, 0);
141     } else {
142         bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
143         check_size(s, count * type_sizes2[type]);
144         tnput(s->buf, count, ptr_val, type, 0);
145     }
146
147     s->num_entries++;
148 }
149
150 static void add_entry1(TiffEncoderContext * s,
151                        enum TiffTags tag, enum TiffTypes type, int val){
152     uint16_t w = val;
153     uint32_t dw= val;
154     add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
155 }
156
157 /**
158  * Encode one strip in tiff file.
159  *
160  * @param s Tiff context
161  * @param src input buffer
162  * @param dst output buffer
163  * @param n size of input buffer
164  * @param compr compression method
165  * @return number of output bytes. If an output error is encountered, -1 is returned
166  */
167 static int encode_strip(TiffEncoderContext * s, const int8_t * src,
168                         uint8_t * dst, int n, int compr)
169 {
170
171     switch (compr) {
172 #if CONFIG_ZLIB
173     case TIFF_DEFLATE:
174     case TIFF_ADOBE_DEFLATE:
175         {
176             unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
177             if (compress(dst, &zlen, src, n) != Z_OK) {
178                 av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
179                 return -1;
180             }
181             return zlen;
182         }
183 #endif
184     case TIFF_RAW:
185         if (check_size(s, n))
186             return -1;
187         memcpy(dst, src, n);
188         return n;
189     case TIFF_PACKBITS:
190         return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start), src, 1, n, 2, 0xff, -1, 0);
191     case TIFF_LZW:
192         return ff_lzw_encode(s->lzws, src, n);
193     default:
194         return -1;
195     }
196 }
197
198 static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum)
199 {
200     AVFrame *p = &s->picture;
201     int i, j, k;
202     int w = (s->width - 1) / s->subsampling[0] + 1;
203     uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
204     uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
205     if(s->width % s->subsampling[0] || s->height % s->subsampling[1]){
206         for (i = 0; i < w; i++){
207             for (j = 0; j < s->subsampling[1]; j++)
208                 for (k = 0; k < s->subsampling[0]; k++)
209                     *dst++ = p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
210                                         FFMIN(i * s->subsampling[0] + k, s->width-1)];
211             *dst++ = *pu++;
212             *dst++ = *pv++;
213         }
214     }else{
215         for (i = 0; i < w; i++){
216             for (j = 0; j < s->subsampling[1]; j++)
217                 for (k = 0; k < s->subsampling[0]; k++)
218                     *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
219                                         i * s->subsampling[0] + k];
220             *dst++ = *pu++;
221             *dst++ = *pv++;
222         }
223     }
224 }
225
226 static av_cold int encode_init(AVCodecContext *avctx)
227 {
228     TiffEncoderContext *s = avctx->priv_data;
229
230     avctx->coded_frame= &s->picture;
231     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
232     avctx->coded_frame->key_frame = 1;
233     s->avctx = avctx;
234
235     return 0;
236 }
237
238 static int encode_frame(AVCodecContext * avctx, AVPacket *pkt,
239                         const AVFrame *pict, int *got_packet)
240 {
241     TiffEncoderContext *s = avctx->priv_data;
242     AVFrame *const p = &s->picture;
243     int i;
244     uint8_t *ptr;
245     uint8_t *offset;
246     uint32_t strips;
247     int bytes_per_row;
248     uint32_t res[2] = { s->dpi, 1 };        // image resolution (72/1)
249     uint16_t bpp_tab[4];
250     int ret = -1;
251     int is_yuv = 0;
252     int shift_h, shift_v;
253
254     *p = *pict;
255
256     s->width = avctx->width;
257     s->height = avctx->height;
258     s->subsampling[0] = 1;
259     s->subsampling[1] = 1;
260
261     avctx->bits_per_coded_sample =
262     s->bpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[avctx->pix_fmt]);
263
264     switch (avctx->pix_fmt) {
265     case PIX_FMT_RGBA64LE:
266     case PIX_FMT_RGBA:
267     case PIX_FMT_RGB48LE:
268     case PIX_FMT_RGB24:
269         s->photometric_interpretation = 2;
270         break;
271     case PIX_FMT_GRAY8:
272         avctx->bits_per_coded_sample = 0x28;
273     case PIX_FMT_GRAY8A:
274     case PIX_FMT_GRAY16LE:
275     case PIX_FMT_MONOBLACK:
276         s->photometric_interpretation = 1;
277         break;
278     case PIX_FMT_PAL8:
279         s->photometric_interpretation = 3;
280         break;
281     case PIX_FMT_MONOWHITE:
282         s->photometric_interpretation = 0;
283         break;
284     case PIX_FMT_YUV420P:
285     case PIX_FMT_YUV422P:
286     case PIX_FMT_YUV440P:
287     case PIX_FMT_YUV444P:
288     case PIX_FMT_YUV410P:
289     case PIX_FMT_YUV411P:
290         s->photometric_interpretation = 6;
291         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
292                 &shift_h, &shift_v);
293         s->subsampling[0] = 1 << shift_h;
294         s->subsampling[1] = 1 << shift_v;
295         is_yuv = 1;
296         break;
297     default:
298         av_log(s->avctx, AV_LOG_ERROR,
299                "This colors format is not supported\n");
300         return -1;
301     }
302
303     s->bpp_tab_size = av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
304     for (i = 0; i < s->bpp_tab_size; i++)
305         bpp_tab[i] = av_pix_fmt_descriptors[avctx->pix_fmt].comp[i].depth_minus1 + 1;
306
307     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
308         //best choose for DEFLATE
309         s->rps = s->height;
310     else
311         s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);     // suggest size of strip
312     s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
313
314     strips = (s->height - 1) / s->rps + 1;
315
316     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width * avctx->height * s->bpp * 2 +
317                                   avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
318         return ret;
319     ptr          = pkt->data;
320     s->buf_start = pkt->data;
321     s->buf       = &ptr;
322     s->buf_size  = pkt->size;
323
324     if (check_size(s, 8))
325         goto fail;
326
327     // write header
328     bytestream_put_le16(&ptr, 0x4949);
329     bytestream_put_le16(&ptr, 42);
330
331     offset = ptr;
332     bytestream_put_le32(&ptr, 0);
333
334     av_fast_padded_mallocz(&s->strip_sizes, &s->strip_sizes_size, sizeof(s->strip_sizes[0]) * strips);
335     av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
336
337     if (!s->strip_sizes || !s->strip_offsets) {
338         ret = AVERROR(ENOMEM);
339         goto fail;
340     }
341
342     bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
343                     * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
344     if (is_yuv){
345         av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
346         if (s->yuv_line == NULL){
347             ret = AVERROR(ENOMEM);
348             goto fail;
349         }
350     }
351
352 #if CONFIG_ZLIB
353     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
354         uint8_t *zbuf;
355         int zlen, zn;
356         int j;
357
358         zlen = bytes_per_row * s->rps;
359         zbuf = av_malloc(zlen);
360         s->strip_offsets[0] = ptr - pkt->data;
361         zn = 0;
362         for (j = 0; j < s->rps; j++) {
363             if (is_yuv){
364                 pack_yuv(s, s->yuv_line, j);
365                 memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
366                 j += s->subsampling[1] - 1;
367             }
368             else
369                 memcpy(zbuf + j * bytes_per_row,
370                        p->data[0] + j * p->linesize[0], bytes_per_row);
371             zn += bytes_per_row;
372         }
373         ret = encode_strip(s, zbuf, ptr, zn, s->compr);
374         av_free(zbuf);
375         if (ret < 0) {
376             av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
377             goto fail;
378         }
379         ptr += ret;
380         s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
381     } else
382 #endif
383     {
384         if(s->compr == TIFF_LZW)
385             s->lzws = av_malloc(ff_lzw_encode_state_size);
386         for (i = 0; i < s->height; i++) {
387             if (s->strip_sizes[i / s->rps] == 0) {
388                 if(s->compr == TIFF_LZW){
389                     ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
390                                        12, FF_LZW_TIFF, put_bits);
391                 }
392                 s->strip_offsets[i / s->rps] = ptr - pkt->data;
393             }
394             if (is_yuv){
395                  pack_yuv(s, s->yuv_line, i);
396                  ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
397                  i += s->subsampling[1] - 1;
398             }
399             else
400                 ret = encode_strip(s, p->data[0] + i * p->linesize[0],
401                         ptr, bytes_per_row, s->compr);
402             if (ret < 0) {
403                 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
404                 goto fail;
405             }
406             s->strip_sizes[i / s->rps] += ret;
407             ptr += ret;
408             if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
409                 ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
410                 s->strip_sizes[(i / s->rps )] += ret ;
411                 ptr += ret;
412             }
413         }
414         if(s->compr == TIFF_LZW)
415             av_free(s->lzws);
416     }
417
418     s->num_entries = 0;
419
420     add_entry1(s,TIFF_SUBFILE,           TIFF_LONG,             0);
421     add_entry1(s,TIFF_WIDTH,             TIFF_LONG,             s->width);
422     add_entry1(s,TIFF_HEIGHT,            TIFF_LONG,             s->height);
423
424     if (s->bpp_tab_size)
425     add_entry(s, TIFF_BPP,               TIFF_SHORT,    s->bpp_tab_size, bpp_tab);
426
427     add_entry1(s,TIFF_COMPR,             TIFF_SHORT,            s->compr);
428     add_entry1(s,TIFF_INVERT,            TIFF_SHORT,            s->photometric_interpretation);
429     add_entry(s, TIFF_STRIP_OFFS,        TIFF_LONG,     strips, s->strip_offsets);
430
431     if (s->bpp_tab_size)
432     add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT,            s->bpp_tab_size);
433
434     add_entry1(s,TIFF_ROWSPERSTRIP,      TIFF_LONG,             s->rps);
435     add_entry(s, TIFF_STRIP_SIZE,        TIFF_LONG,     strips, s->strip_sizes);
436     add_entry(s, TIFF_XRES,              TIFF_RATIONAL, 1,      res);
437     add_entry(s, TIFF_YRES,              TIFF_RATIONAL, 1,      res);
438     add_entry1(s,TIFF_RES_UNIT,          TIFF_SHORT,            2);
439
440     if(!(avctx->flags & CODEC_FLAG_BITEXACT))
441     add_entry(s, TIFF_SOFTWARE_NAME,     TIFF_STRING,
442               strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
443
444     if (avctx->pix_fmt == PIX_FMT_PAL8) {
445         uint16_t pal[256 * 3];
446         for (i = 0; i < 256; i++) {
447             uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
448             pal[i]       = ((rgb >> 16) & 0xff) * 257;
449             pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
450             pal[i + 512] = ( rgb        & 0xff) * 257;
451         }
452         add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
453     }
454     if (is_yuv){
455         /** according to CCIR Recommendation 601.1 */
456         uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
457         add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT,    2, s->subsampling);
458         add_entry(s, TIFF_REFERENCE_BW,      TIFF_RATIONAL, 6, refbw);
459     }
460     bytestream_put_le32(&offset, ptr - pkt->data);    // write offset to dir
461
462     if (check_size(s, 6 + s->num_entries * 12)) {
463         ret = AVERROR(EINVAL);
464         goto fail;
465     }
466     bytestream_put_le16(&ptr, s->num_entries);  // write tag count
467     bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
468     bytestream_put_le32(&ptr, 0);
469
470     pkt->size   = ptr - pkt->data;
471     pkt->flags |= AV_PKT_FLAG_KEY;
472     *got_packet = 1;
473
474 fail:
475     return ret < 0 ? ret : 0;
476 }
477
478 static av_cold int encode_close(AVCodecContext *avctx)
479 {
480     TiffEncoderContext *s = avctx->priv_data;
481
482     av_freep(&s->strip_sizes);
483     av_freep(&s->strip_offsets);
484     av_freep(&s->yuv_line);
485
486     return 0;
487 }
488
489 #define OFFSET(x) offsetof(TiffEncoderContext, x)
490 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
491 static const AVOption options[] = {
492     {"dpi", "set the image resolution (in dpi)", OFFSET(dpi), AV_OPT_TYPE_INT, {.dbl = 72}, 1, 0x10000, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_ENCODING_PARAM},
493     { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
494     { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
495     { "raw",      NULL, 0, AV_OPT_TYPE_CONST, {TIFF_RAW},      0, 0, VE, "compression_algo" },
496     { "lzw",      NULL, 0, AV_OPT_TYPE_CONST, {TIFF_LZW},      0, 0, VE, "compression_algo" },
497 #if CONFIG_ZLIB
498     { "deflate",  NULL, 0, AV_OPT_TYPE_CONST, {TIFF_DEFLATE},  0, 0, VE, "compression_algo" },
499 #endif
500     { NULL },
501 };
502
503 static const AVClass tiffenc_class = {
504     .class_name = "TIFF encoder",
505     .item_name  = av_default_item_name,
506     .option     = options,
507     .version    = LIBAVUTIL_VERSION_INT,
508 };
509
510 AVCodec ff_tiff_encoder = {
511     .name           = "tiff",
512     .type           = AVMEDIA_TYPE_VIDEO,
513     .id             = AV_CODEC_ID_TIFF,
514     .priv_data_size = sizeof(TiffEncoderContext),
515     .init           = encode_init,
516     .encode2        = encode_frame,
517     .close          = encode_close,
518     .pix_fmts       = (const enum PixelFormat[]) {
519         PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8, PIX_FMT_GRAY8A, PIX_FMT_GRAY16LE,
520         PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
521         PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV440P, PIX_FMT_YUV444P,
522         PIX_FMT_YUV410P, PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
523         PIX_FMT_RGBA, PIX_FMT_RGBA64LE,
524         PIX_FMT_NONE
525     },
526     .long_name      = NULL_IF_CONFIG_SMALL("TIFF image"),
527     .priv_class     = &tiffenc_class,
528 };