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