GIFLoader.cpp 23 KB

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