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.

995 lines
34KB

  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/bprint.h"
  23. #include "libavutil/imgutils.h"
  24. #include "avcodec.h"
  25. #include "bytestream.h"
  26. #include "internal.h"
  27. #include "png.h"
  28. #include "pngdsp.h"
  29. #include "thread.h"
  30. #include <zlib.h>
  31. typedef struct PNGDecContext {
  32. PNGDSPContext dsp;
  33. AVCodecContext *avctx;
  34. GetByteContext gb;
  35. ThreadFrame last_picture;
  36. ThreadFrame picture;
  37. int state;
  38. int width, height;
  39. int bit_depth;
  40. int color_type;
  41. int compression_type;
  42. int interlace_type;
  43. int filter_type;
  44. int channels;
  45. int bits_per_pixel;
  46. int bpp;
  47. uint8_t *image_buf;
  48. int image_linesize;
  49. uint32_t palette[256];
  50. uint8_t *crow_buf;
  51. uint8_t *last_row;
  52. unsigned int last_row_size;
  53. uint8_t *tmp_row;
  54. unsigned int tmp_row_size;
  55. uint8_t *buffer;
  56. int buffer_size;
  57. int pass;
  58. int crow_size; /* compressed row size (include filter type) */
  59. int row_size; /* decompressed row size */
  60. int pass_row_size; /* decompress row size of the current pass */
  61. int y;
  62. z_stream zstream;
  63. } PNGDecContext;
  64. /* Mask to determine which pixels are valid in a pass */
  65. static const uint8_t png_pass_mask[NB_PASSES] = {
  66. 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
  67. };
  68. /* Mask to determine which y pixels can be written in a pass */
  69. static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
  70. 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  71. };
  72. /* Mask to determine which pixels to overwrite while displaying */
  73. static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
  74. 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
  75. };
  76. /* NOTE: we try to construct a good looking image at each pass. width
  77. * is the original image width. We also do pixel format conversion at
  78. * this stage */
  79. static void png_put_interlaced_row(uint8_t *dst, int width,
  80. int bits_per_pixel, int pass,
  81. int color_type, const uint8_t *src)
  82. {
  83. int x, mask, dsp_mask, j, src_x, b, bpp;
  84. uint8_t *d;
  85. const uint8_t *s;
  86. mask = png_pass_mask[pass];
  87. dsp_mask = png_pass_dsp_mask[pass];
  88. switch (bits_per_pixel) {
  89. case 1:
  90. src_x = 0;
  91. for (x = 0; x < width; x++) {
  92. j = (x & 7);
  93. if ((dsp_mask << j) & 0x80) {
  94. b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
  95. dst[x >> 3] &= 0xFF7F>>j;
  96. dst[x >> 3] |= b << (7 - j);
  97. }
  98. if ((mask << j) & 0x80)
  99. src_x++;
  100. }
  101. break;
  102. case 2:
  103. src_x = 0;
  104. for (x = 0; x < width; x++) {
  105. int j2 = 2 * (x & 3);
  106. j = (x & 7);
  107. if ((dsp_mask << j) & 0x80) {
  108. b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
  109. dst[x >> 2] &= 0xFF3F>>j2;
  110. dst[x >> 2] |= b << (6 - j2);
  111. }
  112. if ((mask << j) & 0x80)
  113. src_x++;
  114. }
  115. break;
  116. case 4:
  117. src_x = 0;
  118. for (x = 0; x < width; x++) {
  119. int j2 = 4*(x&1);
  120. j = (x & 7);
  121. if ((dsp_mask << j) & 0x80) {
  122. b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
  123. dst[x >> 1] &= 0xFF0F>>j2;
  124. dst[x >> 1] |= b << (4 - j2);
  125. }
  126. if ((mask << j) & 0x80)
  127. src_x++;
  128. }
  129. break;
  130. default:
  131. bpp = bits_per_pixel >> 3;
  132. d = dst;
  133. s = src;
  134. for (x = 0; x < width; x++) {
  135. j = x & 7;
  136. if ((dsp_mask << j) & 0x80) {
  137. memcpy(d, s, bpp);
  138. }
  139. d += bpp;
  140. if ((mask << j) & 0x80)
  141. s += bpp;
  142. }
  143. break;
  144. }
  145. }
  146. void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
  147. int w, int bpp)
  148. {
  149. int i;
  150. for (i = 0; i < w; i++) {
  151. int a, b, c, p, pa, pb, pc;
  152. a = dst[i - bpp];
  153. b = top[i];
  154. c = top[i - bpp];
  155. p = b - c;
  156. pc = a - c;
  157. pa = abs(p);
  158. pb = abs(pc);
  159. pc = abs(p + pc);
  160. if (pa <= pb && pa <= pc)
  161. p = a;
  162. else if (pb <= pc)
  163. p = b;
  164. else
  165. p = c;
  166. dst[i] = p + src[i];
  167. }
  168. }
  169. #define UNROLL1(bpp, op) \
  170. { \
  171. r = dst[0]; \
  172. if (bpp >= 2) \
  173. g = dst[1]; \
  174. if (bpp >= 3) \
  175. b = dst[2]; \
  176. if (bpp >= 4) \
  177. a = dst[3]; \
  178. for (; i <= size - bpp; i += bpp) { \
  179. dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
  180. if (bpp == 1) \
  181. continue; \
  182. dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
  183. if (bpp == 2) \
  184. continue; \
  185. dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
  186. if (bpp == 3) \
  187. continue; \
  188. dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
  189. } \
  190. }
  191. #define UNROLL_FILTER(op) \
  192. if (bpp == 1) { \
  193. UNROLL1(1, op) \
  194. } else if (bpp == 2) { \
  195. UNROLL1(2, op) \
  196. } else if (bpp == 3) { \
  197. UNROLL1(3, op) \
  198. } else if (bpp == 4) { \
  199. UNROLL1(4, op) \
  200. } \
  201. for (; i < size; i++) { \
  202. dst[i] = op(dst[i - bpp], src[i], last[i]); \
  203. }
  204. /* NOTE: 'dst' can be equal to 'last' */
  205. static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
  206. uint8_t *src, uint8_t *last, int size, int bpp)
  207. {
  208. int i, p, r, g, b, a;
  209. switch (filter_type) {
  210. case PNG_FILTER_VALUE_NONE:
  211. memcpy(dst, src, size);
  212. break;
  213. case PNG_FILTER_VALUE_SUB:
  214. for (i = 0; i < bpp; i++)
  215. dst[i] = src[i];
  216. if (bpp == 4) {
  217. p = *(int *)dst;
  218. for (; i < size; i += bpp) {
  219. unsigned s = *(int *)(src + i);
  220. p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
  221. *(int *)(dst + i) = p;
  222. }
  223. } else {
  224. #define OP_SUB(x, s, l) ((x) + (s))
  225. UNROLL_FILTER(OP_SUB);
  226. }
  227. break;
  228. case PNG_FILTER_VALUE_UP:
  229. dsp->add_bytes_l2(dst, src, last, size);
  230. break;
  231. case PNG_FILTER_VALUE_AVG:
  232. for (i = 0; i < bpp; i++) {
  233. p = (last[i] >> 1);
  234. dst[i] = p + src[i];
  235. }
  236. #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
  237. UNROLL_FILTER(OP_AVG);
  238. break;
  239. case PNG_FILTER_VALUE_PAETH:
  240. for (i = 0; i < bpp; i++) {
  241. p = last[i];
  242. dst[i] = p + src[i];
  243. }
  244. if (bpp > 2 && size > 4) {
  245. /* would write off the end of the array if we let it process
  246. * the last pixel with bpp=3 */
  247. int w = bpp == 4 ? size : size - 3;
  248. dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
  249. i = w;
  250. }
  251. ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
  252. break;
  253. }
  254. }
  255. /* This used to be called "deloco" in FFmpeg
  256. * and is actually an inverse reversible colorspace transformation */
  257. #define YUV2RGB(NAME, TYPE) \
  258. static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
  259. { \
  260. int i; \
  261. for (i = 0; i < size; i += 3 + alpha) { \
  262. int g = dst [i + 1]; \
  263. dst[i + 0] += g; \
  264. dst[i + 2] += g; \
  265. } \
  266. }
  267. YUV2RGB(rgb8, uint8_t)
  268. YUV2RGB(rgb16, uint16_t)
  269. /* process exactly one decompressed row */
  270. static void png_handle_row(PNGDecContext *s)
  271. {
  272. uint8_t *ptr, *last_row;
  273. int got_line;
  274. if (!s->interlace_type) {
  275. ptr = s->image_buf + s->image_linesize * s->y;
  276. if (s->y == 0)
  277. last_row = s->last_row;
  278. else
  279. last_row = ptr - s->image_linesize;
  280. png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
  281. last_row, s->row_size, s->bpp);
  282. /* loco lags by 1 row so that it doesn't interfere with top prediction */
  283. if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
  284. if (s->bit_depth == 16) {
  285. deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
  286. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  287. } else {
  288. deloco_rgb8(ptr - s->image_linesize, s->row_size,
  289. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  290. }
  291. }
  292. s->y++;
  293. if (s->y == s->height) {
  294. s->state |= PNG_ALLIMAGE;
  295. if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
  296. if (s->bit_depth == 16) {
  297. deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
  298. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  299. } else {
  300. deloco_rgb8(ptr, s->row_size,
  301. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
  302. }
  303. }
  304. }
  305. } else {
  306. got_line = 0;
  307. for (;;) {
  308. ptr = s->image_buf + s->image_linesize * s->y;
  309. if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
  310. /* if we already read one row, it is time to stop to
  311. * wait for the next one */
  312. if (got_line)
  313. break;
  314. png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
  315. s->last_row, s->pass_row_size, s->bpp);
  316. FFSWAP(uint8_t *, s->last_row, s->tmp_row);
  317. FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
  318. got_line = 1;
  319. }
  320. if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
  321. png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
  322. s->color_type, s->last_row);
  323. }
  324. s->y++;
  325. if (s->y == s->height) {
  326. memset(s->last_row, 0, s->row_size);
  327. for (;;) {
  328. if (s->pass == NB_PASSES - 1) {
  329. s->state |= PNG_ALLIMAGE;
  330. goto the_end;
  331. } else {
  332. s->pass++;
  333. s->y = 0;
  334. s->pass_row_size = ff_png_pass_row_size(s->pass,
  335. s->bits_per_pixel,
  336. s->width);
  337. s->crow_size = s->pass_row_size + 1;
  338. if (s->pass_row_size != 0)
  339. break;
  340. /* skip pass if empty row */
  341. }
  342. }
  343. }
  344. }
  345. the_end:;
  346. }
  347. }
  348. static int png_decode_idat(PNGDecContext *s, int length)
  349. {
  350. int ret;
  351. s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
  352. s->zstream.next_in = (unsigned char *)s->gb.buffer;
  353. bytestream2_skip(&s->gb, length);
  354. /* decode one line if possible */
  355. while (s->zstream.avail_in > 0) {
  356. ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
  357. if (ret != Z_OK && ret != Z_STREAM_END) {
  358. av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
  359. return AVERROR_EXTERNAL;
  360. }
  361. if (s->zstream.avail_out == 0) {
  362. if (!(s->state & PNG_ALLIMAGE)) {
  363. png_handle_row(s);
  364. }
  365. s->zstream.avail_out = s->crow_size;
  366. s->zstream.next_out = s->crow_buf;
  367. }
  368. if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
  369. av_log(NULL, AV_LOG_WARNING,
  370. "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
  371. return 0;
  372. }
  373. }
  374. return 0;
  375. }
  376. static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
  377. const uint8_t *data_end)
  378. {
  379. z_stream zstream;
  380. unsigned char *buf;
  381. unsigned buf_size;
  382. int ret;
  383. zstream.zalloc = ff_png_zalloc;
  384. zstream.zfree = ff_png_zfree;
  385. zstream.opaque = NULL;
  386. if (inflateInit(&zstream) != Z_OK)
  387. return AVERROR_EXTERNAL;
  388. zstream.next_in = (unsigned char *)data;
  389. zstream.avail_in = data_end - data;
  390. av_bprint_init(bp, 0, -1);
  391. while (zstream.avail_in > 0) {
  392. av_bprint_get_buffer(bp, 1, &buf, &buf_size);
  393. if (!buf_size) {
  394. ret = AVERROR(ENOMEM);
  395. goto fail;
  396. }
  397. zstream.next_out = buf;
  398. zstream.avail_out = buf_size;
  399. ret = inflate(&zstream, Z_PARTIAL_FLUSH);
  400. if (ret != Z_OK && ret != Z_STREAM_END) {
  401. ret = AVERROR_EXTERNAL;
  402. goto fail;
  403. }
  404. bp->len += zstream.next_out - buf;
  405. if (ret == Z_STREAM_END)
  406. break;
  407. }
  408. inflateEnd(&zstream);
  409. bp->str[bp->len] = 0;
  410. return 0;
  411. fail:
  412. inflateEnd(&zstream);
  413. av_bprint_finalize(bp, NULL);
  414. return ret;
  415. }
  416. static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
  417. {
  418. size_t extra = 0, i;
  419. uint8_t *out, *q;
  420. for (i = 0; i < size_in; i++)
  421. extra += in[i] >= 0x80;
  422. if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
  423. return NULL;
  424. q = out = av_malloc(size_in + extra + 1);
  425. if (!out)
  426. return NULL;
  427. for (i = 0; i < size_in; i++) {
  428. if (in[i] >= 0x80) {
  429. *(q++) = 0xC0 | (in[i] >> 6);
  430. *(q++) = 0x80 | (in[i] & 0x3F);
  431. } else {
  432. *(q++) = in[i];
  433. }
  434. }
  435. *(q++) = 0;
  436. return out;
  437. }
  438. static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
  439. AVDictionary **dict)
  440. {
  441. int ret, method;
  442. const uint8_t *data = s->gb.buffer;
  443. const uint8_t *data_end = data + length;
  444. const uint8_t *keyword = data;
  445. const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
  446. uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
  447. unsigned text_len;
  448. AVBPrint bp;
  449. if (!keyword_end)
  450. return AVERROR_INVALIDDATA;
  451. data = keyword_end + 1;
  452. if (compressed) {
  453. if (data == data_end)
  454. return AVERROR_INVALIDDATA;
  455. method = *(data++);
  456. if (method)
  457. return AVERROR_INVALIDDATA;
  458. if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
  459. return ret;
  460. text_len = bp.len;
  461. av_bprint_finalize(&bp, (char **)&text);
  462. if (!text)
  463. return AVERROR(ENOMEM);
  464. } else {
  465. text = (uint8_t *)data;
  466. text_len = data_end - text;
  467. }
  468. kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
  469. txt_utf8 = iso88591_to_utf8(text, text_len);
  470. if (text != data)
  471. av_free(text);
  472. if (!(kw_utf8 && txt_utf8)) {
  473. av_free(kw_utf8);
  474. av_free(txt_utf8);
  475. return AVERROR(ENOMEM);
  476. }
  477. av_dict_set(dict, kw_utf8, txt_utf8,
  478. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  479. return 0;
  480. }
  481. static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
  482. uint32_t length)
  483. {
  484. if (length != 13)
  485. return AVERROR_INVALIDDATA;
  486. s->width = bytestream2_get_be32(&s->gb);
  487. s->height = bytestream2_get_be32(&s->gb);
  488. if (av_image_check_size(s->width, s->height, 0, avctx)) {
  489. s->width = s->height = 0;
  490. av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
  491. return AVERROR_INVALIDDATA;
  492. }
  493. s->bit_depth = bytestream2_get_byte(&s->gb);
  494. s->color_type = bytestream2_get_byte(&s->gb);
  495. s->compression_type = bytestream2_get_byte(&s->gb);
  496. s->filter_type = bytestream2_get_byte(&s->gb);
  497. s->interlace_type = bytestream2_get_byte(&s->gb);
  498. bytestream2_skip(&s->gb, 4); /* crc */
  499. s->state |= PNG_IHDR;
  500. if (avctx->debug & FF_DEBUG_PICT_INFO)
  501. av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
  502. "compression_type=%d filter_type=%d interlace_type=%d\n",
  503. s->width, s->height, s->bit_depth, s->color_type,
  504. s->compression_type, s->filter_type, s->interlace_type);
  505. return 0;
  506. }
  507. static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
  508. {
  509. if (s->state & PNG_IDAT) {
  510. av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
  511. return AVERROR_INVALIDDATA;
  512. }
  513. avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
  514. avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
  515. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
  516. avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
  517. bytestream2_skip(&s->gb, 1); /* unit specifier */
  518. bytestream2_skip(&s->gb, 4); /* crc */
  519. return 0;
  520. }
  521. static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
  522. uint32_t length, AVFrame *p)
  523. {
  524. int ret;
  525. if (!(s->state & PNG_IHDR)) {
  526. av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
  527. return AVERROR_INVALIDDATA;
  528. }
  529. if (!(s->state & PNG_IDAT)) {
  530. /* init image info */
  531. avctx->width = s->width;
  532. avctx->height = s->height;
  533. s->channels = ff_png_get_nb_channels(s->color_type);
  534. s->bits_per_pixel = s->bit_depth * s->channels;
  535. s->bpp = (s->bits_per_pixel + 7) >> 3;
  536. s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
  537. if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  538. s->color_type == PNG_COLOR_TYPE_RGB) {
  539. avctx->pix_fmt = AV_PIX_FMT_RGB24;
  540. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  541. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  542. avctx->pix_fmt = AV_PIX_FMT_RGBA;
  543. } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
  544. s->color_type == PNG_COLOR_TYPE_GRAY) {
  545. avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  546. } else if (s->bit_depth == 16 &&
  547. s->color_type == PNG_COLOR_TYPE_GRAY) {
  548. avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
  549. } else if (s->bit_depth == 16 &&
  550. s->color_type == PNG_COLOR_TYPE_RGB) {
  551. avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
  552. } else if (s->bit_depth == 16 &&
  553. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  554. avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
  555. } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
  556. s->color_type == PNG_COLOR_TYPE_PALETTE) {
  557. avctx->pix_fmt = AV_PIX_FMT_PAL8;
  558. } else if (s->bit_depth == 1 && s->bits_per_pixel == 1) {
  559. avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
  560. } else if (s->bit_depth == 8 &&
  561. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  562. avctx->pix_fmt = AV_PIX_FMT_YA8;
  563. } else if (s->bit_depth == 16 &&
  564. s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  565. avctx->pix_fmt = AV_PIX_FMT_YA16BE;
  566. } else {
  567. av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
  568. "and color type %d\n",
  569. s->bit_depth, s->color_type);
  570. return AVERROR_INVALIDDATA;
  571. }
  572. if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
  573. return ret;
  574. ff_thread_finish_setup(avctx);
  575. p->pict_type = AV_PICTURE_TYPE_I;
  576. p->key_frame = 1;
  577. p->interlaced_frame = !!s->interlace_type;
  578. /* compute the compressed row size */
  579. if (!s->interlace_type) {
  580. s->crow_size = s->row_size + 1;
  581. } else {
  582. s->pass = 0;
  583. s->pass_row_size = ff_png_pass_row_size(s->pass,
  584. s->bits_per_pixel,
  585. s->width);
  586. s->crow_size = s->pass_row_size + 1;
  587. }
  588. av_dlog(avctx, "row_size=%d crow_size =%d\n",
  589. s->row_size, s->crow_size);
  590. s->image_buf = p->data[0];
  591. s->image_linesize = p->linesize[0];
  592. /* copy the palette if needed */
  593. if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
  594. memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
  595. /* empty row is used if differencing to the first row */
  596. av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
  597. if (!s->last_row)
  598. return AVERROR_INVALIDDATA;
  599. if (s->interlace_type ||
  600. s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
  601. av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
  602. if (!s->tmp_row)
  603. return AVERROR_INVALIDDATA;
  604. }
  605. /* compressed row */
  606. av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
  607. if (!s->buffer)
  608. return AVERROR(ENOMEM);
  609. /* we want crow_buf+1 to be 16-byte aligned */
  610. s->crow_buf = s->buffer + 15;
  611. s->zstream.avail_out = s->crow_size;
  612. s->zstream.next_out = s->crow_buf;
  613. }
  614. s->state |= PNG_IDAT;
  615. if ((ret = png_decode_idat(s, length)) < 0)
  616. return ret;
  617. bytestream2_skip(&s->gb, 4); /* crc */
  618. return 0;
  619. }
  620. static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
  621. uint32_t length)
  622. {
  623. int n, i, r, g, b;
  624. if ((length % 3) != 0 || length > 256 * 3)
  625. return AVERROR_INVALIDDATA;
  626. /* read the palette */
  627. n = length / 3;
  628. for (i = 0; i < n; i++) {
  629. r = bytestream2_get_byte(&s->gb);
  630. g = bytestream2_get_byte(&s->gb);
  631. b = bytestream2_get_byte(&s->gb);
  632. s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
  633. }
  634. for (; i < 256; i++)
  635. s->palette[i] = (0xFFU << 24);
  636. s->state |= PNG_PLTE;
  637. bytestream2_skip(&s->gb, 4); /* crc */
  638. return 0;
  639. }
  640. static int decode_frame_png(AVCodecContext *avctx,
  641. void *data, int *got_frame,
  642. AVPacket *avpkt)
  643. {
  644. PNGDecContext *const s = avctx->priv_data;
  645. const uint8_t *buf = avpkt->data;
  646. int buf_size = avpkt->size;
  647. AVFrame *p;
  648. AVDictionary *metadata = NULL;
  649. uint32_t tag, length;
  650. int64_t sig;
  651. int ret;
  652. ff_thread_release_buffer(avctx, &s->last_picture);
  653. FFSWAP(ThreadFrame, s->picture, s->last_picture);
  654. p = s->picture.f;
  655. bytestream2_init(&s->gb, buf, buf_size);
  656. /* check signature */
  657. sig = bytestream2_get_be64(&s->gb);
  658. if (sig != PNGSIG &&
  659. sig != MNGSIG) {
  660. av_log(avctx, AV_LOG_ERROR, "Missing png signature\n");
  661. return AVERROR_INVALIDDATA;
  662. }
  663. s->y = s->state = 0;
  664. /* init the zlib */
  665. s->zstream.zalloc = ff_png_zalloc;
  666. s->zstream.zfree = ff_png_zfree;
  667. s->zstream.opaque = NULL;
  668. ret = inflateInit(&s->zstream);
  669. if (ret != Z_OK) {
  670. av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
  671. return AVERROR_EXTERNAL;
  672. }
  673. for (;;) {
  674. if (bytestream2_get_bytes_left(&s->gb) <= 0) {
  675. av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", bytestream2_get_bytes_left(&s->gb));
  676. if ( s->state & PNG_ALLIMAGE
  677. && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
  678. goto exit_loop;
  679. goto fail;
  680. }
  681. length = bytestream2_get_be32(&s->gb);
  682. if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
  683. av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
  684. goto fail;
  685. }
  686. tag = bytestream2_get_le32(&s->gb);
  687. if (avctx->debug & FF_DEBUG_STARTCODE)
  688. av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
  689. (tag & 0xff),
  690. ((tag >> 8) & 0xff),
  691. ((tag >> 16) & 0xff),
  692. ((tag >> 24) & 0xff), length);
  693. switch (tag) {
  694. case MKTAG('I', 'H', 'D', 'R'):
  695. if (decode_ihdr_chunk(avctx, s, length) < 0)
  696. goto fail;
  697. break;
  698. case MKTAG('p', 'H', 'Y', 's'):
  699. if (decode_phys_chunk(avctx, s) < 0)
  700. goto fail;
  701. break;
  702. case MKTAG('I', 'D', 'A', 'T'):
  703. if (decode_idat_chunk(avctx, s, length, p) < 0)
  704. goto fail;
  705. break;
  706. case MKTAG('P', 'L', 'T', 'E'):
  707. if (decode_plte_chunk(avctx, s, length) < 0)
  708. goto skip_tag;
  709. break;
  710. case MKTAG('t', 'R', 'N', 'S'):
  711. {
  712. int v, i;
  713. /* read the transparency. XXX: Only palette mode supported */
  714. if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
  715. length > 256 ||
  716. !(s->state & PNG_PLTE))
  717. goto skip_tag;
  718. for (i = 0; i < length; i++) {
  719. v = bytestream2_get_byte(&s->gb);
  720. s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
  721. }
  722. bytestream2_skip(&s->gb, 4); /* crc */
  723. }
  724. break;
  725. case MKTAG('t', 'E', 'X', 't'):
  726. if (decode_text_chunk(s, length, 0, &metadata) < 0)
  727. av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
  728. bytestream2_skip(&s->gb, length + 4);
  729. break;
  730. case MKTAG('z', 'T', 'X', 't'):
  731. if (decode_text_chunk(s, length, 1, &metadata) < 0)
  732. av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
  733. bytestream2_skip(&s->gb, length + 4);
  734. break;
  735. case MKTAG('I', 'E', 'N', 'D'):
  736. if (!(s->state & PNG_ALLIMAGE))
  737. av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
  738. if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
  739. goto fail;
  740. }
  741. bytestream2_skip(&s->gb, 4); /* crc */
  742. goto exit_loop;
  743. default:
  744. /* skip tag */
  745. skip_tag:
  746. bytestream2_skip(&s->gb, length + 4);
  747. break;
  748. }
  749. }
  750. exit_loop:
  751. if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE){
  752. int i, j, k;
  753. uint8_t *pd = p->data[0];
  754. for (j = 0; j < s->height; j++) {
  755. i = s->width / 8;
  756. for (k = 7; k >= 1; k--)
  757. if ((s->width&7) >= k)
  758. pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
  759. for (i--; i >= 0; i--) {
  760. pd[8*i + 7]= pd[i] & 1;
  761. pd[8*i + 6]= (pd[i]>>1) & 1;
  762. pd[8*i + 5]= (pd[i]>>2) & 1;
  763. pd[8*i + 4]= (pd[i]>>3) & 1;
  764. pd[8*i + 3]= (pd[i]>>4) & 1;
  765. pd[8*i + 2]= (pd[i]>>5) & 1;
  766. pd[8*i + 1]= (pd[i]>>6) & 1;
  767. pd[8*i + 0]= pd[i]>>7;
  768. }
  769. pd += s->image_linesize;
  770. }
  771. }
  772. if (s->bits_per_pixel == 2){
  773. int i, j;
  774. uint8_t *pd = p->data[0];
  775. for (j = 0; j < s->height; j++) {
  776. i = s->width / 4;
  777. if (s->color_type == PNG_COLOR_TYPE_PALETTE){
  778. if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
  779. if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
  780. if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
  781. for (i--; i >= 0; i--) {
  782. pd[4*i + 3]= pd[i] & 3;
  783. pd[4*i + 2]= (pd[i]>>2) & 3;
  784. pd[4*i + 1]= (pd[i]>>4) & 3;
  785. pd[4*i + 0]= pd[i]>>6;
  786. }
  787. } else {
  788. if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  789. if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  790. if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  791. for (i--; i >= 0; i--) {
  792. pd[4*i + 3]= ( pd[i] & 3)*0x55;
  793. pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
  794. pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
  795. pd[4*i + 0]= ( pd[i]>>6 )*0x55;
  796. }
  797. }
  798. pd += s->image_linesize;
  799. }
  800. }
  801. if (s->bits_per_pixel == 4){
  802. int i, j;
  803. uint8_t *pd = p->data[0];
  804. for (j = 0; j < s->height; j++) {
  805. i = s->width/2;
  806. if (s->color_type == PNG_COLOR_TYPE_PALETTE){
  807. if (s->width&1) pd[2*i+0]= pd[i]>>4;
  808. for (i--; i >= 0; i--) {
  809. pd[2*i + 1] = pd[i] & 15;
  810. pd[2*i + 0] = pd[i] >> 4;
  811. }
  812. } else {
  813. if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
  814. for (i--; i >= 0; i--) {
  815. pd[2*i + 1] = (pd[i] & 15) * 0x11;
  816. pd[2*i + 0] = (pd[i] >> 4) * 0x11;
  817. }
  818. }
  819. pd += s->image_linesize;
  820. }
  821. }
  822. /* handle p-frames only if a predecessor frame is available */
  823. if (s->last_picture.f->data[0]) {
  824. if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
  825. && s->last_picture.f->width == p->width
  826. && s->last_picture.f->height== p->height
  827. && s->last_picture.f->format== p->format
  828. ) {
  829. int i, j;
  830. uint8_t *pd = p->data[0];
  831. uint8_t *pd_last = s->last_picture.f->data[0];
  832. int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
  833. ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
  834. for (j = 0; j < s->height; j++) {
  835. for (i = 0; i < ls; i++)
  836. pd[i] += pd_last[i];
  837. pd += s->image_linesize;
  838. pd_last += s->image_linesize;
  839. }
  840. }
  841. }
  842. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  843. av_frame_set_metadata(p, metadata);
  844. metadata = NULL;
  845. if ((ret = av_frame_ref(data, s->picture.f)) < 0)
  846. return ret;
  847. *got_frame = 1;
  848. ret = bytestream2_tell(&s->gb);
  849. the_end:
  850. inflateEnd(&s->zstream);
  851. s->crow_buf = NULL;
  852. return ret;
  853. fail:
  854. av_dict_free(&metadata);
  855. ff_thread_report_progress(&s->picture, INT_MAX, 0);
  856. ret = AVERROR_INVALIDDATA;
  857. goto the_end;
  858. }
  859. static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  860. {
  861. PNGDecContext *psrc = src->priv_data;
  862. PNGDecContext *pdst = dst->priv_data;
  863. if (dst == src)
  864. return 0;
  865. ff_thread_release_buffer(dst, &pdst->picture);
  866. if (psrc->picture.f->data[0])
  867. return ff_thread_ref_frame(&pdst->picture, &psrc->picture);
  868. return 0;
  869. }
  870. static av_cold int png_dec_init(AVCodecContext *avctx)
  871. {
  872. PNGDecContext *s = avctx->priv_data;
  873. s->avctx = avctx;
  874. s->last_picture.f = av_frame_alloc();
  875. s->picture.f = av_frame_alloc();
  876. if (!s->last_picture.f || !s->picture.f)
  877. return AVERROR(ENOMEM);
  878. if (!avctx->internal->is_copy) {
  879. avctx->internal->allocate_progress = 1;
  880. ff_pngdsp_init(&s->dsp);
  881. }
  882. return 0;
  883. }
  884. static av_cold int png_dec_end(AVCodecContext *avctx)
  885. {
  886. PNGDecContext *s = avctx->priv_data;
  887. ff_thread_release_buffer(avctx, &s->last_picture);
  888. av_frame_free(&s->last_picture.f);
  889. ff_thread_release_buffer(avctx, &s->picture);
  890. av_frame_free(&s->picture.f);
  891. av_freep(&s->buffer);
  892. s->buffer_size = 0;
  893. av_freep(&s->last_row);
  894. s->last_row_size = 0;
  895. av_freep(&s->tmp_row);
  896. s->tmp_row_size = 0;
  897. return 0;
  898. }
  899. AVCodec ff_png_decoder = {
  900. .name = "png",
  901. .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
  902. .type = AVMEDIA_TYPE_VIDEO,
  903. .id = AV_CODEC_ID_PNG,
  904. .priv_data_size = sizeof(PNGDecContext),
  905. .init = png_dec_init,
  906. .close = png_dec_end,
  907. .decode = decode_frame_png,
  908. .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
  909. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  910. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
  911. };