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.

468 lines
15KB

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