Truly independent web browser
/*
* Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AnyOf.h>
#include <AK/NeverDestroyed.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/RefPtr.h>
#include <AK/Time.h>
#include <Compositor/PaintingSurface.h>
#include <LibGfx/Bitmap.h>
#ifdef USE_DIRECTX
# include <LibGfx/Direct3DContext.h>
#endif
#include <Compositor/SkiaBackendContext.h>
#include <core/SkSurface.h>
#include <gpu/ganesh/GrContextOptions.h>
#include <gpu/ganesh/GrDirectContext.h>
#ifdef USE_DIRECTX
# include <AK/Windows.h>
# include <gpu/ganesh/d3d/GrD3DBackendContext.h>
# include <gpu/ganesh/d3d/GrD3DDirectContext.h>
#endif
#ifdef USE_VULKAN
# include <Compositor/SkiaVulkanMemoryAllocator.h>
# include <gpu/MutableTextureState.h>
# include <gpu/ganesh/vk/GrVkDirectContext.h>
# include <gpu/vk/VulkanBackendContext.h>
# include <gpu/vk/VulkanExtensions.h>
# include <gpu/vk/VulkanMutableTextureState.h>
# include <string.h>
template<>
constexpr bool AllocatedWithSystemAllocator<skgpu::VulkanExtensions> = true;
#endif
#ifdef AK_OS_MACOS
# include <gpu/ganesh/GrBackendSurface.h>
# include <gpu/ganesh/mtl/GrMtlBackendContext.h>
# include <gpu/ganesh/mtl/GrMtlBackendSurface.h>
# include <gpu/ganesh/mtl/GrMtlDirectContext.h>
#endif
namespace Gfx {
#if defined(AK_OS_MACOS) || defined(USE_DIRECTX) || defined(USE_VULKAN)
static constexpr size_t skia_resource_cache_limit = 256 * MiB;
#endif
static constexpr auto skia_deferred_cleanup_interval = AK::Duration::from_seconds(1);
static constexpr auto skia_aggressive_cleanup_interval = AK::Duration::from_seconds(5);
static constexpr auto skia_deferred_cleanup_resource_age = std::chrono::seconds(5);
static constexpr auto skia_idle_cleanup_delay = AK::Duration::from_seconds(6);
static constexpr auto skia_resource_cache_high_watermark = 384 * MiB;
static constexpr auto skia_resource_cache_critical_watermark = 512 * MiB;
static auto& main_thread_context()
{
static NeverDestroyed<RefPtr<SkiaBackendContext>> context;
return *context;
}
static void invoke_async_flush_callback(void* context)
{
auto* callback = static_cast<Function<void()>*>(context);
auto callback_to_invoke = move(*callback);
delete callback;
callback_to_invoke();
}
static SkSurfaces::BackendSurfaceAccess backend_access_for(PaintingSurface const& surface)
{
// Only an image shared with another process is handed over for presentation. A render target Skia allocated
// itself is read back instead, and it has no memory to present if allocating it failed during the flush.
return surface.wraps_shared_image() ? SkSurfaces::BackendSurfaceAccess::kPresent : SkSurfaces::BackendSurfaceAccess::kNoAccess;
}
void SkiaBackendContext::check_async_work_completion()
{
if (auto* context = sk_context())
context->checkAsyncWorkCompletion();
}
#ifdef USE_VULKAN
// The external queue family only reaches the same device and driver. Anything else takes the foreign one, which not
// every device has.
static u32 queue_family_receiving_shared_images(VulkanContext const& vulkan_context)
{
auto has_foreign_queue_family = any_of(vulkan_context.enabled_device_extensions, [](char const* extension) {
return strcmp(extension, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME) == 0;
});
return !vulkan_context.is_preferred_device && has_foreign_queue_family ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_EXTERNAL;
}
#endif
static void flush_surface(SkiaBackendContext& backend_context, PaintingSurface& surface, GrFlushInfo const& flush_info)
{
auto& context = *backend_context.sk_context();
#ifdef USE_VULKAN
// NB: A driver can keep an image compressed in memory that only it knows about, even when the image's layout has
// no compression. It only writes the actual pixels out once the image is released to another owner, so without
// this, whoever else reads the shared image's memory sees the compressed data.
if (surface.wraps_shared_image()) {
auto const handed_over_state = skgpu::MutableTextureStates::MakeVulkan(VK_IMAGE_LAYOUT_GENERAL, queue_family_receiving_shared_images(backend_context.vulkan_context()));
context.flush(&surface.sk_surface(), flush_info, &handed_over_state);
return;
}
#endif
context.flush(&surface.sk_surface(), backend_access_for(surface), flush_info);
}
void SkiaBackendContext::flush_and_submit(PaintingSurface& surface)
{
auto& context = *sk_context();
flush_surface(*this, surface, {});
context.submit(GrSyncCpu::kYes);
perform_post_flush_cleanup();
}
void SkiaBackendContext::flush_and_submit_async(PaintingSurface& surface, Function<void()>&& callback)
{
auto& context = *sk_context();
GrFlushInfo flush_info {};
flush_info.fFinishedProc = invoke_async_flush_callback;
flush_info.fFinishedContext = new Function<void()>(move(callback));
flush_surface(*this, surface, flush_info);
VERIFY(context.submit(GrSyncCpu::kNo));
perform_post_flush_cleanup();
}
void SkiaBackendContext::flush_and_submit_async(Function<void()>&& callback)
{
auto& context = *sk_context();
GrFlushInfo flush_info {};
flush_info.fFinishedProc = invoke_async_flush_callback;
flush_info.fFinishedContext = new Function<void()>(move(callback));
context.flush(flush_info);
VERIFY(context.submit(GrSyncCpu::kNo));
perform_post_flush_cleanup();
}
void SkiaBackendContext::perform_post_flush_cleanup()
{
auto* context = sk_context();
if (!context)
return;
static thread_local Optional<MonotonicTime> s_last_deferred_cleanup;
static thread_local Optional<MonotonicTime> s_last_aggressive_cleanup;
auto const now = MonotonicTime::now();
if (s_last_deferred_cleanup.has_value() && now - *s_last_deferred_cleanup < skia_deferred_cleanup_interval)
return;
s_last_deferred_cleanup = now;
context->performDeferredCleanup(skia_deferred_cleanup_resource_age);
if (!m_idle_cleanup_timer) {
m_idle_cleanup_timer = Core::Timer::create_single_shot(skia_idle_cleanup_delay, [this] {
auto& context = *sk_context();
context.checkAsyncWorkCompletion();
context.purgeUnlockedResources(GrPurgeResourceOptions::kAllResources);
});
}
m_idle_cleanup_timer->restart();
size_t resource_bytes = 0;
context->getResourceCacheUsage(nullptr, &resource_bytes);
if (resource_bytes < skia_resource_cache_high_watermark)
return;
if (s_last_aggressive_cleanup.has_value() && now - *s_last_aggressive_cleanup < skia_aggressive_cleanup_interval)
return;
s_last_aggressive_cleanup = now;
context->performDeferredCleanup(std::chrono::milliseconds(0));
context->getResourceCacheUsage(nullptr, &resource_bytes);
if (resource_bytes >= skia_resource_cache_critical_watermark)
context->purgeUnlockedResources(GrPurgeResourceOptions::kScratchResourcesOnly);
}
size_t SkiaBackendContext::resource_cache_bytes() const
{
size_t bytes = 0;
if (auto* context = sk_context())
context->getResourceCacheUsage(nullptr, &bytes);
return bytes;
}
bool SkiaBackendContext::can_hold_texture_of_size(IntSize size) const
{
auto* context = sk_context();
if (!context)
return false;
auto max_texture_size = context->maxTextureSize();
return size.width() <= max_texture_size && size.height() <= max_texture_size;
}
void SkiaBackendContext::initialize_gpu_backend(Optional<GpuDeviceIdentity> const& preferred_device)
{
VERIFY(!main_thread_context());
main_thread_context() = create_independent_gpu_backend(preferred_device);
}
RefPtr<SkiaBackendContext> SkiaBackendContext::create_independent_gpu_backend([[maybe_unused]] Optional<GpuDeviceIdentity> const& preferred_device)
{
#ifdef AK_OS_MACOS
auto metal_context = get_metal_context();
if (!metal_context)
return {};
return create_metal_context(*metal_context);
#elif defined(USE_DIRECTX)
auto maybe_direct3d_context = Gfx::create_direct3d_context();
if (maybe_direct3d_context.is_error()) {
dbgln("Direct3D 12 context creation failed: {}", maybe_direct3d_context.error());
return {};
}
return create_direct3d_context(maybe_direct3d_context.release_value());
#elif defined(USE_VULKAN)
auto maybe_vulkan_context = Gfx::create_vulkan_context(preferred_device);
if (maybe_vulkan_context.is_error()) {
dbgln("Vulkan context creation failed: {}", maybe_vulkan_context.error());
return {};
}
auto vulkan_context = maybe_vulkan_context.release_value();
return create_vulkan_context(vulkan_context);
#else
return {};
#endif
}
RefPtr<SkiaBackendContext> SkiaBackendContext::the_main_thread_context()
{
return main_thread_context();
}
#ifdef USE_DIRECTX
class SkiaDirect3DBackendContext final : public SkiaBackendContext {
AK_MAKE_NONCOPYABLE(SkiaDirect3DBackendContext);
AK_MAKE_NONMOVABLE(SkiaDirect3DBackendContext);
public:
SkiaDirect3DBackendContext(sk_sp<GrDirectContext> context, NonnullRefPtr<Direct3DContext> direct3d_context)
: m_context(move(context))
, m_direct3d_context(move(direct3d_context))
{
}
~SkiaDirect3DBackendContext() override
{
m_context.reset();
}
GrDirectContext* sk_context() const override { return m_context.get(); }
VulkanContext const& vulkan_context() override { VERIFY_NOT_REACHED(); }
MetalContext& metal_context() override { VERIFY_NOT_REACHED(); }
Direct3DContext& direct3d_context() override { return m_direct3d_context; }
private:
sk_sp<GrDirectContext> m_context;
NonnullRefPtr<Direct3DContext> m_direct3d_context;
};
RefPtr<SkiaBackendContext> SkiaBackendContext::create_direct3d_context(NonnullRefPtr<Direct3DContext> direct3d_context)
{
GrD3DBackendContext backend_context;
backend_context.fAdapter.retain(direct3d_context->adapter());
backend_context.fDevice.retain(direct3d_context->device());
backend_context.fQueue.retain(direct3d_context->queue());
backend_context.fProtectedContext = GrProtected::kNo;
auto context = GrDirectContexts::MakeD3D(backend_context);
if (!context) {
dbgln("Skia Direct3D context creation failed");
return {};
}
context->setResourceCacheLimit(skia_resource_cache_limit);
return adopt_ref(*new SkiaDirect3DBackendContext(move(context), move(direct3d_context)));
}
#endif
#ifdef USE_VULKAN
class SkiaVulkanBackendContext final : public SkiaBackendContext {
AK_MAKE_NONCOPYABLE(SkiaVulkanBackendContext);
AK_MAKE_NONMOVABLE(SkiaVulkanBackendContext);
public:
SkiaVulkanBackendContext(sk_sp<GrDirectContext> context, VulkanContext const& vulkan_context, NonnullOwnPtr<skgpu::VulkanExtensions> extensions)
: m_context(move(context))
, m_extensions(move(extensions))
, m_vulkan_context(vulkan_context)
{
}
~SkiaVulkanBackendContext() override
{
m_context.reset();
# ifdef USE_VULKAN_DMABUF_IMAGES
if (m_vulkan_context.command_pool != VK_NULL_HANDLE)
vkDestroyCommandPool(m_vulkan_context.logical_device, m_vulkan_context.command_pool, nullptr);
# endif
if (m_vulkan_context.logical_device != VK_NULL_HANDLE)
vkDestroyDevice(m_vulkan_context.logical_device, nullptr);
if (m_vulkan_context.instance != VK_NULL_HANDLE)
vkDestroyInstance(m_vulkan_context.instance, nullptr);
}
skgpu::VulkanExtensions const* extensions() const { return m_extensions.ptr(); }
GrDirectContext* sk_context() const override { return m_context.get(); }
VulkanContext const& vulkan_context() override { return m_vulkan_context; }
MetalContext& metal_context() override { VERIFY_NOT_REACHED(); }
private:
sk_sp<GrDirectContext> m_context;
NonnullOwnPtr<skgpu::VulkanExtensions> m_extensions;
VulkanContext const m_vulkan_context;
};
RefPtr<SkiaBackendContext> SkiaBackendContext::create_vulkan_context(VulkanContext const& vulkan_context)
{
skgpu::VulkanBackendContext backend_context;
backend_context.fInstance = vulkan_context.instance;
backend_context.fDevice = vulkan_context.logical_device;
backend_context.fQueue = vulkan_context.graphics_queue;
backend_context.fGraphicsQueueIndex = vulkan_context.graphics_queue_family;
backend_context.fPhysicalDevice = vulkan_context.physical_device;
backend_context.fMaxAPIVersion = vulkan_context.api_version;
backend_context.fGetProc = [](char const* proc_name, VkInstance instance, VkDevice device) {
if (device != VK_NULL_HANDLE) {
return vkGetDeviceProcAddr(device, proc_name);
}
return vkGetInstanceProcAddr(instance, proc_name);
};
auto extensions = make<skgpu::VulkanExtensions>();
extensions->init(backend_context.fGetProc, vulkan_context.instance, vulkan_context.physical_device, 0, nullptr, vulkan_context.enabled_device_extensions.size(), vulkan_context.enabled_device_extensions.data());
backend_context.fVkExtensions = extensions.ptr();
// Skia samples through a YCbCr conversion only once it knows the device has that enabled.
VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcr_conversion_features {};
ycbcr_conversion_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
ycbcr_conversion_features.samplerYcbcrConversion = vulkan_context.can_sample_through_ycbcr_conversion ? VK_TRUE : VK_FALSE;
VkPhysicalDeviceFeatures2 features {};
features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
features.pNext = &ycbcr_conversion_features;
backend_context.fDeviceFeatures2 = &features;
backend_context.fMemoryAllocator = create_skia_vulkan_memory_allocator(vulkan_context);
VERIFY(backend_context.fMemoryAllocator);
GrContextOptions options;
options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo;
sk_sp<GrDirectContext> ctx = GrDirectContexts::MakeVulkan(backend_context, options);
VERIFY(ctx);
ctx->setResourceCacheLimit(skia_resource_cache_limit);
return adopt_ref(*new SkiaVulkanBackendContext(ctx, vulkan_context, move(extensions)));
}
#endif
#ifdef AK_OS_MACOS
class SkiaMetalBackendContext final : public SkiaBackendContext {
AK_MAKE_NONCOPYABLE(SkiaMetalBackendContext);
AK_MAKE_NONMOVABLE(SkiaMetalBackendContext);
public:
SkiaMetalBackendContext(sk_sp<GrDirectContext> context, NonnullRefPtr<MetalContext> metal_context)
: m_context(move(context))
, m_metal_context(move(metal_context))
{
}
~SkiaMetalBackendContext() override
{
m_context.reset();
}
GrDirectContext* sk_context() const override { return m_context.get(); }
VulkanContext const& vulkan_context() override { VERIFY_NOT_REACHED(); }
MetalContext& metal_context() override { return m_metal_context; }
private:
sk_sp<GrDirectContext> m_context;
NonnullRefPtr<MetalContext> m_metal_context;
};
RefPtr<SkiaBackendContext> SkiaBackendContext::create_metal_context(NonnullRefPtr<MetalContext> metal_context)
{
GrMtlBackendContext backend_context;
backend_context.fDevice.retain(metal_context->device());
backend_context.fQueue.retain(metal_context->queue());
sk_sp<GrDirectContext> ctx = GrDirectContexts::MakeMetal(backend_context);
VERIFY(ctx);
ctx->setResourceCacheLimit(skia_resource_cache_limit);
return adopt_ref(*new SkiaMetalBackendContext(move(ctx), move(metal_context)));
}
#endif
}