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.

545 lines
18KB

  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 int 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. if (check_size(s, count * type_sizes2[type]))
  118. return AVERROR_INVALIDDATA;
  119. tnput(s->buf, count, ptr_val, type, 0);
  120. }
  121. s->num_entries++;
  122. return 0;
  123. }
  124. static int add_entry1(TiffEncoderContext *s,
  125. enum TiffTags tag, enum TiffTypes type, int val)
  126. {
  127. uint16_t w = val;
  128. uint32_t dw = val;
  129. return add_entry(s, tag, type, 1,
  130. type == TIFF_SHORT ? (void *)&w : (void *)&dw);
  131. }
  132. /**
  133. * Encode one strip in tiff file
  134. *
  135. * @param s Tiff context
  136. * @param src Input buffer
  137. * @param dst Output buffer
  138. * @param n Size of input buffer
  139. * @param compr Compression method
  140. * @return Number of output bytes. If an output error is encountered, -1 returned
  141. */
  142. static int encode_strip(TiffEncoderContext *s, const int8_t *src,
  143. uint8_t *dst, int n, int compr)
  144. {
  145. switch (compr) {
  146. #if CONFIG_ZLIB
  147. case TIFF_DEFLATE:
  148. case TIFF_ADOBE_DEFLATE:
  149. {
  150. unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
  151. if (compress(dst, &zlen, src, n) != Z_OK) {
  152. av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
  153. return -1;
  154. }
  155. return zlen;
  156. }
  157. #endif
  158. case TIFF_RAW:
  159. if (check_size(s, n))
  160. return -1;
  161. memcpy(dst, src, n);
  162. return n;
  163. case TIFF_PACKBITS:
  164. return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start),
  165. src, 1, n, 2, 0xff, -1, 0);
  166. case TIFF_LZW:
  167. return ff_lzw_encode(s->lzws, src, n);
  168. default:
  169. return -1;
  170. }
  171. }
  172. static void pack_yuv(TiffEncoderContext *s, const AVFrame *p,
  173. uint8_t *dst, int lnum)
  174. {
  175. int i, j, k;
  176. int w = (s->width - 1) / s->subsampling[0] + 1;
  177. uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
  178. uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
  179. for (i = 0; i < w; i++) {
  180. for (j = 0; j < s->subsampling[1]; j++)
  181. for (k = 0; k < s->subsampling[0]; k++)
  182. *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
  183. i * s->subsampling[0] + k];
  184. *dst++ = *pu++;
  185. *dst++ = *pv++;
  186. }
  187. }
  188. #define ADD_ENTRY(s, tag, type, count, ptr_val) \
  189. do { \
  190. ret = add_entry(s, tag, type, count, ptr_val); \
  191. if (ret < 0) \
  192. goto fail; \
  193. } while(0);
  194. #define ADD_ENTRY1(s, tag, type, val) \
  195. do { \
  196. ret = add_entry1(s, tag, type, val); \
  197. if (ret < 0) \
  198. goto fail; \
  199. } while(0);
  200. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  201. const AVFrame *pict, int *got_packet)
  202. {
  203. TiffEncoderContext *s = avctx->priv_data;
  204. const AVFrame *const p = pict;
  205. int i;
  206. uint8_t *ptr;
  207. uint8_t *offset;
  208. uint32_t strips;
  209. uint32_t *strip_sizes = NULL;
  210. uint32_t *strip_offsets = NULL;
  211. int bytes_per_row;
  212. uint32_t res[2] = { 72, 1 }; // image resolution (72/1)
  213. uint16_t bpp_tab[] = { 8, 8, 8, 8 };
  214. int ret = 0;
  215. int is_yuv = 0;
  216. uint8_t *yuv_line = NULL;
  217. int shift_h, shift_v;
  218. int packet_size;
  219. const AVPixFmtDescriptor *pfd;
  220. s->avctx = avctx;
  221. s->width = avctx->width;
  222. s->height = avctx->height;
  223. s->subsampling[0] = 1;
  224. s->subsampling[1] = 1;
  225. switch (avctx->pix_fmt) {
  226. case AV_PIX_FMT_RGB48LE:
  227. case AV_PIX_FMT_GRAY16LE:
  228. case AV_PIX_FMT_RGBA:
  229. case AV_PIX_FMT_RGB24:
  230. case AV_PIX_FMT_GRAY8:
  231. case AV_PIX_FMT_PAL8:
  232. pfd = av_pix_fmt_desc_get(avctx->pix_fmt);
  233. s->bpp = av_get_bits_per_pixel(pfd);
  234. if (pfd->flags & AV_PIX_FMT_FLAG_PAL)
  235. s->photometric_interpretation = TIFF_PHOTOMETRIC_PALETTE;
  236. else if (pfd->flags & AV_PIX_FMT_FLAG_RGB)
  237. s->photometric_interpretation = TIFF_PHOTOMETRIC_RGB;
  238. else
  239. s->photometric_interpretation = TIFF_PHOTOMETRIC_BLACK_IS_ZERO;
  240. s->bpp_tab_size = pfd->nb_components;
  241. for (i = 0; i < s->bpp_tab_size; i++)
  242. bpp_tab[i] = s->bpp / s->bpp_tab_size;
  243. break;
  244. case AV_PIX_FMT_MONOBLACK:
  245. s->bpp = 1;
  246. s->photometric_interpretation = TIFF_PHOTOMETRIC_BLACK_IS_ZERO;
  247. s->bpp_tab_size = 0;
  248. break;
  249. case AV_PIX_FMT_MONOWHITE:
  250. s->bpp = 1;
  251. s->photometric_interpretation = TIFF_PHOTOMETRIC_WHITE_IS_ZERO;
  252. s->bpp_tab_size = 0;
  253. break;
  254. case AV_PIX_FMT_YUV420P:
  255. case AV_PIX_FMT_YUV422P:
  256. case AV_PIX_FMT_YUV444P:
  257. case AV_PIX_FMT_YUV410P:
  258. case AV_PIX_FMT_YUV411P:
  259. av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v);
  260. s->photometric_interpretation = TIFF_PHOTOMETRIC_YCBCR;
  261. s->bpp = 8 + (16 >> (shift_h + shift_v));
  262. s->subsampling[0] = 1 << shift_h;
  263. s->subsampling[1] = 1 << shift_v;
  264. s->bpp_tab_size = 3;
  265. is_yuv = 1;
  266. break;
  267. default:
  268. av_log(s->avctx, AV_LOG_ERROR,
  269. "This colors format is not supported\n");
  270. return -1;
  271. }
  272. if (s->compr == TIFF_DEFLATE ||
  273. s->compr == TIFF_ADOBE_DEFLATE ||
  274. s->compr == TIFF_LZW)
  275. // best choice for DEFLATE
  276. s->rps = s->height;
  277. else
  278. // suggest size of strip
  279. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);
  280. // round rps up
  281. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1];
  282. strips = (s->height - 1) / s->rps + 1;
  283. packet_size = avctx->height * ((avctx->width * s->bpp + 7) >> 3) * 2 +
  284. avctx->height * 4 + FF_MIN_BUFFER_SIZE;
  285. if (!pkt->data &&
  286. (ret = av_new_packet(pkt, packet_size)) < 0) {
  287. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  288. return ret;
  289. }
  290. ptr = pkt->data;
  291. s->buf_start = pkt->data;
  292. s->buf = &ptr;
  293. s->buf_size = pkt->size;
  294. if (check_size(s, 8))
  295. goto fail;
  296. // write header
  297. bytestream_put_le16(&ptr, 0x4949);
  298. bytestream_put_le16(&ptr, 42);
  299. offset = ptr;
  300. bytestream_put_le32(&ptr, 0);
  301. strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
  302. strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
  303. if (!strip_sizes || !strip_offsets) {
  304. ret = AVERROR(ENOMEM);
  305. goto fail;
  306. }
  307. bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *
  308. s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  309. if (is_yuv) {
  310. yuv_line = av_malloc(bytes_per_row);
  311. if (!yuv_line) {
  312. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  313. ret = AVERROR(ENOMEM);
  314. goto fail;
  315. }
  316. }
  317. #if CONFIG_ZLIB
  318. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
  319. uint8_t *zbuf;
  320. int zlen, zn;
  321. int j;
  322. zlen = bytes_per_row * s->rps;
  323. zbuf = av_malloc(zlen);
  324. if (!zbuf) {
  325. ret = AVERROR(ENOMEM);
  326. goto fail;
  327. }
  328. strip_offsets[0] = ptr - pkt->data;
  329. zn = 0;
  330. for (j = 0; j < s->rps; j++) {
  331. if (is_yuv) {
  332. pack_yuv(s, p, yuv_line, j);
  333. memcpy(zbuf + zn, yuv_line, bytes_per_row);
  334. j += s->subsampling[1] - 1;
  335. } else
  336. memcpy(zbuf + j * bytes_per_row,
  337. p->data[0] + j * p->linesize[0], bytes_per_row);
  338. zn += bytes_per_row;
  339. }
  340. ret = encode_strip(s, zbuf, ptr, zn, s->compr);
  341. av_free(zbuf);
  342. if (ret < 0) {
  343. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  344. goto fail;
  345. }
  346. ptr += ret;
  347. strip_sizes[0] = ptr - pkt->data - strip_offsets[0];
  348. } else
  349. #endif
  350. if (s->compr == TIFF_LZW) {
  351. s->lzws = av_malloc(ff_lzw_encode_state_size);
  352. if (!s->lzws) {
  353. ret = AVERROR(ENOMEM);
  354. goto fail;
  355. }
  356. }
  357. for (i = 0; i < s->height; i++) {
  358. if (strip_sizes[i / s->rps] == 0) {
  359. if (s->compr == TIFF_LZW) {
  360. ff_lzw_encode_init(s->lzws, ptr,
  361. s->buf_size - (*s->buf - s->buf_start),
  362. 12, FF_LZW_TIFF, put_bits);
  363. }
  364. strip_offsets[i / s->rps] = ptr - pkt->data;
  365. }
  366. if (is_yuv) {
  367. pack_yuv(s, p, yuv_line, i);
  368. ret = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
  369. i += s->subsampling[1] - 1;
  370. } else
  371. ret = encode_strip(s, p->data[0] + i * p->linesize[0],
  372. ptr, bytes_per_row, s->compr);
  373. if (ret < 0) {
  374. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  375. goto fail;
  376. }
  377. strip_sizes[i / s->rps] += ret;
  378. ptr += ret;
  379. if (s->compr == TIFF_LZW &&
  380. (i == s->height - 1 || i % s->rps == s->rps - 1)) {
  381. ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
  382. strip_sizes[(i / s->rps)] += ret;
  383. ptr += ret;
  384. }
  385. }
  386. if (s->compr == TIFF_LZW)
  387. av_free(s->lzws);
  388. s->num_entries = 0;
  389. ADD_ENTRY1(s, TIFF_SUBFILE, TIFF_LONG, 0);
  390. ADD_ENTRY1(s, TIFF_WIDTH, TIFF_LONG, s->width);
  391. ADD_ENTRY1(s, TIFF_HEIGHT, TIFF_LONG, s->height);
  392. if (s->bpp_tab_size)
  393. ADD_ENTRY(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
  394. ADD_ENTRY1(s, TIFF_COMPR, TIFF_SHORT, s->compr);
  395. ADD_ENTRY1(s, TIFF_PHOTOMETRIC, TIFF_SHORT, s->photometric_interpretation);
  396. ADD_ENTRY(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, strip_offsets);
  397. if (s->bpp_tab_size)
  398. ADD_ENTRY1(s, TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
  399. ADD_ENTRY1(s, TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
  400. ADD_ENTRY(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, strip_sizes);
  401. ADD_ENTRY(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
  402. ADD_ENTRY(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
  403. ADD_ENTRY1(s, TIFF_RES_UNIT, TIFF_SHORT, 2);
  404. if (!(avctx->flags & CODEC_FLAG_BITEXACT))
  405. ADD_ENTRY(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
  406. strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
  407. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  408. uint16_t pal[256 * 3];
  409. for (i = 0; i < 256; i++) {
  410. uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
  411. pal[i] = ((rgb >> 16) & 0xff) * 257;
  412. pal[i + 256] = ((rgb >> 8) & 0xff) * 257;
  413. pal[i + 512] = (rgb & 0xff) * 257;
  414. }
  415. ADD_ENTRY(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
  416. }
  417. if (is_yuv) {
  418. /** according to CCIR Recommendation 601.1 */
  419. uint32_t refbw[12] = { 15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1 };
  420. ADD_ENTRY(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
  421. ADD_ENTRY(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
  422. }
  423. // write offset to dir
  424. bytestream_put_le32(&offset, ptr - pkt->data);
  425. if (check_size(s, 6 + s->num_entries * 12)) {
  426. ret = AVERROR(EINVAL);
  427. goto fail;
  428. }
  429. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  430. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  431. bytestream_put_le32(&ptr, 0);
  432. pkt->size = ptr - pkt->data;
  433. pkt->flags |= AV_PKT_FLAG_KEY;
  434. *got_packet = 1;
  435. fail:
  436. av_free(strip_sizes);
  437. av_free(strip_offsets);
  438. av_free(yuv_line);
  439. return ret;
  440. }
  441. static av_cold int encode_init(AVCodecContext *avctx)
  442. {
  443. avctx->coded_frame = av_frame_alloc();
  444. if (!avctx->coded_frame)
  445. return AVERROR(ENOMEM);
  446. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  447. avctx->coded_frame->key_frame = 1;
  448. return 0;
  449. }
  450. static av_cold int encode_close(AVCodecContext *avctx)
  451. {
  452. av_frame_free(&avctx->coded_frame);
  453. return 0;
  454. }
  455. #define OFFSET(x) offsetof(TiffEncoderContext, x)
  456. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  457. static const AVOption options[] = {
  458. { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, { .i64 = TIFF_PACKBITS }, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
  459. { "packbits", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_PACKBITS }, 0, 0, VE, "compression_algo" },
  460. { "raw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_RAW }, 0, 0, VE, "compression_algo" },
  461. { "lzw", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_LZW }, 0, 0, VE, "compression_algo" },
  462. #if CONFIG_ZLIB
  463. { "deflate", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TIFF_DEFLATE }, 0, 0, VE, "compression_algo" },
  464. #endif
  465. { NULL },
  466. };
  467. static const AVClass tiffenc_class = {
  468. .class_name = "TIFF encoder",
  469. .item_name = av_default_item_name,
  470. .option = options,
  471. .version = LIBAVUTIL_VERSION_INT,
  472. };
  473. AVCodec ff_tiff_encoder = {
  474. .name = "tiff",
  475. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  476. .type = AVMEDIA_TYPE_VIDEO,
  477. .id = AV_CODEC_ID_TIFF,
  478. .priv_data_size = sizeof(TiffEncoderContext),
  479. .init = encode_init,
  480. .close = encode_close,
  481. .encode2 = encode_frame,
  482. .pix_fmts = (const enum AVPixelFormat[]) {
  483. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB48LE, AV_PIX_FMT_PAL8,
  484. AV_PIX_FMT_RGBA,
  485. AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16LE,
  486. AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_MONOWHITE,
  487. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
  488. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
  489. AV_PIX_FMT_NONE
  490. },
  491. .priv_class = &tiffenc_class,
  492. };