1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef mozilla_layers_NativeLayerCA_h
7 #define mozilla_layers_NativeLayerCA_h
9 #include <IOSurface/IOSurface.h>
12 #include <unordered_map>
15 #include "mozilla/Mutex.h"
16 #include "mozilla/TimeStamp.h"
18 #include "mozilla/gfx/MacIOSurface.h"
19 #include "mozilla/layers/NativeLayer.h"
20 #include "CFTypeRefPtr.h"
22 #include "nsISupportsImpl.h"
37 class RenderMacIOSurfaceTextureHost
;
42 class NativeLayerRootSnapshotterCA
;
43 class SurfacePoolHandleCA
;
45 enum class VideoLowPowerType
{
46 // These must be kept synchronized with the telemetry histogram enums.
47 NotVideo
, // Never emitted as telemetry. No video is visible.
48 LowPower
, // As best we can tell, we are in the "detached",
49 // low-power compositing mode. We don't use "Success"
50 // because of name collision with telemetry generation.
51 FailMultipleVideo
, // There is more than one video visible.
52 FailWindowed
, // The window is not fullscreen.
53 FailOverlaid
, // Something is on top of the video (likely captions).
54 FailBacking
, // The layer behind the video is not full-coverage black.
55 FailMacOSVersion
, // macOS version does not meet requirements.
56 FailPref
, // Pref is not set.
57 FailSurface
, // Surface is not eligible.
58 FailEnqueue
, // Enqueueing the video didn't work.
61 // NativeLayerRootCA is the CoreAnimation implementation of the NativeLayerRoot
62 // interface. A NativeLayerRootCA is created by the widget around an existing
63 // CALayer with a call to CreateForCALayer - this CALayer is the root of the
64 // "onscreen" representation of this layer tree.
65 // All methods can be called from any thread, there is internal locking.
66 // All effects from mutating methods are buffered locally and don't modify the
67 // underlying CoreAnimation layers until CommitToScreen() is called. This
68 // ensures that the modifications happen on the right thread.
70 // More specifically: During normal operation, screen updates are driven from a
71 // compositing thread. On this thread, the layers are created / destroyed, their
72 // contents are painted, and the result is committed to the screen. However,
73 // there are some scenarios that need to involve the main thread, most notably
74 // window resizing: During a window resize, we still need the drawing part to
75 // happen on the compositing thread, but the modifications to the underlying
76 // CALayers need to happen on the main thread, once compositing is done.
78 // NativeLayerRootCA + NativeLayerCA create and maintain *two* CALayer tree
79 // representations: An "onscreen" representation and an "offscreen"
80 // representation. These representations are updated via calls to
81 // CommitToScreen() and CommitOffscreen(), respectively. The reason for having
82 // two representations is the following: Our implementation of the snapshotter
83 // API uses CARenderer, which lets us render the composited result of our layer
84 // tree into a GPU buffer. But CARenderer requires "ownership" of the rendered
85 // CALayers in the sense that it associates the CALayers with a local
86 // "CAContext". A CALayer can only be associated with one CAContext at any time.
87 // If we wanted te render our *onscreen* CALayers with CARenderer, we would need
88 // to remove them from the window, reparent them to the CARenderer, render them,
89 // and then put them back into the window. This would lead to a visible flashing
90 // effect. To solve this problem, we build two CALayer representations, so that
91 // one representation can stay inside the window and the other can stay attached
93 class NativeLayerRootCA
: public NativeLayerRoot
{
95 static already_AddRefed
<NativeLayerRootCA
> CreateForCALayer(CALayer
* aLayer
);
97 virtual NativeLayerRootCA
* AsNativeLayerRootCA() override
{ return this; }
99 // Can be called on any thread at any point. Returns whether comitting was
100 // successful. Will return false if called off the main thread while
101 // off-main-thread commits are suspended.
102 bool CommitToScreen() override
;
104 void CommitOffscreen();
105 void OnNativeLayerRootSnapshotterDestroyed(
106 NativeLayerRootSnapshotterCA
* aNativeLayerRootSnapshotter
);
108 // Enters a mode during which CommitToScreen(), when called on a non-main
109 // thread, will not apply any updates to the CALayer tree.
110 void SuspendOffMainThreadCommits();
112 // Exits the mode entered by SuspendOffMainThreadCommits().
113 // Returns true if the last CommitToScreen() was canceled due to suspension,
114 // indicating that another call to CommitToScreen() is needed.
115 bool UnsuspendOffMainThreadCommits();
117 bool AreOffMainThreadCommitsSuspended();
119 void DumpLayerTreeToFile(const char* aPath
);
121 enum class WhichRepresentation
: uint8_t { ONSCREEN
, OFFSCREEN
};
123 // Overridden methods
124 already_AddRefed
<NativeLayer
> CreateLayer(const gfx::IntSize
& aSize
, bool aIsOpaque
,
125 SurfacePoolHandle
* aSurfacePoolHandle
) override
;
126 void AppendLayer(NativeLayer
* aLayer
) override
;
127 void RemoveLayer(NativeLayer
* aLayer
) override
;
128 void SetLayers(const nsTArray
<RefPtr
<NativeLayer
>>& aLayers
) override
;
129 UniquePtr
<NativeLayerRootSnapshotter
> CreateSnapshotter() override
;
131 void SetBackingScale(float aBackingScale
);
132 float BackingScale();
134 already_AddRefed
<NativeLayer
> CreateLayerForExternalTexture(bool aIsOpaque
) override
;
135 already_AddRefed
<NativeLayer
> CreateLayerForColor(gfx::DeviceColor aColor
) override
;
137 void SetWindowIsFullscreen(bool aFullscreen
);
139 VideoLowPowerType
CheckVideoLowPower();
142 explicit NativeLayerRootCA(CALayer
* aLayer
);
143 ~NativeLayerRootCA() override
;
145 struct Representation
{
146 explicit Representation(CALayer
* aRootCALayer
);
148 void Commit(WhichRepresentation aRepresentation
,
149 const nsTArray
<RefPtr
<NativeLayerCA
>>& aSublayers
, bool aWindowIsFullscreen
);
150 CALayer
* mRootCALayer
= nullptr; // strong
151 bool mMutatedLayerStructure
= false;
154 template <typename F
>
155 void ForAllRepresentations(F aFn
);
157 Mutex mMutex MOZ_UNANNOTATED
; // protects all other fields
158 Representation mOnscreenRepresentation
;
159 Representation mOffscreenRepresentation
;
160 NativeLayerRootSnapshotterCA
* mWeakSnapshotter
= nullptr;
161 nsTArray
<RefPtr
<NativeLayerCA
>> mSublayers
; // in z-order
162 float mBackingScale
= 1.0f
;
163 bool mMutated
= false;
165 // While mOffMainThreadCommitsSuspended is true, no commits
166 // should happen on a non-main thread, because they might race with
167 // main-thread driven updates such as window shape changes, and cause
169 bool mOffMainThreadCommitsSuspended
= false;
171 // Set to true if CommitToScreen() was aborted because of commit suspension.
172 // Set to false when CommitToScreen() completes successfully. When true,
173 // indicates that CommitToScreen() needs to be called at the next available
175 bool mCommitPending
= false;
177 // Updated by the layer's view's window to match the fullscreen state
179 bool mWindowIsFullscreen
= false;
181 // How many times have we committed since the last time we emitted
183 unsigned int mTelemetryCommitCount
= 0;
186 class RenderSourceNLRS
;
188 class NativeLayerRootSnapshotterCA final
: public NativeLayerRootSnapshotter
{
190 static UniquePtr
<NativeLayerRootSnapshotterCA
> Create(NativeLayerRootCA
* aLayerRoot
,
191 CALayer
* aRootCALayer
);
192 virtual ~NativeLayerRootSnapshotterCA();
194 bool ReadbackPixels(const gfx::IntSize
& aReadbackSize
, gfx::SurfaceFormat aReadbackFormat
,
195 const Range
<uint8_t>& aReadbackBuffer
) override
;
196 already_AddRefed
<profiler_screenshots::RenderSource
> GetWindowContents(
197 const gfx::IntSize
& aWindowSize
) override
;
198 already_AddRefed
<profiler_screenshots::DownscaleTarget
> CreateDownscaleTarget(
199 const gfx::IntSize
& aSize
) override
;
200 already_AddRefed
<profiler_screenshots::AsyncReadbackBuffer
> CreateAsyncReadbackBuffer(
201 const gfx::IntSize
& aSize
) override
;
204 NativeLayerRootSnapshotterCA(NativeLayerRootCA
* aLayerRoot
, RefPtr
<gl::GLContext
>&& aGL
,
205 CALayer
* aRootCALayer
);
206 void UpdateSnapshot(const gfx::IntSize
& aSize
);
208 RefPtr
<NativeLayerRootCA
> mLayerRoot
;
209 RefPtr
<gl::GLContext
> mGL
;
211 // Can be null. Created and updated in UpdateSnapshot.
212 RefPtr
<RenderSourceNLRS
> mSnapshot
;
213 CARenderer
* mRenderer
= nullptr; // strong
216 // NativeLayerCA wraps a CALayer and lets you draw to it. It ensures that only
217 // fully-drawn frames make their way to the screen, by maintaining a swap chain
219 // All calls to mutating methods are buffered, and don't take effect on the
220 // underlying CoreAnimation layers until ApplyChanges() is called.
221 // The two most important methods are NextSurface and NotifySurfaceReady:
222 // NextSurface takes an available surface from the swap chain or creates a new
223 // surface if necessary. This surface can then be drawn to. Once drawing is
224 // finished, NotifySurfaceReady marks the surface as ready. This surface is
225 // committed to the layer during the next call to ApplyChanges().
226 // The swap chain keeps track of invalid areas within the surfaces.
227 class NativeLayerCA
: public NativeLayer
{
229 virtual NativeLayerCA
* AsNativeLayerCA() override
{ return this; }
231 // Overridden methods
232 gfx::IntSize
GetSize() override
;
233 void SetPosition(const gfx::IntPoint
& aPosition
) override
;
234 gfx::IntPoint
GetPosition() override
;
235 void SetTransform(const gfx::Matrix4x4
& aTransform
) override
;
236 gfx::Matrix4x4
GetTransform() override
;
237 gfx::IntRect
GetRect() override
;
238 void SetSamplingFilter(gfx::SamplingFilter aSamplingFilter
) override
;
239 RefPtr
<gfx::DrawTarget
> NextSurfaceAsDrawTarget(const gfx::IntRect
& aDisplayRect
,
240 const gfx::IntRegion
& aUpdateRegion
,
241 gfx::BackendType aBackendType
) override
;
242 Maybe
<GLuint
> NextSurfaceAsFramebuffer(const gfx::IntRect
& aDisplayRect
,
243 const gfx::IntRegion
& aUpdateRegion
,
244 bool aNeedsDepth
) override
;
245 void NotifySurfaceReady() override
;
246 void DiscardBackbuffers() override
;
247 bool IsOpaque() override
;
248 void SetClipRect(const Maybe
<gfx::IntRect
>& aClipRect
) override
;
249 Maybe
<gfx::IntRect
> ClipRect() override
;
250 gfx::IntRect
CurrentSurfaceDisplayRect() override
;
251 void SetSurfaceIsFlipped(bool aIsFlipped
) override
;
252 bool SurfaceIsFlipped() override
;
254 void DumpLayer(std::ostream
& aOutputStream
);
256 void AttachExternalImage(wr::RenderTextureHost
* aExternalImage
) override
;
258 void SetRootWindowIsFullscreen(bool aFullscreen
);
261 friend class NativeLayerRootCA
;
263 NativeLayerCA(const gfx::IntSize
& aSize
, bool aIsOpaque
, SurfacePoolHandleCA
* aSurfacePoolHandle
);
264 explicit NativeLayerCA(bool aIsOpaque
);
265 explicit NativeLayerCA(gfx::DeviceColor aColor
);
266 ~NativeLayerCA() override
;
268 // Gets the next surface for drawing from our swap chain and stores it in
269 // mInProgressSurface. Returns whether this was successful.
270 // mInProgressSurface is guaranteed to be not in use by the window server.
271 // After a call to NextSurface, NextSurface must not be called again until
272 // after NotifySurfaceReady has been called. Can be called on any thread. When
273 // used from multiple threads, callers need to make sure that they still only
274 // call NextSurface and NotifySurfaceReady alternatingly and not in any other
276 bool NextSurface(const MutexAutoLock
& aProofOfLock
);
278 // To be called by NativeLayerRootCA:
279 typedef NativeLayerRootCA::WhichRepresentation WhichRepresentation
;
280 CALayer
* UnderlyingCALayer(WhichRepresentation aRepresentation
);
282 enum class UpdateType
{
283 None
, // Order is important. Each enum must fully encompass the
284 OnlyVideo
, // work implied by the previous enums.
288 UpdateType
HasUpdate(WhichRepresentation aRepresentation
);
289 bool WillUpdateAffectLayers(WhichRepresentation aRepresentation
);
290 bool ApplyChanges(WhichRepresentation aRepresentation
, UpdateType aUpdate
);
292 void SetBackingScale(float aBackingScale
);
294 // Invalidates the specified region in all surfaces that are tracked by this
296 void InvalidateRegionThroughoutSwapchain(const MutexAutoLock
& aProofOfLock
,
297 const gfx::IntRegion
& aRegion
);
299 // Invalidate aUpdateRegion and make sure that mInProgressSurface retains any
300 // valid content from the previous surface outside of aUpdateRegion, so that
301 // only aUpdateRegion needs to be drawn. If content needs to be copied,
302 // aCopyFn is called to do the copying.
303 // aCopyFn: Fn(CFTypeRefPtr<IOSurfaceRef> aValidSourceIOSurface,
304 // const gfx::IntRegion& aCopyRegion) -> void
305 template <typename F
>
306 void HandlePartialUpdate(const MutexAutoLock
& aProofOfLock
, const gfx::IntRect
& aDisplayRect
,
307 const gfx::IntRegion
& aUpdateRegion
, F
&& aCopyFn
);
309 struct SurfaceWithInvalidRegion
{
310 CFTypeRefPtr
<IOSurfaceRef
> mSurface
;
311 gfx::IntRegion mInvalidRegion
;
314 struct SurfaceWithInvalidRegionAndCheckCount
{
315 SurfaceWithInvalidRegion mEntry
;
316 uint32_t mCheckCount
; // The number of calls to IOSurfaceIsInUse
319 Maybe
<SurfaceWithInvalidRegion
> GetUnusedSurfaceAndCleanUp(const MutexAutoLock
& aProofOfLock
);
322 bool IsVideoAndLocked(const MutexAutoLock
& aProofOfLock
);
323 bool ShouldSpecializeVideo(const MutexAutoLock
& aProofOfLock
);
324 bool HasExtent() const { return mHasExtent
; }
325 void SetHasExtent(bool aHasExtent
) { mHasExtent
= aHasExtent
; }
327 // This function returns a CGRect if a clip should be applied to the layer.
328 // If set, the CGRect has the scaled position of the clip relative to the
329 // surface origin and the scaled size of the clip rect.
330 static Maybe
<CGRect
> CalculateClipGeometry(
331 const gfx::IntSize
& aSize
, const gfx::IntPoint
& aPosition
, const gfx::Matrix4x4
& aTransform
,
332 const gfx::IntRect
& aDisplayRect
, const Maybe
<gfx::IntRect
>& aClipRect
, float aBackingScale
);
334 // Wraps one CALayer representation of this NativeLayer.
335 struct Representation
{
339 CALayer
* UnderlyingCALayer() { return mWrappingCALayer
; }
341 bool EnqueueSurface(IOSurfaceRef aSurfaceRef
);
343 // Applies buffered changes to the native CALayers. The contract with the
344 // caller is as follows: If any of these values have changed since the last
345 // call to ApplyChanges, mMutated[Field] needs to have been set to true
346 // before the call. If aUpdate is not All, then a partial update will be
347 // applied. In such a case, ApplyChanges may not make any changes that
348 // require a CATransacation, because no transaction will be created. In a
349 // a partial update, the return value will indicate if all the needed
350 // changes were able to be applied under these restrictions. A false return
351 // value indicates an All update is necessary.
352 bool ApplyChanges(UpdateType aUpdate
, const gfx::IntSize
& aSize
, bool aIsOpaque
,
353 const gfx::IntPoint
& aPosition
, const gfx::Matrix4x4
& aTransform
,
354 const gfx::IntRect
& aDisplayRect
, const Maybe
<gfx::IntRect
>& aClipRect
,
355 float aBackingScale
, bool aSurfaceIsFlipped
,
356 gfx::SamplingFilter aSamplingFilter
, bool aSpecializeVideo
,
357 CFTypeRefPtr
<IOSurfaceRef
> aFrontSurface
, CFTypeRefPtr
<CGColorRef
> aColor
,
358 bool aIsDRM
, bool aIsVideo
);
360 // Return whether any aspects of this layer representation have been mutated
361 // since the last call to ApplyChanges, i.e. whether ApplyChanges needs to
363 // This is used to optimize away a CATransaction commit if no layers have
365 UpdateType
HasUpdate(bool aIsVideo
);
367 // Lazily initialized by first call to ApplyChanges. mWrappingLayer is the
368 // layer that applies the intersection of mDisplayRect and mClipRect (if
369 // set), and mContentCALayer is the layer that hosts the IOSurface. We do
370 // not share clip layers between consecutive NativeLayerCA objects with the
372 CALayer
* mWrappingCALayer
= nullptr; // strong
373 CALayer
* mContentCALayer
= nullptr; // strong
374 CALayer
* mOpaquenessTintLayer
= nullptr; // strong
377 bool mLogNextVideoSurface
= false;
380 bool mMutatedPosition
: 1;
381 bool mMutatedTransform
: 1;
382 bool mMutatedDisplayRect
: 1;
383 bool mMutatedClipRect
: 1;
384 bool mMutatedBackingScale
: 1;
385 bool mMutatedSize
: 1;
386 bool mMutatedSurfaceIsFlipped
: 1;
387 bool mMutatedFrontSurface
: 1;
388 bool mMutatedSamplingFilter
: 1;
389 bool mMutatedSpecializeVideo
: 1;
390 bool mMutatedIsDRM
: 1;
393 Representation
& GetRepresentation(WhichRepresentation aRepresentation
);
394 template <typename F
>
395 void ForAllRepresentations(F aFn
);
397 // Controls access to all fields of this class.
398 Mutex mMutex MOZ_UNANNOTATED
;
400 // Each IOSurface is initially created inside NextSurface.
401 // The surface stays alive until the recycling mechanism in NextSurface
402 // determines it is no longer needed (because the swap chain has grown too
403 // long) or until DiscardBackbuffers() is called or the layer is destroyed.
404 // During the surface's lifetime, it will continuously move through the fields
405 // mInProgressSurface, mFrontSurface, and back to front through the mSurfaces
409 // ------[NextSurface()]-----> mInProgressSurface
410 // --[NotifySurfaceReady()]--> mFrontSurface
411 // --[NotifySurfaceReady()]--> mSurfaces.back() --> .... -->
414 // We mark an IOSurface as "in use" as long as it is either in
415 // mInProgressSurface. When it is in mFrontSurface or in the mSurfaces queue,
416 // it is not marked as "in use" by us - but it can be "in use" by the window
417 // server. Consequently, IOSurfaceIsInUse on a surface from mSurfaces reflects
418 // whether the window server is still reading from the surface, and we can use
419 // this indicator to decide when to recycle the surface.
421 // Users of NativeLayerCA normally proceed in this order:
422 // 1. Begin a frame by calling NextSurface to get the surface.
423 // 2. Draw to the surface.
424 // 3. Mark the surface as done by calling NotifySurfaceReady.
425 // 4. Call NativeLayerRoot::CommitToScreen(), which calls ApplyChanges()
426 // during a CATransaction.
428 // The surface we returned from the most recent call to NextSurface, before
429 // the matching call to NotifySurfaceReady.
430 // Will only be Some() between calls to NextSurface and NotifySurfaceReady.
431 Maybe
<SurfaceWithInvalidRegion
> mInProgressSurface
;
432 Maybe
<gfx::IntRegion
> mInProgressUpdateRegion
;
433 Maybe
<gfx::IntRect
> mInProgressDisplayRect
;
435 // The surface that the most recent call to NotifySurfaceReady was for.
436 // Will be Some() after the first call to NotifySurfaceReady, for the rest of
437 // the layer's life time.
438 Maybe
<SurfaceWithInvalidRegion
> mFrontSurface
;
440 // The queue of surfaces which make up the rest of our "swap chain".
441 // mSurfaces.front() is the next surface we'll attempt to use.
442 // mSurfaces.back() is the one that was used most recently.
443 std::vector
<SurfaceWithInvalidRegionAndCheckCount
> mSurfaces
;
445 // Non-null between calls to NextSurfaceAsDrawTarget and NotifySurfaceReady.
446 RefPtr
<MacIOSurface
> mInProgressLockedIOSurface
;
448 RefPtr
<SurfacePoolHandleCA
> mSurfacePoolHandle
;
449 RefPtr
<wr::RenderMacIOSurfaceTextureHost
> mTextureHost
;
451 Representation mOnscreenRepresentation
;
452 Representation mOffscreenRepresentation
;
454 gfx::IntPoint mPosition
;
455 gfx::Matrix4x4 mTransform
;
456 gfx::IntRect mDisplayRect
;
458 Maybe
<gfx::IntRect
> mClipRect
;
459 gfx::SamplingFilter mSamplingFilter
= gfx::SamplingFilter::POINT
;
460 float mBackingScale
= 1.0f
;
461 bool mSurfaceIsFlipped
= false;
462 CFTypeRefPtr
<CGColorRef
> mColor
;
463 const bool mIsOpaque
= false;
464 bool mRootWindowIsFullscreen
= false;
465 bool mSpecializeVideo
= false;
466 bool mHasExtent
= false;
470 // Track the consistency of our caller's API usage. Layers that are drawn
471 // should only ever be called with NotifySurfaceReady. Layers that are
472 // external should only ever be called with AttachExternalImage.
473 bool mHasEverAttachExternalImage
= false;
474 bool mHasEverNotifySurfaceReady
= false;
478 } // namespace layers
479 } // namespace mozilla
481 #endif // mozilla_layers_NativeLayerCA_h