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.

1497 lines
51KB

  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. //#define DEBUG
  22. #include "libavutil/avassert.h"
  23. #include "libavutil/bprint.h"
  24. #include "libavutil/imgutils.h"
  25. #include "avcodec.h"
  26. #include "bytestream.h"
  27. #include "internal.h"
  28. #include "apng.h"
  29. #include "png.h"
  30. #include "pngdsp.h"
  31. #include "thread.h"
  32. #include <zlib.h>
  33. typedef struct PNGDecContext {
  34. PNGDSPContext dsp;
  35. AVCodecContext *avctx;
  36. GetByteContext gb;
  37. ThreadFrame previous_picture;
  38. ThreadFrame last_picture;
  39. ThreadFrame picture;
  40. int state;
  41. int width, height;
  42. int cur_w, cur_h;
  43. int last_w, last_h;
  44. int x_offset, y_offset;
  45. int last_x_offset, last_y_offset;
  46. uint8_t dispose_op, blend_op;
  47. uint8_t last_dispose_op;
  48. int bit_depth;
  49. int color_type;
  50. int compression_type;
  51. int interlace_type;
  52. int filter_type;
  53. int channels;
  54. int bits_per_pixel;
  55. int bpp;
  56. int has_trns;
  57. uint8_t transparent_color_be[6];
  58. uint8_t *image_buf;
  59. int image_linesize;
  60. uint32_t palette[256];
  61. uint8_t *crow_buf;
  62. uint8_t *last_row;
  63. unsigned int last_row_size;
  64. uint8_t *tmp_row;
  65. unsigned int tmp_row_size;
  66. uint8_t *buffer;
  67. int buffer_size;
  68. int pass;
  69. int crow_size; /* compressed row size (include filter type) */
  70. int row_size; /* decompressed row size */
  71. int pass_row_size; /* decompress row size of the current pass */
  72. int y;
  73. z_stream zstream;
  74. } PNGDecContext;
  75. /* Mask to determine which pixels are valid in a pass */
  76. static const uint8_t png_pass_mask[NB_PASSES] = {
  77. 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
  78. };
  79. /* Mask to determine which y pixels can be written in a pass */
  80. static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
  81. 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  82. };
  83. /* Mask to determine which pixels to overwrite while displaying */
  84. static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
  85. 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
  86. };
  87. /* NOTE: we try to construct a good looking image at each pass. width
  88. * is the original image width. We also do pixel format conversion at
  89. * this stage */
  90. static void png_put_interlaced_row(uint8_t *dst, int width,
  91. int bits_per_pixel, int pass,
  92. int color_type, const uint8_t *src)
  93. {
  94. int x, mask, dsp_mask, j, src_x, b, bpp;
  95. uint8_t *d;
  96. const uint8_t *s;
  97. mask = png_pass_mask[pass];
  98. dsp_mask = png_pass_dsp_mask[pass];
  99. switch (bits_per_pixel) {
  100. case 1:
  101. src_x = 0;
  102. for (x = 0; x < width; x++) {
  103. j = (x & 7);
  104. if ((dsp_mask << j) & 0x80) {
  105. b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
  106. dst[x >> 3] &= 0xFF7F>>j;
  107. dst[x >> 3] |= b << (7 - j);
  108. }
  109. if ((mask << j) & 0x80)
  110. src_x++;
  111. }
  112. break;
  113. case 2:
  114. src_x = 0;
  115. for (x = 0; x < width; x++) {
  116. int j2 = 2 * (x & 3);
  117. j = (x & 7);
  118. if ((dsp_mask << j) & 0x80) {
  119. b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
  120. dst[x >> 2] &= 0xFF3F>>j2;
  121. dst[x >> 2] |= b << (6 - j2);
  122. }
  123. if ((mask << j) & 0x80)
  124. src_x++;
  125. }
  126. break;
  127. case 4:
  128. src_x = 0;
  129. for (x = 0; x < width; x++) {
  130. int j2 = 4*(x&1);
  131. j = (x & 7);
  132. if ((dsp_mask << j) & 0x80) {
  133. b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
  134. dst[x >> 1] &= 0xFF0F>>j2;
  135. dst[x >> 1] |= b << (4 - j2);
  136. }
  137. if ((mask << j) & 0x80)
  138. src_x++;
  139. }
  140. break;
  141. default:
  142. bpp = bits_per_pixel >> 3;
  143. d = dst;
  144. s = src;
  145. for (x = 0; x < width; x++) {
  146. j = x & 7;
  147. if ((dsp_mask << j) & 0x80) {
  148. memcpy(d, s, bpp);
  149. }
  150. d += bpp;
  151. if ((mask << j) & 0x80)
  152. s += bpp;
  153. }
  154. break;
  155. }
  156. }
  157. void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
  158. int w, int bpp)
  159. {
  160. int i;
  161. for (i = 0; i < w; i++) {
  162. int a, b, c, p, pa, pb, pc;
  163. a = dst[i - bpp];
  164. b = top[i];
  165. c = top[i - bpp];
  166. p = b - c;
  167. pc = a - c;
  168. pa = abs(p);
  169. pb = abs(pc);
  170. pc = abs(p + pc);
  171. if (pa <= pb && pa <= pc)
  172. p = a;
  173. else if (pb <= pc)
  174. p = b;
  175. else
  176. p = c;
  177. dst[i] = p + src[i];
  178. }
  179. }
  180. #define UNROLL1(bpp, op) \
  181. { \
  182. r = dst[0]; \
  183. if (bpp >= 2) \
  184. g = dst[1]; \
  185. if (bpp >= 3) \
  186. b = dst[2]; \
  187. if (bpp >= 4) \
  188. a = dst[3]; \
  189. for (; i <= size - bpp; i += bpp) { \
  190. dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
  191. if (bpp == 1) \
  192. continue; \
  193. dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
  194. if (bpp == 2) \
  195. continue; \
  196. dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
  197. if (bpp == 3) \
  198. continue; \
  199. dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
  200. } \
  201. }
  202. #define UNROLL_FILTER(op) \
  203. if (bpp == 1) { \
  204. UNROLL1(1, op) \
  205. } else if (bpp == 2) { \
  206. UNROLL1(2, op) \
  207. } else if (bpp == 3) { \
  208. UNROLL1(3, op) \
  209. } else if (bpp == 4) { \
  210. UNROLL1(4, op) \
  211. } \
  212. for (; i < size; i++) { \
  213. dst[i] = op(dst[i - bpp], src[i], last[i]); \
  214. }
  215. /* NOTE: 'dst' can be equal to 'last' */
  216. static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
  217. uint8_t *src, uint8_t *last, int size, int bpp)
  218. {
  219. int i, p, r, g, b, a;
  220. switch (filter_type) {
  221. case PNG_FILTER_VALUE_NONE:
  222. memcpy(dst, src, size);
  223. break;
  224. case PNG_FILTER_VALUE_SUB:
  225. for (i = 0; i < bpp; i++)
  226. dst[i] = src[i];
  227. if (bpp == 4) {
  228. p = *(int *)dst;
  229. for (; i < size; i += bpp) {
  230. unsigned s = *(int *)(src + i);
  231. p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
  232. *(int *)(dst + i) = p;
  233. }
  234. } else {
  235. #define OP_SUB(x, s, l) ((x) + (s))
  236. UNROLL_FILTER(OP_SUB);
  237. }
  238. break;
  239. case PNG_FILTER_VALUE_UP:
  240. dsp->add_bytes_l2(dst, src, last, size);
  241. break;
  242. case PNG_FILTER_VALUE_AVG:
  243. for (i = 0; i < bpp; i++) {
  244. p = (last[i] >> 1);
  245. dst[i] = p + src[i];
  246. }
  247. #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
  248. UNROLL_FILTER(OP_AVG);
  249. break;
  250. case PNG_FILTER_VALUE_PAETH:
  251. for (i = 0; i < bpp; i++) {
  252. p = last[i];
  253. dst[i] = p + src[i];
  254. }
  255. if (bpp > 2 && size > 4) {
  256. /* would write off the end of the array if we let it process
  257. * the last pixel with bpp=3 */
  258. int w = (bpp & 3) ? size - 3 : size;
  259. if (w > i) {
  260. dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
  261. i = w;
  262. }
  263. }
  264. ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
  265. break;
  266. }
  267. }
  268. /* This used to be called "deloco" in FFmpeg
  269. * and is actually an inverse reversible colorspace transformation */
  270. #define YUV2RGB(NAME, TYPE) \
  271. static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
  272. { \
  273. int i; \
  274. for (i = 0; i < size; i += 3 + alpha) { \
  275. int g = dst [i + 1]; \
  276. dst[i + 0] += g; \
  277. dst[i + 2] += g; \
  278. } \
  279. }
  280. YUV2RGB(rgb8, uint8_t)
  281. YUV2RGB(rgb16, uint16_t)
  282. /* process exactly one decompressed row */
  283. static void png_handle_row(PNGDecContext *s)
  284. {
  285. uint8_t *ptr, *last_row;
  286. int got_line;
  287. if (!s->interlace_type) {
  288. ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
  289. if (s->y == 0)
  290. last_row = s->last_row;
  291. else
  292. last_row = ptr - s->image_linesize;
  293. png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
  294. last_row, s->row_size, s->bpp);
  295. /* loco lags by 1 row so that it doesn't interfere with top prediction */
  296. if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
  297. if (s->bit_depth == 16) {
  298. deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
  299. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  300. } else {
  301. deloco_rgb8(ptr - s->image_linesize, s->row_size,
  302. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  303. }
  304. }
  305. s->y++;
  306. if (s->y == s->cur_h) {
  307. s->state |= PNG_ALLIMAGE;
  308. if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
  309. if (s->bit_depth == 16) {
  310. deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
  311. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  312. } else {
  313. deloco_rgb8(ptr, s->row_size,
  314. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  315. }
  316. }
  317. }
  318. } else {
  319. got_line = 0;
  320. for (;;) {
  321. ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
  322. if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
  323. /* if we already read one row, it is time to stop to
  324. * wait for the next one */
  325. if (got_line)
  326. break;
  327. png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
  328. s->last_row, s->pass_row_size, s->bpp);
  329. FFSWAP(uint8_t *, s->last_row, s->tmp_row);
  330. FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
  331. got_line = 1;
  332. }
  333. if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
  334. png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
  335. s->color_type, s->last_row);
  336. }
  337. s->y++;
  338. if (s->y == s->cur_h) {
  339. memset(s->last_row, 0, s->row_size);
  340. for (;;) {
  341. if (s->pass == NB_PASSES - 1) {
  342. s->state |= PNG_ALLIMAGE;
  343. goto the_end;
  344. } else {
  345. s->pass++;
  346. s->y = 0;
  347. s->pass_row_size = ff_png_pass_row_size(s->pass,
  348. s->bits_per_pixel,
  349. s->cur_w);
  350. s->crow_size = s->pass_row_size + 1;
  351. if (s->pass_row_size != 0)
  352. break;
  353. /* skip pass if empty row */
  354. }
  355. }
  356. }
  357. }
  358. the_end:;
  359. }
  360. }
  361. static int png_decode_idat(PNGDecContext *s, int length)
  362. {
  363. int ret;
  364. s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
  365. s->zstream.next_in = (unsigned char *)s->gb.buffer;
  366. bytestream2_skip(&s->gb, length);
  367. /* decode one line if possible */
  368. while (s->zstream.avail_in > 0) {
  369. ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
  370. if (ret != Z_OK && ret != Z_STREAM_END) {
  371. av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
  372. return AVERROR_EXTERNAL;
  373. }
  374. if (s->zstream.avail_out == 0) {
  375. if (!(s->state & PNG_ALLIMAGE)) {
  376. png_handle_row(s);
  377. }
  378. s->zstream.avail_out = s->crow_size;
  379. s->zstream.next_out = s->crow_buf;
  380. }
  381. if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
  382. av_log(NULL, AV_LOG_WARNING,
  383. "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
  384. return 0;
  385. }
  386. }
  387. return 0;
  388. }
  389. static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
  390. const uint8_t *data_end)
  391. {
  392. z_stream zstream;
  393. unsigned char *buf;
  394. unsigned buf_size;
  395. int ret;
  396. zstream.zalloc = ff_png_zalloc;
  397. zstream.zfree = ff_png_zfree;
  398. zstream.opaque = NULL;
  399. if (inflateInit(&zstream) != Z_OK)
  400. return AVERROR_EXTERNAL;
  401. zstream.next_in = (unsigned char *)data;
  402. zstream.avail_in = data_end - data;
  403. av_bprint_init(bp, 0, -1);
  404. while (zstream.avail_in > 0) {
  405. av_bprint_get_buffer(bp, 2, &buf, &buf_size);
  406. if (buf_size < 2) {
  407. ret = AVERROR(ENOMEM);
  408. goto fail;
  409. }
  410. zstream.next_out = buf;
  411. zstream.avail_out = buf_size - 1;
  412. ret = inflate(&zstream, Z_PARTIAL_FLUSH);
  413. if (ret != Z_OK && ret != Z_STREAM_END) {
  414. ret = AVERROR_EXTERNAL;
  415. goto fail;
  416. }
  417. bp->len += zstream.next_out - buf;
  418. if (ret == Z_STREAM_END)
  419. break;
  420. }
  421. inflateEnd(&zstream);
  422. bp->str[bp->len] = 0;
  423. return 0;
  424. fail:
  425. inflateEnd(&zstream);
  426. av_bprint_finalize(bp, NULL);
  427. return ret;
  428. }
  429. static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
  430. {
  431. size_t extra = 0, i;
  432. uint8_t *out, *q;
  433. for (i = 0; i < size_in; i++)
  434. extra += in[i] >= 0x80;
  435. if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
  436. return NULL;
  437. q = out = av_malloc(size_in + extra + 1);
  438. if (!out)
  439. return NULL;
  440. for (i = 0; i < size_in; i++) {
  441. if (in[i] >= 0x80) {
  442. *(q++) = 0xC0 | (in[i] >> 6);
  443. *(q++) = 0x80 | (in[i] & 0x3F);
  444. } else {
  445. *(q++) = in[i];
  446. }
  447. }
  448. *(q++) = 0;
  449. return out;
  450. }
  451. static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
  452. AVDictionary **dict)
  453. {
  454. int ret, method;
  455. const uint8_t *data = s->gb.buffer;
  456. const uint8_t *data_end = data + length;
  457. const uint8_t *keyword = data;
  458. const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
  459. uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
  460. unsigned text_len;
  461. AVBPrint bp;
  462. if (!keyword_end)
  463. return AVERROR_INVALIDDATA;
  464. data = keyword_end + 1;
  465. if (compressed) {
  466. if (data == data_end)
  467. return AVERROR_INVALIDDATA;
  468. method = *(data++);
  469. if (method)
  470. return AVERROR_INVALIDDATA;
  471. if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
  472. return ret;
  473. text_len = bp.len;
  474. av_bprint_finalize(&bp, (char **)&text);
  475. if (!text)
  476. return AVERROR(ENOMEM);
  477. } else {
  478. text = (uint8_t *)data;
  479. text_len = data_end - text;
  480. }
  481. kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
  482. txt_utf8 = iso88591_to_utf8(text, text_len);
  483. if (text != data)
  484. av_free(text);
  485. if (!(kw_utf8 && txt_utf8)) {
  486. av_free(kw_utf8);
  487. av_free(txt_utf8);
  488. return AVERROR(ENOMEM);
  489. }
  490. av_dict_set(dict, kw_utf8, txt_utf8,
  491. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  492. return 0;
  493. }
  494. static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
  495. uint32_t length)
  496. {
  497. if (length != 13)
  498. return AVERROR_INVALIDDATA;
  499. if (s->state & PNG_IDAT) {
  500. av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
  501. return AVERROR_INVALIDDATA;
  502. }
  503. if (s->state & PNG_IHDR) {
  504. av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
  505. return AVERROR_INVALIDDATA;
  506. }
  507. s->width = s->cur_w = bytestream2_get_be32(&s->gb);
  508. s->height = s->cur_h = bytestream2_get_be32(&s->gb);
  509. if (av_image_check_size(s->width, s->height, 0, avctx)) {
  510. s->cur_w = s->cur_h = s->width = s->height = 0;
  511. av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
  512. return AVERROR_INVALIDDATA;
  513. }
  514. s->bit_depth = bytestream2_get_byte(&s->gb);
  515. if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
  516. s->bit_depth != 8 && s->bit_depth != 16) {
  517. av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
  518. goto error;
  519. }
  520. s->color_type = bytestream2_get_byte(&s->gb);
  521. s->compression_type = bytestream2_get_byte(&s->gb);
  522. s->filter_type = bytestream2_get_byte(&s->gb);
  523. s->interlace_type = bytestream2_get_byte(&s->gb);
  524. bytestream2_skip(&s->gb, 4); /* crc */
  525. s->state |= PNG_IHDR;
  526. if (avctx->debug & FF_DEBUG_PICT_INFO)
  527. av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
  528. "compression_type=%d filter_type=%d interlace_type=%d\n",
  529. s->width, s->height, s->bit_depth, s->color_type,
  530. s->compression_type, s->filter_type, s->interlace_type);
  531. return 0;
  532. error:
  533. s->cur_w = s->cur_h = s->width = s->height = 0;
  534. s->bit_depth = 8;
  535. return AVERROR_INVALIDDATA;
  536. }
  537. static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
  538. {
  539. if (s->state & PNG_IDAT) {
  540. av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
  541. return AVERROR_INVALIDDATA;
  542. }
  543. avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
  544. avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
  545. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
  546. avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
  547. bytestream2_skip(&s->gb, 1); /* unit specifier */
  548. bytestream2_skip(&s->gb, 4); /* crc */
  549. return 0;
  550. }
  551. static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
  552. uint32_t length, AVFrame *p)
  553. {
  554. int ret;
  555. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  556. if (!(s->state & PNG_IHDR)) {
  557. av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
  558. return AVERROR_INVALIDDATA;
  559. }
  560. if (!(s->state & PNG_IDAT)) {
  561. /* init image info */
  562. avctx->width = s->width;
  563. avctx->height = s->height;
  564. s->channels = ff_png_get_nb_channels(s->color_type);
  565. s->bits_per_pixel = s->bit_depth * s->channels;
  566. s->bpp = (s->bits_per_pixel + 7) >> 3;
  567. s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
  568. if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  569. s->color_type == PNG_COLOR_TYPE_RGB) {
  570. avctx->pix_fmt = AV_PIX_FMT_RGB24;
  571. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  572. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  573. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  574. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  575. s->color_type == PNG_COLOR_TYPE_GRAY) {
  576. avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  577. } else if (s->bit_depth == 16 &&
  578. s->color_type == PNG_COLOR_TYPE_GRAY) {
  579. avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
  580. } else if (s->bit_depth == 16 &&
  581. s->color_type == PNG_COLOR_TYPE_RGB) {
  582. avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
  583. } else if (s->bit_depth == 16 &&
  584. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  585. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  586. } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
  587. s->color_type == PNG_COLOR_TYPE_PALETTE) {
  588. avctx->pix_fmt = AV_PIX_FMT_PAL8;
  589. } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
  590. avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
  591. } else if (s->bit_depth == 8 &&
  592. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  593. avctx->pix_fmt = AV_PIX_FMT_YA8;
  594. } else if (s->bit_depth == 16 &&
  595. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  596. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  597. } else {
  598. av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
  599. "and color type %d\n",
  600. s->bit_depth, s->color_type);
  601. return AVERROR_INVALIDDATA;
  602. }
  603. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  604. switch (avctx->pix_fmt) {
  605. case AV_PIX_FMT_RGB24:
  606. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  607. break;
  608. case AV_PIX_FMT_RGB48BE:
  609. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  610. break;
  611. case AV_PIX_FMT_GRAY8:
  612. avctx->pix_fmt = AV_PIX_FMT_YA8;
  613. break;
  614. case AV_PIX_FMT_GRAY16BE:
  615. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  616. break;
  617. default:
  618. avpriv_request_sample(avctx, "bit depth %d "
  619. "and color type %d with TRNS",
  620. s->bit_depth, s->color_type);
  621. return AVERROR_INVALIDDATA;
  622. }
  623. s->bpp += byte_depth;
  624. }
  625. if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  626. return ret;
  627. if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
  628. ff_thread_release_buffer(avctx, &s->previous_picture);
  629. if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  630. return ret;
  631. }
  632. ff_thread_finish_setup(avctx);
  633. p->pict_type = AV_PICTURE_TYPE_I;
  634. p->key_frame = 1;
  635. p->interlaced_frame = !!s->interlace_type;
  636. /* compute the compressed row size */
  637. if (!s->interlace_type) {
  638. s->crow_size = s->row_size + 1;
  639. } else {
  640. s->pass = 0;
  641. s->pass_row_size = ff_png_pass_row_size(s->pass,
  642. s->bits_per_pixel,
  643. s->cur_w);
  644. s->crow_size = s->pass_row_size + 1;
  645. }
  646. ff_dlog(avctx, "row_size=%d crow_size =%d\n",
  647. s->row_size, s->crow_size);
  648. s->image_buf = p->data[0];
  649. s->image_linesize = p->linesize[0];
  650. /* copy the palette if needed */
  651. if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
  652. memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
  653. /* empty row is used if differencing to the first row */
  654. av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
  655. if (!s->last_row)
  656. return AVERROR_INVALIDDATA;
  657. if (s->interlace_type ||
  658. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  659. av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
  660. if (!s->tmp_row)
  661. return AVERROR_INVALIDDATA;
  662. }
  663. /* compressed row */
  664. av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
  665. if (!s->buffer)
  666. return AVERROR(ENOMEM);
  667. /* we want crow_buf+1 to be 16-byte aligned */
  668. s->crow_buf = s->buffer + 15;
  669. s->zstream.avail_out = s->crow_size;
  670. s->zstream.next_out = s->crow_buf;
  671. }
  672. s->state |= PNG_IDAT;
  673. /* set image to non-transparent bpp while decompressing */
  674. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  675. s->bpp -= byte_depth;
  676. ret = png_decode_idat(s, length);
  677. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  678. s->bpp += byte_depth;
  679. if (ret < 0)
  680. return ret;
  681. bytestream2_skip(&s->gb, 4); /* crc */
  682. return 0;
  683. }
  684. static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
  685. uint32_t length)
  686. {
  687. int n, i, r, g, b;
  688. if ((length % 3) != 0 || length > 256 * 3)
  689. return AVERROR_INVALIDDATA;
  690. /* read the palette */
  691. n = length / 3;
  692. for (i = 0; i < n; i++) {
  693. r = bytestream2_get_byte(&s->gb);
  694. g = bytestream2_get_byte(&s->gb);
  695. b = bytestream2_get_byte(&s->gb);
  696. s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
  697. }
  698. for (; i < 256; i++)
  699. s->palette[i] = (0xFFU << 24);
  700. s->state |= PNG_PLTE;
  701. bytestream2_skip(&s->gb, 4); /* crc */
  702. return 0;
  703. }
  704. static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
  705. uint32_t length)
  706. {
  707. int v, i;
  708. if (!(s->state & PNG_IHDR)) {
  709. av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
  710. return AVERROR_INVALIDDATA;
  711. }
  712. if (s->state & PNG_IDAT) {
  713. av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
  714. return AVERROR_INVALIDDATA;
  715. }
  716. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  717. if (length > 256 || !(s->state & PNG_PLTE))
  718. return AVERROR_INVALIDDATA;
  719. for (i = 0; i < length; i++) {
  720. v = bytestream2_get_byte(&s->gb);
  721. s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
  722. }
  723. } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
  724. if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
  725. (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
  726. s->bit_depth == 1)
  727. return AVERROR_INVALIDDATA;
  728. for (i = 0; i < length / 2; i++) {
  729. /* only use the least significant bits */
  730. v = bytestream2_get_be16(&s->gb) & ((1 << s->bit_depth) - 1);
  731. if (s->bit_depth > 8)
  732. AV_WB16(&s->transparent_color_be[2 * i], v);
  733. else
  734. s->transparent_color_be[i] = v;
  735. }
  736. } else {
  737. return AVERROR_INVALIDDATA;
  738. }
  739. bytestream2_skip(&s->gb, 4); /* crc */
  740. s->has_trns = 1;
  741. return 0;
  742. }
  743. static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
  744. {
  745. if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
  746. int i, j, k;
  747. uint8_t *pd = p->data[0];
  748. for (j = 0; j < s->height; j++) {
  749. i = s->width / 8;
  750. for (k = 7; k >= 1; k--)
  751. if ((s->width&7) >= k)
  752. pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
  753. for (i--; i >= 0; i--) {
  754. pd[8*i + 7]= pd[i] & 1;
  755. pd[8*i + 6]= (pd[i]>>1) & 1;
  756. pd[8*i + 5]= (pd[i]>>2) & 1;
  757. pd[8*i + 4]= (pd[i]>>3) & 1;
  758. pd[8*i + 3]= (pd[i]>>4) & 1;
  759. pd[8*i + 2]= (pd[i]>>5) & 1;
  760. pd[8*i + 1]= (pd[i]>>6) & 1;
  761. pd[8*i + 0]= pd[i]>>7;
  762. }
  763. pd += s->image_linesize;
  764. }
  765. } else if (s->bits_per_pixel == 2) {
  766. int i, j;
  767. uint8_t *pd = p->data[0];
  768. for (j = 0; j < s->height; j++) {
  769. i = s->width / 4;
  770. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  771. if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
  772. if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
  773. if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
  774. for (i--; i >= 0; i--) {
  775. pd[4*i + 3]= pd[i] & 3;
  776. pd[4*i + 2]= (pd[i]>>2) & 3;
  777. pd[4*i + 1]= (pd[i]>>4) & 3;
  778. pd[4*i + 0]= pd[i]>>6;
  779. }
  780. } else {
  781. if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  782. if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  783. if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  784. for (i--; i >= 0; i--) {
  785. pd[4*i + 3]= ( pd[i] & 3)*0x55;
  786. pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  787. pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  788. pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  789. }
  790. }
  791. pd += s->image_linesize;
  792. }
  793. } else if (s->bits_per_pixel == 4) {
  794. int i, j;
  795. uint8_t *pd = p->data[0];
  796. for (j = 0; j < s->height; j++) {
  797. i = s->width/2;
  798. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  799. if (s->width&1) pd[2*i+0]= pd[i]>>4;
  800. for (i--; i >= 0; i--) {
  801. pd[2*i + 1] = pd[i] & 15;
  802. pd[2*i + 0] = pd[i] >> 4;
  803. }
  804. } else {
  805. if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
  806. for (i--; i >= 0; i--) {
  807. pd[2*i + 1] = (pd[i] & 15) * 0x11;
  808. pd[2*i + 0] = (pd[i] >> 4) * 0x11;
  809. }
  810. }
  811. pd += s->image_linesize;
  812. }
  813. }
  814. }
  815. static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
  816. uint32_t length)
  817. {
  818. uint32_t sequence_number;
  819. int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
  820. if (length != 26)
  821. return AVERROR_INVALIDDATA;
  822. if (!(s->state & PNG_IHDR)) {
  823. av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
  824. return AVERROR_INVALIDDATA;
  825. }
  826. s->last_w = s->cur_w;
  827. s->last_h = s->cur_h;
  828. s->last_x_offset = s->x_offset;
  829. s->last_y_offset = s->y_offset;
  830. s->last_dispose_op = s->dispose_op;
  831. sequence_number = bytestream2_get_be32(&s->gb);
  832. cur_w = bytestream2_get_be32(&s->gb);
  833. cur_h = bytestream2_get_be32(&s->gb);
  834. x_offset = bytestream2_get_be32(&s->gb);
  835. y_offset = bytestream2_get_be32(&s->gb);
  836. bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
  837. dispose_op = bytestream2_get_byte(&s->gb);
  838. blend_op = bytestream2_get_byte(&s->gb);
  839. bytestream2_skip(&s->gb, 4); /* crc */
  840. if (sequence_number == 0 &&
  841. (cur_w != s->width ||
  842. cur_h != s->height ||
  843. x_offset != 0 ||
  844. y_offset != 0) ||
  845. cur_w <= 0 || cur_h <= 0 ||
  846. x_offset < 0 || y_offset < 0 ||
  847. cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
  848. return AVERROR_INVALIDDATA;
  849. if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
  850. av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
  851. return AVERROR_INVALIDDATA;
  852. }
  853. if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
  854. // No previous frame to revert to for the first frame
  855. // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
  856. dispose_op = APNG_DISPOSE_OP_BACKGROUND;
  857. }
  858. if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
  859. avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
  860. avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
  861. avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
  862. avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
  863. avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
  864. avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
  865. )) {
  866. // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
  867. blend_op = APNG_BLEND_OP_SOURCE;
  868. }
  869. s->cur_w = cur_w;
  870. s->cur_h = cur_h;
  871. s->x_offset = x_offset;
  872. s->y_offset = y_offset;
  873. s->dispose_op = dispose_op;
  874. s->blend_op = blend_op;
  875. return 0;
  876. }
  877. static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
  878. {
  879. int i, j;
  880. uint8_t *pd = p->data[0];
  881. uint8_t *pd_last = s->last_picture.f->data[0];
  882. int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
  883. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  884. for (j = 0; j < s->height; j++) {
  885. for (i = 0; i < ls; i++)
  886. pd[i] += pd_last[i];
  887. pd += s->image_linesize;
  888. pd_last += s->image_linesize;
  889. }
  890. }
  891. // divide by 255 and round to nearest
  892. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  893. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  894. static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
  895. AVFrame *p)
  896. {
  897. size_t x, y;
  898. uint8_t *buffer = av_malloc(s->image_linesize * s->height);
  899. if (!buffer)
  900. return AVERROR(ENOMEM);
  901. if (s->blend_op == APNG_BLEND_OP_OVER &&
  902. avctx->pix_fmt != AV_PIX_FMT_RGBA &&
  903. avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
  904. avctx->pix_fmt != AV_PIX_FMT_PAL8) {
  905. avpriv_request_sample(avctx, "Blending with pixel format %s",
  906. av_get_pix_fmt_name(avctx->pix_fmt));
  907. return AVERROR_PATCHWELCOME;
  908. }
  909. // Do the disposal operation specified by the last frame on the frame
  910. if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
  911. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  912. memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
  913. if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
  914. for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
  915. memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
  916. memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
  917. ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
  918. } else {
  919. ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
  920. memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
  921. }
  922. // Perform blending
  923. if (s->blend_op == APNG_BLEND_OP_SOURCE) {
  924. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  925. size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
  926. memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
  927. }
  928. } else { // APNG_BLEND_OP_OVER
  929. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  930. uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
  931. uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
  932. for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
  933. size_t b;
  934. uint8_t foreground_alpha, background_alpha, output_alpha;
  935. uint8_t output[10];
  936. // Since we might be blending alpha onto alpha, we use the following equations:
  937. // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
  938. // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
  939. switch (avctx->pix_fmt) {
  940. case AV_PIX_FMT_RGBA:
  941. foreground_alpha = foreground[3];
  942. background_alpha = background[3];
  943. break;
  944. case AV_PIX_FMT_GRAY8A:
  945. foreground_alpha = foreground[1];
  946. background_alpha = background[1];
  947. break;
  948. case AV_PIX_FMT_PAL8:
  949. foreground_alpha = s->palette[foreground[0]] >> 24;
  950. background_alpha = s->palette[background[0]] >> 24;
  951. break;
  952. }
  953. if (foreground_alpha == 0)
  954. continue;
  955. if (foreground_alpha == 255) {
  956. memcpy(background, foreground, s->bpp);
  957. continue;
  958. }
  959. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  960. // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
  961. avpriv_request_sample(avctx, "Alpha blending palette samples");
  962. background[0] = foreground[0];
  963. continue;
  964. }
  965. output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
  966. av_assert0(s->bpp <= 10);
  967. for (b = 0; b < s->bpp - 1; ++b) {
  968. if (output_alpha == 0) {
  969. output[b] = 0;
  970. } else if (background_alpha == 255) {
  971. output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
  972. } else {
  973. output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
  974. }
  975. }
  976. output[b] = output_alpha;
  977. memcpy(background, output, s->bpp);
  978. }
  979. }
  980. }
  981. // Copy blended buffer into the frame and free
  982. memcpy(p->data[0], buffer, s->image_linesize * s->height);
  983. av_free(buffer);
  984. return 0;
  985. }
  986. static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
  987. AVFrame *p, AVPacket *avpkt)
  988. {
  989. AVDictionary *metadata = NULL;
  990. uint32_t tag, length;
  991. int decode_next_dat = 0;
  992. int ret;
  993. for (;;) {
  994. length = bytestream2_get_bytes_left(&s->gb);
  995. if (length <= 0) {
  996. if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
  997. if (!(s->state & PNG_IDAT))
  998. return 0;
  999. else
  1000. goto exit_loop;
  1001. }
  1002. av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
  1003. if ( s->state & PNG_ALLIMAGE
  1004. && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
  1005. goto exit_loop;
  1006. ret = AVERROR_INVALIDDATA;
  1007. goto fail;
  1008. }
  1009. length = bytestream2_get_be32(&s->gb);
  1010. if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
  1011. av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
  1012. ret = AVERROR_INVALIDDATA;
  1013. goto fail;
  1014. }
  1015. tag = bytestream2_get_le32(&s->gb);
  1016. if (avctx->debug & FF_DEBUG_STARTCODE)
  1017. av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
  1018. (tag & 0xff),
  1019. ((tag >> 8) & 0xff),
  1020. ((tag >> 16) & 0xff),
  1021. ((tag >> 24) & 0xff), length);
  1022. switch (tag) {
  1023. case MKTAG('I', 'H', 'D', 'R'):
  1024. if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
  1025. goto fail;
  1026. break;
  1027. case MKTAG('p', 'H', 'Y', 's'):
  1028. if ((ret = decode_phys_chunk(avctx, s)) < 0)
  1029. goto fail;
  1030. break;
  1031. case MKTAG('f', 'c', 'T', 'L'):
  1032. if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
  1033. goto skip_tag;
  1034. if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
  1035. goto fail;
  1036. decode_next_dat = 1;
  1037. break;
  1038. case MKTAG('f', 'd', 'A', 'T'):
  1039. if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
  1040. goto skip_tag;
  1041. if (!decode_next_dat) {
  1042. ret = AVERROR_INVALIDDATA;
  1043. goto fail;
  1044. }
  1045. bytestream2_get_be32(&s->gb);
  1046. length -= 4;
  1047. /* fallthrough */
  1048. case MKTAG('I', 'D', 'A', 'T'):
  1049. if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
  1050. goto skip_tag;
  1051. if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
  1052. goto fail;
  1053. break;
  1054. case MKTAG('P', 'L', 'T', 'E'):
  1055. if (decode_plte_chunk(avctx, s, length) < 0)
  1056. goto skip_tag;
  1057. break;
  1058. case MKTAG('t', 'R', 'N', 'S'):
  1059. if (decode_trns_chunk(avctx, s, length) < 0)
  1060. goto skip_tag;
  1061. break;
  1062. case MKTAG('t', 'E', 'X', 't'):
  1063. if (decode_text_chunk(s, length, 0, &metadata) < 0)
  1064. av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
  1065. bytestream2_skip(&s->gb, length + 4);
  1066. break;
  1067. case MKTAG('z', 'T', 'X', 't'):
  1068. if (decode_text_chunk(s, length, 1, &metadata) < 0)
  1069. av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
  1070. bytestream2_skip(&s->gb, length + 4);
  1071. break;
  1072. case MKTAG('I', 'E', 'N', 'D'):
  1073. if (!(s->state & PNG_ALLIMAGE))
  1074. av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
  1075. if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
  1076. ret = AVERROR_INVALIDDATA;
  1077. goto fail;
  1078. }
  1079. bytestream2_skip(&s->gb, 4); /* crc */
  1080. goto exit_loop;
  1081. default:
  1082. /* skip tag */
  1083. skip_tag:
  1084. bytestream2_skip(&s->gb, length + 4);
  1085. break;
  1086. }
  1087. }
  1088. exit_loop:
  1089. if (s->bits_per_pixel <= 4)
  1090. handle_small_bpp(s, p);
  1091. /* apply transparency if needed */
  1092. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  1093. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  1094. size_t raw_bpp = s->bpp - byte_depth;
  1095. unsigned x, y;
  1096. av_assert0(s->bit_depth > 1);
  1097. for (y = 0; y < s->height; ++y) {
  1098. uint8_t *row = &s->image_buf[s->image_linesize * y];
  1099. /* since we're updating in-place, we have to go from right to left */
  1100. for (x = s->width; x > 0; --x) {
  1101. uint8_t *pixel = &row[s->bpp * (x - 1)];
  1102. memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
  1103. if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
  1104. memset(&pixel[raw_bpp], 0, byte_depth);
  1105. } else {
  1106. memset(&pixel[raw_bpp], 0xff, byte_depth);
  1107. }
  1108. }
  1109. }
  1110. }
  1111. /* handle p-frames only if a predecessor frame is available */
  1112. if (s->last_picture.f->data[0]) {
  1113. if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
  1114. && s->last_picture.f->width == p->width
  1115. && s->last_picture.f->height== p->height
  1116. && s->last_picture.f->format== p->format
  1117. ) {
  1118. if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
  1119. handle_p_frame_png(s, p);
  1120. else if (CONFIG_APNG_DECODER &&
  1121. avctx->codec_id == AV_CODEC_ID_APNG &&
  1122. (ret = handle_p_frame_apng(avctx, s, p)) < 0)
  1123. goto fail;
  1124. }
  1125. }
  1126. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  1127. av_frame_set_metadata(p, metadata);
  1128. metadata = NULL;
  1129. return 0;
  1130. fail:
  1131. av_dict_free(&metadata);
  1132. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  1133. return ret;
  1134. }
  1135. #if CONFIG_PNG_DECODER
  1136. static int decode_frame_png(AVCodecContext *avctx,
  1137. void *data, int *got_frame,
  1138. AVPacket *avpkt)
  1139. {
  1140. PNGDecContext *const s = avctx->priv_data;
  1141. const uint8_t *buf = avpkt->data;
  1142. int buf_size = avpkt->size;
  1143. AVFrame *p;
  1144. int64_t sig;
  1145. int ret;
  1146. ff_thread_release_buffer(avctx, &s->last_picture);
  1147. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  1148. p = s->picture.f;
  1149. bytestream2_init(&s->gb, buf, buf_size);
  1150. /* check signature */
  1151. sig = bytestream2_get_be64(&s->gb);
  1152. if (sig != PNGSIG &&
  1153. sig != MNGSIG) {
  1154. av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
  1155. return AVERROR_INVALIDDATA;
  1156. }
  1157. s->y = s->state = s->has_trns = 0;
  1158. /* init the zlib */
  1159. s->zstream.zalloc = ff_png_zalloc;
  1160. s->zstream.zfree = ff_png_zfree;
  1161. s->zstream.opaque = NULL;
  1162. ret = inflateInit(&s->zstream);
  1163. if (ret != Z_OK) {
  1164. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  1165. return AVERROR_EXTERNAL;
  1166. }
  1167. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1168. goto the_end;
  1169. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  1170. return ret;
  1171. *got_frame = 1;
  1172. ret = bytestream2_tell(&s->gb);
  1173. the_end:
  1174. inflateEnd(&s->zstream);
  1175. s->crow_buf = NULL;
  1176. return ret;
  1177. }
  1178. #endif
  1179. #if CONFIG_APNG_DECODER
  1180. static int decode_frame_apng(AVCodecContext *avctx,
  1181. void *data, int *got_frame,
  1182. AVPacket *avpkt)
  1183. {
  1184. PNGDecContext *const s = avctx->priv_data;
  1185. int ret;
  1186. AVFrame *p;
  1187. ff_thread_release_buffer(avctx, &s->last_picture);
  1188. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  1189. p = s->picture.f;
  1190. if (!(s->state & PNG_IHDR)) {
  1191. if (!avctx->extradata_size)
  1192. return AVERROR_INVALIDDATA;
  1193. /* only init fields, there is no zlib use in extradata */
  1194. s->zstream.zalloc = ff_png_zalloc;
  1195. s->zstream.zfree = ff_png_zfree;
  1196. bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
  1197. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1198. goto end;
  1199. }
  1200. /* reset state for a new frame */
  1201. if ((ret = inflateInit(&s->zstream)) != Z_OK) {
  1202. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  1203. ret = AVERROR_EXTERNAL;
  1204. goto end;
  1205. }
  1206. s->y = 0;
  1207. s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
  1208. bytestream2_init(&s->gb, avpkt->data, avpkt->size);
  1209. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1210. goto end;
  1211. if (!(s->state & PNG_ALLIMAGE))
  1212. av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
  1213. if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
  1214. ret = AVERROR_INVALIDDATA;
  1215. goto end;
  1216. }
  1217. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  1218. goto end;
  1219. *got_frame = 1;
  1220. ret = bytestream2_tell(&s->gb);
  1221. end:
  1222. inflateEnd(&s->zstream);
  1223. return ret;
  1224. }
  1225. #endif
  1226. static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  1227. {
  1228. PNGDecContext *psrc = src->priv_data;
  1229. PNGDecContext *pdst = dst->priv_data;
  1230. int ret;
  1231. if (dst == src)
  1232. return 0;
  1233. ff_thread_release_buffer(dst, &pdst->picture);
  1234. if (psrc->picture.f->data[0] &&
  1235. (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
  1236. return ret;
  1237. if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
  1238. pdst->width = psrc->width;
  1239. pdst->height = psrc->height;
  1240. pdst->bit_depth = psrc->bit_depth;
  1241. pdst->color_type = psrc->color_type;
  1242. pdst->compression_type = psrc->compression_type;
  1243. pdst->interlace_type = psrc->interlace_type;
  1244. pdst->filter_type = psrc->filter_type;
  1245. pdst->cur_w = psrc->cur_w;
  1246. pdst->cur_h = psrc->cur_h;
  1247. pdst->x_offset = psrc->x_offset;
  1248. pdst->y_offset = psrc->y_offset;
  1249. pdst->has_trns = psrc->has_trns;
  1250. memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
  1251. pdst->dispose_op = psrc->dispose_op;
  1252. memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
  1253. pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
  1254. ff_thread_release_buffer(dst, &pdst->last_picture);
  1255. if (psrc->last_picture.f->data[0] &&
  1256. (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
  1257. return ret;
  1258. ff_thread_release_buffer(dst, &pdst->previous_picture);
  1259. if (psrc->previous_picture.f->data[0] &&
  1260. (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
  1261. return ret;
  1262. }
  1263. return 0;
  1264. }
  1265. static av_cold int png_dec_init(AVCodecContext *avctx)
  1266. {
  1267. PNGDecContext *s = avctx->priv_data;
  1268. avctx->color_range = AVCOL_RANGE_JPEG;
  1269. s->avctx = avctx;
  1270. s->previous_picture.f = av_frame_alloc();
  1271. s->last_picture.f = av_frame_alloc();
  1272. s->picture.f = av_frame_alloc();
  1273. if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
  1274. av_frame_free(&s->previous_picture.f);
  1275. av_frame_free(&s->last_picture.f);
  1276. av_frame_free(&s->picture.f);
  1277. return AVERROR(ENOMEM);
  1278. }
  1279. if (!avctx->internal->is_copy) {
  1280. avctx->internal->allocate_progress = 1;
  1281. ff_pngdsp_init(&s->dsp);
  1282. }
  1283. return 0;
  1284. }
  1285. static av_cold int png_dec_end(AVCodecContext *avctx)
  1286. {
  1287. PNGDecContext *s = avctx->priv_data;
  1288. ff_thread_release_buffer(avctx, &s->previous_picture);
  1289. av_frame_free(&s->previous_picture.f);
  1290. ff_thread_release_buffer(avctx, &s->last_picture);
  1291. av_frame_free(&s->last_picture.f);
  1292. ff_thread_release_buffer(avctx, &s->picture);
  1293. av_frame_free(&s->picture.f);
  1294. av_freep(&s->buffer);
  1295. s->buffer_size = 0;
  1296. av_freep(&s->last_row);
  1297. s->last_row_size = 0;
  1298. av_freep(&s->tmp_row);
  1299. s->tmp_row_size = 0;
  1300. return 0;
  1301. }
  1302. #if CONFIG_APNG_DECODER
  1303. AVCodec ff_apng_decoder = {
  1304. .name = "apng",
  1305. .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
  1306. .type = AVMEDIA_TYPE_VIDEO,
  1307. .id = AV_CODEC_ID_APNG,
  1308. .priv_data_size = sizeof(PNGDecContext),
  1309. .init = png_dec_init,
  1310. .close = png_dec_end,
  1311. .decode = decode_frame_apng,
  1312. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  1313. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1314. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
  1315. };
  1316. #endif
  1317. #if CONFIG_PNG_DECODER
  1318. AVCodec ff_png_decoder = {
  1319. .name = "png",
  1320. .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
  1321. .type = AVMEDIA_TYPE_VIDEO,
  1322. .id = AV_CODEC_ID_PNG,
  1323. .priv_data_size = sizeof(PNGDecContext),
  1324. .init = png_dec_init,
  1325. .close = png_dec_end,
  1326. .decode = decode_frame_png,
  1327. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  1328. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1329. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
  1330. };
  1331. #endif