PNGLoader.cpp 14 KB

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