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.

501 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 "internal.h"
  31. #if CONFIG_ZLIB
  32. #include <zlib.h>
  33. #endif
  34. #include "libavutil/opt.h"
  35. #include "bytestream.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[6] = {
  43. 0, 1, 1, 2, 4, 8
  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. int rps; ///< row per strip
  57. uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
  58. int num_entries; ///< number of entires
  59. uint8_t **buf; ///< actual position in buffer
  60. uint8_t *buf_start; ///< pointer to first byte in buffer
  61. int buf_size; ///< buffer size
  62. uint16_t subsampling[2]; ///< YUV subsampling factors
  63. struct LZWEncodeState *lzws; ///< LZW Encode state
  64. uint32_t dpi; ///< image resolution in DPI
  65. } TiffEncoderContext;
  66. /**
  67. * Check free space in buffer
  68. * @param s Tiff context
  69. * @param need Needed bytes
  70. * @return 0 - ok, 1 - no free space
  71. */
  72. static inline int check_size(TiffEncoderContext * s, uint64_t need)
  73. {
  74. if (s->buf_size < *s->buf - s->buf_start + need) {
  75. *s->buf = s->buf_start + s->buf_size + 1;
  76. av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
  77. return 1;
  78. }
  79. return 0;
  80. }
  81. /**
  82. * Put n values to buffer
  83. *
  84. * @param p Pointer to pointer to output buffer
  85. * @param n Number of values
  86. * @param val Pointer to values
  87. * @param type Type of values
  88. * @param flip =0 - normal copy, >0 - flip
  89. */
  90. static void tnput(uint8_t ** p, int n, const uint8_t * val, enum TiffTypes type,
  91. int flip)
  92. {
  93. int i;
  94. #if HAVE_BIGENDIAN
  95. flip ^= ((int[]) {0, 0, 0, 1, 3, 3})[type];
  96. #endif
  97. for (i = 0; i < n * type_sizes2[type]; i++)
  98. *(*p)++ = val[i ^ flip];
  99. }
  100. /**
  101. * Add entry to directory in tiff header.
  102. * @param s Tiff context
  103. * @param tag Tag that identifies the entry
  104. * @param type Entry type
  105. * @param count The number of values
  106. * @param ptr_val Pointer to values
  107. */
  108. static void add_entry(TiffEncoderContext * s,
  109. enum TiffTags tag, enum TiffTypes type, int count,
  110. const void *ptr_val)
  111. {
  112. uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
  113. av_assert0(s->num_entries < TIFF_MAX_ENTRY);
  114. bytestream_put_le16(&entries_ptr, tag);
  115. bytestream_put_le16(&entries_ptr, type);
  116. bytestream_put_le32(&entries_ptr, count);
  117. if (type_sizes[type] * count <= 4) {
  118. tnput(&entries_ptr, count, ptr_val, type, 0);
  119. } else {
  120. bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
  121. check_size(s, count * type_sizes2[type]);
  122. tnput(s->buf, count, ptr_val, type, 0);
  123. }
  124. s->num_entries++;
  125. }
  126. static void add_entry1(TiffEncoderContext * s,
  127. enum TiffTags tag, enum TiffTypes type, int val){
  128. uint16_t w = val;
  129. uint32_t dw= val;
  130. add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
  131. }
  132. /**
  133. * Encode one strip in tiff file
  134. *
  135. * @param s Tiff context
  136. * @param src Input buffer
  137. * @param dst Output buffer
  138. * @param n Size of input buffer
  139. * @param compr Compression method
  140. * @return Number of output bytes. If an output error is encountered, -1 returned
  141. */
  142. static int encode_strip(TiffEncoderContext * s, const int8_t * src,
  143. uint8_t * dst, int n, int compr)
  144. {
  145. switch (compr) {
  146. #if CONFIG_ZLIB
  147. case TIFF_DEFLATE:
  148. case TIFF_ADOBE_DEFLATE:
  149. {
  150. unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
  151. if (compress(dst, &zlen, src, n) != Z_OK) {
  152. av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
  153. return -1;
  154. }
  155. return zlen;
  156. }
  157. #endif
  158. case TIFF_RAW:
  159. if (check_size(s, n))
  160. return -1;
  161. memcpy(dst, src, n);
  162. return n;
  163. case TIFF_PACKBITS:
  164. return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start), src, 1, n, 2, 0xff, -1, 0);
  165. case TIFF_LZW:
  166. return ff_lzw_encode(s->lzws, src, n);
  167. default:
  168. return -1;
  169. }
  170. }
  171. static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum)
  172. {
  173. AVFrame *p = &s->picture;
  174. int i, j, k;
  175. int w = (s->width - 1) / s->subsampling[0] + 1;
  176. uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
  177. uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
  178. if(s->width % s->subsampling[0] || s->height % s->subsampling[1]){
  179. for (i = 0; i < w; i++){
  180. for (j = 0; j < s->subsampling[1]; j++)
  181. for (k = 0; k < s->subsampling[0]; k++)
  182. *dst++ = p->data[0][FFMIN(lnum + j, s->height-1) * p->linesize[0] +
  183. FFMIN(i * s->subsampling[0] + k, s->width-1)];
  184. *dst++ = *pu++;
  185. *dst++ = *pv++;
  186. }
  187. }else{
  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][(lnum + j) * p->linesize[0] +
  192. i * s->subsampling[0] + k];
  193. *dst++ = *pu++;
  194. *dst++ = *pv++;
  195. }
  196. }
  197. }
  198. static int encode_frame(AVCodecContext * avctx, AVPacket *pkt,
  199. const AVFrame *pict, int *got_packet)
  200. {
  201. TiffEncoderContext *s = avctx->priv_data;
  202. AVFrame *const p = &s->picture;
  203. int i;
  204. uint8_t *ptr;
  205. uint8_t *offset;
  206. uint32_t strips;
  207. uint32_t *strip_sizes = NULL;
  208. uint32_t *strip_offsets = NULL;
  209. int bytes_per_row;
  210. uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1)
  211. uint16_t bpp_tab[4];
  212. int ret = -1;
  213. int is_yuv = 0;
  214. uint8_t *yuv_line = NULL;
  215. int shift_h, shift_v;
  216. s->avctx = avctx;
  217. *p = *pict;
  218. p->pict_type = AV_PICTURE_TYPE_I;
  219. p->key_frame = 1;
  220. avctx->coded_frame= &s->picture;
  221. s->width = avctx->width;
  222. s->height = avctx->height;
  223. s->subsampling[0] = 1;
  224. s->subsampling[1] = 1;
  225. avctx->bits_per_coded_sample =
  226. s->bpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[avctx->pix_fmt]);
  227. switch (avctx->pix_fmt) {
  228. case PIX_FMT_RGBA64LE:
  229. case PIX_FMT_RGB48LE:
  230. case PIX_FMT_RGBA:
  231. case PIX_FMT_RGB24:
  232. s->photometric_interpretation = 2;
  233. break;
  234. case PIX_FMT_GRAY8:
  235. avctx->bits_per_coded_sample = 0x28;
  236. case PIX_FMT_GRAY8A:
  237. case PIX_FMT_GRAY16LE:
  238. s->photometric_interpretation = 1;
  239. break;
  240. case PIX_FMT_PAL8:
  241. s->photometric_interpretation = 3;
  242. break;
  243. case PIX_FMT_MONOBLACK:
  244. case PIX_FMT_MONOWHITE:
  245. s->photometric_interpretation = avctx->pix_fmt == PIX_FMT_MONOBLACK;
  246. break;
  247. case PIX_FMT_YUV420P:
  248. case PIX_FMT_YUV422P:
  249. case PIX_FMT_YUV444P:
  250. case PIX_FMT_YUV410P:
  251. case PIX_FMT_YUV411P:
  252. s->photometric_interpretation = 6;
  253. avcodec_get_chroma_sub_sample(avctx->pix_fmt,
  254. &shift_h, &shift_v);
  255. s->subsampling[0] = 1 << shift_h;
  256. s->subsampling[1] = 1 << shift_v;
  257. is_yuv = 1;
  258. break;
  259. default:
  260. av_log(s->avctx, AV_LOG_ERROR,
  261. "This colors format is not supported\n");
  262. return -1;
  263. }
  264. s->bpp_tab_size = av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
  265. for (i = 0; i < s->bpp_tab_size; i++)
  266. bpp_tab[i] = av_pix_fmt_descriptors[avctx->pix_fmt].comp[i].depth_minus1 + 1;
  267. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
  268. //best choose for DEFLATE
  269. s->rps = s->height;
  270. else
  271. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip
  272. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
  273. strips = (s->height - 1) / s->rps + 1;
  274. if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width * avctx->height * s->bpp * 2 +
  275. avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0)
  276. return ret;
  277. ptr = pkt->data;
  278. s->buf_start = pkt->data;
  279. s->buf = &ptr;
  280. s->buf_size = pkt->size;
  281. if (check_size(s, 8))
  282. goto fail;
  283. // write header
  284. bytestream_put_le16(&ptr, 0x4949);
  285. bytestream_put_le16(&ptr, 42);
  286. offset = ptr;
  287. bytestream_put_le32(&ptr, 0);
  288. strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
  289. strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
  290. bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
  291. * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  292. if (is_yuv){
  293. yuv_line = av_malloc(bytes_per_row);
  294. if (yuv_line == NULL){
  295. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  296. goto fail;
  297. }
  298. }
  299. #if CONFIG_ZLIB
  300. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
  301. uint8_t *zbuf;
  302. int zlen, zn;
  303. int j;
  304. zlen = bytes_per_row * s->rps;
  305. zbuf = av_malloc(zlen);
  306. strip_offsets[0] = ptr - pkt->data;
  307. zn = 0;
  308. for (j = 0; j < s->rps; j++) {
  309. if (is_yuv){
  310. pack_yuv(s, yuv_line, j);
  311. memcpy(zbuf + zn, yuv_line, bytes_per_row);
  312. j += s->subsampling[1] - 1;
  313. }
  314. else
  315. memcpy(zbuf + j * bytes_per_row,
  316. p->data[0] + j * p->linesize[0], bytes_per_row);
  317. zn += bytes_per_row;
  318. }
  319. ret = encode_strip(s, zbuf, ptr, zn, s->compr);
  320. av_free(zbuf);
  321. if (ret < 0) {
  322. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  323. goto fail;
  324. }
  325. ptr += ret;
  326. strip_sizes[0] = ptr - pkt->data - strip_offsets[0];
  327. } else
  328. #endif
  329. {
  330. if(s->compr == TIFF_LZW)
  331. s->lzws = av_malloc(ff_lzw_encode_state_size);
  332. for (i = 0; i < s->height; i++) {
  333. if (strip_sizes[i / s->rps] == 0) {
  334. if(s->compr == TIFF_LZW){
  335. ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
  336. 12, FF_LZW_TIFF, put_bits);
  337. }
  338. strip_offsets[i / s->rps] = ptr - pkt->data;
  339. }
  340. if (is_yuv){
  341. pack_yuv(s, yuv_line, i);
  342. ret = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
  343. i += s->subsampling[1] - 1;
  344. }
  345. else
  346. ret = encode_strip(s, p->data[0] + i * p->linesize[0],
  347. ptr, bytes_per_row, s->compr);
  348. if (ret < 0) {
  349. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  350. goto fail;
  351. }
  352. strip_sizes[i / s->rps] += ret;
  353. ptr += ret;
  354. if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
  355. ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
  356. strip_sizes[(i / s->rps )] += ret ;
  357. ptr += ret;
  358. }
  359. }
  360. if(s->compr == TIFF_LZW)
  361. av_free(s->lzws);
  362. }
  363. s->num_entries = 0;
  364. add_entry1(s,TIFF_SUBFILE, TIFF_LONG, 0);
  365. add_entry1(s,TIFF_WIDTH, TIFF_LONG, s->width);
  366. add_entry1(s,TIFF_HEIGHT, TIFF_LONG, s->height);
  367. if (s->bpp_tab_size)
  368. add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
  369. add_entry1(s,TIFF_COMPR, TIFF_SHORT, s->compr);
  370. add_entry1(s,TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation);
  371. add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, strip_offsets);
  372. if (s->bpp_tab_size)
  373. add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
  374. add_entry1(s,TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
  375. add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, strip_sizes);
  376. add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
  377. add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
  378. add_entry1(s,TIFF_RES_UNIT, TIFF_SHORT, 2);
  379. if(!(avctx->flags & CODEC_FLAG_BITEXACT))
  380. add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
  381. strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
  382. if (avctx->pix_fmt == PIX_FMT_PAL8) {
  383. uint16_t pal[256 * 3];
  384. for (i = 0; i < 256; i++) {
  385. uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
  386. pal[i] = ((rgb >> 16) & 0xff) * 257;
  387. pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
  388. pal[i + 512] = ( rgb & 0xff) * 257;
  389. }
  390. add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
  391. }
  392. if (is_yuv){
  393. /** according to CCIR Recommendation 601.1 */
  394. uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
  395. add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
  396. add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
  397. }
  398. bytestream_put_le32(&offset, ptr - pkt->data); // write offset to dir
  399. if (check_size(s, 6 + s->num_entries * 12)) {
  400. ret = AVERROR(EINVAL);
  401. goto fail;
  402. }
  403. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  404. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  405. bytestream_put_le32(&ptr, 0);
  406. pkt->size = ptr - pkt->data;
  407. pkt->flags |= AV_PKT_FLAG_KEY;
  408. *got_packet = 1;
  409. fail:
  410. av_free(strip_sizes);
  411. av_free(strip_offsets);
  412. av_free(yuv_line);
  413. return ret < 0 ? ret : 0;
  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. .encode2 = encode_frame,
  440. .pix_fmts = (const enum PixelFormat[]) {
  441. PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8, PIX_FMT_GRAY8A, PIX_FMT_GRAY16LE,
  442. PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
  443. PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P,
  444. PIX_FMT_YUV410P, PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
  445. PIX_FMT_RGBA, PIX_FMT_RGBA64LE,
  446. PIX_FMT_NONE
  447. },
  448. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  449. .priv_class = &tiffenc_class,
  450. };