1 /*
2  * Copyright 2021 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 #undef LOG_TAG
18 #define LOG_TAG "HwcComposer"
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 
21 #include "AidlComposerHal.h"
22 
23 #include <SurfaceFlingerProperties.h>
24 #include <android-base/file.h>
25 #include <android/binder_ibinder_platform.h>
26 #include <android/binder_manager.h>
27 #include <common/FlagManager.h>
28 #include <gui/TraceUtils.h>
29 #include <log/log.h>
30 #include <utils/Trace.h>
31 
32 #include <aidl/android/hardware/graphics/composer3/BnComposerCallback.h>
33 
34 #include <algorithm>
35 #include <cinttypes>
36 
37 #include "HWC2.h"
38 
39 namespace android {
40 
41 using hardware::hidl_handle;
42 using hardware::hidl_vec;
43 using hardware::Return;
44 
45 using aidl::android::hardware::graphics::composer3::BnComposerCallback;
46 using aidl::android::hardware::graphics::composer3::Capability;
47 using aidl::android::hardware::graphics::composer3::ClientTargetPropertyWithBrightness;
48 using aidl::android::hardware::graphics::composer3::PowerMode;
49 using aidl::android::hardware::graphics::composer3::VirtualDisplay;
50 
51 using aidl::android::hardware::graphics::composer3::CommandResultPayload;
52 
53 using AidlColorMode = aidl::android::hardware::graphics::composer3::ColorMode;
54 using AidlContentType = aidl::android::hardware::graphics::composer3::ContentType;
55 using AidlDisplayIdentification =
56         aidl::android::hardware::graphics::composer3::DisplayIdentification;
57 using AidlDisplayContentSample = aidl::android::hardware::graphics::composer3::DisplayContentSample;
58 using AidlDisplayAttribute = aidl::android::hardware::graphics::composer3::DisplayAttribute;
59 using AidlDisplayCapability = aidl::android::hardware::graphics::composer3::DisplayCapability;
60 using AidlHdrCapabilities = aidl::android::hardware::graphics::composer3::HdrCapabilities;
61 using AidlHdrConversionCapability =
62         aidl::android::hardware::graphics::common::HdrConversionCapability;
63 using AidlHdrConversionStrategy = aidl::android::hardware::graphics::common::HdrConversionStrategy;
64 using AidlOverlayProperties = aidl::android::hardware::graphics::composer3::OverlayProperties;
65 using AidlPerFrameMetadata = aidl::android::hardware::graphics::composer3::PerFrameMetadata;
66 using AidlPerFrameMetadataKey = aidl::android::hardware::graphics::composer3::PerFrameMetadataKey;
67 using AidlPerFrameMetadataBlob = aidl::android::hardware::graphics::composer3::PerFrameMetadataBlob;
68 using AidlRenderIntent = aidl::android::hardware::graphics::composer3::RenderIntent;
69 using AidlVsyncPeriodChangeConstraints =
70         aidl::android::hardware::graphics::composer3::VsyncPeriodChangeConstraints;
71 using AidlVsyncPeriodChangeTimeline =
72         aidl::android::hardware::graphics::composer3::VsyncPeriodChangeTimeline;
73 using AidlDisplayContentSamplingAttributes =
74         aidl::android::hardware::graphics::composer3::DisplayContentSamplingAttributes;
75 using AidlFormatColorComponent = aidl::android::hardware::graphics::composer3::FormatColorComponent;
76 using AidlDisplayConnectionType =
77         aidl::android::hardware::graphics::composer3::DisplayConnectionType;
78 
79 using AidlColorTransform = aidl::android::hardware::graphics::common::ColorTransform;
80 using AidlDataspace = aidl::android::hardware::graphics::common::Dataspace;
81 using AidlDisplayHotplugEvent = aidl::android::hardware::graphics::common::DisplayHotplugEvent;
82 using AidlFRect = aidl::android::hardware::graphics::common::FRect;
83 using AidlRect = aidl::android::hardware::graphics::common::Rect;
84 using AidlTransform = aidl::android::hardware::graphics::common::Transform;
85 
86 namespace Hwc2 {
87 
88 namespace {
89 
90 template <typename To, typename From>
translate(From x)91 To translate(From x) {
92     return static_cast<To>(x);
93 }
94 
95 template <typename To, typename From>
translate(const std::vector<From> & in)96 std::vector<To> translate(const std::vector<From>& in) {
97     std::vector<To> out;
98     out.reserve(in.size());
99     std::transform(in.begin(), in.end(), std::back_inserter(out),
100                    [](From x) { return translate<To>(x); });
101     return out;
102 }
103 
104 template <>
translate(IComposerClient::Rect x)105 AidlRect translate(IComposerClient::Rect x) {
106     return AidlRect{
107             .left = x.left,
108             .top = x.top,
109             .right = x.right,
110             .bottom = x.bottom,
111     };
112 }
113 
114 template <>
translate(IComposerClient::FRect x)115 AidlFRect translate(IComposerClient::FRect x) {
116     return AidlFRect{
117             .left = x.left,
118             .top = x.top,
119             .right = x.right,
120             .bottom = x.bottom,
121     };
122 }
123 
124 template <>
translate(IComposerClient::PerFrameMetadataBlob x)125 AidlPerFrameMetadataBlob translate(IComposerClient::PerFrameMetadataBlob x) {
126     AidlPerFrameMetadataBlob blob;
127     blob.key = translate<AidlPerFrameMetadataKey>(x.key),
128     std::copy(x.blob.begin(), x.blob.end(), std::inserter(blob.blob, blob.blob.end()));
129     return blob;
130 }
131 
132 template <>
translate(IComposerClient::PerFrameMetadata x)133 AidlPerFrameMetadata translate(IComposerClient::PerFrameMetadata x) {
134     return AidlPerFrameMetadata{
135             .key = translate<AidlPerFrameMetadataKey>(x.key),
136             .value = x.value,
137     };
138 }
139 
140 template <>
translate(AidlDisplayContentSample x)141 DisplayedFrameStats translate(AidlDisplayContentSample x) {
142     return DisplayedFrameStats{
143             .numFrames = static_cast<uint64_t>(x.frameCount),
144             .component_0_sample = translate<uint64_t>(x.sampleComponent0),
145             .component_1_sample = translate<uint64_t>(x.sampleComponent1),
146             .component_2_sample = translate<uint64_t>(x.sampleComponent2),
147             .component_3_sample = translate<uint64_t>(x.sampleComponent3),
148     };
149 }
150 
151 template <>
translate(IComposerClient::VsyncPeriodChangeConstraints x)152 AidlVsyncPeriodChangeConstraints translate(IComposerClient::VsyncPeriodChangeConstraints x) {
153     return AidlVsyncPeriodChangeConstraints{
154             .desiredTimeNanos = x.desiredTimeNanos,
155             .seamlessRequired = x.seamlessRequired,
156     };
157 }
158 
159 template <>
translate(AidlVsyncPeriodChangeTimeline x)160 VsyncPeriodChangeTimeline translate(AidlVsyncPeriodChangeTimeline x) {
161     return VsyncPeriodChangeTimeline{
162             .newVsyncAppliedTimeNanos = x.newVsyncAppliedTimeNanos,
163             .refreshRequired = x.refreshRequired,
164             .refreshTimeNanos = x.refreshTimeNanos,
165     };
166 }
makeMat4(std::vector<float> in)167 mat4 makeMat4(std::vector<float> in) {
168     return mat4(static_cast<const float*>(in.data()));
169 }
170 
171 } // namespace
172 
173 class AidlIComposerCallbackWrapper : public BnComposerCallback {
174 public:
AidlIComposerCallbackWrapper(HWC2::ComposerCallback & callback)175     AidlIComposerCallbackWrapper(HWC2::ComposerCallback& callback) : mCallback(callback) {}
176 
onHotplug(int64_t in_display,bool in_connected)177     ::ndk::ScopedAStatus onHotplug(int64_t in_display, bool in_connected) override {
178         const auto event = in_connected ? AidlDisplayHotplugEvent::CONNECTED
179                                         : AidlDisplayHotplugEvent::DISCONNECTED;
180         mCallback.onComposerHalHotplugEvent(translate<Display>(in_display), event);
181         return ::ndk::ScopedAStatus::ok();
182     }
183 
onRefresh(int64_t in_display)184     ::ndk::ScopedAStatus onRefresh(int64_t in_display) override {
185         mCallback.onComposerHalRefresh(translate<Display>(in_display));
186         return ::ndk::ScopedAStatus::ok();
187     }
188 
onSeamlessPossible(int64_t in_display)189     ::ndk::ScopedAStatus onSeamlessPossible(int64_t in_display) override {
190         mCallback.onComposerHalSeamlessPossible(translate<Display>(in_display));
191         return ::ndk::ScopedAStatus::ok();
192     }
193 
onVsync(int64_t in_display,int64_t in_timestamp,int32_t in_vsyncPeriodNanos)194     ::ndk::ScopedAStatus onVsync(int64_t in_display, int64_t in_timestamp,
195                                  int32_t in_vsyncPeriodNanos) override {
196         mCallback.onComposerHalVsync(translate<Display>(in_display), in_timestamp,
197                                      static_cast<uint32_t>(in_vsyncPeriodNanos));
198         return ::ndk::ScopedAStatus::ok();
199     }
200 
onVsyncPeriodTimingChanged(int64_t in_display,const AidlVsyncPeriodChangeTimeline & in_updatedTimeline)201     ::ndk::ScopedAStatus onVsyncPeriodTimingChanged(
202             int64_t in_display, const AidlVsyncPeriodChangeTimeline& in_updatedTimeline) override {
203         mCallback.onComposerHalVsyncPeriodTimingChanged(translate<Display>(in_display),
204                                                         translate<V2_4::VsyncPeriodChangeTimeline>(
205                                                                 in_updatedTimeline));
206         return ::ndk::ScopedAStatus::ok();
207     }
208 
onVsyncIdle(int64_t in_display)209     ::ndk::ScopedAStatus onVsyncIdle(int64_t in_display) override {
210         mCallback.onComposerHalVsyncIdle(translate<Display>(in_display));
211         return ::ndk::ScopedAStatus::ok();
212     }
213 
onRefreshRateChangedDebug(const RefreshRateChangedDebugData & refreshRateChangedDebugData)214     ::ndk::ScopedAStatus onRefreshRateChangedDebug(
215             const RefreshRateChangedDebugData& refreshRateChangedDebugData) override {
216         mCallback.onRefreshRateChangedDebug(refreshRateChangedDebugData);
217         return ::ndk::ScopedAStatus::ok();
218     }
219 
onHotplugEvent(int64_t in_display,AidlDisplayHotplugEvent event)220     ::ndk::ScopedAStatus onHotplugEvent(int64_t in_display,
221                                         AidlDisplayHotplugEvent event) override {
222         mCallback.onComposerHalHotplugEvent(translate<Display>(in_display), event);
223         return ::ndk::ScopedAStatus::ok();
224     }
225 
226 private:
227     HWC2::ComposerCallback& mCallback;
228 };
229 
instance(const std::string & serviceName)230 std::string AidlComposer::instance(const std::string& serviceName) {
231     return std::string(AidlIComposer::descriptor) + "/" + serviceName;
232 }
233 
isDeclared(const std::string & serviceName)234 bool AidlComposer::isDeclared(const std::string& serviceName) {
235     return AServiceManager_isDeclared(instance(serviceName).c_str());
236 }
237 
AidlComposer(const std::string & serviceName)238 AidlComposer::AidlComposer(const std::string& serviceName) {
239     // This only waits if the service is actually declared
240     mAidlComposer = AidlIComposer::fromBinder(
241             ndk::SpAIBinder(AServiceManager_waitForService(instance(serviceName).c_str())));
242     if (!mAidlComposer) {
243         LOG_ALWAYS_FATAL("Failed to get AIDL composer service");
244         return;
245     }
246 
247     if (!mAidlComposer->createClient(&mAidlComposerClient).isOk()) {
248         LOG_ALWAYS_FATAL("Can't create AidlComposerClient, fallback to HIDL");
249         return;
250     }
251 
252     addReader(translate<Display>(kSingleReaderKey));
253 
254     // If unable to read interface version, then become backwards compatible.
255     const auto status = mAidlComposerClient->getInterfaceVersion(&mComposerInterfaceVersion);
256     if (!status.isOk()) {
257         ALOGE("getInterfaceVersion for AidlComposer constructor failed %s",
258               status.getDescription().c_str());
259     }
260 
261     if (mComposerInterfaceVersion <= 1) {
262         if (sysprop::clear_slots_with_set_layer_buffer(false)) {
263             mClearSlotBuffer = sp<GraphicBuffer>::make(1, 1, PIXEL_FORMAT_RGBX_8888,
264                                                        GraphicBuffer::USAGE_HW_COMPOSER |
265                                                                GraphicBuffer::USAGE_SW_READ_OFTEN |
266                                                                GraphicBuffer::USAGE_SW_WRITE_OFTEN,
267                                                        "AidlComposer");
268             if (!mClearSlotBuffer || mClearSlotBuffer->initCheck() != ::android::OK) {
269                 LOG_ALWAYS_FATAL("Failed to allocate a buffer for clearing layer buffer slots");
270                 return;
271             }
272         }
273     }
274     if (getLayerLifecycleBatchCommand()) {
275         mEnableLayerCommandBatchingFlag =
276                 FlagManager::getInstance().enable_layer_command_batching();
277     }
278     ALOGI("Loaded AIDL composer3 HAL service");
279 }
280 
281 AidlComposer::~AidlComposer() = default;
282 
isSupported(OptionalFeature feature) const283 bool AidlComposer::isSupported(OptionalFeature feature) const {
284     switch (feature) {
285         case OptionalFeature::RefreshRateSwitching:
286         case OptionalFeature::ExpectedPresentTime:
287         case OptionalFeature::DisplayBrightnessCommand:
288         case OptionalFeature::KernelIdleTimer:
289         case OptionalFeature::PhysicalDisplayOrientation:
290             return true;
291     }
292 }
293 
isVrrSupported() const294 bool AidlComposer::isVrrSupported() const {
295     return mComposerInterfaceVersion >= 3 && FlagManager::getInstance().vrr_config();
296 }
297 
getCapabilities()298 std::vector<Capability> AidlComposer::getCapabilities() {
299     std::vector<Capability> capabilities;
300     const auto status = mAidlComposer->getCapabilities(&capabilities);
301     if (!status.isOk()) {
302         ALOGE("getCapabilities failed %s", status.getDescription().c_str());
303         return {};
304     }
305     return capabilities;
306 }
307 
dumpDebugInfo()308 std::string AidlComposer::dumpDebugInfo() {
309     int pipefds[2];
310     int result = pipe(pipefds);
311     if (result < 0) {
312         ALOGE("dumpDebugInfo: pipe failed: %s", strerror(errno));
313         return {};
314     }
315 
316     std::string str;
317     // Use other thread to read pipe to prevent
318     // pipe is full, making HWC be blocked in writing.
319     std::thread t([&]() {
320         base::ReadFdToString(pipefds[0], &str);
321     });
322     const auto status = mAidlComposer->dump(pipefds[1], /*args*/ nullptr, /*numArgs*/ 0);
323     // Close the write-end of the pipe to make sure that when reading from the
324     // read-end we will get eof instead of blocking forever
325     close(pipefds[1]);
326 
327     if (status != STATUS_OK) {
328         ALOGE("dumpDebugInfo: dump failed: %d", status);
329     }
330 
331     t.join();
332     close(pipefds[0]);
333 
334     std::string hash;
335     mAidlComposer->getInterfaceHash(&hash);
336     return std::string(mAidlComposer->descriptor) +
337             " version:" + std::to_string(mComposerInterfaceVersion) + " hash:" + hash + str;
338 }
339 
registerCallback(HWC2::ComposerCallback & callback)340 void AidlComposer::registerCallback(HWC2::ComposerCallback& callback) {
341     if (mAidlComposerCallback) {
342         ALOGE("Callback already registered");
343     }
344 
345     mAidlComposerCallback = ndk::SharedRefBase::make<AidlIComposerCallbackWrapper>(callback);
346 
347     ndk::SpAIBinder binder = mAidlComposerCallback->asBinder();
348     AIBinder_setMinSchedulerPolicy(binder.get(), SCHED_FIFO, 2);
349 
350     const auto status = mAidlComposerClient->registerCallback(mAidlComposerCallback);
351     if (!status.isOk()) {
352         ALOGE("registerCallback failed %s", status.getDescription().c_str());
353     }
354 }
355 
executeCommands(Display display)356 Error AidlComposer::executeCommands(Display display) {
357     mMutex.lock_shared();
358     auto error = execute(display);
359     mMutex.unlock_shared();
360     return error;
361 }
362 
getMaxVirtualDisplayCount()363 uint32_t AidlComposer::getMaxVirtualDisplayCount() {
364     int32_t count = 0;
365     const auto status = mAidlComposerClient->getMaxVirtualDisplayCount(&count);
366     if (!status.isOk()) {
367         ALOGE("getMaxVirtualDisplayCount failed %s", status.getDescription().c_str());
368         return 0;
369     }
370     return static_cast<uint32_t>(count);
371 }
372 
createVirtualDisplay(uint32_t width,uint32_t height,PixelFormat * format,Display * outDisplay)373 Error AidlComposer::createVirtualDisplay(uint32_t width, uint32_t height, PixelFormat* format,
374                                          Display* outDisplay) {
375     using AidlPixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
376     const int32_t bufferSlotCount = 1;
377     VirtualDisplay virtualDisplay;
378     const auto status =
379             mAidlComposerClient->createVirtualDisplay(static_cast<int32_t>(width),
380                                                       static_cast<int32_t>(height),
381                                                       static_cast<AidlPixelFormat>(*format),
382                                                       bufferSlotCount, &virtualDisplay);
383 
384     if (!status.isOk()) {
385         ALOGE("createVirtualDisplay failed %s", status.getDescription().c_str());
386         return static_cast<Error>(status.getServiceSpecificError());
387     }
388 
389     *outDisplay = translate<Display>(virtualDisplay.display);
390     *format = static_cast<PixelFormat>(virtualDisplay.format);
391     addDisplay(translate<Display>(virtualDisplay.display));
392     return Error::NONE;
393 }
394 
destroyVirtualDisplay(Display display)395 Error AidlComposer::destroyVirtualDisplay(Display display) {
396     const auto status = mAidlComposerClient->destroyVirtualDisplay(translate<int64_t>(display));
397     if (!status.isOk()) {
398         ALOGE("destroyVirtualDisplay failed %s", status.getDescription().c_str());
399         return static_cast<Error>(status.getServiceSpecificError());
400     }
401     removeDisplay(display);
402     return Error::NONE;
403 }
404 
acceptDisplayChanges(Display display)405 Error AidlComposer::acceptDisplayChanges(Display display) {
406     Error error = Error::NONE;
407     mMutex.lock_shared();
408     if (auto writer = getWriter(display)) {
409         writer->get().acceptDisplayChanges(translate<int64_t>(display));
410     } else {
411         error = Error::BAD_DISPLAY;
412     }
413     mMutex.unlock_shared();
414     return error;
415 }
416 
createLayer(Display display,Layer * outLayer)417 Error AidlComposer::createLayer(Display display, Layer* outLayer) {
418     int64_t layer;
419     Error error = Error::NONE;
420     if (!mEnableLayerCommandBatchingFlag) {
421         const auto status = mAidlComposerClient->createLayer(translate<int64_t>(display),
422                                                              kMaxLayerBufferCount, &layer);
423         if (!status.isOk()) {
424             ALOGE("createLayer failed %s", status.getDescription().c_str());
425             return static_cast<Error>(status.getServiceSpecificError());
426         }
427     } else {
428         // generate a unique layerID. map in AidlComposer with <SF_layerID, HWC_layerID>
429         // Add this as a new displayCommand in execute command.
430         // return the SF generated layerID instead of calling HWC
431         layer = mLayerID++;
432         mMutex.lock_shared();
433         if (auto writer = getWriter(display)) {
434             writer->get().setLayerLifecycleBatchCommandType(translate<int64_t>(display),
435                                                             translate<int64_t>(layer),
436                                                             LayerLifecycleBatchCommandType::CREATE);
437             writer->get().setNewBufferSlotCount(translate<int64_t>(display),
438                                                 translate<int64_t>(layer), kMaxLayerBufferCount);
439         } else {
440             error = Error::BAD_DISPLAY;
441         }
442         mMutex.unlock_shared();
443     }
444     *outLayer = translate<Layer>(layer);
445     return error;
446 }
447 
destroyLayer(Display display,Layer layer)448 Error AidlComposer::destroyLayer(Display display, Layer layer) {
449     Error error = Error::NONE;
450     if (!mEnableLayerCommandBatchingFlag) {
451         const auto status = mAidlComposerClient->destroyLayer(translate<int64_t>(display),
452                                                               translate<int64_t>(layer));
453         if (!status.isOk()) {
454             ALOGE("destroyLayer failed %s", status.getDescription().c_str());
455             return static_cast<Error>(status.getServiceSpecificError());
456         }
457     } else {
458         mMutex.lock_shared();
459         if (auto writer = getWriter(display)) {
460             writer->get()
461                     .setLayerLifecycleBatchCommandType(translate<int64_t>(display),
462                                                        translate<int64_t>(layer),
463                                                        LayerLifecycleBatchCommandType::DESTROY);
464         } else {
465             error = Error::BAD_DISPLAY;
466         }
467         mMutex.unlock_shared();
468     }
469 
470     return error;
471 }
472 
getActiveConfig(Display display,Config * outConfig)473 Error AidlComposer::getActiveConfig(Display display, Config* outConfig) {
474     int32_t config;
475     const auto status = mAidlComposerClient->getActiveConfig(translate<int64_t>(display), &config);
476     if (!status.isOk()) {
477         ALOGE("getActiveConfig failed %s", status.getDescription().c_str());
478         return static_cast<Error>(status.getServiceSpecificError());
479     }
480     *outConfig = translate<Config>(config);
481     return Error::NONE;
482 }
483 
getChangedCompositionTypes(Display display,std::vector<Layer> * outLayers,std::vector<aidl::android::hardware::graphics::composer3::Composition> * outTypes)484 Error AidlComposer::getChangedCompositionTypes(
485         Display display, std::vector<Layer>* outLayers,
486         std::vector<aidl::android::hardware::graphics::composer3::Composition>* outTypes) {
487     std::vector<ChangedCompositionLayer> changedLayers;
488     Error error = Error::NONE;
489     {
490         mMutex.lock_shared();
491         if (auto reader = getReader(display)) {
492             changedLayers = reader->get().takeChangedCompositionTypes(translate<int64_t>(display));
493         } else {
494             error = Error::BAD_DISPLAY;
495         }
496         mMutex.unlock_shared();
497     }
498     outLayers->reserve(changedLayers.size());
499     outTypes->reserve(changedLayers.size());
500 
501     for (const auto& layer : changedLayers) {
502         outLayers->emplace_back(translate<Layer>(layer.layer));
503         outTypes->emplace_back(layer.composition);
504     }
505     return error;
506 }
507 
getColorModes(Display display,std::vector<ColorMode> * outModes)508 Error AidlComposer::getColorModes(Display display, std::vector<ColorMode>* outModes) {
509     std::vector<AidlColorMode> modes;
510     const auto status = mAidlComposerClient->getColorModes(translate<int64_t>(display), &modes);
511     if (!status.isOk()) {
512         ALOGE("getColorModes failed %s", status.getDescription().c_str());
513         return static_cast<Error>(status.getServiceSpecificError());
514     }
515     *outModes = translate<ColorMode>(modes);
516     return Error::NONE;
517 }
518 
getDisplayAttribute(Display display,Config config,IComposerClient::Attribute attribute,int32_t * outValue)519 Error AidlComposer::getDisplayAttribute(Display display, Config config,
520                                         IComposerClient::Attribute attribute, int32_t* outValue) {
521     const auto status =
522             mAidlComposerClient->getDisplayAttribute(translate<int64_t>(display),
523                                                      translate<int32_t>(config),
524                                                      static_cast<AidlDisplayAttribute>(attribute),
525                                                      outValue);
526     if (!status.isOk()) {
527         ALOGE("getDisplayAttribute failed %s", status.getDescription().c_str());
528         return static_cast<Error>(status.getServiceSpecificError());
529     }
530     return Error::NONE;
531 }
532 
getDisplayConfigs(Display display,std::vector<Config> * outConfigs)533 Error AidlComposer::getDisplayConfigs(Display display, std::vector<Config>* outConfigs) {
534     std::vector<int32_t> configs;
535     const auto status =
536             mAidlComposerClient->getDisplayConfigs(translate<int64_t>(display), &configs);
537     if (!status.isOk()) {
538         ALOGE("getDisplayConfigs failed %s", status.getDescription().c_str());
539         return static_cast<Error>(status.getServiceSpecificError());
540     }
541     *outConfigs = translate<Config>(configs);
542     return Error::NONE;
543 }
544 
getDisplayConfigurations(Display display,int32_t maxFrameIntervalNs,std::vector<DisplayConfiguration> * outConfigs)545 Error AidlComposer::getDisplayConfigurations(Display display, int32_t maxFrameIntervalNs,
546                                              std::vector<DisplayConfiguration>* outConfigs) {
547     const auto status =
548             mAidlComposerClient->getDisplayConfigurations(translate<int64_t>(display),
549                                                           maxFrameIntervalNs, outConfigs);
550     if (!status.isOk()) {
551         ALOGE("getDisplayConfigurations failed %s", status.getDescription().c_str());
552         return static_cast<Error>(status.getServiceSpecificError());
553     }
554 
555     return Error::NONE;
556 }
557 
getDisplayName(Display display,std::string * outName)558 Error AidlComposer::getDisplayName(Display display, std::string* outName) {
559     const auto status = mAidlComposerClient->getDisplayName(translate<int64_t>(display), outName);
560     if (!status.isOk()) {
561         ALOGE("getDisplayName failed %s", status.getDescription().c_str());
562         return static_cast<Error>(status.getServiceSpecificError());
563     }
564     return Error::NONE;
565 }
566 
getDisplayRequests(Display display,uint32_t * outDisplayRequestMask,std::vector<Layer> * outLayers,std::vector<uint32_t> * outLayerRequestMasks)567 Error AidlComposer::getDisplayRequests(Display display, uint32_t* outDisplayRequestMask,
568                                        std::vector<Layer>* outLayers,
569                                        std::vector<uint32_t>* outLayerRequestMasks) {
570     Error error = Error::NONE;
571     DisplayRequest displayRequests;
572     {
573         mMutex.lock_shared();
574         if (auto reader = getReader(display)) {
575             displayRequests = reader->get().takeDisplayRequests(translate<int64_t>(display));
576         } else {
577             error = Error::BAD_DISPLAY;
578         }
579         mMutex.unlock_shared();
580     }
581     *outDisplayRequestMask = translate<uint32_t>(displayRequests.mask);
582     outLayers->reserve(displayRequests.layerRequests.size());
583     outLayerRequestMasks->reserve(displayRequests.layerRequests.size());
584 
585     for (const auto& layer : displayRequests.layerRequests) {
586         outLayers->emplace_back(translate<Layer>(layer.layer));
587         outLayerRequestMasks->emplace_back(translate<uint32_t>(layer.mask));
588     }
589     return error;
590 }
591 
getDozeSupport(Display display,bool * outSupport)592 Error AidlComposer::getDozeSupport(Display display, bool* outSupport) {
593     std::vector<AidlDisplayCapability> capabilities;
594     const auto status =
595             mAidlComposerClient->getDisplayCapabilities(translate<int64_t>(display), &capabilities);
596     if (!status.isOk()) {
597         ALOGE("getDisplayCapabilities failed %s", status.getDescription().c_str());
598         return static_cast<Error>(status.getServiceSpecificError());
599     }
600     *outSupport = std::find(capabilities.begin(), capabilities.end(),
601                             AidlDisplayCapability::DOZE) != capabilities.end();
602     return Error::NONE;
603 }
604 
hasDisplayIdleTimerCapability(Display display,bool * outSupport)605 Error AidlComposer::hasDisplayIdleTimerCapability(Display display, bool* outSupport) {
606     std::vector<AidlDisplayCapability> capabilities;
607     const auto status =
608             mAidlComposerClient->getDisplayCapabilities(translate<int64_t>(display), &capabilities);
609     if (!status.isOk()) {
610         ALOGE("getDisplayCapabilities failed %s", status.getDescription().c_str());
611         return static_cast<Error>(status.getServiceSpecificError());
612     }
613     *outSupport = std::find(capabilities.begin(), capabilities.end(),
614                             AidlDisplayCapability::DISPLAY_IDLE_TIMER) != capabilities.end();
615     return Error::NONE;
616 }
617 
getHdrCapabilities(Display display,std::vector<Hdr> * outTypes,float * outMaxLuminance,float * outMaxAverageLuminance,float * outMinLuminance)618 Error AidlComposer::getHdrCapabilities(Display display, std::vector<Hdr>* outTypes,
619                                        float* outMaxLuminance, float* outMaxAverageLuminance,
620                                        float* outMinLuminance) {
621     AidlHdrCapabilities capabilities;
622     const auto status =
623             mAidlComposerClient->getHdrCapabilities(translate<int64_t>(display), &capabilities);
624     if (!status.isOk()) {
625         ALOGE("getHdrCapabilities failed %s", status.getDescription().c_str());
626         return static_cast<Error>(status.getServiceSpecificError());
627     }
628 
629     *outTypes = capabilities.types;
630     *outMaxLuminance = capabilities.maxLuminance;
631     *outMaxAverageLuminance = capabilities.maxAverageLuminance;
632     *outMinLuminance = capabilities.minLuminance;
633     return Error::NONE;
634 }
635 
getLayerLifecycleBatchCommand()636 bool AidlComposer::getLayerLifecycleBatchCommand() {
637     std::vector<Capability> capabilities = getCapabilities();
638     bool hasCapability = std::find(capabilities.begin(), capabilities.end(),
639                                    Capability::LAYER_LIFECYCLE_BATCH_COMMAND) != capabilities.end();
640     return hasCapability;
641 }
642 
getOverlaySupport(AidlOverlayProperties * outProperties)643 Error AidlComposer::getOverlaySupport(AidlOverlayProperties* outProperties) {
644     const auto status = mAidlComposerClient->getOverlaySupport(outProperties);
645     if (!status.isOk()) {
646         ALOGE("getOverlaySupport failed %s", status.getDescription().c_str());
647         return static_cast<Error>(status.getServiceSpecificError());
648     }
649     return Error::NONE;
650 }
651 
getReleaseFences(Display display,std::vector<Layer> * outLayers,std::vector<int> * outReleaseFences)652 Error AidlComposer::getReleaseFences(Display display, std::vector<Layer>* outLayers,
653                                      std::vector<int>* outReleaseFences) {
654     Error error = Error::NONE;
655     std::vector<ReleaseFences::Layer> fences;
656     {
657         mMutex.lock_shared();
658         if (auto reader = getReader(display)) {
659             fences = reader->get().takeReleaseFences(translate<int64_t>(display));
660         } else {
661             error = Error::BAD_DISPLAY;
662         }
663         mMutex.unlock_shared();
664     }
665     outLayers->reserve(fences.size());
666     outReleaseFences->reserve(fences.size());
667 
668     for (auto& fence : fences) {
669         outLayers->emplace_back(translate<Layer>(fence.layer));
670         // take ownership
671         const int fenceOwner = fence.fence.get();
672         *fence.fence.getR() = -1;
673         outReleaseFences->emplace_back(fenceOwner);
674     }
675     return error;
676 }
677 
presentDisplay(Display display,int * outPresentFence)678 Error AidlComposer::presentDisplay(Display display, int* outPresentFence) {
679     const auto displayId = translate<int64_t>(display);
680     ATRACE_FORMAT("HwcPresentDisplay %" PRId64, displayId);
681 
682     Error error = Error::NONE;
683     mMutex.lock_shared();
684     auto writer = getWriter(display);
685     auto reader = getReader(display);
686     if (writer && reader) {
687         writer->get().presentDisplay(displayId);
688         error = execute(display);
689     } else {
690         error = Error::BAD_DISPLAY;
691     }
692 
693     if (error != Error::NONE) {
694         mMutex.unlock_shared();
695         return error;
696     }
697 
698     auto fence = reader->get().takePresentFence(displayId);
699     mMutex.unlock_shared();
700     // take ownership
701     *outPresentFence = fence.get();
702     *fence.getR() = -1;
703     return Error::NONE;
704 }
705 
setActiveConfig(Display display,Config config)706 Error AidlComposer::setActiveConfig(Display display, Config config) {
707     const auto status = mAidlComposerClient->setActiveConfig(translate<int64_t>(display),
708                                                              translate<int32_t>(config));
709     if (!status.isOk()) {
710         ALOGE("setActiveConfig failed %s", status.getDescription().c_str());
711         return static_cast<Error>(status.getServiceSpecificError());
712     }
713     return Error::NONE;
714 }
715 
setClientTarget(Display display,uint32_t slot,const sp<GraphicBuffer> & target,int acquireFence,Dataspace dataspace,const std::vector<IComposerClient::Rect> & damage,float hdrSdrRatio)716 Error AidlComposer::setClientTarget(Display display, uint32_t slot, const sp<GraphicBuffer>& target,
717                                     int acquireFence, Dataspace dataspace,
718                                     const std::vector<IComposerClient::Rect>& damage,
719                                     float hdrSdrRatio) {
720     const native_handle_t* handle = nullptr;
721     if (target.get()) {
722         handle = target->getNativeBuffer()->handle;
723     }
724 
725     Error error = Error::NONE;
726     mMutex.lock_shared();
727     if (auto writer = getWriter(display)) {
728         writer->get()
729                 .setClientTarget(translate<int64_t>(display), slot, handle, acquireFence,
730                                  translate<aidl::android::hardware::graphics::common::Dataspace>(
731                                          dataspace),
732                                  translate<AidlRect>(damage), hdrSdrRatio);
733     } else {
734         error = Error::BAD_DISPLAY;
735     }
736     mMutex.unlock_shared();
737     return error;
738 }
739 
setColorMode(Display display,ColorMode mode,RenderIntent renderIntent)740 Error AidlComposer::setColorMode(Display display, ColorMode mode, RenderIntent renderIntent) {
741     const auto status =
742             mAidlComposerClient->setColorMode(translate<int64_t>(display),
743                                               translate<AidlColorMode>(mode),
744                                               translate<AidlRenderIntent>(renderIntent));
745     if (!status.isOk()) {
746         ALOGE("setColorMode failed %s", status.getDescription().c_str());
747         return static_cast<Error>(status.getServiceSpecificError());
748     }
749     return Error::NONE;
750 }
751 
setColorTransform(Display display,const float * matrix)752 Error AidlComposer::setColorTransform(Display display, const float* matrix) {
753     auto error = Error::NONE;
754     mMutex.lock_shared();
755     if (auto writer = getWriter(display)) {
756         writer->get().setColorTransform(translate<int64_t>(display), matrix);
757     } else {
758         error = Error::BAD_DISPLAY;
759     }
760     mMutex.unlock_shared();
761     return error;
762 }
763 
setOutputBuffer(Display display,const native_handle_t * buffer,int releaseFence)764 Error AidlComposer::setOutputBuffer(Display display, const native_handle_t* buffer,
765                                     int releaseFence) {
766     auto error = Error::NONE;
767     mMutex.lock_shared();
768     if (auto writer = getWriter(display)) {
769         writer->get().setOutputBuffer(translate<int64_t>(display), 0, buffer, dup(releaseFence));
770     } else {
771         error = Error::BAD_DISPLAY;
772     }
773     mMutex.unlock_shared();
774     return error;
775 }
776 
setPowerMode(Display display,IComposerClient::PowerMode mode)777 Error AidlComposer::setPowerMode(Display display, IComposerClient::PowerMode mode) {
778     const auto status = mAidlComposerClient->setPowerMode(translate<int64_t>(display),
779                                                           translate<PowerMode>(mode));
780     if (!status.isOk()) {
781         ALOGE("setPowerMode failed %s", status.getDescription().c_str());
782         return static_cast<Error>(status.getServiceSpecificError());
783     }
784     return Error::NONE;
785 }
786 
setVsyncEnabled(Display display,IComposerClient::Vsync enabled)787 Error AidlComposer::setVsyncEnabled(Display display, IComposerClient::Vsync enabled) {
788     const bool enableVsync = enabled == IComposerClient::Vsync::ENABLE;
789     const auto status =
790             mAidlComposerClient->setVsyncEnabled(translate<int64_t>(display), enableVsync);
791     if (!status.isOk()) {
792         ALOGE("setVsyncEnabled failed %s", status.getDescription().c_str());
793         return static_cast<Error>(status.getServiceSpecificError());
794     }
795     return Error::NONE;
796 }
797 
setClientTargetSlotCount(Display display)798 Error AidlComposer::setClientTargetSlotCount(Display display) {
799     const int32_t bufferSlotCount = BufferQueue::NUM_BUFFER_SLOTS;
800     const auto status = mAidlComposerClient->setClientTargetSlotCount(translate<int64_t>(display),
801                                                                       bufferSlotCount);
802     if (!status.isOk()) {
803         ALOGE("setClientTargetSlotCount failed %s", status.getDescription().c_str());
804         return static_cast<Error>(status.getServiceSpecificError());
805     }
806     return Error::NONE;
807 }
808 
validateDisplay(Display display,nsecs_t expectedPresentTime,int32_t frameIntervalNs,uint32_t * outNumTypes,uint32_t * outNumRequests)809 Error AidlComposer::validateDisplay(Display display, nsecs_t expectedPresentTime,
810                                     int32_t frameIntervalNs, uint32_t* outNumTypes,
811                                     uint32_t* outNumRequests) {
812     const auto displayId = translate<int64_t>(display);
813     ATRACE_FORMAT("HwcValidateDisplay %" PRId64, displayId);
814 
815     Error error = Error::NONE;
816     mMutex.lock_shared();
817     auto writer = getWriter(display);
818     auto reader = getReader(display);
819     if (writer && reader) {
820         writer->get().validateDisplay(displayId, ClockMonotonicTimestamp{expectedPresentTime},
821                                       frameIntervalNs);
822         error = execute(display);
823     } else {
824         error = Error::BAD_DISPLAY;
825     }
826 
827     if (error != Error::NONE) {
828         mMutex.unlock_shared();
829         return error;
830     }
831 
832     reader->get().hasChanges(displayId, outNumTypes, outNumRequests);
833 
834     mMutex.unlock_shared();
835     return Error::NONE;
836 }
837 
presentOrValidateDisplay(Display display,nsecs_t expectedPresentTime,int32_t frameIntervalNs,uint32_t * outNumTypes,uint32_t * outNumRequests,int * outPresentFence,uint32_t * state)838 Error AidlComposer::presentOrValidateDisplay(Display display, nsecs_t expectedPresentTime,
839                                              int32_t frameIntervalNs, uint32_t* outNumTypes,
840                                              uint32_t* outNumRequests, int* outPresentFence,
841                                              uint32_t* state) {
842     const auto displayId = translate<int64_t>(display);
843     ATRACE_FORMAT("HwcPresentOrValidateDisplay %" PRId64, displayId);
844 
845     Error error = Error::NONE;
846     mMutex.lock_shared();
847     auto writer = getWriter(display);
848     auto reader = getReader(display);
849     if (writer && reader) {
850         writer->get().presentOrvalidateDisplay(displayId,
851                                                ClockMonotonicTimestamp{expectedPresentTime},
852                                                frameIntervalNs);
853         error = execute(display);
854     } else {
855         error = Error::BAD_DISPLAY;
856     }
857 
858     if (error != Error::NONE) {
859         mMutex.unlock_shared();
860         return error;
861     }
862 
863     const auto result = reader->get().takePresentOrValidateStage(displayId);
864     if (!result.has_value()) {
865         *state = translate<uint32_t>(-1);
866         mMutex.unlock_shared();
867         return Error::NO_RESOURCES;
868     }
869 
870     *state = translate<uint32_t>(*result);
871 
872     if (*result == PresentOrValidate::Result::Presented) {
873         auto fence = reader->get().takePresentFence(displayId);
874         // take ownership
875         *outPresentFence = fence.get();
876         *fence.getR() = -1;
877     }
878 
879     if (*result == PresentOrValidate::Result::Validated) {
880         reader->get().hasChanges(displayId, outNumTypes, outNumRequests);
881     }
882 
883     mMutex.unlock_shared();
884     return Error::NONE;
885 }
886 
setCursorPosition(Display display,Layer layer,int32_t x,int32_t y)887 Error AidlComposer::setCursorPosition(Display display, Layer layer, int32_t x, int32_t y) {
888     Error error = Error::NONE;
889     mMutex.lock_shared();
890     if (auto writer = getWriter(display)) {
891         writer->get().setLayerCursorPosition(translate<int64_t>(display), translate<int64_t>(layer),
892                                              x, y);
893     } else {
894         error = Error::BAD_DISPLAY;
895     }
896     mMutex.unlock_shared();
897     return error;
898 }
899 
setLayerBuffer(Display display,Layer layer,uint32_t slot,const sp<GraphicBuffer> & buffer,int acquireFence)900 Error AidlComposer::setLayerBuffer(Display display, Layer layer, uint32_t slot,
901                                    const sp<GraphicBuffer>& buffer, int acquireFence) {
902     const native_handle_t* handle = nullptr;
903     if (buffer.get()) {
904         handle = buffer->getNativeBuffer()->handle;
905     }
906 
907     Error error = Error::NONE;
908     mMutex.lock_shared();
909     if (auto writer = getWriter(display)) {
910         writer->get().setLayerBuffer(translate<int64_t>(display), translate<int64_t>(layer), slot,
911                                      handle, acquireFence);
912     } else {
913         error = Error::BAD_DISPLAY;
914     }
915     mMutex.unlock_shared();
916     return error;
917 }
918 
setLayerBufferSlotsToClear(Display display,Layer layer,const std::vector<uint32_t> & slotsToClear,uint32_t activeBufferSlot)919 Error AidlComposer::setLayerBufferSlotsToClear(Display display, Layer layer,
920                                                const std::vector<uint32_t>& slotsToClear,
921                                                uint32_t activeBufferSlot) {
922     if (slotsToClear.empty()) {
923         return Error::NONE;
924     }
925 
926     Error error = Error::NONE;
927     mMutex.lock_shared();
928     if (auto writer = getWriter(display)) {
929         if (mComposerInterfaceVersion > 1) {
930             writer->get().setLayerBufferSlotsToClear(translate<int64_t>(display),
931                                                      translate<int64_t>(layer), slotsToClear);
932             // Backwards compatible way of clearing buffer slots is to set the layer buffer with a
933             // placeholder buffer, using the slot that needs to cleared... tricky.
934         } else if (mClearSlotBuffer != nullptr) {
935             for (uint32_t slot : slotsToClear) {
936                 // Don't clear the active buffer slot because we need to restore the active buffer
937                 // after clearing the requested buffer slots with a placeholder buffer.
938                 if (slot != activeBufferSlot) {
939                     writer->get().setLayerBufferWithNewCommand(translate<int64_t>(display),
940                                                                translate<int64_t>(layer), slot,
941                                                                mClearSlotBuffer->handle,
942                                                                /*fence*/ -1);
943                 }
944             }
945             // Since we clear buffers by setting them to a placeholder buffer, we want to make
946             // sure that the last setLayerBuffer command is sent with the currently active
947             // buffer, not the placeholder buffer, so that there is no perceptual change when
948             // buffers are discarded.
949             writer->get().setLayerBufferWithNewCommand(translate<int64_t>(display),
950                                                        translate<int64_t>(layer), activeBufferSlot,
951                                                        // The active buffer is still cached in
952                                                        // its slot and doesn't need a fence.
953                                                        /*buffer*/ nullptr, /*fence*/ -1);
954         }
955     } else {
956         error = Error::BAD_DISPLAY;
957     }
958     mMutex.unlock_shared();
959     return error;
960 }
961 
setLayerSurfaceDamage(Display display,Layer layer,const std::vector<IComposerClient::Rect> & damage)962 Error AidlComposer::setLayerSurfaceDamage(Display display, Layer layer,
963                                           const std::vector<IComposerClient::Rect>& damage) {
964     Error error = Error::NONE;
965     mMutex.lock_shared();
966     if (auto writer = getWriter(display)) {
967         writer->get().setLayerSurfaceDamage(translate<int64_t>(display), translate<int64_t>(layer),
968                                             translate<AidlRect>(damage));
969     } else {
970         error = Error::BAD_DISPLAY;
971     }
972     mMutex.unlock_shared();
973     return error;
974 }
975 
setLayerBlendMode(Display display,Layer layer,IComposerClient::BlendMode mode)976 Error AidlComposer::setLayerBlendMode(Display display, Layer layer,
977                                       IComposerClient::BlendMode mode) {
978     Error error = Error::NONE;
979     mMutex.lock_shared();
980     if (auto writer = getWriter(display)) {
981         writer->get().setLayerBlendMode(translate<int64_t>(display), translate<int64_t>(layer),
982                                         translate<BlendMode>(mode));
983     } else {
984         error = Error::BAD_DISPLAY;
985     }
986     mMutex.unlock_shared();
987     return error;
988 }
989 
setLayerColor(Display display,Layer layer,const Color & color)990 Error AidlComposer::setLayerColor(Display display, Layer layer, const Color& color) {
991     Error error = Error::NONE;
992     mMutex.lock_shared();
993     if (auto writer = getWriter(display)) {
994         writer->get().setLayerColor(translate<int64_t>(display), translate<int64_t>(layer), color);
995     } else {
996         error = Error::BAD_DISPLAY;
997     }
998     mMutex.unlock_shared();
999     return error;
1000 }
1001 
setLayerCompositionType(Display display,Layer layer,aidl::android::hardware::graphics::composer3::Composition type)1002 Error AidlComposer::setLayerCompositionType(
1003         Display display, Layer layer,
1004         aidl::android::hardware::graphics::composer3::Composition type) {
1005     Error error = Error::NONE;
1006     mMutex.lock_shared();
1007     if (auto writer = getWriter(display)) {
1008         writer->get().setLayerCompositionType(translate<int64_t>(display),
1009                                               translate<int64_t>(layer), type);
1010     } else {
1011         error = Error::BAD_DISPLAY;
1012     }
1013     mMutex.unlock_shared();
1014     return error;
1015 }
1016 
setLayerDataspace(Display display,Layer layer,Dataspace dataspace)1017 Error AidlComposer::setLayerDataspace(Display display, Layer layer, Dataspace dataspace) {
1018     Error error = Error::NONE;
1019     mMutex.lock_shared();
1020     if (auto writer = getWriter(display)) {
1021         writer->get().setLayerDataspace(translate<int64_t>(display), translate<int64_t>(layer),
1022                                         translate<AidlDataspace>(dataspace));
1023     } else {
1024         error = Error::BAD_DISPLAY;
1025     }
1026     mMutex.unlock_shared();
1027     return error;
1028 }
1029 
setLayerDisplayFrame(Display display,Layer layer,const IComposerClient::Rect & frame)1030 Error AidlComposer::setLayerDisplayFrame(Display display, Layer layer,
1031                                          const IComposerClient::Rect& frame) {
1032     Error error = Error::NONE;
1033     mMutex.lock_shared();
1034     if (auto writer = getWriter(display)) {
1035         writer->get().setLayerDisplayFrame(translate<int64_t>(display), translate<int64_t>(layer),
1036                                            translate<AidlRect>(frame));
1037     } else {
1038         error = Error::BAD_DISPLAY;
1039     }
1040     mMutex.unlock_shared();
1041     return error;
1042 }
1043 
setLayerPlaneAlpha(Display display,Layer layer,float alpha)1044 Error AidlComposer::setLayerPlaneAlpha(Display display, Layer layer, float alpha) {
1045     Error error = Error::NONE;
1046     mMutex.lock_shared();
1047     if (auto writer = getWriter(display)) {
1048         writer->get().setLayerPlaneAlpha(translate<int64_t>(display), translate<int64_t>(layer),
1049                                          alpha);
1050     } else {
1051         error = Error::BAD_DISPLAY;
1052     }
1053     mMutex.unlock_shared();
1054     return error;
1055 }
1056 
setLayerSidebandStream(Display display,Layer layer,const native_handle_t * stream)1057 Error AidlComposer::setLayerSidebandStream(Display display, Layer layer,
1058                                            const native_handle_t* stream) {
1059     Error error = Error::NONE;
1060     mMutex.lock_shared();
1061     if (auto writer = getWriter(display)) {
1062         writer->get().setLayerSidebandStream(translate<int64_t>(display), translate<int64_t>(layer),
1063                                              stream);
1064     } else {
1065         error = Error::BAD_DISPLAY;
1066     }
1067     mMutex.unlock_shared();
1068     return error;
1069 }
1070 
setLayerSourceCrop(Display display,Layer layer,const IComposerClient::FRect & crop)1071 Error AidlComposer::setLayerSourceCrop(Display display, Layer layer,
1072                                        const IComposerClient::FRect& crop) {
1073     Error error = Error::NONE;
1074     mMutex.lock_shared();
1075     if (auto writer = getWriter(display)) {
1076         writer->get().setLayerSourceCrop(translate<int64_t>(display), translate<int64_t>(layer),
1077                                          translate<AidlFRect>(crop));
1078     } else {
1079         error = Error::BAD_DISPLAY;
1080     }
1081     mMutex.unlock_shared();
1082     return error;
1083 }
1084 
setLayerTransform(Display display,Layer layer,Transform transform)1085 Error AidlComposer::setLayerTransform(Display display, Layer layer, Transform transform) {
1086     Error error = Error::NONE;
1087     mMutex.lock_shared();
1088     if (auto writer = getWriter(display)) {
1089         writer->get().setLayerTransform(translate<int64_t>(display), translate<int64_t>(layer),
1090                                         translate<AidlTransform>(transform));
1091     } else {
1092         error = Error::BAD_DISPLAY;
1093     }
1094     mMutex.unlock_shared();
1095     return error;
1096 }
1097 
setLayerVisibleRegion(Display display,Layer layer,const std::vector<IComposerClient::Rect> & visible)1098 Error AidlComposer::setLayerVisibleRegion(Display display, Layer layer,
1099                                           const std::vector<IComposerClient::Rect>& visible) {
1100     Error error = Error::NONE;
1101     mMutex.lock_shared();
1102     if (auto writer = getWriter(display)) {
1103         writer->get().setLayerVisibleRegion(translate<int64_t>(display), translate<int64_t>(layer),
1104                                             translate<AidlRect>(visible));
1105     } else {
1106         error = Error::BAD_DISPLAY;
1107     }
1108     mMutex.unlock_shared();
1109     return error;
1110 }
1111 
setLayerZOrder(Display display,Layer layer,uint32_t z)1112 Error AidlComposer::setLayerZOrder(Display display, Layer layer, uint32_t z) {
1113     Error error = Error::NONE;
1114     mMutex.lock_shared();
1115     if (auto writer = getWriter(display)) {
1116         writer->get().setLayerZOrder(translate<int64_t>(display), translate<int64_t>(layer), z);
1117     } else {
1118         error = Error::BAD_DISPLAY;
1119     }
1120     mMutex.unlock_shared();
1121     return error;
1122 }
1123 
execute(Display display)1124 Error AidlComposer::execute(Display display) {
1125     auto writer = getWriter(display);
1126     auto reader = getReader(display);
1127     if (!writer || !reader) {
1128         return Error::BAD_DISPLAY;
1129     }
1130 
1131     auto commands = writer->get().takePendingCommands();
1132     if (commands.empty()) {
1133         return Error::NONE;
1134     }
1135 
1136     { // scope for results
1137         std::vector<CommandResultPayload> results;
1138         auto status = mAidlComposerClient->executeCommands(commands, &results);
1139         if (!status.isOk()) {
1140             ALOGE("executeCommands failed %s", status.getDescription().c_str());
1141             return static_cast<Error>(status.getServiceSpecificError());
1142         }
1143 
1144         reader->get().parse(std::move(results));
1145     }
1146     const auto commandErrors = reader->get().takeErrors();
1147     Error error = Error::NONE;
1148     for (const auto& cmdErr : commandErrors) {
1149         const auto index = static_cast<size_t>(cmdErr.commandIndex);
1150         if (index < 0 || index >= commands.size()) {
1151             ALOGE("invalid command index %zu", index);
1152             return Error::BAD_PARAMETER;
1153         }
1154 
1155         const auto& command = commands[index];
1156         if (command.validateDisplay || command.presentDisplay || command.presentOrValidateDisplay) {
1157             error = translate<Error>(cmdErr.errorCode);
1158         } else {
1159             ALOGW("command '%s' generated error %" PRId32, command.toString().c_str(),
1160                   cmdErr.errorCode);
1161         }
1162     }
1163 
1164     return error;
1165 }
1166 
setLayerPerFrameMetadata(Display display,Layer layer,const std::vector<IComposerClient::PerFrameMetadata> & perFrameMetadatas)1167 Error AidlComposer::setLayerPerFrameMetadata(
1168         Display display, Layer layer,
1169         const std::vector<IComposerClient::PerFrameMetadata>& perFrameMetadatas) {
1170     Error error = Error::NONE;
1171     mMutex.lock_shared();
1172     if (auto writer = getWriter(display)) {
1173         writer->get().setLayerPerFrameMetadata(translate<int64_t>(display),
1174                                                translate<int64_t>(layer),
1175                                                translate<AidlPerFrameMetadata>(perFrameMetadatas));
1176     } else {
1177         error = Error::BAD_DISPLAY;
1178     }
1179     mMutex.unlock_shared();
1180     return error;
1181 }
1182 
getPerFrameMetadataKeys(Display display)1183 std::vector<IComposerClient::PerFrameMetadataKey> AidlComposer::getPerFrameMetadataKeys(
1184         Display display) {
1185     std::vector<AidlPerFrameMetadataKey> keys;
1186     const auto status =
1187             mAidlComposerClient->getPerFrameMetadataKeys(translate<int64_t>(display), &keys);
1188     if (!status.isOk()) {
1189         ALOGE("getPerFrameMetadataKeys failed %s", status.getDescription().c_str());
1190         return {};
1191     }
1192     return translate<IComposerClient::PerFrameMetadataKey>(keys);
1193 }
1194 
getRenderIntents(Display display,ColorMode colorMode,std::vector<RenderIntent> * outRenderIntents)1195 Error AidlComposer::getRenderIntents(Display display, ColorMode colorMode,
1196                                      std::vector<RenderIntent>* outRenderIntents) {
1197     std::vector<AidlRenderIntent> renderIntents;
1198     const auto status = mAidlComposerClient->getRenderIntents(translate<int64_t>(display),
1199                                                               translate<AidlColorMode>(colorMode),
1200                                                               &renderIntents);
1201     if (!status.isOk()) {
1202         ALOGE("getRenderIntents failed %s", status.getDescription().c_str());
1203         return static_cast<Error>(status.getServiceSpecificError());
1204     }
1205     *outRenderIntents = translate<RenderIntent>(renderIntents);
1206     return Error::NONE;
1207 }
1208 
getDataspaceSaturationMatrix(Dataspace dataspace,mat4 * outMatrix)1209 Error AidlComposer::getDataspaceSaturationMatrix(Dataspace dataspace, mat4* outMatrix) {
1210     std::vector<float> matrix;
1211     const auto status =
1212             mAidlComposerClient->getDataspaceSaturationMatrix(translate<AidlDataspace>(dataspace),
1213                                                               &matrix);
1214     if (!status.isOk()) {
1215         ALOGE("getDataspaceSaturationMatrix failed %s", status.getDescription().c_str());
1216         return static_cast<Error>(status.getServiceSpecificError());
1217     }
1218     *outMatrix = makeMat4(matrix);
1219     return Error::NONE;
1220 }
1221 
getDisplayIdentificationData(Display display,uint8_t * outPort,std::vector<uint8_t> * outData)1222 Error AidlComposer::getDisplayIdentificationData(Display display, uint8_t* outPort,
1223                                                  std::vector<uint8_t>* outData) {
1224     AidlDisplayIdentification displayIdentification;
1225     const auto status =
1226             mAidlComposerClient->getDisplayIdentificationData(translate<int64_t>(display),
1227                                                               &displayIdentification);
1228     if (!status.isOk()) {
1229         ALOGE("getDisplayIdentificationData failed %s", status.getDescription().c_str());
1230         return static_cast<Error>(status.getServiceSpecificError());
1231     }
1232 
1233     *outPort = static_cast<uint8_t>(displayIdentification.port);
1234     *outData = displayIdentification.data;
1235 
1236     return Error::NONE;
1237 }
1238 
setLayerColorTransform(Display display,Layer layer,const float * matrix)1239 Error AidlComposer::setLayerColorTransform(Display display, Layer layer, const float* matrix) {
1240     Error error = Error::NONE;
1241     mMutex.lock_shared();
1242     if (auto writer = getWriter(display)) {
1243         writer->get().setLayerColorTransform(translate<int64_t>(display), translate<int64_t>(layer),
1244                                              matrix);
1245     } else {
1246         error = Error::BAD_DISPLAY;
1247     }
1248     mMutex.unlock_shared();
1249     return error;
1250 }
1251 
getDisplayedContentSamplingAttributes(Display display,PixelFormat * outFormat,Dataspace * outDataspace,uint8_t * outComponentMask)1252 Error AidlComposer::getDisplayedContentSamplingAttributes(Display display, PixelFormat* outFormat,
1253                                                           Dataspace* outDataspace,
1254                                                           uint8_t* outComponentMask) {
1255     if (!outFormat || !outDataspace || !outComponentMask) {
1256         return Error::BAD_PARAMETER;
1257     }
1258 
1259     AidlDisplayContentSamplingAttributes attributes;
1260     const auto status =
1261             mAidlComposerClient->getDisplayedContentSamplingAttributes(translate<int64_t>(display),
1262                                                                        &attributes);
1263     if (!status.isOk()) {
1264         ALOGE("getDisplayedContentSamplingAttributes failed %s", status.getDescription().c_str());
1265         return static_cast<Error>(status.getServiceSpecificError());
1266     }
1267 
1268     *outFormat = translate<PixelFormat>(attributes.format);
1269     *outDataspace = translate<Dataspace>(attributes.dataspace);
1270     *outComponentMask = static_cast<uint8_t>(attributes.componentMask);
1271     return Error::NONE;
1272 }
1273 
setDisplayContentSamplingEnabled(Display display,bool enabled,uint8_t componentMask,uint64_t maxFrames)1274 Error AidlComposer::setDisplayContentSamplingEnabled(Display display, bool enabled,
1275                                                      uint8_t componentMask, uint64_t maxFrames) {
1276     const auto status =
1277             mAidlComposerClient
1278                     ->setDisplayedContentSamplingEnabled(translate<int64_t>(display), enabled,
1279                                                          static_cast<AidlFormatColorComponent>(
1280                                                                  componentMask),
1281                                                          static_cast<int64_t>(maxFrames));
1282     if (!status.isOk()) {
1283         ALOGE("setDisplayedContentSamplingEnabled failed %s", status.getDescription().c_str());
1284         return static_cast<Error>(status.getServiceSpecificError());
1285     }
1286     return Error::NONE;
1287 }
1288 
getDisplayedContentSample(Display display,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats)1289 Error AidlComposer::getDisplayedContentSample(Display display, uint64_t maxFrames,
1290                                               uint64_t timestamp, DisplayedFrameStats* outStats) {
1291     if (!outStats) {
1292         return Error::BAD_PARAMETER;
1293     }
1294 
1295     AidlDisplayContentSample sample;
1296     const auto status =
1297             mAidlComposerClient->getDisplayedContentSample(translate<int64_t>(display),
1298                                                            static_cast<int64_t>(maxFrames),
1299                                                            static_cast<int64_t>(timestamp),
1300                                                            &sample);
1301     if (!status.isOk()) {
1302         ALOGE("getDisplayedContentSample failed %s", status.getDescription().c_str());
1303         return static_cast<Error>(status.getServiceSpecificError());
1304     }
1305     *outStats = translate<DisplayedFrameStats>(sample);
1306     return Error::NONE;
1307 }
1308 
setLayerPerFrameMetadataBlobs(Display display,Layer layer,const std::vector<IComposerClient::PerFrameMetadataBlob> & metadata)1309 Error AidlComposer::setLayerPerFrameMetadataBlobs(
1310         Display display, Layer layer,
1311         const std::vector<IComposerClient::PerFrameMetadataBlob>& metadata) {
1312     Error error = Error::NONE;
1313     mMutex.lock_shared();
1314     if (auto writer = getWriter(display)) {
1315         writer->get().setLayerPerFrameMetadataBlobs(translate<int64_t>(display),
1316                                                     translate<int64_t>(layer),
1317                                                     translate<AidlPerFrameMetadataBlob>(metadata));
1318     } else {
1319         error = Error::BAD_DISPLAY;
1320     }
1321     mMutex.unlock_shared();
1322     return error;
1323 }
1324 
setDisplayBrightness(Display display,float brightness,float brightnessNits,const DisplayBrightnessOptions & options)1325 Error AidlComposer::setDisplayBrightness(Display display, float brightness, float brightnessNits,
1326                                          const DisplayBrightnessOptions& options) {
1327     Error error = Error::NONE;
1328     mMutex.lock_shared();
1329     if (auto writer = getWriter(display)) {
1330         writer->get().setDisplayBrightness(translate<int64_t>(display), brightness, brightnessNits);
1331 
1332         if (options.applyImmediately) {
1333             error = execute(display);
1334             mMutex.unlock_shared();
1335             return error;
1336         }
1337     } else {
1338         error = Error::BAD_DISPLAY;
1339     }
1340     mMutex.unlock_shared();
1341     return error;
1342 }
1343 
getDisplayCapabilities(Display display,std::vector<AidlDisplayCapability> * outCapabilities)1344 Error AidlComposer::getDisplayCapabilities(Display display,
1345                                            std::vector<AidlDisplayCapability>* outCapabilities) {
1346     const auto status = mAidlComposerClient->getDisplayCapabilities(translate<int64_t>(display),
1347                                                                     outCapabilities);
1348     if (!status.isOk()) {
1349         ALOGE("getDisplayCapabilities failed %s", status.getDescription().c_str());
1350         outCapabilities->clear();
1351         return static_cast<Error>(status.getServiceSpecificError());
1352     }
1353     return Error::NONE;
1354 }
1355 
getDisplayConnectionType(Display display,IComposerClient::DisplayConnectionType * outType)1356 V2_4::Error AidlComposer::getDisplayConnectionType(
1357         Display display, IComposerClient::DisplayConnectionType* outType) {
1358     AidlDisplayConnectionType type;
1359     const auto status =
1360             mAidlComposerClient->getDisplayConnectionType(translate<int64_t>(display), &type);
1361     if (!status.isOk()) {
1362         ALOGE("getDisplayConnectionType failed %s", status.getDescription().c_str());
1363         return static_cast<V2_4::Error>(status.getServiceSpecificError());
1364     }
1365     *outType = translate<IComposerClient::DisplayConnectionType>(type);
1366     return V2_4::Error::NONE;
1367 }
1368 
getDisplayVsyncPeriod(Display display,VsyncPeriodNanos * outVsyncPeriod)1369 V2_4::Error AidlComposer::getDisplayVsyncPeriod(Display display, VsyncPeriodNanos* outVsyncPeriod) {
1370     int32_t vsyncPeriod;
1371     const auto status =
1372             mAidlComposerClient->getDisplayVsyncPeriod(translate<int64_t>(display), &vsyncPeriod);
1373     if (!status.isOk()) {
1374         ALOGE("getDisplayVsyncPeriod failed %s", status.getDescription().c_str());
1375         return static_cast<V2_4::Error>(status.getServiceSpecificError());
1376     }
1377     *outVsyncPeriod = translate<VsyncPeriodNanos>(vsyncPeriod);
1378     return V2_4::Error::NONE;
1379 }
1380 
setActiveConfigWithConstraints(Display display,Config config,const IComposerClient::VsyncPeriodChangeConstraints & vsyncPeriodChangeConstraints,VsyncPeriodChangeTimeline * outTimeline)1381 V2_4::Error AidlComposer::setActiveConfigWithConstraints(
1382         Display display, Config config,
1383         const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
1384         VsyncPeriodChangeTimeline* outTimeline) {
1385     AidlVsyncPeriodChangeTimeline timeline;
1386     const auto status =
1387             mAidlComposerClient
1388                     ->setActiveConfigWithConstraints(translate<int64_t>(display),
1389                                                      translate<int32_t>(config),
1390                                                      translate<AidlVsyncPeriodChangeConstraints>(
1391                                                              vsyncPeriodChangeConstraints),
1392                                                      &timeline);
1393     if (!status.isOk()) {
1394         ALOGE("setActiveConfigWithConstraints failed %s", status.getDescription().c_str());
1395         return static_cast<V2_4::Error>(status.getServiceSpecificError());
1396     }
1397     *outTimeline = translate<VsyncPeriodChangeTimeline>(timeline);
1398     return V2_4::Error::NONE;
1399 }
1400 
setAutoLowLatencyMode(Display display,bool on)1401 V2_4::Error AidlComposer::setAutoLowLatencyMode(Display display, bool on) {
1402     const auto status = mAidlComposerClient->setAutoLowLatencyMode(translate<int64_t>(display), on);
1403     if (!status.isOk()) {
1404         ALOGE("setAutoLowLatencyMode failed %s", status.getDescription().c_str());
1405         return static_cast<V2_4::Error>(status.getServiceSpecificError());
1406     }
1407     return V2_4::Error::NONE;
1408 }
1409 
getSupportedContentTypes(Display displayId,std::vector<IComposerClient::ContentType> * outSupportedContentTypes)1410 V2_4::Error AidlComposer::getSupportedContentTypes(
1411         Display displayId, std::vector<IComposerClient::ContentType>* outSupportedContentTypes) {
1412     std::vector<AidlContentType> types;
1413     const auto status =
1414             mAidlComposerClient->getSupportedContentTypes(translate<int64_t>(displayId), &types);
1415     if (!status.isOk()) {
1416         ALOGE("getSupportedContentTypes failed %s", status.getDescription().c_str());
1417         return static_cast<V2_4::Error>(status.getServiceSpecificError());
1418     }
1419     *outSupportedContentTypes = translate<IComposerClient::ContentType>(types);
1420     return V2_4::Error::NONE;
1421 }
1422 
setContentType(Display display,IComposerClient::ContentType contentType)1423 V2_4::Error AidlComposer::setContentType(Display display,
1424                                          IComposerClient::ContentType contentType) {
1425     const auto status =
1426             mAidlComposerClient->setContentType(translate<int64_t>(display),
1427                                                 translate<AidlContentType>(contentType));
1428     if (!status.isOk()) {
1429         ALOGE("setContentType failed %s", status.getDescription().c_str());
1430         return static_cast<V2_4::Error>(status.getServiceSpecificError());
1431     }
1432     return V2_4::Error::NONE;
1433 }
1434 
setLayerGenericMetadata(Display,Layer,const std::string &,bool,const std::vector<uint8_t> &)1435 V2_4::Error AidlComposer::setLayerGenericMetadata(Display, Layer, const std::string&, bool,
1436                                                   const std::vector<uint8_t>&) {
1437     // There are no users for this API. See b/209691612.
1438     return V2_4::Error::UNSUPPORTED;
1439 }
1440 
getLayerGenericMetadataKeys(std::vector<IComposerClient::LayerGenericMetadataKey> *)1441 V2_4::Error AidlComposer::getLayerGenericMetadataKeys(
1442         std::vector<IComposerClient::LayerGenericMetadataKey>*) {
1443     // There are no users for this API. See b/209691612.
1444     return V2_4::Error::UNSUPPORTED;
1445 }
1446 
setBootDisplayConfig(Display display,Config config)1447 Error AidlComposer::setBootDisplayConfig(Display display, Config config) {
1448     const auto status = mAidlComposerClient->setBootDisplayConfig(translate<int64_t>(display),
1449                                                                   translate<int32_t>(config));
1450     if (!status.isOk()) {
1451         ALOGE("setBootDisplayConfig failed %s", status.getDescription().c_str());
1452         return static_cast<Error>(status.getServiceSpecificError());
1453     }
1454     return Error::NONE;
1455 }
1456 
clearBootDisplayConfig(Display display)1457 Error AidlComposer::clearBootDisplayConfig(Display display) {
1458     const auto status = mAidlComposerClient->clearBootDisplayConfig(translate<int64_t>(display));
1459     if (!status.isOk()) {
1460         ALOGE("clearBootDisplayConfig failed %s", status.getDescription().c_str());
1461         return static_cast<Error>(status.getServiceSpecificError());
1462     }
1463     return Error::NONE;
1464 }
1465 
getPreferredBootDisplayConfig(Display display,Config * config)1466 Error AidlComposer::getPreferredBootDisplayConfig(Display display, Config* config) {
1467     int32_t displayConfig;
1468     const auto status =
1469             mAidlComposerClient->getPreferredBootDisplayConfig(translate<int64_t>(display),
1470                                                                &displayConfig);
1471     if (!status.isOk()) {
1472         ALOGE("getPreferredBootDisplayConfig failed %s", status.getDescription().c_str());
1473         return static_cast<Error>(status.getServiceSpecificError());
1474     }
1475     *config = translate<uint32_t>(displayConfig);
1476     return Error::NONE;
1477 }
1478 
getHdrConversionCapabilities(std::vector<AidlHdrConversionCapability> * hdrConversionCapabilities)1479 Error AidlComposer::getHdrConversionCapabilities(
1480         std::vector<AidlHdrConversionCapability>* hdrConversionCapabilities) {
1481     const auto status =
1482             mAidlComposerClient->getHdrConversionCapabilities(hdrConversionCapabilities);
1483     if (!status.isOk()) {
1484         hdrConversionCapabilities = {};
1485         ALOGE("getHdrConversionCapabilities failed %s", status.getDescription().c_str());
1486         return static_cast<Error>(status.getServiceSpecificError());
1487     }
1488     return Error::NONE;
1489 }
1490 
setHdrConversionStrategy(AidlHdrConversionStrategy hdrConversionStrategy,Hdr * outPreferredHdrOutputType)1491 Error AidlComposer::setHdrConversionStrategy(AidlHdrConversionStrategy hdrConversionStrategy,
1492                                              Hdr* outPreferredHdrOutputType) {
1493     const auto status = mAidlComposerClient->setHdrConversionStrategy(hdrConversionStrategy,
1494                                                                       outPreferredHdrOutputType);
1495     if (!status.isOk()) {
1496         ALOGE("setHdrConversionStrategy failed %s", status.getDescription().c_str());
1497         return static_cast<Error>(status.getServiceSpecificError());
1498     }
1499     return Error::NONE;
1500 }
1501 
setRefreshRateChangedCallbackDebugEnabled(Display displayId,bool enabled)1502 Error AidlComposer::setRefreshRateChangedCallbackDebugEnabled(Display displayId, bool enabled) {
1503     const auto status =
1504             mAidlComposerClient->setRefreshRateChangedCallbackDebugEnabled(translate<int64_t>(
1505                                                                                    displayId),
1506                                                                            enabled);
1507     if (!status.isOk()) {
1508         ALOGE("setRefreshRateChangedCallbackDebugEnabled failed %s",
1509               status.getDescription().c_str());
1510         return static_cast<Error>(status.getServiceSpecificError());
1511     }
1512     return Error::NONE;
1513 }
1514 
notifyExpectedPresent(Display displayId,nsecs_t expectedPresentTime,int32_t frameIntervalNs)1515 Error AidlComposer::notifyExpectedPresent(Display displayId, nsecs_t expectedPresentTime,
1516                                           int32_t frameIntervalNs) {
1517     const auto status =
1518             mAidlComposerClient->notifyExpectedPresent(translate<int64_t>(displayId),
1519                                                        ClockMonotonicTimestamp{expectedPresentTime},
1520                                                        frameIntervalNs);
1521 
1522     if (!status.isOk()) {
1523         ALOGE("notifyExpectedPresent failed %s", status.getDescription().c_str());
1524         return static_cast<Error>(status.getServiceSpecificError());
1525     }
1526     return Error::NONE;
1527 }
1528 
getClientTargetProperty(Display display,ClientTargetPropertyWithBrightness * outClientTargetProperty)1529 Error AidlComposer::getClientTargetProperty(
1530         Display display, ClientTargetPropertyWithBrightness* outClientTargetProperty) {
1531     Error error = Error::NONE;
1532     mMutex.lock_shared();
1533     if (auto reader = getReader(display)) {
1534         *outClientTargetProperty =
1535                 reader->get().takeClientTargetProperty(translate<int64_t>(display));
1536     } else {
1537         error = Error::BAD_DISPLAY;
1538     }
1539     mMutex.unlock_shared();
1540     return error;
1541 }
1542 
setLayerBrightness(Display display,Layer layer,float brightness)1543 Error AidlComposer::setLayerBrightness(Display display, Layer layer, float brightness) {
1544     Error error = Error::NONE;
1545     mMutex.lock_shared();
1546     if (auto writer = getWriter(display)) {
1547         writer->get().setLayerBrightness(translate<int64_t>(display), translate<int64_t>(layer),
1548                                          brightness);
1549     } else {
1550         error = Error::BAD_DISPLAY;
1551     }
1552     mMutex.unlock_shared();
1553     return error;
1554 }
1555 
setLayerBlockingRegion(Display display,Layer layer,const std::vector<IComposerClient::Rect> & blocking)1556 Error AidlComposer::setLayerBlockingRegion(Display display, Layer layer,
1557                                            const std::vector<IComposerClient::Rect>& blocking) {
1558     Error error = Error::NONE;
1559     mMutex.lock_shared();
1560     if (auto writer = getWriter(display)) {
1561         writer->get().setLayerBlockingRegion(translate<int64_t>(display), translate<int64_t>(layer),
1562                                              translate<AidlRect>(blocking));
1563     } else {
1564         error = Error::BAD_DISPLAY;
1565     }
1566     mMutex.unlock_shared();
1567     return error;
1568 }
1569 
getDisplayDecorationSupport(Display display,std::optional<DisplayDecorationSupport> * support)1570 Error AidlComposer::getDisplayDecorationSupport(Display display,
1571                                                 std::optional<DisplayDecorationSupport>* support) {
1572     const auto status =
1573             mAidlComposerClient->getDisplayDecorationSupport(translate<int64_t>(display), support);
1574     if (!status.isOk()) {
1575         ALOGE("getDisplayDecorationSupport failed %s", status.getDescription().c_str());
1576         support->reset();
1577         return static_cast<Error>(status.getServiceSpecificError());
1578     }
1579     return Error::NONE;
1580 }
1581 
setIdleTimerEnabled(Display displayId,std::chrono::milliseconds timeout)1582 Error AidlComposer::setIdleTimerEnabled(Display displayId, std::chrono::milliseconds timeout) {
1583     const auto status =
1584             mAidlComposerClient->setIdleTimerEnabled(translate<int64_t>(displayId),
1585                                                      translate<int32_t>(timeout.count()));
1586     if (!status.isOk()) {
1587         ALOGE("setIdleTimerEnabled failed %s", status.getDescription().c_str());
1588         return static_cast<Error>(status.getServiceSpecificError());
1589     }
1590     return Error::NONE;
1591 }
1592 
getPhysicalDisplayOrientation(Display displayId,AidlTransform * outDisplayOrientation)1593 Error AidlComposer::getPhysicalDisplayOrientation(Display displayId,
1594                                                   AidlTransform* outDisplayOrientation) {
1595     const auto status =
1596             mAidlComposerClient->getDisplayPhysicalOrientation(translate<int64_t>(displayId),
1597                                                                outDisplayOrientation);
1598     if (!status.isOk()) {
1599         ALOGE("getPhysicalDisplayOrientation failed %s", status.getDescription().c_str());
1600         return static_cast<Error>(status.getServiceSpecificError());
1601     }
1602     return Error::NONE;
1603 }
1604 
getWriter(Display display)1605 ftl::Optional<std::reference_wrapper<ComposerClientWriter>> AidlComposer::getWriter(Display display)
1606         REQUIRES_SHARED(mMutex) {
1607     return mWriters.get(display);
1608 }
1609 
getReader(Display display)1610 ftl::Optional<std::reference_wrapper<ComposerClientReader>> AidlComposer::getReader(Display display)
1611         REQUIRES_SHARED(mMutex) {
1612     if (mSingleReader) {
1613         display = translate<Display>(kSingleReaderKey);
1614     }
1615     return mReaders.get(display);
1616 }
1617 
removeDisplay(Display display)1618 void AidlComposer::removeDisplay(Display display) {
1619     mMutex.lock();
1620     bool wasErased = mWriters.erase(display);
1621     ALOGW_IF(!wasErased,
1622              "Attempting to remove writer for display %" PRId64 " which is not connected",
1623              translate<int64_t>(display));
1624     if (!mSingleReader) {
1625         removeReader(display);
1626     }
1627     mMutex.unlock();
1628 }
1629 
onHotplugDisconnect(Display display)1630 void AidlComposer::onHotplugDisconnect(Display display) {
1631     removeDisplay(display);
1632 }
1633 
hasMultiThreadedPresentSupport(Display display)1634 bool AidlComposer::hasMultiThreadedPresentSupport(Display display) {
1635     if (!FlagManager::getInstance().multithreaded_present()) return false;
1636     const auto displayId = translate<int64_t>(display);
1637     std::vector<AidlDisplayCapability> capabilities;
1638     const auto status = mAidlComposerClient->getDisplayCapabilities(displayId, &capabilities);
1639     if (!status.isOk()) {
1640         ALOGE("getDisplayCapabilities failed %s", status.getDescription().c_str());
1641         return false;
1642     }
1643     return std::find(capabilities.begin(), capabilities.end(),
1644                      AidlDisplayCapability::MULTI_THREADED_PRESENT) != capabilities.end();
1645 }
1646 
addReader(Display display)1647 void AidlComposer::addReader(Display display) {
1648     const auto displayId = translate<int64_t>(display);
1649     std::optional<int64_t> displayOpt;
1650     if (displayId != kSingleReaderKey) {
1651         displayOpt.emplace(displayId);
1652     }
1653     auto [it, added] = mReaders.try_emplace(display, std::move(displayOpt));
1654     ALOGW_IF(!added, "Attempting to add writer for display %" PRId64 " which is already connected",
1655              displayId);
1656 }
1657 
removeReader(Display display)1658 void AidlComposer::removeReader(Display display) {
1659     bool wasErased = mReaders.erase(display);
1660     ALOGW_IF(!wasErased,
1661              "Attempting to remove reader for display %" PRId64 " which is not connected",
1662              translate<int64_t>(display));
1663 }
1664 
addDisplay(Display display)1665 void AidlComposer::addDisplay(Display display) {
1666     const auto displayId = translate<int64_t>(display);
1667     mMutex.lock();
1668     auto [it, added] = mWriters.try_emplace(display, displayId);
1669     ALOGW_IF(!added, "Attempting to add writer for display %" PRId64 " which is already connected",
1670              displayId);
1671     if (mSingleReader) {
1672         if (hasMultiThreadedPresentSupport(display)) {
1673             mSingleReader = false;
1674             removeReader(translate<Display>(kSingleReaderKey));
1675             // Note that this includes the new display.
1676             for (const auto& [existingDisplay, _] : mWriters) {
1677                 addReader(existingDisplay);
1678             }
1679         }
1680     } else {
1681         addReader(display);
1682     }
1683     mMutex.unlock();
1684 }
1685 
onHotplugConnect(Display display)1686 void AidlComposer::onHotplugConnect(Display display) {
1687     addDisplay(display);
1688 }
1689 } // namespace Hwc2
1690 } // namespace android
1691