BMPLoader.cpp 44 KB

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