BMPLoader.cpp 42 KB

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