PPMLoader.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 "PPMLoader.h"
  27. #include <AK/Endian.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/MappedFile.h>
  30. #include <AK/ScopeGuard.h>
  31. #include <AK/StringBuilder.h>
  32. #include <string.h>
  33. //#define PPM_DEBUG
  34. namespace Gfx {
  35. struct PPMLoadingContext {
  36. enum Type {
  37. Unknown,
  38. P3_ASCII,
  39. P6_RAWBITS
  40. };
  41. enum State {
  42. NotDecoded = 0,
  43. Error,
  44. MagicNumber,
  45. Width,
  46. Height,
  47. Maxval,
  48. Bitmap,
  49. Decoded
  50. };
  51. Type type { Type::Unknown };
  52. State state { State::NotDecoded };
  53. const u8* data { nullptr };
  54. size_t data_size { 0 };
  55. u16 width { 0 };
  56. u16 height { 0 };
  57. u16 max_val { 0 };
  58. RefPtr<Gfx::Bitmap> bitmap;
  59. };
  60. class Streamer {
  61. public:
  62. Streamer(const u8* data, size_t size)
  63. : m_data_ptr(data)
  64. , m_size_remaining(size)
  65. {
  66. }
  67. template<typename T>
  68. bool read(T& value)
  69. {
  70. if (m_size_remaining < sizeof(T))
  71. return false;
  72. value = *((const NetworkOrdered<T>*)m_data_ptr);
  73. m_data_ptr += sizeof(T);
  74. m_size_remaining -= sizeof(T);
  75. return true;
  76. }
  77. bool read_bytes(u8* buffer, size_t count)
  78. {
  79. if (m_size_remaining < count)
  80. return false;
  81. memcpy(buffer, m_data_ptr, count);
  82. m_data_ptr += count;
  83. m_size_remaining -= count;
  84. return true;
  85. }
  86. bool at_end() const { return !m_size_remaining; }
  87. void step_back()
  88. {
  89. m_data_ptr -= 1;
  90. m_size_remaining += 1;
  91. }
  92. private:
  93. const u8* m_data_ptr { nullptr };
  94. size_t m_size_remaining { 0 };
  95. };
  96. ALWAYS_INLINE static Color adjust_color(u16 max_val, Color& color)
  97. {
  98. color.set_red((color.red() * 255) / max_val);
  99. color.set_green((color.green() * 255) / max_val);
  100. color.set_blue((color.blue() * 255) / max_val);
  101. return color;
  102. }
  103. static bool read_number(Streamer& streamer, u16* value)
  104. {
  105. u8 byte;
  106. StringBuilder sb;
  107. while (streamer.read(byte)) {
  108. if (byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r') {
  109. streamer.step_back();
  110. break;
  111. }
  112. sb.append(byte);
  113. }
  114. auto opt_value = sb.to_string().to_uint();
  115. if (!opt_value.has_value()) {
  116. return false;
  117. }
  118. *value = (u16)opt_value.value();
  119. return true;
  120. }
  121. static bool read_comment(PPMLoadingContext& context, Streamer& streamer)
  122. {
  123. (void)context;
  124. bool exist = false;
  125. u8 byte;
  126. while (streamer.read(byte)) {
  127. switch (byte) {
  128. case '#': {
  129. exist = true;
  130. break;
  131. }
  132. case '\t':
  133. case '\n': {
  134. return exist;
  135. }
  136. default:
  137. break;
  138. }
  139. }
  140. return exist;
  141. }
  142. static bool read_magic_number(PPMLoadingContext& context, Streamer& streamer)
  143. {
  144. if (context.state >= PPMLoadingContext::MagicNumber)
  145. return true;
  146. if (!context.data || context.data_size < 2) {
  147. context.state = PPMLoadingContext::State::Error;
  148. #ifdef PPM_DEBUG
  149. dbg() << "There is not enough data.";
  150. #endif
  151. return false;
  152. }
  153. u8 magic_number[2];
  154. if (!streamer.read_bytes(magic_number, 2)) {
  155. context.state = PPMLoadingContext::State::Error;
  156. #ifdef PPM_DEBUG
  157. dbg() << "We can't read magic number.";
  158. #endif
  159. return false;
  160. }
  161. if (magic_number[0] == 'P' && magic_number[1] == '3') {
  162. context.type = PPMLoadingContext::P3_ASCII;
  163. context.state = PPMLoadingContext::MagicNumber;
  164. return true;
  165. }
  166. if (magic_number[0] == 'P' && magic_number[1] == '6') {
  167. context.type = PPMLoadingContext::P6_RAWBITS;
  168. context.state = PPMLoadingContext::MagicNumber;
  169. return true;
  170. }
  171. context.state = PPMLoadingContext::State::Error;
  172. #ifdef PPM_DEBUG
  173. dbg() << "Magic number is not valid." << (char)magic_number[0] << (char)magic_number[1];
  174. #endif
  175. return false;
  176. }
  177. static bool read_white_space(PPMLoadingContext& context, Streamer& streamer)
  178. {
  179. bool exist = false;
  180. u8 byte;
  181. while (streamer.read(byte)) {
  182. switch (byte) {
  183. case ' ':
  184. case '\t':
  185. case '\n':
  186. case '\r': {
  187. exist = true;
  188. break;
  189. }
  190. case '#': {
  191. streamer.step_back();
  192. read_comment(context, streamer);
  193. break;
  194. }
  195. default: {
  196. streamer.step_back();
  197. return exist;
  198. }
  199. }
  200. }
  201. return exist;
  202. }
  203. static bool read_width(PPMLoadingContext& context, Streamer& streamer)
  204. {
  205. bool result = read_number(streamer, &context.width);
  206. if (!result || context.width == 0) {
  207. return false;
  208. }
  209. context.state = PPMLoadingContext::Width;
  210. return true;
  211. }
  212. static bool read_height(PPMLoadingContext& context, Streamer& streamer)
  213. {
  214. bool result = read_number(streamer, &context.height);
  215. if (!result || context.height == 0) {
  216. return false;
  217. }
  218. context.state = PPMLoadingContext::Height;
  219. return true;
  220. }
  221. static bool read_max_val(PPMLoadingContext& context, Streamer& streamer)
  222. {
  223. bool result = read_number(streamer, &context.max_val);
  224. if (!result || context.max_val == 0) {
  225. return false;
  226. }
  227. if (context.max_val > 255) {
  228. #ifdef PPM_DEBUG
  229. dbg() << "We can't parse 2 byte color.";
  230. #endif
  231. context.state = PPMLoadingContext::Error;
  232. return false;
  233. }
  234. context.state = PPMLoadingContext::Maxval;
  235. return true;
  236. }
  237. static bool read_image_data(PPMLoadingContext& context, Streamer& streamer)
  238. {
  239. Vector<Gfx::Color> color_data;
  240. color_data.ensure_capacity(context.width * context.height);
  241. if (context.type == PPMLoadingContext::P3_ASCII) {
  242. u16 red;
  243. u16 green;
  244. u16 blue;
  245. while (true) {
  246. if (!read_number(streamer, &red))
  247. break;
  248. if (!read_white_space(context, streamer))
  249. break;
  250. if (!read_number(streamer, &green))
  251. break;
  252. if (!read_white_space(context, streamer))
  253. break;
  254. if (!read_number(streamer, &blue))
  255. break;
  256. if (!read_white_space(context, streamer))
  257. break;
  258. Color color { (u8)red, (u8)green, (u8)blue };
  259. if (context.max_val < 255)
  260. color = adjust_color(context.max_val, color);
  261. color_data.append(color);
  262. }
  263. } else if (context.type == PPMLoadingContext::P6_RAWBITS) {
  264. u8 pixel[3];
  265. while (streamer.read_bytes(pixel, 3)) {
  266. color_data.append({ pixel[0], pixel[1], pixel[2] });
  267. }
  268. }
  269. if (context.width * context.height != color_data.size())
  270. return false;
  271. context.bitmap = Bitmap::create_purgeable(BitmapFormat::RGB32, { context.width, context.height });
  272. size_t index = 0;
  273. for (int y = 0; y < context.height; ++y) {
  274. for (int x = 0; x < context.width; ++x) {
  275. context.bitmap->set_pixel(x, y, color_data.at(index));
  276. index++;
  277. }
  278. }
  279. context.state = PPMLoadingContext::State::Bitmap;
  280. return true;
  281. }
  282. static bool decode_ppm(PPMLoadingContext& context)
  283. {
  284. if (context.state >= PPMLoadingContext::State::Decoded)
  285. return true;
  286. auto error_guard = ArmedScopeGuard([&] {
  287. context.state = PPMLoadingContext::State::Error;
  288. });
  289. Streamer streamer(context.data, context.data_size);
  290. if (!read_magic_number(context, streamer))
  291. return false;
  292. if (!read_white_space(context, streamer))
  293. return false;
  294. if (!read_width(context, streamer))
  295. return false;
  296. if (!read_white_space(context, streamer))
  297. return false;
  298. if (!read_height(context, streamer))
  299. return false;
  300. if (!read_white_space(context, streamer))
  301. return false;
  302. if (!read_max_val(context, streamer))
  303. return false;
  304. if (!read_white_space(context, streamer))
  305. return false;
  306. if (!read_image_data(context, streamer))
  307. return false;
  308. error_guard.disarm();
  309. context.state = PPMLoadingContext::State::Decoded;
  310. return true;
  311. }
  312. static RefPtr<Gfx::Bitmap> load_ppm_impl(const u8* data, size_t data_size)
  313. {
  314. PPMLoadingContext context;
  315. context.data = data;
  316. context.data_size = data_size;
  317. if (!decode_ppm(context))
  318. return nullptr;
  319. return context.bitmap;
  320. }
  321. RefPtr<Gfx::Bitmap> load_ppm(const StringView& path)
  322. {
  323. MappedFile mapped_file(path);
  324. if (!mapped_file.is_valid()) {
  325. return nullptr;
  326. }
  327. auto bitmap = load_ppm_impl((const u8*)mapped_file.data(), mapped_file.size());
  328. if (bitmap)
  329. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PPM: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  330. return bitmap;
  331. }
  332. RefPtr<Gfx::Bitmap> load_ppm_from_memory(const u8* data, size_t length)
  333. {
  334. auto bitmap = load_ppm_impl(data, length);
  335. if (bitmap)
  336. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PPM: <memory>", bitmap->width(), bitmap->height()));
  337. return bitmap;
  338. }
  339. PPMImageDecoderPlugin::PPMImageDecoderPlugin(const u8* data, size_t size)
  340. {
  341. m_context = make<PPMLoadingContext>();
  342. m_context->data = data;
  343. m_context->data_size = size;
  344. }
  345. PPMImageDecoderPlugin::~PPMImageDecoderPlugin()
  346. {
  347. }
  348. IntSize PPMImageDecoderPlugin::size()
  349. {
  350. if (m_context->state == PPMLoadingContext::State::Error)
  351. return {};
  352. if (m_context->state < PPMLoadingContext::State::Decoded) {
  353. bool success = decode_ppm(*m_context);
  354. if (!success)
  355. return {};
  356. }
  357. return { m_context->width, m_context->height };
  358. }
  359. RefPtr<Gfx::Bitmap> PPMImageDecoderPlugin::bitmap()
  360. {
  361. if (m_context->state == PPMLoadingContext::State::Error)
  362. return nullptr;
  363. if (m_context->state < PPMLoadingContext::State::Decoded) {
  364. bool success = decode_ppm(*m_context);
  365. if (!success)
  366. return nullptr;
  367. }
  368. ASSERT(m_context->bitmap);
  369. return m_context->bitmap;
  370. }
  371. void PPMImageDecoderPlugin::set_volatile()
  372. {
  373. if (m_context->bitmap)
  374. m_context->bitmap->set_volatile();
  375. }
  376. bool PPMImageDecoderPlugin::set_nonvolatile()
  377. {
  378. if (!m_context->bitmap)
  379. return false;
  380. return m_context->bitmap->set_nonvolatile();
  381. }
  382. bool PPMImageDecoderPlugin::sniff()
  383. {
  384. if (m_context->data_size < 2)
  385. return false;
  386. if (m_context->data[0] == 'P' && m_context->data[1] == '3')
  387. return true;
  388. if (m_context->data[0] == 'P' && m_context->data[1] == '6')
  389. return true;
  390. return false;
  391. }
  392. bool PPMImageDecoderPlugin::is_animated()
  393. {
  394. return false;
  395. }
  396. size_t PPMImageDecoderPlugin::loop_count()
  397. {
  398. return 0;
  399. }
  400. size_t PPMImageDecoderPlugin::frame_count()
  401. {
  402. return 1;
  403. }
  404. ImageFrameDescriptor PPMImageDecoderPlugin::frame(size_t i)
  405. {
  406. if (i > 0) {
  407. return { bitmap(), 0 };
  408. }
  409. return {};
  410. }
  411. }