GIFLoader.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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/Endian.h>
  10. #include <AK/Error.h>
  11. #include <AK/IntegralMath.h>
  12. #include <AK/Memory.h>
  13. #include <AK/MemoryStream.h>
  14. #include <AK/Try.h>
  15. #include <LibGfx/ImageFormats/GIFLoader.h>
  16. #include <string.h>
  17. namespace Gfx {
  18. // Row strides and offsets for each interlace pass.
  19. static constexpr Array<int, 4> INTERLACE_ROW_STRIDES = { 8, 8, 4, 2 };
  20. static constexpr Array<int, 4> INTERLACE_ROW_OFFSETS = { 0, 4, 2, 1 };
  21. struct GIFImageDescriptor {
  22. u16 x { 0 };
  23. u16 y { 0 };
  24. u16 width { 0 };
  25. u16 height { 0 };
  26. bool use_global_color_map { true };
  27. bool interlaced { false };
  28. Color color_map[256];
  29. u8 lzw_min_code_size { 0 };
  30. Vector<u8> lzw_encoded_bytes;
  31. // Fields from optional graphic control extension block
  32. enum DisposalMethod : u8 {
  33. None = 0,
  34. InPlace = 1,
  35. RestoreBackground = 2,
  36. RestorePrevious = 3,
  37. };
  38. DisposalMethod disposal_method { None };
  39. u8 transparency_index { 0 };
  40. u16 duration { 0 };
  41. bool transparent { false };
  42. bool user_input { false };
  43. const IntRect rect() const
  44. {
  45. return { this->x, this->y, this->width, this->height };
  46. }
  47. };
  48. struct LogicalScreen {
  49. u16 width;
  50. u16 height;
  51. Color color_map[256];
  52. };
  53. struct GIFLoadingContext {
  54. enum State {
  55. NotDecoded = 0,
  56. FrameDescriptorsLoaded,
  57. FrameComplete,
  58. };
  59. State state { NotDecoded };
  60. enum ErrorState {
  61. NoError = 0,
  62. FailedToDecodeAllFrames,
  63. FailedToDecodeAnyFrame,
  64. FailedToLoadFrameDescriptors,
  65. };
  66. ErrorState error_state { NoError };
  67. u8 const* data { nullptr };
  68. size_t data_size { 0 };
  69. LogicalScreen logical_screen {};
  70. u8 background_color_index { 0 };
  71. Vector<NonnullOwnPtr<GIFImageDescriptor>> images {};
  72. size_t loops { 1 };
  73. RefPtr<Gfx::Bitmap> frame_buffer;
  74. size_t current_frame { 0 };
  75. RefPtr<Gfx::Bitmap> prev_frame_buffer;
  76. };
  77. enum class GIFFormat {
  78. GIF87a,
  79. GIF89a,
  80. };
  81. static ErrorOr<GIFFormat> decode_gif_header(Stream& stream)
  82. {
  83. static auto valid_header_87 = "GIF87a"sv;
  84. static auto valid_header_89 = "GIF89a"sv;
  85. Array<u8, 6> header;
  86. TRY(stream.read_until_filled(header));
  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 Error::from_string_literal("GIF header unknown");
  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. ErrorOr<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 Error::from_string_literal("LZWDecoder tries to read ouf of bounds");
  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 Error::from_string_literal("Corrupted LZW stream, invalid code");
  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 Error::from_string_literal("Corrupted LZW stream, valid new code but output buffer is empty");
  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 ErrorOr<void> decode_frame(GIFLoadingContext& context, size_t frame_index)
  226. {
  227. if (frame_index >= context.images.size()) {
  228. return Error::from_string_literal("frame_index size too high");
  229. }
  230. if (context.state >= GIFLoadingContext::State::FrameComplete && frame_index == context.current_frame) {
  231. return {};
  232. }
  233. size_t start_frame = context.current_frame + 1;
  234. if (context.state < GIFLoadingContext::State::FrameComplete) {
  235. start_frame = 0;
  236. context.frame_buffer = TRY(Bitmap::create(BitmapFormat::BGRA8888, { context.logical_screen.width, context.logical_screen.height }));
  237. context.prev_frame_buffer = TRY(Bitmap::create(BitmapFormat::BGRA8888, { context.logical_screen.width, context.logical_screen.height }));
  238. } else if (frame_index < context.current_frame) {
  239. start_frame = 0;
  240. }
  241. for (size_t i = start_frame; i <= frame_index; ++i) {
  242. auto& image = context.images.at(i);
  243. auto const previous_image_disposal_method = i > 0 ? context.images.at(i - 1)->disposal_method : GIFImageDescriptor::DisposalMethod::None;
  244. if (i == 0) {
  245. context.frame_buffer->fill(Color::Transparent);
  246. } else if (i > 0 && image->disposal_method == GIFImageDescriptor::DisposalMethod::RestorePrevious
  247. && previous_image_disposal_method != GIFImageDescriptor::DisposalMethod::RestorePrevious) {
  248. // This marks the start of a run of frames that once disposed should be restored to the
  249. // previous underlying image contents. Therefore we make a copy of the current frame
  250. // buffer so that it can be restored later.
  251. copy_frame_buffer(*context.prev_frame_buffer, *context.frame_buffer);
  252. }
  253. if (previous_image_disposal_method == GIFImageDescriptor::DisposalMethod::RestoreBackground) {
  254. // Note: RestoreBackground could be interpreted either as restoring the underlying
  255. // background of the entire image (e.g. container element's background-color), or the
  256. // background color of the GIF itself. It appears that all major browsers and most other
  257. // GIF decoders adhere to the former interpretation, therefore we will do the same by
  258. // clearing the entire frame buffer to transparent.
  259. clear_rect(*context.frame_buffer, context.images[i - 1]->rect(), Color::Transparent);
  260. } else if (i > 0 && previous_image_disposal_method == GIFImageDescriptor::DisposalMethod::RestorePrevious) {
  261. // Previous frame indicated that once disposed, it should be restored to *its* previous
  262. // underlying image contents, therefore we restore the saved previous frame buffer.
  263. copy_frame_buffer(*context.frame_buffer, *context.prev_frame_buffer);
  264. }
  265. if (image->lzw_min_code_size > 8)
  266. return Error::from_string_literal("LZW minimum code size is greater than 8");
  267. LZWDecoder decoder(image->lzw_encoded_bytes, image->lzw_min_code_size);
  268. // Add GIF-specific control codes
  269. int const clear_code = decoder.add_control_code();
  270. int const end_of_information_code = decoder.add_control_code();
  271. auto const& color_map = image->use_global_color_map ? context.logical_screen.color_map : image->color_map;
  272. int pixel_index = 0;
  273. int row = 0;
  274. int interlace_pass = 0;
  275. while (true) {
  276. ErrorOr<u16> code = decoder.next_code();
  277. if (code.is_error()) {
  278. dbgln_if(GIF_DEBUG, "Unexpectedly reached end of gif frame data");
  279. return code.release_error();
  280. }
  281. if (code.value() == clear_code) {
  282. decoder.reset();
  283. continue;
  284. }
  285. if (code.value() == end_of_information_code)
  286. break;
  287. if (!image->width)
  288. continue;
  289. auto colors = decoder.get_output();
  290. for (auto const& color : colors) {
  291. auto c = color_map[color];
  292. int x = pixel_index % image->width + image->x;
  293. int y = row + image->y;
  294. if (context.frame_buffer->rect().contains(x, y) && (!image->transparent || color != image->transparency_index)) {
  295. context.frame_buffer->set_pixel(x, y, c);
  296. }
  297. ++pixel_index;
  298. if (pixel_index % image->width == 0) {
  299. if (image->interlaced) {
  300. if (interlace_pass < 4) {
  301. if (row + INTERLACE_ROW_STRIDES[interlace_pass] >= image->height) {
  302. ++interlace_pass;
  303. if (interlace_pass < 4)
  304. row = INTERLACE_ROW_OFFSETS[interlace_pass];
  305. } else {
  306. row += INTERLACE_ROW_STRIDES[interlace_pass];
  307. }
  308. }
  309. } else {
  310. ++row;
  311. }
  312. }
  313. }
  314. }
  315. context.current_frame = i;
  316. context.state = GIFLoadingContext::State::FrameComplete;
  317. }
  318. return {};
  319. }
  320. static ErrorOr<void> load_gif_frame_descriptors(GIFLoadingContext& context)
  321. {
  322. if (context.data_size < 32)
  323. return Error::from_string_literal("Size too short for GIF frame descriptors");
  324. FixedMemoryStream stream { { context.data, context.data_size } };
  325. TRY(decode_gif_header(stream));
  326. context.logical_screen.width = TRY(stream.read_value<LittleEndian<u16>>());
  327. context.logical_screen.height = TRY(stream.read_value<LittleEndian<u16>>());
  328. if (context.logical_screen.width > maximum_width_for_decoded_images || context.logical_screen.height > maximum_height_for_decoded_images) {
  329. dbgln("This GIF is too large for comfort: {}x{}", context.logical_screen.width, context.logical_screen.height);
  330. return Error::from_string_literal("This GIF is too large for comfort");
  331. }
  332. auto gcm_info = TRY(stream.read_value<u8>());
  333. context.background_color_index = TRY(stream.read_value<u8>());
  334. [[maybe_unused]] auto pixel_aspect_ratio = TRY(stream.read_value<u8>());
  335. u8 bits_per_pixel = (gcm_info & 7) + 1;
  336. int color_map_entry_count = 1;
  337. for (int i = 0; i < bits_per_pixel; ++i)
  338. color_map_entry_count *= 2;
  339. for (int i = 0; i < color_map_entry_count; ++i) {
  340. u8 r = TRY(stream.read_value<u8>());
  341. u8 g = TRY(stream.read_value<u8>());
  342. u8 b = TRY(stream.read_value<u8>());
  343. context.logical_screen.color_map[i] = { r, g, b };
  344. }
  345. NonnullOwnPtr<GIFImageDescriptor> current_image = make<GIFImageDescriptor>();
  346. for (;;) {
  347. u8 sentinel = TRY(stream.read_value<u8>());
  348. if (sentinel == '!') {
  349. u8 extension_type = TRY(stream.read_value<u8>());
  350. u8 sub_block_length = 0;
  351. Vector<u8> sub_block {};
  352. for (;;) {
  353. sub_block_length = TRY(stream.read_value<u8>());
  354. if (sub_block_length == 0)
  355. break;
  356. TRY(sub_block.try_resize(sub_block.size() + sub_block_length));
  357. TRY(stream.read_until_filled(sub_block.span().slice_from_end(sub_block_length)));
  358. }
  359. if (extension_type == 0xF9) {
  360. if (sub_block.size() != 4) {
  361. dbgln_if(GIF_DEBUG, "Unexpected graphic control size");
  362. continue;
  363. }
  364. u8 disposal_method = (sub_block[0] & 0x1C) >> 2;
  365. current_image->disposal_method = (GIFImageDescriptor::DisposalMethod)disposal_method;
  366. u8 user_input = (sub_block[0] & 0x2) >> 1;
  367. current_image->user_input = user_input == 1;
  368. u8 transparent = sub_block[0] & 1;
  369. current_image->transparent = transparent == 1;
  370. u16 duration = sub_block[1] + ((u16)sub_block[2] << 8);
  371. current_image->duration = duration;
  372. current_image->transparency_index = sub_block[3];
  373. }
  374. if (extension_type == 0xFF) {
  375. if (sub_block.size() != 14) {
  376. dbgln_if(GIF_DEBUG, "Unexpected application extension size: {}", sub_block.size());
  377. continue;
  378. }
  379. if (sub_block[11] != 1) {
  380. dbgln_if(GIF_DEBUG, "Unexpected application extension format");
  381. continue;
  382. }
  383. u16 loops = sub_block[12] + (sub_block[13] << 8);
  384. context.loops = loops;
  385. }
  386. continue;
  387. }
  388. if (sentinel == ',') {
  389. context.images.append(move(current_image));
  390. auto& image = context.images.last();
  391. image->x = TRY(stream.read_value<LittleEndian<u16>>());
  392. image->y = TRY(stream.read_value<LittleEndian<u16>>());
  393. image->width = TRY(stream.read_value<LittleEndian<u16>>());
  394. image->height = TRY(stream.read_value<LittleEndian<u16>>());
  395. auto packed_fields = TRY(stream.read_value<u8>());
  396. image->use_global_color_map = !(packed_fields & 0x80);
  397. image->interlaced = (packed_fields & 0x40) != 0;
  398. if (!image->use_global_color_map) {
  399. size_t local_color_table_size = AK::exp2<size_t>((packed_fields & 7) + 1);
  400. for (size_t i = 0; i < local_color_table_size; ++i) {
  401. u8 r = TRY(stream.read_value<u8>());
  402. u8 g = TRY(stream.read_value<u8>());
  403. u8 b = TRY(stream.read_value<u8>());
  404. image->color_map[i] = { r, g, b };
  405. }
  406. }
  407. image->lzw_min_code_size = TRY(stream.read_value<u8>());
  408. u8 lzw_encoded_bytes_expected = 0;
  409. for (;;) {
  410. lzw_encoded_bytes_expected = TRY(stream.read_value<u8>());
  411. if (lzw_encoded_bytes_expected == 0)
  412. break;
  413. Array<u8, 256> buffer;
  414. TRY(stream.read_until_filled(buffer.span().trim(lzw_encoded_bytes_expected)));
  415. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  416. image->lzw_encoded_bytes.append(buffer[i]);
  417. }
  418. }
  419. current_image = make<GIFImageDescriptor>();
  420. continue;
  421. }
  422. if (sentinel == ';') {
  423. break;
  424. }
  425. return Error::from_string_literal("Unexpected sentinel");
  426. }
  427. context.state = GIFLoadingContext::State::FrameDescriptorsLoaded;
  428. return {};
  429. }
  430. GIFImageDecoderPlugin::GIFImageDecoderPlugin(u8 const* data, size_t size)
  431. {
  432. m_context = make<GIFLoadingContext>();
  433. m_context->data = data;
  434. m_context->data_size = size;
  435. }
  436. GIFImageDecoderPlugin::~GIFImageDecoderPlugin() = default;
  437. IntSize GIFImageDecoderPlugin::size()
  438. {
  439. if (m_context->error_state == GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors) {
  440. return {};
  441. }
  442. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  443. if (load_gif_frame_descriptors(*m_context).is_error()) {
  444. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  445. return {};
  446. }
  447. }
  448. return { m_context->logical_screen.width, m_context->logical_screen.height };
  449. }
  450. ErrorOr<void> GIFImageDecoderPlugin::initialize()
  451. {
  452. FixedMemoryStream stream { { m_context->data, m_context->data_size } };
  453. TRY(decode_gif_header(stream));
  454. return {};
  455. }
  456. bool GIFImageDecoderPlugin::sniff(ReadonlyBytes data)
  457. {
  458. FixedMemoryStream stream { data };
  459. return !decode_gif_header(stream).is_error();
  460. }
  461. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> GIFImageDecoderPlugin::create(ReadonlyBytes data)
  462. {
  463. return adopt_nonnull_own_or_enomem(new (nothrow) GIFImageDecoderPlugin(data.data(), data.size()));
  464. }
  465. bool GIFImageDecoderPlugin::is_animated()
  466. {
  467. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  468. return false;
  469. }
  470. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  471. if (load_gif_frame_descriptors(*m_context).is_error()) {
  472. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  473. return false;
  474. }
  475. }
  476. return m_context->images.size() > 1;
  477. }
  478. size_t GIFImageDecoderPlugin::loop_count()
  479. {
  480. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  481. return 0;
  482. }
  483. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  484. if (load_gif_frame_descriptors(*m_context).is_error()) {
  485. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  486. return 0;
  487. }
  488. }
  489. return m_context->loops;
  490. }
  491. size_t GIFImageDecoderPlugin::frame_count()
  492. {
  493. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  494. return 1;
  495. }
  496. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  497. if (load_gif_frame_descriptors(*m_context).is_error()) {
  498. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  499. return 1;
  500. }
  501. }
  502. return m_context->images.size();
  503. }
  504. size_t GIFImageDecoderPlugin::first_animated_frame_index()
  505. {
  506. return 0;
  507. }
  508. ErrorOr<ImageFrameDescriptor> GIFImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  509. {
  510. if (m_context->error_state >= GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame) {
  511. return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed");
  512. }
  513. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  514. if (auto result = load_gif_frame_descriptors(*m_context); result.is_error()) {
  515. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  516. return result.release_error();
  517. }
  518. }
  519. if (m_context->error_state == GIFLoadingContext::ErrorState::NoError) {
  520. if (auto result = decode_frame(*m_context, index); result.is_error()) {
  521. if (m_context->state < GIFLoadingContext::State::FrameComplete) {
  522. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame;
  523. return result.release_error();
  524. }
  525. if (auto result = decode_frame(*m_context, 0); result.is_error()) {
  526. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame;
  527. return result.release_error();
  528. }
  529. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAllFrames;
  530. }
  531. }
  532. ImageFrameDescriptor frame {};
  533. frame.image = TRY(m_context->frame_buffer->clone());
  534. frame.duration = m_context->images[index]->duration * 10;
  535. if (frame.duration <= 10) {
  536. frame.duration = 100;
  537. }
  538. return frame;
  539. }
  540. ErrorOr<Optional<ReadonlyBytes>> GIFImageDecoderPlugin::icc_data()
  541. {
  542. return OptionalNone {};
  543. }
  544. }