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.

509 lines
15KB

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