• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/BlurRegion.h>
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 #include <ui/Rotation.h>
39 
40 #include <gui/CpuConsumer.h>
41 #include <gui/ISurfaceComposer.h>
42 #include <gui/ITransactionCompletedListener.h>
43 #include <gui/LayerState.h>
44 #include <gui/SurfaceControl.h>
45 #include <math/vec3.h>
46 
47 namespace android {
48 
49 class HdrCapabilities;
50 class ISurfaceComposerClient;
51 class IGraphicBufferProducer;
52 class IRegionSamplingListener;
53 class ITunnelModeEnabledListener;
54 class Region;
55 
56 struct SurfaceControlStats {
SurfaceControlStatsSurfaceControlStats57     SurfaceControlStats(const sp<SurfaceControl>& sc, nsecs_t latchTime, nsecs_t acquireTime,
58                         const sp<Fence>& presentFence, const sp<Fence>& prevReleaseFence,
59                         uint32_t hint, FrameEventHistoryStats eventStats)
60           : surfaceControl(sc),
61             latchTime(latchTime),
62             acquireTime(acquireTime),
63             presentFence(presentFence),
64             previousReleaseFence(prevReleaseFence),
65             transformHint(hint),
66             frameEventStats(eventStats) {}
67 
68     sp<SurfaceControl> surfaceControl;
69     nsecs_t latchTime = -1;
70     nsecs_t acquireTime = -1;
71     sp<Fence> presentFence;
72     sp<Fence> previousReleaseFence;
73     uint32_t transformHint = 0;
74     FrameEventHistoryStats frameEventStats;
75 };
76 
77 using TransactionCompletedCallbackTakesContext =
78         std::function<void(void* /*context*/, nsecs_t /*latchTime*/,
79                            const sp<Fence>& /*presentFence*/,
80                            const std::vector<SurfaceControlStats>& /*stats*/)>;
81 using TransactionCompletedCallback =
82         std::function<void(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
83                            const std::vector<SurfaceControlStats>& /*stats*/)>;
84 using ReleaseBufferCallback =
85         std::function<void(const ReleaseCallbackId&, const sp<Fence>& /*releaseFence*/,
86                            uint32_t transformHint, uint32_t currentMaxAcquiredBufferCount)>;
87 
88 using SurfaceStatsCallback =
89         std::function<void(void* /*context*/, nsecs_t /*latchTime*/,
90                            const sp<Fence>& /*presentFence*/,
91                            const SurfaceStats& /*stats*/)>;
92 
93 // ---------------------------------------------------------------------------
94 
95 class SurfaceComposerClient : public RefBase
96 {
97     friend class Composer;
98 public:
99                 SurfaceComposerClient();
100                 SurfaceComposerClient(const sp<ISurfaceComposerClient>& client);
101     virtual     ~SurfaceComposerClient();
102 
103     // Always make sure we could initialize
104     status_t    initCheck() const;
105 
106     // Return the connection of this client
107     sp<IBinder> connection() const;
108 
109     // Forcibly remove connection before all references have gone away.
110     void        dispose();
111 
112     // callback when the composer is dies
113     status_t linkToComposerDeath(const sp<IBinder::DeathRecipient>& recipient,
114             void* cookie = nullptr, uint32_t flags = 0);
115 
116     // Get transactional state of given display.
117     static status_t getDisplayState(const sp<IBinder>& display, ui::DisplayState*);
118 
119     // Get immutable information about given physical display.
120     static status_t getStaticDisplayInfo(const sp<IBinder>& display, ui::StaticDisplayInfo*);
121 
122     // Get dynamic information about given physical display.
123     static status_t getDynamicDisplayInfo(const sp<IBinder>& display, ui::DynamicDisplayInfo*);
124 
125     // Shorthand for the active display mode from getDynamicDisplayInfo().
126     // TODO(b/180391891): Update clients to use getDynamicDisplayInfo and remove this function.
127     static status_t getActiveDisplayMode(const sp<IBinder>& display, ui::DisplayMode*);
128 
129     // Sets the refresh rate boundaries for the display.
130     static status_t setDesiredDisplayModeSpecs(
131             const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode,
132             bool allowGroupSwitching, float primaryRefreshRateMin, float primaryRefreshRateMax,
133             float appRequestRefreshRateMin, float appRequestRefreshRateMax);
134     // Gets the refresh rate boundaries for the display.
135     static status_t getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
136                                                ui::DisplayModeId* outDefaultMode,
137                                                bool* outAllowGroupSwitching,
138                                                float* outPrimaryRefreshRateMin,
139                                                float* outPrimaryRefreshRateMax,
140                                                float* outAppRequestRefreshRateMin,
141                                                float* outAppRequestRefreshRateMax);
142 
143     // Get the coordinates of the display's native color primaries
144     static status_t getDisplayNativePrimaries(const sp<IBinder>& display,
145             ui::DisplayPrimaries& outPrimaries);
146 
147     // Sets the active color mode for the given display
148     static status_t setActiveColorMode(const sp<IBinder>& display,
149             ui::ColorMode colorMode);
150 
151     // Switches on/off Auto Low Latency Mode on the connected display. This should only be
152     // called if the connected display supports Auto Low Latency Mode as reported by
153     // #getAutoLowLatencyModeSupport
154     static void setAutoLowLatencyMode(const sp<IBinder>& display, bool on);
155 
156     // Turns Game mode on/off on the connected display. This should only be called
157     // if the display supports Game content type, as reported by #getGameContentTypeSupport
158     static void setGameContentType(const sp<IBinder>& display, bool on);
159 
160     /* Triggers screen on/off or low power mode and waits for it to complete */
161     static void setDisplayPowerMode(const sp<IBinder>& display, int mode);
162 
163     /* Returns the composition preference of the default data space and default pixel format,
164      * as well as the wide color gamut data space and wide color gamut pixel format.
165      * If the wide color gamut data space is V0_SRGB, then it implies that the platform
166      * has no wide color gamut support.
167      */
168     static status_t getCompositionPreference(ui::Dataspace* defaultDataspace,
169                                              ui::PixelFormat* defaultPixelFormat,
170                                              ui::Dataspace* wideColorGamutDataspace,
171                                              ui::PixelFormat* wideColorGamutPixelFormat);
172 
173     /*
174      * Gets whether SurfaceFlinger can support protected content in GPU composition.
175      * Requires the ACCESS_SURFACE_FLINGER permission.
176      */
177     static bool getProtectedContentSupport();
178 
179     /**
180      * Gets the context priority of surface flinger's render engine.
181      */
182     static int getGPUContextPriority();
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,
218                                          const gui::DisplayBrightness& brightness);
219 
220     static status_t addHdrLayerInfoListener(const sp<IBinder>& displayToken,
221                                             const sp<gui::IHdrLayerInfoListener>& listener);
222     static status_t removeHdrLayerInfoListener(const sp<IBinder>& displayToken,
223                                                const sp<gui::IHdrLayerInfoListener>& listener);
224 
225     /*
226      * Sends a power boost to the composer. This function is asynchronous.
227      *
228      * boostId
229      *      boost id according to android::hardware::power::Boost
230      *
231      * Returns NO_ERROR upon success.
232      */
233     static status_t notifyPowerBoost(int32_t boostId);
234 
235     /*
236      * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows
237      * material design guidelines.
238      *
239      * ambientColor
240      *      Color to the ambient shadow. The alpha is premultiplied.
241      *
242      * spotColor
243      *      Color to the spot shadow. The alpha is premultiplied. The position of the spot shadow
244      *      depends on the light position.
245      *
246      * lightPosY/lightPosZ
247      *      Position of the light used to cast the spot shadow. The X value is always the display
248      *      width / 2.
249      *
250      * lightRadius
251      *      Radius of the light casting the shadow.
252      */
253     static status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
254                                             float lightPosY, float lightPosZ, float lightRadius);
255 
256     // ------------------------------------------------------------------------
257     // surface creation / destruction
258 
259     static sp<SurfaceComposerClient> getDefault();
260 
261     //! Create a surface
262     sp<SurfaceControl> createSurface(const String8& name, // name of the surface
263                                      uint32_t w,          // width in pixel
264                                      uint32_t h,          // height in pixel
265                                      PixelFormat format,  // pixel-format desired
266                                      uint32_t flags = 0,  // usage flags
267                                      const sp<IBinder>& parentHandle = nullptr, // parentHandle
268                                      LayerMetadata metadata = LayerMetadata(),  // metadata
269                                      uint32_t* outTransformHint = nullptr);
270 
271     status_t createSurfaceChecked(const String8& name, // name of the surface
272                                   uint32_t w,          // width in pixel
273                                   uint32_t h,          // height in pixel
274                                   PixelFormat format,  // pixel-format desired
275                                   sp<SurfaceControl>* outSurface,
276                                   uint32_t flags = 0,                        // usage flags
277                                   const sp<IBinder>& parentHandle = nullptr, // parentHandle
278                                   LayerMetadata metadata = LayerMetadata(),  // metadata
279                                   uint32_t* outTransformHint = nullptr);
280 
281     //! Create a surface
282     sp<SurfaceControl> createWithSurfaceParent(const String8& name,       // name of the surface
283                                                uint32_t w,                // width in pixel
284                                                uint32_t h,                // height in pixel
285                                                PixelFormat format,        // pixel-format desired
286                                                uint32_t flags = 0,        // usage flags
287                                                Surface* parent = nullptr, // parent
288                                                LayerMetadata metadata = LayerMetadata(), // metadata
289                                                uint32_t* outTransformHint = nullptr);
290 
291     // Creates a mirrored hierarchy for the mirrorFromSurface. This returns a SurfaceControl
292     // which is a parent of the root of the mirrored hierarchy.
293     //
294     //  Real Hierarchy    Mirror
295     //                      SC (value that's returned)
296     //                      |
297     //      A               A'
298     //      |               |
299     //      B               B'
300     sp<SurfaceControl> mirrorSurface(SurfaceControl* mirrorFromSurface);
301 
302     //! Create a virtual display
303     static sp<IBinder> createDisplay(const String8& displayName, bool secure);
304 
305     //! Destroy a virtual display
306     static void destroyDisplay(const sp<IBinder>& display);
307 
308     //! Get stable IDs for connected physical displays
309     static std::vector<PhysicalDisplayId> getPhysicalDisplayIds();
310     static std::optional<PhysicalDisplayId> getInternalDisplayId();
311 
312     //! Get token for a physical display given its stable ID
313     static sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId);
314     static sp<IBinder> getInternalDisplayToken();
315 
316     static status_t enableVSyncInjections(bool enable);
317 
318     static status_t injectVSync(nsecs_t when);
319 
320     struct SCHash {
operatorSCHash321         std::size_t operator()(const sp<SurfaceControl>& sc) const {
322             return std::hash<SurfaceControl *>{}(sc.get());
323         }
324     };
325 
326     struct IBinderHash {
operatorIBinderHash327         std::size_t operator()(const sp<IBinder>& iBinder) const {
328             return std::hash<IBinder*>{}(iBinder.get());
329         }
330     };
331 
332     struct TCLHash {
operatorTCLHash333         std::size_t operator()(const sp<ITransactionCompletedListener>& tcl) const {
334             return std::hash<IBinder*>{}((tcl) ? IInterface::asBinder(tcl).get() : nullptr);
335         }
336     };
337 
338     struct CallbackInfo {
339         // All the callbacks that have been requested for a TransactionCompletedListener in the
340         // Transaction
341         std::unordered_set<CallbackId, CallbackIdHash> callbackIds;
342         // All the SurfaceControls that have been modified in this TransactionCompletedListener's
343         // process that require a callback if there is one or more callbackIds set.
344         std::unordered_set<sp<SurfaceControl>, SCHash> surfaceControls;
345     };
346 
347     class Transaction : public Parcelable {
348     private:
349         static std::atomic<uint32_t> idCounter;
350         int64_t generateId();
351 
352     protected:
353         std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> mComposerStates;
354         SortedVector<DisplayState> mDisplayStates;
355         std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash>
356                 mListenerCallbacks;
357 
358         uint64_t mId;
359 
360         uint32_t mForceSynchronous = 0;
361         uint32_t mTransactionNestCount = 0;
362         bool mAnimation = false;
363         bool mEarlyWakeupStart = false;
364         bool mEarlyWakeupEnd = false;
365 
366         // Indicates that the Transaction contains a buffer that should be cached
367         bool mContainsBuffer = false;
368 
369         // mDesiredPresentTime is the time in nanoseconds that the client would like the transaction
370         // to be presented. When it is not possible to present at exactly that time, it will be
371         // presented after the time has passed.
372         //
373         // If the client didn't pass a desired presentation time, mDesiredPresentTime will be
374         // populated to the time setBuffer was called, and mIsAutoTimestamp will be set to true.
375         //
376         // Desired present times that are more than 1 second in the future may be ignored.
377         // When a desired present time has already passed, the transaction will be presented as soon
378         // as possible.
379         //
380         // Transactions from the same process are presented in the same order that they are applied.
381         // The desired present time does not affect this ordering.
382         int64_t mDesiredPresentTime = 0;
383         bool mIsAutoTimestamp = true;
384 
385         // The vsync id provided by Choreographer.getVsyncId and the input event id
386         FrameTimelineInfo mFrameTimelineInfo;
387 
388         // If not null, transactions will be queued up using this token otherwise a common token
389         // per process will be used.
390         sp<IBinder> mApplyToken = nullptr;
391 
392         InputWindowCommands mInputWindowCommands;
393         int mStatus = NO_ERROR;
394 
395         layer_state_t* getLayerState(const sp<SurfaceControl>& sc);
396         DisplayState& getDisplayState(const sp<IBinder>& token);
397 
398         void cacheBuffers();
399         void registerSurfaceControlForCallback(const sp<SurfaceControl>& sc);
400         void setReleaseBufferCallback(layer_state_t*, const ReleaseCallbackId&,
401                                       ReleaseBufferCallback);
402         void removeReleaseBufferCallback(layer_state_t*);
403 
404     public:
405         Transaction();
406         virtual ~Transaction() = default;
407         Transaction(Transaction const& other);
408 
409         // Factory method that creates a new Transaction instance from the parcel.
410         static std::unique_ptr<Transaction> createFromParcel(const Parcel* parcel);
411 
412         status_t writeToParcel(Parcel* parcel) const override;
413         status_t readFromParcel(const Parcel* parcel) override;
414 
415         // Clears the contents of the transaction without applying it.
416         void clear();
417 
418         status_t apply(bool synchronous = false);
419         // Merge another transaction in to this one, clearing other
420         // as if it had been applied.
421         Transaction& merge(Transaction&& other);
422         Transaction& show(const sp<SurfaceControl>& sc);
423         Transaction& hide(const sp<SurfaceControl>& sc);
424         Transaction& setPosition(const sp<SurfaceControl>& sc,
425                 float x, float y);
426         Transaction& setSize(const sp<SurfaceControl>& sc,
427                 uint32_t w, uint32_t h);
428         Transaction& setLayer(const sp<SurfaceControl>& sc,
429                 int32_t z);
430 
431         // Sets a Z order relative to the Surface specified by "relativeTo" but
432         // without becoming a full child of the relative. Z-ordering works exactly
433         // as if it were a child however.
434         //
435         // As a nod to sanity, only non-child surfaces may have a relative Z-order.
436         //
437         // This overrides any previous call and is overriden by any future calls
438         // to setLayer.
439         //
440         // If the relative is removed, the Surface will have no layer and be
441         // invisible, until the next time set(Relative)Layer is called.
442         Transaction& setRelativeLayer(const sp<SurfaceControl>& sc,
443                                       const sp<SurfaceControl>& relativeTo, int32_t z);
444         Transaction& setFlags(const sp<SurfaceControl>& sc,
445                 uint32_t flags, uint32_t mask);
446         Transaction& setTransparentRegionHint(const sp<SurfaceControl>& sc,
447                 const Region& transparentRegion);
448         Transaction& setAlpha(const sp<SurfaceControl>& sc,
449                 float alpha);
450         Transaction& setMatrix(const sp<SurfaceControl>& sc,
451                 float dsdx, float dtdx, float dtdy, float dsdy);
452         Transaction& setCrop(const sp<SurfaceControl>& sc, const Rect& crop);
453         Transaction& setCornerRadius(const sp<SurfaceControl>& sc, float cornerRadius);
454         Transaction& setBackgroundBlurRadius(const sp<SurfaceControl>& sc,
455                                              int backgroundBlurRadius);
456         Transaction& setBlurRegions(const sp<SurfaceControl>& sc,
457                                     const std::vector<BlurRegion>& regions);
458         Transaction& setLayerStack(const sp<SurfaceControl>& sc, uint32_t layerStack);
459         Transaction& setMetadata(const sp<SurfaceControl>& sc, uint32_t key, const Parcel& p);
460 
461         /// Reparents the current layer to the new parent handle. The new parent must not be null.
462         Transaction& reparent(const sp<SurfaceControl>& sc, const sp<SurfaceControl>& newParent);
463 
464         Transaction& setColor(const sp<SurfaceControl>& sc, const half3& color);
465 
466         // Sets the background color of a layer with the specified color, alpha, and dataspace
467         Transaction& setBackgroundColor(const sp<SurfaceControl>& sc, const half3& color,
468                                         float alpha, ui::Dataspace dataspace);
469 
470         Transaction& setTransform(const sp<SurfaceControl>& sc, uint32_t transform);
471         Transaction& setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
472                                                   bool transformToDisplayInverse);
473         Transaction& setBuffer(const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer,
474                                const ReleaseCallbackId& id = ReleaseCallbackId::INVALID_ID,
475                                ReleaseBufferCallback callback = nullptr);
476         Transaction& setCachedBuffer(const sp<SurfaceControl>& sc, int32_t bufferId);
477         Transaction& setAcquireFence(const sp<SurfaceControl>& sc, const sp<Fence>& fence);
478         Transaction& setDataspace(const sp<SurfaceControl>& sc, ui::Dataspace dataspace);
479         Transaction& setHdrMetadata(const sp<SurfaceControl>& sc, const HdrMetadata& hdrMetadata);
480         Transaction& setSurfaceDamageRegion(const sp<SurfaceControl>& sc,
481                                             const Region& surfaceDamageRegion);
482         Transaction& setApi(const sp<SurfaceControl>& sc, int32_t api);
483         Transaction& setSidebandStream(const sp<SurfaceControl>& sc,
484                                        const sp<NativeHandle>& sidebandStream);
485         Transaction& setDesiredPresentTime(nsecs_t desiredPresentTime);
486         Transaction& setColorSpaceAgnostic(const sp<SurfaceControl>& sc, const bool agnostic);
487 
488         // Sets information about the priority of the frame.
489         Transaction& setFrameRateSelectionPriority(const sp<SurfaceControl>& sc, int32_t priority);
490 
491         Transaction& addTransactionCallback(TransactionCompletedCallbackTakesContext callback,
492                                             void* callbackContext, CallbackId::Type callbackType);
493 
494         Transaction& addTransactionCompletedCallback(
495                 TransactionCompletedCallbackTakesContext callback, void* callbackContext);
496 
497         Transaction& addTransactionCommittedCallback(
498                 TransactionCompletedCallbackTakesContext callback, void* callbackContext);
499 
500         // ONLY FOR BLAST ADAPTER
501         Transaction& notifyProducerDisconnect(const sp<SurfaceControl>& sc);
502         // Set the framenumber generated by the graphics producer to mimic BufferQueue behaviour.
503         Transaction& setFrameNumber(const sp<SurfaceControl>& sc, uint64_t frameNumber);
504 
505 #ifndef NO_INPUT
506         Transaction& setInputWindowInfo(const sp<SurfaceControl>& sc, const InputWindowInfo& info);
507         Transaction& setFocusedWindow(const FocusRequest& request);
508         Transaction& syncInputWindows();
509 #endif
510 
511         // Set a color transform matrix on the given layer on the built-in display.
512         Transaction& setColorTransform(const sp<SurfaceControl>& sc, const mat3& matrix,
513                                        const vec3& translation);
514 
515         Transaction& setGeometry(const sp<SurfaceControl>& sc,
516                 const Rect& source, const Rect& dst, int transform);
517         Transaction& setShadowRadius(const sp<SurfaceControl>& sc, float cornerRadius);
518 
519         Transaction& setFrameRate(const sp<SurfaceControl>& sc, float frameRate,
520                                   int8_t compatibility, int8_t changeFrameRateStrategy);
521 
522         // Set by window manager indicating the layer and all its children are
523         // in a different orientation than the display. The hint suggests that
524         // the graphic producers should receive a transform hint as if the
525         // display was in this orientation. When the display changes to match
526         // the layer orientation, the graphic producer may not need to allocate
527         // a buffer of a different size.
528         Transaction& setFixedTransformHint(const sp<SurfaceControl>& sc, int32_t transformHint);
529 
530         // Sets the frame timeline vsync id received from choreographer that corresponds
531         // to the transaction, and the input event id that identifies the input event that caused
532         // the current frame.
533         Transaction& setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo);
534 
535         // Indicates that the consumer should acquire the next frame as soon as it
536         // can and not wait for a frame to become available. This is only relevant
537         // in shared buffer mode.
538         Transaction& setAutoRefresh(const sp<SurfaceControl>& sc, bool autoRefresh);
539 
540         // Sets that this surface control and its children are trusted overlays for input
541         Transaction& setTrustedOverlay(const sp<SurfaceControl>& sc, bool isTrustedOverlay);
542 
543         // Queues up transactions using this token in SurfaceFlinger.  By default, all transactions
544         // from a client are placed on the same queue. This can be used to prevent multiple
545         // transactions from blocking each other.
546         Transaction& setApplyToken(const sp<IBinder>& token);
547 
548         /**
549          * Provides the stretch effect configured on a container that the
550          * surface is rendered within.
551          * @param sc target surface the stretch should be applied to
552          * @param stretchEffect the corresponding stretch effect to be applied
553          *    to the surface. This can be directly on the surface itself or
554          *    configured from a parent of the surface in which case the
555          *    StretchEffect provided has parameters mapping the position of
556          *    the surface within the container that has the stretch configured
557          *    on it
558          * @return The transaction being constructed
559          */
560         Transaction& setStretchEffect(const sp<SurfaceControl>& sc,
561                                       const StretchEffect& stretchEffect);
562 
563         Transaction& setBufferCrop(const sp<SurfaceControl>& sc, const Rect& bufferCrop);
564         Transaction& setDestinationFrame(const sp<SurfaceControl>& sc,
565                                          const Rect& destinationFrame);
566 
567         status_t setDisplaySurface(const sp<IBinder>& token,
568                 const sp<IGraphicBufferProducer>& bufferProducer);
569 
570         void setDisplayLayerStack(const sp<IBinder>& token, uint32_t layerStack);
571 
572         /* setDisplayProjection() defines the projection of layer stacks
573          * to a given display.
574          *
575          * - orientation defines the display's orientation.
576          * - layerStackRect defines which area of the window manager coordinate
577          * space will be used.
578          * - displayRect defines where on the display will layerStackRect be
579          * mapped to. displayRect is specified post-orientation, that is
580          * it uses the orientation seen by the end-user.
581          */
582         void setDisplayProjection(const sp<IBinder>& token, ui::Rotation orientation,
583                                   const Rect& layerStackRect, const Rect& displayRect);
584         void setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height);
585         void setAnimationTransaction();
586         void setEarlyWakeupStart();
587         void setEarlyWakeupEnd();
588     };
589 
590     status_t clearLayerFrameStats(const sp<IBinder>& token) const;
591     status_t getLayerFrameStats(const sp<IBinder>& token, FrameStats* outStats) const;
592     static status_t clearAnimationFrameStats();
593     static status_t getAnimationFrameStats(FrameStats* outStats);
594 
595     static status_t overrideHdrTypes(const sp<IBinder>& display,
596                                      const std::vector<ui::Hdr>& hdrTypes);
597 
598     static status_t onPullAtom(const int32_t atomId, std::string* outData, bool* success);
599 
600     static void setDisplayProjection(const sp<IBinder>& token, ui::Rotation orientation,
601                                      const Rect& layerStackRect, const Rect& displayRect);
602 
getClient()603     inline sp<ISurfaceComposerClient> getClient() { return mClient; }
604 
605     static status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
606                                                           ui::PixelFormat* outFormat,
607                                                           ui::Dataspace* outDataspace,
608                                                           uint8_t* outComponentMask);
609     static status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
610                                                      uint8_t componentMask, uint64_t maxFrames);
611 
612     static status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
613                                               uint64_t timestamp, DisplayedFrameStats* outStats);
614     static status_t addRegionSamplingListener(const Rect& samplingArea,
615                                               const sp<IBinder>& stopLayerHandle,
616                                               const sp<IRegionSamplingListener>& listener);
617     static status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener);
618     static status_t addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener);
619     static status_t removeFpsListener(const sp<gui::IFpsListener>& listener);
620     static status_t addTunnelModeEnabledListener(
621             const sp<gui::ITunnelModeEnabledListener>& listener);
622     static status_t removeTunnelModeEnabledListener(
623             const sp<gui::ITunnelModeEnabledListener>& listener);
624 
625 private:
626     virtual void onFirstRef();
627 
628     mutable     Mutex                       mLock;
629                 status_t                    mStatus;
630                 sp<ISurfaceComposerClient>  mClient;
631 };
632 
633 // ---------------------------------------------------------------------------
634 
635 class ScreenshotClient {
636 public:
637     static status_t captureDisplay(const DisplayCaptureArgs& captureArgs,
638                                    const sp<IScreenCaptureListener>& captureListener);
639     static status_t captureDisplay(uint64_t displayOrLayerStack,
640                                    const sp<IScreenCaptureListener>& captureListener);
641     static status_t captureLayers(const LayerCaptureArgs& captureArgs,
642                                   const sp<IScreenCaptureListener>& captureListener);
643 };
644 
645 // ---------------------------------------------------------------------------
646 
647 class JankDataListener : public VirtualLightRefBase {
648 public:
649     virtual ~JankDataListener() = 0;
650     virtual void onJankDataAvailable(const std::vector<JankData>& jankData) = 0;
651 };
652 
653 class TransactionCompletedListener : public BnTransactionCompletedListener {
654     TransactionCompletedListener();
655 
656     int64_t getNextIdLocked() REQUIRES(mMutex);
657 
658     std::mutex mMutex;
659 
660     // This lock needs to be recursive so we can unregister a callback from within that callback.
661     std::recursive_mutex mSurfaceStatsListenerMutex;
662 
663     bool mListening GUARDED_BY(mMutex) = false;
664 
665     int64_t mCallbackIdCounter GUARDED_BY(mMutex) = 1;
666     struct CallbackTranslation {
667         TransactionCompletedCallback callbackFunction;
668         std::unordered_map<sp<IBinder>, sp<SurfaceControl>, SurfaceComposerClient::IBinderHash>
669                 surfaceControls;
670     };
671 
672     struct SurfaceStatsCallbackEntry {
SurfaceStatsCallbackEntrySurfaceStatsCallbackEntry673         SurfaceStatsCallbackEntry(void* context, void* cookie, SurfaceStatsCallback callback)
674                 : context(context),
675                 cookie(cookie),
676                 callback(callback) {}
677 
678         void* context;
679         void* cookie;
680         SurfaceStatsCallback callback;
681     };
682 
683     std::unordered_map<CallbackId, CallbackTranslation, CallbackIdHash> mCallbacks
684             GUARDED_BY(mMutex);
685     std::multimap<sp<IBinder>, sp<JankDataListener>> mJankListeners GUARDED_BY(mMutex);
686     std::unordered_map<ReleaseCallbackId, ReleaseBufferCallback, ReleaseBufferCallbackIdHash>
687             mReleaseBufferCallbacks GUARDED_BY(mMutex);
688 
689     // This is protected by mSurfaceStatsListenerMutex, but GUARDED_BY isn't supported for
690     // std::recursive_mutex
691     std::multimap<sp<IBinder>, SurfaceStatsCallbackEntry> mSurfaceStatsListeners;
692 
693 public:
694     static sp<TransactionCompletedListener> getInstance();
695     static sp<ITransactionCompletedListener> getIInstance();
696 
697     void startListeningLocked() REQUIRES(mMutex);
698 
699     CallbackId addCallbackFunction(
700             const TransactionCompletedCallback& callbackFunction,
701             const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
702                     surfaceControls,
703             CallbackId::Type callbackType);
704 
705     void addSurfaceControlToCallbacks(
706             const sp<SurfaceControl>& surfaceControl,
707             const std::unordered_set<CallbackId, CallbackIdHash>& callbackIds);
708 
709     /*
710      * Adds a jank listener to be informed about SurfaceFlinger's jank classification for a specific
711      * surface. Jank classifications arrive as part of the transaction callbacks about previous
712      * frames submitted to this Surface.
713      */
714     void addJankListener(const sp<JankDataListener>& listener, sp<SurfaceControl> surfaceControl);
715 
716     /**
717      * Removes a jank listener previously added to addJankCallback.
718      */
719     void removeJankListener(const sp<JankDataListener>& listener);
720 
721     void addSurfaceStatsListener(void* context, void* cookie, sp<SurfaceControl> surfaceControl,
722                 SurfaceStatsCallback listener);
723     void removeSurfaceStatsListener(void* context, void* cookie);
724 
725     void setReleaseBufferCallback(const ReleaseCallbackId&, ReleaseBufferCallback);
726     void removeReleaseBufferCallback(const ReleaseCallbackId&);
727 
728     // BnTransactionCompletedListener overrides
729     void onTransactionCompleted(ListenerStats stats) override;
730     void onReleaseBuffer(ReleaseCallbackId, sp<Fence> releaseFence, uint32_t transformHint,
731                          uint32_t currentMaxAcquiredBufferCount) override;
732 
733 private:
734     ReleaseBufferCallback popReleaseBufferCallbackLocked(const ReleaseCallbackId&);
735 };
736 
737 } // namespace android
738