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.

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