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