BMPLoader.cpp 53 KB

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