Bitmap.cpp 16 KB

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