ILBMLoader.cpp 16 KB

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