PNGLoader.cpp 9.8 KB

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