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.

1498 lines
52KB

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