You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

552 lines
18KB

  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. * @file
  23. * TIFF image encoder
  24. * @author Bartlomiej Wolowiec
  25. */
  26. #include "config.h"
  27. #if CONFIG_ZLIB
  28. #include <zlib.h>
  29. #endif
  30. #include "libavutil/imgutils.h"
  31. #include "libavutil/log.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "avcodec.h"
  35. #include "bytestream.h"
  36. #include "internal.h"
  37. #include "lzw.h"
  38. #include "put_bits.h"
  39. #include "rle.h"
  40. #include "tiff.h"
  41. #define TIFF_MAX_ENTRY 32
  42. /** sizes of various TIFF field types (string size = 1)*/
  43. static const uint8_t type_sizes2[14] = {
  44. 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4
  45. };
  46. typedef struct TiffEncoderContext {
  47. AVClass *class; ///< for private options
  48. AVCodecContext *avctx;
  49. AVFrame picture;
  50. int width; ///< picture width
  51. int height; ///< picture height
  52. unsigned int bpp; ///< bits per pixel
  53. int compr; ///< compression level
  54. int bpp_tab_size; ///< bpp_tab size
  55. int photometric_interpretation; ///< photometric interpretation
  56. int strips; ///< number of strips
  57. uint32_t *strip_sizes;
  58. unsigned int strip_sizes_size;
  59. uint32_t *strip_offsets;
  60. unsigned int strip_offsets_size;
  61. uint8_t *yuv_line;
  62. unsigned int yuv_line_size;
  63. int rps; ///< row per strip
  64. uint8_t entries[TIFF_MAX_ENTRY * 12]; ///< entries in header
  65. int num_entries; ///< number of entries
  66. uint8_t **buf; ///< actual position in buffer
  67. uint8_t *buf_start; ///< pointer to first byte in buffer
  68. int buf_size; ///< buffer size
  69. uint16_t subsampling[2]; ///< YUV subsampling factors
  70. struct LZWEncodeState *lzws; ///< LZW encode state
  71. uint32_t dpi; ///< image resolution in DPI
  72. } TiffEncoderContext;
  73. /**
  74. * Check free space in buffer.
  75. *
  76. * @param s Tiff context
  77. * @param need Needed bytes
  78. * @return 0 - ok, 1 - no free space
  79. */
  80. static inline int check_size(TiffEncoderContext *s, uint64_t need)
  81. {
  82. if (s->buf_size < *s->buf - s->buf_start + need) {
  83. *s->buf = s->buf_start + s->buf_size + 1;
  84. av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
  85. return 1;
  86. }
  87. return 0;
  88. }
  89. /**
  90. * Put n values to buffer.
  91. *
  92. * @param p pointer to pointer to output buffer
  93. * @param n number of values
  94. * @param val pointer to values
  95. * @param type type of values
  96. * @param flip = 0 - normal copy, >0 - flip
  97. */
  98. static void tnput(uint8_t **p, int n, const uint8_t *val, enum TiffTypes type,
  99. int flip)
  100. {
  101. int i;
  102. #if HAVE_BIGENDIAN
  103. flip ^= ((int[]) { 0, 0, 0, 1, 3, 3 })[type];
  104. #endif
  105. for (i = 0; i < n * type_sizes2[type]; i++)
  106. *(*p)++ = val[i ^ flip];
  107. }
  108. /**
  109. * Add entry to directory in tiff header.
  110. *
  111. * @param s Tiff context
  112. * @param tag tag that identifies the entry
  113. * @param type entry type
  114. * @param count the number of values
  115. * @param ptr_val pointer to values
  116. */
  117. static void add_entry(TiffEncoderContext *s, enum TiffTags tag,
  118. enum TiffTypes type, int count, const void *ptr_val)
  119. {
  120. uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
  121. av_assert0(s->num_entries < TIFF_MAX_ENTRY);
  122. bytestream_put_le16(&entries_ptr, tag);
  123. bytestream_put_le16(&entries_ptr, type);
  124. bytestream_put_le32(&entries_ptr, count);
  125. if (type_sizes[type] * (int64_t)count <= 4) {
  126. tnput(&entries_ptr, count, ptr_val, type, 0);
  127. } else {
  128. bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
  129. check_size(s, count * (int64_t)type_sizes2[type]);
  130. tnput(s->buf, count, ptr_val, type, 0);
  131. }
  132. s->num_entries++;
  133. }
  134. static void add_entry1(TiffEncoderContext *s,
  135. enum TiffTags tag, enum TiffTypes type, int val)
  136. {
  137. uint16_t w = val;
  138. uint32_t dw = val;
  139. add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
  140. }
  141. /**
  142. * Encode one strip in tiff file.
  143. *
  144. * @param s Tiff context
  145. * @param src input buffer
  146. * @param dst output buffer
  147. * @param n size of input buffer
  148. * @param compr compression method
  149. * @return number of output bytes. If an output error is encountered, -1 is returned
  150. */
  151. static int encode_strip(TiffEncoderContext *s, const int8_t *src,
  152. uint8_t *dst, int n, int compr)
  153. {
  154. switch (compr) {
  155. #if CONFIG_ZLIB
  156. case TIFF_DEFLATE:
  157. case TIFF_ADOBE_DEFLATE:
  158. {
  159. unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
  160. if (compress(dst, &zlen, src, n) != Z_OK) {
  161. av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
  162. return -1;
  163. }
  164. return zlen;
  165. }
  166. #endif
  167. case TIFF_RAW:
  168. if (check_size(s, n))
  169. return -1;
  170. memcpy(dst, src, n);
  171. return n;
  172. case TIFF_PACKBITS:
  173. return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start),
  174. src, 1, n, 2, 0xff, -1, 0);
  175. case TIFF_LZW:
  176. return ff_lzw_encode(s->lzws, src, n);
  177. default:
  178. return -1;
  179. }
  180. }
  181. static void pack_yuv(TiffEncoderContext *s, uint8_t *dst, int lnum)
  182. {
  183. AVFrame *p = &s->picture;
  184. int i, j, k;
  185. int w = (s->width - 1) / s->subsampling[0] + 1;
  186. uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
  187. uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
  188. if (s->width % s->subsampling[0] || s->height % s->subsampling[1]) {
  189. for (i = 0; i < w; i++) {
  190. for (j = 0; j < s->subsampling[1]; j++)
  191. for (k = 0; k < s->subsampling[0]; k++)
  192. *dst++ = p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
  193. FFMIN(i * s->subsampling[0] + k, s->width-1)];
  194. *dst++ = *pu++;
  195. *dst++ = *pv++;
  196. }
  197. }else{
  198. for (i = 0; i < w; i++) {
  199. for (j = 0; j < s->subsampling[1]; j++)
  200. for (k = 0; k < s->subsampling[0]; k++)
  201. *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
  202. i * s->subsampling[0] + k];
  203. *dst++ = *pu++;
  204. *dst++ = *pv++;
  205. }
  206. }
  207. }
  208. static av_cold int encode_init(AVCodecContext *avctx)
  209. {
  210. TiffEncoderContext *s = avctx->priv_data;
  211. avctx->coded_frame = &s->picture;
  212. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  213. avctx->coded_frame->key_frame = 1;
  214. s->avctx = avctx;
  215. return 0;
  216. }
  217. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  218. const AVFrame *pict, int *got_packet)
  219. {
  220. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  221. TiffEncoderContext *s = avctx->priv_data;
  222. AVFrame *const p = &s->picture;
  223. int i;
  224. uint8_t *ptr;
  225. uint8_t *offset;
  226. uint32_t strips;
  227. int bytes_per_row;
  228. uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
  229. uint16_t bpp_tab[4];
  230. int ret = -1;
  231. int is_yuv = 0, alpha = 0;
  232. int shift_h, shift_v;
  233. *p = *pict;
  234. s->width = avctx->width;
  235. s->height = avctx->height;
  236. s->subsampling[0] = 1;
  237. s->subsampling[1] = 1;
  238. avctx->bits_per_coded_sample =
  239. s->bpp = av_get_bits_per_pixel(desc);
  240. s->bpp_tab_size = desc->nb_components;
  241. switch (avctx->pix_fmt) {
  242. case AV_PIX_FMT_RGBA64LE:
  243. case AV_PIX_FMT_RGBA:
  244. alpha = 1;
  245. case AV_PIX_FMT_RGB48LE:
  246. case AV_PIX_FMT_RGB24:
  247. s->photometric_interpretation = 2;
  248. break;
  249. case AV_PIX_FMT_GRAY8:
  250. avctx->bits_per_coded_sample = 0x28;
  251. case AV_PIX_FMT_GRAY8A:
  252. alpha = avctx->pix_fmt == AV_PIX_FMT_GRAY8A;
  253. case AV_PIX_FMT_GRAY16LE:
  254. case AV_PIX_FMT_MONOBLACK:
  255. s->photometric_interpretation = 1;
  256. break;
  257. case AV_PIX_FMT_PAL8:
  258. s->photometric_interpretation = 3;
  259. break;
  260. case AV_PIX_FMT_MONOWHITE:
  261. s->photometric_interpretation = 0;
  262. break;
  263. case AV_PIX_FMT_YUV420P:
  264. case AV_PIX_FMT_YUV422P:
  265. case AV_PIX_FMT_YUV440P:
  266. case AV_PIX_FMT_YUV444P:
  267. case AV_PIX_FMT_YUV410P:
  268. case AV_PIX_FMT_YUV411P:
  269. av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);
  270. s->photometric_interpretation = 6;
  271. s->subsampling[0] = 1 << shift_h;
  272. s->subsampling[1] = 1 << shift_v;
  273. is_yuv = 1;
  274. break;
  275. default:
  276. av_log(s->avctx, AV_LOG_ERROR,
  277. "This colors format is not supported\n");
  278. return -1;
  279. }
  280. for (i = 0; i < s->bpp_tab_size; i++)
  281. bpp_tab[i] = desc->comp[i].depth_minus1 + 1;
  282. if (s->compr == TIFF_DEFLATE ||
  283. s->compr == TIFF_ADOBE_DEFLATE ||
  284. s->compr == TIFF_LZW)
  285. // best choice for DEFLATE
  286. s->rps = s->height;
  287. else
  288. // suggest size of strip
  289. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);
  290. // round rps up
  291. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1];
  292. strips = (s->height - 1) / s->rps + 1;
  293. if ((ret = ff_alloc_packet2(avctx, pkt,
  294. avctx->width * avctx->height * s->bpp * 2 +
  295. avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
  296. return ret;
  297. ptr = pkt->data;
  298. s->buf_start = pkt->data;
  299. s->buf = &ptr;
  300. s->buf_size = pkt->size;
  301. if (check_size(s, 8))
  302. goto fail;
  303. // write header
  304. bytestream_put_le16(&ptr, 0x4949);
  305. bytestream_put_le16(&ptr, 42);
  306. offset = ptr;
  307. bytestream_put_le32(&ptr, 0);
  308. av_fast_padded_mallocz(&s->strip_sizes , &s->strip_sizes_size , sizeof(s->strip_sizes [0]) * strips);
  309. av_fast_padded_mallocz(&s->strip_offsets, &s->strip_offsets_size, sizeof(s->strip_offsets[0]) * strips);
  310. if (!s->strip_sizes || !s->strip_offsets) {
  311. ret = AVERROR(ENOMEM);
  312. goto fail;
  313. }
  314. bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
  315. s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  316. if (is_yuv) {
  317. av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);
  318. if (s->yuv_line == NULL) {
  319. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  320. ret = AVERROR(ENOMEM);
  321. goto fail;
  322. }
  323. }
  324. #if CONFIG_ZLIB
  325. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
  326. uint8_t *zbuf;
  327. int zlen, zn;
  328. int j;
  329. zlen = bytes_per_row * s->rps;
  330. zbuf = av_malloc(zlen);
  331. if (!zbuf) {
  332. ret = AVERROR(ENOMEM);
  333. goto fail;
  334. }
  335. s->strip_offsets[0] = ptr - pkt->data;
  336. zn = 0;
  337. for (j = 0; j < s->rps; j++) {
  338. if (is_yuv) {
  339. pack_yuv(s, s->yuv_line, j);
  340. memcpy(zbuf + zn, s->yuv_line, bytes_per_row);
  341. j += s->subsampling[1] - 1;
  342. } else
  343. memcpy(zbuf + j * bytes_per_row,
  344. p->data[0] + j * p->linesize[0], bytes_per_row);
  345. zn += bytes_per_row;
  346. }
  347. ret = encode_strip(s, zbuf, ptr, zn, s->compr);
  348. av_free(zbuf);
  349. if (ret < 0) {
  350. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  351. goto fail;
  352. }
  353. ptr += ret;
  354. s->strip_sizes[0] = ptr - pkt->data - s->strip_offsets[0];
  355. } else
  356. #endif
  357. {
  358. if (s->compr == TIFF_LZW) {
  359. s->lzws = av_malloc(ff_lzw_encode_state_size);
  360. if (!s->lzws) {
  361. ret = AVERROR(ENOMEM);
  362. goto fail;
  363. }
  364. }
  365. for (i = 0; i < s->height; i++) {
  366. if (s->strip_sizes[i / s->rps] == 0) {
  367. if (s->compr == TIFF_LZW) {
  368. ff_lzw_encode_init(s->lzws, ptr,
  369. s->buf_size - (*s->buf - s->buf_start),
  370. 12, FF_LZW_TIFF, put_bits);
  371. }
  372. s->strip_offsets[i / s->rps] = ptr - pkt->data;
  373. }
  374. if (is_yuv) {
  375. pack_yuv(s, s->yuv_line, i);
  376. ret = encode_strip(s, s->yuv_line, ptr, bytes_per_row, s->compr);
  377. i += s->subsampling[1] - 1;
  378. } else
  379. ret = encode_strip(s, p->data[0] + i * p->linesize[0],
  380. ptr, bytes_per_row, s->compr);
  381. if (ret < 0) {
  382. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  383. goto fail;
  384. }
  385. s->strip_sizes[i / s->rps] += ret;
  386. ptr += ret;
  387. if (s->compr == TIFF_LZW &&
  388. (i == s->height - 1 || i % s->rps == s->rps - 1)) {
  389. ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
  390. s->strip_sizes[(i / s->rps)] += ret;
  391. ptr += ret;
  392. }
  393. }
  394. if (s->compr == TIFF_LZW)
  395. av_free(s->lzws);
  396. }
  397. s->num_entries = 0;
  398. add_entry1(s, TIFF_SUBFILE, TIFF_LONG, 0);
  399. add_entry1(s, TIFF_WIDTH, TIFF_LONG, s->width);
  400. add_entry1(s, TIFF_HEIGHT, TIFF_LONG, s->height);
  401. if (s->bpp_tab_size)
  402. add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
  403. add_entry1(s, TIFF_COMPR, TIFF_SHORT, s->compr);
  404. add_entry1(s, TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation);
  405. add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, s->strip_offsets);
  406. if (s->bpp_tab_size)
  407. add_entry1(s, TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
  408. add_entry1(s, TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
  409. add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, s->strip_sizes);
  410. add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
  411. add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
  412. add_entry1(s, TIFF_RES_UNIT, TIFF_SHORT, 2);
  413. if (!(avctx->flags & CODEC_FLAG_BITEXACT))
  414. add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
  415. strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
  416. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  417. uint16_t pal[256 * 3];
  418. for (i = 0; i < 256; i++) {
  419. uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
  420. pal[i] = ((rgb >> 16) & 0xff) * 257;
  421. pal[i + 256] = ((rgb >> 8) & 0xff) * 257;
  422. pal[i + 512] = (rgb & 0xff) * 257;
  423. }
  424. add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
  425. }
  426. if (alpha)
  427. add_entry1(s,TIFF_EXTRASAMPLES, TIFF_SHORT, 2);
  428. if (is_yuv) {
  429. /** according to CCIR Recommendation 601.1 */
  430. uint32_t refbw[12] = { 15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1 };
  431. add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
  432. if (avctx->chroma_sample_location == AVCHROMA_LOC_TOPLEFT)
  433. add_entry1(s, TIFF_YCBCR_POSITIONING, TIFF_SHORT, 2);
  434. add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
  435. }
  436. // write offset to dir
  437. bytestream_put_le32(&offset, ptr - pkt->data);
  438. if (check_size(s, 6 + s->num_entries * 12)) {
  439. ret = AVERROR(EINVAL);
  440. goto fail;
  441. }
  442. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  443. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  444. bytestream_put_le32(&ptr, 0);
  445. pkt->size = ptr - pkt->data;
  446. pkt->flags |= AV_PKT_FLAG_KEY;
  447. *got_packet = 1;
  448. fail:
  449. return ret < 0 ? ret : 0;
  450. }
  451. static av_cold int encode_close(AVCodecContext *avctx)
  452. {
  453. TiffEncoderContext *s = avctx->priv_data;
  454. av_freep(&s->strip_sizes);
  455. av_freep(&s->strip_offsets);
  456. av_freep(&s->yuv_line);
  457. return 0;
  458. }
  459. #define OFFSET(x) offsetof(TiffEncoderContext, x)
  460. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  461. static const AVOption options[] = {
  462. {"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},
  463. { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, { .i64 = TIFF_PACKBITS }, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
  464. { "packbits", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_PACKBITS }, 0, 0, VE, "compression_algo" },
  465. { "raw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_RAW }, 0, 0, VE, "compression_algo" },
  466. { "lzw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_LZW }, 0, 0, VE, "compression_algo" },
  467. #if CONFIG_ZLIB
  468. { "deflate", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_DEFLATE }, 0, 0, VE, "compression_algo" },
  469. #endif
  470. { NULL },
  471. };
  472. static const AVClass tiffenc_class = {
  473. .class_name = "TIFF encoder",
  474. .item_name = av_default_item_name,
  475. .option = options,
  476. .version = LIBAVUTIL_VERSION_INT,
  477. };
  478. AVCodec ff_tiff_encoder = {
  479. .name = "tiff",
  480. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  481. .type = AVMEDIA_TYPE_VIDEO,
  482. .id = AV_CODEC_ID_TIFF,
  483. .priv_data_size = sizeof(TiffEncoderContext),
  484. .init = encode_init,
  485. .encode2 = encode_frame,
  486. .close = encode_close,
  487. .pix_fmts = (const enum AVPixelFormat[]) {
  488. AV_PIX_FMT_RGB24, AV_PIX_FMT_PAL8, AV_PIX_FMT_GRAY8,
  489. AV_PIX_FMT_GRAY8A, AV_PIX_FMT_GRAY16LE,
  490. AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_MONOWHITE,
  491. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
  492. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_RGB48LE,
  493. AV_PIX_FMT_RGBA, AV_PIX_FMT_RGBA64LE,
  494. AV_PIX_FMT_NONE
  495. },
  496. .priv_class = &tiffenc_class,
  497. };