ILBMLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. * Copyright (c) 2023, Nicolas Ramz <nicolas.ramz@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteReader.h>
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/FixedArray.h>
  10. #include <AK/IntegralMath.h>
  11. #include <LibGfx/FourCC.h>
  12. #include <LibGfx/ImageFormats/ILBMLoader.h>
  13. namespace Gfx {
  14. struct IFFHeader {
  15. FourCC form;
  16. BigEndian<u32> file_size;
  17. FourCC format;
  18. };
  19. static_assert(AssertSize<IFFHeader, 12>());
  20. struct Chunk {
  21. FourCC type;
  22. ReadonlyBytes data;
  23. };
  24. enum class CompressionType : u8 {
  25. None = 0,
  26. ByteRun = 1,
  27. __Count
  28. };
  29. enum class MaskType : u8 {
  30. None = 0,
  31. HasMask = 1,
  32. HasTransparentColor = 2,
  33. HasLasso = 3,
  34. __Count
  35. };
  36. enum class ViewportMode : u32 {
  37. EHB = 0x80,
  38. HAM = 0x800
  39. };
  40. enum class Format : u8 {
  41. // Amiga interleaved format
  42. ILBM = 0,
  43. // PC-DeluxePaint chunky format
  44. PBM = 1
  45. };
  46. AK_ENUM_BITWISE_OPERATORS(ViewportMode);
  47. struct ChunkHeader {
  48. FourCC chunk_type;
  49. BigEndian<u32> chunk_size;
  50. };
  51. struct BMHDHeader {
  52. BigEndian<u16> width;
  53. BigEndian<u16> height;
  54. BigEndian<i16> x;
  55. BigEndian<i16> y;
  56. u8 planes;
  57. MaskType mask;
  58. CompressionType compression;
  59. u8 pad;
  60. BigEndian<u16> transparent_color;
  61. u8 x_aspect;
  62. u8 y_aspect;
  63. BigEndian<u16> page_width;
  64. BigEndian<u16> page_height;
  65. };
  66. static_assert(sizeof(BMHDHeader) == 20);
  67. struct ILBMLoadingContext {
  68. enum class State {
  69. NotDecoded = 0,
  70. HeaderDecoded,
  71. BitmapDecoded
  72. };
  73. State state { State::NotDecoded };
  74. ReadonlyBytes data;
  75. // points to current chunk
  76. ReadonlyBytes chunks_cursor;
  77. // max number of bytes per plane row
  78. u16 pitch;
  79. ViewportMode viewport_mode;
  80. Vector<Color> color_table;
  81. // number of bits needed to describe current palette
  82. u8 cmap_bits;
  83. RefPtr<Gfx::Bitmap> bitmap;
  84. BMHDHeader bm_header;
  85. Format format;
  86. };
  87. static ErrorOr<void> decode_iff_ilbm_header(ILBMLoadingContext& context)
  88. {
  89. if (context.state >= ILBMLoadingContext::State::HeaderDecoded)
  90. return {};
  91. if (context.data.size() < sizeof(IFFHeader))
  92. return Error::from_string_literal("Missing IFF header");
  93. auto& header = *bit_cast<IFFHeader const*>(context.data.data());
  94. if (header.form != FourCC("FORM") || (header.format != FourCC("ILBM") && header.format != FourCC("PBM ")))
  95. return Error::from_string_literal("Invalid IFF-ILBM header");
  96. context.format = header.format == FourCC("ILBM") ? Format::ILBM : Format::PBM;
  97. return {};
  98. }
  99. static ErrorOr<Vector<Color>> decode_cmap_chunk(Chunk cmap_chunk)
  100. {
  101. size_t const size = cmap_chunk.data.size() / 3;
  102. Vector<Color> color_table;
  103. TRY(color_table.try_ensure_capacity(size));
  104. for (size_t i = 0; i < size; ++i) {
  105. color_table.unchecked_append(Color(cmap_chunk.data[i * 3], cmap_chunk.data[(i * 3) + 1], cmap_chunk.data[(i * 3) + 2]));
  106. }
  107. return color_table;
  108. }
  109. static ErrorOr<RefPtr<Gfx::Bitmap>> chunky_to_bitmap(ILBMLoadingContext& context, ByteBuffer const& chunky)
  110. {
  111. auto const width = context.bm_header.width;
  112. auto const height = context.bm_header.height;
  113. RefPtr<Gfx::Bitmap> bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, { width, height }));
  114. dbgln_if(ILBM_DEBUG, "created Bitmap {}x{}", width, height);
  115. for (int row = 0; row < height; ++row) {
  116. // Keep color: in HAM mode, current color
  117. // may be based on previous color instead of coming from
  118. // the palette.
  119. Color color = Color::Black;
  120. for (int col = 0; col < width; ++col) {
  121. u8 index = chunky[(width * row) + col];
  122. if (index < context.color_table.size()) {
  123. color = context.color_table[index];
  124. } else if (has_flag(context.viewport_mode, ViewportMode::HAM)) {
  125. // Get the control bit which will tell use how current pixel should be calculated
  126. u8 control = (index >> context.cmap_bits) & 0x3;
  127. // Since we only have (cmap_bits - 2) bits to define the component,
  128. // we need to pad it to 8 bits.
  129. u8 component = (index % context.color_table.size()) << (8 - context.cmap_bits);
  130. if (control == 1) {
  131. color.set_blue(component);
  132. } else if (control == 2) {
  133. color.set_red(component);
  134. } else {
  135. color.set_green(component);
  136. }
  137. } else {
  138. return Error::from_string_literal("Color map index out of bounds but HAM bit not set");
  139. }
  140. bitmap->set_pixel(col, row, color);
  141. }
  142. }
  143. dbgln_if(ILBM_DEBUG, "filled Bitmap");
  144. return bitmap;
  145. }
  146. static ErrorOr<ByteBuffer> planar_to_chunky(ReadonlyBytes bitplanes, ILBMLoadingContext& context)
  147. {
  148. dbgln_if(ILBM_DEBUG, "planar_to_chunky");
  149. u16 pitch = context.pitch;
  150. u16 width = context.bm_header.width;
  151. u16 height = context.bm_header.height;
  152. u8 planes = context.bm_header.planes;
  153. auto chunky = TRY(ByteBuffer::create_zeroed(static_cast<size_t>(width) * height));
  154. for (u16 y = 0; y < height; y++) {
  155. size_t scanline = static_cast<size_t>(y) * width;
  156. for (u8 p = 0; p < planes; p++) {
  157. u8 const plane_mask = 1 << p;
  158. size_t offset_base = (pitch * planes * y) + (p * pitch);
  159. if (offset_base + pitch > bitplanes.size() || scanline + ((pitch - 1) * 8) + 7 >= chunky.size())
  160. return Error::from_string_literal("Malformed bitplane data");
  161. for (u16 i = 0; i < pitch; i++) {
  162. u8 bit = bitplanes[offset_base + i];
  163. for (u8 b = 0; b < 8; b++) {
  164. u8 mask = 1 << (7 - b);
  165. // get current plane
  166. if (bit & mask) {
  167. u16 x = (i * 8) + b;
  168. chunky[scanline + x] |= plane_mask;
  169. }
  170. }
  171. }
  172. }
  173. }
  174. return chunky;
  175. }
  176. static ErrorOr<ByteBuffer> uncompress_byte_run(ReadonlyBytes data, ILBMLoadingContext& context)
  177. {
  178. auto length = data.size();
  179. dbgln_if(ILBM_DEBUG, "uncompress_byte_run pitch={} size={}", context.pitch, data.size());
  180. size_t plane_data_size = context.pitch * context.bm_header.height * context.bm_header.planes;
  181. // The maximum run length of this compression method is 127 bytes, so the uncompressed size
  182. // cannot be more than 127 times the size of the chunk we are decompressing.
  183. if (plane_data_size > NumericLimits<u32>::max() || ceil_div(plane_data_size, 127ul) > length)
  184. return Error::from_string_literal("Uncompressed data size too large");
  185. auto plane_data = TRY(ByteBuffer::create_uninitialized(plane_data_size));
  186. u32 index = 0;
  187. u32 read_bytes = 0;
  188. // Uncompressing is done once we've read all buffer or plane buffer has been fully filled
  189. while (read_bytes < length && index < plane_data_size) {
  190. auto const byte = static_cast<i8>(data[read_bytes++]);
  191. if (byte >= -127 && byte <= -1) {
  192. // read next byte
  193. if (read_bytes == data.size())
  194. return Error::from_string_literal("Malformed compressed data");
  195. u8 next_byte = data[read_bytes++];
  196. if (index + -byte >= plane_data.size())
  197. return Error::from_string_literal("Malformed compressed data");
  198. for (u16 i = 0; i < -byte + 1; ++i) {
  199. plane_data[index++] = next_byte;
  200. }
  201. } else if (byte >= 0) {
  202. if (index + byte >= plane_data_size || read_bytes + byte >= length)
  203. return Error::from_string_literal("Malformed compressed data");
  204. for (u16 i = 0; i < byte + 1; ++i) {
  205. plane_data[index] = data[read_bytes];
  206. read_bytes++;
  207. index++;
  208. }
  209. }
  210. }
  211. if (index != plane_data_size)
  212. return Error::from_string_literal("Unexpected end of chunk while decompressing data");
  213. return plane_data;
  214. }
  215. static ErrorOr<void> extend_ehb_palette(ILBMLoadingContext& context)
  216. {
  217. dbgln_if(ILBM_DEBUG, "need to extend palette");
  218. for (size_t i = 0; i < 32; ++i) {
  219. auto const color = context.color_table[i];
  220. TRY(context.color_table.try_append(color.darkened()));
  221. }
  222. return {};
  223. }
  224. static ErrorOr<void> reduce_ham_palette(ILBMLoadingContext& context)
  225. {
  226. u8 bits = context.cmap_bits;
  227. dbgln_if(ILBM_DEBUG, "reduce palette planes={} bits={}", context.bm_header.planes, context.cmap_bits);
  228. if (bits > context.bm_header.planes) {
  229. dbgln_if(ILBM_DEBUG, "need to reduce palette");
  230. bits -= (bits - context.bm_header.planes) + 2;
  231. // bits shouldn't theorically be less than 4 bits in HAM mode.
  232. if (bits < 4)
  233. return Error::from_string_literal("Error while reducing CMAP for HAM: bits too small");
  234. context.color_table.resize((context.color_table.size() >> bits));
  235. context.cmap_bits = bits;
  236. }
  237. return {};
  238. }
  239. static ErrorOr<void> decode_body_chunk(Chunk body_chunk, ILBMLoadingContext& context)
  240. {
  241. dbgln_if(ILBM_DEBUG, "decode_body_chunk {}", body_chunk.data.size());
  242. ByteBuffer pixel_data;
  243. if (context.bm_header.compression == CompressionType::ByteRun) {
  244. auto plane_data = TRY(uncompress_byte_run(body_chunk.data, context));
  245. if (context.format == Format::ILBM)
  246. pixel_data = TRY(planar_to_chunky(plane_data, context));
  247. else
  248. pixel_data = plane_data;
  249. } else {
  250. if (context.format == Format::ILBM)
  251. pixel_data = TRY(planar_to_chunky(body_chunk.data, context));
  252. else
  253. pixel_data = TRY(ByteBuffer::copy(body_chunk.data.data(), body_chunk.data.size()));
  254. }
  255. // Some files already have 64 colors defined in the palette,
  256. // maybe for upward compatibility with 256 colors software/hardware.
  257. // DPaint 4 & previous files only have 32 colors so the
  258. // palette needs to be extended only for these files.
  259. if (has_flag(context.viewport_mode, ViewportMode::EHB) && context.color_table.size() < 64) {
  260. TRY(extend_ehb_palette(context));
  261. } else if (has_flag(context.viewport_mode, ViewportMode::HAM)) {
  262. TRY(reduce_ham_palette(context));
  263. }
  264. context.bitmap = TRY(chunky_to_bitmap(context, pixel_data));
  265. return {};
  266. }
  267. static ErrorOr<Chunk> decode_iff_chunk_header(ReadonlyBytes chunks)
  268. {
  269. if (chunks.size() < sizeof(ChunkHeader))
  270. return Error::from_string_literal("Not enough data for IFF chunk header");
  271. auto const& header = *bit_cast<ChunkHeader const*>(chunks.data());
  272. if (chunks.size() < sizeof(ChunkHeader) + header.chunk_size)
  273. return Error::from_string_literal("Not enough data for IFF chunk");
  274. return Chunk { header.chunk_type, { chunks.data() + sizeof(ChunkHeader), header.chunk_size } };
  275. }
  276. static ErrorOr<Chunk> decode_iff_advance_chunk(ReadonlyBytes& chunks)
  277. {
  278. auto chunk = TRY(decode_iff_chunk_header(chunks));
  279. chunks = chunks.slice(sizeof(ChunkHeader) + chunk.data.size());
  280. // add padding if needed
  281. if (chunk.data.size() % 2 != 0) {
  282. if (chunks.is_empty())
  283. return Error::from_string_literal("Missing data for padding byte");
  284. if (*chunks.data() != 0)
  285. return Error::from_string_literal("Padding byte is not 0");
  286. chunks = chunks.slice(1);
  287. }
  288. return chunk;
  289. }
  290. static ErrorOr<void> decode_iff_chunks(ILBMLoadingContext& context)
  291. {
  292. auto& chunks = context.chunks_cursor;
  293. dbgln_if(ILBM_DEBUG, "decode_iff_chunks");
  294. while (!chunks.is_empty()) {
  295. auto chunk = TRY(decode_iff_advance_chunk(chunks));
  296. if (chunk.type == FourCC("CMAP")) {
  297. // Some files (HAM mainly) have CMAP chunks larger than the planes they advertise: I'm not sure
  298. // why but we should not return an error in this case.
  299. context.color_table = TRY(decode_cmap_chunk(chunk));
  300. context.cmap_bits = AK::ceil_log2(context.color_table.size());
  301. } else if (chunk.type == FourCC("BODY")) {
  302. if (context.color_table.is_empty())
  303. return Error::from_string_literal("Decoding BODY chunk without a color map is not currently supported");
  304. TRY(decode_body_chunk(chunk, context));
  305. context.state = ILBMLoadingContext::State::BitmapDecoded;
  306. } else if (chunk.type == FourCC("CRNG")) {
  307. dbgln_if(ILBM_DEBUG, "Chunk:CRNG");
  308. } else if (chunk.type == FourCC("CAMG")) {
  309. context.viewport_mode = static_cast<ViewportMode>(AK::convert_between_host_and_big_endian(ByteReader::load32(chunk.data.data())));
  310. dbgln_if(ILBM_DEBUG, "Chunk:CAMG, Viewport={}, EHB={}, HAM={}", (u32)context.viewport_mode, has_flag(context.viewport_mode, ViewportMode::EHB), has_flag(context.viewport_mode, ViewportMode::HAM));
  311. }
  312. }
  313. if (context.state != ILBMLoadingContext::State::BitmapDecoded)
  314. return Error::from_string_literal("Missing body chunk");
  315. return {};
  316. }
  317. static ErrorOr<void> decode_bmhd_chunk(ILBMLoadingContext& context)
  318. {
  319. context.chunks_cursor = context.data.slice(sizeof(IFFHeader));
  320. auto first_chunk = TRY(decode_iff_advance_chunk(context.chunks_cursor));
  321. if (first_chunk.type != FourCC("BMHD"))
  322. return Error::from_string_literal("IFFImageDecoderPlugin: Invalid chunk type, expected BMHD");
  323. if (first_chunk.data.size() < sizeof(BMHDHeader))
  324. return Error::from_string_literal("IFFImageDecoderPlugin: Not enough data for header chunk");
  325. context.bm_header = *bit_cast<BMHDHeader const*>(first_chunk.data.data());
  326. if (context.bm_header.planes > 8)
  327. return Error::from_string_literal("IFFImageDecoderPlugin: Deep ILBMs are not currently supported");
  328. if (context.bm_header.mask >= MaskType::__Count)
  329. return Error::from_string_literal("IFFImageDecoderPlugin: Unsupported mask type");
  330. if (context.bm_header.compression >= CompressionType::__Count)
  331. return Error::from_string_literal("IFFImageDecoderPlugin: Unsupported compression type");
  332. context.pitch = ceil_div((u16)context.bm_header.width, (u16)16) * 2;
  333. context.state = ILBMLoadingContext::State::HeaderDecoded;
  334. dbgln_if(ILBM_DEBUG, "IFFImageDecoderPlugin: BMHD: {}x{} ({},{}), p={}, m={}, c={}",
  335. context.bm_header.width,
  336. context.bm_header.height,
  337. context.bm_header.x,
  338. context.bm_header.y,
  339. context.bm_header.planes,
  340. to_underlying(context.bm_header.mask),
  341. to_underlying(context.bm_header.compression));
  342. return {};
  343. }
  344. ILBMImageDecoderPlugin::ILBMImageDecoderPlugin(ReadonlyBytes data, NonnullOwnPtr<ILBMLoadingContext> context)
  345. : m_context(move(context))
  346. {
  347. m_context->data = data;
  348. }
  349. ILBMImageDecoderPlugin::~ILBMImageDecoderPlugin() = default;
  350. IntSize ILBMImageDecoderPlugin::size()
  351. {
  352. return IntSize { m_context->bm_header.width, m_context->bm_header.height };
  353. }
  354. bool ILBMImageDecoderPlugin::sniff(ReadonlyBytes data)
  355. {
  356. ILBMLoadingContext context;
  357. context.data = data;
  358. return !decode_iff_ilbm_header(context).is_error();
  359. }
  360. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> ILBMImageDecoderPlugin::create(ReadonlyBytes data)
  361. {
  362. auto context = TRY(try_make<ILBMLoadingContext>());
  363. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) ILBMImageDecoderPlugin(data, move(context))));
  364. TRY(decode_iff_ilbm_header(*plugin->m_context));
  365. TRY(decode_bmhd_chunk(*plugin->m_context));
  366. return plugin;
  367. }
  368. ErrorOr<ImageFrameDescriptor> ILBMImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  369. {
  370. if (index > 0)
  371. return Error::from_string_literal("ILBMImageDecoderPlugin: frame index must be 0");
  372. if (m_context->state < ILBMLoadingContext::State::BitmapDecoded)
  373. TRY(decode_iff_chunks(*m_context));
  374. VERIFY(m_context->bitmap);
  375. return ImageFrameDescriptor { m_context->bitmap, 0 };
  376. }
  377. }