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.

1613 lines
55KB

  1. /*
  2. * PNG image format
  3. * Copyright (c) 2003 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. //#define DEBUG
  22. #include "libavutil/avassert.h"
  23. #include "libavutil/bprint.h"
  24. #include "libavutil/imgutils.h"
  25. #include "libavutil/stereo3d.h"
  26. #include "avcodec.h"
  27. #include "bytestream.h"
  28. #include "internal.h"
  29. #include "apng.h"
  30. #include "png.h"
  31. #include "pngdsp.h"
  32. #include "thread.h"
  33. #include <zlib.h>
  34. enum PNGHeaderState {
  35. PNG_IHDR = 1 << 0,
  36. PNG_PLTE = 1 << 1,
  37. };
  38. enum PNGImageState {
  39. PNG_IDAT = 1 << 0,
  40. PNG_ALLIMAGE = 1 << 1,
  41. };
  42. typedef struct PNGDecContext {
  43. PNGDSPContext dsp;
  44. AVCodecContext *avctx;
  45. GetByteContext gb;
  46. ThreadFrame previous_picture;
  47. ThreadFrame last_picture;
  48. ThreadFrame picture;
  49. enum PNGHeaderState hdr_state;
  50. enum PNGImageState pic_state;
  51. int width, height;
  52. int cur_w, cur_h;
  53. int last_w, last_h;
  54. int x_offset, y_offset;
  55. int last_x_offset, last_y_offset;
  56. uint8_t dispose_op, blend_op;
  57. uint8_t last_dispose_op;
  58. int bit_depth;
  59. int color_type;
  60. int compression_type;
  61. int interlace_type;
  62. int filter_type;
  63. int channels;
  64. int bits_per_pixel;
  65. int bpp;
  66. int has_trns;
  67. uint8_t transparent_color_be[6];
  68. uint8_t *image_buf;
  69. int image_linesize;
  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. static void 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. /* process exactly one decompressed row */
  293. static void png_handle_row(PNGDecContext *s)
  294. {
  295. uint8_t *ptr, *last_row;
  296. int got_line;
  297. if (!s->interlace_type) {
  298. ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
  299. if (s->y == 0)
  300. last_row = s->last_row;
  301. else
  302. last_row = ptr - s->image_linesize;
  303. png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
  304. last_row, s->row_size, s->bpp);
  305. /* loco lags by 1 row so that it doesn't interfere with top prediction */
  306. if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
  307. if (s->bit_depth == 16) {
  308. deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
  309. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  310. } else {
  311. deloco_rgb8(ptr - s->image_linesize, s->row_size,
  312. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  313. }
  314. }
  315. s->y++;
  316. if (s->y == s->cur_h) {
  317. s->pic_state |= PNG_ALLIMAGE;
  318. if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
  319. if (s->bit_depth == 16) {
  320. deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
  321. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  322. } else {
  323. deloco_rgb8(ptr, s->row_size,
  324. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  325. }
  326. }
  327. }
  328. } else {
  329. got_line = 0;
  330. for (;;) {
  331. ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
  332. if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
  333. /* if we already read one row, it is time to stop to
  334. * wait for the next one */
  335. if (got_line)
  336. break;
  337. png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
  338. s->last_row, s->pass_row_size, s->bpp);
  339. FFSWAP(uint8_t *, s->last_row, s->tmp_row);
  340. FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
  341. got_line = 1;
  342. }
  343. if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
  344. png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
  345. s->color_type, s->last_row);
  346. }
  347. s->y++;
  348. if (s->y == s->cur_h) {
  349. memset(s->last_row, 0, s->row_size);
  350. for (;;) {
  351. if (s->pass == NB_PASSES - 1) {
  352. s->pic_state |= PNG_ALLIMAGE;
  353. goto the_end;
  354. } else {
  355. s->pass++;
  356. s->y = 0;
  357. s->pass_row_size = ff_png_pass_row_size(s->pass,
  358. s->bits_per_pixel,
  359. s->cur_w);
  360. s->crow_size = s->pass_row_size + 1;
  361. if (s->pass_row_size != 0)
  362. break;
  363. /* skip pass if empty row */
  364. }
  365. }
  366. }
  367. }
  368. the_end:;
  369. }
  370. }
  371. static int png_decode_idat(PNGDecContext *s, int length)
  372. {
  373. int ret;
  374. s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
  375. s->zstream.next_in = (unsigned char *)s->gb.buffer;
  376. bytestream2_skip(&s->gb, length);
  377. /* decode one line if possible */
  378. while (s->zstream.avail_in > 0) {
  379. ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
  380. if (ret != Z_OK && ret != Z_STREAM_END) {
  381. av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
  382. return AVERROR_EXTERNAL;
  383. }
  384. if (s->zstream.avail_out == 0) {
  385. if (!(s->pic_state & PNG_ALLIMAGE)) {
  386. png_handle_row(s);
  387. }
  388. s->zstream.avail_out = s->crow_size;
  389. s->zstream.next_out = s->crow_buf;
  390. }
  391. if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
  392. av_log(NULL, AV_LOG_WARNING,
  393. "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
  394. return 0;
  395. }
  396. }
  397. return 0;
  398. }
  399. static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
  400. const uint8_t *data_end)
  401. {
  402. z_stream zstream;
  403. unsigned char *buf;
  404. unsigned buf_size;
  405. int ret;
  406. zstream.zalloc = ff_png_zalloc;
  407. zstream.zfree = ff_png_zfree;
  408. zstream.opaque = NULL;
  409. if (inflateInit(&zstream) != Z_OK)
  410. return AVERROR_EXTERNAL;
  411. zstream.next_in = (unsigned char *)data;
  412. zstream.avail_in = data_end - data;
  413. av_bprint_init(bp, 0, -1);
  414. while (zstream.avail_in > 0) {
  415. av_bprint_get_buffer(bp, 2, &buf, &buf_size);
  416. if (buf_size < 2) {
  417. ret = AVERROR(ENOMEM);
  418. goto fail;
  419. }
  420. zstream.next_out = buf;
  421. zstream.avail_out = buf_size - 1;
  422. ret = inflate(&zstream, Z_PARTIAL_FLUSH);
  423. if (ret != Z_OK && ret != Z_STREAM_END) {
  424. ret = AVERROR_EXTERNAL;
  425. goto fail;
  426. }
  427. bp->len += zstream.next_out - buf;
  428. if (ret == Z_STREAM_END)
  429. break;
  430. }
  431. inflateEnd(&zstream);
  432. bp->str[bp->len] = 0;
  433. return 0;
  434. fail:
  435. inflateEnd(&zstream);
  436. av_bprint_finalize(bp, NULL);
  437. return ret;
  438. }
  439. static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
  440. {
  441. size_t extra = 0, i;
  442. uint8_t *out, *q;
  443. for (i = 0; i < size_in; i++)
  444. extra += in[i] >= 0x80;
  445. if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
  446. return NULL;
  447. q = out = av_malloc(size_in + extra + 1);
  448. if (!out)
  449. return NULL;
  450. for (i = 0; i < size_in; i++) {
  451. if (in[i] >= 0x80) {
  452. *(q++) = 0xC0 | (in[i] >> 6);
  453. *(q++) = 0x80 | (in[i] & 0x3F);
  454. } else {
  455. *(q++) = in[i];
  456. }
  457. }
  458. *(q++) = 0;
  459. return out;
  460. }
  461. static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
  462. AVDictionary **dict)
  463. {
  464. int ret, method;
  465. const uint8_t *data = s->gb.buffer;
  466. const uint8_t *data_end = data + length;
  467. const uint8_t *keyword = data;
  468. const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
  469. uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
  470. unsigned text_len;
  471. AVBPrint bp;
  472. if (!keyword_end)
  473. return AVERROR_INVALIDDATA;
  474. data = keyword_end + 1;
  475. if (compressed) {
  476. if (data == data_end)
  477. return AVERROR_INVALIDDATA;
  478. method = *(data++);
  479. if (method)
  480. return AVERROR_INVALIDDATA;
  481. if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
  482. return ret;
  483. text_len = bp.len;
  484. av_bprint_finalize(&bp, (char **)&text);
  485. if (!text)
  486. return AVERROR(ENOMEM);
  487. } else {
  488. text = (uint8_t *)data;
  489. text_len = data_end - text;
  490. }
  491. kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
  492. txt_utf8 = iso88591_to_utf8(text, text_len);
  493. if (text != data)
  494. av_free(text);
  495. if (!(kw_utf8 && txt_utf8)) {
  496. av_free(kw_utf8);
  497. av_free(txt_utf8);
  498. return AVERROR(ENOMEM);
  499. }
  500. av_dict_set(dict, kw_utf8, txt_utf8,
  501. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  502. return 0;
  503. }
  504. static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
  505. uint32_t length)
  506. {
  507. if (length != 13)
  508. return AVERROR_INVALIDDATA;
  509. if (s->pic_state & PNG_IDAT) {
  510. av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
  511. return AVERROR_INVALIDDATA;
  512. }
  513. if (s->hdr_state & PNG_IHDR) {
  514. av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
  515. return AVERROR_INVALIDDATA;
  516. }
  517. s->width = s->cur_w = bytestream2_get_be32(&s->gb);
  518. s->height = s->cur_h = bytestream2_get_be32(&s->gb);
  519. if (av_image_check_size(s->width, s->height, 0, avctx)) {
  520. s->cur_w = s->cur_h = s->width = s->height = 0;
  521. av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
  522. return AVERROR_INVALIDDATA;
  523. }
  524. s->bit_depth = bytestream2_get_byte(&s->gb);
  525. if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
  526. s->bit_depth != 8 && s->bit_depth != 16) {
  527. av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
  528. goto error;
  529. }
  530. s->color_type = bytestream2_get_byte(&s->gb);
  531. s->compression_type = bytestream2_get_byte(&s->gb);
  532. s->filter_type = bytestream2_get_byte(&s->gb);
  533. s->interlace_type = bytestream2_get_byte(&s->gb);
  534. bytestream2_skip(&s->gb, 4); /* crc */
  535. s->hdr_state |= PNG_IHDR;
  536. if (avctx->debug & FF_DEBUG_PICT_INFO)
  537. av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
  538. "compression_type=%d filter_type=%d interlace_type=%d\n",
  539. s->width, s->height, s->bit_depth, s->color_type,
  540. s->compression_type, s->filter_type, s->interlace_type);
  541. return 0;
  542. error:
  543. s->cur_w = s->cur_h = s->width = s->height = 0;
  544. s->bit_depth = 8;
  545. return AVERROR_INVALIDDATA;
  546. }
  547. static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
  548. {
  549. if (s->pic_state & PNG_IDAT) {
  550. av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
  551. return AVERROR_INVALIDDATA;
  552. }
  553. avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
  554. avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
  555. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
  556. avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
  557. bytestream2_skip(&s->gb, 1); /* unit specifier */
  558. bytestream2_skip(&s->gb, 4); /* crc */
  559. return 0;
  560. }
  561. static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
  562. uint32_t length, AVFrame *p)
  563. {
  564. int ret;
  565. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  566. if (!(s->hdr_state & PNG_IHDR)) {
  567. av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
  568. return AVERROR_INVALIDDATA;
  569. }
  570. if (!(s->pic_state & PNG_IDAT)) {
  571. /* init image info */
  572. ret = ff_set_dimensions(avctx, s->width, s->height);
  573. if (ret < 0)
  574. return ret;
  575. s->channels = ff_png_get_nb_channels(s->color_type);
  576. s->bits_per_pixel = s->bit_depth * s->channels;
  577. s->bpp = (s->bits_per_pixel + 7) >> 3;
  578. s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
  579. if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  580. s->color_type == PNG_COLOR_TYPE_RGB) {
  581. avctx->pix_fmt = AV_PIX_FMT_RGB24;
  582. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  583. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  584. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  585. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  586. s->color_type == PNG_COLOR_TYPE_GRAY) {
  587. avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  588. } else if (s->bit_depth == 16 &&
  589. s->color_type == PNG_COLOR_TYPE_GRAY) {
  590. avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
  591. } else if (s->bit_depth == 16 &&
  592. s->color_type == PNG_COLOR_TYPE_RGB) {
  593. avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
  594. } else if (s->bit_depth == 16 &&
  595. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  596. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  597. } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
  598. s->color_type == PNG_COLOR_TYPE_PALETTE) {
  599. avctx->pix_fmt = AV_PIX_FMT_PAL8;
  600. } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
  601. avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
  602. } else if (s->bit_depth == 8 &&
  603. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  604. avctx->pix_fmt = AV_PIX_FMT_YA8;
  605. } else if (s->bit_depth == 16 &&
  606. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  607. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  608. } else {
  609. av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
  610. "and color type %d\n",
  611. s->bit_depth, s->color_type);
  612. return AVERROR_INVALIDDATA;
  613. }
  614. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  615. switch (avctx->pix_fmt) {
  616. case AV_PIX_FMT_RGB24:
  617. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  618. break;
  619. case AV_PIX_FMT_RGB48BE:
  620. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  621. break;
  622. case AV_PIX_FMT_GRAY8:
  623. avctx->pix_fmt = AV_PIX_FMT_YA8;
  624. break;
  625. case AV_PIX_FMT_GRAY16BE:
  626. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  627. break;
  628. default:
  629. avpriv_request_sample(avctx, "bit depth %d "
  630. "and color type %d with TRNS",
  631. s->bit_depth, s->color_type);
  632. return AVERROR_INVALIDDATA;
  633. }
  634. s->bpp += byte_depth;
  635. }
  636. if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  637. return ret;
  638. if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
  639. ff_thread_release_buffer(avctx, &s->previous_picture);
  640. if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  641. return ret;
  642. }
  643. p->pict_type = AV_PICTURE_TYPE_I;
  644. p->key_frame = 1;
  645. p->interlaced_frame = !!s->interlace_type;
  646. ff_thread_finish_setup(avctx);
  647. /* compute the compressed row size */
  648. if (!s->interlace_type) {
  649. s->crow_size = s->row_size + 1;
  650. } else {
  651. s->pass = 0;
  652. s->pass_row_size = ff_png_pass_row_size(s->pass,
  653. s->bits_per_pixel,
  654. s->cur_w);
  655. s->crow_size = s->pass_row_size + 1;
  656. }
  657. ff_dlog(avctx, "row_size=%d crow_size =%d\n",
  658. s->row_size, s->crow_size);
  659. s->image_buf = p->data[0];
  660. s->image_linesize = p->linesize[0];
  661. /* copy the palette if needed */
  662. if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
  663. memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
  664. /* empty row is used if differencing to the first row */
  665. av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
  666. if (!s->last_row)
  667. return AVERROR_INVALIDDATA;
  668. if (s->interlace_type ||
  669. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  670. av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
  671. if (!s->tmp_row)
  672. return AVERROR_INVALIDDATA;
  673. }
  674. /* compressed row */
  675. av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
  676. if (!s->buffer)
  677. return AVERROR(ENOMEM);
  678. /* we want crow_buf+1 to be 16-byte aligned */
  679. s->crow_buf = s->buffer + 15;
  680. s->zstream.avail_out = s->crow_size;
  681. s->zstream.next_out = s->crow_buf;
  682. }
  683. s->pic_state |= PNG_IDAT;
  684. /* set image to non-transparent bpp while decompressing */
  685. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  686. s->bpp -= byte_depth;
  687. ret = png_decode_idat(s, length);
  688. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
  689. s->bpp += byte_depth;
  690. if (ret < 0)
  691. return ret;
  692. bytestream2_skip(&s->gb, 4); /* crc */
  693. return 0;
  694. }
  695. static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
  696. uint32_t length)
  697. {
  698. int n, i, r, g, b;
  699. if ((length % 3) != 0 || length > 256 * 3)
  700. return AVERROR_INVALIDDATA;
  701. /* read the palette */
  702. n = length / 3;
  703. for (i = 0; i < n; i++) {
  704. r = bytestream2_get_byte(&s->gb);
  705. g = bytestream2_get_byte(&s->gb);
  706. b = bytestream2_get_byte(&s->gb);
  707. s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
  708. }
  709. for (; i < 256; i++)
  710. s->palette[i] = (0xFFU << 24);
  711. s->hdr_state |= PNG_PLTE;
  712. bytestream2_skip(&s->gb, 4); /* crc */
  713. return 0;
  714. }
  715. static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
  716. uint32_t length)
  717. {
  718. int v, i;
  719. if (!(s->hdr_state & PNG_IHDR)) {
  720. av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
  721. return AVERROR_INVALIDDATA;
  722. }
  723. if (s->pic_state & PNG_IDAT) {
  724. av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
  725. return AVERROR_INVALIDDATA;
  726. }
  727. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  728. if (length > 256 || !(s->hdr_state & PNG_PLTE))
  729. return AVERROR_INVALIDDATA;
  730. for (i = 0; i < length; i++) {
  731. unsigned v = bytestream2_get_byte(&s->gb);
  732. s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
  733. }
  734. } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
  735. if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
  736. (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
  737. s->bit_depth == 1)
  738. return AVERROR_INVALIDDATA;
  739. for (i = 0; i < length / 2; i++) {
  740. /* only use the least significant bits */
  741. v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
  742. if (s->bit_depth > 8)
  743. AV_WB16(&s->transparent_color_be[2 * i], v);
  744. else
  745. s->transparent_color_be[i] = v;
  746. }
  747. } else {
  748. return AVERROR_INVALIDDATA;
  749. }
  750. bytestream2_skip(&s->gb, 4); /* crc */
  751. s->has_trns = 1;
  752. return 0;
  753. }
  754. static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
  755. {
  756. int ret, cnt = 0;
  757. uint8_t *data, profile_name[82];
  758. AVBPrint bp;
  759. AVFrameSideData *sd;
  760. while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
  761. if (cnt > 80) {
  762. av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
  763. return AVERROR_INVALIDDATA;
  764. }
  765. length = FFMAX(length - cnt, 0);
  766. if (bytestream2_get_byte(&s->gb) != 0) {
  767. av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
  768. return AVERROR_INVALIDDATA;
  769. }
  770. length = FFMAX(length - 1, 0);
  771. if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
  772. return ret;
  773. av_bprint_finalize(&bp, (char **)&data);
  774. sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
  775. if (!sd) {
  776. av_free(data);
  777. return AVERROR(ENOMEM);
  778. }
  779. av_dict_set(&sd->metadata, "name", profile_name, 0);
  780. memcpy(sd->data, data, bp.len);
  781. av_free(data);
  782. /* ICC compressed data and CRC */
  783. bytestream2_skip(&s->gb, length + 4);
  784. return 0;
  785. }
  786. static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
  787. {
  788. if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
  789. int i, j, k;
  790. uint8_t *pd = p->data[0];
  791. for (j = 0; j < s->height; j++) {
  792. i = s->width / 8;
  793. for (k = 7; k >= 1; k--)
  794. if ((s->width&7) >= k)
  795. pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
  796. for (i--; i >= 0; i--) {
  797. pd[8*i + 7]= pd[i] & 1;
  798. pd[8*i + 6]= (pd[i]>>1) & 1;
  799. pd[8*i + 5]= (pd[i]>>2) & 1;
  800. pd[8*i + 4]= (pd[i]>>3) & 1;
  801. pd[8*i + 3]= (pd[i]>>4) & 1;
  802. pd[8*i + 2]= (pd[i]>>5) & 1;
  803. pd[8*i + 1]= (pd[i]>>6) & 1;
  804. pd[8*i + 0]= pd[i]>>7;
  805. }
  806. pd += s->image_linesize;
  807. }
  808. } else if (s->bits_per_pixel == 2) {
  809. int i, j;
  810. uint8_t *pd = p->data[0];
  811. for (j = 0; j < s->height; j++) {
  812. i = s->width / 4;
  813. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  814. if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
  815. if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
  816. if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
  817. for (i--; i >= 0; i--) {
  818. pd[4*i + 3]= pd[i] & 3;
  819. pd[4*i + 2]= (pd[i]>>2) & 3;
  820. pd[4*i + 1]= (pd[i]>>4) & 3;
  821. pd[4*i + 0]= pd[i]>>6;
  822. }
  823. } else {
  824. if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  825. if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  826. if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  827. for (i--; i >= 0; i--) {
  828. pd[4*i + 3]= ( pd[i] & 3)*0x55;
  829. pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  830. pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  831. pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  832. }
  833. }
  834. pd += s->image_linesize;
  835. }
  836. } else if (s->bits_per_pixel == 4) {
  837. int i, j;
  838. uint8_t *pd = p->data[0];
  839. for (j = 0; j < s->height; j++) {
  840. i = s->width/2;
  841. if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
  842. if (s->width&1) pd[2*i+0]= pd[i]>>4;
  843. for (i--; i >= 0; i--) {
  844. pd[2*i + 1] = pd[i] & 15;
  845. pd[2*i + 0] = pd[i] >> 4;
  846. }
  847. } else {
  848. if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
  849. for (i--; i >= 0; i--) {
  850. pd[2*i + 1] = (pd[i] & 15) * 0x11;
  851. pd[2*i + 0] = (pd[i] >> 4) * 0x11;
  852. }
  853. }
  854. pd += s->image_linesize;
  855. }
  856. }
  857. }
  858. static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
  859. uint32_t length)
  860. {
  861. uint32_t sequence_number;
  862. int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
  863. if (length != 26)
  864. return AVERROR_INVALIDDATA;
  865. if (!(s->hdr_state & PNG_IHDR)) {
  866. av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
  867. return AVERROR_INVALIDDATA;
  868. }
  869. s->last_w = s->cur_w;
  870. s->last_h = s->cur_h;
  871. s->last_x_offset = s->x_offset;
  872. s->last_y_offset = s->y_offset;
  873. s->last_dispose_op = s->dispose_op;
  874. sequence_number = bytestream2_get_be32(&s->gb);
  875. cur_w = bytestream2_get_be32(&s->gb);
  876. cur_h = bytestream2_get_be32(&s->gb);
  877. x_offset = bytestream2_get_be32(&s->gb);
  878. y_offset = bytestream2_get_be32(&s->gb);
  879. bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
  880. dispose_op = bytestream2_get_byte(&s->gb);
  881. blend_op = bytestream2_get_byte(&s->gb);
  882. bytestream2_skip(&s->gb, 4); /* crc */
  883. if (sequence_number == 0 &&
  884. (cur_w != s->width ||
  885. cur_h != s->height ||
  886. x_offset != 0 ||
  887. y_offset != 0) ||
  888. cur_w <= 0 || cur_h <= 0 ||
  889. x_offset < 0 || y_offset < 0 ||
  890. cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
  891. return AVERROR_INVALIDDATA;
  892. if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
  893. av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
  894. return AVERROR_INVALIDDATA;
  895. }
  896. if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
  897. dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
  898. // No previous frame to revert to for the first frame
  899. // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
  900. dispose_op = APNG_DISPOSE_OP_BACKGROUND;
  901. }
  902. if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
  903. avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
  904. avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
  905. avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
  906. avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
  907. avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
  908. avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
  909. )) {
  910. // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
  911. blend_op = APNG_BLEND_OP_SOURCE;
  912. }
  913. s->cur_w = cur_w;
  914. s->cur_h = cur_h;
  915. s->x_offset = x_offset;
  916. s->y_offset = y_offset;
  917. s->dispose_op = dispose_op;
  918. s->blend_op = blend_op;
  919. return 0;
  920. }
  921. static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
  922. {
  923. int i, j;
  924. uint8_t *pd = p->data[0];
  925. uint8_t *pd_last = s->last_picture.f->data[0];
  926. int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
  927. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  928. for (j = 0; j < s->height; j++) {
  929. for (i = 0; i < ls; i++)
  930. pd[i] += pd_last[i];
  931. pd += s->image_linesize;
  932. pd_last += s->image_linesize;
  933. }
  934. }
  935. // divide by 255 and round to nearest
  936. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  937. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  938. static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
  939. AVFrame *p)
  940. {
  941. size_t x, y;
  942. uint8_t *buffer;
  943. if (s->blend_op == APNG_BLEND_OP_OVER &&
  944. avctx->pix_fmt != AV_PIX_FMT_RGBA &&
  945. avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
  946. avctx->pix_fmt != AV_PIX_FMT_PAL8) {
  947. avpriv_request_sample(avctx, "Blending with pixel format %s",
  948. av_get_pix_fmt_name(avctx->pix_fmt));
  949. return AVERROR_PATCHWELCOME;
  950. }
  951. buffer = av_malloc_array(s->image_linesize, s->height);
  952. if (!buffer)
  953. return AVERROR(ENOMEM);
  954. // Do the disposal operation specified by the last frame on the frame
  955. if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
  956. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  957. memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
  958. if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
  959. for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
  960. memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
  961. memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
  962. ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
  963. } else {
  964. ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
  965. memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
  966. }
  967. // Perform blending
  968. if (s->blend_op == APNG_BLEND_OP_SOURCE) {
  969. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  970. size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
  971. memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
  972. }
  973. } else { // APNG_BLEND_OP_OVER
  974. for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
  975. uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
  976. uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
  977. for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
  978. size_t b;
  979. uint8_t foreground_alpha, background_alpha, output_alpha;
  980. uint8_t output[10];
  981. // Since we might be blending alpha onto alpha, we use the following equations:
  982. // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
  983. // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
  984. switch (avctx->pix_fmt) {
  985. case AV_PIX_FMT_RGBA:
  986. foreground_alpha = foreground[3];
  987. background_alpha = background[3];
  988. break;
  989. case AV_PIX_FMT_GRAY8A:
  990. foreground_alpha = foreground[1];
  991. background_alpha = background[1];
  992. break;
  993. case AV_PIX_FMT_PAL8:
  994. foreground_alpha = s->palette[foreground[0]] >> 24;
  995. background_alpha = s->palette[background[0]] >> 24;
  996. break;
  997. }
  998. if (foreground_alpha == 0)
  999. continue;
  1000. if (foreground_alpha == 255) {
  1001. memcpy(background, foreground, s->bpp);
  1002. continue;
  1003. }
  1004. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  1005. // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
  1006. avpriv_request_sample(avctx, "Alpha blending palette samples");
  1007. background[0] = foreground[0];
  1008. continue;
  1009. }
  1010. output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
  1011. av_assert0(s->bpp <= 10);
  1012. for (b = 0; b < s->bpp - 1; ++b) {
  1013. if (output_alpha == 0) {
  1014. output[b] = 0;
  1015. } else if (background_alpha == 255) {
  1016. output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
  1017. } else {
  1018. output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
  1019. }
  1020. }
  1021. output[b] = output_alpha;
  1022. memcpy(background, output, s->bpp);
  1023. }
  1024. }
  1025. }
  1026. // Copy blended buffer into the frame and free
  1027. memcpy(p->data[0], buffer, s->image_linesize * s->height);
  1028. av_free(buffer);
  1029. return 0;
  1030. }
  1031. static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
  1032. AVFrame *p, AVPacket *avpkt)
  1033. {
  1034. AVDictionary **metadatap = NULL;
  1035. uint32_t tag, length;
  1036. int decode_next_dat = 0;
  1037. int ret;
  1038. for (;;) {
  1039. length = bytestream2_get_bytes_left(&s->gb);
  1040. if (length <= 0) {
  1041. if (avctx->codec_id == AV_CODEC_ID_PNG &&
  1042. avctx->skip_frame == AVDISCARD_ALL) {
  1043. return 0;
  1044. }
  1045. if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
  1046. if (!(s->pic_state & PNG_IDAT))
  1047. return 0;
  1048. else
  1049. goto exit_loop;
  1050. }
  1051. av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
  1052. if ( s->pic_state & PNG_ALLIMAGE
  1053. && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
  1054. goto exit_loop;
  1055. ret = AVERROR_INVALIDDATA;
  1056. goto fail;
  1057. }
  1058. length = bytestream2_get_be32(&s->gb);
  1059. if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
  1060. av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
  1061. ret = AVERROR_INVALIDDATA;
  1062. goto fail;
  1063. }
  1064. tag = bytestream2_get_le32(&s->gb);
  1065. if (avctx->debug & FF_DEBUG_STARTCODE)
  1066. av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
  1067. av_fourcc2str(tag), length);
  1068. if (avctx->codec_id == AV_CODEC_ID_PNG &&
  1069. avctx->skip_frame == AVDISCARD_ALL) {
  1070. switch(tag) {
  1071. case MKTAG('I', 'H', 'D', 'R'):
  1072. case MKTAG('p', 'H', 'Y', 's'):
  1073. case MKTAG('t', 'E', 'X', 't'):
  1074. case MKTAG('I', 'D', 'A', 'T'):
  1075. case MKTAG('t', 'R', 'N', 'S'):
  1076. break;
  1077. default:
  1078. goto skip_tag;
  1079. }
  1080. }
  1081. metadatap = &p->metadata;
  1082. switch (tag) {
  1083. case MKTAG('I', 'H', 'D', 'R'):
  1084. if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
  1085. goto fail;
  1086. break;
  1087. case MKTAG('p', 'H', 'Y', 's'):
  1088. if ((ret = decode_phys_chunk(avctx, s)) < 0)
  1089. goto fail;
  1090. break;
  1091. case MKTAG('f', 'c', 'T', 'L'):
  1092. if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
  1093. goto skip_tag;
  1094. if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
  1095. goto fail;
  1096. decode_next_dat = 1;
  1097. break;
  1098. case MKTAG('f', 'd', 'A', 'T'):
  1099. if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
  1100. goto skip_tag;
  1101. if (!decode_next_dat) {
  1102. ret = AVERROR_INVALIDDATA;
  1103. goto fail;
  1104. }
  1105. bytestream2_get_be32(&s->gb);
  1106. length -= 4;
  1107. /* fallthrough */
  1108. case MKTAG('I', 'D', 'A', 'T'):
  1109. if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
  1110. goto skip_tag;
  1111. if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
  1112. goto fail;
  1113. break;
  1114. case MKTAG('P', 'L', 'T', 'E'):
  1115. if (decode_plte_chunk(avctx, s, length) < 0)
  1116. goto skip_tag;
  1117. break;
  1118. case MKTAG('t', 'R', 'N', 'S'):
  1119. if (decode_trns_chunk(avctx, s, length) < 0)
  1120. goto skip_tag;
  1121. break;
  1122. case MKTAG('t', 'E', 'X', 't'):
  1123. if (decode_text_chunk(s, length, 0, metadatap) < 0)
  1124. av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
  1125. bytestream2_skip(&s->gb, length + 4);
  1126. break;
  1127. case MKTAG('z', 'T', 'X', 't'):
  1128. if (decode_text_chunk(s, length, 1, metadatap) < 0)
  1129. av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
  1130. bytestream2_skip(&s->gb, length + 4);
  1131. break;
  1132. case MKTAG('s', 'T', 'E', 'R'): {
  1133. int mode = bytestream2_get_byte(&s->gb);
  1134. AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
  1135. if (!stereo3d)
  1136. goto fail;
  1137. if (mode == 0 || mode == 1) {
  1138. stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
  1139. stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
  1140. } else {
  1141. av_log(avctx, AV_LOG_WARNING,
  1142. "Unknown value in sTER chunk (%d)\n", mode);
  1143. }
  1144. bytestream2_skip(&s->gb, 4); /* crc */
  1145. break;
  1146. }
  1147. case MKTAG('i', 'C', 'C', 'P'): {
  1148. if (decode_iccp_chunk(s, length, p) < 0)
  1149. goto fail;
  1150. break;
  1151. }
  1152. case MKTAG('I', 'E', 'N', 'D'):
  1153. if (!(s->pic_state & PNG_ALLIMAGE))
  1154. av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
  1155. if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
  1156. ret = AVERROR_INVALIDDATA;
  1157. goto fail;
  1158. }
  1159. bytestream2_skip(&s->gb, 4); /* crc */
  1160. goto exit_loop;
  1161. default:
  1162. /* skip tag */
  1163. skip_tag:
  1164. bytestream2_skip(&s->gb, length + 4);
  1165. break;
  1166. }
  1167. }
  1168. exit_loop:
  1169. if (avctx->codec_id == AV_CODEC_ID_PNG &&
  1170. avctx->skip_frame == AVDISCARD_ALL) {
  1171. return 0;
  1172. }
  1173. if (s->bits_per_pixel <= 4)
  1174. handle_small_bpp(s, p);
  1175. /* apply transparency if needed */
  1176. if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
  1177. size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
  1178. size_t raw_bpp = s->bpp - byte_depth;
  1179. unsigned x, y;
  1180. av_assert0(s->bit_depth > 1);
  1181. for (y = 0; y < s->height; ++y) {
  1182. uint8_t *row = &s->image_buf[s->image_linesize * y];
  1183. /* since we're updating in-place, we have to go from right to left */
  1184. for (x = s->width; x > 0; --x) {
  1185. uint8_t *pixel = &row[s->bpp * (x - 1)];
  1186. memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
  1187. if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
  1188. memset(&pixel[raw_bpp], 0, byte_depth);
  1189. } else {
  1190. memset(&pixel[raw_bpp], 0xff, byte_depth);
  1191. }
  1192. }
  1193. }
  1194. }
  1195. /* handle P-frames only if a predecessor frame is available */
  1196. if (s->last_picture.f->data[0]) {
  1197. if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
  1198. && s->last_picture.f->width == p->width
  1199. && s->last_picture.f->height== p->height
  1200. && s->last_picture.f->format== p->format
  1201. ) {
  1202. if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
  1203. handle_p_frame_png(s, p);
  1204. else if (CONFIG_APNG_DECODER &&
  1205. avctx->codec_id == AV_CODEC_ID_APNG &&
  1206. (ret = handle_p_frame_apng(avctx, s, p)) < 0)
  1207. goto fail;
  1208. }
  1209. }
  1210. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  1211. ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
  1212. return 0;
  1213. fail:
  1214. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  1215. ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
  1216. return ret;
  1217. }
  1218. #if CONFIG_PNG_DECODER
  1219. static int decode_frame_png(AVCodecContext *avctx,
  1220. void *data, int *got_frame,
  1221. AVPacket *avpkt)
  1222. {
  1223. PNGDecContext *const s = avctx->priv_data;
  1224. const uint8_t *buf = avpkt->data;
  1225. int buf_size = avpkt->size;
  1226. AVFrame *p;
  1227. int64_t sig;
  1228. int ret;
  1229. ff_thread_release_buffer(avctx, &s->last_picture);
  1230. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  1231. p = s->picture.f;
  1232. bytestream2_init(&s->gb, buf, buf_size);
  1233. /* check signature */
  1234. sig = bytestream2_get_be64(&s->gb);
  1235. if (sig != PNGSIG &&
  1236. sig != MNGSIG) {
  1237. av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
  1238. return AVERROR_INVALIDDATA;
  1239. }
  1240. s->y = s->has_trns = 0;
  1241. s->hdr_state = 0;
  1242. s->pic_state = 0;
  1243. /* init the zlib */
  1244. s->zstream.zalloc = ff_png_zalloc;
  1245. s->zstream.zfree = ff_png_zfree;
  1246. s->zstream.opaque = NULL;
  1247. ret = inflateInit(&s->zstream);
  1248. if (ret != Z_OK) {
  1249. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  1250. return AVERROR_EXTERNAL;
  1251. }
  1252. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1253. goto the_end;
  1254. if (avctx->skip_frame == AVDISCARD_ALL) {
  1255. *got_frame = 0;
  1256. ret = bytestream2_tell(&s->gb);
  1257. goto the_end;
  1258. }
  1259. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  1260. return ret;
  1261. *got_frame = 1;
  1262. ret = bytestream2_tell(&s->gb);
  1263. the_end:
  1264. inflateEnd(&s->zstream);
  1265. s->crow_buf = NULL;
  1266. return ret;
  1267. }
  1268. #endif
  1269. #if CONFIG_APNG_DECODER
  1270. static int decode_frame_apng(AVCodecContext *avctx,
  1271. void *data, int *got_frame,
  1272. AVPacket *avpkt)
  1273. {
  1274. PNGDecContext *const s = avctx->priv_data;
  1275. int ret;
  1276. AVFrame *p;
  1277. ff_thread_release_buffer(avctx, &s->last_picture);
  1278. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  1279. p = s->picture.f;
  1280. if (!(s->hdr_state & PNG_IHDR)) {
  1281. if (!avctx->extradata_size)
  1282. return AVERROR_INVALIDDATA;
  1283. /* only init fields, there is no zlib use in extradata */
  1284. s->zstream.zalloc = ff_png_zalloc;
  1285. s->zstream.zfree = ff_png_zfree;
  1286. bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
  1287. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1288. goto end;
  1289. }
  1290. /* reset state for a new frame */
  1291. if ((ret = inflateInit(&s->zstream)) != Z_OK) {
  1292. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  1293. ret = AVERROR_EXTERNAL;
  1294. goto end;
  1295. }
  1296. s->y = 0;
  1297. s->pic_state = 0;
  1298. bytestream2_init(&s->gb, avpkt->data, avpkt->size);
  1299. if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
  1300. goto end;
  1301. if (!(s->pic_state & PNG_ALLIMAGE))
  1302. av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
  1303. if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
  1304. ret = AVERROR_INVALIDDATA;
  1305. goto end;
  1306. }
  1307. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  1308. goto end;
  1309. *got_frame = 1;
  1310. ret = bytestream2_tell(&s->gb);
  1311. end:
  1312. inflateEnd(&s->zstream);
  1313. return ret;
  1314. }
  1315. #endif
  1316. #if HAVE_THREADS
  1317. static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  1318. {
  1319. PNGDecContext *psrc = src->priv_data;
  1320. PNGDecContext *pdst = dst->priv_data;
  1321. int ret;
  1322. if (dst == src)
  1323. return 0;
  1324. ff_thread_release_buffer(dst, &pdst->picture);
  1325. if (psrc->picture.f->data[0] &&
  1326. (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
  1327. return ret;
  1328. if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
  1329. pdst->width = psrc->width;
  1330. pdst->height = psrc->height;
  1331. pdst->bit_depth = psrc->bit_depth;
  1332. pdst->color_type = psrc->color_type;
  1333. pdst->compression_type = psrc->compression_type;
  1334. pdst->interlace_type = psrc->interlace_type;
  1335. pdst->filter_type = psrc->filter_type;
  1336. pdst->cur_w = psrc->cur_w;
  1337. pdst->cur_h = psrc->cur_h;
  1338. pdst->x_offset = psrc->x_offset;
  1339. pdst->y_offset = psrc->y_offset;
  1340. pdst->has_trns = psrc->has_trns;
  1341. memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
  1342. pdst->dispose_op = psrc->dispose_op;
  1343. memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
  1344. pdst->hdr_state |= psrc->hdr_state;
  1345. ff_thread_release_buffer(dst, &pdst->last_picture);
  1346. if (psrc->last_picture.f->data[0] &&
  1347. (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
  1348. return ret;
  1349. ff_thread_release_buffer(dst, &pdst->previous_picture);
  1350. if (psrc->previous_picture.f->data[0] &&
  1351. (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
  1352. return ret;
  1353. }
  1354. return 0;
  1355. }
  1356. #endif
  1357. static av_cold int png_dec_init(AVCodecContext *avctx)
  1358. {
  1359. PNGDecContext *s = avctx->priv_data;
  1360. avctx->color_range = AVCOL_RANGE_JPEG;
  1361. s->avctx = avctx;
  1362. s->previous_picture.f = av_frame_alloc();
  1363. s->last_picture.f = av_frame_alloc();
  1364. s->picture.f = av_frame_alloc();
  1365. if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
  1366. av_frame_free(&s->previous_picture.f);
  1367. av_frame_free(&s->last_picture.f);
  1368. av_frame_free(&s->picture.f);
  1369. return AVERROR(ENOMEM);
  1370. }
  1371. if (!avctx->internal->is_copy) {
  1372. avctx->internal->allocate_progress = 1;
  1373. ff_pngdsp_init(&s->dsp);
  1374. }
  1375. return 0;
  1376. }
  1377. static av_cold int png_dec_end(AVCodecContext *avctx)
  1378. {
  1379. PNGDecContext *s = avctx->priv_data;
  1380. ff_thread_release_buffer(avctx, &s->previous_picture);
  1381. av_frame_free(&s->previous_picture.f);
  1382. ff_thread_release_buffer(avctx, &s->last_picture);
  1383. av_frame_free(&s->last_picture.f);
  1384. ff_thread_release_buffer(avctx, &s->picture);
  1385. av_frame_free(&s->picture.f);
  1386. av_freep(&s->buffer);
  1387. s->buffer_size = 0;
  1388. av_freep(&s->last_row);
  1389. s->last_row_size = 0;
  1390. av_freep(&s->tmp_row);
  1391. s->tmp_row_size = 0;
  1392. return 0;
  1393. }
  1394. #if CONFIG_APNG_DECODER
  1395. AVCodec ff_apng_decoder = {
  1396. .name = "apng",
  1397. .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
  1398. .type = AVMEDIA_TYPE_VIDEO,
  1399. .id = AV_CODEC_ID_APNG,
  1400. .priv_data_size = sizeof(PNGDecContext),
  1401. .init = png_dec_init,
  1402. .close = png_dec_end,
  1403. .decode = decode_frame_apng,
  1404. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  1405. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1406. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
  1407. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1408. };
  1409. #endif
  1410. #if CONFIG_PNG_DECODER
  1411. AVCodec ff_png_decoder = {
  1412. .name = "png",
  1413. .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
  1414. .type = AVMEDIA_TYPE_VIDEO,
  1415. .id = AV_CODEC_ID_PNG,
  1416. .priv_data_size = sizeof(PNGDecContext),
  1417. .init = png_dec_init,
  1418. .close = png_dec_end,
  1419. .decode = decode_frame_png,
  1420. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  1421. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1422. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
  1423. .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE,
  1424. };
  1425. #endif