PGMLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. * Copyright (c) 2020, Hüseyin ASLITÜRK <asliturk@hotmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "PGMLoader.h"
  27. #include <AK/LexicalPath.h>
  28. #include <AK/MappedFile.h>
  29. #include <AK/NetworkOrdered.h>
  30. #include <AK/StringBuilder.h>
  31. #include <string.h>
  32. namespace Gfx {
  33. struct PGMLoadingContext {
  34. enum Type {
  35. Unknown,
  36. P2_ASCII,
  37. P5_RAWBITS
  38. };
  39. enum State {
  40. NotDecoded = 0,
  41. Error,
  42. MagicNumber,
  43. Width,
  44. Height,
  45. Maxval,
  46. Bitmap,
  47. Decoded
  48. };
  49. Type type { Type::Unknown };
  50. State state { State::NotDecoded };
  51. const u8* data { nullptr };
  52. size_t data_size { 0 };
  53. u16 width { 0 };
  54. u16 height { 0 };
  55. u16 max_val { 0 };
  56. RefPtr<Gfx::Bitmap> bitmap;
  57. };
  58. class Streamer {
  59. public:
  60. Streamer(const u8* data, size_t size)
  61. : m_data_ptr(data)
  62. , m_size_remaining(size)
  63. {
  64. }
  65. template<typename T>
  66. bool read(T& value)
  67. {
  68. if (m_size_remaining < sizeof(T))
  69. return false;
  70. value = *((const NetworkOrdered<T>*)m_data_ptr);
  71. m_data_ptr += sizeof(T);
  72. m_size_remaining -= sizeof(T);
  73. return true;
  74. }
  75. bool read_bytes(u8* buffer, size_t count)
  76. {
  77. if (m_size_remaining < count)
  78. return false;
  79. memcpy(buffer, m_data_ptr, count);
  80. m_data_ptr += count;
  81. m_size_remaining -= count;
  82. return true;
  83. }
  84. bool at_end() const { return !m_size_remaining; }
  85. void step_back()
  86. {
  87. m_data_ptr -= 1;
  88. m_size_remaining += 1;
  89. }
  90. private:
  91. const u8* m_data_ptr { nullptr };
  92. size_t m_size_remaining { 0 };
  93. };
  94. ALWAYS_INLINE static Color adjust_color(u16 max_val, Color& color)
  95. {
  96. color.set_red((color.red() * 255) / max_val);
  97. color.set_green((color.green() * 255) / max_val);
  98. color.set_blue((color.blue() * 255) / max_val);
  99. return color;
  100. }
  101. static bool read_number(Streamer& streamer, u16* value)
  102. {
  103. u8 byte;
  104. StringBuilder sb;
  105. while (streamer.read(byte)) {
  106. if (byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r') {
  107. streamer.step_back();
  108. break;
  109. }
  110. sb.append(byte);
  111. }
  112. auto opt_value = sb.to_string().to_uint();
  113. if (!opt_value.has_value()) {
  114. return false;
  115. }
  116. *value = (u16)opt_value.value();
  117. return true;
  118. }
  119. static bool read_comment(PGMLoadingContext& context, Streamer& streamer)
  120. {
  121. (void)context;
  122. bool exist = false;
  123. u8 byte;
  124. while (streamer.read(byte)) {
  125. switch (byte) {
  126. case '#': {
  127. exist = true;
  128. break;
  129. }
  130. case '\t':
  131. case '\n': {
  132. return exist;
  133. }
  134. default:
  135. break;
  136. }
  137. }
  138. return exist;
  139. }
  140. static bool read_magic_number(PGMLoadingContext& context, Streamer& streamer)
  141. {
  142. if (context.state >= PGMLoadingContext::MagicNumber)
  143. return true;
  144. if (!context.data || context.data_size < 2) {
  145. context.state = PGMLoadingContext::State::Error;
  146. dbg() << "There is no enough data.";
  147. return false;
  148. }
  149. u8 magic_number[2];
  150. if (!streamer.read_bytes(magic_number, 2)) {
  151. context.state = PGMLoadingContext::State::Error;
  152. dbg() << "We can't read magic number.";
  153. return false;
  154. }
  155. if (magic_number[0] == 'P' && magic_number[1] == '2') {
  156. context.type = PGMLoadingContext::P2_ASCII;
  157. context.state = PGMLoadingContext::MagicNumber;
  158. return true;
  159. }
  160. if (magic_number[0] == 'P' && magic_number[1] == '5') {
  161. context.type = PGMLoadingContext::P5_RAWBITS;
  162. context.state = PGMLoadingContext::MagicNumber;
  163. return true;
  164. }
  165. context.state = PGMLoadingContext::State::Error;
  166. dbg() << "Magic number is not valid:" << (char)magic_number[0] << (char)magic_number[1];
  167. return false;
  168. }
  169. static bool read_white_space(PGMLoadingContext& context, Streamer& streamer)
  170. {
  171. bool exist = false;
  172. u8 byte;
  173. while (streamer.read(byte)) {
  174. switch (byte) {
  175. case ' ':
  176. case '\t':
  177. case '\n':
  178. case '\r': {
  179. exist = true;
  180. break;
  181. }
  182. case '#': {
  183. streamer.step_back();
  184. read_comment(context, streamer);
  185. break;
  186. }
  187. default: {
  188. streamer.step_back();
  189. return exist;
  190. }
  191. }
  192. }
  193. return exist;
  194. }
  195. static bool read_width(PGMLoadingContext& context, Streamer& streamer)
  196. {
  197. bool result = read_number(streamer, &context.width);
  198. if (!result || context.width == 0) {
  199. return false;
  200. }
  201. context.state = PGMLoadingContext::Width;
  202. return true;
  203. }
  204. static bool read_height(PGMLoadingContext& context, Streamer& streamer)
  205. {
  206. bool result = read_number(streamer, &context.height);
  207. if (!result || context.height == 0) {
  208. return false;
  209. }
  210. context.state = PGMLoadingContext::Height;
  211. return true;
  212. }
  213. static bool read_max_val(PGMLoadingContext& context, Streamer& streamer)
  214. {
  215. bool result = read_number(streamer, &context.max_val);
  216. if (!result || context.max_val == 0) {
  217. return false;
  218. }
  219. if (context.max_val > 255) {
  220. dbg() << "We can't pars 2 byte color.";
  221. context.state = PGMLoadingContext::Error;
  222. return false;
  223. }
  224. context.state = PGMLoadingContext::Maxval;
  225. return true;
  226. }
  227. static bool read_image_data(PGMLoadingContext& context, Streamer& streamer)
  228. {
  229. Vector<Gfx::Color> color_data;
  230. if (context.type == PGMLoadingContext::P2_ASCII) {
  231. u16 value;
  232. while (true) {
  233. if (!read_number(streamer, &value))
  234. break;
  235. if (!read_white_space(context, streamer))
  236. break;
  237. color_data.append({ (u8)value, (u8)value, (u8)value });
  238. }
  239. } else if (context.type == PGMLoadingContext::P5_RAWBITS) {
  240. u8 pixel;
  241. while (streamer.read(pixel)) {
  242. color_data.append({ pixel, pixel, pixel });
  243. }
  244. }
  245. context.bitmap = Bitmap::create_purgeable(BitmapFormat::RGB32, { context.width, context.height });
  246. size_t index = 0;
  247. for (int y = 0; y < context.height; ++y) {
  248. for (int x = 0; x < context.width; ++x) {
  249. Color color = color_data.at(index);
  250. if (context.max_val < 255)
  251. color = adjust_color(context.max_val, color);
  252. context.bitmap->set_pixel(x, y, color);
  253. index++;
  254. }
  255. }
  256. context.state = PGMLoadingContext::State::Bitmap;
  257. return true;
  258. }
  259. static bool decode_pgm(PGMLoadingContext& context)
  260. {
  261. if (context.state >= PGMLoadingContext::State::Decoded)
  262. return true;
  263. Streamer streamer(context.data, context.data_size);
  264. if (!read_magic_number(context, streamer))
  265. return false;
  266. if (!read_white_space(context, streamer))
  267. return false;
  268. if (!read_width(context, streamer))
  269. return false;
  270. if (!read_white_space(context, streamer))
  271. return false;
  272. if (!read_height(context, streamer))
  273. return false;
  274. if (!read_white_space(context, streamer))
  275. return false;
  276. if (!read_max_val(context, streamer))
  277. return false;
  278. if (!read_white_space(context, streamer))
  279. return false;
  280. if (!read_image_data(context, streamer))
  281. return false;
  282. context.state = PGMLoadingContext::State::Decoded;
  283. return true;
  284. }
  285. static RefPtr<Gfx::Bitmap> load_pgm_impl(const u8* data, size_t data_size)
  286. {
  287. PGMLoadingContext context;
  288. context.data = data;
  289. context.data_size = data_size;
  290. if (!decode_pgm(context))
  291. return nullptr;
  292. return context.bitmap;
  293. }
  294. RefPtr<Gfx::Bitmap> load_pgm(const StringView& path)
  295. {
  296. MappedFile mapped_file(path);
  297. if (!mapped_file.is_valid()) {
  298. return nullptr;
  299. }
  300. auto bitmap = load_pgm_impl((const u8*)mapped_file.data(), mapped_file.size());
  301. if (bitmap)
  302. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PGM: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  303. return bitmap;
  304. }
  305. RefPtr<Gfx::Bitmap> load_pgm_from_memory(const u8* data, size_t length)
  306. {
  307. auto bitmap = load_pgm_impl(data, length);
  308. if (bitmap)
  309. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PGM: <memory>", bitmap->width(), bitmap->height()));
  310. return bitmap;
  311. }
  312. PGMImageDecoderPlugin::PGMImageDecoderPlugin(const u8* data, size_t size)
  313. {
  314. m_context = make<PGMLoadingContext>();
  315. m_context->data = data;
  316. m_context->data_size = size;
  317. }
  318. PGMImageDecoderPlugin::~PGMImageDecoderPlugin()
  319. {
  320. }
  321. IntSize PGMImageDecoderPlugin::size()
  322. {
  323. if (m_context->state == PGMLoadingContext::State::Error)
  324. return {};
  325. if (m_context->state < PGMLoadingContext::State::Decoded) {
  326. bool success = decode_pgm(*m_context);
  327. if (!success)
  328. return {};
  329. }
  330. return { m_context->width, m_context->height };
  331. }
  332. RefPtr<Gfx::Bitmap> PGMImageDecoderPlugin::bitmap()
  333. {
  334. if (m_context->state == PGMLoadingContext::State::Error)
  335. return nullptr;
  336. if (m_context->state < PGMLoadingContext::State::Decoded) {
  337. bool success = decode_pgm(*m_context);
  338. if (!success)
  339. return nullptr;
  340. }
  341. ASSERT(m_context->bitmap);
  342. return m_context->bitmap;
  343. }
  344. void PGMImageDecoderPlugin::set_volatile()
  345. {
  346. if (m_context->bitmap)
  347. m_context->bitmap->set_volatile();
  348. }
  349. bool PGMImageDecoderPlugin::set_nonvolatile()
  350. {
  351. if (!m_context->bitmap)
  352. return false;
  353. return m_context->bitmap->set_nonvolatile();
  354. }
  355. bool PGMImageDecoderPlugin::sniff()
  356. {
  357. if (m_context->data_size < 2)
  358. return false;
  359. if (m_context->data[0] == 'P' && m_context->data[1] == '2')
  360. return true;
  361. if (m_context->data[0] == 'P' && m_context->data[1] == '5')
  362. return true;
  363. return false;
  364. }
  365. bool PGMImageDecoderPlugin::is_animated()
  366. {
  367. return false;
  368. }
  369. size_t PGMImageDecoderPlugin::loop_count()
  370. {
  371. return 0;
  372. }
  373. size_t PGMImageDecoderPlugin::frame_count()
  374. {
  375. return 1;
  376. }
  377. ImageFrameDescriptor PGMImageDecoderPlugin::frame(size_t i)
  378. {
  379. if (i > 0) {
  380. return { bitmap(), 0 };
  381. }
  382. return {};
  383. }
  384. }