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