BMPLoader.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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. buffer = ByteBuffer::create_zeroed(buffer_size);
  801. // Avoid as many if statements as possible by pulling out
  802. // compression-dependent actions into separate lambdas
  803. Function<u32()> get_buffer_index;
  804. Function<bool(u32, bool)> set_byte;
  805. Function<Optional<u32>()> read_byte;
  806. if (compression == Compression::RLE8) {
  807. get_buffer_index = [&]() -> u32 { return row * total_columns + column; };
  808. } else if (compression == Compression::RLE4) {
  809. get_buffer_index = [&]() -> u32 { return (row * total_columns + column) / 2; };
  810. } else {
  811. get_buffer_index = [&]() -> u32 { return (row * total_columns + column) * 3; };
  812. }
  813. if (compression == Compression::RLE8) {
  814. set_byte = [&](u32 color, bool) -> bool {
  815. if (column >= total_columns) {
  816. column = 0;
  817. row++;
  818. }
  819. auto index = get_buffer_index();
  820. if (index >= buffer.size()) {
  821. dbgln("BMP has badly-formatted RLE data");
  822. return false;
  823. }
  824. buffer[index] = color;
  825. column++;
  826. return true;
  827. };
  828. } else if (compression == Compression::RLE24) {
  829. set_byte = [&](u32 color, bool) -> bool {
  830. if (column >= total_columns) {
  831. column = 0;
  832. row++;
  833. }
  834. auto index = get_buffer_index();
  835. if (index + 3 >= buffer.size()) {
  836. dbgln("BMP has badly-formatted RLE data");
  837. return false;
  838. }
  839. ((u32&)buffer[index]) = color;
  840. column++;
  841. return true;
  842. };
  843. } else {
  844. set_byte = [&](u32 byte, bool rle4_set_second_nibble) -> bool {
  845. if (column >= total_columns) {
  846. column = 0;
  847. row++;
  848. }
  849. u32 index = get_buffer_index();
  850. if (index >= buffer.size() || (rle4_set_second_nibble && index + 1 >= buffer.size())) {
  851. dbgln("BMP has badly-formatted RLE data");
  852. return false;
  853. }
  854. if (column % 2) {
  855. buffer[index] |= byte >> 4;
  856. if (rle4_set_second_nibble) {
  857. buffer[index + 1] |= byte << 4;
  858. column++;
  859. }
  860. } else {
  861. if (rle4_set_second_nibble) {
  862. buffer[index] = byte;
  863. column++;
  864. } else {
  865. buffer[index] |= byte & 0xf0;
  866. }
  867. }
  868. column++;
  869. return true;
  870. };
  871. }
  872. if (compression == Compression::RLE24) {
  873. read_byte = [&]() -> Optional<u32> {
  874. if (!streamer.has_u24()) {
  875. dbgln("BMP has badly-formatted RLE data");
  876. return {};
  877. }
  878. return streamer.read_u24();
  879. };
  880. } else {
  881. read_byte = [&]() -> Optional<u32> {
  882. if (!streamer.has_u8()) {
  883. dbgln("BMP has badly-formatted RLE data");
  884. return {};
  885. }
  886. return streamer.read_u8();
  887. };
  888. }
  889. while (true) {
  890. u32 byte;
  891. switch (currently_consuming) {
  892. case RLEState::PixelCount:
  893. if (!streamer.has_u8())
  894. return false;
  895. byte = streamer.read_u8();
  896. if (!byte) {
  897. currently_consuming = RLEState::Meta;
  898. } else {
  899. pixel_count = byte;
  900. currently_consuming = RLEState::PixelValue;
  901. }
  902. break;
  903. case RLEState::PixelValue: {
  904. auto result = read_byte();
  905. if (!result.has_value())
  906. return false;
  907. byte = result.value();
  908. for (u16 i = 0; i < pixel_count; ++i) {
  909. if (compression != Compression::RLE4) {
  910. if (!set_byte(byte, true))
  911. return false;
  912. } else {
  913. if (!set_byte(byte, i != pixel_count - 1))
  914. return false;
  915. i++;
  916. }
  917. }
  918. currently_consuming = RLEState::PixelCount;
  919. break;
  920. }
  921. case RLEState::Meta:
  922. if (!streamer.has_u8())
  923. return false;
  924. byte = streamer.read_u8();
  925. if (!byte) {
  926. column = 0;
  927. row++;
  928. currently_consuming = RLEState::PixelCount;
  929. continue;
  930. }
  931. if (byte == 1)
  932. return true;
  933. if (byte == 2) {
  934. if (!streamer.has_u8())
  935. return false;
  936. u8 offset_x = streamer.read_u8();
  937. if (!streamer.has_u8())
  938. return false;
  939. u8 offset_y = streamer.read_u8();
  940. column += offset_x;
  941. if (column >= total_columns) {
  942. column -= total_columns;
  943. row++;
  944. }
  945. row += offset_y;
  946. currently_consuming = RLEState::PixelCount;
  947. continue;
  948. }
  949. // Consume literal bytes
  950. pixel_count = byte;
  951. i16 i = byte;
  952. while (i >= 1) {
  953. auto result = read_byte();
  954. if (!result.has_value())
  955. return false;
  956. byte = result.value();
  957. if (!set_byte(byte, i != 1))
  958. return false;
  959. i--;
  960. if (compression == Compression::RLE4)
  961. i--;
  962. }
  963. // Optionally consume a padding byte
  964. if (compression != Compression::RLE4) {
  965. if (pixel_count % 2) {
  966. if (!streamer.has_u8())
  967. return false;
  968. byte = streamer.read_u8();
  969. }
  970. } else {
  971. if (((pixel_count + 1) / 2) % 2) {
  972. if (!streamer.has_u8())
  973. return false;
  974. byte = streamer.read_u8();
  975. }
  976. }
  977. currently_consuming = RLEState::PixelCount;
  978. break;
  979. }
  980. }
  981. VERIFY_NOT_REACHED();
  982. }
  983. static bool decode_bmp_pixel_data(BMPLoadingContext& context)
  984. {
  985. if (context.state == BMPLoadingContext::State::Error)
  986. return false;
  987. if (context.state <= BMPLoadingContext::State::ColorTableDecoded && !decode_bmp_color_table(context))
  988. return false;
  989. const u16 bits_per_pixel = context.dib.core.bpp;
  990. BitmapFormat format = [&]() -> BitmapFormat {
  991. switch (bits_per_pixel) {
  992. case 1:
  993. return BitmapFormat::Indexed1;
  994. case 2:
  995. return BitmapFormat::Indexed2;
  996. case 4:
  997. return BitmapFormat::Indexed4;
  998. case 8:
  999. return BitmapFormat::Indexed8;
  1000. case 16:
  1001. if (context.dib.info.masks.size() == 4)
  1002. return BitmapFormat::BGRA8888;
  1003. return BitmapFormat::BGRx8888;
  1004. case 24:
  1005. return BitmapFormat::BGRx8888;
  1006. case 32:
  1007. return BitmapFormat::BGRA8888;
  1008. default:
  1009. return BitmapFormat::Invalid;
  1010. }
  1011. }();
  1012. if (format == BitmapFormat::Invalid) {
  1013. dbgln("BMP has invalid bpp of {}", bits_per_pixel);
  1014. context.state = BMPLoadingContext::State::Error;
  1015. return false;
  1016. }
  1017. const u32 width = abs(context.dib.core.width);
  1018. const u32 height = abs(context.dib.core.height);
  1019. context.bitmap = Bitmap::create_purgeable(format, { static_cast<int>(width), static_cast<int>(height) });
  1020. if (!context.bitmap) {
  1021. dbgln("BMP appears to have overly large dimensions");
  1022. return false;
  1023. }
  1024. ByteBuffer rle_buffer;
  1025. ReadonlyBytes bytes { context.file_bytes + context.data_offset, context.file_size - context.data_offset };
  1026. if (context.dib.info.compression == Compression::RLE4 || context.dib.info.compression == Compression::RLE8
  1027. || context.dib.info.compression == Compression::RLE24) {
  1028. if (!uncompress_bmp_rle_data(context, rle_buffer))
  1029. return false;
  1030. bytes = rle_buffer.bytes();
  1031. }
  1032. InputStreamer streamer(bytes.data(), bytes.size());
  1033. auto process_row = [&](u32 row) -> bool {
  1034. u32 space_remaining_before_consuming_row = streamer.remaining();
  1035. for (u32 column = 0; column < width;) {
  1036. switch (bits_per_pixel) {
  1037. case 1: {
  1038. if (!streamer.has_u8())
  1039. return false;
  1040. u8 byte = streamer.read_u8();
  1041. u8 mask = 8;
  1042. while (column < width && mask > 0) {
  1043. mask -= 1;
  1044. context.bitmap->scanline_u8(row)[column++] = (byte >> mask) & 0x1;
  1045. }
  1046. break;
  1047. }
  1048. case 2: {
  1049. if (!streamer.has_u8())
  1050. return false;
  1051. u8 byte = streamer.read_u8();
  1052. u8 mask = 8;
  1053. while (column < width && mask > 0) {
  1054. mask -= 2;
  1055. context.bitmap->scanline_u8(row)[column++] = (byte >> mask) & 0x3;
  1056. }
  1057. break;
  1058. }
  1059. case 4: {
  1060. if (!streamer.has_u8())
  1061. return false;
  1062. u8 byte = streamer.read_u8();
  1063. context.bitmap->scanline_u8(row)[column++] = (byte >> 4) & 0xf;
  1064. if (column < width)
  1065. context.bitmap->scanline_u8(row)[column++] = byte & 0xf;
  1066. break;
  1067. }
  1068. case 8:
  1069. if (!streamer.has_u8())
  1070. return false;
  1071. context.bitmap->scanline_u8(row)[column++] = streamer.read_u8();
  1072. break;
  1073. case 16: {
  1074. if (!streamer.has_u16())
  1075. return false;
  1076. context.bitmap->scanline(row)[column++] = int_to_scaled_rgb(context, streamer.read_u16());
  1077. break;
  1078. }
  1079. case 24: {
  1080. if (!streamer.has_u24())
  1081. return false;
  1082. context.bitmap->scanline(row)[column++] = streamer.read_u24();
  1083. break;
  1084. }
  1085. case 32:
  1086. if (!streamer.has_u32())
  1087. return false;
  1088. if (context.dib.info.masks.is_empty()) {
  1089. context.bitmap->scanline(row)[column++] = streamer.read_u32() | 0xff000000;
  1090. } else {
  1091. context.bitmap->scanline(row)[column++] = int_to_scaled_rgb(context, streamer.read_u32());
  1092. }
  1093. break;
  1094. }
  1095. }
  1096. auto consumed = space_remaining_before_consuming_row - streamer.remaining();
  1097. // Calculate padding
  1098. u8 bytes_to_drop = [consumed]() -> u8 {
  1099. switch (consumed % 4) {
  1100. case 0:
  1101. return 0;
  1102. case 1:
  1103. return 3;
  1104. case 2:
  1105. return 2;
  1106. case 3:
  1107. return 1;
  1108. }
  1109. VERIFY_NOT_REACHED();
  1110. }();
  1111. if (streamer.remaining() < bytes_to_drop)
  1112. return false;
  1113. streamer.drop_bytes(bytes_to_drop);
  1114. return true;
  1115. };
  1116. if (context.dib.core.height < 0) {
  1117. // BMP is stored top-down
  1118. for (u32 row = 0; row < height; ++row) {
  1119. if (!process_row(row))
  1120. return false;
  1121. }
  1122. } else {
  1123. for (i32 row = height - 1; row >= 0; --row) {
  1124. if (!process_row(row))
  1125. return false;
  1126. }
  1127. }
  1128. for (size_t i = 0; i < context.color_table.size(); ++i)
  1129. context.bitmap->set_palette_color(i, Color::from_rgb(context.color_table[i]));
  1130. context.state = BMPLoadingContext::State::PixelDataDecoded;
  1131. return true;
  1132. }
  1133. static RefPtr<Bitmap> load_bmp_impl(const u8* data, size_t data_size)
  1134. {
  1135. BMPLoadingContext context;
  1136. context.file_bytes = data;
  1137. context.file_size = data_size;
  1138. // Forces a decode of the header, dib, and color table as well
  1139. if (!decode_bmp_pixel_data(context)) {
  1140. context.state = BMPLoadingContext::State::Error;
  1141. return nullptr;
  1142. }
  1143. return context.bitmap;
  1144. }
  1145. BMPImageDecoderPlugin::BMPImageDecoderPlugin(const u8* data, size_t data_size)
  1146. {
  1147. m_context = make<BMPLoadingContext>();
  1148. m_context->file_bytes = data;
  1149. m_context->file_size = data_size;
  1150. }
  1151. BMPImageDecoderPlugin::~BMPImageDecoderPlugin()
  1152. {
  1153. }
  1154. IntSize BMPImageDecoderPlugin::size()
  1155. {
  1156. if (m_context->state == BMPLoadingContext::State::Error)
  1157. return {};
  1158. if (m_context->state < BMPLoadingContext::State::DIBDecoded && !decode_bmp_dib(*m_context))
  1159. return {};
  1160. return { m_context->dib.core.width, abs(m_context->dib.core.height) };
  1161. }
  1162. RefPtr<Gfx::Bitmap> BMPImageDecoderPlugin::bitmap()
  1163. {
  1164. if (m_context->state == BMPLoadingContext::State::Error)
  1165. return nullptr;
  1166. if (m_context->state < BMPLoadingContext::State::PixelDataDecoded && !decode_bmp_pixel_data(*m_context))
  1167. return nullptr;
  1168. VERIFY(m_context->bitmap);
  1169. return m_context->bitmap;
  1170. }
  1171. void BMPImageDecoderPlugin::set_volatile()
  1172. {
  1173. if (m_context->bitmap)
  1174. m_context->bitmap->set_volatile();
  1175. }
  1176. bool BMPImageDecoderPlugin::set_nonvolatile()
  1177. {
  1178. if (!m_context->bitmap)
  1179. return false;
  1180. return m_context->bitmap->set_nonvolatile();
  1181. }
  1182. bool BMPImageDecoderPlugin::sniff()
  1183. {
  1184. return decode_bmp_header(*m_context);
  1185. }
  1186. bool BMPImageDecoderPlugin::is_animated()
  1187. {
  1188. return false;
  1189. }
  1190. size_t BMPImageDecoderPlugin::loop_count()
  1191. {
  1192. return 0;
  1193. }
  1194. size_t BMPImageDecoderPlugin::frame_count()
  1195. {
  1196. return 1;
  1197. }
  1198. ImageFrameDescriptor BMPImageDecoderPlugin::frame(size_t i)
  1199. {
  1200. if (i > 0)
  1201. return { bitmap(), 0 };
  1202. return {};
  1203. }
  1204. }