BMPLoader.cpp 44 KB

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