tiffenc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 "avcodec.h"
  27. #if CONFIG_ZLIB
  28. #include <zlib.h>
  29. #endif
  30. #include "libavutil/opt.h"
  31. #include "bytestream.h"
  32. #include "tiff.h"
  33. #include "rle.h"
  34. #include "lzw.h"
  35. #include "put_bits.h"
  36. #define TIFF_MAX_ENTRY 32
  37. /** sizes of various TIFF field types (string size = 1)*/
  38. static const uint8_t type_sizes2[6] = {
  39. 0, 1, 1, 2, 4, 8
  40. };
  41. typedef struct TiffEncoderContext {
  42. AVClass *avclass;
  43. AVCodecContext *avctx;
  44. AVFrame picture;
  45. int width; ///< picture width
  46. int height; ///< picture height
  47. unsigned int bpp; ///< bits per pixel
  48. int compr; ///< compression level
  49. int bpp_tab_size; ///< bpp_tab size
  50. int photometric_interpretation; ///< photometric interpretation
  51. int strips; ///< number of strips
  52. int rps; ///< row per strip
  53. uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
  54. int num_entries; ///< number of entires
  55. uint8_t **buf; ///< actual position in buffer
  56. uint8_t *buf_start; ///< pointer to first byte in buffer
  57. int buf_size; ///< buffer size
  58. uint16_t subsampling[2]; ///< YUV subsampling factors
  59. struct LZWEncodeState *lzws; ///< LZW Encode state
  60. uint32_t dpi; ///< image resolution in DPI
  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. inline static 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, unsigned char *buf,
  184. int buf_size, void *data)
  185. {
  186. TiffEncoderContext *s = avctx->priv_data;
  187. AVFrame *pict = data;
  188. AVFrame *const p = (AVFrame *) & s->picture;
  189. int i;
  190. int n;
  191. uint8_t *ptr = buf;
  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] = { s->dpi, 1 }; // image resolution (72/1)
  198. uint16_t bpp_tab[] = { 8, 8, 8, 8 };
  199. int ret = -1;
  200. int is_yuv = 0;
  201. uint8_t *yuv_line = NULL;
  202. int shift_h, shift_v;
  203. s->avctx = avctx;
  204. s->buf_start = buf;
  205. s->buf = &ptr;
  206. s->buf_size = buf_size;
  207. *p = *pict;
  208. p->pict_type = AV_PICTURE_TYPE_I;
  209. p->key_frame = 1;
  210. avctx->coded_frame= &s->picture;
  211. s->compr = TIFF_PACKBITS;
  212. if (avctx->compression_level == 0) {
  213. s->compr = TIFF_RAW;
  214. } else if(avctx->compression_level == 2) {
  215. s->compr = TIFF_LZW;
  216. #if CONFIG_ZLIB
  217. } else if ((avctx->compression_level >= 3)) {
  218. s->compr = TIFF_DEFLATE;
  219. #endif
  220. }
  221. s->width = avctx->width;
  222. s->height = avctx->height;
  223. s->subsampling[0] = 1;
  224. s->subsampling[1] = 1;
  225. switch (avctx->pix_fmt) {
  226. case PIX_FMT_RGB48LE:
  227. s->bpp = 48;
  228. s->photometric_interpretation = 2;
  229. bpp_tab[0] = 16;
  230. bpp_tab[1] = 16;
  231. bpp_tab[2] = 16;
  232. bpp_tab[3] = 16;
  233. break;
  234. case PIX_FMT_RGB24:
  235. s->bpp = 24;
  236. s->photometric_interpretation = 2;
  237. break;
  238. case PIX_FMT_GRAY8:
  239. s->bpp = 8;
  240. s->photometric_interpretation = 1;
  241. break;
  242. case PIX_FMT_PAL8:
  243. s->bpp = 8;
  244. s->photometric_interpretation = 3;
  245. break;
  246. case PIX_FMT_MONOBLACK:
  247. case PIX_FMT_MONOWHITE:
  248. s->bpp = 1;
  249. s->photometric_interpretation = avctx->pix_fmt == PIX_FMT_MONOBLACK;
  250. bpp_tab[0] = 1;
  251. break;
  252. case PIX_FMT_YUV420P:
  253. case PIX_FMT_YUV422P:
  254. case PIX_FMT_YUV444P:
  255. case PIX_FMT_YUV410P:
  256. case PIX_FMT_YUV411P:
  257. s->photometric_interpretation = 6;
  258. avcodec_get_chroma_sub_sample(avctx->pix_fmt,
  259. &shift_h, &shift_v);
  260. s->bpp = 8 + (16 >> (shift_h + shift_v));
  261. s->subsampling[0] = 1 << shift_h;
  262. s->subsampling[1] = 1 << shift_v;
  263. s->bpp_tab_size = 3;
  264. is_yuv = 1;
  265. break;
  266. default:
  267. av_log(s->avctx, AV_LOG_ERROR,
  268. "This colors format is not supported\n");
  269. return -1;
  270. }
  271. if (!is_yuv)
  272. s->bpp_tab_size = (s->bpp >= 48) ? ((s->bpp + 7) >> 4):((s->bpp + 7) >> 3);
  273. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
  274. //best choose for DEFLATE
  275. s->rps = s->height;
  276. else
  277. s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip
  278. s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
  279. strips = (s->height - 1) / s->rps + 1;
  280. if (check_size(s, 8))
  281. goto fail;
  282. // write header
  283. bytestream_put_le16(&ptr, 0x4949);
  284. bytestream_put_le16(&ptr, 42);
  285. offset = ptr;
  286. bytestream_put_le32(&ptr, 0);
  287. strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
  288. strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
  289. bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
  290. * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
  291. if (is_yuv){
  292. yuv_line = av_malloc(bytes_per_row);
  293. if (yuv_line == NULL){
  294. av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
  295. goto fail;
  296. }
  297. }
  298. #if CONFIG_ZLIB
  299. if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
  300. uint8_t *zbuf;
  301. int zlen, zn;
  302. int j;
  303. zlen = bytes_per_row * s->rps;
  304. zbuf = av_malloc(zlen);
  305. strip_offsets[0] = ptr - buf;
  306. zn = 0;
  307. for (j = 0; j < s->rps; j++) {
  308. if (is_yuv){
  309. pack_yuv(s, yuv_line, j);
  310. memcpy(zbuf + zn, yuv_line, bytes_per_row);
  311. j += s->subsampling[1] - 1;
  312. }
  313. else
  314. memcpy(zbuf + j * bytes_per_row,
  315. p->data[0] + j * p->linesize[0], bytes_per_row);
  316. zn += bytes_per_row;
  317. }
  318. n = encode_strip(s, zbuf, ptr, zn, s->compr);
  319. av_free(zbuf);
  320. if (n<0) {
  321. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  322. goto fail;
  323. }
  324. ptr += n;
  325. strip_sizes[0] = ptr - buf - strip_offsets[0];
  326. } else
  327. #endif
  328. {
  329. if(s->compr == TIFF_LZW)
  330. s->lzws = av_malloc(ff_lzw_encode_state_size);
  331. for (i = 0; i < s->height; i++) {
  332. if (strip_sizes[i / s->rps] == 0) {
  333. if(s->compr == TIFF_LZW){
  334. ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
  335. 12, FF_LZW_TIFF, put_bits);
  336. }
  337. strip_offsets[i / s->rps] = ptr - buf;
  338. }
  339. if (is_yuv){
  340. pack_yuv(s, yuv_line, i);
  341. n = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
  342. i += s->subsampling[1] - 1;
  343. }
  344. else
  345. n = encode_strip(s, p->data[0] + i * p->linesize[0],
  346. ptr, bytes_per_row, s->compr);
  347. if (n < 0) {
  348. av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
  349. goto fail;
  350. }
  351. strip_sizes[i / s->rps] += n;
  352. ptr += n;
  353. if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
  354. int ret;
  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 - buf); // write offset to dir
  399. if (check_size(s, 6 + s->num_entries * 12))
  400. goto fail;
  401. bytestream_put_le16(&ptr, s->num_entries); // write tag count
  402. bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
  403. bytestream_put_le32(&ptr, 0);
  404. ret = ptr - buf;
  405. fail:
  406. av_free(strip_sizes);
  407. av_free(strip_offsets);
  408. av_free(yuv_line);
  409. return ret;
  410. }
  411. static const AVOption options[]={
  412. {"dpi", "set the image resolution (in dpi)", offsetof(TiffEncoderContext, dpi), AV_OPT_TYPE_INT, {.dbl = 72}, 1, 0x10000, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_ENCODING_PARAM},
  413. {NULL}
  414. };
  415. static const AVClass class = { "tiff", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
  416. AVCodec ff_tiff_encoder = {
  417. .name = "tiff",
  418. .type = AVMEDIA_TYPE_VIDEO,
  419. .id = CODEC_ID_TIFF,
  420. .priv_data_size = sizeof(TiffEncoderContext),
  421. .encode = encode_frame,
  422. .pix_fmts =
  423. (const enum PixelFormat[]) {PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8,
  424. PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
  425. PIX_FMT_YUV420P, PIX_FMT_YUV422P,
  426. PIX_FMT_YUV444P, PIX_FMT_YUV410P,
  427. PIX_FMT_YUV411P, PIX_FMT_RGB48LE,
  428. PIX_FMT_NONE},
  429. .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
  430. .priv_class= &class,
  431. };