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.

506 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/log.h"
  27. #include "libavutil/opt.h"
  28. #include "avcodec.h"
  29. #if CONFIG_ZLIB
  30. #include <zlib.h>
  31. #endif
  32. #include "libavutil/opt.h"
  33. #include "bytestream.h"
  34. #include "tiff.h"
  35. #include "rle.h"
  36. #include "lzw.h"
  37. #include "put_bits.h"
  38. #define TIFF_MAX_ENTRY 32
  39. /** sizes of various TIFF field types (string size = 1)*/
  40. static const uint8_t type_sizes2[6] = {
  41. 0, 1, 1, 2, 4, 8
  42. };
  43. typedef struct TiffEncoderContext {
  44. AVClass *class; ///< for private options
  45. AVCodecContext *avctx;
  46. AVFrame picture;
  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. int photometric_interpretation; ///< photometric interpretation
  53. int strips; ///< number of strips
  54. int rps; ///< row per strip
  55. uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
  56. int num_entries; ///< number of entires
  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. uint32_t dpi; ///< image resolution in DPI
  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. inline static 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,
  107. enum TiffTags tag, enum TiffTypes type, int count,
  108. const void *ptr_val)
  109. {
  110. uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
  111. assert(s->num_entries < TIFF_MAX_ENTRY);
  112. bytestream_put_le16(&entries_ptr, tag);
  113. bytestream_put_le16(&entries_ptr, type);
  114. bytestream_put_le32(&entries_ptr, count);
  115. if (type_sizes[type] * count <= 4) {
  116. tnput(&entries_ptr, count, ptr_val, type, 0);
  117. } else {
  118. bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
  119. check_size(s, count * type_sizes2[type]);
  120. tnput(s->buf, count, ptr_val, type, 0);
  121. }
  122. s->num_entries++;
  123. }
  124. static void add_entry1(TiffEncoderContext * s,
  125. enum TiffTags tag, enum TiffTypes type, int val){
  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), src, 1, n, 2, 0xff, -1, 0);
  163. case TIFF_LZW:
  164. return ff_lzw_encode(s->lzws, src, n);
  165. default:
  166. return -1;
  167. }
  168. }
  169. static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum)
  170. {
  171. AVFrame *p = &s->picture;
  172. int i, j, k;
  173. int w = (s->width - 1) / s->subsampling[0] + 1;
  174. uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
  175. uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
  176. for (i = 0; i < w; i++){
  177. for (j = 0; j < s->subsampling[1]; j++)
  178. for (k = 0; k < s->subsampling[0]; k++)
  179. *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
  180. i * s->subsampling[0] + k];
  181. *dst++ = *pu++;
  182. *dst++ = *pv++;
  183. }
  184. }
  185. static int encode_frame(AVCodecContext * avctx, AVPacket *pkt,
  186. const AVFrame *pict, int *got_packet)
  187. {
  188. TiffEncoderContext *s = avctx->priv_data;
  189. AVFrame *const p = (AVFrame *) & s->picture;
  190. int i;
  191. uint8_t *ptr;
  192. uint8_t *offset;
  193. uint32_t strips;
  194. uint32_t *strip_sizes = NULL;
  195. uint32_t *strip_offsets = NULL;
  196. int bytes_per_row;
  197. uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
  198. uint16_t bpp_tab[] = { 8, 8, 8, 8 };
  199. int ret = -1;
  200. int is_yuv = 0;
  201. uint8_t *yuv_line = NULL;
  202. int shift_h, shift_v;
  203. s->avctx = avctx;
  204. *p = *pict;
  205. p->pict_type = AV_PICTURE_TYPE_I;
  206. p->key_frame = 1;
  207. avctx->coded_frame= &s->picture;
  208. s->width = avctx->width;
  209. s->height = avctx->height;
  210. s->subsampling[0] = 1;
  211. s->subsampling[1] = 1;
  212. switch (avctx->pix_fmt) {
  213. case PIX_FMT_RGBA64LE:
  214. s->bpp = 64;
  215. s->photometric_interpretation = 2;
  216. bpp_tab[0] = 16;
  217. bpp_tab[1] = 16;
  218. bpp_tab[2] = 16;
  219. bpp_tab[3] = 16;
  220. break;
  221. case PIX_FMT_RGB48LE:
  222. s->bpp = 48;
  223. s->photometric_interpretation = 2;
  224. bpp_tab[0] = 16;
  225. bpp_tab[1] = 16;
  226. bpp_tab[2] = 16;
  227. bpp_tab[3] = 16;
  228. break;
  229. case PIX_FMT_RGBA:
  230. s->bpp = 32;
  231. s->photometric_interpretation = 2;
  232. break;
  233. case PIX_FMT_RGB24:
  234. s->bpp = 24;
  235. s->photometric_interpretation = 2;
  236. break;
  237. case PIX_FMT_GRAY8:
  238. s->bpp = 8;
  239. s->photometric_interpretation = 1;
  240. break;
  241. case PIX_FMT_PAL8:
  242. s->bpp = 8;
  243. s->photometric_interpretation = 3;
  244. break;
  245. case PIX_FMT_MONOBLACK:
  246. case PIX_FMT_MONOWHITE:
  247. s->bpp = 1;
  248. s->photometric_interpretation = avctx->pix_fmt == PIX_FMT_MONOBLACK;
  249. bpp_tab[0] = 1;
  250. break;
  251. case PIX_FMT_YUV420P:
  252. case PIX_FMT_YUV422P:
  253. case PIX_FMT_YUV444P:
  254. case PIX_FMT_YUV410P:
  255. case PIX_FMT_YUV411P:
  256. s->photometric_interpretation = 6;
  257. avcodec_get_chroma_sub_sample(avctx->pix_fmt,
  258. &shift_h, &shift_v);
  259. s->bpp = 8 + (16 >> (shift_h + shift_v));
  260. s->subsampling[0] = 1 << shift_h;
  261. s->subsampling[1] = 1 << shift_v;
  262. s->bpp_tab_size = 3;
  263. is_yuv = 1;
  264. break;
  265. default:
  266. av_log(s->avctx, AV_LOG_ERROR,
  267. "This colors format is not supported\n");
  268. return -1;
  269. }
  270. if (!is_yuv)
  271. s->bpp_tab_size = (s->bpp >= 48) ? ((s->bpp + 7) >> 4):((s->bpp + 7) >> 3);
  272. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
  273. //best choose for DEFLATE
  274. s->rps = s->height;
  275. else
  276. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip
  277. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
  278. strips = (s->height - 1) / s->rps + 1;
  279. if (!pkt->data &&
  280. (ret = av_new_packet(pkt, avctx->width * avctx->height * s->bpp * 2 +
  281. avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0) {
  282. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  283. return ret;
  284. }
  285. ptr = pkt->data;
  286. s->buf_start = pkt->data;
  287. s->buf = &ptr;
  288. s->buf_size = pkt->size;
  289. if (check_size(s, 8))
  290. goto fail;
  291. // write header
  292. bytestream_put_le16(&ptr, 0x4949);
  293. bytestream_put_le16(&ptr, 42);
  294. offset = ptr;
  295. bytestream_put_le32(&ptr, 0);
  296. strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
  297. strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
  298. bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
  299. * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  300. if (is_yuv){
  301. yuv_line = av_malloc(bytes_per_row);
  302. if (yuv_line == NULL){
  303. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  304. goto fail;
  305. }
  306. }
  307. #if CONFIG_ZLIB
  308. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
  309. uint8_t *zbuf;
  310. int zlen, zn;
  311. int j;
  312. zlen = bytes_per_row * s->rps;
  313. zbuf = av_malloc(zlen);
  314. strip_offsets[0] = ptr - pkt->data;
  315. zn = 0;
  316. for (j = 0; j < s->rps; j++) {
  317. if (is_yuv){
  318. pack_yuv(s, yuv_line, j);
  319. memcpy(zbuf + zn, yuv_line, bytes_per_row);
  320. j += s->subsampling[1] - 1;
  321. }
  322. else
  323. memcpy(zbuf + j * bytes_per_row,
  324. p->data[0] + j * p->linesize[0], bytes_per_row);
  325. zn += bytes_per_row;
  326. }
  327. ret = encode_strip(s, zbuf, ptr, zn, s->compr);
  328. av_free(zbuf);
  329. if (ret < 0) {
  330. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  331. goto fail;
  332. }
  333. ptr += ret;
  334. strip_sizes[0] = ptr - pkt->data - strip_offsets[0];
  335. } else
  336. #endif
  337. {
  338. if(s->compr == TIFF_LZW)
  339. s->lzws = av_malloc(ff_lzw_encode_state_size);
  340. for (i = 0; i < s->height; i++) {
  341. if (strip_sizes[i / s->rps] == 0) {
  342. if(s->compr == TIFF_LZW){
  343. ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
  344. 12, FF_LZW_TIFF, put_bits);
  345. }
  346. strip_offsets[i / s->rps] = ptr - pkt->data;
  347. }
  348. if (is_yuv){
  349. pack_yuv(s, yuv_line, i);
  350. ret = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
  351. i += s->subsampling[1] - 1;
  352. }
  353. else
  354. ret = encode_strip(s, p->data[0] + i * p->linesize[0],
  355. ptr, bytes_per_row, s->compr);
  356. if (ret < 0) {
  357. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  358. goto fail;
  359. }
  360. strip_sizes[i / s->rps] += ret;
  361. ptr += ret;
  362. if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
  363. ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
  364. strip_sizes[(i / s->rps )] += ret ;
  365. ptr += ret;
  366. }
  367. }
  368. if(s->compr == TIFF_LZW)
  369. av_free(s->lzws);
  370. }
  371. s->num_entries = 0;
  372. add_entry1(s,TIFF_SUBFILE, TIFF_LONG, 0);
  373. add_entry1(s,TIFF_WIDTH, TIFF_LONG, s->width);
  374. add_entry1(s,TIFF_HEIGHT, TIFF_LONG, s->height);
  375. if (s->bpp_tab_size)
  376. add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
  377. add_entry1(s,TIFF_COMPR, TIFF_SHORT, s->compr);
  378. add_entry1(s,TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation);
  379. add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, strip_offsets);
  380. if (s->bpp_tab_size)
  381. add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
  382. add_entry1(s,TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
  383. add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, strip_sizes);
  384. add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
  385. add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
  386. add_entry1(s,TIFF_RES_UNIT, TIFF_SHORT, 2);
  387. if(!(avctx->flags & CODEC_FLAG_BITEXACT))
  388. add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
  389. strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
  390. if (avctx->pix_fmt == PIX_FMT_PAL8) {
  391. uint16_t pal[256 * 3];
  392. for (i = 0; i < 256; i++) {
  393. uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
  394. pal[i] = ((rgb >> 16) & 0xff) * 257;
  395. pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
  396. pal[i + 512] = ( rgb & 0xff) * 257;
  397. }
  398. add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
  399. }
  400. if (is_yuv){
  401. /** according to CCIR Recommendation 601.1 */
  402. uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
  403. add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
  404. add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
  405. }
  406. bytestream_put_le32(&offset, ptr - pkt->data); // write offset to dir
  407. if (check_size(s, 6 + s->num_entries * 12)) {
  408. ret = AVERROR(EINVAL);
  409. goto fail;
  410. }
  411. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  412. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  413. bytestream_put_le32(&ptr, 0);
  414. pkt->size = ptr - pkt->data;
  415. pkt->flags |= AV_PKT_FLAG_KEY;
  416. *got_packet = 1;
  417. fail:
  418. av_free(strip_sizes);
  419. av_free(strip_offsets);
  420. av_free(yuv_line);
  421. return ret;
  422. }
  423. #define OFFSET(x) offsetof(TiffEncoderContext, x)
  424. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  425. static const AVOption options[] = {
  426. {"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},
  427. { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
  428. { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
  429. { "raw", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_RAW}, 0, 0, VE, "compression_algo" },
  430. { "lzw", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_LZW}, 0, 0, VE, "compression_algo" },
  431. #if CONFIG_ZLIB
  432. { "deflate", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_DEFLATE}, 0, 0, VE, "compression_algo" },
  433. #endif
  434. { NULL },
  435. };
  436. static const AVClass tiffenc_class = {
  437. .class_name = "TIFF encoder",
  438. .item_name = av_default_item_name,
  439. .option = options,
  440. .version = LIBAVUTIL_VERSION_INT,
  441. };
  442. AVCodec ff_tiff_encoder = {
  443. .name = "tiff",
  444. .type = AVMEDIA_TYPE_VIDEO,
  445. .id = CODEC_ID_TIFF,
  446. .priv_data_size = sizeof(TiffEncoderContext),
  447. .encode2 = encode_frame,
  448. .pix_fmts =
  449. (const enum PixelFormat[]) {PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8,
  450. PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
  451. PIX_FMT_YUV420P, PIX_FMT_YUV422P,
  452. PIX_FMT_YUV444P, PIX_FMT_YUV410P,
  453. PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
  454. PIX_FMT_RGBA, PIX_FMT_RGBA64LE, PIX_FMT_NONE},
  455. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  456. .priv_class = &tiffenc_class,
  457. };