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 <ui/Fence.h>
30 #include <ui/FloatRect.h>
31 #include <ui/GraphicBuffer.h>
32
33 #include <android/configuration.h>
34
35 #include <inttypes.h>
36 #include <algorithm>
37 #include <iterator>
38 #include <set>
39
40 #include "../Promise.h"
41 #include "ComposerHal.h"
42
43 namespace android {
44
45 using android::Fence;
46 using android::FloatRect;
47 using android::GraphicBuffer;
48 using android::HdrCapabilities;
49 using android::HdrMetadata;
50 using android::Rect;
51 using android::Region;
52 using android::sp;
53
54 namespace HWC2 {
55
56 using namespace android::hardware::graphics::composer::hal;
57
58 namespace Hwc2 = android::Hwc2;
59
60 namespace {
61
hasMetadataKey(const std::set<Hwc2::PerFrameMetadataKey> & keys,const Hwc2::PerFrameMetadataKey & key)62 inline bool hasMetadataKey(const std::set<Hwc2::PerFrameMetadataKey>& keys,
63 const Hwc2::PerFrameMetadataKey& key) {
64 return keys.find(key) != keys.end();
65 }
66
67 } // namespace anonymous
68
69 // Display methods
70 Display::~Display() = default;
71
Config(Display & display,HWConfigId id)72 Display::Config::Config(Display& display, HWConfigId id)
73 : mDisplay(display),
74 mId(id),
75 mWidth(-1),
76 mHeight(-1),
77 mVsyncPeriod(-1),
78 mDpiX(-1),
79 mDpiY(-1) {}
80
Builder(Display & display,HWConfigId id)81 Display::Config::Builder::Builder(Display& display, HWConfigId id)
82 : mConfig(new Config(display, id)) {}
83
getDefaultDensity()84 float Display::Config::Builder::getDefaultDensity() {
85 // Default density is based on TVs: 1080p displays get XHIGH density, lower-
86 // resolution displays get TV density. Maybe eventually we'll need to update
87 // it for 4k displays, though hopefully those will just report accurate DPI
88 // information to begin with. This is also used for virtual displays and
89 // older HWC implementations, so be careful about orientation.
90
91 auto longDimension = std::max(mConfig->mWidth, mConfig->mHeight);
92 if (longDimension >= 1080) {
93 return ACONFIGURATION_DENSITY_XHIGH;
94 } else {
95 return ACONFIGURATION_DENSITY_TV;
96 }
97 }
98
99 namespace impl {
100
Display(android::Hwc2::Composer & composer,const std::unordered_set<Capability> & capabilities,HWDisplayId id,DisplayType type)101 Display::Display(android::Hwc2::Composer& composer,
102 const std::unordered_set<Capability>& capabilities, HWDisplayId id,
103 DisplayType type)
104 : mComposer(composer), mCapabilities(capabilities), mId(id), mType(type) {
105 ALOGV("Created display %" PRIu64, id);
106 }
107
~Display()108 Display::~Display() {
109 mLayers.clear();
110
111 Error error = Error::NONE;
112 const char* msg;
113 switch (mType) {
114 case DisplayType::PHYSICAL:
115 error = setVsyncEnabled(HWC2::Vsync::DISABLE);
116 msg = "disable VSYNC for";
117 break;
118
119 case DisplayType::VIRTUAL:
120 error = static_cast<Error>(mComposer.destroyVirtualDisplay(mId));
121 msg = "destroy virtual";
122 break;
123
124 case DisplayType::INVALID: // Used in unit tests.
125 break;
126 }
127
128 ALOGE_IF(error != Error::NONE, "%s: Failed to %s display %" PRIu64 ": %d", __FUNCTION__, msg,
129 mId, static_cast<int32_t>(error));
130
131 ALOGV("Destroyed display %" PRIu64, mId);
132 }
133
134 // Required by HWC2 display
acceptChanges()135 Error Display::acceptChanges()
136 {
137 auto intError = mComposer.acceptDisplayChanges(mId);
138 return static_cast<Error>(intError);
139 }
140
createLayer(HWC2::Layer ** outLayer)141 Error Display::createLayer(HWC2::Layer** outLayer) {
142 if (!outLayer) {
143 return Error::BAD_PARAMETER;
144 }
145 HWLayerId layerId = 0;
146 auto intError = mComposer.createLayer(mId, &layerId);
147 auto error = static_cast<Error>(intError);
148 if (error != Error::NONE) {
149 return error;
150 }
151
152 auto layer = std::make_unique<impl::Layer>(mComposer, mCapabilities, mId, layerId);
153 *outLayer = layer.get();
154 mLayers.emplace(layerId, std::move(layer));
155 return Error::NONE;
156 }
157
destroyLayer(HWC2::Layer * layer)158 Error Display::destroyLayer(HWC2::Layer* layer) {
159 if (!layer) {
160 return Error::BAD_PARAMETER;
161 }
162 mLayers.erase(layer->getId());
163 return Error::NONE;
164 }
165
getActiveConfig(std::shared_ptr<const Display::Config> * outConfig) const166 Error Display::getActiveConfig(
167 std::shared_ptr<const Display::Config>* outConfig) const
168 {
169 ALOGV("[%" PRIu64 "] getActiveConfig", mId);
170 HWConfigId configId = 0;
171 auto intError = mComposer.getActiveConfig(mId, &configId);
172 auto error = static_cast<Error>(intError);
173
174 if (error != Error::NONE) {
175 ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
176 *outConfig = nullptr;
177 return error;
178 }
179
180 if (mConfigs.count(configId) != 0) {
181 *outConfig = mConfigs.at(configId);
182 } else {
183 ALOGE("[%" PRIu64 "] getActiveConfig returned unknown config %u", mId,
184 configId);
185 // Return no error, but the caller needs to check for a null pointer to
186 // detect this case
187 *outConfig = nullptr;
188 }
189
190 return Error::NONE;
191 }
192
isVsyncPeriodSwitchSupported() const193 bool Display::isVsyncPeriodSwitchSupported() const {
194 ALOGV("[%" PRIu64 "] isVsyncPeriodSwitchSupported()", mId);
195
196 return mComposer.isVsyncPeriodSwitchSupported();
197 }
198
getDisplayVsyncPeriod(nsecs_t * outVsyncPeriod) const199 Error Display::getDisplayVsyncPeriod(nsecs_t* outVsyncPeriod) const {
200 ALOGV("[%" PRIu64 "] getDisplayVsyncPeriod", mId);
201
202 Error error;
203
204 if (isVsyncPeriodSwitchSupported()) {
205 Hwc2::VsyncPeriodNanos vsyncPeriodNanos = 0;
206 auto intError = mComposer.getDisplayVsyncPeriod(mId, &vsyncPeriodNanos);
207 error = static_cast<Error>(intError);
208 *outVsyncPeriod = static_cast<nsecs_t>(vsyncPeriodNanos);
209 } else {
210 // Get the default vsync period
211 std::shared_ptr<const Display::Config> config;
212 error = getActiveConfig(&config);
213 if (error != Error::NONE) {
214 return error;
215 }
216 if (!config) {
217 // HWC has updated the display modes and hasn't notified us yet.
218 return Error::BAD_CONFIG;
219 }
220
221 *outVsyncPeriod = config->getVsyncPeriod();
222 }
223
224 return error;
225 }
226
getActiveConfigIndex(int * outIndex) const227 Error Display::getActiveConfigIndex(int* outIndex) const {
228 ALOGV("[%" PRIu64 "] getActiveConfigIndex", mId);
229 HWConfigId configId = 0;
230 auto intError = mComposer.getActiveConfig(mId, &configId);
231 auto error = static_cast<Error>(intError);
232
233 if (error != Error::NONE) {
234 ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
235 *outIndex = -1;
236 return error;
237 }
238
239 auto pos = mConfigs.find(configId);
240 if (pos != mConfigs.end()) {
241 *outIndex = std::distance(mConfigs.begin(), pos);
242 ALOGV("[%" PRIu64 "] index = %d", mId, *outIndex);
243 } else {
244 ALOGE("[%" PRIu64 "] getActiveConfig returned unknown config %u", mId, configId);
245 // Return no error, but the caller needs to check for a negative index
246 // to detect this case
247 *outIndex = -1;
248 }
249
250 return Error::NONE;
251 }
252
getChangedCompositionTypes(std::unordered_map<HWC2::Layer *,Composition> * outTypes)253 Error Display::getChangedCompositionTypes(std::unordered_map<HWC2::Layer*, Composition>* outTypes) {
254 std::vector<Hwc2::Layer> layerIds;
255 std::vector<Hwc2::IComposerClient::Composition> types;
256 auto intError = mComposer.getChangedCompositionTypes(
257 mId, &layerIds, &types);
258 uint32_t numElements = layerIds.size();
259 auto error = static_cast<Error>(intError);
260 error = static_cast<Error>(intError);
261 if (error != Error::NONE) {
262 return error;
263 }
264
265 outTypes->clear();
266 outTypes->reserve(numElements);
267 for (uint32_t element = 0; element < numElements; ++element) {
268 auto layer = getLayerById(layerIds[element]);
269 if (layer) {
270 auto type = types[element];
271 ALOGV("getChangedCompositionTypes: adding %" PRIu64 " %s",
272 layer->getId(), to_string(type).c_str());
273 outTypes->emplace(layer, type);
274 } else {
275 ALOGE("getChangedCompositionTypes: invalid layer %" PRIu64 " found"
276 " on display %" PRIu64, layerIds[element], mId);
277 }
278 }
279
280 return Error::NONE;
281 }
282
getColorModes(std::vector<ColorMode> * outModes) const283 Error Display::getColorModes(std::vector<ColorMode>* outModes) const
284 {
285 auto intError = mComposer.getColorModes(mId, outModes);
286 return static_cast<Error>(intError);
287 }
288
getSupportedPerFrameMetadata() const289 int32_t Display::getSupportedPerFrameMetadata() const
290 {
291 int32_t supportedPerFrameMetadata = 0;
292
293 std::vector<Hwc2::PerFrameMetadataKey> tmpKeys = mComposer.getPerFrameMetadataKeys(mId);
294 std::set<Hwc2::PerFrameMetadataKey> keys(tmpKeys.begin(), tmpKeys.end());
295
296 // Check whether a specific metadata type is supported. A metadata type is considered
297 // supported if and only if all required fields are supported.
298
299 // SMPTE2086
300 if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X) &&
301 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y) &&
302 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X) &&
303 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y) &&
304 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X) &&
305 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y) &&
306 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::WHITE_POINT_X) &&
307 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::WHITE_POINT_Y) &&
308 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_LUMINANCE) &&
309 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MIN_LUMINANCE)) {
310 supportedPerFrameMetadata |= HdrMetadata::Type::SMPTE2086;
311 }
312 // CTA861_3
313 if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL) &&
314 hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL)) {
315 supportedPerFrameMetadata |= HdrMetadata::Type::CTA861_3;
316 }
317
318 // HDR10PLUS
319 if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::HDR10_PLUS_SEI)) {
320 supportedPerFrameMetadata |= HdrMetadata::Type::HDR10PLUS;
321 }
322
323 return supportedPerFrameMetadata;
324 }
325
getRenderIntents(ColorMode colorMode,std::vector<RenderIntent> * outRenderIntents) const326 Error Display::getRenderIntents(ColorMode colorMode,
327 std::vector<RenderIntent>* outRenderIntents) const
328 {
329 auto intError = mComposer.getRenderIntents(mId, colorMode, outRenderIntents);
330 return static_cast<Error>(intError);
331 }
332
getDataspaceSaturationMatrix(Dataspace dataspace,android::mat4 * outMatrix)333 Error Display::getDataspaceSaturationMatrix(Dataspace dataspace, android::mat4* outMatrix)
334 {
335 auto intError = mComposer.getDataspaceSaturationMatrix(dataspace, outMatrix);
336 return static_cast<Error>(intError);
337 }
338
getConfigs() const339 std::vector<std::shared_ptr<const Display::Config>> Display::getConfigs() const
340 {
341 std::vector<std::shared_ptr<const Config>> configs;
342 for (const auto& element : mConfigs) {
343 configs.emplace_back(element.second);
344 }
345 return configs;
346 }
347
getName(std::string * outName) const348 Error Display::getName(std::string* outName) const
349 {
350 auto intError = mComposer.getDisplayName(mId, outName);
351 return static_cast<Error>(intError);
352 }
353
getRequests(HWC2::DisplayRequest * outDisplayRequests,std::unordered_map<HWC2::Layer *,LayerRequest> * outLayerRequests)354 Error Display::getRequests(HWC2::DisplayRequest* outDisplayRequests,
355 std::unordered_map<HWC2::Layer*, LayerRequest>* outLayerRequests) {
356 uint32_t intDisplayRequests = 0;
357 std::vector<Hwc2::Layer> layerIds;
358 std::vector<uint32_t> layerRequests;
359 auto intError = mComposer.getDisplayRequests(
360 mId, &intDisplayRequests, &layerIds, &layerRequests);
361 uint32_t numElements = layerIds.size();
362 auto error = static_cast<Error>(intError);
363 if (error != Error::NONE) {
364 return error;
365 }
366
367 *outDisplayRequests = static_cast<DisplayRequest>(intDisplayRequests);
368 outLayerRequests->clear();
369 outLayerRequests->reserve(numElements);
370 for (uint32_t element = 0; element < numElements; ++element) {
371 auto layer = getLayerById(layerIds[element]);
372 if (layer) {
373 auto layerRequest =
374 static_cast<LayerRequest>(layerRequests[element]);
375 outLayerRequests->emplace(layer, layerRequest);
376 } else {
377 ALOGE("getRequests: invalid layer %" PRIu64 " found on display %"
378 PRIu64, layerIds[element], mId);
379 }
380 }
381
382 return Error::NONE;
383 }
384
getConnectionType(android::DisplayConnectionType * outType) const385 Error Display::getConnectionType(android::DisplayConnectionType* outType) const {
386 if (mType != DisplayType::PHYSICAL) return Error::BAD_DISPLAY;
387
388 using ConnectionType = Hwc2::IComposerClient::DisplayConnectionType;
389 ConnectionType connectionType;
390 const auto error = static_cast<Error>(mComposer.getDisplayConnectionType(mId, &connectionType));
391 if (error != Error::NONE) {
392 return error;
393 }
394
395 *outType = connectionType == ConnectionType::INTERNAL
396 ? android::DisplayConnectionType::Internal
397 : android::DisplayConnectionType::External;
398 return Error::NONE;
399 }
400
supportsDoze(bool * outSupport) const401 Error Display::supportsDoze(bool* outSupport) const {
402 *outSupport = mDisplayCapabilities.count(DisplayCapability::DOZE) > 0;
403 return Error::NONE;
404 }
405
getHdrCapabilities(HdrCapabilities * outCapabilities) const406 Error Display::getHdrCapabilities(HdrCapabilities* outCapabilities) const
407 {
408 float maxLuminance = -1.0f;
409 float maxAverageLuminance = -1.0f;
410 float minLuminance = -1.0f;
411 std::vector<Hwc2::Hdr> types;
412 auto intError = mComposer.getHdrCapabilities(mId, &types,
413 &maxLuminance, &maxAverageLuminance, &minLuminance);
414 auto error = static_cast<HWC2::Error>(intError);
415
416 if (error != Error::NONE) {
417 return error;
418 }
419
420 *outCapabilities = HdrCapabilities(std::move(types),
421 maxLuminance, maxAverageLuminance, minLuminance);
422 return Error::NONE;
423 }
424
getDisplayedContentSamplingAttributes(hal::PixelFormat * outFormat,Dataspace * outDataspace,uint8_t * outComponentMask) const425 Error Display::getDisplayedContentSamplingAttributes(hal::PixelFormat* outFormat,
426 Dataspace* outDataspace,
427 uint8_t* outComponentMask) const {
428 auto intError = mComposer.getDisplayedContentSamplingAttributes(mId, outFormat, outDataspace,
429 outComponentMask);
430 return static_cast<Error>(intError);
431 }
432
setDisplayContentSamplingEnabled(bool enabled,uint8_t componentMask,uint64_t maxFrames) const433 Error Display::setDisplayContentSamplingEnabled(bool enabled, uint8_t componentMask,
434 uint64_t maxFrames) const {
435 auto intError =
436 mComposer.setDisplayContentSamplingEnabled(mId, enabled, componentMask, maxFrames);
437 return static_cast<Error>(intError);
438 }
439
getDisplayedContentSample(uint64_t maxFrames,uint64_t timestamp,android::DisplayedFrameStats * outStats) const440 Error Display::getDisplayedContentSample(uint64_t maxFrames, uint64_t timestamp,
441 android::DisplayedFrameStats* outStats) const {
442 auto intError = mComposer.getDisplayedContentSample(mId, maxFrames, timestamp, outStats);
443 return static_cast<Error>(intError);
444 }
445
getReleaseFences(std::unordered_map<HWC2::Layer *,sp<Fence>> * outFences) const446 Error Display::getReleaseFences(std::unordered_map<HWC2::Layer*, sp<Fence>>* outFences) const {
447 std::vector<Hwc2::Layer> layerIds;
448 std::vector<int> fenceFds;
449 auto intError = mComposer.getReleaseFences(mId, &layerIds, &fenceFds);
450 auto error = static_cast<Error>(intError);
451 uint32_t numElements = layerIds.size();
452 if (error != Error::NONE) {
453 return error;
454 }
455
456 std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
457 releaseFences.reserve(numElements);
458 for (uint32_t element = 0; element < numElements; ++element) {
459 auto layer = getLayerById(layerIds[element]);
460 if (layer) {
461 sp<Fence> fence(new Fence(fenceFds[element]));
462 releaseFences.emplace(layer, fence);
463 } else {
464 ALOGE("getReleaseFences: invalid layer %" PRIu64
465 " found on display %" PRIu64, layerIds[element], mId);
466 for (; element < numElements; ++element) {
467 close(fenceFds[element]);
468 }
469 return Error::BAD_LAYER;
470 }
471 }
472
473 *outFences = std::move(releaseFences);
474 return Error::NONE;
475 }
476
present(sp<Fence> * outPresentFence)477 Error Display::present(sp<Fence>* outPresentFence)
478 {
479 int32_t presentFenceFd = -1;
480 auto intError = mComposer.presentDisplay(mId, &presentFenceFd);
481 auto error = static_cast<Error>(intError);
482 if (error != Error::NONE) {
483 return error;
484 }
485
486 *outPresentFence = new Fence(presentFenceFd);
487 return Error::NONE;
488 }
489
setActiveConfigWithConstraints(const std::shared_ptr<const HWC2::Display::Config> & config,const VsyncPeriodChangeConstraints & constraints,VsyncPeriodChangeTimeline * outTimeline)490 Error Display::setActiveConfigWithConstraints(
491 const std::shared_ptr<const HWC2::Display::Config>& config,
492 const VsyncPeriodChangeConstraints& constraints, VsyncPeriodChangeTimeline* outTimeline) {
493 ALOGV("[%" PRIu64 "] setActiveConfigWithConstraints", mId);
494 if (config->getDisplayId() != mId) {
495 ALOGE("setActiveConfigWithConstraints received config %u for the wrong display %" PRIu64
496 " (expected %" PRIu64 ")",
497 config->getId(), config->getDisplayId(), mId);
498 return Error::BAD_CONFIG;
499 }
500
501 if (isVsyncPeriodSwitchSupported()) {
502 Hwc2::IComposerClient::VsyncPeriodChangeConstraints hwc2Constraints;
503 hwc2Constraints.desiredTimeNanos = constraints.desiredTimeNanos;
504 hwc2Constraints.seamlessRequired = constraints.seamlessRequired;
505
506 Hwc2::VsyncPeriodChangeTimeline vsyncPeriodChangeTimeline = {};
507 auto intError =
508 mComposer.setActiveConfigWithConstraints(mId, config->getId(), hwc2Constraints,
509 &vsyncPeriodChangeTimeline);
510 outTimeline->newVsyncAppliedTimeNanos = vsyncPeriodChangeTimeline.newVsyncAppliedTimeNanos;
511 outTimeline->refreshRequired = vsyncPeriodChangeTimeline.refreshRequired;
512 outTimeline->refreshTimeNanos = vsyncPeriodChangeTimeline.refreshTimeNanos;
513 return static_cast<Error>(intError);
514 }
515
516 // Use legacy setActiveConfig instead
517 ALOGV("fallback to legacy setActiveConfig");
518 const auto now = systemTime();
519 if (constraints.desiredTimeNanos > now || constraints.seamlessRequired) {
520 ALOGE("setActiveConfigWithConstraints received constraints that can't be satisfied");
521 }
522
523 auto intError_2_4 = mComposer.setActiveConfig(mId, config->getId());
524 outTimeline->newVsyncAppliedTimeNanos = std::max(now, constraints.desiredTimeNanos);
525 outTimeline->refreshRequired = true;
526 outTimeline->refreshTimeNanos = now;
527 return static_cast<Error>(intError_2_4);
528 }
529
setActiveConfig(const std::shared_ptr<const Config> & config)530 Error Display::setActiveConfig(const std::shared_ptr<const Config>& config)
531 {
532 if (config->getDisplayId() != mId) {
533 ALOGE("setActiveConfig received config %u for the wrong display %"
534 PRIu64 " (expected %" PRIu64 ")", config->getId(),
535 config->getDisplayId(), mId);
536 return Error::BAD_CONFIG;
537 }
538 auto intError = mComposer.setActiveConfig(mId, config->getId());
539 return static_cast<Error>(intError);
540 }
541
setClientTarget(uint32_t slot,const sp<GraphicBuffer> & target,const sp<Fence> & acquireFence,Dataspace dataspace)542 Error Display::setClientTarget(uint32_t slot, const sp<GraphicBuffer>& target,
543 const sp<Fence>& acquireFence, Dataspace dataspace)
544 {
545 // TODO: Properly encode client target surface damage
546 int32_t fenceFd = acquireFence->dup();
547 auto intError = mComposer.setClientTarget(mId, slot, target,
548 fenceFd, dataspace, std::vector<Hwc2::IComposerClient::Rect>());
549 return static_cast<Error>(intError);
550 }
551
setColorMode(ColorMode mode,RenderIntent renderIntent)552 Error Display::setColorMode(ColorMode mode, RenderIntent renderIntent)
553 {
554 auto intError = mComposer.setColorMode(mId, mode, renderIntent);
555 return static_cast<Error>(intError);
556 }
557
setColorTransform(const android::mat4 & matrix,ColorTransform hint)558 Error Display::setColorTransform(const android::mat4& matrix, ColorTransform hint) {
559 auto intError = mComposer.setColorTransform(mId, matrix.asArray(), hint);
560 return static_cast<Error>(intError);
561 }
562
setOutputBuffer(const sp<GraphicBuffer> & buffer,const sp<Fence> & releaseFence)563 Error Display::setOutputBuffer(const sp<GraphicBuffer>& buffer,
564 const sp<Fence>& releaseFence)
565 {
566 int32_t fenceFd = releaseFence->dup();
567 auto handle = buffer->getNativeBuffer()->handle;
568 auto intError = mComposer.setOutputBuffer(mId, handle, fenceFd);
569 close(fenceFd);
570 return static_cast<Error>(intError);
571 }
572
setPowerMode(PowerMode mode)573 Error Display::setPowerMode(PowerMode mode)
574 {
575 auto intMode = static_cast<Hwc2::IComposerClient::PowerMode>(mode);
576 auto intError = mComposer.setPowerMode(mId, intMode);
577
578 if (mode == PowerMode::ON) {
579 std::call_once(mDisplayCapabilityQueryFlag, [this]() {
580 std::vector<Hwc2::DisplayCapability> tmpCapabilities;
581 auto error =
582 static_cast<Error>(mComposer.getDisplayCapabilities(mId, &tmpCapabilities));
583 if (error == Error::NONE) {
584 for (auto capability : tmpCapabilities) {
585 mDisplayCapabilities.emplace(static_cast<DisplayCapability>(capability));
586 }
587 } else if (error == Error::UNSUPPORTED) {
588 if (mCapabilities.count(Capability::SKIP_CLIENT_COLOR_TRANSFORM)) {
589 mDisplayCapabilities.emplace(DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM);
590 }
591 bool dozeSupport = false;
592 error = static_cast<Error>(mComposer.getDozeSupport(mId, &dozeSupport));
593 if (error == Error::NONE && dozeSupport) {
594 mDisplayCapabilities.emplace(DisplayCapability::DOZE);
595 }
596 }
597 });
598 }
599
600 return static_cast<Error>(intError);
601 }
602
setVsyncEnabled(Vsync enabled)603 Error Display::setVsyncEnabled(Vsync enabled)
604 {
605 auto intEnabled = static_cast<Hwc2::IComposerClient::Vsync>(enabled);
606 auto intError = mComposer.setVsyncEnabled(mId, intEnabled);
607 return static_cast<Error>(intError);
608 }
609
validate(uint32_t * outNumTypes,uint32_t * outNumRequests)610 Error Display::validate(uint32_t* outNumTypes, uint32_t* outNumRequests)
611 {
612 uint32_t numTypes = 0;
613 uint32_t numRequests = 0;
614 auto intError = mComposer.validateDisplay(mId, &numTypes, &numRequests);
615 auto error = static_cast<Error>(intError);
616 if (error != Error::NONE && !hasChangesError(error)) {
617 return error;
618 }
619
620 *outNumTypes = numTypes;
621 *outNumRequests = numRequests;
622 return error;
623 }
624
presentOrValidate(uint32_t * outNumTypes,uint32_t * outNumRequests,sp<android::Fence> * outPresentFence,uint32_t * state)625 Error Display::presentOrValidate(uint32_t* outNumTypes, uint32_t* outNumRequests,
626 sp<android::Fence>* outPresentFence, uint32_t* state) {
627
628 uint32_t numTypes = 0;
629 uint32_t numRequests = 0;
630 int32_t presentFenceFd = -1;
631 auto intError = mComposer.presentOrValidateDisplay(
632 mId, &numTypes, &numRequests, &presentFenceFd, state);
633 auto error = static_cast<Error>(intError);
634 if (error != Error::NONE && !hasChangesError(error)) {
635 return error;
636 }
637
638 if (*state == 1) {
639 *outPresentFence = new Fence(presentFenceFd);
640 }
641
642 if (*state == 0) {
643 *outNumTypes = numTypes;
644 *outNumRequests = numRequests;
645 }
646 return error;
647 }
648
setDisplayBrightness(float brightness)649 std::future<Error> Display::setDisplayBrightness(float brightness) {
650 return promise::defer([composer = &mComposer, id = mId, brightness] {
651 const auto intError = composer->setDisplayBrightness(id, brightness);
652 return static_cast<Error>(intError);
653 });
654 }
655
setAutoLowLatencyMode(bool on)656 Error Display::setAutoLowLatencyMode(bool on) {
657 auto intError = mComposer.setAutoLowLatencyMode(mId, on);
658 return static_cast<Error>(intError);
659 }
660
getSupportedContentTypes(std::vector<ContentType> * outSupportedContentTypes) const661 Error Display::getSupportedContentTypes(std::vector<ContentType>* outSupportedContentTypes) const {
662 std::vector<Hwc2::IComposerClient::ContentType> tmpSupportedContentTypes;
663 auto intError = mComposer.getSupportedContentTypes(mId, &tmpSupportedContentTypes);
664 for (Hwc2::IComposerClient::ContentType contentType : tmpSupportedContentTypes) {
665 outSupportedContentTypes->push_back(static_cast<ContentType>(contentType));
666 }
667 return static_cast<Error>(intError);
668 }
669
setContentType(ContentType contentType)670 Error Display::setContentType(ContentType contentType) {
671 auto intError = mComposer.setContentType(mId, contentType);
672 return static_cast<Error>(intError);
673 }
674
getClientTargetProperty(ClientTargetProperty * outClientTargetProperty)675 Error Display::getClientTargetProperty(ClientTargetProperty* outClientTargetProperty) {
676 const auto error = mComposer.getClientTargetProperty(mId, outClientTargetProperty);
677 return static_cast<Error>(error);
678 }
679
680 // For use by Device
681
setConnected(bool connected)682 void Display::setConnected(bool connected) {
683 if (!mIsConnected && connected) {
684 mComposer.setClientTargetSlotCount(mId);
685 if (mType == DisplayType::PHYSICAL) {
686 loadConfigs();
687 }
688 }
689 mIsConnected = connected;
690 }
691
getAttribute(HWConfigId configId,Attribute attribute)692 int32_t Display::getAttribute(HWConfigId configId, Attribute attribute) {
693 int32_t value = 0;
694 auto intError = mComposer.getDisplayAttribute(mId, configId, attribute, &value);
695 auto error = static_cast<Error>(intError);
696 if (error != Error::NONE) {
697 ALOGE("getDisplayAttribute(%" PRIu64 ", %u, %s) failed: %s (%d)", mId,
698 configId, to_string(attribute).c_str(),
699 to_string(error).c_str(), intError);
700 return -1;
701 }
702 return value;
703 }
704
loadConfig(HWConfigId configId)705 void Display::loadConfig(HWConfigId configId) {
706 ALOGV("[%" PRIu64 "] loadConfig(%u)", mId, configId);
707
708 auto config = Config::Builder(*this, configId)
709 .setWidth(getAttribute(configId, hal::Attribute::WIDTH))
710 .setHeight(getAttribute(configId, hal::Attribute::HEIGHT))
711 .setVsyncPeriod(getAttribute(configId, hal::Attribute::VSYNC_PERIOD))
712 .setDpiX(getAttribute(configId, hal::Attribute::DPI_X))
713 .setDpiY(getAttribute(configId, hal::Attribute::DPI_Y))
714 .setConfigGroup(getAttribute(configId, hal::Attribute::CONFIG_GROUP))
715 .build();
716 mConfigs.emplace(configId, std::move(config));
717 }
718
loadConfigs()719 void Display::loadConfigs()
720 {
721 ALOGV("[%" PRIu64 "] loadConfigs", mId);
722
723 std::vector<HWConfigId> configIds;
724 auto intError = mComposer.getDisplayConfigs(mId, &configIds);
725 auto error = static_cast<Error>(intError);
726 if (error != Error::NONE) {
727 ALOGE("[%" PRIu64 "] getDisplayConfigs [2] failed: %s (%d)", mId,
728 to_string(error).c_str(), intError);
729 return;
730 }
731
732 for (auto configId : configIds) {
733 loadConfig(configId);
734 }
735 }
736
737 // Other Display methods
738
getLayerById(HWLayerId id) const739 HWC2::Layer* Display::getLayerById(HWLayerId id) const {
740 if (mLayers.count(id) == 0) {
741 return nullptr;
742 }
743
744 return mLayers.at(id).get();
745 }
746 } // namespace impl
747
748 // Layer methods
749
750 Layer::~Layer() = default;
751
752 namespace impl {
753
Layer(android::Hwc2::Composer & composer,const std::unordered_set<Capability> & capabilities,HWDisplayId displayId,HWLayerId layerId)754 Layer::Layer(android::Hwc2::Composer& composer, const std::unordered_set<Capability>& capabilities,
755 HWDisplayId displayId, HWLayerId layerId)
756 : mComposer(composer),
757 mCapabilities(capabilities),
758 mDisplayId(displayId),
759 mId(layerId),
760 mColorMatrix(android::mat4()) {
761 ALOGV("Created layer %" PRIu64 " on display %" PRIu64, layerId, displayId);
762 }
763
~Layer()764 Layer::~Layer()
765 {
766 auto intError = mComposer.destroyLayer(mDisplayId, mId);
767 auto error = static_cast<Error>(intError);
768 ALOGE_IF(error != Error::NONE,
769 "destroyLayer(%" PRIu64 ", %" PRIu64 ")"
770 " failed: %s (%d)",
771 mDisplayId, mId, to_string(error).c_str(), intError);
772 }
773
setCursorPosition(int32_t x,int32_t y)774 Error Layer::setCursorPosition(int32_t x, int32_t y)
775 {
776 auto intError = mComposer.setCursorPosition(mDisplayId, mId, x, y);
777 return static_cast<Error>(intError);
778 }
779
setBuffer(uint32_t slot,const sp<GraphicBuffer> & buffer,const sp<Fence> & acquireFence)780 Error Layer::setBuffer(uint32_t slot, const sp<GraphicBuffer>& buffer,
781 const sp<Fence>& acquireFence)
782 {
783 if (buffer == nullptr && mBufferSlot == slot) {
784 return Error::NONE;
785 }
786 mBufferSlot = slot;
787
788 int32_t fenceFd = acquireFence->dup();
789 auto intError = mComposer.setLayerBuffer(mDisplayId, mId, slot, buffer,
790 fenceFd);
791 return static_cast<Error>(intError);
792 }
793
setSurfaceDamage(const Region & damage)794 Error Layer::setSurfaceDamage(const Region& damage)
795 {
796 if (damage.isRect() && mDamageRegion.isRect() &&
797 (damage.getBounds() == mDamageRegion.getBounds())) {
798 return Error::NONE;
799 }
800 mDamageRegion = damage;
801
802 // We encode default full-screen damage as INVALID_RECT upstream, but as 0
803 // rects for HWC
804 Hwc2::Error intError = Hwc2::Error::NONE;
805 if (damage.isRect() && damage.getBounds() == Rect::INVALID_RECT) {
806 intError = mComposer.setLayerSurfaceDamage(mDisplayId,
807 mId, std::vector<Hwc2::IComposerClient::Rect>());
808 } else {
809 size_t rectCount = 0;
810 auto rectArray = damage.getArray(&rectCount);
811
812 std::vector<Hwc2::IComposerClient::Rect> hwcRects;
813 for (size_t rect = 0; rect < rectCount; ++rect) {
814 hwcRects.push_back({rectArray[rect].left, rectArray[rect].top,
815 rectArray[rect].right, rectArray[rect].bottom});
816 }
817
818 intError = mComposer.setLayerSurfaceDamage(mDisplayId, mId, hwcRects);
819 }
820
821 return static_cast<Error>(intError);
822 }
823
setBlendMode(BlendMode mode)824 Error Layer::setBlendMode(BlendMode mode)
825 {
826 auto intError = mComposer.setLayerBlendMode(mDisplayId, mId, mode);
827 return static_cast<Error>(intError);
828 }
829
setColor(Color color)830 Error Layer::setColor(Color color) {
831 auto intError = mComposer.setLayerColor(mDisplayId, mId, color);
832 return static_cast<Error>(intError);
833 }
834
setCompositionType(Composition type)835 Error Layer::setCompositionType(Composition type)
836 {
837 auto intError = mComposer.setLayerCompositionType(mDisplayId, mId, type);
838 return static_cast<Error>(intError);
839 }
840
setDataspace(Dataspace dataspace)841 Error Layer::setDataspace(Dataspace dataspace)
842 {
843 if (dataspace == mDataSpace) {
844 return Error::NONE;
845 }
846 mDataSpace = dataspace;
847 auto intError = mComposer.setLayerDataspace(mDisplayId, mId, mDataSpace);
848 return static_cast<Error>(intError);
849 }
850
setPerFrameMetadata(const int32_t supportedPerFrameMetadata,const android::HdrMetadata & metadata)851 Error Layer::setPerFrameMetadata(const int32_t supportedPerFrameMetadata,
852 const android::HdrMetadata& metadata)
853 {
854 if (metadata == mHdrMetadata) {
855 return Error::NONE;
856 }
857
858 mHdrMetadata = metadata;
859 int validTypes = mHdrMetadata.validTypes & supportedPerFrameMetadata;
860 std::vector<Hwc2::PerFrameMetadata> perFrameMetadatas;
861 if (validTypes & HdrMetadata::SMPTE2086) {
862 perFrameMetadatas.insert(perFrameMetadatas.end(),
863 {{Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X,
864 mHdrMetadata.smpte2086.displayPrimaryRed.x},
865 {Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y,
866 mHdrMetadata.smpte2086.displayPrimaryRed.y},
867 {Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X,
868 mHdrMetadata.smpte2086.displayPrimaryGreen.x},
869 {Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y,
870 mHdrMetadata.smpte2086.displayPrimaryGreen.y},
871 {Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X,
872 mHdrMetadata.smpte2086.displayPrimaryBlue.x},
873 {Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y,
874 mHdrMetadata.smpte2086.displayPrimaryBlue.y},
875 {Hwc2::PerFrameMetadataKey::WHITE_POINT_X,
876 mHdrMetadata.smpte2086.whitePoint.x},
877 {Hwc2::PerFrameMetadataKey::WHITE_POINT_Y,
878 mHdrMetadata.smpte2086.whitePoint.y},
879 {Hwc2::PerFrameMetadataKey::MAX_LUMINANCE,
880 mHdrMetadata.smpte2086.maxLuminance},
881 {Hwc2::PerFrameMetadataKey::MIN_LUMINANCE,
882 mHdrMetadata.smpte2086.minLuminance}});
883 }
884
885 if (validTypes & HdrMetadata::CTA861_3) {
886 perFrameMetadatas.insert(perFrameMetadatas.end(),
887 {{Hwc2::PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL,
888 mHdrMetadata.cta8613.maxContentLightLevel},
889 {Hwc2::PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL,
890 mHdrMetadata.cta8613.maxFrameAverageLightLevel}});
891 }
892
893 Error error = static_cast<Error>(
894 mComposer.setLayerPerFrameMetadata(mDisplayId, mId, perFrameMetadatas));
895
896 if (validTypes & HdrMetadata::HDR10PLUS) {
897 if (CC_UNLIKELY(mHdrMetadata.hdr10plus.size() == 0)) {
898 return Error::BAD_PARAMETER;
899 }
900
901 std::vector<Hwc2::PerFrameMetadataBlob> perFrameMetadataBlobs;
902 perFrameMetadataBlobs.push_back(
903 {Hwc2::PerFrameMetadataKey::HDR10_PLUS_SEI, mHdrMetadata.hdr10plus});
904 Error setMetadataBlobsError = static_cast<Error>(
905 mComposer.setLayerPerFrameMetadataBlobs(mDisplayId, mId, perFrameMetadataBlobs));
906 if (error == Error::NONE) {
907 return setMetadataBlobsError;
908 }
909 }
910 return error;
911 }
912
setDisplayFrame(const Rect & frame)913 Error Layer::setDisplayFrame(const Rect& frame)
914 {
915 Hwc2::IComposerClient::Rect hwcRect{frame.left, frame.top,
916 frame.right, frame.bottom};
917 auto intError = mComposer.setLayerDisplayFrame(mDisplayId, mId, hwcRect);
918 return static_cast<Error>(intError);
919 }
920
setPlaneAlpha(float alpha)921 Error Layer::setPlaneAlpha(float alpha)
922 {
923 auto intError = mComposer.setLayerPlaneAlpha(mDisplayId, mId, alpha);
924 return static_cast<Error>(intError);
925 }
926
setSidebandStream(const native_handle_t * stream)927 Error Layer::setSidebandStream(const native_handle_t* stream)
928 {
929 if (mCapabilities.count(Capability::SIDEBAND_STREAM) == 0) {
930 ALOGE("Attempted to call setSidebandStream without checking that the "
931 "device supports sideband streams");
932 return Error::UNSUPPORTED;
933 }
934 auto intError = mComposer.setLayerSidebandStream(mDisplayId, mId, stream);
935 return static_cast<Error>(intError);
936 }
937
setSourceCrop(const FloatRect & crop)938 Error Layer::setSourceCrop(const FloatRect& crop)
939 {
940 Hwc2::IComposerClient::FRect hwcRect{
941 crop.left, crop.top, crop.right, crop.bottom};
942 auto intError = mComposer.setLayerSourceCrop(mDisplayId, mId, hwcRect);
943 return static_cast<Error>(intError);
944 }
945
setTransform(Transform transform)946 Error Layer::setTransform(Transform transform)
947 {
948 auto intTransform = static_cast<Hwc2::Transform>(transform);
949 auto intError = mComposer.setLayerTransform(mDisplayId, mId, intTransform);
950 return static_cast<Error>(intError);
951 }
952
setVisibleRegion(const Region & region)953 Error Layer::setVisibleRegion(const Region& region)
954 {
955 if (region.isRect() && mVisibleRegion.isRect() &&
956 (region.getBounds() == mVisibleRegion.getBounds())) {
957 return Error::NONE;
958 }
959 mVisibleRegion = region;
960
961 size_t rectCount = 0;
962 auto rectArray = region.getArray(&rectCount);
963
964 std::vector<Hwc2::IComposerClient::Rect> hwcRects;
965 for (size_t rect = 0; rect < rectCount; ++rect) {
966 hwcRects.push_back({rectArray[rect].left, rectArray[rect].top,
967 rectArray[rect].right, rectArray[rect].bottom});
968 }
969
970 auto intError = mComposer.setLayerVisibleRegion(mDisplayId, mId, hwcRects);
971 return static_cast<Error>(intError);
972 }
973
setZOrder(uint32_t z)974 Error Layer::setZOrder(uint32_t z)
975 {
976 auto intError = mComposer.setLayerZOrder(mDisplayId, mId, z);
977 return static_cast<Error>(intError);
978 }
979
setInfo(uint32_t type,uint32_t appId)980 Error Layer::setInfo(uint32_t type, uint32_t appId)
981 {
982 auto intError = mComposer.setLayerInfo(mDisplayId, mId, type, appId);
983 return static_cast<Error>(intError);
984 }
985
986 // Composer HAL 2.3
setColorTransform(const android::mat4 & matrix)987 Error Layer::setColorTransform(const android::mat4& matrix) {
988 if (matrix == mColorMatrix) {
989 return Error::NONE;
990 }
991 auto intError = mComposer.setLayerColorTransform(mDisplayId, mId, matrix.asArray());
992 Error error = static_cast<Error>(intError);
993 if (error != Error::NONE) {
994 return error;
995 }
996 mColorMatrix = matrix;
997 return error;
998 }
999
1000 // Composer HAL 2.4
setLayerGenericMetadata(const std::string & name,bool mandatory,const std::vector<uint8_t> & value)1001 Error Layer::setLayerGenericMetadata(const std::string& name, bool mandatory,
1002 const std::vector<uint8_t>& value) {
1003 auto intError = mComposer.setLayerGenericMetadata(mDisplayId, mId, name, mandatory, value);
1004 return static_cast<Error>(intError);
1005 }
1006
1007 } // namespace impl
1008 } // namespace HWC2
1009 } // namespace android
1010
1011 // TODO(b/129481165): remove the #pragma below and fix conversion issues
1012 #pragma clang diagnostic pop // ignored "-Wconversion"
1013