BMPLoader.cpp 44 KB

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