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.

1705 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. uint32_t palette[256];
  71. uint8_t *crow_buf;
  72. uint8_t *last_row;
  73. unsigned int last_row_size;
  74. uint8_t *tmp_row;
  75. unsigned int tmp_row_size;
  76. uint8_t *buffer;
  77. int buffer_size;
  78. int pass;
  79. int crow_size; /* compressed row size (include filter type) */
  80. int row_size; /* decompressed row size */
  81. int pass_row_size; /* decompress row size of the current pass */
  82. int y;
  83. z_stream zstream;
  84. } PNGDecContext;
  85. /* Mask to determine which pixels are valid in a pass */
  86. static const uint8_t png_pass_mask[NB_PASSES] = {
  87. 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
  88. };
  89. /* Mask to determine which y pixels can be written in a pass */
  90. static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
  91. 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  92. };
  93. /* Mask to determine which pixels to overwrite while displaying */
  94. static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
  95. 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
  96. };
  97. /* NOTE: we try to construct a good looking image at each pass. width
  98. * is the original image width. We also do pixel format conversion at
  99. * this stage */
  100. static void png_put_interlaced_row(uint8_t *dst, int width,
  101. int bits_per_pixel, int pass,
  102. int color_type, const uint8_t *src)
  103. {
  104. int x, mask, dsp_mask, j, src_x, b, bpp;
  105. uint8_t *d;
  106. const uint8_t *s;
  107. mask = png_pass_mask[pass];
  108. dsp_mask = png_pass_dsp_mask[pass];
  109. switch (bits_per_pixel) {
  110. case 1:
  111. src_x = 0;
  112. for (x = 0; x < width; x++) {
  113. j = (x & 7);
  114. if ((dsp_mask << j) & 0x80) {
  115. b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
  116. dst[x >> 3] &= 0xFF7F>>j;
  117. dst[x >> 3] |= b << (7 - j);
  118. }
  119. if ((mask << j) & 0x80)
  120. src_x++;
  121. }
  122. break;
  123. case 2:
  124. src_x = 0;
  125. for (x = 0; x < width; x++) {
  126. int j2 = 2 * (x & 3);
  127. j = (x & 7);
  128. if ((dsp_mask << j) & 0x80) {
  129. b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
  130. dst[x >> 2] &= 0xFF3F>>j2;
  131. dst[x >> 2] |= b << (6 - j2);
  132. }
  133. if ((mask << j) & 0x80)
  134. src_x++;
  135. }
  136. break;
  137. case 4:
  138. src_x = 0;
  139. for (x = 0; x < width; x++) {
  140. int j2 = 4*(x&1);
  141. j = (x & 7);
  142. if ((dsp_mask << j) & 0x80) {
  143. b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
  144. dst[x >> 1] &= 0xFF0F>>j2;
  145. dst[x >> 1] |= b << (4 - j2);
  146. }
  147. if ((mask << j) & 0x80)
  148. src_x++;
  149. }
  150. break;
  151. default:
  152. bpp = bits_per_pixel >> 3;
  153. d = dst;
  154. s = src;
  155. for (x = 0; x < width; x++) {
  156. j = x & 7;
  157. if ((dsp_mask << j) & 0x80) {
  158. memcpy(d, s, bpp);
  159. }
  160. d += bpp;
  161. if ((mask << j) & 0x80)
  162. s += bpp;
  163. }
  164. break;
  165. }
  166. }
  167. void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
  168. int w, int bpp)
  169. {
  170. int i;
  171. for (i = 0; i < w; i++) {
  172. int a, b, c, p, pa, pb, pc;
  173. a = dst[i - bpp];
  174. b = top[i];
  175. c = top[i - bpp];
  176. p = b - c;
  177. pc = a - c;
  178. pa = abs(p);
  179. pb = abs(pc);
  180. pc = abs(p + pc);
  181. if (pa <= pb && pa <= pc)
  182. p = a;
  183. else if (pb <= pc)
  184. p = b;
  185. else
  186. p = c;
  187. dst[i] = p + src[i];
  188. }
  189. }
  190. #define UNROLL1(bpp, op) \
  191. { \
  192. r = dst[0]; \
  193. if (bpp >= 2) \
  194. g = dst[1]; \
  195. if (bpp >= 3) \
  196. b = dst[2]; \
  197. if (bpp >= 4) \
  198. a = dst[3]; \
  199. for (; i <= size - bpp; i += bpp) { \
  200. dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
  201. if (bpp == 1) \
  202. continue; \
  203. dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
  204. if (bpp == 2) \
  205. continue; \
  206. dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
  207. if (bpp == 3) \
  208. continue; \
  209. dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
  210. } \
  211. }
  212. #define UNROLL_FILTER(op) \
  213. if (bpp == 1) { \
  214. UNROLL1(1, op) \
  215. } else if (bpp == 2) { \
  216. UNROLL1(2, op) \
  217. } else if (bpp == 3) { \
  218. UNROLL1(3, op) \
  219. } else if (bpp == 4) { \
  220. UNROLL1(4, op) \
  221. } \
  222. for (; i < size; i++) { \
  223. dst[i] = op(dst[i - bpp], src[i], last[i]); \
  224. }
  225. /* NOTE: 'dst' can be equal to 'last' */
  226. void ff_png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
  227. uint8_t *src, uint8_t *last, int size, int bpp)
  228. {
  229. int i, p, r, g, b, a;
  230. switch (filter_type) {
  231. case PNG_FILTER_VALUE_NONE:
  232. memcpy(dst, src, size);
  233. break;
  234. case PNG_FILTER_VALUE_SUB:
  235. for (i = 0; i < bpp; i++)
  236. dst[i] = src[i];
  237. if (bpp == 4) {
  238. p = *(int *)dst;
  239. for (; i < size; i += bpp) {
  240. unsigned s = *(int *)(src + i);
  241. p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
  242. *(int *)(dst + i) = p;
  243. }
  244. } else {
  245. #define OP_SUB(x, s, l) ((x) + (s))
  246. UNROLL_FILTER(OP_SUB);
  247. }
  248. break;
  249. case PNG_FILTER_VALUE_UP:
  250. dsp->add_bytes_l2(dst, src, last, size);
  251. break;
  252. case PNG_FILTER_VALUE_AVG:
  253. for (i = 0; i < bpp; i++) {
  254. p = (last[i] >> 1);
  255. dst[i] = p + src[i];
  256. }
  257. #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
  258. UNROLL_FILTER(OP_AVG);
  259. break;
  260. case PNG_FILTER_VALUE_PAETH:
  261. for (i = 0; i < bpp; i++) {
  262. p = last[i];
  263. dst[i] = p + src[i];
  264. }
  265. if (bpp > 2 && size > 4) {
  266. /* would write off the end of the array if we let it process
  267. * the last pixel with bpp=3 */
  268. int w = (bpp & 3) ? size - 3 : size;
  269. if (w > i) {
  270. dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
  271. i = w;
  272. }
  273. }
  274. ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
  275. break;
  276. }
  277. }
  278. /* This used to be called "deloco" in FFmpeg
  279. * and is actually an inverse reversible colorspace transformation */
  280. #define YUV2RGB(NAME, TYPE) \
  281. static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
  282. { \
  283. int i; \
  284. for (i = 0; i < size; i += 3 + alpha) { \
  285. int g = dst [i + 1]; \
  286. dst[i + 0] += g; \
  287. dst[i + 2] += g; \
  288. } \
  289. }
  290. YUV2RGB(rgb8, uint8_t)
  291. YUV2RGB(rgb16, uint16_t)
  292. static int percent_missing(PNGDecContext *s)
  293. {
  294. if (s->interlace_type) {
  295. return 100 - 100 * s->pass / (NB_PASSES - 1);
  296. } else {
  297. return 100 - 100 * s->y / s->cur_h;
  298. }
  299. }
  300. /* process exactly one decompressed row */
  301. static void png_handle_row(PNGDecContext *s, uint8_t *dst, ptrdiff_t dst_stride)
  302. {
  303. uint8_t *ptr, *last_row;
  304. int got_line;
  305. if (!s->interlace_type) {
  306. ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
  307. if (s->y == 0)
  308. last_row = s->last_row;
  309. else
  310. last_row = ptr - dst_stride;
  311. ff_png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
  312. last_row, s->row_size, s->bpp);
  313. /* loco lags by 1 row so that it doesn't interfere with top prediction */
  314. if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
  315. if (s->bit_depth == 16) {
  316. deloco_rgb16((uint16_t *)(ptr - dst_stride), s->row_size / 2,
  317. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  318. } else {
  319. deloco_rgb8(ptr - dst_stride, s->row_size,
  320. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  321. }
  322. }
  323. s->y++;
  324. if (s->y == s->cur_h) {
  325. s->pic_state |= PNG_ALLIMAGE;
  326. if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
  327. if (s->bit_depth == 16) {
  328. deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
  329. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  330. } else {
  331. deloco_rgb8(ptr, s->row_size,
  332. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  333. }
  334. }
  335. }
  336. } else {
  337. got_line = 0;
  338. for (;;) {
  339. ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
  340. if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
  341. /* if we already read one row, it is time to stop to
  342. * wait for the next one */
  343. if (got_line)
  344. break;
  345. ff_png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
  346. s->last_row, s->pass_row_size, s->bpp);
  347. FFSWAP(uint8_t *, s->last_row, s->tmp_row);
  348. FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
  349. got_line = 1;
  350. }
  351. if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
  352. png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
  353. s->color_type, s->last_row);
  354. }
  355. s->y++;
  356. if (s->y == s->cur_h) {
  357. memset(s->last_row, 0, s->row_size);
  358. for (;;) {
  359. if (s->pass == NB_PASSES - 1) {
  360. s->pic_state |= PNG_ALLIMAGE;
  361. goto the_end;
  362. } else {
  363. s->pass++;
  364. s->y = 0;
  365. s->pass_row_size = ff_png_pass_row_size(s->pass,
  366. s->bits_per_pixel,
  367. s->cur_w);
  368. s->crow_size = s->pass_row_size + 1;
  369. if (s->pass_row_size != 0)
  370. break;
  371. /* skip pass if empty row */
  372. }
  373. }
  374. }
  375. }
  376. the_end:;
  377. }
  378. }
  379. static int png_decode_idat(PNGDecContext *s, int length,
  380. uint8_t *dst, ptrdiff_t dst_stride)
  381. {
  382. int ret;
  383. s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
  384. s->zstream.next_in = s->gb.buffer;
  385. bytestream2_skip(&s->gb, length);
  386. /* decode one line if possible */
  387. while (s->zstream.avail_in > 0) {
  388. ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
  389. if (ret != Z_OK && ret != Z_STREAM_END) {
  390. av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
  391. return AVERROR_EXTERNAL;
  392. }
  393. if (s->zstream.avail_out == 0) {
  394. if (!(s->pic_state & PNG_ALLIMAGE)) {
  395. png_handle_row(s, dst, dst_stride);
  396. }
  397. s->zstream.avail_out = s->crow_size;
  398. s->zstream.next_out = s->crow_buf;
  399. }
  400. if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
  401. av_log(s->avctx, AV_LOG_WARNING,
  402. "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
  403. return 0;
  404. }
  405. }
  406. return 0;
  407. }
  408. static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
  409. const uint8_t *data_end)
  410. {
  411. z_stream zstream;
  412. unsigned char *buf;
  413. unsigned buf_size;
  414. int ret;
  415. zstream.zalloc = ff_png_zalloc;
  416. zstream.zfree = ff_png_zfree;
  417. zstream.opaque = NULL;
  418. if (inflateInit(&zstream) != Z_OK)
  419. return AVERROR_EXTERNAL;
  420. zstream.next_in = data;
  421. zstream.avail_in = data_end - data;
  422. av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
  423. while (zstream.avail_in > 0) {
  424. av_bprint_get_buffer(bp, 2, &buf, &buf_size);
  425. if (buf_size < 2) {
  426. ret = AVERROR(ENOMEM);
  427. goto fail;
  428. }
  429. zstream.next_out = buf;
  430. zstream.avail_out = buf_size - 1;
  431. ret = inflate(&zstream, Z_PARTIAL_FLUSH);
  432. if (ret != Z_OK && ret != Z_STREAM_END) {
  433. ret = AVERROR_EXTERNAL;
  434. goto fail;
  435. }
  436. bp->len += zstream.next_out - buf;
  437. if (ret == Z_STREAM_END)
  438. break;
  439. }
  440. inflateEnd(&zstream);
  441. bp->str[bp->len] = 0;
  442. return 0;
  443. fail:
  444. inflateEnd(&zstream);
  445. av_bprint_finalize(bp, NULL);
  446. return ret;
  447. }
  448. static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
  449. {
  450. size_t extra = 0, i;
  451. uint8_t *out, *q;
  452. for (i = 0; i < size_in; i++)
  453. extra += in[i] >= 0x80;
  454. if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
  455. return NULL;
  456. q = out = av_malloc(size_in + extra + 1);
  457. if (!out)
  458. return NULL;
  459. for (i = 0; i < size_in; i++) {
  460. if (in[i] >= 0x80) {
  461. *(q++) = 0xC0 | (in[i] >> 6);
  462. *(q++) = 0x80 | (in[i] & 0x3F);
  463. } else {
  464. *(q++) = in[i];
  465. }
  466. }
  467. *(q++) = 0;
  468. return out;
  469. }
  470. static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
  471. AVDictionary **dict)
  472. {
  473. int ret, method;
  474. const uint8_t *data = s->gb.buffer;
  475. const uint8_t *data_end = data + length;
  476. const uint8_t *keyword = data;
  477. const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
  478. uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
  479. unsigned text_len;
  480. AVBPrint bp;
  481. if (!keyword_end)
  482. return AVERROR_INVALIDDATA;
  483. data = keyword_end + 1;
  484. if (compressed) {
  485. if (data == data_end)
  486. return AVERROR_INVALIDDATA;
  487. method = *(data++);
  488. if (method)
  489. return AVERROR_INVALIDDATA;
  490. if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
  491. return ret;
  492. text_len = bp.len;
  493. ret = av_bprint_finalize(&bp, (char **)&text);
  494. if (ret < 0)
  495. return ret;
  496. } else {
  497. text = (uint8_t *)data;
  498. text_len = data_end - text;
  499. }
  500. kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
  501. txt_utf8 = iso88591_to_utf8(text, text_len);
  502. if (text != data)
  503. av_free(text);
  504. if (!(kw_utf8 && txt_utf8)) {
  505. av_free(kw_utf8);
  506. av_free(txt_utf8);
  507. return AVERROR(ENOMEM);
  508. }
  509. av_dict_set(dict, kw_utf8, txt_utf8,
  510. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  511. return 0;
  512. }
  513. static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
  514. uint32_t length)
  515. {
  516. if (length != 13)
  517. return AVERROR_INVALIDDATA;
  518. if (s->pic_state & PNG_IDAT) {
  519. av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
  520. return AVERROR_INVALIDDATA;
  521. }
  522. if (s->hdr_state & PNG_IHDR) {
  523. av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
  524. return AVERROR_INVALIDDATA;
  525. }
  526. s->width = s->cur_w = bytestream2_get_be32(&s->gb);
  527. s->height = s->cur_h = bytestream2_get_be32(&s->gb);
  528. if (av_image_check_size(s->width, s->height, 0, avctx)) {
  529. s->cur_w = s->cur_h = s->width = s->height = 0;
  530. av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
  531. return AVERROR_INVALIDDATA;
  532. }
  533. s->bit_depth = bytestream2_get_byte(&s->gb);
  534. if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
  535. s->bit_depth != 8 && s->bit_depth != 16) {
  536. av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
  537. goto error;
  538. }
  539. s->color_type = bytestream2_get_byte(&s->gb);
  540. s->compression_type = bytestream2_get_byte(&s->gb);
  541. if (s->compression_type) {
  542. av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
  543. goto error;
  544. }
  545. s->filter_type = bytestream2_get_byte(&s->gb);
  546. s->interlace_type = bytestream2_get_byte(&s->gb);
  547. bytestream2_skip(&s->gb, 4); /* crc */
  548. s->hdr_state |= PNG_IHDR;
  549. if (avctx->debug & FF_DEBUG_PICT_INFO)
  550. av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
  551. "compression_type=%d filter_type=%d interlace_type=%d\n",
  552. s->width, s->height, s->bit_depth, s->color_type,
  553. s->compression_type, s->filter_type, s->interlace_type);
  554. return 0;
  555. error:
  556. s->cur_w = s->cur_h = s->width = s->height = 0;
  557. s->bit_depth = 8;
  558. return AVERROR_INVALIDDATA;
  559. }
  560. static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
  561. {
  562. if (s->pic_state & PNG_IDAT) {
  563. av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
  564. return AVERROR_INVALIDDATA;
  565. }
  566. avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
  567. avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
  568. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
  569. avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
  570. bytestream2_skip(&s->gb, 1); /* unit specifier */
  571. bytestream2_skip(&s->gb, 4); /* crc */
  572. return 0;
  573. }
  574. static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
  575. uint32_t length, AVFrame *p)
  576. {
  577. int ret;
  578. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  579. if (!(s->hdr_state & PNG_IHDR)) {
  580. av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
  581. return AVERROR_INVALIDDATA;
  582. }
  583. if (!(s->pic_state & PNG_IDAT)) {
  584. /* init image info */
  585. ret = ff_set_dimensions(avctx, s->width, s->height);
  586. if (ret < 0)
  587. return ret;
  588. s->channels = ff_png_get_nb_channels(s->color_type);
  589. s->bits_per_pixel = s->bit_depth * s->channels;
  590. s->bpp = (s->bits_per_pixel + 7) >> 3;
  591. s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
  592. if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  593. s->color_type == PNG_COLOR_TYPE_RGB) {
  594. avctx->pix_fmt = AV_PIX_FMT_RGB24;
  595. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  596. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  597. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  598. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  599. s->color_type == PNG_COLOR_TYPE_GRAY) {
  600. avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  601. } else if (s->bit_depth == 16 &&
  602. s->color_type == PNG_COLOR_TYPE_GRAY) {
  603. avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
  604. } else if (s->bit_depth == 16 &&
  605. s->color_type == PNG_COLOR_TYPE_RGB) {
  606. avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
  607. } else if (s->bit_depth == 16 &&
  608. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  609. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  610. } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
  611. s->color_type == PNG_COLOR_TYPE_PALETTE) {
  612. avctx->pix_fmt = AV_PIX_FMT_PAL8;
  613. } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
  614. avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
  615. } else if (s->bit_depth == 8 &&
  616. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  617. avctx->pix_fmt = AV_PIX_FMT_YA8;
  618. } else if (s->bit_depth == 16 &&
  619. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  620. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  621. } else {
  622. avpriv_report_missing_feature(avctx,
  623. "Bit depth %d color type %d",
  624. s->bit_depth, s->color_type);
  625. return AVERROR_PATCHWELCOME;
  626. }
  627. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  628. switch (avctx->pix_fmt) {
  629. case AV_PIX_FMT_RGB24:
  630. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  631. break;
  632. case AV_PIX_FMT_RGB48BE:
  633. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  634. break;
  635. case AV_PIX_FMT_GRAY8:
  636. avctx->pix_fmt = AV_PIX_FMT_YA8;
  637. break;
  638. case AV_PIX_FMT_GRAY16BE:
  639. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  640. break;
  641. default:
  642. avpriv_request_sample(avctx, "bit depth %d "
  643. "and color type %d with TRNS",
  644. s->bit_depth, s->color_type);
  645. return AVERROR_INVALIDDATA;
  646. }
  647. s->bpp += byte_depth;
  648. }
  649. ff_thread_release_buffer(avctx, &s->picture);
  650. if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  651. return ret;
  652. p->pict_type = AV_PICTURE_TYPE_I;
  653. p->key_frame = 1;
  654. p->interlaced_frame = !!s->interlace_type;
  655. ff_thread_finish_setup(avctx);
  656. /* compute the compressed row size */
  657. if (!s->interlace_type) {
  658. s->crow_size = s->row_size + 1;
  659. } else {
  660. s->pass = 0;
  661. s->pass_row_size = ff_png_pass_row_size(s->pass,
  662. s->bits_per_pixel,
  663. s->cur_w);
  664. s->crow_size = s->pass_row_size + 1;
  665. }
  666. ff_dlog(avctx, "row_size=%d crow_size =%d\n",
  667. s->row_size, s->crow_size);
  668. /* copy the palette if needed */
  669. if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
  670. memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
  671. /* empty row is used if differencing to the first row */
  672. av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
  673. if (!s->last_row)
  674. return AVERROR_INVALIDDATA;
  675. if (s->interlace_type ||
  676. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  677. av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
  678. if (!s->tmp_row)
  679. return AVERROR_INVALIDDATA;
  680. }
  681. /* compressed row */
  682. av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
  683. if (!s->buffer)
  684. return AVERROR(ENOMEM);
  685. /* we want crow_buf+1 to be 16-byte aligned */
  686. s->crow_buf = s->buffer + 15;
  687. s->zstream.avail_out = s->crow_size;
  688. s->zstream.next_out = s->crow_buf;
  689. }
  690. s->pic_state |= PNG_IDAT;
  691. /* set image to non-transparent bpp while decompressing */
  692. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  693. s->bpp -= byte_depth;
  694. ret = png_decode_idat(s, length, p->data[0], p->linesize[0]);
  695. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  696. s->bpp += byte_depth;
  697. if (ret < 0)
  698. return ret;
  699. bytestream2_skip(&s->gb, 4); /* crc */
  700. return 0;
  701. }
  702. static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
  703. uint32_t length)
  704. {
  705. int n, i, r, g, b;
  706. if ((length % 3) != 0 || length > 256 * 3)
  707. return AVERROR_INVALIDDATA;
  708. /* read the palette */
  709. n = length / 3;
  710. for (i = 0; i < n; i++) {
  711. r = bytestream2_get_byte(&s->gb);
  712. g = bytestream2_get_byte(&s->gb);
  713. b = bytestream2_get_byte(&s->gb);
  714. s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
  715. }
  716. for (; i < 256; i++)
  717. s->palette[i] = (0xFFU << 24);
  718. s->hdr_state |= PNG_PLTE;
  719. bytestream2_skip(&s->gb, 4); /* crc */
  720. return 0;
  721. }
  722. static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
  723. uint32_t length)
  724. {
  725. int v, i;
  726. if (!(s->hdr_state & PNG_IHDR)) {
  727. av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
  728. return AVERROR_INVALIDDATA;
  729. }
  730. if (s->pic_state & PNG_IDAT) {
  731. av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
  732. return AVERROR_INVALIDDATA;
  733. }
  734. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  735. if (length > 256 || !(s->hdr_state & PNG_PLTE))
  736. return AVERROR_INVALIDDATA;
  737. for (i = 0; i < length; i++) {
  738. unsigned v = bytestream2_get_byte(&s->gb);
  739. s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
  740. }
  741. } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
  742. if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
  743. (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
  744. s->bit_depth == 1)
  745. return AVERROR_INVALIDDATA;
  746. for (i = 0; i < length / 2; i++) {
  747. /* only use the least significant bits */
  748. v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
  749. if (s->bit_depth > 8)
  750. AV_WB16(&s->transparent_color_be[2 * i], v);
  751. else
  752. s->transparent_color_be[i] = v;
  753. }
  754. } else {
  755. return AVERROR_INVALIDDATA;
  756. }
  757. bytestream2_skip(&s->gb, 4); /* crc */
  758. s->has_trns = 1;
  759. return 0;
  760. }
  761. static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
  762. {
  763. int ret, cnt = 0;
  764. uint8_t *data, profile_name[82];
  765. AVBPrint bp;
  766. AVFrameSideData *sd;
  767. while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
  768. if (cnt > 80) {
  769. av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
  770. return AVERROR_INVALIDDATA;
  771. }
  772. length = FFMAX(length - cnt, 0);
  773. if (bytestream2_get_byte(&s->gb) != 0) {
  774. av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
  775. return AVERROR_INVALIDDATA;
  776. }
  777. length = FFMAX(length - 1, 0);
  778. if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
  779. return ret;
  780. ret = av_bprint_finalize(&bp, (char **)&data);
  781. if (ret < 0)
  782. return ret;
  783. sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
  784. if (!sd) {
  785. av_free(data);
  786. return AVERROR(ENOMEM);
  787. }
  788. av_dict_set(&sd->metadata, "name", profile_name, 0);
  789. memcpy(sd->data, data, bp.len);
  790. av_free(data);
  791. /* ICC compressed data and CRC */
  792. bytestream2_skip(&s->gb, length + 4);
  793. return 0;
  794. }
  795. static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
  796. {
  797. if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
  798. int i, j, k;
  799. uint8_t *pd = p->data[0];
  800. for (j = 0; j < s->height; j++) {
  801. i = s->width / 8;
  802. for (k = 7; k >= 1; k--)
  803. if ((s->width&7) >= k)
  804. pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
  805. for (i--; i >= 0; i--) {
  806. pd[8*i + 7]= pd[i] & 1;
  807. pd[8*i + 6]= (pd[i]>>1) & 1;
  808. pd[8*i + 5]= (pd[i]>>2) & 1;
  809. pd[8*i + 4]= (pd[i]>>3) & 1;
  810. pd[8*i + 3]= (pd[i]>>4) & 1;
  811. pd[8*i + 2]= (pd[i]>>5) & 1;
  812. pd[8*i + 1]= (pd[i]>>6) & 1;
  813. pd[8*i + 0]= pd[i]>>7;
  814. }
  815. pd += p->linesize[0];
  816. }
  817. } else if (s->bits_per_pixel == 2) {
  818. int i, j;
  819. uint8_t *pd = p->data[0];
  820. for (j = 0; j < s->height; j++) {
  821. i = s->width / 4;
  822. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  823. if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
  824. if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
  825. if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
  826. for (i--; i >= 0; i--) {
  827. pd[4*i + 3]= pd[i] & 3;
  828. pd[4*i + 2]= (pd[i]>>2) & 3;
  829. pd[4*i + 1]= (pd[i]>>4) & 3;
  830. pd[4*i + 0]= pd[i]>>6;
  831. }
  832. } else {
  833. if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  834. if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  835. if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  836. for (i--; i >= 0; i--) {
  837. pd[4*i + 3]= ( pd[i] & 3)*0x55;
  838. pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  839. pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  840. pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  841. }
  842. }
  843. pd += p->linesize[0];
  844. }
  845. } else if (s->bits_per_pixel == 4) {
  846. int i, j;
  847. uint8_t *pd = p->data[0];
  848. for (j = 0; j < s->height; j++) {
  849. i = s->width/2;
  850. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  851. if (s->width&1) pd[2*i+0]= pd[i]>>4;
  852. for (i--; i >= 0; i--) {
  853. pd[2*i + 1] = pd[i] & 15;
  854. pd[2*i + 0] = pd[i] >> 4;
  855. }
  856. } else {
  857. if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
  858. for (i--; i >= 0; i--) {
  859. pd[2*i + 1] = (pd[i] & 15) * 0x11;
  860. pd[2*i + 0] = (pd[i] >> 4) * 0x11;
  861. }
  862. }
  863. pd += p->linesize[0];
  864. }
  865. }
  866. }
  867. static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
  868. uint32_t length)
  869. {
  870. uint32_t sequence_number;
  871. int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
  872. if (length != 26)
  873. return AVERROR_INVALIDDATA;
  874. if (!(s->hdr_state & PNG_IHDR)) {
  875. av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
  876. return AVERROR_INVALIDDATA;
  877. }
  878. if (s->pic_state & PNG_IDAT) {
  879. av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
  880. return AVERROR_INVALIDDATA;
  881. }
  882. s->last_w = s->cur_w;
  883. s->last_h = s->cur_h;
  884. s->last_x_offset = s->x_offset;
  885. s->last_y_offset = s->y_offset;
  886. s->last_dispose_op = s->dispose_op;
  887. sequence_number = bytestream2_get_be32(&s->gb);
  888. cur_w = bytestream2_get_be32(&s->gb);
  889. cur_h = bytestream2_get_be32(&s->gb);
  890. x_offset = bytestream2_get_be32(&s->gb);
  891. y_offset = bytestream2_get_be32(&s->gb);
  892. bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
  893. dispose_op = bytestream2_get_byte(&s->gb);
  894. blend_op = bytestream2_get_byte(&s->gb);
  895. bytestream2_skip(&s->gb, 4); /* crc */
  896. if (sequence_number == 0 &&
  897. (cur_w != s->width ||
  898. cur_h != s->height ||
  899. x_offset != 0 ||
  900. y_offset != 0) ||
  901. cur_w <= 0 || cur_h <= 0 ||
  902. x_offset < 0 || y_offset < 0 ||
  903. cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
  904. return AVERROR_INVALIDDATA;
  905. if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
  906. av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
  907. return AVERROR_INVALIDDATA;
  908. }
  909. if ((sequence_number == 0 || !s->last_picture.f->data[0]) &&
  910. dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
  911. // No previous frame to revert to for the first frame
  912. // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
  913. dispose_op = APNG_DISPOSE_OP_BACKGROUND;
  914. }
  915. if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
  916. avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
  917. avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
  918. avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
  919. avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
  920. avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
  921. avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
  922. )) {
  923. // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
  924. blend_op = APNG_BLEND_OP_SOURCE;
  925. }
  926. s->cur_w = cur_w;
  927. s->cur_h = cur_h;
  928. s->x_offset = x_offset;
  929. s->y_offset = y_offset;
  930. s->dispose_op = dispose_op;
  931. s->blend_op = blend_op;
  932. return 0;
  933. }
  934. static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
  935. {
  936. int i, j;
  937. uint8_t *pd = p->data[0];
  938. uint8_t *pd_last = s->last_picture.f->data[0];
  939. int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
  940. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  941. for (j = 0; j < s->height; j++) {
  942. for (i = 0; i < ls; i++)
  943. pd[i] += pd_last[i];
  944. pd += p->linesize[0];
  945. pd_last += s->last_picture.f->linesize[0];
  946. }
  947. }
  948. // divide by 255 and round to nearest
  949. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  950. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  951. static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
  952. AVFrame *p)
  953. {
  954. uint8_t *dst = p->data[0];
  955. ptrdiff_t dst_stride = p->linesize[0];
  956. const uint8_t *src = s->last_picture.f->data[0];
  957. ptrdiff_t src_stride = s->last_picture.f->linesize[0];
  958. size_t x, y;
  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. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  968. // need to reset a rectangle to background:
  969. // create a new writable copy
  970. if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
  971. int ret = av_frame_make_writable(s->last_picture.f);
  972. if (ret < 0)
  973. return ret;
  974. src = s->last_picture.f->data[0];
  975. src_stride = s->last_picture.f->linesize[0];
  976. for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; y++) {
  977. memset(s->last_picture.f->data[0] + src_stride * y +
  978. s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
  979. }
  980. }
  981. // copy unchanged rectangles from the last frame
  982. for (y = 0; y < s->y_offset; y++)
  983. memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
  984. for (y = s->y_offset; y < s->y_offset + s->cur_h; y++) {
  985. memcpy(dst + y * dst_stride, src + y * src_stride, s->x_offset * s->bpp);
  986. memcpy(dst + y * dst_stride + (s->x_offset + s->cur_w) * s->bpp,
  987. src + y * src_stride + (s->x_offset + s->cur_w) * s->bpp,
  988. (p->width - s->cur_w - s->x_offset) * s->bpp);
  989. }
  990. for (y = s->y_offset + s->cur_h; y < p->height; y++)
  991. memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
  992. if (s->blend_op == APNG_BLEND_OP_OVER) {
  993. // Perform blending
  994. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  995. uint8_t *foreground = dst + dst_stride * y + s->bpp * s->x_offset;
  996. const uint8_t *background = src + src_stride * y + s->bpp * s->x_offset;
  997. for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
  998. size_t b;
  999. uint8_t foreground_alpha, background_alpha, output_alpha;
  1000. uint8_t output[10];
  1001. // Since we might be blending alpha onto alpha, we use the following equations:
  1002. // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
  1003. // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
  1004. switch (avctx->pix_fmt) {
  1005. case AV_PIX_FMT_RGBA:
  1006. foreground_alpha = foreground[3];
  1007. background_alpha = background[3];
  1008. break;
  1009. case AV_PIX_FMT_GRAY8A:
  1010. foreground_alpha = foreground[1];
  1011. background_alpha = background[1];
  1012. break;
  1013. case AV_PIX_FMT_PAL8:
  1014. foreground_alpha = s->palette[foreground[0]] >> 24;
  1015. background_alpha = s->palette[background[0]] >> 24;
  1016. break;
  1017. }
  1018. if (foreground_alpha == 255)
  1019. continue;
  1020. if (foreground_alpha == 0) {
  1021. memcpy(foreground, background, s->bpp);
  1022. continue;
  1023. }
  1024. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  1025. // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
  1026. avpriv_request_sample(avctx, "Alpha blending palette samples");
  1027. continue;
  1028. }
  1029. output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
  1030. av_assert0(s->bpp <= 10);
  1031. for (b = 0; b < s->bpp - 1; ++b) {
  1032. if (output_alpha == 0) {
  1033. output[b] = 0;
  1034. } else if (background_alpha == 255) {
  1035. output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
  1036. } else {
  1037. output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
  1038. }
  1039. }
  1040. output[b] = output_alpha;
  1041. memcpy(foreground, output, s->bpp);
  1042. }
  1043. }
  1044. }
  1045. return 0;
  1046. }
  1047. static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
  1048. AVFrame *p, const 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 = &p->data[0][p->linesize[0] * 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