• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20 
21 // #define LOG_NDEBUG 0
22 
23 #undef LOG_TAG
24 #define LOG_TAG "HWC2"
25 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
26 
27 #include "HWC2.h"
28 
29 #include <android/configuration.h>
30 #include <common/FlagManager.h>
31 #include <ui/Fence.h>
32 #include <ui/FloatRect.h>
33 #include <ui/GraphicBuffer.h>
34 
35 #include <algorithm>
36 #include <cinttypes>
37 #include <iterator>
38 #include <set>
39 
40 using aidl::android::hardware::graphics::composer3::Color;
41 using aidl::android::hardware::graphics::composer3::Composition;
42 using AidlCapability = aidl::android::hardware::graphics::composer3::Capability;
43 using aidl::android::hardware::graphics::composer3::DisplayCapability;
44 using aidl::android::hardware::graphics::composer3::OverlayProperties;
45 
46 namespace android {
47 
48 using android::Fence;
49 using android::FloatRect;
50 using android::GraphicBuffer;
51 using android::HdrCapabilities;
52 using android::HdrMetadata;
53 using android::Rect;
54 using android::Region;
55 using android::sp;
56 
57 namespace HWC2 {
58 
59 using namespace android::hardware::graphics::composer::hal;
60 
61 namespace Hwc2 = android::Hwc2;
62 
63 namespace {
64 
hasMetadataKey(const std::set<Hwc2::PerFrameMetadataKey> & keys,const Hwc2::PerFrameMetadataKey & key)65 inline bool hasMetadataKey(const std::set<Hwc2::PerFrameMetadataKey>& keys,
66                            const Hwc2::PerFrameMetadataKey& key) {
67     return keys.find(key) != keys.end();
68 }
69 
70 } // namespace anonymous
71 
72 // Display methods
73 Display::~Display() = default;
74 
75 namespace impl {
76 
Display(android::Hwc2::Composer & composer,const std::unordered_set<AidlCapability> & capabilities,HWDisplayId id,DisplayType type)77 Display::Display(android::Hwc2::Composer& composer,
78                  const std::unordered_set<AidlCapability>& capabilities, HWDisplayId id,
79                  DisplayType type)
80       : mComposer(composer), mCapabilities(capabilities), mId(id), mType(type) {
81     ALOGV("Created display %" PRIu64, id);
82     if (mType == hal::DisplayType::VIRTUAL) {
83         loadDisplayCapabilities();
84     }
85 }
86 
~Display()87 Display::~Display() {
88     // Note: The calls to onOwningDisplayDestroyed() are allowed (and expected)
89     // to call Display::onLayerDestroyed(). As that call removes entries from
90     // mLayers, we do not want to have a for loop directly over it here. Since
91     // the end goal is an empty mLayers anyway, we just go ahead and swap an
92     // initially empty local container with mLayers, and then enumerate
93     // the contents of the local container.
94     Layers destroyingLayers;
95     std::swap(mLayers, destroyingLayers);
96     for (const auto& [_, weakLayer] : destroyingLayers) {
97         if (std::shared_ptr layer = weakLayer.lock()) {
98             layer->onOwningDisplayDestroyed();
99         }
100     }
101 
102     Error error = Error::NONE;
103     const char* msg;
104     switch (mType) {
105         case DisplayType::PHYSICAL:
106             error = setVsyncEnabled(HWC2::Vsync::DISABLE);
107             msg = "disable VSYNC for";
108             break;
109 
110         case DisplayType::VIRTUAL:
111             error = static_cast<Error>(mComposer.destroyVirtualDisplay(mId));
112             msg = "destroy virtual";
113             break;
114 
115         case DisplayType::INVALID: // Used in unit tests.
116             break;
117     }
118 
119     ALOGE_IF(error != Error::NONE, "%s: Failed to %s display %" PRIu64 ": %d", __FUNCTION__, msg,
120              mId, static_cast<int32_t>(error));
121 
122     ALOGV("Destroyed display %" PRIu64, mId);
123 }
124 
125 // Required by HWC2 display
acceptChanges()126 Error Display::acceptChanges()
127 {
128     auto intError = mComposer.acceptDisplayChanges(mId);
129     return static_cast<Error>(intError);
130 }
131 
createLayer()132 base::expected<std::shared_ptr<HWC2::Layer>, hal::Error> Display::createLayer() {
133     HWLayerId layerId = 0;
134     auto intError = mComposer.createLayer(mId, &layerId);
135     auto error = static_cast<Error>(intError);
136     if (error != Error::NONE) {
137         return base::unexpected(error);
138     }
139 
140     auto layer = std::make_shared<impl::Layer>(mComposer, mCapabilities, *this, layerId);
141     mLayers.emplace(layerId, layer);
142     return layer;
143 }
144 
onLayerDestroyed(hal::HWLayerId layerId)145 void Display::onLayerDestroyed(hal::HWLayerId layerId) {
146     mLayers.erase(layerId);
147 }
148 
isVsyncPeriodSwitchSupported() const149 bool Display::isVsyncPeriodSwitchSupported() const {
150     ALOGV("[%" PRIu64 "] isVsyncPeriodSwitchSupported()", mId);
151 
152     return mComposer.isSupported(android::Hwc2::Composer::OptionalFeature::RefreshRateSwitching);
153 }
154 
hasDisplayIdleTimerCapability() const155 bool Display::hasDisplayIdleTimerCapability() const {
156     bool isCapabilitySupported = false;
157     return mComposer.hasDisplayIdleTimerCapability(mId, &isCapabilitySupported) == Error::NONE &&
158             isCapabilitySupported;
159 }
160 
getPhysicalDisplayOrientation(Hwc2::AidlTransform * outTransform) const161 Error Display::getPhysicalDisplayOrientation(Hwc2::AidlTransform* outTransform) const {
162     auto error = mComposer.getPhysicalDisplayOrientation(mId, outTransform);
163     return static_cast<Error>(error);
164 }
165 
getChangedCompositionTypes(std::unordered_map<HWC2::Layer *,Composition> * outTypes)166 Error Display::getChangedCompositionTypes(std::unordered_map<HWC2::Layer*, Composition>* outTypes) {
167     std::vector<Hwc2::Layer> layerIds;
168     std::vector<Composition> types;
169     auto intError = mComposer.getChangedCompositionTypes(
170             mId, &layerIds, &types);
171     uint32_t numElements = layerIds.size();
172     const auto error = static_cast<Error>(intError);
173     if (error != Error::NONE) {
174         return error;
175     }
176 
177     outTypes->clear();
178     outTypes->reserve(numElements);
179     for (uint32_t element = 0; element < numElements; ++element) {
180         auto layer = getLayerById(layerIds[element]);
181         if (layer) {
182             auto type = types[element];
183             ALOGV("getChangedCompositionTypes: adding %" PRIu64 " %s",
184                     layer->getId(), to_string(type).c_str());
185             outTypes->emplace(layer.get(), type);
186         } else {
187             ALOGE("getChangedCompositionTypes: invalid layer %" PRIu64 " found"
188                     " on display %" PRIu64, layerIds[element], mId);
189         }
190     }
191 
192     return Error::NONE;
193 }
194 
getColorModes(std::vector<ColorMode> * outModes) const195 Error Display::getColorModes(std::vector<ColorMode>* outModes) const
196 {
197     auto intError = mComposer.getColorModes(mId, outModes);
198     return static_cast<Error>(intError);
199 }
200 
getSupportedPerFrameMetadata() const201 int32_t Display::getSupportedPerFrameMetadata() const
202 {
203     int32_t supportedPerFrameMetadata = 0;
204 
205     std::vector<Hwc2::PerFrameMetadataKey> tmpKeys = mComposer.getPerFrameMetadataKeys(mId);
206     std::set<Hwc2::PerFrameMetadataKey> keys(tmpKeys.begin(), tmpKeys.end());
207 
208     // Check whether a specific metadata type is supported. A metadata type is considered
209     // supported if and only if all required fields are supported.
210 
211     // SMPTE2086
212     if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X) &&
213         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y) &&
214         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X) &&
215         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y) &&
216         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X) &&
217         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y) &&
218         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::WHITE_POINT_X) &&
219         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::WHITE_POINT_Y) &&
220         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_LUMINANCE) &&
221         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MIN_LUMINANCE)) {
222         supportedPerFrameMetadata |= HdrMetadata::Type::SMPTE2086;
223     }
224     // CTA861_3
225     if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL) &&
226         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL)) {
227         supportedPerFrameMetadata |= HdrMetadata::Type::CTA861_3;
228     }
229 
230     // HDR10PLUS
231     if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::HDR10_PLUS_SEI)) {
232         supportedPerFrameMetadata |= HdrMetadata::Type::HDR10PLUS;
233     }
234 
235     return supportedPerFrameMetadata;
236 }
237 
getRenderIntents(ColorMode colorMode,std::vector<RenderIntent> * outRenderIntents) const238 Error Display::getRenderIntents(ColorMode colorMode,
239         std::vector<RenderIntent>* outRenderIntents) const
240 {
241     auto intError = mComposer.getRenderIntents(mId, colorMode, outRenderIntents);
242     return static_cast<Error>(intError);
243 }
244 
getDataspaceSaturationMatrix(Dataspace dataspace,android::mat4 * outMatrix)245 Error Display::getDataspaceSaturationMatrix(Dataspace dataspace, android::mat4* outMatrix)
246 {
247     auto intError = mComposer.getDataspaceSaturationMatrix(dataspace, outMatrix);
248     return static_cast<Error>(intError);
249 }
250 
getName(std::string * outName) const251 Error Display::getName(std::string* outName) const
252 {
253     auto intError = mComposer.getDisplayName(mId, outName);
254     return static_cast<Error>(intError);
255 }
256 
getRequests(HWC2::DisplayRequest * outDisplayRequests,std::unordered_map<HWC2::Layer *,LayerRequest> * outLayerRequests)257 Error Display::getRequests(HWC2::DisplayRequest* outDisplayRequests,
258                            std::unordered_map<HWC2::Layer*, LayerRequest>* outLayerRequests) {
259     uint32_t intDisplayRequests = 0;
260     std::vector<Hwc2::Layer> layerIds;
261     std::vector<uint32_t> layerRequests;
262     auto intError = mComposer.getDisplayRequests(
263             mId, &intDisplayRequests, &layerIds, &layerRequests);
264     uint32_t numElements = layerIds.size();
265     auto error = static_cast<Error>(intError);
266     if (error != Error::NONE) {
267         return error;
268     }
269 
270     *outDisplayRequests = static_cast<DisplayRequest>(intDisplayRequests);
271     outLayerRequests->clear();
272     outLayerRequests->reserve(numElements);
273     for (uint32_t element = 0; element < numElements; ++element) {
274         auto layer = getLayerById(layerIds[element]);
275         if (layer) {
276             auto layerRequest =
277                     static_cast<LayerRequest>(layerRequests[element]);
278             outLayerRequests->emplace(layer.get(), layerRequest);
279         } else {
280             ALOGE("getRequests: invalid layer %" PRIu64 " found on display %"
281                     PRIu64, layerIds[element], mId);
282         }
283     }
284 
285     return Error::NONE;
286 }
287 
getConnectionType() const288 ftl::Expected<ui::DisplayConnectionType, hal::Error> Display::getConnectionType() const {
289     if (!mConnectionType) {
290         mConnectionType = [this]() -> decltype(mConnectionType) {
291             if (mType != DisplayType::PHYSICAL) {
292                 return ftl::Unexpected(Error::BAD_DISPLAY);
293             }
294 
295             using ConnectionType = Hwc2::IComposerClient::DisplayConnectionType;
296             ConnectionType connectionType;
297 
298             if (const auto error = static_cast<Error>(
299                         mComposer.getDisplayConnectionType(mId, &connectionType));
300                 error != Error::NONE) {
301                 return ftl::Unexpected(error);
302             }
303 
304             return connectionType == ConnectionType::INTERNAL ? ui::DisplayConnectionType::Internal
305                                                               : ui::DisplayConnectionType::External;
306         }();
307     }
308 
309     return *mConnectionType;
310 }
311 
hasCapability(DisplayCapability capability) const312 bool Display::hasCapability(DisplayCapability capability) const {
313     std::scoped_lock lock(mDisplayCapabilitiesMutex);
314     if (mDisplayCapabilities) {
315         return mDisplayCapabilities->count(capability) > 0;
316     }
317 
318     ALOGW("Can't query capability %s."
319           " Display Capabilities were not queried from HWC yet",
320           to_string(capability).c_str());
321 
322     return false;
323 }
324 
supportsDoze(bool * outSupport) const325 Error Display::supportsDoze(bool* outSupport) const {
326     {
327         std::scoped_lock lock(mDisplayCapabilitiesMutex);
328         if (!mDisplayCapabilities) {
329             // The display has not turned on since boot, so DOZE support is unknown.
330             ALOGW("%s: haven't queried capabilities yet!", __func__);
331             return Error::NO_RESOURCES;
332         }
333     }
334     *outSupport = hasCapability(DisplayCapability::DOZE);
335     return Error::NONE;
336 }
337 
getHdrCapabilities(HdrCapabilities * outCapabilities) const338 Error Display::getHdrCapabilities(HdrCapabilities* outCapabilities) const
339 {
340     float maxLuminance = -1.0f;
341     float maxAverageLuminance = -1.0f;
342     float minLuminance = -1.0f;
343     std::vector<Hwc2::Hdr> hdrTypes;
344     auto intError = mComposer.getHdrCapabilities(mId, &hdrTypes, &maxLuminance,
345                                                  &maxAverageLuminance, &minLuminance);
346     auto error = static_cast<HWC2::Error>(intError);
347 
348     if (error != Error::NONE) {
349         return error;
350     }
351 
352     *outCapabilities =
353             HdrCapabilities(std::move(hdrTypes), maxLuminance, maxAverageLuminance, minLuminance);
354     return Error::NONE;
355 }
356 
getOverlaySupport(OverlayProperties * outProperties) const357 Error Display::getOverlaySupport(OverlayProperties* outProperties) const {
358     auto intError = mComposer.getOverlaySupport(outProperties);
359     return static_cast<Error>(intError);
360 }
361 
getDisplayedContentSamplingAttributes(hal::PixelFormat * outFormat,Dataspace * outDataspace,uint8_t * outComponentMask) const362 Error Display::getDisplayedContentSamplingAttributes(hal::PixelFormat* outFormat,
363                                                      Dataspace* outDataspace,
364                                                      uint8_t* outComponentMask) const {
365     auto intError = mComposer.getDisplayedContentSamplingAttributes(mId, outFormat, outDataspace,
366                                                                     outComponentMask);
367     return static_cast<Error>(intError);
368 }
369 
setDisplayContentSamplingEnabled(bool enabled,uint8_t componentMask,uint64_t maxFrames) const370 Error Display::setDisplayContentSamplingEnabled(bool enabled, uint8_t componentMask,
371                                                 uint64_t maxFrames) const {
372     auto intError =
373             mComposer.setDisplayContentSamplingEnabled(mId, enabled, componentMask, maxFrames);
374     return static_cast<Error>(intError);
375 }
376 
getDisplayedContentSample(uint64_t maxFrames,uint64_t timestamp,android::DisplayedFrameStats * outStats) const377 Error Display::getDisplayedContentSample(uint64_t maxFrames, uint64_t timestamp,
378                                          android::DisplayedFrameStats* outStats) const {
379     auto intError = mComposer.getDisplayedContentSample(mId, maxFrames, timestamp, outStats);
380     return static_cast<Error>(intError);
381 }
382 
getReleaseFences(std::unordered_map<HWC2::Layer *,sp<Fence>> * outFences) const383 Error Display::getReleaseFences(std::unordered_map<HWC2::Layer*, sp<Fence>>* outFences) const {
384     std::vector<Hwc2::Layer> layerIds;
385     std::vector<int> fenceFds;
386     auto intError = mComposer.getReleaseFences(mId, &layerIds, &fenceFds);
387     auto error = static_cast<Error>(intError);
388     uint32_t numElements = layerIds.size();
389     if (error != Error::NONE) {
390         return error;
391     }
392 
393     std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
394     releaseFences.reserve(numElements);
395     for (uint32_t element = 0; element < numElements; ++element) {
396         auto layer = getLayerById(layerIds[element]);
397         if (layer) {
398             sp<Fence> fence(sp<Fence>::make(fenceFds[element]));
399             releaseFences.emplace(layer.get(), fence);
400         } else {
401             ALOGE("getReleaseFences: invalid layer %" PRIu64
402                     " found on display %" PRIu64, layerIds[element], mId);
403             for (; element < numElements; ++element) {
404                 close(fenceFds[element]);
405             }
406             return Error::BAD_LAYER;
407         }
408     }
409 
410     *outFences = std::move(releaseFences);
411     return Error::NONE;
412 }
413 
present(sp<Fence> * outPresentFence)414 Error Display::present(sp<Fence>* outPresentFence)
415 {
416     int32_t presentFenceFd = -1;
417     auto intError = mComposer.presentDisplay(mId, &presentFenceFd);
418     auto error = static_cast<Error>(intError);
419     if (error != Error::NONE) {
420         return error;
421     }
422 
423     *outPresentFence = sp<Fence>::make(presentFenceFd);
424     return Error::NONE;
425 }
426 
setActiveConfigWithConstraints(hal::HWConfigId configId,const VsyncPeriodChangeConstraints & constraints,VsyncPeriodChangeTimeline * outTimeline)427 Error Display::setActiveConfigWithConstraints(hal::HWConfigId configId,
428                                               const VsyncPeriodChangeConstraints& constraints,
429                                               VsyncPeriodChangeTimeline* outTimeline) {
430     ALOGV("[%" PRIu64 "] setActiveConfigWithConstraints", mId);
431 
432     // FIXME (b/319505580): At least the first config set on an external display must be
433     // `setActiveConfig`, so skip over the block that calls `setActiveConfigWithConstraints`
434     // for simplicity.
435     const bool connected_display = FlagManager::getInstance().connected_display();
436 
437     if (isVsyncPeriodSwitchSupported() &&
438         (!connected_display ||
439          getConnectionType().value_opt() != ui::DisplayConnectionType::External)) {
440         Hwc2::IComposerClient::VsyncPeriodChangeConstraints hwc2Constraints;
441         hwc2Constraints.desiredTimeNanos = constraints.desiredTimeNanos;
442         hwc2Constraints.seamlessRequired = constraints.seamlessRequired;
443 
444         Hwc2::VsyncPeriodChangeTimeline vsyncPeriodChangeTimeline = {};
445         auto intError = mComposer.setActiveConfigWithConstraints(mId, configId, hwc2Constraints,
446                                                                  &vsyncPeriodChangeTimeline);
447         outTimeline->newVsyncAppliedTimeNanos = vsyncPeriodChangeTimeline.newVsyncAppliedTimeNanos;
448         outTimeline->refreshRequired = vsyncPeriodChangeTimeline.refreshRequired;
449         outTimeline->refreshTimeNanos = vsyncPeriodChangeTimeline.refreshTimeNanos;
450         return static_cast<Error>(intError);
451     }
452 
453     // Use legacy setActiveConfig instead
454     ALOGV("fallback to legacy setActiveConfig");
455     const auto now = systemTime();
456     if (constraints.desiredTimeNanos > now || constraints.seamlessRequired) {
457         ALOGE("setActiveConfigWithConstraints received constraints that can't be satisfied");
458     }
459 
460     auto intError_2_4 = mComposer.setActiveConfig(mId, configId);
461     outTimeline->newVsyncAppliedTimeNanos = std::max(now, constraints.desiredTimeNanos);
462     outTimeline->refreshRequired = true;
463     outTimeline->refreshTimeNanos = now;
464     return static_cast<Error>(intError_2_4);
465 }
466 
setClientTarget(uint32_t slot,const sp<GraphicBuffer> & target,const sp<Fence> & acquireFence,Dataspace dataspace,float hdrSdrRatio)467 Error Display::setClientTarget(uint32_t slot, const sp<GraphicBuffer>& target,
468                                const sp<Fence>& acquireFence, Dataspace dataspace,
469                                float hdrSdrRatio) {
470     // TODO: Properly encode client target surface damage
471     int32_t fenceFd = acquireFence->dup();
472     auto intError =
473             mComposer.setClientTarget(mId, slot, target, fenceFd, dataspace,
474                                       std::vector<Hwc2::IComposerClient::Rect>(), hdrSdrRatio);
475     return static_cast<Error>(intError);
476 }
477 
setColorMode(ColorMode mode,RenderIntent renderIntent)478 Error Display::setColorMode(ColorMode mode, RenderIntent renderIntent)
479 {
480     auto intError = mComposer.setColorMode(mId, mode, renderIntent);
481     return static_cast<Error>(intError);
482 }
483 
setColorTransform(const android::mat4 & matrix)484 Error Display::setColorTransform(const android::mat4& matrix) {
485     auto intError = mComposer.setColorTransform(mId, matrix.asArray());
486     return static_cast<Error>(intError);
487 }
488 
setOutputBuffer(const sp<GraphicBuffer> & buffer,const sp<Fence> & releaseFence)489 Error Display::setOutputBuffer(const sp<GraphicBuffer>& buffer,
490         const sp<Fence>& releaseFence)
491 {
492     int32_t fenceFd = releaseFence->dup();
493     auto handle = buffer->getNativeBuffer()->handle;
494     auto intError = mComposer.setOutputBuffer(mId, handle, fenceFd);
495     close(fenceFd);
496     return static_cast<Error>(intError);
497 }
498 
setPowerMode(PowerMode mode)499 Error Display::setPowerMode(PowerMode mode)
500 {
501     auto intMode = static_cast<Hwc2::IComposerClient::PowerMode>(mode);
502     auto intError = mComposer.setPowerMode(mId, intMode);
503 
504     if (mode == PowerMode::ON) {
505         loadDisplayCapabilities();
506     }
507 
508     return static_cast<Error>(intError);
509 }
510 
setVsyncEnabled(Vsync enabled)511 Error Display::setVsyncEnabled(Vsync enabled)
512 {
513     auto intEnabled = static_cast<Hwc2::IComposerClient::Vsync>(enabled);
514     auto intError = mComposer.setVsyncEnabled(mId, intEnabled);
515     return static_cast<Error>(intError);
516 }
517 
validate(nsecs_t expectedPresentTime,int32_t frameIntervalNs,uint32_t * outNumTypes,uint32_t * outNumRequests)518 Error Display::validate(nsecs_t expectedPresentTime, int32_t frameIntervalNs, uint32_t* outNumTypes,
519                         uint32_t* outNumRequests) {
520     uint32_t numTypes = 0;
521     uint32_t numRequests = 0;
522     auto intError = mComposer.validateDisplay(mId, expectedPresentTime, frameIntervalNs, &numTypes,
523                                               &numRequests);
524     auto error = static_cast<Error>(intError);
525     if (error != Error::NONE && !hasChangesError(error)) {
526         return error;
527     }
528 
529     *outNumTypes = numTypes;
530     *outNumRequests = numRequests;
531     return error;
532 }
533 
presentOrValidate(nsecs_t expectedPresentTime,int32_t frameIntervalNs,uint32_t * outNumTypes,uint32_t * outNumRequests,sp<android::Fence> * outPresentFence,uint32_t * state)534 Error Display::presentOrValidate(nsecs_t expectedPresentTime, int32_t frameIntervalNs,
535                                  uint32_t* outNumTypes, uint32_t* outNumRequests,
536                                  sp<android::Fence>* outPresentFence, uint32_t* state) {
537     uint32_t numTypes = 0;
538     uint32_t numRequests = 0;
539     int32_t presentFenceFd = -1;
540     auto intError =
541             mComposer.presentOrValidateDisplay(mId, expectedPresentTime, frameIntervalNs, &numTypes,
542                                                &numRequests, &presentFenceFd, state);
543     auto error = static_cast<Error>(intError);
544     if (error != Error::NONE && !hasChangesError(error)) {
545         return error;
546     }
547 
548     if (*state == 1) {
549         *outPresentFence = sp<Fence>::make(presentFenceFd);
550     }
551 
552     if (*state == 0) {
553         *outNumTypes = numTypes;
554         *outNumRequests = numRequests;
555     }
556     return error;
557 }
558 
setDisplayBrightness(float brightness,float brightnessNits,const Hwc2::Composer::DisplayBrightnessOptions & options)559 ftl::Future<Error> Display::setDisplayBrightness(
560         float brightness, float brightnessNits,
561         const Hwc2::Composer::DisplayBrightnessOptions& options) {
562     return ftl::defer([composer = &mComposer, id = mId, brightness, brightnessNits, options] {
563         const auto intError =
564                 composer->setDisplayBrightness(id, brightness, brightnessNits, options);
565         return static_cast<Error>(intError);
566     });
567 }
568 
setBootDisplayConfig(hal::HWConfigId configId)569 Error Display::setBootDisplayConfig(hal::HWConfigId configId) {
570     auto intError = mComposer.setBootDisplayConfig(mId, configId);
571     return static_cast<Error>(intError);
572 }
573 
clearBootDisplayConfig()574 Error Display::clearBootDisplayConfig() {
575     auto intError = mComposer.clearBootDisplayConfig(mId);
576     return static_cast<Error>(intError);
577 }
578 
getPreferredBootDisplayConfig(hal::HWConfigId * configId) const579 Error Display::getPreferredBootDisplayConfig(hal::HWConfigId* configId) const {
580     auto intError = mComposer.getPreferredBootDisplayConfig(mId, configId);
581     return static_cast<Error>(intError);
582 }
583 
setAutoLowLatencyMode(bool on)584 Error Display::setAutoLowLatencyMode(bool on) {
585     auto intError = mComposer.setAutoLowLatencyMode(mId, on);
586     return static_cast<Error>(intError);
587 }
588 
getSupportedContentTypes(std::vector<ContentType> * outSupportedContentTypes) const589 Error Display::getSupportedContentTypes(std::vector<ContentType>* outSupportedContentTypes) const {
590     std::vector<Hwc2::IComposerClient::ContentType> tmpSupportedContentTypes;
591     auto intError = mComposer.getSupportedContentTypes(mId, &tmpSupportedContentTypes);
592     for (Hwc2::IComposerClient::ContentType contentType : tmpSupportedContentTypes) {
593         outSupportedContentTypes->push_back(static_cast<ContentType>(contentType));
594     }
595     return static_cast<Error>(intError);
596 }
597 
setContentType(ContentType contentType)598 Error Display::setContentType(ContentType contentType) {
599     auto intError = mComposer.setContentType(mId, contentType);
600     return static_cast<Error>(intError);
601 }
602 
getClientTargetProperty(aidl::android::hardware::graphics::composer3::ClientTargetPropertyWithBrightness * outClientTargetProperty)603 Error Display::getClientTargetProperty(
604         aidl::android::hardware::graphics::composer3::ClientTargetPropertyWithBrightness*
605                 outClientTargetProperty) {
606     const auto error = mComposer.getClientTargetProperty(mId, outClientTargetProperty);
607     return static_cast<Error>(error);
608 }
609 
getDisplayDecorationSupport(std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> * support)610 Error Display::getDisplayDecorationSupport(
611         std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport>*
612                 support) {
613     const auto error = mComposer.getDisplayDecorationSupport(mId, support);
614     return static_cast<Error>(error);
615 }
616 
setIdleTimerEnabled(std::chrono::milliseconds timeout)617 Error Display::setIdleTimerEnabled(std::chrono::milliseconds timeout) {
618     const auto error = mComposer.setIdleTimerEnabled(mId, timeout);
619     return static_cast<Error>(error);
620 }
621 
622 // For use by Device
623 
setConnected(bool connected)624 void Display::setConnected(bool connected) {
625     if (!mIsConnected && connected) {
626         mComposer.setClientTargetSlotCount(mId);
627     }
628     mIsConnected = connected;
629 }
630 
631 // Other Display methods
632 
getLayerById(HWLayerId id) const633 std::shared_ptr<HWC2::Layer> Display::getLayerById(HWLayerId id) const {
634     auto it = mLayers.find(id);
635     return it != mLayers.end() ? it->second.lock() : nullptr;
636 }
637 
loadDisplayCapabilities()638 void Display::loadDisplayCapabilities() {
639     std::call_once(mDisplayCapabilityQueryFlag, [this]() {
640         std::vector<DisplayCapability> tmpCapabilities;
641         auto error =
642                 static_cast<Error>(mComposer.getDisplayCapabilities(mId, &tmpCapabilities));
643         if (error == Error::NONE) {
644             std::scoped_lock lock(mDisplayCapabilitiesMutex);
645             mDisplayCapabilities.emplace();
646             for (auto capability : tmpCapabilities) {
647                 mDisplayCapabilities->emplace(capability);
648             }
649         } else if (error == Error::UNSUPPORTED) {
650             std::scoped_lock lock(mDisplayCapabilitiesMutex);
651             mDisplayCapabilities.emplace();
652             if (mCapabilities.count(AidlCapability::SKIP_CLIENT_COLOR_TRANSFORM)) {
653                 mDisplayCapabilities->emplace(DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM);
654             }
655             bool dozeSupport = false;
656             error = static_cast<Error>(mComposer.getDozeSupport(mId, &dozeSupport));
657             if (error == Error::NONE && dozeSupport) {
658                 mDisplayCapabilities->emplace(DisplayCapability::DOZE);
659             }
660         }
661     });
662 }
663 } // namespace impl
664 
665 // Layer methods
666 
667 namespace {
convertRegionToHwcRects(const Region & region)668 std::vector<Hwc2::IComposerClient::Rect> convertRegionToHwcRects(const Region& region) {
669     size_t rectCount = 0;
670     Rect const* rectArray = region.getArray(&rectCount);
671 
672     std::vector<Hwc2::IComposerClient::Rect> hwcRects;
673     hwcRects.reserve(rectCount);
674     for (size_t rect = 0; rect < rectCount; ++rect) {
675         hwcRects.push_back({rectArray[rect].left, rectArray[rect].top, rectArray[rect].right,
676                             rectArray[rect].bottom});
677     }
678     return hwcRects;
679 }
680 } // namespace
681 
682 Layer::~Layer() = default;
683 
684 namespace impl {
685 
Layer(android::Hwc2::Composer & composer,const std::unordered_set<AidlCapability> & capabilities,HWC2::Display & display,HWLayerId layerId)686 Layer::Layer(android::Hwc2::Composer& composer,
687              const std::unordered_set<AidlCapability>& capabilities, HWC2::Display& display,
688              HWLayerId layerId)
689       : mComposer(composer),
690         mCapabilities(capabilities),
691         mDisplay(&display),
692         mId(layerId),
693         mColorMatrix(android::mat4()) {
694     ALOGV("Created layer %" PRIu64 " on display %" PRIu64, layerId, display.getId());
695 }
696 
~Layer()697 Layer::~Layer()
698 {
699     onOwningDisplayDestroyed();
700 }
701 
onOwningDisplayDestroyed()702 void Layer::onOwningDisplayDestroyed() {
703     // Note: onOwningDisplayDestroyed() may be called to perform cleanup by
704     // either the Layer dtor or by the Display dtor and must be safe to call
705     // from either path. In particular, the call to Display::onLayerDestroyed()
706     // is expected to be safe to do,
707 
708     if (CC_UNLIKELY(!mDisplay)) {
709         return;
710     }
711 
712     mDisplay->onLayerDestroyed(mId);
713 
714     // Note: If the HWC display was actually disconnected, these calls are will
715     // return an error. We always make them as there may be other reasons for
716     // the HWC2::Display to be destroyed.
717     auto intError = mComposer.destroyLayer(mDisplay->getId(), mId);
718     auto error = static_cast<Error>(intError);
719     ALOGE_IF(error != Error::NONE,
720              "destroyLayer(%" PRIu64 ", %" PRIu64 ")"
721              " failed: %s (%d)",
722              mDisplay->getId(), mId, to_string(error).c_str(), intError);
723 
724     mDisplay = nullptr;
725 }
726 
setCursorPosition(int32_t x,int32_t y)727 Error Layer::setCursorPosition(int32_t x, int32_t y)
728 {
729     if (CC_UNLIKELY(!mDisplay)) {
730         return Error::BAD_DISPLAY;
731     }
732 
733     auto intError = mComposer.setCursorPosition(mDisplay->getId(), mId, x, y);
734     return static_cast<Error>(intError);
735 }
736 
setBuffer(uint32_t slot,const sp<GraphicBuffer> & buffer,const sp<Fence> & acquireFence)737 Error Layer::setBuffer(uint32_t slot, const sp<GraphicBuffer>& buffer,
738         const sp<Fence>& acquireFence)
739 {
740     if (CC_UNLIKELY(!mDisplay)) {
741         return Error::BAD_DISPLAY;
742     }
743 
744     if (buffer == nullptr && mBufferSlot == slot) {
745         return Error::NONE;
746     }
747     mBufferSlot = slot;
748 
749     int32_t fenceFd = acquireFence->dup();
750     auto intError = mComposer.setLayerBuffer(mDisplay->getId(), mId, slot, buffer, fenceFd);
751     return static_cast<Error>(intError);
752 }
753 
setBufferSlotsToClear(const std::vector<uint32_t> & slotsToClear,uint32_t activeBufferSlot)754 Error Layer::setBufferSlotsToClear(const std::vector<uint32_t>& slotsToClear,
755                                    uint32_t activeBufferSlot) {
756     if (CC_UNLIKELY(!mDisplay)) {
757         return Error::BAD_DISPLAY;
758     }
759     auto intError = mComposer.setLayerBufferSlotsToClear(mDisplay->getId(), mId, slotsToClear,
760                                                          activeBufferSlot);
761     return static_cast<Error>(intError);
762 }
763 
setSurfaceDamage(const Region & damage)764 Error Layer::setSurfaceDamage(const Region& damage)
765 {
766     if (CC_UNLIKELY(!mDisplay)) {
767         return Error::BAD_DISPLAY;
768     }
769 
770     if (damage.isRect() && mDamageRegion.isRect() &&
771         (damage.getBounds() == mDamageRegion.getBounds())) {
772         return Error::NONE;
773     }
774     mDamageRegion = damage;
775 
776     // We encode default full-screen damage as INVALID_RECT upstream, but as 0
777     // rects for HWC
778     Hwc2::Error intError = Hwc2::Error::NONE;
779     if (damage.isRect() && damage.getBounds() == Rect::INVALID_RECT) {
780         intError = mComposer.setLayerSurfaceDamage(mDisplay->getId(), mId,
781                                                    std::vector<Hwc2::IComposerClient::Rect>());
782     } else {
783         const auto hwcRects = convertRegionToHwcRects(damage);
784         intError = mComposer.setLayerSurfaceDamage(mDisplay->getId(), mId, hwcRects);
785     }
786 
787     return static_cast<Error>(intError);
788 }
789 
setBlendMode(BlendMode mode)790 Error Layer::setBlendMode(BlendMode mode)
791 {
792     if (CC_UNLIKELY(!mDisplay)) {
793         return Error::BAD_DISPLAY;
794     }
795 
796     auto intError = mComposer.setLayerBlendMode(mDisplay->getId(), mId, mode);
797     return static_cast<Error>(intError);
798 }
799 
setColor(Color color)800 Error Layer::setColor(Color color) {
801     if (CC_UNLIKELY(!mDisplay)) {
802         return Error::BAD_DISPLAY;
803     }
804 
805     auto intError = mComposer.setLayerColor(mDisplay->getId(), mId, color);
806     return static_cast<Error>(intError);
807 }
808 
setCompositionType(Composition type)809 Error Layer::setCompositionType(Composition type)
810 {
811     if (CC_UNLIKELY(!mDisplay)) {
812         return Error::BAD_DISPLAY;
813     }
814 
815     auto intError = mComposer.setLayerCompositionType(mDisplay->getId(), mId, type);
816     return static_cast<Error>(intError);
817 }
818 
setDataspace(Dataspace dataspace)819 Error Layer::setDataspace(Dataspace dataspace)
820 {
821     if (CC_UNLIKELY(!mDisplay)) {
822         return Error::BAD_DISPLAY;
823     }
824 
825     if (dataspace == mDataSpace) {
826         return Error::NONE;
827     }
828     mDataSpace = dataspace;
829     auto intError = mComposer.setLayerDataspace(mDisplay->getId(), mId, mDataSpace);
830     return static_cast<Error>(intError);
831 }
832 
setPerFrameMetadata(const int32_t supportedPerFrameMetadata,const android::HdrMetadata & metadata)833 Error Layer::setPerFrameMetadata(const int32_t supportedPerFrameMetadata,
834         const android::HdrMetadata& metadata)
835 {
836     if (CC_UNLIKELY(!mDisplay)) {
837         return Error::BAD_DISPLAY;
838     }
839 
840     if (metadata == mHdrMetadata) {
841         return Error::NONE;
842     }
843 
844     mHdrMetadata = metadata;
845     int validTypes = mHdrMetadata.validTypes & supportedPerFrameMetadata;
846     std::vector<Hwc2::PerFrameMetadata> perFrameMetadatas;
847     if (validTypes & HdrMetadata::SMPTE2086) {
848         perFrameMetadatas.insert(perFrameMetadatas.end(),
849                                  {{Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X,
850                                    mHdrMetadata.smpte2086.displayPrimaryRed.x},
851                                   {Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y,
852                                    mHdrMetadata.smpte2086.displayPrimaryRed.y},
853                                   {Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X,
854                                    mHdrMetadata.smpte2086.displayPrimaryGreen.x},
855                                   {Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y,
856                                    mHdrMetadata.smpte2086.displayPrimaryGreen.y},
857                                   {Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X,
858                                    mHdrMetadata.smpte2086.displayPrimaryBlue.x},
859                                   {Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y,
860                                    mHdrMetadata.smpte2086.displayPrimaryBlue.y},
861                                   {Hwc2::PerFrameMetadataKey::WHITE_POINT_X,
862                                    mHdrMetadata.smpte2086.whitePoint.x},
863                                   {Hwc2::PerFrameMetadataKey::WHITE_POINT_Y,
864                                    mHdrMetadata.smpte2086.whitePoint.y},
865                                   {Hwc2::PerFrameMetadataKey::MAX_LUMINANCE,
866                                    mHdrMetadata.smpte2086.maxLuminance},
867                                   {Hwc2::PerFrameMetadataKey::MIN_LUMINANCE,
868                                    mHdrMetadata.smpte2086.minLuminance}});
869     }
870 
871     if (validTypes & HdrMetadata::CTA861_3) {
872         perFrameMetadatas.insert(perFrameMetadatas.end(),
873                                  {{Hwc2::PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL,
874                                    mHdrMetadata.cta8613.maxContentLightLevel},
875                                   {Hwc2::PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL,
876                                    mHdrMetadata.cta8613.maxFrameAverageLightLevel}});
877     }
878 
879     const Error error = static_cast<Error>(
880         mComposer.setLayerPerFrameMetadata(mDisplay->getId(), mId, perFrameMetadatas));
881     if (error != Error::NONE) {
882         return error;
883     }
884 
885     std::vector<Hwc2::PerFrameMetadataBlob> perFrameMetadataBlobs;
886     if (validTypes & HdrMetadata::HDR10PLUS) {
887         if (CC_UNLIKELY(mHdrMetadata.hdr10plus.size() == 0)) {
888             return Error::BAD_PARAMETER;
889         }
890 
891         perFrameMetadataBlobs.push_back(
892                 {Hwc2::PerFrameMetadataKey::HDR10_PLUS_SEI, mHdrMetadata.hdr10plus});
893     }
894 
895     return static_cast<Error>(
896             mComposer.setLayerPerFrameMetadataBlobs(mDisplay->getId(), mId, perFrameMetadataBlobs));
897 }
898 
setDisplayFrame(const Rect & frame)899 Error Layer::setDisplayFrame(const Rect& frame)
900 {
901     if (CC_UNLIKELY(!mDisplay)) {
902         return Error::BAD_DISPLAY;
903     }
904 
905     Hwc2::IComposerClient::Rect hwcRect{frame.left, frame.top,
906         frame.right, frame.bottom};
907     auto intError = mComposer.setLayerDisplayFrame(mDisplay->getId(), mId, hwcRect);
908     return static_cast<Error>(intError);
909 }
910 
setPlaneAlpha(float alpha)911 Error Layer::setPlaneAlpha(float alpha)
912 {
913     if (CC_UNLIKELY(!mDisplay)) {
914         return Error::BAD_DISPLAY;
915     }
916 
917     auto intError = mComposer.setLayerPlaneAlpha(mDisplay->getId(), mId, alpha);
918     return static_cast<Error>(intError);
919 }
920 
setSidebandStream(const native_handle_t * stream)921 Error Layer::setSidebandStream(const native_handle_t* stream)
922 {
923     if (CC_UNLIKELY(!mDisplay)) {
924         return Error::BAD_DISPLAY;
925     }
926 
927     if (mCapabilities.count(AidlCapability::SIDEBAND_STREAM) == 0) {
928         ALOGE("Attempted to call setSidebandStream without checking that the "
929                 "device supports sideband streams");
930         return Error::UNSUPPORTED;
931     }
932     auto intError = mComposer.setLayerSidebandStream(mDisplay->getId(), mId, stream);
933     return static_cast<Error>(intError);
934 }
935 
setSourceCrop(const FloatRect & crop)936 Error Layer::setSourceCrop(const FloatRect& crop)
937 {
938     if (CC_UNLIKELY(!mDisplay)) {
939         return Error::BAD_DISPLAY;
940     }
941 
942     Hwc2::IComposerClient::FRect hwcRect{
943         crop.left, crop.top, crop.right, crop.bottom};
944     auto intError = mComposer.setLayerSourceCrop(mDisplay->getId(), mId, hwcRect);
945     return static_cast<Error>(intError);
946 }
947 
setTransform(Transform transform)948 Error Layer::setTransform(Transform transform)
949 {
950     if (CC_UNLIKELY(!mDisplay)) {
951         return Error::BAD_DISPLAY;
952     }
953 
954     auto intTransform = static_cast<Hwc2::Transform>(transform);
955     auto intError = mComposer.setLayerTransform(mDisplay->getId(), mId, intTransform);
956     return static_cast<Error>(intError);
957 }
958 
setVisibleRegion(const Region & region)959 Error Layer::setVisibleRegion(const Region& region)
960 {
961     if (CC_UNLIKELY(!mDisplay)) {
962         return Error::BAD_DISPLAY;
963     }
964 
965     if (region.isRect() && mVisibleRegion.isRect() &&
966         (region.getBounds() == mVisibleRegion.getBounds())) {
967         return Error::NONE;
968     }
969     mVisibleRegion = region;
970     const auto hwcRects = convertRegionToHwcRects(region);
971     auto intError = mComposer.setLayerVisibleRegion(mDisplay->getId(), mId, hwcRects);
972     return static_cast<Error>(intError);
973 }
974 
setZOrder(uint32_t z)975 Error Layer::setZOrder(uint32_t z)
976 {
977     if (CC_UNLIKELY(!mDisplay)) {
978         return Error::BAD_DISPLAY;
979     }
980 
981     auto intError = mComposer.setLayerZOrder(mDisplay->getId(), mId, z);
982     return static_cast<Error>(intError);
983 }
984 
985 // Composer HAL 2.3
setColorTransform(const android::mat4 & matrix)986 Error Layer::setColorTransform(const android::mat4& matrix) {
987     if (CC_UNLIKELY(!mDisplay)) {
988         return Error::BAD_DISPLAY;
989     }
990 
991     if (matrix == mColorMatrix) {
992         return Error::NONE;
993     }
994     auto intError = mComposer.setLayerColorTransform(mDisplay->getId(), mId, matrix.asArray());
995     Error error = static_cast<Error>(intError);
996     if (error != Error::NONE) {
997         return error;
998     }
999     mColorMatrix = matrix;
1000     return error;
1001 }
1002 
1003 // Composer HAL 2.4
setLayerGenericMetadata(const std::string & name,bool mandatory,const std::vector<uint8_t> & value)1004 Error Layer::setLayerGenericMetadata(const std::string& name, bool mandatory,
1005                                      const std::vector<uint8_t>& value) {
1006     if (CC_UNLIKELY(!mDisplay)) {
1007         return Error::BAD_DISPLAY;
1008     }
1009 
1010     auto intError =
1011             mComposer.setLayerGenericMetadata(mDisplay->getId(), mId, name, mandatory, value);
1012     return static_cast<Error>(intError);
1013 }
1014 
1015 // AIDL HAL
setBrightness(float brightness)1016 Error Layer::setBrightness(float brightness) {
1017     if (CC_UNLIKELY(!mDisplay)) {
1018         return Error::BAD_DISPLAY;
1019     }
1020 
1021     auto intError = mComposer.setLayerBrightness(mDisplay->getId(), mId, brightness);
1022     return static_cast<Error>(intError);
1023 }
1024 
setBlockingRegion(const Region & region)1025 Error Layer::setBlockingRegion(const Region& region) {
1026     if (CC_UNLIKELY(!mDisplay)) {
1027         return Error::BAD_DISPLAY;
1028     }
1029 
1030     if (region.isRect() && mBlockingRegion.isRect() &&
1031         (region.getBounds() == mBlockingRegion.getBounds())) {
1032         return Error::NONE;
1033     }
1034     mBlockingRegion = region;
1035     const auto hwcRects = convertRegionToHwcRects(region);
1036     const auto intError = mComposer.setLayerBlockingRegion(mDisplay->getId(), mId, hwcRects);
1037     return static_cast<Error>(intError);
1038 }
1039 
1040 } // namespace impl
1041 } // namespace HWC2
1042 } // namespace android
1043 
1044 // TODO(b/129481165): remove the #pragma below and fix conversion issues
1045 #pragma clang diagnostic pop // ignored "-Wconversion"
1046