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 #ifndef ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
18 #define ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
19 
20 #include <stdint.h>
21 #include <sys/types.h>
22 #include <set>
23 #include <unordered_map>
24 #include <unordered_set>
25 
26 #include <binder/IBinder.h>
27 
28 #include <utils/RefBase.h>
29 #include <utils/Singleton.h>
30 #include <utils/SortedVector.h>
31 #include <utils/threads.h>
32 
33 #include <ui/ConfigStoreTypes.h>
34 #include <ui/DisplayedFrameStats.h>
35 #include <ui/FrameStats.h>
36 #include <ui/GraphicTypes.h>
37 #include <ui/PixelFormat.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 // ---------------------------------------------------------------------------
49 
50 struct DisplayInfo;
51 class HdrCapabilities;
52 class ISurfaceComposerClient;
53 class IGraphicBufferProducer;
54 class IRegionSamplingListener;
55 class Region;
56 
57 // ---------------------------------------------------------------------------
58 
59 struct SurfaceControlStats {
SurfaceControlStatsSurfaceControlStats60     SurfaceControlStats(const sp<SurfaceControl>& sc, nsecs_t time,
61                         const sp<Fence>& prevReleaseFence)
62           : surfaceControl(sc), acquireTime(time), previousReleaseFence(prevReleaseFence) {}
63 
64     sp<SurfaceControl> surfaceControl;
65     nsecs_t acquireTime = -1;
66     sp<Fence> previousReleaseFence;
67 };
68 
69 using TransactionCompletedCallbackTakesContext =
70         std::function<void(void* /*context*/, nsecs_t /*latchTime*/,
71                            const sp<Fence>& /*presentFence*/,
72                            const std::vector<SurfaceControlStats>& /*stats*/)>;
73 using TransactionCompletedCallback =
74         std::function<void(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
75                            const std::vector<SurfaceControlStats>& /*stats*/)>;
76 
77 // ---------------------------------------------------------------------------
78 
79 class SurfaceComposerClient : public RefBase
80 {
81     friend class Composer;
82 public:
83                 SurfaceComposerClient();
84                 SurfaceComposerClient(const sp<ISurfaceComposerClient>& client);
85     virtual     ~SurfaceComposerClient();
86 
87     // Always make sure we could initialize
88     status_t    initCheck() const;
89 
90     // Return the connection of this client
91     sp<IBinder> connection() const;
92 
93     // Forcibly remove connection before all references have gone away.
94     void        dispose();
95 
96     // callback when the composer is dies
97     status_t linkToComposerDeath(const sp<IBinder::DeathRecipient>& recipient,
98             void* cookie = nullptr, uint32_t flags = 0);
99 
100     // Get a list of supported configurations for a given display
101     static status_t getDisplayConfigs(const sp<IBinder>& display,
102             Vector<DisplayInfo>* configs);
103 
104     // Get the DisplayInfo for the currently-active configuration
105     static status_t getDisplayInfo(const sp<IBinder>& display,
106             DisplayInfo* info);
107 
108     // Get the index of the current active configuration (relative to the list
109     // returned by getDisplayInfo)
110     static int getActiveConfig(const sp<IBinder>& display);
111 
112     // Set a new active configuration using an index relative to the list
113     // returned by getDisplayInfo
114     static status_t setActiveConfig(const sp<IBinder>& display, int id);
115 
116     // Sets the allowed display configurations to be used.
117     // The allowedConfigs in a vector of indexes corresponding to the configurations
118     // returned from getDisplayConfigs().
119     static status_t setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
120                                              const std::vector<int32_t>& allowedConfigs);
121 
122     // Returns the allowed display configurations currently set.
123     // The allowedConfigs in a vector of indexes corresponding to the configurations
124     // returned from getDisplayConfigs().
125     static status_t getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
126                                              std::vector<int32_t>* outAllowedConfigs);
127 
128     // Gets the list of supported color modes for the given display
129     static status_t getDisplayColorModes(const sp<IBinder>& display,
130             Vector<ui::ColorMode>* outColorModes);
131 
132     // Get the coordinates of the display's native color primaries
133     static status_t getDisplayNativePrimaries(const sp<IBinder>& display,
134             ui::DisplayPrimaries& outPrimaries);
135 
136     // Gets the active color mode for the given display
137     static ui::ColorMode getActiveColorMode(const sp<IBinder>& display);
138 
139     // Sets the active color mode for the given display
140     static status_t setActiveColorMode(const sp<IBinder>& display,
141             ui::ColorMode colorMode);
142 
143     /* Triggers screen on/off or low power mode and waits for it to complete */
144     static void setDisplayPowerMode(const sp<IBinder>& display, int mode);
145 
146     /* Returns the composition preference of the default data space and default pixel format,
147      * as well as the wide color gamut data space and wide color gamut pixel format.
148      * If the wide color gamut data space is V0_SRGB, then it implies that the platform
149      * has no wide color gamut support.
150      */
151     static status_t getCompositionPreference(ui::Dataspace* defaultDataspace,
152                                              ui::PixelFormat* defaultPixelFormat,
153                                              ui::Dataspace* wideColorGamutDataspace,
154                                              ui::PixelFormat* wideColorGamutPixelFormat);
155 
156     /*
157      * Gets whether SurfaceFlinger can support protected content in GPU composition.
158      * Requires the ACCESS_SURFACE_FLINGER permission.
159      */
160     static bool getProtectedContentSupport();
161 
162     /**
163      * Called from SurfaceControl d'tor to 'destroy' the surface (or rather, reparent it
164      * to null), but without needing an sp<SurfaceControl> to avoid infinite ressurection.
165      */
166     static void doDropReferenceTransaction(const sp<IBinder>& handle,
167             const sp<ISurfaceComposerClient>& client);
168 
169     /**
170      * Uncaches a buffer in ISurfaceComposer. It must be uncached via a transaction so that it is
171      * in order with other transactions that use buffers.
172      */
173     static void doUncacheBufferTransaction(uint64_t cacheId);
174 
175     // Queries whether a given display is wide color display.
176     static status_t isWideColorDisplay(const sp<IBinder>& display, bool* outIsWideColorDisplay);
177 
178     /*
179      * Returns whether brightness operations are supported on a display.
180      *
181      * displayToken
182      *      The token of the display.
183      *
184      * Returns whether brightness operations are supported on a display or not.
185      */
186     static bool getDisplayBrightnessSupport(const sp<IBinder>& displayToken);
187 
188     /*
189      * Sets the brightness of a display.
190      *
191      * displayToken
192      *      The token of the display whose brightness is set.
193      * brightness
194      *      A number between 0.0 (minimum brightness) and 1.0 (maximum brightness), or -1.0f to
195      *      turn the backlight off.
196      *
197      * Returns NO_ERROR upon success. Otherwise,
198      *      NAME_NOT_FOUND    if the display handle is invalid, or
199      *      BAD_VALUE         if the brightness value is invalid, or
200      *      INVALID_OPERATION if brightness operaetions are not supported.
201      */
202     static status_t setDisplayBrightness(const sp<IBinder>& displayToken, float brightness);
203 
204     /*
205      * Sends a power hint to the composer. This function is asynchronous.
206      *
207      * hintId
208      *      hint id according to android::hardware::power::V1_0::PowerHint
209      *
210      * Returns NO_ERROR upon success.
211      */
212     static status_t notifyPowerHint(int32_t hintId);
213 
214     // ------------------------------------------------------------------------
215     // surface creation / destruction
216 
217     static sp<SurfaceComposerClient> getDefault();
218 
219     //! Create a surface
220     sp<SurfaceControl> createSurface(const String8& name,              // name of the surface
221                                      uint32_t w,                       // width in pixel
222                                      uint32_t h,                       // height in pixel
223                                      PixelFormat format,               // pixel-format desired
224                                      uint32_t flags = 0,               // usage flags
225                                      SurfaceControl* parent = nullptr, // parent
226                                      LayerMetadata metadata = LayerMetadata() // metadata
227     );
228 
229     status_t createSurfaceChecked(const String8& name, // name of the surface
230                                   uint32_t w,          // width in pixel
231                                   uint32_t h,          // height in pixel
232                                   PixelFormat format,  // pixel-format desired
233                                   sp<SurfaceControl>* outSurface,
234                                   uint32_t flags = 0,                      // usage flags
235                                   SurfaceControl* parent = nullptr,        // parent
236                                   LayerMetadata metadata = LayerMetadata() // metadata
237     );
238 
239     //! Create a surface
240     sp<SurfaceControl> createWithSurfaceParent(const String8& name,       // name of the surface
241                                                uint32_t w,                // width in pixel
242                                                uint32_t h,                // height in pixel
243                                                PixelFormat format,        // pixel-format desired
244                                                uint32_t flags = 0,        // usage flags
245                                                Surface* parent = nullptr, // parent
246                                                LayerMetadata metadata = LayerMetadata() // metadata
247     );
248 
249     //! Create a virtual display
250     static sp<IBinder> createDisplay(const String8& displayName, bool secure);
251 
252     //! Destroy a virtual display
253     static void destroyDisplay(const sp<IBinder>& display);
254 
255     //! Get stable IDs for connected physical displays
256     static std::vector<PhysicalDisplayId> getPhysicalDisplayIds();
257     static std::optional<PhysicalDisplayId> getInternalDisplayId();
258 
259     //! Get token for a physical display given its stable ID
260     static sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId);
261     static sp<IBinder> getInternalDisplayToken();
262 
263     static status_t enableVSyncInjections(bool enable);
264 
265     static status_t injectVSync(nsecs_t when);
266 
267     struct SCHash {
operatorSCHash268         std::size_t operator()(const sp<SurfaceControl>& sc) const {
269             return std::hash<SurfaceControl *>{}(sc.get());
270         }
271     };
272 
273     struct TCLHash {
operatorTCLHash274         std::size_t operator()(const sp<ITransactionCompletedListener>& tcl) const {
275             return std::hash<IBinder*>{}((tcl) ? IInterface::asBinder(tcl).get() : nullptr);
276         }
277     };
278 
279     struct CallbackInfo {
280         // All the callbacks that have been requested for a TransactionCompletedListener in the
281         // Transaction
282         std::unordered_set<CallbackId> callbackIds;
283         // All the SurfaceControls that have been modified in this TransactionCompletedListener's
284         // process that require a callback if there is one or more callbackIds set.
285         std::unordered_set<sp<SurfaceControl>, SCHash> surfaceControls;
286     };
287 
288     class Transaction {
289         std::unordered_map<sp<SurfaceControl>, ComposerState, SCHash> mComposerStates;
290         SortedVector<DisplayState > mDisplayStates;
291         std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash>
292                 mListenerCallbacks;
293 
294         uint32_t                    mForceSynchronous = 0;
295         uint32_t                    mTransactionNestCount = 0;
296         bool                        mAnimation = false;
297         bool                        mEarlyWakeup = false;
298 
299         // Indicates that the Transaction contains a buffer that should be cached
300         bool mContainsBuffer = false;
301 
302         // mDesiredPresentTime is the time in nanoseconds that the client would like the transaction
303         // to be presented. When it is not possible to present at exactly that time, it will be
304         // presented after the time has passed.
305         //
306         // Desired present times that are more than 1 second in the future may be ignored.
307         // When a desired present time has already passed, the transaction will be presented as soon
308         // as possible.
309         //
310         // Transactions from the same process are presented in the same order that they are applied.
311         // The desired present time does not affect this ordering.
312         int64_t mDesiredPresentTime = -1;
313 
314         InputWindowCommands mInputWindowCommands;
315         int mStatus = NO_ERROR;
316 
317         layer_state_t* getLayerState(const sp<SurfaceControl>& sc);
318         DisplayState& getDisplayState(const sp<IBinder>& token);
319 
320         void cacheBuffers();
321         void registerSurfaceControlForCallback(const sp<SurfaceControl>& sc);
322 
323     public:
324         Transaction() = default;
325         virtual ~Transaction() = default;
326         Transaction(Transaction const& other);
327 
328         status_t apply(bool synchronous = false);
329         // Merge another transaction in to this one, clearing other
330         // as if it had been applied.
331         Transaction& merge(Transaction&& other);
332         Transaction& show(const sp<SurfaceControl>& sc);
333         Transaction& hide(const sp<SurfaceControl>& sc);
334         Transaction& setPosition(const sp<SurfaceControl>& sc,
335                 float x, float y);
336         Transaction& setSize(const sp<SurfaceControl>& sc,
337                 uint32_t w, uint32_t h);
338         Transaction& setLayer(const sp<SurfaceControl>& sc,
339                 int32_t z);
340 
341         // Sets a Z order relative to the Surface specified by "relativeTo" but
342         // without becoming a full child of the relative. Z-ordering works exactly
343         // as if it were a child however.
344         //
345         // As a nod to sanity, only non-child surfaces may have a relative Z-order.
346         //
347         // This overrides any previous call and is overriden by any future calls
348         // to setLayer.
349         //
350         // If the relative is removed, the Surface will have no layer and be
351         // invisible, until the next time set(Relative)Layer is called.
352         Transaction& setRelativeLayer(const sp<SurfaceControl>& sc,
353                 const sp<IBinder>& relativeTo, int32_t z);
354         Transaction& setFlags(const sp<SurfaceControl>& sc,
355                 uint32_t flags, uint32_t mask);
356         Transaction& setTransparentRegionHint(const sp<SurfaceControl>& sc,
357                 const Region& transparentRegion);
358         Transaction& setAlpha(const sp<SurfaceControl>& sc,
359                 float alpha);
360         Transaction& setMatrix(const sp<SurfaceControl>& sc,
361                 float dsdx, float dtdx, float dtdy, float dsdy);
362         Transaction& setCrop_legacy(const sp<SurfaceControl>& sc, const Rect& crop);
363         Transaction& setCornerRadius(const sp<SurfaceControl>& sc, float cornerRadius);
364         Transaction& setLayerStack(const sp<SurfaceControl>& sc, uint32_t layerStack);
365         Transaction& setMetadata(const sp<SurfaceControl>& sc, uint32_t key, const Parcel& p);
366         // Defers applying any changes made in this transaction until the Layer
367         // identified by handle reaches the given frameNumber. If the Layer identified
368         // by handle is removed, then we will apply this transaction regardless of
369         // what frame number has been reached.
370         Transaction& deferTransactionUntil_legacy(const sp<SurfaceControl>& sc,
371                                                   const sp<IBinder>& handle, uint64_t frameNumber);
372         // A variant of deferTransactionUntil_legacy which identifies the Layer we wait for by
373         // Surface instead of Handle. Useful for clients which may not have the
374         // SurfaceControl for some of their Surfaces. Otherwise behaves identically.
375         Transaction& deferTransactionUntil_legacy(const sp<SurfaceControl>& sc,
376                                                   const sp<Surface>& barrierSurface,
377                                                   uint64_t frameNumber);
378         // Reparents all children of this layer to the new parent handle.
379         Transaction& reparentChildren(const sp<SurfaceControl>& sc,
380                 const sp<IBinder>& newParentHandle);
381 
382         /// Reparents the current layer to the new parent handle. The new parent must not be null.
383         // This can be used instead of reparentChildren if the caller wants to
384         // only re-parent a specific child.
385         Transaction& reparent(const sp<SurfaceControl>& sc,
386                 const sp<IBinder>& newParentHandle);
387 
388         Transaction& setColor(const sp<SurfaceControl>& sc, const half3& color);
389 
390         // Sets the background color of a layer with the specified color, alpha, and dataspace
391         Transaction& setBackgroundColor(const sp<SurfaceControl>& sc, const half3& color,
392                                         float alpha, ui::Dataspace dataspace);
393 
394         Transaction& setTransform(const sp<SurfaceControl>& sc, uint32_t transform);
395         Transaction& setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
396                                                   bool transformToDisplayInverse);
397         Transaction& setCrop(const sp<SurfaceControl>& sc, const Rect& crop);
398         Transaction& setFrame(const sp<SurfaceControl>& sc, const Rect& frame);
399         Transaction& setBuffer(const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer);
400         Transaction& setCachedBuffer(const sp<SurfaceControl>& sc, int32_t bufferId);
401         Transaction& setAcquireFence(const sp<SurfaceControl>& sc, const sp<Fence>& fence);
402         Transaction& setDataspace(const sp<SurfaceControl>& sc, ui::Dataspace dataspace);
403         Transaction& setHdrMetadata(const sp<SurfaceControl>& sc, const HdrMetadata& hdrMetadata);
404         Transaction& setSurfaceDamageRegion(const sp<SurfaceControl>& sc,
405                                             const Region& surfaceDamageRegion);
406         Transaction& setApi(const sp<SurfaceControl>& sc, int32_t api);
407         Transaction& setSidebandStream(const sp<SurfaceControl>& sc,
408                                        const sp<NativeHandle>& sidebandStream);
409         Transaction& setDesiredPresentTime(nsecs_t desiredPresentTime);
410         Transaction& setColorSpaceAgnostic(const sp<SurfaceControl>& sc, const bool agnostic);
411 
412         Transaction& addTransactionCompletedCallback(
413                 TransactionCompletedCallbackTakesContext callback, void* callbackContext);
414 
415         // Detaches all child surfaces (and their children recursively)
416         // from their SurfaceControl.
417         // The child SurfaceControls will not throw exceptions or return errors,
418         // but transactions will have no effect.
419         // The child surfaces will continue to follow their parent surfaces,
420         // and remain eligible for rendering, but their relative state will be
421         // frozen. We use this in the WindowManager, in app shutdown/relaunch
422         // scenarios, where the app would otherwise clean up its child Surfaces.
423         // Sometimes the WindowManager needs to extend their lifetime slightly
424         // in order to perform an exit animation or prevent flicker.
425         Transaction& detachChildren(const sp<SurfaceControl>& sc);
426         // Set an override scaling mode as documented in <system/window.h>
427         // the override scaling mode will take precedence over any client
428         // specified scaling mode. -1 will clear the override scaling mode.
429         Transaction& setOverrideScalingMode(const sp<SurfaceControl>& sc,
430                 int32_t overrideScalingMode);
431 
432         // If the size changes in this transaction, all geometry updates specified
433         // in this transaction will not complete until a buffer of the new size
434         // arrives. As some elements normally apply immediately, this enables
435         // freezing the total geometry of a surface until a resize is completed.
436         Transaction& setGeometryAppliesWithResize(const sp<SurfaceControl>& sc);
437 
438 #ifndef NO_INPUT
439         Transaction& setInputWindowInfo(const sp<SurfaceControl>& sc, const InputWindowInfo& info);
440         Transaction& transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken);
441         Transaction& syncInputWindows();
442 #endif
443 
444         // Set a color transform matrix on the given layer on the built-in display.
445         Transaction& setColorTransform(const sp<SurfaceControl>& sc, const mat3& matrix,
446                                        const vec3& translation);
447 
448         Transaction& setGeometry(const sp<SurfaceControl>& sc,
449                 const Rect& source, const Rect& dst, int transform);
450 
451         status_t setDisplaySurface(const sp<IBinder>& token,
452                 const sp<IGraphicBufferProducer>& bufferProducer);
453 
454         void setDisplayLayerStack(const sp<IBinder>& token, uint32_t layerStack);
455 
456         /* setDisplayProjection() defines the projection of layer stacks
457          * to a given display.
458          *
459          * - orientation defines the display's orientation.
460          * - layerStackRect defines which area of the window manager coordinate
461          * space will be used.
462          * - displayRect defines where on the display will layerStackRect be
463          * mapped to. displayRect is specified post-orientation, that is
464          * it uses the orientation seen by the end-user.
465          */
466         void setDisplayProjection(const sp<IBinder>& token,
467                 uint32_t orientation,
468                 const Rect& layerStackRect,
469                 const Rect& displayRect);
470         void setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height);
471         void setAnimationTransaction();
472         void setEarlyWakeup();
473     };
474 
475     status_t clearLayerFrameStats(const sp<IBinder>& token) const;
476     status_t getLayerFrameStats(const sp<IBinder>& token, FrameStats* outStats) const;
477     static status_t clearAnimationFrameStats();
478     static status_t getAnimationFrameStats(FrameStats* outStats);
479 
480     static status_t getHdrCapabilities(const sp<IBinder>& display,
481             HdrCapabilities* outCapabilities);
482 
483     static void setDisplayProjection(const sp<IBinder>& token,
484             uint32_t orientation,
485             const Rect& layerStackRect,
486             const Rect& displayRect);
487 
getClient()488     inline sp<ISurfaceComposerClient> getClient() { return mClient; }
489 
490     static status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
491                                                           ui::PixelFormat* outFormat,
492                                                           ui::Dataspace* outDataspace,
493                                                           uint8_t* outComponentMask);
494     static status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
495                                                      uint8_t componentMask, uint64_t maxFrames);
496 
497     static status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
498                                               uint64_t timestamp, DisplayedFrameStats* outStats);
499     static status_t addRegionSamplingListener(const Rect& samplingArea,
500                                               const sp<IBinder>& stopLayerHandle,
501                                               const sp<IRegionSamplingListener>& listener);
502     static status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener);
503 
504 private:
505     virtual void onFirstRef();
506 
507     mutable     Mutex                       mLock;
508                 status_t                    mStatus;
509                 sp<ISurfaceComposerClient>  mClient;
510 };
511 
512 // ---------------------------------------------------------------------------
513 
514 class ScreenshotClient {
515 public:
516     // if cropping isn't required, callers may pass in a default Rect, e.g.:
517     //   capture(display, producer, Rect(), reqWidth, ...);
518     static status_t capture(const sp<IBinder>& display, const ui::Dataspace reqDataSpace,
519                             const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
520                             uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform,
521                             uint32_t rotation, bool captureSecureLayers,
522                             sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers);
523     static status_t capture(const sp<IBinder>& display, const ui::Dataspace reqDataSpace,
524                             const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
525                             uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform,
526                             uint32_t rotation, sp<GraphicBuffer>* outBuffer);
527     static status_t capture(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
528                             sp<GraphicBuffer>* outBuffer);
529     static status_t captureLayers(const sp<IBinder>& layerHandle, const ui::Dataspace reqDataSpace,
530                                   const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
531                                   float frameScale, sp<GraphicBuffer>* outBuffer);
532     static status_t captureChildLayers(
533             const sp<IBinder>& layerHandle, const ui::Dataspace reqDataSpace,
534             const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
535             const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>&
536                     excludeHandles,
537             float frameScale, sp<GraphicBuffer>* outBuffer);
538 };
539 
540 // ---------------------------------------------------------------------------
541 
542 class TransactionCompletedListener : public BnTransactionCompletedListener {
543     TransactionCompletedListener();
544 
545     CallbackId getNextIdLocked() REQUIRES(mMutex);
546 
547     std::mutex mMutex;
548 
549     bool mListening GUARDED_BY(mMutex) = false;
550 
551     CallbackId mCallbackIdCounter GUARDED_BY(mMutex) = 1;
552 
553     struct IBinderHash {
operatorIBinderHash554         std::size_t operator()(const sp<IBinder>& iBinder) const {
555             return std::hash<IBinder*>{}(iBinder.get());
556         }
557     };
558 
559     struct CallbackTranslation {
560         TransactionCompletedCallback callbackFunction;
561         std::unordered_map<sp<IBinder>, sp<SurfaceControl>, IBinderHash> surfaceControls;
562     };
563 
564     std::unordered_map<CallbackId, CallbackTranslation> mCallbacks GUARDED_BY(mMutex);
565 
566 public:
567     static sp<TransactionCompletedListener> getInstance();
568     static sp<ITransactionCompletedListener> getIInstance();
569 
570     void startListeningLocked() REQUIRES(mMutex);
571 
572     CallbackId addCallbackFunction(
573             const TransactionCompletedCallback& callbackFunction,
574             const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
575                     surfaceControls);
576 
577     void addSurfaceControlToCallbacks(const sp<SurfaceControl>& surfaceControl,
578                                       const std::unordered_set<CallbackId>& callbackIds);
579 
580     // Overrides BnTransactionCompletedListener's onTransactionCompleted
581     void onTransactionCompleted(ListenerStats stats) override;
582 };
583 
584 // ---------------------------------------------------------------------------
585 
586 }; // namespace android
587 
588 #endif // ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
589