1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "CanvasContext.h"
#include "LayerUserData.h"
#include "Utility.h"
#include "gfxUtils.h"
#include "ipc/WebGPUChild.h"
#include "mozilla/ProfilerMarkers.h"
#include "mozilla/SVGObserverUtils.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/dom/HTMLCanvasElement.h"
#include "mozilla/dom/WebGPUBinding.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/CanvasManagerChild.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/layers/CanvasRenderer.h"
#include "mozilla/layers/CompositableForwarder.h"
#include "mozilla/layers/ImageDataSerializer.h"
#include "mozilla/layers/LayersSurfaces.h"
#include "mozilla/layers/RenderRootStateManager.h"
#include "mozilla/layers/WebRenderCanvasRenderer.h"
#include "nsDisplayList.h"
namespace mozilla {
inline void ImplCycleCollectionTraverse(
nsCycleCollectionTraversalCallback& aCallback,
dom::GPUCanvasConfiguration& aField, const char* aName, uint32_t aFlags) {
aField.TraverseForCC(aCallback, aFlags);
}
inline void ImplCycleCollectionUnlink(dom::GPUCanvasConfiguration& aField) {
aField.UnlinkForCC();
}
} // namespace mozilla
// -
namespace mozilla::webgpu {
NS_IMPL_CYCLE_COLLECTING_ADDREF(CanvasContext)
NS_IMPL_CYCLE_COLLECTING_RELEASE(CanvasContext)
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_WEAK_PTR(CanvasContext, mConfiguration,
mCurrentTexture, mCanvasElement,
mOffscreenCanvas)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(CanvasContext)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsICanvasRenderingContextInternal)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
// -
CanvasContext::CanvasContext() = default;
CanvasContext::~CanvasContext() {
Unconfigure();
RemovePostRefreshObserver();
}
JSObject* CanvasContext::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return dom::GPUCanvasContext_Binding::Wrap(aCx, this, aGivenProto);
}
// -
void CanvasContext::GetCanvas(
dom::OwningHTMLCanvasElementOrOffscreenCanvas& aRetVal) const {
if (mCanvasElement) {
aRetVal.SetAsHTMLCanvasElement() = mCanvasElement;
} else if (mOffscreenCanvas) {
aRetVal.SetAsOffscreenCanvas() = mOffscreenCanvas;
} else {
MOZ_CRASH(
"This should only happen briefly during CC Unlink, and no JS should "
"happen then.");
}
}
// Note: `SetDimensions` assumes it can ignore this `ErrorResult` because the
// format is already validated. Revisit if adding other error cases.
void CanvasContext::Configure(const dom::GPUCanvasConfiguration& aConfig,
ErrorResult& aRv) {
Unconfigure();
// Only the three formats explicitly listed are permitted here (one of which
// is not yet supported).
// https://www.w3.org/TR/webgpu/#supported-context-formats
switch (aConfig.mFormat) {
case dom::GPUTextureFormat::Rgba8unorm:
mGfxFormat = gfx::SurfaceFormat::R8G8B8A8;
break;
case dom::GPUTextureFormat::Bgra8unorm:
mGfxFormat = gfx::SurfaceFormat::B8G8R8A8;
break;
case dom::GPUTextureFormat::Rgba16float:
aRv.ThrowTypeError(
"Canvas texture format `rgba16float` is not yet supported. "
"Subscribe to <https://bugzilla.mozilla.org/show_bug.cgi?id=1834395>"
" for updates on its development in Firefox.");
return;
default:
aRv.ThrowTypeError(
nsPrintfCString("`%s` is not a supported context format.",
dom::GetEnumString(aConfig.mFormat).get()));
return;
}
mConfiguration.reset(new dom::GPUCanvasConfiguration(aConfig));
mRemoteTextureOwnerId = Some(layers::RemoteTextureOwnerId::GetNext());
mUseSharedTextureInSwapChain =
aConfig.mDevice->mSupportSharedTextureInSwapChain;
if (mUseSharedTextureInSwapChain) {
bool client_can_use = wgpu_client_use_shared_texture_in_swapChain(
ConvertTextureFormat(aConfig.mFormat));
if (!client_can_use) {
gfxCriticalNote << "WebGPU: disabling SharedTexture swapchain: \n"
"canvas configuration format not supported";
mUseSharedTextureInSwapChain = false;
}
}
if (!gfx::gfxVars::AllowWebGPUPresentWithoutReadback()) {
gfxCriticalNote
<< "WebGPU: disabling SharedTexture swapchain: \n"
"`dom.webgpu.allow-present-without-readback` pref is false";
mUseSharedTextureInSwapChain = false;
}
#ifdef XP_WIN
// When WebRender does not use hardware acceleration, disable shared texture
// in swap chain. Since compositor device might not exist.
if (gfx::gfxVars::UseSoftwareWebRender() &&
!gfx::gfxVars::AllowSoftwareWebRenderD3D11()) {
gfxCriticalNote << "WebGPU: disabling SharedTexture swapchain: \n"
"WebRender is not using hardware acceleration";
mUseSharedTextureInSwapChain = false;
}
#elif defined(XP_LINUX) && !defined(MOZ_WIDGET_ANDROID)
// When DMABufDevice is not enabled, disable shared texture in swap chain.
const auto& modifiers = gfx::gfxVars::DMABufModifiersARGB();
if (modifiers.IsEmpty()) {
gfxCriticalNote << "WebGPU: disabling SharedTexture swapchain: \n"
"missing GBM_FORMAT_ARGB8888 dmabuf format";
mUseSharedTextureInSwapChain = false;
}
#endif
// buffer count doesn't matter much, will be created on demand
const size_t maxBufferCount = 10;
for (size_t i = 0; i < maxBufferCount; ++i) {
mBufferIds.AppendElement(
ffi::wgpu_client_make_buffer_id(aConfig.mDevice->GetClient()));
}
mCurrentTexture = aConfig.mDevice->InitSwapChain(
mConfiguration.get(), mRemoteTextureOwnerId.ref(), mBufferIds,
mUseSharedTextureInSwapChain, mGfxFormat, mCanvasSize);
if (!mCurrentTexture) {
Unconfigure();
return;
}
mCurrentTexture->mTargetContext = this;
mChild = aConfig.mDevice->GetChild();
if (mCanvasElement) {
mWaitingCanvasRendererInitialized = true;
}
ForceNewFrame();
}
void CanvasContext::Unconfigure() {
if (mChild && mChild->CanSend() && mRemoteTextureOwnerId) {
auto txn_type = layers::ToRemoteTextureTxnType(mFwdTransactionTracker);
auto txn_id = layers::ToRemoteTextureTxnId(mFwdTransactionTracker);
ffi::wgpu_client_swap_chain_drop(
mChild->GetClient(), mRemoteTextureOwnerId->mId, txn_type, txn_id);
for (auto& id : mBufferIds) {
ffi::wgpu_client_free_buffer_id(mChild->GetClient(), id);
}
}
mBufferIds.Clear();
mRemoteTextureOwnerId = Nothing();
mFwdTransactionTracker = nullptr;
mChild = nullptr;
mConfiguration = nullptr;
mCurrentTexture = nullptr;
mGfxFormat = gfx::SurfaceFormat::UNKNOWN;
}
NS_IMETHODIMP CanvasContext::SetDimensions(int32_t aWidth, int32_t aHeight) {
const auto newSize = gfx::IntSize{aWidth, aHeight};
if (newSize == mCanvasSize) return NS_OK; // No-op no-change resizes.
mCanvasSize = newSize;
if (mConfiguration) {
const auto copy = dom::GPUCanvasConfiguration{
*mConfiguration}; // So we can't null it out on ourselves.
// The format in `mConfiguration` was already validated, we won't get an
// error here.
Configure(copy, IgnoredErrorResult());
}
return NS_OK;
}
void CanvasContext::GetConfiguration(
dom::Nullable<dom::GPUCanvasConfiguration>& aRv) {
if (mConfiguration) {
aRv.SetValue(*mConfiguration);
} else {
aRv.SetNull();
}
}
RefPtr<Texture> CanvasContext::GetCurrentTexture(ErrorResult& aRv) {
if (!mCurrentTexture) {
aRv.ThrowInvalidStateError("Canvas not configured");
return nullptr;
}
MOZ_ASSERT(mConfiguration);
MOZ_ASSERT(mRemoteTextureOwnerId.isSome());
if (mNewTextureRequested) {
mNewTextureRequested = false;
mCurrentTexture = mConfiguration->mDevice->CreateTextureForSwapChain(
mConfiguration.get(), mCanvasSize, mRemoteTextureOwnerId.ref());
mCurrentTexture->mTargetContext = this;
}
return mCurrentTexture;
}
void CanvasContext::MaybeQueueSwapChainPresent() {
if (!mConfiguration) {
return;
}
MOZ_ASSERT(mCurrentTexture);
if (mCurrentTexture) {
mChild->NotifyWaitForSubmit(mCurrentTexture->GetId());
}
if (mPendingSwapChainPresent) {
return;
}
mPendingSwapChainPresent = true;
if (mWaitingCanvasRendererInitialized) {
return;
}
InvalidateCanvasContent();
}
Maybe<layers::SurfaceDescriptor> CanvasContext::SwapChainPresent() {
mPendingSwapChainPresent = false;
if (!mChild || !mChild->CanSend() || mRemoteTextureOwnerId.isNothing() ||
!mCurrentTexture) {
return Nothing();
}
mLastRemoteTextureId = Some(layers::RemoteTextureId::GetNext());
mChild->SwapChainPresent(mCurrentTexture->GetId(), *mLastRemoteTextureId,
*mRemoteTextureOwnerId);
if (mUseSharedTextureInSwapChain) {
mCurrentTexture->Destroy();
mNewTextureRequested = true;
}
PROFILER_MARKER_UNTYPED("WebGPU: SwapChainPresent", GRAPHICS_WebGPU);
mChild->FlushQueuedMessages();
return Some(layers::SurfaceDescriptorRemoteTexture(*mLastRemoteTextureId,
*mRemoteTextureOwnerId));
}
bool CanvasContext::UpdateWebRenderCanvasData(
mozilla::nsDisplayListBuilder* aBuilder, WebRenderCanvasData* aCanvasData) {
auto* renderer = aCanvasData->GetCanvasRenderer();
if (renderer && mRemoteTextureOwnerId.isSome() &&
renderer->GetRemoteTextureOwnerId() == mRemoteTextureOwnerId) {
return true;
}
renderer = aCanvasData->CreateCanvasRenderer();
if (!InitializeCanvasRenderer(aBuilder, renderer)) {
// Clear CanvasRenderer of WebRenderCanvasData
aCanvasData->ClearCanvasRenderer();
return false;
}
return true;
}
bool CanvasContext::InitializeCanvasRenderer(
nsDisplayListBuilder* aBuilder, layers::CanvasRenderer* aRenderer) {
if (mRemoteTextureOwnerId.isNothing()) {
return false;
}
layers::CanvasRendererData data;
data.mContext = this;
data.mSize = mCanvasSize;
data.mIsOpaque = false;
data.mRemoteTextureOwnerId = mRemoteTextureOwnerId;
aRenderer->Initialize(data);
aRenderer->SetDirty();
if (mWaitingCanvasRendererInitialized) {
InvalidateCanvasContent();
}
mWaitingCanvasRendererInitialized = false;
return true;
}
mozilla::UniquePtr<uint8_t[]> CanvasContext::GetImageBuffer(
mozilla::CanvasUtils::ImageExtraction aExtractionBehavior,
int32_t* out_format, gfx::IntSize* out_imageSize) {
*out_format = 0;
*out_imageSize = {};
gfxAlphaType any;
RefPtr<gfx::SourceSurface> snapshot = GetSurfaceSnapshot(&any);
if (!snapshot) {
return nullptr;
}
RefPtr<gfx::DataSourceSurface> dataSurface = snapshot->GetDataSurface();
*out_imageSize = dataSurface->GetSize();
if (ShouldResistFingerprinting(RFPTarget::CanvasRandomization)) {
gfxUtils::GetImageBufferWithRandomNoise(dataSurface,
/* aIsAlphaPremultiplied */ true,
GetCookieJarSettings(),
PrincipalOrNull(), &*out_format);
}
return gfxUtils::GetImageBuffer(dataSurface, /* aIsAlphaPremultiplied */ true,
&*out_format);
}
NS_IMETHODIMP CanvasContext::GetInputStream(
const char* aMimeType, const nsAString& aEncoderOptions,
mozilla::CanvasUtils::ImageExtraction aExtractionBehavior,
nsIInputStream** aStream) {
gfxAlphaType any;
RefPtr<gfx::SourceSurface> snapshot = GetSurfaceSnapshot(&any);
if (!snapshot) {
return NS_ERROR_FAILURE;
}
RefPtr<gfx::DataSourceSurface> dataSurface = snapshot->GetDataSurface();
if (ShouldResistFingerprinting(RFPTarget::CanvasRandomization)) {
return gfxUtils::GetInputStreamWithRandomNoise(
dataSurface, /* aIsAlphaPremultiplied */ true, aMimeType,
aEncoderOptions, GetCookieJarSettings(), PrincipalOrNull(), aStream);
}
return gfxUtils::GetInputStream(dataSurface, /* aIsAlphaPremultiplied */ true,
aMimeType, aEncoderOptions, aStream);
}
bool CanvasContext::GetIsOpaque() {
if (!mConfiguration) {
return false;
}
return mConfiguration->mAlphaMode == dom::GPUCanvasAlphaMode::Opaque;
}
already_AddRefed<gfx::SourceSurface> CanvasContext::GetSurfaceSnapshot(
gfxAlphaType* aOutAlphaType) {
const bool isOpaque = GetIsOpaque();
gfx::SurfaceFormat snapshotFormat = mGfxFormat;
if (isOpaque) {
if (aOutAlphaType) {
*aOutAlphaType = gfxAlphaType::Opaque;
}
if (mGfxFormat == gfx::SurfaceFormat::B8G8R8A8) {
snapshotFormat = gfx::SurfaceFormat::B8G8R8X8;
} else if (mGfxFormat == gfx::SurfaceFormat::R8G8B8A8) {
snapshotFormat = gfx::SurfaceFormat::R8G8B8X8;
}
} else {
if (aOutAlphaType) {
*aOutAlphaType = gfxAlphaType::Premult;
}
}
auto* const cm = gfx::CanvasManagerChild::Get();
if (!cm) {
return nullptr;
}
if (!mChild || !mChild->CanSend() || mRemoteTextureOwnerId.isNothing()) {
return nullptr;
}
MOZ_ASSERT(mRemoteTextureOwnerId.isSome());
// The parent side needs to create a command encoder which will be submitted
// and dropped right away so we create and release an encoder ID here.
RawId commandEncoderId =
ffi::wgpu_client_make_command_encoder_id(mChild->GetClient());
RawId commandBufferId =
ffi::wgpu_client_make_command_buffer_id(mChild->GetClient());
RefPtr<gfx::DataSourceSurface> snapshot = cm->GetSnapshot(
cm->Id(), mChild->Id(), mRemoteTextureOwnerId, Some(commandEncoderId),
Some(commandBufferId), snapshotFormat, /* aPremultiply */ false,
/* aYFlip */ false);
ffi::wgpu_client_free_command_encoder_id(mChild->GetClient(),
commandEncoderId);
ffi::wgpu_client_free_command_buffer_id(mChild->GetClient(), commandBufferId);
if (!snapshot) {
return nullptr;
}
// Clear alpha channel to 0xFF / 1.0 for opaque contexts.
// https://www.w3.org/TR/webgpu/#abstract-opdef-get-a-copy-of-the-image-contents-of-a-context
if (isOpaque) {
gfx::DataSourceSurface::ScopedMap map(snapshot,
gfx::DataSourceSurface::WRITE);
if (!map.IsMapped()) {
return nullptr;
}
for (int32_t y = 0; y < snapshot->GetSize().height; y++) {
for (int32_t x = 0; x < snapshot->GetSize().width; x++) {
uint8_t* const pixel = map.GetData() + y * map.GetStride() + x * 4;
pixel[3] = 0xFF;
}
}
}
return snapshot.forget();
}
Maybe<layers::SurfaceDescriptor> CanvasContext::GetFrontBuffer(
WebGLFramebufferJS*, const bool) {
if (mPendingSwapChainPresent) {
auto desc = SwapChainPresent();
MOZ_ASSERT(!mPendingSwapChainPresent);
return desc;
}
return Nothing();
}
already_AddRefed<layers::FwdTransactionTracker>
CanvasContext::UseCompositableForwarder(
layers::CompositableForwarder* aForwarder) {
return layers::FwdTransactionTracker::GetOrCreate(mFwdTransactionTracker);
}
void CanvasContext::ForceNewFrame() {
if (!mCanvasElement && !mOffscreenCanvas) {
return;
}
// Force a new frame to be built, which will execute the
// `CanvasContextType::WebGPU` switch case in `CreateWebRenderCommands` and
// populate the WR user data.
if (mCanvasElement) {
mCanvasElement->InvalidateCanvas();
} else if (mOffscreenCanvas) {
dom::OffscreenCanvasDisplayData data;
data.mSize = mCanvasSize;
data.mIsOpaque = false;
mOffscreenCanvas->UpdateDisplayData(data);
}
}
void CanvasContext::InvalidateCanvasContent() {
if (!mCanvasElement && !mOffscreenCanvas) {
MOZ_ASSERT_UNREACHABLE("unexpected to be called");
return;
}
if (mCanvasElement) {
SVGObserverUtils::InvalidateDirectRenderingObservers(mCanvasElement);
mCanvasElement->InvalidateCanvasContent(nullptr);
} else if (mOffscreenCanvas) {
mOffscreenCanvas->QueueCommitToCompositor();
}
}
} // namespace mozilla::webgpu
|