PNGLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. #include <AK/FileSystemPath.h>
  2. #include <AK/MappedFile.h>
  3. #include <AK/NetworkOrdered.h>
  4. #include <LibDraw/PNGLoader.h>
  5. #include <LibDraw/puff.c>
  6. #include <fcntl.h>
  7. #include <serenity.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <sys/mman.h>
  11. #include <sys/stat.h>
  12. #include <unistd.h>
  13. //#define PNG_STOPWATCH_DEBUG
  14. struct PNG_IHDR {
  15. NetworkOrdered<u32> width;
  16. NetworkOrdered<u32> height;
  17. u8 bit_depth { 0 };
  18. u8 color_type { 0 };
  19. u8 compression_method { 0 };
  20. u8 filter_method { 0 };
  21. u8 interlace_method { 0 };
  22. };
  23. static_assert(sizeof(PNG_IHDR) == 13);
  24. struct Scanline {
  25. u8 filter { 0 };
  26. ByteBuffer data {};
  27. };
  28. struct [[gnu::packed]] PaletteEntry
  29. {
  30. u8 r;
  31. u8 g;
  32. u8 b;
  33. //u8 a;
  34. };
  35. struct [[gnu::packed]] Triplet
  36. {
  37. u8 r;
  38. u8 g;
  39. u8 b;
  40. };
  41. struct [[gnu::packed]] Triplet16
  42. {
  43. u16 r;
  44. u16 g;
  45. u16 b;
  46. };
  47. struct [[gnu::packed]] Quad16
  48. {
  49. u16 r;
  50. u16 g;
  51. u16 b;
  52. u16 a;
  53. };
  54. struct PNGLoadingContext {
  55. int width { -1 };
  56. int height { -1 };
  57. u8 bit_depth { 0 };
  58. u8 color_type { 0 };
  59. u8 compression_method { 0 };
  60. u8 filter_method { 0 };
  61. u8 interlace_method { 0 };
  62. u8 bytes_per_pixel { 0 };
  63. bool has_seen_zlib_header { false };
  64. bool has_alpha() const { return color_type & 4 || palette_transparency_data.size() > 0; }
  65. Vector<Scanline> scanlines;
  66. RefPtr<GraphicsBitmap> bitmap;
  67. u8* decompression_buffer { nullptr };
  68. int decompression_buffer_size { 0 };
  69. Vector<u8> compressed_data;
  70. Vector<PaletteEntry> palette_data;
  71. Vector<u8> palette_transparency_data;
  72. };
  73. class Streamer {
  74. public:
  75. Streamer(const u8* data, int size)
  76. : m_original_data(data)
  77. , m_original_size(size)
  78. , m_data_ptr(data)
  79. , m_size_remaining(size)
  80. {
  81. }
  82. template<typename T>
  83. bool read(T& value)
  84. {
  85. if (m_size_remaining < (int)sizeof(T))
  86. return false;
  87. value = *((const NetworkOrdered<T>*)m_data_ptr);
  88. m_data_ptr += sizeof(T);
  89. m_size_remaining -= sizeof(T);
  90. return true;
  91. }
  92. bool read_bytes(u8* buffer, int count)
  93. {
  94. if (m_size_remaining < count)
  95. return false;
  96. memcpy(buffer, m_data_ptr, count);
  97. m_data_ptr += count;
  98. m_size_remaining -= count;
  99. return true;
  100. }
  101. bool wrap_bytes(ByteBuffer& buffer, int count)
  102. {
  103. if (m_size_remaining < count)
  104. return false;
  105. buffer = ByteBuffer::wrap(m_data_ptr, count);
  106. m_data_ptr += count;
  107. m_size_remaining -= count;
  108. return true;
  109. }
  110. bool at_end() const { return !m_size_remaining; }
  111. private:
  112. const u8* m_original_data;
  113. int m_original_size;
  114. const u8* m_data_ptr;
  115. int m_size_remaining;
  116. };
  117. static RefPtr<GraphicsBitmap> load_png_impl(const u8*, int);
  118. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  119. RefPtr<GraphicsBitmap> load_png(const StringView& path)
  120. {
  121. MappedFile mapped_file(path);
  122. if (!mapped_file.is_valid())
  123. return nullptr;
  124. auto bitmap = load_png_impl((const u8*)mapped_file.data(), mapped_file.size());
  125. if (bitmap)
  126. bitmap->set_mmap_name(String::format("GraphicsBitmap [%dx%d] - Decoded PNG: %s", bitmap->width(), bitmap->height(), canonicalized_path(path).characters()));
  127. return bitmap;
  128. }
  129. RefPtr<GraphicsBitmap> load_png_from_memory(const u8* data, size_t length)
  130. {
  131. auto bitmap = load_png_impl(data, length);
  132. if (bitmap)
  133. bitmap->set_mmap_name(String::format("GraphicsBitmap [%dx%d] - Decoded PNG: <memory>", bitmap->width(), bitmap->height()));
  134. return bitmap;
  135. }
  136. [[gnu::always_inline]] static inline u8 paeth_predictor(int a, int b, int c)
  137. {
  138. int p = a + b - c;
  139. int pa = abs(p - a);
  140. int pb = abs(p - b);
  141. int pc = abs(p - c);
  142. if (pa <= pb && pa <= pc)
  143. return a;
  144. if (pb <= pc)
  145. return b;
  146. return c;
  147. }
  148. union [[gnu::packed]] Pixel
  149. {
  150. RGBA32 rgba { 0 };
  151. u8 v[4];
  152. struct {
  153. u8 r;
  154. u8 g;
  155. u8 b;
  156. u8 a;
  157. };
  158. };
  159. static_assert(sizeof(Pixel) == 4);
  160. template<bool has_alpha, u8 filter_type>
  161. [[gnu::always_inline]] static inline void unfilter_impl(GraphicsBitmap& bitmap, int y, const void* dummy_scanline_data)
  162. {
  163. auto* dummy_scanline = (const Pixel*)dummy_scanline_data;
  164. if constexpr (filter_type == 0) {
  165. auto* pixels = (Pixel*)bitmap.scanline(y);
  166. for (int i = 0; i < bitmap.width(); ++i) {
  167. auto& x = pixels[i];
  168. swap(x.r, x.b);
  169. }
  170. }
  171. if constexpr (filter_type == 1) {
  172. auto* pixels = (Pixel*)bitmap.scanline(y);
  173. swap(pixels[0].r, pixels[0].b);
  174. for (int i = 1; i < bitmap.width(); ++i) {
  175. auto& x = pixels[i];
  176. swap(x.r, x.b);
  177. auto& a = (const Pixel&)pixels[i - 1];
  178. x.v[0] += a.v[0];
  179. x.v[1] += a.v[1];
  180. x.v[2] += a.v[2];
  181. if constexpr (has_alpha)
  182. x.v[3] += a.v[3];
  183. }
  184. return;
  185. }
  186. if constexpr (filter_type == 2) {
  187. auto* pixels = (Pixel*)bitmap.scanline(y);
  188. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  189. for (int i = 0; i < bitmap.width(); ++i) {
  190. auto& x = pixels[i];
  191. swap(x.r, x.b);
  192. const Pixel& b = pixels_y_minus_1[i];
  193. x.v[0] += b.v[0];
  194. x.v[1] += b.v[1];
  195. x.v[2] += b.v[2];
  196. if constexpr (has_alpha)
  197. x.v[3] += b.v[3];
  198. }
  199. return;
  200. }
  201. if constexpr (filter_type == 3) {
  202. auto* pixels = (Pixel*)bitmap.scanline(y);
  203. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  204. for (int i = 0; i < bitmap.width(); ++i) {
  205. auto& x = pixels[i];
  206. swap(x.r, x.b);
  207. Pixel a;
  208. if (i != 0)
  209. a = pixels[i - 1];
  210. const Pixel& b = pixels_y_minus_1[i];
  211. x.v[0] = x.v[0] + ((a.v[0] + b.v[0]) / 2);
  212. x.v[1] = x.v[1] + ((a.v[1] + b.v[1]) / 2);
  213. x.v[2] = x.v[2] + ((a.v[2] + b.v[2]) / 2);
  214. if constexpr (has_alpha)
  215. x.v[3] = x.v[3] + ((a.v[3] + b.v[3]) / 2);
  216. }
  217. return;
  218. }
  219. if constexpr (filter_type == 4) {
  220. auto* pixels = (Pixel*)bitmap.scanline(y);
  221. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  222. for (int i = 0; i < bitmap.width(); ++i) {
  223. auto& x = pixels[i];
  224. swap(x.r, x.b);
  225. Pixel a;
  226. const Pixel& b = pixels_y_minus_1[i];
  227. Pixel c;
  228. if (i != 0) {
  229. a = pixels[i - 1];
  230. c = pixels_y_minus_1[i - 1];
  231. }
  232. x.v[0] += paeth_predictor(a.v[0], b.v[0], c.v[0]);
  233. x.v[1] += paeth_predictor(a.v[1], b.v[1], c.v[1]);
  234. x.v[2] += paeth_predictor(a.v[2], b.v[2], c.v[2]);
  235. if constexpr (has_alpha)
  236. x.v[3] += paeth_predictor(a.v[3], b.v[3], c.v[3]);
  237. }
  238. }
  239. }
  240. [[gnu::noinline]] static void unfilter(PNGLoadingContext& context)
  241. {
  242. {
  243. #ifdef PNG_STOPWATCH_DEBUG
  244. Stopwatch sw("load_png_impl: unfilter: unpack");
  245. #endif
  246. // First unpack the scanlines to RGBA:
  247. switch (context.color_type) {
  248. case 2:
  249. if (context.bit_depth == 8) {
  250. for (int y = 0; y < context.height; ++y) {
  251. auto* triplets = (Triplet*)context.scanlines[y].data.data();
  252. for (int i = 0; i < context.width; ++i) {
  253. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  254. pixel.r = triplets[i].r;
  255. pixel.g = triplets[i].g;
  256. pixel.b = triplets[i].b;
  257. pixel.a = 0xff;
  258. }
  259. }
  260. } else if (context.bit_depth == 16) {
  261. for (int y = 0; y < context.height; ++y) {
  262. auto* triplets = (Triplet16*)context.scanlines[y].data.data();
  263. for (int i = 0; i < context.width; ++i) {
  264. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  265. pixel.r = triplets[i].r & 0xFF;
  266. pixel.g = triplets[i].g & 0xFF;
  267. pixel.b = triplets[i].b & 0xFF;
  268. pixel.a = 0xff;
  269. }
  270. }
  271. } else {
  272. ASSERT_NOT_REACHED();
  273. }
  274. break;
  275. case 6:
  276. if (context.bit_depth == 8) {
  277. for (int y = 0; y < context.height; ++y) {
  278. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  279. }
  280. } else if (context.bit_depth == 16) {
  281. for (int y = 0; y < context.height; ++y) {
  282. auto* triplets = (Quad16*)context.scanlines[y].data.data();
  283. for (int i = 0; i < context.width; ++i) {
  284. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  285. pixel.r = triplets[i].r & 0xFF;
  286. pixel.g = triplets[i].g & 0xFF;
  287. pixel.b = triplets[i].b & 0xFF;
  288. pixel.a = triplets[i].a & 0xFF;
  289. }
  290. }
  291. } else {
  292. ASSERT_NOT_REACHED();
  293. }
  294. break;
  295. case 3:
  296. for (int y = 0; y < context.height; ++y) {
  297. auto* palette_index = (u8*)context.scanlines[y].data.data();
  298. for (int i = 0; i < context.width; ++i) {
  299. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  300. auto& color = context.palette_data.at((int)palette_index[i]);
  301. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1
  302. ? (int)context.palette_transparency_data.data()[palette_index[i]]
  303. : 0xFF;
  304. pixel.r = color.r;
  305. pixel.g = color.g;
  306. pixel.b = color.b;
  307. pixel.a = transparency;
  308. }
  309. }
  310. break;
  311. default:
  312. ASSERT_NOT_REACHED();
  313. break;
  314. }
  315. }
  316. auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32));
  317. #ifdef PNG_STOPWATCH_DEBUG
  318. Stopwatch sw("load_png_impl: unfilter: process");
  319. #endif
  320. for (int y = 0; y < context.height; ++y) {
  321. auto filter = context.scanlines[y].filter;
  322. if (filter == 0) {
  323. if (context.has_alpha())
  324. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline.data());
  325. else
  326. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline.data());
  327. continue;
  328. }
  329. if (filter == 1) {
  330. if (context.has_alpha())
  331. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline.data());
  332. else
  333. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline.data());
  334. continue;
  335. }
  336. if (filter == 2) {
  337. if (context.has_alpha())
  338. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline.data());
  339. else
  340. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline.data());
  341. continue;
  342. }
  343. if (filter == 3) {
  344. if (context.has_alpha())
  345. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline.data());
  346. else
  347. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline.data());
  348. continue;
  349. }
  350. if (filter == 4) {
  351. if (context.has_alpha())
  352. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline.data());
  353. else
  354. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline.data());
  355. continue;
  356. }
  357. }
  358. }
  359. static RefPtr<GraphicsBitmap> load_png_impl(const u8* data, int data_size)
  360. {
  361. #ifdef PNG_STOPWATCH_DEBUG
  362. Stopwatch sw("load_png_impl: total");
  363. #endif
  364. const u8* data_ptr = data;
  365. int data_remaining = data_size;
  366. const u8 png_header[8] = { 0x89, 'P', 'N', 'G', 13, 10, 26, 10 };
  367. if (memcmp(data, png_header, sizeof(png_header))) {
  368. dbgprintf("Invalid PNG header\n");
  369. return nullptr;
  370. }
  371. PNGLoadingContext context;
  372. context.compressed_data.ensure_capacity(data_size);
  373. data_ptr += sizeof(png_header);
  374. data_remaining -= sizeof(png_header);
  375. {
  376. #ifdef PNG_STOPWATCH_DEBUG
  377. Stopwatch sw("load_png_impl: read chunks");
  378. #endif
  379. Streamer streamer(data_ptr, data_remaining);
  380. while (!streamer.at_end()) {
  381. if (!process_chunk(streamer, context)) {
  382. return nullptr;
  383. }
  384. }
  385. }
  386. {
  387. #ifdef PNG_STOPWATCH_DEBUG
  388. Stopwatch sw("load_png_impl: uncompress");
  389. #endif
  390. unsigned long srclen = context.compressed_data.size() - 6;
  391. unsigned long destlen = context.decompression_buffer_size;
  392. int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  393. if (ret < 0)
  394. return nullptr;
  395. context.compressed_data.clear();
  396. }
  397. {
  398. #ifdef PNG_STOPWATCH_DEBUG
  399. Stopwatch sw("load_png_impl: extract scanlines");
  400. #endif
  401. context.scanlines.ensure_capacity(context.height);
  402. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  403. for (int y = 0; y < context.height; ++y) {
  404. u8 filter;
  405. if (!streamer.read(filter))
  406. return nullptr;
  407. context.scanlines.append({ filter });
  408. auto& scanline_buffer = context.scanlines.last().data;
  409. if (!streamer.wrap_bytes(scanline_buffer, context.width * context.bytes_per_pixel))
  410. return nullptr;
  411. }
  412. }
  413. {
  414. #ifdef PNG_STOPWATCH_DEBUG
  415. Stopwatch sw("load_png_impl: create bitmap");
  416. #endif
  417. context.bitmap = GraphicsBitmap::create(context.has_alpha() ? GraphicsBitmap::Format::RGBA32 : GraphicsBitmap::Format::RGB32, { context.width, context.height });
  418. }
  419. unfilter(context);
  420. munmap(context.decompression_buffer, context.decompression_buffer_size);
  421. context.decompression_buffer = nullptr;
  422. context.decompression_buffer_size = 0;
  423. return context.bitmap;
  424. }
  425. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context)
  426. {
  427. if (data.size() < (int)sizeof(PNG_IHDR))
  428. return false;
  429. auto& ihdr = *(const PNG_IHDR*)data.data();
  430. context.width = ihdr.width;
  431. context.height = ihdr.height;
  432. context.bit_depth = ihdr.bit_depth;
  433. context.color_type = ihdr.color_type;
  434. context.compression_method = ihdr.compression_method;
  435. context.filter_method = ihdr.filter_method;
  436. context.interlace_method = ihdr.interlace_method;
  437. #ifdef PNG_DEBUG
  438. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  439. printf(" Color type: %d\n", context.color_type);
  440. printf("Compress Method: %d\n", context.compression_method);
  441. printf(" Filter Method: %d\n", context.filter_method);
  442. printf(" Interlace type: %d\n", context.interlace_method);
  443. #endif
  444. // FIXME: Implement Adam7 deinterlacing
  445. if (context.interlace_method != 0) {
  446. dbgprintf("PNGLoader::process_IHDR: Interlaced PNGs not currently supported.\n");
  447. return false;
  448. }
  449. switch (context.color_type) {
  450. case 0: // Each pixel is a grayscale sample.
  451. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  452. // FIXME: Implement grayscale PNG support.
  453. dbgprintf("PNGLoader::process_IHDR: Unsupported grayscale format.\n");
  454. return false;
  455. case 2:
  456. context.bytes_per_pixel = 3 * (ihdr.bit_depth / 8);
  457. break;
  458. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  459. // FIXME: Implement support for 1/2/4 bit palette based images.
  460. if (ihdr.bit_depth != 8) {
  461. dbgprintf("PNGLoader::process_IHDR: Unsupported index-based format (%d bpp).\n", context.bit_depth);
  462. return false;
  463. }
  464. context.bytes_per_pixel = 1;
  465. break;
  466. case 6:
  467. context.bytes_per_pixel = 4 * (ihdr.bit_depth / 8);
  468. break;
  469. default:
  470. ASSERT_NOT_REACHED();
  471. }
  472. context.decompression_buffer_size = (context.width * context.height * context.bytes_per_pixel + context.height);
  473. context.decompression_buffer = (u8*)mmap_with_name(nullptr, context.decompression_buffer_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, "PNG decompression buffer");
  474. return true;
  475. }
  476. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  477. {
  478. context.compressed_data.append(data.data(), data.size());
  479. return true;
  480. }
  481. static bool process_PLTE(const ByteBuffer& data, PNGLoadingContext& context)
  482. {
  483. context.palette_data.append((const PaletteEntry*)data.data(), data.size() / 3);
  484. return true;
  485. }
  486. static bool process_tRNS(const ByteBuffer& data, PNGLoadingContext& context)
  487. {
  488. switch (context.color_type) {
  489. case 3:
  490. context.palette_transparency_data.append(data.data(), data.size());
  491. break;
  492. }
  493. return true;
  494. }
  495. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  496. {
  497. u32 chunk_size;
  498. if (!streamer.read(chunk_size)) {
  499. printf("Bail at chunk_size\n");
  500. return false;
  501. }
  502. u8 chunk_type[5];
  503. chunk_type[4] = '\0';
  504. if (!streamer.read_bytes(chunk_type, 4)) {
  505. printf("Bail at chunk_type\n");
  506. return false;
  507. }
  508. ByteBuffer chunk_data;
  509. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  510. printf("Bail at chunk_data\n");
  511. return false;
  512. }
  513. u32 chunk_crc;
  514. if (!streamer.read(chunk_crc)) {
  515. printf("Bail at chunk_crc\n");
  516. return false;
  517. }
  518. #ifdef PNG_DEBUG
  519. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  520. #endif
  521. if (!strcmp((const char*)chunk_type, "IHDR"))
  522. return process_IHDR(chunk_data, context);
  523. if (!strcmp((const char*)chunk_type, "IDAT"))
  524. return process_IDAT(chunk_data, context);
  525. if (!strcmp((const char*)chunk_type, "PLTE"))
  526. return process_PLTE(chunk_data, context);
  527. if (!strcmp((const char*)chunk_type, "tRNS"))
  528. return process_tRNS(chunk_data, context);
  529. return true;
  530. }