GIFLoader.cpp 23 KB

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