BMPLoader.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. 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, 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. 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 constexpr (BMP_DEBUG) {
  448. dbgln("BMP file size: {}", context.file_size);
  449. dbgln("BMP data offset: {}", context.data_offset);
  450. }
  451. if (context.data_offset >= context.file_size) {
  452. dbgln_if(BMP_DEBUG, "BMP data offset is beyond file end?!");
  453. return Error::from_string_literal("BMP data offset is beyond file end");
  454. }
  455. return {};
  456. }
  457. static bool decode_bmp_core_dib(BMPLoadingContext& context, InputStreamer& streamer)
  458. {
  459. auto& core = context.dib.core;
  460. // The width and height are u16 fields in the actual BITMAPCOREHEADER format.
  461. if (context.dib_type == DIBType::Core) {
  462. core.width = streamer.read_u16();
  463. core.height = streamer.read_u16();
  464. } else {
  465. core.width = streamer.read_i32();
  466. core.height = streamer.read_i32();
  467. }
  468. if (core.width < 0) {
  469. dbgln("BMP has a negative width: {}", core.width);
  470. return false;
  471. }
  472. if (static_cast<size_t>(core.width) > maximum_width_for_decoded_images || static_cast<size_t>(abs(core.height)) > maximum_height_for_decoded_images) {
  473. dbgln("This BMP is too large for comfort: {}x{}", core.width, abs(core.height));
  474. return false;
  475. }
  476. auto color_planes = streamer.read_u16();
  477. if (color_planes != 1) {
  478. dbgln("BMP has an invalid number of color planes: {}", color_planes);
  479. return false;
  480. }
  481. core.bpp = streamer.read_u16();
  482. switch (core.bpp) {
  483. case 1:
  484. case 2:
  485. case 4:
  486. case 8:
  487. case 16:
  488. case 24:
  489. case 32:
  490. break;
  491. default:
  492. dbgln("BMP has an invalid bpp: {}", core.bpp);
  493. context.state = BMPLoadingContext::State::Error;
  494. return false;
  495. }
  496. if constexpr (BMP_DEBUG) {
  497. dbgln("BMP width: {}", core.width);
  498. dbgln("BMP height: {}", core.height);
  499. dbgln("BMP bits_per_pixel: {}", core.bpp);
  500. }
  501. return true;
  502. }
  503. ALWAYS_INLINE static bool is_supported_compression_format(BMPLoadingContext& context, u32 compression)
  504. {
  505. return compression == Compression::RGB || compression == Compression::BITFIELDS
  506. || compression == Compression::ALPHABITFIELDS || compression == Compression::RLE8
  507. || compression == Compression::RLE4 || (compression == Compression::RLE24 && context.dib_type <= DIBType::OSV2);
  508. }
  509. static bool decode_bmp_osv2_dib(BMPLoadingContext& context, InputStreamer& streamer, bool short_variant = false)
  510. {
  511. auto& core = context.dib.core;
  512. core.width = streamer.read_u32();
  513. core.height = streamer.read_u32();
  514. if (core.width < 0) {
  515. dbgln("BMP has a negative width: {}", core.width);
  516. return false;
  517. }
  518. auto color_planes = streamer.read_u16();
  519. if (color_planes != 1) {
  520. dbgln("BMP has an invalid number of color planes: {}", color_planes);
  521. return false;
  522. }
  523. core.bpp = streamer.read_u16();
  524. switch (core.bpp) {
  525. case 1:
  526. case 2:
  527. case 4:
  528. case 8:
  529. case 24:
  530. break;
  531. default:
  532. // OS/2 didn't expect 16- or 32-bpp to be popular.
  533. dbgln("BMP has an invalid bpp: {}", core.bpp);
  534. context.state = BMPLoadingContext::State::Error;
  535. return false;
  536. }
  537. if constexpr (BMP_DEBUG) {
  538. dbgln("BMP width: {}", core.width);
  539. dbgln("BMP height: {}", core.height);
  540. dbgln("BMP bits_per_pixel: {}", core.bpp);
  541. }
  542. if (short_variant)
  543. return true;
  544. auto& info = context.dib.info;
  545. auto& osv2 = context.dib.osv2;
  546. info.compression = streamer.read_u32();
  547. info.image_size = streamer.read_u32();
  548. info.horizontal_resolution = streamer.read_u32();
  549. info.vertical_resolution = streamer.read_u32();
  550. info.number_of_palette_colors = streamer.read_u32();
  551. info.number_of_important_palette_colors = streamer.read_u32();
  552. if (!is_supported_compression_format(context, info.compression)) {
  553. dbgln("BMP has unsupported compression value: {}", info.compression);
  554. return false;
  555. }
  556. if (info.number_of_palette_colors > color_palette_limit || info.number_of_important_palette_colors > color_palette_limit) {
  557. dbgln("BMP header indicates too many palette colors: {}", info.number_of_palette_colors);
  558. return false;
  559. }
  560. // Units (2) + reserved (2)
  561. streamer.drop_bytes(4);
  562. osv2.recording = streamer.read_u16();
  563. osv2.halftoning = streamer.read_u16();
  564. osv2.size1 = streamer.read_u32();
  565. osv2.size2 = streamer.read_u32();
  566. // ColorEncoding (4) + Identifier (4)
  567. streamer.drop_bytes(8);
  568. if constexpr (BMP_DEBUG) {
  569. dbgln("BMP compression: {}", info.compression);
  570. dbgln("BMP image size: {}", info.image_size);
  571. dbgln("BMP horizontal res: {}", info.horizontal_resolution);
  572. dbgln("BMP vertical res: {}", info.vertical_resolution);
  573. dbgln("BMP colors: {}", info.number_of_palette_colors);
  574. dbgln("BMP important colors: {}", info.number_of_important_palette_colors);
  575. }
  576. return true;
  577. }
  578. static bool decode_bmp_info_dib(BMPLoadingContext& context, InputStreamer& streamer)
  579. {
  580. if (!decode_bmp_core_dib(context, streamer))
  581. return false;
  582. auto& info = context.dib.info;
  583. auto compression = streamer.read_u32();
  584. info.compression = compression;
  585. if (!is_supported_compression_format(context, compression)) {
  586. dbgln("BMP has unsupported compression value: {}", compression);
  587. return false;
  588. }
  589. info.image_size = streamer.read_u32();
  590. info.horizontal_resolution = streamer.read_i32();
  591. info.vertical_resolution = streamer.read_i32();
  592. info.number_of_palette_colors = streamer.read_u32();
  593. info.number_of_important_palette_colors = streamer.read_u32();
  594. if (info.number_of_palette_colors > color_palette_limit || info.number_of_important_palette_colors > color_palette_limit) {
  595. dbgln("BMP header indicates too many palette colors: {}", info.number_of_palette_colors);
  596. return false;
  597. }
  598. if (info.number_of_important_palette_colors == 0)
  599. info.number_of_important_palette_colors = info.number_of_palette_colors;
  600. if constexpr (BMP_DEBUG) {
  601. dbgln("BMP compression: {}", info.compression);
  602. dbgln("BMP image size: {}", info.image_size);
  603. dbgln("BMP horizontal res: {}", info.horizontal_resolution);
  604. dbgln("BMP vertical res: {}", info.vertical_resolution);
  605. dbgln("BMP colors: {}", info.number_of_palette_colors);
  606. dbgln("BMP important colors: {}", info.number_of_important_palette_colors);
  607. }
  608. return true;
  609. }
  610. static bool decode_bmp_v2_dib(BMPLoadingContext& context, InputStreamer& streamer)
  611. {
  612. if (!decode_bmp_info_dib(context, streamer))
  613. return false;
  614. context.dib.info.masks.append(streamer.read_u32());
  615. context.dib.info.masks.append(streamer.read_u32());
  616. context.dib.info.masks.append(streamer.read_u32());
  617. if constexpr (BMP_DEBUG) {
  618. dbgln("BMP red mask: {:#08x}", context.dib.info.masks[0]);
  619. dbgln("BMP green mask: {:#08x}", context.dib.info.masks[1]);
  620. dbgln("BMP blue mask: {:#08x}", context.dib.info.masks[2]);
  621. }
  622. return true;
  623. }
  624. static bool decode_bmp_v3_dib(BMPLoadingContext& context, InputStreamer& streamer)
  625. {
  626. if (!decode_bmp_v2_dib(context, streamer))
  627. return false;
  628. // There is zero documentation about when alpha masks actually get applied.
  629. // Well, there's some, but it's not even close to comprehensive. So, this is
  630. // in no way based off of any spec, it's simply based off of the BMP test
  631. // suite results.
  632. if (context.dib.info.compression == Compression::ALPHABITFIELDS) {
  633. context.dib.info.masks.append(streamer.read_u32());
  634. dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", context.dib.info.masks[3]);
  635. } else if (context.dib_size() >= 56 && context.dib.core.bpp >= 16) {
  636. auto mask = streamer.read_u32();
  637. if ((context.dib.core.bpp == 32 && mask != 0) || context.dib.core.bpp == 16) {
  638. context.dib.info.masks.append(mask);
  639. dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", mask);
  640. } else {
  641. dbgln_if(BMP_DEBUG, "BMP alpha mask (ignored): {:#08x}", mask);
  642. }
  643. } else {
  644. streamer.drop_bytes(4);
  645. dbgln_if(BMP_DEBUG, "BMP alpha mask skipped");
  646. }
  647. return true;
  648. }
  649. static bool decode_bmp_v4_dib(BMPLoadingContext& context, InputStreamer& streamer)
  650. {
  651. if (!decode_bmp_v3_dib(context, streamer))
  652. return false;
  653. auto& v4 = context.dib.v4;
  654. v4.color_space = streamer.read_u32();
  655. v4.red_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  656. v4.green_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  657. v4.blue_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };
  658. v4.gamma_endpoint = { streamer.read_u32(), streamer.read_u32(), streamer.read_u32() };
  659. if constexpr (BMP_DEBUG) {
  660. dbgln("BMP color space: {}", v4.color_space);
  661. dbgln("BMP red endpoint: {}", v4.red_endpoint);
  662. dbgln("BMP green endpoint: {}", v4.green_endpoint);
  663. dbgln("BMP blue endpoint: {}", v4.blue_endpoint);
  664. dbgln("BMP gamma endpoint: {}", v4.gamma_endpoint);
  665. }
  666. return true;
  667. }
  668. static bool decode_bmp_v5_dib(BMPLoadingContext& context, InputStreamer& streamer)
  669. {
  670. if (!decode_bmp_v4_dib(context, streamer))
  671. return false;
  672. auto& v5 = context.dib.v5;
  673. v5.intent = streamer.read_u32();
  674. v5.profile_data = streamer.read_u32();
  675. v5.profile_size = streamer.read_u32();
  676. streamer.drop_bytes(4); // Ignore reserved field.
  677. if constexpr (BMP_DEBUG) {
  678. dbgln("BMP intent: {}", v5.intent);
  679. dbgln("BMP profile data: {}", v5.profile_data);
  680. dbgln("BMP profile size: {}", v5.profile_size);
  681. }
  682. return true;
  683. }
  684. static ErrorOr<void> decode_bmp_dib(BMPLoadingContext& context)
  685. {
  686. if (context.state == BMPLoadingContext::State::Error)
  687. return Error::from_string_literal("Error before starting decode_bmp_dib");
  688. if (context.state >= BMPLoadingContext::State::DIBDecoded)
  689. return {};
  690. if (!context.is_included_in_ico)
  691. TRY(decode_bmp_header(context));
  692. u8 header_size = context.is_included_in_ico ? 0 : bmp_header_size;
  693. if (context.file_size < (u8)(header_size + 4))
  694. return Error::from_string_literal("File size too short");
  695. InputStreamer streamer(context.file_bytes + header_size, 4);
  696. u32 dib_size = streamer.read_u32();
  697. if (context.file_size < header_size + dib_size)
  698. return Error::from_string_literal("File size too short");
  699. if (!context.is_included_in_ico && (context.data_offset < header_size + dib_size)) {
  700. dbgln("Shenanigans! BMP pixel data and header usually don't overlap.");
  701. return Error::from_string_literal("BMP pixel data and header usually don't overlap");
  702. }
  703. // 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.
  704. // We are also assuming that no Extra bit masks are present
  705. u32 dib_offset = context.is_included_in_ico ? dib_size : context.data_offset - header_size - 4;
  706. streamer = InputStreamer(context.file_bytes + header_size + 4, dib_offset);
  707. dbgln_if(BMP_DEBUG, "BMP dib size: {}", dib_size);
  708. bool error = false;
  709. if (dib_size == 12) {
  710. context.dib_type = DIBType::Core;
  711. if (!decode_bmp_core_dib(context, streamer))
  712. error = true;
  713. } else if (dib_size == 64) {
  714. context.dib_type = DIBType::OSV2;
  715. if (!decode_bmp_osv2_dib(context, streamer))
  716. error = true;
  717. } else if (dib_size == 16) {
  718. context.dib_type = DIBType::OSV2Short;
  719. if (!decode_bmp_osv2_dib(context, streamer, true))
  720. error = true;
  721. } else if (dib_size == 40) {
  722. context.dib_type = DIBType::Info;
  723. if (!decode_bmp_info_dib(context, streamer))
  724. error = true;
  725. } else if (dib_size == 52) {
  726. context.dib_type = DIBType::V2;
  727. if (!decode_bmp_v2_dib(context, streamer))
  728. error = true;
  729. } else if (dib_size == 56) {
  730. context.dib_type = DIBType::V3;
  731. if (!decode_bmp_v3_dib(context, streamer))
  732. error = true;
  733. } else if (dib_size == 108) {
  734. context.dib_type = DIBType::V4;
  735. if (!decode_bmp_v4_dib(context, streamer))
  736. error = true;
  737. } else if (dib_size == 124) {
  738. context.dib_type = DIBType::V5;
  739. if (!decode_bmp_v5_dib(context, streamer))
  740. error = true;
  741. } else {
  742. dbgln("Unsupported BMP DIB size: {}", dib_size);
  743. error = true;
  744. }
  745. switch (context.dib.info.compression) {
  746. case Compression::RGB:
  747. case Compression::RLE8:
  748. case Compression::RLE4:
  749. case Compression::BITFIELDS:
  750. case Compression::RLE24:
  751. case Compression::PNG:
  752. case Compression::ALPHABITFIELDS:
  753. case Compression::CMYK:
  754. case Compression::CMYKRLE8:
  755. case Compression::CMYKRLE4:
  756. break;
  757. default:
  758. error = true;
  759. }
  760. if (!error && !set_dib_bitmasks(context, streamer))
  761. error = true;
  762. if (error) {
  763. dbgln("BMP has an invalid DIB");
  764. context.state = BMPLoadingContext::State::Error;
  765. return Error::from_string_literal("BMP has an invalid DIB");
  766. }
  767. // 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
  768. if (context.is_included_in_ico) {
  769. if (context.dib.core.bpp > 8)
  770. context.data_offset = dib_size;
  771. else {
  772. auto bytes_per_color = context.dib_type == DIBType::Core ? 3 : 4;
  773. u32 max_colors = 1 << context.dib.core.bpp;
  774. 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;
  775. context.data_offset = dib_size + size_of_color_table;
  776. }
  777. }
  778. context.state = BMPLoadingContext::State::DIBDecoded;
  779. return {};
  780. }
  781. static ErrorOr<void> decode_bmp_color_table(BMPLoadingContext& context)
  782. {
  783. if (context.state == BMPLoadingContext::State::Error)
  784. return Error::from_string_literal("Error before starting decode_bmp_color_table");
  785. if (context.state >= BMPLoadingContext::State::ColorTableDecoded)
  786. return {};
  787. if (context.dib.core.bpp > 8) {
  788. context.state = BMPLoadingContext::State::ColorTableDecoded;
  789. return {};
  790. }
  791. auto bytes_per_color = context.dib_type == DIBType::Core ? 3 : 4;
  792. u32 max_colors = 1 << context.dib.core.bpp;
  793. u8 header_size = !context.is_included_in_ico ? bmp_header_size : 0;
  794. VERIFY(context.data_offset >= header_size + context.dib_size());
  795. u32 size_of_color_table;
  796. if (!context.is_included_in_ico) {
  797. size_of_color_table = context.data_offset - header_size - context.dib_size();
  798. } else {
  799. size_of_color_table = (context.dib.info.number_of_palette_colors > 0 ? context.dib.info.number_of_palette_colors : max_colors) * bytes_per_color;
  800. }
  801. if (context.dib_type <= DIBType::OSV2) {
  802. // Partial color tables are not supported, so the space of the color
  803. // table must be at least enough for the maximum amount of colors
  804. if (size_of_color_table < 3 * max_colors) {
  805. // This is against the spec, but most viewers process it anyways
  806. dbgln("BMP with CORE header does not have enough colors. Has: {}, expected: {}", size_of_color_table, (3 * max_colors));
  807. }
  808. }
  809. InputStreamer streamer(context.file_bytes + header_size + context.dib_size(), size_of_color_table);
  810. for (u32 i = 0; !streamer.at_end() && i < max_colors; ++i) {
  811. if (bytes_per_color == 4) {
  812. if (!streamer.has_u32())
  813. return Error::from_string_literal("Cannot read 32 bits");
  814. context.color_table.append(streamer.read_u32());
  815. } else {
  816. if (!streamer.has_u24())
  817. return Error::from_string_literal("Cannot read 24 bits");
  818. context.color_table.append(streamer.read_u24());
  819. }
  820. }
  821. context.state = BMPLoadingContext::State::ColorTableDecoded;
  822. return {};
  823. }
  824. struct RLEState {
  825. enum : u8 {
  826. PixelCount = 0,
  827. PixelValue,
  828. Meta, // Represents just consuming a null byte, which indicates something special
  829. };
  830. };
  831. static ErrorOr<void> uncompress_bmp_rle_data(BMPLoadingContext& context, ByteBuffer& buffer)
  832. {
  833. // RLE-compressed images cannot be stored top-down
  834. if (context.dib.core.height < 0) {
  835. dbgln_if(BMP_DEBUG, "BMP is top-down and RLE compressed");
  836. context.state = BMPLoadingContext::State::Error;
  837. return Error::from_string_literal("BMP is top-down and RLE compressed");
  838. }
  839. InputStreamer streamer(context.file_bytes + context.data_offset, context.file_size - context.data_offset);
  840. auto compression = context.dib.info.compression;
  841. u32 total_rows = static_cast<u32>(context.dib.core.height);
  842. u32 total_columns = round_up_to_power_of_two(static_cast<u32>(context.dib.core.width), 4);
  843. u32 column = 0;
  844. u32 row = 0;
  845. auto currently_consuming = RLEState::PixelCount;
  846. i16 pixel_count = 0;
  847. // ByteBuffer asserts that allocating the memory never fails.
  848. // FIXME: ByteBuffer should return either RefPtr<> or Optional<>.
  849. // Decoding the RLE data on-the-fly might actually be faster, and avoids this topic entirely.
  850. u32 buffer_size;
  851. if (compression == Compression::RLE24) {
  852. buffer_size = total_rows * round_up_to_power_of_two(total_columns, 4) * 4;
  853. } else {
  854. buffer_size = total_rows * round_up_to_power_of_two(total_columns, 4);
  855. }
  856. if (buffer_size > 300 * MiB) {
  857. dbgln("Suspiciously large amount of RLE data");
  858. return Error::from_string_literal("Suspiciously large amount of RLE data");
  859. }
  860. auto buffer_result = ByteBuffer::create_zeroed(buffer_size);
  861. if (buffer_result.is_error()) {
  862. dbgln("Not enough memory for buffer allocation");
  863. return buffer_result.release_error();
  864. }
  865. buffer = buffer_result.release_value();
  866. // Avoid as many if statements as possible by pulling out
  867. // compression-dependent actions into separate lambdas
  868. Function<u32()> get_buffer_index;
  869. Function<ErrorOr<void>(u32, bool)> set_byte;
  870. Function<ErrorOr<u32>()> read_byte;
  871. if (compression == Compression::RLE8) {
  872. get_buffer_index = [&]() -> u32 { return row * total_columns + column; };
  873. } else if (compression == Compression::RLE4) {
  874. get_buffer_index = [&]() -> u32 { return (row * total_columns + column) / 2; };
  875. } else {
  876. get_buffer_index = [&]() -> u32 { return (row * total_columns + column) * 3; };
  877. }
  878. if (compression == Compression::RLE8) {
  879. set_byte = [&](u32 color, bool) -> ErrorOr<void> {
  880. if (column >= total_columns) {
  881. column = 0;
  882. row++;
  883. }
  884. auto index = get_buffer_index();
  885. if (index >= buffer.size()) {
  886. dbgln("BMP has badly-formatted RLE data");
  887. return Error::from_string_literal("BMP has badly-formatted RLE data");
  888. }
  889. buffer[index] = color;
  890. column++;
  891. return {};
  892. };
  893. } else if (compression == Compression::RLE24) {
  894. set_byte = [&](u32 color, bool) -> ErrorOr<void> {
  895. if (column >= total_columns) {
  896. column = 0;
  897. row++;
  898. }
  899. auto index = get_buffer_index();
  900. if (index + 3 >= buffer.size()) {
  901. dbgln("BMP has badly-formatted RLE data");
  902. return Error::from_string_literal("BMP has badly-formatted RLE data");
  903. }
  904. ((u32&)buffer[index]) = color;
  905. column++;
  906. return {};
  907. };
  908. } else {
  909. set_byte = [&](u32 byte, bool rle4_set_second_nibble) -> ErrorOr<void> {
  910. if (column >= total_columns) {
  911. column = 0;
  912. row++;
  913. }
  914. u32 index = get_buffer_index();
  915. if (index >= buffer.size() || (rle4_set_second_nibble && index + 1 >= buffer.size())) {
  916. dbgln("BMP has badly-formatted RLE data");
  917. return Error::from_string_literal("BMP has badly-formatted RLE data");
  918. }
  919. if (column % 2) {
  920. buffer[index] |= byte >> 4;
  921. if (rle4_set_second_nibble) {
  922. buffer[index + 1] |= byte << 4;
  923. column++;
  924. }
  925. } else {
  926. if (rle4_set_second_nibble) {
  927. buffer[index] = byte;
  928. column++;
  929. } else {
  930. buffer[index] |= byte & 0xf0;
  931. }
  932. }
  933. column++;
  934. return {};
  935. };
  936. }
  937. if (compression == Compression::RLE24) {
  938. read_byte = [&]() -> ErrorOr<u32> {
  939. if (!streamer.has_u24()) {
  940. dbgln("BMP has badly-formatted RLE data");
  941. return Error::from_string_literal("BMP has badly-formatted RLE data");
  942. }
  943. return streamer.read_u24();
  944. };
  945. } else {
  946. read_byte = [&]() -> ErrorOr<u32> {
  947. if (!streamer.has_u8()) {
  948. dbgln("BMP has badly-formatted RLE data");
  949. return Error::from_string_literal("BMP has badly-formatted RLE data");
  950. }
  951. return streamer.read_u8();
  952. };
  953. }
  954. while (true) {
  955. u32 byte;
  956. switch (currently_consuming) {
  957. case RLEState::PixelCount:
  958. if (!streamer.has_u8())
  959. return Error::from_string_literal("Cannot read 8 bits");
  960. byte = streamer.read_u8();
  961. if (!byte) {
  962. currently_consuming = RLEState::Meta;
  963. } else {
  964. pixel_count = byte;
  965. currently_consuming = RLEState::PixelValue;
  966. }
  967. break;
  968. case RLEState::PixelValue:
  969. byte = TRY(read_byte());
  970. for (u16 i = 0; i < pixel_count; ++i) {
  971. if (compression != Compression::RLE4) {
  972. TRY(set_byte(byte, true));
  973. } else {
  974. TRY(set_byte(byte, i != pixel_count - 1));
  975. i++;
  976. }
  977. }
  978. currently_consuming = RLEState::PixelCount;
  979. break;
  980. case RLEState::Meta:
  981. if (!streamer.has_u8())
  982. return Error::from_string_literal("Cannot read 8 bits");
  983. byte = streamer.read_u8();
  984. if (!byte) {
  985. column = 0;
  986. row++;
  987. currently_consuming = RLEState::PixelCount;
  988. continue;
  989. }
  990. if (byte == 1)
  991. return {};
  992. if (byte == 2) {
  993. if (!streamer.has_u8())
  994. return Error::from_string_literal("Cannot read 8 bits");
  995. u8 offset_x = streamer.read_u8();
  996. if (!streamer.has_u8())
  997. return Error::from_string_literal("Cannot read 8 bits");
  998. u8 offset_y = streamer.read_u8();
  999. column += offset_x;
  1000. if (column >= total_columns) {
  1001. column -= total_columns;
  1002. row++;
  1003. }
  1004. row += offset_y;
  1005. currently_consuming = RLEState::PixelCount;
  1006. continue;
  1007. }
  1008. // Consume literal bytes
  1009. pixel_count = byte;
  1010. i16 i = byte;
  1011. while (i >= 1) {
  1012. byte = TRY(read_byte());
  1013. TRY(set_byte(byte, i != 1));
  1014. i--;
  1015. if (compression == Compression::RLE4)
  1016. i--;
  1017. }
  1018. // Optionally consume a padding byte
  1019. if (compression != Compression::RLE4) {
  1020. if (pixel_count % 2) {
  1021. if (!streamer.has_u8())
  1022. return Error::from_string_literal("Cannot read 8 bits");
  1023. byte = streamer.read_u8();
  1024. }
  1025. } else {
  1026. if (((pixel_count + 1) / 2) % 2) {
  1027. if (!streamer.has_u8())
  1028. return Error::from_string_literal("Cannot read 8 bits");
  1029. byte = streamer.read_u8();
  1030. }
  1031. }
  1032. currently_consuming = RLEState::PixelCount;
  1033. break;
  1034. }
  1035. }
  1036. VERIFY_NOT_REACHED();
  1037. }
  1038. static ErrorOr<void> decode_bmp_pixel_data(BMPLoadingContext& context)
  1039. {
  1040. if (context.state == BMPLoadingContext::State::Error)
  1041. return Error::from_string_literal("Error before starting decode_bmp_pixel_data");
  1042. if (context.state <= BMPLoadingContext::State::ColorTableDecoded)
  1043. TRY(decode_bmp_color_table(context));
  1044. u16 const bits_per_pixel = context.dib.core.bpp;
  1045. BitmapFormat format = [&]() -> BitmapFormat {
  1046. // NOTE: If this is an BMP included in an ICO, the bitmap format will be converted to BGRA8888.
  1047. // This is because images with less than 32 bits of color depth follow a particular format:
  1048. // the image is encoded with a color mask (the "XOR mask") together with an opacity mask (the "AND mask") of 1 bit per pixel.
  1049. // The height of the encoded image must be exactly twice the real height, before both masks are combined.
  1050. // Bitmaps have no knowledge of this format as they do not store extra rows for the AND mask.
  1051. if (context.is_included_in_ico)
  1052. return BitmapFormat::BGRA8888;
  1053. switch (bits_per_pixel) {
  1054. case 1:
  1055. return BitmapFormat::Indexed1;
  1056. case 2:
  1057. return BitmapFormat::Indexed2;
  1058. case 4:
  1059. return BitmapFormat::Indexed4;
  1060. case 8:
  1061. return BitmapFormat::Indexed8;
  1062. case 16:
  1063. if (context.dib.info.masks.size() == 4)
  1064. return BitmapFormat::BGRA8888;
  1065. return BitmapFormat::BGRx8888;
  1066. case 24:
  1067. return BitmapFormat::BGRx8888;
  1068. case 32:
  1069. return BitmapFormat::BGRA8888;
  1070. default:
  1071. return BitmapFormat::Invalid;
  1072. }
  1073. }();
  1074. if (format == BitmapFormat::Invalid) {
  1075. dbgln("BMP has invalid bpp of {}", bits_per_pixel);
  1076. context.state = BMPLoadingContext::State::Error;
  1077. return Error::from_string_literal("BMP has invalid bpp");
  1078. }
  1079. u32 const width = abs(context.dib.core.width);
  1080. u32 const height = !context.is_included_in_ico ? context.dib.core.height : (context.dib.core.height / 2);
  1081. context.bitmap = TRY(Bitmap::create(format, { static_cast<int>(width), static_cast<int>(height) }));
  1082. ByteBuffer rle_buffer;
  1083. ReadonlyBytes bytes { context.file_bytes + context.data_offset, context.file_size - context.data_offset };
  1084. if (context.dib.info.compression == Compression::RLE4 || context.dib.info.compression == Compression::RLE8
  1085. || context.dib.info.compression == Compression::RLE24) {
  1086. TRY(uncompress_bmp_rle_data(context, rle_buffer));
  1087. bytes = rle_buffer.bytes();
  1088. }
  1089. InputStreamer streamer(bytes.data(), bytes.size());
  1090. auto process_row_padding = [&](u8 const consumed) -> ErrorOr<void> {
  1091. // Calculate padding
  1092. u8 remaining = consumed % 4;
  1093. u8 bytes_to_drop = remaining == 0 ? 0 : 4 - remaining;
  1094. if (streamer.remaining() < bytes_to_drop)
  1095. return Error::from_string_literal("Not enough bytes available to drop");
  1096. streamer.drop_bytes(bytes_to_drop);
  1097. return {};
  1098. };
  1099. auto process_row = [&](u32 row) -> ErrorOr<void> {
  1100. u32 space_remaining_before_consuming_row = streamer.remaining();
  1101. for (u32 column = 0; column < width;) {
  1102. switch (bits_per_pixel) {
  1103. case 1: {
  1104. if (!streamer.has_u8())
  1105. return Error::from_string_literal("Cannot read 8 bits");
  1106. u8 byte = streamer.read_u8();
  1107. u8 mask = 8;
  1108. while (column < width && mask > 0) {
  1109. mask -= 1;
  1110. auto color_idx = (byte >> mask) & 0x1;
  1111. if (context.is_included_in_ico) {
  1112. auto color = context.color_table[color_idx];
  1113. context.bitmap->scanline(row)[column++] = color;
  1114. } else {
  1115. context.bitmap->scanline_u8(row)[column++] = color_idx;
  1116. }
  1117. }
  1118. break;
  1119. }
  1120. case 2: {
  1121. if (!streamer.has_u8())
  1122. return Error::from_string_literal("Cannot read 8 bits");
  1123. u8 byte = streamer.read_u8();
  1124. u8 mask = 8;
  1125. while (column < width && mask > 0) {
  1126. mask -= 2;
  1127. auto color_idx = (byte >> mask) & 0x3;
  1128. if (context.is_included_in_ico) {
  1129. auto color = context.color_table[color_idx];
  1130. context.bitmap->scanline(row)[column++] = color;
  1131. } else {
  1132. context.bitmap->scanline_u8(row)[column++] = color_idx;
  1133. }
  1134. }
  1135. break;
  1136. }
  1137. case 4: {
  1138. if (!streamer.has_u8()) {
  1139. return Error::from_string_literal("Cannot read 8 bits");
  1140. }
  1141. u8 byte = streamer.read_u8();
  1142. u32 high_color_idx = (byte >> 4) & 0xf;
  1143. u32 low_color_idx = byte & 0xf;
  1144. if (context.is_included_in_ico) {
  1145. auto high_color = context.color_table[high_color_idx];
  1146. auto low_color = context.color_table[low_color_idx];
  1147. context.bitmap->scanline(row)[column++] = high_color;
  1148. if (column < width) {
  1149. context.bitmap->scanline(row)[column++] = low_color;
  1150. }
  1151. } else {
  1152. context.bitmap->scanline_u8(row)[column++] = high_color_idx;
  1153. if (column < width)
  1154. context.bitmap->scanline_u8(row)[column++] = low_color_idx;
  1155. }
  1156. break;
  1157. }
  1158. case 8: {
  1159. if (!streamer.has_u8())
  1160. return Error::from_string_literal("Cannot read 8 bits");
  1161. u8 byte = streamer.read_u8();
  1162. if (context.is_included_in_ico) {
  1163. auto color = context.color_table[byte];
  1164. context.bitmap->scanline(row)[column++] = color;
  1165. } else {
  1166. context.bitmap->scanline_u8(row)[column++] = byte;
  1167. }
  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) {
  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) {
  1237. for (i32 row = height - 1; row >= 0; --row) {
  1238. TRY(process_mask_row(row));
  1239. }
  1240. }
  1241. }
  1242. if (!context.is_included_in_ico) {
  1243. for (size_t i = 0; i < context.color_table.size(); ++i) {
  1244. context.bitmap->set_palette_color(i, Color::from_rgb(context.color_table[i]));
  1245. }
  1246. }
  1247. context.state = BMPLoadingContext::State::PixelDataDecoded;
  1248. return {};
  1249. }
  1250. BMPImageDecoderPlugin::BMPImageDecoderPlugin(u8 const* data, size_t data_size, IncludedInICO is_included_in_ico)
  1251. {
  1252. m_context = make<BMPLoadingContext>();
  1253. m_context->file_bytes = data;
  1254. m_context->file_size = data_size;
  1255. m_context->is_included_in_ico = (is_included_in_ico == IncludedInICO::Yes);
  1256. }
  1257. BMPImageDecoderPlugin::~BMPImageDecoderPlugin() = default;
  1258. IntSize BMPImageDecoderPlugin::size()
  1259. {
  1260. return { m_context->dib.core.width, abs(m_context->dib.core.height) };
  1261. }
  1262. bool BMPImageDecoderPlugin::sniff(ReadonlyBytes data)
  1263. {
  1264. BMPLoadingContext context;
  1265. context.file_bytes = data.data();
  1266. context.file_size = data.size();
  1267. return !decode_bmp_header(context).is_error();
  1268. }
  1269. ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> BMPImageDecoderPlugin::create_impl(ReadonlyBytes data, IncludedInICO included_in_ico)
  1270. {
  1271. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(data.data(), data.size(), included_in_ico)));
  1272. TRY(decode_bmp_dib(*plugin->m_context));
  1273. return plugin;
  1274. }
  1275. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> BMPImageDecoderPlugin::create(ReadonlyBytes data)
  1276. {
  1277. return create_impl(data, IncludedInICO::No);
  1278. }
  1279. ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> BMPImageDecoderPlugin::create_as_included_in_ico(Badge<ICOImageDecoderPlugin>, ReadonlyBytes data)
  1280. {
  1281. return create_impl(data, IncludedInICO::Yes);
  1282. }
  1283. bool BMPImageDecoderPlugin::sniff_dib()
  1284. {
  1285. return !decode_bmp_dib(*m_context).is_error();
  1286. }
  1287. bool BMPImageDecoderPlugin::is_animated()
  1288. {
  1289. return false;
  1290. }
  1291. size_t BMPImageDecoderPlugin::loop_count()
  1292. {
  1293. return 0;
  1294. }
  1295. size_t BMPImageDecoderPlugin::frame_count()
  1296. {
  1297. return 1;
  1298. }
  1299. size_t BMPImageDecoderPlugin::first_animated_frame_index()
  1300. {
  1301. return 0;
  1302. }
  1303. ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1304. {
  1305. if (index > 0)
  1306. return Error::from_string_literal("BMPImageDecoderPlugin: Invalid frame index");
  1307. if (m_context->state == BMPLoadingContext::State::Error)
  1308. return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");
  1309. if (m_context->state < BMPLoadingContext::State::PixelDataDecoded)
  1310. TRY(decode_bmp_pixel_data(*m_context));
  1311. VERIFY(m_context->bitmap);
  1312. return ImageFrameDescriptor { m_context->bitmap, 0 };
  1313. }
  1314. ErrorOr<Optional<ReadonlyBytes>> BMPImageDecoderPlugin::icc_data()
  1315. {
  1316. if (m_context->dib_type != DIBType::V5)
  1317. return OptionalNone {};
  1318. // FIXME: For LINKED, return data from the linked file?
  1319. // FIXME: For sRGB and WINDOWS_COLOR_SPACE, return an sRGB profile somehow.
  1320. // FIXME: For CALIBRATED_RGB, do something with v4.{red_endpoint,green_endpoint,blue_endpoint,gamma_endpoint}
  1321. if (m_context->dib.v4.color_space != ColorSpace::EMBEDDED)
  1322. return OptionalNone {};
  1323. auto const& v5 = m_context->dib.v5;
  1324. if (!v5.profile_data || !v5.profile_size)
  1325. return OptionalNone {};
  1326. // FIXME: Do something with v5.intent (which has a GamutMappingIntent value).
  1327. u8 header_size = m_context->is_included_in_ico ? 0 : bmp_header_size;
  1328. if (v5.profile_data + header_size + v5.profile_size > m_context->file_size)
  1329. return Error::from_string_literal("BMPImageDecoderPlugin: ICC profile data out of bounds");
  1330. return ReadonlyBytes { m_context->file_bytes + header_size + v5.profile_data, v5.profile_size };
  1331. }
  1332. }