FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
tiffenc.c
Go to the documentation of this file.
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 "config.h"
29 #if CONFIG_ZLIB
30 #include <zlib.h>
31 #endif
32 
33 #include "libavutil/imgutils.h"
34 #include "libavutil/log.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "avcodec.h"
38 #include "bytestream.h"
39 #include "internal.h"
40 #include "lzw.h"
41 #include "put_bits.h"
42 #include "rle.h"
43 #include "tiff.h"
44 
45 #define TIFF_MAX_ENTRY 32
46 
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
50 };
51 
52 typedef struct TiffEncoderContext {
53  AVClass *class; ///< for private options
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  enum TiffPhotometric 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
79 
80 /**
81  * Check free space in buffer.
82  *
83  * @param s Tiff context
84  * @param need Needed bytes
85  * @return 0 - ok, 1 - no free space
86  */
87 static inline int check_size(TiffEncoderContext *s, uint64_t need)
88 {
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");
92  return 1;
93  }
94  return 0;
95 }
96 
97 /**
98  * Put n values to buffer.
99  *
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
105  */
106 static void tnput(uint8_t **p, int n, const uint8_t *val, enum TiffTypes type,
107  int flip)
108 {
109  int i;
110 #if HAVE_BIGENDIAN
111  flip ^= ((int[]) { 0, 0, 0, 1, 3, 3 })[type];
112 #endif
113  for (i = 0; i < n * type_sizes2[type]; i++)
114  *(*p)++ = val[i ^ flip];
115 }
116 
117 /**
118  * Add entry to directory in tiff header.
119  *
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
125  */
127  enum TiffTypes type, int count, const void *ptr_val)
128 {
129  uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
130 
132 
133  bytestream_put_le16(&entries_ptr, tag);
134  bytestream_put_le16(&entries_ptr, type);
135  bytestream_put_le32(&entries_ptr, count);
136 
137  if (type_sizes[type] * (int64_t)count <= 4) {
138  tnput(&entries_ptr, count, ptr_val, type, 0);
139  } else {
140  bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
141  if (check_size(s, count * (int64_t)type_sizes2[type]))
142  return AVERROR_INVALIDDATA;
143  tnput(s->buf, count, ptr_val, type, 0);
144  }
145 
146  s->num_entries++;
147  return 0;
148 }
149 
151  enum TiffTags tag, enum TiffTypes type, int val)
152 {
153  uint16_t w = val;
154  uint32_t dw = val;
155  return add_entry(s, tag, type, 1,
156  type == TIFF_SHORT ? (void *)&w : (void *)&dw);
157 }
158 
159 /**
160  * Encode one strip in tiff file.
161  *
162  * @param s Tiff context
163  * @param src input buffer
164  * @param dst output buffer
165  * @param n size of input buffer
166  * @param compr compression method
167  * @return number of output bytes. If an output error is encountered, -1 is returned
168  */
169 static int encode_strip(TiffEncoderContext *s, const int8_t *src,
170  uint8_t *dst, int n, int compr)
171 {
172  switch (compr) {
173 #if CONFIG_ZLIB
174  case TIFF_DEFLATE:
175  case TIFF_ADOBE_DEFLATE:
176  {
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");
180  return -1;
181  }
182  return zlen;
183  }
184 #endif
185  case TIFF_RAW:
186  if (check_size(s, n))
187  return -1;
188  memcpy(dst, src, n);
189  return n;
190  case TIFF_PACKBITS:
191  return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start),
192  src, 1, n, 2, 0xff, -1, 0);
193  case TIFF_LZW:
194  return ff_lzw_encode(s->lzws, src, n);
195  default:
196  return -1;
197  }
198 }
199 
200 static void pack_yuv(TiffEncoderContext *s, const AVFrame *p,
201  uint8_t *dst, int lnum)
202 {
203  int i, j, k;
204  int w = (s->width - 1) / s->subsampling[0] + 1;
205  uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
206  uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
207  if (s->width % s->subsampling[0] || s->height % s->subsampling[1]) {
208  for (i = 0; i < w; i++) {
209  for (j = 0; j < s->subsampling[1]; j++)
210  for (k = 0; k < s->subsampling[0]; k++)
211  *dst++ = p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
212  FFMIN(i * s->subsampling[0] + k, s->width-1)];
213  *dst++ = *pu++;
214  *dst++ = *pv++;
215  }
216  }else{
217  for (i = 0; i < w; i++) {
218  for (j = 0; j < s->subsampling[1]; j++)
219  for (k = 0; k < s->subsampling[0]; k++)
220  *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
221  i * s->subsampling[0] + k];
222  *dst++ = *pu++;
223  *dst++ = *pv++;
224  }
225  }
226 }
227 
228 #define ADD_ENTRY(s, tag, type, count, ptr_val) \
229  do { \
230  ret = add_entry(s, tag, type, count, ptr_val); \
231  if (ret < 0) \
232  goto fail; \
233  } while(0);
234 
235 #define ADD_ENTRY1(s, tag, type, val) \
236  do { \
237  ret = add_entry1(s, tag, type, val); \
238  if (ret < 0) \
239  goto fail; \
240  } while(0);
241 
243  const AVFrame *pict, int *got_packet)
244 {
245  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
246  TiffEncoderContext *s = avctx->priv_data;
247  const AVFrame *const p = pict;
248  int i;
249  uint8_t *ptr;
250  uint8_t *offset;
251  uint32_t strips;
252  int bytes_per_row;
253  uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
254  uint16_t bpp_tab[4];
255  int ret = 0;
256  int is_yuv = 0, alpha = 0;
257  int shift_h, shift_v;
258  int packet_size;
259 
260  s->width = avctx->width;
261  s->height = avctx->height;
262  s->subsampling[0] = 1;
263  s->subsampling[1] = 1;
264 
265  avctx->bits_per_coded_sample =
266  s->bpp = av_get_bits_per_pixel(desc);
267  s->bpp_tab_size = desc->nb_components;
268 
269  switch (avctx->pix_fmt) {
270  case AV_PIX_FMT_RGBA64LE:
271  case AV_PIX_FMT_RGBA:
272  alpha = 1;
273  case AV_PIX_FMT_RGB48LE:
274  case AV_PIX_FMT_RGB24:
276  break;
277  case AV_PIX_FMT_GRAY8:
278  avctx->bits_per_coded_sample = 0x28;
279  case AV_PIX_FMT_GRAY8A:
280  alpha = avctx->pix_fmt == AV_PIX_FMT_GRAY8A;
281  case AV_PIX_FMT_GRAY16LE:
284  break;
285  case AV_PIX_FMT_PAL8:
287  break;
290  break;
291  case AV_PIX_FMT_YUV420P:
292  case AV_PIX_FMT_YUV422P:
293  case AV_PIX_FMT_YUV440P:
294  case AV_PIX_FMT_YUV444P:
295  case AV_PIX_FMT_YUV410P:
296  case AV_PIX_FMT_YUV411P:
297  av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);
299  s->subsampling[0] = 1 << shift_h;
300  s->subsampling[1] = 1 << shift_v;
301  is_yuv = 1;
302  break;
303  default:
305  "This colors format is not supported\n");
306  return -1;
307  }
308 
309  for (i = 0; i < s->bpp_tab_size; i++)
310  bpp_tab[i] = desc->comp[i].depth_minus1 + 1;
311 
312  if (s->compr == TIFF_DEFLATE ||
313  s->compr == TIFF_ADOBE_DEFLATE ||
314  s->compr == TIFF_LZW)
315  // best choice for DEFLATE
316  s->rps = s->height;
317  else
318  // suggest size of strip
319  s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);
320  // round rps up
321  s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1];
322 
323  strips = (s->height - 1) / s->rps + 1;
324 
325  bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
326  s->subsampling[0] * s->subsampling[1] + 7) >> 3;
327  packet_size = avctx->height * bytes_per_row * 2 +
328  avctx->height * 4 + FF_MIN_BUFFER_SIZE;
329 
330  if ((ret = ff_alloc_packet2(avctx, pkt, packet_size)) < 0)
331  return ret;
332  ptr = pkt->data;
333  s->buf_start = pkt->data;
334  s->buf = &ptr;
335  s->buf_size = pkt->size;
336 
337  if (check_size(s, 8)) {
338  ret = AVERROR(EINVAL);
339  goto fail;
340  }
341 
342  // write header
343  bytestream_put_le16(&ptr, 0x4949);
344  bytestream_put_le16(&ptr, 42);
345 
346  offset = ptr;
347  bytestream_put_le32(&ptr, 0);
348 
349  if (strips > INT_MAX / FFMAX(sizeof(s->strip_sizes[0]), sizeof(s->strip_offsets[0]))) {
350  ret = AVERROR(ENOMEM);
351  goto fail;
352  }
353  av_fast_padded_mallocz(&s->strip_sizes , &s->strip_sizes_size , sizeof(s->strip_sizes [0]) * strips);
354  av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
355 
356  if (!s->strip_sizes || !s->strip_offsets) {
357  ret = AVERROR(ENOMEM);
358  goto fail;
359  }
360 
361  if (is_yuv) {
362  av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
363  if (s->yuv_line == NULL) {
364  av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
365  ret = AVERROR(ENOMEM);
366  goto fail;
367  }
368  }
369 
370 #if CONFIG_ZLIB
371  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
372  uint8_t *zbuf;
373  int zlen, zn;
374  int j;
375 
376  zlen = bytes_per_row * s->rps;
377  zbuf = av_malloc(zlen);
378  if (!zbuf) {
379  ret = AVERROR(ENOMEM);
380  goto fail;
381  }
382  s->strip_offsets[0] = ptr - pkt->data;
383  zn = 0;
384  for (j = 0; j < s->rps; j++) {
385  if (is_yuv) {
386  pack_yuv(s, p, s->yuv_line, j);
387  memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
388  j += s->subsampling[1] - 1;
389  } else
390  memcpy(zbuf + j * bytes_per_row,
391  p->data[0] + j * p->linesize[0], bytes_per_row);
392  zn += bytes_per_row;
393  }
394  ret = encode_strip(s, zbuf, ptr, zn, s->compr);
395  av_free(zbuf);
396  if (ret < 0) {
397  av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
398  goto fail;
399  }
400  ptr += ret;
401  s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
402  } else
403 #endif
404  {
405  if (s->compr == TIFF_LZW) {
407  if (!s->lzws) {
408  ret = AVERROR(ENOMEM);
409  goto fail;
410  }
411  }
412  for (i = 0; i < s->height; i++) {
413  if (s->strip_sizes[i / s->rps] == 0) {
414  if (s->compr == TIFF_LZW) {
415  ff_lzw_encode_init(s->lzws, ptr,
416  s->buf_size - (*s->buf - s->buf_start),
417  12, FF_LZW_TIFF, put_bits);
418  }
419  s->strip_offsets[i / s->rps] = ptr - pkt->data;
420  }
421  if (is_yuv) {
422  pack_yuv(s, p, s->yuv_line, i);
423  ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
424  i += s->subsampling[1] - 1;
425  } else
426  ret = encode_strip(s, p->data[0] + i * p->linesize[0],
427  ptr, bytes_per_row, s->compr);
428  if (ret < 0) {
429  av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
430  goto fail;
431  }
432  s->strip_sizes[i / s->rps] += ret;
433  ptr += ret;
434  if (s->compr == TIFF_LZW &&
435  (i == s->height - 1 || i % s->rps == s->rps - 1)) {
437  s->strip_sizes[(i / s->rps)] += ret;
438  ptr += ret;
439  }
440  }
441  if (s->compr == TIFF_LZW)
442  av_freep(&s->lzws);
443  }
444 
445  s->num_entries = 0;
446 
450 
451  if (s->bpp_tab_size)
452  ADD_ENTRY(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
453 
457 
458  if (s->bpp_tab_size)
460 
463  ADD_ENTRY(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
464  if (avctx->sample_aspect_ratio.num > 0 &&
465  avctx->sample_aspect_ratio.den > 0) {
466  AVRational y = av_mul_q(av_make_q(s->dpi, 1),
467  avctx->sample_aspect_ratio);
468  res[0] = y.num;
469  res[1] = y.den;
470  }
471  ADD_ENTRY(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
473 
474  if (!(avctx->flags & CODEC_FLAG_BITEXACT))
476  strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
477 
478  if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
479  uint16_t pal[256 * 3];
480  for (i = 0; i < 256; i++) {
481  uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
482  pal[i] = ((rgb >> 16) & 0xff) * 257;
483  pal[i + 256] = ((rgb >> 8) & 0xff) * 257;
484  pal[i + 512] = (rgb & 0xff) * 257;
485  }
486  ADD_ENTRY(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
487  }
488  if (alpha)
490  if (is_yuv) {
491  /** according to CCIR Recommendation 601.1 */
492  uint32_t refbw[12] = { 15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1 };
497  }
498  // write offset to dir
499  bytestream_put_le32(&offset, ptr - pkt->data);
500 
501  if (check_size(s, 6 + s->num_entries * 12)) {
502  ret = AVERROR(EINVAL);
503  goto fail;
504  }
505  bytestream_put_le16(&ptr, s->num_entries); // write tag count
506  bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
507  bytestream_put_le32(&ptr, 0);
508 
509  pkt->size = ptr - pkt->data;
510  pkt->flags |= AV_PKT_FLAG_KEY;
511  *got_packet = 1;
512 
513 fail:
514  return ret < 0 ? ret : 0;
515 }
516 
518 {
519  TiffEncoderContext *s = avctx->priv_data;
520 
521  avctx->coded_frame = av_frame_alloc();
522  if (!avctx->coded_frame)
523  return AVERROR(ENOMEM);
524 
526  avctx->coded_frame->key_frame = 1;
527  s->avctx = avctx;
528 
529  return 0;
530 }
531 
533 {
534  TiffEncoderContext *s = avctx->priv_data;
535 
536  av_frame_free(&avctx->coded_frame);
537  av_freep(&s->strip_sizes);
538  av_freep(&s->strip_offsets);
539  av_freep(&s->yuv_line);
540 
541  return 0;
542 }
543 
544 #define OFFSET(x) offsetof(TiffEncoderContext, x)
545 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
546 static const AVOption options[] = {
547  {"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},
548  { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, { .i64 = TIFF_PACKBITS }, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
549  { "packbits", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_PACKBITS }, 0, 0, VE, "compression_algo" },
550  { "raw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_RAW }, 0, 0, VE, "compression_algo" },
551  { "lzw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_LZW }, 0, 0, VE, "compression_algo" },
552 #if CONFIG_ZLIB
553  { "deflate", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_DEFLATE }, 0, 0, VE, "compression_algo" },
554 #endif
555  { NULL },
556 };
557 
558 static const AVClass tiffenc_class = {
559  .class_name = "TIFF encoder",
560  .item_name = av_default_item_name,
561  .option = options,
562  .version = LIBAVUTIL_VERSION_INT,
563 };
564 
566  .name = "tiff",
567  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
568  .type = AVMEDIA_TYPE_VIDEO,
569  .id = AV_CODEC_ID_TIFF,
570  .priv_data_size = sizeof(TiffEncoderContext),
571  .init = encode_init,
572  .close = encode_close,
574  .encode2 = encode_frame,
575  .pix_fmts = (const enum AVPixelFormat[]) {
583  },
584  .priv_class = &tiffenc_class,
585 };