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