BMPLoader.cpp 43 KB

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