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.

526 lines
17KB

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