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.

513 lines
16KB

  1. /*
  2. * PNG image format
  3. * Copyright (c) 2003 Fabrice Bellard
  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. #include "avcodec.h"
  22. #include "internal.h"
  23. #include "bytestream.h"
  24. #include "dsputil.h"
  25. #include "png.h"
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/opt.h"
  28. /* TODO:
  29. * - add 2, 4 and 16 bit depth support
  30. */
  31. #include <zlib.h>
  32. #define IOBUF_SIZE 4096
  33. typedef struct PNGEncContext {
  34. AVClass *class;
  35. DSPContext dsp;
  36. uint8_t *bytestream;
  37. uint8_t *bytestream_start;
  38. uint8_t *bytestream_end;
  39. AVFrame picture;
  40. int filter_type;
  41. z_stream zstream;
  42. uint8_t buf[IOBUF_SIZE];
  43. int dpi; ///< Physical pixel density, in dots per inch, if set
  44. int dpm; ///< Physical pixel density, in dots per meter, if set
  45. } PNGEncContext;
  46. static void png_get_interlaced_row(uint8_t *dst, int row_size,
  47. int bits_per_pixel, int pass,
  48. const uint8_t *src, int width)
  49. {
  50. int x, mask, dst_x, j, b, bpp;
  51. uint8_t *d;
  52. const uint8_t *s;
  53. static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  54. mask = masks[pass];
  55. switch(bits_per_pixel) {
  56. case 1:
  57. memset(dst, 0, row_size);
  58. dst_x = 0;
  59. for(x = 0; x < width; x++) {
  60. j = (x & 7);
  61. if ((mask << j) & 0x80) {
  62. b = (src[x >> 3] >> (7 - j)) & 1;
  63. dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
  64. dst_x++;
  65. }
  66. }
  67. break;
  68. default:
  69. bpp = bits_per_pixel >> 3;
  70. d = dst;
  71. s = src;
  72. for(x = 0; x < width; x++) {
  73. j = x & 7;
  74. if ((mask << j) & 0x80) {
  75. memcpy(d, s, bpp);
  76. d += bpp;
  77. }
  78. s += bpp;
  79. }
  80. break;
  81. }
  82. }
  83. static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
  84. {
  85. int i;
  86. for(i = 0; i < w; i++) {
  87. int a, b, c, p, pa, pb, pc;
  88. a = src[i - bpp];
  89. b = top[i];
  90. c = top[i - bpp];
  91. p = b - c;
  92. pc = a - c;
  93. pa = abs(p);
  94. pb = abs(pc);
  95. pc = abs(p + pc);
  96. if (pa <= pb && pa <= pc)
  97. p = a;
  98. else if (pb <= pc)
  99. p = b;
  100. else
  101. p = c;
  102. dst[i] = src[i] - p;
  103. }
  104. }
  105. static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
  106. uint8_t *src, uint8_t *top, int size, int bpp)
  107. {
  108. int i;
  109. switch(filter_type) {
  110. case PNG_FILTER_VALUE_NONE:
  111. memcpy(dst, src, size);
  112. break;
  113. case PNG_FILTER_VALUE_SUB:
  114. dsp->diff_bytes(dst, src, src-bpp, size);
  115. memcpy(dst, src, bpp);
  116. break;
  117. case PNG_FILTER_VALUE_UP:
  118. dsp->diff_bytes(dst, src, top, size);
  119. break;
  120. case PNG_FILTER_VALUE_AVG:
  121. for(i = 0; i < bpp; i++)
  122. dst[i] = src[i] - (top[i] >> 1);
  123. for(; i < size; i++)
  124. dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
  125. break;
  126. case PNG_FILTER_VALUE_PAETH:
  127. for(i = 0; i < bpp; i++)
  128. dst[i] = src[i] - top[i];
  129. sub_png_paeth_prediction(dst+i, src+i, top+i, size-i, bpp);
  130. break;
  131. }
  132. }
  133. static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
  134. uint8_t *src, uint8_t *top, int size, int bpp)
  135. {
  136. int pred = s->filter_type;
  137. av_assert0(bpp || !pred);
  138. if(!top && pred)
  139. pred = PNG_FILTER_VALUE_SUB;
  140. if(pred == PNG_FILTER_VALUE_MIXED) {
  141. int i;
  142. int cost, bcost = INT_MAX;
  143. uint8_t *buf1 = dst, *buf2 = dst + size + 16;
  144. for(pred=0; pred<5; pred++) {
  145. png_filter_row(&s->dsp, buf1+1, pred, src, top, size, bpp);
  146. buf1[0] = pred;
  147. cost = 0;
  148. for(i=0; i<=size; i++)
  149. cost += abs((int8_t)buf1[i]);
  150. if(cost < bcost) {
  151. bcost = cost;
  152. FFSWAP(uint8_t*, buf1, buf2);
  153. }
  154. }
  155. return buf2;
  156. } else {
  157. png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
  158. dst[0] = pred;
  159. return dst;
  160. }
  161. }
  162. static void png_write_chunk(uint8_t **f, uint32_t tag,
  163. const uint8_t *buf, int length)
  164. {
  165. uint32_t crc;
  166. uint8_t tagbuf[4];
  167. bytestream_put_be32(f, length);
  168. crc = crc32(0, Z_NULL, 0);
  169. AV_WL32(tagbuf, tag);
  170. crc = crc32(crc, tagbuf, 4);
  171. bytestream_put_be32(f, av_bswap32(tag));
  172. if (length > 0) {
  173. crc = crc32(crc, buf, length);
  174. memcpy(*f, buf, length);
  175. *f += length;
  176. }
  177. bytestream_put_be32(f, crc);
  178. }
  179. /* XXX: do filtering */
  180. static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
  181. {
  182. int ret;
  183. s->zstream.avail_in = size;
  184. s->zstream.next_in = (uint8_t *)data;
  185. while (s->zstream.avail_in > 0) {
  186. ret = deflate(&s->zstream, Z_NO_FLUSH);
  187. if (ret != Z_OK)
  188. return -1;
  189. if (s->zstream.avail_out == 0) {
  190. if(s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
  191. png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
  192. s->zstream.avail_out = IOBUF_SIZE;
  193. s->zstream.next_out = s->buf;
  194. }
  195. }
  196. return 0;
  197. }
  198. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  199. const AVFrame *pict, int *got_packet)
  200. {
  201. PNGEncContext *s = avctx->priv_data;
  202. AVFrame * const p= &s->picture;
  203. int bit_depth, color_type, y, len, row_size, ret, is_progressive;
  204. int bits_per_pixel, pass_row_size, enc_row_size;
  205. int64_t max_packet_size;
  206. int compression_level;
  207. uint8_t *ptr, *top;
  208. uint8_t *crow_base = NULL, *crow_buf, *crow;
  209. uint8_t *progressive_buf = NULL;
  210. uint8_t *top_buf = NULL;
  211. *p = *pict;
  212. p->pict_type= AV_PICTURE_TYPE_I;
  213. p->key_frame= 1;
  214. is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
  215. switch(avctx->pix_fmt) {
  216. case AV_PIX_FMT_RGBA64BE:
  217. bit_depth = 16;
  218. color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  219. break;
  220. case AV_PIX_FMT_RGB48BE:
  221. bit_depth = 16;
  222. color_type = PNG_COLOR_TYPE_RGB;
  223. break;
  224. case AV_PIX_FMT_RGBA:
  225. bit_depth = 8;
  226. color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  227. break;
  228. case AV_PIX_FMT_RGB24:
  229. bit_depth = 8;
  230. color_type = PNG_COLOR_TYPE_RGB;
  231. break;
  232. case AV_PIX_FMT_GRAY16BE:
  233. bit_depth = 16;
  234. color_type = PNG_COLOR_TYPE_GRAY;
  235. break;
  236. case AV_PIX_FMT_GRAY8:
  237. bit_depth = 8;
  238. color_type = PNG_COLOR_TYPE_GRAY;
  239. break;
  240. case AV_PIX_FMT_GRAY8A:
  241. bit_depth = 8;
  242. color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  243. break;
  244. case AV_PIX_FMT_MONOBLACK:
  245. bit_depth = 1;
  246. color_type = PNG_COLOR_TYPE_GRAY;
  247. break;
  248. case AV_PIX_FMT_PAL8:
  249. bit_depth = 8;
  250. color_type = PNG_COLOR_TYPE_PALETTE;
  251. break;
  252. default:
  253. return -1;
  254. }
  255. bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
  256. row_size = (avctx->width * bits_per_pixel + 7) >> 3;
  257. s->zstream.zalloc = ff_png_zalloc;
  258. s->zstream.zfree = ff_png_zfree;
  259. s->zstream.opaque = NULL;
  260. compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT ?
  261. Z_DEFAULT_COMPRESSION :
  262. av_clip(avctx->compression_level, 0, 9);
  263. ret = deflateInit2(&s->zstream, compression_level,
  264. Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
  265. if (ret != Z_OK)
  266. return -1;
  267. enc_row_size = deflateBound(&s->zstream, row_size);
  268. max_packet_size = avctx->height * (int64_t)(enc_row_size +
  269. ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
  270. + FF_MIN_BUFFER_SIZE;
  271. if (max_packet_size > INT_MAX)
  272. return AVERROR(ENOMEM);
  273. if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
  274. return ret;
  275. s->bytestream_start =
  276. s->bytestream = pkt->data;
  277. s->bytestream_end = pkt->data + pkt->size;
  278. crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
  279. if (!crow_base)
  280. goto fail;
  281. crow_buf = crow_base + 15; // pixel data should be aligned, but there's a control byte before it
  282. if (is_progressive) {
  283. progressive_buf = av_malloc(row_size + 1);
  284. if (!progressive_buf)
  285. goto fail;
  286. }
  287. if (is_progressive) {
  288. top_buf = av_malloc(row_size + 1);
  289. if (!top_buf)
  290. goto fail;
  291. }
  292. /* write png header */
  293. AV_WB64(s->bytestream, PNGSIG);
  294. s->bytestream += 8;
  295. AV_WB32(s->buf, avctx->width);
  296. AV_WB32(s->buf + 4, avctx->height);
  297. s->buf[8] = bit_depth;
  298. s->buf[9] = color_type;
  299. s->buf[10] = 0; /* compression type */
  300. s->buf[11] = 0; /* filter type */
  301. s->buf[12] = is_progressive; /* interlace type */
  302. png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
  303. if (s->dpm) {
  304. AV_WB32(s->buf, s->dpm);
  305. AV_WB32(s->buf + 4, s->dpm);
  306. s->buf[8] = 1; /* unit specifier is meter */
  307. } else {
  308. AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
  309. AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
  310. s->buf[8] = 0; /* unit specifier is unknown */
  311. }
  312. png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
  313. /* put the palette if needed */
  314. if (color_type == PNG_COLOR_TYPE_PALETTE) {
  315. int has_alpha, alpha, i;
  316. unsigned int v;
  317. uint32_t *palette;
  318. uint8_t *alpha_ptr;
  319. palette = (uint32_t *)p->data[1];
  320. ptr = s->buf;
  321. alpha_ptr = s->buf + 256 * 3;
  322. has_alpha = 0;
  323. for(i = 0; i < 256; i++) {
  324. v = palette[i];
  325. alpha = v >> 24;
  326. if (alpha != 0xff)
  327. has_alpha = 1;
  328. *alpha_ptr++ = alpha;
  329. bytestream_put_be24(&ptr, v);
  330. }
  331. png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
  332. if (has_alpha) {
  333. png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
  334. }
  335. }
  336. /* now put each row */
  337. s->zstream.avail_out = IOBUF_SIZE;
  338. s->zstream.next_out = s->buf;
  339. if (is_progressive) {
  340. int pass;
  341. for(pass = 0; pass < NB_PASSES; pass++) {
  342. /* NOTE: a pass is completely omitted if no pixels would be
  343. output */
  344. pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
  345. if (pass_row_size > 0) {
  346. top = NULL;
  347. for(y = 0; y < avctx->height; y++) {
  348. if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
  349. ptr = p->data[0] + y * p->linesize[0];
  350. FFSWAP(uint8_t*, progressive_buf, top_buf);
  351. png_get_interlaced_row(progressive_buf, pass_row_size,
  352. bits_per_pixel, pass,
  353. ptr, avctx->width);
  354. crow = png_choose_filter(s, crow_buf, progressive_buf, top, pass_row_size, bits_per_pixel>>3);
  355. png_write_row(s, crow, pass_row_size + 1);
  356. top = progressive_buf;
  357. }
  358. }
  359. }
  360. }
  361. } else {
  362. top = NULL;
  363. for(y = 0; y < avctx->height; y++) {
  364. ptr = p->data[0] + y * p->linesize[0];
  365. crow = png_choose_filter(s, crow_buf, ptr, top, row_size, bits_per_pixel>>3);
  366. png_write_row(s, crow, row_size + 1);
  367. top = ptr;
  368. }
  369. }
  370. /* compress last bytes */
  371. for(;;) {
  372. ret = deflate(&s->zstream, Z_FINISH);
  373. if (ret == Z_OK || ret == Z_STREAM_END) {
  374. len = IOBUF_SIZE - s->zstream.avail_out;
  375. if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
  376. png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
  377. }
  378. s->zstream.avail_out = IOBUF_SIZE;
  379. s->zstream.next_out = s->buf;
  380. if (ret == Z_STREAM_END)
  381. break;
  382. } else {
  383. goto fail;
  384. }
  385. }
  386. png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
  387. pkt->size = s->bytestream - s->bytestream_start;
  388. pkt->flags |= AV_PKT_FLAG_KEY;
  389. *got_packet = 1;
  390. ret = 0;
  391. the_end:
  392. av_free(crow_base);
  393. av_free(progressive_buf);
  394. av_free(top_buf);
  395. deflateEnd(&s->zstream);
  396. return ret;
  397. fail:
  398. ret = -1;
  399. goto the_end;
  400. }
  401. static av_cold int png_enc_init(AVCodecContext *avctx){
  402. PNGEncContext *s = avctx->priv_data;
  403. switch(avctx->pix_fmt) {
  404. case AV_PIX_FMT_RGBA:
  405. avctx->bits_per_coded_sample = 32;
  406. break;
  407. case AV_PIX_FMT_RGB24:
  408. avctx->bits_per_coded_sample = 24;
  409. break;
  410. case AV_PIX_FMT_GRAY8:
  411. avctx->bits_per_coded_sample = 0x28;
  412. break;
  413. case AV_PIX_FMT_MONOBLACK:
  414. avctx->bits_per_coded_sample = 1;
  415. break;
  416. case AV_PIX_FMT_PAL8:
  417. avctx->bits_per_coded_sample = 8;
  418. }
  419. avcodec_get_frame_defaults(&s->picture);
  420. avctx->coded_frame= &s->picture;
  421. ff_dsputil_init(&s->dsp, avctx);
  422. s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
  423. if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
  424. s->filter_type = PNG_FILTER_VALUE_NONE;
  425. if (s->dpi && s->dpm) {
  426. av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
  427. return AVERROR(EINVAL);
  428. } else if (s->dpi) {
  429. s->dpm = s->dpi * 10000 / 254;
  430. }
  431. return 0;
  432. }
  433. #define OFFSET(x) offsetof(PNGEncContext, x)
  434. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  435. static const AVOption options[] = {
  436. {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
  437. {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
  438. { NULL }
  439. };
  440. static const AVClass pngenc_class = {
  441. .class_name = "PNG encoder",
  442. .item_name = av_default_item_name,
  443. .option = options,
  444. .version = LIBAVUTIL_VERSION_INT,
  445. };
  446. AVCodec ff_png_encoder = {
  447. .name = "png",
  448. .type = AVMEDIA_TYPE_VIDEO,
  449. .id = AV_CODEC_ID_PNG,
  450. .priv_data_size = sizeof(PNGEncContext),
  451. .init = png_enc_init,
  452. .encode2 = encode_frame,
  453. .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
  454. .pix_fmts = (const enum AVPixelFormat[]){
  455. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
  456. AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
  457. AV_PIX_FMT_PAL8,
  458. AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
  459. AV_PIX_FMT_GRAY16BE,
  460. AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
  461. },
  462. .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
  463. .priv_class = &pngenc_class,
  464. };