1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
18 #define ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
19 
20 #include <stdint.h>
21 #include <sys/types.h>
22 #include <unordered_map>
23 
24 #include <binder/IBinder.h>
25 
26 #include <utils/RefBase.h>
27 #include <utils/Singleton.h>
28 #include <utils/SortedVector.h>
29 #include <utils/threads.h>
30 
31 #include <ui/FrameStats.h>
32 #include <ui/GraphicTypes.h>
33 #include <ui/PixelFormat.h>
34 
35 #include <gui/CpuConsumer.h>
36 #include <gui/SurfaceControl.h>
37 #include <math/vec3.h>
38 #include <gui/LayerState.h>
39 
40 namespace android {
41 
42 // ---------------------------------------------------------------------------
43 
44 struct DisplayInfo;
45 class HdrCapabilities;
46 class ISurfaceComposerClient;
47 class IGraphicBufferProducer;
48 class Region;
49 
50 // ---------------------------------------------------------------------------
51 
52 class SurfaceComposerClient : public RefBase
53 {
54     friend class Composer;
55 public:
56                 SurfaceComposerClient();
57                 SurfaceComposerClient(const sp<ISurfaceComposerClient>& client);
58                 SurfaceComposerClient(const sp<IGraphicBufferProducer>& parent);
59     virtual     ~SurfaceComposerClient();
60 
61     // Always make sure we could initialize
62     status_t    initCheck() const;
63 
64     // Return the connection of this client
65     sp<IBinder> connection() const;
66 
67     // Forcibly remove connection before all references have gone away.
68     void        dispose();
69 
70     // callback when the composer is dies
71     status_t linkToComposerDeath(const sp<IBinder::DeathRecipient>& recipient,
72             void* cookie = NULL, uint32_t flags = 0);
73 
74     // Get a list of supported configurations for a given display
75     static status_t getDisplayConfigs(const sp<IBinder>& display,
76             Vector<DisplayInfo>* configs);
77 
78     // Get the DisplayInfo for the currently-active configuration
79     static status_t getDisplayInfo(const sp<IBinder>& display,
80             DisplayInfo* info);
81 
82     // Get the index of the current active configuration (relative to the list
83     // returned by getDisplayInfo)
84     static int getActiveConfig(const sp<IBinder>& display);
85 
86     // Set a new active configuration using an index relative to the list
87     // returned by getDisplayInfo
88     static status_t setActiveConfig(const sp<IBinder>& display, int id);
89 
90     // Gets the list of supported color modes for the given display
91     static status_t getDisplayColorModes(const sp<IBinder>& display,
92             Vector<ui::ColorMode>* outColorModes);
93 
94     // Gets the active color mode for the given display
95     static ui::ColorMode getActiveColorMode(const sp<IBinder>& display);
96 
97     // Sets the active color mode for the given display
98     static status_t setActiveColorMode(const sp<IBinder>& display,
99             ui::ColorMode colorMode);
100 
101     /* Triggers screen on/off or low power mode and waits for it to complete */
102     static void setDisplayPowerMode(const sp<IBinder>& display, int mode);
103 
104     // ------------------------------------------------------------------------
105     // surface creation / destruction
106 
107     //! Create a surface
108     sp<SurfaceControl> createSurface(
109             const String8& name,// name of the surface
110             uint32_t w,         // width in pixel
111             uint32_t h,         // height in pixel
112             PixelFormat format, // pixel-format desired
113             uint32_t flags = 0, // usage flags
114             SurfaceControl* parent = nullptr, // parent
115             int32_t windowType = -1, // from WindowManager.java (STATUS_BAR, INPUT_METHOD, etc.)
116             int32_t ownerUid = -1 // UID of the task
117     );
118 
119     status_t createSurfaceChecked(
120             const String8& name,// name of the surface
121             uint32_t w,         // width in pixel
122             uint32_t h,         // height in pixel
123             PixelFormat format, // pixel-format desired
124             sp<SurfaceControl>* outSurface,
125             uint32_t flags = 0, // usage flags
126             SurfaceControl* parent = nullptr, // parent
127             int32_t windowType = -1, // from WindowManager.java (STATUS_BAR, INPUT_METHOD, etc.)
128             int32_t ownerUid = -1 // UID of the task
129     );
130 
131     //! Create a virtual display
132     static sp<IBinder> createDisplay(const String8& displayName, bool secure);
133 
134     //! Destroy a virtual display
135     static void destroyDisplay(const sp<IBinder>& display);
136 
137     //! Get the token for the existing default displays.
138     //! Possible values for id are eDisplayIdMain and eDisplayIdHdmi.
139     static sp<IBinder> getBuiltInDisplay(int32_t id);
140 
141     static status_t enableVSyncInjections(bool enable);
142 
143     static status_t injectVSync(nsecs_t when);
144 
145     struct SCHash {
operatorSCHash146         std::size_t operator()(const sp<SurfaceControl>& sc) const {
147             return std::hash<SurfaceControl *>{}(sc.get());
148         }
149     };
150 
151     class Transaction {
152         std::unordered_map<sp<SurfaceControl>, ComposerState, SCHash> mComposerStates;
153         SortedVector<DisplayState > mDisplayStates;
154         uint32_t                    mForceSynchronous = 0;
155         uint32_t                    mTransactionNestCount = 0;
156         bool                        mAnimation = false;
157         bool                        mEarlyWakeup = false;
158 
159         int mStatus = NO_ERROR;
160 
161         layer_state_t* getLayerState(const sp<SurfaceControl>& sc);
162         DisplayState& getDisplayState(const sp<IBinder>& token);
163 
164     public:
165         Transaction() = default;
166         virtual ~Transaction() = default;
167         Transaction(Transaction const& other);
168 
169         status_t apply(bool synchronous = false);
170         // Merge another transaction in to this one, clearing other
171         // as if it had been applied.
172         Transaction& merge(Transaction&& other);
173         Transaction& show(const sp<SurfaceControl>& sc);
174         Transaction& hide(const sp<SurfaceControl>& sc);
175         Transaction& setPosition(const sp<SurfaceControl>& sc,
176                 float x, float y);
177         Transaction& setSize(const sp<SurfaceControl>& sc,
178                 uint32_t w, uint32_t h);
179         Transaction& setLayer(const sp<SurfaceControl>& sc,
180                 int32_t z);
181 
182         // Sets a Z order relative to the Surface specified by "relativeTo" but
183         // without becoming a full child of the relative. Z-ordering works exactly
184         // as if it were a child however.
185         //
186         // As a nod to sanity, only non-child surfaces may have a relative Z-order.
187         //
188         // This overrides any previous call and is overriden by any future calls
189         // to setLayer.
190         //
191         // If the relative is removed, the Surface will have no layer and be
192         // invisible, until the next time set(Relative)Layer is called.
193         Transaction& setRelativeLayer(const sp<SurfaceControl>& sc,
194                 const sp<IBinder>& relativeTo, int32_t z);
195         Transaction& setFlags(const sp<SurfaceControl>& sc,
196                 uint32_t flags, uint32_t mask);
197         Transaction& setTransparentRegionHint(const sp<SurfaceControl>& sc,
198                 const Region& transparentRegion);
199         Transaction& setAlpha(const sp<SurfaceControl>& sc,
200                 float alpha);
201         Transaction& setMatrix(const sp<SurfaceControl>& sc,
202                 float dsdx, float dtdx, float dtdy, float dsdy);
203         Transaction& setCrop(const sp<SurfaceControl>& sc, const Rect& crop);
204         Transaction& setFinalCrop(const sp<SurfaceControl>& sc, const Rect& crop);
205         Transaction& setLayerStack(const sp<SurfaceControl>& sc, uint32_t layerStack);
206         // Defers applying any changes made in this transaction until the Layer
207         // identified by handle reaches the given frameNumber. If the Layer identified
208         // by handle is removed, then we will apply this transaction regardless of
209         // what frame number has been reached.
210         Transaction& deferTransactionUntil(const sp<SurfaceControl>& sc,
211                 const sp<IBinder>& handle,
212                 uint64_t frameNumber);
213         // A variant of deferTransactionUntil which identifies the Layer we wait for by
214         // Surface instead of Handle. Useful for clients which may not have the
215         // SurfaceControl for some of their Surfaces. Otherwise behaves identically.
216         Transaction& deferTransactionUntil(const sp<SurfaceControl>& sc,
217                 const sp<Surface>& barrierSurface,
218                 uint64_t frameNumber);
219         // Reparents all children of this layer to the new parent handle.
220         Transaction& reparentChildren(const sp<SurfaceControl>& sc,
221                 const sp<IBinder>& newParentHandle);
222 
223         /// Reparents the current layer to the new parent handle. The new parent must not be null.
224         // This can be used instead of reparentChildren if the caller wants to
225         // only re-parent a specific child.
226         Transaction& reparent(const sp<SurfaceControl>& sc,
227                 const sp<IBinder>& newParentHandle);
228 
229         Transaction& setColor(const sp<SurfaceControl>& sc, const half3& color);
230 
231         // Detaches all child surfaces (and their children recursively)
232         // from their SurfaceControl.
233         // The child SurfaceControls will not throw exceptions or return errors,
234         // but transactions will have no effect.
235         // The child surfaces will continue to follow their parent surfaces,
236         // and remain eligible for rendering, but their relative state will be
237         // frozen. We use this in the WindowManager, in app shutdown/relaunch
238         // scenarios, where the app would otherwise clean up its child Surfaces.
239         // Sometimes the WindowManager needs to extend their lifetime slightly
240         // in order to perform an exit animation or prevent flicker.
241         Transaction& detachChildren(const sp<SurfaceControl>& sc);
242         // Set an override scaling mode as documented in <system/window.h>
243         // the override scaling mode will take precedence over any client
244         // specified scaling mode. -1 will clear the override scaling mode.
245         Transaction& setOverrideScalingMode(const sp<SurfaceControl>& sc,
246                 int32_t overrideScalingMode);
247 
248         // If the size changes in this transaction, all geometry updates specified
249         // in this transaction will not complete until a buffer of the new size
250         // arrives. As some elements normally apply immediately, this enables
251         // freezing the total geometry of a surface until a resize is completed.
252         Transaction& setGeometryAppliesWithResize(const sp<SurfaceControl>& sc);
253 
254         Transaction& destroySurface(const sp<SurfaceControl>& sc);
255 
256         status_t setDisplaySurface(const sp<IBinder>& token,
257                 const sp<IGraphicBufferProducer>& bufferProducer);
258 
259         void setDisplayLayerStack(const sp<IBinder>& token, uint32_t layerStack);
260 
261         /* setDisplayProjection() defines the projection of layer stacks
262          * to a given display.
263          *
264          * - orientation defines the display's orientation.
265          * - layerStackRect defines which area of the window manager coordinate
266          * space will be used.
267          * - displayRect defines where on the display will layerStackRect be
268          * mapped to. displayRect is specified post-orientation, that is
269          * it uses the orientation seen by the end-user.
270          */
271         void setDisplayProjection(const sp<IBinder>& token,
272                 uint32_t orientation,
273                 const Rect& layerStackRect,
274                 const Rect& displayRect);
275         void setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height);
276         void setAnimationTransaction();
277         void setEarlyWakeup();
278     };
279 
280     status_t    destroySurface(const sp<IBinder>& id);
281 
282     status_t clearLayerFrameStats(const sp<IBinder>& token) const;
283     status_t getLayerFrameStats(const sp<IBinder>& token, FrameStats* outStats) const;
284     static status_t clearAnimationFrameStats();
285     static status_t getAnimationFrameStats(FrameStats* outStats);
286 
287     static status_t getHdrCapabilities(const sp<IBinder>& display,
288             HdrCapabilities* outCapabilities);
289 
290     static void setDisplayProjection(const sp<IBinder>& token,
291             uint32_t orientation,
292             const Rect& layerStackRect,
293             const Rect& displayRect);
294 
getClient()295     inline sp<ISurfaceComposerClient> getClient() { return mClient; }
296 
297 private:
298     virtual void onFirstRef();
299 
300     mutable     Mutex                       mLock;
301                 status_t                    mStatus;
302                 sp<ISurfaceComposerClient>  mClient;
303                 wp<IGraphicBufferProducer>  mParent;
304 };
305 
306 // ---------------------------------------------------------------------------
307 
308 class ScreenshotClient {
309 public:
310     // if cropping isn't required, callers may pass in a default Rect, e.g.:
311     //   capture(display, producer, Rect(), reqWidth, ...);
312     static status_t capture(const sp<IBinder>& display, Rect sourceCrop, uint32_t reqWidth,
313                             uint32_t reqHeight, int32_t minLayerZ, int32_t maxLayerZ,
314                             bool useIdentityTransform, uint32_t rotation,
315                             sp<GraphicBuffer>* outBuffer);
316     static status_t captureLayers(const sp<IBinder>& layerHandle, Rect sourceCrop, float frameScale,
317                                   sp<GraphicBuffer>* outBuffer);
318     static status_t captureChildLayers(const sp<IBinder>& layerHandle, Rect sourceCrop,
319                                        float frameScale, sp<GraphicBuffer>* outBuffer);
320 };
321 
322 // ---------------------------------------------------------------------------
323 }; // namespace android
324 
325 #endif // ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
326