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.

529 lines
17KB

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