BMPLoader.cpp 43 KB

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