BMPLoader.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2022, Bruno Conde <brunompconde@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BuiltinWrappers.h>
  8. #include <AK/Debug.h>
  9. #include <AK/DeprecatedString.h>
  10. #include <AK/Error.h>
  11. #include <AK/Function.h>
  12. #include <AK/Try.h>
  13. #include <AK/Vector.h>
  14. #include <LibGfx/BMPLoader.h>
  15. namespace Gfx {
  16. const u8 bmp_header_size = 14;
  17. const u32 color_palette_limit = 1024;
  18. // Compression flags
  19. struct Compression {
  20. enum : u32 {
  21. RGB = 0,
  22. RLE8,
  23. RLE4,
  24. BITFIELDS,
  25. RLE24, // doubles as JPEG for V4+, but that is unsupported
  26. PNG,
  27. ALPHABITFIELDS,
  28. CMYK = 11,
  29. CMYKRLE8,
  30. CMYKRLE4,
  31. };
  32. };
  33. struct DIBCore {
  34. // u16 for BITMAPHEADERCORE, but i32 for everything else. If the dib type is
  35. // BITMAPHEADERCORE, this is range checked.
  36. i32 width;
  37. i32 height;
  38. u16 bpp;
  39. };
  40. struct DIBInfo {
  41. u32 compression { Compression::RGB };
  42. u32 image_size { 0 };
  43. i32 horizontal_resolution { 0 };
  44. i32 vertical_resolution { 0 };
  45. u32 number_of_palette_colors { 0 };
  46. u32 number_of_important_palette_colors { number_of_palette_colors };
  47. // Introduced in the BITMAPV2INFOHEADER and would ideally be stored in the
  48. // DIBV2 struct, however with a compression value of BI_BITFIELDS or
  49. // BI_ALPHABITFIELDS, these can be specified with the Info header.
  50. Vector<u32> masks;
  51. Vector<i8> mask_shifts;
  52. Vector<u8> mask_sizes;
  53. };
  54. struct DIBOSV2 {
  55. u16 recording;
  56. u16 halftoning;
  57. u16 size1;
  58. u16 size2;
  59. };
  60. template<typename T>
  61. struct Endpoint {
  62. T x;
  63. T y;
  64. T z;
  65. };
  66. }
  67. namespace AK {
  68. template<typename T>
  69. struct Formatter<Gfx::Endpoint<T>> : Formatter<StringView> {
  70. ErrorOr<void> format(FormatBuilder& builder, Gfx::Endpoint<T> const& value)
  71. {
  72. return Formatter<StringView>::format(builder, DeprecatedString::formatted("({}, {}, {})", value.x, value.y, value.z));
  73. }
  74. };
  75. }
  76. namespace Gfx {
  77. struct DIBV4 {
  78. u32 color_space { 0 };
  79. Endpoint<i32> red_endpoint { 0, 0, 0 };
  80. Endpoint<i32> green_endpoint { 0, 0, 0 };
  81. Endpoint<i32> blue_endpoint { 0, 0, 0 };
  82. Endpoint<u32> gamma_endpoint { 0, 0, 0 };
  83. };
  84. struct DIBV5 {
  85. u32 intent { 0 };
  86. u32 profile_data { 0 };
  87. u32 profile_size { 0 };
  88. };
  89. struct DIB {
  90. DIBCore core;
  91. DIBInfo info;
  92. DIBOSV2 osv2;
  93. DIBV4 v4;
  94. DIBV5 v5;
  95. };
  96. enum class DIBType {
  97. Core = 0,
  98. OSV2Short,
  99. OSV2,
  100. Info,
  101. V2,
  102. V3,
  103. V4,
  104. V5
  105. };
  106. struct BMPLoadingContext {
  107. enum class State {
  108. NotDecoded = 0,
  109. HeaderDecoded,
  110. DIBDecoded,
  111. ColorTableDecoded,
  112. PixelDataDecoded,
  113. Error,
  114. };
  115. State state { State::NotDecoded };
  116. u8 const* file_bytes { nullptr };
  117. size_t file_size { 0 };
  118. u32 data_offset { 0 };
  119. bool is_included_in_ico { false };
  120. DIB dib;
  121. DIBType dib_type;
  122. Vector<u32> color_table;
  123. RefPtr<Gfx::Bitmap> bitmap;
  124. u32 dib_size() const
  125. {
  126. switch (dib_type) {
  127. case DIBType::Core:
  128. return 12;
  129. case DIBType::OSV2Short:
  130. return 16;
  131. case DIBType::OSV2:
  132. return 64;
  133. case DIBType::Info:
  134. return 40;
  135. case DIBType::V2:
  136. return 52;
  137. case DIBType::V3:
  138. return 56;
  139. case DIBType::V4:
  140. return 108;
  141. case DIBType::V5:
  142. return 124;
  143. }
  144. VERIFY_NOT_REACHED();
  145. }
  146. };
  147. class InputStreamer {
  148. public:
  149. InputStreamer(u8 const* data, size_t size)
  150. : m_data_ptr(data)
  151. , m_size_remaining(size)
  152. {
  153. }
  154. u8 read_u8()
  155. {
  156. VERIFY(m_size_remaining >= 1);
  157. m_size_remaining--;
  158. return *(m_data_ptr++);
  159. }
  160. u16 read_u16()
  161. {
  162. return read_u8() | (read_u8() << 8);
  163. }
  164. u32 read_u24()
  165. {
  166. return read_u8() | (read_u8() << 8) | (read_u8() << 16);
  167. }
  168. i32 read_i32()
  169. {
  170. return static_cast<i32>(read_u16() | (read_u16() << 16));
  171. }
  172. u32 read_u32()
  173. {
  174. return read_u16() | (read_u16() << 16);
  175. }
  176. void drop_bytes(u8 num_bytes)
  177. {
  178. VERIFY(m_size_remaining >= num_bytes);
  179. m_size_remaining -= num_bytes;
  180. m_data_ptr += num_bytes;
  181. }
  182. bool at_end() const { return !m_size_remaining; }
  183. bool has_u8() const { return m_size_remaining >= 1; }
  184. bool has_u16() const { return m_size_remaining >= 2; }
  185. bool has_u24() const { return m_size_remaining >= 3; }
  186. bool has_u32() const { return m_size_remaining >= 4; }
  187. size_t remaining() const { return m_size_remaining; }
  188. private:
  189. u8 const* m_data_ptr { nullptr };
  190. size_t m_size_remaining { 0 };
  191. };
  192. // Lookup table for distributing all possible 2-bit numbers evenly into 8-bit numbers
  193. static u8 scaling_factors_2bit[4] = {
  194. 0x00,
  195. 0x55,
  196. 0xaa,
  197. 0xff,
  198. };
  199. // Lookup table for distributing all possible 3-bit numbers evenly into 8-bit numbers
  200. static u8 scaling_factors_3bit[8] = {
  201. 0x00,
  202. 0x24,
  203. 0x48,
  204. 0x6d,
  205. 0x91,
  206. 0xb6,
  207. 0xdb,
  208. 0xff,
  209. };
  210. static u8 scale_masked_8bit_number(u8 number, u8 bits_set)
  211. {
  212. // If there are more than 4 bit set, an easy way to scale the number is to
  213. // just copy the most significant bits into the least significant bits
  214. if (bits_set >= 4)
  215. return number | (number >> bits_set);
  216. if (!bits_set)
  217. return 0;
  218. if (bits_set == 1)
  219. return number ? 0xff : 0;
  220. if (bits_set == 2)
  221. return scaling_factors_2bit[number >> 6];
  222. return scaling_factors_3bit[number >> 5];
  223. }
  224. static u8 get_scaled_color(u32 data, u8 mask_size, i8 mask_shift)
  225. {
  226. // A negative mask_shift indicates we actually need to left shift
  227. // the result in order to get out a valid 8-bit color (for example, the blue
  228. // value in an RGB555 encoding is XXXBBBBB, which needs to be shifted to the
  229. // left by 3, hence it would have a "mask_shift" value of -3).
  230. if (mask_shift < 0)
  231. return scale_masked_8bit_number(data << -mask_shift, mask_size);
  232. return scale_masked_8bit_number(data >> mask_shift, mask_size);
  233. }
  234. // Scales an 8-bit number with "mask_size" bits set (and "8 - mask_size" bits
  235. // ignored). This function scales the number appropriately over the entire
  236. // 256 value color spectrum.
  237. // Note that a much simpler scaling can be done by simple bit shifting. If you
  238. // just ignore the bottom 8-mask_size bits, then you get *close*. However,
  239. // consider, as an example, a 5 bit number (so the bottom 3 bits are ignored).
  240. // The purest white you could get is 0xf8, which is 248 in RGB-land. We need
  241. // to scale the values in order to reach the proper value of 255.
  242. static u32 int_to_scaled_rgb(BMPLoadingContext& context, u32 data)
  243. {
  244. dbgln_if(BMP_DEBUG, "DIB info sizes before access: #masks={}, #mask_sizes={}, #mask_shifts={}",
  245. context.dib.info.masks.size(),
  246. context.dib.info.mask_sizes.size(),
  247. context.dib.info.mask_shifts.size());
  248. u8 r = get_scaled_color(data & context.dib.info.masks[0], context.dib.info.mask_sizes[0], context.dib.info.mask_shifts[0]);
  249. u8 g = get_scaled_color(data & context.dib.info.masks[1], context.dib.info.mask_sizes[1], context.dib.info.mask_shifts[1]);
  250. u8 b = get_scaled_color(data & context.dib.info.masks[2], context.dib.info.mask_sizes[2], context.dib.info.mask_shifts[2]);
  251. u32 color = (r << 16) | (g << 8) | b;
  252. if (context.dib.info.masks.size() == 4) {
  253. // The bitmap has an alpha mask
  254. u8 a = get_scaled_color(data & context.dib.info.masks[3], context.dib.info.mask_sizes[3], context.dib.info.mask_shifts[3]);
  255. color |= (a << 24);
  256. } else {
  257. color |= 0xff000000;
  258. }
  259. return color;
  260. }
  261. static void populate_dib_mask_info_if_needed(BMPLoadingContext& context)
  262. {
  263. if (context.dib.info.masks.is_empty())
  264. return;
  265. // Mask shift is the number of right shifts needed to align the MSb of the
  266. // mask to the MSb of the LSB. Note that this can be a negative number.
  267. // Mask size is the number of set bits in the mask. This is required for
  268. // color scaling (for example, ensuring that a 4-bit color value spans the
  269. // entire 256 value color spectrum.
  270. auto& masks = context.dib.info.masks;
  271. auto& mask_shifts = context.dib.info.mask_shifts;
  272. auto& mask_sizes = context.dib.info.mask_sizes;
  273. if (!mask_shifts.is_empty() && !mask_sizes.is_empty())
  274. return;
  275. VERIFY(mask_shifts.is_empty() && mask_sizes.is_empty());
  276. mask_shifts.ensure_capacity(masks.size());
  277. mask_sizes.ensure_capacity(masks.size());
  278. for (size_t i = 0; i < masks.size(); ++i) {
  279. u32 mask = masks[i];
  280. if (!mask) {
  281. mask_shifts.append(0);
  282. mask_sizes.append(0);
  283. continue;
  284. }
  285. int trailing_zeros = count_trailing_zeroes(mask);
  286. // If mask is exactly `0xFFFFFFFF`, then we might try to count the trailing zeros of 0x00000000 here, so we need the safe version:
  287. int size = count_trailing_zeroes_safe(~(mask >> trailing_zeros));
  288. if (size > 8) {
  289. // Drop lowest bits if mask is longer than 8 bits.
  290. trailing_zeros += size - 8;
  291. size = 8;
  292. }
  293. mask_shifts.append(size + trailing_zeros - 8);
  294. mask_sizes.append(size);
  295. }
  296. }
  297. static bool check_for_invalid_bitmask_combinations(BMPLoadingContext& context)
  298. {
  299. auto& bpp = context.dib.core.bpp;
  300. auto& compression = context.dib.info.compression;
  301. if (compression == Compression::ALPHABITFIELDS && context.dib_type != DIBType::Info)
  302. return false;
  303. switch (context.dib_type) {
  304. case DIBType::Core:
  305. if (bpp == 2 || bpp == 16 || bpp == 32)
  306. return false;
  307. break;
  308. case DIBType::Info:
  309. switch (compression) {
  310. case Compression::BITFIELDS:
  311. case Compression::ALPHABITFIELDS:
  312. if (bpp != 16 && bpp != 32)
  313. return false;
  314. break;
  315. case Compression::RGB:
  316. break;
  317. case Compression::RLE8:
  318. if (bpp > 8)
  319. return false;
  320. break;
  321. case Compression::RLE4:
  322. // TODO: This is a guess
  323. if (bpp > 4)
  324. return false;
  325. break;
  326. default:
  327. // Other compressions are not officially supported.
  328. // Technically, we could even drop ALPHABITFIELDS.
  329. return false;
  330. }
  331. break;
  332. case DIBType::OSV2Short:
  333. case DIBType::OSV2:
  334. case DIBType::V2:
  335. case DIBType::V3:
  336. case DIBType::V4:
  337. case DIBType::V5:
  338. if (compression == Compression::BITFIELDS && bpp != 16 && bpp != 32)
  339. return false;
  340. break;
  341. }
  342. return true;
  343. }
  344. static bool set_dib_bitmasks(BMPLoadingContext& context, InputStreamer& streamer)
  345. {
  346. if (!check_for_invalid_bitmask_combinations(context))
  347. return false;
  348. auto& bpp = context.dib.core.bpp;
  349. if (bpp <= 8 || bpp == 24)
  350. return true;
  351. auto& compression = context.dib.info.compression;
  352. auto& type = context.dib_type;
  353. if (type > DIBType::OSV2 && bpp == 16 && compression == Compression::RGB) {
  354. context.dib.info.masks.extend({ 0x7c00, 0x03e0, 0x001f });
  355. context.dib.info.mask_shifts.extend({ 7, 2, -3 });
  356. context.dib.info.mask_sizes.extend({ 5, 5, 5 });
  357. } else if (type == DIBType::Info && (compression == Compression::BITFIELDS || compression == Compression::ALPHABITFIELDS)) {
  358. // Consume the extra BITFIELDS bytes
  359. auto number_of_mask_fields = compression == Compression::ALPHABITFIELDS ? 4 : 3;
  360. for (auto i = 0; i < number_of_mask_fields; i++) {
  361. if (!streamer.has_u32())
  362. return false;
  363. context.dib.info.masks.append(streamer.read_u32());
  364. }
  365. }
  366. populate_dib_mask_info_if_needed(context);
  367. return true;
  368. }
  369. static ErrorOr<void> decode_bmp_header(BMPLoadingContext& context)
  370. {
  371. if (context.state == BMPLoadingContext::State::Error)
  372. return Error::from_string_literal("Error before starting decode_bmp_header");
  373. if (context.state >= BMPLoadingContext::State::HeaderDecoded)
  374. return {};
  375. if (!context.file_bytes || context.file_size < bmp_header_size) {
  376. dbgln_if(BMP_DEBUG, "Missing BMP header");
  377. context.state = BMPLoadingContext::State::Error;
  378. return Error::from_string_literal("Missing BMP header");
  379. }
  380. InputStreamer streamer(context.file_bytes, bmp_header_size);
  381. u16 header = streamer.read_u16();
  382. if (header != 0x4d42) {
  383. dbgln_if(BMP_DEBUG, "BMP has invalid magic header number: {:#04x}", header);
  384. context.state = BMPLoadingContext::State::Error;
  385. return Error::from_string_literal("BMP has invalid magic header number");
  386. }
  387. // The reported size of the file in the header is actually not important
  388. // for decoding the file. Some specifications say that this value should
  389. // be the size of the header instead, so we just rely on the known file
  390. // size, instead of a possibly-correct-but-also-possibly-incorrect reported
  391. // value of the file size.
  392. streamer.drop_bytes(4);
  393. // Ignore reserved bytes
  394. streamer.drop_bytes(4);
  395. context.data_offset = streamer.read_u32();
  396. if constexpr (BMP_DEBUG) {
  397. dbgln("BMP file size: {}", context.file_size);
  398. dbgln("BMP data offset: {}", context.data_offset);
  399. }
  400. if (context.data_offset >= context.file_size) {
  401. dbgln_if(BMP_DEBUG, "BMP data offset is beyond file end?!");
  402. return Error::from_string_literal("BMP data offset is beyond file end");
  403. }
  404. context.state = BMPLoadingContext::State::HeaderDecoded;
  405. return {};
  406. }
  407. static bool decode_bmp_core_dib(BMPLoadingContext& context, InputStreamer& streamer)
  408. {
  409. auto& core = context.dib.core;
  410. // The width and height are u16 fields in the actual BITMAPCOREHEADER format.
  411. if (context.dib_type == DIBType::Core) {
  412. core.width = streamer.read_u16();
  413. core.height = streamer.read_u16();
  414. } else {
  415. core.width = streamer.read_i32();
  416. core.height = streamer.read_i32();
  417. }
  418. if (core.width < 0) {
  419. dbgln("BMP has a negative width: {}", core.width);
  420. return false;
  421. }
  422. if (static_cast<size_t>(core.width) > maximum_width_for_decoded_images || static_cast<size_t>(abs(core.height)) > maximum_height_for_decoded_images) {
  423. dbgln("This BMP is too large for comfort: {}x{}", core.width, abs(core.height));
  424. return false;
  425. }
  426. auto color_planes = streamer.read_u16();
  427. if (color_planes != 1) {
  428. dbgln("BMP has an invalid number of color planes: {}", color_planes);
  429. return false;
  430. }
  431. core.bpp = streamer.read_u16();
  432. switch (core.bpp) {
  433. case 1:
  434. case 2:
  435. case 4:
  436. case 8:
  437. case 16:
  438. case 24:
  439. case 32:
  440. break;
  441. default:
  442. dbgln("BMP has an invalid bpp: {}", core.bpp);
  443. context.state = BMPLoadingContext::State::Error;
  444. return false;
  445. }
  446. if constexpr (BMP_DEBUG) {
  447. dbgln("BMP width: {}", core.width);
  448. dbgln("BMP height: {}", core.height);
  449. dbgln("BMP bits_per_pixel: {}", core.bpp);
  450. }
  451. return true;
  452. }
  453. ALWAYS_INLINE static bool is_supported_compression_format(BMPLoadingContext& context, u32 compression)
  454. {
  455. return compression == Compression::RGB || compression == Compression::BITFIELDS
  456. || compression == Compression::ALPHABITFIELDS || compression == Compression::RLE8
  457. || compression == Compression::RLE4 || (compression == Compression::RLE24 && context.dib_type <= DIBType::OSV2);
  458. }
  459. static bool decode_bmp_osv2_dib(BMPLoadingContext& context, InputStreamer& streamer, bool short_variant = false)
  460. {
  461. auto& core = context.dib.core;
  462. core.width = streamer.read_u32();
  463. core.height = streamer.read_u32();
  464. if (core.width < 0) {
  465. dbgln("BMP has a negative width: {}", core.width);
  466. return false;
  467. }
  468. auto color_planes = streamer.read_u16();
  469. if (color_planes != 1) {
  470. dbgln("BMP has an invalid number of color planes: {}", color_planes);
  471. return false;
  472. }
  473. core.bpp = streamer.read_u16();
  474. switch (core.bpp) {
  475. case 1:
  476. case 2:
  477. case 4:
  478. case 8:
  479. case 24:
  480. break;
  481. default:
  482. // OS/2 didn't expect 16- or 32-bpp to be popular.
  483. dbgln("BMP has an invalid bpp: {}", core.bpp);
  484. context.state = BMPLoadingContext::State::Error;
  485. return false;
  486. }
  487. if constexpr (BMP_DEBUG) {
  488. dbgln("BMP width: {}", core.width);
  489. dbgln("BMP height: {}", core.height);
  490. dbgln("BMP bits_per_pixel: {}", core.bpp);
  491. }
  492. if (short_variant)
  493. return true;
  494. auto& info = context.dib.info;
  495. auto& osv2 = context.dib.osv2;
  496. info.compression = streamer.read_u32();
  497. info.image_size = streamer.read_u32();
  498. info.horizontal_resolution = streamer.read_u32();
  499. info.vertical_resolution = streamer.read_u32();
  500. info.number_of_palette_colors = streamer.read_u32();
  501. info.number_of_important_palette_colors = streamer.read_u32();
  502. if (!is_supported_compression_format(context, info.compression)) {
  503. dbgln("BMP has unsupported compression value: {}", info.compression);
  504. return false;
  505. }
  506. if (info.number_of_palette_colors > color_palette_limit || info.number_of_important_palette_colors > color_palette_limit) {
  507. dbgln("BMP header indicates too many palette colors: {}", info.number_of_palette_colors);
  508. return false;
  509. }
  510. // Units (2) + reserved (2)
  511. streamer.drop_bytes(4);
  512. osv2.recording = streamer.read_u16();
  513. osv2.halftoning = streamer.read_u16();
  514. osv2.size1 = streamer.read_u32();
  515. osv2.size2 = streamer.read_u32();
  516. // ColorEncoding (4) + Identifier (4)
  517. streamer.drop_bytes(8);
  518. if constexpr (BMP_DEBUG) {
  519. dbgln("BMP compression: {}", info.compression);
  520. dbgln("BMP image size: {}", info.image_size);
  521. dbgln("BMP horizontal res: {}", info.horizontal_resolution);
  522. dbgln("BMP vertical res: {}", info.vertical_resolution);
  523. dbgln("BMP colors: {}", info.number_of_palette_colors);
  524. dbgln("BMP important colors: {}", info.number_of_important_palette_colors);
  525. }
  526. return true;
  527. }
  528. static bool decode_bmp_info_dib(BMPLoadingContext& context, InputStreamer& streamer)
  529. {
  530. if (!decode_bmp_core_dib(context, streamer))
  531. return false;
  532. auto& info = context.dib.info;
  533. auto compression = streamer.read_u32();
  534. info.compression = compression;
  535. if (!is_supported_compression_format(context, compression)) {
  536. dbgln("BMP has unsupported compression value: {}", compression);
  537. return false;
  538. }
  539. info.image_size = streamer.read_u32();
  540. info.horizontal_resolution = streamer.read_i32();
  541. info.vertical_resolution = streamer.read_i32();
  542. info.number_of_palette_colors = streamer.read_u32();
  543. info.number_of_important_palette_colors = streamer.read_u32();
  544. if (info.number_of_palette_colors > color_palette_limit || info.number_of_important_palette_colors > color_palette_limit) {
  545. dbgln("BMP header indicates too many palette colors: {}", info.number_of_palette_colors);
  546. return false;
  547. }
  548. if (info.number_of_important_palette_colors == 0)
  549. info.number_of_important_palette_colors = info.number_of_palette_colors;
  550. if constexpr (BMP_DEBUG) {
  551. dbgln("BMP compression: {}", info.compression);
  552. dbgln("BMP image size: {}", info.image_size);
  553. dbgln("BMP horizontal res: {}", info.horizontal_resolution);
  554. dbgln("BMP vertical res: {}", info.vertical_resolution);
  555. dbgln("BMP colors: {}", info.number_of_palette_colors);
  556. dbgln("BMP important colors: {}", info.number_of_important_palette_colors);
  557. }
  558. return true;
  559. }
  560. static bool decode_bmp_v2_dib(BMPLoadingContext& context, InputStreamer& streamer)
  561. {
  562. if (!decode_bmp_info_dib(context, streamer))
  563. return false;
  564. context.dib.info.masks.append(streamer.read_u32());
  565. context.dib.info.masks.append(streamer.read_u32());
  566. context.dib.info.masks.append(streamer.read_u32());
  567. if constexpr (BMP_DEBUG) {
  568. dbgln("BMP red mask: {:#08x}", context.dib.info.masks[0]);
  569. dbgln("BMP green mask: {:#08x}", context.dib.info.masks[1]);
  570. dbgln("BMP blue mask: {:#08x}", context.dib.info.masks[2]);
  571. }
  572. return true;
  573. }
  574. static bool decode_bmp_v3_dib(BMPLoadingContext& context, InputStreamer& streamer)
  575. {
  576. if (!decode_bmp_v2_dib(context, streamer))
  577. return false;
  578. // There is zero documentation about when alpha masks actually get applied.
  579. // Well, there's some, but it's not even close to comprehensive. So, this is
  580. // in no way based off of any spec, it's simply based off of the BMP test
  581. // suite results.
  582. if (context.dib.info.compression == Compression::ALPHABITFIELDS) {
  583. context.dib.info.masks.append(streamer.read_u32());
  584. dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", context.dib.info.masks[3]);
  585. } else if (context.dib_size() >= 56 && context.dib.core.bpp >= 16) {
  586. auto mask = streamer.read_u32();
  587. if ((context.dib.core.bpp == 32 && mask != 0) || context.dib.core.bpp == 16) {
  588. context.dib.info.masks.append(mask);
  589. dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", mask);
  590. }
  591. } else {
  592. streamer.drop_bytes(4);
  593. }
  594. return true;
  595. }
  596. static bool decode_bmp_v4_dib(BMPLoadingContext& context, InputStreamer& streamer)
  597. {
  598. if (!decode_bmp_v3_dib(context, streamer))
  599. return false;
  600. auto& v4 = context.dib.v4;
  601. v4.color_space = streamer.read_u32();
  602. v4.red_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  603. v4.green_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  604. v4.blue_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  605. v4.gamma_endpoint = { streamer.read_u32(), streamer.read_u32(), streamer.read_u32() };
  606. if constexpr (BMP_DEBUG) {
  607. dbgln("BMP color space: {}", v4.color_space);
  608. dbgln("BMP red endpoint: {}", v4.red_endpoint);
  609. dbgln("BMP green endpoint: {}", v4.green_endpoint);
  610. dbgln("BMP blue endpoint: {}", v4.blue_endpoint);
  611. dbgln("BMP gamma endpoint: {}", v4.gamma_endpoint);
  612. }
  613. return true;
  614. }
  615. static bool decode_bmp_v5_dib(BMPLoadingContext& context, InputStreamer& streamer)
  616. {
  617. if (!decode_bmp_v4_dib(context, streamer))
  618. return false;
  619. auto& v5 = context.dib.v5;
  620. v5.intent = streamer.read_u32();
  621. v5.profile_data = streamer.read_u32();
  622. v5.profile_size = streamer.read_u32();
  623. if constexpr (BMP_DEBUG) {
  624. dbgln("BMP intent: {}", v5.intent);
  625. dbgln("BMP profile data: {}", v5.profile_data);
  626. dbgln("BMP profile size: {}", v5.profile_size);
  627. }
  628. return true;
  629. }
  630. static ErrorOr<void> decode_bmp_dib(BMPLoadingContext& context)
  631. {
  632. if (context.state == BMPLoadingContext::State::Error)
  633. return Error::from_string_literal("Error before starting decode_bmp_dib");
  634. if (context.state >= BMPLoadingContext::State::DIBDecoded)
  635. return {};
  636. if (!context.is_included_in_ico && context.state < BMPLoadingContext::State::HeaderDecoded)
  637. TRY(decode_bmp_header(context));
  638. u8 header_size = context.is_included_in_ico ? 0 : bmp_header_size;
  639. if (!context.is_included_in_ico && context.file_size < (u8)(header_size + 4))
  640. return Error::from_string_literal("File size too short");
  641. if (context.is_included_in_ico && context.file_size < 4)
  642. return Error::from_string_literal("File size too short");
  643. InputStreamer streamer(context.file_bytes + (context.is_included_in_ico ? 0 : header_size), 4);
  644. u32 dib_size = streamer.read_u32();
  645. if (context.file_size < header_size + dib_size)
  646. return Error::from_string_literal("File size too short");
  647. if (!context.is_included_in_ico && (context.data_offset < header_size + dib_size)) {
  648. dbgln("Shenanigans! BMP pixel data and header usually don't overlap.");
  649. return Error::from_string_literal("BMP pixel data and header usually don't overlap");
  650. }
  651. // NOTE: If this is a headless BMP (embedded on ICO files), then we can only infer the data_offset after we know the data table size.
  652. // We are also assuming that no Extra bit masks are present
  653. u32 dib_offset = context.is_included_in_ico ? dib_size : context.data_offset - header_size - 4;
  654. streamer = InputStreamer(context.file_bytes + header_size + 4, dib_offset);
  655. dbgln_if(BMP_DEBUG, "BMP dib size: {}", dib_size);
  656. bool error = false;
  657. if (dib_size == 12) {
  658. context.dib_type = DIBType::Core;
  659. if (!decode_bmp_core_dib(context, streamer))
  660. error = true;
  661. } else if (dib_size == 64) {
  662. context.dib_type = DIBType::OSV2;
  663. if (!decode_bmp_osv2_dib(context, streamer))
  664. error = true;
  665. } else if (dib_size == 16) {
  666. context.dib_type = DIBType::OSV2Short;
  667. if (!decode_bmp_osv2_dib(context, streamer, true))
  668. error = true;
  669. } else if (dib_size == 40) {
  670. context.dib_type = DIBType::Info;
  671. if (!decode_bmp_info_dib(context, streamer))
  672. error = true;
  673. } else if (dib_size == 52) {
  674. context.dib_type = DIBType::V2;
  675. if (!decode_bmp_v2_dib(context, streamer))
  676. error = true;
  677. } else if (dib_size == 56) {
  678. context.dib_type = DIBType::V3;
  679. if (!decode_bmp_v3_dib(context, streamer))
  680. error = true;
  681. } else if (dib_size == 108) {
  682. context.dib_type = DIBType::V4;
  683. if (!decode_bmp_v4_dib(context, streamer))
  684. error = true;
  685. } else if (dib_size == 124) {
  686. context.dib_type = DIBType::V5;
  687. if (!decode_bmp_v5_dib(context, streamer))
  688. error = true;
  689. } else {
  690. dbgln("Unsupported BMP DIB size: {}", dib_size);
  691. error = true;
  692. }
  693. switch (context.dib.info.compression) {
  694. case Compression::RGB:
  695. case Compression::RLE8:
  696. case Compression::RLE4:
  697. case Compression::BITFIELDS:
  698. case Compression::RLE24:
  699. case Compression::PNG:
  700. case Compression::ALPHABITFIELDS:
  701. case Compression::CMYK:
  702. case Compression::CMYKRLE8:
  703. case Compression::CMYKRLE4:
  704. break;
  705. default:
  706. error = true;
  707. }
  708. if (!error && !set_dib_bitmasks(context, streamer))
  709. error = true;
  710. if (error) {
  711. dbgln("BMP has an invalid DIB");
  712. context.state = BMPLoadingContext::State::Error;
  713. return Error::from_string_literal("BMP has an invalid DIB");
  714. }
  715. // NOTE: If this is a headless BMP (included on ICOns), the data_offset is set based on the number_of_palette_colors found on the DIB header
  716. if (context.is_included_in_ico) {
  717. if (context.dib.core.bpp > 8)
  718. context.data_offset = dib_size;
  719. else {
  720. auto bytes_per_color = context.dib_type == DIBType::Core ? 3 : 4;
  721. u32 max_colors = 1 << context.dib.core.bpp;
  722. auto size_of_color_table = (context.dib.info.number_of_palette_colors > 0 ? context.dib.info.number_of_palette_colors : max_colors) * bytes_per_color;
  723. context.data_offset = dib_size + size_of_color_table;
  724. }
  725. }
  726. context.state = BMPLoadingContext::State::DIBDecoded;
  727. return {};
  728. }
  729. static ErrorOr<void> decode_bmp_color_table(BMPLoadingContext& context)
  730. {
  731. if (context.state == BMPLoadingContext::State::Error)
  732. return Error::from_string_literal("Error before starting decode_bmp_color_table");
  733. if (context.state < BMPLoadingContext::State::DIBDecoded)
  734. TRY(decode_bmp_dib(context));
  735. if (context.state >= BMPLoadingContext::State::ColorTableDecoded)
  736. return {};
  737. if (context.dib.core.bpp > 8) {
  738. context.state = BMPLoadingContext::State::ColorTableDecoded;
  739. return {};
  740. }
  741. auto bytes_per_color = context.dib_type == DIBType::Core ? 3 : 4;
  742. u32 max_colors = 1 << context.dib.core.bpp;
  743. u8 header_size = !context.is_included_in_ico ? bmp_header_size : 0;
  744. VERIFY(context.data_offset >= header_size + context.dib_size());
  745. u32 size_of_color_table;
  746. if (!context.is_included_in_ico) {
  747. size_of_color_table = context.data_offset - header_size - context.dib_size();
  748. } else {
  749. size_of_color_table = (context.dib.info.number_of_palette_colors > 0 ? context.dib.info.number_of_palette_colors : max_colors) * bytes_per_color;
  750. }
  751. if (context.dib_type <= DIBType::OSV2) {
  752. // Partial color tables are not supported, so the space of the color
  753. // table must be at least enough for the maximum amount of colors
  754. if (size_of_color_table < 3 * max_colors) {
  755. // This is against the spec, but most viewers process it anyways
  756. dbgln("BMP with CORE header does not have enough colors. Has: {}, expected: {}", size_of_color_table, (3 * max_colors));
  757. }
  758. }
  759. InputStreamer streamer(context.file_bytes + header_size + context.dib_size(), size_of_color_table);
  760. for (u32 i = 0; !streamer.at_end() && i < max_colors; ++i) {
  761. if (bytes_per_color == 4) {
  762. if (!streamer.has_u32())
  763. return Error::from_string_literal("Cannot read 32 bits");
  764. context.color_table.append(streamer.read_u32());
  765. } else {
  766. if (!streamer.has_u24())
  767. return Error::from_string_literal("Cannot read 24 bits");
  768. context.color_table.append(streamer.read_u24());
  769. }
  770. }
  771. context.state = BMPLoadingContext::State::ColorTableDecoded;
  772. return {};
  773. }
  774. struct RLEState {
  775. enum : u8 {
  776. PixelCount = 0,
  777. PixelValue,
  778. Meta, // Represents just consuming a null byte, which indicates something special
  779. };
  780. };
  781. static ErrorOr<void> uncompress_bmp_rle_data(BMPLoadingContext& context, ByteBuffer& buffer)
  782. {
  783. // RLE-compressed images cannot be stored top-down
  784. if (context.dib.core.height < 0) {
  785. dbgln_if(BMP_DEBUG, "BMP is top-down and RLE compressed");
  786. context.state = BMPLoadingContext::State::Error;
  787. return Error::from_string_literal("BMP is top-down and RLE compressed");
  788. }
  789. InputStreamer streamer(context.file_bytes + context.data_offset, context.file_size - context.data_offset);
  790. auto compression = context.dib.info.compression;
  791. u32 total_rows = static_cast<u32>(context.dib.core.height);
  792. u32 total_columns = round_up_to_power_of_two(static_cast<u32>(context.dib.core.width), 4);
  793. u32 column = 0;
  794. u32 row = 0;
  795. auto currently_consuming = RLEState::PixelCount;
  796. i16 pixel_count = 0;
  797. // ByteBuffer asserts that allocating the memory never fails.
  798. // FIXME: ByteBuffer should return either RefPtr<> or Optional<>.
  799. // Decoding the RLE data on-the-fly might actually be faster, and avoids this topic entirely.
  800. u32 buffer_size;
  801. if (compression == Compression::RLE24) {
  802. buffer_size = total_rows * round_up_to_power_of_two(total_columns, 4) * 4;
  803. } else {
  804. buffer_size = total_rows * round_up_to_power_of_two(total_columns, 4);
  805. }
  806. if (buffer_size > 300 * MiB) {
  807. dbgln("Suspiciously large amount of RLE data");
  808. return Error::from_string_literal("Suspiciously large amount of RLE data");
  809. }
  810. auto buffer_result = ByteBuffer::create_zeroed(buffer_size);
  811. if (buffer_result.is_error()) {
  812. dbgln("Not enough memory for buffer allocation");
  813. return buffer_result.release_error();
  814. }
  815. buffer = buffer_result.release_value();
  816. // Avoid as many if statements as possible by pulling out
  817. // compression-dependent actions into separate lambdas
  818. Function<u32()> get_buffer_index;
  819. Function<ErrorOr<void>(u32, bool)> set_byte;
  820. Function<ErrorOr<u32>()> read_byte;
  821. if (compression == Compression::RLE8) {
  822. get_buffer_index = [&]() -> u32 { return row * total_columns + column; };
  823. } else if (compression == Compression::RLE4) {
  824. get_buffer_index = [&]() -> u32 { return (row * total_columns + column) / 2; };
  825. } else {
  826. get_buffer_index = [&]() -> u32 { return (row * total_columns + column) * 3; };
  827. }
  828. if (compression == Compression::RLE8) {
  829. set_byte = [&](u32 color, bool) -> ErrorOr<void> {
  830. if (column >= total_columns) {
  831. column = 0;
  832. row++;
  833. }
  834. auto index = get_buffer_index();
  835. if (index >= buffer.size()) {
  836. dbgln("BMP has badly-formatted RLE data");
  837. return Error::from_string_literal("BMP has badly-formatted RLE data");
  838. }
  839. buffer[index] = color;
  840. column++;
  841. return {};
  842. };
  843. } else if (compression == Compression::RLE24) {
  844. set_byte = [&](u32 color, bool) -> ErrorOr<void> {
  845. if (column >= total_columns) {
  846. column = 0;
  847. row++;
  848. }
  849. auto index = get_buffer_index();
  850. if (index + 3 >= buffer.size()) {
  851. dbgln("BMP has badly-formatted RLE data");
  852. return Error::from_string_literal("BMP has badly-formatted RLE data");
  853. }
  854. ((u32&)buffer[index]) = color;
  855. column++;
  856. return {};
  857. };
  858. } else {
  859. set_byte = [&](u32 byte, bool rle4_set_second_nibble) -> ErrorOr<void> {
  860. if (column >= total_columns) {
  861. column = 0;
  862. row++;
  863. }
  864. u32 index = get_buffer_index();
  865. if (index >= buffer.size() || (rle4_set_second_nibble && index + 1 >= buffer.size())) {
  866. dbgln("BMP has badly-formatted RLE data");
  867. return Error::from_string_literal("BMP has badly-formatted RLE data");
  868. }
  869. if (column % 2) {
  870. buffer[index] |= byte >> 4;
  871. if (rle4_set_second_nibble) {
  872. buffer[index + 1] |= byte << 4;
  873. column++;
  874. }
  875. } else {
  876. if (rle4_set_second_nibble) {
  877. buffer[index] = byte;
  878. column++;
  879. } else {
  880. buffer[index] |= byte & 0xf0;
  881. }
  882. }
  883. column++;
  884. return {};
  885. };
  886. }
  887. if (compression == Compression::RLE24) {
  888. read_byte = [&]() -> ErrorOr<u32> {
  889. if (!streamer.has_u24()) {
  890. dbgln("BMP has badly-formatted RLE data");
  891. return Error::from_string_literal("BMP has badly-formatted RLE data");
  892. }
  893. return streamer.read_u24();
  894. };
  895. } else {
  896. read_byte = [&]() -> ErrorOr<u32> {
  897. if (!streamer.has_u8()) {
  898. dbgln("BMP has badly-formatted RLE data");
  899. return Error::from_string_literal("BMP has badly-formatted RLE data");
  900. }
  901. return streamer.read_u8();
  902. };
  903. }
  904. while (true) {
  905. u32 byte;
  906. switch (currently_consuming) {
  907. case RLEState::PixelCount:
  908. if (!streamer.has_u8())
  909. return Error::from_string_literal("Cannot read 8 bits");
  910. byte = streamer.read_u8();
  911. if (!byte) {
  912. currently_consuming = RLEState::Meta;
  913. } else {
  914. pixel_count = byte;
  915. currently_consuming = RLEState::PixelValue;
  916. }
  917. break;
  918. case RLEState::PixelValue:
  919. byte = TRY(read_byte());
  920. for (u16 i = 0; i < pixel_count; ++i) {
  921. if (compression != Compression::RLE4) {
  922. TRY(set_byte(byte, true));
  923. } else {
  924. TRY(set_byte(byte, i != pixel_count - 1));
  925. i++;
  926. }
  927. }
  928. currently_consuming = RLEState::PixelCount;
  929. break;
  930. case RLEState::Meta:
  931. if (!streamer.has_u8())
  932. return Error::from_string_literal("Cannot read 8 bits");
  933. byte = streamer.read_u8();
  934. if (!byte) {
  935. column = 0;
  936. row++;
  937. currently_consuming = RLEState::PixelCount;
  938. continue;
  939. }
  940. if (byte == 1)
  941. return {};
  942. if (byte == 2) {
  943. if (!streamer.has_u8())
  944. return Error::from_string_literal("Cannot read 8 bits");
  945. u8 offset_x = streamer.read_u8();
  946. if (!streamer.has_u8())
  947. return Error::from_string_literal("Cannot read 8 bits");
  948. u8 offset_y = streamer.read_u8();
  949. column += offset_x;
  950. if (column >= total_columns) {
  951. column -= total_columns;
  952. row++;
  953. }
  954. row += offset_y;
  955. currently_consuming = RLEState::PixelCount;
  956. continue;
  957. }
  958. // Consume literal bytes
  959. pixel_count = byte;
  960. i16 i = byte;
  961. while (i >= 1) {
  962. byte = TRY(read_byte());
  963. TRY(set_byte(byte, i != 1));
  964. i--;
  965. if (compression == Compression::RLE4)
  966. i--;
  967. }
  968. // Optionally consume a padding byte
  969. if (compression != Compression::RLE4) {
  970. if (pixel_count % 2) {
  971. if (!streamer.has_u8())
  972. return Error::from_string_literal("Cannot read 8 bits");
  973. byte = streamer.read_u8();
  974. }
  975. } else {
  976. if (((pixel_count + 1) / 2) % 2) {
  977. if (!streamer.has_u8())
  978. return Error::from_string_literal("Cannot read 8 bits");
  979. byte = streamer.read_u8();
  980. }
  981. }
  982. currently_consuming = RLEState::PixelCount;
  983. break;
  984. }
  985. }
  986. VERIFY_NOT_REACHED();
  987. }
  988. static ErrorOr<void> decode_bmp_pixel_data(BMPLoadingContext& context)
  989. {
  990. if (context.state == BMPLoadingContext::State::Error)
  991. return Error::from_string_literal("Error before starting decode_bmp_pixel_data");
  992. if (context.state <= BMPLoadingContext::State::ColorTableDecoded)
  993. TRY(decode_bmp_color_table(context));
  994. const u16 bits_per_pixel = context.dib.core.bpp;
  995. BitmapFormat format = [&]() -> BitmapFormat {
  996. // NOTE: If this is an BMP included in an ICO, the bitmap format will be converted to BGRA8888.
  997. // This is because images with less than 32 bits of color depth follow a particular format:
  998. // the image is encoded with a color mask (the "XOR mask") together with an opacity mask (the "AND mask") of 1 bit per pixel.
  999. // The height of the encoded image must be exactly twice the real height, before both masks are combined.
  1000. // Bitmaps have no knowledge of this format as they do not store extra rows for the AND mask.
  1001. if (context.is_included_in_ico)
  1002. return BitmapFormat::BGRA8888;
  1003. switch (bits_per_pixel) {
  1004. case 1:
  1005. return BitmapFormat::Indexed1;
  1006. case 2:
  1007. return BitmapFormat::Indexed2;
  1008. case 4:
  1009. return BitmapFormat::Indexed4;
  1010. case 8:
  1011. return BitmapFormat::Indexed8;
  1012. case 16:
  1013. if (context.dib.info.masks.size() == 4)
  1014. return BitmapFormat::BGRA8888;
  1015. return BitmapFormat::BGRx8888;
  1016. case 24:
  1017. return BitmapFormat::BGRx8888;
  1018. case 32:
  1019. return BitmapFormat::BGRA8888;
  1020. default:
  1021. return BitmapFormat::Invalid;
  1022. }
  1023. }();
  1024. if (format == BitmapFormat::Invalid) {
  1025. dbgln("BMP has invalid bpp of {}", bits_per_pixel);
  1026. context.state = BMPLoadingContext::State::Error;
  1027. return Error::from_string_literal("BMP has invalid bpp");
  1028. }
  1029. const u32 width = abs(context.dib.core.width);
  1030. const u32 height = !context.is_included_in_ico ? context.dib.core.height : (context.dib.core.height / 2);
  1031. context.bitmap = TRY(Bitmap::try_create(format, { static_cast<int>(width), static_cast<int>(height) }));
  1032. ByteBuffer rle_buffer;
  1033. ReadonlyBytes bytes { context.file_bytes + context.data_offset, context.file_size - context.data_offset };
  1034. if (context.dib.info.compression == Compression::RLE4 || context.dib.info.compression == Compression::RLE8
  1035. || context.dib.info.compression == Compression::RLE24) {
  1036. TRY(uncompress_bmp_rle_data(context, rle_buffer));
  1037. bytes = rle_buffer.bytes();
  1038. }
  1039. InputStreamer streamer(bytes.data(), bytes.size());
  1040. auto process_row_padding = [&](const u8 consumed) -> ErrorOr<void> {
  1041. // Calculate padding
  1042. u8 remaining = consumed % 4;
  1043. u8 bytes_to_drop = remaining == 0 ? 0 : 4 - remaining;
  1044. if (streamer.remaining() < bytes_to_drop)
  1045. return Error::from_string_literal("Not enough bytes available to drop");
  1046. streamer.drop_bytes(bytes_to_drop);
  1047. return {};
  1048. };
  1049. auto process_row = [&](u32 row) -> ErrorOr<void> {
  1050. u32 space_remaining_before_consuming_row = streamer.remaining();
  1051. for (u32 column = 0; column < width;) {
  1052. switch (bits_per_pixel) {
  1053. case 1: {
  1054. if (!streamer.has_u8())
  1055. return Error::from_string_literal("Cannot read 8 bits");
  1056. u8 byte = streamer.read_u8();
  1057. u8 mask = 8;
  1058. while (column < width && mask > 0) {
  1059. mask -= 1;
  1060. auto color_idx = (byte >> mask) & 0x1;
  1061. if (context.is_included_in_ico) {
  1062. auto color = context.color_table[color_idx];
  1063. context.bitmap->scanline(row)[column++] = color;
  1064. } else {
  1065. context.bitmap->scanline_u8(row)[column++] = color_idx;
  1066. }
  1067. }
  1068. break;
  1069. }
  1070. case 2: {
  1071. if (!streamer.has_u8())
  1072. return Error::from_string_literal("Cannot read 8 bits");
  1073. u8 byte = streamer.read_u8();
  1074. u8 mask = 8;
  1075. while (column < width && mask > 0) {
  1076. mask -= 2;
  1077. auto color_idx = (byte >> mask) & 0x3;
  1078. if (context.is_included_in_ico) {
  1079. auto color = context.color_table[color_idx];
  1080. context.bitmap->scanline(row)[column++] = color;
  1081. } else {
  1082. context.bitmap->scanline_u8(row)[column++] = color_idx;
  1083. }
  1084. }
  1085. break;
  1086. }
  1087. case 4: {
  1088. if (!streamer.has_u8()) {
  1089. return Error::from_string_literal("Cannot read 8 bits");
  1090. }
  1091. u8 byte = streamer.read_u8();
  1092. u32 high_color_idx = (byte >> 4) & 0xf;
  1093. u32 low_color_idx = byte & 0xf;
  1094. if (context.is_included_in_ico) {
  1095. auto high_color = context.color_table[high_color_idx];
  1096. auto low_color = context.color_table[low_color_idx];
  1097. context.bitmap->scanline(row)[column++] = high_color;
  1098. if (column < width) {
  1099. context.bitmap->scanline(row)[column++] = low_color;
  1100. }
  1101. } else {
  1102. context.bitmap->scanline_u8(row)[column++] = high_color_idx;
  1103. if (column < width)
  1104. context.bitmap->scanline_u8(row)[column++] = low_color_idx;
  1105. }
  1106. break;
  1107. }
  1108. case 8: {
  1109. if (!streamer.has_u8())
  1110. return Error::from_string_literal("Cannot read 8 bits");
  1111. u8 byte = streamer.read_u8();
  1112. if (context.is_included_in_ico) {
  1113. auto color = context.color_table[byte];
  1114. context.bitmap->scanline(row)[column++] = color;
  1115. } else {
  1116. context.bitmap->scanline_u8(row)[column++] = byte;
  1117. }
  1118. break;
  1119. }
  1120. case 16: {
  1121. if (!streamer.has_u16())
  1122. return Error::from_string_literal("Cannot read 16 bits");
  1123. context.bitmap->scanline(row)[column++] = int_to_scaled_rgb(context, streamer.read_u16());
  1124. break;
  1125. }
  1126. case 24: {
  1127. if (!streamer.has_u24())
  1128. return Error::from_string_literal("Cannot read 24 bits");
  1129. context.bitmap->scanline(row)[column++] = streamer.read_u24();
  1130. break;
  1131. }
  1132. case 32:
  1133. if (!streamer.has_u32())
  1134. return Error::from_string_literal("Cannot read 32 bits");
  1135. if (context.dib.info.masks.is_empty()) {
  1136. context.bitmap->scanline(row)[column++] = streamer.read_u32();
  1137. } else {
  1138. context.bitmap->scanline(row)[column++] = int_to_scaled_rgb(context, streamer.read_u32());
  1139. }
  1140. break;
  1141. }
  1142. }
  1143. auto consumed = space_remaining_before_consuming_row - streamer.remaining();
  1144. return process_row_padding(consumed);
  1145. };
  1146. auto process_mask_row = [&](u32 row) -> ErrorOr<void> {
  1147. u32 space_remaining_before_consuming_row = streamer.remaining();
  1148. for (u32 column = 0; column < width;) {
  1149. if (!streamer.has_u8())
  1150. return Error::from_string_literal("Cannot read 8 bits");
  1151. u8 byte = streamer.read_u8();
  1152. u8 mask = 8;
  1153. while (column < width && mask > 0) {
  1154. mask -= 1;
  1155. // apply transparency mask
  1156. // AND mask = 0 -> fully opaque
  1157. // AND mask = 1 -> fully transparent
  1158. u8 and_byte = (byte >> (mask)) & 0x1;
  1159. auto pixel = context.bitmap->scanline(row)[column];
  1160. if (and_byte) {
  1161. pixel &= 0x00ffffff;
  1162. } else if (context.dib.core.bpp < 32) {
  1163. pixel |= 0xff000000;
  1164. }
  1165. context.bitmap->scanline(row)[column++] = pixel;
  1166. }
  1167. }
  1168. auto consumed = space_remaining_before_consuming_row - streamer.remaining();
  1169. return process_row_padding(consumed);
  1170. };
  1171. if (context.dib.core.height < 0) {
  1172. // BMP is stored top-down
  1173. for (u32 row = 0; row < height; ++row) {
  1174. TRY(process_row(row));
  1175. }
  1176. if (context.is_included_in_ico) {
  1177. for (u32 row = 0; row < height; ++row) {
  1178. TRY(process_mask_row(row));
  1179. }
  1180. }
  1181. } else {
  1182. // BMP is stored bottom-up
  1183. for (i32 row = height - 1; row >= 0; --row) {
  1184. TRY(process_row(row));
  1185. }
  1186. if (context.is_included_in_ico) {
  1187. for (i32 row = height - 1; row >= 0; --row) {
  1188. TRY(process_mask_row(row));
  1189. }
  1190. }
  1191. }
  1192. if (!context.is_included_in_ico) {
  1193. for (size_t i = 0; i < context.color_table.size(); ++i) {
  1194. context.bitmap->set_palette_color(i, Color::from_rgb(context.color_table[i]));
  1195. }
  1196. }
  1197. context.state = BMPLoadingContext::State::PixelDataDecoded;
  1198. return {};
  1199. }
  1200. BMPImageDecoderPlugin::BMPImageDecoderPlugin(u8 const* data, size_t data_size, IncludedInICO is_included_in_ico)
  1201. {
  1202. m_context = make<BMPLoadingContext>();
  1203. m_context->file_bytes = data;
  1204. m_context->file_size = data_size;
  1205. m_context->is_included_in_ico = (is_included_in_ico == IncludedInICO::Yes);
  1206. }
  1207. BMPImageDecoderPlugin::~BMPImageDecoderPlugin() = default;
  1208. IntSize BMPImageDecoderPlugin::size()
  1209. {
  1210. if (m_context->state == BMPLoadingContext::State::Error)
  1211. return {};
  1212. if (m_context->state < BMPLoadingContext::State::DIBDecoded && decode_bmp_dib(*m_context).is_error())
  1213. return {};
  1214. return { m_context->dib.core.width, abs(m_context->dib.core.height) };
  1215. }
  1216. void BMPImageDecoderPlugin::set_volatile()
  1217. {
  1218. if (m_context->bitmap)
  1219. m_context->bitmap->set_volatile();
  1220. }
  1221. bool BMPImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  1222. {
  1223. if (!m_context->bitmap)
  1224. return false;
  1225. return m_context->bitmap->set_nonvolatile(was_purged);
  1226. }
  1227. bool BMPImageDecoderPlugin::initialize()
  1228. {
  1229. return !decode_bmp_header(*m_context).is_error();
  1230. }
  1231. ErrorOr<bool> BMPImageDecoderPlugin::sniff(ReadonlyBytes data)
  1232. {
  1233. BMPLoadingContext context;
  1234. context.file_bytes = data.data();
  1235. context.file_size = data.size();
  1236. return !decode_bmp_header(context).is_error();
  1237. }
  1238. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> BMPImageDecoderPlugin::create(ReadonlyBytes data)
  1239. {
  1240. return adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(data.data(), data.size()));
  1241. }
  1242. ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> BMPImageDecoderPlugin::create_as_included_in_ico(Badge<ICOImageDecoderPlugin>, ReadonlyBytes data)
  1243. {
  1244. return adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(data.data(), data.size(), IncludedInICO::Yes));
  1245. }
  1246. bool BMPImageDecoderPlugin::sniff_dib()
  1247. {
  1248. return !decode_bmp_dib(*m_context).is_error();
  1249. }
  1250. bool BMPImageDecoderPlugin::is_animated()
  1251. {
  1252. return false;
  1253. }
  1254. size_t BMPImageDecoderPlugin::loop_count()
  1255. {
  1256. return 0;
  1257. }
  1258. size_t BMPImageDecoderPlugin::frame_count()
  1259. {
  1260. return 1;
  1261. }
  1262. ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index)
  1263. {
  1264. if (index > 0)
  1265. return Error::from_string_literal("BMPImageDecoderPlugin: Invalid frame index");
  1266. if (m_context->state == BMPLoadingContext::State::Error)
  1267. return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");
  1268. if (m_context->state < BMPLoadingContext::State::PixelDataDecoded)
  1269. TRY(decode_bmp_pixel_data(*m_context));
  1270. VERIFY(m_context->bitmap);
  1271. return ImageFrameDescriptor { m_context->bitmap, 0 };
  1272. }
  1273. }