1 /*
2  * Copyright (C) 2010 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 <cstdint>
20 #include <memory>
21 #include <mutex>
22 #include <optional>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <vector>
26 
27 #include <android-base/thread_annotations.h>
28 #include <ftl/expected.h>
29 #include <ftl/future.h>
30 #include <ui/DisplayIdentification.h>
31 #include <ui/FenceTime.h>
32 
33 // TODO(b/129481165): remove the #pragma below and fix conversion issues
34 #pragma clang diagnostic push
35 #pragma clang diagnostic ignored "-Wconversion"
36 #pragma clang diagnostic ignored "-Wextra"
37 #include <ui/GraphicTypes.h>
38 #pragma clang diagnostic pop // ignored "-Wconversion -Wextra"
39 
40 #include <utils/StrongPointer.h>
41 #include <utils/Timers.h>
42 
43 #include "DisplayMode.h"
44 #include "HWC2.h"
45 #include "Hal.h"
46 
47 #include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
48 #include <aidl/android/hardware/graphics/common/Hdr.h>
49 #include <aidl/android/hardware/graphics/common/HdrConversionCapability.h>
50 #include <aidl/android/hardware/graphics/common/HdrConversionStrategy.h>
51 #include <aidl/android/hardware/graphics/composer3/Capability.h>
52 #include <aidl/android/hardware/graphics/composer3/ClientTargetPropertyWithBrightness.h>
53 #include <aidl/android/hardware/graphics/composer3/Composition.h>
54 #include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
55 #include <aidl/android/hardware/graphics/composer3/OverlayProperties.h>
56 
57 namespace android {
58 
59 namespace hal = hardware::graphics::composer::hal;
60 
61 struct DisplayedFrameStats;
62 class GraphicBuffer;
63 class TestableSurfaceFlinger;
64 struct HWComposerTest;
65 struct CompositionInfo;
66 
67 namespace Hwc2 {
68 class Composer;
69 } // namespace Hwc2
70 
71 namespace compositionengine {
72 class Output;
73 } // namespace compositionengine
74 
75 struct KnownHWCGenericLayerMetadata {
76     const char* name;
77     const uint32_t id;
78 };
79 
80 // See the comment for SurfaceFlinger::getHwComposer for the thread safety rules for accessing
81 // this class.
82 class HWComposer {
83 public:
84     struct DeviceRequestedChanges {
85         using ChangedTypes =
86                 std::unordered_map<HWC2::Layer*,
87                                    aidl::android::hardware::graphics::composer3::Composition>;
88         using ClientTargetProperty =
89                 aidl::android::hardware::graphics::composer3::ClientTargetPropertyWithBrightness;
90         using DisplayRequests = hal::DisplayRequest;
91         using LayerRequests = std::unordered_map<HWC2::Layer*, hal::LayerRequest>;
92 
93         ChangedTypes changedTypes;
94         DisplayRequests displayRequests;
95         LayerRequests layerRequests;
96         ClientTargetProperty clientTargetProperty;
97     };
98 
99     struct HWCDisplayMode {
100         hal::HWConfigId hwcId;
101         int32_t width = -1;
102         int32_t height = -1;
103         nsecs_t vsyncPeriod = -1;
104         float dpiX = -1.f;
105         float dpiY = -1.f;
106         int32_t configGroup = -1;
107         std::optional<hal::VrrConfig> vrrConfig;
108 
109         friend std::ostream& operator<<(std::ostream& os, const HWCDisplayMode& mode) {
110             return os << "id=" << mode.hwcId << " res=" << mode.width << "x" << mode.height
111                       << " vsyncPeriod=" << mode.vsyncPeriod << " dpi=" << mode.dpiX << "x"
112                       << mode.dpiY << " group=" << mode.configGroup
113                       << " vrrConfig=" << to_string(mode.vrrConfig).c_str();
114         }
115     };
116 
117     virtual ~HWComposer();
118 
119     virtual void setCallback(HWC2::ComposerCallback&) = 0;
120 
121     virtual bool getDisplayIdentificationData(hal::HWDisplayId, uint8_t* outPort,
122                                               DisplayIdentificationData* outData) const = 0;
123 
124     virtual bool hasCapability(aidl::android::hardware::graphics::composer3::Capability) const = 0;
125     virtual bool hasDisplayCapability(
126             HalDisplayId,
127             aidl::android::hardware::graphics::composer3::DisplayCapability) const = 0;
128 
129     virtual size_t getMaxVirtualDisplayCount() const = 0;
130     virtual size_t getMaxVirtualDisplayDimension() const = 0;
131 
132     // Attempts to allocate a virtual display on the HWC. The maximum number of virtual displays
133     // supported by the HWC can be queried in advance, but allocation may fail for other reasons.
134     virtual bool allocateVirtualDisplay(HalVirtualDisplayId, ui::Size, ui::PixelFormat*) = 0;
135 
136     virtual void allocatePhysicalDisplay(hal::HWDisplayId, PhysicalDisplayId) = 0;
137 
138     // Attempts to create a new layer on this display
139     virtual std::shared_ptr<HWC2::Layer> createLayer(HalDisplayId) = 0;
140 
141     // Gets any required composition change requests from the HWC device.
142     //
143     // Note that frameUsesClientComposition must be set correctly based on
144     // whether the current frame appears to use client composition. If it is
145     // false some internal optimizations are allowed to present the display
146     // with fewer handshakes, but this does not work if client composition is
147     // expected.
148     virtual status_t getDeviceCompositionChanges(
149             HalDisplayId, bool frameUsesClientComposition,
150             std::optional<std::chrono::steady_clock::time_point> earliestPresentTime,
151             nsecs_t expectedPresentTime, Fps frameInterval,
152             std::optional<DeviceRequestedChanges>* outChanges) = 0;
153 
154     virtual status_t setClientTarget(HalDisplayId, uint32_t slot, const sp<Fence>& acquireFence,
155                                      const sp<GraphicBuffer>& target, ui::Dataspace,
156                                      float hdrSdrRatio) = 0;
157 
158     // Present layers to the display and read releaseFences.
159     virtual status_t presentAndGetReleaseFences(
160             HalDisplayId,
161             std::optional<std::chrono::steady_clock::time_point> earliestPresentTime) = 0;
162 
163     virtual status_t executeCommands(HalDisplayId) = 0;
164 
165     // set power mode
166     virtual status_t setPowerMode(PhysicalDisplayId, hal::PowerMode) = 0;
167 
168     // Sets a color transform to be applied to the result of composition
169     virtual status_t setColorTransform(HalDisplayId, const mat4& transform) = 0;
170 
171     // reset state when a display is disconnected
172     virtual void disconnectDisplay(HalDisplayId) = 0;
173 
174     // Get the present fence/timestamp received from the last call to present.
175     virtual sp<Fence> getPresentFence(HalDisplayId) const = 0;
176     virtual nsecs_t getPresentTimestamp(PhysicalDisplayId) const = 0;
177 
178     // Get last release fence for the given layer
179     virtual sp<Fence> getLayerReleaseFence(HalDisplayId, HWC2::Layer*) const = 0;
180 
181     // Set the output buffer and acquire fence for a virtual display.
182     virtual status_t setOutputBuffer(HalVirtualDisplayId, const sp<Fence>& acquireFence,
183                                      const sp<GraphicBuffer>& buffer) = 0;
184 
185     // After SurfaceFlinger has retrieved the release fences for all the frames,
186     // it can call this to clear the shared pointers in the release fence map
187     virtual void clearReleaseFences(HalDisplayId) = 0;
188 
189     // Fetches the HDR capabilities of the given display
190     virtual status_t getHdrCapabilities(HalDisplayId, HdrCapabilities* outCapabilities) = 0;
191 
192     virtual const aidl::android::hardware::graphics::composer3::OverlayProperties&
193     getOverlaySupport() const = 0;
194 
195     virtual int32_t getSupportedPerFrameMetadata(HalDisplayId) const = 0;
196 
197     // Returns the available RenderIntent of the given display.
198     virtual std::vector<ui::RenderIntent> getRenderIntents(HalDisplayId, ui::ColorMode) const = 0;
199 
200     virtual mat4 getDataspaceSaturationMatrix(HalDisplayId, ui::Dataspace) = 0;
201 
202     // Returns the attributes of the color sampling engine.
203     virtual status_t getDisplayedContentSamplingAttributes(HalDisplayId, ui::PixelFormat* outFormat,
204                                                            ui::Dataspace* outDataspace,
205                                                            uint8_t* outComponentMask) = 0;
206     virtual status_t setDisplayContentSamplingEnabled(HalDisplayId, bool enabled,
207                                                       uint8_t componentMask,
208                                                       uint64_t maxFrames) = 0;
209     virtual status_t getDisplayedContentSample(HalDisplayId, uint64_t maxFrames, uint64_t timestamp,
210                                                DisplayedFrameStats* outStats) = 0;
211 
212     // Sets the brightness of a display.
213     virtual ftl::Future<status_t> setDisplayBrightness(
214             PhysicalDisplayId, float brightness, float brightnessNits,
215             const Hwc2::Composer::DisplayBrightnessOptions&) = 0;
216 
217     // Get whether the display skipped validation on the latest present
218     virtual bool getValidateSkipped(HalDisplayId displayId) const = 0;
219 
220     // Events handling ---------------------------------------------------------
221 
222     // Returns stable display ID (and display name on connection of new or previously disconnected
223     // display), or std::nullopt if hotplug event was ignored.
224     // This function is called from SurfaceFlinger.
225     virtual std::optional<DisplayIdentificationInfo> onHotplug(hal::HWDisplayId,
226                                                                hal::Connection) = 0;
227 
228     // If true we'll update the DeviceProductInfo on subsequent hotplug connected events.
229     // TODO(b/157555476): Remove when the framework has proper support for headless mode
230     virtual bool updatesDeviceProductInfoOnHotplugReconnect() const = 0;
231 
232     // Called when a vsync happens. If the vsync is valid, returns the
233     // corresponding PhysicalDisplayId. Otherwise returns nullopt.
234     virtual std::optional<PhysicalDisplayId> onVsync(hal::HWDisplayId, nsecs_t timestamp) = 0;
235 
236     virtual void setVsyncEnabled(PhysicalDisplayId, hal::Vsync enabled) = 0;
237 
238     virtual bool isConnected(PhysicalDisplayId) const = 0;
239 
240     virtual std::vector<HWCDisplayMode> getModes(PhysicalDisplayId,
241                                                  int32_t maxFrameIntervalNs) const = 0;
242 
243     virtual ftl::Expected<hal::HWConfigId, status_t> getActiveMode(PhysicalDisplayId) const = 0;
244 
245     virtual std::vector<ui::ColorMode> getColorModes(PhysicalDisplayId) const = 0;
246 
247     virtual status_t setActiveColorMode(PhysicalDisplayId, ui::ColorMode mode,
248                                         ui::RenderIntent) = 0;
249 
250     // Composer 2.4
251     virtual ui::DisplayConnectionType getDisplayConnectionType(PhysicalDisplayId) const = 0;
252     virtual bool isVsyncPeriodSwitchSupported(PhysicalDisplayId) const = 0;
253     virtual ftl::Expected<nsecs_t, status_t> getDisplayVsyncPeriod(PhysicalDisplayId) const = 0;
254     virtual status_t setActiveModeWithConstraints(PhysicalDisplayId, hal::HWConfigId,
255                                                   const hal::VsyncPeriodChangeConstraints&,
256                                                   hal::VsyncPeriodChangeTimeline* outTimeline) = 0;
257     virtual status_t setAutoLowLatencyMode(PhysicalDisplayId, bool on) = 0;
258     virtual status_t getSupportedContentTypes(
259             PhysicalDisplayId, std::vector<hal::ContentType>* outSupportedContentTypes) const = 0;
260 
supportsContentType(PhysicalDisplayId displayId,hal::ContentType type)261     bool supportsContentType(PhysicalDisplayId displayId, hal::ContentType type) const {
262         std::vector<hal::ContentType> types;
263         return getSupportedContentTypes(displayId, &types) == NO_ERROR &&
264                 std::find(types.begin(), types.end(), type) != types.end();
265     }
266 
267     virtual status_t setContentType(PhysicalDisplayId, hal::ContentType) = 0;
268 
269     virtual const std::unordered_map<std::string, bool>& getSupportedLayerGenericMetadata()
270             const = 0;
271 
272     virtual void dump(std::string& out) const = 0;
273 
274     virtual void dumpOverlayProperties(std::string& out) const = 0;
275 
276     virtual Hwc2::Composer* getComposer() const = 0;
277 
278     // Returns the first display connected at boot. Its connection via HWComposer::onHotplug,
279     // which in practice is immediately after HWComposer construction, must occur before any
280     // call to this function.
281     // The primary display can be temporarily disconnected from the perspective
282     // of this class. Callers must not call getPrimaryHwcDisplayId() or getPrimaryDisplayId()
283     // if isHeadless().
284     //
285     // TODO(b/182939859): Remove special cases for primary display.
286     virtual hal::HWDisplayId getPrimaryHwcDisplayId() const = 0;
287     virtual PhysicalDisplayId getPrimaryDisplayId() const = 0;
288     virtual bool isHeadless() const = 0;
289 
290     virtual std::optional<PhysicalDisplayId> toPhysicalDisplayId(hal::HWDisplayId) const = 0;
291     virtual std::optional<hal::HWDisplayId> fromPhysicalDisplayId(PhysicalDisplayId) const = 0;
292 
293     // Composer 3.0
294     virtual status_t setBootDisplayMode(PhysicalDisplayId, hal::HWConfigId) = 0;
295     virtual status_t clearBootDisplayMode(PhysicalDisplayId) = 0;
296     virtual std::optional<hal::HWConfigId> getPreferredBootDisplayMode(PhysicalDisplayId) = 0;
297     virtual status_t getDisplayDecorationSupport(
298             PhysicalDisplayId,
299             std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport>*
300                     support) = 0;
301     virtual status_t setIdleTimerEnabled(PhysicalDisplayId, std::chrono::milliseconds timeout) = 0;
302     virtual bool hasDisplayIdleTimerCapability(PhysicalDisplayId) const = 0;
303     virtual Hwc2::AidlTransform getPhysicalDisplayOrientation(PhysicalDisplayId) const = 0;
304     virtual std::vector<aidl::android::hardware::graphics::common::HdrConversionCapability>
305     getHdrConversionCapabilities() const = 0;
306     virtual status_t setHdrConversionStrategy(
307             aidl::android::hardware::graphics::common::HdrConversionStrategy,
308             aidl::android::hardware::graphics::common::Hdr*) = 0;
309     virtual status_t setRefreshRateChangedCallbackDebugEnabled(PhysicalDisplayId, bool enabled) = 0;
310     virtual status_t notifyExpectedPresent(PhysicalDisplayId, TimePoint expectedPresentTime,
311                                            Fps frameInterval) = 0;
312 };
313 
314 static inline bool operator==(const android::HWComposer::DeviceRequestedChanges& lhs,
315                               const android::HWComposer::DeviceRequestedChanges& rhs) {
316     return lhs.changedTypes == rhs.changedTypes && lhs.displayRequests == rhs.displayRequests &&
317             lhs.layerRequests == rhs.layerRequests &&
318             lhs.clientTargetProperty == rhs.clientTargetProperty;
319 }
320 
321 namespace impl {
322 
323 class HWComposer final : public android::HWComposer {
324 public:
325     explicit HWComposer(std::unique_ptr<Hwc2::Composer> composer);
326     explicit HWComposer(const std::string& composerServiceName);
327 
328     ~HWComposer() override;
329 
330     void setCallback(HWC2::ComposerCallback&) override;
331 
332     bool getDisplayIdentificationData(hal::HWDisplayId, uint8_t* outPort,
333                                       DisplayIdentificationData* outData) const override;
334 
335     bool hasCapability(aidl::android::hardware::graphics::composer3::Capability) const override;
336     bool hasDisplayCapability(
337             HalDisplayId,
338             aidl::android::hardware::graphics::composer3::DisplayCapability) const override;
339 
340     size_t getMaxVirtualDisplayCount() const override;
341     size_t getMaxVirtualDisplayDimension() const override;
342 
343     bool allocateVirtualDisplay(HalVirtualDisplayId, ui::Size, ui::PixelFormat*) override;
344 
345     // Called from SurfaceFlinger, when the state for a new physical display needs to be recreated.
346     void allocatePhysicalDisplay(hal::HWDisplayId, PhysicalDisplayId) override;
347 
348     // Attempts to create a new layer on this display
349     std::shared_ptr<HWC2::Layer> createLayer(HalDisplayId) override;
350 
351     status_t getDeviceCompositionChanges(
352             HalDisplayId, bool frameUsesClientComposition,
353             std::optional<std::chrono::steady_clock::time_point> earliestPresentTime,
354             nsecs_t expectedPresentTime, Fps frameInterval,
355             std::optional<DeviceRequestedChanges>* outChanges) override;
356 
357     status_t setClientTarget(HalDisplayId, uint32_t slot, const sp<Fence>& acquireFence,
358                              const sp<GraphicBuffer>& target, ui::Dataspace,
359                              float hdrSdrRatio) override;
360 
361     // Present layers to the display and read releaseFences.
362     status_t presentAndGetReleaseFences(
363             HalDisplayId,
364             std::optional<std::chrono::steady_clock::time_point> earliestPresentTime) override;
365 
366     status_t executeCommands(HalDisplayId) override;
367 
368     // set power mode
369     status_t setPowerMode(PhysicalDisplayId, hal::PowerMode mode) override;
370 
371     // Sets a color transform to be applied to the result of composition
372     status_t setColorTransform(HalDisplayId, const mat4& transform) override;
373 
374     // reset state when a display is disconnected
375     void disconnectDisplay(HalDisplayId) override;
376 
377     // Get the present fence/timestamp received from the last call to present.
378     sp<Fence> getPresentFence(HalDisplayId) const override;
379     nsecs_t getPresentTimestamp(PhysicalDisplayId) const override;
380 
381     // Get last release fence for the given layer
382     sp<Fence> getLayerReleaseFence(HalDisplayId, HWC2::Layer*) const override;
383 
384     // Set the output buffer and acquire fence for a virtual display.
385     status_t setOutputBuffer(HalVirtualDisplayId, const sp<Fence>& acquireFence,
386                              const sp<GraphicBuffer>& buffer) override;
387 
388     // After SurfaceFlinger has retrieved the release fences for all the frames,
389     // it can call this to clear the shared pointers in the release fence map
390     void clearReleaseFences(HalDisplayId) override;
391 
392     // Fetches the HDR capabilities of the given display
393     status_t getHdrCapabilities(HalDisplayId, HdrCapabilities* outCapabilities) override;
394 
395     const aidl::android::hardware::graphics::composer3::OverlayProperties& getOverlaySupport()
396             const override;
397 
398     int32_t getSupportedPerFrameMetadata(HalDisplayId) const override;
399 
400     // Returns the available RenderIntent of the given display.
401     std::vector<ui::RenderIntent> getRenderIntents(HalDisplayId, ui::ColorMode) const override;
402 
403     mat4 getDataspaceSaturationMatrix(HalDisplayId, ui::Dataspace) override;
404 
405     // Returns the attributes of the color sampling engine.
406     status_t getDisplayedContentSamplingAttributes(HalDisplayId, ui::PixelFormat* outFormat,
407                                                    ui::Dataspace* outDataspace,
408                                                    uint8_t* outComponentMask) override;
409     status_t setDisplayContentSamplingEnabled(HalDisplayId, bool enabled, uint8_t componentMask,
410                                               uint64_t maxFrames) override;
411     status_t getDisplayedContentSample(HalDisplayId, uint64_t maxFrames, uint64_t timestamp,
412                                        DisplayedFrameStats* outStats) override;
413     ftl::Future<status_t> setDisplayBrightness(
414             PhysicalDisplayId, float brightness, float brightnessNits,
415             const Hwc2::Composer::DisplayBrightnessOptions&) override;
416 
417     // Events handling ---------------------------------------------------------
418 
419     // Returns PhysicalDisplayId (and display name on connection of new or previously disconnected
420     // display), or std::nullopt if hotplug event was ignored.
421     std::optional<DisplayIdentificationInfo> onHotplug(hal::HWDisplayId, hal::Connection) override;
422 
423     bool updatesDeviceProductInfoOnHotplugReconnect() const override;
424 
425     std::optional<PhysicalDisplayId> onVsync(hal::HWDisplayId, nsecs_t timestamp) override;
426     void setVsyncEnabled(PhysicalDisplayId, hal::Vsync enabled) override;
427 
428     bool isConnected(PhysicalDisplayId) const override;
429 
430     std::vector<HWCDisplayMode> getModes(PhysicalDisplayId,
431                                          int32_t maxFrameIntervalNs) const override;
432 
433     ftl::Expected<hal::HWConfigId, status_t> getActiveMode(PhysicalDisplayId) const override;
434 
435     std::vector<ui::ColorMode> getColorModes(PhysicalDisplayId) const override;
436 
437     status_t setActiveColorMode(PhysicalDisplayId, ui::ColorMode, ui::RenderIntent) override;
438 
439     bool getValidateSkipped(HalDisplayId displayId) const override;
440 
441     // Composer 2.4
442     ui::DisplayConnectionType getDisplayConnectionType(PhysicalDisplayId) const override;
443     bool isVsyncPeriodSwitchSupported(PhysicalDisplayId) const override;
444     ftl::Expected<nsecs_t, status_t> getDisplayVsyncPeriod(PhysicalDisplayId) const override;
445     status_t setActiveModeWithConstraints(PhysicalDisplayId, hal::HWConfigId,
446                                           const hal::VsyncPeriodChangeConstraints&,
447                                           hal::VsyncPeriodChangeTimeline* outTimeline) override;
448     status_t setAutoLowLatencyMode(PhysicalDisplayId, bool) override;
449     status_t getSupportedContentTypes(PhysicalDisplayId,
450                                       std::vector<hal::ContentType>*) const override;
451     status_t setContentType(PhysicalDisplayId, hal::ContentType) override;
452 
453     const std::unordered_map<std::string, bool>& getSupportedLayerGenericMetadata() const override;
454 
455     // Composer 3.0
456     status_t setBootDisplayMode(PhysicalDisplayId, hal::HWConfigId) override;
457     status_t clearBootDisplayMode(PhysicalDisplayId) override;
458     std::optional<hal::HWConfigId> getPreferredBootDisplayMode(PhysicalDisplayId) override;
459     status_t getDisplayDecorationSupport(
460             PhysicalDisplayId,
461             std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport>*
462                     support) override;
463     status_t setIdleTimerEnabled(PhysicalDisplayId, std::chrono::milliseconds timeout) override;
464     bool hasDisplayIdleTimerCapability(PhysicalDisplayId) const override;
465     Hwc2::AidlTransform getPhysicalDisplayOrientation(PhysicalDisplayId) const override;
466     std::vector<aidl::android::hardware::graphics::common::HdrConversionCapability>
467     getHdrConversionCapabilities() const override;
468     status_t setHdrConversionStrategy(
469             aidl::android::hardware::graphics::common::HdrConversionStrategy,
470             aidl::android::hardware::graphics::common::Hdr*) override;
471     status_t setRefreshRateChangedCallbackDebugEnabled(PhysicalDisplayId, bool enabled) override;
472     status_t notifyExpectedPresent(PhysicalDisplayId, TimePoint expectedPresentTime,
473                                    Fps frameInterval) override;
474 
475     // for debugging ----------------------------------------------------------
476     void dump(std::string& out) const override;
477     void dumpOverlayProperties(std::string& out) const override;
478 
getComposer()479     Hwc2::Composer* getComposer() const override { return mComposer.get(); }
480 
getPrimaryHwcDisplayId()481     hal::HWDisplayId getPrimaryHwcDisplayId() const override {
482         LOG_ALWAYS_FATAL_IF(!mPrimaryHwcDisplayId, "Missing HWC primary display");
483         return *mPrimaryHwcDisplayId;
484     }
485 
getPrimaryDisplayId()486     PhysicalDisplayId getPrimaryDisplayId() const override {
487         const auto id = toPhysicalDisplayId(getPrimaryHwcDisplayId());
488         LOG_ALWAYS_FATAL_IF(!id, "Missing primary display");
489         return *id;
490     }
491 
isHeadless()492     virtual bool isHeadless() const override { return !mPrimaryHwcDisplayId; }
493 
494     std::optional<PhysicalDisplayId> toPhysicalDisplayId(hal::HWDisplayId) const override;
495     std::optional<hal::HWDisplayId> fromPhysicalDisplayId(PhysicalDisplayId) const override;
496 
497 private:
498     // For unit tests
499     friend TestableSurfaceFlinger;
500     friend HWComposerTest;
501 
502     struct DisplayData {
503         std::unique_ptr<HWC2::Display> hwcDisplay;
504 
505         sp<Fence> lastPresentFence = Fence::NO_FENCE; // signals when the last set op retires
506         nsecs_t lastPresentTimestamp = 0;
507 
508         std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
509 
510         bool validateWasSkipped;
511         hal::Error presentError;
512 
513         bool vsyncTraceToggle = false;
514 
515         std::mutex vsyncEnabledLock;
516         hal::Vsync vsyncEnabled GUARDED_BY(vsyncEnabledLock) = hal::Vsync::DISABLE;
517     };
518 
519     std::optional<DisplayIdentificationInfo> onHotplugConnect(hal::HWDisplayId);
520     std::optional<DisplayIdentificationInfo> onHotplugDisconnect(hal::HWDisplayId);
521     bool shouldIgnoreHotplugConnect(hal::HWDisplayId, bool hasDisplayIdentificationData) const;
522 
523     std::vector<HWCDisplayMode> getModesFromDisplayConfigurations(uint64_t hwcDisplayId,
524                                                                   int32_t maxFrameIntervalNs) const;
525     std::vector<HWCDisplayMode> getModesFromLegacyDisplayConfigs(uint64_t hwcDisplayId) const;
526 
527     int32_t getAttribute(hal::HWDisplayId hwcDisplayId, hal::HWConfigId configId,
528                          hal::Attribute attribute) const;
529 
530     void loadCapabilities();
531     void loadLayerMetadataSupport();
532     void loadOverlayProperties();
533     void loadHdrConversionCapabilities();
534 
535     std::unordered_map<HalDisplayId, DisplayData> mDisplayData;
536 
537     std::unique_ptr<android::Hwc2::Composer> mComposer;
538     std::unordered_set<aidl::android::hardware::graphics::composer3::Capability> mCapabilities;
539     aidl::android::hardware::graphics::composer3::OverlayProperties mOverlayProperties;
540     std::vector<aidl::android::hardware::graphics::common::HdrConversionCapability>
541             mHdrConversionCapabilities = {};
542 
543     std::unordered_map<std::string, bool> mSupportedLayerGenericMetadata;
544     bool mRegisteredCallback = false;
545 
546     std::unordered_map<hal::HWDisplayId, PhysicalDisplayId> mPhysicalDisplayIdMap;
547     std::optional<hal::HWDisplayId> mPrimaryHwcDisplayId;
548     bool mHasMultiDisplaySupport = false;
549 
550     const size_t mMaxVirtualDisplayDimension;
551     const bool mUpdateDeviceProductInfoOnHotplugReconnect;
552     bool mEnableVrrTimeout;
553 };
554 
555 } // namespace impl
556 } // namespace android
557