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