GIFLoader.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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/Array.h>
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/MappedFile.h>
  30. #include <AK/MemoryStream.h>
  31. #include <AK/NonnullOwnPtrVector.h>
  32. #include <LibGfx/GIFLoader.h>
  33. #include <LibGfx/Painter.h>
  34. #include <math.h>
  35. #include <stdio.h>
  36. #include <string.h>
  37. //#define GIF_DEBUG
  38. namespace Gfx {
  39. // Row strides and offsets for each interlace pass.
  40. static const int INTERLACE_ROW_STRIDES[] = { 8, 8, 4, 2 };
  41. static const int INTERLACE_ROW_OFFSETS[] = { 0, 4, 2, 1 };
  42. struct ImageDescriptor {
  43. u16 x { 0 };
  44. u16 y { 0 };
  45. u16 width { 0 };
  46. u16 height { 0 };
  47. bool use_global_color_map { true };
  48. bool interlaced { false };
  49. Color color_map[256];
  50. u8 lzw_min_code_size { 0 };
  51. Vector<u8> lzw_encoded_bytes;
  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. const IntRect rect() const
  65. {
  66. return { this->x, this->y, this->width, this->height };
  67. }
  68. };
  69. struct LogicalScreen {
  70. u16 width;
  71. u16 height;
  72. Color color_map[256];
  73. };
  74. struct GIFLoadingContext {
  75. enum State {
  76. NotDecoded = 0,
  77. FrameDescriptorsLoaded,
  78. FrameComplete,
  79. };
  80. State state { NotDecoded };
  81. enum ErrorState {
  82. NoError = 0,
  83. FailedToDecodeAllFrames,
  84. FailedToDecodeAnyFrame,
  85. FailedToLoadFrameDescriptors,
  86. };
  87. ErrorState error_state { NoError };
  88. const u8* data { nullptr };
  89. size_t data_size { 0 };
  90. LogicalScreen logical_screen {};
  91. u8 background_color_index { 0 };
  92. NonnullOwnPtrVector<ImageDescriptor> images {};
  93. size_t loops { 1 };
  94. RefPtr<Gfx::Bitmap> frame_buffer;
  95. size_t current_frame { 0 };
  96. RefPtr<Gfx::Bitmap> prev_frame_buffer;
  97. };
  98. RefPtr<Gfx::Bitmap> load_gif(const StringView& path)
  99. {
  100. auto file_or_error = MappedFile::map(path);
  101. if (file_or_error.is_error())
  102. return nullptr;
  103. GIFImageDecoderPlugin gif_decoder((const u8*)file_or_error.value()->data(), file_or_error.value()->size());
  104. auto bitmap = gif_decoder.bitmap();
  105. if (bitmap)
  106. bitmap->set_mmap_name(String::formatted("Gfx::Bitmap [{}] - Decoded GIF: {}", bitmap->size(), LexicalPath::canonicalized_path(path)));
  107. return bitmap;
  108. }
  109. RefPtr<Gfx::Bitmap> load_gif_from_memory(const u8* data, size_t length)
  110. {
  111. GIFImageDecoderPlugin gif_decoder(data, length);
  112. auto bitmap = gif_decoder.bitmap();
  113. if (bitmap)
  114. bitmap->set_mmap_name(String::formatted("Gfx::Bitmap [{}] - Decoded GIF: <memory>", bitmap->size()));
  115. return bitmap;
  116. }
  117. enum class GIFFormat {
  118. GIF87a,
  119. GIF89a,
  120. };
  121. static Optional<GIFFormat> decode_gif_header(InputMemoryStream& stream)
  122. {
  123. static const char valid_header_87[] = "GIF87a";
  124. static const char valid_header_89[] = "GIF89a";
  125. Array<u8, 6> header;
  126. stream >> header;
  127. if (stream.handle_any_error())
  128. return {};
  129. if (header.span() == ReadonlyBytes { valid_header_87, 6 })
  130. return GIFFormat::GIF87a;
  131. if (header.span() == ReadonlyBytes { valid_header_89, 6 })
  132. return GIFFormat::GIF89a;
  133. return {};
  134. }
  135. class LZWDecoder {
  136. private:
  137. static constexpr int max_code_size = 12;
  138. public:
  139. explicit LZWDecoder(const Vector<u8>& lzw_bytes, u8 min_code_size)
  140. : m_lzw_bytes(lzw_bytes)
  141. , m_code_size(min_code_size)
  142. , m_original_code_size(min_code_size)
  143. , m_table_capacity(pow(2, min_code_size))
  144. {
  145. init_code_table();
  146. }
  147. u16 add_control_code()
  148. {
  149. const u16 control_code = m_code_table.size();
  150. m_code_table.append(Vector<u8> {});
  151. m_original_code_table.append(Vector<u8> {});
  152. if (m_code_table.size() >= m_table_capacity && m_code_size < max_code_size) {
  153. ++m_code_size;
  154. ++m_original_code_size;
  155. m_table_capacity *= 2;
  156. }
  157. return control_code;
  158. }
  159. void reset()
  160. {
  161. m_code_table.clear();
  162. m_code_table.append(m_original_code_table);
  163. m_code_size = m_original_code_size;
  164. m_table_capacity = pow(2, m_code_size);
  165. m_output.clear();
  166. }
  167. Optional<u16> next_code()
  168. {
  169. size_t current_byte_index = m_current_bit_index / 8;
  170. if (current_byte_index >= m_lzw_bytes.size()) {
  171. return {};
  172. }
  173. // Extract the code bits using a 32-bit mask to cover the possibility that if
  174. // the current code size > 9 bits then the code can span 3 bytes.
  175. u8 current_bit_offset = m_current_bit_index % 8;
  176. u32 mask = (u32)(m_table_capacity - 1) << current_bit_offset;
  177. // Make a padded copy of the final bytes in the data to ensure we don't read past the end.
  178. if (current_byte_index + sizeof(mask) > m_lzw_bytes.size()) {
  179. u8 padded_last_bytes[sizeof(mask)] = { 0 };
  180. for (int i = 0; current_byte_index + i < m_lzw_bytes.size(); ++i) {
  181. padded_last_bytes[i] = m_lzw_bytes[current_byte_index + i];
  182. }
  183. const u32* addr = (const u32*)&padded_last_bytes;
  184. m_current_code = (*addr & mask) >> current_bit_offset;
  185. } else {
  186. const u32* addr = (const u32*)&m_lzw_bytes.at(current_byte_index);
  187. m_current_code = (*addr & mask) >> current_bit_offset;
  188. }
  189. if (m_current_code > m_code_table.size()) {
  190. #ifdef GIF_DEBUG
  191. dbg() << "Corrupted LZW stream, invalid code: " << m_current_code << " at bit index: "
  192. << m_current_bit_index << ", code table size: " << m_code_table.size();
  193. #endif
  194. return {};
  195. } else if (m_current_code == m_code_table.size() && m_output.is_empty()) {
  196. #ifdef GIF_DEBUG
  197. dbg() << "Corrupted LZW stream, valid new code but output buffer is empty: " << m_current_code
  198. << " at bit index: " << m_current_bit_index << ", code table size: " << m_code_table.size();
  199. #endif
  200. return {};
  201. }
  202. m_current_bit_index += m_code_size;
  203. return m_current_code;
  204. }
  205. Vector<u8>& get_output()
  206. {
  207. ASSERT(m_current_code <= m_code_table.size());
  208. if (m_current_code < m_code_table.size()) {
  209. Vector<u8> new_entry = m_output;
  210. m_output = m_code_table.at(m_current_code);
  211. new_entry.append(m_output[0]);
  212. extend_code_table(new_entry);
  213. } else if (m_current_code == m_code_table.size()) {
  214. ASSERT(!m_output.is_empty());
  215. m_output.append(m_output[0]);
  216. extend_code_table(m_output);
  217. }
  218. return m_output;
  219. }
  220. private:
  221. void init_code_table()
  222. {
  223. m_code_table.clear();
  224. for (u16 i = 0; i < m_table_capacity; ++i) {
  225. m_code_table.append({ (u8)i });
  226. }
  227. m_original_code_table = m_code_table;
  228. }
  229. void extend_code_table(const Vector<u8>& entry)
  230. {
  231. if (entry.size() > 1 && m_code_table.size() < 4096) {
  232. m_code_table.append(entry);
  233. if (m_code_table.size() >= m_table_capacity && m_code_size < max_code_size) {
  234. ++m_code_size;
  235. m_table_capacity *= 2;
  236. }
  237. }
  238. }
  239. const Vector<u8>& m_lzw_bytes;
  240. int m_current_bit_index { 0 };
  241. Vector<Vector<u8>> m_code_table {};
  242. Vector<Vector<u8>> m_original_code_table {};
  243. u8 m_code_size { 0 };
  244. u8 m_original_code_size { 0 };
  245. u32 m_table_capacity { 0 };
  246. u16 m_current_code { 0 };
  247. Vector<u8> m_output {};
  248. };
  249. static void copy_frame_buffer(Bitmap& dest, const Bitmap& src)
  250. {
  251. ASSERT(dest.size_in_bytes() == src.size_in_bytes());
  252. memcpy(dest.scanline(0), src.scanline(0), dest.size_in_bytes());
  253. }
  254. static bool decode_frame(GIFLoadingContext& context, size_t frame_index)
  255. {
  256. if (frame_index >= context.images.size()) {
  257. return false;
  258. }
  259. if (context.state >= GIFLoadingContext::State::FrameComplete && frame_index == context.current_frame) {
  260. return true;
  261. }
  262. size_t start_frame = context.current_frame + 1;
  263. if (context.state < GIFLoadingContext::State::FrameComplete) {
  264. start_frame = 0;
  265. context.frame_buffer = Bitmap::create_purgeable(BitmapFormat::RGBA32, { context.logical_screen.width, context.logical_screen.height });
  266. if (!context.frame_buffer)
  267. return false;
  268. context.prev_frame_buffer = Bitmap::create_purgeable(BitmapFormat::RGBA32, { context.logical_screen.width, context.logical_screen.height });
  269. if (!context.prev_frame_buffer)
  270. return false;
  271. } else if (frame_index < context.current_frame) {
  272. start_frame = 0;
  273. }
  274. for (size_t i = start_frame; i <= frame_index; ++i) {
  275. auto& image = context.images.at(i);
  276. const auto previous_image_disposal_method = i > 0 ? context.images.at(i - 1).disposal_method : ImageDescriptor::DisposalMethod::None;
  277. if (i == 0) {
  278. context.frame_buffer->fill(Color::Transparent);
  279. } else if (i > 0 && image.disposal_method == ImageDescriptor::DisposalMethod::RestorePrevious
  280. && previous_image_disposal_method != ImageDescriptor::DisposalMethod::RestorePrevious) {
  281. // This marks the start of a run of frames that once disposed should be restored to the
  282. // previous underlying image contents. Therefore we make a copy of the current frame
  283. // buffer so that it can be restored later.
  284. copy_frame_buffer(*context.prev_frame_buffer, *context.frame_buffer);
  285. }
  286. if (previous_image_disposal_method == ImageDescriptor::DisposalMethod::RestoreBackground) {
  287. // Note: RestoreBackground could be interpreted either as restoring the underlying
  288. // background of the entire image (e.g. container element's background-color), or the
  289. // background color of the GIF itself. It appears that all major browsers and most other
  290. // GIF decoders adhere to the former interpretation, therefore we will do the same by
  291. // clearing the entire frame buffer to transparent.
  292. Painter painter(*context.frame_buffer);
  293. painter.clear_rect(context.images.at(i - 1).rect(), Color::Transparent);
  294. } else if (i > 0 && previous_image_disposal_method == ImageDescriptor::DisposalMethod::RestorePrevious) {
  295. // Previous frame indicated that once disposed, it should be restored to *its* previous
  296. // underlying image contents, therefore we restore the saved previous frame buffer.
  297. copy_frame_buffer(*context.frame_buffer, *context.prev_frame_buffer);
  298. }
  299. LZWDecoder decoder(image.lzw_encoded_bytes, image.lzw_min_code_size);
  300. // Add GIF-specific control codes
  301. const int clear_code = decoder.add_control_code();
  302. const int end_of_information_code = decoder.add_control_code();
  303. const auto& color_map = image.use_global_color_map ? context.logical_screen.color_map : image.color_map;
  304. int pixel_index = 0;
  305. int row = 0;
  306. int interlace_pass = 0;
  307. while (true) {
  308. Optional<u16> code = decoder.next_code();
  309. if (!code.has_value()) {
  310. #ifdef GIF_DEBUG
  311. dbgln("Unexpectedly reached end of gif frame data");
  312. #endif
  313. return false;
  314. }
  315. if (code.value() == clear_code) {
  316. decoder.reset();
  317. continue;
  318. }
  319. if (code.value() == end_of_information_code)
  320. break;
  321. if (!image.width)
  322. continue;
  323. auto colors = decoder.get_output();
  324. for (const auto& color : colors) {
  325. auto c = color_map[color];
  326. int x = pixel_index % image.width + image.x;
  327. int y = row + image.y;
  328. if (context.frame_buffer->rect().contains(x, y) && (!image.transparent || color != image.transparency_index)) {
  329. context.frame_buffer->set_pixel(x, y, c);
  330. }
  331. ++pixel_index;
  332. if (pixel_index % image.width == 0) {
  333. if (image.interlaced) {
  334. if (row + INTERLACE_ROW_STRIDES[interlace_pass] >= image.height) {
  335. ++interlace_pass;
  336. // FIXME: We could probably figure this out earlier and fail before doing a bunch of work.
  337. if (interlace_pass >= 4)
  338. return false;
  339. row = INTERLACE_ROW_OFFSETS[interlace_pass];
  340. } else {
  341. row += INTERLACE_ROW_STRIDES[interlace_pass];
  342. }
  343. } else {
  344. ++row;
  345. }
  346. }
  347. }
  348. }
  349. context.current_frame = i;
  350. context.state = GIFLoadingContext::State::FrameComplete;
  351. }
  352. return true;
  353. }
  354. static bool load_gif_frame_descriptors(GIFLoadingContext& context)
  355. {
  356. if (context.data_size < 32)
  357. return false;
  358. InputMemoryStream stream { { context.data, context.data_size } };
  359. Optional<GIFFormat> format = decode_gif_header(stream);
  360. if (!format.has_value()) {
  361. return false;
  362. }
  363. LittleEndian<u16> value;
  364. stream >> value;
  365. context.logical_screen.width = value;
  366. stream >> value;
  367. context.logical_screen.height = value;
  368. if (stream.handle_any_error())
  369. return false;
  370. if (context.logical_screen.width > maximum_width_for_decoded_images || context.logical_screen.height > maximum_height_for_decoded_images) {
  371. dbgln("This GIF is too large for comfort: {}x{}", context.logical_screen.width, context.logical_screen.height);
  372. return false;
  373. }
  374. u8 gcm_info = 0;
  375. stream >> gcm_info;
  376. if (stream.handle_any_error())
  377. return false;
  378. stream >> context.background_color_index;
  379. if (stream.handle_any_error())
  380. return false;
  381. u8 pixel_aspect_ratio = 0;
  382. stream >> pixel_aspect_ratio;
  383. if (stream.handle_any_error())
  384. return false;
  385. u8 bits_per_pixel = (gcm_info & 7) + 1;
  386. int color_map_entry_count = 1;
  387. for (int i = 0; i < bits_per_pixel; ++i)
  388. color_map_entry_count *= 2;
  389. for (int i = 0; i < color_map_entry_count; ++i) {
  390. u8 r = 0;
  391. u8 g = 0;
  392. u8 b = 0;
  393. stream >> r >> g >> b;
  394. context.logical_screen.color_map[i] = { r, g, b };
  395. }
  396. if (stream.handle_any_error())
  397. return false;
  398. NonnullOwnPtr<ImageDescriptor> current_image = make<ImageDescriptor>();
  399. for (;;) {
  400. u8 sentinel = 0;
  401. stream >> sentinel;
  402. if (stream.handle_any_error())
  403. return false;
  404. if (sentinel == '!') {
  405. u8 extension_type = 0;
  406. stream >> extension_type;
  407. if (stream.handle_any_error())
  408. return false;
  409. u8 sub_block_length = 0;
  410. Vector<u8> sub_block {};
  411. for (;;) {
  412. stream >> sub_block_length;
  413. if (stream.handle_any_error())
  414. return false;
  415. if (sub_block_length == 0)
  416. break;
  417. u8 dummy = 0;
  418. for (u16 i = 0; i < sub_block_length; ++i) {
  419. stream >> dummy;
  420. sub_block.append(dummy);
  421. }
  422. if (stream.handle_any_error())
  423. return false;
  424. }
  425. if (extension_type == 0xF9) {
  426. if (sub_block.size() != 4) {
  427. #ifdef GIF_DEBUG
  428. dbgln("Unexpected graphic control size");
  429. #endif
  430. continue;
  431. }
  432. u8 disposal_method = (sub_block[0] & 0x1C) >> 2;
  433. current_image->disposal_method = (ImageDescriptor::DisposalMethod)disposal_method;
  434. u8 user_input = (sub_block[0] & 0x2) >> 1;
  435. current_image->user_input = user_input == 1;
  436. u8 transparent = sub_block[0] & 1;
  437. current_image->transparent = transparent == 1;
  438. u16 duration = sub_block[1] + ((u16)sub_block[2] >> 8);
  439. current_image->duration = duration;
  440. current_image->transparency_index = sub_block[3];
  441. }
  442. if (extension_type == 0xFF) {
  443. if (sub_block.size() != 14) {
  444. #ifdef GIF_DEBUG
  445. dbg() << "Unexpected application extension size: " << sub_block.size();
  446. #endif
  447. continue;
  448. }
  449. if (sub_block[11] != 1) {
  450. #ifdef GIF_DEBUG
  451. dbgln("Unexpected application extension format");
  452. #endif
  453. continue;
  454. }
  455. u16 loops = sub_block[12] + (sub_block[13] << 8);
  456. context.loops = loops;
  457. }
  458. continue;
  459. }
  460. if (sentinel == ',') {
  461. context.images.append(move(current_image));
  462. auto& image = context.images.last();
  463. LittleEndian<u16> tmp;
  464. u8 packed_fields { 0 };
  465. stream >> tmp;
  466. image.x = tmp;
  467. stream >> tmp;
  468. image.y = tmp;
  469. stream >> tmp;
  470. image.width = tmp;
  471. stream >> tmp;
  472. image.height = tmp;
  473. stream >> packed_fields;
  474. if (stream.handle_any_error())
  475. return false;
  476. image.use_global_color_map = !(packed_fields & 0x80);
  477. image.interlaced = (packed_fields & 0x40) != 0;
  478. if (!image.use_global_color_map) {
  479. size_t local_color_table_size = pow(2, (packed_fields & 7) + 1);
  480. for (size_t i = 0; i < local_color_table_size; ++i) {
  481. u8 r = 0;
  482. u8 g = 0;
  483. u8 b = 0;
  484. stream >> r >> g >> b;
  485. image.color_map[i] = { r, g, b };
  486. }
  487. }
  488. stream >> image.lzw_min_code_size;
  489. if (stream.handle_any_error())
  490. return false;
  491. u8 lzw_encoded_bytes_expected = 0;
  492. for (;;) {
  493. stream >> lzw_encoded_bytes_expected;
  494. if (stream.handle_any_error())
  495. return false;
  496. if (lzw_encoded_bytes_expected == 0)
  497. break;
  498. Array<u8, 256> buffer;
  499. stream >> buffer.span().trim(lzw_encoded_bytes_expected);
  500. if (stream.handle_any_error())
  501. return false;
  502. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  503. image.lzw_encoded_bytes.append(buffer[i]);
  504. }
  505. }
  506. current_image = make<ImageDescriptor>();
  507. continue;
  508. }
  509. if (sentinel == ';') {
  510. break;
  511. }
  512. return false;
  513. }
  514. context.state = GIFLoadingContext::State::FrameDescriptorsLoaded;
  515. return true;
  516. }
  517. GIFImageDecoderPlugin::GIFImageDecoderPlugin(const u8* data, size_t size)
  518. {
  519. m_context = make<GIFLoadingContext>();
  520. m_context->data = data;
  521. m_context->data_size = size;
  522. }
  523. GIFImageDecoderPlugin::~GIFImageDecoderPlugin() { }
  524. IntSize GIFImageDecoderPlugin::size()
  525. {
  526. if (m_context->error_state == GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors) {
  527. return {};
  528. }
  529. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  530. if (!load_gif_frame_descriptors(*m_context)) {
  531. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  532. return {};
  533. }
  534. }
  535. return { m_context->logical_screen.width, m_context->logical_screen.height };
  536. }
  537. RefPtr<Gfx::Bitmap> GIFImageDecoderPlugin::bitmap()
  538. {
  539. if (m_context->state < GIFLoadingContext::State::FrameComplete) {
  540. return frame(0).image;
  541. }
  542. return m_context->frame_buffer;
  543. }
  544. void GIFImageDecoderPlugin::set_volatile()
  545. {
  546. if (m_context->frame_buffer) {
  547. m_context->frame_buffer->set_volatile();
  548. }
  549. }
  550. bool GIFImageDecoderPlugin::set_nonvolatile()
  551. {
  552. if (!m_context->frame_buffer) {
  553. return true;
  554. }
  555. return m_context->frame_buffer->set_nonvolatile();
  556. }
  557. bool GIFImageDecoderPlugin::sniff()
  558. {
  559. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  560. return decode_gif_header(stream).has_value();
  561. }
  562. bool GIFImageDecoderPlugin::is_animated()
  563. {
  564. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  565. return false;
  566. }
  567. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  568. if (!load_gif_frame_descriptors(*m_context)) {
  569. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  570. return false;
  571. }
  572. }
  573. return m_context->images.size() > 1;
  574. }
  575. size_t GIFImageDecoderPlugin::loop_count()
  576. {
  577. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  578. return 0;
  579. }
  580. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  581. if (!load_gif_frame_descriptors(*m_context)) {
  582. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  583. return 0;
  584. }
  585. }
  586. return m_context->loops;
  587. }
  588. size_t GIFImageDecoderPlugin::frame_count()
  589. {
  590. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  591. return 1;
  592. }
  593. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  594. if (!load_gif_frame_descriptors(*m_context)) {
  595. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  596. return 1;
  597. }
  598. }
  599. return m_context->images.size();
  600. }
  601. ImageFrameDescriptor GIFImageDecoderPlugin::frame(size_t i)
  602. {
  603. if (m_context->error_state >= GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame) {
  604. return {};
  605. }
  606. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  607. if (!load_gif_frame_descriptors(*m_context)) {
  608. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  609. return {};
  610. }
  611. }
  612. if (m_context->error_state == GIFLoadingContext::ErrorState::NoError && !decode_frame(*m_context, i)) {
  613. if (m_context->state < GIFLoadingContext::State::FrameComplete || !decode_frame(*m_context, 0)) {
  614. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame;
  615. return {};
  616. }
  617. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAllFrames;
  618. }
  619. ImageFrameDescriptor frame {};
  620. frame.image = m_context->frame_buffer->clone();
  621. frame.duration = m_context->images.at(i).duration * 10;
  622. if (frame.duration <= 10) {
  623. frame.duration = 100;
  624. }
  625. return frame;
  626. }
  627. }