GIFLoader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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/BitStream.h>
  9. #include <AK/Debug.h>
  10. #include <AK/Endian.h>
  11. #include <AK/Error.h>
  12. #include <AK/IntegralMath.h>
  13. #include <AK/Memory.h>
  14. #include <AK/MemoryStream.h>
  15. #include <AK/Try.h>
  16. #include <LibCompress/LZWDecoder.h>
  17. #include <LibGfx/ImageFormats/GIFLoader.h>
  18. #include <string.h>
  19. namespace Gfx {
  20. // Row strides and offsets for each interlace pass.
  21. static constexpr Array<int, 4> INTERLACE_ROW_STRIDES = { 8, 8, 4, 2 };
  22. static constexpr Array<int, 4> INTERLACE_ROW_OFFSETS = { 0, 4, 2, 1 };
  23. struct GIFImageDescriptor {
  24. u16 x { 0 };
  25. u16 y { 0 };
  26. u16 width { 0 };
  27. u16 height { 0 };
  28. bool use_global_color_map { true };
  29. bool interlaced { false };
  30. Color color_map[256];
  31. u8 lzw_min_code_size { 0 };
  32. Vector<u8> lzw_encoded_bytes;
  33. // Fields from optional graphic control extension block
  34. enum DisposalMethod : u8 {
  35. None = 0,
  36. InPlace = 1,
  37. RestoreBackground = 2,
  38. RestorePrevious = 3,
  39. };
  40. DisposalMethod disposal_method { None };
  41. u8 transparency_index { 0 };
  42. u16 duration { 0 };
  43. bool transparent { false };
  44. bool user_input { false };
  45. IntRect rect() const
  46. {
  47. return { this->x, this->y, this->width, this->height };
  48. }
  49. };
  50. struct LogicalScreen {
  51. u16 width;
  52. u16 height;
  53. Color color_map[256];
  54. };
  55. struct GIFLoadingContext {
  56. GIFLoadingContext(FixedMemoryStream stream)
  57. : stream(move(stream))
  58. {
  59. }
  60. enum State {
  61. NotDecoded = 0,
  62. FrameDescriptorsLoaded,
  63. FrameComplete,
  64. };
  65. State state { NotDecoded };
  66. enum ErrorState {
  67. NoError = 0,
  68. FailedToDecodeAllFrames,
  69. FailedToDecodeAnyFrame,
  70. FailedToLoadFrameDescriptors,
  71. };
  72. ErrorState error_state { NoError };
  73. FixedMemoryStream stream;
  74. LogicalScreen logical_screen {};
  75. u8 background_color_index { 0 };
  76. Vector<NonnullOwnPtr<GIFImageDescriptor>> images {};
  77. size_t loops { 1 };
  78. RefPtr<Gfx::Bitmap> frame_buffer;
  79. size_t current_frame { 0 };
  80. RefPtr<Gfx::Bitmap> prev_frame_buffer;
  81. };
  82. enum class GIFFormat {
  83. GIF87a,
  84. GIF89a,
  85. };
  86. static ErrorOr<GIFFormat> decode_gif_header(Stream& stream)
  87. {
  88. static auto valid_header_87 = "GIF87a"sv;
  89. static auto valid_header_89 = "GIF89a"sv;
  90. Array<u8, 6> header;
  91. TRY(stream.read_until_filled(header));
  92. if (header.span() == valid_header_87.bytes())
  93. return GIFFormat::GIF87a;
  94. if (header.span() == valid_header_89.bytes())
  95. return GIFFormat::GIF89a;
  96. return Error::from_string_literal("GIF header unknown");
  97. }
  98. static void copy_frame_buffer(Bitmap& dest, Bitmap const& src)
  99. {
  100. VERIFY(dest.size_in_bytes() == src.size_in_bytes());
  101. memcpy(dest.scanline(0), src.scanline(0), dest.size_in_bytes());
  102. }
  103. static void clear_rect(Bitmap& bitmap, IntRect const& rect, Color color)
  104. {
  105. auto intersection_rect = rect.intersected(bitmap.rect());
  106. if (intersection_rect.is_empty())
  107. return;
  108. ARGB32* dst = bitmap.scanline(intersection_rect.top()) + intersection_rect.left();
  109. size_t const dst_skip = bitmap.pitch() / sizeof(ARGB32);
  110. for (int i = intersection_rect.height() - 1; i >= 0; --i) {
  111. fast_u32_fill(dst, color.value(), intersection_rect.width());
  112. dst += dst_skip;
  113. }
  114. }
  115. static ErrorOr<void> decode_frame(GIFLoadingContext& context, size_t frame_index)
  116. {
  117. if (frame_index >= context.images.size()) {
  118. return Error::from_string_literal("frame_index size too high");
  119. }
  120. if (context.state >= GIFLoadingContext::State::FrameComplete && frame_index == context.current_frame) {
  121. return {};
  122. }
  123. size_t start_frame = context.current_frame + 1;
  124. if (context.state < GIFLoadingContext::State::FrameComplete) {
  125. start_frame = 0;
  126. context.frame_buffer = TRY(Bitmap::create(BitmapFormat::BGRA8888, { context.logical_screen.width, context.logical_screen.height }));
  127. context.prev_frame_buffer = TRY(Bitmap::create(BitmapFormat::BGRA8888, { context.logical_screen.width, context.logical_screen.height }));
  128. } else if (frame_index < context.current_frame) {
  129. start_frame = 0;
  130. }
  131. for (size_t i = start_frame; i <= frame_index; ++i) {
  132. auto& image = context.images.at(i);
  133. auto const previous_image_disposal_method = i > 0 ? context.images.at(i - 1)->disposal_method : GIFImageDescriptor::DisposalMethod::None;
  134. if (i == 0) {
  135. context.frame_buffer->fill(Color::Transparent);
  136. } else if (i > 0 && image->disposal_method == GIFImageDescriptor::DisposalMethod::RestorePrevious
  137. && previous_image_disposal_method != GIFImageDescriptor::DisposalMethod::RestorePrevious) {
  138. // This marks the start of a run of frames that once disposed should be restored to the
  139. // previous underlying image contents. Therefore we make a copy of the current frame
  140. // buffer so that it can be restored later.
  141. copy_frame_buffer(*context.prev_frame_buffer, *context.frame_buffer);
  142. }
  143. if (previous_image_disposal_method == GIFImageDescriptor::DisposalMethod::RestoreBackground) {
  144. // Note: RestoreBackground could be interpreted either as restoring the underlying
  145. // background of the entire image (e.g. container element's background-color), or the
  146. // background color of the GIF itself. It appears that all major browsers and most other
  147. // GIF decoders adhere to the former interpretation, therefore we will do the same by
  148. // clearing the entire frame buffer to transparent.
  149. clear_rect(*context.frame_buffer, context.images[i - 1]->rect(), Color::Transparent);
  150. } else if (i > 0 && previous_image_disposal_method == GIFImageDescriptor::DisposalMethod::RestorePrevious) {
  151. // Previous frame indicated that once disposed, it should be restored to *its* previous
  152. // underlying image contents, therefore we restore the saved previous frame buffer.
  153. copy_frame_buffer(*context.frame_buffer, *context.prev_frame_buffer);
  154. }
  155. if (image->lzw_min_code_size > 8)
  156. return Error::from_string_literal("LZW minimum code size is greater than 8");
  157. auto decoded_stream = TRY(Compress::LZWDecoder<LittleEndianInputBitStream>::decode_all(image->lzw_encoded_bytes, image->lzw_min_code_size));
  158. auto const& color_map = image->use_global_color_map ? context.logical_screen.color_map : image->color_map;
  159. int pixel_index = 0;
  160. int row = 0;
  161. int interlace_pass = 0;
  162. if (!image->width)
  163. continue;
  164. for (auto const& color : decoded_stream.bytes()) {
  165. auto c = color_map[color];
  166. int x = pixel_index % image->width + image->x;
  167. int y = row + image->y;
  168. if (context.frame_buffer->rect().contains(x, y) && (!image->transparent || color != image->transparency_index)) {
  169. context.frame_buffer->set_pixel(x, y, c);
  170. }
  171. ++pixel_index;
  172. if (pixel_index % image->width == 0) {
  173. if (image->interlaced) {
  174. if (interlace_pass < 4) {
  175. if (row + INTERLACE_ROW_STRIDES[interlace_pass] >= image->height) {
  176. ++interlace_pass;
  177. if (interlace_pass < 4)
  178. row = INTERLACE_ROW_OFFSETS[interlace_pass];
  179. } else {
  180. row += INTERLACE_ROW_STRIDES[interlace_pass];
  181. }
  182. }
  183. } else {
  184. ++row;
  185. }
  186. }
  187. }
  188. context.current_frame = i;
  189. context.state = GIFLoadingContext::State::FrameComplete;
  190. }
  191. return {};
  192. }
  193. static ErrorOr<void> load_header_and_logical_screen(GIFLoadingContext& context)
  194. {
  195. if (TRY(context.stream.size()) < 32)
  196. return Error::from_string_literal("Size too short for GIF frame descriptors");
  197. TRY(decode_gif_header(context.stream));
  198. context.logical_screen.width = TRY(context.stream.read_value<LittleEndian<u16>>());
  199. context.logical_screen.height = TRY(context.stream.read_value<LittleEndian<u16>>());
  200. auto packed_fields = TRY(context.stream.read_value<u8>());
  201. context.background_color_index = TRY(context.stream.read_value<u8>());
  202. [[maybe_unused]] auto pixel_aspect_ratio = TRY(context.stream.read_value<u8>());
  203. // Global Color Table; if the flag is set, the Global Color Table will
  204. // immediately follow the Logical Screen Descriptor.
  205. bool global_color_table_flag = packed_fields & 0x80;
  206. if (global_color_table_flag) {
  207. u8 bits_per_pixel = (packed_fields & 7) + 1;
  208. int color_map_entry_count = 1;
  209. for (int i = 0; i < bits_per_pixel; ++i)
  210. color_map_entry_count *= 2;
  211. for (int i = 0; i < color_map_entry_count; ++i) {
  212. u8 r = TRY(context.stream.read_value<u8>());
  213. u8 g = TRY(context.stream.read_value<u8>());
  214. u8 b = TRY(context.stream.read_value<u8>());
  215. context.logical_screen.color_map[i] = { r, g, b };
  216. }
  217. }
  218. return {};
  219. }
  220. static ErrorOr<void> load_gif_frame_descriptors(GIFLoadingContext& context)
  221. {
  222. NonnullOwnPtr<GIFImageDescriptor> current_image = make<GIFImageDescriptor>();
  223. for (;;) {
  224. u8 sentinel = TRY(context.stream.read_value<u8>());
  225. if (sentinel == '!') {
  226. u8 extension_type = TRY(context.stream.read_value<u8>());
  227. u8 sub_block_length = 0;
  228. Vector<u8> sub_block {};
  229. for (;;) {
  230. sub_block_length = TRY(context.stream.read_value<u8>());
  231. if (sub_block_length == 0)
  232. break;
  233. TRY(sub_block.try_resize(sub_block.size() + sub_block_length));
  234. TRY(context.stream.read_until_filled(sub_block.span().slice_from_end(sub_block_length)));
  235. }
  236. if (extension_type == 0xF9) {
  237. if (sub_block.size() != 4) {
  238. dbgln_if(GIF_DEBUG, "Unexpected graphic control size");
  239. continue;
  240. }
  241. u8 disposal_method = (sub_block[0] & 0x1C) >> 2;
  242. current_image->disposal_method = (GIFImageDescriptor::DisposalMethod)disposal_method;
  243. u8 user_input = (sub_block[0] & 0x2) >> 1;
  244. current_image->user_input = user_input == 1;
  245. u8 transparent = sub_block[0] & 1;
  246. current_image->transparent = transparent == 1;
  247. u16 duration = sub_block[1] + ((u16)sub_block[2] << 8);
  248. current_image->duration = duration;
  249. current_image->transparency_index = sub_block[3];
  250. }
  251. if (extension_type == 0xFF) {
  252. if (sub_block.size() != 14) {
  253. dbgln_if(GIF_DEBUG, "Unexpected application extension size: {}", sub_block.size());
  254. continue;
  255. }
  256. if (sub_block[11] != 1) {
  257. dbgln_if(GIF_DEBUG, "Unexpected application extension format");
  258. continue;
  259. }
  260. u16 loops = sub_block[12] + (sub_block[13] << 8);
  261. context.loops = loops;
  262. }
  263. continue;
  264. }
  265. if (sentinel == ',') {
  266. context.images.append(move(current_image));
  267. auto& image = context.images.last();
  268. image->x = TRY(context.stream.read_value<LittleEndian<u16>>());
  269. image->y = TRY(context.stream.read_value<LittleEndian<u16>>());
  270. image->width = TRY(context.stream.read_value<LittleEndian<u16>>());
  271. image->height = TRY(context.stream.read_value<LittleEndian<u16>>());
  272. auto packed_fields = TRY(context.stream.read_value<u8>());
  273. image->use_global_color_map = !(packed_fields & 0x80);
  274. image->interlaced = (packed_fields & 0x40) != 0;
  275. if (!image->use_global_color_map) {
  276. size_t local_color_table_size = AK::exp2<size_t>((packed_fields & 7) + 1);
  277. for (size_t i = 0; i < local_color_table_size; ++i) {
  278. u8 r = TRY(context.stream.read_value<u8>());
  279. u8 g = TRY(context.stream.read_value<u8>());
  280. u8 b = TRY(context.stream.read_value<u8>());
  281. image->color_map[i] = { r, g, b };
  282. }
  283. }
  284. image->lzw_min_code_size = TRY(context.stream.read_value<u8>());
  285. u8 lzw_encoded_bytes_expected = 0;
  286. for (;;) {
  287. lzw_encoded_bytes_expected = TRY(context.stream.read_value<u8>());
  288. if (lzw_encoded_bytes_expected == 0)
  289. break;
  290. Array<u8, 256> buffer;
  291. TRY(context.stream.read_until_filled(buffer.span().trim(lzw_encoded_bytes_expected)));
  292. for (int i = 0; i < lzw_encoded_bytes_expected; ++i) {
  293. image->lzw_encoded_bytes.append(buffer[i]);
  294. }
  295. }
  296. current_image = make<GIFImageDescriptor>();
  297. continue;
  298. }
  299. if (sentinel == ';') {
  300. break;
  301. }
  302. return Error::from_string_literal("Unexpected sentinel");
  303. }
  304. context.state = GIFLoadingContext::State::FrameDescriptorsLoaded;
  305. return {};
  306. }
  307. GIFImageDecoderPlugin::GIFImageDecoderPlugin(FixedMemoryStream stream)
  308. {
  309. m_context = make<GIFLoadingContext>(move(stream));
  310. }
  311. GIFImageDecoderPlugin::~GIFImageDecoderPlugin() = default;
  312. IntSize GIFImageDecoderPlugin::size()
  313. {
  314. return { m_context->logical_screen.width, m_context->logical_screen.height };
  315. }
  316. bool GIFImageDecoderPlugin::sniff(ReadonlyBytes data)
  317. {
  318. FixedMemoryStream stream { data };
  319. return !decode_gif_header(stream).is_error();
  320. }
  321. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> GIFImageDecoderPlugin::create(ReadonlyBytes data)
  322. {
  323. FixedMemoryStream stream { data };
  324. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) GIFImageDecoderPlugin(move(stream))));
  325. TRY(load_header_and_logical_screen(*plugin->m_context));
  326. return plugin;
  327. }
  328. bool GIFImageDecoderPlugin::is_animated()
  329. {
  330. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  331. return false;
  332. }
  333. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  334. if (load_gif_frame_descriptors(*m_context).is_error()) {
  335. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  336. return false;
  337. }
  338. }
  339. return m_context->images.size() > 1;
  340. }
  341. size_t GIFImageDecoderPlugin::loop_count()
  342. {
  343. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  344. return 0;
  345. }
  346. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  347. if (load_gif_frame_descriptors(*m_context).is_error()) {
  348. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  349. return 0;
  350. }
  351. }
  352. return m_context->loops;
  353. }
  354. size_t GIFImageDecoderPlugin::frame_count()
  355. {
  356. if (m_context->error_state != GIFLoadingContext::ErrorState::NoError) {
  357. return 1;
  358. }
  359. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  360. if (load_gif_frame_descriptors(*m_context).is_error()) {
  361. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  362. return 1;
  363. }
  364. }
  365. return m_context->images.size();
  366. }
  367. size_t GIFImageDecoderPlugin::first_animated_frame_index()
  368. {
  369. return 0;
  370. }
  371. ErrorOr<ImageFrameDescriptor> GIFImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  372. {
  373. if (m_context->error_state >= GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame) {
  374. return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed");
  375. }
  376. if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
  377. if (auto result = load_gif_frame_descriptors(*m_context); result.is_error()) {
  378. m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
  379. return result.release_error();
  380. }
  381. }
  382. if (m_context->error_state == GIFLoadingContext::ErrorState::NoError) {
  383. if (auto result = decode_frame(*m_context, index); result.is_error()) {
  384. if (m_context->state < GIFLoadingContext::State::FrameComplete) {
  385. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame;
  386. return result.release_error();
  387. }
  388. if (auto result = decode_frame(*m_context, 0); result.is_error()) {
  389. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame;
  390. return result.release_error();
  391. }
  392. m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAllFrames;
  393. }
  394. }
  395. ImageFrameDescriptor frame {};
  396. frame.image = TRY(m_context->frame_buffer->clone());
  397. frame.duration = m_context->images[index]->duration * 10;
  398. if (frame.duration <= 10) {
  399. frame.duration = 100;
  400. }
  401. return frame;
  402. }
  403. }