Bitmap.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  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/Checked.h>
  27. #include <AK/LexicalPath.h>
  28. #include <AK/Memory.h>
  29. #include <AK/MemoryStream.h>
  30. #include <AK/Optional.h>
  31. #include <AK/ScopeGuard.h>
  32. #include <AK/String.h>
  33. #include <LibGfx/BMPLoader.h>
  34. #include <LibGfx/Bitmap.h>
  35. #include <LibGfx/GIFLoader.h>
  36. #include <LibGfx/ICOLoader.h>
  37. #include <LibGfx/JPGLoader.h>
  38. #include <LibGfx/PBMLoader.h>
  39. #include <LibGfx/PGMLoader.h>
  40. #include <LibGfx/PNGLoader.h>
  41. #include <LibGfx/PPMLoader.h>
  42. #include <LibGfx/ShareableBitmap.h>
  43. #include <fcntl.h>
  44. #include <stdio.h>
  45. #include <sys/mman.h>
  46. #ifdef __serenity__
  47. # include <serenity.h>
  48. #endif
  49. namespace Gfx {
  50. struct BackingStore {
  51. void* data { nullptr };
  52. size_t pitch { 0 };
  53. size_t size_in_bytes { 0 };
  54. };
  55. size_t Bitmap::minimum_pitch(size_t physical_width, BitmapFormat format)
  56. {
  57. size_t element_size;
  58. switch (determine_storage_format(format)) {
  59. case StorageFormat::Indexed8:
  60. element_size = 1;
  61. break;
  62. case StorageFormat::RGB32:
  63. case StorageFormat::RGBA32:
  64. element_size = 4;
  65. break;
  66. default:
  67. ASSERT_NOT_REACHED();
  68. }
  69. return physical_width * element_size;
  70. }
  71. static bool size_would_overflow(BitmapFormat format, const IntSize& size, int scale_factor)
  72. {
  73. if (size.width() < 0 || size.height() < 0)
  74. return true;
  75. // This check is a bit arbitrary, but should protect us from most shenanigans:
  76. if (size.width() >= 32768 || size.height() >= 32768 || scale_factor < 1 || scale_factor > 4)
  77. return true;
  78. // In contrast, this check is absolutely necessary:
  79. size_t pitch = Bitmap::minimum_pitch(size.width() * scale_factor, format);
  80. return Checked<size_t>::multiplication_would_overflow(pitch, size.height() * scale_factor);
  81. }
  82. RefPtr<Bitmap> Bitmap::create(BitmapFormat format, const IntSize& size, int scale_factor)
  83. {
  84. auto backing_store = Bitmap::allocate_backing_store(format, size, scale_factor, Purgeable::No);
  85. if (!backing_store.has_value())
  86. return nullptr;
  87. return adopt(*new Bitmap(format, size, scale_factor, Purgeable::No, backing_store.value()));
  88. }
  89. RefPtr<Bitmap> Bitmap::create_purgeable(BitmapFormat format, const IntSize& size, int scale_factor)
  90. {
  91. auto backing_store = Bitmap::allocate_backing_store(format, size, scale_factor, Purgeable::Yes);
  92. if (!backing_store.has_value())
  93. return nullptr;
  94. return adopt(*new Bitmap(format, size, scale_factor, Purgeable::Yes, backing_store.value()));
  95. }
  96. #ifdef __serenity__
  97. RefPtr<Bitmap> Bitmap::create_shareable(BitmapFormat format, const IntSize& size, int scale_factor)
  98. {
  99. if (size_would_overflow(format, size, scale_factor))
  100. return nullptr;
  101. const auto pitch = minimum_pitch(size.width() * scale_factor, format);
  102. const auto data_size = size_in_bytes(pitch, size.height() * scale_factor);
  103. auto anon_fd = anon_create(round_up_to_power_of_two(data_size, PAGE_SIZE), O_CLOEXEC);
  104. if (anon_fd < 0)
  105. return nullptr;
  106. return Bitmap::create_with_anon_fd(format, anon_fd, size, scale_factor, {}, ShouldCloseAnonymousFile::No);
  107. }
  108. #endif
  109. Bitmap::Bitmap(BitmapFormat format, const IntSize& size, int scale_factor, Purgeable purgeable, const BackingStore& backing_store)
  110. : m_size(size)
  111. , m_scale(scale_factor)
  112. , m_data(backing_store.data)
  113. , m_pitch(backing_store.pitch)
  114. , m_format(format)
  115. , m_purgeable(purgeable == Purgeable::Yes)
  116. {
  117. ASSERT(!m_size.is_empty());
  118. ASSERT(!size_would_overflow(format, size, scale_factor));
  119. ASSERT(m_data);
  120. ASSERT(backing_store.size_in_bytes == size_in_bytes());
  121. allocate_palette_from_format(format, {});
  122. m_needs_munmap = true;
  123. }
  124. RefPtr<Bitmap> Bitmap::create_wrapper(BitmapFormat format, const IntSize& size, int scale_factor, size_t pitch, void* data)
  125. {
  126. if (size_would_overflow(format, size, scale_factor))
  127. return nullptr;
  128. return adopt(*new Bitmap(format, size, scale_factor, pitch, data));
  129. }
  130. RefPtr<Bitmap> Bitmap::load_from_file(const StringView& path, int scale_factor)
  131. {
  132. if (scale_factor > 1 && path.starts_with("/res/")) {
  133. LexicalPath lexical_path { path };
  134. StringBuilder highdpi_icon_path;
  135. highdpi_icon_path.append(lexical_path.dirname());
  136. highdpi_icon_path.append("/");
  137. highdpi_icon_path.append(lexical_path.title());
  138. highdpi_icon_path.appendf("-%dx.", scale_factor);
  139. highdpi_icon_path.append(lexical_path.extension());
  140. RefPtr<Bitmap> bmp;
  141. #define __ENUMERATE_IMAGE_FORMAT(Name, Ext) \
  142. if (path.ends_with(Ext, CaseSensitivity::CaseInsensitive)) \
  143. bmp = load_##Name(highdpi_icon_path.to_string());
  144. ENUMERATE_IMAGE_FORMATS
  145. #undef __ENUMERATE_IMAGE_FORMAT
  146. if (bmp) {
  147. ASSERT(bmp->width() % scale_factor == 0);
  148. ASSERT(bmp->height() % scale_factor == 0);
  149. bmp->m_size.set_width(bmp->width() / scale_factor);
  150. bmp->m_size.set_height(bmp->height() / scale_factor);
  151. bmp->m_scale = scale_factor;
  152. return bmp;
  153. }
  154. }
  155. #define __ENUMERATE_IMAGE_FORMAT(Name, Ext) \
  156. if (path.ends_with(Ext, CaseSensitivity::CaseInsensitive)) \
  157. return load_##Name(path);
  158. ENUMERATE_IMAGE_FORMATS
  159. #undef __ENUMERATE_IMAGE_FORMAT
  160. return nullptr;
  161. }
  162. Bitmap::Bitmap(BitmapFormat format, const IntSize& size, int scale_factor, size_t pitch, void* data)
  163. : m_size(size)
  164. , m_scale(scale_factor)
  165. , m_data(data)
  166. , m_pitch(pitch)
  167. , m_format(format)
  168. {
  169. ASSERT(pitch >= minimum_pitch(size.width() * scale_factor, format));
  170. ASSERT(!size_would_overflow(format, size, scale_factor));
  171. // FIXME: assert that `data` is actually long enough!
  172. allocate_palette_from_format(format, {});
  173. }
  174. static bool check_size(const IntSize& size, int scale_factor, BitmapFormat format, unsigned actual_size)
  175. {
  176. // FIXME: Code duplication of size_in_bytes() and m_pitch
  177. unsigned expected_size_min = Bitmap::minimum_pitch(size.width() * scale_factor, format) * size.height() * scale_factor;
  178. unsigned expected_size_max = round_up_to_power_of_two(expected_size_min, PAGE_SIZE);
  179. if (expected_size_min > actual_size || actual_size > expected_size_max) {
  180. // Getting here is most likely an error.
  181. dbgln("Constructing a shared bitmap for format {} and size {} @ {}x, which demands {} bytes, which rounds up to at most {}.",
  182. static_cast<int>(format),
  183. size,
  184. scale_factor,
  185. expected_size_min,
  186. expected_size_max);
  187. dbgln("However, we were given {} bytes, which is outside this range?! Refusing cowardly.", actual_size);
  188. return false;
  189. }
  190. return true;
  191. }
  192. RefPtr<Bitmap> Bitmap::create_with_anon_fd(BitmapFormat format, int anon_fd, const IntSize& size, int scale_factor, const Vector<RGBA32>& palette, ShouldCloseAnonymousFile should_close_anon_fd)
  193. {
  194. void* data = nullptr;
  195. {
  196. // If ShouldCloseAnonymousFile::Yes, it's our responsibility to close 'anon_fd' no matter what.
  197. ScopeGuard close_guard = [&] {
  198. if (should_close_anon_fd == ShouldCloseAnonymousFile::Yes) {
  199. int rc = close(anon_fd);
  200. ASSERT(rc == 0);
  201. anon_fd = -1;
  202. }
  203. };
  204. if (size_would_overflow(format, size, scale_factor))
  205. return nullptr;
  206. const auto pitch = minimum_pitch(size.width() * scale_factor, format);
  207. const auto data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  208. data = mmap(nullptr, round_up_to_power_of_two(data_size_in_bytes, PAGE_SIZE), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, anon_fd, 0);
  209. if (data == MAP_FAILED) {
  210. perror("mmap");
  211. return nullptr;
  212. }
  213. }
  214. return adopt(*new Bitmap(format, anon_fd, size, scale_factor, data, palette));
  215. }
  216. /// Read a bitmap as described by:
  217. /// - actual size
  218. /// - width
  219. /// - height
  220. /// - scale_factor
  221. /// - format
  222. /// - palette count
  223. /// - palette data (= palette count * RGBA32)
  224. /// - image data (= actual size * u8)
  225. RefPtr<Bitmap> Bitmap::create_from_serialized_byte_buffer(ByteBuffer&& buffer)
  226. {
  227. InputMemoryStream stream { buffer };
  228. unsigned actual_size;
  229. unsigned width;
  230. unsigned height;
  231. unsigned scale_factor;
  232. BitmapFormat format;
  233. unsigned palette_size;
  234. Vector<RGBA32> palette;
  235. auto read = [&]<typename T>(T& value) {
  236. if (stream.read({ &value, sizeof(T) }) != sizeof(T))
  237. return false;
  238. return true;
  239. };
  240. if (!read(actual_size) || !read(width) || !read(height) || !read(scale_factor) || !read(format) || !read(palette_size))
  241. return nullptr;
  242. if (format > BitmapFormat::RGBA32 || format < BitmapFormat::Indexed1)
  243. return nullptr;
  244. if (!check_size({ width, height }, scale_factor, format, actual_size))
  245. return {};
  246. palette.ensure_capacity(palette_size);
  247. for (size_t i = 0; i < palette_size; ++i) {
  248. if (!read(palette[i]))
  249. return {};
  250. }
  251. if (stream.remaining() < actual_size)
  252. return {};
  253. auto data = stream.bytes().slice(stream.offset(), actual_size);
  254. auto bitmap = Bitmap::create(format, { width, height }, scale_factor);
  255. if (!bitmap)
  256. return {};
  257. bitmap->m_palette = new RGBA32[palette_size];
  258. memcpy(bitmap->m_palette, palette.data(), palette_size * sizeof(RGBA32));
  259. data.copy_to({ bitmap->scanline(0), bitmap->size_in_bytes() });
  260. return bitmap;
  261. }
  262. ByteBuffer Bitmap::serialize_to_byte_buffer() const
  263. {
  264. auto buffer = ByteBuffer::create_uninitialized(5 * sizeof(unsigned) + sizeof(BitmapFormat) + sizeof(RGBA32) * palette_size(m_format) + size_in_bytes());
  265. OutputMemoryStream stream { buffer };
  266. auto write = [&]<typename T>(T value) {
  267. if (stream.write({ &value, sizeof(T) }) != sizeof(T))
  268. return false;
  269. return true;
  270. };
  271. auto palette = palette_to_vector();
  272. if (!write(size_in_bytes()) || !write((unsigned)size().width()) || !write((unsigned)size().height()) || !write((unsigned)scale()) || !write(m_format) || !write((unsigned)palette.size()))
  273. return {};
  274. for (auto& p : palette) {
  275. if (!write(p))
  276. return {};
  277. }
  278. auto size = size_in_bytes();
  279. ASSERT(stream.remaining() == size);
  280. if (stream.write({ scanline(0), size }) != size)
  281. return {};
  282. return buffer;
  283. }
  284. Bitmap::Bitmap(BitmapFormat format, int anon_fd, const IntSize& size, int scale_factor, void* data, const Vector<RGBA32>& palette)
  285. : m_size(size)
  286. , m_scale(scale_factor)
  287. , m_data(data)
  288. , m_pitch(minimum_pitch(size.width() * scale_factor, format))
  289. , m_format(format)
  290. , m_needs_munmap(true)
  291. , m_purgeable(true)
  292. , m_anon_fd(anon_fd)
  293. {
  294. ASSERT(!is_indexed() || !palette.is_empty());
  295. ASSERT(!size_would_overflow(format, size, scale_factor));
  296. if (is_indexed(m_format))
  297. allocate_palette_from_format(m_format, palette);
  298. }
  299. RefPtr<Gfx::Bitmap> Bitmap::clone() const
  300. {
  301. RefPtr<Gfx::Bitmap> new_bitmap {};
  302. if (m_purgeable) {
  303. new_bitmap = Bitmap::create_purgeable(format(), size(), scale());
  304. } else {
  305. new_bitmap = Bitmap::create(format(), size(), scale());
  306. }
  307. if (!new_bitmap) {
  308. return nullptr;
  309. }
  310. ASSERT(size_in_bytes() == new_bitmap->size_in_bytes());
  311. memcpy(new_bitmap->scanline(0), scanline(0), size_in_bytes());
  312. return new_bitmap;
  313. }
  314. RefPtr<Gfx::Bitmap> Bitmap::rotated(Gfx::RotationDirection rotation_direction) const
  315. {
  316. auto new_bitmap = Gfx::Bitmap::create(this->format(), { height(), width() }, scale());
  317. if (!new_bitmap)
  318. return nullptr;
  319. auto w = this->physical_width();
  320. auto h = this->physical_height();
  321. for (int i = 0; i < w; i++) {
  322. for (int j = 0; j < h; j++) {
  323. Color color;
  324. if (rotation_direction == Gfx::RotationDirection::Left)
  325. color = this->get_pixel(w - i - 1, j);
  326. else
  327. color = this->get_pixel(i, h - j - 1);
  328. new_bitmap->set_pixel(j, i, color);
  329. }
  330. }
  331. return new_bitmap;
  332. }
  333. RefPtr<Gfx::Bitmap> Bitmap::flipped(Gfx::Orientation orientation) const
  334. {
  335. auto new_bitmap = Gfx::Bitmap::create(this->format(), { width(), height() }, scale());
  336. if (!new_bitmap)
  337. return nullptr;
  338. auto w = this->physical_width();
  339. auto h = this->physical_height();
  340. for (int i = 0; i < w; i++) {
  341. for (int j = 0; j < h; j++) {
  342. Color color = this->get_pixel(i, j);
  343. if (orientation == Orientation::Vertical)
  344. new_bitmap->set_pixel(i, h - j - 1, color);
  345. else
  346. new_bitmap->set_pixel(w - i - 1, j, color);
  347. }
  348. }
  349. return new_bitmap;
  350. }
  351. #ifdef __serenity__
  352. RefPtr<Bitmap> Bitmap::to_bitmap_backed_by_anon_fd() const
  353. {
  354. if (m_anon_fd != -1)
  355. return *this;
  356. auto anon_fd = anon_create(round_up_to_power_of_two(size_in_bytes(), PAGE_SIZE), O_CLOEXEC);
  357. if (anon_fd < 0)
  358. return nullptr;
  359. auto bitmap = Bitmap::create_with_anon_fd(m_format, anon_fd, size(), scale(), palette_to_vector(), ShouldCloseAnonymousFile::No);
  360. if (!bitmap)
  361. return nullptr;
  362. memcpy(bitmap->scanline(0), scanline(0), size_in_bytes());
  363. return bitmap;
  364. }
  365. #endif
  366. Bitmap::~Bitmap()
  367. {
  368. if (m_needs_munmap) {
  369. int rc = munmap(m_data, size_in_bytes());
  370. ASSERT(rc == 0);
  371. }
  372. if (m_anon_fd != -1) {
  373. int rc = close(m_anon_fd);
  374. ASSERT(rc == 0);
  375. }
  376. m_data = nullptr;
  377. delete[] m_palette;
  378. }
  379. void Bitmap::set_mmap_name([[maybe_unused]] const StringView& name)
  380. {
  381. ASSERT(m_needs_munmap);
  382. #ifdef __serenity__
  383. ::set_mmap_name(m_data, size_in_bytes(), name.to_string().characters());
  384. #endif
  385. }
  386. void Bitmap::fill(Color color)
  387. {
  388. ASSERT(!is_indexed(m_format));
  389. for (int y = 0; y < physical_height(); ++y) {
  390. auto* scanline = this->scanline(y);
  391. fast_u32_fill(scanline, color.value(), physical_width());
  392. }
  393. }
  394. void Bitmap::set_volatile()
  395. {
  396. ASSERT(m_purgeable);
  397. if (m_volatile)
  398. return;
  399. #ifdef __serenity__
  400. int rc = madvise(m_data, size_in_bytes(), MADV_SET_VOLATILE);
  401. if (rc < 0) {
  402. perror("madvise(MADV_SET_VOLATILE)");
  403. ASSERT_NOT_REACHED();
  404. }
  405. #endif
  406. m_volatile = true;
  407. }
  408. [[nodiscard]] bool Bitmap::set_nonvolatile()
  409. {
  410. ASSERT(m_purgeable);
  411. if (!m_volatile)
  412. return true;
  413. #ifdef __serenity__
  414. int rc = madvise(m_data, size_in_bytes(), MADV_SET_NONVOLATILE);
  415. if (rc < 0) {
  416. perror("madvise(MADV_SET_NONVOLATILE)");
  417. ASSERT_NOT_REACHED();
  418. }
  419. #else
  420. int rc = 0;
  421. #endif
  422. m_volatile = false;
  423. return rc == 0;
  424. }
  425. #ifdef __serenity__
  426. ShareableBitmap Bitmap::to_shareable_bitmap() const
  427. {
  428. auto bitmap = to_bitmap_backed_by_anon_fd();
  429. if (!bitmap)
  430. return {};
  431. return ShareableBitmap(*bitmap);
  432. }
  433. #endif
  434. Optional<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, const IntSize& size, int scale_factor, [[maybe_unused]] Purgeable purgeable)
  435. {
  436. if (size_would_overflow(format, size, scale_factor))
  437. return {};
  438. const auto pitch = minimum_pitch(size.width() * scale_factor, format);
  439. const auto data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  440. int map_flags = MAP_ANONYMOUS | MAP_PRIVATE;
  441. if (purgeable == Purgeable::Yes)
  442. map_flags |= MAP_NORESERVE;
  443. #ifdef __serenity__
  444. void* data = mmap_with_name(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0, String::format("GraphicsBitmap [%dx%d]", size.width(), size.height()).characters());
  445. #else
  446. void* data = mmap(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0);
  447. #endif
  448. if (data == MAP_FAILED) {
  449. perror("mmap");
  450. return {};
  451. }
  452. return { { data, pitch, data_size_in_bytes } };
  453. }
  454. void Bitmap::allocate_palette_from_format(BitmapFormat format, const Vector<RGBA32>& source_palette)
  455. {
  456. size_t size = palette_size(format);
  457. if (size == 0)
  458. return;
  459. m_palette = new RGBA32[size];
  460. if (!source_palette.is_empty()) {
  461. ASSERT(source_palette.size() == size);
  462. memcpy(m_palette, source_palette.data(), size * sizeof(RGBA32));
  463. }
  464. }
  465. Vector<RGBA32> Bitmap::palette_to_vector() const
  466. {
  467. Vector<RGBA32> vector;
  468. auto size = palette_size(m_format);
  469. vector.ensure_capacity(size);
  470. for (size_t i = 0; i < size; ++i)
  471. vector.unchecked_append(palette_color(i).value());
  472. return vector;
  473. }
  474. }