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.

937 lines
32KB

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