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
56 
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]; ///< entries in header
72  int num_entries; ///< number of entries
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
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  */
128  enum TiffTypes type, int count, const void *ptr_val)
129 {
130  uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
131 
133 
134  bytestream_put_le16(&entries_ptr, tag);
135  bytestream_put_le16(&entries_ptr, type);
136  bytestream_put_le32(&entries_ptr, count);
137 
138  if (type_sizes[type] * (int64_t)count <= 4) {
139  tnput(&entries_ptr, count, ptr_val, type, 0);
140  } else {
141  bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
142  check_size(s, count * (int64_t)type_sizes2[type]);
143  tnput(s->buf, count, ptr_val, type, 0);
144  }
145 
146  s->num_entries++;
147 }
148 
150  enum TiffTags tag, enum TiffTypes type, int val)
151 {
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  switch (compr) {
171 #if CONFIG_ZLIB
172  case TIFF_DEFLATE:
173  case TIFF_ADOBE_DEFLATE:
174  {
175  unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
176  if (compress(dst, &zlen, src, n) != Z_OK) {
177  av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
178  return -1;
179  }
180  return zlen;
181  }
182 #endif
183  case TIFF_RAW:
184  if (check_size(s, n))
185  return -1;
186  memcpy(dst, src, n);
187  return n;
188  case TIFF_PACKBITS:
189  return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start),
190  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 
227 {
228  TiffEncoderContext *s = avctx->priv_data;
229 
230  avctx->coded_frame = &s->picture;
232  avctx->coded_frame->key_frame = 1;
233  s->avctx = avctx;
234 
235  return 0;
236 }
237 
239  const AVFrame *pict, int *got_packet)
240 {
241  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
242  TiffEncoderContext *s = avctx->priv_data;
243  AVFrame *const p = &s->picture;
244  int i;
245  uint8_t *ptr;
246  uint8_t *offset;
247  uint32_t strips;
248  int bytes_per_row;
249  uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
250  uint16_t bpp_tab[4];
251  int ret = -1;
252  int is_yuv = 0, alpha = 0;
253  int shift_h, shift_v;
254 
255  *p = *pict;
256 
257  s->width = avctx->width;
258  s->height = avctx->height;
259  s->subsampling[0] = 1;
260  s->subsampling[1] = 1;
261 
262  avctx->bits_per_coded_sample =
263  s->bpp = av_get_bits_per_pixel(desc);
264  s->bpp_tab_size = desc->nb_components;
265 
266  switch (avctx->pix_fmt) {
267  case AV_PIX_FMT_RGBA64LE:
268  case AV_PIX_FMT_RGBA:
269  alpha = 1;
270  case AV_PIX_FMT_RGB48LE:
271  case AV_PIX_FMT_RGB24:
273  break;
274  case AV_PIX_FMT_GRAY8:
275  avctx->bits_per_coded_sample = 0x28;
276  case AV_PIX_FMT_GRAY8A:
277  alpha = avctx->pix_fmt == AV_PIX_FMT_GRAY8A;
278  case AV_PIX_FMT_GRAY16LE:
281  break;
282  case AV_PIX_FMT_PAL8:
284  break;
287  break;
288  case AV_PIX_FMT_YUV420P:
289  case AV_PIX_FMT_YUV422P:
290  case AV_PIX_FMT_YUV440P:
291  case AV_PIX_FMT_YUV444P:
292  case AV_PIX_FMT_YUV410P:
293  case AV_PIX_FMT_YUV411P:
294  av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);
296  s->subsampling[0] = 1 << shift_h;
297  s->subsampling[1] = 1 << shift_v;
298  is_yuv = 1;
299  break;
300  default:
302  "This colors format is not supported\n");
303  return -1;
304  }
305 
306  for (i = 0; i < s->bpp_tab_size; i++)
307  bpp_tab[i] = desc->comp[i].depth_minus1 + 1;
308 
309  if (s->compr == TIFF_DEFLATE ||
310  s->compr == TIFF_ADOBE_DEFLATE ||
311  s->compr == TIFF_LZW)
312  // best choice for DEFLATE
313  s->rps = s->height;
314  else
315  // suggest size of strip
316  s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);
317  // round rps up
318  s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1];
319 
320  strips = (s->height - 1) / s->rps + 1;
321 
322  if ((ret = ff_alloc_packet2(avctx, pkt,
323  avctx->width * avctx->height * s->bpp * 2 +
324  avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
325  return ret;
326  ptr = pkt->data;
327  s->buf_start = pkt->data;
328  s->buf = &ptr;
329  s->buf_size = pkt->size;
330 
331  if (check_size(s, 8))
332  goto fail;
333 
334  // write header
335  bytestream_put_le16(&ptr, 0x4949);
336  bytestream_put_le16(&ptr, 42);
337 
338  offset = ptr;
339  bytestream_put_le32(&ptr, 0);
340 
341  av_fast_padded_mallocz(&s->strip_sizes , &s->strip_sizes_size , sizeof(s->strip_sizes [0]) * strips);
342  av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
343 
344  if (!s->strip_sizes || !s->strip_offsets) {
345  ret = AVERROR(ENOMEM);
346  goto fail;
347  }
348 
349  bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
350  s->subsampling[0] * s->subsampling[1] + 7) >> 3;
351  if (is_yuv) {
352  av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
353  if (s->yuv_line == NULL) {
354  av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
355  ret = AVERROR(ENOMEM);
356  goto fail;
357  }
358  }
359 
360 #if CONFIG_ZLIB
361  if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
362  uint8_t *zbuf;
363  int zlen, zn;
364  int j;
365 
366  zlen = bytes_per_row * s->rps;
367  zbuf = av_malloc(zlen);
368  if (!zbuf) {
369  ret = AVERROR(ENOMEM);
370  goto fail;
371  }
372  s->strip_offsets[0] = ptr - pkt->data;
373  zn = 0;
374  for (j = 0; j < s->rps; j++) {
375  if (is_yuv) {
376  pack_yuv(s, s->yuv_line, j);
377  memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
378  j += s->subsampling[1] - 1;
379  } else
380  memcpy(zbuf + j * bytes_per_row,
381  p->data[0] + j * p->linesize[0], bytes_per_row);
382  zn += bytes_per_row;
383  }
384  ret = encode_strip(s, zbuf, ptr, zn, s->compr);
385  av_free(zbuf);
386  if (ret < 0) {
387  av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
388  goto fail;
389  }
390  ptr += ret;
391  s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
392  } else
393 #endif
394  {
395  if (s->compr == TIFF_LZW) {
397  if (!s->lzws) {
398  ret = AVERROR(ENOMEM);
399  goto fail;
400  }
401  }
402  for (i = 0; i < s->height; i++) {
403  if (s->strip_sizes[i / s->rps] == 0) {
404  if (s->compr == TIFF_LZW) {
405  ff_lzw_encode_init(s->lzws, ptr,
406  s->buf_size - (*s->buf - s->buf_start),
407  12, FF_LZW_TIFF, put_bits);
408  }
409  s->strip_offsets[i / s->rps] = ptr - pkt->data;
410  }
411  if (is_yuv) {
412  pack_yuv(s, s->yuv_line, i);
413  ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
414  i += s->subsampling[1] - 1;
415  } else
416  ret = encode_strip(s, p->data[0] + i * p->linesize[0],
417  ptr, bytes_per_row, s->compr);
418  if (ret < 0) {
419  av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
420  goto fail;
421  }
422  s->strip_sizes[i / s->rps] += ret;
423  ptr += ret;
424  if (s->compr == TIFF_LZW &&
425  (i == s->height - 1 || i % s->rps == s->rps - 1)) {
427  s->strip_sizes[(i / s->rps)] += ret;
428  ptr += ret;
429  }
430  }
431  if (s->compr == TIFF_LZW)
432  av_free(s->lzws);
433  }
434 
435  s->num_entries = 0;
436 
440 
441  if (s->bpp_tab_size)
442  add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
443 
447 
448  if (s->bpp_tab_size)
450 
453  add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
454  add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
456 
457  if (!(avctx->flags & CODEC_FLAG_BITEXACT))
459  strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
460 
461  if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
462  uint16_t pal[256 * 3];
463  for (i = 0; i < 256; i++) {
464  uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
465  pal[i] = ((rgb >> 16) & 0xff) * 257;
466  pal[i + 256] = ((rgb >> 8) & 0xff) * 257;
467  pal[i + 512] = (rgb & 0xff) * 257;
468  }
469  add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
470  }
471  if (alpha)
473  if (is_yuv) {
474  /** according to CCIR Recommendation 601.1 */
475  uint32_t refbw[12] = { 15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1 };
480  }
481  // write offset to dir
482  bytestream_put_le32(&offset, ptr - pkt->data);
483 
484  if (check_size(s, 6 + s->num_entries * 12)) {
485  ret = AVERROR(EINVAL);
486  goto fail;
487  }
488  bytestream_put_le16(&ptr, s->num_entries); // write tag count
489  bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
490  bytestream_put_le32(&ptr, 0);
491 
492  pkt->size = ptr - pkt->data;
493  pkt->flags |= AV_PKT_FLAG_KEY;
494  *got_packet = 1;
495 
496 fail:
497  return ret < 0 ? ret : 0;
498 }
499 
501 {
502  TiffEncoderContext *s = avctx->priv_data;
503 
504  av_freep(&s->strip_sizes);
505  av_freep(&s->strip_offsets);
506  av_freep(&s->yuv_line);
507 
508  return 0;
509 }
510 
511 #define OFFSET(x) offsetof(TiffEncoderContext, x)
512 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
513 static const AVOption options[] = {
514  {"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},
515  { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, { .i64 = TIFF_PACKBITS }, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
516  { "packbits", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_PACKBITS }, 0, 0, VE, "compression_algo" },
517  { "raw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_RAW }, 0, 0, VE, "compression_algo" },
518  { "lzw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_LZW }, 0, 0, VE, "compression_algo" },
519 #if CONFIG_ZLIB
520  { "deflate", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_DEFLATE }, 0, 0, VE, "compression_algo" },
521 #endif
522  { NULL },
523 };
524 
525 static const AVClass tiffenc_class = {
526  .class_name = "TIFF encoder",
527  .item_name = av_default_item_name,
528  .option = options,
529  .version = LIBAVUTIL_VERSION_INT,
530 };
531 
533  .name = "tiff",
534  .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
535  .type = AVMEDIA_TYPE_VIDEO,
536  .id = AV_CODEC_ID_TIFF,
537  .priv_data_size = sizeof(TiffEncoderContext),
538  .init = encode_init,
539  .encode2 = encode_frame,
540  .close = encode_close,
541  .pix_fmts = (const enum AVPixelFormat[]) {
549  },
550  .priv_class = &tiffenc_class,
551 };