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
33 #include "libavutil/imgutils.h"
34 #include "libavutil/log.h"
35 #include "libavutil/opt.h"
36 #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;
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;
68 unsigned int yuv_line_size;
69 int rps; ///< row per strip
70 uint8_t entries[TIFF_MAX_ENTRY * 12]; ///< entries in header
71 int num_entries; ///< number of entries
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
81 * Check free space in buffer.
83 * @param s Tiff context
84 * @param need Needed bytes
85 * @return 0 - ok, 1 - no free space
87 static inline int check_size(TiffEncoderContext *s, uint64_t need)
89 if (s->buf_size < *s->buf - s->buf_start + need) {
90 *s->buf = s->buf_start + s->buf_size + 1;
91 av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
98 * Put n values to buffer.
100 * @param p pointer to pointer to output buffer
101 * @param n number of values
102 * @param val pointer to values
103 * @param type type of values
104 * @param flip = 0 - normal copy, >0 - flip
106 static void tnput(uint8_t **p, int n, const uint8_t *val, enum TiffTypes type,
111 flip ^= ((int[]) { 0, 0, 0, 1, 3, 3 })[type];
113 for (i = 0; i < n * type_sizes2[type]; i++)
114 *(*p)++ = val[i ^ flip];
118 * Add entry to directory in tiff header.
120 * @param s Tiff context
121 * @param tag tag that identifies the entry
122 * @param type entry type
123 * @param count the number of values
124 * @param ptr_val pointer to values
126 static void add_entry(TiffEncoderContext *s, enum TiffTags tag,
127 enum TiffTypes type, int count, const void *ptr_val)
129 uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
131 av_assert0(s->num_entries < TIFF_MAX_ENTRY);
133 bytestream_put_le16(&entries_ptr, tag);
134 bytestream_put_le16(&entries_ptr, type);
135 bytestream_put_le32(&entries_ptr, count);
137 if (type_sizes[type] * (int64_t)count <= 4) {
138 tnput(&entries_ptr, count, ptr_val, type, 0);
140 bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
141 check_size(s, count * (int64_t)type_sizes2[type]);
142 tnput(s->buf, count, ptr_val, type, 0);
148 static void add_entry1(TiffEncoderContext *s,
149 enum TiffTags tag, enum TiffTypes type, int val)
153 add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
157 * Encode one strip in tiff file.
159 * @param s Tiff context
160 * @param src input buffer
161 * @param dst output buffer
162 * @param n size of input buffer
163 * @param compr compression method
164 * @return number of output bytes. If an output error is encountered, -1 is returned
166 static int encode_strip(TiffEncoderContext *s, const int8_t *src,
167 uint8_t *dst, int n, int compr)
172 case TIFF_ADOBE_DEFLATE:
174 unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
175 if (compress(dst, &zlen, src, n) != Z_OK) {
176 av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
183 if (check_size(s, n))
188 return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start),
189 src, 1, n, 2, 0xff, -1, 0);
191 return ff_lzw_encode(s->lzws, src, n);
197 static void pack_yuv(TiffEncoderContext *s, const AVFrame *p,
198 uint8_t *dst, int lnum)
201 int w = (s->width - 1) / s->subsampling[0] + 1;
202 uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
203 uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
204 if (s->width % s->subsampling[0] || s->height % s->subsampling[1]) {
205 for (i = 0; i < w; i++) {
206 for (j = 0; j < s->subsampling[1]; j++)
207 for (k = 0; k < s->subsampling[0]; k++)
208 *dst++ = p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
209 FFMIN(i * s->subsampling[0] + k, s->width-1)];
214 for (i = 0; i < w; i++) {
215 for (j = 0; j < s->subsampling[1]; j++)
216 for (k = 0; k < s->subsampling[0]; k++)
217 *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
218 i * s->subsampling[0] + k];
225 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
226 const AVFrame *pict, int *got_packet)
228 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
229 TiffEncoderContext *s = avctx->priv_data;
230 const AVFrame *const p = pict;
236 uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
239 int is_yuv = 0, alpha = 0;
240 int shift_h, shift_v;
242 s->width = avctx->width;
243 s->height = avctx->height;
244 s->subsampling[0] = 1;
245 s->subsampling[1] = 1;
247 avctx->bits_per_coded_sample =
248 s->bpp = av_get_bits_per_pixel(desc);
249 s->bpp_tab_size = desc->nb_components;
251 switch (avctx->pix_fmt) {
252 case AV_PIX_FMT_RGBA64LE:
253 case AV_PIX_FMT_RGBA:
255 case AV_PIX_FMT_RGB48LE:
256 case AV_PIX_FMT_RGB24:
257 s->photometric_interpretation = 2;
259 case AV_PIX_FMT_GRAY8:
260 avctx->bits_per_coded_sample = 0x28;
261 case AV_PIX_FMT_GRAY8A:
262 alpha = avctx->pix_fmt == AV_PIX_FMT_GRAY8A;
263 case AV_PIX_FMT_GRAY16LE:
264 case AV_PIX_FMT_MONOBLACK:
265 s->photometric_interpretation = 1;
267 case AV_PIX_FMT_PAL8:
268 s->photometric_interpretation = 3;
270 case AV_PIX_FMT_MONOWHITE:
271 s->photometric_interpretation = 0;
273 case AV_PIX_FMT_YUV420P:
274 case AV_PIX_FMT_YUV422P:
275 case AV_PIX_FMT_YUV440P:
276 case AV_PIX_FMT_YUV444P:
277 case AV_PIX_FMT_YUV410P:
278 case AV_PIX_FMT_YUV411P:
279 av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);
280 s->photometric_interpretation = 6;
281 s->subsampling[0] = 1 << shift_h;
282 s->subsampling[1] = 1 << shift_v;
286 av_log(s->avctx, AV_LOG_ERROR,
287 "This colors format is not supported\n");
291 for (i = 0; i < s->bpp_tab_size; i++)
292 bpp_tab[i] = desc->comp[i].depth_minus1 + 1;
294 if (s->compr == TIFF_DEFLATE ||
295 s->compr == TIFF_ADOBE_DEFLATE ||
296 s->compr == TIFF_LZW)
297 // best choice for DEFLATE
300 // suggest size of strip
301 s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);
303 s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1];
305 strips = (s->height - 1) / s->rps + 1;
307 if ((ret = ff_alloc_packet2(avctx, pkt,
308 avctx->width * avctx->height * s->bpp * 2 +
309 avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
312 s->buf_start = pkt->data;
314 s->buf_size = pkt->size;
316 if (check_size(s, 8))
320 bytestream_put_le16(&ptr, 0x4949);
321 bytestream_put_le16(&ptr, 42);
324 bytestream_put_le32(&ptr, 0);
326 av_fast_padded_mallocz(&s->strip_sizes , &s->strip_sizes_size , sizeof(s->strip_sizes [0]) * strips);
327 av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
329 if (!s->strip_sizes || !s->strip_offsets) {
330 ret = AVERROR(ENOMEM);
334 bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
335 s->subsampling[0] * s->subsampling[1] + 7) >> 3;
337 av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
338 if (s->yuv_line == NULL) {
339 av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
340 ret = AVERROR(ENOMEM);
346 if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
351 zlen = bytes_per_row * s->rps;
352 zbuf = av_malloc(zlen);
354 ret = AVERROR(ENOMEM);
357 s->strip_offsets[0] = ptr - pkt->data;
359 for (j = 0; j < s->rps; j++) {
361 pack_yuv(s, p, s->yuv_line, j);
362 memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
363 j += s->subsampling[1] - 1;
365 memcpy(zbuf + j * bytes_per_row,
366 p->data[0] + j * p->linesize[0], bytes_per_row);
369 ret = encode_strip(s, zbuf, ptr, zn, s->compr);
372 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
376 s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
380 if (s->compr == TIFF_LZW) {
381 s->lzws = av_malloc(ff_lzw_encode_state_size);
383 ret = AVERROR(ENOMEM);
387 for (i = 0; i < s->height; i++) {
388 if (s->strip_sizes[i / s->rps] == 0) {
389 if (s->compr == TIFF_LZW) {
390 ff_lzw_encode_init(s->lzws, ptr,
391 s->buf_size - (*s->buf - s->buf_start),
392 12, FF_LZW_TIFF, put_bits);
394 s->strip_offsets[i / s->rps] = ptr - pkt->data;
397 pack_yuv(s, p, s->yuv_line, i);
398 ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
399 i += s->subsampling[1] - 1;
401 ret = encode_strip(s, p->data[0] + i * p->linesize[0],
402 ptr, bytes_per_row, s->compr);
404 av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
407 s->strip_sizes[i / s->rps] += ret;
409 if (s->compr == TIFF_LZW &&
410 (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;
416 if (s->compr == TIFF_LZW)
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);
427 add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
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);
434 add_entry1(s, TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
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);
442 if (!(avctx->flags & CODEC_FLAG_BITEXACT))
443 add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
444 strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
446 if (avctx->pix_fmt == AV_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;
454 add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
457 add_entry1(s,TIFF_EXTRASAMPLES, TIFF_SHORT, 2);
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 if (avctx->chroma_sample_location == AVCHROMA_LOC_TOPLEFT)
463 add_entry1(s, TIFF_YCBCR_POSITIONING, TIFF_SHORT, 2);
464 add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
466 // write offset to dir
467 bytestream_put_le32(&offset, ptr - pkt->data);
469 if (check_size(s, 6 + s->num_entries * 12)) {
470 ret = AVERROR(EINVAL);
473 bytestream_put_le16(&ptr, s->num_entries); // write tag count
474 bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
475 bytestream_put_le32(&ptr, 0);
477 pkt->size = ptr - pkt->data;
478 pkt->flags |= AV_PKT_FLAG_KEY;
482 return ret < 0 ? ret : 0;
485 static av_cold int encode_init(AVCodecContext *avctx)
487 TiffEncoderContext *s = avctx->priv_data;
489 avctx->coded_frame = av_frame_alloc();
490 if (!avctx->coded_frame)
491 return AVERROR(ENOMEM);
493 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
494 avctx->coded_frame->key_frame = 1;
500 static av_cold int encode_close(AVCodecContext *avctx)
502 TiffEncoderContext *s = avctx->priv_data;
504 av_frame_free(&avctx->coded_frame);
505 av_freep(&s->strip_sizes);
506 av_freep(&s->strip_offsets);
507 av_freep(&s->yuv_line);
512 #define OFFSET(x) offsetof(TiffEncoderContext, x)
513 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
514 static const AVOption options[] = {
515 {"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},
516 { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, { .i64 = TIFF_PACKBITS }, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
517 { "packbits", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_PACKBITS }, 0, 0, VE, "compression_algo" },
518 { "raw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_RAW }, 0, 0, VE, "compression_algo" },
519 { "lzw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_LZW }, 0, 0, VE, "compression_algo" },
521 { "deflate", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_DEFLATE }, 0, 0, VE, "compression_algo" },
526 static const AVClass tiffenc_class = {
527 .class_name = "TIFF encoder",
528 .item_name = av_default_item_name,
530 .version = LIBAVUTIL_VERSION_INT,
533 AVCodec ff_tiff_encoder = {
535 .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
536 .type = AVMEDIA_TYPE_VIDEO,
537 .id = AV_CODEC_ID_TIFF,
538 .priv_data_size = sizeof(TiffEncoderContext),
540 .close = encode_close,
541 .encode2 = encode_frame,
542 .pix_fmts = (const enum AVPixelFormat[]) {
543 AV_PIX_FMT_RGB24, AV_PIX_FMT_PAL8, AV_PIX_FMT_GRAY8,
544 AV_PIX_FMT_GRAY8A, AV_PIX_FMT_GRAY16LE,
545 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_MONOWHITE,
546 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
547 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_RGB48LE,
548 AV_PIX_FMT_RGBA, AV_PIX_FMT_RGBA64LE,
551 .priv_class = &tiffenc_class,