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 // #define LOG_NDEBUG 0
18 
19 #undef LOG_TAG
20 #define LOG_TAG "HWC2"
21 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
22 
23 #include "HWC2.h"
24 #include "ComposerHal.h"
25 
26 #include <ui/Fence.h>
27 #include <ui/FloatRect.h>
28 #include <ui/GraphicBuffer.h>
29 #include <ui/Region.h>
30 
31 #include <android/configuration.h>
32 
33 #include <inttypes.h>
34 #include <algorithm>
35 #include <iterator>
36 #include <set>
37 
38 using android::Fence;
39 using android::FloatRect;
40 using android::GraphicBuffer;
41 using android::HdrCapabilities;
42 using android::HdrMetadata;
43 using android::Rect;
44 using android::Region;
45 using android::sp;
46 using android::hardware::Return;
47 using android::hardware::Void;
48 
49 namespace HWC2 {
50 
51 namespace Hwc2 = android::Hwc2;
52 using android::ui::ColorMode;
53 using android::ui::Dataspace;
54 using android::ui::PixelFormat;
55 using android::ui::RenderIntent;
56 
57 namespace {
58 
hasMetadataKey(const std::set<Hwc2::PerFrameMetadataKey> & keys,const Hwc2::PerFrameMetadataKey & key)59 inline bool hasMetadataKey(const std::set<Hwc2::PerFrameMetadataKey>& keys,
60                            const Hwc2::PerFrameMetadataKey& key) {
61     return keys.find(key) != keys.end();
62 }
63 
64 class ComposerCallbackBridge : public Hwc2::IComposerCallback {
65 public:
ComposerCallbackBridge(ComposerCallback * callback,int32_t sequenceId)66     ComposerCallbackBridge(ComposerCallback* callback, int32_t sequenceId)
67             : mCallback(callback), mSequenceId(sequenceId) {}
68 
onHotplug(Hwc2::Display display,IComposerCallback::Connection conn)69     Return<void> onHotplug(Hwc2::Display display,
70                            IComposerCallback::Connection conn) override
71     {
72         HWC2::Connection connection = static_cast<HWC2::Connection>(conn);
73         mCallback->onHotplugReceived(mSequenceId, display, connection);
74         return Void();
75     }
76 
onRefresh(Hwc2::Display display)77     Return<void> onRefresh(Hwc2::Display display) override
78     {
79         mCallback->onRefreshReceived(mSequenceId, display);
80         return Void();
81     }
82 
onVsync(Hwc2::Display display,int64_t timestamp)83     Return<void> onVsync(Hwc2::Display display, int64_t timestamp) override
84     {
85         mCallback->onVsyncReceived(mSequenceId, display, timestamp);
86         return Void();
87     }
88 
89 private:
90     ComposerCallback* mCallback;
91     int32_t mSequenceId;
92 };
93 
94 } // namespace anonymous
95 
96 
97 // Device methods
98 
Device(std::unique_ptr<android::Hwc2::Composer> composer)99 Device::Device(std::unique_ptr<android::Hwc2::Composer> composer) : mComposer(std::move(composer)) {
100     loadCapabilities();
101 }
102 
registerCallback(ComposerCallback * callback,int32_t sequenceId)103 void Device::registerCallback(ComposerCallback* callback, int32_t sequenceId) {
104     if (mRegisteredCallback) {
105         ALOGW("Callback already registered. Ignored extra registration "
106                 "attempt.");
107         return;
108     }
109     mRegisteredCallback = true;
110     sp<ComposerCallbackBridge> callbackBridge(
111             new ComposerCallbackBridge(callback, sequenceId));
112     mComposer->registerCallback(callbackBridge);
113 }
114 
115 // Required by HWC2 device
116 
dump() const117 std::string Device::dump() const
118 {
119     return mComposer->dumpDebugInfo();
120 }
121 
getMaxVirtualDisplayCount() const122 uint32_t Device::getMaxVirtualDisplayCount() const
123 {
124     return mComposer->getMaxVirtualDisplayCount();
125 }
126 
createVirtualDisplay(uint32_t width,uint32_t height,PixelFormat * format,Display ** outDisplay)127 Error Device::createVirtualDisplay(uint32_t width, uint32_t height,
128         PixelFormat* format, Display** outDisplay)
129 {
130     ALOGI("Creating virtual display");
131 
132     hwc2_display_t displayId = 0;
133     auto intError = mComposer->createVirtualDisplay(width, height,
134             format, &displayId);
135     auto error = static_cast<Error>(intError);
136     if (error != Error::None) {
137         return error;
138     }
139 
140     auto display = std::make_unique<Display>(
141             *mComposer.get(), mCapabilities, displayId, DisplayType::Virtual);
142     display->setConnected(true);
143     *outDisplay = display.get();
144     mDisplays.emplace(displayId, std::move(display));
145     ALOGI("Created virtual display");
146     return Error::None;
147 }
148 
destroyDisplay(hwc2_display_t displayId)149 void Device::destroyDisplay(hwc2_display_t displayId)
150 {
151     ALOGI("Destroying display %" PRIu64, displayId);
152     mDisplays.erase(displayId);
153 }
154 
onHotplug(hwc2_display_t displayId,Connection connection)155 void Device::onHotplug(hwc2_display_t displayId, Connection connection) {
156     if (connection == Connection::Connected) {
157         // If we get a hotplug connected event for a display we already have,
158         // destroy the display and recreate it. This will force us to requery
159         // the display params and recreate all layers on that display.
160         auto oldDisplay = getDisplayById(displayId);
161         if (oldDisplay != nullptr && oldDisplay->isConnected()) {
162             ALOGI("Hotplug connecting an already connected display."
163                     " Clearing old display state.");
164         }
165         mDisplays.erase(displayId);
166 
167         DisplayType displayType;
168         auto intError = mComposer->getDisplayType(displayId,
169                 reinterpret_cast<Hwc2::IComposerClient::DisplayType *>(
170                         &displayType));
171         auto error = static_cast<Error>(intError);
172         if (error != Error::None) {
173             ALOGE("getDisplayType(%" PRIu64 ") failed: %s (%d). "
174                     "Aborting hotplug attempt.",
175                     displayId, to_string(error).c_str(), intError);
176             return;
177         }
178 
179         auto newDisplay = std::make_unique<Display>(
180                 *mComposer.get(), mCapabilities, displayId, displayType);
181         newDisplay->setConnected(true);
182         mDisplays.emplace(displayId, std::move(newDisplay));
183     } else if (connection == Connection::Disconnected) {
184         // The display will later be destroyed by a call to
185         // destroyDisplay(). For now we just mark it disconnected.
186         auto display = getDisplayById(displayId);
187         if (display) {
188             display->setConnected(false);
189         } else {
190             ALOGW("Attempted to disconnect unknown display %" PRIu64,
191                   displayId);
192         }
193     }
194 }
195 
196 // Other Device methods
197 
getDisplayById(hwc2_display_t id)198 Display* Device::getDisplayById(hwc2_display_t id) {
199     auto iter = mDisplays.find(id);
200     return iter == mDisplays.end() ? nullptr : iter->second.get();
201 }
202 
203 // Device initialization methods
204 
loadCapabilities()205 void Device::loadCapabilities()
206 {
207     static_assert(sizeof(Capability) == sizeof(int32_t),
208             "Capability size has changed");
209     auto capabilities = mComposer->getCapabilities();
210     for (auto capability : capabilities) {
211         mCapabilities.emplace(static_cast<Capability>(capability));
212     }
213 }
214 
flushCommands()215 Error Device::flushCommands()
216 {
217     return static_cast<Error>(mComposer->executeCommands());
218 }
219 
220 // Display methods
221 
Display(android::Hwc2::Composer & composer,const std::unordered_set<Capability> & capabilities,hwc2_display_t id,DisplayType type)222 Display::Display(android::Hwc2::Composer& composer,
223                  const std::unordered_set<Capability>& capabilities, hwc2_display_t id,
224                  DisplayType type)
225       : mComposer(composer),
226         mCapabilities(capabilities),
227         mId(id),
228         mIsConnected(false),
229         mType(type) {
230     ALOGV("Created display %" PRIu64, id);
231 }
232 
~Display()233 Display::~Display() {
234     mLayers.clear();
235 
236     if (mType == DisplayType::Virtual) {
237         ALOGV("Destroying virtual display");
238         auto intError = mComposer.destroyVirtualDisplay(mId);
239         auto error = static_cast<Error>(intError);
240         ALOGE_IF(error != Error::None, "destroyVirtualDisplay(%" PRIu64
241                 ") failed: %s (%d)", mId, to_string(error).c_str(), intError);
242     } else if (mType == DisplayType::Physical) {
243         auto error = setVsyncEnabled(HWC2::Vsync::Disable);
244         if (error != Error::None) {
245             ALOGE("~Display: Failed to disable vsync for display %" PRIu64
246                     ": %s (%d)", mId, to_string(error).c_str(),
247                     static_cast<int32_t>(error));
248         }
249     }
250 }
251 
Config(Display & display,hwc2_config_t id)252 Display::Config::Config(Display& display, hwc2_config_t id)
253   : mDisplay(display),
254     mId(id),
255     mWidth(-1),
256     mHeight(-1),
257     mVsyncPeriod(-1),
258     mDpiX(-1),
259     mDpiY(-1) {}
260 
Builder(Display & display,hwc2_config_t id)261 Display::Config::Builder::Builder(Display& display, hwc2_config_t id)
262   : mConfig(new Config(display, id)) {}
263 
getDefaultDensity()264 float Display::Config::Builder::getDefaultDensity() {
265     // Default density is based on TVs: 1080p displays get XHIGH density, lower-
266     // resolution displays get TV density. Maybe eventually we'll need to update
267     // it for 4k displays, though hopefully those will just report accurate DPI
268     // information to begin with. This is also used for virtual displays and
269     // older HWC implementations, so be careful about orientation.
270 
271     auto longDimension = std::max(mConfig->mWidth, mConfig->mHeight);
272     if (longDimension >= 1080) {
273         return ACONFIGURATION_DENSITY_XHIGH;
274     } else {
275         return ACONFIGURATION_DENSITY_TV;
276     }
277 }
278 
279 // Required by HWC2 display
280 
acceptChanges()281 Error Display::acceptChanges()
282 {
283     auto intError = mComposer.acceptDisplayChanges(mId);
284     return static_cast<Error>(intError);
285 }
286 
createLayer(Layer ** outLayer)287 Error Display::createLayer(Layer** outLayer)
288 {
289     if (!outLayer) {
290         return Error::BadParameter;
291     }
292     hwc2_layer_t layerId = 0;
293     auto intError = mComposer.createLayer(mId, &layerId);
294     auto error = static_cast<Error>(intError);
295     if (error != Error::None) {
296         return error;
297     }
298 
299     auto layer = std::make_unique<Layer>(
300             mComposer, mCapabilities, mId, layerId);
301     *outLayer = layer.get();
302     mLayers.emplace(layerId, std::move(layer));
303     return Error::None;
304 }
305 
destroyLayer(Layer * layer)306 Error Display::destroyLayer(Layer* layer)
307 {
308     if (!layer) {
309         return Error::BadParameter;
310     }
311     mLayers.erase(layer->getId());
312     return Error::None;
313 }
314 
getActiveConfig(std::shared_ptr<const Display::Config> * outConfig) const315 Error Display::getActiveConfig(
316         std::shared_ptr<const Display::Config>* outConfig) const
317 {
318     ALOGV("[%" PRIu64 "] getActiveConfig", mId);
319     hwc2_config_t configId = 0;
320     auto intError = mComposer.getActiveConfig(mId, &configId);
321     auto error = static_cast<Error>(intError);
322 
323     if (error != Error::None) {
324         ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
325         *outConfig = nullptr;
326         return error;
327     }
328 
329     if (mConfigs.count(configId) != 0) {
330         *outConfig = mConfigs.at(configId);
331     } else {
332         ALOGE("[%" PRIu64 "] getActiveConfig returned unknown config %u", mId,
333                 configId);
334         // Return no error, but the caller needs to check for a null pointer to
335         // detect this case
336         *outConfig = nullptr;
337     }
338 
339     return Error::None;
340 }
341 
getActiveConfigIndex(int * outIndex) const342 Error Display::getActiveConfigIndex(int* outIndex) const {
343     ALOGV("[%" PRIu64 "] getActiveConfigIndex", mId);
344     hwc2_config_t configId = 0;
345     auto intError = mComposer.getActiveConfig(mId, &configId);
346     auto error = static_cast<Error>(intError);
347 
348     if (error != Error::None) {
349         ALOGE("Unable to get active config for mId:[%" PRIu64 "]", mId);
350         *outIndex = -1;
351         return error;
352     }
353 
354     auto pos = mConfigs.find(configId);
355     if (pos != mConfigs.end()) {
356         *outIndex = std::distance(mConfigs.begin(), pos);
357     } else {
358         ALOGE("[%" PRIu64 "] getActiveConfig returned unknown config %u", mId, configId);
359         // Return no error, but the caller needs to check for a negative index
360         // to detect this case
361         *outIndex = -1;
362     }
363 
364     return Error::None;
365 }
366 
getChangedCompositionTypes(std::unordered_map<Layer *,Composition> * outTypes)367 Error Display::getChangedCompositionTypes(
368         std::unordered_map<Layer*, Composition>* outTypes)
369 {
370     std::vector<Hwc2::Layer> layerIds;
371     std::vector<Hwc2::IComposerClient::Composition> types;
372     auto intError = mComposer.getChangedCompositionTypes(
373             mId, &layerIds, &types);
374     uint32_t numElements = layerIds.size();
375     auto error = static_cast<Error>(intError);
376     error = static_cast<Error>(intError);
377     if (error != Error::None) {
378         return error;
379     }
380 
381     outTypes->clear();
382     outTypes->reserve(numElements);
383     for (uint32_t element = 0; element < numElements; ++element) {
384         auto layer = getLayerById(layerIds[element]);
385         if (layer) {
386             auto type = static_cast<Composition>(types[element]);
387             ALOGV("getChangedCompositionTypes: adding %" PRIu64 " %s",
388                     layer->getId(), to_string(type).c_str());
389             outTypes->emplace(layer, type);
390         } else {
391             ALOGE("getChangedCompositionTypes: invalid layer %" PRIu64 " found"
392                     " on display %" PRIu64, layerIds[element], mId);
393         }
394     }
395 
396     return Error::None;
397 }
398 
getColorModes(std::vector<ColorMode> * outModes) const399 Error Display::getColorModes(std::vector<ColorMode>* outModes) const
400 {
401     auto intError = mComposer.getColorModes(mId, outModes);
402     return static_cast<Error>(intError);
403 }
404 
getSupportedPerFrameMetadata(int32_t * outSupportedPerFrameMetadata) const405 Error Display::getSupportedPerFrameMetadata(int32_t* outSupportedPerFrameMetadata) const
406 {
407     *outSupportedPerFrameMetadata = 0;
408     std::vector<Hwc2::PerFrameMetadataKey> tmpKeys;
409     auto intError = mComposer.getPerFrameMetadataKeys(mId, &tmpKeys);
410     auto error = static_cast<Error>(intError);
411     if (error != Error::None) {
412         return error;
413     }
414 
415     // Check whether a specific metadata type is supported. A metadata type is considered
416     // supported if and only if all required fields are supported.
417 
418     // SMPTE2086
419     std::set<Hwc2::PerFrameMetadataKey> keys(tmpKeys.begin(), tmpKeys.end());
420     if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X) &&
421         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y) &&
422         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X) &&
423         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y) &&
424         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X) &&
425         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y) &&
426         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::WHITE_POINT_X) &&
427         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::WHITE_POINT_Y) &&
428         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_LUMINANCE) &&
429         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MIN_LUMINANCE)) {
430         *outSupportedPerFrameMetadata |= HdrMetadata::Type::SMPTE2086;
431     }
432     // CTA861_3
433     if (hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL) &&
434         hasMetadataKey(keys, Hwc2::PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL)) {
435         *outSupportedPerFrameMetadata |= HdrMetadata::Type::CTA861_3;
436     }
437 
438     return Error::None;
439 }
440 
getRenderIntents(ColorMode colorMode,std::vector<RenderIntent> * outRenderIntents) const441 Error Display::getRenderIntents(ColorMode colorMode,
442         std::vector<RenderIntent>* outRenderIntents) const
443 {
444     auto intError = mComposer.getRenderIntents(mId, colorMode, outRenderIntents);
445     return static_cast<Error>(intError);
446 }
447 
getDataspaceSaturationMatrix(Dataspace dataspace,android::mat4 * outMatrix)448 Error Display::getDataspaceSaturationMatrix(Dataspace dataspace, android::mat4* outMatrix)
449 {
450     auto intError = mComposer.getDataspaceSaturationMatrix(dataspace, outMatrix);
451     return static_cast<Error>(intError);
452 }
453 
getConfigs() const454 std::vector<std::shared_ptr<const Display::Config>> Display::getConfigs() const
455 {
456     std::vector<std::shared_ptr<const Config>> configs;
457     for (const auto& element : mConfigs) {
458         configs.emplace_back(element.second);
459     }
460     return configs;
461 }
462 
getName(std::string * outName) const463 Error Display::getName(std::string* outName) const
464 {
465     auto intError = mComposer.getDisplayName(mId, outName);
466     return static_cast<Error>(intError);
467 }
468 
getRequests(HWC2::DisplayRequest * outDisplayRequests,std::unordered_map<Layer *,LayerRequest> * outLayerRequests)469 Error Display::getRequests(HWC2::DisplayRequest* outDisplayRequests,
470         std::unordered_map<Layer*, LayerRequest>* outLayerRequests)
471 {
472     uint32_t intDisplayRequests;
473     std::vector<Hwc2::Layer> layerIds;
474     std::vector<uint32_t> layerRequests;
475     auto intError = mComposer.getDisplayRequests(
476             mId, &intDisplayRequests, &layerIds, &layerRequests);
477     uint32_t numElements = layerIds.size();
478     auto error = static_cast<Error>(intError);
479     if (error != Error::None) {
480         return error;
481     }
482 
483     *outDisplayRequests = static_cast<DisplayRequest>(intDisplayRequests);
484     outLayerRequests->clear();
485     outLayerRequests->reserve(numElements);
486     for (uint32_t element = 0; element < numElements; ++element) {
487         auto layer = getLayerById(layerIds[element]);
488         if (layer) {
489             auto layerRequest =
490                     static_cast<LayerRequest>(layerRequests[element]);
491             outLayerRequests->emplace(layer, layerRequest);
492         } else {
493             ALOGE("getRequests: invalid layer %" PRIu64 " found on display %"
494                     PRIu64, layerIds[element], mId);
495         }
496     }
497 
498     return Error::None;
499 }
500 
getType(DisplayType * outType) const501 Error Display::getType(DisplayType* outType) const
502 {
503     *outType = mType;
504     return Error::None;
505 }
506 
supportsDoze(bool * outSupport) const507 Error Display::supportsDoze(bool* outSupport) const
508 {
509     bool intSupport = false;
510     auto intError = mComposer.getDozeSupport(mId, &intSupport);
511     auto error = static_cast<Error>(intError);
512     if (error != Error::None) {
513         return error;
514     }
515     *outSupport = static_cast<bool>(intSupport);
516     return Error::None;
517 }
518 
getHdrCapabilities(HdrCapabilities * outCapabilities) const519 Error Display::getHdrCapabilities(HdrCapabilities* outCapabilities) const
520 {
521     float maxLuminance = -1.0f;
522     float maxAverageLuminance = -1.0f;
523     float minLuminance = -1.0f;
524     std::vector<Hwc2::Hdr> types;
525     auto intError = mComposer.getHdrCapabilities(mId, &types,
526             &maxLuminance, &maxAverageLuminance, &minLuminance);
527     auto error = static_cast<HWC2::Error>(intError);
528 
529     if (error != Error::None) {
530         return error;
531     }
532 
533     *outCapabilities = HdrCapabilities(std::move(types),
534             maxLuminance, maxAverageLuminance, minLuminance);
535     return Error::None;
536 }
537 
getReleaseFences(std::unordered_map<Layer *,sp<Fence>> * outFences) const538 Error Display::getReleaseFences(
539         std::unordered_map<Layer*, sp<Fence>>* outFences) const
540 {
541     std::vector<Hwc2::Layer> layerIds;
542     std::vector<int> fenceFds;
543     auto intError = mComposer.getReleaseFences(mId, &layerIds, &fenceFds);
544     auto error = static_cast<Error>(intError);
545     uint32_t numElements = layerIds.size();
546     if (error != Error::None) {
547         return error;
548     }
549 
550     std::unordered_map<Layer*, sp<Fence>> releaseFences;
551     releaseFences.reserve(numElements);
552     for (uint32_t element = 0; element < numElements; ++element) {
553         auto layer = getLayerById(layerIds[element]);
554         if (layer) {
555             sp<Fence> fence(new Fence(fenceFds[element]));
556             releaseFences.emplace(layer, fence);
557         } else {
558             ALOGE("getReleaseFences: invalid layer %" PRIu64
559                     " found on display %" PRIu64, layerIds[element], mId);
560             for (; element < numElements; ++element) {
561                 close(fenceFds[element]);
562             }
563             return Error::BadLayer;
564         }
565     }
566 
567     *outFences = std::move(releaseFences);
568     return Error::None;
569 }
570 
present(sp<Fence> * outPresentFence)571 Error Display::present(sp<Fence>* outPresentFence)
572 {
573     int32_t presentFenceFd = -1;
574     auto intError = mComposer.presentDisplay(mId, &presentFenceFd);
575     auto error = static_cast<Error>(intError);
576     if (error != Error::None) {
577         return error;
578     }
579 
580     *outPresentFence = new Fence(presentFenceFd);
581     return Error::None;
582 }
583 
setActiveConfig(const std::shared_ptr<const Config> & config)584 Error Display::setActiveConfig(const std::shared_ptr<const Config>& config)
585 {
586     if (config->getDisplayId() != mId) {
587         ALOGE("setActiveConfig received config %u for the wrong display %"
588                 PRIu64 " (expected %" PRIu64 ")", config->getId(),
589                 config->getDisplayId(), mId);
590         return Error::BadConfig;
591     }
592     auto intError = mComposer.setActiveConfig(mId, config->getId());
593     return static_cast<Error>(intError);
594 }
595 
setClientTarget(uint32_t slot,const sp<GraphicBuffer> & target,const sp<Fence> & acquireFence,Dataspace dataspace)596 Error Display::setClientTarget(uint32_t slot, const sp<GraphicBuffer>& target,
597         const sp<Fence>& acquireFence, Dataspace dataspace)
598 {
599     // TODO: Properly encode client target surface damage
600     int32_t fenceFd = acquireFence->dup();
601     auto intError = mComposer.setClientTarget(mId, slot, target,
602             fenceFd, dataspace, std::vector<Hwc2::IComposerClient::Rect>());
603     return static_cast<Error>(intError);
604 }
605 
setColorMode(ColorMode mode,RenderIntent renderIntent)606 Error Display::setColorMode(ColorMode mode, RenderIntent renderIntent)
607 {
608     auto intError = mComposer.setColorMode(mId, mode, renderIntent);
609     return static_cast<Error>(intError);
610 }
611 
setColorTransform(const android::mat4 & matrix,android_color_transform_t hint)612 Error Display::setColorTransform(const android::mat4& matrix,
613         android_color_transform_t hint)
614 {
615     auto intError = mComposer.setColorTransform(mId,
616             matrix.asArray(), static_cast<Hwc2::ColorTransform>(hint));
617     return static_cast<Error>(intError);
618 }
619 
setOutputBuffer(const sp<GraphicBuffer> & buffer,const sp<Fence> & releaseFence)620 Error Display::setOutputBuffer(const sp<GraphicBuffer>& buffer,
621         const sp<Fence>& releaseFence)
622 {
623     int32_t fenceFd = releaseFence->dup();
624     auto handle = buffer->getNativeBuffer()->handle;
625     auto intError = mComposer.setOutputBuffer(mId, handle, fenceFd);
626     close(fenceFd);
627     return static_cast<Error>(intError);
628 }
629 
setPowerMode(PowerMode mode)630 Error Display::setPowerMode(PowerMode mode)
631 {
632     auto intMode = static_cast<Hwc2::IComposerClient::PowerMode>(mode);
633     auto intError = mComposer.setPowerMode(mId, intMode);
634     return static_cast<Error>(intError);
635 }
636 
setVsyncEnabled(Vsync enabled)637 Error Display::setVsyncEnabled(Vsync enabled)
638 {
639     auto intEnabled = static_cast<Hwc2::IComposerClient::Vsync>(enabled);
640     auto intError = mComposer.setVsyncEnabled(mId, intEnabled);
641     return static_cast<Error>(intError);
642 }
643 
validate(uint32_t * outNumTypes,uint32_t * outNumRequests)644 Error Display::validate(uint32_t* outNumTypes, uint32_t* outNumRequests)
645 {
646     uint32_t numTypes = 0;
647     uint32_t numRequests = 0;
648     auto intError = mComposer.validateDisplay(mId, &numTypes, &numRequests);
649     auto error = static_cast<Error>(intError);
650     if (error != Error::None && error != Error::HasChanges) {
651         return error;
652     }
653 
654     *outNumTypes = numTypes;
655     *outNumRequests = numRequests;
656     return error;
657 }
658 
presentOrValidate(uint32_t * outNumTypes,uint32_t * outNumRequests,sp<android::Fence> * outPresentFence,uint32_t * state)659 Error Display::presentOrValidate(uint32_t* outNumTypes, uint32_t* outNumRequests,
660                                  sp<android::Fence>* outPresentFence, uint32_t* state) {
661 
662     uint32_t numTypes = 0;
663     uint32_t numRequests = 0;
664     int32_t presentFenceFd = -1;
665     auto intError = mComposer.presentOrValidateDisplay(
666             mId, &numTypes, &numRequests, &presentFenceFd, state);
667     auto error = static_cast<Error>(intError);
668     if (error != Error::None && error != Error::HasChanges) {
669         return error;
670     }
671 
672     if (*state == 1) {
673         *outPresentFence = new Fence(presentFenceFd);
674     }
675 
676     if (*state == 0) {
677         *outNumTypes = numTypes;
678         *outNumRequests = numRequests;
679     }
680     return error;
681 }
682 
683 // For use by Device
684 
setConnected(bool connected)685 void Display::setConnected(bool connected) {
686     if (!mIsConnected && connected) {
687         mComposer.setClientTargetSlotCount(mId);
688         if (mType == DisplayType::Physical) {
689             loadConfigs();
690         }
691     }
692     mIsConnected = connected;
693 }
694 
getAttribute(hwc2_config_t configId,Attribute attribute)695 int32_t Display::getAttribute(hwc2_config_t configId, Attribute attribute)
696 {
697     int32_t value = 0;
698     auto intError = mComposer.getDisplayAttribute(mId, configId,
699             static_cast<Hwc2::IComposerClient::Attribute>(attribute),
700             &value);
701     auto error = static_cast<Error>(intError);
702     if (error != Error::None) {
703         ALOGE("getDisplayAttribute(%" PRIu64 ", %u, %s) failed: %s (%d)", mId,
704                 configId, to_string(attribute).c_str(),
705                 to_string(error).c_str(), intError);
706         return -1;
707     }
708     return value;
709 }
710 
loadConfig(hwc2_config_t configId)711 void Display::loadConfig(hwc2_config_t configId)
712 {
713     ALOGV("[%" PRIu64 "] loadConfig(%u)", mId, configId);
714 
715     auto config = Config::Builder(*this, configId)
716             .setWidth(getAttribute(configId, Attribute::Width))
717             .setHeight(getAttribute(configId, Attribute::Height))
718             .setVsyncPeriod(getAttribute(configId, Attribute::VsyncPeriod))
719             .setDpiX(getAttribute(configId, Attribute::DpiX))
720             .setDpiY(getAttribute(configId, Attribute::DpiY))
721             .build();
722     mConfigs.emplace(configId, std::move(config));
723 }
724 
loadConfigs()725 void Display::loadConfigs()
726 {
727     ALOGV("[%" PRIu64 "] loadConfigs", mId);
728 
729     std::vector<Hwc2::Config> configIds;
730     auto intError = mComposer.getDisplayConfigs(mId, &configIds);
731     auto error = static_cast<Error>(intError);
732     if (error != Error::None) {
733         ALOGE("[%" PRIu64 "] getDisplayConfigs [2] failed: %s (%d)", mId,
734                 to_string(error).c_str(), intError);
735         return;
736     }
737 
738     for (auto configId : configIds) {
739         loadConfig(configId);
740     }
741 }
742 
743 // Other Display methods
744 
getLayerById(hwc2_layer_t id) const745 Layer* Display::getLayerById(hwc2_layer_t id) const
746 {
747     if (mLayers.count(id) == 0) {
748         return nullptr;
749     }
750 
751     return mLayers.at(id).get();
752 }
753 
754 // Layer methods
755 
Layer(android::Hwc2::Composer & composer,const std::unordered_set<Capability> & capabilities,hwc2_display_t displayId,hwc2_layer_t layerId)756 Layer::Layer(android::Hwc2::Composer& composer, const std::unordered_set<Capability>& capabilities,
757              hwc2_display_t displayId, hwc2_layer_t layerId)
758   : mComposer(composer),
759     mCapabilities(capabilities),
760     mDisplayId(displayId),
761     mId(layerId)
762 {
763     ALOGV("Created layer %" PRIu64 " on display %" PRIu64, layerId, displayId);
764 }
765 
~Layer()766 Layer::~Layer()
767 {
768     auto intError = mComposer.destroyLayer(mDisplayId, mId);
769     auto error = static_cast<Error>(intError);
770     ALOGE_IF(error != Error::None, "destroyLayer(%" PRIu64 ", %" PRIu64 ")"
771             " failed: %s (%d)", mDisplayId, mId, to_string(error).c_str(),
772             intError);
773     if (mLayerDestroyedListener) {
774         mLayerDestroyedListener(this);
775     }
776 }
777 
setLayerDestroyedListener(std::function<void (Layer *)> listener)778 void Layer::setLayerDestroyedListener(std::function<void(Layer*)> listener) {
779     LOG_ALWAYS_FATAL_IF(mLayerDestroyedListener && listener,
780             "Attempt to set layer destroyed listener multiple times");
781     mLayerDestroyedListener = listener;
782 }
783 
setCursorPosition(int32_t x,int32_t y)784 Error Layer::setCursorPosition(int32_t x, int32_t y)
785 {
786     auto intError = mComposer.setCursorPosition(mDisplayId, mId, x, y);
787     return static_cast<Error>(intError);
788 }
789 
setBuffer(uint32_t slot,const sp<GraphicBuffer> & buffer,const sp<Fence> & acquireFence)790 Error Layer::setBuffer(uint32_t slot, const sp<GraphicBuffer>& buffer,
791         const sp<Fence>& acquireFence)
792 {
793     int32_t fenceFd = acquireFence->dup();
794     auto intError = mComposer.setLayerBuffer(mDisplayId, mId, slot, buffer,
795                                              fenceFd);
796     return static_cast<Error>(intError);
797 }
798 
setSurfaceDamage(const Region & damage)799 Error Layer::setSurfaceDamage(const Region& damage)
800 {
801     // We encode default full-screen damage as INVALID_RECT upstream, but as 0
802     // rects for HWC
803     Hwc2::Error intError = Hwc2::Error::NONE;
804     if (damage.isRect() && damage.getBounds() == Rect::INVALID_RECT) {
805         intError = mComposer.setLayerSurfaceDamage(mDisplayId,
806                 mId, std::vector<Hwc2::IComposerClient::Rect>());
807     } else {
808         size_t rectCount = 0;
809         auto rectArray = damage.getArray(&rectCount);
810 
811         std::vector<Hwc2::IComposerClient::Rect> hwcRects;
812         for (size_t rect = 0; rect < rectCount; ++rect) {
813             hwcRects.push_back({rectArray[rect].left, rectArray[rect].top,
814                     rectArray[rect].right, rectArray[rect].bottom});
815         }
816 
817         intError = mComposer.setLayerSurfaceDamage(mDisplayId, mId, hwcRects);
818     }
819 
820     return static_cast<Error>(intError);
821 }
822 
setBlendMode(BlendMode mode)823 Error Layer::setBlendMode(BlendMode mode)
824 {
825     auto intMode = static_cast<Hwc2::IComposerClient::BlendMode>(mode);
826     auto intError = mComposer.setLayerBlendMode(mDisplayId, mId, intMode);
827     return static_cast<Error>(intError);
828 }
829 
setColor(hwc_color_t color)830 Error Layer::setColor(hwc_color_t color)
831 {
832     Hwc2::IComposerClient::Color hwcColor{color.r, color.g, color.b, color.a};
833     auto intError = mComposer.setLayerColor(mDisplayId, mId, hwcColor);
834     return static_cast<Error>(intError);
835 }
836 
setCompositionType(Composition type)837 Error Layer::setCompositionType(Composition type)
838 {
839     auto intType = static_cast<Hwc2::IComposerClient::Composition>(type);
840     auto intError = mComposer.setLayerCompositionType(
841             mDisplayId, mId, intType);
842     return static_cast<Error>(intError);
843 }
844 
setDataspace(Dataspace dataspace)845 Error Layer::setDataspace(Dataspace dataspace)
846 {
847     if (dataspace == mDataSpace) {
848         return Error::None;
849     }
850     mDataSpace = dataspace;
851     auto intError = mComposer.setLayerDataspace(mDisplayId, mId, mDataSpace);
852     return static_cast<Error>(intError);
853 }
854 
setPerFrameMetadata(const int32_t supportedPerFrameMetadata,const android::HdrMetadata & metadata)855 Error Layer::setPerFrameMetadata(const int32_t supportedPerFrameMetadata,
856         const android::HdrMetadata& metadata)
857 {
858     if (metadata == mHdrMetadata) {
859         return Error::None;
860     }
861 
862     mHdrMetadata = metadata;
863     int validTypes = mHdrMetadata.validTypes & supportedPerFrameMetadata;
864     std::vector<Hwc2::PerFrameMetadata> perFrameMetadatas;
865     if (validTypes & HdrMetadata::SMPTE2086) {
866         perFrameMetadatas.insert(perFrameMetadatas.end(),
867                                  {{Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X,
868                                          mHdrMetadata.smpte2086.displayPrimaryRed.x},
869                                    {Hwc2::PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y,
870                                          mHdrMetadata.smpte2086.displayPrimaryRed.y},
871                                    {Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X,
872                                          mHdrMetadata.smpte2086.displayPrimaryGreen.x},
873                                    {Hwc2::PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y,
874                                          mHdrMetadata.smpte2086.displayPrimaryGreen.y},
875                                    {Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X,
876                                          mHdrMetadata.smpte2086.displayPrimaryBlue.x},
877                                    {Hwc2::PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y,
878                                          mHdrMetadata.smpte2086.displayPrimaryBlue.y},
879                                    {Hwc2::PerFrameMetadataKey::WHITE_POINT_X,
880                                          mHdrMetadata.smpte2086.whitePoint.x},
881                                    {Hwc2::PerFrameMetadataKey::WHITE_POINT_Y,
882                                          mHdrMetadata.smpte2086.whitePoint.y},
883                                    {Hwc2::PerFrameMetadataKey::MAX_LUMINANCE,
884                                          mHdrMetadata.smpte2086.maxLuminance},
885                                    {Hwc2::PerFrameMetadataKey::MIN_LUMINANCE,
886                                          mHdrMetadata.smpte2086.minLuminance}});
887     }
888 
889     if (validTypes & HdrMetadata::CTA861_3) {
890         perFrameMetadatas.insert(perFrameMetadatas.end(),
891                                  {{Hwc2::PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL,
892                                          mHdrMetadata.cta8613.maxContentLightLevel},
893                                    {Hwc2::PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL,
894                                          mHdrMetadata.cta8613.maxFrameAverageLightLevel}});
895     }
896 
897     auto intError = mComposer.setLayerPerFrameMetadata(mDisplayId, mId, perFrameMetadatas);
898     return static_cast<Error>(intError);
899 }
900 
setDisplayFrame(const Rect & frame)901 Error Layer::setDisplayFrame(const Rect& frame)
902 {
903     Hwc2::IComposerClient::Rect hwcRect{frame.left, frame.top,
904         frame.right, frame.bottom};
905     auto intError = mComposer.setLayerDisplayFrame(mDisplayId, mId, hwcRect);
906     return static_cast<Error>(intError);
907 }
908 
setPlaneAlpha(float alpha)909 Error Layer::setPlaneAlpha(float alpha)
910 {
911     auto intError = mComposer.setLayerPlaneAlpha(mDisplayId, mId, alpha);
912     return static_cast<Error>(intError);
913 }
914 
setSidebandStream(const native_handle_t * stream)915 Error Layer::setSidebandStream(const native_handle_t* stream)
916 {
917     if (mCapabilities.count(Capability::SidebandStream) == 0) {
918         ALOGE("Attempted to call setSidebandStream without checking that the "
919                 "device supports sideband streams");
920         return Error::Unsupported;
921     }
922     auto intError = mComposer.setLayerSidebandStream(mDisplayId, mId, stream);
923     return static_cast<Error>(intError);
924 }
925 
setSourceCrop(const FloatRect & crop)926 Error Layer::setSourceCrop(const FloatRect& crop)
927 {
928     Hwc2::IComposerClient::FRect hwcRect{
929         crop.left, crop.top, crop.right, crop.bottom};
930     auto intError = mComposer.setLayerSourceCrop(mDisplayId, mId, hwcRect);
931     return static_cast<Error>(intError);
932 }
933 
setTransform(Transform transform)934 Error Layer::setTransform(Transform transform)
935 {
936     auto intTransform = static_cast<Hwc2::Transform>(transform);
937     auto intError = mComposer.setLayerTransform(mDisplayId, mId, intTransform);
938     return static_cast<Error>(intError);
939 }
940 
setVisibleRegion(const Region & region)941 Error Layer::setVisibleRegion(const Region& region)
942 {
943     size_t rectCount = 0;
944     auto rectArray = region.getArray(&rectCount);
945 
946     std::vector<Hwc2::IComposerClient::Rect> hwcRects;
947     for (size_t rect = 0; rect < rectCount; ++rect) {
948         hwcRects.push_back({rectArray[rect].left, rectArray[rect].top,
949                 rectArray[rect].right, rectArray[rect].bottom});
950     }
951 
952     auto intError = mComposer.setLayerVisibleRegion(mDisplayId, mId, hwcRects);
953     return static_cast<Error>(intError);
954 }
955 
setZOrder(uint32_t z)956 Error Layer::setZOrder(uint32_t z)
957 {
958     auto intError = mComposer.setLayerZOrder(mDisplayId, mId, z);
959     return static_cast<Error>(intError);
960 }
961 
setInfo(uint32_t type,uint32_t appId)962 Error Layer::setInfo(uint32_t type, uint32_t appId)
963 {
964   auto intError = mComposer.setLayerInfo(mDisplayId, mId, type, appId);
965   return static_cast<Error>(intError);
966 }
967 
968 } // namespace HWC2
969