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.

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