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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #include <chrono>
19 #pragma clang diagnostic push
20 #pragma clang diagnostic ignored "-Wconversion"
21 
22 // #define LOG_NDEBUG 0
23 
24 #undef LOG_TAG
25 #define LOG_TAG "HWComposer"
26 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
27 
28 #include "HWComposer.h"
29 
30 #include <android-base/properties.h>
31 #include <compositionengine/Output.h>
32 #include <compositionengine/OutputLayer.h>
33 #include <compositionengine/impl/OutputLayerCompositionState.h>
34 #include <ftl/concat.h>
35 #include <gui/TraceUtils.h>
36 #include <log/log.h>
37 #include <ui/DebugUtils.h>
38 #include <ui/GraphicBuffer.h>
39 #include <utils/Errors.h>
40 #include <utils/Trace.h>
41 
42 #include "../Layer.h" // needed only for debugging
43 #include "../SurfaceFlingerProperties.h"
44 #include "ComposerHal.h"
45 #include "HWC2.h"
46 
47 #define LOG_HWC_DISPLAY_ERROR(hwcDisplayId, msg) \
48     ALOGE("%s failed for HWC display %" PRIu64 ": %s", __FUNCTION__, hwcDisplayId, msg)
49 
50 #define LOG_DISPLAY_ERROR(displayId, msg) \
51     ALOGE("%s failed for display %s: %s", __FUNCTION__, to_string(displayId).c_str(), msg)
52 
53 #define LOG_HWC_ERROR(what, error, displayId)                          \
54     ALOGE("%s: %s failed for display %s: %s (%d)", __FUNCTION__, what, \
55           to_string(displayId).c_str(), to_string(error).c_str(), static_cast<int32_t>(error))
56 
57 #define RETURN_IF_INVALID_DISPLAY(displayId, ...)            \
58     do {                                                     \
59         if (mDisplayData.count(displayId) == 0) {            \
60             LOG_DISPLAY_ERROR(displayId, "Invalid display"); \
61             return __VA_ARGS__;                              \
62         }                                                    \
63     } while (false)
64 
65 #define RETURN_IF_HWC_ERROR_FOR(what, error, displayId, ...) \
66     do {                                                     \
67         if (error != hal::Error::NONE) {                     \
68             LOG_HWC_ERROR(what, error, displayId);           \
69             return __VA_ARGS__;                              \
70         }                                                    \
71     } while (false)
72 
73 #define RETURN_IF_HWC_ERROR(error, displayId, ...) \
74     RETURN_IF_HWC_ERROR_FOR(__FUNCTION__, error, displayId, __VA_ARGS__)
75 
76 using aidl::android::hardware::graphics::common::HdrConversionCapability;
77 using aidl::android::hardware::graphics::common::HdrConversionStrategy;
78 using aidl::android::hardware::graphics::composer3::Capability;
79 using aidl::android::hardware::graphics::composer3::DisplayCapability;
80 using namespace std::string_literals;
81 
82 namespace android {
83 
84 HWComposer::~HWComposer() = default;
85 
86 namespace impl {
87 
HWComposer(std::unique_ptr<Hwc2::Composer> composer)88 HWComposer::HWComposer(std::unique_ptr<Hwc2::Composer> composer)
89       : mComposer(std::move(composer)),
90         mMaxVirtualDisplayDimension(static_cast<size_t>(sysprop::max_virtual_display_dimension(0))),
91         mUpdateDeviceProductInfoOnHotplugReconnect(
92                 sysprop::update_device_product_info_on_hotplug_reconnect(false)),
93         mEnableVrrTimeout(base::GetBoolProperty("debug.sf.vrr_timeout_hint_enabled"s, true)) {}
94 
HWComposer(const std::string & composerServiceName)95 HWComposer::HWComposer(const std::string& composerServiceName)
96       : HWComposer(Hwc2::Composer::create(composerServiceName)) {}
97 
~HWComposer()98 HWComposer::~HWComposer() {
99     mDisplayData.clear();
100 }
101 
setCallback(HWC2::ComposerCallback & callback)102 void HWComposer::setCallback(HWC2::ComposerCallback& callback) {
103     loadCapabilities();
104     loadLayerMetadataSupport();
105     loadOverlayProperties();
106     loadHdrConversionCapabilities();
107 
108     if (mRegisteredCallback) {
109         ALOGW("Callback already registered. Ignored extra registration attempt.");
110         return;
111     }
112     mRegisteredCallback = true;
113 
114     mComposer->registerCallback(callback);
115 }
116 
getDisplayIdentificationData(hal::HWDisplayId hwcDisplayId,uint8_t * outPort,DisplayIdentificationData * outData) const117 bool HWComposer::getDisplayIdentificationData(hal::HWDisplayId hwcDisplayId, uint8_t* outPort,
118                                               DisplayIdentificationData* outData) const {
119     const auto error = static_cast<hal::Error>(
120             mComposer->getDisplayIdentificationData(hwcDisplayId, outPort, outData));
121     if (error != hal::Error::NONE) {
122         if (error != hal::Error::UNSUPPORTED) {
123             LOG_HWC_DISPLAY_ERROR(hwcDisplayId, to_string(error).c_str());
124         }
125         return false;
126     }
127     return true;
128 }
129 
hasCapability(Capability capability) const130 bool HWComposer::hasCapability(Capability capability) const {
131     return mCapabilities.count(capability) > 0;
132 }
133 
hasDisplayCapability(HalDisplayId displayId,DisplayCapability capability) const134 bool HWComposer::hasDisplayCapability(HalDisplayId displayId, DisplayCapability capability) const {
135     RETURN_IF_INVALID_DISPLAY(displayId, false);
136     return mDisplayData.at(displayId).hwcDisplay->hasCapability(capability);
137 }
138 
onHotplug(hal::HWDisplayId hwcDisplayId,hal::Connection connection)139 std::optional<DisplayIdentificationInfo> HWComposer::onHotplug(hal::HWDisplayId hwcDisplayId,
140                                                                hal::Connection connection) {
141     switch (connection) {
142         case hal::Connection::CONNECTED:
143             return onHotplugConnect(hwcDisplayId);
144         case hal::Connection::DISCONNECTED:
145             return onHotplugDisconnect(hwcDisplayId);
146         case hal::Connection::INVALID:
147             return {};
148     }
149 }
150 
updatesDeviceProductInfoOnHotplugReconnect() const151 bool HWComposer::updatesDeviceProductInfoOnHotplugReconnect() const {
152     return mUpdateDeviceProductInfoOnHotplugReconnect;
153 }
154 
onVsync(hal::HWDisplayId hwcDisplayId,nsecs_t timestamp)155 std::optional<PhysicalDisplayId> HWComposer::onVsync(hal::HWDisplayId hwcDisplayId,
156                                                      nsecs_t timestamp) {
157     const auto displayIdOpt = toPhysicalDisplayId(hwcDisplayId);
158     if (!displayIdOpt) {
159         LOG_HWC_DISPLAY_ERROR(hwcDisplayId, "Invalid HWC display");
160         return {};
161     }
162 
163     RETURN_IF_INVALID_DISPLAY(*displayIdOpt, {});
164 
165     auto& displayData = mDisplayData[*displayIdOpt];
166 
167     {
168         // There have been reports of HWCs that signal several vsync events
169         // with the same timestamp when turning the display off and on. This
170         // is a bug in the HWC implementation, but filter the extra events
171         // out here so they don't cause havoc downstream.
172         if (timestamp == displayData.lastPresentTimestamp) {
173             ALOGW("Ignoring duplicate VSYNC event from HWC for display %s (t=%" PRId64 ")",
174                   to_string(*displayIdOpt).c_str(), timestamp);
175             return {};
176         }
177 
178         displayData.lastPresentTimestamp = timestamp;
179     }
180 
181     ATRACE_INT(ftl::Concat("HW_VSYNC_", displayIdOpt->value).c_str(),
182                displayData.vsyncTraceToggle);
183     displayData.vsyncTraceToggle = !displayData.vsyncTraceToggle;
184 
185     return displayIdOpt;
186 }
187 
getMaxVirtualDisplayCount() const188 size_t HWComposer::getMaxVirtualDisplayCount() const {
189     return mComposer->getMaxVirtualDisplayCount();
190 }
191 
getMaxVirtualDisplayDimension() const192 size_t HWComposer::getMaxVirtualDisplayDimension() const {
193     return mMaxVirtualDisplayDimension;
194 }
195 
allocateVirtualDisplay(HalVirtualDisplayId displayId,ui::Size resolution,ui::PixelFormat * format)196 bool HWComposer::allocateVirtualDisplay(HalVirtualDisplayId displayId, ui::Size resolution,
197                                         ui::PixelFormat* format) {
198     if (!resolution.isValid()) {
199         ALOGE("%s: Invalid resolution %dx%d", __func__, resolution.width, resolution.height);
200         return false;
201     }
202 
203     const uint32_t width = static_cast<uint32_t>(resolution.width);
204     const uint32_t height = static_cast<uint32_t>(resolution.height);
205 
206     if (mMaxVirtualDisplayDimension > 0 &&
207         (width > mMaxVirtualDisplayDimension || height > mMaxVirtualDisplayDimension)) {
208         ALOGE("%s: Resolution %ux%u exceeds maximum dimension %zu", __func__, width, height,
209               mMaxVirtualDisplayDimension);
210         return false;
211     }
212 
213     hal::HWDisplayId hwcDisplayId;
214     const auto error = static_cast<hal::Error>(
215             mComposer->createVirtualDisplay(width, height, format, &hwcDisplayId));
216     RETURN_IF_HWC_ERROR_FOR("createVirtualDisplay", error, displayId, false);
217 
218     auto display = std::make_unique<HWC2::impl::Display>(*mComposer.get(), mCapabilities,
219                                                          hwcDisplayId, hal::DisplayType::VIRTUAL);
220     display->setConnected(true);
221     auto& displayData = mDisplayData[displayId];
222     displayData.hwcDisplay = std::move(display);
223     return true;
224 }
225 
allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId,PhysicalDisplayId displayId)226 void HWComposer::allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId,
227                                          PhysicalDisplayId displayId) {
228     mPhysicalDisplayIdMap[hwcDisplayId] = displayId;
229 
230     if (!mPrimaryHwcDisplayId) {
231         mPrimaryHwcDisplayId = hwcDisplayId;
232     }
233 
234     auto& displayData = mDisplayData[displayId];
235     auto newDisplay =
236             std::make_unique<HWC2::impl::Display>(*mComposer.get(), mCapabilities, hwcDisplayId,
237                                                   hal::DisplayType::PHYSICAL);
238     newDisplay->setConnected(true);
239     displayData.hwcDisplay = std::move(newDisplay);
240 }
241 
getAttribute(hal::HWDisplayId hwcDisplayId,hal::HWConfigId configId,hal::Attribute attribute) const242 int32_t HWComposer::getAttribute(hal::HWDisplayId hwcDisplayId, hal::HWConfigId configId,
243                                  hal::Attribute attribute) const {
244     int32_t value = 0;
245     auto error = static_cast<hal::Error>(
246             mComposer->getDisplayAttribute(hwcDisplayId, configId, attribute, &value));
247 
248     RETURN_IF_HWC_ERROR_FOR("getDisplayAttribute", error, *toPhysicalDisplayId(hwcDisplayId), -1);
249     return value;
250 }
251 
createLayer(HalDisplayId displayId)252 std::shared_ptr<HWC2::Layer> HWComposer::createLayer(HalDisplayId displayId) {
253     RETURN_IF_INVALID_DISPLAY(displayId, nullptr);
254 
255     auto expected = mDisplayData[displayId].hwcDisplay->createLayer();
256     if (!expected.has_value()) {
257         auto error = std::move(expected).error();
258         RETURN_IF_HWC_ERROR(error, displayId, nullptr);
259     }
260     return std::move(expected).value();
261 }
262 
isConnected(PhysicalDisplayId displayId) const263 bool HWComposer::isConnected(PhysicalDisplayId displayId) const {
264     return mDisplayData.count(displayId) && mDisplayData.at(displayId).hwcDisplay->isConnected();
265 }
266 
getModes(PhysicalDisplayId displayId,int32_t maxFrameIntervalNs) const267 std::vector<HWComposer::HWCDisplayMode> HWComposer::getModes(PhysicalDisplayId displayId,
268                                                              int32_t maxFrameIntervalNs) const {
269     RETURN_IF_INVALID_DISPLAY(displayId, {});
270 
271     const auto hwcDisplayId = mDisplayData.at(displayId).hwcDisplay->getId();
272 
273     if (mComposer->isVrrSupported()) {
274         return getModesFromDisplayConfigurations(hwcDisplayId, maxFrameIntervalNs);
275     }
276 
277     return getModesFromLegacyDisplayConfigs(hwcDisplayId);
278 }
279 
getModesFromDisplayConfigurations(uint64_t hwcDisplayId,int32_t maxFrameIntervalNs) const280 std::vector<HWComposer::HWCDisplayMode> HWComposer::getModesFromDisplayConfigurations(
281         uint64_t hwcDisplayId, int32_t maxFrameIntervalNs) const {
282     std::vector<hal::DisplayConfiguration> configs;
283     auto error = static_cast<hal::Error>(
284             mComposer->getDisplayConfigurations(hwcDisplayId, maxFrameIntervalNs, &configs));
285     RETURN_IF_HWC_ERROR_FOR("getDisplayConfigurations", error, *toPhysicalDisplayId(hwcDisplayId),
286                             {});
287 
288     std::vector<HWCDisplayMode> modes;
289     modes.reserve(configs.size());
290     for (auto config : configs) {
291         auto hwcMode = HWCDisplayMode{.hwcId = static_cast<hal::HWConfigId>(config.configId),
292                                       .width = config.width,
293                                       .height = config.height,
294                                       .vsyncPeriod = config.vsyncPeriod,
295                                       .configGroup = config.configGroup,
296                                       .vrrConfig = config.vrrConfig};
297 
298         if (config.dpi) {
299             hwcMode.dpiX = config.dpi->x;
300             hwcMode.dpiY = config.dpi->y;
301         }
302 
303         if (!mEnableVrrTimeout) {
304             hwcMode.vrrConfig->notifyExpectedPresentConfig = {};
305         }
306 
307         modes.push_back(hwcMode);
308     }
309 
310     return modes;
311 }
312 
getModesFromLegacyDisplayConfigs(uint64_t hwcDisplayId) const313 std::vector<HWComposer::HWCDisplayMode> HWComposer::getModesFromLegacyDisplayConfigs(
314         uint64_t hwcDisplayId) const {
315     std::vector<hal::HWConfigId> configIds;
316     auto error = static_cast<hal::Error>(mComposer->getDisplayConfigs(hwcDisplayId, &configIds));
317     RETURN_IF_HWC_ERROR_FOR("getDisplayConfigs", error, *toPhysicalDisplayId(hwcDisplayId), {});
318 
319     std::vector<HWCDisplayMode> modes;
320     modes.reserve(configIds.size());
321     for (auto configId : configIds) {
322         auto hwcMode = HWCDisplayMode{
323                 .hwcId = configId,
324                 .width = getAttribute(hwcDisplayId, configId, hal::Attribute::WIDTH),
325                 .height = getAttribute(hwcDisplayId, configId, hal::Attribute::HEIGHT),
326                 .vsyncPeriod = getAttribute(hwcDisplayId, configId, hal::Attribute::VSYNC_PERIOD),
327                 .configGroup = getAttribute(hwcDisplayId, configId, hal::Attribute::CONFIG_GROUP),
328         };
329 
330         const int32_t dpiX = getAttribute(hwcDisplayId, configId, hal::Attribute::DPI_X);
331         const int32_t dpiY = getAttribute(hwcDisplayId, configId, hal::Attribute::DPI_Y);
332         if (dpiX != -1) {
333             hwcMode.dpiX = static_cast<float>(dpiX) / 1000.f;
334         }
335         if (dpiY != -1) {
336             hwcMode.dpiY = static_cast<float>(dpiY) / 1000.f;
337         }
338 
339         modes.push_back(hwcMode);
340     }
341     return modes;
342 }
343 
getActiveMode(PhysicalDisplayId displayId) const344 ftl::Expected<hal::HWConfigId, status_t> HWComposer::getActiveMode(
345         PhysicalDisplayId displayId) const {
346     RETURN_IF_INVALID_DISPLAY(displayId, ftl::Unexpected(BAD_INDEX));
347     const auto hwcId = *fromPhysicalDisplayId(displayId);
348 
349     hal::HWConfigId configId;
350     const auto error = static_cast<hal::Error>(mComposer->getActiveConfig(hwcId, &configId));
351     if (error == hal::Error::BAD_CONFIG) {
352         return ftl::Unexpected(NO_INIT);
353     }
354 
355     RETURN_IF_HWC_ERROR_FOR("getActiveConfig", error, displayId, ftl::Unexpected(UNKNOWN_ERROR));
356     return configId;
357 }
358 
359 // Composer 2.4
360 
getDisplayConnectionType(PhysicalDisplayId displayId) const361 ui::DisplayConnectionType HWComposer::getDisplayConnectionType(PhysicalDisplayId displayId) const {
362     RETURN_IF_INVALID_DISPLAY(displayId, ui::DisplayConnectionType::Internal);
363     const auto& hwcDisplay = mDisplayData.at(displayId).hwcDisplay;
364 
365     if (const auto connectionType = hwcDisplay->getConnectionType()) {
366         return connectionType.value();
367     } else {
368         LOG_HWC_ERROR(__func__, connectionType.error(), displayId);
369         return hwcDisplay->getId() == mPrimaryHwcDisplayId ? ui::DisplayConnectionType::Internal
370                                                            : ui::DisplayConnectionType::External;
371     }
372 }
373 
isVsyncPeriodSwitchSupported(PhysicalDisplayId displayId) const374 bool HWComposer::isVsyncPeriodSwitchSupported(PhysicalDisplayId displayId) const {
375     RETURN_IF_INVALID_DISPLAY(displayId, false);
376     return mDisplayData.at(displayId).hwcDisplay->isVsyncPeriodSwitchSupported();
377 }
378 
getDisplayVsyncPeriod(PhysicalDisplayId displayId) const379 ftl::Expected<nsecs_t, status_t> HWComposer::getDisplayVsyncPeriod(
380         PhysicalDisplayId displayId) const {
381     RETURN_IF_INVALID_DISPLAY(displayId, ftl::Unexpected(BAD_INDEX));
382 
383     if (!isVsyncPeriodSwitchSupported(displayId)) {
384         return ftl::Unexpected(INVALID_OPERATION);
385     }
386 
387     const auto hwcId = *fromPhysicalDisplayId(displayId);
388     Hwc2::VsyncPeriodNanos vsyncPeriodNanos = 0;
389     const auto error =
390             static_cast<hal::Error>(mComposer->getDisplayVsyncPeriod(hwcId, &vsyncPeriodNanos));
391     RETURN_IF_HWC_ERROR(error, displayId, ftl::Unexpected(UNKNOWN_ERROR));
392     return static_cast<nsecs_t>(vsyncPeriodNanos);
393 }
394 
getColorModes(PhysicalDisplayId displayId) const395 std::vector<ui::ColorMode> HWComposer::getColorModes(PhysicalDisplayId displayId) const {
396     RETURN_IF_INVALID_DISPLAY(displayId, {});
397 
398     std::vector<ui::ColorMode> modes;
399     auto error = mDisplayData.at(displayId).hwcDisplay->getColorModes(&modes);
400     RETURN_IF_HWC_ERROR(error, displayId, {});
401     return modes;
402 }
403 
setActiveColorMode(PhysicalDisplayId displayId,ui::ColorMode mode,ui::RenderIntent renderIntent)404 status_t HWComposer::setActiveColorMode(PhysicalDisplayId displayId, ui::ColorMode mode,
405                                         ui::RenderIntent renderIntent) {
406     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
407 
408     auto& displayData = mDisplayData[displayId];
409     auto error = displayData.hwcDisplay->setColorMode(mode, renderIntent);
410     RETURN_IF_HWC_ERROR_FOR(("setColorMode(" + decodeColorMode(mode) + ", " +
411                              decodeRenderIntent(renderIntent) + ")")
412                                     .c_str(),
413                             error, displayId, UNKNOWN_ERROR);
414 
415     return NO_ERROR;
416 }
417 
setVsyncEnabled(PhysicalDisplayId displayId,hal::Vsync enabled)418 void HWComposer::setVsyncEnabled(PhysicalDisplayId displayId, hal::Vsync enabled) {
419     RETURN_IF_INVALID_DISPLAY(displayId);
420     auto& displayData = mDisplayData[displayId];
421 
422     // NOTE: we use our own internal lock here because we have to call
423     // into the HWC with the lock held, and we want to make sure
424     // that even if HWC blocks (which it shouldn't), it won't
425     // affect other threads.
426     std::lock_guard lock(displayData.vsyncEnabledLock);
427     if (enabled == displayData.vsyncEnabled) {
428         return;
429     }
430 
431     ATRACE_CALL();
432     auto error = displayData.hwcDisplay->setVsyncEnabled(enabled);
433     RETURN_IF_HWC_ERROR(error, displayId);
434 
435     displayData.vsyncEnabled = enabled;
436 
437     ATRACE_INT(ftl::Concat("HW_VSYNC_ON_", displayId.value).c_str(),
438                enabled == hal::Vsync::ENABLE ? 1 : 0);
439 }
440 
setClientTarget(HalDisplayId displayId,uint32_t slot,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & target,ui::Dataspace dataspace,float hdrSdrRatio)441 status_t HWComposer::setClientTarget(HalDisplayId displayId, uint32_t slot,
442                                      const sp<Fence>& acquireFence, const sp<GraphicBuffer>& target,
443                                      ui::Dataspace dataspace, float hdrSdrRatio) {
444     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
445 
446     ALOGV("%s for display %s", __FUNCTION__, to_string(displayId).c_str());
447     auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
448     auto error = hwcDisplay->setClientTarget(slot, target, acquireFence, dataspace, hdrSdrRatio);
449     RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
450     return NO_ERROR;
451 }
452 
getDeviceCompositionChanges(HalDisplayId displayId,bool frameUsesClientComposition,std::optional<std::chrono::steady_clock::time_point> earliestPresentTime,nsecs_t expectedPresentTime,Fps frameInterval,std::optional<android::HWComposer::DeviceRequestedChanges> * outChanges)453 status_t HWComposer::getDeviceCompositionChanges(
454         HalDisplayId displayId, bool frameUsesClientComposition,
455         std::optional<std::chrono::steady_clock::time_point> earliestPresentTime,
456         nsecs_t expectedPresentTime, Fps frameInterval,
457         std::optional<android::HWComposer::DeviceRequestedChanges>* outChanges) {
458     ATRACE_CALL();
459 
460     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
461 
462     auto& displayData = mDisplayData[displayId];
463     auto& hwcDisplay = displayData.hwcDisplay;
464     if (!hwcDisplay->isConnected()) {
465         return NO_ERROR;
466     }
467 
468     uint32_t numTypes = 0;
469     uint32_t numRequests = 0;
470 
471     hal::Error error = hal::Error::NONE;
472 
473     // First try to skip validate altogether. We can do that when
474     // 1. The previous frame has not been presented yet or already passed the
475     // earliest time to present. Otherwise, we may present a frame too early.
476     // 2. There is no client composition. Otherwise, we first need to render the
477     // client target buffer.
478     const bool canSkipValidate = [&] {
479         // We must call validate if we have client composition
480         if (frameUsesClientComposition) {
481             return false;
482         }
483 
484         // If composer supports getting the expected present time, we can skip
485         // as composer will make sure to prevent early presentation
486         if (!earliestPresentTime) {
487             return true;
488         }
489 
490         // composer doesn't support getting the expected present time. We can only
491         // skip validate if we know that we are not going to present early.
492         return std::chrono::steady_clock::now() >= *earliestPresentTime;
493     }();
494 
495     displayData.validateWasSkipped = false;
496     ATRACE_FORMAT("NextFrameInterval %d_Hz", frameInterval.getIntValue());
497     if (canSkipValidate) {
498         sp<Fence> outPresentFence = Fence::NO_FENCE;
499         uint32_t state = UINT32_MAX;
500         error = hwcDisplay->presentOrValidate(expectedPresentTime, frameInterval.getPeriodNsecs(),
501                                               &numTypes, &numRequests, &outPresentFence, &state);
502         if (!hasChangesError(error)) {
503             RETURN_IF_HWC_ERROR_FOR("presentOrValidate", error, displayId, UNKNOWN_ERROR);
504         }
505         if (state == 1) { //Present Succeeded.
506             std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
507             error = hwcDisplay->getReleaseFences(&releaseFences);
508             displayData.releaseFences = std::move(releaseFences);
509             displayData.lastPresentFence = outPresentFence;
510             displayData.validateWasSkipped = true;
511             displayData.presentError = error;
512             return NO_ERROR;
513         }
514         // Present failed but Validate ran.
515     } else {
516         error = hwcDisplay->validate(expectedPresentTime, frameInterval.getPeriodNsecs(), &numTypes,
517                                      &numRequests);
518     }
519     ALOGV("SkipValidate failed, Falling back to SLOW validate/present");
520     if (!hasChangesError(error)) {
521         RETURN_IF_HWC_ERROR_FOR("validate", error, displayId, BAD_INDEX);
522     }
523 
524     android::HWComposer::DeviceRequestedChanges::ChangedTypes changedTypes;
525     changedTypes.reserve(numTypes);
526     error = hwcDisplay->getChangedCompositionTypes(&changedTypes);
527     RETURN_IF_HWC_ERROR_FOR("getChangedCompositionTypes", error, displayId, BAD_INDEX);
528 
529     auto displayRequests = static_cast<hal::DisplayRequest>(0);
530     android::HWComposer::DeviceRequestedChanges::LayerRequests layerRequests;
531     layerRequests.reserve(numRequests);
532     error = hwcDisplay->getRequests(&displayRequests, &layerRequests);
533     RETURN_IF_HWC_ERROR_FOR("getRequests", error, displayId, BAD_INDEX);
534 
535     DeviceRequestedChanges::ClientTargetProperty clientTargetProperty;
536     error = hwcDisplay->getClientTargetProperty(&clientTargetProperty);
537 
538     outChanges->emplace(DeviceRequestedChanges{std::move(changedTypes), std::move(displayRequests),
539                                                std::move(layerRequests),
540                                                std::move(clientTargetProperty)});
541     error = hwcDisplay->acceptChanges();
542     RETURN_IF_HWC_ERROR_FOR("acceptChanges", error, displayId, BAD_INDEX);
543 
544     return NO_ERROR;
545 }
546 
getPresentFence(HalDisplayId displayId) const547 sp<Fence> HWComposer::getPresentFence(HalDisplayId displayId) const {
548     RETURN_IF_INVALID_DISPLAY(displayId, Fence::NO_FENCE);
549     return mDisplayData.at(displayId).lastPresentFence;
550 }
551 
getPresentTimestamp(PhysicalDisplayId displayId) const552 nsecs_t HWComposer::getPresentTimestamp(PhysicalDisplayId displayId) const {
553     RETURN_IF_INVALID_DISPLAY(displayId, 0);
554     return mDisplayData.at(displayId).lastPresentTimestamp;
555 }
556 
getLayerReleaseFence(HalDisplayId displayId,HWC2::Layer * layer) const557 sp<Fence> HWComposer::getLayerReleaseFence(HalDisplayId displayId, HWC2::Layer* layer) const {
558     RETURN_IF_INVALID_DISPLAY(displayId, Fence::NO_FENCE);
559     const auto& displayFences = mDisplayData.at(displayId).releaseFences;
560     auto fence = displayFences.find(layer);
561     if (fence == displayFences.end()) {
562         ALOGV("getLayerReleaseFence: Release fence not found");
563         return Fence::NO_FENCE;
564     }
565     return fence->second;
566 }
567 
presentAndGetReleaseFences(HalDisplayId displayId,std::optional<std::chrono::steady_clock::time_point> earliestPresentTime)568 status_t HWComposer::presentAndGetReleaseFences(
569         HalDisplayId displayId,
570         std::optional<std::chrono::steady_clock::time_point> earliestPresentTime) {
571     ATRACE_CALL();
572 
573     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
574 
575     auto& displayData = mDisplayData[displayId];
576     auto& hwcDisplay = displayData.hwcDisplay;
577 
578     if (displayData.validateWasSkipped) {
579         // explicitly flush all pending commands
580         auto error = static_cast<hal::Error>(mComposer->executeCommands(hwcDisplay->getId()));
581         RETURN_IF_HWC_ERROR_FOR("executeCommands", error, displayId, UNKNOWN_ERROR);
582         RETURN_IF_HWC_ERROR_FOR("present", displayData.presentError, displayId, UNKNOWN_ERROR);
583         return NO_ERROR;
584     }
585 
586     if (earliestPresentTime) {
587         ATRACE_NAME("wait for earliest present time");
588         std::this_thread::sleep_until(*earliestPresentTime);
589     }
590 
591     auto error = hwcDisplay->present(&displayData.lastPresentFence);
592     RETURN_IF_HWC_ERROR_FOR("present", error, displayId, UNKNOWN_ERROR);
593 
594     std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
595     error = hwcDisplay->getReleaseFences(&releaseFences);
596     RETURN_IF_HWC_ERROR_FOR("getReleaseFences", error, displayId, UNKNOWN_ERROR);
597 
598     displayData.releaseFences = std::move(releaseFences);
599 
600     return NO_ERROR;
601 }
602 
executeCommands(HalDisplayId displayId)603 status_t HWComposer::executeCommands(HalDisplayId displayId) {
604     auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
605     auto error = static_cast<hal::Error>(mComposer->executeCommands(hwcDisplay->getId()));
606     RETURN_IF_HWC_ERROR_FOR("executeCommands", error, displayId, UNKNOWN_ERROR);
607     return NO_ERROR;
608 }
609 
setPowerMode(PhysicalDisplayId displayId,hal::PowerMode mode)610 status_t HWComposer::setPowerMode(PhysicalDisplayId displayId, hal::PowerMode mode) {
611     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
612 
613     if (mode == hal::PowerMode::OFF) {
614         setVsyncEnabled(displayId, hal::Vsync::DISABLE);
615     }
616 
617     const auto& displayData = mDisplayData[displayId];
618     auto& hwcDisplay = displayData.hwcDisplay;
619     switch (mode) {
620         case hal::PowerMode::OFF:
621         case hal::PowerMode::ON:
622             ALOGV("setPowerMode: Calling HWC %s", to_string(mode).c_str());
623             {
624                 auto error = hwcDisplay->setPowerMode(mode);
625                 if (error != hal::Error::NONE) {
626                     LOG_HWC_ERROR(("setPowerMode(" + to_string(mode) + ")").c_str(), error,
627                                   displayId);
628                 }
629             }
630             break;
631         case hal::PowerMode::DOZE:
632         case hal::PowerMode::DOZE_SUSPEND:
633             ALOGV("setPowerMode: Calling HWC %s", to_string(mode).c_str());
634             {
635                 bool supportsDoze = false;
636                 const auto queryDozeError = hwcDisplay->supportsDoze(&supportsDoze);
637 
638                 // queryDozeError might be NO_RESOURCES, in the case of a display that has never
639                 // been turned on. In that case, attempt to set to DOZE anyway.
640                 if (!supportsDoze && queryDozeError == hal::Error::NONE) {
641                     mode = hal::PowerMode::ON;
642                 }
643 
644                 auto error = hwcDisplay->setPowerMode(mode);
645                 if (error != hal::Error::NONE) {
646                     LOG_HWC_ERROR(("setPowerMode(" + to_string(mode) + ")").c_str(), error,
647                                   displayId);
648                     // If the display had never been turned on, so its doze
649                     // support was unknown, it may truly not support doze. Try
650                     // switching it to ON instead.
651                     if (queryDozeError == hal::Error::NO_RESOURCES) {
652                         ALOGD("%s: failed to set %s to %s. Trying again with ON", __func__,
653                               to_string(displayId).c_str(), to_string(mode).c_str());
654                         error = hwcDisplay->setPowerMode(hal::PowerMode::ON);
655                         if (error != hal::Error::NONE) {
656                             LOG_HWC_ERROR("setPowerMode(ON)", error, displayId);
657                         }
658                     }
659                 }
660             }
661             break;
662         default:
663             ALOGV("setPowerMode: Not calling HWC");
664             break;
665     }
666 
667     return NO_ERROR;
668 }
669 
setActiveModeWithConstraints(PhysicalDisplayId displayId,hal::HWConfigId hwcModeId,const hal::VsyncPeriodChangeConstraints & constraints,hal::VsyncPeriodChangeTimeline * outTimeline)670 status_t HWComposer::setActiveModeWithConstraints(
671         PhysicalDisplayId displayId, hal::HWConfigId hwcModeId,
672         const hal::VsyncPeriodChangeConstraints& constraints,
673         hal::VsyncPeriodChangeTimeline* outTimeline) {
674     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
675 
676     auto error = mDisplayData[displayId].hwcDisplay->setActiveConfigWithConstraints(hwcModeId,
677                                                                                     constraints,
678                                                                                     outTimeline);
679     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
680     return NO_ERROR;
681 }
682 
setColorTransform(HalDisplayId displayId,const mat4 & transform)683 status_t HWComposer::setColorTransform(HalDisplayId displayId, const mat4& transform) {
684     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
685 
686     auto& displayData = mDisplayData[displayId];
687     auto error = displayData.hwcDisplay->setColorTransform(transform);
688     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
689     return NO_ERROR;
690 }
691 
disconnectDisplay(HalDisplayId displayId)692 void HWComposer::disconnectDisplay(HalDisplayId displayId) {
693     RETURN_IF_INVALID_DISPLAY(displayId);
694     auto& displayData = mDisplayData[displayId];
695     const auto hwcDisplayId = displayData.hwcDisplay->getId();
696 
697     mPhysicalDisplayIdMap.erase(hwcDisplayId);
698     mDisplayData.erase(displayId);
699 
700     // Reset the primary display ID if we're disconnecting it.
701     // This way isHeadless() will return false, which is necessary
702     // because getPrimaryDisplayId() will crash.
703     if (mPrimaryHwcDisplayId == hwcDisplayId) {
704         mPrimaryHwcDisplayId.reset();
705     }
706 }
707 
setOutputBuffer(HalVirtualDisplayId displayId,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buffer)708 status_t HWComposer::setOutputBuffer(HalVirtualDisplayId displayId, const sp<Fence>& acquireFence,
709                                      const sp<GraphicBuffer>& buffer) {
710     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
711     const auto& displayData = mDisplayData[displayId];
712 
713     auto error = displayData.hwcDisplay->setOutputBuffer(buffer, acquireFence);
714     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
715     return NO_ERROR;
716 }
717 
clearReleaseFences(HalDisplayId displayId)718 void HWComposer::clearReleaseFences(HalDisplayId displayId) {
719     RETURN_IF_INVALID_DISPLAY(displayId);
720     mDisplayData[displayId].releaseFences.clear();
721 }
722 
getHdrCapabilities(HalDisplayId displayId,HdrCapabilities * outCapabilities)723 status_t HWComposer::getHdrCapabilities(HalDisplayId displayId, HdrCapabilities* outCapabilities) {
724     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
725 
726     auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
727     auto error = hwcDisplay->getHdrCapabilities(outCapabilities);
728     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
729     return NO_ERROR;
730 }
731 
732 const aidl::android::hardware::graphics::composer3::OverlayProperties&
getOverlaySupport() const733 HWComposer::getOverlaySupport() const {
734     return mOverlayProperties;
735 }
736 
getSupportedPerFrameMetadata(HalDisplayId displayId) const737 int32_t HWComposer::getSupportedPerFrameMetadata(HalDisplayId displayId) const {
738     RETURN_IF_INVALID_DISPLAY(displayId, 0);
739     return mDisplayData.at(displayId).hwcDisplay->getSupportedPerFrameMetadata();
740 }
741 
getRenderIntents(HalDisplayId displayId,ui::ColorMode colorMode) const742 std::vector<ui::RenderIntent> HWComposer::getRenderIntents(HalDisplayId displayId,
743                                                            ui::ColorMode colorMode) const {
744     RETURN_IF_INVALID_DISPLAY(displayId, {});
745 
746     std::vector<ui::RenderIntent> renderIntents;
747     auto error = mDisplayData.at(displayId).hwcDisplay->getRenderIntents(colorMode, &renderIntents);
748     RETURN_IF_HWC_ERROR(error, displayId, {});
749     return renderIntents;
750 }
751 
getDataspaceSaturationMatrix(HalDisplayId displayId,ui::Dataspace dataspace)752 mat4 HWComposer::getDataspaceSaturationMatrix(HalDisplayId displayId, ui::Dataspace dataspace) {
753     RETURN_IF_INVALID_DISPLAY(displayId, {});
754 
755     mat4 matrix;
756     auto error = mDisplayData[displayId].hwcDisplay->getDataspaceSaturationMatrix(dataspace,
757             &matrix);
758     RETURN_IF_HWC_ERROR(error, displayId, {});
759     return matrix;
760 }
761 
getDisplayedContentSamplingAttributes(HalDisplayId displayId,ui::PixelFormat * outFormat,ui::Dataspace * outDataspace,uint8_t * outComponentMask)762 status_t HWComposer::getDisplayedContentSamplingAttributes(HalDisplayId displayId,
763                                                            ui::PixelFormat* outFormat,
764                                                            ui::Dataspace* outDataspace,
765                                                            uint8_t* outComponentMask) {
766     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
767     const auto error =
768             mDisplayData[displayId]
769                     .hwcDisplay->getDisplayedContentSamplingAttributes(outFormat, outDataspace,
770                                                                        outComponentMask);
771     if (error == hal::Error::UNSUPPORTED) RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
772     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
773     return NO_ERROR;
774 }
775 
setDisplayContentSamplingEnabled(HalDisplayId displayId,bool enabled,uint8_t componentMask,uint64_t maxFrames)776 status_t HWComposer::setDisplayContentSamplingEnabled(HalDisplayId displayId, bool enabled,
777                                                       uint8_t componentMask, uint64_t maxFrames) {
778     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
779     const auto error =
780             mDisplayData[displayId].hwcDisplay->setDisplayContentSamplingEnabled(enabled,
781                                                                                  componentMask,
782                                                                                  maxFrames);
783 
784     if (error == hal::Error::UNSUPPORTED) RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
785     if (error == hal::Error::BAD_PARAMETER) RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
786     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
787     return NO_ERROR;
788 }
789 
getDisplayedContentSample(HalDisplayId displayId,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats)790 status_t HWComposer::getDisplayedContentSample(HalDisplayId displayId, uint64_t maxFrames,
791                                                uint64_t timestamp, DisplayedFrameStats* outStats) {
792     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
793     const auto error =
794             mDisplayData[displayId].hwcDisplay->getDisplayedContentSample(maxFrames, timestamp,
795                                                                           outStats);
796     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
797     return NO_ERROR;
798 }
799 
setDisplayBrightness(PhysicalDisplayId displayId,float brightness,float brightnessNits,const Hwc2::Composer::DisplayBrightnessOptions & options)800 ftl::Future<status_t> HWComposer::setDisplayBrightness(
801         PhysicalDisplayId displayId, float brightness, float brightnessNits,
802         const Hwc2::Composer::DisplayBrightnessOptions& options) {
803     RETURN_IF_INVALID_DISPLAY(displayId, ftl::yield<status_t>(BAD_INDEX));
804     auto& display = mDisplayData[displayId].hwcDisplay;
805 
806     return display->setDisplayBrightness(brightness, brightnessNits, options)
807             .then([displayId](hal::Error error) -> status_t {
808                 if (error == hal::Error::UNSUPPORTED) {
809                     RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
810                 }
811                 if (error == hal::Error::BAD_PARAMETER) {
812                     RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
813                 }
814                 RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
815                 return NO_ERROR;
816             });
817 }
818 
getValidateSkipped(HalDisplayId displayId) const819 bool HWComposer::getValidateSkipped(HalDisplayId displayId) const {
820     if (mDisplayData.count(displayId) == 0) {
821         return false;
822     }
823     return mDisplayData.at(displayId).validateWasSkipped;
824 }
825 
setBootDisplayMode(PhysicalDisplayId displayId,hal::HWConfigId displayModeId)826 status_t HWComposer::setBootDisplayMode(PhysicalDisplayId displayId,
827                                         hal::HWConfigId displayModeId) {
828     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
829     const auto error = mDisplayData[displayId].hwcDisplay->setBootDisplayConfig(displayModeId);
830     if (error == hal::Error::UNSUPPORTED) {
831         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
832     }
833     if (error == hal::Error::BAD_PARAMETER) {
834         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
835     }
836     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
837     return NO_ERROR;
838 }
839 
clearBootDisplayMode(PhysicalDisplayId displayId)840 status_t HWComposer::clearBootDisplayMode(PhysicalDisplayId displayId) {
841     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
842     const auto error = mDisplayData[displayId].hwcDisplay->clearBootDisplayConfig();
843     if (error == hal::Error::UNSUPPORTED) {
844         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
845     }
846     if (error == hal::Error::BAD_PARAMETER) {
847         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
848     }
849     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
850     return NO_ERROR;
851 }
852 
getPreferredBootDisplayMode(PhysicalDisplayId displayId)853 std::optional<hal::HWConfigId> HWComposer::getPreferredBootDisplayMode(
854         PhysicalDisplayId displayId) {
855     RETURN_IF_INVALID_DISPLAY(displayId, std::nullopt);
856     hal::HWConfigId displayModeId;
857     const auto error =
858             mDisplayData[displayId].hwcDisplay->getPreferredBootDisplayConfig(&displayModeId);
859     if (error != hal::Error::NONE) {
860         LOG_DISPLAY_ERROR(displayId, to_string(error).c_str());
861         return std::nullopt;
862     }
863     return displayModeId;
864 }
865 
getHdrConversionCapabilities() const866 std::vector<HdrConversionCapability> HWComposer::getHdrConversionCapabilities() const {
867     return mHdrConversionCapabilities;
868 }
869 
setHdrConversionStrategy(HdrConversionStrategy hdrConversionStrategy,aidl::android::hardware::graphics::common::Hdr * outPreferredHdrOutputType)870 status_t HWComposer::setHdrConversionStrategy(
871         HdrConversionStrategy hdrConversionStrategy,
872         aidl::android::hardware::graphics::common::Hdr* outPreferredHdrOutputType) {
873     const auto error =
874             mComposer->setHdrConversionStrategy(hdrConversionStrategy, outPreferredHdrOutputType);
875     if (error != hal::Error::NONE) {
876         ALOGE("Error in setting HDR conversion strategy %s", to_string(error).c_str());
877         return INVALID_OPERATION;
878     }
879     return NO_ERROR;
880 }
881 
setRefreshRateChangedCallbackDebugEnabled(PhysicalDisplayId displayId,bool enabled)882 status_t HWComposer::setRefreshRateChangedCallbackDebugEnabled(PhysicalDisplayId displayId,
883                                                                bool enabled) {
884     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
885     const auto error =
886             mComposer->setRefreshRateChangedCallbackDebugEnabled(mDisplayData[displayId]
887                                                                          .hwcDisplay->getId(),
888                                                                  enabled);
889     if (error != hal::Error::NONE) {
890         ALOGE("Error in setting refresh refresh rate change callback debug enabled %s",
891               to_string(error).c_str());
892         return INVALID_OPERATION;
893     }
894     return NO_ERROR;
895 }
896 
notifyExpectedPresent(PhysicalDisplayId displayId,TimePoint expectedPresentTime,Fps frameInterval)897 status_t HWComposer::notifyExpectedPresent(PhysicalDisplayId displayId,
898                                            TimePoint expectedPresentTime, Fps frameInterval) {
899     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
900     ATRACE_FORMAT("%s ExpectedPresentTime in %.2fms frameInterval %.2fms", __func__,
901                   ticks<std::milli, float>(expectedPresentTime - TimePoint::now()),
902                   ticks<std::milli, float>(Duration::fromNs(frameInterval.getPeriodNsecs())));
903     const auto error = mComposer->notifyExpectedPresent(mDisplayData[displayId].hwcDisplay->getId(),
904                                                         expectedPresentTime.ns(),
905                                                         frameInterval.getPeriodNsecs());
906     if (error != hal::Error::NONE) {
907         ALOGE("Error in notifyExpectedPresent call %s", to_string(error).c_str());
908         return INVALID_OPERATION;
909     }
910     return NO_ERROR;
911 }
912 
getDisplayDecorationSupport(PhysicalDisplayId displayId,std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> * support)913 status_t HWComposer::getDisplayDecorationSupport(
914         PhysicalDisplayId displayId,
915         std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport>*
916                 support) {
917     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
918     const auto error = mDisplayData[displayId].hwcDisplay->getDisplayDecorationSupport(support);
919     if (error == hal::Error::UNSUPPORTED) {
920         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
921     }
922     if (error == hal::Error::BAD_PARAMETER) {
923         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
924     }
925     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
926     return NO_ERROR;
927 }
928 
setAutoLowLatencyMode(PhysicalDisplayId displayId,bool on)929 status_t HWComposer::setAutoLowLatencyMode(PhysicalDisplayId displayId, bool on) {
930     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
931     const auto error = mDisplayData[displayId].hwcDisplay->setAutoLowLatencyMode(on);
932     if (error == hal::Error::UNSUPPORTED) {
933         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
934     }
935     if (error == hal::Error::BAD_PARAMETER) {
936         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
937     }
938     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
939     return NO_ERROR;
940 }
941 
getSupportedContentTypes(PhysicalDisplayId displayId,std::vector<hal::ContentType> * outSupportedContentTypes) const942 status_t HWComposer::getSupportedContentTypes(
943         PhysicalDisplayId displayId,
944         std::vector<hal::ContentType>* outSupportedContentTypes) const {
945     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
946     const auto error = mDisplayData.at(displayId).hwcDisplay->getSupportedContentTypes(
947             outSupportedContentTypes);
948 
949     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
950 
951     return NO_ERROR;
952 }
953 
setContentType(PhysicalDisplayId displayId,hal::ContentType contentType)954 status_t HWComposer::setContentType(PhysicalDisplayId displayId, hal::ContentType contentType) {
955     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
956     const auto error = mDisplayData[displayId].hwcDisplay->setContentType(contentType);
957     if (error == hal::Error::UNSUPPORTED) {
958         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
959     }
960     if (error == hal::Error::BAD_PARAMETER) {
961         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
962     }
963     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
964 
965     return NO_ERROR;
966 }
967 
getSupportedLayerGenericMetadata() const968 const std::unordered_map<std::string, bool>& HWComposer::getSupportedLayerGenericMetadata() const {
969     return mSupportedLayerGenericMetadata;
970 }
971 
dumpOverlayProperties(std::string & result) const972 void HWComposer::dumpOverlayProperties(std::string& result) const {
973     // dump overlay properties
974     result.append("OverlayProperties:\n");
975     base::StringAppendF(&result, "supportMixedColorSpaces: %d\n",
976                         mOverlayProperties.supportMixedColorSpaces);
977     base::StringAppendF(&result, "SupportedBufferCombinations(%zu entries)\n",
978                         mOverlayProperties.combinations.size());
979     for (const auto& combination : mOverlayProperties.combinations) {
980         result.append("    pixelFormats=\n");
981         for (const auto& pixelFormat : combination.pixelFormats) {
982             base::StringAppendF(&result, "        %s (%d)\n",
983                                 decodePixelFormat(static_cast<PixelFormat>(pixelFormat)).c_str(),
984                                 static_cast<uint32_t>(pixelFormat));
985         }
986         result.append("    standards=\n");
987         for (const auto& standard : combination.standards) {
988             base::StringAppendF(&result, "        %s (%d)\n",
989                                 decodeStandardOnly(static_cast<uint32_t>(standard)).c_str(),
990                                 static_cast<uint32_t>(standard));
991         }
992         result.append("    transfers=\n");
993         for (const auto& transfer : combination.transfers) {
994             base::StringAppendF(&result, "        %s (%d)\n",
995                                 decodeTransferOnly(static_cast<uint32_t>(transfer)).c_str(),
996                                 static_cast<uint32_t>(transfer));
997         }
998         result.append("    ranges=\n");
999         for (const auto& range : combination.ranges) {
1000             base::StringAppendF(&result, "        %s (%d)\n",
1001                                 decodeRangeOnly(static_cast<uint32_t>(range)).c_str(),
1002                                 static_cast<uint32_t>(range));
1003         }
1004         result.append("\n");
1005     }
1006 }
1007 
dump(std::string & result) const1008 void HWComposer::dump(std::string& result) const {
1009     result.append(mComposer->dumpDebugInfo());
1010     dumpOverlayProperties(result);
1011 }
1012 
toPhysicalDisplayId(hal::HWDisplayId hwcDisplayId) const1013 std::optional<PhysicalDisplayId> HWComposer::toPhysicalDisplayId(
1014         hal::HWDisplayId hwcDisplayId) const {
1015     if (const auto it = mPhysicalDisplayIdMap.find(hwcDisplayId);
1016         it != mPhysicalDisplayIdMap.end()) {
1017         return it->second;
1018     }
1019     return {};
1020 }
1021 
fromPhysicalDisplayId(PhysicalDisplayId displayId) const1022 std::optional<hal::HWDisplayId> HWComposer::fromPhysicalDisplayId(
1023         PhysicalDisplayId displayId) const {
1024     if (const auto it = mDisplayData.find(displayId); it != mDisplayData.end()) {
1025         return it->second.hwcDisplay->getId();
1026     }
1027     return {};
1028 }
1029 
shouldIgnoreHotplugConnect(hal::HWDisplayId hwcDisplayId,bool hasDisplayIdentificationData) const1030 bool HWComposer::shouldIgnoreHotplugConnect(hal::HWDisplayId hwcDisplayId,
1031                                             bool hasDisplayIdentificationData) const {
1032     if (mHasMultiDisplaySupport && !hasDisplayIdentificationData) {
1033         ALOGE("Ignoring connection of display %" PRIu64 " without identification data",
1034               hwcDisplayId);
1035         return true;
1036     }
1037 
1038     // Legacy mode only supports IDs LEGACY_DISPLAY_TYPE_PRIMARY and LEGACY_DISPLAY_TYPE_EXTERNAL.
1039     if (!mHasMultiDisplaySupport && mPhysicalDisplayIdMap.size() == 2) {
1040         ALOGE("Ignoring connection of tertiary display %" PRIu64, hwcDisplayId);
1041         return true;
1042     }
1043 
1044     return false;
1045 }
1046 
onHotplugConnect(hal::HWDisplayId hwcDisplayId)1047 std::optional<DisplayIdentificationInfo> HWComposer::onHotplugConnect(
1048         hal::HWDisplayId hwcDisplayId) {
1049     std::optional<DisplayIdentificationInfo> info;
1050     if (const auto displayId = toPhysicalDisplayId(hwcDisplayId)) {
1051         info = DisplayIdentificationInfo{.id = *displayId,
1052                                          .name = std::string(),
1053                                          .deviceProductInfo = std::nullopt};
1054         if (mUpdateDeviceProductInfoOnHotplugReconnect) {
1055             uint8_t port;
1056             DisplayIdentificationData data;
1057             getDisplayIdentificationData(hwcDisplayId, &port, &data);
1058             if (auto newInfo = parseDisplayIdentificationData(port, data)) {
1059                 info->deviceProductInfo = std::move(newInfo->deviceProductInfo);
1060             } else {
1061                 ALOGE("Failed to parse identification data for display %" PRIu64, hwcDisplayId);
1062             }
1063         }
1064     } else {
1065         uint8_t port;
1066         DisplayIdentificationData data;
1067         const bool hasDisplayIdentificationData =
1068                 getDisplayIdentificationData(hwcDisplayId, &port, &data);
1069         if (mPhysicalDisplayIdMap.empty()) {
1070             mHasMultiDisplaySupport = hasDisplayIdentificationData;
1071             ALOGI("Switching to %s multi-display mode",
1072                   mHasMultiDisplaySupport ? "generalized" : "legacy");
1073         }
1074 
1075         if (shouldIgnoreHotplugConnect(hwcDisplayId, hasDisplayIdentificationData)) {
1076             return {};
1077         }
1078 
1079         info = [this, hwcDisplayId, &port, &data, hasDisplayIdentificationData] {
1080             const bool isPrimary = !mPrimaryHwcDisplayId;
1081             if (mHasMultiDisplaySupport) {
1082                 if (const auto info = parseDisplayIdentificationData(port, data)) {
1083                     return *info;
1084                 }
1085                 ALOGE("Failed to parse identification data for display %" PRIu64, hwcDisplayId);
1086             } else {
1087                 ALOGW_IF(hasDisplayIdentificationData,
1088                          "Ignoring identification data for display %" PRIu64, hwcDisplayId);
1089                 port = isPrimary ? LEGACY_DISPLAY_TYPE_PRIMARY : LEGACY_DISPLAY_TYPE_EXTERNAL;
1090             }
1091 
1092             return DisplayIdentificationInfo{.id = PhysicalDisplayId::fromPort(port),
1093                                              .name = isPrimary ? "Primary display"
1094                                                                : "Secondary display",
1095                                              .deviceProductInfo = std::nullopt};
1096         }();
1097 
1098         mComposer->onHotplugConnect(hwcDisplayId);
1099     }
1100 
1101     if (!isConnected(info->id)) {
1102         allocatePhysicalDisplay(hwcDisplayId, info->id);
1103     }
1104     return info;
1105 }
1106 
onHotplugDisconnect(hal::HWDisplayId hwcDisplayId)1107 std::optional<DisplayIdentificationInfo> HWComposer::onHotplugDisconnect(
1108         hal::HWDisplayId hwcDisplayId) {
1109     LOG_ALWAYS_FATAL_IF(hwcDisplayId == mPrimaryHwcDisplayId,
1110                         "Primary display cannot be disconnected.");
1111 
1112     const auto displayId = toPhysicalDisplayId(hwcDisplayId);
1113     if (!displayId) {
1114         LOG_HWC_DISPLAY_ERROR(hwcDisplayId, "Invalid HWC display");
1115         return {};
1116     }
1117 
1118     if (!isConnected(*displayId)) {
1119         LOG_HWC_DISPLAY_ERROR(hwcDisplayId, "Already disconnected");
1120         return {};
1121     }
1122 
1123     // The display will later be destroyed by a call to HWComposer::disconnectDisplay. For now, mark
1124     // it as disconnected.
1125     mDisplayData.at(*displayId).hwcDisplay->setConnected(false);
1126     mComposer->onHotplugDisconnect(hwcDisplayId);
1127     return DisplayIdentificationInfo{.id = *displayId};
1128 }
1129 
loadCapabilities()1130 void HWComposer::loadCapabilities() {
1131     static_assert(sizeof(hal::Capability) == sizeof(int32_t), "Capability size has changed");
1132     auto capabilities = mComposer->getCapabilities();
1133     for (auto capability : capabilities) {
1134         mCapabilities.emplace(capability);
1135     }
1136 }
1137 
loadOverlayProperties()1138 void HWComposer::loadOverlayProperties() {
1139     mComposer->getOverlaySupport(&mOverlayProperties);
1140 }
1141 
loadHdrConversionCapabilities()1142 void HWComposer::loadHdrConversionCapabilities() {
1143     const auto error = mComposer->getHdrConversionCapabilities(&mHdrConversionCapabilities);
1144     if (error != hal::Error::NONE) {
1145         ALOGE("Error in fetching HDR conversion capabilities %s", to_string(error).c_str());
1146         mHdrConversionCapabilities = {};
1147     }
1148 }
1149 
setIdleTimerEnabled(PhysicalDisplayId displayId,std::chrono::milliseconds timeout)1150 status_t HWComposer::setIdleTimerEnabled(PhysicalDisplayId displayId,
1151                                          std::chrono::milliseconds timeout) {
1152     ATRACE_CALL();
1153     RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
1154     const auto error = mDisplayData[displayId].hwcDisplay->setIdleTimerEnabled(timeout);
1155     if (error == hal::Error::UNSUPPORTED) {
1156         RETURN_IF_HWC_ERROR(error, displayId, INVALID_OPERATION);
1157     }
1158     if (error == hal::Error::BAD_PARAMETER) {
1159         RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
1160     }
1161     RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
1162     return NO_ERROR;
1163 }
1164 
hasDisplayIdleTimerCapability(PhysicalDisplayId displayId) const1165 bool HWComposer::hasDisplayIdleTimerCapability(PhysicalDisplayId displayId) const {
1166     RETURN_IF_INVALID_DISPLAY(displayId, false);
1167     return mDisplayData.at(displayId).hwcDisplay->hasDisplayIdleTimerCapability();
1168 }
1169 
getPhysicalDisplayOrientation(PhysicalDisplayId displayId) const1170 Hwc2::AidlTransform HWComposer::getPhysicalDisplayOrientation(PhysicalDisplayId displayId) const {
1171     ATRACE_CALL();
1172     RETURN_IF_INVALID_DISPLAY(displayId, Hwc2::AidlTransform::NONE);
1173     Hwc2::AidlTransform outTransform;
1174     const auto& hwcDisplay = mDisplayData.at(displayId).hwcDisplay;
1175     const auto error = hwcDisplay->getPhysicalDisplayOrientation(&outTransform);
1176     RETURN_IF_HWC_ERROR(error, displayId, Hwc2::AidlTransform::NONE);
1177     return outTransform;
1178 }
1179 
loadLayerMetadataSupport()1180 void HWComposer::loadLayerMetadataSupport() {
1181     mSupportedLayerGenericMetadata.clear();
1182 
1183     std::vector<Hwc2::IComposerClient::LayerGenericMetadataKey> supportedMetadataKeyInfo;
1184     const auto error = mComposer->getLayerGenericMetadataKeys(&supportedMetadataKeyInfo);
1185     if (error != hardware::graphics::composer::V2_4::Error::NONE) {
1186         if (error != hardware::graphics::composer::V2_4::Error::UNSUPPORTED) {
1187             ALOGE("%s: %s failed: %s (%d)", __FUNCTION__, "getLayerGenericMetadataKeys",
1188                   toString(error).c_str(), static_cast<int32_t>(error));
1189         }
1190         return;
1191     }
1192 
1193     for (const auto& [name, mandatory] : supportedMetadataKeyInfo) {
1194         mSupportedLayerGenericMetadata.emplace(name, mandatory);
1195     }
1196 }
1197 
1198 } // namespace impl
1199 } // namespace android
1200 
1201 // TODO(b/129481165): remove the #pragma below and fix conversion issues
1202 #pragma clang diagnostic pop // ignored "-Wconversion"
1203