BMPLoader.cpp 43 KB

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