ILBMLoader.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * Copyright (c) 2023, Nicolas Ramz <nicolas.ramz@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Endian.h>
  8. #include <AK/FixedArray.h>
  9. #include <LibGfx/ImageFormats/ILBMLoader.h>
  10. namespace Gfx {
  11. struct IFFHeader {
  12. FourCC form;
  13. BigEndian<u32> file_size;
  14. FourCC format;
  15. };
  16. static_assert(AssertSize<IFFHeader, 12>());
  17. struct Chunk {
  18. FourCC type;
  19. ReadonlyBytes data;
  20. };
  21. enum class CompressionType : u8 {
  22. None = 0,
  23. ByteRun = 1
  24. };
  25. enum class MaskType : u8 {
  26. None = 0,
  27. HasMask = 1,
  28. HasTransparentColor = 2,
  29. HasLasso = 3
  30. };
  31. struct ChunkHeader {
  32. FourCC chunk_type;
  33. BigEndian<u32> chunk_size;
  34. };
  35. struct BMHDHeader {
  36. BigEndian<u16> width;
  37. BigEndian<u16> height;
  38. BigEndian<i16> x;
  39. BigEndian<i16> y;
  40. u8 planes;
  41. MaskType mask;
  42. CompressionType compression;
  43. u8 pad;
  44. BigEndian<u16> transparent_color;
  45. u8 x_aspect;
  46. u8 y_aspect;
  47. BigEndian<u16> page_width;
  48. BigEndian<u16> page_height;
  49. };
  50. static_assert(sizeof(BMHDHeader) == 20);
  51. struct ILBMLoadingContext {
  52. enum class State {
  53. NotDecoded = 0,
  54. HeaderDecoded,
  55. BitmapDecoded
  56. };
  57. State state { State::NotDecoded };
  58. ReadonlyBytes data;
  59. // points to current chunk
  60. ReadonlyBytes chunks_cursor;
  61. // max number of bytes per plane row
  62. u16 pitch;
  63. FixedArray<Color> color_table;
  64. RefPtr<Gfx::Bitmap> bitmap;
  65. BMHDHeader bm_header;
  66. };
  67. static ErrorOr<void> decode_iff_ilbm_header(ILBMLoadingContext& context)
  68. {
  69. if (context.state >= ILBMLoadingContext::State::HeaderDecoded)
  70. return {};
  71. if (context.data.size() < sizeof(IFFHeader))
  72. return Error::from_string_literal("Missing IFF header");
  73. auto& header = *bit_cast<IFFHeader const*>(context.data.data());
  74. if (header.form != FourCC("FORM") || header.format != FourCC("ILBM"))
  75. return Error::from_string_literal("Invalid IFF-ILBM header");
  76. return {};
  77. }
  78. static ErrorOr<FixedArray<Color>> decode_cmap_chunk(Chunk cmap_chunk)
  79. {
  80. size_t const size = cmap_chunk.data.size() / 3;
  81. FixedArray<Color> color_table = TRY(FixedArray<Color>::create(size));
  82. for (size_t i = 0; i < size; ++i) {
  83. color_table[i] = Color(cmap_chunk.data[i * 3], cmap_chunk.data[(i * 3) + 1], cmap_chunk.data[(i * 3) + 2]);
  84. }
  85. return color_table;
  86. }
  87. static ErrorOr<RefPtr<Gfx::Bitmap>> chunky_to_bitmap(ILBMLoadingContext& context, ByteBuffer const& chunky)
  88. {
  89. auto const width = context.bm_header.width;
  90. auto const height = context.bm_header.height;
  91. RefPtr<Gfx::Bitmap> bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, { width, height }));
  92. dbgln_if(ILBM_DEBUG, "created Bitmap {}x{}", width, height);
  93. for (int row = 0; row < height; ++row) {
  94. for (int col = 0; col < width; ++col) {
  95. u8 index = chunky[(width * row) + col];
  96. bitmap->set_pixel(col, row, context.color_table[index]);
  97. }
  98. }
  99. dbgln_if(ILBM_DEBUG, "filled Bitmap");
  100. return bitmap;
  101. }
  102. static ErrorOr<ByteBuffer> planar_to_chunky(ReadonlyBytes bitplanes, ILBMLoadingContext& context)
  103. {
  104. dbgln_if(ILBM_DEBUG, "planar_to_chunky");
  105. u16 pitch = context.pitch;
  106. u16 width = context.bm_header.width;
  107. u16 height = context.bm_header.height;
  108. u8 planes = context.bm_header.planes;
  109. auto chunky = TRY(ByteBuffer::create_zeroed(width * height));
  110. for (u16 y = 0; y < height; y++) {
  111. for (u8 p = 0; p < planes; p++) {
  112. u8 const plane_mask = 1 << p;
  113. for (u16 i = 0; i < pitch; i++) {
  114. u16 offset = (pitch * planes * y) + (p * pitch) + i;
  115. u8 bit = bitplanes[offset];
  116. for (u8 b = 0; b < 8; b++) {
  117. u8 mask = 1 << (7 - b);
  118. // get current plane
  119. if (bit & mask) {
  120. u16 x = (i * 8) + b;
  121. chunky[(y * width) + x] |= plane_mask;
  122. }
  123. }
  124. }
  125. }
  126. }
  127. return chunky;
  128. }
  129. static ErrorOr<ByteBuffer> uncompress_byte_run(ReadonlyBytes data, ILBMLoadingContext& context)
  130. {
  131. auto length = data.size();
  132. dbgln_if(ILBM_DEBUG, "uncompress_byte_run pitch={} size={}", context.pitch, data.size());
  133. auto plane_data = TRY(ByteBuffer::create_uninitialized(context.pitch * context.bm_header.height * context.bm_header.planes));
  134. u32 index = 0;
  135. u32 read_bytes = 0;
  136. while (read_bytes < length) {
  137. auto const byte = static_cast<i8>(data[read_bytes++]);
  138. if (byte >= -127 && byte <= -1) {
  139. // read next byte
  140. u8 next_byte = data[read_bytes++];
  141. for (u16 i = 0; i < -byte + 1; ++i) {
  142. plane_data[index++] = next_byte;
  143. }
  144. } else if (byte >= 0) {
  145. for (u16 i = 0; i < byte + 1; ++i) {
  146. plane_data[index] = data[read_bytes];
  147. read_bytes++;
  148. index++;
  149. }
  150. }
  151. }
  152. return plane_data;
  153. }
  154. static ErrorOr<void> decode_body_chunk(Chunk body_chunk, ILBMLoadingContext& context)
  155. {
  156. dbgln_if(ILBM_DEBUG, "decode_body_chunk {}", body_chunk.data.size());
  157. ByteBuffer pixel_data;
  158. if (context.bm_header.compression == CompressionType::ByteRun) {
  159. auto plane_data = TRY(uncompress_byte_run(body_chunk.data, context));
  160. pixel_data = TRY(planar_to_chunky(plane_data, context));
  161. } else {
  162. pixel_data = TRY(planar_to_chunky(body_chunk.data, context));
  163. }
  164. context.bitmap = TRY(chunky_to_bitmap(context, pixel_data));
  165. return {};
  166. }
  167. static ErrorOr<Chunk> decode_iff_chunk_header(ReadonlyBytes chunks)
  168. {
  169. if (chunks.size() < sizeof(ChunkHeader))
  170. return Error::from_string_literal("Not enough data for IFF chunk header");
  171. auto const& header = *bit_cast<ChunkHeader const*>(chunks.data());
  172. if (chunks.size() < sizeof(ChunkHeader) + header.chunk_size)
  173. return Error::from_string_literal("Not enough data for IFF chunk");
  174. return Chunk { header.chunk_type, { chunks.data() + sizeof(ChunkHeader), header.chunk_size } };
  175. }
  176. static ErrorOr<Chunk> decode_iff_advance_chunk(ReadonlyBytes& chunks)
  177. {
  178. auto chunk = TRY(decode_iff_chunk_header(chunks));
  179. chunks = chunks.slice(sizeof(ChunkHeader) + chunk.data.size());
  180. // add padding if needed
  181. if (chunk.data.size() % 2 != 0) {
  182. if (chunks.is_empty())
  183. return Error::from_string_literal("Missing data for padding byte");
  184. if (*chunks.data() != 0)
  185. return Error::from_string_literal("Padding byte is not 0");
  186. chunks = chunks.slice(1);
  187. }
  188. return chunk;
  189. }
  190. static ErrorOr<void> decode_iff_chunks(ILBMLoadingContext& context)
  191. {
  192. auto& chunks = context.chunks_cursor;
  193. dbgln_if(ILBM_DEBUG, "decode_iff_chunks");
  194. while (!chunks.is_empty()) {
  195. auto chunk = TRY(decode_iff_advance_chunk(chunks));
  196. if (chunk.type == FourCC("CMAP")) {
  197. context.color_table = TRY(decode_cmap_chunk(chunk));
  198. } else if (chunk.type == FourCC("BODY")) {
  199. TRY(decode_body_chunk(chunk, context));
  200. context.state = ILBMLoadingContext::State::BitmapDecoded;
  201. } else if (chunk.type == FourCC("CRNG")) {
  202. dbgln_if(ILBM_DEBUG, "Chunk:CRNG");
  203. }
  204. }
  205. return {};
  206. }
  207. static ErrorOr<void> decode_bmhd_chunk(ILBMLoadingContext& context)
  208. {
  209. context.chunks_cursor = context.data.slice(sizeof(IFFHeader));
  210. auto first_chunk = TRY(decode_iff_advance_chunk(context.chunks_cursor));
  211. if (first_chunk.type != FourCC("BMHD"))
  212. return Error::from_string_literal("IFFImageDecoderPlugin: Invalid chunk type, expected BMHD");
  213. context.bm_header = *bit_cast<BMHDHeader const*>(first_chunk.data.data());
  214. context.pitch = ceil_div((u16)context.bm_header.width, (u16)16) * 2;
  215. context.state = ILBMLoadingContext::State::HeaderDecoded;
  216. dbgln_if(ILBM_DEBUG, "IFFImageDecoderPlugin: BMHD: {}x{} ({},{}), p={}, m={}, c={}",
  217. context.bm_header.width,
  218. context.bm_header.height,
  219. context.bm_header.x,
  220. context.bm_header.y,
  221. context.bm_header.planes,
  222. to_underlying(context.bm_header.mask),
  223. to_underlying(context.bm_header.compression));
  224. return {};
  225. }
  226. ILBMImageDecoderPlugin::ILBMImageDecoderPlugin(ReadonlyBytes data, NonnullOwnPtr<ILBMLoadingContext> context)
  227. : m_context(move(context))
  228. {
  229. m_context->data = data;
  230. }
  231. ILBMImageDecoderPlugin::~ILBMImageDecoderPlugin() = default;
  232. IntSize ILBMImageDecoderPlugin::size()
  233. {
  234. return IntSize { m_context->bm_header.width, m_context->bm_header.height };
  235. }
  236. bool ILBMImageDecoderPlugin::sniff(ReadonlyBytes data)
  237. {
  238. ILBMLoadingContext context;
  239. context.data = data;
  240. return !decode_iff_ilbm_header(context).is_error();
  241. }
  242. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> ILBMImageDecoderPlugin::create(ReadonlyBytes data)
  243. {
  244. auto context = TRY(try_make<ILBMLoadingContext>());
  245. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) ILBMImageDecoderPlugin(data, move(context))));
  246. TRY(decode_iff_ilbm_header(*plugin->m_context));
  247. TRY(decode_bmhd_chunk(*plugin->m_context));
  248. return plugin;
  249. }
  250. ErrorOr<ImageFrameDescriptor> ILBMImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  251. {
  252. if (index > 0)
  253. return Error::from_string_literal("ILBMImageDecoderPlugin: frame index must be 0");
  254. if (m_context->state < ILBMLoadingContext::State::BitmapDecoded)
  255. TRY(decode_iff_chunks(*m_context));
  256. VERIFY(m_context->bitmap);
  257. return ImageFrameDescriptor { m_context->bitmap, 0 };
  258. }
  259. ErrorOr<Optional<ReadonlyBytes>> ILBMImageDecoderPlugin::icc_data()
  260. {
  261. return OptionalNone {};
  262. }
  263. }