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.

497 lines
16KB

  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, unsigned char *buf,
  186. int buf_size, void *data)
  187. {
  188. TiffEncoderContext *s = avctx->priv_data;
  189. AVFrame *pict = data;
  190. AVFrame *const p = (AVFrame *) & s->picture;
  191. int i;
  192. int n;
  193. uint8_t *ptr = buf;
  194. uint8_t *offset;
  195. uint32_t strips;
  196. uint32_t *strip_sizes = NULL;
  197. uint32_t *strip_offsets = NULL;
  198. int bytes_per_row;
  199. uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
  200. uint16_t bpp_tab[] = { 8, 8, 8, 8 };
  201. int ret = -1;
  202. int is_yuv = 0;
  203. uint8_t *yuv_line = NULL;
  204. int shift_h, shift_v;
  205. s->avctx = avctx;
  206. s->buf_start = buf;
  207. s->buf = &ptr;
  208. s->buf_size = buf_size;
  209. *p = *pict;
  210. p->pict_type = AV_PICTURE_TYPE_I;
  211. p->key_frame = 1;
  212. avctx->coded_frame= &s->picture;
  213. s->width = avctx->width;
  214. s->height = avctx->height;
  215. s->subsampling[0] = 1;
  216. s->subsampling[1] = 1;
  217. switch (avctx->pix_fmt) {
  218. case PIX_FMT_RGBA64LE:
  219. s->bpp = 64;
  220. s->photometric_interpretation = 2;
  221. bpp_tab[0] = 16;
  222. bpp_tab[1] = 16;
  223. bpp_tab[2] = 16;
  224. bpp_tab[3] = 16;
  225. break;
  226. case PIX_FMT_RGB48LE:
  227. s->bpp = 48;
  228. s->photometric_interpretation = 2;
  229. bpp_tab[0] = 16;
  230. bpp_tab[1] = 16;
  231. bpp_tab[2] = 16;
  232. bpp_tab[3] = 16;
  233. break;
  234. case PIX_FMT_RGBA:
  235. s->bpp = 32;
  236. s->photometric_interpretation = 2;
  237. break;
  238. case PIX_FMT_RGB24:
  239. s->bpp = 24;
  240. s->photometric_interpretation = 2;
  241. break;
  242. case PIX_FMT_GRAY8:
  243. s->bpp = 8;
  244. s->photometric_interpretation = 1;
  245. break;
  246. case PIX_FMT_PAL8:
  247. s->bpp = 8;
  248. s->photometric_interpretation = 3;
  249. break;
  250. case PIX_FMT_MONOBLACK:
  251. case PIX_FMT_MONOWHITE:
  252. s->bpp = 1;
  253. s->photometric_interpretation = avctx->pix_fmt == PIX_FMT_MONOBLACK;
  254. bpp_tab[0] = 1;
  255. break;
  256. case PIX_FMT_YUV420P:
  257. case PIX_FMT_YUV422P:
  258. case PIX_FMT_YUV444P:
  259. case PIX_FMT_YUV410P:
  260. case PIX_FMT_YUV411P:
  261. s->photometric_interpretation = 6;
  262. avcodec_get_chroma_sub_sample(avctx->pix_fmt,
  263. &shift_h, &shift_v);
  264. s->bpp = 8 + (16 >> (shift_h + shift_v));
  265. s->subsampling[0] = 1 << shift_h;
  266. s->subsampling[1] = 1 << shift_v;
  267. s->bpp_tab_size = 3;
  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. if (!is_yuv)
  276. s->bpp_tab_size = (s->bpp >= 48) ? ((s->bpp + 7) >> 4):((s->bpp + 7) >> 3);
  277. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
  278. //best choose for DEFLATE
  279. s->rps = s->height;
  280. else
  281. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip
  282. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
  283. strips = (s->height - 1) / s->rps + 1;
  284. if (check_size(s, 8))
  285. goto fail;
  286. // write header
  287. bytestream_put_le16(&ptr, 0x4949);
  288. bytestream_put_le16(&ptr, 42);
  289. offset = ptr;
  290. bytestream_put_le32(&ptr, 0);
  291. strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
  292. strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
  293. bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
  294. * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  295. if (is_yuv){
  296. yuv_line = av_malloc(bytes_per_row);
  297. if (yuv_line == NULL){
  298. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  299. goto fail;
  300. }
  301. }
  302. #if CONFIG_ZLIB
  303. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
  304. uint8_t *zbuf;
  305. int zlen, zn;
  306. int j;
  307. zlen = bytes_per_row * s->rps;
  308. zbuf = av_malloc(zlen);
  309. strip_offsets[0] = ptr - buf;
  310. zn = 0;
  311. for (j = 0; j < s->rps; j++) {
  312. if (is_yuv){
  313. pack_yuv(s, yuv_line, j);
  314. memcpy(zbuf + zn, yuv_line, bytes_per_row);
  315. j += s->subsampling[1] - 1;
  316. }
  317. else
  318. memcpy(zbuf + j * bytes_per_row,
  319. p->data[0] + j * p->linesize[0], bytes_per_row);
  320. zn += bytes_per_row;
  321. }
  322. n = encode_strip(s, zbuf, ptr, zn, s->compr);
  323. av_free(zbuf);
  324. if (n<0) {
  325. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  326. goto fail;
  327. }
  328. ptr += n;
  329. strip_sizes[0] = ptr - buf - strip_offsets[0];
  330. } else
  331. #endif
  332. {
  333. if(s->compr == TIFF_LZW)
  334. s->lzws = av_malloc(ff_lzw_encode_state_size);
  335. for (i = 0; i < s->height; i++) {
  336. if (strip_sizes[i / s->rps] == 0) {
  337. if(s->compr == TIFF_LZW){
  338. ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
  339. 12, FF_LZW_TIFF, put_bits);
  340. }
  341. strip_offsets[i / s->rps] = ptr - buf;
  342. }
  343. if (is_yuv){
  344. pack_yuv(s, yuv_line, i);
  345. n = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
  346. i += s->subsampling[1] - 1;
  347. }
  348. else
  349. n = encode_strip(s, p->data[0] + i * p->linesize[0],
  350. ptr, bytes_per_row, s->compr);
  351. if (n < 0) {
  352. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  353. goto fail;
  354. }
  355. strip_sizes[i / s->rps] += n;
  356. ptr += n;
  357. if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
  358. int ret;
  359. ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
  360. strip_sizes[(i / s->rps )] += ret ;
  361. ptr += ret;
  362. }
  363. }
  364. if(s->compr == TIFF_LZW)
  365. av_free(s->lzws);
  366. }
  367. s->num_entries = 0;
  368. add_entry1(s,TIFF_SUBFILE, TIFF_LONG, 0);
  369. add_entry1(s,TIFF_WIDTH, TIFF_LONG, s->width);
  370. add_entry1(s,TIFF_HEIGHT, TIFF_LONG, s->height);
  371. if (s->bpp_tab_size)
  372. add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
  373. add_entry1(s,TIFF_COMPR, TIFF_SHORT, s->compr);
  374. add_entry1(s,TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation);
  375. add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, strip_offsets);
  376. if (s->bpp_tab_size)
  377. add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
  378. add_entry1(s,TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
  379. add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, strip_sizes);
  380. add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
  381. add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
  382. add_entry1(s,TIFF_RES_UNIT, TIFF_SHORT, 2);
  383. if(!(avctx->flags & CODEC_FLAG_BITEXACT))
  384. add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
  385. strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
  386. if (avctx->pix_fmt == PIX_FMT_PAL8) {
  387. uint16_t pal[256 * 3];
  388. for (i = 0; i < 256; i++) {
  389. uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
  390. pal[i] = ((rgb >> 16) & 0xff) * 257;
  391. pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
  392. pal[i + 512] = ( rgb & 0xff) * 257;
  393. }
  394. add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
  395. }
  396. if (is_yuv){
  397. /** according to CCIR Recommendation 601.1 */
  398. uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
  399. add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
  400. add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
  401. }
  402. bytestream_put_le32(&offset, ptr - buf); // write offset to dir
  403. if (check_size(s, 6 + s->num_entries * 12))
  404. goto fail;
  405. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  406. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  407. bytestream_put_le32(&ptr, 0);
  408. ret = ptr - buf;
  409. fail:
  410. av_free(strip_sizes);
  411. av_free(strip_offsets);
  412. av_free(yuv_line);
  413. return ret;
  414. }
  415. #define OFFSET(x) offsetof(TiffEncoderContext, x)
  416. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  417. static const AVOption options[] = {
  418. {"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},
  419. { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
  420. { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
  421. { "raw", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_RAW}, 0, 0, VE, "compression_algo" },
  422. { "lzw", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_LZW}, 0, 0, VE, "compression_algo" },
  423. #if CONFIG_ZLIB
  424. { "deflate", NULL, 0, AV_OPT_TYPE_CONST, {TIFF_DEFLATE}, 0, 0, VE, "compression_algo" },
  425. #endif
  426. { NULL },
  427. };
  428. static const AVClass tiffenc_class = {
  429. .class_name = "TIFF encoder",
  430. .item_name = av_default_item_name,
  431. .option = options,
  432. .version = LIBAVUTIL_VERSION_INT,
  433. };
  434. AVCodec ff_tiff_encoder = {
  435. .name = "tiff",
  436. .type = AVMEDIA_TYPE_VIDEO,
  437. .id = CODEC_ID_TIFF,
  438. .priv_data_size = sizeof(TiffEncoderContext),
  439. .encode = encode_frame,
  440. .pix_fmts =
  441. (const enum PixelFormat[]) {PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8,
  442. PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
  443. PIX_FMT_YUV420P, PIX_FMT_YUV422P,
  444. PIX_FMT_YUV444P, PIX_FMT_YUV410P,
  445. PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
  446. PIX_FMT_RGBA, PIX_FMT_RGBA64LE, PIX_FMT_NONE},
  447. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  448. .priv_class = &tiffenc_class,
  449. };