GIFLoader.cpp 23 KB

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