WebPLoader.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /*
  2. * Copyright (c) 2023, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Endian.h>
  8. #include <AK/Format.h>
  9. #include <LibGfx/WebPLoader.h>
  10. // Container: https://developers.google.com/speed/webp/docs/riff_container
  11. // Lossless format: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
  12. // Lossy format: https://datatracker.ietf.org/doc/html/rfc6386
  13. namespace Gfx {
  14. namespace {
  15. struct FourCC {
  16. constexpr FourCC(char const* name)
  17. {
  18. cc[0] = name[0];
  19. cc[1] = name[1];
  20. cc[2] = name[2];
  21. cc[3] = name[3];
  22. }
  23. bool operator==(FourCC const&) const = default;
  24. bool operator!=(FourCC const&) const = default;
  25. char cc[4];
  26. };
  27. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  28. struct WebPFileHeader {
  29. FourCC riff;
  30. LittleEndian<u32> file_size;
  31. FourCC webp;
  32. };
  33. static_assert(AssertSize<WebPFileHeader, 12>());
  34. struct ChunkHeader {
  35. FourCC chunk_type;
  36. LittleEndian<u32> chunk_size;
  37. };
  38. static_assert(AssertSize<ChunkHeader, 8>());
  39. struct Chunk {
  40. FourCC type;
  41. ReadonlyBytes data;
  42. };
  43. }
  44. struct WebPLoadingContext {
  45. enum State {
  46. NotDecoded = 0,
  47. Error,
  48. HeaderDecoded,
  49. SizeDecoded,
  50. ChunksDecoded,
  51. BitmapDecoded,
  52. };
  53. State state { State::NotDecoded };
  54. ReadonlyBytes data;
  55. RefPtr<Gfx::Bitmap> bitmap;
  56. Optional<ReadonlyBytes> icc_data;
  57. template<size_t N>
  58. [[nodiscard]] class Error error(char const (&string_literal)[N])
  59. {
  60. state = WebPLoadingContext::State::Error;
  61. return Error::from_string_literal(string_literal);
  62. }
  63. };
  64. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  65. static ErrorOr<void> decode_webp_header(WebPLoadingContext& context)
  66. {
  67. if (context.state >= WebPLoadingContext::HeaderDecoded)
  68. return {};
  69. if (context.data.size() < sizeof(WebPFileHeader))
  70. return context.error("Missing WebP header");
  71. auto& header = *bit_cast<WebPFileHeader const*>(context.data.data());
  72. if (header.riff != FourCC("RIFF") || header.webp != FourCC("WEBP"))
  73. return context.error("Invalid WebP header");
  74. // "File Size: [...] The size of the file in bytes starting at offset 8. The maximum value of this field is 2^32 minus 10 bytes."
  75. u32 const maximum_webp_file_size = 0xffff'ffff - 9;
  76. if (header.file_size > maximum_webp_file_size)
  77. return context.error("WebP header file size over maximum");
  78. // "The file size in the header is the total size of the chunks that follow plus 4 bytes for the 'WEBP' FourCC.
  79. // The file SHOULD NOT contain any data after the data specified by File Size.
  80. // Readers MAY parse such files, ignoring the trailing data."
  81. if (context.data.size() - 8 < header.file_size)
  82. return context.error("WebP data too small for size in header");
  83. if (context.data.size() - 8 > header.file_size) {
  84. dbgln_if(WEBP_DEBUG, "WebP has {} bytes of data, but header needs only {}. Trimming.", context.data.size(), header.file_size + 8);
  85. context.data = context.data.trim(header.file_size + 8);
  86. }
  87. context.state = WebPLoadingContext::HeaderDecoded;
  88. return {};
  89. }
  90. // https://developers.google.com/speed/webp/docs/riff_container#riff_file_format
  91. static ErrorOr<Chunk> decode_webp_chunk_header(WebPLoadingContext& context, ReadonlyBytes chunks)
  92. {
  93. if (chunks.size() < sizeof(ChunkHeader))
  94. return context.error("Not enough data for WebP chunk header");
  95. auto const& header = *bit_cast<ChunkHeader const*>(chunks.data());
  96. dbgln_if(WEBP_DEBUG, "chunk {} size {}", header.chunk_type, header.chunk_size);
  97. if (chunks.size() < sizeof(ChunkHeader) + header.chunk_size)
  98. return context.error("Not enough data for WebP chunk");
  99. return Chunk { header.chunk_type, { chunks.data() + sizeof(ChunkHeader), header.chunk_size } };
  100. }
  101. // https://developers.google.com/speed/webp/docs/riff_container#riff_file_format
  102. static ErrorOr<Chunk> decode_webp_advance_chunk(WebPLoadingContext& context, ReadonlyBytes& chunks)
  103. {
  104. auto chunk = TRY(decode_webp_chunk_header(context, chunks));
  105. // "Chunk Size: 32 bits (uint32)
  106. // The size of the chunk in bytes, not including this field, the chunk identifier or padding.
  107. // Chunk Payload: Chunk Size bytes
  108. // The data payload. If Chunk Size is odd, a single padding byte -- that MUST be 0 to conform with RIFF -- is added."
  109. chunks = chunks.slice(sizeof(ChunkHeader) + chunk.data.size());
  110. if (chunk.data.size() % 2 != 0) {
  111. if (chunks.is_empty())
  112. return context.error("Missing data for padding byte");
  113. if (*chunks.data() != 0)
  114. return context.error("Padding byte is not 0");
  115. chunks = chunks.slice(1);
  116. }
  117. return chunk;
  118. }
  119. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossy
  120. static ErrorOr<void> decode_webp_simple_lossy(WebPLoadingContext& context, Chunk const& vp8_chunk)
  121. {
  122. // FIXME
  123. (void)context;
  124. (void)vp8_chunk;
  125. return {};
  126. }
  127. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
  128. static ErrorOr<void> decode_webp_simple_lossless(WebPLoadingContext& context, Chunk const& vp8l_chunk)
  129. {
  130. // FIXME
  131. (void)context;
  132. (void)vp8l_chunk;
  133. return {};
  134. }
  135. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  136. static ErrorOr<void> decode_webp_extended(WebPLoadingContext& context, Chunk const& vp8x_chunk, ReadonlyBytes chunks)
  137. {
  138. // FIXME: Do something with this.
  139. (void)vp8x_chunk;
  140. // FIXME: This isn't quite to spec, which says
  141. // "All chunks SHOULD be placed in the same order as listed above.
  142. // If a chunk appears in the wrong place, the file is invalid, but readers MAY parse the file, ignoring the chunks that are out of order."
  143. while (!chunks.is_empty()) {
  144. auto chunk = TRY(decode_webp_advance_chunk(context, chunks));
  145. if (chunk.type == FourCC("ICCP"))
  146. context.icc_data = chunk.data;
  147. // FIXME: Probably want to make this and decode_webp_simple_lossy/lossless call the same function
  148. // instead of calling the _simple functions from the _extended function.
  149. if (chunk.type == FourCC("VP8 "))
  150. TRY(decode_webp_simple_lossy(context, chunk));
  151. if (chunk.type == FourCC("VP8X"))
  152. TRY(decode_webp_simple_lossless(context, chunk));
  153. }
  154. context.state = WebPLoadingContext::State::ChunksDecoded;
  155. return {};
  156. }
  157. static ErrorOr<void> decode_webp_chunks(WebPLoadingContext& context)
  158. {
  159. if (context.state >= WebPLoadingContext::State::ChunksDecoded)
  160. return {};
  161. if (context.state < WebPLoadingContext::HeaderDecoded)
  162. TRY(decode_webp_header(context));
  163. ReadonlyBytes chunks = context.data.slice(sizeof(WebPFileHeader));
  164. auto first_chunk = TRY(decode_webp_advance_chunk(context, chunks));
  165. if (first_chunk.type == FourCC("VP8 ")) {
  166. context.state = WebPLoadingContext::State::ChunksDecoded;
  167. return decode_webp_simple_lossy(context, first_chunk);
  168. }
  169. if (first_chunk.type == FourCC("VP8L")) {
  170. context.state = WebPLoadingContext::State::ChunksDecoded;
  171. return decode_webp_simple_lossless(context, first_chunk);
  172. }
  173. if (first_chunk.type == FourCC("VP8X"))
  174. return decode_webp_extended(context, first_chunk, chunks);
  175. return context.error("WebPImageDecoderPlugin: Invalid first chunk type");
  176. }
  177. WebPImageDecoderPlugin::WebPImageDecoderPlugin(ReadonlyBytes data, OwnPtr<WebPLoadingContext> context)
  178. : m_context(move(context))
  179. {
  180. m_context->data = data;
  181. }
  182. WebPImageDecoderPlugin::~WebPImageDecoderPlugin() = default;
  183. IntSize WebPImageDecoderPlugin::size()
  184. {
  185. if (m_context->state == WebPLoadingContext::State::Error)
  186. return {};
  187. if (m_context->state < WebPLoadingContext::State::SizeDecoded) {
  188. // FIXME
  189. }
  190. // FIXME
  191. return { 0, 0 };
  192. }
  193. void WebPImageDecoderPlugin::set_volatile()
  194. {
  195. if (m_context->bitmap)
  196. m_context->bitmap->set_volatile();
  197. }
  198. bool WebPImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  199. {
  200. if (!m_context->bitmap)
  201. return false;
  202. return m_context->bitmap->set_nonvolatile(was_purged);
  203. }
  204. bool WebPImageDecoderPlugin::initialize()
  205. {
  206. return !decode_webp_header(*m_context).is_error();
  207. }
  208. ErrorOr<bool> WebPImageDecoderPlugin::sniff(ReadonlyBytes data)
  209. {
  210. WebPLoadingContext context;
  211. context.data = data;
  212. TRY(decode_webp_header(context));
  213. return true;
  214. }
  215. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> WebPImageDecoderPlugin::create(ReadonlyBytes data)
  216. {
  217. auto context = TRY(try_make<WebPLoadingContext>());
  218. return adopt_nonnull_own_or_enomem(new (nothrow) WebPImageDecoderPlugin(data, move(context)));
  219. }
  220. bool WebPImageDecoderPlugin::is_animated()
  221. {
  222. // FIXME
  223. return false;
  224. }
  225. size_t WebPImageDecoderPlugin::loop_count()
  226. {
  227. // FIXME
  228. return 0;
  229. }
  230. size_t WebPImageDecoderPlugin::frame_count()
  231. {
  232. // FIXME
  233. return 1;
  234. }
  235. ErrorOr<ImageFrameDescriptor> WebPImageDecoderPlugin::frame(size_t index)
  236. {
  237. if (index >= frame_count())
  238. return Error::from_string_literal("WebPImageDecoderPlugin: Invalid frame index");
  239. return Error::from_string_literal("WebPImageDecoderPlugin: decoding not yet implemented");
  240. }
  241. ErrorOr<Optional<ReadonlyBytes>> WebPImageDecoderPlugin::icc_data()
  242. {
  243. TRY(decode_webp_chunks(*m_context));
  244. // FIXME: "If this chunk is not present, sRGB SHOULD be assumed."
  245. return m_context->icc_data;
  246. }
  247. }
  248. template<>
  249. struct AK::Formatter<Gfx::FourCC> : StandardFormatter {
  250. ErrorOr<void> format(FormatBuilder& builder, Gfx::FourCC const& four_cc)
  251. {
  252. TRY(builder.put_padding('\'', 1));
  253. TRY(builder.put_padding(four_cc.cc[0], 1));
  254. TRY(builder.put_padding(four_cc.cc[1], 1));
  255. TRY(builder.put_padding(four_cc.cc[2], 1));
  256. TRY(builder.put_padding(four_cc.cc[3], 1));
  257. TRY(builder.put_padding('\'', 1));
  258. return {};
  259. }
  260. };