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.

1704 lines
58KB

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