GIFLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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/Lzw.h>
  17. #include <LibGfx/ImageFormats/GIFLoader.h>
  18. #include <LibGfx/Painter.h>
  19. #include <string.h>
  20. namespace Gfx {
  21. // Row strides and offsets for each interlace pass.
  22. static constexpr Array<int, 4> INTERLACE_ROW_STRIDES = { 8, 8, 4, 2 };
  23. static constexpr Array<int, 4> INTERLACE_ROW_OFFSETS = { 0, 4, 2, 1 };
  24. struct GIFImageDescriptor {
  25. u16 x { 0 };
  26. u16 y { 0 };
  27. u16 width { 0 };
  28. u16 height { 0 };
  29. bool use_global_color_map { true };
  30. bool interlaced { false };
  31. Color color_map[256];
  32. u8 lzw_min_code_size { 0 };
  33. ByteBuffer lzw_encoded_bytes;
  34. // Fields from optional graphic control extension block
  35. enum DisposalMethod : u8 {
  36. None = 0,
  37. InPlace = 1,
  38. RestoreBackground = 2,
  39. RestorePrevious = 3,
  40. };
  41. DisposalMethod disposal_method { None };
  42. u8 transparency_index { 0 };
  43. u16 duration { 0 };
  44. bool transparent { false };
  45. bool user_input { false };
  46. IntRect rect() const
  47. {
  48. return { this->x, this->y, this->width, this->height };
  49. }
  50. };
  51. struct LogicalScreen {
  52. u16 width;
  53. u16 height;
  54. Color color_map[256];
  55. };
  56. struct GIFLoadingContext {
  57. GIFLoadingContext(FixedMemoryStream stream)
  58. : stream(move(stream))
  59. {
  60. }
  61. enum State {
  62. NotDecoded = 0,
  63. FrameDescriptorsLoaded,
  64. FrameComplete,
  65. };
  66. State state { NotDecoded };
  67. enum ErrorState {
  68. NoError = 0,
  69. FailedToDecodeAllFrames,
  70. FailedToDecodeAnyFrame,
  71. FailedToLoadFrameDescriptors,
  72. };
  73. ErrorState error_state { NoError };
  74. FixedMemoryStream stream;
  75. LogicalScreen logical_screen {};
  76. u8 background_color_index { 0 };
  77. Vector<NonnullOwnPtr<GIFImageDescriptor>> images {};
  78. size_t loops { 1 };
  79. RefPtr<Gfx::Bitmap> frame_buffer;
  80. size_t current_frame { 0 };
  81. RefPtr<Gfx::Bitmap> prev_frame_buffer;
  82. };
  83. enum class GIFFormat {
  84. GIF87a,
  85. GIF89a,
  86. };
  87. static ErrorOr<GIFFormat> decode_gif_header(Stream& stream)
  88. {
  89. static auto valid_header_87 = "GIF87a"sv;
  90. static auto valid_header_89 = "GIF89a"sv;
  91. Array<u8, 6> header;
  92. TRY(stream.read_until_filled(header));
  93. if (header.span() == valid_header_87.bytes())
  94. return GIFFormat::GIF87a;
  95. if (header.span() == valid_header_89.bytes())
  96. return GIFFormat::GIF89a;
  97. return Error::from_string_literal("GIF header unknown");
  98. }
  99. static void copy_frame_buffer(Bitmap& dest, Bitmap const& src)
  100. {
  101. VERIFY(dest.size_in_bytes() == src.size_in_bytes());
  102. memcpy(dest.scanline(0), src.scanline(0), dest.size_in_bytes());
  103. }
  104. static void clear_rect(Bitmap& bitmap, IntRect const& rect, Color color)
  105. {
  106. auto intersection_rect = rect.intersected(bitmap.rect());
  107. if (intersection_rect.is_empty())
  108. return;
  109. ARGB32* dst = bitmap.scanline(intersection_rect.top()) + intersection_rect.left();
  110. size_t const dst_skip = bitmap.pitch() / sizeof(ARGB32);
  111. for (int i = intersection_rect.height() - 1; i >= 0; --i) {
  112. fast_u32_fill(dst, color.value(), intersection_rect.width());
  113. dst += dst_skip;
  114. }
  115. }
  116. static ErrorOr<void> decode_frame(GIFLoadingContext& context, size_t frame_index)
  117. {
  118. if (frame_index >= context.images.size()) {
  119. return Error::from_string_literal("frame_index size too high");
  120. }
  121. if (context.state >= GIFLoadingContext::State::FrameComplete && frame_index == context.current_frame) {
  122. return {};
  123. }
  124. size_t start_frame = context.current_frame + 1;
  125. if (context.state < GIFLoadingContext::State::FrameComplete) {
  126. start_frame = 0;
  127. context.frame_buffer = TRY(Bitmap::create(BitmapFormat::BGRA8888, { context.logical_screen.width, context.logical_screen.height }));
  128. context.prev_frame_buffer = TRY(Bitmap::create(BitmapFormat::BGRA8888, { context.logical_screen.width, context.logical_screen.height }));
  129. } else if (frame_index < context.current_frame) {
  130. start_frame = 0;
  131. }
  132. for (size_t i = start_frame; i <= frame_index; ++i) {
  133. auto& image = context.images.at(i);
  134. auto const previous_image_disposal_method = i > 0 ? context.images.at(i - 1)->disposal_method : GIFImageDescriptor::DisposalMethod::None;
  135. if (i == 0) {
  136. auto painter = Gfx::Painter::create(*context.frame_buffer);
  137. painter->clear_rect(context.frame_buffer->rect().to_type<float>(), Color::Transparent);
  138. } else if (i > 0 && image->disposal_method == GIFImageDescriptor::DisposalMethod::RestorePrevious
  139. && previous_image_disposal_method != GIFImageDescriptor::DisposalMethod::RestorePrevious) {
  140. // This marks the start of a run of frames that once disposed should be restored to the
  141. // previous underlying image contents. Therefore we make a copy of the current frame
  142. // buffer so that it can be restored later.
  143. copy_frame_buffer(*context.prev_frame_buffer, *context.frame_buffer);
  144. }
  145. if (previous_image_disposal_method == GIFImageDescriptor::DisposalMethod::RestoreBackground) {
  146. // Note: RestoreBackground could be interpreted either as restoring the underlying
  147. // background of the entire image (e.g. container element's background-color), or the
  148. // background color of the GIF itself. It appears that all major browsers and most other
  149. // GIF decoders adhere to the former interpretation, therefore we will do the same by
  150. // clearing the entire frame buffer to transparent.
  151. clear_rect(*context.frame_buffer, context.images[i - 1]->rect(), Color::Transparent);
  152. } else if (i > 0 && previous_image_disposal_method == GIFImageDescriptor::DisposalMethod::RestorePrevious) {
  153. // Previous frame indicated that once disposed, it should be restored to *its* previous
  154. // underlying image contents, therefore we restore the saved previous frame buffer.
  155. copy_frame_buffer(*context.frame_buffer, *context.prev_frame_buffer);
  156. }
  157. if (image->lzw_min_code_size > 8)
  158. return Error::from_string_literal("LZW minimum code size is greater than 8");
  159. auto decoded_stream = TRY(Compress::LzwDecompressor<LittleEndianInputBitStream>::decompress_all(image->lzw_encoded_bytes, image->lzw_min_code_size));
  160. auto const& color_map = image->use_global_color_map ? context.logical_screen.color_map : image->color_map;
  161. int pixel_index = 0;
  162. int row = 0;
  163. int interlace_pass = 0;
  164. if (!image->width)
  165. continue;
  166. for (auto const& color : decoded_stream.bytes()) {
  167. auto c = color_map[color];
  168. int x = pixel_index % image->width + image->x;
  169. int y = row + image->y;
  170. if (context.frame_buffer->rect().contains(x, y) && (!image->transparent || color != image->transparency_index)) {
  171. context.frame_buffer->set_pixel(x, y, c);
  172. }
  173. ++pixel_index;
  174. if (pixel_index % image->width == 0) {
  175. if (image->interlaced) {
  176. if (interlace_pass < 4) {
  177. if (row + INTERLACE_ROW_STRIDES[interlace_pass] >= image->height) {
  178. ++interlace_pass;
  179. if (interlace_pass < 4)
  180. row = INTERLACE_ROW_OFFSETS[interlace_pass];
  181. } else {
  182. row += INTERLACE_ROW_STRIDES[interlace_pass];
  183. }
  184. }
  185. } else {
  186. ++row;
  187. }
  188. }
  189. }
  190. context.current_frame = i;
  191. context.state = GIFLoadingContext::State::FrameComplete;
  192. }
  193. return {};
  194. }
  195. static ErrorOr<void> load_header_and_logical_screen(GIFLoadingContext& context)
  196. {
  197. if (TRY(context.stream.size()) < 32)
  198. return Error::from_string_literal("Size too short for GIF frame descriptors");
  199. TRY(decode_gif_header(context.stream));
  200. context.logical_screen.width = TRY(context.stream.read_value<LittleEndian<u16>>());
  201. context.logical_screen.height = TRY(context.stream.read_value<LittleEndian<u16>>());
  202. auto packed_fields = TRY(context.stream.read_value<u8>());
  203. context.background_color_index = TRY(context.stream.read_value<u8>());
  204. [[maybe_unused]] auto pixel_aspect_ratio = TRY(context.stream.read_value<u8>());
  205. // Global Color Table; if the flag is set, the Global Color Table will
  206. // immediately follow the Logical Screen Descriptor.
  207. bool global_color_table_flag = packed_fields & 0x80;
  208. if (global_color_table_flag) {
  209. u8 bits_per_pixel = (packed_fields & 7) + 1;
  210. size_t color_map_entry_count = 1 << bits_per_pixel;
  211. for (size_t 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. dbgln_if(GIF_DEBUG, "Graphic control: disposal_method={}, user_input={}, transparent={}, duration={}", (int)current_image->disposal_method, current_image->user_input, current_image->transparent, current_image->duration);
  251. }
  252. if (extension_type == 0xFF) {
  253. if (sub_block.size() != 14) {
  254. dbgln_if(GIF_DEBUG, "Unexpected application extension size: {}", sub_block.size());
  255. continue;
  256. }
  257. if (sub_block[11] != 1) {
  258. dbgln_if(GIF_DEBUG, "Unexpected application extension format");
  259. continue;
  260. }
  261. u16 loops = sub_block[12] + (sub_block[13] << 8);
  262. context.loops = loops;
  263. dbgln_if(GIF_DEBUG, "Application extension: loops={}", context.loops);
  264. }
  265. continue;
  266. }
  267. if (sentinel == ',') {
  268. context.images.append(move(current_image));
  269. auto& image = context.images.last();
  270. image->x = TRY(context.stream.read_value<LittleEndian<u16>>());
  271. image->y = TRY(context.stream.read_value<LittleEndian<u16>>());
  272. image->width = TRY(context.stream.read_value<LittleEndian<u16>>());
  273. image->height = TRY(context.stream.read_value<LittleEndian<u16>>());
  274. auto packed_fields = TRY(context.stream.read_value<u8>());
  275. image->use_global_color_map = !(packed_fields & 0x80);
  276. image->interlaced = (packed_fields & 0x40) != 0;
  277. dbgln_if(GIF_DEBUG, "Image descriptor: x={}, y={}, width={}, height={}, use_global_color_map={}, local_map_size_exponent={}, interlaced={}", image->x, image->y, image->width, image->height, image->use_global_color_map, (packed_fields & 7) + 1, image->interlaced);
  278. if (!image->use_global_color_map) {
  279. size_t local_color_table_size = AK::exp2<size_t>((packed_fields & 7) + 1);
  280. for (size_t i = 0; i < local_color_table_size; ++i) {
  281. u8 r = TRY(context.stream.read_value<u8>());
  282. u8 g = TRY(context.stream.read_value<u8>());
  283. u8 b = TRY(context.stream.read_value<u8>());
  284. image->color_map[i] = { r, g, b };
  285. }
  286. }
  287. image->lzw_min_code_size = TRY(context.stream.read_value<u8>());
  288. for (;;) {
  289. auto const lzw_encoded_bytes_expected = TRY(context.stream.read_value<u8>());
  290. // Block terminator
  291. if (lzw_encoded_bytes_expected == 0)
  292. break;
  293. auto const lzw_subblock = TRY(image->lzw_encoded_bytes.get_bytes_for_writing(lzw_encoded_bytes_expected));
  294. TRY(context.stream.read_until_filled(lzw_subblock));
  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. }