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