QOILoader.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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/ImageFormats/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(Stream& stream)
  21. {
  22. auto header = TRY(stream.read_value<QOIHeader>());
  23. if (StringView { header.magic, array_size(header.magic) } != QOI_MAGIC)
  24. return Error::from_string_literal("Invalid QOI image: incorrect header magic");
  25. header.width = AK::convert_between_host_and_big_endian(header.width);
  26. header.height = AK::convert_between_host_and_big_endian(header.height);
  27. return header;
  28. }
  29. static ErrorOr<Color> decode_qoi_op_rgb(Stream& stream, u8 first_byte, Color pixel)
  30. {
  31. VERIFY(first_byte == QOI_OP_RGB);
  32. u8 bytes[3];
  33. TRY(stream.read_until_filled({ &bytes, array_size(bytes) }));
  34. // The alpha value remains unchanged from the previous pixel.
  35. return Color { bytes[0], bytes[1], bytes[2], pixel.alpha() };
  36. }
  37. static ErrorOr<Color> decode_qoi_op_rgba(Stream& stream, u8 first_byte)
  38. {
  39. VERIFY(first_byte == QOI_OP_RGBA);
  40. u8 bytes[4];
  41. TRY(stream.read_until_filled({ &bytes, array_size(bytes) }));
  42. return Color { bytes[0], bytes[1], bytes[2], bytes[3] };
  43. }
  44. static ErrorOr<u8> decode_qoi_op_index(Stream&, u8 first_byte)
  45. {
  46. VERIFY((first_byte & QOI_MASK_2) == QOI_OP_INDEX);
  47. u8 index = first_byte & ~QOI_MASK_2;
  48. VERIFY(index <= 63);
  49. return index;
  50. }
  51. static ErrorOr<Color> decode_qoi_op_diff(Stream&, u8 first_byte, Color pixel)
  52. {
  53. VERIFY((first_byte & QOI_MASK_2) == QOI_OP_DIFF);
  54. u8 dr = (first_byte & 0b00110000) >> 4;
  55. u8 dg = (first_byte & 0b00001100) >> 2;
  56. u8 db = (first_byte & 0b00000011);
  57. VERIFY(dr <= 3 && dg <= 3 && db <= 3);
  58. // Values are stored as unsigned integers with a bias of 2.
  59. return Color {
  60. static_cast<u8>(pixel.red() + static_cast<i8>(dr - 2)),
  61. static_cast<u8>(pixel.green() + static_cast<i8>(dg - 2)),
  62. static_cast<u8>(pixel.blue() + static_cast<i8>(db - 2)),
  63. pixel.alpha(),
  64. };
  65. }
  66. static ErrorOr<Color> decode_qoi_op_luma(Stream& stream, u8 first_byte, Color pixel)
  67. {
  68. VERIFY((first_byte & QOI_MASK_2) == QOI_OP_LUMA);
  69. auto byte = TRY(stream.read_value<u8>());
  70. u8 diff_green = (first_byte & ~QOI_MASK_2);
  71. u8 dr_dg = (byte & 0b11110000) >> 4;
  72. u8 db_dg = (byte & 0b00001111);
  73. // 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.
  74. return Color {
  75. static_cast<u8>(pixel.red() + static_cast<i8>((diff_green - 32) + (dr_dg - 8))),
  76. static_cast<u8>(pixel.green() + static_cast<i8>(diff_green - 32)),
  77. static_cast<u8>(pixel.blue() + static_cast<i8>((diff_green - 32) + (db_dg - 8))),
  78. pixel.alpha(),
  79. };
  80. }
  81. static ErrorOr<u8> decode_qoi_op_run(Stream&, u8 first_byte)
  82. {
  83. VERIFY((first_byte & QOI_MASK_2) == QOI_OP_RUN);
  84. u8 run = first_byte & ~QOI_MASK_2;
  85. // The run-length is stored with a bias of -1.
  86. run += 1;
  87. // 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.
  88. if (run == QOI_OP_RGB || run == QOI_OP_RGBA)
  89. return Error::from_string_literal("Invalid QOI image: illegal run length");
  90. VERIFY(run >= 1 && run <= 62);
  91. return run;
  92. }
  93. static ErrorOr<void> decode_qoi_end_marker(Stream& stream)
  94. {
  95. u8 bytes[array_size(END_MARKER)];
  96. TRY(stream.read_until_filled({ &bytes, array_size(bytes) }));
  97. if (!stream.is_eof())
  98. return Error::from_string_literal("Invalid QOI image: expected end of stream but more bytes are available");
  99. if (memcmp(&END_MARKER, &bytes, array_size(bytes)) != 0)
  100. return Error::from_string_literal("Invalid QOI image: incorrect end marker");
  101. return {};
  102. }
  103. static ErrorOr<NonnullRefPtr<Bitmap>> decode_qoi_image(Stream& stream, u32 width, u32 height)
  104. {
  105. // FIXME: Why is Gfx::Bitmap's size signed? Makes no sense whatsoever.
  106. if (width > NumericLimits<int>::max())
  107. return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, width exceeds maximum Gfx::Bitmap width");
  108. if (height > NumericLimits<int>::max())
  109. return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, height exceeds maximum Gfx::Bitmap height");
  110. auto bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, { width, height }));
  111. u8 run = 0;
  112. Color pixel = { 0, 0, 0, 255 };
  113. Color previous_pixels[64] {};
  114. for (u32 y = 0; y < height; ++y) {
  115. for (u32 x = 0; x < width; ++x) {
  116. if (run > 0)
  117. --run;
  118. if (run == 0) {
  119. auto first_byte = TRY(stream.read_value<u8>());
  120. if (first_byte == QOI_OP_RGB)
  121. pixel = TRY(decode_qoi_op_rgb(stream, first_byte, pixel));
  122. else if (first_byte == QOI_OP_RGBA)
  123. pixel = TRY(decode_qoi_op_rgba(stream, first_byte));
  124. else if ((first_byte & QOI_MASK_2) == QOI_OP_INDEX)
  125. pixel = previous_pixels[TRY(decode_qoi_op_index(stream, first_byte))];
  126. else if ((first_byte & QOI_MASK_2) == QOI_OP_DIFF)
  127. pixel = TRY(decode_qoi_op_diff(stream, first_byte, pixel));
  128. else if ((first_byte & QOI_MASK_2) == QOI_OP_LUMA)
  129. pixel = TRY(decode_qoi_op_luma(stream, first_byte, pixel));
  130. else if ((first_byte & QOI_MASK_2) == QOI_OP_RUN)
  131. run = TRY(decode_qoi_op_run(stream, first_byte));
  132. else
  133. return Error::from_string_literal("Invalid QOI image: unknown chunk tag");
  134. }
  135. auto index_position = (pixel.red() * 3 + pixel.green() * 5 + pixel.blue() * 7 + pixel.alpha() * 11) % 64;
  136. previous_pixels[index_position] = pixel;
  137. bitmap->set_pixel(x, y, pixel);
  138. }
  139. }
  140. TRY(decode_qoi_end_marker(stream));
  141. return { move(bitmap) };
  142. }
  143. QOIImageDecoderPlugin::QOIImageDecoderPlugin(NonnullOwnPtr<Stream> stream)
  144. {
  145. m_context = make<QOILoadingContext>();
  146. m_context->stream = move(stream);
  147. }
  148. IntSize QOIImageDecoderPlugin::size()
  149. {
  150. if (m_context->state < QOILoadingContext::State::HeaderDecoded) {
  151. // FIXME: This is a weird API (inherited from ImageDecoderPlugin), should probably propagate errors by returning ErrorOr<IntSize>.
  152. // For the time being, ignore the result and rely on the context's state.
  153. (void)decode_header_and_update_context(*m_context->stream);
  154. }
  155. if (m_context->state == QOILoadingContext::State::Error)
  156. return {};
  157. return { m_context->header.width, m_context->header.height };
  158. }
  159. ErrorOr<void> QOIImageDecoderPlugin::initialize()
  160. {
  161. return decode_header_and_update_context(*m_context->stream);
  162. }
  163. bool QOIImageDecoderPlugin::sniff(ReadonlyBytes data)
  164. {
  165. FixedMemoryStream stream { { data.data(), data.size() } };
  166. return !decode_qoi_header(stream).is_error();
  167. }
  168. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> QOIImageDecoderPlugin::create(ReadonlyBytes data)
  169. {
  170. auto stream = TRY(try_make<FixedMemoryStream>(data));
  171. return adopt_nonnull_own_or_enomem(new (nothrow) QOIImageDecoderPlugin(move(stream)));
  172. }
  173. ErrorOr<ImageFrameDescriptor> QOIImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  174. {
  175. if (index > 0)
  176. return Error::from_string_literal("Invalid frame index");
  177. // No one should try to decode the frame again after an error was already returned.
  178. VERIFY(m_context->state != QOILoadingContext::State::Error);
  179. if (m_context->state == QOILoadingContext::State::NotDecoded) {
  180. TRY(decode_header_and_update_context(*m_context->stream));
  181. TRY(decode_image_and_update_context(*m_context->stream));
  182. } else if (m_context->state == QOILoadingContext::State::HeaderDecoded) {
  183. TRY(decode_image_and_update_context(*m_context->stream));
  184. }
  185. VERIFY(m_context->state == QOILoadingContext::State::ImageDecoded);
  186. VERIFY(m_context->bitmap);
  187. return ImageFrameDescriptor { m_context->bitmap, 0 };
  188. }
  189. ErrorOr<void> QOIImageDecoderPlugin::decode_header_and_update_context(Stream& stream)
  190. {
  191. VERIFY(m_context->state < QOILoadingContext::State::HeaderDecoded);
  192. auto error_or_header = decode_qoi_header(stream);
  193. if (error_or_header.is_error()) {
  194. m_context->state = QOILoadingContext::State::Error;
  195. return error_or_header.release_error();
  196. }
  197. m_context->state = QOILoadingContext::State::HeaderDecoded;
  198. m_context->header = error_or_header.release_value();
  199. return {};
  200. }
  201. ErrorOr<void> QOIImageDecoderPlugin::decode_image_and_update_context(Stream& stream)
  202. {
  203. VERIFY(m_context->state < QOILoadingContext::State::ImageDecoded);
  204. auto error_or_bitmap = decode_qoi_image(stream, m_context->header.width, m_context->header.height);
  205. if (error_or_bitmap.is_error()) {
  206. m_context->state = QOILoadingContext::State::Error;
  207. return error_or_bitmap.release_error();
  208. }
  209. m_context->state = QOILoadingContext::State::ImageDecoded;
  210. m_context->bitmap = error_or_bitmap.release_value();
  211. return {};
  212. }
  213. ErrorOr<Optional<ReadonlyBytes>> QOIImageDecoderPlugin::icc_data()
  214. {
  215. return OptionalNone {};
  216. }
  217. }