GIFLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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/LexicalPath.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_frame_descriptors(GIFLoadingContext&);
  37. struct RGB {
  38. u8 r;
  39. u8 g;
  40. u8 b;
  41. };
  42. struct ImageDescriptor {
  43. u16 x;
  44. u16 y;
  45. u16 width;
  46. u16 height;
  47. bool use_global_color_map;
  48. RGB color_map[256];
  49. u8 lzw_min_code_size;
  50. Vector<u8> lzw_encoded_bytes;
  51. RefPtr<Gfx::Bitmap> bitmap;
  52. // Fields from optional graphic control extension block
  53. enum DisposalMethod : u8 {
  54. None = 0,
  55. InPlace = 1,
  56. RestoreBackground = 2,
  57. RestorePrevious = 3,
  58. };
  59. DisposalMethod disposal_method { None };
  60. u8 transparency_index { 0 };
  61. u16 duration { 0 };
  62. bool transparent { false };
  63. bool user_input { false };
  64. };
  65. struct LogicalScreen {
  66. u16 width;
  67. u16 height;
  68. RGB color_map[256];
  69. };
  70. struct GIFLoadingContext {
  71. enum State {
  72. NotDecoded = 0,
  73. Error,
  74. FrameDescriptorsLoaded,
  75. };
  76. State state { NotDecoded };
  77. size_t frames_decoded { 0 };
  78. const u8* data { nullptr };
  79. size_t data_size { 0 };
  80. LogicalScreen logical_screen {};
  81. u8 background_color_index { 0 };
  82. NonnullOwnPtrVector<ImageDescriptor> images {};
  83. size_t loops { 1 };
  84. };
  85. RefPtr<Gfx::Bitmap> load_gif(const StringView& path)
  86. {
  87. MappedFile mapped_file(path);
  88. if (!mapped_file.is_valid())
  89. return nullptr;
  90. GIFImageDecoderPlugin gif_decoder((const u8*)mapped_file.data(), mapped_file.size());
  91. auto bitmap = gif_decoder.bitmap();
  92. if (bitmap)
  93. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded GIF: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  94. return bitmap;
  95. }
  96. RefPtr<Gfx::Bitmap> load_gif_from_memory(const u8* data, size_t length)
  97. {
  98. GIFImageDecoderPlugin gif_decoder(data, length);
  99. auto bitmap = gif_decoder.bitmap();
  100. if (bitmap)
  101. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded GIF: <memory>", bitmap->width(), bitmap->height()));
  102. return bitmap;
  103. }
  104. enum class GIFFormat {
  105. GIF87a,
  106. GIF89a,
  107. };
  108. Optional<GIFFormat> decode_gif_header(BufferStream& stream)
  109. {
  110. static const char valid_header_87[] = "GIF87a";
  111. static const char valid_header_89[] = "GIF89a";
  112. char header[6];
  113. for (int i = 0; i < 6; ++i)
  114. stream >> header[i];
  115. if (stream.handle_read_failure())
  116. return {};
  117. if (!memcmp(header, valid_header_87, sizeof(header)))
  118. return GIFFormat::GIF87a;
  119. else if (!memcmp(header, valid_header_89, sizeof(header)))
  120. return GIFFormat::GIF89a;
  121. return {};
  122. }
  123. class LZWDecoder {
  124. private:
  125. static constexpr int max_code_size = 12;
  126. public:
  127. explicit LZWDecoder(const Vector<u8>& lzw_bytes, u8 min_code_size)
  128. : m_lzw_bytes(lzw_bytes)
  129. , m_code_size(min_code_size)
  130. , m_original_code_size(min_code_size)
  131. , m_table_capacity(pow(2, min_code_size))
  132. {
  133. init_code_table();
  134. }
  135. u16 add_control_code()
  136. {
  137. const u16 control_code = m_code_table.size();
  138. m_code_table.append(Vector<u8> {});
  139. m_original_code_table.append(Vector<u8> {});
  140. if (m_code_table.size() >= m_table_capacity && m_code_size < max_code_size) {
  141. ++m_code_size;
  142. ++m_original_code_size;
  143. m_table_capacity *= 2;
  144. }
  145. return control_code;
  146. }
  147. void reset()
  148. {
  149. m_code_table.clear();
  150. m_code_table.append(m_original_code_table);
  151. m_code_size = m_original_code_size;
  152. m_table_capacity = pow(2, m_code_size);
  153. m_output.clear();
  154. }
  155. Optional<u16> next_code()
  156. {
  157. size_t current_byte_index = m_current_bit_index / 8;
  158. if (current_byte_index >= m_lzw_bytes.size()) {
  159. return {};
  160. }
  161. // Extract the code bits using a 32-bit mask to cover the possibility that if
  162. // the current code size > 9 bits then the code can span 3 bytes.
  163. u8 current_bit_offset = m_current_bit_index % 8;
  164. u32 mask = (u32)(m_table_capacity - 1) << current_bit_offset;
  165. // Make a padded copy of the final bytes in the data to ensure we don't read past the end.
  166. if (current_byte_index + sizeof(mask) > m_lzw_bytes.size()) {
  167. u8 padded_last_bytes[sizeof(mask)] = { 0 };
  168. for (int i = 0; current_byte_index + i < m_lzw_bytes.size(); ++i) {
  169. padded_last_bytes[i] = m_lzw_bytes[current_byte_index + i];
  170. }
  171. const u32* addr = (const u32*)&padded_last_bytes;
  172. m_current_code = (*addr & mask) >> current_bit_offset;
  173. } else {
  174. const u32* addr = (const u32*)&m_lzw_bytes.at(current_byte_index);
  175. m_current_code = (*addr & mask) >> current_bit_offset;
  176. }
  177. if (m_current_code > m_code_table.size()) {
  178. dbg() << "Corrupted LZW stream, invalid code: " << m_current_code << " at bit index: "
  179. << m_current_bit_index << ", code table size: " << m_code_table.size();
  180. return {};
  181. }
  182. m_current_bit_index += m_code_size;
  183. return m_current_code;
  184. }
  185. Vector<u8>& get_output()
  186. {
  187. ASSERT(m_current_code <= m_code_table.size());
  188. if (m_current_code < m_code_table.size()) {
  189. Vector<u8> new_entry = m_output;
  190. m_output = m_code_table.at(m_current_code);
  191. new_entry.append(m_output[0]);
  192. extend_code_table(new_entry);
  193. } else if (m_current_code == m_code_table.size()) {
  194. m_output.append(m_output[0]);
  195. extend_code_table(m_output);
  196. }
  197. return m_output;
  198. }
  199. private:
  200. void init_code_table()
  201. {
  202. m_code_table.clear();
  203. for (u16 i = 0; i < m_table_capacity; ++i) {
  204. m_code_table.append({ (u8)i });
  205. }
  206. m_original_code_table = m_code_table;
  207. }
  208. void extend_code_table(const Vector<u8>& entry)
  209. {
  210. if (entry.size() > 1 && m_code_table.size() < 4096) {
  211. m_code_table.append(entry);
  212. if (m_code_table.size() >= m_table_capacity && m_code_size < max_code_size) {
  213. ++m_code_size;
  214. m_table_capacity *= 2;
  215. }
  216. }
  217. }
  218. const Vector<u8>& m_lzw_bytes;
  219. int m_current_bit_index { 0 };
  220. Vector<Vector<u8>> m_code_table {};
  221. Vector<Vector<u8>> m_original_code_table {};
  222. u8 m_code_size { 0 };
  223. u8 m_original_code_size { 0 };
  224. u32 m_table_capacity { 0 };
  225. u16 m_current_code { 0 };
  226. Vector<u8> m_output {};
  227. };
  228. bool decode_frames_up_to_index(GIFLoadingContext& context, size_t frame_index)
  229. {
  230. if (frame_index >= context.images.size()) {
  231. return false;
  232. }
  233. for (size_t i = context.frames_decoded; i <= frame_index; ++i) {
  234. auto& image = context.images.at(i);
  235. 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());
  236. dbg() << "Decoding frame: " << i + 1 << " of " << context.images.size();
  237. LZWDecoder decoder(image.lzw_encoded_bytes, image.lzw_min_code_size);
  238. // Add GIF-specific control codes
  239. const int clear_code = decoder.add_control_code();
  240. const int end_of_information_code = decoder.add_control_code();
  241. auto background_rgb = context.logical_screen.color_map[context.background_color_index];
  242. Color background_color = Color(background_rgb.r, background_rgb.g, background_rgb.b);
  243. image.bitmap = Bitmap::create_purgeable(BitmapFormat::RGBA32, { context.logical_screen.width, context.logical_screen.height });
  244. image.bitmap->fill(background_color);
  245. if (i > 0 && image.disposal_method == ImageDescriptor::DisposalMethod::InPlace) {
  246. for (int y = 0; y < image.bitmap->height(); ++y) {
  247. for (int x = 0; x < image.bitmap->width(); ++x) {
  248. image.bitmap->set_pixel(x, y, context.images.at(i - 1).bitmap->get_pixel(x, y));
  249. }
  250. }
  251. }
  252. int pixel_index = 0;
  253. RGB transparent_color { 0, 0, 0 };
  254. if (image.transparent) {
  255. transparent_color = context.logical_screen.color_map[image.transparency_index];
  256. }
  257. while (true) {
  258. Optional<u16> code = decoder.next_code();
  259. if (!code.has_value()) {
  260. dbg() << "Unexpectedly reached end of gif frame data";
  261. return false;
  262. }
  263. if (code.value() == clear_code) {
  264. decoder.reset();
  265. continue;
  266. } else if (code.value() == end_of_information_code) {
  267. break;
  268. }
  269. auto colors = decoder.get_output();
  270. for (const auto& color : colors) {
  271. auto rgb = context.logical_screen.color_map[color];
  272. int x = pixel_index % image.width + image.x;
  273. int y = pixel_index / image.width + image.y;
  274. Color c = Color(rgb.r, rgb.g, rgb.b);
  275. if (image.transparent) {
  276. if (rgb.r == transparent_color.r && rgb.g == transparent_color.g && rgb.b == transparent_color.b) {
  277. c.set_alpha(0);
  278. }
  279. }
  280. image.bitmap->set_pixel(x, y, c);
  281. ++pixel_index;
  282. }
  283. }
  284. ++context.frames_decoded;
  285. }
  286. return true;
  287. }
  288. bool load_gif_frame_descriptors(GIFLoadingContext& context)
  289. {
  290. if (context.data_size < 32)
  291. return false;
  292. auto buffer = ByteBuffer::wrap(context.data, context.data_size);
  293. BufferStream stream(buffer);
  294. Optional<GIFFormat> format = decode_gif_header(stream);
  295. if (!format.has_value()) {
  296. return false;
  297. }
  298. printf("Format is %s\n", format.value() == GIFFormat::GIF89a ? "GIF89a" : "GIF87a");
  299. stream >> context.logical_screen.width;
  300. stream >> context.logical_screen.height;
  301. if (stream.handle_read_failure())
  302. return false;
  303. u8 gcm_info = 0;
  304. stream >> gcm_info;
  305. if (stream.handle_read_failure())
  306. return false;
  307. bool global_color_map_follows_descriptor = gcm_info & 0x80;
  308. u8 bits_per_pixel = (gcm_info & 7) + 1;
  309. u8 bits_of_color_resolution = (gcm_info >> 4) & 7;
  310. printf("LogicalScreen: %dx%d\n", context.logical_screen.width, context.logical_screen.height);
  311. printf("global_color_map_follows_descriptor: %u\n", global_color_map_follows_descriptor);
  312. printf("bits_per_pixel: %u\n", bits_per_pixel);
  313. printf("bits_of_color_resolution: %u\n", bits_of_color_resolution);
  314. stream >> context.background_color_index;
  315. if (stream.handle_read_failure())
  316. return false;
  317. printf("background_color: %u\n", context.background_color_index);
  318. u8 pixel_aspect_ratio = 0;
  319. stream >> pixel_aspect_ratio;
  320. if (stream.handle_read_failure())
  321. return false;
  322. int color_map_entry_count = 1;
  323. for (int i = 0; i < bits_per_pixel; ++i)
  324. color_map_entry_count *= 2;
  325. printf("color_map_entry_count: %d\n", color_map_entry_count);
  326. for (int i = 0; i < color_map_entry_count; ++i) {
  327. stream >> context.logical_screen.color_map[i].r;
  328. stream >> context.logical_screen.color_map[i].g;
  329. stream >> context.logical_screen.color_map[i].b;
  330. }
  331. if (stream.handle_read_failure())
  332. return false;
  333. for (int i = 0; i < color_map_entry_count; ++i) {
  334. auto& rgb = context.logical_screen.color_map[i];
  335. printf("[%02x]: %s\n", i, Color(rgb.r, rgb.g, rgb.b).to_string().characters());
  336. }
  337. NonnullOwnPtr<ImageDescriptor> current_image = make<ImageDescriptor>();
  338. for (;;) {
  339. u8 sentinel = 0;
  340. stream >> sentinel;
  341. printf("Sentinel: %02x\n", sentinel);
  342. if (sentinel == 0x21) {
  343. u8 extension_type = 0;
  344. stream >> extension_type;
  345. if (stream.handle_read_failure())
  346. return false;
  347. printf("Extension block of type %02x\n", extension_type);
  348. u8 sub_block_length = 0;
  349. Vector<u8> sub_block {};
  350. for (;;) {
  351. stream >> sub_block_length;
  352. if (stream.handle_read_failure())
  353. return false;
  354. if (sub_block_length == 0)
  355. break;
  356. u8 dummy = 0;
  357. for (u16 i = 0; i < sub_block_length; ++i) {
  358. stream >> dummy;
  359. sub_block.append(dummy);
  360. }
  361. if (stream.handle_read_failure())
  362. return false;
  363. }
  364. if (extension_type == 0xF9) {
  365. if (sub_block.size() != 4) {
  366. dbg() << "Unexpected graphic control size";
  367. continue;
  368. }
  369. u8 disposal_method = (sub_block[0] & 0x1C) >> 2;
  370. current_image->disposal_method = (ImageDescriptor::DisposalMethod)disposal_method;
  371. u8 user_input = (sub_block[0] & 0x2) >> 1;
  372. current_image->user_input = user_input == 1;
  373. u8 transparent = sub_block[0] & 1;
  374. current_image->transparent = transparent == 1;
  375. u16 duration = sub_block[1] + ((u16)sub_block[2] >> 8);
  376. current_image->duration = duration;
  377. current_image->transparency_index = sub_block[3];
  378. }
  379. if (extension_type == 0xFF) {
  380. if (sub_block.size() != 14) {
  381. dbg() << "Unexpected application extension size: " << sub_block.size();
  382. continue;
  383. }
  384. if (sub_block[11] != 1) {
  385. dbg() << "Unexpected application extension format";
  386. continue;
  387. }
  388. u16 loops = sub_block[12] + (sub_block[13] << 8);
  389. context.loops = loops;
  390. }
  391. continue;
  392. }
  393. if (sentinel == 0x2c) {
  394. context.images.append(move(current_image));
  395. auto& image = context.images.last();
  396. u8 packed_fields { 0 };
  397. stream >> image.x;
  398. stream >> image.y;
  399. stream >> image.width;
  400. stream >> image.height;
  401. stream >> packed_fields;
  402. if (stream.handle_read_failure())
  403. return false;
  404. printf("Image descriptor: %d,%d %dx%d, %02x\n", image.x, image.y, image.width, image.height, packed_fields);
  405. stream >> image.lzw_min_code_size;
  406. printf("min code size: %u\n", image.lzw_min_code_size);
  407. u8 lzw_encoded_bytes_expected = 0;
  408. for (;;) {
  409. stream >> lzw_encoded_bytes_expected;
  410. if (stream.handle_read_failure())
  411. return false;
  412. if (lzw_encoded_bytes_expected == 0)
  413. break;
  414. u8 buffer[256];
  415. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  416. stream >> buffer[i];
  417. }
  418. if (stream.handle_read_failure())
  419. return false;
  420. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  421. image.lzw_encoded_bytes.append(buffer[i]);
  422. }
  423. }
  424. current_image = make<ImageDescriptor>();
  425. continue;
  426. }
  427. if (sentinel == 0x3b) {
  428. printf("Trailer! Awesome :)\n");
  429. break;
  430. }
  431. return false;
  432. }
  433. context.state = GIFLoadingContext::State::FrameDescriptorsLoaded;
  434. return true;
  435. }
  436. GIFImageDecoderPlugin::GIFImageDecoderPlugin(const u8* data, size_t size)
  437. {
  438. m_context = make<GIFLoadingContext>();
  439. m_context->data = data;
  440. m_context->data_size = size;
  441. }
  442. GIFImageDecoderPlugin::~GIFImageDecoderPlugin() {}
  443. IntSize GIFImageDecoderPlugin::size()
  444. {
  445. if (m_context->state == GIFLoadingContext::State::Error) {
  446. return {};
  447. }
  448. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  449. if (!load_gif_frame_descriptors(*m_context)) {
  450. m_context->state = GIFLoadingContext::State::Error;
  451. return {};
  452. }
  453. }
  454. return { m_context->logical_screen.width, m_context->logical_screen.height };
  455. }
  456. RefPtr<Gfx::Bitmap> GIFImageDecoderPlugin::bitmap()
  457. {
  458. return frame(0).image;
  459. }
  460. void GIFImageDecoderPlugin::set_volatile()
  461. {
  462. for (size_t i = 0; i < m_context->frames_decoded; ++i) {
  463. m_context->images.at(i).bitmap->set_volatile();
  464. }
  465. }
  466. bool GIFImageDecoderPlugin::set_nonvolatile()
  467. {
  468. if (m_context->images.is_empty()) {
  469. return false;
  470. }
  471. bool success = true;
  472. for (size_t i = 0; i < m_context->frames_decoded; ++i) {
  473. success &= m_context->images.at(i).bitmap->set_nonvolatile();
  474. }
  475. return success;
  476. }
  477. bool GIFImageDecoderPlugin::sniff()
  478. {
  479. auto buffer = ByteBuffer::wrap(m_context->data, m_context->data_size);
  480. BufferStream stream(buffer);
  481. return decode_gif_header(stream).has_value();
  482. }
  483. bool GIFImageDecoderPlugin::is_animated()
  484. {
  485. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  486. if (!load_gif_frame_descriptors(*m_context)) {
  487. m_context->state = GIFLoadingContext::State::Error;
  488. return false;
  489. }
  490. }
  491. return m_context->images.size() > 1;
  492. }
  493. size_t GIFImageDecoderPlugin::loop_count()
  494. {
  495. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  496. if (!load_gif_frame_descriptors(*m_context)) {
  497. m_context->state = GIFLoadingContext::State::Error;
  498. return 0;
  499. }
  500. }
  501. return m_context->loops;
  502. }
  503. size_t GIFImageDecoderPlugin::frame_count()
  504. {
  505. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  506. if (!load_gif_frame_descriptors(*m_context)) {
  507. m_context->state = GIFLoadingContext::State::Error;
  508. return 1;
  509. }
  510. }
  511. return m_context->images.size();
  512. }
  513. ImageFrameDescriptor GIFImageDecoderPlugin::frame(size_t i)
  514. {
  515. if (m_context->state == GIFLoadingContext::State::Error) {
  516. return {};
  517. }
  518. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  519. if (!load_gif_frame_descriptors(*m_context)) {
  520. m_context->state = GIFLoadingContext::State::Error;
  521. return {};
  522. }
  523. }
  524. if (!decode_frames_up_to_index(*m_context, i)) {
  525. m_context->state = GIFLoadingContext::State::Error;
  526. return {};
  527. }
  528. ImageFrameDescriptor frame {};
  529. frame.image = m_context->images.at(i).bitmap;
  530. frame.duration = m_context->images.at(i).duration * 10;
  531. if (frame.duration <= 10) {
  532. frame.duration = 100;
  533. }
  534. return frame;
  535. }
  536. }