BMPLoader.cpp 42 KB

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