PNGLoader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 PNGLoadingContext {
  29. int width { -1 };
  30. int height { -1 };
  31. u8 bit_depth { 0 };
  32. u8 color_type { 0 };
  33. u8 compression_method { 0 };
  34. u8 filter_method { 0 };
  35. u8 interlace_method { 0 };
  36. u8 bytes_per_pixel { 0 };
  37. bool has_seen_zlib_header { false };
  38. bool has_alpha() const { return color_type & 4; }
  39. Vector<Scanline> scanlines;
  40. RefPtr<GraphicsBitmap> bitmap;
  41. u8* decompression_buffer { nullptr };
  42. int decompression_buffer_size { 0 };
  43. Vector<u8> compressed_data;
  44. };
  45. class Streamer {
  46. public:
  47. Streamer(const u8* data, int size)
  48. : m_original_data(data)
  49. , m_original_size(size)
  50. , m_data_ptr(data)
  51. , m_size_remaining(size)
  52. {
  53. }
  54. template<typename T>
  55. bool read(T& value)
  56. {
  57. if (m_size_remaining < (int)sizeof(T))
  58. return false;
  59. value = *((const NetworkOrdered<T>*)m_data_ptr);
  60. m_data_ptr += sizeof(T);
  61. m_size_remaining -= sizeof(T);
  62. return true;
  63. }
  64. bool read_bytes(u8* buffer, int count)
  65. {
  66. if (m_size_remaining < count)
  67. return false;
  68. memcpy(buffer, m_data_ptr, count);
  69. m_data_ptr += count;
  70. m_size_remaining -= count;
  71. return true;
  72. }
  73. bool wrap_bytes(ByteBuffer& buffer, int count)
  74. {
  75. if (m_size_remaining < count)
  76. return false;
  77. buffer = ByteBuffer::wrap(m_data_ptr, count);
  78. m_data_ptr += count;
  79. m_size_remaining -= count;
  80. return true;
  81. }
  82. bool at_end() const { return !m_size_remaining; }
  83. private:
  84. const u8* m_original_data;
  85. int m_original_size;
  86. const u8* m_data_ptr;
  87. int m_size_remaining;
  88. };
  89. static RefPtr<GraphicsBitmap> load_png_impl(const u8*, int);
  90. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  91. RefPtr<GraphicsBitmap> load_png(const StringView& path)
  92. {
  93. MappedFile mapped_file(path);
  94. if (!mapped_file.is_valid())
  95. return nullptr;
  96. auto bitmap = load_png_impl((const u8*)mapped_file.pointer(), mapped_file.size());
  97. if (bitmap)
  98. bitmap->set_mmap_name(String::format("GraphicsBitmap [%dx%d] - Decoded PNG: %s", bitmap->width(), bitmap->height(), canonicalized_path(path).characters()));
  99. return bitmap;
  100. }
  101. RefPtr<GraphicsBitmap> load_png_from_memory(const u8* data, size_t length)
  102. {
  103. auto bitmap = load_png_impl(data, length);
  104. if (bitmap)
  105. bitmap->set_mmap_name(String::format("GraphicsBitmap [%dx%d] - Decoded PNG: <memory>", bitmap->width(), bitmap->height()));
  106. return bitmap;
  107. }
  108. [[gnu::always_inline]] static inline u8 paeth_predictor(int a, int b, int c)
  109. {
  110. int p = a + b - c;
  111. int pa = abs(p - a);
  112. int pb = abs(p - b);
  113. int pc = abs(p - c);
  114. if (pa <= pb && pa <= pc)
  115. return a;
  116. if (pb <= pc)
  117. return b;
  118. return c;
  119. }
  120. union [[gnu::packed]] Pixel
  121. {
  122. RGBA32 rgba { 0 };
  123. u8 v[4];
  124. struct {
  125. u8 r;
  126. u8 g;
  127. u8 b;
  128. u8 a;
  129. };
  130. };
  131. static_assert(sizeof(Pixel) == 4);
  132. template<bool has_alpha, u8 filter_type>
  133. [[gnu::always_inline]] static inline void unfilter_impl(GraphicsBitmap& bitmap, int y, const void* dummy_scanline_data)
  134. {
  135. auto* dummy_scanline = (const Pixel*)dummy_scanline_data;
  136. if constexpr (filter_type == 0) {
  137. auto* pixels = (Pixel*)bitmap.scanline(y);
  138. for (int i = 0; i < bitmap.width(); ++i) {
  139. auto& x = pixels[i];
  140. swap(x.r, x.b);
  141. }
  142. }
  143. if constexpr (filter_type == 1) {
  144. auto* pixels = (Pixel*)bitmap.scanline(y);
  145. swap(pixels[0].r, pixels[0].b);
  146. for (int i = 1; i < bitmap.width(); ++i) {
  147. auto& x = pixels[i];
  148. swap(x.r, x.b);
  149. auto& a = (const Pixel&)pixels[i - 1];
  150. x.v[0] += a.v[0];
  151. x.v[1] += a.v[1];
  152. x.v[2] += a.v[2];
  153. if constexpr (has_alpha)
  154. x.v[3] += a.v[3];
  155. }
  156. return;
  157. }
  158. if constexpr (filter_type == 2) {
  159. auto* pixels = (Pixel*)bitmap.scanline(y);
  160. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  161. for (int i = 0; i < bitmap.width(); ++i) {
  162. auto& x = pixels[i];
  163. swap(x.r, x.b);
  164. const Pixel& b = pixels_y_minus_1[i];
  165. x.v[0] += b.v[0];
  166. x.v[1] += b.v[1];
  167. x.v[2] += b.v[2];
  168. if constexpr (has_alpha)
  169. x.v[3] += b.v[3];
  170. }
  171. return;
  172. }
  173. if constexpr (filter_type == 3) {
  174. auto* pixels = (Pixel*)bitmap.scanline(y);
  175. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  176. for (int i = 0; i < bitmap.width(); ++i) {
  177. auto& x = pixels[i];
  178. swap(x.r, x.b);
  179. Pixel a;
  180. if (i != 0)
  181. a = pixels[i - 1];
  182. const Pixel& b = pixels_y_minus_1[i];
  183. x.v[0] = x.v[0] + ((a.v[0] + b.v[0]) / 2);
  184. x.v[1] = x.v[1] + ((a.v[1] + b.v[1]) / 2);
  185. x.v[2] = x.v[2] + ((a.v[2] + b.v[2]) / 2);
  186. if constexpr (has_alpha)
  187. x.v[3] = x.v[3] + ((a.v[3] + b.v[3]) / 2);
  188. }
  189. return;
  190. }
  191. if constexpr (filter_type == 4) {
  192. auto* pixels = (Pixel*)bitmap.scanline(y);
  193. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  194. for (int i = 0; i < bitmap.width(); ++i) {
  195. auto& x = pixels[i];
  196. swap(x.r, x.b);
  197. Pixel a;
  198. const Pixel& b = pixels_y_minus_1[i];
  199. Pixel c;
  200. if (i != 0) {
  201. a = pixels[i - 1];
  202. c = pixels_y_minus_1[i - 1];
  203. }
  204. x.v[0] += paeth_predictor(a.v[0], b.v[0], c.v[0]);
  205. x.v[1] += paeth_predictor(a.v[1], b.v[1], c.v[1]);
  206. x.v[2] += paeth_predictor(a.v[2], b.v[2], c.v[2]);
  207. if constexpr (has_alpha)
  208. x.v[3] += paeth_predictor(a.v[3], b.v[3], c.v[3]);
  209. }
  210. }
  211. }
  212. [[gnu::noinline]] static void unfilter(PNGLoadingContext& context)
  213. {
  214. {
  215. #ifdef PNG_STOPWATCH_DEBUG
  216. Stopwatch sw("load_png_impl: unfilter: unpack");
  217. #endif
  218. // First unpack the scanlines to RGBA:
  219. switch (context.color_type) {
  220. case 2:
  221. for (int y = 0; y < context.height; ++y) {
  222. struct [[gnu::packed]] Triplet
  223. {
  224. u8 r;
  225. u8 g;
  226. u8 b;
  227. };
  228. auto* triplets = (Triplet*)context.scanlines[y].data.pointer();
  229. for (int i = 0; i < context.width; ++i) {
  230. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  231. pixel.r = triplets[i].r;
  232. pixel.g = triplets[i].g;
  233. pixel.b = triplets[i].b;
  234. pixel.a = 0xff;
  235. }
  236. }
  237. break;
  238. case 6:
  239. for (int y = 0; y < context.height; ++y) {
  240. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.pointer(), context.scanlines[y].data.size());
  241. }
  242. break;
  243. default:
  244. ASSERT_NOT_REACHED();
  245. break;
  246. }
  247. }
  248. auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32));
  249. #ifdef PNG_STOPWATCH_DEBUG
  250. Stopwatch sw("load_png_impl: unfilter: process");
  251. #endif
  252. for (int y = 0; y < context.height; ++y) {
  253. auto filter = context.scanlines[y].filter;
  254. if (filter == 0) {
  255. if (context.has_alpha())
  256. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline.pointer());
  257. else
  258. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline.pointer());
  259. continue;
  260. }
  261. if (filter == 1) {
  262. if (context.has_alpha())
  263. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline.pointer());
  264. else
  265. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline.pointer());
  266. continue;
  267. }
  268. if (filter == 2) {
  269. if (context.has_alpha())
  270. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline.pointer());
  271. else
  272. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline.pointer());
  273. continue;
  274. }
  275. if (filter == 3) {
  276. if (context.has_alpha())
  277. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline.pointer());
  278. else
  279. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline.pointer());
  280. continue;
  281. }
  282. if (filter == 4) {
  283. if (context.has_alpha())
  284. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline.pointer());
  285. else
  286. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline.pointer());
  287. continue;
  288. }
  289. }
  290. }
  291. static RefPtr<GraphicsBitmap> load_png_impl(const u8* data, int data_size)
  292. {
  293. #ifdef PNG_STOPWATCH_DEBUG
  294. Stopwatch sw("load_png_impl: total");
  295. #endif
  296. const u8* data_ptr = data;
  297. int data_remaining = data_size;
  298. const u8 png_header[8] = { 0x89, 'P', 'N', 'G', 13, 10, 26, 10 };
  299. if (memcmp(data, png_header, sizeof(png_header))) {
  300. dbgprintf("Invalid PNG header\n");
  301. return nullptr;
  302. }
  303. PNGLoadingContext context;
  304. context.compressed_data.ensure_capacity(data_size);
  305. data_ptr += sizeof(png_header);
  306. data_remaining -= sizeof(png_header);
  307. {
  308. #ifdef PNG_STOPWATCH_DEBUG
  309. Stopwatch sw("load_png_impl: read chunks");
  310. #endif
  311. Streamer streamer(data_ptr, data_remaining);
  312. while (!streamer.at_end()) {
  313. if (!process_chunk(streamer, context)) {
  314. return nullptr;
  315. }
  316. }
  317. }
  318. {
  319. #ifdef PNG_STOPWATCH_DEBUG
  320. Stopwatch sw("load_png_impl: uncompress");
  321. #endif
  322. unsigned long srclen = context.compressed_data.size() - 6;
  323. unsigned long destlen = context.decompression_buffer_size;
  324. int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  325. if (ret < 0)
  326. return nullptr;
  327. context.compressed_data.clear();
  328. }
  329. {
  330. #ifdef PNG_STOPWATCH_DEBUG
  331. Stopwatch sw("load_png_impl: extract scanlines");
  332. #endif
  333. context.scanlines.ensure_capacity(context.height);
  334. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  335. for (int y = 0; y < context.height; ++y) {
  336. u8 filter;
  337. if (!streamer.read(filter))
  338. return nullptr;
  339. context.scanlines.append({ filter });
  340. auto& scanline_buffer = context.scanlines.last().data;
  341. if (!streamer.wrap_bytes(scanline_buffer, context.width * context.bytes_per_pixel))
  342. return nullptr;
  343. }
  344. }
  345. {
  346. #ifdef PNG_STOPWATCH_DEBUG
  347. Stopwatch sw("load_png_impl: create bitmap");
  348. #endif
  349. context.bitmap = GraphicsBitmap::create(context.has_alpha() ? GraphicsBitmap::Format::RGBA32 : GraphicsBitmap::Format::RGB32, { context.width, context.height });
  350. }
  351. unfilter(context);
  352. munmap(context.decompression_buffer, context.decompression_buffer_size);
  353. context.decompression_buffer = nullptr;
  354. context.decompression_buffer_size = 0;
  355. return context.bitmap;
  356. }
  357. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context)
  358. {
  359. if (data.size() < (int)sizeof(PNG_IHDR))
  360. return false;
  361. auto& ihdr = *(const PNG_IHDR*)data.pointer();
  362. context.width = ihdr.width;
  363. context.height = ihdr.height;
  364. context.bit_depth = ihdr.bit_depth;
  365. context.color_type = ihdr.color_type;
  366. context.compression_method = ihdr.compression_method;
  367. context.filter_method = ihdr.filter_method;
  368. context.interlace_method = ihdr.interlace_method;
  369. switch (context.color_type) {
  370. case 2:
  371. context.bytes_per_pixel = 3;
  372. break;
  373. case 6:
  374. context.bytes_per_pixel = 4;
  375. break;
  376. default:
  377. ASSERT_NOT_REACHED();
  378. }
  379. #ifdef PNG_DEBUG
  380. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  381. printf(" Color type: %b\n", context.color_type);
  382. printf(" Interlace type: %b\n", context.interlace_method);
  383. #endif
  384. context.decompression_buffer_size = (context.width * context.height * context.bytes_per_pixel + context.height);
  385. 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");
  386. return true;
  387. }
  388. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  389. {
  390. context.compressed_data.append(data.pointer(), data.size());
  391. return true;
  392. }
  393. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  394. {
  395. u32 chunk_size;
  396. if (!streamer.read(chunk_size)) {
  397. printf("Bail at chunk_size\n");
  398. return false;
  399. }
  400. u8 chunk_type[5];
  401. chunk_type[4] = '\0';
  402. if (!streamer.read_bytes(chunk_type, 4)) {
  403. printf("Bail at chunk_type\n");
  404. return false;
  405. }
  406. ByteBuffer chunk_data;
  407. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  408. printf("Bail at chunk_data\n");
  409. return false;
  410. }
  411. u32 chunk_crc;
  412. if (!streamer.read(chunk_crc)) {
  413. printf("Bail at chunk_crc\n");
  414. return false;
  415. }
  416. #ifdef PNG_DEBUG
  417. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  418. #endif
  419. if (!strcmp((const char*)chunk_type, "IHDR"))
  420. return process_IHDR(chunk_data, context);
  421. if (!strcmp((const char*)chunk_type, "IDAT"))
  422. return process_IDAT(chunk_data, context);
  423. return true;
  424. }