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