Bitmap.cpp 17 KB

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