BMPLoader.cpp 52 KB

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