GIFLoader.cpp 23 KB

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