]> git.sesse.net Git - ffmpeg/blob - libavcodec/tiffenc.c
Merge remote-tracking branch 'cus/stable'
[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, alpha = 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         alpha = 1;
268     case PIX_FMT_RGB48LE:
269     case PIX_FMT_RGB24:
270         s->photometric_interpretation = 2;
271         break;
272     case PIX_FMT_GRAY8:
273         avctx->bits_per_coded_sample = 0x28;
274     case PIX_FMT_GRAY8A:
275         alpha = avctx->pix_fmt == PIX_FMT_GRAY8A;
276     case PIX_FMT_GRAY16LE:
277     case PIX_FMT_MONOBLACK:
278         s->photometric_interpretation = 1;
279         break;
280     case PIX_FMT_PAL8:
281         s->photometric_interpretation = 3;
282         break;
283     case PIX_FMT_MONOWHITE:
284         s->photometric_interpretation = 0;
285         break;
286     case PIX_FMT_YUV420P:
287     case PIX_FMT_YUV422P:
288     case PIX_FMT_YUV440P:
289     case PIX_FMT_YUV444P:
290     case PIX_FMT_YUV410P:
291     case PIX_FMT_YUV411P:
292         s->photometric_interpretation = 6;
293         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
294                 &shift_h, &shift_v);
295         s->subsampling[0] = 1 << shift_h;
296         s->subsampling[1] = 1 << shift_v;
297         is_yuv = 1;
298         break;
299     default:
300         av_log(s->avctx, AV_LOG_ERROR,
301                "This colors format is not supported\n");
302         return -1;
303     }
304
305     s->bpp_tab_size = av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
306     for (i = 0; i < s->bpp_tab_size; i++)
307         bpp_tab[i] = av_pix_fmt_descriptors[avctx->pix_fmt].comp[i].depth_minus1 + 1;
308
309     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
310         //best choose for DEFLATE
311         s->rps = s->height;
312     else
313         s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);     // suggest size of strip
314     s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
315
316     strips = (s->height - 1) / s->rps + 1;
317
318     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width * avctx->height * s->bpp * 2 +
319                                   avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
320         return ret;
321     ptr          = pkt->data;
322     s->buf_start = pkt->data;
323     s->buf       = &ptr;
324     s->buf_size  = pkt->size;
325
326     if (check_size(s, 8))
327         goto fail;
328
329     // write header
330     bytestream_put_le16(&ptr, 0x4949);
331     bytestream_put_le16(&ptr, 42);
332
333     offset = ptr;
334     bytestream_put_le32(&ptr, 0);
335
336     av_fast_padded_mallocz(&s->strip_sizes, &s->strip_sizes_size, sizeof(s->strip_sizes[0]) * strips);
337     av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
338
339     if (!s->strip_sizes || !s->strip_offsets) {
340         ret = AVERROR(ENOMEM);
341         goto fail;
342     }
343
344     bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
345                     * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
346     if (is_yuv){
347         av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
348         if (s->yuv_line == NULL){
349             ret = AVERROR(ENOMEM);
350             goto fail;
351         }
352     }
353
354 #if CONFIG_ZLIB
355     if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
356         uint8_t *zbuf;
357         int zlen, zn;
358         int j;
359
360         zlen = bytes_per_row * s->rps;
361         zbuf = av_malloc(zlen);
362         s->strip_offsets[0] = ptr - pkt->data;
363         zn = 0;
364         for (j = 0; j < s->rps; j++) {
365             if (is_yuv){
366                 pack_yuv(s, s->yuv_line, j);
367                 memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
368                 j += s->subsampling[1] - 1;
369             }
370             else
371                 memcpy(zbuf + j * bytes_per_row,
372                        p->data[0] + j * p->linesize[0], bytes_per_row);
373             zn += bytes_per_row;
374         }
375         ret = encode_strip(s, zbuf, ptr, zn, s->compr);
376         av_free(zbuf);
377         if (ret < 0) {
378             av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
379             goto fail;
380         }
381         ptr += ret;
382         s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
383     } else
384 #endif
385     {
386         if(s->compr == TIFF_LZW)
387             s->lzws = av_malloc(ff_lzw_encode_state_size);
388         for (i = 0; i < s->height; i++) {
389             if (s->strip_sizes[i / s->rps] == 0) {
390                 if(s->compr == TIFF_LZW){
391                     ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
392                                        12, FF_LZW_TIFF, put_bits);
393                 }
394                 s->strip_offsets[i / s->rps] = ptr - pkt->data;
395             }
396             if (is_yuv){
397                  pack_yuv(s, s->yuv_line, i);
398                  ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
399                  i += s->subsampling[1] - 1;
400             }
401             else
402                 ret = encode_strip(s, p->data[0] + i * p->linesize[0],
403                         ptr, bytes_per_row, s->compr);
404             if (ret < 0) {
405                 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
406                 goto fail;
407             }
408             s->strip_sizes[i / s->rps] += ret;
409             ptr += ret;
410             if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
411                 ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
412                 s->strip_sizes[(i / s->rps )] += ret ;
413                 ptr += ret;
414             }
415         }
416         if(s->compr == TIFF_LZW)
417             av_free(s->lzws);
418     }
419
420     s->num_entries = 0;
421
422     add_entry1(s,TIFF_SUBFILE,           TIFF_LONG,             0);
423     add_entry1(s,TIFF_WIDTH,             TIFF_LONG,             s->width);
424     add_entry1(s,TIFF_HEIGHT,            TIFF_LONG,             s->height);
425
426     if (s->bpp_tab_size)
427     add_entry(s, TIFF_BPP,               TIFF_SHORT,    s->bpp_tab_size, bpp_tab);
428
429     add_entry1(s,TIFF_COMPR,             TIFF_SHORT,            s->compr);
430     add_entry1(s,TIFF_INVERT,            TIFF_SHORT,            s->photometric_interpretation);
431     add_entry(s, TIFF_STRIP_OFFS,        TIFF_LONG,     strips, s->strip_offsets);
432
433     if (s->bpp_tab_size)
434     add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT,            s->bpp_tab_size);
435
436     add_entry1(s,TIFF_ROWSPERSTRIP,      TIFF_LONG,             s->rps);
437     add_entry(s, TIFF_STRIP_SIZE,        TIFF_LONG,     strips, s->strip_sizes);
438     add_entry(s, TIFF_XRES,              TIFF_RATIONAL, 1,      res);
439     add_entry(s, TIFF_YRES,              TIFF_RATIONAL, 1,      res);
440     add_entry1(s,TIFF_RES_UNIT,          TIFF_SHORT,            2);
441
442     if(!(avctx->flags & CODEC_FLAG_BITEXACT))
443     add_entry(s, TIFF_SOFTWARE_NAME,     TIFF_STRING,
444               strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
445
446     if (avctx->pix_fmt == PIX_FMT_PAL8) {
447         uint16_t pal[256 * 3];
448         for (i = 0; i < 256; i++) {
449             uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
450             pal[i]       = ((rgb >> 16) & 0xff) * 257;
451             pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
452             pal[i + 512] = ( rgb        & 0xff) * 257;
453         }
454         add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
455     }
456     if (alpha)
457         add_entry1(s,TIFF_EXTRASAMPLES,      TIFF_SHORT,            2);
458     if (is_yuv){
459         /** according to CCIR Recommendation 601.1 */
460         uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
461         add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT,    2, s->subsampling);
462         add_entry(s, TIFF_REFERENCE_BW,      TIFF_RATIONAL, 6, refbw);
463     }
464     bytestream_put_le32(&offset, ptr - pkt->data);    // write offset to dir
465
466     if (check_size(s, 6 + s->num_entries * 12)) {
467         ret = AVERROR(EINVAL);
468         goto fail;
469     }
470     bytestream_put_le16(&ptr, s->num_entries);  // write tag count
471     bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
472     bytestream_put_le32(&ptr, 0);
473
474     pkt->size   = ptr - pkt->data;
475     pkt->flags |= AV_PKT_FLAG_KEY;
476     *got_packet = 1;
477
478 fail:
479     return ret < 0 ? ret : 0;
480 }
481
482 static av_cold int encode_close(AVCodecContext *avctx)
483 {
484     TiffEncoderContext *s = avctx->priv_data;
485
486     av_freep(&s->strip_sizes);
487     av_freep(&s->strip_offsets);
488     av_freep(&s->yuv_line);
489
490     return 0;
491 }
492
493 #define OFFSET(x) offsetof(TiffEncoderContext, x)
494 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
495 static const AVOption options[] = {
496     {"dpi", "set the image resolution (in dpi)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 72}, 1, 0x10000, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_ENCODING_PARAM},
497     { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {.i64 = TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
498     { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
499     { "raw",      NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_RAW},      0, 0, VE, "compression_algo" },
500     { "lzw",      NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_LZW},      0, 0, VE, "compression_algo" },
501 #if CONFIG_ZLIB
502     { "deflate",  NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_DEFLATE},  0, 0, VE, "compression_algo" },
503 #endif
504     { NULL },
505 };
506
507 static const AVClass tiffenc_class = {
508     .class_name = "TIFF encoder",
509     .item_name  = av_default_item_name,
510     .option     = options,
511     .version    = LIBAVUTIL_VERSION_INT,
512 };
513
514 AVCodec ff_tiff_encoder = {
515     .name           = "tiff",
516     .type           = AVMEDIA_TYPE_VIDEO,
517     .id             = AV_CODEC_ID_TIFF,
518     .priv_data_size = sizeof(TiffEncoderContext),
519     .init           = encode_init,
520     .encode2        = encode_frame,
521     .close          = encode_close,
522     .pix_fmts       = (const enum PixelFormat[]) {
523         PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8, PIX_FMT_GRAY8A, PIX_FMT_GRAY16LE,
524         PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
525         PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV440P, PIX_FMT_YUV444P,
526         PIX_FMT_YUV410P, PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
527         PIX_FMT_RGBA, PIX_FMT_RGBA64LE,
528         PIX_FMT_NONE
529     },
530     .long_name      = NULL_IF_CONFIG_SMALL("TIFF image"),
531     .priv_class     = &tiffenc_class,
532 };