PPMLoader.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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/StringBuilder.h>
  31. #include <string.h>
  32. namespace Gfx {
  33. struct PPMLoadingContext {
  34. enum Type {
  35. Unknown,
  36. P3_ASCII,
  37. P6_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(PPMLoadingContext& 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(PPMLoadingContext& context, Streamer& streamer)
  141. {
  142. if (context.state >= PPMLoadingContext::MagicNumber)
  143. return true;
  144. if (!context.data || context.data_size < 2) {
  145. context.state = PPMLoadingContext::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 = PPMLoadingContext::State::Error;
  152. dbg() << "We can't read magic number.";
  153. return false;
  154. }
  155. if (magic_number[0] == 'P' && magic_number[1] == '3') {
  156. context.type = PPMLoadingContext::P3_ASCII;
  157. context.state = PPMLoadingContext::MagicNumber;
  158. return true;
  159. }
  160. if (magic_number[0] == 'P' && magic_number[1] == '6') {
  161. context.type = PPMLoadingContext::P6_RAWBITS;
  162. context.state = PPMLoadingContext::MagicNumber;
  163. return true;
  164. }
  165. context.state = PPMLoadingContext::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(PPMLoadingContext& 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(PPMLoadingContext& 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 = PPMLoadingContext::Width;
  202. return true;
  203. }
  204. static bool read_height(PPMLoadingContext& 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 = PPMLoadingContext::Height;
  211. return true;
  212. }
  213. static bool read_max_val(PPMLoadingContext& 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 = PPMLoadingContext::Error;
  222. return false;
  223. }
  224. context.state = PPMLoadingContext::Maxval;
  225. return true;
  226. }
  227. static bool read_image_data(PPMLoadingContext& context, Streamer& streamer)
  228. {
  229. Vector<Gfx::Color> color_data;
  230. if (context.type == PPMLoadingContext::P3_ASCII) {
  231. u16 red;
  232. u16 green;
  233. u16 blue;
  234. while (true) {
  235. if (!read_number(streamer, &red))
  236. break;
  237. if (!read_white_space(context, streamer))
  238. break;
  239. if (!read_number(streamer, &green))
  240. break;
  241. if (!read_white_space(context, streamer))
  242. break;
  243. if (!read_number(streamer, &blue))
  244. break;
  245. if (!read_white_space(context, streamer))
  246. break;
  247. Color color { (u8)red, (u8)green, (u8)blue };
  248. if (context.max_val < 255)
  249. color = adjust_color(context.max_val, color);
  250. color_data.append(color);
  251. }
  252. } else if (context.type == PPMLoadingContext::P6_RAWBITS) {
  253. u8 pixel[3];
  254. while (streamer.read_bytes(pixel, 3)) {
  255. color_data.append({ pixel[0], pixel[1], pixel[2] });
  256. }
  257. }
  258. context.bitmap = Bitmap::create_purgeable(BitmapFormat::RGB32, { context.width, context.height });
  259. size_t index = 0;
  260. for (int y = 0; y < context.height; ++y) {
  261. for (int x = 0; x < context.width; ++x) {
  262. context.bitmap->set_pixel(x, y, color_data.at(index));
  263. index++;
  264. }
  265. }
  266. context.state = PPMLoadingContext::State::Bitmap;
  267. return true;
  268. }
  269. static bool decode_ppm(PPMLoadingContext& context)
  270. {
  271. if (context.state >= PPMLoadingContext::State::Decoded)
  272. return true;
  273. Streamer streamer(context.data, context.data_size);
  274. if (!read_magic_number(context, streamer))
  275. return false;
  276. if (!read_white_space(context, streamer))
  277. return false;
  278. if (!read_width(context, streamer))
  279. return false;
  280. if (!read_white_space(context, streamer))
  281. return false;
  282. if (!read_height(context, streamer))
  283. return false;
  284. if (!read_white_space(context, streamer))
  285. return false;
  286. if (!read_max_val(context, streamer))
  287. return false;
  288. if (!read_white_space(context, streamer))
  289. return false;
  290. if (!read_image_data(context, streamer))
  291. return false;
  292. context.state = PPMLoadingContext::State::Decoded;
  293. return true;
  294. }
  295. static RefPtr<Gfx::Bitmap> load_ppm_impl(const u8* data, size_t data_size)
  296. {
  297. PPMLoadingContext context;
  298. context.data = data;
  299. context.data_size = data_size;
  300. if (!decode_ppm(context))
  301. return nullptr;
  302. return context.bitmap;
  303. }
  304. RefPtr<Gfx::Bitmap> load_ppm(const StringView& path)
  305. {
  306. MappedFile mapped_file(path);
  307. if (!mapped_file.is_valid()) {
  308. return nullptr;
  309. }
  310. auto bitmap = load_ppm_impl((const u8*)mapped_file.data(), mapped_file.size());
  311. if (bitmap)
  312. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PPM: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  313. return bitmap;
  314. }
  315. RefPtr<Gfx::Bitmap> load_ppm_from_memory(const u8* data, size_t length)
  316. {
  317. auto bitmap = load_ppm_impl(data, length);
  318. if (bitmap)
  319. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PPM: <memory>", bitmap->width(), bitmap->height()));
  320. return bitmap;
  321. }
  322. PPMImageDecoderPlugin::PPMImageDecoderPlugin(const u8* data, size_t size)
  323. {
  324. m_context = make<PPMLoadingContext>();
  325. m_context->data = data;
  326. m_context->data_size = size;
  327. }
  328. PPMImageDecoderPlugin::~PPMImageDecoderPlugin()
  329. {
  330. }
  331. IntSize PPMImageDecoderPlugin::size()
  332. {
  333. if (m_context->state == PPMLoadingContext::State::Error)
  334. return {};
  335. if (m_context->state < PPMLoadingContext::State::Decoded) {
  336. bool success = decode_ppm(*m_context);
  337. if (!success)
  338. return {};
  339. }
  340. return { m_context->width, m_context->height };
  341. }
  342. RefPtr<Gfx::Bitmap> PPMImageDecoderPlugin::bitmap()
  343. {
  344. if (m_context->state == PPMLoadingContext::State::Error)
  345. return nullptr;
  346. if (m_context->state < PPMLoadingContext::State::Decoded) {
  347. bool success = decode_ppm(*m_context);
  348. if (!success)
  349. return nullptr;
  350. }
  351. ASSERT(m_context->bitmap);
  352. return m_context->bitmap;
  353. }
  354. void PPMImageDecoderPlugin::set_volatile()
  355. {
  356. if (m_context->bitmap)
  357. m_context->bitmap->set_volatile();
  358. }
  359. bool PPMImageDecoderPlugin::set_nonvolatile()
  360. {
  361. if (!m_context->bitmap)
  362. return false;
  363. return m_context->bitmap->set_nonvolatile();
  364. }
  365. bool PPMImageDecoderPlugin::sniff()
  366. {
  367. if (m_context->data_size < 2)
  368. return false;
  369. if (m_context->data[0] == 'P' && m_context->data[1] == '3')
  370. return true;
  371. if (m_context->data[0] == 'P' && m_context->data[1] == '6')
  372. return true;
  373. return false;
  374. }
  375. bool PPMImageDecoderPlugin::is_animated()
  376. {
  377. return false;
  378. }
  379. size_t PPMImageDecoderPlugin::loop_count()
  380. {
  381. return 0;
  382. }
  383. size_t PPMImageDecoderPlugin::frame_count()
  384. {
  385. return 1;
  386. }
  387. ImageFrameDescriptor PPMImageDecoderPlugin::frame(size_t i)
  388. {
  389. if (i > 0) {
  390. return { bitmap(), 0 };
  391. }
  392. return {};
  393. }
  394. }