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.

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