3 * Copyright (c) 2007 Bartlomiej Wolowiec
5 * This file is part of FFmpeg.
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.
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.
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
25 * @author Bartlomiej Wolowiec
28 #include "libavutil/imgutils.h"
29 #include "libavutil/log.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
38 #include "bytestream.h"
45 #define TIFF_MAX_ENTRY 32
47 /** sizes of various TIFF field types (string size = 1)*/
48 static const uint8_t type_sizes2[14] = {
49 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4
52 typedef struct TiffEncoderContext {
53 AVClass *class; ///< for private options
54 AVCodecContext *avctx;
57 int width; ///< picture width
58 int height; ///< picture height
59 unsigned int bpp; ///< bits per pixel
60 int compr; ///< compression level
61 int bpp_tab_size; ///< bpp_tab size
62 int photometric_interpretation; ///< photometric interpretation
63 int strips; ///< number of strips
64 uint32_t *strip_sizes;
65 unsigned int strip_sizes_size;
66 uint32_t *strip_offsets;
67 unsigned int strip_offsets_size;
69 unsigned int yuv_line_size;
70 int rps; ///< row per strip
71 uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
72 int num_entries; ///< number of entires
73 uint8_t **buf; ///< actual position in buffer
74 uint8_t *buf_start; ///< pointer to first byte in buffer
75 int buf_size; ///< buffer size
76 uint16_t subsampling[2]; ///< YUV subsampling factors
77 struct LZWEncodeState *lzws; ///< LZW Encode state
78 uint32_t dpi; ///< image resolution in DPI
83 * Check free space in buffer.
85 * @param s Tiff context
86 * @param need Needed bytes
87 * @return 0 - ok, 1 - no free space
89 static inline int check_size(TiffEncoderContext * s, uint64_t need)
91 if (s->buf_size < *s->buf - s->buf_start + need) {
92 *s->buf = s->buf_start + s->buf_size + 1;
93 av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
100 * Put n values to buffer.
102 * @param p pointer to pointer to output buffer
103 * @param n number of values
104 * @param val pointer to values
105 * @param type type of values
106 * @param flip = 0 - normal copy, >0 - flip
108 static void tnput(uint8_t ** p, int n, const uint8_t * val, enum TiffTypes type,
113 flip ^= ((int[]) {0, 0, 0, 1, 3, 3})[type];
115 for (i = 0; i < n * type_sizes2[type]; i++)
116 *(*p)++ = val[i ^ flip];
120 * Add entry to directory in tiff header.
122 * @param s Tiff context
123 * @param tag tag that identifies the entry
124 * @param type entry type
125 * @param count the number of values
126 * @param ptr_val pointer to values
128 static void add_entry(TiffEncoderContext * s,
129 enum TiffTags tag, enum TiffTypes type, int count,
132 uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
134 av_assert0(s->num_entries < TIFF_MAX_ENTRY);
136 bytestream_put_le16(&entries_ptr, tag);
137 bytestream_put_le16(&entries_ptr, type);
138 bytestream_put_le32(&entries_ptr, count);
140 if (type_sizes[type] * count <= 4) {
141 tnput(&entries_ptr, count, ptr_val, type, 0);
143 bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
144 check_size(s, count * type_sizes2[type]);
145 tnput(s->buf, count, ptr_val, type, 0);
151 static void add_entry1(TiffEncoderContext * s,
152 enum TiffTags tag, enum TiffTypes type, int val){
155 add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
159 * Encode one strip in tiff file.
161 * @param s Tiff context
162 * @param src input buffer
163 * @param dst output buffer
164 * @param n size of input buffer
165 * @param compr compression method
166 * @return number of output bytes. If an output error is encountered, -1 is returned
168 static int encode_strip(TiffEncoderContext * s, const int8_t * src,
169 uint8_t * dst, int n, int compr)
175 case TIFF_ADOBE_DEFLATE:
177 unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
178 if (compress(dst, &zlen, src, n) != Z_OK) {
179 av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
186 if (check_size(s, n))
191 return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start), src, 1, n, 2, 0xff, -1, 0);
193 return ff_lzw_encode(s->lzws, src, n);
199 static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum)
201 AVFrame *p = &s->picture;
203 int w = (s->width - 1) / s->subsampling[0] + 1;
204 uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
205 uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
206 if(s->width % s->subsampling[0] || s->height % s->subsampling[1]){
207 for (i = 0; i < w; i++){
208 for (j = 0; j < s->subsampling[1]; j++)
209 for (k = 0; k < s->subsampling[0]; k++)
210 *dst++ = p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
211 FFMIN(i * s->subsampling[0] + k, s->width-1)];
216 for (i = 0; i < w; i++){
217 for (j = 0; j < s->subsampling[1]; j++)
218 for (k = 0; k < s->subsampling[0]; k++)
219 *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
220 i * s->subsampling[0] + k];
227 static av_cold int encode_init(AVCodecContext *avctx)
229 TiffEncoderContext *s = avctx->priv_data;
231 avctx->coded_frame= &s->picture;
232 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
233 avctx->coded_frame->key_frame = 1;
239 static int encode_frame(AVCodecContext * avctx, AVPacket *pkt,
240 const AVFrame *pict, int *got_packet)
242 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
243 TiffEncoderContext *s = avctx->priv_data;
244 AVFrame *const p = &s->picture;
250 uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
253 int is_yuv = 0, alpha = 0;
254 int shift_h, shift_v;
258 s->width = avctx->width;
259 s->height = avctx->height;
260 s->subsampling[0] = 1;
261 s->subsampling[1] = 1;
263 avctx->bits_per_coded_sample =
264 s->bpp = av_get_bits_per_pixel(desc);
265 s->bpp_tab_size = desc->nb_components;
267 switch (avctx->pix_fmt) {
268 case AV_PIX_FMT_RGBA64LE:
269 case AV_PIX_FMT_RGBA:
271 case AV_PIX_FMT_RGB48LE:
272 case AV_PIX_FMT_RGB24:
273 s->photometric_interpretation = 2;
275 case AV_PIX_FMT_GRAY8:
276 avctx->bits_per_coded_sample = 0x28;
277 case AV_PIX_FMT_GRAY8A:
278 alpha = avctx->pix_fmt == AV_PIX_FMT_GRAY8A;
279 case AV_PIX_FMT_GRAY16LE:
280 case AV_PIX_FMT_MONOBLACK:
281 s->photometric_interpretation = 1;
283 case AV_PIX_FMT_PAL8:
284 s->photometric_interpretation = 3;
286 case AV_PIX_FMT_MONOWHITE:
287 s->photometric_interpretation = 0;
289 case AV_PIX_FMT_YUV420P:
290 case AV_PIX_FMT_YUV422P:
291 case AV_PIX_FMT_YUV440P:
292 case AV_PIX_FMT_YUV444P:
293 case AV_PIX_FMT_YUV410P:
294 case AV_PIX_FMT_YUV411P:
295 s->photometric_interpretation = 6;
296 avcodec_get_chroma_sub_sample(avctx->pix_fmt,
298 s->subsampling[0] = 1 << shift_h;
299 s->subsampling[1] = 1 << shift_v;
303 av_log(s->avctx, AV_LOG_ERROR,
304 "This colors format is not supported\n");
308 for (i = 0; i < s->bpp_tab_size; i++)
309 bpp_tab[i] = desc->comp[i].depth_minus1 + 1;
311 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
312 //best choose for DEFLATE
315 s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip
316 s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
318 strips = (s->height - 1) / s->rps + 1;
320 if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width * avctx->height * s->bpp * 2 +
321 avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
324 s->buf_start = pkt->data;
326 s->buf_size = pkt->size;
328 if (check_size(s, 8))
332 bytestream_put_le16(&ptr, 0x4949);
333 bytestream_put_le16(&ptr, 42);
336 bytestream_put_le32(&ptr, 0);
338 av_fast_padded_mallocz(&s->strip_sizes, &s->strip_sizes_size, sizeof(s->strip_sizes[0]) * strips);
339 av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
341 if (!s->strip_sizes || !s->strip_offsets) {
342 ret = AVERROR(ENOMEM);
346 bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
347 * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
349 av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
350 if (s->yuv_line == NULL){
351 av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
352 ret = AVERROR(ENOMEM);
358 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
363 zlen = bytes_per_row * s->rps;
364 zbuf = av_malloc(zlen);
366 ret = AVERROR(ENOMEM);
369 s->strip_offsets[0] = ptr - pkt->data;
371 for (j = 0; j < s->rps; j++) {
373 pack_yuv(s, s->yuv_line, j);
374 memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
375 j += s->subsampling[1] - 1;
378 memcpy(zbuf + j * bytes_per_row,
379 p->data[0] + j * p->linesize[0], bytes_per_row);
382 ret = encode_strip(s, zbuf, ptr, zn, s->compr);
385 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
389 s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
393 if (s->compr == TIFF_LZW) {
394 s->lzws = av_malloc(ff_lzw_encode_state_size);
396 ret = AVERROR(ENOMEM);
400 for (i = 0; i < s->height; i++) {
401 if (s->strip_sizes[i / s->rps] == 0) {
402 if(s->compr == TIFF_LZW){
403 ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
404 12, FF_LZW_TIFF, put_bits);
406 s->strip_offsets[i / s->rps] = ptr - pkt->data;
409 pack_yuv(s, s->yuv_line, i);
410 ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
411 i += s->subsampling[1] - 1;
414 ret = encode_strip(s, p->data[0] + i * p->linesize[0],
415 ptr, bytes_per_row, s->compr);
417 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
420 s->strip_sizes[i / s->rps] += ret;
422 if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
423 ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
424 s->strip_sizes[(i / s->rps )] += ret ;
428 if(s->compr == TIFF_LZW)
434 add_entry1(s,TIFF_SUBFILE, TIFF_LONG, 0);
435 add_entry1(s,TIFF_WIDTH, TIFF_LONG, s->width);
436 add_entry1(s,TIFF_HEIGHT, TIFF_LONG, s->height);
439 add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
441 add_entry1(s,TIFF_COMPR, TIFF_SHORT, s->compr);
442 add_entry1(s,TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation);
443 add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, s->strip_offsets);
446 add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
448 add_entry1(s,TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
449 add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, s->strip_sizes);
450 add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
451 add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
452 add_entry1(s,TIFF_RES_UNIT, TIFF_SHORT, 2);
454 if(!(avctx->flags & CODEC_FLAG_BITEXACT))
455 add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
456 strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
458 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
459 uint16_t pal[256 * 3];
460 for (i = 0; i < 256; i++) {
461 uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
462 pal[i] = ((rgb >> 16) & 0xff) * 257;
463 pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
464 pal[i + 512] = ( rgb & 0xff) * 257;
466 add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
469 add_entry1(s,TIFF_EXTRASAMPLES, TIFF_SHORT, 2);
471 /** according to CCIR Recommendation 601.1 */
472 uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
473 add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
474 add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
476 bytestream_put_le32(&offset, ptr - pkt->data); // write offset to dir
478 if (check_size(s, 6 + s->num_entries * 12)) {
479 ret = AVERROR(EINVAL);
482 bytestream_put_le16(&ptr, s->num_entries); // write tag count
483 bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
484 bytestream_put_le32(&ptr, 0);
486 pkt->size = ptr - pkt->data;
487 pkt->flags |= AV_PKT_FLAG_KEY;
491 return ret < 0 ? ret : 0;
494 static av_cold int encode_close(AVCodecContext *avctx)
496 TiffEncoderContext *s = avctx->priv_data;
498 av_freep(&s->strip_sizes);
499 av_freep(&s->strip_offsets);
500 av_freep(&s->yuv_line);
505 #define OFFSET(x) offsetof(TiffEncoderContext, x)
506 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
507 static const AVOption options[] = {
508 {"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},
509 { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {.i64 = TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
510 { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
511 { "raw", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_RAW}, 0, 0, VE, "compression_algo" },
512 { "lzw", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_LZW}, 0, 0, VE, "compression_algo" },
514 { "deflate", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_DEFLATE}, 0, 0, VE, "compression_algo" },
519 static const AVClass tiffenc_class = {
520 .class_name = "TIFF encoder",
521 .item_name = av_default_item_name,
523 .version = LIBAVUTIL_VERSION_INT,
526 AVCodec ff_tiff_encoder = {
528 .type = AVMEDIA_TYPE_VIDEO,
529 .id = AV_CODEC_ID_TIFF,
530 .priv_data_size = sizeof(TiffEncoderContext),
532 .encode2 = encode_frame,
533 .close = encode_close,
534 .pix_fmts = (const enum AVPixelFormat[]) {
535 AV_PIX_FMT_RGB24, AV_PIX_FMT_PAL8, AV_PIX_FMT_GRAY8,
536 AV_PIX_FMT_GRAY8A, AV_PIX_FMT_GRAY16LE,
537 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_MONOWHITE,
538 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
539 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_RGB48LE,
540 AV_PIX_FMT_RGBA, AV_PIX_FMT_RGBA64LE,
543 .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
544 .priv_class = &tiffenc_class,