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