BMPLoader.cpp 43 KB

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