PNGLoader.cpp 14 KB

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