ILBMLoader.cpp 16 KB

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