Bitmap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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 physical_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 physical_width * element_size;
  69. }
  70. static bool size_would_overflow(BitmapFormat format, const IntSize& size, int scale_factor)
  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 || scale_factor < 1 || scale_factor > 4)
  76. return true;
  77. // In contrast, this check is absolutely necessary:
  78. size_t pitch = Bitmap::minimum_pitch(size.width() * scale_factor, format);
  79. return Checked<size_t>::multiplication_would_overflow(pitch, size.height() * scale_factor);
  80. }
  81. RefPtr<Bitmap> Bitmap::create(BitmapFormat format, const IntSize& size, int scale_factor)
  82. {
  83. auto backing_store = Bitmap::allocate_backing_store(format, size, scale_factor, Purgeable::No);
  84. if (!backing_store.has_value())
  85. return nullptr;
  86. return adopt(*new Bitmap(format, size, scale_factor, Purgeable::No, backing_store.value()));
  87. }
  88. RefPtr<Bitmap> Bitmap::create_purgeable(BitmapFormat format, const IntSize& size, int scale_factor)
  89. {
  90. auto backing_store = Bitmap::allocate_backing_store(format, size, scale_factor, Purgeable::Yes);
  91. if (!backing_store.has_value())
  92. return nullptr;
  93. return adopt(*new Bitmap(format, size, scale_factor, Purgeable::Yes, backing_store.value()));
  94. }
  95. #ifdef __serenity__
  96. RefPtr<Bitmap> Bitmap::create_shareable(BitmapFormat format, const IntSize& size, int scale_factor)
  97. {
  98. if (size_would_overflow(format, size, scale_factor))
  99. return nullptr;
  100. const auto pitch = minimum_pitch(size.width() * scale_factor, format);
  101. const auto data_size = size_in_bytes(pitch, size.height() * scale_factor);
  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, scale_factor, {}, ShouldCloseAnonymousFile::No);
  106. }
  107. #endif
  108. Bitmap::Bitmap(BitmapFormat format, const IntSize& size, int scale_factor, Purgeable purgeable, const BackingStore& backing_store)
  109. : m_size(size)
  110. , m_scale(scale_factor)
  111. , m_data(backing_store.data)
  112. , m_pitch(backing_store.pitch)
  113. , m_format(format)
  114. , m_purgeable(purgeable == Purgeable::Yes)
  115. {
  116. ASSERT(!m_size.is_empty());
  117. ASSERT(!size_would_overflow(format, size, scale_factor));
  118. ASSERT(m_data);
  119. ASSERT(backing_store.size_in_bytes == size_in_bytes());
  120. allocate_palette_from_format(format, {});
  121. m_needs_munmap = true;
  122. }
  123. RefPtr<Bitmap> Bitmap::create_wrapper(BitmapFormat format, const IntSize& size, int scale_factor, size_t pitch, void* data)
  124. {
  125. if (size_would_overflow(format, size, scale_factor))
  126. return nullptr;
  127. return adopt(*new Bitmap(format, size, scale_factor, pitch, data));
  128. }
  129. RefPtr<Bitmap> Bitmap::load_from_file(const StringView& path)
  130. {
  131. #define __ENUMERATE_IMAGE_FORMAT(Name, Ext) \
  132. if (path.ends_with(Ext, CaseSensitivity::CaseInsensitive)) \
  133. return load_##Name(path);
  134. ENUMERATE_IMAGE_FORMATS
  135. #undef __ENUMERATE_IMAGE_FORMAT
  136. return nullptr;
  137. }
  138. Bitmap::Bitmap(BitmapFormat format, const IntSize& size, int scale_factor, size_t pitch, void* data)
  139. : m_size(size)
  140. , m_scale(scale_factor)
  141. , m_data(data)
  142. , m_pitch(pitch)
  143. , m_format(format)
  144. {
  145. ASSERT(pitch >= minimum_pitch(size.width() * scale_factor, format));
  146. ASSERT(!size_would_overflow(format, size, scale_factor));
  147. // FIXME: assert that `data` is actually long enough!
  148. allocate_palette_from_format(format, {});
  149. }
  150. static bool check_size(const IntSize& size, int scale_factor, 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() * scale_factor, format) * size.height() * scale_factor;
  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 {} @ {}x, which demands {} bytes, which rounds up to at most {}.",
  158. static_cast<int>(format),
  159. size,
  160. scale_factor,
  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, int scale_factor, const Vector<RGBA32>& palette, 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, scale_factor))
  181. return nullptr;
  182. const auto pitch = minimum_pitch(size.width() * scale_factor, format);
  183. const auto data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  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, scale_factor, data, palette));
  191. }
  192. /// Read a bitmap as described by:
  193. /// - actual size
  194. /// - width
  195. /// - height
  196. /// - scale_factor
  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. unsigned scale_factor;
  208. BitmapFormat format;
  209. unsigned palette_size;
  210. Vector<RGBA32> palette;
  211. auto read = [&]<typename T>(T& value) {
  212. if (stream.read({ &value, sizeof(T) }) != sizeof(T))
  213. return false;
  214. return true;
  215. };
  216. if (!read(actual_size) || !read(width) || !read(height) || !read(scale_factor) || !read(format) || !read(palette_size))
  217. return nullptr;
  218. if (format > BitmapFormat::RGBA32 || format < BitmapFormat::Indexed1)
  219. return nullptr;
  220. if (!check_size({ width, height }, scale_factor, format, actual_size))
  221. return {};
  222. palette.ensure_capacity(palette_size);
  223. for (size_t i = 0; i < palette_size; ++i) {
  224. if (!read(palette[i]))
  225. return {};
  226. }
  227. if (stream.remaining() < actual_size)
  228. return {};
  229. auto data = stream.bytes().slice(stream.offset(), actual_size);
  230. auto bitmap = Bitmap::create(format, { width, height }, scale_factor);
  231. if (!bitmap)
  232. return {};
  233. bitmap->m_palette = new RGBA32[palette_size];
  234. memcpy(bitmap->m_palette, palette.data(), palette_size * sizeof(RGBA32));
  235. data.copy_to({ bitmap->scanline(0), bitmap->size_in_bytes() });
  236. return bitmap;
  237. }
  238. ByteBuffer Bitmap::serialize_to_byte_buffer() const
  239. {
  240. auto buffer = ByteBuffer::create_uninitialized(4 * sizeof(unsigned) + sizeof(BitmapFormat) + sizeof(RGBA32) * palette_size(m_format) + size_in_bytes());
  241. OutputMemoryStream stream { buffer };
  242. auto write = [&]<typename T>(T value) {
  243. if (stream.write({ &value, sizeof(T) }) != sizeof(T))
  244. return false;
  245. return true;
  246. };
  247. auto palette = palette_to_vector();
  248. if (!write(size_in_bytes()) || !write((unsigned)size().width()) || !write((unsigned)size().height()) || !write((unsigned)scale()) || !write(m_format) || !write((unsigned)palette.size()))
  249. return {};
  250. for (auto& p : palette) {
  251. if (!write(p))
  252. return {};
  253. }
  254. auto size = size_in_bytes();
  255. ASSERT(stream.remaining() == size);
  256. if (stream.write({ scanline(0), size }) != size)
  257. return {};
  258. return buffer;
  259. }
  260. Bitmap::Bitmap(BitmapFormat format, int anon_fd, const IntSize& size, int scale_factor, void* data, const Vector<RGBA32>& palette)
  261. : m_size(size)
  262. , m_scale(scale_factor)
  263. , m_data(data)
  264. , m_pitch(minimum_pitch(size.width() * scale_factor, format))
  265. , m_format(format)
  266. , m_needs_munmap(true)
  267. , m_purgeable(true)
  268. , m_anon_fd(anon_fd)
  269. {
  270. ASSERT(!is_indexed() || !palette.is_empty());
  271. ASSERT(!size_would_overflow(format, size, scale_factor));
  272. if (is_indexed(m_format))
  273. allocate_palette_from_format(m_format, palette);
  274. }
  275. RefPtr<Gfx::Bitmap> Bitmap::clone() const
  276. {
  277. RefPtr<Gfx::Bitmap> new_bitmap {};
  278. if (m_purgeable) {
  279. new_bitmap = Bitmap::create_purgeable(format(), size(), scale());
  280. } else {
  281. new_bitmap = Bitmap::create(format(), size(), scale());
  282. }
  283. if (!new_bitmap) {
  284. return nullptr;
  285. }
  286. ASSERT(size_in_bytes() == new_bitmap->size_in_bytes());
  287. memcpy(new_bitmap->scanline(0), scanline(0), size_in_bytes());
  288. return new_bitmap;
  289. }
  290. RefPtr<Gfx::Bitmap> Bitmap::rotated(Gfx::RotationDirection rotation_direction) const
  291. {
  292. auto new_bitmap = Gfx::Bitmap::create(this->format(), { height(), width() }, scale());
  293. if (!new_bitmap)
  294. return nullptr;
  295. auto w = this->physical_width();
  296. auto h = this->physical_height();
  297. for (int i = 0; i < w; i++) {
  298. for (int j = 0; j < h; j++) {
  299. Color color;
  300. if (rotation_direction == Gfx::RotationDirection::Left)
  301. color = this->get_pixel(w - i - 1, j);
  302. else
  303. color = this->get_pixel(i, h - j - 1);
  304. new_bitmap->set_pixel(j, i, color);
  305. }
  306. }
  307. return new_bitmap;
  308. }
  309. RefPtr<Gfx::Bitmap> Bitmap::flipped(Gfx::Orientation orientation) const
  310. {
  311. auto new_bitmap = Gfx::Bitmap::create(this->format(), { width(), height() }, scale());
  312. if (!new_bitmap)
  313. return nullptr;
  314. auto w = this->physical_width();
  315. auto h = this->physical_height();
  316. for (int i = 0; i < w; i++) {
  317. for (int j = 0; j < h; j++) {
  318. Color color = this->get_pixel(i, j);
  319. if (orientation == Orientation::Vertical)
  320. new_bitmap->set_pixel(i, h - j - 1, color);
  321. else
  322. new_bitmap->set_pixel(w - i - 1, j, color);
  323. }
  324. }
  325. return new_bitmap;
  326. }
  327. #ifdef __serenity__
  328. RefPtr<Bitmap> Bitmap::to_bitmap_backed_by_anon_fd() const
  329. {
  330. if (m_anon_fd != -1)
  331. return *this;
  332. auto anon_fd = anon_create(round_up_to_power_of_two(size_in_bytes(), PAGE_SIZE), O_CLOEXEC);
  333. if (anon_fd < 0)
  334. return nullptr;
  335. auto bitmap = Bitmap::create_with_anon_fd(m_format, anon_fd, size(), scale(), palette_to_vector(), ShouldCloseAnonymousFile::No);
  336. if (!bitmap)
  337. return nullptr;
  338. memcpy(bitmap->scanline(0), scanline(0), size_in_bytes());
  339. return bitmap;
  340. }
  341. #endif
  342. Bitmap::~Bitmap()
  343. {
  344. if (m_needs_munmap) {
  345. int rc = munmap(m_data, size_in_bytes());
  346. ASSERT(rc == 0);
  347. }
  348. if (m_anon_fd != -1) {
  349. int rc = close(m_anon_fd);
  350. ASSERT(rc == 0);
  351. }
  352. m_data = nullptr;
  353. delete[] m_palette;
  354. }
  355. void Bitmap::set_mmap_name([[maybe_unused]] const StringView& name)
  356. {
  357. ASSERT(m_needs_munmap);
  358. #ifdef __serenity__
  359. ::set_mmap_name(m_data, size_in_bytes(), name.to_string().characters());
  360. #endif
  361. }
  362. void Bitmap::fill(Color color)
  363. {
  364. ASSERT(!is_indexed(m_format));
  365. for (int y = 0; y < physical_height(); ++y) {
  366. auto* scanline = this->scanline(y);
  367. fast_u32_fill(scanline, color.value(), physical_width());
  368. }
  369. }
  370. void Bitmap::set_volatile()
  371. {
  372. ASSERT(m_purgeable);
  373. if (m_volatile)
  374. return;
  375. #ifdef __serenity__
  376. int rc = madvise(m_data, size_in_bytes(), MADV_SET_VOLATILE);
  377. if (rc < 0) {
  378. perror("madvise(MADV_SET_VOLATILE)");
  379. ASSERT_NOT_REACHED();
  380. }
  381. #endif
  382. m_volatile = true;
  383. }
  384. [[nodiscard]] bool Bitmap::set_nonvolatile()
  385. {
  386. ASSERT(m_purgeable);
  387. if (!m_volatile)
  388. return true;
  389. #ifdef __serenity__
  390. int rc = madvise(m_data, size_in_bytes(), MADV_SET_NONVOLATILE);
  391. if (rc < 0) {
  392. perror("madvise(MADV_SET_NONVOLATILE)");
  393. ASSERT_NOT_REACHED();
  394. }
  395. #else
  396. int rc = 0;
  397. #endif
  398. m_volatile = false;
  399. return rc == 0;
  400. }
  401. #ifdef __serenity__
  402. ShareableBitmap Bitmap::to_shareable_bitmap() const
  403. {
  404. auto bitmap = to_bitmap_backed_by_anon_fd();
  405. if (!bitmap)
  406. return {};
  407. return ShareableBitmap(*bitmap);
  408. }
  409. #endif
  410. Optional<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, const IntSize& size, int scale_factor, [[maybe_unused]] Purgeable purgeable)
  411. {
  412. if (size_would_overflow(format, size, scale_factor))
  413. return {};
  414. const auto pitch = minimum_pitch(size.width() * scale_factor, format);
  415. const auto data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);
  416. int map_flags = MAP_ANONYMOUS | MAP_PRIVATE;
  417. if (purgeable == Purgeable::Yes)
  418. map_flags |= MAP_NORESERVE;
  419. #ifdef __serenity__
  420. 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());
  421. #else
  422. void* data = mmap(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0);
  423. #endif
  424. if (data == MAP_FAILED) {
  425. perror("mmap");
  426. return {};
  427. }
  428. return { { data, pitch, data_size_in_bytes } };
  429. }
  430. void Bitmap::allocate_palette_from_format(BitmapFormat format, const Vector<RGBA32>& source_palette)
  431. {
  432. size_t size = palette_size(format);
  433. if (size == 0)
  434. return;
  435. m_palette = new RGBA32[size];
  436. if (!source_palette.is_empty()) {
  437. ASSERT(source_palette.size() == size);
  438. memcpy(m_palette, source_palette.data(), size * sizeof(RGBA32));
  439. }
  440. }
  441. Vector<RGBA32> Bitmap::palette_to_vector() const
  442. {
  443. Vector<RGBA32> vector;
  444. auto size = palette_size(m_format);
  445. vector.ensure_capacity(size);
  446. for (size_t i = 0; i < size; ++i)
  447. vector.unchecked_append(palette_color(i).value());
  448. return vector;
  449. }
  450. }