GIFLoader.cpp 23 KB

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