1 /*
2  * Copyright (C) 2022 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 #include "ComposerClient.h"
18 
19 #include <aidlcommonsupport/NativeHandle.h>
20 #include <android/binder_ibinder_platform.h>
21 
22 #include "Common.h"
23 #include "Device.h"
24 #include "GuestFrameComposer.h"
25 #include "HostFrameComposer.h"
26 #include "Time.h"
27 
28 namespace aidl::android::hardware::graphics::composer3::impl {
29 namespace {
30 
31 #define GET_DISPLAY_OR_RETURN_ERROR()                                        \
32     std::shared_ptr<Display> display = getDisplay(displayId);                \
33     if (display == nullptr) {                                                \
34         ALOGE("%s failed to get display:%" PRIu64, __FUNCTION__, displayId); \
35         return ToBinderStatus(HWC3::Error::BadDisplay);                      \
36     }
37 
38 }  // namespace
39 
40 using ::aidl::android::hardware::graphics::common::PixelFormat;
41 
42 class ComposerClient::CommandResultWriter {
43    public:
CommandResultWriter(std::vector<CommandResultPayload> * results)44     CommandResultWriter(std::vector<CommandResultPayload>* results)
45         : mIndex(0), mResults(results) {}
46 
nextCommand()47     void nextCommand() { ++mIndex; }
48 
addError(HWC3::Error error)49     void addError(HWC3::Error error) {
50         CommandError commandErrorResult;
51         commandErrorResult.commandIndex = mIndex;
52         commandErrorResult.errorCode = static_cast<int32_t>(error);
53         mResults->emplace_back(std::move(commandErrorResult));
54     }
55 
addPresentFence(int64_t displayId,::android::base::unique_fd fence)56     void addPresentFence(int64_t displayId, ::android::base::unique_fd fence) {
57         if (fence >= 0) {
58             PresentFence presentFenceResult;
59             presentFenceResult.display = displayId;
60             presentFenceResult.fence = ndk::ScopedFileDescriptor(fence.release());
61             mResults->emplace_back(std::move(presentFenceResult));
62         }
63     }
64 
addReleaseFences(int64_t displayId,std::unordered_map<int64_t,::android::base::unique_fd> layerFences)65     void addReleaseFences(int64_t displayId,
66                           std::unordered_map<int64_t, ::android::base::unique_fd> layerFences) {
67         ReleaseFences releaseFencesResult;
68         releaseFencesResult.display = displayId;
69         for (auto& [layer, layerFence] : layerFences) {
70             if (layerFence >= 0) {
71                 ReleaseFences::Layer releaseFencesLayerResult;
72                 releaseFencesLayerResult.layer = layer;
73                 releaseFencesLayerResult.fence = ndk::ScopedFileDescriptor(layerFence.release());
74                 releaseFencesResult.layers.emplace_back(std::move(releaseFencesLayerResult));
75             }
76         }
77         mResults->emplace_back(std::move(releaseFencesResult));
78     }
79 
addChanges(const DisplayChanges & changes)80     void addChanges(const DisplayChanges& changes) {
81         if (changes.compositionChanges) {
82             mResults->emplace_back(*changes.compositionChanges);
83         }
84         if (changes.displayRequestChanges) {
85             mResults->emplace_back(*changes.displayRequestChanges);
86         }
87     }
88 
addPresentOrValidateResult(int64_t displayId,PresentOrValidate::Result pov)89     void addPresentOrValidateResult(int64_t displayId, PresentOrValidate::Result pov) {
90         PresentOrValidate result;
91         result.display = displayId;
92         result.result = pov;
93         mResults->emplace_back(std::move(result));
94     }
95 
96    private:
97     int32_t mIndex = 0;
98     std::vector<CommandResultPayload>* mResults = nullptr;
99 };
100 
ComposerClient()101 ComposerClient::ComposerClient() { DEBUG_LOG("%s", __FUNCTION__); }
102 
~ComposerClient()103 ComposerClient::~ComposerClient() {
104     DEBUG_LOG("%s", __FUNCTION__);
105 
106     std::lock_guard<std::mutex> lock(mDisplaysMutex);
107 
108     destroyDisplaysLocked();
109 
110     if (mOnClientDestroyed) {
111         mOnClientDestroyed();
112     }
113 }
114 
init()115 HWC3::Error ComposerClient::init() {
116     DEBUG_LOG("%s", __FUNCTION__);
117 
118     HWC3::Error error = HWC3::Error::None;
119 
120     std::lock_guard<std::mutex> lock(mDisplaysMutex);
121 
122     mResources = std::make_unique<ComposerResources>();
123     if (!mResources) {
124         ALOGE("%s failed to allocate ComposerResources", __FUNCTION__);
125         return HWC3::Error::NoResources;
126     }
127 
128     error = mResources->init();
129     if (error != HWC3::Error::None) {
130         ALOGE("%s failed to initialize ComposerResources", __FUNCTION__);
131         return error;
132     }
133 
134     error = Device::getInstance().getComposer(&mComposer);
135     if (error != HWC3::Error::None) {
136         ALOGE("%s failed to get FrameComposer", __FUNCTION__);
137         return error;
138     }
139 
140     const auto HotplugCallback = [this](bool connected,   //
141                                         uint32_t id,      //
142                                         uint32_t width,   //
143                                         uint32_t height,  //
144                                         uint32_t dpiX,    //
145                                         uint32_t dpiY,    //
146                                         uint32_t refreshRate) {
147         handleHotplug(connected, id, width, height, dpiX, dpiY, refreshRate);
148     };
149     error = mComposer->registerOnHotplugCallback(HotplugCallback);
150     if (error != HWC3::Error::None) {
151         ALOGE("%s failed to register hotplug callback", __FUNCTION__);
152         return error;
153     }
154 
155     error = createDisplaysLocked();
156     if (error != HWC3::Error::None) {
157         ALOGE("%s failed to create displays.", __FUNCTION__);
158         return error;
159     }
160 
161     DEBUG_LOG("%s initialized!", __FUNCTION__);
162     return HWC3::Error::None;
163 }
164 
createLayer(int64_t displayId,int32_t bufferSlotCount,int64_t * layerId)165 ndk::ScopedAStatus ComposerClient::createLayer(int64_t displayId, int32_t bufferSlotCount,
166                                                int64_t* layerId) {
167     DEBUG_LOG("%s display:%" PRIu64, __FUNCTION__, displayId);
168 
169     GET_DISPLAY_OR_RETURN_ERROR();
170 
171     HWC3::Error error = display->createLayer(layerId);
172     if (error != HWC3::Error::None) {
173         ALOGE("%s: display:%" PRIu64 " failed to create layer", __FUNCTION__, displayId);
174         return ToBinderStatus(error);
175     }
176 
177     error = mResources->addLayer(displayId, *layerId, static_cast<uint32_t>(bufferSlotCount));
178     if (error != HWC3::Error::None) {
179         ALOGE("%s: display:%" PRIu64 " resources failed to create layer", __FUNCTION__, displayId);
180         return ToBinderStatus(error);
181     }
182 
183     return ToBinderStatus(HWC3::Error::None);
184 }
185 
createVirtualDisplay(int32_t,int32_t,PixelFormat,int32_t,VirtualDisplay *)186 ndk::ScopedAStatus ComposerClient::createVirtualDisplay(int32_t /*width*/, int32_t /*height*/,
187                                                         PixelFormat /*formatHint*/,
188                                                         int32_t /*outputBufferSlotCount*/,
189                                                         VirtualDisplay* /*display*/) {
190     DEBUG_LOG("%s", __FUNCTION__);
191 
192     return ToBinderStatus(HWC3::Error::Unsupported);
193 }
194 
destroyLayer(int64_t displayId,int64_t layerId)195 ndk::ScopedAStatus ComposerClient::destroyLayer(int64_t displayId, int64_t layerId) {
196     DEBUG_LOG("%s display:%" PRIu64, __FUNCTION__, displayId);
197 
198     GET_DISPLAY_OR_RETURN_ERROR();
199 
200     HWC3::Error error = display->destroyLayer(layerId);
201     if (error != HWC3::Error::None) {
202         ALOGE("%s: display:%" PRIu64 " failed to destroy layer:%" PRIu64, __FUNCTION__, displayId,
203               layerId);
204         return ToBinderStatus(error);
205     }
206 
207     error = mResources->removeLayer(displayId, layerId);
208     if (error != HWC3::Error::None) {
209         ALOGE("%s: display:%" PRIu64 " resources failed to destroy layer:%" PRIu64, __FUNCTION__,
210               displayId, layerId);
211         return ToBinderStatus(error);
212     }
213 
214     return ToBinderStatus(HWC3::Error::None);
215 }
216 
destroyVirtualDisplay(int64_t)217 ndk::ScopedAStatus ComposerClient::destroyVirtualDisplay(int64_t /*displayId*/) {
218     DEBUG_LOG("%s", __FUNCTION__);
219 
220     return ToBinderStatus(HWC3::Error::Unsupported);
221 }
222 
executeCommands(const std::vector<DisplayCommand> & commands,std::vector<CommandResultPayload> * commandResultPayloads)223 ndk::ScopedAStatus ComposerClient::executeCommands(
224     const std::vector<DisplayCommand>& commands,
225     std::vector<CommandResultPayload>* commandResultPayloads) {
226     DEBUG_LOG("%s", __FUNCTION__);
227 
228     CommandResultWriter commandResults(commandResultPayloads);
229     for (const DisplayCommand& command : commands) {
230         executeDisplayCommand(commandResults, command);
231         commandResults.nextCommand();
232     }
233 
234     return ToBinderStatus(HWC3::Error::None);
235 }
236 
getActiveConfig(int64_t displayId,int32_t * config)237 ndk::ScopedAStatus ComposerClient::getActiveConfig(int64_t displayId, int32_t* config) {
238     DEBUG_LOG("%s", __FUNCTION__);
239 
240     GET_DISPLAY_OR_RETURN_ERROR();
241 
242     return ToBinderStatus(display->getActiveConfig(config));
243 }
244 
getColorModes(int64_t displayId,std::vector<ColorMode> * colorModes)245 ndk::ScopedAStatus ComposerClient::getColorModes(int64_t displayId,
246                                                  std::vector<ColorMode>* colorModes) {
247     DEBUG_LOG("%s", __FUNCTION__);
248 
249     GET_DISPLAY_OR_RETURN_ERROR();
250 
251     return ToBinderStatus(display->getColorModes(colorModes));
252 }
253 
getDataspaceSaturationMatrix(common::Dataspace dataspace,std::vector<float> * matrix)254 ndk::ScopedAStatus ComposerClient::getDataspaceSaturationMatrix(common::Dataspace dataspace,
255                                                                 std::vector<float>* matrix) {
256     DEBUG_LOG("%s", __FUNCTION__);
257 
258     if (dataspace != common::Dataspace::SRGB_LINEAR) {
259         return ToBinderStatus(HWC3::Error::BadParameter);
260     }
261 
262     // clang-format off
263   constexpr std::array<float, 16> kUnit {
264     1.0f, 0.0f, 0.0f, 0.0f,
265     0.0f, 1.0f, 0.0f, 0.0f,
266     0.0f, 0.0f, 1.0f, 0.0f,
267     0.0f, 0.0f, 0.0f, 1.0f,
268   };
269     // clang-format on
270     matrix->clear();
271     matrix->insert(matrix->begin(), kUnit.begin(), kUnit.end());
272 
273     return ToBinderStatus(HWC3::Error::None);
274 }
275 
getDisplayAttribute(int64_t displayId,int32_t config,DisplayAttribute attribute,int32_t * value)276 ndk::ScopedAStatus ComposerClient::getDisplayAttribute(int64_t displayId, int32_t config,
277                                                        DisplayAttribute attribute, int32_t* value) {
278     DEBUG_LOG("%s", __FUNCTION__);
279 
280     GET_DISPLAY_OR_RETURN_ERROR();
281 
282     return ToBinderStatus(display->getDisplayAttribute(config, attribute, value));
283 }
284 
getDisplayCapabilities(int64_t displayId,std::vector<DisplayCapability> * outCaps)285 ndk::ScopedAStatus ComposerClient::getDisplayCapabilities(int64_t displayId,
286                                                           std::vector<DisplayCapability>* outCaps) {
287     DEBUG_LOG("%s", __FUNCTION__);
288 
289     GET_DISPLAY_OR_RETURN_ERROR();
290 
291     return ToBinderStatus(display->getDisplayCapabilities(outCaps));
292 }
293 
getDisplayConfigs(int64_t displayId,std::vector<int32_t> * outConfigs)294 ndk::ScopedAStatus ComposerClient::getDisplayConfigs(int64_t displayId,
295                                                      std::vector<int32_t>* outConfigs) {
296     DEBUG_LOG("%s", __FUNCTION__);
297 
298     GET_DISPLAY_OR_RETURN_ERROR();
299 
300     return ToBinderStatus(display->getDisplayConfigs(outConfigs));
301 }
302 
getDisplayConnectionType(int64_t displayId,DisplayConnectionType * outType)303 ndk::ScopedAStatus ComposerClient::getDisplayConnectionType(int64_t displayId,
304                                                             DisplayConnectionType* outType) {
305     DEBUG_LOG("%s", __FUNCTION__);
306 
307     GET_DISPLAY_OR_RETURN_ERROR();
308 
309     return ToBinderStatus(display->getDisplayConnectionType(outType));
310 }
311 
getDisplayIdentificationData(int64_t displayId,DisplayIdentification * outIdentification)312 ndk::ScopedAStatus ComposerClient::getDisplayIdentificationData(
313     int64_t displayId, DisplayIdentification* outIdentification) {
314     DEBUG_LOG("%s", __FUNCTION__);
315 
316     GET_DISPLAY_OR_RETURN_ERROR();
317 
318     return ToBinderStatus(display->getDisplayIdentificationData(outIdentification));
319 }
320 
getDisplayName(int64_t displayId,std::string * outName)321 ndk::ScopedAStatus ComposerClient::getDisplayName(int64_t displayId, std::string* outName) {
322     DEBUG_LOG("%s", __FUNCTION__);
323 
324     GET_DISPLAY_OR_RETURN_ERROR();
325 
326     return ToBinderStatus(display->getDisplayName(outName));
327 }
328 
getDisplayVsyncPeriod(int64_t displayId,int32_t * outVsyncPeriod)329 ndk::ScopedAStatus ComposerClient::getDisplayVsyncPeriod(int64_t displayId,
330                                                          int32_t* outVsyncPeriod) {
331     DEBUG_LOG("%s", __FUNCTION__);
332 
333     GET_DISPLAY_OR_RETURN_ERROR();
334 
335     return ToBinderStatus(display->getDisplayVsyncPeriod(outVsyncPeriod));
336 }
337 
getDisplayedContentSample(int64_t displayId,int64_t maxFrames,int64_t timestamp,DisplayContentSample * outSamples)338 ndk::ScopedAStatus ComposerClient::getDisplayedContentSample(int64_t displayId, int64_t maxFrames,
339                                                              int64_t timestamp,
340                                                              DisplayContentSample* outSamples) {
341     DEBUG_LOG("%s", __FUNCTION__);
342 
343     GET_DISPLAY_OR_RETURN_ERROR();
344 
345     return ToBinderStatus(display->getDisplayedContentSample(maxFrames, timestamp, outSamples));
346 }
347 
getDisplayedContentSamplingAttributes(int64_t displayId,DisplayContentSamplingAttributes * outAttributes)348 ndk::ScopedAStatus ComposerClient::getDisplayedContentSamplingAttributes(
349     int64_t displayId, DisplayContentSamplingAttributes* outAttributes) {
350     DEBUG_LOG("%s", __FUNCTION__);
351 
352     GET_DISPLAY_OR_RETURN_ERROR();
353 
354     return ToBinderStatus(display->getDisplayedContentSamplingAttributes(outAttributes));
355 }
356 
getDisplayPhysicalOrientation(int64_t displayId,common::Transform * outOrientation)357 ndk::ScopedAStatus ComposerClient::getDisplayPhysicalOrientation(
358     int64_t displayId, common::Transform* outOrientation) {
359     DEBUG_LOG("%s", __FUNCTION__);
360 
361     GET_DISPLAY_OR_RETURN_ERROR();
362 
363     return ToBinderStatus(display->getDisplayPhysicalOrientation(outOrientation));
364 }
365 
getHdrCapabilities(int64_t displayId,HdrCapabilities * outCapabilities)366 ndk::ScopedAStatus ComposerClient::getHdrCapabilities(int64_t displayId,
367                                                       HdrCapabilities* outCapabilities) {
368     DEBUG_LOG("%s", __FUNCTION__);
369 
370     GET_DISPLAY_OR_RETURN_ERROR();
371 
372     return ToBinderStatus(display->getHdrCapabilities(outCapabilities));
373 }
374 
getOverlaySupport(OverlayProperties *)375 ndk::ScopedAStatus ComposerClient::getOverlaySupport(OverlayProperties* /*properties*/) {
376     DEBUG_LOG("%s", __FUNCTION__);
377 
378     return ToBinderStatus(HWC3::Error::Unsupported);
379 }
380 
getMaxVirtualDisplayCount(int32_t * outCount)381 ndk::ScopedAStatus ComposerClient::getMaxVirtualDisplayCount(int32_t* outCount) {
382     DEBUG_LOG("%s", __FUNCTION__);
383 
384     // Not supported.
385     *outCount = 0;
386 
387     return ToBinderStatus(HWC3::Error::None);
388 }
389 
getPerFrameMetadataKeys(int64_t displayId,std::vector<PerFrameMetadataKey> * outKeys)390 ndk::ScopedAStatus ComposerClient::getPerFrameMetadataKeys(
391     int64_t displayId, std::vector<PerFrameMetadataKey>* outKeys) {
392     DEBUG_LOG("%s", __FUNCTION__);
393 
394     GET_DISPLAY_OR_RETURN_ERROR();
395 
396     return ToBinderStatus(display->getPerFrameMetadataKeys(outKeys));
397 }
398 
getReadbackBufferAttributes(int64_t displayId,ReadbackBufferAttributes * outAttributes)399 ndk::ScopedAStatus ComposerClient::getReadbackBufferAttributes(
400     int64_t displayId, ReadbackBufferAttributes* outAttributes) {
401     DEBUG_LOG("%s", __FUNCTION__);
402 
403     GET_DISPLAY_OR_RETURN_ERROR();
404 
405     return ToBinderStatus(display->getReadbackBufferAttributes(outAttributes));
406 }
407 
getReadbackBufferFence(int64_t displayId,ndk::ScopedFileDescriptor * outAcquireFence)408 ndk::ScopedAStatus ComposerClient::getReadbackBufferFence(
409     int64_t displayId, ndk::ScopedFileDescriptor* outAcquireFence) {
410     DEBUG_LOG("%s", __FUNCTION__);
411 
412     GET_DISPLAY_OR_RETURN_ERROR();
413 
414     return ToBinderStatus(display->getReadbackBufferFence(outAcquireFence));
415 }
416 
getRenderIntents(int64_t displayId,ColorMode mode,std::vector<RenderIntent> * outIntents)417 ndk::ScopedAStatus ComposerClient::getRenderIntents(int64_t displayId, ColorMode mode,
418                                                     std::vector<RenderIntent>* outIntents) {
419     DEBUG_LOG("%s", __FUNCTION__);
420 
421     GET_DISPLAY_OR_RETURN_ERROR();
422 
423     return ToBinderStatus(display->getRenderIntents(mode, outIntents));
424 }
425 
getSupportedContentTypes(int64_t displayId,std::vector<ContentType> * outTypes)426 ndk::ScopedAStatus ComposerClient::getSupportedContentTypes(int64_t displayId,
427                                                             std::vector<ContentType>* outTypes) {
428     DEBUG_LOG("%s", __FUNCTION__);
429 
430     GET_DISPLAY_OR_RETURN_ERROR();
431 
432     return ToBinderStatus(display->getSupportedContentTypes(outTypes));
433 }
434 
getDisplayDecorationSupport(int64_t displayId,std::optional<common::DisplayDecorationSupport> * outSupport)435 ndk::ScopedAStatus ComposerClient::getDisplayDecorationSupport(
436     int64_t displayId, std::optional<common::DisplayDecorationSupport>* outSupport) {
437     DEBUG_LOG("%s", __FUNCTION__);
438 
439     GET_DISPLAY_OR_RETURN_ERROR();
440 
441     return ToBinderStatus(display->getDecorationSupport(outSupport));
442 }
443 
registerCallback(const std::shared_ptr<IComposerCallback> & callback)444 ndk::ScopedAStatus ComposerClient::registerCallback(
445     const std::shared_ptr<IComposerCallback>& callback) {
446     DEBUG_LOG("%s", __FUNCTION__);
447 
448     const bool isFirstRegisterCallback = mCallbacks == nullptr;
449 
450     mCallbacks = callback;
451 
452     {
453         std::lock_guard<std::mutex> lock(mDisplaysMutex);
454         for (auto& [_, display] : mDisplays) {
455             display->registerCallback(callback);
456         }
457     }
458 
459     if (isFirstRegisterCallback) {
460         std::vector<int64_t> displayIds;
461         {
462             std::lock_guard<std::mutex> lock(mDisplaysMutex);
463             for (auto& [displayId, _] : mDisplays) {
464                 displayIds.push_back(displayId);
465             }
466         }
467 
468         for (auto displayId : displayIds) {
469             DEBUG_LOG("%s initial registration, hotplug connecting display:%" PRIu64, __FUNCTION__,
470                       displayId);
471             mCallbacks->onHotplug(displayId, /*connected=*/true);
472         }
473     }
474 
475     return ndk::ScopedAStatus::ok();
476 }
477 
setActiveConfig(int64_t displayId,int32_t configId)478 ndk::ScopedAStatus ComposerClient::setActiveConfig(int64_t displayId, int32_t configId) {
479     DEBUG_LOG("%s display:%" PRIu64 " config:%" PRIu32, __FUNCTION__, displayId, configId);
480 
481     GET_DISPLAY_OR_RETURN_ERROR();
482 
483     return ToBinderStatus(display->setActiveConfig(configId));
484 }
485 
setActiveConfigWithConstraints(int64_t displayId,int32_t configId,const VsyncPeriodChangeConstraints & constraints,VsyncPeriodChangeTimeline * outTimeline)486 ndk::ScopedAStatus ComposerClient::setActiveConfigWithConstraints(
487     int64_t displayId, int32_t configId, const VsyncPeriodChangeConstraints& constraints,
488     VsyncPeriodChangeTimeline* outTimeline) {
489     DEBUG_LOG("%s display:%" PRIu64 " config:%" PRIu32, __FUNCTION__, displayId, configId);
490 
491     GET_DISPLAY_OR_RETURN_ERROR();
492 
493     return ToBinderStatus(
494         display->setActiveConfigWithConstraints(configId, constraints, outTimeline));
495 }
496 
setBootDisplayConfig(int64_t displayId,int32_t configId)497 ndk::ScopedAStatus ComposerClient::setBootDisplayConfig(int64_t displayId, int32_t configId) {
498     DEBUG_LOG("%s display:%" PRIu64 " config:%" PRIu32, __FUNCTION__, displayId, configId);
499 
500     GET_DISPLAY_OR_RETURN_ERROR();
501 
502     return ToBinderStatus(display->setBootConfig(configId));
503 }
504 
clearBootDisplayConfig(int64_t displayId)505 ndk::ScopedAStatus ComposerClient::clearBootDisplayConfig(int64_t displayId) {
506     DEBUG_LOG("%s display:%" PRIu64, __FUNCTION__, displayId);
507 
508     GET_DISPLAY_OR_RETURN_ERROR();
509 
510     return ToBinderStatus(display->clearBootConfig());
511 }
512 
getPreferredBootDisplayConfig(int64_t displayId,int32_t * outConfigId)513 ndk::ScopedAStatus ComposerClient::getPreferredBootDisplayConfig(int64_t displayId,
514                                                                  int32_t* outConfigId) {
515     DEBUG_LOG("%s display:%" PRIu64, __FUNCTION__, displayId);
516 
517     GET_DISPLAY_OR_RETURN_ERROR();
518 
519     return ToBinderStatus(display->getPreferredBootConfig(outConfigId));
520 }
521 
getHdrConversionCapabilities(std::vector<aidl::android::hardware::graphics::common::HdrConversionCapability> * capabilities)522 ndk::ScopedAStatus ComposerClient::getHdrConversionCapabilities(
523     std::vector<aidl::android::hardware::graphics::common::HdrConversionCapability>* capabilities) {
524     DEBUG_LOG("%s", __FUNCTION__);
525     capabilities->clear();
526     return ToBinderStatus(HWC3::Error::None);
527 }
528 
setHdrConversionStrategy(const aidl::android::hardware::graphics::common::HdrConversionStrategy & conversionStrategy,aidl::android::hardware::graphics::common::Hdr * preferredHdrOutputType)529 ndk::ScopedAStatus ComposerClient::setHdrConversionStrategy(
530     const aidl::android::hardware::graphics::common::HdrConversionStrategy& conversionStrategy,
531     aidl::android::hardware::graphics::common::Hdr* preferredHdrOutputType) {
532     DEBUG_LOG("%s", __FUNCTION__);
533     using HdrConversionStrategyTag =
534         aidl::android::hardware::graphics::common::HdrConversionStrategy::Tag;
535     switch (conversionStrategy.getTag()) {
536         case HdrConversionStrategyTag::autoAllowedHdrTypes: {
537             auto autoHdrTypes =
538                 conversionStrategy.get<HdrConversionStrategyTag::autoAllowedHdrTypes>();
539             if (autoHdrTypes.size() != 0) {
540                 return ToBinderStatus(HWC3::Error::Unsupported);
541             }
542             break;
543         }
544         case HdrConversionStrategyTag::passthrough:
545         case HdrConversionStrategyTag::forceHdrConversion: {
546             break;
547         }
548     }
549     *preferredHdrOutputType = aidl::android::hardware::graphics::common::Hdr::INVALID;
550     return ToBinderStatus(HWC3::Error::None);
551 }
552 
setAutoLowLatencyMode(int64_t displayId,bool on)553 ndk::ScopedAStatus ComposerClient::setAutoLowLatencyMode(int64_t displayId, bool on) {
554     DEBUG_LOG("%s", __FUNCTION__);
555 
556     GET_DISPLAY_OR_RETURN_ERROR();
557 
558     return ToBinderStatus(display->setAutoLowLatencyMode(on));
559 }
560 
setClientTargetSlotCount(int64_t displayId,int32_t count)561 ndk::ScopedAStatus ComposerClient::setClientTargetSlotCount(int64_t displayId, int32_t count) {
562     DEBUG_LOG("%s", __FUNCTION__);
563 
564     GET_DISPLAY_OR_RETURN_ERROR();
565 
566     return ToBinderStatus(
567         mResources->setDisplayClientTargetCacheSize(displayId, static_cast<uint32_t>(count)));
568 }
569 
setColorMode(int64_t displayId,ColorMode mode,RenderIntent intent)570 ndk::ScopedAStatus ComposerClient::setColorMode(int64_t displayId, ColorMode mode,
571                                                 RenderIntent intent) {
572     DEBUG_LOG("%s", __FUNCTION__);
573 
574     GET_DISPLAY_OR_RETURN_ERROR();
575 
576     return ToBinderStatus(display->setColorMode(mode, intent));
577 }
578 
setContentType(int64_t displayId,ContentType type)579 ndk::ScopedAStatus ComposerClient::setContentType(int64_t displayId, ContentType type) {
580     DEBUG_LOG("%s", __FUNCTION__);
581 
582     GET_DISPLAY_OR_RETURN_ERROR();
583 
584     return ToBinderStatus(display->setContentType(type));
585 }
586 
setDisplayedContentSamplingEnabled(int64_t displayId,bool enable,FormatColorComponent componentMask,int64_t maxFrames)587 ndk::ScopedAStatus ComposerClient::setDisplayedContentSamplingEnabled(
588     int64_t displayId, bool enable, FormatColorComponent componentMask, int64_t maxFrames) {
589     DEBUG_LOG("%s", __FUNCTION__);
590 
591     GET_DISPLAY_OR_RETURN_ERROR();
592 
593     return ToBinderStatus(
594         display->setDisplayedContentSamplingEnabled(enable, componentMask, maxFrames));
595 }
596 
setPowerMode(int64_t displayId,PowerMode mode)597 ndk::ScopedAStatus ComposerClient::setPowerMode(int64_t displayId, PowerMode mode) {
598     DEBUG_LOG("%s", __FUNCTION__);
599 
600     GET_DISPLAY_OR_RETURN_ERROR();
601 
602     return ToBinderStatus(display->setPowerMode(mode));
603 }
604 
setReadbackBuffer(int64_t displayId,const aidl::android::hardware::common::NativeHandle & buffer,const ndk::ScopedFileDescriptor & releaseFence)605 ndk::ScopedAStatus ComposerClient::setReadbackBuffer(
606     int64_t displayId, const aidl::android::hardware::common::NativeHandle& buffer,
607     const ndk::ScopedFileDescriptor& releaseFence) {
608     DEBUG_LOG("%s", __FUNCTION__);
609 
610     GET_DISPLAY_OR_RETURN_ERROR();
611 
612     // Owned by mResources.
613     buffer_handle_t importedBuffer = nullptr;
614 
615     auto releaser = mResources->createReleaser(true /* isBuffer */);
616     auto error =
617         mResources->getDisplayReadbackBuffer(displayId, buffer, &importedBuffer, releaser.get());
618     if (error != HWC3::Error::None) {
619         ALOGE("%s: failed to get readback buffer from resources.", __FUNCTION__);
620         return ToBinderStatus(error);
621     }
622 
623     error = display->setReadbackBuffer(importedBuffer, releaseFence);
624     if (error != HWC3::Error::None) {
625         ALOGE("%s: failed to set readback buffer to display.", __FUNCTION__);
626         return ToBinderStatus(error);
627     }
628 
629     return ToBinderStatus(HWC3::Error::None);
630 }
631 
setVsyncEnabled(int64_t displayId,bool enabled)632 ndk::ScopedAStatus ComposerClient::setVsyncEnabled(int64_t displayId, bool enabled) {
633     DEBUG_LOG("%s", __FUNCTION__);
634 
635     GET_DISPLAY_OR_RETURN_ERROR();
636 
637     return ToBinderStatus(display->setVsyncEnabled(enabled));
638 }
639 
setIdleTimerEnabled(int64_t displayId,int32_t timeoutMs)640 ndk::ScopedAStatus ComposerClient::setIdleTimerEnabled(int64_t displayId, int32_t timeoutMs) {
641     DEBUG_LOG("%s", __FUNCTION__);
642 
643     GET_DISPLAY_OR_RETURN_ERROR();
644 
645     return ToBinderStatus(display->setIdleTimerEnabled(timeoutMs));
646 }
647 
setRefreshRateChangedCallbackDebugEnabled(int64_t displayId,bool)648 ndk::ScopedAStatus ComposerClient::setRefreshRateChangedCallbackDebugEnabled(int64_t displayId,
649                                                                              bool) {
650     DEBUG_LOG("%s", __FUNCTION__);
651 
652     GET_DISPLAY_OR_RETURN_ERROR();
653 
654     return ToBinderStatus(HWC3::Error::Unsupported);
655 }
656 
getDisplayConfigurations(int64_t displayId,int32_t,std::vector<DisplayConfiguration> * outDisplayConfig)657 ndk::ScopedAStatus ComposerClient::getDisplayConfigurations(
658     int64_t displayId, int32_t /*maxFrameIntervalNs*/,
659     std::vector<DisplayConfiguration>* outDisplayConfig) {
660     DEBUG_LOG("%s", __FUNCTION__);
661 
662     GET_DISPLAY_OR_RETURN_ERROR();
663 
664     return ToBinderStatus(display->getDisplayConfigurations(outDisplayConfig));
665 }
666 
notifyExpectedPresent(int64_t displayId,const ClockMonotonicTimestamp &,int32_t)667 ndk::ScopedAStatus ComposerClient::notifyExpectedPresent(
668     int64_t displayId, const ClockMonotonicTimestamp& /*expectedPresentTime*/,
669     int32_t /*frameIntervalNs*/) {
670     DEBUG_LOG("%s", __FUNCTION__);
671 
672     GET_DISPLAY_OR_RETURN_ERROR();
673 
674     return ToBinderStatus(HWC3::Error::Unsupported);
675 }
676 
getMaxLayerPictureProfiles(int64_t displayId,int32_t *)677 ndk::ScopedAStatus ComposerClient::getMaxLayerPictureProfiles(int64_t displayId, int32_t*) {
678     DEBUG_LOG("%s", __FUNCTION__);
679 
680     GET_DISPLAY_OR_RETURN_ERROR();
681 
682     return ToBinderStatus(HWC3::Error::Unsupported);
683 }
684 
startHdcpNegotiation(int64_t displayId,const aidl::android::hardware::drm::HdcpLevels &)685 ndk::ScopedAStatus ComposerClient::startHdcpNegotiation(int64_t displayId,
686     const aidl::android::hardware::drm::HdcpLevels& /*levels*/) {
687     DEBUG_LOG("%s", __FUNCTION__);
688 
689     GET_DISPLAY_OR_RETURN_ERROR();
690 
691     return ToBinderStatus(HWC3::Error::Unsupported);
692 }
693 
getLuts(int64_t displayId,const std::vector<Buffer> &,std::vector<Luts> *)694 ndk::ScopedAStatus ComposerClient::getLuts(int64_t displayId,
695         const std::vector<Buffer>&,
696         std::vector<Luts>*) {
697     DEBUG_LOG("%s", __FUNCTION__);
698 
699     GET_DISPLAY_OR_RETURN_ERROR();
700 
701     return ToBinderStatus(HWC3::Error::Unsupported);
702 }
703 
createBinder()704 ndk::SpAIBinder ComposerClient::createBinder() {
705     auto binder = BnComposerClient::createBinder();
706     AIBinder_setInheritRt(binder.get(), true);
707     return binder;
708 }
709 
710 namespace {
711 
712 #define DISPATCH_LAYER_COMMAND(layerCmd, commandResults, display, layer, field, funcName)         \
713     do {                                                                                          \
714         if (layerCmd.field) {                                                                     \
715             ComposerClient::executeLayerCommandSetLayer##funcName(commandResults, display, layer, \
716                                                                   *layerCmd.field);               \
717         }                                                                                         \
718     } while (0)
719 
720 #define DISPATCH_DISPLAY_COMMAND(displayCmd, commandResults, display, field, funcName)   \
721     do {                                                                                 \
722         if (displayCmd.field) {                                                          \
723             executeDisplayCommand##funcName(commandResults, display, *displayCmd.field); \
724         }                                                                                \
725     } while (0)
726 
727 #define DISPATCH_DISPLAY_BOOL_COMMAND(displayCmd, commandResults, display, field, funcName) \
728     do {                                                                                    \
729         if (displayCmd.field) {                                                             \
730             executeDisplayCommand##funcName(commandResults, display);                       \
731         }                                                                                   \
732     } while (0)
733 
734 #define DISPATCH_DISPLAY_BOOL_COMMAND_AND_DATA(displayCmd, commandResults, display, field, data, \
735                                                funcName)                                         \
736     do {                                                                                         \
737         if (displayCmd.field) {                                                                  \
738             executeDisplayCommand##funcName(commandResults, display, displayCmd.data);           \
739         }                                                                                        \
740     } while (0)
741 
742 #define LOG_DISPLAY_COMMAND_ERROR(display, error)                                      \
743     do {                                                                               \
744         const std::string errorString = toString(error);                               \
745         ALOGE("%s: display:%" PRId64 " failed with:%s", __FUNCTION__, display.getId(), \
746               errorString.c_str());                                                    \
747     } while (0)
748 
749 #define LOG_LAYER_COMMAND_ERROR(display, layer, error)                                  \
750     do {                                                                                \
751         const std::string errorString = toString(error);                                \
752         ALOGE("%s: display:%" PRId64 " layer:%" PRId64 " failed with:%s", __FUNCTION__, \
753               display.getId(), layer->getId(), errorString.c_str());                    \
754     } while (0)
755 
756 }  // namespace
757 
executeDisplayCommand(CommandResultWriter & commandResults,const DisplayCommand & displayCommand)758 void ComposerClient::executeDisplayCommand(CommandResultWriter& commandResults,
759                                            const DisplayCommand& displayCommand) {
760     std::shared_ptr<Display> display = getDisplay(displayCommand.display);
761     if (display == nullptr) {
762         commandResults.addError(HWC3::Error::BadDisplay);
763         return;
764     }
765 
766     for (const LayerCommand& layerCmd : displayCommand.layers) {
767         executeLayerCommand(commandResults, *display, layerCmd);
768     }
769 
770     DISPATCH_DISPLAY_COMMAND(displayCommand, commandResults, *display, colorTransformMatrix,
771                              SetColorTransform);
772     DISPATCH_DISPLAY_COMMAND(displayCommand, commandResults, *display, brightness, SetBrightness);
773     DISPATCH_DISPLAY_COMMAND(displayCommand, commandResults, *display, clientTarget,
774                              SetClientTarget);
775     DISPATCH_DISPLAY_COMMAND(displayCommand, commandResults, *display, virtualDisplayOutputBuffer,
776                              SetOutputBuffer);
777     DISPATCH_DISPLAY_BOOL_COMMAND_AND_DATA(displayCommand, commandResults, *display,
778                                            validateDisplay, expectedPresentTime, ValidateDisplay);
779     DISPATCH_DISPLAY_BOOL_COMMAND(displayCommand, commandResults, *display, acceptDisplayChanges,
780                                   AcceptDisplayChanges);
781     DISPATCH_DISPLAY_BOOL_COMMAND(displayCommand, commandResults, *display, presentDisplay,
782                                   PresentDisplay);
783     DISPATCH_DISPLAY_BOOL_COMMAND_AND_DATA(displayCommand, commandResults, *display,
784                                            presentOrValidateDisplay, expectedPresentTime,
785                                            PresentOrValidateDisplay);
786 }
787 
executeLayerCommand(CommandResultWriter & commandResults,Display & display,const LayerCommand & layerCommand)788 void ComposerClient::executeLayerCommand(CommandResultWriter& commandResults, Display& display,
789                                          const LayerCommand& layerCommand) {
790     Layer* layer = display.getLayer(layerCommand.layer);
791     if (layer == nullptr) {
792         commandResults.addError(HWC3::Error::BadLayer);
793         return;
794     }
795 
796     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, cursorPosition,
797                            CursorPosition);
798     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, buffer, Buffer);
799     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, damage, SurfaceDamage);
800     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, blendMode, BlendMode);
801     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, color, Color);
802     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, composition, Composition);
803     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, dataspace, Dataspace);
804     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, displayFrame,
805                            DisplayFrame);
806     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, planeAlpha, PlaneAlpha);
807     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, sidebandStream,
808                            SidebandStream);
809     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, sourceCrop, SourceCrop);
810     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, transform, Transform);
811     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, visibleRegion,
812                            VisibleRegion);
813     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, z, ZOrder);
814     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, colorTransform,
815                            ColorTransform);
816     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, brightness, Brightness);
817     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, perFrameMetadata,
818                            PerFrameMetadata);
819     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, perFrameMetadataBlob,
820                            PerFrameMetadataBlobs);
821     DISPATCH_LAYER_COMMAND(layerCommand, commandResults, display, layer, luts,
822                            Luts);
823 }
824 
executeDisplayCommandSetColorTransform(CommandResultWriter & commandResults,Display & display,const std::vector<float> & matrix)825 void ComposerClient::executeDisplayCommandSetColorTransform(CommandResultWriter& commandResults,
826                                                             Display& display,
827                                                             const std::vector<float>& matrix) {
828     DEBUG_LOG("%s", __FUNCTION__);
829 
830     auto error = display.setColorTransform(matrix);
831     if (error != HWC3::Error::None) {
832         LOG_DISPLAY_COMMAND_ERROR(display, error);
833         commandResults.addError(error);
834     }
835 }
836 
executeDisplayCommandSetBrightness(CommandResultWriter & commandResults,Display & display,const DisplayBrightness & brightness)837 void ComposerClient::executeDisplayCommandSetBrightness(CommandResultWriter& commandResults,
838                                                         Display& display,
839                                                         const DisplayBrightness& brightness) {
840     DEBUG_LOG("%s", __FUNCTION__);
841 
842     auto error = display.setBrightness(brightness.brightness);
843     if (error != HWC3::Error::None) {
844         LOG_DISPLAY_COMMAND_ERROR(display, error);
845         commandResults.addError(error);
846     }
847 }
848 
executeDisplayCommandSetClientTarget(CommandResultWriter & commandResults,Display & display,const ClientTarget & clientTarget)849 void ComposerClient::executeDisplayCommandSetClientTarget(CommandResultWriter& commandResults,
850                                                           Display& display,
851                                                           const ClientTarget& clientTarget) {
852     DEBUG_LOG("%s", __FUNCTION__);
853 
854     // Owned by mResources.
855     buffer_handle_t importedBuffer = nullptr;
856 
857     auto releaser = mResources->createReleaser(/*isBuffer=*/true);
858     auto error = mResources->getDisplayClientTarget(display.getId(), clientTarget.buffer,
859                                                     &importedBuffer, releaser.get());
860     if (error != HWC3::Error::None) {
861         LOG_DISPLAY_COMMAND_ERROR(display, error);
862         commandResults.addError(error);
863         return;
864     }
865 
866     error = display.setClientTarget(importedBuffer, clientTarget.buffer.fence,
867                                     clientTarget.dataspace, clientTarget.damage);
868     if (error != HWC3::Error::None) {
869         LOG_DISPLAY_COMMAND_ERROR(display, error);
870         commandResults.addError(error);
871         return;
872     }
873 }
874 
executeDisplayCommandSetOutputBuffer(CommandResultWriter & commandResults,Display & display,const Buffer & buffer)875 void ComposerClient::executeDisplayCommandSetOutputBuffer(CommandResultWriter& commandResults,
876                                                           Display& display, const Buffer& buffer) {
877     DEBUG_LOG("%s", __FUNCTION__);
878 
879     // Owned by mResources.
880     buffer_handle_t importedBuffer = nullptr;
881 
882     auto releaser = mResources->createReleaser(/*isBuffer=*/true);
883     auto error = mResources->getDisplayOutputBuffer(display.getId(), buffer, &importedBuffer,
884                                                     releaser.get());
885     if (error != HWC3::Error::None) {
886         LOG_DISPLAY_COMMAND_ERROR(display, error);
887         commandResults.addError(error);
888         return;
889     }
890 
891     error = display.setOutputBuffer(importedBuffer, buffer.fence);
892     if (error != HWC3::Error::None) {
893         LOG_DISPLAY_COMMAND_ERROR(display, error);
894         commandResults.addError(error);
895         return;
896     }
897 }
898 
executeDisplayCommandValidateDisplay(CommandResultWriter & commandResults,Display & display,const std::optional<ClockMonotonicTimestamp> expectedPresentTime)899 void ComposerClient::executeDisplayCommandValidateDisplay(
900     CommandResultWriter& commandResults, Display& display,
901     const std::optional<ClockMonotonicTimestamp> expectedPresentTime) {
902     DEBUG_LOG("%s", __FUNCTION__);
903 
904     auto error = display.setExpectedPresentTime(expectedPresentTime);
905     if (error != HWC3::Error::None) {
906         LOG_DISPLAY_COMMAND_ERROR(display, error);
907         commandResults.addError(error);
908     }
909 
910     DisplayChanges changes;
911 
912     error = display.validate(&changes);
913     if (error != HWC3::Error::None) {
914         LOG_DISPLAY_COMMAND_ERROR(display, error);
915         commandResults.addError(error);
916     } else {
917         commandResults.addChanges(changes);
918     }
919 
920     mResources->setDisplayMustValidateState(display.getId(), false);
921 }
922 
executeDisplayCommandAcceptDisplayChanges(CommandResultWriter & commandResults,Display & display)923 void ComposerClient::executeDisplayCommandAcceptDisplayChanges(CommandResultWriter& commandResults,
924                                                                Display& display) {
925     DEBUG_LOG("%s", __FUNCTION__);
926 
927     auto error = display.acceptChanges();
928     if (error != HWC3::Error::None) {
929         LOG_DISPLAY_COMMAND_ERROR(display, error);
930         commandResults.addError(error);
931     }
932 }
933 
executeDisplayCommandPresentOrValidateDisplay(CommandResultWriter & commandResults,Display & display,const std::optional<ClockMonotonicTimestamp> expectedPresentTime)934 void ComposerClient::executeDisplayCommandPresentOrValidateDisplay(
935     CommandResultWriter& commandResults, Display& display,
936     const std::optional<ClockMonotonicTimestamp> expectedPresentTime) {
937     DEBUG_LOG("%s", __FUNCTION__);
938 
939     // TODO: Support SKIP_VALIDATE.
940 
941     auto error = display.setExpectedPresentTime(expectedPresentTime);
942     if (error != HWC3::Error::None) {
943         LOG_DISPLAY_COMMAND_ERROR(display, error);
944         commandResults.addError(error);
945     }
946 
947     DisplayChanges changes;
948 
949     error = display.validate(&changes);
950     if (error != HWC3::Error::None) {
951         LOG_DISPLAY_COMMAND_ERROR(display, error);
952         commandResults.addError(error);
953     } else {
954         const int64_t displayId = display.getId();
955         commandResults.addChanges(changes);
956         commandResults.addPresentOrValidateResult(displayId, PresentOrValidate::Result::Validated);
957     }
958 
959     mResources->setDisplayMustValidateState(display.getId(), false);
960 }
961 
executeDisplayCommandPresentDisplay(CommandResultWriter & commandResults,Display & display)962 void ComposerClient::executeDisplayCommandPresentDisplay(CommandResultWriter& commandResults,
963                                                          Display& display) {
964     DEBUG_LOG("%s", __FUNCTION__);
965 
966     if (mResources->mustValidateDisplay(display.getId())) {
967         ALOGE("%s: display:%" PRIu64 " not validated", __FUNCTION__, display.getId());
968         commandResults.addError(HWC3::Error::NotValidated);
969         return;
970     }
971 
972     ::android::base::unique_fd displayFence;
973     std::unordered_map<int64_t, ::android::base::unique_fd> layerFences;
974 
975     auto error = display.present(&displayFence, &layerFences);
976     if (error != HWC3::Error::None) {
977         LOG_DISPLAY_COMMAND_ERROR(display, error);
978         commandResults.addError(error);
979     } else {
980         const int64_t displayId = display.getId();
981         commandResults.addPresentFence(displayId, std::move(displayFence));
982         commandResults.addReleaseFences(displayId, std::move(layerFences));
983     }
984 }
985 
executeLayerCommandSetLayerCursorPosition(CommandResultWriter & commandResults,Display & display,Layer * layer,const common::Point & cursorPosition)986 void ComposerClient::executeLayerCommandSetLayerCursorPosition(
987     CommandResultWriter& commandResults, Display& display, Layer* layer,
988     const common::Point& cursorPosition) {
989     DEBUG_LOG("%s", __FUNCTION__);
990 
991     auto error = layer->setCursorPosition(cursorPosition);
992     if (error != HWC3::Error::None) {
993         LOG_LAYER_COMMAND_ERROR(display, layer, error);
994         commandResults.addError(error);
995     }
996 }
997 
executeLayerCommandSetLayerBuffer(CommandResultWriter & commandResults,Display & display,Layer * layer,const Buffer & buffer)998 void ComposerClient::executeLayerCommandSetLayerBuffer(CommandResultWriter& commandResults,
999                                                        Display& display, Layer* layer,
1000                                                        const Buffer& buffer) {
1001     DEBUG_LOG("%s", __FUNCTION__);
1002 
1003     // Owned by mResources.
1004     buffer_handle_t importedBuffer = nullptr;
1005 
1006     auto releaser = mResources->createReleaser(/*isBuffer=*/true);
1007     auto error = mResources->getLayerBuffer(display.getId(), layer->getId(), buffer,
1008                                             &importedBuffer, releaser.get());
1009     if (error != HWC3::Error::None) {
1010         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1011         commandResults.addError(error);
1012         return;
1013     }
1014 
1015     error = layer->setBuffer(importedBuffer, buffer.fence);
1016     if (error != HWC3::Error::None) {
1017         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1018         commandResults.addError(error);
1019     }
1020 }
1021 
executeLayerCommandSetLayerSurfaceDamage(CommandResultWriter & commandResults,Display & display,Layer * layer,const std::vector<std::optional<common::Rect>> & damage)1022 void ComposerClient::executeLayerCommandSetLayerSurfaceDamage(
1023     CommandResultWriter& commandResults, Display& display, Layer* layer,
1024     const std::vector<std::optional<common::Rect>>& damage) {
1025     DEBUG_LOG("%s", __FUNCTION__);
1026 
1027     auto error = layer->setSurfaceDamage(damage);
1028     if (error != HWC3::Error::None) {
1029         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1030         commandResults.addError(error);
1031     }
1032 }
1033 
executeLayerCommandSetLayerBlendMode(CommandResultWriter & commandResults,Display & display,Layer * layer,const ParcelableBlendMode & blendMode)1034 void ComposerClient::executeLayerCommandSetLayerBlendMode(CommandResultWriter& commandResults,
1035                                                           Display& display, Layer* layer,
1036                                                           const ParcelableBlendMode& blendMode) {
1037     DEBUG_LOG("%s", __FUNCTION__);
1038 
1039     auto error = layer->setBlendMode(blendMode.blendMode);
1040     if (error != HWC3::Error::None) {
1041         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1042         commandResults.addError(error);
1043     }
1044 }
1045 
executeLayerCommandSetLayerColor(CommandResultWriter & commandResults,Display & display,Layer * layer,const Color & color)1046 void ComposerClient::executeLayerCommandSetLayerColor(CommandResultWriter& commandResults,
1047                                                       Display& display, Layer* layer,
1048                                                       const Color& color) {
1049     DEBUG_LOG("%s", __FUNCTION__);
1050 
1051     auto error = layer->setColor(color);
1052     if (error != HWC3::Error::None) {
1053         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1054         commandResults.addError(error);
1055     }
1056 }
1057 
executeLayerCommandSetLayerComposition(CommandResultWriter & commandResults,Display & display,Layer * layer,const ParcelableComposition & composition)1058 void ComposerClient::executeLayerCommandSetLayerComposition(
1059     CommandResultWriter& commandResults, Display& display, Layer* layer,
1060     const ParcelableComposition& composition) {
1061     DEBUG_LOG("%s", __FUNCTION__);
1062 
1063     auto error = layer->setCompositionType(composition.composition);
1064     if (error != HWC3::Error::None) {
1065         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1066         commandResults.addError(error);
1067     }
1068 }
1069 
executeLayerCommandSetLayerDataspace(CommandResultWriter & commandResults,Display & display,Layer * layer,const ParcelableDataspace & dataspace)1070 void ComposerClient::executeLayerCommandSetLayerDataspace(CommandResultWriter& commandResults,
1071                                                           Display& display, Layer* layer,
1072                                                           const ParcelableDataspace& dataspace) {
1073     DEBUG_LOG("%s", __FUNCTION__);
1074 
1075     auto error = layer->setDataspace(dataspace.dataspace);
1076     if (error != HWC3::Error::None) {
1077         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1078         commandResults.addError(error);
1079     }
1080 }
1081 
executeLayerCommandSetLayerDisplayFrame(CommandResultWriter & commandResults,Display & display,Layer * layer,const common::Rect & rect)1082 void ComposerClient::executeLayerCommandSetLayerDisplayFrame(CommandResultWriter& commandResults,
1083                                                              Display& display, Layer* layer,
1084                                                              const common::Rect& rect) {
1085     DEBUG_LOG("%s", __FUNCTION__);
1086 
1087     auto error = layer->setDisplayFrame(rect);
1088     if (error != HWC3::Error::None) {
1089         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1090         commandResults.addError(error);
1091     }
1092 }
1093 
executeLayerCommandSetLayerPlaneAlpha(CommandResultWriter & commandResults,Display & display,Layer * layer,const PlaneAlpha & planeAlpha)1094 void ComposerClient::executeLayerCommandSetLayerPlaneAlpha(CommandResultWriter& commandResults,
1095                                                            Display& display, Layer* layer,
1096                                                            const PlaneAlpha& planeAlpha) {
1097     DEBUG_LOG("%s", __FUNCTION__);
1098 
1099     auto error = layer->setPlaneAlpha(planeAlpha.alpha);
1100     if (error != HWC3::Error::None) {
1101         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1102         commandResults.addError(error);
1103     }
1104 }
1105 
executeLayerCommandSetLayerSidebandStream(CommandResultWriter & commandResults,Display & display,Layer * layer,const aidl::android::hardware::common::NativeHandle & handle)1106 void ComposerClient::executeLayerCommandSetLayerSidebandStream(
1107     CommandResultWriter& commandResults, Display& display, Layer* layer,
1108     const aidl::android::hardware::common::NativeHandle& handle) {
1109     DEBUG_LOG("%s", __FUNCTION__);
1110 
1111     // Owned by mResources.
1112     buffer_handle_t importedStream = nullptr;
1113 
1114     auto releaser = mResources->createReleaser(/*isBuffer=*/false);
1115     auto error = mResources->getLayerSidebandStream(display.getId(), layer->getId(), handle,
1116                                                     &importedStream, releaser.get());
1117     if (error != HWC3::Error::None) {
1118         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1119         commandResults.addError(error);
1120         return;
1121     }
1122 
1123     error = layer->setSidebandStream(importedStream);
1124     if (error != HWC3::Error::None) {
1125         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1126         commandResults.addError(error);
1127     }
1128 }
1129 
executeLayerCommandSetLayerSourceCrop(CommandResultWriter & commandResults,Display & display,Layer * layer,const common::FRect & sourceCrop)1130 void ComposerClient::executeLayerCommandSetLayerSourceCrop(CommandResultWriter& commandResults,
1131                                                            Display& display, Layer* layer,
1132                                                            const common::FRect& sourceCrop) {
1133     DEBUG_LOG("%s", __FUNCTION__);
1134 
1135     auto error = layer->setSourceCrop(sourceCrop);
1136     if (error != HWC3::Error::None) {
1137         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1138         commandResults.addError(error);
1139     }
1140 }
1141 
executeLayerCommandSetLayerTransform(CommandResultWriter & commandResults,Display & display,Layer * layer,const ParcelableTransform & transform)1142 void ComposerClient::executeLayerCommandSetLayerTransform(CommandResultWriter& commandResults,
1143                                                           Display& display, Layer* layer,
1144                                                           const ParcelableTransform& transform) {
1145     DEBUG_LOG("%s", __FUNCTION__);
1146 
1147     auto error = layer->setTransform(transform.transform);
1148     if (error != HWC3::Error::None) {
1149         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1150         commandResults.addError(error);
1151     }
1152 }
1153 
executeLayerCommandSetLayerVisibleRegion(CommandResultWriter & commandResults,Display & display,Layer * layer,const std::vector<std::optional<common::Rect>> & visibleRegion)1154 void ComposerClient::executeLayerCommandSetLayerVisibleRegion(
1155     CommandResultWriter& commandResults, Display& display, Layer* layer,
1156     const std::vector<std::optional<common::Rect>>& visibleRegion) {
1157     DEBUG_LOG("%s", __FUNCTION__);
1158 
1159     auto error = layer->setVisibleRegion(visibleRegion);
1160     if (error != HWC3::Error::None) {
1161         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1162         commandResults.addError(error);
1163     }
1164 }
1165 
executeLayerCommandSetLayerZOrder(CommandResultWriter & commandResults,Display & display,Layer * layer,const ZOrder & zOrder)1166 void ComposerClient::executeLayerCommandSetLayerZOrder(CommandResultWriter& commandResults,
1167                                                        Display& display, Layer* layer,
1168                                                        const ZOrder& zOrder) {
1169     DEBUG_LOG("%s", __FUNCTION__);
1170 
1171     auto error = layer->setZOrder(zOrder.z);
1172     if (error != HWC3::Error::None) {
1173         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1174         commandResults.addError(error);
1175     }
1176 }
1177 
executeLayerCommandSetLayerPerFrameMetadata(CommandResultWriter & commandResults,Display & display,Layer * layer,const std::vector<std::optional<PerFrameMetadata>> & perFrameMetadata)1178 void ComposerClient::executeLayerCommandSetLayerPerFrameMetadata(
1179     CommandResultWriter& commandResults, Display& display, Layer* layer,
1180     const std::vector<std::optional<PerFrameMetadata>>& perFrameMetadata) {
1181     DEBUG_LOG("%s", __FUNCTION__);
1182 
1183     auto error = layer->setPerFrameMetadata(perFrameMetadata);
1184     if (error != HWC3::Error::None) {
1185         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1186         commandResults.addError(error);
1187     }
1188 }
1189 
executeLayerCommandSetLayerColorTransform(CommandResultWriter & commandResults,Display & display,Layer * layer,const std::vector<float> & colorTransform)1190 void ComposerClient::executeLayerCommandSetLayerColorTransform(
1191     CommandResultWriter& commandResults, Display& display, Layer* layer,
1192     const std::vector<float>& colorTransform) {
1193     DEBUG_LOG("%s", __FUNCTION__);
1194 
1195     auto error = layer->setColorTransform(colorTransform);
1196     if (error != HWC3::Error::None) {
1197         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1198         commandResults.addError(error);
1199     }
1200 }
1201 
executeLayerCommandSetLayerBrightness(CommandResultWriter & commandResults,Display & display,Layer * layer,const LayerBrightness & brightness)1202 void ComposerClient::executeLayerCommandSetLayerBrightness(CommandResultWriter& commandResults,
1203                                                            Display& display, Layer* layer,
1204                                                            const LayerBrightness& brightness) {
1205     DEBUG_LOG("%s", __FUNCTION__);
1206 
1207     auto error = layer->setBrightness(brightness.brightness);
1208     if (error != HWC3::Error::None) {
1209         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1210         commandResults.addError(error);
1211     }
1212 }
1213 
executeLayerCommandSetLayerPerFrameMetadataBlobs(CommandResultWriter & commandResults,Display & display,Layer * layer,const std::vector<std::optional<PerFrameMetadataBlob>> & perFrameMetadataBlob)1214 void ComposerClient::executeLayerCommandSetLayerPerFrameMetadataBlobs(
1215     CommandResultWriter& commandResults, Display& display, Layer* layer,
1216     const std::vector<std::optional<PerFrameMetadataBlob>>& perFrameMetadataBlob) {
1217     DEBUG_LOG("%s", __FUNCTION__);
1218 
1219     auto error = layer->setPerFrameMetadataBlobs(perFrameMetadataBlob);
1220     if (error != HWC3::Error::None) {
1221         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1222         commandResults.addError(error);
1223     }
1224 }
1225 
executeLayerCommandSetLayerLuts(CommandResultWriter & commandResults,Display & display,Layer * layer,const Luts & luts)1226 void ComposerClient::executeLayerCommandSetLayerLuts(CommandResultWriter& commandResults,
1227                                                      Display& display, Layer* layer,
1228                                                      const Luts& luts) {
1229     DEBUG_LOG("%s", __FUNCTION__);
1230 
1231     auto error = layer->setLuts(luts);
1232     if (error != HWC3::Error::None) {
1233         LOG_LAYER_COMMAND_ERROR(display, layer, error);
1234         commandResults.addError(error);
1235     }
1236 }
1237 
getDisplay(int64_t displayId)1238 std::shared_ptr<Display> ComposerClient::getDisplay(int64_t displayId) {
1239     std::lock_guard<std::mutex> lock(mDisplaysMutex);
1240 
1241     auto it = mDisplays.find(displayId);
1242     if (it == mDisplays.end()) {
1243         ALOGE("%s: no display:%" PRIu64, __FUNCTION__, displayId);
1244         return nullptr;
1245     }
1246     return it->second;
1247 }
1248 
createDisplaysLocked()1249 HWC3::Error ComposerClient::createDisplaysLocked() {
1250     DEBUG_LOG("%s", __FUNCTION__);
1251 
1252     if (!mComposer) {
1253         ALOGE("%s composer not initialized!", __FUNCTION__);
1254         return HWC3::Error::NoResources;
1255     }
1256 
1257     std::vector<DisplayMultiConfigs> displays;
1258 
1259     HWC3::Error error = findDisplays(mComposer->getDrmPresenter(), &displays);
1260     if (error != HWC3::Error::None) {
1261         ALOGE("%s failed to find display configs", __FUNCTION__);
1262         return error;
1263     }
1264 
1265     for (const auto& iter : displays) {
1266         error = createDisplayLocked(iter.displayId, iter.activeConfigId, iter.configs);
1267         if (error != HWC3::Error::None) {
1268             ALOGE("%s failed to create display from config", __FUNCTION__);
1269             return error;
1270         }
1271     }
1272 
1273     return HWC3::Error::None;
1274 }
1275 
createDisplayLocked(int64_t displayId,int32_t activeConfigId,const std::vector<DisplayConfig> & configs)1276 HWC3::Error ComposerClient::createDisplayLocked(int64_t displayId, int32_t activeConfigId,
1277                                                 const std::vector<DisplayConfig>& configs) {
1278     DEBUG_LOG("%s", __FUNCTION__);
1279 
1280     if (!mComposer) {
1281         ALOGE("%s composer not initialized!", __FUNCTION__);
1282         return HWC3::Error::NoResources;
1283     }
1284 
1285     auto display = std::make_shared<Display>(mComposer, displayId);
1286     if (display == nullptr) {
1287         ALOGE("%s failed to allocate display", __FUNCTION__);
1288         return HWC3::Error::NoResources;
1289     }
1290 
1291     HWC3::Error error = display->init(configs, activeConfigId);
1292     if (error != HWC3::Error::None) {
1293         ALOGE("%s failed to initialize display:%" PRIu64, __FUNCTION__, displayId);
1294         return error;
1295     }
1296 
1297     error = mComposer->onDisplayCreate(display.get());
1298     if (error != HWC3::Error::None) {
1299         ALOGE("%s failed to register display:%" PRIu64 " with composer", __FUNCTION__, displayId);
1300         return error;
1301     }
1302 
1303     display->setPowerMode(PowerMode::ON);
1304 
1305     DEBUG_LOG("%s: adding display:%" PRIu64, __FUNCTION__, displayId);
1306     mDisplays.emplace(displayId, std::move(display));
1307 
1308     error = mResources->addPhysicalDisplay(displayId);
1309     if (error != HWC3::Error::None) {
1310         ALOGE("%s failed to initialize display:%" PRIu64 " resources", __FUNCTION__, displayId);
1311         return error;
1312     }
1313 
1314     return HWC3::Error::None;
1315 }
1316 
destroyDisplaysLocked()1317 HWC3::Error ComposerClient::destroyDisplaysLocked() {
1318     DEBUG_LOG("%s", __FUNCTION__);
1319 
1320     std::vector<int64_t> displayIds;
1321     for (const auto& [displayId, _] : mDisplays) {
1322         displayIds.push_back(displayId);
1323     }
1324     for (const int64_t displayId : displayIds) {
1325         destroyDisplayLocked(displayId);
1326     }
1327 
1328     return HWC3::Error::None;
1329 }
1330 
destroyDisplayLocked(int64_t displayId)1331 HWC3::Error ComposerClient::destroyDisplayLocked(int64_t displayId) {
1332     DEBUG_LOG("%s display:%" PRId64, __FUNCTION__, displayId);
1333 
1334     auto it = mDisplays.find(displayId);
1335     if (it == mDisplays.end()) {
1336         ALOGE("%s: display:%" PRId64 " no such display?", __FUNCTION__, displayId);
1337         return HWC3::Error::BadDisplay;
1338     }
1339 
1340     Display* display = it->second.get();
1341 
1342     display->setPowerMode(PowerMode::OFF);
1343 
1344     HWC3::Error error = mComposer->onDisplayDestroy(it->second.get());
1345     if (error != HWC3::Error::None) {
1346         ALOGE("%s: display:%" PRId64 " failed to destroy with frame composer", __FUNCTION__,
1347               displayId);
1348     }
1349 
1350     error = mResources->removeDisplay(displayId);
1351     if (error != HWC3::Error::None) {
1352         ALOGE("%s: display:%" PRId64 " failed to destroy with resources", __FUNCTION__, displayId);
1353     }
1354 
1355     mDisplays.erase(it);
1356 
1357     return HWC3::Error::None;
1358 }
1359 
handleHotplug(bool connected,uint32_t id,uint32_t width,uint32_t height,uint32_t dpiX,uint32_t dpiY,uint32_t refreshRateHz)1360 HWC3::Error ComposerClient::handleHotplug(bool connected, uint32_t id, uint32_t width,
1361                                           uint32_t height, uint32_t dpiX, uint32_t dpiY,
1362                                           uint32_t refreshRateHz) {
1363     if (!mCallbacks) {
1364         return HWC3::Error::None;
1365     }
1366 
1367     const int64_t displayId = static_cast<int64_t>(id);
1368 
1369     if (connected) {
1370         const int32_t configId = static_cast<int32_t>(id);
1371         int32_t vsyncPeriodNanos = HertzToPeriodNanos(refreshRateHz);
1372         const std::vector<DisplayConfig> configs = {
1373             DisplayConfig(configId, static_cast<int>(width), static_cast<int>(height),
1374                           static_cast<int>(dpiX), static_cast<int>(dpiY), vsyncPeriodNanos)};
1375         {
1376             std::lock_guard<std::mutex> lock(mDisplaysMutex);
1377             createDisplayLocked(displayId, configId, configs);
1378         }
1379 
1380         ALOGI("Hotplug connecting display:%" PRIu32 " w:%" PRIu32 " h:%" PRIu32 " dpiX:%" PRIu32
1381               " dpiY %" PRIu32 "fps %" PRIu32,
1382               id, width, height, dpiX, dpiY, refreshRateHz);
1383         mCallbacks->onHotplug(displayId, /*connected=*/true);
1384     } else {
1385         ALOGI("Hotplug disconnecting display:%" PRIu64, displayId);
1386         mCallbacks->onHotplug(displayId, /*connected=*/false);
1387 
1388         {
1389             std::lock_guard<std::mutex> lock(mDisplaysMutex);
1390             destroyDisplayLocked(displayId);
1391         }
1392     }
1393 
1394     return HWC3::Error::None;
1395 }
1396 
1397 }  // namespace aidl::android::hardware::graphics::composer3::impl
1398