BMPLoader.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  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. // 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. // TODO: This is a guess
  380. if (bpp > 4)
  381. return false;
  382. break;
  383. default:
  384. // Other compressions are not officially supported.
  385. // Technically, we could even drop ALPHABITFIELDS.
  386. return false;
  387. }
  388. break;
  389. case DIBType::OSV2Short:
  390. case DIBType::OSV2:
  391. case DIBType::V2:
  392. case DIBType::V3:
  393. case DIBType::V4:
  394. case DIBType::V5:
  395. if (compression == Compression::BITFIELDS && bpp != 16 && bpp != 32)
  396. return false;
  397. break;
  398. }
  399. return true;
  400. }
  401. static bool set_dib_bitmasks(BMPLoadingContext& context, InputStreamer& streamer)
  402. {
  403. if (!check_for_invalid_bitmask_combinations(context))
  404. return false;
  405. auto& bpp = context.dib.core.bpp;
  406. if (bpp <= 8 || bpp == 24)
  407. return true;
  408. auto& compression = context.dib.info.compression;
  409. auto& type = context.dib_type;
  410. if (type > DIBType::OSV2 && bpp == 16 && compression == Compression::RGB) {
  411. context.dib.info.masks.extend({ 0x7c00, 0x03e0, 0x001f });
  412. context.dib.info.mask_shifts.extend({ 7, 2, -3 });
  413. context.dib.info.mask_sizes.extend({ 5, 5, 5 });
  414. } else if (type == DIBType::Info && (compression == Compression::BITFIELDS || compression == Compression::ALPHABITFIELDS)) {
  415. // Consume the extra BITFIELDS bytes
  416. auto number_of_mask_fields = compression == Compression::ALPHABITFIELDS ? 4 : 3;
  417. for (auto i = 0; i < number_of_mask_fields; i++) {
  418. if (!streamer.has_u32())
  419. return false;
  420. context.dib.info.masks.append(streamer.read_u32());
  421. }
  422. }
  423. populate_dib_mask_info_if_needed(context);
  424. return true;
  425. }
  426. static ErrorOr<void> decode_bmp_header(BMPLoadingContext& context)
  427. {
  428. if (context.state == BMPLoadingContext::State::Error)
  429. return Error::from_string_literal("Error before starting decode_bmp_header");
  430. if (context.state >= BMPLoadingContext::State::HeaderDecoded)
  431. return {};
  432. if (!context.file_bytes || context.file_size < bmp_header_size) {
  433. dbgln_if(BMP_DEBUG, "Missing BMP header");
  434. context.state = BMPLoadingContext::State::Error;
  435. return Error::from_string_literal("Missing BMP header");
  436. }
  437. InputStreamer streamer(context.file_bytes, bmp_header_size);
  438. u16 header = streamer.read_u16();
  439. if (header != 0x4d42) {
  440. dbgln_if(BMP_DEBUG, "BMP has invalid magic header number: {:#04x}", header);
  441. context.state = BMPLoadingContext::State::Error;
  442. return Error::from_string_literal("BMP has invalid magic header number");
  443. }
  444. // The reported size of the file in the header is actually not important
  445. // for decoding the file. Some specifications say that this value should
  446. // be the size of the header instead, so we just rely on the known file
  447. // size, instead of a possibly-correct-but-also-possibly-incorrect reported
  448. // value of the file size.
  449. streamer.drop_bytes(4);
  450. // Ignore reserved bytes
  451. streamer.drop_bytes(4);
  452. context.data_offset = streamer.read_u32();
  453. if constexpr (BMP_DEBUG) {
  454. dbgln("BMP file size: {}", context.file_size);
  455. dbgln("BMP data offset: {}", context.data_offset);
  456. }
  457. if (context.data_offset >= context.file_size) {
  458. dbgln_if(BMP_DEBUG, "BMP data offset is beyond file end?!");
  459. return Error::from_string_literal("BMP data offset is beyond file end");
  460. }
  461. context.state = BMPLoadingContext::State::HeaderDecoded;
  462. return {};
  463. }
  464. static bool decode_bmp_core_dib(BMPLoadingContext& context, InputStreamer& streamer)
  465. {
  466. auto& core = context.dib.core;
  467. // The width and height are u16 fields in the actual BITMAPCOREHEADER format.
  468. if (context.dib_type == DIBType::Core) {
  469. core.width = streamer.read_u16();
  470. core.height = streamer.read_u16();
  471. } else {
  472. core.width = streamer.read_i32();
  473. core.height = streamer.read_i32();
  474. }
  475. if (core.width < 0) {
  476. dbgln("BMP has a negative width: {}", core.width);
  477. return false;
  478. }
  479. if (static_cast<size_t>(core.width) > maximum_width_for_decoded_images || static_cast<size_t>(abs(core.height)) > maximum_height_for_decoded_images) {
  480. dbgln("This BMP is too large for comfort: {}x{}", core.width, abs(core.height));
  481. return false;
  482. }
  483. auto color_planes = streamer.read_u16();
  484. if (color_planes != 1) {
  485. dbgln("BMP has an invalid number of color planes: {}", color_planes);
  486. return false;
  487. }
  488. core.bpp = streamer.read_u16();
  489. switch (core.bpp) {
  490. case 1:
  491. case 2:
  492. case 4:
  493. case 8:
  494. case 16:
  495. case 24:
  496. case 32:
  497. break;
  498. default:
  499. dbgln("BMP has an invalid bpp: {}", core.bpp);
  500. context.state = BMPLoadingContext::State::Error;
  501. return false;
  502. }
  503. if constexpr (BMP_DEBUG) {
  504. dbgln("BMP width: {}", core.width);
  505. dbgln("BMP height: {}", core.height);
  506. dbgln("BMP bits_per_pixel: {}", core.bpp);
  507. }
  508. return true;
  509. }
  510. ALWAYS_INLINE static bool is_supported_compression_format(BMPLoadingContext& context, u32 compression)
  511. {
  512. return compression == Compression::RGB || compression == Compression::BITFIELDS
  513. || compression == Compression::ALPHABITFIELDS || compression == Compression::RLE8
  514. || compression == Compression::RLE4 || (compression == Compression::RLE24 && context.dib_type <= DIBType::OSV2);
  515. }
  516. static bool decode_bmp_osv2_dib(BMPLoadingContext& context, InputStreamer& streamer, bool short_variant = false)
  517. {
  518. auto& core = context.dib.core;
  519. core.width = streamer.read_u32();
  520. core.height = streamer.read_u32();
  521. if (core.width < 0) {
  522. dbgln("BMP has a negative width: {}", core.width);
  523. return false;
  524. }
  525. auto color_planes = streamer.read_u16();
  526. if (color_planes != 1) {
  527. dbgln("BMP has an invalid number of color planes: {}", color_planes);
  528. return false;
  529. }
  530. core.bpp = streamer.read_u16();
  531. switch (core.bpp) {
  532. case 1:
  533. case 2:
  534. case 4:
  535. case 8:
  536. case 24:
  537. break;
  538. default:
  539. // OS/2 didn't expect 16- or 32-bpp to be popular.
  540. dbgln("BMP has an invalid bpp: {}", core.bpp);
  541. context.state = BMPLoadingContext::State::Error;
  542. return false;
  543. }
  544. if constexpr (BMP_DEBUG) {
  545. dbgln("BMP width: {}", core.width);
  546. dbgln("BMP height: {}", core.height);
  547. dbgln("BMP bits_per_pixel: {}", core.bpp);
  548. }
  549. if (short_variant)
  550. return true;
  551. auto& info = context.dib.info;
  552. auto& osv2 = context.dib.osv2;
  553. info.compression = streamer.read_u32();
  554. info.image_size = streamer.read_u32();
  555. info.horizontal_resolution = streamer.read_u32();
  556. info.vertical_resolution = streamer.read_u32();
  557. info.number_of_palette_colors = streamer.read_u32();
  558. info.number_of_important_palette_colors = streamer.read_u32();
  559. if (!is_supported_compression_format(context, info.compression)) {
  560. dbgln("BMP has unsupported compression value: {}", info.compression);
  561. return false;
  562. }
  563. if (info.number_of_palette_colors > color_palette_limit || info.number_of_important_palette_colors > color_palette_limit) {
  564. dbgln("BMP header indicates too many palette colors: {}", info.number_of_palette_colors);
  565. return false;
  566. }
  567. // Units (2) + reserved (2)
  568. streamer.drop_bytes(4);
  569. osv2.recording = streamer.read_u16();
  570. osv2.halftoning = streamer.read_u16();
  571. osv2.size1 = streamer.read_u32();
  572. osv2.size2 = streamer.read_u32();
  573. // ColorEncoding (4) + Identifier (4)
  574. streamer.drop_bytes(8);
  575. if constexpr (BMP_DEBUG) {
  576. dbgln("BMP compression: {}", info.compression);
  577. dbgln("BMP image size: {}", info.image_size);
  578. dbgln("BMP horizontal res: {}", info.horizontal_resolution);
  579. dbgln("BMP vertical res: {}", info.vertical_resolution);
  580. dbgln("BMP colors: {}", info.number_of_palette_colors);
  581. dbgln("BMP important colors: {}", info.number_of_important_palette_colors);
  582. }
  583. return true;
  584. }
  585. static bool decode_bmp_info_dib(BMPLoadingContext& context, InputStreamer& streamer)
  586. {
  587. if (!decode_bmp_core_dib(context, streamer))
  588. return false;
  589. auto& info = context.dib.info;
  590. auto compression = streamer.read_u32();
  591. info.compression = compression;
  592. if (!is_supported_compression_format(context, compression)) {
  593. dbgln("BMP has unsupported compression value: {}", compression);
  594. return false;
  595. }
  596. info.image_size = streamer.read_u32();
  597. info.horizontal_resolution = streamer.read_i32();
  598. info.vertical_resolution = streamer.read_i32();
  599. info.number_of_palette_colors = streamer.read_u32();
  600. info.number_of_important_palette_colors = streamer.read_u32();
  601. if (info.number_of_palette_colors > color_palette_limit || info.number_of_important_palette_colors > color_palette_limit) {
  602. dbgln("BMP header indicates too many palette colors: {}", info.number_of_palette_colors);
  603. return false;
  604. }
  605. if (info.number_of_important_palette_colors == 0)
  606. info.number_of_important_palette_colors = info.number_of_palette_colors;
  607. if constexpr (BMP_DEBUG) {
  608. dbgln("BMP compression: {}", info.compression);
  609. dbgln("BMP image size: {}", info.image_size);
  610. dbgln("BMP horizontal res: {}", info.horizontal_resolution);
  611. dbgln("BMP vertical res: {}", info.vertical_resolution);
  612. dbgln("BMP colors: {}", info.number_of_palette_colors);
  613. dbgln("BMP important colors: {}", info.number_of_important_palette_colors);
  614. }
  615. return true;
  616. }
  617. static bool decode_bmp_v2_dib(BMPLoadingContext& context, InputStreamer& streamer)
  618. {
  619. if (!decode_bmp_info_dib(context, streamer))
  620. return false;
  621. context.dib.info.masks.append(streamer.read_u32());
  622. context.dib.info.masks.append(streamer.read_u32());
  623. context.dib.info.masks.append(streamer.read_u32());
  624. if constexpr (BMP_DEBUG) {
  625. dbgln("BMP red mask: {:#08x}", context.dib.info.masks[0]);
  626. dbgln("BMP green mask: {:#08x}", context.dib.info.masks[1]);
  627. dbgln("BMP blue mask: {:#08x}", context.dib.info.masks[2]);
  628. }
  629. return true;
  630. }
  631. static bool decode_bmp_v3_dib(BMPLoadingContext& context, InputStreamer& streamer)
  632. {
  633. if (!decode_bmp_v2_dib(context, streamer))
  634. return false;
  635. // There is zero documentation about when alpha masks actually get applied.
  636. // Well, there's some, but it's not even close to comprehensive. So, this is
  637. // in no way based off of any spec, it's simply based off of the BMP test
  638. // suite results.
  639. if (context.dib.info.compression == Compression::ALPHABITFIELDS) {
  640. context.dib.info.masks.append(streamer.read_u32());
  641. dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", context.dib.info.masks[3]);
  642. } else if (context.dib_size() >= 56 && context.dib.core.bpp >= 16) {
  643. auto mask = streamer.read_u32();
  644. if ((context.dib.core.bpp == 32 && mask != 0) || context.dib.core.bpp == 16) {
  645. context.dib.info.masks.append(mask);
  646. dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", mask);
  647. } else {
  648. dbgln_if(BMP_DEBUG, "BMP alpha mask (ignored): {:#08x}", mask);
  649. }
  650. } else {
  651. streamer.drop_bytes(4);
  652. dbgln_if(BMP_DEBUG, "BMP alpha mask skipped");
  653. }
  654. return true;
  655. }
  656. static bool decode_bmp_v4_dib(BMPLoadingContext& context, InputStreamer& streamer)
  657. {
  658. if (!decode_bmp_v3_dib(context, streamer))
  659. return false;
  660. auto& v4 = context.dib.v4;
  661. v4.color_space = streamer.read_u32();
  662. v4.red_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  663. v4.green_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  664. v4.blue_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  665. v4.gamma_endpoint = { streamer.read_u32(), streamer.read_u32(), streamer.read_u32() };
  666. if constexpr (BMP_DEBUG) {
  667. dbgln("BMP color space: {}", v4.color_space);
  668. dbgln("BMP red endpoint: {}", v4.red_endpoint);
  669. dbgln("BMP green endpoint: {}", v4.green_endpoint);
  670. dbgln("BMP blue endpoint: {}", v4.blue_endpoint);
  671. dbgln("BMP gamma endpoint: {}", v4.gamma_endpoint);
  672. }
  673. return true;
  674. }
  675. static bool decode_bmp_v5_dib(BMPLoadingContext& context, InputStreamer& streamer)
  676. {
  677. if (!decode_bmp_v4_dib(context, streamer))
  678. return false;
  679. auto& v5 = context.dib.v5;
  680. v5.intent = streamer.read_u32();
  681. v5.profile_data = streamer.read_u32();
  682. v5.profile_size = streamer.read_u32();
  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. void BMPImageDecoderPlugin::set_volatile()
  1275. {
  1276. if (m_context->bitmap)
  1277. m_context->bitmap->set_volatile();
  1278. }
  1279. bool BMPImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  1280. {
  1281. if (!m_context->bitmap)
  1282. return false;
  1283. return m_context->bitmap->set_nonvolatile(was_purged);
  1284. }
  1285. bool BMPImageDecoderPlugin::initialize()
  1286. {
  1287. return !decode_bmp_header(*m_context).is_error();
  1288. }
  1289. ErrorOr<bool> BMPImageDecoderPlugin::sniff(ReadonlyBytes data)
  1290. {
  1291. BMPLoadingContext context;
  1292. context.file_bytes = data.data();
  1293. context.file_size = data.size();
  1294. return !decode_bmp_header(context).is_error();
  1295. }
  1296. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> BMPImageDecoderPlugin::create(ReadonlyBytes data)
  1297. {
  1298. return adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(data.data(), data.size()));
  1299. }
  1300. ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> BMPImageDecoderPlugin::create_as_included_in_ico(Badge<ICOImageDecoderPlugin>, ReadonlyBytes data)
  1301. {
  1302. return adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(data.data(), data.size(), IncludedInICO::Yes));
  1303. }
  1304. bool BMPImageDecoderPlugin::sniff_dib()
  1305. {
  1306. return !decode_bmp_dib(*m_context).is_error();
  1307. }
  1308. bool BMPImageDecoderPlugin::is_animated()
  1309. {
  1310. return false;
  1311. }
  1312. size_t BMPImageDecoderPlugin::loop_count()
  1313. {
  1314. return 0;
  1315. }
  1316. size_t BMPImageDecoderPlugin::frame_count()
  1317. {
  1318. return 1;
  1319. }
  1320. ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index)
  1321. {
  1322. if (index > 0)
  1323. return Error::from_string_literal("BMPImageDecoderPlugin: Invalid frame index");
  1324. if (m_context->state == BMPLoadingContext::State::Error)
  1325. return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");
  1326. if (m_context->state < BMPLoadingContext::State::PixelDataDecoded)
  1327. TRY(decode_bmp_pixel_data(*m_context));
  1328. VERIFY(m_context->bitmap);
  1329. return ImageFrameDescriptor { m_context->bitmap, 0 };
  1330. }
  1331. ErrorOr<Optional<ReadonlyBytes>> BMPImageDecoderPlugin::icc_data()
  1332. {
  1333. TRY(decode_bmp_dib(*m_context));
  1334. if (m_context->dib_type != DIBType::V5)
  1335. return OptionalNone {};
  1336. // FIXME: For LINKED, return data from the linked file?
  1337. // FIXME: For sRGB and WINDOWS_COLOR_SPACE, return an sRGB profile somehow.
  1338. // FIXME: For CALIBRATED_RGB, do something with v4.{red_endpoint,green_endpoint,blue_endpoint,gamma_endpoint}
  1339. if (m_context->dib.v4.color_space != ColorSpace::EMBEDDED)
  1340. return OptionalNone {};
  1341. auto const& v5 = m_context->dib.v5;
  1342. if (!v5.profile_data || !v5.profile_size)
  1343. return OptionalNone {};
  1344. // FIXME: Do something with v5.intent (which has a GamutMappingIntent value).
  1345. u8 header_size = m_context->is_included_in_ico ? 0 : bmp_header_size;
  1346. if (v5.profile_data + header_size + v5.profile_size > m_context->file_size)
  1347. return Error::from_string_literal("BMPImageDecoderPlugin: ICC profile data out of bounds");
  1348. return ReadonlyBytes { m_context->file_bytes + header_size + v5.profile_data, v5.profile_size };
  1349. }
  1350. }