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.

510 lines
17KB

  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 "libavutil/pixdesc.h"
  29. #include "avcodec.h"
  30. #include "config.h"
  31. #if CONFIG_ZLIB
  32. #include <zlib.h>
  33. #endif
  34. #include "bytestream.h"
  35. #include "tiff.h"
  36. #include "rle.h"
  37. #include "lzw.h"
  38. #include "put_bits.h"
  39. #define TIFF_MAX_ENTRY 32
  40. /** sizes of various TIFF field types (string size = 1)*/
  41. static const uint8_t type_sizes2[6] = {
  42. 0, 1, 1, 2, 4, 8
  43. };
  44. typedef struct TiffEncoderContext {
  45. AVClass *class; ///< for private options
  46. AVCodecContext *avctx;
  47. AVFrame picture;
  48. int width; ///< picture width
  49. int height; ///< picture height
  50. unsigned int bpp; ///< bits per pixel
  51. int compr; ///< compression level
  52. int bpp_tab_size; ///< bpp_tab size
  53. int photometric_interpretation; ///< photometric interpretation
  54. int strips; ///< number of strips
  55. int rps; ///< row per strip
  56. uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
  57. int num_entries; ///< number of entires
  58. uint8_t **buf; ///< actual position in buffer
  59. uint8_t *buf_start; ///< pointer to first byte in buffer
  60. int buf_size; ///< buffer size
  61. uint16_t subsampling[2]; ///< YUV subsampling factors
  62. struct LZWEncodeState *lzws; ///< LZW Encode state
  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. static inline 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, AVPacket *pkt,
  186. const AVFrame *pict, int *got_packet)
  187. {
  188. TiffEncoderContext *s = avctx->priv_data;
  189. AVFrame *const p = &s->picture;
  190. int i;
  191. uint8_t *ptr;
  192. uint8_t *offset;
  193. uint32_t strips;
  194. uint32_t *strip_sizes = NULL;
  195. uint32_t *strip_offsets = NULL;
  196. int bytes_per_row;
  197. uint32_t res[2] = { 72, 1 }; // image resolution (72/1)
  198. uint16_t bpp_tab[] = { 8, 8, 8, 8 };
  199. int ret;
  200. int is_yuv = 0;
  201. uint8_t *yuv_line = NULL;
  202. int shift_h, shift_v;
  203. const AVPixFmtDescriptor* pfd;
  204. s->avctx = avctx;
  205. *p = *pict;
  206. p->pict_type = AV_PICTURE_TYPE_I;
  207. p->key_frame = 1;
  208. avctx->coded_frame= &s->picture;
  209. s->width = avctx->width;
  210. s->height = avctx->height;
  211. s->subsampling[0] = 1;
  212. s->subsampling[1] = 1;
  213. switch (avctx->pix_fmt) {
  214. case AV_PIX_FMT_RGB48LE:
  215. case AV_PIX_FMT_GRAY16LE:
  216. case AV_PIX_FMT_RGB24:
  217. case AV_PIX_FMT_GRAY8:
  218. case AV_PIX_FMT_PAL8:
  219. pfd = av_pix_fmt_desc_get(avctx->pix_fmt);
  220. s->bpp = av_get_bits_per_pixel(pfd);
  221. if (pfd->flags & PIX_FMT_PAL) {
  222. s->photometric_interpretation = 3;
  223. } else if (pfd->flags & PIX_FMT_RGB) {
  224. s->photometric_interpretation = 2;
  225. } else {
  226. s->photometric_interpretation = 1;
  227. }
  228. s->bpp_tab_size = pfd->nb_components;
  229. for (i = 0; i < s->bpp_tab_size; i++) {
  230. bpp_tab[i] = s->bpp / s->bpp_tab_size;
  231. }
  232. break;
  233. case AV_PIX_FMT_MONOBLACK:
  234. s->bpp = 1;
  235. s->photometric_interpretation = 1;
  236. s->bpp_tab_size = 0;
  237. break;
  238. case AV_PIX_FMT_MONOWHITE:
  239. s->bpp = 1;
  240. s->photometric_interpretation = 0;
  241. s->bpp_tab_size = 0;
  242. break;
  243. case AV_PIX_FMT_YUV420P:
  244. case AV_PIX_FMT_YUV422P:
  245. case AV_PIX_FMT_YUV444P:
  246. case AV_PIX_FMT_YUV410P:
  247. case AV_PIX_FMT_YUV411P:
  248. s->photometric_interpretation = 6;
  249. avcodec_get_chroma_sub_sample(avctx->pix_fmt,
  250. &shift_h, &shift_v);
  251. s->bpp = 8 + (16 >> (shift_h + shift_v));
  252. s->subsampling[0] = 1 << shift_h;
  253. s->subsampling[1] = 1 << shift_v;
  254. s->bpp_tab_size = 3;
  255. is_yuv = 1;
  256. break;
  257. default:
  258. av_log(s->avctx, AV_LOG_ERROR,
  259. "This colors format is not supported\n");
  260. return -1;
  261. }
  262. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
  263. //best choose for DEFLATE
  264. s->rps = s->height;
  265. else
  266. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip
  267. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
  268. strips = (s->height - 1) / s->rps + 1;
  269. if (!pkt->data &&
  270. (ret = av_new_packet(pkt, avctx->width * avctx->height * s->bpp * 2 +
  271. avctx->height * 4 + FF_MIN_BUFFER_SIZE)) < 0) {
  272. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  273. return ret;
  274. }
  275. ptr = pkt->data;
  276. s->buf_start = pkt->data;
  277. s->buf = &ptr;
  278. s->buf_size = pkt->size;
  279. if (check_size(s, 8))
  280. goto fail;
  281. // write header
  282. bytestream_put_le16(&ptr, 0x4949);
  283. bytestream_put_le16(&ptr, 42);
  284. offset = ptr;
  285. bytestream_put_le32(&ptr, 0);
  286. strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
  287. strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
  288. if (!strip_sizes || !strip_offsets) {
  289. ret = AVERROR(ENOMEM);
  290. goto fail;
  291. }
  292. bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
  293. * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  294. if (is_yuv){
  295. yuv_line = av_malloc(bytes_per_row);
  296. if (yuv_line == NULL){
  297. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  298. ret = AVERROR(ENOMEM);
  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. if (!zbuf) {
  310. ret = AVERROR(ENOMEM);
  311. goto fail;
  312. }
  313. strip_offsets[0] = ptr - pkt->data;
  314. zn = 0;
  315. for (j = 0; j < s->rps; j++) {
  316. if (is_yuv){
  317. pack_yuv(s, yuv_line, j);
  318. memcpy(zbuf + zn, yuv_line, bytes_per_row);
  319. j += s->subsampling[1] - 1;
  320. }
  321. else
  322. memcpy(zbuf + j * bytes_per_row,
  323. p->data[0] + j * p->linesize[0], bytes_per_row);
  324. zn += bytes_per_row;
  325. }
  326. ret = encode_strip(s, zbuf, ptr, zn, s->compr);
  327. av_free(zbuf);
  328. if (ret < 0) {
  329. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  330. goto fail;
  331. }
  332. ptr += ret;
  333. strip_sizes[0] = ptr - pkt->data - strip_offsets[0];
  334. } else
  335. #endif
  336. {
  337. if (s->compr == TIFF_LZW) {
  338. s->lzws = av_malloc(ff_lzw_encode_state_size);
  339. if (!s->lzws) {
  340. ret = AVERROR(ENOMEM);
  341. goto fail;
  342. }
  343. }
  344. for (i = 0; i < s->height; i++) {
  345. if (strip_sizes[i / s->rps] == 0) {
  346. if(s->compr == TIFF_LZW){
  347. ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
  348. 12, FF_LZW_TIFF, put_bits);
  349. }
  350. strip_offsets[i / s->rps] = ptr - pkt->data;
  351. }
  352. if (is_yuv){
  353. pack_yuv(s, yuv_line, i);
  354. ret = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
  355. i += s->subsampling[1] - 1;
  356. }
  357. else
  358. ret = encode_strip(s, p->data[0] + i * p->linesize[0],
  359. ptr, bytes_per_row, s->compr);
  360. if (ret < 0) {
  361. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  362. goto fail;
  363. }
  364. strip_sizes[i / s->rps] += ret;
  365. ptr += ret;
  366. if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
  367. ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
  368. strip_sizes[(i / s->rps )] += ret ;
  369. ptr += ret;
  370. }
  371. }
  372. if(s->compr == TIFF_LZW)
  373. av_free(s->lzws);
  374. }
  375. s->num_entries = 0;
  376. add_entry1(s,TIFF_SUBFILE, TIFF_LONG, 0);
  377. add_entry1(s,TIFF_WIDTH, TIFF_LONG, s->width);
  378. add_entry1(s,TIFF_HEIGHT, TIFF_LONG, s->height);
  379. if (s->bpp_tab_size)
  380. add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab);
  381. add_entry1(s,TIFF_COMPR, TIFF_SHORT, s->compr);
  382. add_entry1(s,TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation);
  383. add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, strip_offsets);
  384. if (s->bpp_tab_size)
  385. add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size);
  386. add_entry1(s,TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps);
  387. add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, strip_sizes);
  388. add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res);
  389. add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res);
  390. add_entry1(s,TIFF_RES_UNIT, TIFF_SHORT, 2);
  391. if(!(avctx->flags & CODEC_FLAG_BITEXACT))
  392. add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING,
  393. strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
  394. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  395. uint16_t pal[256 * 3];
  396. for (i = 0; i < 256; i++) {
  397. uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
  398. pal[i] = ((rgb >> 16) & 0xff) * 257;
  399. pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
  400. pal[i + 512] = ( rgb & 0xff) * 257;
  401. }
  402. add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
  403. }
  404. if (is_yuv){
  405. /** according to CCIR Recommendation 601.1 */
  406. uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
  407. add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling);
  408. add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw);
  409. }
  410. bytestream_put_le32(&offset, ptr - pkt->data); // write offset to dir
  411. if (check_size(s, 6 + s->num_entries * 12)) {
  412. ret = AVERROR(EINVAL);
  413. goto fail;
  414. }
  415. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  416. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  417. bytestream_put_le32(&ptr, 0);
  418. pkt->size = ptr - pkt->data;
  419. pkt->flags |= AV_PKT_FLAG_KEY;
  420. *got_packet = 1;
  421. fail:
  422. av_free(strip_sizes);
  423. av_free(strip_offsets);
  424. av_free(yuv_line);
  425. return ret;
  426. }
  427. #define OFFSET(x) offsetof(TiffEncoderContext, x)
  428. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  429. static const AVOption options[] = {
  430. { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, {.i64 = TIFF_PACKBITS}, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" },
  431. { "packbits", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_PACKBITS}, 0, 0, VE, "compression_algo" },
  432. { "raw", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_RAW}, 0, 0, VE, "compression_algo" },
  433. { "lzw", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_LZW}, 0, 0, VE, "compression_algo" },
  434. #if CONFIG_ZLIB
  435. { "deflate", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = TIFF_DEFLATE}, 0, 0, VE, "compression_algo" },
  436. #endif
  437. { NULL },
  438. };
  439. static const AVClass tiffenc_class = {
  440. .class_name = "TIFF encoder",
  441. .item_name = av_default_item_name,
  442. .option = options,
  443. .version = LIBAVUTIL_VERSION_INT,
  444. };
  445. AVCodec ff_tiff_encoder = {
  446. .name = "tiff",
  447. .type = AVMEDIA_TYPE_VIDEO,
  448. .id = AV_CODEC_ID_TIFF,
  449. .priv_data_size = sizeof(TiffEncoderContext),
  450. .encode2 = encode_frame,
  451. .pix_fmts = (const enum AVPixelFormat[]) {
  452. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB48LE, AV_PIX_FMT_PAL8,
  453. AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16LE,
  454. AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_MONOWHITE,
  455. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
  456. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
  457. AV_PIX_FMT_NONE
  458. },
  459. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  460. .priv_class = &tiffenc_class,
  461. };