PNGLoader.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. struct PNG_IHDR {
  12. NetworkOrdered<dword> width;
  13. NetworkOrdered<dword> height;
  14. byte bit_depth { 0 };
  15. byte color_type { 0 };
  16. byte compression_method { 0 };
  17. byte filter_method { 0 };
  18. byte interlace_method { 0 };
  19. };
  20. static_assert(sizeof(PNG_IHDR) == 13);
  21. struct Scanline {
  22. byte filter { 0 };
  23. ByteBuffer data;
  24. };
  25. struct PNGLoadingContext {
  26. int width { -1 };
  27. int height { -1 };
  28. byte bit_depth { 0 };
  29. byte color_type { 0 };
  30. byte compression_method { 0 };
  31. byte filter_method { 0 };
  32. byte interlace_method { 0 };
  33. byte bytes_per_pixel { 0 };
  34. bool has_seen_zlib_header { false };
  35. bool has_alpha() const { return color_type & 4; }
  36. Vector<Scanline> scanlines;
  37. RetainPtr<GraphicsBitmap> bitmap;
  38. byte* decompression_buffer { nullptr };
  39. int decompression_buffer_size { 0 };
  40. Vector<byte> compressed_data;
  41. };
  42. class Streamer {
  43. public:
  44. Streamer(const byte* data, int size)
  45. : m_original_data(data)
  46. , m_original_size(size)
  47. , m_data_ptr(data)
  48. , m_size_remaining(size)
  49. {
  50. }
  51. template<typename T>
  52. bool read(T& value)
  53. {
  54. if (m_size_remaining < sizeof(T))
  55. return false;
  56. value = *((NetworkOrdered<T>*)m_data_ptr);
  57. m_data_ptr += sizeof(T);
  58. m_size_remaining -= sizeof(T);
  59. return true;
  60. }
  61. bool read_bytes(byte* buffer, int count)
  62. {
  63. if (m_size_remaining < count)
  64. return false;
  65. memcpy(buffer, m_data_ptr, count);
  66. m_data_ptr += count;
  67. m_size_remaining -= count;
  68. return true;
  69. }
  70. bool wrap_bytes(ByteBuffer& buffer, int count)
  71. {
  72. if (m_size_remaining < count)
  73. return false;
  74. buffer = ByteBuffer::wrap((void*)m_data_ptr, count);
  75. m_data_ptr += count;
  76. m_size_remaining -= count;
  77. return true;
  78. }
  79. bool at_end() const { return !m_size_remaining; }
  80. private:
  81. const byte* m_original_data;
  82. int m_original_size;
  83. const byte* m_data_ptr;
  84. int m_size_remaining;
  85. };
  86. static RetainPtr<GraphicsBitmap> load_png_impl(const byte*, int);
  87. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  88. RetainPtr<GraphicsBitmap> load_png(const String& path)
  89. {
  90. int fd = open(path.characters(), O_RDONLY);
  91. if (fd < 0) {
  92. perror("open");
  93. return nullptr;
  94. }
  95. struct stat st;
  96. if (fstat(fd, &st) < 0) {
  97. perror("fstat");
  98. if (close(fd) < 0)
  99. perror("close");
  100. return nullptr;
  101. }
  102. if (st.st_size < 8) {
  103. if (close(fd) < 0)
  104. perror("close");
  105. return nullptr;
  106. }
  107. auto* mapped_file = (byte*)mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
  108. if (mapped_file == MAP_FAILED) {
  109. if (close(fd) < 0)
  110. perror("close");
  111. return nullptr;
  112. }
  113. auto bitmap = load_png_impl(mapped_file, st.st_size);
  114. if (munmap(mapped_file, st.st_size) < 0)
  115. perror("munmap");
  116. if (close(fd) < 0)
  117. perror("close");
  118. return bitmap;
  119. }
  120. static byte paeth_predictor(int a, int b, int c)
  121. {
  122. int p = a + b - c;
  123. int pa = abs(p - a);
  124. int pb = abs(p - b);
  125. int pc = abs(p - c);
  126. if (pa <= pb && pa <= pc)
  127. return a;
  128. if (pb <= pc)
  129. return b;
  130. return c;
  131. }
  132. static RetainPtr<GraphicsBitmap> load_png_impl(const byte* data, int data_size)
  133. {
  134. Stopwatch sw("load_png_impl: total");
  135. const byte* data_ptr = data;
  136. int data_remaining = data_size;
  137. const byte png_header[8] = { 0x89, 'P', 'N', 'G', 13, 10, 26, 10 };
  138. if (memcmp(data, png_header, sizeof(png_header))) {
  139. dbgprintf("Invalid PNG header\n");
  140. return nullptr;
  141. }
  142. PNGLoadingContext context;
  143. context.compressed_data.ensure_capacity(data_size);
  144. data_ptr += sizeof(png_header);
  145. data_remaining -= sizeof(png_header);
  146. {
  147. Stopwatch sw("load_png_impl: read chunks");
  148. Streamer streamer(data_ptr, data_remaining);
  149. while (!streamer.at_end()) {
  150. if (!process_chunk(streamer, context)) {
  151. return nullptr;
  152. }
  153. }
  154. }
  155. {
  156. Stopwatch sw("load_png_impl: uncompress");
  157. unsigned long srclen = context.compressed_data.size() - 6;
  158. unsigned long destlen = context.decompression_buffer_size;
  159. int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  160. if (ret < 0)
  161. return nullptr;
  162. context.compressed_data.clear();
  163. }
  164. {
  165. Stopwatch sw("load_png_impl: extract scanlines");
  166. context.scanlines.ensure_capacity(context.height);
  167. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  168. for (int y = 0; y < context.height; ++y) {
  169. byte filter;
  170. if (!streamer.read(filter))
  171. return nullptr;
  172. context.scanlines.append({ filter });
  173. auto& scanline_buffer = context.scanlines.last().data;
  174. if (!streamer.wrap_bytes(scanline_buffer, context.width * context.bytes_per_pixel))
  175. return nullptr;
  176. }
  177. }
  178. {
  179. Stopwatch sw("load_png_impl: create bitmap");
  180. context.bitmap = GraphicsBitmap::create(GraphicsBitmap::Format::RGBA32, { context.width, context.height });
  181. }
  182. union [[gnu::packed]] Pixel {
  183. RGBA32 rgba { 0 };
  184. struct {
  185. byte r;
  186. byte g;
  187. byte b;
  188. byte a;
  189. };
  190. };
  191. static_assert(sizeof(Pixel) == 4);
  192. {
  193. Stopwatch sw("load_png_impl: unfilter");
  194. for (int y = 0; y < context.height; ++y) {
  195. auto filter = context.scanlines[y].filter;
  196. switch (context.color_type) {
  197. case 2: {
  198. struct [[gnu::packed]] Triplet { byte r; byte g; byte b; };
  199. auto* triplets = (Triplet*)context.scanlines[y].data.pointer();
  200. for (int i = 0; i < context.width; ++i) {
  201. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  202. pixel.r = triplets[i].r;
  203. pixel.g = triplets[i].g;
  204. pixel.b = triplets[i].b;
  205. pixel.a = 0xff;
  206. }
  207. break;
  208. }
  209. case 6:
  210. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.pointer(), context.scanlines[y].data.size());
  211. break;
  212. default:
  213. ASSERT_NOT_REACHED();
  214. break;
  215. }
  216. if (filter == 0)
  217. continue;
  218. for (int i = 0; i < context.width; ++i) {
  219. auto& x = (Pixel&)context.bitmap->scanline(y)[i];
  220. swap(x.r, x.b);
  221. Pixel a;
  222. Pixel b;
  223. Pixel c;
  224. if (i != 0) a.rgba = context.bitmap->scanline(y)[i - 1];
  225. if (y != 0) b.rgba = context.bitmap->scanline(y - 1)[i];
  226. if (y != 0 && i != 0) c.rgba = context.bitmap->scanline(y - 1)[i - 1];
  227. if (filter == 1) {
  228. x.r += a.r;
  229. x.g += a.g;
  230. x.b += a.b;
  231. if (context.has_alpha())
  232. x.a += a.a;
  233. } else if (filter == 2) {
  234. x.r += b.r;
  235. x.g += b.g;
  236. x.b += b.b;
  237. if (context.has_alpha())
  238. x.a += b.a;
  239. } if (filter == 3) {
  240. x.r = x.r + ((a.r + b.r) / 2);
  241. x.g = x.g + ((a.g + b.g) / 2);
  242. x.b = x.b + ((a.b + b.b) / 2);
  243. if (context.has_alpha())
  244. x.a = x.a + ((a.a + b.a) / 2);
  245. } if (filter == 4) {
  246. x.r += paeth_predictor(a.r, b.r, c.r);
  247. x.g += paeth_predictor(a.g, b.g, c.g);
  248. x.b += paeth_predictor(a.b, b.b, c.b);
  249. if (context.has_alpha())
  250. x.a += paeth_predictor(a.a, b.a, c.a);
  251. }
  252. }
  253. }
  254. }
  255. munmap(context.decompression_buffer, context.decompression_buffer_size);
  256. context.decompression_buffer = nullptr;
  257. context.decompression_buffer_size = 0;
  258. return context.bitmap;
  259. }
  260. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context)
  261. {
  262. if (data.size() < sizeof(PNG_IHDR))
  263. return false;
  264. auto& ihdr = *(const PNG_IHDR*)data.pointer();
  265. context.width = ihdr.width;
  266. context.height = ihdr.height;
  267. context.bit_depth = ihdr.bit_depth;
  268. context.color_type = ihdr.color_type;
  269. context.compression_method = ihdr.compression_method;
  270. context.filter_method = ihdr.filter_method;
  271. context.interlace_method = ihdr.interlace_method;
  272. switch (context.color_type) {
  273. case 2:
  274. context.bytes_per_pixel = 3;
  275. break;
  276. case 6:
  277. context.bytes_per_pixel = 4;
  278. break;
  279. default:
  280. ASSERT_NOT_REACHED();
  281. }
  282. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  283. printf(" Color type: %b\n", context.color_type);
  284. printf(" Interlace type: %b\n", context.interlace_method);
  285. context.decompression_buffer_size = (context.width * context.height * context.bytes_per_pixel + context.height);
  286. context.decompression_buffer = (byte*)mmap(nullptr, context.decompression_buffer_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
  287. return true;
  288. }
  289. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  290. {
  291. context.compressed_data.append(data.pointer(), data.size());
  292. return true;
  293. }
  294. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  295. {
  296. dword chunk_size;
  297. if (!streamer.read(chunk_size)) {
  298. printf("Bail at chunk_size\n");
  299. return false;
  300. }
  301. byte chunk_type[5];
  302. chunk_type[4] = '\0';
  303. if (!streamer.read_bytes(chunk_type, 4)) {
  304. printf("Bail at chunk_type\n");
  305. return false;
  306. }
  307. ByteBuffer chunk_data;
  308. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  309. printf("Bail at chunk_data\n");
  310. return false;
  311. }
  312. dword chunk_crc;
  313. if (!streamer.read(chunk_crc)) {
  314. printf("Bail at chunk_crc\n");
  315. return false;
  316. }
  317. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  318. if (!strcmp((const char*)chunk_type, "IHDR"))
  319. return process_IHDR(chunk_data, context);
  320. if (!strcmp((const char*)chunk_type, "IDAT"))
  321. return process_IDAT(chunk_data, context);
  322. return true;
  323. }