Bitmap.cpp 15 KB

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