QOILoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Endian.h>
  7. #include <AK/MemoryStream.h>
  8. #include <LibGfx/Bitmap.h>
  9. #include <LibGfx/QOILoader.h>
  10. namespace Gfx {
  11. static constexpr auto QOI_MAGIC = "qoif"sv;
  12. static constexpr u8 QOI_OP_RGB = 0b11111110;
  13. static constexpr u8 QOI_OP_RGBA = 0b11111111;
  14. static constexpr u8 QOI_OP_INDEX = 0b00000000;
  15. static constexpr u8 QOI_OP_DIFF = 0b01000000;
  16. static constexpr u8 QOI_OP_LUMA = 0b10000000;
  17. static constexpr u8 QOI_OP_RUN = 0b11000000;
  18. static constexpr u8 QOI_MASK_2 = 0b11000000;
  19. static constexpr u8 END_MARKER[] = { 0, 0, 0, 0, 0, 0, 0, 1 };
  20. static ErrorOr<QOIHeader> decode_qoi_header(InputMemoryStream& stream)
  21. {
  22. QOIHeader header;
  23. stream >> Bytes { &header, sizeof(header) };
  24. if (stream.handle_any_error())
  25. return Error::from_string_literal("Invalid QOI image: end of stream while reading header");
  26. if (StringView { header.magic, array_size(header.magic) } != QOI_MAGIC)
  27. return Error::from_string_literal("Invalid QOI image: incorrect header magic");
  28. header.width = AK::convert_between_host_and_big_endian(header.width);
  29. header.height = AK::convert_between_host_and_big_endian(header.height);
  30. return header;
  31. }
  32. static ErrorOr<Color> decode_qoi_op_rgb(InputMemoryStream& stream, Color pixel)
  33. {
  34. u8 bytes[4];
  35. stream >> Bytes { &bytes, array_size(bytes) };
  36. if (stream.handle_any_error())
  37. return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RGB chunk");
  38. VERIFY(bytes[0] == QOI_OP_RGB);
  39. // The alpha value remains unchanged from the previous pixel.
  40. return Color { bytes[1], bytes[2], bytes[3], pixel.alpha() };
  41. }
  42. static ErrorOr<Color> decode_qoi_op_rgba(InputMemoryStream& stream)
  43. {
  44. u8 bytes[5];
  45. stream >> Bytes { &bytes, array_size(bytes) };
  46. if (stream.handle_any_error())
  47. return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RGBA chunk");
  48. VERIFY(bytes[0] == QOI_OP_RGBA);
  49. return Color { bytes[1], bytes[2], bytes[3], bytes[4] };
  50. }
  51. static ErrorOr<u8> decode_qoi_op_index(InputMemoryStream& stream)
  52. {
  53. u8 byte;
  54. stream >> byte;
  55. if (stream.handle_any_error())
  56. return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_INDEX chunk");
  57. VERIFY((byte & QOI_MASK_2) == QOI_OP_INDEX);
  58. u8 index = byte & ~QOI_MASK_2;
  59. VERIFY(index <= 63);
  60. return index;
  61. }
  62. static ErrorOr<Color> decode_qoi_op_diff(InputMemoryStream& stream, Color pixel)
  63. {
  64. u8 byte;
  65. stream >> byte;
  66. if (stream.handle_any_error())
  67. return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_DIFF chunk");
  68. VERIFY((byte & QOI_MASK_2) == QOI_OP_DIFF);
  69. u8 dr = (byte & 0b00110000) >> 4;
  70. u8 dg = (byte & 0b00001100) >> 2;
  71. u8 db = (byte & 0b00000011);
  72. VERIFY(dr <= 3 && dg <= 3 && db <= 3);
  73. // Values are stored as unsigned integers with a bias of 2.
  74. return Color {
  75. static_cast<u8>(pixel.red() + static_cast<i8>(dr - 2)),
  76. static_cast<u8>(pixel.green() + static_cast<i8>(dg - 2)),
  77. static_cast<u8>(pixel.blue() + static_cast<i8>(db - 2)),
  78. pixel.alpha(),
  79. };
  80. }
  81. static ErrorOr<Color> decode_qoi_op_luma(InputMemoryStream& stream, Color pixel)
  82. {
  83. u8 bytes[2];
  84. stream >> Bytes { &bytes, array_size(bytes) };
  85. if (stream.handle_any_error())
  86. return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_LUMA chunk");
  87. VERIFY((bytes[0] & QOI_MASK_2) == QOI_OP_LUMA);
  88. u8 diff_green = (bytes[0] & ~QOI_MASK_2);
  89. u8 dr_dg = (bytes[1] & 0b11110000) >> 4;
  90. u8 db_dg = (bytes[1] & 0b00001111);
  91. // Values are stored as unsigned integers with a bias of 32 for the green channel and a bias of 8 for the red and blue channel.
  92. return Color {
  93. static_cast<u8>(pixel.red() + static_cast<i8>((diff_green - 32) + (dr_dg - 8))),
  94. static_cast<u8>(pixel.green() + static_cast<i8>(diff_green - 32)),
  95. static_cast<u8>(pixel.blue() + static_cast<i8>((diff_green - 32) + (db_dg - 8))),
  96. pixel.alpha(),
  97. };
  98. }
  99. static ErrorOr<u8> decode_qoi_op_run(InputMemoryStream& stream)
  100. {
  101. u8 byte;
  102. stream >> byte;
  103. if (stream.handle_any_error())
  104. return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RUN chunk");
  105. VERIFY((byte & QOI_MASK_2) == QOI_OP_RUN);
  106. u8 run = byte & ~QOI_MASK_2;
  107. // The run-length is stored with a bias of -1.
  108. run += 1;
  109. // Note that the run-lengths 63 and 64 (b111110 and b111111) are illegal as they are occupied by the QOI_OP_RGB and QOI_OP_RGBA tags.
  110. if (run == QOI_OP_RGB || run == QOI_OP_RGBA)
  111. return Error::from_string_literal("Invalid QOI image: illegal run length");
  112. VERIFY(run >= 1 && run <= 62);
  113. return run;
  114. }
  115. static ErrorOr<void> decode_qoi_end_marker(InputMemoryStream& stream)
  116. {
  117. u8 bytes[array_size(END_MARKER)];
  118. stream >> Bytes { &bytes, array_size(bytes) };
  119. if (stream.handle_any_error())
  120. return Error::from_string_literal("Invalid QOI image: end of stream while reading end marker");
  121. if (!stream.eof())
  122. return Error::from_string_literal("Invalid QOI image: expected end of stream but more bytes are available");
  123. if (memcmp(&END_MARKER, &bytes, array_size(bytes)) != 0)
  124. return Error::from_string_literal("Invalid QOI image: incorrect end marker");
  125. return {};
  126. }
  127. static ErrorOr<NonnullRefPtr<Bitmap>> decode_qoi_image(InputMemoryStream& stream, u32 width, u32 height)
  128. {
  129. // FIXME: Why is Gfx::Bitmap's size signed? Makes no sense whatsoever.
  130. if (width > NumericLimits<int>::max())
  131. return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, width exceeds maximum Gfx::Bitmap width");
  132. if (height > NumericLimits<int>::max())
  133. return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, height exceeds maximum Gfx::Bitmap height");
  134. auto bitmap = TRY(Bitmap::try_create(BitmapFormat::BGRA8888, { width, height }));
  135. u8 run = 0;
  136. Color pixel = { 0, 0, 0, 255 };
  137. Color previous_pixels[64] {};
  138. for (u32 y = 0; y < height; ++y) {
  139. for (u32 x = 0; x < width; ++x) {
  140. if (run > 0)
  141. --run;
  142. if (run == 0) {
  143. u8 tag = stream.peek_or_error();
  144. if (stream.handle_any_error())
  145. return Error::from_string_literal("Invalid QOI image: end of stream while reading chunk tag");
  146. if (tag == QOI_OP_RGB)
  147. pixel = TRY(decode_qoi_op_rgb(stream, pixel));
  148. else if (tag == QOI_OP_RGBA)
  149. pixel = TRY(decode_qoi_op_rgba(stream));
  150. else if ((tag & QOI_MASK_2) == QOI_OP_INDEX)
  151. pixel = previous_pixels[TRY(decode_qoi_op_index(stream))];
  152. else if ((tag & QOI_MASK_2) == QOI_OP_DIFF)
  153. pixel = TRY(decode_qoi_op_diff(stream, pixel));
  154. else if ((tag & QOI_MASK_2) == QOI_OP_LUMA)
  155. pixel = TRY(decode_qoi_op_luma(stream, pixel));
  156. else if ((tag & QOI_MASK_2) == QOI_OP_RUN)
  157. run = TRY(decode_qoi_op_run(stream));
  158. else
  159. return Error::from_string_literal("Invalid QOI image: unknown chunk tag");
  160. }
  161. auto index_position = (pixel.red() * 3 + pixel.green() * 5 + pixel.blue() * 7 + pixel.alpha() * 11) % 64;
  162. previous_pixels[index_position] = pixel;
  163. bitmap->set_pixel(x, y, pixel);
  164. }
  165. }
  166. TRY(decode_qoi_end_marker(stream));
  167. return { move(bitmap) };
  168. }
  169. QOIImageDecoderPlugin::QOIImageDecoderPlugin(u8 const* data, size_t size)
  170. {
  171. m_context = make<QOILoadingContext>();
  172. m_context->data = data;
  173. m_context->data_size = size;
  174. }
  175. IntSize QOIImageDecoderPlugin::size()
  176. {
  177. if (m_context->state < QOILoadingContext::State::HeaderDecoded) {
  178. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  179. // FIXME: This is a weird API (inherited from ImageDecoderPlugin), should probably propagate errors by returning ErrorOr<IntSize>.
  180. // For the time being, ignore the result and rely on the context's state.
  181. (void)decode_header_and_update_context(stream);
  182. }
  183. if (m_context->state == QOILoadingContext::State::Error)
  184. return {};
  185. return { m_context->header.width, m_context->header.height };
  186. }
  187. void QOIImageDecoderPlugin::set_volatile()
  188. {
  189. if (m_context->bitmap)
  190. m_context->bitmap->set_volatile();
  191. }
  192. bool QOIImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  193. {
  194. if (!m_context->bitmap)
  195. return false;
  196. return m_context->bitmap->set_nonvolatile(was_purged);
  197. }
  198. bool QOIImageDecoderPlugin::initialize()
  199. {
  200. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  201. return !decode_qoi_header(stream).is_error();
  202. }
  203. ErrorOr<bool> QOIImageDecoderPlugin::sniff(ReadonlyBytes data)
  204. {
  205. InputMemoryStream stream { { data.data(), data.size() } };
  206. return !decode_qoi_header(stream).is_error();
  207. }
  208. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> QOIImageDecoderPlugin::create(ReadonlyBytes data)
  209. {
  210. return adopt_nonnull_own_or_enomem(new (nothrow) QOIImageDecoderPlugin(data.data(), data.size()));
  211. }
  212. ErrorOr<ImageFrameDescriptor> QOIImageDecoderPlugin::frame(size_t index)
  213. {
  214. if (index > 0)
  215. return Error::from_string_literal("Invalid frame index");
  216. if (m_context->state == QOILoadingContext::State::NotDecoded) {
  217. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  218. TRY(decode_header_and_update_context(stream));
  219. TRY(decode_image_and_update_context(stream));
  220. } else if (m_context->state == QOILoadingContext::State::HeaderDecoded) {
  221. InputMemoryStream stream { { m_context->data, m_context->data_size } };
  222. VERIFY(stream.discard_or_error(sizeof(m_context->header)));
  223. TRY(decode_image_and_update_context(stream));
  224. }
  225. if (m_context->state == QOILoadingContext::State::ImageDecoded) {
  226. VERIFY(m_context->bitmap);
  227. return ImageFrameDescriptor { m_context->bitmap, 0 };
  228. }
  229. VERIFY(m_context->state == QOILoadingContext::State::Error);
  230. VERIFY(m_context->error.has_value());
  231. return *m_context->error;
  232. }
  233. ErrorOr<void> QOIImageDecoderPlugin::decode_header_and_update_context(InputMemoryStream& stream)
  234. {
  235. VERIFY(m_context->state < QOILoadingContext::State::HeaderDecoded);
  236. auto error_or_header = decode_qoi_header(stream);
  237. if (error_or_header.is_error()) {
  238. m_context->state = QOILoadingContext::State::Error;
  239. m_context->error = error_or_header.release_error();
  240. return *m_context->error;
  241. }
  242. m_context->state = QOILoadingContext::State::HeaderDecoded;
  243. m_context->header = error_or_header.release_value();
  244. return {};
  245. }
  246. ErrorOr<void> QOIImageDecoderPlugin::decode_image_and_update_context(InputMemoryStream& stream)
  247. {
  248. VERIFY(m_context->state < QOILoadingContext::State::ImageDecoded);
  249. auto error_or_bitmap = decode_qoi_image(stream, m_context->header.width, m_context->header.height);
  250. if (error_or_bitmap.is_error()) {
  251. m_context->state = QOILoadingContext::State::Error;
  252. m_context->error = error_or_bitmap.release_error();
  253. return *m_context->error;
  254. }
  255. m_context->state = QOILoadingContext::State::ImageDecoded;
  256. m_context->bitmap = error_or_bitmap.release_value();
  257. return {};
  258. }
  259. }