Bitmap.cpp 17 KB

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