1 /*
2  * Copyright (C) 2006 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_ISURFACE_COMPOSER_H
18 #define ANDROID_GUI_ISURFACE_COMPOSER_H
19 
20 #include <stdint.h>
21 #include <sys/types.h>
22 
23 #include <binder/IBinder.h>
24 #include <binder/IInterface.h>
25 
26 #include <gui/ITransactionCompletedListener.h>
27 
28 #include <ui/ConfigStoreTypes.h>
29 #include <ui/DisplayedFrameStats.h>
30 #include <ui/FrameStats.h>
31 #include <ui/GraphicBuffer.h>
32 #include <ui/GraphicTypes.h>
33 #include <ui/PixelFormat.h>
34 
35 #include <utils/Errors.h>
36 #include <utils/RefBase.h>
37 #include <utils/Timers.h>
38 #include <utils/Vector.h>
39 
40 #include <optional>
41 #include <unordered_set>
42 #include <vector>
43 
44 namespace android {
45 // ----------------------------------------------------------------------------
46 
47 struct client_cache_t;
48 struct ComposerState;
49 struct DisplayState;
50 struct DisplayInfo;
51 struct DisplayStatInfo;
52 struct InputWindowCommands;
53 class LayerDebugInfo;
54 class HdrCapabilities;
55 class IDisplayEventConnection;
56 class IGraphicBufferProducer;
57 class ISurfaceComposerClient;
58 class IRegionSamplingListener;
59 class Rect;
60 enum class FrameEvent;
61 
62 /*
63  * This class defines the Binder IPC interface for accessing various
64  * SurfaceFlinger features.
65  */
66 class ISurfaceComposer: public IInterface {
67 public:
68     DECLARE_META_INTERFACE(SurfaceComposer)
69 
70     // flags for setTransactionState()
71     enum {
72         eSynchronous = 0x01,
73         eAnimation   = 0x02,
74 
75         // Indicates that this transaction will likely result in a lot of layers being composed, and
76         // thus, SurfaceFlinger should wake-up earlier to avoid missing frame deadlines. In this
77         // case SurfaceFlinger will wake up at (sf vsync offset - debug.sf.early_phase_offset_ns)
78         eEarlyWakeup = 0x04
79     };
80 
81     enum Rotation {
82         eRotateNone = 0,
83         eRotate90   = 1,
84         eRotate180  = 2,
85         eRotate270  = 3
86     };
87 
88     enum VsyncSource {
89         eVsyncSourceApp = 0,
90         eVsyncSourceSurfaceFlinger = 1
91     };
92 
93     enum ConfigChanged { eConfigChangedSuppress = 0, eConfigChangedDispatch = 1 };
94 
95     /*
96      * Create a connection with SurfaceFlinger.
97      */
98     virtual sp<ISurfaceComposerClient> createConnection() = 0;
99 
100     /* return an IDisplayEventConnection */
101     virtual sp<IDisplayEventConnection> createDisplayEventConnection(
102             VsyncSource vsyncSource = eVsyncSourceApp,
103             ConfigChanged configChanged = eConfigChangedSuppress) = 0;
104 
105     /* create a virtual display
106      * requires ACCESS_SURFACE_FLINGER permission.
107      */
108     virtual sp<IBinder> createDisplay(const String8& displayName,
109             bool secure) = 0;
110 
111     /* destroy a virtual display
112      * requires ACCESS_SURFACE_FLINGER permission.
113      */
114     virtual void destroyDisplay(const sp<IBinder>& display) = 0;
115 
116     /* get stable IDs for connected physical displays.
117      */
118     virtual std::vector<PhysicalDisplayId> getPhysicalDisplayIds() const = 0;
119 
120     // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic.
getInternalDisplayId()121     std::optional<PhysicalDisplayId> getInternalDisplayId() const {
122         const auto displayIds = getPhysicalDisplayIds();
123         return displayIds.empty() ? std::nullopt : std::make_optional(displayIds.front());
124     }
125 
126     /* get token for a physical display given its stable ID obtained via getPhysicalDisplayIds or a
127      * DisplayEventReceiver hotplug event.
128      */
129     virtual sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId) const = 0;
130 
131     // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic.
getInternalDisplayToken()132     sp<IBinder> getInternalDisplayToken() const {
133         const auto displayId = getInternalDisplayId();
134         return displayId ? getPhysicalDisplayToken(*displayId) : nullptr;
135     }
136 
137     /* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */
138     virtual void setTransactionState(const Vector<ComposerState>& state,
139                                      const Vector<DisplayState>& displays, uint32_t flags,
140                                      const sp<IBinder>& applyToken,
141                                      const InputWindowCommands& inputWindowCommands,
142                                      int64_t desiredPresentTime,
143                                      const client_cache_t& uncacheBuffer,
144                                      const std::vector<ListenerCallbacks>& listenerCallbacks) = 0;
145 
146     /* signal that we're done booting.
147      * Requires ACCESS_SURFACE_FLINGER permission
148      */
149     virtual void bootFinished() = 0;
150 
151     /* verify that an IGraphicBufferProducer was created by SurfaceFlinger.
152      */
153     virtual bool authenticateSurfaceTexture(
154             const sp<IGraphicBufferProducer>& surface) const = 0;
155 
156     /* Returns the frame timestamps supported by SurfaceFlinger.
157      */
158     virtual status_t getSupportedFrameTimestamps(
159             std::vector<FrameEvent>* outSupported) const = 0;
160 
161     /* set display power mode. depending on the mode, it can either trigger
162      * screen on, off or low power mode and wait for it to complete.
163      * requires ACCESS_SURFACE_FLINGER permission.
164      */
165     virtual void setPowerMode(const sp<IBinder>& display, int mode) = 0;
166 
167     /* returns information for each configuration of the given display
168      * intended to be used to get information about built-in displays */
169     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
170             Vector<DisplayInfo>* configs) = 0;
171 
172     /* returns display statistics for a given display
173      * intended to be used by the media framework to properly schedule
174      * video frames */
175     virtual status_t getDisplayStats(const sp<IBinder>& display,
176             DisplayStatInfo* stats) = 0;
177 
178     /* indicates which of the configurations returned by getDisplayInfo is
179      * currently active */
180     virtual int getActiveConfig(const sp<IBinder>& display) = 0;
181 
182     /* specifies which configuration (of those returned by getDisplayInfo)
183      * should be used */
184     virtual status_t setActiveConfig(const sp<IBinder>& display, int id) = 0;
185 
186     virtual status_t getDisplayColorModes(const sp<IBinder>& display,
187             Vector<ui::ColorMode>* outColorModes) = 0;
188     virtual status_t getDisplayNativePrimaries(const sp<IBinder>& display,
189             ui::DisplayPrimaries& primaries) = 0;
190     virtual ui::ColorMode getActiveColorMode(const sp<IBinder>& display) = 0;
191     virtual status_t setActiveColorMode(const sp<IBinder>& display,
192             ui::ColorMode colorMode) = 0;
193 
194     /**
195      * Capture the specified screen. This requires READ_FRAME_BUFFER
196      * permission.  This function will fail if there is a secure window on
197      * screen.
198      *
199      * This function can capture a subregion (the source crop) of the screen.
200      * The subregion can be optionally rotated.  It will also be scaled to
201      * match the size of the output buffer.
202      *
203      * reqDataspace and reqPixelFormat specify the data space and pixel format
204      * of the buffer. The caller should pick the data space and pixel format
205      * that it can consume.
206      *
207      * sourceCrop is the crop on the logical display.
208      *
209      * reqWidth and reqHeight specifies the size of the buffer.  When either
210      * of them is 0, they are set to the size of the logical display viewport.
211      *
212      * When useIdentityTransform is true, layer transformations are disabled.
213      *
214      * rotation specifies the rotation of the source crop (and the pixels in
215      * it) around its center.
216      */
217     virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
218                                    bool& outCapturedSecureLayers, const ui::Dataspace reqDataspace,
219                                    const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
220                                    uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform,
221                                    Rotation rotation = eRotateNone,
222                                    bool captureSecureLayers = false) = 0;
223     /**
224      * Capture the specified screen. This requires READ_FRAME_BUFFER
225      * permission.  This function will fail if there is a secure window on
226      * screen.
227      *
228      * This function can capture a subregion (the source crop) of the screen
229      * into an sRGB buffer with RGBA_8888 pixel format.
230      * The subregion can be optionally rotated.  It will also be scaled to
231      * match the size of the output buffer.
232      *
233      * At the moment, sourceCrop is ignored and is always set to the visible
234      * region (projected display viewport) of the screen.
235      *
236      * reqWidth and reqHeight specifies the size of the buffer.  When either
237      * of them is 0, they are set to the size of the logical display viewport.
238      *
239      * When useIdentityTransform is true, layer transformations are disabled.
240      *
241      * rotation specifies the rotation of the source crop (and the pixels in
242      * it) around its center.
243      */
244     virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
245                                    Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
246                                    bool useIdentityTransform, Rotation rotation = eRotateNone) {
247         bool outIgnored;
248         return captureScreen(display, outBuffer, outIgnored, ui::Dataspace::V0_SRGB,
249                              ui::PixelFormat::RGBA_8888, sourceCrop, reqWidth, reqHeight,
250                              useIdentityTransform, rotation);
251     }
252 
253     virtual status_t captureScreen(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
254                                    sp<GraphicBuffer>* outBuffer) = 0;
255 
256     template <class AA>
257     struct SpHash {
operatorSpHash258         size_t operator()(const sp<AA>& k) const { return std::hash<AA*>()(k.get()); }
259     };
260 
261     /**
262      * Capture a subtree of the layer hierarchy, potentially ignoring the root node.
263      *
264      * reqDataspace and reqPixelFormat specify the data space and pixel format
265      * of the buffer. The caller should pick the data space and pixel format
266      * that it can consume.
267      */
268     virtual status_t captureLayers(
269             const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
270             const ui::Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat,
271             const Rect& sourceCrop,
272             const std::unordered_set<sp<IBinder>, SpHash<IBinder>>& excludeHandles,
273             float frameScale = 1.0, bool childrenOnly = false) = 0;
274 
275     /**
276      * Capture a subtree of the layer hierarchy into an sRGB buffer with RGBA_8888 pixel format,
277      * potentially ignoring the root node.
278      */
279     status_t captureLayers(const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
280                            const Rect& sourceCrop, float frameScale = 1.0,
281                            bool childrenOnly = false) {
282         return captureLayers(layerHandleBinder, outBuffer, ui::Dataspace::V0_SRGB,
283                              ui::PixelFormat::RGBA_8888, sourceCrop, {}, frameScale, childrenOnly);
284     }
285 
286     /* Clears the frame statistics for animations.
287      *
288      * Requires the ACCESS_SURFACE_FLINGER permission.
289      */
290     virtual status_t clearAnimationFrameStats() = 0;
291 
292     /* Gets the frame statistics for animations.
293      *
294      * Requires the ACCESS_SURFACE_FLINGER permission.
295      */
296     virtual status_t getAnimationFrameStats(FrameStats* outStats) const = 0;
297 
298     /* Gets the supported HDR capabilities of the given display.
299      *
300      * Requires the ACCESS_SURFACE_FLINGER permission.
301      */
302     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
303             HdrCapabilities* outCapabilities) const = 0;
304 
305     virtual status_t enableVSyncInjections(bool enable) = 0;
306 
307     virtual status_t injectVSync(nsecs_t when) = 0;
308 
309     /* Gets the list of active layers in Z order for debugging purposes
310      *
311      * Requires the ACCESS_SURFACE_FLINGER permission.
312      */
313     virtual status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const = 0;
314 
315     virtual status_t getColorManagement(bool* outGetColorManagement) const = 0;
316 
317     /* Gets the composition preference of the default data space and default pixel format,
318      * as well as the wide color gamut data space and wide color gamut pixel format.
319      * If the wide color gamut data space is V0_SRGB, then it implies that the platform
320      * has no wide color gamut support.
321      *
322      * Requires the ACCESS_SURFACE_FLINGER permission.
323      */
324     virtual status_t getCompositionPreference(ui::Dataspace* defaultDataspace,
325                                               ui::PixelFormat* defaultPixelFormat,
326                                               ui::Dataspace* wideColorGamutDataspace,
327                                               ui::PixelFormat* wideColorGamutPixelFormat) const = 0;
328     /*
329      * Requires the ACCESS_SURFACE_FLINGER permission.
330      */
331     virtual status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
332                                                            ui::PixelFormat* outFormat,
333                                                            ui::Dataspace* outDataspace,
334                                                            uint8_t* outComponentMask) const = 0;
335 
336     /* Turns on the color sampling engine on the display.
337      *
338      * Requires the ACCESS_SURFACE_FLINGER permission.
339      */
340     virtual status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
341                                                       uint8_t componentMask,
342                                                       uint64_t maxFrames) const = 0;
343 
344     /* Returns statistics on the color profile of the last frame displayed for a given display
345      *
346      * Requires the ACCESS_SURFACE_FLINGER permission.
347      */
348     virtual status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
349                                                uint64_t timestamp,
350                                                DisplayedFrameStats* outStats) const = 0;
351 
352     /*
353      * Gets whether SurfaceFlinger can support protected content in GPU composition.
354      * Requires the ACCESS_SURFACE_FLINGER permission.
355      */
356     virtual status_t getProtectedContentSupport(bool* outSupported) const = 0;
357 
358     /*
359      * Queries whether the given display is a wide color display.
360      * Requires the ACCESS_SURFACE_FLINGER permission.
361      */
362     virtual status_t isWideColorDisplay(const sp<IBinder>& token,
363                                         bool* outIsWideColorDisplay) const = 0;
364 
365     /* Registers a listener to stream median luma updates from SurfaceFlinger.
366      *
367      * The sampling area is bounded by both samplingArea and the given stopLayerHandle
368      * (i.e., only layers behind the stop layer will be captured and sampled).
369      *
370      * Multiple listeners may be provided so long as they have independent listeners.
371      * If multiple listeners are provided, the effective sampling region for each listener will
372      * be bounded by whichever stop layer has a lower Z value.
373      *
374      * Requires the same permissions as captureLayers and captureScreen.
375      */
376     virtual status_t addRegionSamplingListener(const Rect& samplingArea,
377                                                const sp<IBinder>& stopLayerHandle,
378                                                const sp<IRegionSamplingListener>& listener) = 0;
379 
380     /*
381      * Removes a listener that was streaming median luma updates from SurfaceFlinger.
382      */
383     virtual status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) = 0;
384 
385     /*
386      * Sets the allowed display configurations to be used.
387      * The allowedConfigs in a vector of indexes corresponding to the configurations
388      * returned from getDisplayConfigs().
389      */
390     virtual status_t setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
391                                               const std::vector<int32_t>& allowedConfigs) = 0;
392 
393     /*
394      * Returns the allowed display configurations currently set.
395      * The allowedConfigs in a vector of indexes corresponding to the configurations
396      * returned from getDisplayConfigs().
397      */
398     virtual status_t getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
399                                               std::vector<int32_t>* outAllowedConfigs) = 0;
400     /*
401      * Gets whether brightness operations are supported on a display.
402      *
403      * displayToken
404      *      The token of the display.
405      * outSupport
406      *      An output parameter for whether brightness operations are supported.
407      *
408      * Returns NO_ERROR upon success. Otherwise,
409      *      NAME_NOT_FOUND if the display is invalid, or
410      *      BAD_VALUE      if the output parameter is invalid.
411      */
412     virtual status_t getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
413                                                  bool* outSupport) const = 0;
414 
415     /*
416      * Sets the brightness of a display.
417      *
418      * displayToken
419      *      The token of the display whose brightness is set.
420      * brightness
421      *      A number between 0.0f (minimum brightness) and 1.0 (maximum brightness), or -1.0f to
422      *      turn the backlight off.
423      *
424      * Returns NO_ERROR upon success. Otherwise,
425      *      NAME_NOT_FOUND    if the display is invalid, or
426      *      BAD_VALUE         if the brightness is invalid, or
427      *      INVALID_OPERATION if brightness operations are not supported.
428      */
429     virtual status_t setDisplayBrightness(const sp<IBinder>& displayToken,
430                                           float brightness) const = 0;
431 
432     /*
433      * Sends a power hint to the composer. This function is asynchronous.
434      *
435      * hintId
436      *      hint id according to android::hardware::power::V1_0::PowerHint
437      *
438      * Returns NO_ERROR upon success.
439      */
440     virtual status_t notifyPowerHint(int32_t hintId) = 0;
441 };
442 
443 // ----------------------------------------------------------------------------
444 
445 class BnSurfaceComposer: public BnInterface<ISurfaceComposer> {
446 public:
447     enum ISurfaceComposerTag {
448         // Note: BOOT_FINISHED must remain this value, it is called from
449         // Java by ActivityManagerService.
450         BOOT_FINISHED = IBinder::FIRST_CALL_TRANSACTION,
451         CREATE_CONNECTION,
452         CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED, // unused, fails permissions check
453         CREATE_DISPLAY_EVENT_CONNECTION,
454         CREATE_DISPLAY,
455         DESTROY_DISPLAY,
456         GET_PHYSICAL_DISPLAY_TOKEN,
457         SET_TRANSACTION_STATE,
458         AUTHENTICATE_SURFACE,
459         GET_SUPPORTED_FRAME_TIMESTAMPS,
460         GET_DISPLAY_CONFIGS,
461         GET_ACTIVE_CONFIG,
462         SET_ACTIVE_CONFIG,
463         CONNECT_DISPLAY_UNUSED, // unused, fails permissions check
464         CAPTURE_SCREEN,
465         CAPTURE_LAYERS,
466         CLEAR_ANIMATION_FRAME_STATS,
467         GET_ANIMATION_FRAME_STATS,
468         SET_POWER_MODE,
469         GET_DISPLAY_STATS,
470         GET_HDR_CAPABILITIES,
471         GET_DISPLAY_COLOR_MODES,
472         GET_ACTIVE_COLOR_MODE,
473         SET_ACTIVE_COLOR_MODE,
474         ENABLE_VSYNC_INJECTIONS,
475         INJECT_VSYNC,
476         GET_LAYER_DEBUG_INFO,
477         GET_COMPOSITION_PREFERENCE,
478         GET_COLOR_MANAGEMENT,
479         GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES,
480         SET_DISPLAY_CONTENT_SAMPLING_ENABLED,
481         GET_DISPLAYED_CONTENT_SAMPLE,
482         GET_PROTECTED_CONTENT_SUPPORT,
483         IS_WIDE_COLOR_DISPLAY,
484         GET_DISPLAY_NATIVE_PRIMARIES,
485         GET_PHYSICAL_DISPLAY_IDS,
486         ADD_REGION_SAMPLING_LISTENER,
487         REMOVE_REGION_SAMPLING_LISTENER,
488         SET_ALLOWED_DISPLAY_CONFIGS,
489         GET_ALLOWED_DISPLAY_CONFIGS,
490         GET_DISPLAY_BRIGHTNESS_SUPPORT,
491         SET_DISPLAY_BRIGHTNESS,
492         CAPTURE_SCREEN_BY_ID,
493         NOTIFY_POWER_HINT,
494         // Always append new enum to the end.
495     };
496 
497     virtual status_t onTransact(uint32_t code, const Parcel& data,
498             Parcel* reply, uint32_t flags = 0);
499 };
500 
501 // ----------------------------------------------------------------------------
502 
503 }; // namespace android
504 
505 #endif // ANDROID_GUI_ISURFACE_COMPOSER_H
506