GIFLoader.cpp 24 KB

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