1 /*
2  * Copyright 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20 
21 #undef LOG_TAG
22 #define LOG_TAG "HwcComposer"
23 
24 #include <log/log.h>
25 
26 #include <algorithm>
27 #include <cinttypes>
28 
29 #include "ComposerHal.h"
30 
31 #include <composer-command-buffer/2.2/ComposerCommandBuffer.h>
32 #include <gui/BufferQueue.h>
33 #include <hidl/HidlTransportSupport.h>
34 #include <hidl/HidlTransportUtils.h>
35 
36 namespace android {
37 
38 using hardware::Return;
39 using hardware::hidl_vec;
40 using hardware::hidl_handle;
41 
42 namespace Hwc2 {
43 
44 Composer::~Composer() = default;
45 
46 namespace {
47 
48 class BufferHandle {
49 public:
BufferHandle(const native_handle_t * buffer)50     explicit BufferHandle(const native_handle_t* buffer) {
51         // nullptr is not a valid handle to HIDL
52         mHandle = (buffer) ? buffer : native_handle_init(mStorage, 0, 0);
53     }
54 
operator const hidl_handle&() const55     operator const hidl_handle&() const // NOLINT(google-explicit-constructor)
56     {
57         return mHandle;
58     }
59 
60 private:
61     NATIVE_HANDLE_DECLARE_STORAGE(mStorage, 0, 0);
62     hidl_handle mHandle;
63 };
64 
65 class FenceHandle
66 {
67 public:
FenceHandle(int fd,bool owned)68     FenceHandle(int fd, bool owned)
69         : mOwned(owned)
70     {
71         native_handle_t* handle;
72         if (fd >= 0) {
73             handle = native_handle_init(mStorage, 1, 0);
74             handle->data[0] = fd;
75         } else {
76             // nullptr is not a valid handle to HIDL
77             handle = native_handle_init(mStorage, 0, 0);
78         }
79         mHandle = handle;
80     }
81 
~FenceHandle()82     ~FenceHandle()
83     {
84         if (mOwned) {
85             native_handle_close(mHandle);
86         }
87     }
88 
operator const hidl_handle&() const89     operator const hidl_handle&() const // NOLINT(google-explicit-constructor)
90     {
91         return mHandle;
92     }
93 
94 private:
95     bool mOwned;
96     NATIVE_HANDLE_DECLARE_STORAGE(mStorage, 1, 0);
97     hidl_handle mHandle;
98 };
99 
100 // assume NO_RESOURCES when Status::isOk returns false
101 constexpr Error kDefaultError = Error::NO_RESOURCES;
102 constexpr V2_4::Error kDefaultError_2_4 = static_cast<V2_4::Error>(kDefaultError);
103 
104 template<typename T, typename U>
unwrapRet(Return<T> & ret,const U & default_val)105 T unwrapRet(Return<T>& ret, const U& default_val)
106 {
107     return (ret.isOk()) ? static_cast<T>(ret) :
108         static_cast<T>(default_val);
109 }
110 
unwrapRet(Return<Error> & ret)111 Error unwrapRet(Return<Error>& ret)
112 {
113     return unwrapRet(ret, kDefaultError);
114 }
115 
116 } // anonymous namespace
117 
118 namespace impl {
119 
120 #if defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
CommandWriter(uint32_t initialMaxSize)121 Composer::CommandWriter::CommandWriter(uint32_t initialMaxSize)
122     : CommandWriterBase(initialMaxSize) {}
123 
~CommandWriter()124 Composer::CommandWriter::~CommandWriter()
125 {
126 }
127 
setLayerInfo(uint32_t type,uint32_t appId)128 void Composer::CommandWriter::setLayerInfo(uint32_t type, uint32_t appId)
129 {
130     constexpr uint16_t kSetLayerInfoLength = 2;
131     beginCommand(static_cast<V2_1::IComposerClient::Command>(
132                          IVrComposerClient::VrCommand::SET_LAYER_INFO),
133                  kSetLayerInfoLength);
134     write(type);
135     write(appId);
136     endCommand();
137 }
138 
setClientTargetMetadata(const IVrComposerClient::BufferMetadata & metadata)139 void Composer::CommandWriter::setClientTargetMetadata(
140         const IVrComposerClient::BufferMetadata& metadata)
141 {
142     constexpr uint16_t kSetClientTargetMetadataLength = 7;
143     beginCommand(static_cast<V2_1::IComposerClient::Command>(
144                          IVrComposerClient::VrCommand::SET_CLIENT_TARGET_METADATA),
145                  kSetClientTargetMetadataLength);
146     writeBufferMetadata(metadata);
147     endCommand();
148 }
149 
setLayerBufferMetadata(const IVrComposerClient::BufferMetadata & metadata)150 void Composer::CommandWriter::setLayerBufferMetadata(
151         const IVrComposerClient::BufferMetadata& metadata)
152 {
153     constexpr uint16_t kSetLayerBufferMetadataLength = 7;
154     beginCommand(static_cast<V2_1::IComposerClient::Command>(
155                          IVrComposerClient::VrCommand::SET_LAYER_BUFFER_METADATA),
156                  kSetLayerBufferMetadataLength);
157     writeBufferMetadata(metadata);
158     endCommand();
159 }
160 
writeBufferMetadata(const IVrComposerClient::BufferMetadata & metadata)161 void Composer::CommandWriter::writeBufferMetadata(
162         const IVrComposerClient::BufferMetadata& metadata)
163 {
164     write(metadata.width);
165     write(metadata.height);
166     write(metadata.stride);
167     write(metadata.layerCount);
168     writeSigned(static_cast<int32_t>(metadata.format));
169     write64(metadata.usage);
170 }
171 #endif // defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
172 
Composer(const std::string & serviceName)173 Composer::Composer(const std::string& serviceName)
174     : mWriter(kWriterInitialSize),
175       mIsUsingVrComposer(serviceName == std::string("vr"))
176 {
177     mComposer = V2_1::IComposer::getService(serviceName);
178 
179     if (mComposer == nullptr) {
180         LOG_ALWAYS_FATAL("failed to get hwcomposer service");
181     }
182 
183     if (sp<IComposer> composer_2_4 = IComposer::castFrom(mComposer)) {
184         composer_2_4->createClient_2_4([&](const auto& tmpError, const auto& tmpClient) {
185             if (tmpError == V2_4::Error::NONE) {
186                 mClient = tmpClient;
187                 mClient_2_2 = tmpClient;
188                 mClient_2_3 = tmpClient;
189                 mClient_2_4 = tmpClient;
190             }
191         });
192     } else if (sp<V2_3::IComposer> composer_2_3 = V2_3::IComposer::castFrom(mComposer)) {
193         composer_2_3->createClient_2_3([&](const auto& tmpError, const auto& tmpClient) {
194             if (tmpError == Error::NONE) {
195                 mClient = tmpClient;
196                 mClient_2_2 = tmpClient;
197                 mClient_2_3 = tmpClient;
198             }
199         });
200     } else {
201         mComposer->createClient([&](const auto& tmpError, const auto& tmpClient) {
202             if (tmpError != Error::NONE) {
203                 return;
204             }
205 
206             mClient = tmpClient;
207             if (sp<V2_2::IComposer> composer_2_2 = V2_2::IComposer::castFrom(mComposer)) {
208                 mClient_2_2 = V2_2::IComposerClient::castFrom(mClient);
209                 LOG_ALWAYS_FATAL_IF(mClient_2_2 == nullptr,
210                                     "IComposer 2.2 did not return IComposerClient 2.2");
211             }
212         });
213     }
214 
215     if (mClient == nullptr) {
216         LOG_ALWAYS_FATAL("failed to create composer client");
217     }
218 
219 #if defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
220     if (mIsUsingVrComposer) {
221         sp<IVrComposerClient> vrClient = IVrComposerClient::castFrom(mClient);
222         if (vrClient == nullptr) {
223             LOG_ALWAYS_FATAL("failed to create vr composer client");
224         }
225     }
226 #endif // defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
227 }
228 
229 Composer::~Composer() = default;
230 
getCapabilities()231 std::vector<IComposer::Capability> Composer::getCapabilities()
232 {
233     std::vector<IComposer::Capability> capabilities;
234     mComposer->getCapabilities(
235             [&](const auto& tmpCapabilities) {
236                 capabilities = tmpCapabilities;
237             });
238     return capabilities;
239 }
240 
dumpDebugInfo()241 std::string Composer::dumpDebugInfo()
242 {
243     std::string info;
244     mComposer->dumpDebugInfo([&](const auto& tmpInfo) {
245         info = tmpInfo.c_str();
246     });
247 
248     return info;
249 }
250 
registerCallback(const sp<IComposerCallback> & callback)251 void Composer::registerCallback(const sp<IComposerCallback>& callback)
252 {
253     android::hardware::setMinSchedulerPolicy(callback, SCHED_FIFO, 2);
254     auto ret = [&]() {
255         if (mClient_2_4) {
256             return mClient_2_4->registerCallback_2_4(callback);
257         }
258         return mClient->registerCallback(callback);
259     }();
260     if (!ret.isOk()) {
261         ALOGE("failed to register IComposerCallback");
262     }
263 }
264 
isRemote()265 bool Composer::isRemote() {
266     return mClient->isRemote();
267 }
268 
resetCommands()269 void Composer::resetCommands() {
270     mWriter.reset();
271 }
272 
executeCommands()273 Error Composer::executeCommands() {
274     return execute();
275 }
276 
getMaxVirtualDisplayCount()277 uint32_t Composer::getMaxVirtualDisplayCount()
278 {
279     auto ret = mClient->getMaxVirtualDisplayCount();
280     return unwrapRet(ret, 0);
281 }
282 
createVirtualDisplay(uint32_t width,uint32_t height,PixelFormat * format,Display * outDisplay)283 Error Composer::createVirtualDisplay(uint32_t width, uint32_t height,
284             PixelFormat* format, Display* outDisplay)
285 {
286     const uint32_t bufferSlotCount = 1;
287     Error error = kDefaultError;
288     if (mClient_2_2) {
289         mClient_2_2->createVirtualDisplay_2_2(width, height,
290                                               static_cast<types::V1_1::PixelFormat>(*format),
291                                               bufferSlotCount,
292                                               [&](const auto& tmpError, const auto& tmpDisplay,
293                                                   const auto& tmpFormat) {
294                                                   error = tmpError;
295                                                   if (error != Error::NONE) {
296                                                       return;
297                                                   }
298 
299                                                   *outDisplay = tmpDisplay;
300                                                   *format = static_cast<types::V1_2::PixelFormat>(
301                                                           tmpFormat);
302                                               });
303     } else {
304         mClient->createVirtualDisplay(width, height,
305                 static_cast<types::V1_0::PixelFormat>(*format), bufferSlotCount,
306                 [&](const auto& tmpError, const auto& tmpDisplay,
307                     const auto& tmpFormat) {
308                     error = tmpError;
309                     if (error != Error::NONE) {
310                         return;
311                     }
312 
313                     *outDisplay = tmpDisplay;
314                     *format = static_cast<PixelFormat>(tmpFormat);
315             });
316     }
317 
318     return error;
319 }
320 
destroyVirtualDisplay(Display display)321 Error Composer::destroyVirtualDisplay(Display display)
322 {
323     auto ret = mClient->destroyVirtualDisplay(display);
324     return unwrapRet(ret);
325 }
326 
acceptDisplayChanges(Display display)327 Error Composer::acceptDisplayChanges(Display display)
328 {
329     mWriter.selectDisplay(display);
330     mWriter.acceptDisplayChanges();
331     return Error::NONE;
332 }
333 
createLayer(Display display,Layer * outLayer)334 Error Composer::createLayer(Display display, Layer* outLayer)
335 {
336     Error error = kDefaultError;
337     mClient->createLayer(display, BufferQueue::NUM_BUFFER_SLOTS,
338             [&](const auto& tmpError, const auto& tmpLayer) {
339                 error = tmpError;
340                 if (error != Error::NONE) {
341                     return;
342                 }
343 
344                 *outLayer = tmpLayer;
345             });
346 
347     return error;
348 }
349 
destroyLayer(Display display,Layer layer)350 Error Composer::destroyLayer(Display display, Layer layer)
351 {
352     auto ret = mClient->destroyLayer(display, layer);
353     return unwrapRet(ret);
354 }
355 
getActiveConfig(Display display,Config * outConfig)356 Error Composer::getActiveConfig(Display display, Config* outConfig)
357 {
358     Error error = kDefaultError;
359     mClient->getActiveConfig(display,
360             [&](const auto& tmpError, const auto& tmpConfig) {
361                 error = tmpError;
362                 if (error != Error::NONE) {
363                     return;
364                 }
365 
366                 *outConfig = tmpConfig;
367             });
368 
369     return error;
370 }
371 
getChangedCompositionTypes(Display display,std::vector<Layer> * outLayers,std::vector<IComposerClient::Composition> * outTypes)372 Error Composer::getChangedCompositionTypes(Display display,
373         std::vector<Layer>* outLayers,
374         std::vector<IComposerClient::Composition>* outTypes)
375 {
376     mReader.takeChangedCompositionTypes(display, outLayers, outTypes);
377     return Error::NONE;
378 }
379 
getColorModes(Display display,std::vector<ColorMode> * outModes)380 Error Composer::getColorModes(Display display,
381         std::vector<ColorMode>* outModes)
382 {
383     Error error = kDefaultError;
384 
385     if (mClient_2_3) {
386         mClient_2_3->getColorModes_2_3(display, [&](const auto& tmpError, const auto& tmpModes) {
387             error = tmpError;
388             if (error != Error::NONE) {
389                 return;
390             }
391 
392             *outModes = tmpModes;
393         });
394     } else if (mClient_2_2) {
395         mClient_2_2->getColorModes_2_2(display, [&](const auto& tmpError, const auto& tmpModes) {
396             error = tmpError;
397             if (error != Error::NONE) {
398                 return;
399             }
400 
401             for (types::V1_1::ColorMode colorMode : tmpModes) {
402                 outModes->push_back(static_cast<ColorMode>(colorMode));
403             }
404         });
405     } else {
406         mClient->getColorModes(display,
407                 [&](const auto& tmpError, const auto& tmpModes) {
408                     error = tmpError;
409                     if (error != Error::NONE) {
410                         return;
411                     }
412                     for (types::V1_0::ColorMode colorMode : tmpModes) {
413                         outModes->push_back(static_cast<ColorMode>(colorMode));
414                     }
415                 });
416     }
417 
418     return error;
419 }
420 
getDisplayAttribute(Display display,Config config,IComposerClient::Attribute attribute,int32_t * outValue)421 Error Composer::getDisplayAttribute(Display display, Config config,
422         IComposerClient::Attribute attribute, int32_t* outValue)
423 {
424     Error error = kDefaultError;
425     if (mClient_2_4) {
426         mClient_2_4->getDisplayAttribute_2_4(display, config, attribute,
427                                              [&](const auto& tmpError, const auto& tmpValue) {
428                                                  error = static_cast<Error>(tmpError);
429                                                  if (error != Error::NONE) {
430                                                      return;
431                                                  }
432 
433                                                  *outValue = tmpValue;
434                                              });
435     } else {
436         mClient->getDisplayAttribute(display, config,
437                                      static_cast<V2_1::IComposerClient::Attribute>(attribute),
438                                      [&](const auto& tmpError, const auto& tmpValue) {
439                                          error = tmpError;
440                                          if (error != Error::NONE) {
441                                              return;
442                                          }
443 
444                                          *outValue = tmpValue;
445                                      });
446     }
447 
448     return error;
449 }
450 
getDisplayConfigs(Display display,std::vector<Config> * outConfigs)451 Error Composer::getDisplayConfigs(Display display,
452         std::vector<Config>* outConfigs)
453 {
454     Error error = kDefaultError;
455     mClient->getDisplayConfigs(display,
456             [&](const auto& tmpError, const auto& tmpConfigs) {
457                 error = tmpError;
458                 if (error != Error::NONE) {
459                     return;
460                 }
461 
462                 *outConfigs = tmpConfigs;
463             });
464 
465     return error;
466 }
467 
getDisplayName(Display display,std::string * outName)468 Error Composer::getDisplayName(Display display, std::string* outName)
469 {
470     Error error = kDefaultError;
471     mClient->getDisplayName(display,
472             [&](const auto& tmpError, const auto& tmpName) {
473                 error = tmpError;
474                 if (error != Error::NONE) {
475                     return;
476                 }
477 
478                 *outName = tmpName.c_str();
479             });
480 
481     return error;
482 }
483 
getDisplayRequests(Display display,uint32_t * outDisplayRequestMask,std::vector<Layer> * outLayers,std::vector<uint32_t> * outLayerRequestMasks)484 Error Composer::getDisplayRequests(Display display,
485         uint32_t* outDisplayRequestMask, std::vector<Layer>* outLayers,
486         std::vector<uint32_t>* outLayerRequestMasks)
487 {
488     mReader.takeDisplayRequests(display, outDisplayRequestMask,
489             outLayers, outLayerRequestMasks);
490     return Error::NONE;
491 }
492 
getDozeSupport(Display display,bool * outSupport)493 Error Composer::getDozeSupport(Display display, bool* outSupport)
494 {
495     Error error = kDefaultError;
496     mClient->getDozeSupport(display,
497             [&](const auto& tmpError, const auto& tmpSupport) {
498                 error = tmpError;
499                 if (error != Error::NONE) {
500                     return;
501                 }
502 
503                 *outSupport = tmpSupport;
504             });
505 
506     return error;
507 }
508 
getHdrCapabilities(Display display,std::vector<Hdr> * outTypes,float * outMaxLuminance,float * outMaxAverageLuminance,float * outMinLuminance)509 Error Composer::getHdrCapabilities(Display display,
510         std::vector<Hdr>* outTypes, float* outMaxLuminance,
511         float* outMaxAverageLuminance, float* outMinLuminance)
512 {
513     Error error = kDefaultError;
514     if (mClient_2_3) {
515         mClient_2_3->getHdrCapabilities_2_3(display,
516                                             [&](const auto& tmpError, const auto& tmpTypes,
517                                                 const auto& tmpMaxLuminance,
518                                                 const auto& tmpMaxAverageLuminance,
519                                                 const auto& tmpMinLuminance) {
520                                                 error = tmpError;
521                                                 if (error != Error::NONE) {
522                                                     return;
523                                                 }
524 
525                                                 *outTypes = tmpTypes;
526                                                 *outMaxLuminance = tmpMaxLuminance;
527                                                 *outMaxAverageLuminance = tmpMaxAverageLuminance;
528                                                 *outMinLuminance = tmpMinLuminance;
529                                             });
530     } else {
531         mClient->getHdrCapabilities(display,
532                                     [&](const auto& tmpError, const auto& tmpTypes,
533                                         const auto& tmpMaxLuminance,
534                                         const auto& tmpMaxAverageLuminance,
535                                         const auto& tmpMinLuminance) {
536                                         error = tmpError;
537                                         if (error != Error::NONE) {
538                                             return;
539                                         }
540 
541                                         outTypes->clear();
542                                         for (auto type : tmpTypes) {
543                                             outTypes->push_back(static_cast<Hdr>(type));
544                                         }
545 
546                                         *outMaxLuminance = tmpMaxLuminance;
547                                         *outMaxAverageLuminance = tmpMaxAverageLuminance;
548                                         *outMinLuminance = tmpMinLuminance;
549                                     });
550     }
551 
552     return error;
553 }
554 
getReleaseFences(Display display,std::vector<Layer> * outLayers,std::vector<int> * outReleaseFences)555 Error Composer::getReleaseFences(Display display,
556         std::vector<Layer>* outLayers, std::vector<int>* outReleaseFences)
557 {
558     mReader.takeReleaseFences(display, outLayers, outReleaseFences);
559     return Error::NONE;
560 }
561 
presentDisplay(Display display,int * outPresentFence)562 Error Composer::presentDisplay(Display display, int* outPresentFence)
563 {
564     mWriter.selectDisplay(display);
565     mWriter.presentDisplay();
566 
567     Error error = execute();
568     if (error != Error::NONE) {
569         return error;
570     }
571 
572     mReader.takePresentFence(display, outPresentFence);
573 
574     return Error::NONE;
575 }
576 
setActiveConfig(Display display,Config config)577 Error Composer::setActiveConfig(Display display, Config config)
578 {
579     auto ret = mClient->setActiveConfig(display, config);
580     return unwrapRet(ret);
581 }
582 
setClientTarget(Display display,uint32_t slot,const sp<GraphicBuffer> & target,int acquireFence,Dataspace dataspace,const std::vector<IComposerClient::Rect> & damage)583 Error Composer::setClientTarget(Display display, uint32_t slot,
584         const sp<GraphicBuffer>& target,
585         int acquireFence, Dataspace dataspace,
586         const std::vector<IComposerClient::Rect>& damage)
587 {
588     mWriter.selectDisplay(display);
589 
590 #if defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
591     if (mIsUsingVrComposer && target.get()) {
592         IVrComposerClient::BufferMetadata metadata = {
593                 .width = target->getWidth(),
594                 .height = target->getHeight(),
595                 .stride = target->getStride(),
596                 .layerCount = target->getLayerCount(),
597                 .format = static_cast<types::V1_2::PixelFormat>(target->getPixelFormat()),
598                 .usage = target->getUsage(),
599         };
600         mWriter.setClientTargetMetadata(metadata);
601     }
602 #endif // defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
603 
604     const native_handle_t* handle = nullptr;
605     if (target.get()) {
606         handle = target->getNativeBuffer()->handle;
607     }
608 
609     mWriter.setClientTarget(slot, handle, acquireFence, dataspace, damage);
610     return Error::NONE;
611 }
612 
setColorMode(Display display,ColorMode mode,RenderIntent renderIntent)613 Error Composer::setColorMode(Display display, ColorMode mode,
614         RenderIntent renderIntent)
615 {
616     hardware::Return<Error> ret(kDefaultError);
617     if (mClient_2_3) {
618         ret = mClient_2_3->setColorMode_2_3(display, mode, renderIntent);
619     } else if (mClient_2_2) {
620         ret = mClient_2_2->setColorMode_2_2(display, static_cast<types::V1_1::ColorMode>(mode),
621                                             renderIntent);
622     } else {
623         ret = mClient->setColorMode(display,
624                 static_cast<types::V1_0::ColorMode>(mode));
625     }
626     return unwrapRet(ret);
627 }
628 
setColorTransform(Display display,const float * matrix,ColorTransform hint)629 Error Composer::setColorTransform(Display display, const float* matrix,
630         ColorTransform hint)
631 {
632     mWriter.selectDisplay(display);
633     mWriter.setColorTransform(matrix, hint);
634     return Error::NONE;
635 }
636 
setOutputBuffer(Display display,const native_handle_t * buffer,int releaseFence)637 Error Composer::setOutputBuffer(Display display, const native_handle_t* buffer,
638         int releaseFence)
639 {
640     mWriter.selectDisplay(display);
641     mWriter.setOutputBuffer(0, buffer, dup(releaseFence));
642     return Error::NONE;
643 }
644 
setPowerMode(Display display,IComposerClient::PowerMode mode)645 Error Composer::setPowerMode(Display display, IComposerClient::PowerMode mode) {
646     Return<Error> ret(Error::UNSUPPORTED);
647     if (mClient_2_2) {
648         ret = mClient_2_2->setPowerMode_2_2(display, mode);
649     } else if (mode != IComposerClient::PowerMode::ON_SUSPEND) {
650         ret = mClient->setPowerMode(display, static_cast<V2_1::IComposerClient::PowerMode>(mode));
651     }
652 
653     return unwrapRet(ret);
654 }
655 
setVsyncEnabled(Display display,IComposerClient::Vsync enabled)656 Error Composer::setVsyncEnabled(Display display, IComposerClient::Vsync enabled)
657 {
658     auto ret = mClient->setVsyncEnabled(display, enabled);
659     return unwrapRet(ret);
660 }
661 
setClientTargetSlotCount(Display display)662 Error Composer::setClientTargetSlotCount(Display display)
663 {
664     const uint32_t bufferSlotCount = BufferQueue::NUM_BUFFER_SLOTS;
665     auto ret = mClient->setClientTargetSlotCount(display, bufferSlotCount);
666     return unwrapRet(ret);
667 }
668 
validateDisplay(Display display,uint32_t * outNumTypes,uint32_t * outNumRequests)669 Error Composer::validateDisplay(Display display, uint32_t* outNumTypes,
670         uint32_t* outNumRequests)
671 {
672     mWriter.selectDisplay(display);
673     mWriter.validateDisplay();
674 
675     Error error = execute();
676     if (error != Error::NONE) {
677         return error;
678     }
679 
680     mReader.hasChanges(display, outNumTypes, outNumRequests);
681 
682     return Error::NONE;
683 }
684 
presentOrValidateDisplay(Display display,uint32_t * outNumTypes,uint32_t * outNumRequests,int * outPresentFence,uint32_t * state)685 Error Composer::presentOrValidateDisplay(Display display, uint32_t* outNumTypes,
686                                uint32_t* outNumRequests, int* outPresentFence, uint32_t* state) {
687    mWriter.selectDisplay(display);
688    mWriter.presentOrvalidateDisplay();
689 
690    Error error = execute();
691    if (error != Error::NONE) {
692        return error;
693    }
694 
695    mReader.takePresentOrValidateStage(display, state);
696 
697    if (*state == 1) { // Present succeeded
698        mReader.takePresentFence(display, outPresentFence);
699    }
700 
701    if (*state == 0) { // Validate succeeded.
702        mReader.hasChanges(display, outNumTypes, outNumRequests);
703    }
704 
705    return Error::NONE;
706 }
707 
setCursorPosition(Display display,Layer layer,int32_t x,int32_t y)708 Error Composer::setCursorPosition(Display display, Layer layer,
709         int32_t x, int32_t y)
710 {
711     mWriter.selectDisplay(display);
712     mWriter.selectLayer(layer);
713     mWriter.setLayerCursorPosition(x, y);
714     return Error::NONE;
715 }
716 
setLayerBuffer(Display display,Layer layer,uint32_t slot,const sp<GraphicBuffer> & buffer,int acquireFence)717 Error Composer::setLayerBuffer(Display display, Layer layer,
718         uint32_t slot, const sp<GraphicBuffer>& buffer, int acquireFence)
719 {
720     mWriter.selectDisplay(display);
721     mWriter.selectLayer(layer);
722 
723 #if defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
724     if (mIsUsingVrComposer && buffer.get()) {
725         IVrComposerClient::BufferMetadata metadata = {
726                 .width = buffer->getWidth(),
727                 .height = buffer->getHeight(),
728                 .stride = buffer->getStride(),
729                 .layerCount = buffer->getLayerCount(),
730                 .format = static_cast<types::V1_2::PixelFormat>(buffer->getPixelFormat()),
731                 .usage = buffer->getUsage(),
732         };
733         mWriter.setLayerBufferMetadata(metadata);
734     }
735 #endif // defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
736 
737     const native_handle_t* handle = nullptr;
738     if (buffer.get()) {
739         handle = buffer->getNativeBuffer()->handle;
740     }
741 
742     mWriter.setLayerBuffer(slot, handle, acquireFence);
743     return Error::NONE;
744 }
745 
setLayerSurfaceDamage(Display display,Layer layer,const std::vector<IComposerClient::Rect> & damage)746 Error Composer::setLayerSurfaceDamage(Display display, Layer layer,
747         const std::vector<IComposerClient::Rect>& damage)
748 {
749     mWriter.selectDisplay(display);
750     mWriter.selectLayer(layer);
751     mWriter.setLayerSurfaceDamage(damage);
752     return Error::NONE;
753 }
754 
setLayerBlendMode(Display display,Layer layer,IComposerClient::BlendMode mode)755 Error Composer::setLayerBlendMode(Display display, Layer layer,
756         IComposerClient::BlendMode mode)
757 {
758     mWriter.selectDisplay(display);
759     mWriter.selectLayer(layer);
760     mWriter.setLayerBlendMode(mode);
761     return Error::NONE;
762 }
763 
setLayerColor(Display display,Layer layer,const IComposerClient::Color & color)764 Error Composer::setLayerColor(Display display, Layer layer,
765         const IComposerClient::Color& color)
766 {
767     mWriter.selectDisplay(display);
768     mWriter.selectLayer(layer);
769     mWriter.setLayerColor(color);
770     return Error::NONE;
771 }
772 
setLayerCompositionType(Display display,Layer layer,IComposerClient::Composition type)773 Error Composer::setLayerCompositionType(Display display, Layer layer,
774         IComposerClient::Composition type)
775 {
776     mWriter.selectDisplay(display);
777     mWriter.selectLayer(layer);
778     mWriter.setLayerCompositionType(type);
779     return Error::NONE;
780 }
781 
setLayerDataspace(Display display,Layer layer,Dataspace dataspace)782 Error Composer::setLayerDataspace(Display display, Layer layer,
783         Dataspace dataspace)
784 {
785     mWriter.selectDisplay(display);
786     mWriter.selectLayer(layer);
787     mWriter.setLayerDataspace(dataspace);
788     return Error::NONE;
789 }
790 
setLayerDisplayFrame(Display display,Layer layer,const IComposerClient::Rect & frame)791 Error Composer::setLayerDisplayFrame(Display display, Layer layer,
792         const IComposerClient::Rect& frame)
793 {
794     mWriter.selectDisplay(display);
795     mWriter.selectLayer(layer);
796     mWriter.setLayerDisplayFrame(frame);
797     return Error::NONE;
798 }
799 
setLayerPlaneAlpha(Display display,Layer layer,float alpha)800 Error Composer::setLayerPlaneAlpha(Display display, Layer layer,
801         float alpha)
802 {
803     mWriter.selectDisplay(display);
804     mWriter.selectLayer(layer);
805     mWriter.setLayerPlaneAlpha(alpha);
806     return Error::NONE;
807 }
808 
setLayerSidebandStream(Display display,Layer layer,const native_handle_t * stream)809 Error Composer::setLayerSidebandStream(Display display, Layer layer,
810         const native_handle_t* stream)
811 {
812     mWriter.selectDisplay(display);
813     mWriter.selectLayer(layer);
814     mWriter.setLayerSidebandStream(stream);
815     return Error::NONE;
816 }
817 
setLayerSourceCrop(Display display,Layer layer,const IComposerClient::FRect & crop)818 Error Composer::setLayerSourceCrop(Display display, Layer layer,
819         const IComposerClient::FRect& crop)
820 {
821     mWriter.selectDisplay(display);
822     mWriter.selectLayer(layer);
823     mWriter.setLayerSourceCrop(crop);
824     return Error::NONE;
825 }
826 
setLayerTransform(Display display,Layer layer,Transform transform)827 Error Composer::setLayerTransform(Display display, Layer layer,
828         Transform transform)
829 {
830     mWriter.selectDisplay(display);
831     mWriter.selectLayer(layer);
832     mWriter.setLayerTransform(transform);
833     return Error::NONE;
834 }
835 
setLayerVisibleRegion(Display display,Layer layer,const std::vector<IComposerClient::Rect> & visible)836 Error Composer::setLayerVisibleRegion(Display display, Layer layer,
837         const std::vector<IComposerClient::Rect>& visible)
838 {
839     mWriter.selectDisplay(display);
840     mWriter.selectLayer(layer);
841     mWriter.setLayerVisibleRegion(visible);
842     return Error::NONE;
843 }
844 
setLayerZOrder(Display display,Layer layer,uint32_t z)845 Error Composer::setLayerZOrder(Display display, Layer layer, uint32_t z)
846 {
847     mWriter.selectDisplay(display);
848     mWriter.selectLayer(layer);
849     mWriter.setLayerZOrder(z);
850     return Error::NONE;
851 }
852 
853 #if defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
setLayerInfo(Display display,Layer layer,uint32_t type,uint32_t appId)854 Error Composer::setLayerInfo(Display display, Layer layer, uint32_t type,
855                              uint32_t appId)
856 {
857     if (mIsUsingVrComposer) {
858         mWriter.selectDisplay(display);
859         mWriter.selectLayer(layer);
860         mWriter.setLayerInfo(type, appId);
861     }
862     return Error::NONE;
863 }
864 #else
setLayerInfo(Display display,Layer layer,uint32_t,uint32_t)865 Error Composer::setLayerInfo(Display display, Layer layer, uint32_t, uint32_t) {
866     if (mIsUsingVrComposer) {
867         mWriter.selectDisplay(display);
868         mWriter.selectLayer(layer);
869     }
870     return Error::NONE;
871 }
872 #endif // defined(USE_VR_COMPOSER) && USE_VR_COMPOSER
873 
execute()874 Error Composer::execute()
875 {
876     // prepare input command queue
877     bool queueChanged = false;
878     uint32_t commandLength = 0;
879     hidl_vec<hidl_handle> commandHandles;
880     if (!mWriter.writeQueue(&queueChanged, &commandLength, &commandHandles)) {
881         mWriter.reset();
882         return Error::NO_RESOURCES;
883     }
884 
885     // set up new input command queue if necessary
886     if (queueChanged) {
887         auto ret = mClient->setInputCommandQueue(*mWriter.getMQDescriptor());
888         auto error = unwrapRet(ret);
889         if (error != Error::NONE) {
890             mWriter.reset();
891             return error;
892         }
893     }
894 
895     if (commandLength == 0) {
896         mWriter.reset();
897         return Error::NONE;
898     }
899 
900     Error error = kDefaultError;
901     hardware::Return<void> ret;
902     auto hidl_callback = [&](const auto& tmpError, const auto& tmpOutChanged,
903                              const auto& tmpOutLength, const auto& tmpOutHandles)
904                          {
905                              error = tmpError;
906 
907                              // set up new output command queue if necessary
908                              if (error == Error::NONE && tmpOutChanged) {
909                                  error = kDefaultError;
910                                  mClient->getOutputCommandQueue(
911                                      [&](const auto& tmpError,
912                                          const auto& tmpDescriptor)
913                                      {
914                                          error = tmpError;
915                                          if (error != Error::NONE) {
916                                              return;
917                                      }
918 
919                                      mReader.setMQDescriptor(tmpDescriptor);
920                                  });
921                              }
922 
923                              if (error != Error::NONE) {
924                                  return;
925                              }
926 
927                              if (mReader.readQueue(tmpOutLength, tmpOutHandles)) {
928                                  error = mReader.parse();
929                                  mReader.reset();
930                              } else {
931                                  error = Error::NO_RESOURCES;
932                              }
933                          };
934     if (mClient_2_2) {
935         ret = mClient_2_2->executeCommands_2_2(commandLength, commandHandles, hidl_callback);
936     } else {
937         ret = mClient->executeCommands(commandLength, commandHandles, hidl_callback);
938     }
939     // executeCommands can fail because of out-of-fd and we do not want to
940     // abort() in that case
941     if (!ret.isOk()) {
942         ALOGE("executeCommands failed because of %s", ret.description().c_str());
943     }
944 
945     if (error == Error::NONE) {
946         std::vector<CommandReader::CommandError> commandErrors =
947             mReader.takeErrors();
948 
949         for (const auto& cmdErr : commandErrors) {
950             auto command =
951                     static_cast<IComposerClient::Command>(mWriter.getCommand(cmdErr.location));
952 
953             if (command == IComposerClient::Command::VALIDATE_DISPLAY ||
954                 command == IComposerClient::Command::PRESENT_DISPLAY ||
955                 command == IComposerClient::Command::PRESENT_OR_VALIDATE_DISPLAY) {
956                 error = cmdErr.error;
957             } else {
958                 ALOGW("command 0x%x generated error %d",
959                         command, cmdErr.error);
960             }
961         }
962     }
963 
964     mWriter.reset();
965 
966     return error;
967 }
968 
969 // Composer HAL 2.2
970 
setLayerPerFrameMetadata(Display display,Layer layer,const std::vector<IComposerClient::PerFrameMetadata> & perFrameMetadatas)971 Error Composer::setLayerPerFrameMetadata(Display display, Layer layer,
972         const std::vector<IComposerClient::PerFrameMetadata>& perFrameMetadatas) {
973     if (!mClient_2_2) {
974         return Error::UNSUPPORTED;
975     }
976 
977     mWriter.selectDisplay(display);
978     mWriter.selectLayer(layer);
979     mWriter.setLayerPerFrameMetadata(perFrameMetadatas);
980     return Error::NONE;
981 }
982 
getPerFrameMetadataKeys(Display display)983 std::vector<IComposerClient::PerFrameMetadataKey> Composer::getPerFrameMetadataKeys(
984         Display display) {
985     std::vector<IComposerClient::PerFrameMetadataKey>  keys;
986     if (!mClient_2_2) {
987         return keys;
988     }
989 
990     Error error = kDefaultError;
991     if (mClient_2_3) {
992         mClient_2_3->getPerFrameMetadataKeys_2_3(display,
993                                                  [&](const auto& tmpError, const auto& tmpKeys) {
994                                                      error = tmpError;
995                                                      if (error != Error::NONE) {
996                                                          ALOGW("getPerFrameMetadataKeys failed "
997                                                                "with %d",
998                                                                tmpError);
999                                                          return;
1000                                                      }
1001                                                      keys = tmpKeys;
1002                                                  });
1003     } else {
1004         mClient_2_2
1005                 ->getPerFrameMetadataKeys(display, [&](const auto& tmpError, const auto& tmpKeys) {
1006                     error = tmpError;
1007                     if (error != Error::NONE) {
1008                         ALOGW("getPerFrameMetadataKeys failed with %d", tmpError);
1009                         return;
1010                     }
1011 
1012                     keys.clear();
1013                     for (auto key : tmpKeys) {
1014                         keys.push_back(static_cast<IComposerClient::PerFrameMetadataKey>(key));
1015                     }
1016                 });
1017     }
1018 
1019     return keys;
1020 }
1021 
getRenderIntents(Display display,ColorMode colorMode,std::vector<RenderIntent> * outRenderIntents)1022 Error Composer::getRenderIntents(Display display, ColorMode colorMode,
1023         std::vector<RenderIntent>* outRenderIntents) {
1024     if (!mClient_2_2) {
1025         outRenderIntents->push_back(RenderIntent::COLORIMETRIC);
1026         return Error::NONE;
1027     }
1028 
1029     Error error = kDefaultError;
1030 
1031     auto getRenderIntentsLambda = [&](const auto& tmpError, const auto& tmpKeys) {
1032         error = tmpError;
1033         if (error != Error::NONE) {
1034             return;
1035         }
1036 
1037         *outRenderIntents = tmpKeys;
1038     };
1039 
1040     if (mClient_2_3) {
1041         mClient_2_3->getRenderIntents_2_3(display, colorMode, getRenderIntentsLambda);
1042     } else {
1043         mClient_2_2->getRenderIntents(display, static_cast<types::V1_1::ColorMode>(colorMode),
1044                                       getRenderIntentsLambda);
1045     }
1046 
1047     return error;
1048 }
1049 
getDataspaceSaturationMatrix(Dataspace dataspace,mat4 * outMatrix)1050 Error Composer::getDataspaceSaturationMatrix(Dataspace dataspace, mat4* outMatrix)
1051 {
1052     if (!mClient_2_2) {
1053         *outMatrix = mat4();
1054         return Error::NONE;
1055     }
1056 
1057     Error error = kDefaultError;
1058     mClient_2_2->getDataspaceSaturationMatrix(static_cast<types::V1_1::Dataspace>(dataspace),
1059                                               [&](const auto& tmpError, const auto& tmpMatrix) {
1060                                                   error = tmpError;
1061                                                   if (error != Error::NONE) {
1062                                                       return;
1063                                                   }
1064                                                   *outMatrix = mat4(tmpMatrix.data());
1065                                               });
1066 
1067     return error;
1068 }
1069 
1070 // Composer HAL 2.3
1071 
getDisplayIdentificationData(Display display,uint8_t * outPort,std::vector<uint8_t> * outData)1072 Error Composer::getDisplayIdentificationData(Display display, uint8_t* outPort,
1073                                              std::vector<uint8_t>* outData) {
1074     if (!mClient_2_3) {
1075         return Error::UNSUPPORTED;
1076     }
1077 
1078     Error error = kDefaultError;
1079     mClient_2_3->getDisplayIdentificationData(display,
1080                                               [&](const auto& tmpError, const auto& tmpPort,
1081                                                   const auto& tmpData) {
1082                                                   error = tmpError;
1083                                                   if (error != Error::NONE) {
1084                                                       return;
1085                                                   }
1086 
1087                                                   *outPort = tmpPort;
1088                                                   *outData = tmpData;
1089                                               });
1090 
1091     return error;
1092 }
1093 
setLayerColorTransform(Display display,Layer layer,const float * matrix)1094 Error Composer::setLayerColorTransform(Display display, Layer layer, const float* matrix)
1095 {
1096     if (!mClient_2_3) {
1097         return Error::UNSUPPORTED;
1098     }
1099 
1100     mWriter.selectDisplay(display);
1101     mWriter.selectLayer(layer);
1102     mWriter.setLayerColorTransform(matrix);
1103     return Error::NONE;
1104 }
1105 
getDisplayedContentSamplingAttributes(Display display,PixelFormat * outFormat,Dataspace * outDataspace,uint8_t * outComponentMask)1106 Error Composer::getDisplayedContentSamplingAttributes(Display display, PixelFormat* outFormat,
1107                                                       Dataspace* outDataspace,
1108                                                       uint8_t* outComponentMask) {
1109     if (!outFormat || !outDataspace || !outComponentMask) {
1110         return Error::BAD_PARAMETER;
1111     }
1112     if (!mClient_2_3) {
1113         return Error::UNSUPPORTED;
1114     }
1115     Error error = kDefaultError;
1116     mClient_2_3->getDisplayedContentSamplingAttributes(display,
1117                                                        [&](const auto tmpError,
1118                                                            const auto& tmpFormat,
1119                                                            const auto& tmpDataspace,
1120                                                            const auto& tmpComponentMask) {
1121                                                            error = tmpError;
1122                                                            if (error == Error::NONE) {
1123                                                                *outFormat = tmpFormat;
1124                                                                *outDataspace = tmpDataspace;
1125                                                                *outComponentMask =
1126                                                                        static_cast<uint8_t>(
1127                                                                                tmpComponentMask);
1128                                                            }
1129                                                        });
1130     return error;
1131 }
1132 
setDisplayContentSamplingEnabled(Display display,bool enabled,uint8_t componentMask,uint64_t maxFrames)1133 Error Composer::setDisplayContentSamplingEnabled(Display display, bool enabled,
1134                                                  uint8_t componentMask, uint64_t maxFrames) {
1135     if (!mClient_2_3) {
1136         return Error::UNSUPPORTED;
1137     }
1138 
1139     auto enable = enabled ? V2_3::IComposerClient::DisplayedContentSampling::ENABLE
1140                           : V2_3::IComposerClient::DisplayedContentSampling::DISABLE;
1141     return mClient_2_3->setDisplayedContentSamplingEnabled(display, enable, componentMask,
1142                                                            maxFrames);
1143 }
1144 
getDisplayedContentSample(Display display,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats)1145 Error Composer::getDisplayedContentSample(Display display, uint64_t maxFrames, uint64_t timestamp,
1146                                           DisplayedFrameStats* outStats) {
1147     if (!outStats) {
1148         return Error::BAD_PARAMETER;
1149     }
1150     if (!mClient_2_3) {
1151         return Error::UNSUPPORTED;
1152     }
1153     Error error = kDefaultError;
1154     mClient_2_3->getDisplayedContentSample(display, maxFrames, timestamp,
1155                                            [&](const auto tmpError, auto tmpNumFrames,
1156                                                const auto& tmpSamples0, const auto& tmpSamples1,
1157                                                const auto& tmpSamples2, const auto& tmpSamples3) {
1158                                                error = tmpError;
1159                                                if (error == Error::NONE) {
1160                                                    outStats->numFrames = tmpNumFrames;
1161                                                    outStats->component_0_sample = tmpSamples0;
1162                                                    outStats->component_1_sample = tmpSamples1;
1163                                                    outStats->component_2_sample = tmpSamples2;
1164                                                    outStats->component_3_sample = tmpSamples3;
1165                                                }
1166                                            });
1167     return error;
1168 }
1169 
setLayerPerFrameMetadataBlobs(Display display,Layer layer,const std::vector<IComposerClient::PerFrameMetadataBlob> & metadata)1170 Error Composer::setLayerPerFrameMetadataBlobs(
1171         Display display, Layer layer,
1172         const std::vector<IComposerClient::PerFrameMetadataBlob>& metadata) {
1173     if (!mClient_2_3) {
1174         return Error::UNSUPPORTED;
1175     }
1176 
1177     mWriter.selectDisplay(display);
1178     mWriter.selectLayer(layer);
1179     mWriter.setLayerPerFrameMetadataBlobs(metadata);
1180     return Error::NONE;
1181 }
1182 
setDisplayBrightness(Display display,float brightness)1183 Error Composer::setDisplayBrightness(Display display, float brightness) {
1184     if (!mClient_2_3) {
1185         return Error::UNSUPPORTED;
1186     }
1187     return mClient_2_3->setDisplayBrightness(display, brightness);
1188 }
1189 
1190 // Composer HAL 2.4
1191 
getDisplayCapabilities(Display display,std::vector<DisplayCapability> * outCapabilities)1192 Error Composer::getDisplayCapabilities(Display display,
1193                                        std::vector<DisplayCapability>* outCapabilities) {
1194     if (!mClient_2_3) {
1195         return Error::UNSUPPORTED;
1196     }
1197 
1198     V2_4::Error error = kDefaultError_2_4;
1199     if (mClient_2_4) {
1200         mClient_2_4->getDisplayCapabilities_2_4(display,
1201                                                 [&](const auto& tmpError, const auto& tmpCaps) {
1202                                                     error = tmpError;
1203                                                     if (error != V2_4::Error::NONE) {
1204                                                         return;
1205                                                     }
1206                                                     *outCapabilities = tmpCaps;
1207                                                 });
1208     } else {
1209         mClient_2_3
1210                 ->getDisplayCapabilities(display, [&](const auto& tmpError, const auto& tmpCaps) {
1211                     error = static_cast<V2_4::Error>(tmpError);
1212                     if (error != V2_4::Error::NONE) {
1213                         return;
1214                     }
1215 
1216                     outCapabilities->resize(tmpCaps.size());
1217                     std::transform(tmpCaps.begin(), tmpCaps.end(), outCapabilities->begin(),
1218                                    [](auto cap) { return static_cast<DisplayCapability>(cap); });
1219                 });
1220     }
1221 
1222     return static_cast<Error>(error);
1223 }
1224 
getDisplayConnectionType(Display display,IComposerClient::DisplayConnectionType * outType)1225 V2_4::Error Composer::getDisplayConnectionType(Display display,
1226                                                IComposerClient::DisplayConnectionType* outType) {
1227     using Error = V2_4::Error;
1228     if (!mClient_2_4) {
1229         return Error::UNSUPPORTED;
1230     }
1231 
1232     Error error = kDefaultError_2_4;
1233     mClient_2_4->getDisplayConnectionType(display, [&](const auto& tmpError, const auto& tmpType) {
1234         error = tmpError;
1235         if (error != V2_4::Error::NONE) {
1236             return;
1237         }
1238 
1239         *outType = tmpType;
1240     });
1241 
1242     return error;
1243 }
1244 
getDisplayVsyncPeriod(Display display,VsyncPeriodNanos * outVsyncPeriod)1245 V2_4::Error Composer::getDisplayVsyncPeriod(Display display, VsyncPeriodNanos* outVsyncPeriod) {
1246     using Error = V2_4::Error;
1247     if (!mClient_2_4) {
1248         return Error::UNSUPPORTED;
1249     }
1250 
1251     Error error = kDefaultError_2_4;
1252     mClient_2_4->getDisplayVsyncPeriod(display,
1253                                        [&](const auto& tmpError, const auto& tmpVsyncPeriod) {
1254                                            error = tmpError;
1255                                            if (error != Error::NONE) {
1256                                                return;
1257                                            }
1258 
1259                                            *outVsyncPeriod = tmpVsyncPeriod;
1260                                        });
1261 
1262     return error;
1263 }
1264 
setActiveConfigWithConstraints(Display display,Config config,const IComposerClient::VsyncPeriodChangeConstraints & vsyncPeriodChangeConstraints,VsyncPeriodChangeTimeline * outTimeline)1265 V2_4::Error Composer::setActiveConfigWithConstraints(
1266         Display display, Config config,
1267         const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
1268         VsyncPeriodChangeTimeline* outTimeline) {
1269     using Error = V2_4::Error;
1270     if (!mClient_2_4) {
1271         return Error::UNSUPPORTED;
1272     }
1273 
1274     Error error = kDefaultError_2_4;
1275     mClient_2_4->setActiveConfigWithConstraints(display, config, vsyncPeriodChangeConstraints,
1276                                                 [&](const auto& tmpError, const auto& tmpTimeline) {
1277                                                     error = tmpError;
1278                                                     if (error != Error::NONE) {
1279                                                         return;
1280                                                     }
1281 
1282                                                     *outTimeline = tmpTimeline;
1283                                                 });
1284 
1285     return error;
1286 }
1287 
setAutoLowLatencyMode(Display display,bool on)1288 V2_4::Error Composer::setAutoLowLatencyMode(Display display, bool on) {
1289     using Error = V2_4::Error;
1290     if (!mClient_2_4) {
1291         return Error::UNSUPPORTED;
1292     }
1293 
1294     return mClient_2_4->setAutoLowLatencyMode(display, on);
1295 }
1296 
getSupportedContentTypes(Display displayId,std::vector<IComposerClient::ContentType> * outSupportedContentTypes)1297 V2_4::Error Composer::getSupportedContentTypes(
1298         Display displayId, std::vector<IComposerClient::ContentType>* outSupportedContentTypes) {
1299     using Error = V2_4::Error;
1300     if (!mClient_2_4) {
1301         return Error::UNSUPPORTED;
1302     }
1303 
1304     Error error = kDefaultError_2_4;
1305     mClient_2_4->getSupportedContentTypes(displayId,
1306                                           [&](const auto& tmpError,
1307                                               const auto& tmpSupportedContentTypes) {
1308                                               error = tmpError;
1309                                               if (error != Error::NONE) {
1310                                                   return;
1311                                               }
1312 
1313                                               *outSupportedContentTypes = tmpSupportedContentTypes;
1314                                           });
1315     return error;
1316 }
1317 
setContentType(Display display,IComposerClient::ContentType contentType)1318 V2_4::Error Composer::setContentType(Display display, IComposerClient::ContentType contentType) {
1319     using Error = V2_4::Error;
1320     if (!mClient_2_4) {
1321         return Error::UNSUPPORTED;
1322     }
1323 
1324     return mClient_2_4->setContentType(display, contentType);
1325 }
1326 
setLayerGenericMetadata(Display display,Layer layer,const std::string & key,bool mandatory,const std::vector<uint8_t> & value)1327 V2_4::Error Composer::setLayerGenericMetadata(Display display, Layer layer, const std::string& key,
1328                                               bool mandatory, const std::vector<uint8_t>& value) {
1329     using Error = V2_4::Error;
1330     if (!mClient_2_4) {
1331         return Error::UNSUPPORTED;
1332     }
1333     mWriter.selectDisplay(display);
1334     mWriter.selectLayer(layer);
1335     mWriter.setLayerGenericMetadata(key, mandatory, value);
1336     return Error::NONE;
1337 }
1338 
getLayerGenericMetadataKeys(std::vector<IComposerClient::LayerGenericMetadataKey> * outKeys)1339 V2_4::Error Composer::getLayerGenericMetadataKeys(
1340         std::vector<IComposerClient::LayerGenericMetadataKey>* outKeys) {
1341     using Error = V2_4::Error;
1342     if (!mClient_2_4) {
1343         return Error::UNSUPPORTED;
1344     }
1345     Error error = kDefaultError_2_4;
1346     mClient_2_4->getLayerGenericMetadataKeys([&](const auto& tmpError, const auto& tmpKeys) {
1347         error = tmpError;
1348         if (error != Error::NONE) {
1349             return;
1350         }
1351 
1352         *outKeys = tmpKeys;
1353     });
1354     return error;
1355 }
1356 
getClientTargetProperty(Display display,IComposerClient::ClientTargetProperty * outClientTargetProperty)1357 Error Composer::getClientTargetProperty(
1358         Display display, IComposerClient::ClientTargetProperty* outClientTargetProperty) {
1359     mReader.takeClientTargetProperty(display, outClientTargetProperty);
1360     return Error::NONE;
1361 }
1362 
~CommandReader()1363 CommandReader::~CommandReader()
1364 {
1365     resetData();
1366 }
1367 
parse()1368 Error CommandReader::parse()
1369 {
1370     resetData();
1371 
1372     IComposerClient::Command command;
1373     uint16_t length = 0;
1374 
1375     while (!isEmpty()) {
1376         if (!beginCommand(&command, &length)) {
1377             break;
1378         }
1379 
1380         bool parsed = false;
1381         switch (command) {
1382         case IComposerClient::Command::SELECT_DISPLAY:
1383             parsed = parseSelectDisplay(length);
1384             break;
1385         case IComposerClient::Command::SET_ERROR:
1386             parsed = parseSetError(length);
1387             break;
1388         case IComposerClient::Command::SET_CHANGED_COMPOSITION_TYPES:
1389             parsed = parseSetChangedCompositionTypes(length);
1390             break;
1391         case IComposerClient::Command::SET_DISPLAY_REQUESTS:
1392             parsed = parseSetDisplayRequests(length);
1393             break;
1394         case IComposerClient::Command::SET_PRESENT_FENCE:
1395             parsed = parseSetPresentFence(length);
1396             break;
1397         case IComposerClient::Command::SET_RELEASE_FENCES:
1398             parsed = parseSetReleaseFences(length);
1399             break;
1400         case IComposerClient::Command ::SET_PRESENT_OR_VALIDATE_DISPLAY_RESULT:
1401             parsed = parseSetPresentOrValidateDisplayResult(length);
1402             break;
1403         case IComposerClient::Command::SET_CLIENT_TARGET_PROPERTY:
1404             parsed = parseSetClientTargetProperty(length);
1405             break;
1406         default:
1407             parsed = false;
1408             break;
1409         }
1410 
1411         endCommand();
1412 
1413         if (!parsed) {
1414             ALOGE("failed to parse command 0x%x length %" PRIu16,
1415                     command, length);
1416             break;
1417         }
1418     }
1419 
1420     return isEmpty() ? Error::NONE : Error::NO_RESOURCES;
1421 }
1422 
parseSelectDisplay(uint16_t length)1423 bool CommandReader::parseSelectDisplay(uint16_t length)
1424 {
1425     if (length != CommandWriterBase::kSelectDisplayLength) {
1426         return false;
1427     }
1428 
1429     mCurrentReturnData = &mReturnData[read64()];
1430 
1431     return true;
1432 }
1433 
parseSetError(uint16_t length)1434 bool CommandReader::parseSetError(uint16_t length)
1435 {
1436     if (length != CommandWriterBase::kSetErrorLength) {
1437         return false;
1438     }
1439 
1440     auto location = read();
1441     auto error = static_cast<Error>(readSigned());
1442 
1443     mErrors.emplace_back(CommandError{location, error});
1444 
1445     return true;
1446 }
1447 
parseSetChangedCompositionTypes(uint16_t length)1448 bool CommandReader::parseSetChangedCompositionTypes(uint16_t length)
1449 {
1450     // (layer id, composition type) pairs
1451     if (length % 3 != 0 || !mCurrentReturnData) {
1452         return false;
1453     }
1454 
1455     uint32_t count = length / 3;
1456     mCurrentReturnData->changedLayers.reserve(count);
1457     mCurrentReturnData->compositionTypes.reserve(count);
1458     while (count > 0) {
1459         auto layer = read64();
1460         auto type = static_cast<IComposerClient::Composition>(readSigned());
1461 
1462         mCurrentReturnData->changedLayers.push_back(layer);
1463         mCurrentReturnData->compositionTypes.push_back(type);
1464 
1465         count--;
1466     }
1467 
1468     return true;
1469 }
1470 
parseSetDisplayRequests(uint16_t length)1471 bool CommandReader::parseSetDisplayRequests(uint16_t length)
1472 {
1473     // display requests followed by (layer id, layer requests) pairs
1474     if (length % 3 != 1 || !mCurrentReturnData) {
1475         return false;
1476     }
1477 
1478     mCurrentReturnData->displayRequests = read();
1479 
1480     uint32_t count = (length - 1) / 3;
1481     mCurrentReturnData->requestedLayers.reserve(count);
1482     mCurrentReturnData->requestMasks.reserve(count);
1483     while (count > 0) {
1484         auto layer = read64();
1485         auto layerRequestMask = read();
1486 
1487         mCurrentReturnData->requestedLayers.push_back(layer);
1488         mCurrentReturnData->requestMasks.push_back(layerRequestMask);
1489 
1490         count--;
1491     }
1492 
1493     return true;
1494 }
1495 
parseSetPresentFence(uint16_t length)1496 bool CommandReader::parseSetPresentFence(uint16_t length)
1497 {
1498     if (length != CommandWriterBase::kSetPresentFenceLength ||
1499             !mCurrentReturnData) {
1500         return false;
1501     }
1502 
1503     if (mCurrentReturnData->presentFence >= 0) {
1504         close(mCurrentReturnData->presentFence);
1505     }
1506     mCurrentReturnData->presentFence = readFence();
1507 
1508     return true;
1509 }
1510 
parseSetReleaseFences(uint16_t length)1511 bool CommandReader::parseSetReleaseFences(uint16_t length)
1512 {
1513     // (layer id, release fence index) pairs
1514     if (length % 3 != 0 || !mCurrentReturnData) {
1515         return false;
1516     }
1517 
1518     uint32_t count = length / 3;
1519     mCurrentReturnData->releasedLayers.reserve(count);
1520     mCurrentReturnData->releaseFences.reserve(count);
1521     while (count > 0) {
1522         auto layer = read64();
1523         auto fence = readFence();
1524 
1525         mCurrentReturnData->releasedLayers.push_back(layer);
1526         mCurrentReturnData->releaseFences.push_back(fence);
1527 
1528         count--;
1529     }
1530 
1531     return true;
1532 }
1533 
parseSetPresentOrValidateDisplayResult(uint16_t length)1534 bool CommandReader::parseSetPresentOrValidateDisplayResult(uint16_t length)
1535 {
1536     if (length != CommandWriterBase::kPresentOrValidateDisplayResultLength || !mCurrentReturnData) {
1537         return false;
1538     }
1539     mCurrentReturnData->presentOrValidateState = read();
1540     return true;
1541 }
1542 
parseSetClientTargetProperty(uint16_t length)1543 bool CommandReader::parseSetClientTargetProperty(uint16_t length) {
1544     if (length != CommandWriterBase::kSetClientTargetPropertyLength || !mCurrentReturnData) {
1545         return false;
1546     }
1547     mCurrentReturnData->clientTargetProperty.pixelFormat = static_cast<PixelFormat>(readSigned());
1548     mCurrentReturnData->clientTargetProperty.dataspace = static_cast<Dataspace>(readSigned());
1549     return true;
1550 }
1551 
resetData()1552 void CommandReader::resetData()
1553 {
1554     mErrors.clear();
1555 
1556     for (auto& data : mReturnData) {
1557         if (data.second.presentFence >= 0) {
1558             close(data.second.presentFence);
1559         }
1560         for (auto fence : data.second.releaseFences) {
1561             if (fence >= 0) {
1562                 close(fence);
1563             }
1564         }
1565     }
1566 
1567     mReturnData.clear();
1568     mCurrentReturnData = nullptr;
1569 }
1570 
takeErrors()1571 std::vector<CommandReader::CommandError> CommandReader::takeErrors()
1572 {
1573     return std::move(mErrors);
1574 }
1575 
hasChanges(Display display,uint32_t * outNumChangedCompositionTypes,uint32_t * outNumLayerRequestMasks) const1576 bool CommandReader::hasChanges(Display display,
1577         uint32_t* outNumChangedCompositionTypes,
1578         uint32_t* outNumLayerRequestMasks) const
1579 {
1580     auto found = mReturnData.find(display);
1581     if (found == mReturnData.end()) {
1582         *outNumChangedCompositionTypes = 0;
1583         *outNumLayerRequestMasks = 0;
1584         return false;
1585     }
1586 
1587     const ReturnData& data = found->second;
1588 
1589     *outNumChangedCompositionTypes = data.compositionTypes.size();
1590     *outNumLayerRequestMasks = data.requestMasks.size();
1591 
1592     return !(data.compositionTypes.empty() && data.requestMasks.empty());
1593 }
1594 
takeChangedCompositionTypes(Display display,std::vector<Layer> * outLayers,std::vector<IComposerClient::Composition> * outTypes)1595 void CommandReader::takeChangedCompositionTypes(Display display,
1596         std::vector<Layer>* outLayers,
1597         std::vector<IComposerClient::Composition>* outTypes)
1598 {
1599     auto found = mReturnData.find(display);
1600     if (found == mReturnData.end()) {
1601         outLayers->clear();
1602         outTypes->clear();
1603         return;
1604     }
1605 
1606     ReturnData& data = found->second;
1607 
1608     *outLayers = std::move(data.changedLayers);
1609     *outTypes = std::move(data.compositionTypes);
1610 }
1611 
takeDisplayRequests(Display display,uint32_t * outDisplayRequestMask,std::vector<Layer> * outLayers,std::vector<uint32_t> * outLayerRequestMasks)1612 void CommandReader::takeDisplayRequests(Display display,
1613         uint32_t* outDisplayRequestMask, std::vector<Layer>* outLayers,
1614         std::vector<uint32_t>* outLayerRequestMasks)
1615 {
1616     auto found = mReturnData.find(display);
1617     if (found == mReturnData.end()) {
1618         *outDisplayRequestMask = 0;
1619         outLayers->clear();
1620         outLayerRequestMasks->clear();
1621         return;
1622     }
1623 
1624     ReturnData& data = found->second;
1625 
1626     *outDisplayRequestMask = data.displayRequests;
1627     *outLayers = std::move(data.requestedLayers);
1628     *outLayerRequestMasks = std::move(data.requestMasks);
1629 }
1630 
takeReleaseFences(Display display,std::vector<Layer> * outLayers,std::vector<int> * outReleaseFences)1631 void CommandReader::takeReleaseFences(Display display,
1632         std::vector<Layer>* outLayers, std::vector<int>* outReleaseFences)
1633 {
1634     auto found = mReturnData.find(display);
1635     if (found == mReturnData.end()) {
1636         outLayers->clear();
1637         outReleaseFences->clear();
1638         return;
1639     }
1640 
1641     ReturnData& data = found->second;
1642 
1643     *outLayers = std::move(data.releasedLayers);
1644     *outReleaseFences = std::move(data.releaseFences);
1645 }
1646 
takePresentFence(Display display,int * outPresentFence)1647 void CommandReader::takePresentFence(Display display, int* outPresentFence)
1648 {
1649     auto found = mReturnData.find(display);
1650     if (found == mReturnData.end()) {
1651         *outPresentFence = -1;
1652         return;
1653     }
1654 
1655     ReturnData& data = found->second;
1656 
1657     *outPresentFence = data.presentFence;
1658     data.presentFence = -1;
1659 }
1660 
takePresentOrValidateStage(Display display,uint32_t * state)1661 void CommandReader::takePresentOrValidateStage(Display display, uint32_t* state) {
1662     auto found = mReturnData.find(display);
1663     if (found == mReturnData.end()) {
1664         *state= -1;
1665         return;
1666     }
1667     ReturnData& data = found->second;
1668     *state = data.presentOrValidateState;
1669 }
1670 
takeClientTargetProperty(Display display,IComposerClient::ClientTargetProperty * outClientTargetProperty)1671 void CommandReader::takeClientTargetProperty(
1672         Display display, IComposerClient::ClientTargetProperty* outClientTargetProperty) {
1673     auto found = mReturnData.find(display);
1674 
1675     // If not found, return the default values.
1676     if (found == mReturnData.end()) {
1677         outClientTargetProperty->pixelFormat = PixelFormat::RGBA_8888;
1678         outClientTargetProperty->dataspace = Dataspace::UNKNOWN;
1679         return;
1680     }
1681 
1682     ReturnData& data = found->second;
1683     *outClientTargetProperty = data.clientTargetProperty;
1684 }
1685 
1686 } // namespace impl
1687 } // namespace Hwc2
1688 } // namespace android
1689 
1690 // TODO(b/129481165): remove the #pragma below and fix conversion issues
1691 #pragma clang diagnostic pop // ignored "-Wconversion"
1692