GIFLoader.cpp 23 KB

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