BMPLoader.cpp 44 KB

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