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.

1475 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. s->color_type = bytestream2_get_byte(&s->gb);
  516. s->compression_type = bytestream2_get_byte(&s->gb);
  517. s->filter_type = bytestream2_get_byte(&s->gb);
  518. s->interlace_type = bytestream2_get_byte(&s->gb);
  519. bytestream2_skip(&s->gb, 4); /* crc */
  520. s->state |= PNG_IHDR;
  521. if (avctx->debug & FF_DEBUG_PICT_INFO)
  522. av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
  523. "compression_type=%d filter_type=%d interlace_type=%d\n",
  524. s->width, s->height, s->bit_depth, s->color_type,
  525. s->compression_type, s->filter_type, s->interlace_type);
  526. return 0;
  527. }
  528. static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
  529. {
  530. if (s->state & PNG_IDAT) {
  531. av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
  532. return AVERROR_INVALIDDATA;
  533. }
  534. avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
  535. avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
  536. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
  537. avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
  538. bytestream2_skip(&s->gb, 1); /* unit specifier */
  539. bytestream2_skip(&s->gb, 4); /* crc */
  540. return 0;
  541. }
  542. static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
  543. uint32_t length, AVFrame *p)
  544. {
  545. int ret;
  546. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  547. if (!(s->state & PNG_IHDR)) {
  548. av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
  549. return AVERROR_INVALIDDATA;
  550. }
  551. if (!(s->state & PNG_IDAT)) {
  552. /* init image info */
  553. avctx->width = s->width;
  554. avctx->height = s->height;
  555. s->channels = ff_png_get_nb_channels(s->color_type);
  556. s->bits_per_pixel = s->bit_depth * s->channels;
  557. s->bpp = (s->bits_per_pixel + 7) >> 3;
  558. s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
  559. if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  560. s->color_type == PNG_COLOR_TYPE_RGB) {
  561. avctx->pix_fmt = AV_PIX_FMT_RGB24;
  562. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  563. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  564. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  565. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  566. s->color_type == PNG_COLOR_TYPE_GRAY) {
  567. avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  568. } else if (s->bit_depth == 16 &&
  569. s->color_type == PNG_COLOR_TYPE_GRAY) {
  570. avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
  571. } else if (s->bit_depth == 16 &&
  572. s->color_type == PNG_COLOR_TYPE_RGB) {
  573. avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
  574. } else if (s->bit_depth == 16 &&
  575. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  576. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  577. } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
  578. s->color_type == PNG_COLOR_TYPE_PALETTE) {
  579. avctx->pix_fmt = AV_PIX_FMT_PAL8;
  580. } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
  581. avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
  582. } else if (s->bit_depth == 8 &&
  583. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  584. avctx->pix_fmt = AV_PIX_FMT_YA8;
  585. } else if (s->bit_depth == 16 &&
  586. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  587. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  588. } else {
  589. av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
  590. "and color type %d\n",
  591. s->bit_depth, s->color_type);
  592. return AVERROR_INVALIDDATA;
  593. }
  594. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  595. switch (avctx->pix_fmt) {
  596. case AV_PIX_FMT_RGB24:
  597. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  598. break;
  599. case AV_PIX_FMT_RGB48BE:
  600. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  601. break;
  602. case AV_PIX_FMT_GRAY8:
  603. avctx->pix_fmt = AV_PIX_FMT_YA8;
  604. break;
  605. case AV_PIX_FMT_GRAY16BE:
  606. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  607. break;
  608. default:
  609. avpriv_request_sample(avctx, "bit depth %d "
  610. "and color type %d with TRNS",
  611. s->bit_depth, s->color_type);
  612. return AVERROR_INVALIDDATA;
  613. }
  614. s->bpp += byte_depth;
  615. }
  616. if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  617. return ret;
  618. if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
  619. ff_thread_release_buffer(avctx, &s->previous_picture);
  620. if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  621. return ret;
  622. }
  623. ff_thread_finish_setup(avctx);
  624. p->pict_type = AV_PICTURE_TYPE_I;
  625. p->key_frame = 1;
  626. p->interlaced_frame = !!s->interlace_type;
  627. /* compute the compressed row size */
  628. if (!s->interlace_type) {
  629. s->crow_size = s->row_size + 1;
  630. } else {
  631. s->pass = 0;
  632. s->pass_row_size = ff_png_pass_row_size(s->pass,
  633. s->bits_per_pixel,
  634. s->cur_w);
  635. s->crow_size = s->pass_row_size + 1;
  636. }
  637. ff_dlog(avctx, "row_size=%d crow_size =%d\n",
  638. s->row_size, s->crow_size);
  639. s->image_buf = p->data[0];
  640. s->image_linesize = p->linesize[0];
  641. /* copy the palette if needed */
  642. if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
  643. memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
  644. /* empty row is used if differencing to the first row */
  645. av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
  646. if (!s->last_row)
  647. return AVERROR_INVALIDDATA;
  648. if (s->interlace_type ||
  649. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  650. av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
  651. if (!s->tmp_row)
  652. return AVERROR_INVALIDDATA;
  653. }
  654. /* compressed row */
  655. av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
  656. if (!s->buffer)
  657. return AVERROR(ENOMEM);
  658. /* we want crow_buf+1 to be 16-byte aligned */
  659. s->crow_buf = s->buffer + 15;
  660. s->zstream.avail_out = s->crow_size;
  661. s->zstream.next_out = s->crow_buf;
  662. }
  663. s->state |= PNG_IDAT;
  664. /* set image to non-transparent bpp while decompressing */
  665. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  666. s->bpp -= byte_depth;
  667. ret = png_decode_idat(s, length);
  668. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  669. s->bpp += byte_depth;
  670. if (ret < 0)
  671. return ret;
  672. bytestream2_skip(&s->gb, 4); /* crc */
  673. return 0;
  674. }
  675. static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
  676. uint32_t length)
  677. {
  678. int n, i, r, g, b;
  679. if ((length % 3) != 0 || length > 256 * 3)
  680. return AVERROR_INVALIDDATA;
  681. /* read the palette */
  682. n = length / 3;
  683. for (i = 0; i < n; i++) {
  684. r = bytestream2_get_byte(&s->gb);
  685. g = bytestream2_get_byte(&s->gb);
  686. b = bytestream2_get_byte(&s->gb);
  687. s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
  688. }
  689. for (; i < 256; i++)
  690. s->palette[i] = (0xFFU << 24);
  691. s->state |= PNG_PLTE;
  692. bytestream2_skip(&s->gb, 4); /* crc */
  693. return 0;
  694. }
  695. static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
  696. uint32_t length)
  697. {
  698. int v, i;
  699. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  700. if (length > 256 || !(s->state & PNG_PLTE))
  701. return AVERROR_INVALIDDATA;
  702. for (i = 0; i < length; i++) {
  703. v = bytestream2_get_byte(&s->gb);
  704. s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
  705. }
  706. } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
  707. if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
  708. (s->color_type == PNG_COLOR_TYPE_RGB && length != 6))
  709. return AVERROR_INVALIDDATA;
  710. for (i = 0; i < length / 2; i++) {
  711. /* only use the least significant bits */
  712. v = bytestream2_get_be16(&s->gb) & ((1 << s->bit_depth) - 1);
  713. if (s->bit_depth > 8)
  714. AV_WB16(&s->transparent_color_be[2 * i], v);
  715. else
  716. s->transparent_color_be[i] = v;
  717. }
  718. } else {
  719. return AVERROR_INVALIDDATA;
  720. }
  721. bytestream2_skip(&s->gb, 4); /* crc */
  722. s->has_trns = 1;
  723. return 0;
  724. }
  725. static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
  726. {
  727. if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
  728. int i, j, k;
  729. uint8_t *pd = p->data[0];
  730. for (j = 0; j < s->height; j++) {
  731. i = s->width / 8;
  732. for (k = 7; k >= 1; k--)
  733. if ((s->width&7) >= k)
  734. pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
  735. for (i--; i >= 0; i--) {
  736. pd[8*i + 7]= pd[i] & 1;
  737. pd[8*i + 6]= (pd[i]>>1) & 1;
  738. pd[8*i + 5]= (pd[i]>>2) & 1;
  739. pd[8*i + 4]= (pd[i]>>3) & 1;
  740. pd[8*i + 3]= (pd[i]>>4) & 1;
  741. pd[8*i + 2]= (pd[i]>>5) & 1;
  742. pd[8*i + 1]= (pd[i]>>6) & 1;
  743. pd[8*i + 0]= pd[i]>>7;
  744. }
  745. pd += s->image_linesize;
  746. }
  747. } else if (s->bits_per_pixel == 2) {
  748. int i, j;
  749. uint8_t *pd = p->data[0];
  750. for (j = 0; j < s->height; j++) {
  751. i = s->width / 4;
  752. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  753. if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
  754. if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
  755. if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
  756. for (i--; i >= 0; i--) {
  757. pd[4*i + 3]= pd[i] & 3;
  758. pd[4*i + 2]= (pd[i]>>2) & 3;
  759. pd[4*i + 1]= (pd[i]>>4) & 3;
  760. pd[4*i + 0]= pd[i]>>6;
  761. }
  762. } else {
  763. if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  764. if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  765. if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  766. for (i--; i >= 0; i--) {
  767. pd[4*i + 3]= ( pd[i] & 3)*0x55;
  768. pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  769. pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  770. pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  771. }
  772. }
  773. pd += s->image_linesize;
  774. }
  775. } else if (s->bits_per_pixel == 4) {
  776. int i, j;
  777. uint8_t *pd = p->data[0];
  778. for (j = 0; j < s->height; j++) {
  779. i = s->width/2;
  780. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  781. if (s->width&1) pd[2*i+0]= pd[i]>>4;
  782. for (i--; i >= 0; i--) {
  783. pd[2*i + 1] = pd[i] & 15;
  784. pd[2*i + 0] = pd[i] >> 4;
  785. }
  786. } else {
  787. if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
  788. for (i--; i >= 0; i--) {
  789. pd[2*i + 1] = (pd[i] & 15) * 0x11;
  790. pd[2*i + 0] = (pd[i] >> 4) * 0x11;
  791. }
  792. }
  793. pd += s->image_linesize;
  794. }
  795. }
  796. }
  797. static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
  798. uint32_t length)
  799. {
  800. uint32_t sequence_number;
  801. int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
  802. if (length != 26)
  803. return AVERROR_INVALIDDATA;
  804. if (!(s->state & PNG_IHDR)) {
  805. av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
  806. return AVERROR_INVALIDDATA;
  807. }
  808. s->last_w = s->cur_w;
  809. s->last_h = s->cur_h;
  810. s->last_x_offset = s->x_offset;
  811. s->last_y_offset = s->y_offset;
  812. s->last_dispose_op = s->dispose_op;
  813. sequence_number = bytestream2_get_be32(&s->gb);
  814. cur_w = bytestream2_get_be32(&s->gb);
  815. cur_h = bytestream2_get_be32(&s->gb);
  816. x_offset = bytestream2_get_be32(&s->gb);
  817. y_offset = bytestream2_get_be32(&s->gb);
  818. bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
  819. dispose_op = bytestream2_get_byte(&s->gb);
  820. blend_op = bytestream2_get_byte(&s->gb);
  821. bytestream2_skip(&s->gb, 4); /* crc */
  822. if (sequence_number == 0 &&
  823. (cur_w != s->width ||
  824. cur_h != s->height ||
  825. x_offset != 0 ||
  826. y_offset != 0) ||
  827. cur_w <= 0 || cur_h <= 0 ||
  828. x_offset < 0 || y_offset < 0 ||
  829. cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
  830. return AVERROR_INVALIDDATA;
  831. if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
  832. av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
  833. return AVERROR_INVALIDDATA;
  834. }
  835. if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
  836. // No previous frame to revert to for the first frame
  837. // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
  838. dispose_op = APNG_DISPOSE_OP_BACKGROUND;
  839. }
  840. if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
  841. avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
  842. avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
  843. avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
  844. avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
  845. avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
  846. avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
  847. )) {
  848. // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
  849. blend_op = APNG_BLEND_OP_SOURCE;
  850. }
  851. s->cur_w = cur_w;
  852. s->cur_h = cur_h;
  853. s->x_offset = x_offset;
  854. s->y_offset = y_offset;
  855. s->dispose_op = dispose_op;
  856. s->blend_op = blend_op;
  857. return 0;
  858. }
  859. static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
  860. {
  861. int i, j;
  862. uint8_t *pd = p->data[0];
  863. uint8_t *pd_last = s->last_picture.f->data[0];
  864. int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
  865. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  866. for (j = 0; j < s->height; j++) {
  867. for (i = 0; i < ls; i++)
  868. pd[i] += pd_last[i];
  869. pd += s->image_linesize;
  870. pd_last += s->image_linesize;
  871. }
  872. }
  873. // divide by 255 and round to nearest
  874. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  875. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  876. static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
  877. AVFrame *p)
  878. {
  879. size_t x, y;
  880. uint8_t *buffer = av_malloc(s->image_linesize * s->height);
  881. if (!buffer)
  882. return AVERROR(ENOMEM);
  883. if (s->blend_op == APNG_BLEND_OP_OVER &&
  884. avctx->pix_fmt != AV_PIX_FMT_RGBA &&
  885. avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
  886. avctx->pix_fmt != AV_PIX_FMT_PAL8) {
  887. avpriv_request_sample(avctx, "Blending with pixel format %s",
  888. av_get_pix_fmt_name(avctx->pix_fmt));
  889. return AVERROR_PATCHWELCOME;
  890. }
  891. // Do the disposal operation specified by the last frame on the frame
  892. if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
  893. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  894. memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
  895. if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
  896. for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
  897. memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
  898. memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
  899. ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
  900. } else {
  901. ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
  902. memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
  903. }
  904. // Perform blending
  905. if (s->blend_op == APNG_BLEND_OP_SOURCE) {
  906. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  907. size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
  908. memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
  909. }
  910. } else { // APNG_BLEND_OP_OVER
  911. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  912. uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
  913. uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
  914. for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
  915. size_t b;
  916. uint8_t foreground_alpha, background_alpha, output_alpha;
  917. uint8_t output[10];
  918. // Since we might be blending alpha onto alpha, we use the following equations:
  919. // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
  920. // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
  921. switch (avctx->pix_fmt) {
  922. case AV_PIX_FMT_RGBA:
  923. foreground_alpha = foreground[3];
  924. background_alpha = background[3];
  925. break;
  926. case AV_PIX_FMT_GRAY8A:
  927. foreground_alpha = foreground[1];
  928. background_alpha = background[1];
  929. break;
  930. case AV_PIX_FMT_PAL8:
  931. foreground_alpha = s->palette[foreground[0]] >> 24;
  932. background_alpha = s->palette[background[0]] >> 24;
  933. break;
  934. }
  935. if (foreground_alpha == 0)
  936. continue;
  937. if (foreground_alpha == 255) {
  938. memcpy(background, foreground, s->bpp);
  939. continue;
  940. }
  941. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  942. // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
  943. avpriv_request_sample(avctx, "Alpha blending palette samples");
  944. background[0] = foreground[0];
  945. continue;
  946. }
  947. output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
  948. av_assert0(s->bpp <= 10);
  949. for (b = 0; b < s->bpp - 1; ++b) {
  950. if (output_alpha == 0) {
  951. output[b] = 0;
  952. } else if (background_alpha == 255) {
  953. output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
  954. } else {
  955. output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
  956. }
  957. }
  958. output[b] = output_alpha;
  959. memcpy(background, output, s->bpp);
  960. }
  961. }
  962. }
  963. // Copy blended buffer into the frame and free
  964. memcpy(p->data[0], buffer, s->image_linesize * s->height);
  965. av_free(buffer);
  966. return 0;
  967. }
  968. static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
  969. AVFrame *p, AVPacket *avpkt)
  970. {
  971. AVDictionary *metadata = NULL;
  972. uint32_t tag, length;
  973. int decode_next_dat = 0;
  974. int ret;
  975. for (;;) {
  976. length = bytestream2_get_bytes_left(&s->gb);
  977. if (length <= 0) {
  978. if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
  979. if (!(s->state & PNG_IDAT))
  980. return 0;
  981. else
  982. goto exit_loop;
  983. }
  984. av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
  985. if ( s->state & PNG_ALLIMAGE
  986. && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
  987. goto exit_loop;
  988. ret = AVERROR_INVALIDDATA;
  989. goto fail;
  990. }
  991. length = bytestream2_get_be32(&s->gb);
  992. if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
  993. av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
  994. ret = AVERROR_INVALIDDATA;
  995. goto fail;
  996. }
  997. tag = bytestream2_get_le32(&s->gb);
  998. if (avctx->debug & FF_DEBUG_STARTCODE)
  999. av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
  1000. (tag & 0xff),
  1001. ((tag >> 8) & 0xff),
  1002. ((tag >> 16) & 0xff),
  1003. ((tag >> 24) & 0xff), length);
  1004. switch (tag) {
  1005. case MKTAG('I', 'H', 'D', 'R'):
  1006. if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
  1007. goto fail;
  1008. break;
  1009. case MKTAG('p', 'H', 'Y', 's'):
  1010. if ((ret = decode_phys_chunk(avctx, s)) < 0)
  1011. goto fail;
  1012. break;
  1013. case MKTAG('f', 'c', 'T', 'L'):
  1014. if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
  1015. goto skip_tag;
  1016. if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
  1017. goto fail;
  1018. decode_next_dat = 1;
  1019. break;
  1020. case MKTAG('f', 'd', 'A', 'T'):
  1021. if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
  1022. goto skip_tag;
  1023. if (!decode_next_dat) {
  1024. ret = AVERROR_INVALIDDATA;
  1025. goto fail;
  1026. }
  1027. bytestream2_get_be32(&s->gb);
  1028. length -= 4;
  1029. /* fallthrough */
  1030. case MKTAG('I', 'D', 'A', 'T'):
  1031. if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
  1032. goto skip_tag;
  1033. if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
  1034. goto fail;
  1035. break;
  1036. case MKTAG('P', 'L', 'T', 'E'):
  1037. if (decode_plte_chunk(avctx, s, length) < 0)
  1038. goto skip_tag;
  1039. break;
  1040. case MKTAG('t', 'R', 'N', 'S'):
  1041. if (decode_trns_chunk(avctx, s, length) < 0)
  1042. goto skip_tag;
  1043. break;
  1044. case MKTAG('t', 'E', 'X', 't'):
  1045. if (decode_text_chunk(s, length, 0, &metadata) < 0)
  1046. av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
  1047. bytestream2_skip(&s->gb, length + 4);
  1048. break;
  1049. case MKTAG('z', 'T', 'X', 't'):
  1050. if (decode_text_chunk(s, length, 1, &metadata) < 0)
  1051. av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
  1052. bytestream2_skip(&s->gb, length + 4);
  1053. break;
  1054. case MKTAG('I', 'E', 'N', 'D'):
  1055. if (!(s->state & PNG_ALLIMAGE))
  1056. av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
  1057. if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
  1058. ret = AVERROR_INVALIDDATA;
  1059. goto fail;
  1060. }
  1061. bytestream2_skip(&s->gb, 4); /* crc */
  1062. goto exit_loop;
  1063. default:
  1064. /* skip tag */
  1065. skip_tag:
  1066. bytestream2_skip(&s->gb, length + 4);
  1067. break;
  1068. }
  1069. }
  1070. exit_loop:
  1071. if (s->bits_per_pixel <= 4)
  1072. handle_small_bpp(s, p);
  1073. /* apply transparency if needed */
  1074. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  1075. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  1076. size_t raw_bpp = s->bpp - byte_depth;
  1077. unsigned x, y;
  1078. for (y = 0; y < s->height; ++y) {
  1079. uint8_t *row = &s->image_buf[s->image_linesize * y];
  1080. /* since we're updating in-place, we have to go from right to left */
  1081. for (x = s->width; x > 0; --x) {
  1082. uint8_t *pixel = &row[s->bpp * (x - 1)];
  1083. memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
  1084. if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
  1085. memset(&pixel[raw_bpp], 0, byte_depth);
  1086. } else {
  1087. memset(&pixel[raw_bpp], 0xff, byte_depth);
  1088. }
  1089. }
  1090. }
  1091. }
  1092. /* handle p-frames only if a predecessor frame is available */
  1093. if (s->last_picture.f->data[0]) {
  1094. if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
  1095. && s->last_picture.f->width == p->width
  1096. && s->last_picture.f->height== p->height
  1097. && s->last_picture.f->format== p->format
  1098. ) {
  1099. if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
  1100. handle_p_frame_png(s, p);
  1101. else if (CONFIG_APNG_DECODER &&
  1102. avctx->codec_id == AV_CODEC_ID_APNG &&
  1103. (ret = handle_p_frame_apng(avctx, s, p)) < 0)
  1104. goto fail;
  1105. }
  1106. }
  1107. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  1108. av_frame_set_metadata(p, metadata);
  1109. metadata = NULL;
  1110. return 0;
  1111. fail:
  1112. av_dict_free(&metadata);
  1113. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  1114. return ret;
  1115. }
  1116. #if CONFIG_PNG_DECODER
  1117. static int decode_frame_png(AVCodecContext *avctx,
  1118. void *data, int *got_frame,
  1119. AVPacket *avpkt)
  1120. {
  1121. PNGDecContext *const s = avctx->priv_data;
  1122. const uint8_t *buf = avpkt->data;
  1123. int buf_size = avpkt->size;
  1124. AVFrame *p;
  1125. int64_t sig;
  1126. int ret;
  1127. ff_thread_release_buffer(avctx, &s->last_picture);
  1128. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  1129. p = s->picture.f;
  1130. bytestream2_init(&s->gb, buf, buf_size);
  1131. /* check signature */
  1132. sig = bytestream2_get_be64(&s->gb);
  1133. if (sig != PNGSIG &&
  1134. sig != MNGSIG) {
  1135. av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
  1136. return AVERROR_INVALIDDATA;
  1137. }
  1138. s->y = s->state = s->has_trns = 0;
  1139. /* init the zlib */
  1140. s->zstream.zalloc = ff_png_zalloc;
  1141. s->zstream.zfree = ff_png_zfree;
  1142. s->zstream.opaque = NULL;
  1143. ret = inflateInit(&s->zstream);
  1144. if (ret != Z_OK) {
  1145. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  1146. return AVERROR_EXTERNAL;
  1147. }
  1148. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1149. goto the_end;
  1150. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  1151. return ret;
  1152. *got_frame = 1;
  1153. ret = bytestream2_tell(&s->gb);
  1154. the_end:
  1155. inflateEnd(&s->zstream);
  1156. s->crow_buf = NULL;
  1157. return ret;
  1158. }
  1159. #endif
  1160. #if CONFIG_APNG_DECODER
  1161. static int decode_frame_apng(AVCodecContext *avctx,
  1162. void *data, int *got_frame,
  1163. AVPacket *avpkt)
  1164. {
  1165. PNGDecContext *const s = avctx->priv_data;
  1166. int ret;
  1167. AVFrame *p;
  1168. ff_thread_release_buffer(avctx, &s->last_picture);
  1169. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  1170. p = s->picture.f;
  1171. if (!(s->state & PNG_IHDR)) {
  1172. if (!avctx->extradata_size)
  1173. return AVERROR_INVALIDDATA;
  1174. /* only init fields, there is no zlib use in extradata */
  1175. s->zstream.zalloc = ff_png_zalloc;
  1176. s->zstream.zfree = ff_png_zfree;
  1177. bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
  1178. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1179. goto end;
  1180. }
  1181. /* reset state for a new frame */
  1182. if ((ret = inflateInit(&s->zstream)) != Z_OK) {
  1183. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  1184. ret = AVERROR_EXTERNAL;
  1185. goto end;
  1186. }
  1187. s->y = 0;
  1188. s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
  1189. bytestream2_init(&s->gb, avpkt->data, avpkt->size);
  1190. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1191. goto end;
  1192. if (!(s->state & PNG_ALLIMAGE))
  1193. av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
  1194. if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
  1195. ret = AVERROR_INVALIDDATA;
  1196. goto end;
  1197. }
  1198. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  1199. goto end;
  1200. *got_frame = 1;
  1201. ret = bytestream2_tell(&s->gb);
  1202. end:
  1203. inflateEnd(&s->zstream);
  1204. return ret;
  1205. }
  1206. #endif
  1207. static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  1208. {
  1209. PNGDecContext *psrc = src->priv_data;
  1210. PNGDecContext *pdst = dst->priv_data;
  1211. int ret;
  1212. if (dst == src)
  1213. return 0;
  1214. ff_thread_release_buffer(dst, &pdst->picture);
  1215. if (psrc->picture.f->data[0] &&
  1216. (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
  1217. return ret;
  1218. if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
  1219. pdst->width = psrc->width;
  1220. pdst->height = psrc->height;
  1221. pdst->bit_depth = psrc->bit_depth;
  1222. pdst->color_type = psrc->color_type;
  1223. pdst->compression_type = psrc->compression_type;
  1224. pdst->interlace_type = psrc->interlace_type;
  1225. pdst->filter_type = psrc->filter_type;
  1226. pdst->cur_w = psrc->cur_w;
  1227. pdst->cur_h = psrc->cur_h;
  1228. pdst->x_offset = psrc->x_offset;
  1229. pdst->y_offset = psrc->y_offset;
  1230. pdst->has_trns = psrc->has_trns;
  1231. memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
  1232. pdst->dispose_op = psrc->dispose_op;
  1233. memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
  1234. pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
  1235. ff_thread_release_buffer(dst, &pdst->last_picture);
  1236. if (psrc->last_picture.f->data[0] &&
  1237. (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
  1238. return ret;
  1239. ff_thread_release_buffer(dst, &pdst->previous_picture);
  1240. if (psrc->previous_picture.f->data[0] &&
  1241. (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
  1242. return ret;
  1243. }
  1244. return 0;
  1245. }
  1246. static av_cold int png_dec_init(AVCodecContext *avctx)
  1247. {
  1248. PNGDecContext *s = avctx->priv_data;
  1249. avctx->color_range = AVCOL_RANGE_JPEG;
  1250. s->avctx = avctx;
  1251. s->previous_picture.f = av_frame_alloc();
  1252. s->last_picture.f = av_frame_alloc();
  1253. s->picture.f = av_frame_alloc();
  1254. if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
  1255. av_frame_free(&s->previous_picture.f);
  1256. av_frame_free(&s->last_picture.f);
  1257. av_frame_free(&s->picture.f);
  1258. return AVERROR(ENOMEM);
  1259. }
  1260. if (!avctx->internal->is_copy) {
  1261. avctx->internal->allocate_progress = 1;
  1262. ff_pngdsp_init(&s->dsp);
  1263. }
  1264. return 0;
  1265. }
  1266. static av_cold int png_dec_end(AVCodecContext *avctx)
  1267. {
  1268. PNGDecContext *s = avctx->priv_data;
  1269. ff_thread_release_buffer(avctx, &s->previous_picture);
  1270. av_frame_free(&s->previous_picture.f);
  1271. ff_thread_release_buffer(avctx, &s->last_picture);
  1272. av_frame_free(&s->last_picture.f);
  1273. ff_thread_release_buffer(avctx, &s->picture);
  1274. av_frame_free(&s->picture.f);
  1275. av_freep(&s->buffer);
  1276. s->buffer_size = 0;
  1277. av_freep(&s->last_row);
  1278. s->last_row_size = 0;
  1279. av_freep(&s->tmp_row);
  1280. s->tmp_row_size = 0;
  1281. return 0;
  1282. }
  1283. #if CONFIG_APNG_DECODER
  1284. AVCodec ff_apng_decoder = {
  1285. .name = "apng",
  1286. .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
  1287. .type = AVMEDIA_TYPE_VIDEO,
  1288. .id = AV_CODEC_ID_APNG,
  1289. .priv_data_size = sizeof(PNGDecContext),
  1290. .init = png_dec_init,
  1291. .close = png_dec_end,
  1292. .decode = decode_frame_apng,
  1293. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  1294. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1295. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
  1296. };
  1297. #endif
  1298. #if CONFIG_PNG_DECODER
  1299. AVCodec ff_png_decoder = {
  1300. .name = "png",
  1301. .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
  1302. .type = AVMEDIA_TYPE_VIDEO,
  1303. .id = AV_CODEC_ID_PNG,
  1304. .priv_data_size = sizeof(PNGDecContext),
  1305. .init = png_dec_init,
  1306. .close = png_dec_end,
  1307. .decode = decode_frame_png,
  1308. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  1309. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1310. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
  1311. };
  1312. #endif