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.

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