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.

546 lines
18KB

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