BMPLoader.cpp 53 KB

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