GIFLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  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 <AK/BufferStream.h>
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/FileSystemPath.h>
  29. #include <AK/MappedFile.h>
  30. #include <AK/NonnullOwnPtrVector.h>
  31. #include <LibGfx/GIFLoader.h>
  32. #include <LibM/math.h>
  33. #include <stdio.h>
  34. #include <string.h>
  35. namespace Gfx {
  36. static bool load_gif_impl(GIFLoadingContext&);
  37. struct GIFLoadingContext {
  38. enum State {
  39. NotDecoded = 0,
  40. Error,
  41. HeaderDecoded,
  42. BitmapDecoded,
  43. };
  44. State state { NotDecoded };
  45. const u8* data { nullptr };
  46. size_t data_size { 0 };
  47. int width { -1 };
  48. int height { -1 };
  49. Vector<RefPtr<Gfx::Bitmap>> frames {};
  50. };
  51. RefPtr<Gfx::Bitmap> load_gif(const StringView& path)
  52. {
  53. MappedFile mapped_file(path);
  54. if (!mapped_file.is_valid())
  55. return nullptr;
  56. GIFImageDecoderPlugin gif_decoder((const u8*)mapped_file.data(), mapped_file.size());
  57. auto bitmap = gif_decoder.bitmap();
  58. if (bitmap)
  59. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded GIF: %s", bitmap->width(), bitmap->height(), canonicalized_path(path).characters()));
  60. return bitmap;
  61. }
  62. RefPtr<Gfx::Bitmap> load_gif_from_memory(const u8* data, size_t length)
  63. {
  64. GIFImageDecoderPlugin gif_decoder(data, length);
  65. auto bitmap = gif_decoder.bitmap();
  66. if (bitmap)
  67. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded GIF: <memory>", bitmap->width(), bitmap->height()));
  68. return bitmap;
  69. }
  70. enum class GIFFormat {
  71. GIF87a,
  72. GIF89a,
  73. };
  74. struct RGB {
  75. u8 r;
  76. u8 g;
  77. u8 b;
  78. };
  79. struct LogicalScreen {
  80. u16 width;
  81. u16 height;
  82. RGB color_map[256];
  83. };
  84. struct ImageDescriptor {
  85. u16 x;
  86. u16 y;
  87. u16 width;
  88. u16 height;
  89. bool use_global_color_map;
  90. RGB color_map[256];
  91. u8 lzw_min_code_size;
  92. Vector<u8> lzw_encoded_bytes;
  93. };
  94. Optional<GIFFormat> decode_gif_header(BufferStream& stream)
  95. {
  96. static const char valid_header_87[] = "GIF87a";
  97. static const char valid_header_89[] = "GIF89a";
  98. char header[6];
  99. for (int i = 0; i < 6; ++i)
  100. stream >> header[i];
  101. if (stream.handle_read_failure())
  102. return {};
  103. if (!memcmp(header, valid_header_87, sizeof(header)))
  104. return GIFFormat::GIF87a;
  105. else if (!memcmp(header, valid_header_89, sizeof(header)))
  106. return GIFFormat::GIF89a;
  107. return {};
  108. }
  109. class LZWDecoder {
  110. public:
  111. struct CodeTableEntry {
  112. Vector<u8> colors;
  113. u16 code;
  114. };
  115. explicit LZWDecoder(const Vector<u8>& lzw_bytes, u8 min_code_size)
  116. : m_lzw_bytes(lzw_bytes)
  117. , m_code_size(min_code_size)
  118. , m_original_code_size(min_code_size)
  119. {
  120. init_code_table();
  121. }
  122. u16 add_control_code()
  123. {
  124. const u16 control_code = m_code_table.size();
  125. m_code_table.append({ {}, control_code });
  126. m_original_code_table.append({ {}, control_code });
  127. if (m_code_table.size() >= pow(2, m_code_size) && m_code_size < 12) {
  128. ++m_code_size;
  129. ++m_original_code_size;
  130. }
  131. return control_code;
  132. }
  133. void reset()
  134. {
  135. m_code_table.clear();
  136. m_code_table.append(m_original_code_table);
  137. m_code_size = m_original_code_size;
  138. m_output.clear();
  139. }
  140. Optional<u16> next_code()
  141. {
  142. size_t current_byte_index = m_current_bit_index / 8;
  143. if (current_byte_index >= m_lzw_bytes.size()) {
  144. return {};
  145. }
  146. // Extract the code bits using a 32-bit mask to cover the possibility that if
  147. // the current code size > 9 bits then the code can span 3 bytes.
  148. u8 current_bit_offset = m_current_bit_index % 8;
  149. u32 mask = (u32)(pow(2, m_code_size) - 1) << current_bit_offset;
  150. // Make a padded copy of the final bytes in the data to ensure we don't read past the end.
  151. if (current_byte_index + sizeof(mask) > m_lzw_bytes.size()) {
  152. u8 padded_last_bytes[sizeof(mask)] = { 0 };
  153. for (int i = 0; current_byte_index + i < m_lzw_bytes.size(); ++i) {
  154. padded_last_bytes[i] = m_lzw_bytes[current_byte_index + i];
  155. }
  156. const u32* addr = (const u32*)&padded_last_bytes;
  157. m_current_code = (*addr & mask) >> current_bit_offset;
  158. } else {
  159. const u32* addr = (const u32*)&m_lzw_bytes.at(current_byte_index);
  160. m_current_code = (*addr & mask) >> current_bit_offset;
  161. }
  162. if (m_current_code > m_code_table.size()) {
  163. dbg() << "Corrupted LZW stream, invalid code: " << m_current_code << " at bit index: "
  164. << m_current_bit_index << ", code table size: " << m_code_table.size();
  165. return {};
  166. }
  167. m_current_bit_index += m_code_size;
  168. return m_current_code;
  169. }
  170. Vector<u8> get_output()
  171. {
  172. ASSERT(m_current_code <= m_code_table.size());
  173. if (m_current_code < m_code_table.size()) {
  174. Vector<u8> new_entry = m_output;
  175. m_output = m_code_table.at(m_current_code).colors;
  176. new_entry.append(m_output[0]);
  177. extend_code_table(new_entry);
  178. } else if (m_current_code == m_code_table.size()) {
  179. m_output.append(m_output[0]);
  180. extend_code_table(m_output);
  181. }
  182. return m_output;
  183. }
  184. private:
  185. void init_code_table()
  186. {
  187. const int initial_table_size = pow(2, m_code_size);
  188. m_code_table.clear();
  189. for (u16 i = 0; i < initial_table_size; ++i) {
  190. m_code_table.append({ { (u8)i }, i });
  191. }
  192. m_original_code_table = m_code_table;
  193. }
  194. void extend_code_table(Vector<u8> entry)
  195. {
  196. if (entry.size() > 1 && m_code_table.size() < 4096) {
  197. m_code_table.append({ entry, (u16)m_code_table.size() });
  198. if (m_code_table.size() >= pow(2, m_code_size) && m_code_size < 12) {
  199. ++m_code_size;
  200. }
  201. }
  202. }
  203. const Vector<u8>& m_lzw_bytes;
  204. int m_current_bit_index { 0 };
  205. Vector<CodeTableEntry> m_code_table {};
  206. Vector<CodeTableEntry> m_original_code_table {};
  207. u8 m_code_size { 0 };
  208. u8 m_original_code_size { 0 };
  209. u16 m_current_code { 0 };
  210. Vector<u8> m_output {};
  211. };
  212. bool load_gif_impl(GIFLoadingContext& context)
  213. {
  214. if (context.data_size < 32)
  215. return false;
  216. auto buffer = ByteBuffer::wrap(context.data, context.data_size);
  217. BufferStream stream(buffer);
  218. Optional<GIFFormat> format = decode_gif_header(stream);
  219. if (!format.has_value()) {
  220. return false;
  221. }
  222. printf("Format is %s\n", format.value() == GIFFormat::GIF89a ? "GIF89a" : "GIF87a");
  223. LogicalScreen logical_screen;
  224. stream >> logical_screen.width;
  225. stream >> logical_screen.height;
  226. if (stream.handle_read_failure())
  227. return false;
  228. context.width = logical_screen.width;
  229. context.height = logical_screen.height;
  230. u8 gcm_info = 0;
  231. stream >> gcm_info;
  232. if (stream.handle_read_failure())
  233. return false;
  234. bool global_color_map_follows_descriptor = gcm_info & 0x80;
  235. u8 bits_per_pixel = (gcm_info & 7) + 1;
  236. u8 bits_of_color_resolution = (gcm_info >> 4) & 7;
  237. printf("LogicalScreen: %dx%d\n", logical_screen.width, logical_screen.height);
  238. printf("global_color_map_follows_descriptor: %u\n", global_color_map_follows_descriptor);
  239. printf("bits_per_pixel: %u\n", bits_per_pixel);
  240. printf("bits_of_color_resolution: %u\n", bits_of_color_resolution);
  241. u8 background_color = 0;
  242. stream >> background_color;
  243. if (stream.handle_read_failure())
  244. return false;
  245. printf("background_color: %u\n", background_color);
  246. u8 pixel_aspect_ratio = 0;
  247. stream >> pixel_aspect_ratio;
  248. if (stream.handle_read_failure())
  249. return false;
  250. int color_map_entry_count = 1;
  251. for (int i = 0; i < bits_per_pixel; ++i)
  252. color_map_entry_count *= 2;
  253. printf("color_map_entry_count: %d\n", color_map_entry_count);
  254. for (int i = 0; i < color_map_entry_count; ++i) {
  255. stream >> logical_screen.color_map[i].r;
  256. stream >> logical_screen.color_map[i].g;
  257. stream >> logical_screen.color_map[i].b;
  258. }
  259. if (stream.handle_read_failure())
  260. return false;
  261. for (int i = 0; i < color_map_entry_count; ++i) {
  262. auto& rgb = logical_screen.color_map[i];
  263. printf("[%02x]: %s\n", i, Color(rgb.r, rgb.g, rgb.b).to_string().characters());
  264. }
  265. NonnullOwnPtrVector<ImageDescriptor> images;
  266. for (;;) {
  267. u8 sentinel = 0;
  268. stream >> sentinel;
  269. printf("Sentinel: %02x\n", sentinel);
  270. if (sentinel == 0x21) {
  271. u8 extension_type = 0;
  272. stream >> extension_type;
  273. if (stream.handle_read_failure())
  274. return false;
  275. printf("Extension block of type %02x\n", extension_type);
  276. u8 sub_block_length = 0;
  277. for (;;) {
  278. stream >> sub_block_length;
  279. if (stream.handle_read_failure())
  280. return false;
  281. if (sub_block_length == 0)
  282. break;
  283. u8 dummy;
  284. for (u16 i = 0; i < sub_block_length; ++i)
  285. stream >> dummy;
  286. if (stream.handle_read_failure())
  287. return false;
  288. }
  289. continue;
  290. }
  291. if (sentinel == 0x2c) {
  292. images.append(make<ImageDescriptor>());
  293. auto& image = images.last();
  294. u8 packed_fields { 0 };
  295. stream >> image.x;
  296. stream >> image.y;
  297. stream >> image.width;
  298. stream >> image.height;
  299. stream >> packed_fields;
  300. if (stream.handle_read_failure())
  301. return false;
  302. printf("Image descriptor: %d,%d %dx%d, %02x\n", image.x, image.y, image.width, image.height, packed_fields);
  303. stream >> image.lzw_min_code_size;
  304. printf("min code size: %u\n", image.lzw_min_code_size);
  305. u8 lzw_encoded_bytes_expected = 0;
  306. for (;;) {
  307. stream >> lzw_encoded_bytes_expected;
  308. if (stream.handle_read_failure())
  309. return false;
  310. if (lzw_encoded_bytes_expected == 0)
  311. break;
  312. u8 buffer[256];
  313. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  314. stream >> buffer[i];
  315. }
  316. if (stream.handle_read_failure())
  317. return false;
  318. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  319. image.lzw_encoded_bytes.append(buffer[i]);
  320. }
  321. }
  322. continue;
  323. }
  324. if (sentinel == 0x3b) {
  325. printf("Trailer! Awesome :)\n");
  326. break;
  327. }
  328. return false;
  329. }
  330. // We exited the block loop after finding a trailer. We should have everything needed.
  331. printf("Image count: %zu\n", images.size());
  332. if (images.is_empty())
  333. return false;
  334. for (size_t i = 0; i < images.size(); ++i) {
  335. auto& image = images.at(i);
  336. printf("Image %zu: %d,%d %dx%d %zu bytes LZW-encoded\n", i, image.x, image.y, image.width, image.height, image.lzw_encoded_bytes.size());
  337. LZWDecoder decoder(image.lzw_encoded_bytes, image.lzw_min_code_size);
  338. // Add GIF-specific control codes
  339. const int clear_code = decoder.add_control_code();
  340. const int end_of_information_code = decoder.add_control_code();
  341. auto bitmap = Bitmap::create_purgeable(BitmapFormat::RGBA32, { image.width, image.height });
  342. int pixel_index = 0;
  343. while (true) {
  344. Optional<u16> code = decoder.next_code();
  345. if (!code.has_value()) {
  346. dbg() << "Unexpectedly reached end of gif frame data";
  347. return false;
  348. }
  349. if (code.value() == clear_code) {
  350. decoder.reset();
  351. continue;
  352. } else if (code.value() == end_of_information_code) {
  353. break;
  354. }
  355. auto colors = decoder.get_output();
  356. for (const auto& color : colors) {
  357. auto rgb = logical_screen.color_map[color];
  358. int x = pixel_index % image.width;
  359. int y = pixel_index / image.width;
  360. Color c = Color(rgb.r, rgb.g, rgb.b);
  361. bitmap->set_pixel(x, y, c);
  362. ++pixel_index;
  363. }
  364. }
  365. context.frames.append(bitmap);
  366. // FIXME: for now only decode the first frame.
  367. break;
  368. }
  369. context.state = GIFLoadingContext::State::BitmapDecoded;
  370. return true;
  371. }
  372. GIFImageDecoderPlugin::GIFImageDecoderPlugin(const u8* data, size_t size)
  373. {
  374. m_context = make<GIFLoadingContext>();
  375. m_context->data = data;
  376. m_context->data_size = size;
  377. }
  378. GIFImageDecoderPlugin::~GIFImageDecoderPlugin() {}
  379. Size GIFImageDecoderPlugin::size()
  380. {
  381. if (m_context->state == GIFLoadingContext::State::Error) {
  382. return {};
  383. }
  384. if (m_context->state < GIFLoadingContext::State::BitmapDecoded) {
  385. if (!load_gif_impl(*m_context)) {
  386. m_context->state = GIFLoadingContext::State::Error;
  387. return {};
  388. }
  389. }
  390. return { m_context->width, m_context->height };
  391. }
  392. RefPtr<Gfx::Bitmap> GIFImageDecoderPlugin::bitmap()
  393. {
  394. if (m_context->state == GIFLoadingContext::State::Error) {
  395. return nullptr;
  396. }
  397. if (m_context->state < GIFLoadingContext::State::BitmapDecoded) {
  398. if (!load_gif_impl(*m_context)) {
  399. m_context->state = GIFLoadingContext::State::Error;
  400. return nullptr;
  401. }
  402. }
  403. // FIXME: for now only return the first frame.
  404. if (m_context->frames.is_empty()) {
  405. return nullptr;
  406. }
  407. return m_context->frames.first();
  408. }
  409. void GIFImageDecoderPlugin::set_volatile()
  410. {
  411. for (auto& frame : m_context->frames) {
  412. frame->set_volatile();
  413. }
  414. }
  415. bool GIFImageDecoderPlugin::set_nonvolatile()
  416. {
  417. if (m_context->frames.is_empty()) {
  418. return false;
  419. }
  420. bool success = true;
  421. for (auto& frame : m_context->frames) {
  422. success &= frame->set_nonvolatile();
  423. }
  424. return success;
  425. }
  426. bool GIFImageDecoderPlugin::sniff()
  427. {
  428. auto buffer = ByteBuffer::wrap(m_context->data, m_context->data_size);
  429. BufferStream stream(buffer);
  430. return decode_gif_header(stream).has_value();
  431. }
  432. bool GIFImageDecoderPlugin::is_animated()
  433. {
  434. return false;
  435. }
  436. size_t GIFImageDecoderPlugin::loop_count()
  437. {
  438. return 0;
  439. }
  440. size_t GIFImageDecoderPlugin::frame_count()
  441. {
  442. return 1;
  443. }
  444. ImageFrameDescriptor GIFImageDecoderPlugin::frame(size_t i)
  445. {
  446. if (i > 0) {
  447. return { bitmap(), 0 };
  448. }
  449. return {};
  450. }
  451. }