1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <stdint.h>
20 #include <sys/types.h>
21 #include <set>
22 #include <unordered_map>
23 #include <unordered_set>
24 
25 #include <binder/IBinder.h>
26 
27 #include <utils/RefBase.h>
28 #include <utils/Singleton.h>
29 #include <utils/SortedVector.h>
30 #include <utils/threads.h>
31 
32 #include <ui/ConfigStoreTypes.h>
33 #include <ui/DisplayedFrameStats.h>
34 #include <ui/FrameStats.h>
35 #include <ui/GraphicTypes.h>
36 #include <ui/PixelFormat.h>
37 #include <ui/Rotation.h>
38 
39 #include <gui/CpuConsumer.h>
40 #include <gui/ISurfaceComposer.h>
41 #include <gui/ITransactionCompletedListener.h>
42 #include <gui/LayerState.h>
43 #include <gui/SurfaceControl.h>
44 #include <math/vec3.h>
45 
46 namespace android {
47 
48 class HdrCapabilities;
49 class ISurfaceComposerClient;
50 class IGraphicBufferProducer;
51 class IRegionSamplingListener;
52 class Region;
53 
54 struct SurfaceControlStats {
SurfaceControlStatsSurfaceControlStats55     SurfaceControlStats(const sp<SurfaceControl>& sc, nsecs_t latchTime, nsecs_t acquireTime,
56                         const sp<Fence>& presentFence, const sp<Fence>& prevReleaseFence,
57                         uint32_t hint, FrameEventHistoryStats eventStats)
58           : surfaceControl(sc),
59             latchTime(latchTime),
60             acquireTime(acquireTime),
61             presentFence(presentFence),
62             previousReleaseFence(prevReleaseFence),
63             transformHint(hint),
64             frameEventStats(eventStats) {}
65 
66     sp<SurfaceControl> surfaceControl;
67     nsecs_t latchTime = -1;
68     nsecs_t acquireTime = -1;
69     sp<Fence> presentFence;
70     sp<Fence> previousReleaseFence;
71     uint32_t transformHint = 0;
72     FrameEventHistoryStats frameEventStats;
73 };
74 
75 using TransactionCompletedCallbackTakesContext =
76         std::function<void(void* /*context*/, nsecs_t /*latchTime*/,
77                            const sp<Fence>& /*presentFence*/,
78                            const std::vector<SurfaceControlStats>& /*stats*/)>;
79 using TransactionCompletedCallback =
80         std::function<void(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
81                            const std::vector<SurfaceControlStats>& /*stats*/)>;
82 
83 // ---------------------------------------------------------------------------
84 
85 class SurfaceComposerClient : public RefBase
86 {
87     friend class Composer;
88 public:
89                 SurfaceComposerClient();
90                 SurfaceComposerClient(const sp<ISurfaceComposerClient>& client);
91     virtual     ~SurfaceComposerClient();
92 
93     // Always make sure we could initialize
94     status_t    initCheck() const;
95 
96     // Return the connection of this client
97     sp<IBinder> connection() const;
98 
99     // Forcibly remove connection before all references have gone away.
100     void        dispose();
101 
102     // callback when the composer is dies
103     status_t linkToComposerDeath(const sp<IBinder::DeathRecipient>& recipient,
104             void* cookie = nullptr, uint32_t flags = 0);
105 
106     // Get transactional state of given display.
107     static status_t getDisplayState(const sp<IBinder>& display, ui::DisplayState*);
108 
109     // Get immutable information about given physical display.
110     static status_t getDisplayInfo(const sp<IBinder>& display, DisplayInfo*);
111 
112     // Get configurations supported by given physical display.
113     static status_t getDisplayConfigs(const sp<IBinder>& display, Vector<DisplayConfig>*);
114 
115     // Get the ID of the active DisplayConfig, as getDisplayConfigs index.
116     static int getActiveConfig(const sp<IBinder>& display);
117 
118     // Shorthand for getDisplayConfigs element at getActiveConfig index.
119     static status_t getActiveDisplayConfig(const sp<IBinder>& display, DisplayConfig*);
120 
121     // Sets the refresh rate boundaries for the display.
122     static status_t setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
123                                                  int32_t defaultConfig, float primaryRefreshRateMin,
124                                                  float primaryRefreshRateMax,
125                                                  float appRequestRefreshRateMin,
126                                                  float appRequestRefreshRateMax);
127     // Gets the refresh rate boundaries for the display.
128     static status_t getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
129                                                  int32_t* outDefaultConfig,
130                                                  float* outPrimaryRefreshRateMin,
131                                                  float* outPrimaryRefreshRateMax,
132                                                  float* outAppRequestRefreshRateMin,
133                                                  float* outAppRequestRefreshRateMax);
134 
135     // Gets the list of supported color modes for the given display
136     static status_t getDisplayColorModes(const sp<IBinder>& display,
137             Vector<ui::ColorMode>* outColorModes);
138 
139     // Get the coordinates of the display's native color primaries
140     static status_t getDisplayNativePrimaries(const sp<IBinder>& display,
141             ui::DisplayPrimaries& outPrimaries);
142 
143     // Gets the active color mode for the given display
144     static ui::ColorMode getActiveColorMode(const sp<IBinder>& display);
145 
146     // Sets the active color mode for the given display
147     static status_t setActiveColorMode(const sp<IBinder>& display,
148             ui::ColorMode colorMode);
149 
150     // Reports whether the connected display supports Auto Low Latency Mode
151     static bool getAutoLowLatencyModeSupport(const sp<IBinder>& display);
152 
153     // Switches on/off Auto Low Latency Mode on the connected display. This should only be
154     // called if the connected display supports Auto Low Latency Mode as reported by
155     // #getAutoLowLatencyModeSupport
156     static void setAutoLowLatencyMode(const sp<IBinder>& display, bool on);
157 
158     // Reports whether the connected display supports Game content type
159     static bool getGameContentTypeSupport(const sp<IBinder>& display);
160 
161     // Turns Game mode on/off on the connected display. This should only be called
162     // if the display supports Game content type, as reported by #getGameContentTypeSupport
163     static void setGameContentType(const sp<IBinder>& display, bool on);
164 
165     /* Triggers screen on/off or low power mode and waits for it to complete */
166     static void setDisplayPowerMode(const sp<IBinder>& display, int mode);
167 
168     /* Returns the composition preference of the default data space and default pixel format,
169      * as well as the wide color gamut data space and wide color gamut pixel format.
170      * If the wide color gamut data space is V0_SRGB, then it implies that the platform
171      * has no wide color gamut support.
172      */
173     static status_t getCompositionPreference(ui::Dataspace* defaultDataspace,
174                                              ui::PixelFormat* defaultPixelFormat,
175                                              ui::Dataspace* wideColorGamutDataspace,
176                                              ui::PixelFormat* wideColorGamutPixelFormat);
177 
178     /*
179      * Gets whether SurfaceFlinger can support protected content in GPU composition.
180      * Requires the ACCESS_SURFACE_FLINGER permission.
181      */
182     static bool getProtectedContentSupport();
183 
184     /**
185      * Uncaches a buffer in ISurfaceComposer. It must be uncached via a transaction so that it is
186      * in order with other transactions that use buffers.
187      */
188     static void doUncacheBufferTransaction(uint64_t cacheId);
189 
190     // Queries whether a given display is wide color display.
191     static status_t isWideColorDisplay(const sp<IBinder>& display, bool* outIsWideColorDisplay);
192 
193     /*
194      * Returns whether brightness operations are supported on a display.
195      *
196      * displayToken
197      *      The token of the display.
198      *
199      * Returns whether brightness operations are supported on a display or not.
200      */
201     static bool getDisplayBrightnessSupport(const sp<IBinder>& displayToken);
202 
203     /*
204      * Sets the brightness of a display.
205      *
206      * displayToken
207      *      The token of the display whose brightness is set.
208      * brightness
209      *      A number between 0.0 (minimum brightness) and 1.0 (maximum brightness), or -1.0f to
210      *      turn the backlight off.
211      *
212      * Returns NO_ERROR upon success. Otherwise,
213      *      NAME_NOT_FOUND    if the display handle is invalid, or
214      *      BAD_VALUE         if the brightness value is invalid, or
215      *      INVALID_OPERATION if brightness operaetions are not supported.
216      */
217     static status_t setDisplayBrightness(const sp<IBinder>& displayToken, float brightness);
218 
219     /*
220      * Sends a power hint to the composer. This function is asynchronous.
221      *
222      * hintId
223      *      hint id according to android::hardware::power::V1_0::PowerHint
224      *
225      * Returns NO_ERROR upon success.
226      */
227     static status_t notifyPowerHint(int32_t hintId);
228 
229     /*
230      * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows
231      * material design guidelines.
232      *
233      * ambientColor
234      *      Color to the ambient shadow. The alpha is premultiplied.
235      *
236      * spotColor
237      *      Color to the spot shadow. The alpha is premultiplied. The position of the spot shadow
238      *      depends on the light position.
239      *
240      * lightPosY/lightPosZ
241      *      Position of the light used to cast the spot shadow. The X value is always the display
242      *      width / 2.
243      *
244      * lightRadius
245      *      Radius of the light casting the shadow.
246      */
247     static status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
248                                             float lightPosY, float lightPosZ, float lightRadius);
249 
250     // ------------------------------------------------------------------------
251     // surface creation / destruction
252 
253     static sp<SurfaceComposerClient> getDefault();
254 
255     //! Create a surface
256     sp<SurfaceControl> createSurface(const String8& name,              // name of the surface
257                                      uint32_t w,                       // width in pixel
258                                      uint32_t h,                       // height in pixel
259                                      PixelFormat format,               // pixel-format desired
260                                      uint32_t flags = 0,               // usage flags
261                                      SurfaceControl* parent = nullptr, // parent
262                                      LayerMetadata metadata = LayerMetadata(), // metadata
263                                      uint32_t* outTransformHint = nullptr);
264 
265     status_t createSurfaceChecked(const String8& name, // name of the surface
266                                   uint32_t w,          // width in pixel
267                                   uint32_t h,          // height in pixel
268                                   PixelFormat format,  // pixel-format desired
269                                   sp<SurfaceControl>* outSurface,
270                                   uint32_t flags = 0,                       // usage flags
271                                   SurfaceControl* parent = nullptr,         // parent
272                                   LayerMetadata metadata = LayerMetadata(), // metadata
273                                   uint32_t* outTransformHint = nullptr);
274 
275     //! Create a surface
276     sp<SurfaceControl> createWithSurfaceParent(const String8& name,       // name of the surface
277                                                uint32_t w,                // width in pixel
278                                                uint32_t h,                // height in pixel
279                                                PixelFormat format,        // pixel-format desired
280                                                uint32_t flags = 0,        // usage flags
281                                                Surface* parent = nullptr, // parent
282                                                LayerMetadata metadata = LayerMetadata(), // metadata
283                                                uint32_t* outTransformHint = nullptr);
284 
285     // Creates a mirrored hierarchy for the mirrorFromSurface. This returns a SurfaceControl
286     // which is a parent of the root of the mirrored hierarchy.
287     //
288     //  Real Hierarchy    Mirror
289     //                      SC (value that's returned)
290     //                      |
291     //      A               A'
292     //      |               |
293     //      B               B'
294     sp<SurfaceControl> mirrorSurface(SurfaceControl* mirrorFromSurface);
295 
296     //! Create a virtual display
297     static sp<IBinder> createDisplay(const String8& displayName, bool secure);
298 
299     //! Destroy a virtual display
300     static void destroyDisplay(const sp<IBinder>& display);
301 
302     //! Get stable IDs for connected physical displays
303     static std::vector<PhysicalDisplayId> getPhysicalDisplayIds();
304     static std::optional<PhysicalDisplayId> getInternalDisplayId();
305 
306     //! Get token for a physical display given its stable ID
307     static sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId);
308     static sp<IBinder> getInternalDisplayToken();
309 
310     static status_t enableVSyncInjections(bool enable);
311 
312     static status_t injectVSync(nsecs_t when);
313 
314     struct SCHash {
operatorSCHash315         std::size_t operator()(const sp<SurfaceControl>& sc) const {
316             return std::hash<SurfaceControl *>{}(sc.get());
317         }
318     };
319 
320     struct IBinderHash {
operatorIBinderHash321         std::size_t operator()(const sp<IBinder>& iBinder) const {
322             return std::hash<IBinder*>{}(iBinder.get());
323         }
324     };
325 
326     struct TCLHash {
operatorTCLHash327         std::size_t operator()(const sp<ITransactionCompletedListener>& tcl) const {
328             return std::hash<IBinder*>{}((tcl) ? IInterface::asBinder(tcl).get() : nullptr);
329         }
330     };
331 
332     struct CallbackInfo {
333         // All the callbacks that have been requested for a TransactionCompletedListener in the
334         // Transaction
335         std::unordered_set<CallbackId> callbackIds;
336         // All the SurfaceControls that have been modified in this TransactionCompletedListener's
337         // process that require a callback if there is one or more callbackIds set.
338         std::unordered_set<sp<SurfaceControl>, SCHash> surfaceControls;
339     };
340 
341     class Transaction : public Parcelable {
342     protected:
343         std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> mComposerStates;
344         SortedVector<DisplayState > mDisplayStates;
345         std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash>
346                 mListenerCallbacks;
347 
348         uint32_t mForceSynchronous = 0;
349         uint32_t mTransactionNestCount = 0;
350         bool mAnimation = false;
351         bool mEarlyWakeup = false;
352         bool mExplicitEarlyWakeupStart = false;
353         bool mExplicitEarlyWakeupEnd = false;
354 
355         // Indicates that the Transaction contains a buffer that should be cached
356         bool mContainsBuffer = false;
357 
358         // mDesiredPresentTime is the time in nanoseconds that the client would like the transaction
359         // to be presented. When it is not possible to present at exactly that time, it will be
360         // presented after the time has passed.
361         //
362         // Desired present times that are more than 1 second in the future may be ignored.
363         // When a desired present time has already passed, the transaction will be presented as soon
364         // as possible.
365         //
366         // Transactions from the same process are presented in the same order that they are applied.
367         // The desired present time does not affect this ordering.
368         int64_t mDesiredPresentTime = -1;
369 
370         InputWindowCommands mInputWindowCommands;
371         int mStatus = NO_ERROR;
372 
373         layer_state_t* getLayerState(const sp<IBinder>& surfaceHandle);
getLayerState(const sp<SurfaceControl> & sc)374         layer_state_t* getLayerState(const sp<SurfaceControl>& sc) {
375             return getLayerState(sc->getHandle());
376         }
377         DisplayState& getDisplayState(const sp<IBinder>& token);
378 
379         void cacheBuffers();
380         void registerSurfaceControlForCallback(const sp<SurfaceControl>& sc);
381 
382     public:
383         Transaction() = default;
384         virtual ~Transaction() = default;
385         Transaction(Transaction const& other);
386 
387         // Factory method that creates a new Transaction instance from the parcel.
388         static std::unique_ptr<Transaction> createFromParcel(const Parcel* parcel);
389 
390         status_t writeToParcel(Parcel* parcel) const override;
391         status_t readFromParcel(const Parcel* parcel) override;
392 
393         // Clears the contents of the transaction without applying it.
394         void clear();
395 
396         status_t apply(bool synchronous = false);
397         // Merge another transaction in to this one, clearing other
398         // as if it had been applied.
399         Transaction& merge(Transaction&& other);
400         Transaction& show(const sp<SurfaceControl>& sc);
401         Transaction& hide(const sp<SurfaceControl>& sc);
402         Transaction& setPosition(const sp<SurfaceControl>& sc,
403                 float x, float y);
404         Transaction& setSize(const sp<SurfaceControl>& sc,
405                 uint32_t w, uint32_t h);
406         Transaction& setLayer(const sp<SurfaceControl>& sc,
407                 int32_t z);
408 
409         // Sets a Z order relative to the Surface specified by "relativeTo" but
410         // without becoming a full child of the relative. Z-ordering works exactly
411         // as if it were a child however.
412         //
413         // As a nod to sanity, only non-child surfaces may have a relative Z-order.
414         //
415         // This overrides any previous call and is overriden by any future calls
416         // to setLayer.
417         //
418         // If the relative is removed, the Surface will have no layer and be
419         // invisible, until the next time set(Relative)Layer is called.
420         Transaction& setRelativeLayer(const sp<SurfaceControl>& sc,
421                 const sp<IBinder>& relativeTo, int32_t z);
422         Transaction& setFlags(const sp<SurfaceControl>& sc,
423                 uint32_t flags, uint32_t mask);
424         Transaction& setTransparentRegionHint(const sp<SurfaceControl>& sc,
425                 const Region& transparentRegion);
426         Transaction& setAlpha(const sp<SurfaceControl>& sc,
427                 float alpha);
428         Transaction& setMatrix(const sp<SurfaceControl>& sc,
429                 float dsdx, float dtdx, float dtdy, float dsdy);
430         Transaction& setCrop_legacy(const sp<SurfaceControl>& sc, const Rect& crop);
431         Transaction& setCornerRadius(const sp<SurfaceControl>& sc, float cornerRadius);
432         Transaction& setBackgroundBlurRadius(const sp<SurfaceControl>& sc,
433                                              int backgroundBlurRadius);
434         Transaction& setLayerStack(const sp<SurfaceControl>& sc, uint32_t layerStack);
435         Transaction& setMetadata(const sp<SurfaceControl>& sc, uint32_t key, const Parcel& p);
436         // Defers applying any changes made in this transaction until the Layer
437         // identified by handle reaches the given frameNumber. If the Layer identified
438         // by handle is removed, then we will apply this transaction regardless of
439         // what frame number has been reached.
440         Transaction& deferTransactionUntil_legacy(const sp<SurfaceControl>& sc,
441                                                   const sp<IBinder>& handle, uint64_t frameNumber);
442         // A variant of deferTransactionUntil_legacy which identifies the Layer we wait for by
443         // Surface instead of Handle. Useful for clients which may not have the
444         // SurfaceControl for some of their Surfaces. Otherwise behaves identically.
445         Transaction& deferTransactionUntil_legacy(const sp<SurfaceControl>& sc,
446                                                   const sp<Surface>& barrierSurface,
447                                                   uint64_t frameNumber);
448         // Reparents all children of this layer to the new parent handle.
449         Transaction& reparentChildren(const sp<SurfaceControl>& sc,
450                 const sp<IBinder>& newParentHandle);
451 
452         /// Reparents the current layer to the new parent handle. The new parent must not be null.
453         // This can be used instead of reparentChildren if the caller wants to
454         // only re-parent a specific child.
455         Transaction& reparent(const sp<SurfaceControl>& sc,
456                 const sp<IBinder>& newParentHandle);
457 
458         Transaction& setColor(const sp<SurfaceControl>& sc, const half3& color);
459 
460         // Sets the background color of a layer with the specified color, alpha, and dataspace
461         Transaction& setBackgroundColor(const sp<SurfaceControl>& sc, const half3& color,
462                                         float alpha, ui::Dataspace dataspace);
463 
464         Transaction& setTransform(const sp<SurfaceControl>& sc, uint32_t transform);
465         Transaction& setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
466                                                   bool transformToDisplayInverse);
467         Transaction& setCrop(const sp<SurfaceControl>& sc, const Rect& crop);
468         Transaction& setFrame(const sp<SurfaceControl>& sc, const Rect& frame);
469         Transaction& setBuffer(const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer);
470         Transaction& setCachedBuffer(const sp<SurfaceControl>& sc, int32_t bufferId);
471         Transaction& setAcquireFence(const sp<SurfaceControl>& sc, const sp<Fence>& fence);
472         Transaction& setDataspace(const sp<SurfaceControl>& sc, ui::Dataspace dataspace);
473         Transaction& setHdrMetadata(const sp<SurfaceControl>& sc, const HdrMetadata& hdrMetadata);
474         Transaction& setSurfaceDamageRegion(const sp<SurfaceControl>& sc,
475                                             const Region& surfaceDamageRegion);
476         Transaction& setApi(const sp<SurfaceControl>& sc, int32_t api);
477         Transaction& setSidebandStream(const sp<SurfaceControl>& sc,
478                                        const sp<NativeHandle>& sidebandStream);
479         Transaction& setDesiredPresentTime(nsecs_t desiredPresentTime);
480         Transaction& setColorSpaceAgnostic(const sp<SurfaceControl>& sc, const bool agnostic);
481 
482         // Sets information about the priority of the frame.
483         Transaction& setFrameRateSelectionPriority(const sp<SurfaceControl>& sc, int32_t priority);
484 
485         Transaction& addTransactionCompletedCallback(
486                 TransactionCompletedCallbackTakesContext callback, void* callbackContext);
487 
488         // ONLY FOR BLAST ADAPTER
489         Transaction& notifyProducerDisconnect(const sp<SurfaceControl>& sc);
490 
491         // Detaches all child surfaces (and their children recursively)
492         // from their SurfaceControl.
493         // The child SurfaceControls will not throw exceptions or return errors,
494         // but transactions will have no effect.
495         // The child surfaces will continue to follow their parent surfaces,
496         // and remain eligible for rendering, but their relative state will be
497         // frozen. We use this in the WindowManager, in app shutdown/relaunch
498         // scenarios, where the app would otherwise clean up its child Surfaces.
499         // Sometimes the WindowManager needs to extend their lifetime slightly
500         // in order to perform an exit animation or prevent flicker.
501         Transaction& detachChildren(const sp<SurfaceControl>& sc);
502         // Set an override scaling mode as documented in <system/window.h>
503         // the override scaling mode will take precedence over any client
504         // specified scaling mode. -1 will clear the override scaling mode.
505         Transaction& setOverrideScalingMode(const sp<SurfaceControl>& sc,
506                 int32_t overrideScalingMode);
507 
508 #ifndef NO_INPUT
509         Transaction& setInputWindowInfo(const sp<SurfaceControl>& sc, const InputWindowInfo& info);
510         Transaction& syncInputWindows();
511 #endif
512 
513         // Set a color transform matrix on the given layer on the built-in display.
514         Transaction& setColorTransform(const sp<SurfaceControl>& sc, const mat3& matrix,
515                                        const vec3& translation);
516 
517         Transaction& setGeometry(const sp<SurfaceControl>& sc,
518                 const Rect& source, const Rect& dst, int transform);
519         Transaction& setShadowRadius(const sp<SurfaceControl>& sc, float cornerRadius);
520 
521         Transaction& setFrameRate(const sp<SurfaceControl>& sc, float frameRate,
522                                   int8_t compatibility);
523 
524         // Set by window manager indicating the layer and all its children are
525         // in a different orientation than the display. The hint suggests that
526         // the graphic producers should receive a transform hint as if the
527         // display was in this orientation. When the display changes to match
528         // the layer orientation, the graphic producer may not need to allocate
529         // a buffer of a different size.
530         Transaction& setFixedTransformHint(const sp<SurfaceControl>& sc, int32_t transformHint);
531 
532         status_t setDisplaySurface(const sp<IBinder>& token,
533                 const sp<IGraphicBufferProducer>& bufferProducer);
534 
535         void setDisplayLayerStack(const sp<IBinder>& token, uint32_t layerStack);
536 
537         /* setDisplayProjection() defines the projection of layer stacks
538          * to a given display.
539          *
540          * - orientation defines the display's orientation.
541          * - layerStackRect defines which area of the window manager coordinate
542          * space will be used.
543          * - displayRect defines where on the display will layerStackRect be
544          * mapped to. displayRect is specified post-orientation, that is
545          * it uses the orientation seen by the end-user.
546          */
547         void setDisplayProjection(const sp<IBinder>& token, ui::Rotation orientation,
548                                   const Rect& layerStackRect, const Rect& displayRect);
549         void setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height);
550         void setAnimationTransaction();
551         void setEarlyWakeup();
552         void setExplicitEarlyWakeupStart();
553         void setExplicitEarlyWakeupEnd();
554     };
555 
556     status_t clearLayerFrameStats(const sp<IBinder>& token) const;
557     status_t getLayerFrameStats(const sp<IBinder>& token, FrameStats* outStats) const;
558     static status_t clearAnimationFrameStats();
559     static status_t getAnimationFrameStats(FrameStats* outStats);
560 
561     static status_t getHdrCapabilities(const sp<IBinder>& display,
562             HdrCapabilities* outCapabilities);
563 
564     static void setDisplayProjection(const sp<IBinder>& token, ui::Rotation orientation,
565                                      const Rect& layerStackRect, const Rect& displayRect);
566 
getClient()567     inline sp<ISurfaceComposerClient> getClient() { return mClient; }
568 
569     static status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
570                                                           ui::PixelFormat* outFormat,
571                                                           ui::Dataspace* outDataspace,
572                                                           uint8_t* outComponentMask);
573     static status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
574                                                      uint8_t componentMask, uint64_t maxFrames);
575 
576     static status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
577                                               uint64_t timestamp, DisplayedFrameStats* outStats);
578     static status_t addRegionSamplingListener(const Rect& samplingArea,
579                                               const sp<IBinder>& stopLayerHandle,
580                                               const sp<IRegionSamplingListener>& listener);
581     static status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener);
582 
583 private:
584     virtual void onFirstRef();
585 
586     mutable     Mutex                       mLock;
587                 status_t                    mStatus;
588                 sp<ISurfaceComposerClient>  mClient;
589 };
590 
591 // ---------------------------------------------------------------------------
592 
593 class ScreenshotClient {
594 public:
595     // if cropping isn't required, callers may pass in a default Rect, e.g.:
596     //   capture(display, producer, Rect(), reqWidth, ...);
597     static status_t capture(const sp<IBinder>& display, ui::Dataspace reqDataSpace,
598                             ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
599                             uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform,
600                             ui::Rotation rotation, bool captureSecureLayers,
601                             sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers);
602     static status_t capture(const sp<IBinder>& display, ui::Dataspace reqDataSpace,
603                             ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
604                             uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform,
605                             ui::Rotation rotation, sp<GraphicBuffer>* outBuffer);
606     static status_t capture(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
607                             sp<GraphicBuffer>* outBuffer);
608     static status_t captureLayers(const sp<IBinder>& layerHandle, ui::Dataspace reqDataSpace,
609                                   ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
610                                   float frameScale, sp<GraphicBuffer>* outBuffer);
611     static status_t captureChildLayers(
612             const sp<IBinder>& layerHandle, ui::Dataspace reqDataSpace,
613             ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
614             const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>&
615                     excludeHandles,
616             float frameScale, sp<GraphicBuffer>* outBuffer);
617 };
618 
619 // ---------------------------------------------------------------------------
620 
621 class TransactionCompletedListener : public BnTransactionCompletedListener {
622     TransactionCompletedListener();
623 
624     CallbackId getNextIdLocked() REQUIRES(mMutex);
625 
626     std::mutex mMutex;
627 
628     bool mListening GUARDED_BY(mMutex) = false;
629 
630     CallbackId mCallbackIdCounter GUARDED_BY(mMutex) = 1;
631 
632     struct CallbackTranslation {
633         TransactionCompletedCallback callbackFunction;
634         std::unordered_map<sp<IBinder>, sp<SurfaceControl>, SurfaceComposerClient::IBinderHash>
635                 surfaceControls;
636     };
637 
638     std::unordered_map<CallbackId, CallbackTranslation> mCallbacks GUARDED_BY(mMutex);
639 
640 public:
641     static sp<TransactionCompletedListener> getInstance();
642     static sp<ITransactionCompletedListener> getIInstance();
643 
644     void startListeningLocked() REQUIRES(mMutex);
645 
646     CallbackId addCallbackFunction(
647             const TransactionCompletedCallback& callbackFunction,
648             const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
649                     surfaceControls);
650 
651     void addSurfaceControlToCallbacks(const sp<SurfaceControl>& surfaceControl,
652                                       const std::unordered_set<CallbackId>& callbackIds);
653 
654     // Overrides BnTransactionCompletedListener's onTransactionCompleted
655     void onTransactionCompleted(ListenerStats stats) override;
656 };
657 
658 } // namespace android
659