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 <memory>
20 #include <optional>
21 #include <string>
22 #include <unordered_map>
23 
24 #include <android/native_window.h>
25 #include <binder/IBinder.h>
26 #include <gui/LayerState.h>
27 #include <math/mat4.h>
28 #include <renderengine/RenderEngine.h>
29 #include <system/window.h>
30 #include <ui/DisplayId.h>
31 #include <ui/DisplayState.h>
32 #include <ui/GraphicTypes.h>
33 #include <ui/HdrCapabilities.h>
34 #include <ui/Region.h>
35 #include <ui/StaticDisplayInfo.h>
36 #include <ui/Transform.h>
37 #include <utils/Errors.h>
38 #include <utils/Mutex.h>
39 #include <utils/RefBase.h>
40 #include <utils/Timers.h>
41 
42 #include "MainThreadGuard.h"
43 
44 #include "DisplayHardware/DisplayIdentification.h"
45 #include "DisplayHardware/DisplayMode.h"
46 #include "DisplayHardware/Hal.h"
47 #include "DisplayHardware/PowerAdvisor.h"
48 
49 #include "Scheduler/RefreshRateConfigs.h"
50 
51 #include "TracedOrdinal.h"
52 
53 namespace android {
54 
55 class Fence;
56 class HWComposer;
57 class IGraphicBufferProducer;
58 class Layer;
59 class RefreshRateOverlay;
60 class SurfaceFlinger;
61 
62 struct CompositionInfo;
63 struct DisplayDeviceCreationArgs;
64 
65 namespace compositionengine {
66 class Display;
67 class DisplaySurface;
68 } // namespace compositionengine
69 
70 class DisplayDevice : public RefBase {
71 public:
72     constexpr static float sDefaultMinLumiance = 0.0;
73     constexpr static float sDefaultMaxLumiance = 500.0;
74     enum { eReceivesInput = 0x01 };
75 
76     explicit DisplayDevice(DisplayDeviceCreationArgs& args);
77 
78     // Must be destroyed on the main thread because it may call into HWComposer.
79     virtual ~DisplayDevice();
80 
getCompositionDisplay()81     std::shared_ptr<compositionengine::Display> getCompositionDisplay() const {
82         return mCompositionDisplay;
83     }
84 
getConnectionType()85     std::optional<ui::DisplayConnectionType> getConnectionType() const { return mConnectionType; }
86 
isVirtual()87     bool isVirtual() const { return !mConnectionType; }
isPrimary()88     bool isPrimary() const { return mIsPrimary; }
isInternal()89     bool isInternal() const {
90         return !isVirtual() && mConnectionType == ui::DisplayConnectionType::Internal;
91     }
92 
93     // isSecure indicates whether this display can be trusted to display
94     // secure surfaces.
95     bool isSecure() const;
96 
97     int getWidth() const;
98     int getHeight() const;
getSize()99     ui::Size getSize() const { return {getWidth(), getHeight()}; }
100 
101     void setLayerStack(ui::LayerStack);
102     void setDisplaySize(int width, int height);
103     void setProjection(ui::Rotation orientation, Rect viewport, Rect frame);
104     void setFlags(uint32_t flags);
105 
getPhysicalOrientation()106     ui::Rotation getPhysicalOrientation() const { return mPhysicalOrientation; }
getOrientation()107     ui::Rotation getOrientation() const { return mOrientation; }
108 
109     static ui::Transform::RotationFlags getPrimaryDisplayRotationFlags();
110 
111     ui::Transform::RotationFlags getTransformHint() const;
112     const ui::Transform& getTransform() const;
113     const Rect& getLayerStackSpaceRect() const;
114     const Rect& getOrientedDisplaySpaceRect() const;
115     bool needsFiltering() const;
116     ui::LayerStack getLayerStack() const;
receivesInput()117     bool receivesInput() const { return mFlags & eReceivesInput; }
118 
119     DisplayId getId() const;
120 
121     // Shorthand to upcast the ID of a display whose type is known as a precondition.
getPhysicalId()122     PhysicalDisplayId getPhysicalId() const {
123         const auto id = PhysicalDisplayId::tryCast(getId());
124         LOG_FATAL_IF(!id);
125         return *id;
126     }
127 
getVirtualId()128     VirtualDisplayId getVirtualId() const {
129         const auto id = VirtualDisplayId::tryCast(getId());
130         LOG_FATAL_IF(!id);
131         return *id;
132     }
133 
getDisplayToken()134     const wp<IBinder>& getDisplayToken() const { return mDisplayToken; }
getSequenceId()135     int32_t getSequenceId() const { return mSequenceId; }
136 
137     const Region& getUndefinedRegion() const;
138 
139     int32_t getSupportedPerFrameMetadata() const;
140 
141     bool hasWideColorGamut() const;
142     // Whether h/w composer has native support for specific HDR type.
143     bool hasHDR10PlusSupport() const;
144     bool hasHDR10Support() const;
145     bool hasHLGSupport() const;
146     bool hasDolbyVisionSupport() const;
147 
148     void overrideHdrTypes(const std::vector<ui::Hdr>& hdrTypes);
149 
150     // The returned HdrCapabilities is the combination of HDR capabilities from
151     // hardware composer and RenderEngine. When the DisplayDevice supports wide
152     // color gamut, RenderEngine is able to simulate HDR support in Display P3
153     // color space for both PQ and HLG HDR contents. The minimum and maximum
154     // luminance will be set to sDefaultMinLumiance and sDefaultMaxLumiance
155     // respectively if hardware composer doesn't return meaningful values.
156     HdrCapabilities getHdrCapabilities() const;
157 
158     // Return true if intent is supported by the display.
159     bool hasRenderIntent(ui::RenderIntent intent) const;
160 
161     const Rect& getBounds() const;
bounds()162     const Rect& bounds() const { return getBounds(); }
163 
164     void setDisplayName(const std::string& displayName);
getDisplayName()165     const std::string& getDisplayName() const { return mDisplayName; }
166 
167     void setDeviceProductInfo(std::optional<DeviceProductInfo> info);
getDeviceProductInfo()168     const std::optional<DeviceProductInfo>& getDeviceProductInfo() const {
169         return mDeviceProductInfo;
170     }
171 
172     /* ------------------------------------------------------------------------
173      * Display power mode management.
174      */
175     hardware::graphics::composer::hal::PowerMode getPowerMode() const;
176     void setPowerMode(hardware::graphics::composer::hal::PowerMode mode);
177     bool isPoweredOn() const;
178 
179     // Enables layer caching on this DisplayDevice
180     void enableLayerCaching(bool enable);
181 
182     ui::Dataspace getCompositionDataSpace() const;
183 
184     /* ------------------------------------------------------------------------
185      * Display mode management.
186      */
187     const DisplayModePtr& getActiveMode() const;
188 
189     struct ActiveModeInfo {
190         DisplayModePtr mode;
191         scheduler::RefreshRateConfigEvent event = scheduler::RefreshRateConfigEvent::None;
192 
193         bool operator!=(const ActiveModeInfo& other) const {
194             return mode != other.mode || event != other.event;
195         }
196     };
197 
198     bool setDesiredActiveMode(const ActiveModeInfo&) EXCLUDES(mActiveModeLock);
199     std::optional<ActiveModeInfo> getDesiredActiveMode() const EXCLUDES(mActiveModeLock);
200     void clearDesiredActiveModeState() EXCLUDES(mActiveModeLock);
getUpcomingActiveMode()201     ActiveModeInfo getUpcomingActiveMode() const REQUIRES(SF_MAIN_THREAD) {
202         return mUpcomingActiveMode;
203     }
204 
205     void setActiveMode(DisplayModeId) REQUIRES(SF_MAIN_THREAD);
206     status_t initiateModeChange(const ActiveModeInfo&,
207                                 const hal::VsyncPeriodChangeConstraints& constraints,
208                                 hal::VsyncPeriodChangeTimeline* outTimeline)
209             REQUIRES(SF_MAIN_THREAD);
210 
211     // Return the immutable list of supported display modes. The HWC may report different modes
212     // after a hotplug reconnect event, in which case the DisplayDevice object will be recreated.
213     // Hotplug reconnects are common for external displays.
214     const DisplayModes& getSupportedModes() const;
215 
216     // Returns nullptr if the given mode ID is not supported. A previously
217     // supported mode may be no longer supported for some devices like TVs and
218     // set-top boxes after a hotplug reconnect.
219     DisplayModePtr getMode(DisplayModeId) const;
220 
221     // Returns the refresh rate configs for this display.
refreshRateConfigs()222     scheduler::RefreshRateConfigs& refreshRateConfigs() const { return *mRefreshRateConfigs; }
223 
224     // Returns a shared pointer to the refresh rate configs for this display.
225     // Clients can store this refresh rate configs and use it even if the DisplayDevice
226     // is destroyed.
holdRefreshRateConfigs()227     std::shared_ptr<scheduler::RefreshRateConfigs> holdRefreshRateConfigs() const {
228         return mRefreshRateConfigs;
229     }
230 
231     // Enables an overlay to be displayed with the current refresh rate
232     void enableRefreshRateOverlay(bool enable, bool showSpinner);
isRefreshRateOverlayEnabled()233     bool isRefreshRateOverlayEnabled() const { return mRefreshRateOverlay != nullptr; }
234     bool onKernelTimerChanged(std::optional<DisplayModeId>, bool timerExpired);
235     void onInvalidate();
236 
237     void onVsync(nsecs_t timestamp);
238     nsecs_t getVsyncPeriodFromHWC() const;
239     nsecs_t getRefreshTimestamp() const;
240 
241     // release HWC resources (if any) for removable displays
242     void disconnect();
243 
244     /* ------------------------------------------------------------------------
245      * Debugging
246      */
247     uint32_t getPageFlipCount() const;
248     std::string getDebugName() const;
249     void dump(std::string& result) const;
250 
251 private:
252     const sp<SurfaceFlinger> mFlinger;
253     HWComposer& mHwComposer;
254     const wp<IBinder> mDisplayToken;
255     const int32_t mSequenceId;
256     const std::optional<ui::DisplayConnectionType> mConnectionType;
257 
258     const std::shared_ptr<compositionengine::Display> mCompositionDisplay;
259 
260     std::string mDisplayName;
261     std::string mActiveModeFPSTrace;
262     std::string mActiveModeFPSHwcTrace;
263 
264     const ui::Rotation mPhysicalOrientation;
265     ui::Rotation mOrientation = ui::ROTATION_0;
266 
267     static ui::Transform::RotationFlags sPrimaryDisplayRotationFlags;
268 
269     hardware::graphics::composer::hal::PowerMode mPowerMode =
270             hardware::graphics::composer::hal::PowerMode::OFF;
271     DisplayModePtr mActiveMode;
272     const DisplayModes mSupportedModes;
273 
274     std::atomic<nsecs_t> mLastHwVsync = 0;
275 
276     // TODO(b/74619554): Remove special cases for primary display.
277     const bool mIsPrimary;
278 
279     uint32_t mFlags = 0;
280 
281     std::optional<DeviceProductInfo> mDeviceProductInfo;
282 
283     std::vector<ui::Hdr> mOverrideHdrTypes;
284 
285     std::shared_ptr<scheduler::RefreshRateConfigs> mRefreshRateConfigs;
286     std::unique_ptr<RefreshRateOverlay> mRefreshRateOverlay;
287 
288     mutable std::mutex mActiveModeLock;
289     ActiveModeInfo mDesiredActiveMode GUARDED_BY(mActiveModeLock);
290     TracedOrdinal<bool> mDesiredActiveModeChanged
291             GUARDED_BY(mActiveModeLock) = {"DesiredActiveModeChanged", false};
292     ActiveModeInfo mUpcomingActiveMode GUARDED_BY(SF_MAIN_THREAD);
293 };
294 
295 struct DisplayDeviceState {
296     struct Physical {
297         PhysicalDisplayId id;
298         ui::DisplayConnectionType type;
299         hardware::graphics::composer::hal::HWDisplayId hwcDisplayId;
300         std::optional<DeviceProductInfo> deviceProductInfo;
301         DisplayModes supportedModes;
302         DisplayModePtr activeMode;
303 
304         bool operator==(const Physical& other) const {
305             return id == other.id && type == other.type && hwcDisplayId == other.hwcDisplayId;
306         }
307     };
308 
isVirtualDisplayDeviceState309     bool isVirtual() const { return !physical; }
310 
311     int32_t sequenceId = sNextSequenceId++;
312     std::optional<Physical> physical;
313     sp<IGraphicBufferProducer> surface;
314     ui::LayerStack layerStack = ui::NO_LAYER_STACK;
315     uint32_t flags = 0;
316     Rect layerStackSpaceRect;
317     Rect orientedDisplaySpaceRect;
318     ui::Rotation orientation = ui::ROTATION_0;
319     uint32_t width = 0;
320     uint32_t height = 0;
321     std::string displayName;
322     bool isSecure = false;
323 
324 private:
325     static std::atomic<int32_t> sNextSequenceId;
326 };
327 
328 struct DisplayDeviceCreationArgs {
329     // We use a constructor to ensure some of the values are set, without
330     // assuming a default value.
331     DisplayDeviceCreationArgs(const sp<SurfaceFlinger>&, HWComposer& hwComposer,
332                               const wp<IBinder>& displayToken,
333                               std::shared_ptr<compositionengine::Display>);
334     const sp<SurfaceFlinger> flinger;
335     HWComposer& hwComposer;
336     const wp<IBinder> displayToken;
337     const std::shared_ptr<compositionengine::Display> compositionDisplay;
338     std::shared_ptr<scheduler::RefreshRateConfigs> refreshRateConfigs;
339 
340     int32_t sequenceId{0};
341     std::optional<ui::DisplayConnectionType> connectionType;
342     bool isSecure{false};
343     sp<ANativeWindow> nativeWindow;
344     sp<compositionengine::DisplaySurface> displaySurface;
345     ui::Rotation physicalOrientation{ui::ROTATION_0};
346     bool hasWideColorGamut{false};
347     HdrCapabilities hdrCapabilities;
348     int32_t supportedPerFrameMetadata{0};
349     std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>> hwcColorModes;
350     hardware::graphics::composer::hal::PowerMode initialPowerMode{
351             hardware::graphics::composer::hal::PowerMode::ON};
352     bool isPrimary{false};
353     DisplayModes supportedModes;
354     DisplayModeId activeModeId;
355 };
356 
357 // Predicates for display lookup.
358 
359 struct WithLayerStack {
WithLayerStackWithLayerStack360     explicit WithLayerStack(ui::LayerStack layerStack) : layerStack(layerStack) {}
361 
operatorWithLayerStack362     bool operator()(const DisplayDevice& display) const {
363         return display.getLayerStack() == layerStack;
364     }
365 
366     ui::LayerStack layerStack;
367 };
368 
369 } // namespace android
370