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.

486 lines
16KB

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