• 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 #include <gui/BufferQueue.h>
23 
24 #include "ComposerHal.h"
25 
26 namespace android {
27 
28 using hardware::Return;
29 using hardware::hidl_vec;
30 using hardware::hidl_handle;
31 
32 namespace Hwc2 {
33 
34 namespace {
35 
36 class BufferHandle {
37 public:
BufferHandle(const native_handle_t * buffer)38     BufferHandle(const native_handle_t* buffer)
39     {
40         // nullptr is not a valid handle to HIDL
41         mHandle = (buffer) ? buffer : native_handle_init(mStorage, 0, 0);
42     }
43 
operator const hidl_handle&() const44     operator const hidl_handle&() const
45     {
46         return mHandle;
47     }
48 
49 private:
50     NATIVE_HANDLE_DECLARE_STORAGE(mStorage, 0, 0);
51     hidl_handle mHandle;
52 };
53 
54 class FenceHandle
55 {
56 public:
FenceHandle(int fd,bool owned)57     FenceHandle(int fd, bool owned)
58         : mOwned(owned)
59     {
60         native_handle_t* handle;
61         if (fd >= 0) {
62             handle = native_handle_init(mStorage, 1, 0);
63             handle->data[0] = fd;
64         } else {
65             // nullptr is not a valid handle to HIDL
66             handle = native_handle_init(mStorage, 0, 0);
67         }
68         mHandle = handle;
69     }
70 
~FenceHandle()71     ~FenceHandle()
72     {
73         if (mOwned) {
74             native_handle_close(mHandle);
75         }
76     }
77 
operator const hidl_handle&() const78     operator const hidl_handle&() const
79     {
80         return mHandle;
81     }
82 
83 private:
84     bool mOwned;
85     NATIVE_HANDLE_DECLARE_STORAGE(mStorage, 1, 0);
86     hidl_handle mHandle;
87 };
88 
89 // assume NO_RESOURCES when Status::isOk returns false
90 constexpr Error kDefaultError = Error::NO_RESOURCES;
91 
92 template<typename T, typename U>
unwrapRet(Return<T> & ret,const U & default_val)93 T unwrapRet(Return<T>& ret, const U& default_val)
94 {
95     return (ret.isOk()) ? static_cast<T>(ret) :
96         static_cast<T>(default_val);
97 }
98 
unwrapRet(Return<Error> & ret)99 Error unwrapRet(Return<Error>& ret)
100 {
101     return unwrapRet(ret, kDefaultError);
102 }
103 
104 } // anonymous namespace
105 
CommandWriter(uint32_t initialMaxSize)106 Composer::CommandWriter::CommandWriter(uint32_t initialMaxSize)
107     : CommandWriterBase(initialMaxSize) {}
108 
~CommandWriter()109 Composer::CommandWriter::~CommandWriter()
110 {
111 }
112 
setLayerInfo(uint32_t type,uint32_t appId)113 void Composer::CommandWriter::setLayerInfo(uint32_t type, uint32_t appId)
114 {
115     constexpr uint16_t kSetLayerInfoLength = 2;
116     beginCommand(
117         static_cast<IComposerClient::Command>(
118             IVrComposerClient::VrCommand::SET_LAYER_INFO),
119         kSetLayerInfoLength);
120     write(type);
121     write(appId);
122     endCommand();
123 }
124 
setClientTargetMetadata(const IVrComposerClient::BufferMetadata & metadata)125 void Composer::CommandWriter::setClientTargetMetadata(
126         const IVrComposerClient::BufferMetadata& metadata)
127 {
128     constexpr uint16_t kSetClientTargetMetadataLength = 7;
129     beginCommand(
130         static_cast<IComposerClient::Command>(
131             IVrComposerClient::VrCommand::SET_CLIENT_TARGET_METADATA),
132         kSetClientTargetMetadataLength);
133     writeBufferMetadata(metadata);
134     endCommand();
135 }
136 
setLayerBufferMetadata(const IVrComposerClient::BufferMetadata & metadata)137 void Composer::CommandWriter::setLayerBufferMetadata(
138         const IVrComposerClient::BufferMetadata& metadata)
139 {
140     constexpr uint16_t kSetLayerBufferMetadataLength = 7;
141     beginCommand(
142         static_cast<IComposerClient::Command>(
143             IVrComposerClient::VrCommand::SET_LAYER_BUFFER_METADATA),
144         kSetLayerBufferMetadataLength);
145     writeBufferMetadata(metadata);
146     endCommand();
147 }
148 
writeBufferMetadata(const IVrComposerClient::BufferMetadata & metadata)149 void Composer::CommandWriter::writeBufferMetadata(
150         const IVrComposerClient::BufferMetadata& metadata)
151 {
152     write(metadata.width);
153     write(metadata.height);
154     write(metadata.stride);
155     write(metadata.layerCount);
156     writeSigned(static_cast<int32_t>(metadata.format));
157     write64(metadata.usage);
158 }
159 
Composer(bool useVrComposer)160 Composer::Composer(bool useVrComposer)
161     : mWriter(kWriterInitialSize),
162       mIsUsingVrComposer(useVrComposer)
163 {
164     if (mIsUsingVrComposer) {
165         mComposer = IComposer::getService("vr");
166     } else {
167         mComposer = IComposer::getService(); // use default name
168     }
169 
170     if (mComposer == nullptr) {
171         LOG_ALWAYS_FATAL("failed to get hwcomposer service");
172     }
173 
174     mComposer->createClient(
175             [&](const auto& tmpError, const auto& tmpClient)
176             {
177                 if (tmpError == Error::NONE) {
178                     mClient = tmpClient;
179                 }
180             });
181     if (mClient == nullptr) {
182         LOG_ALWAYS_FATAL("failed to create composer client");
183     }
184 
185     if (mIsUsingVrComposer) {
186         sp<IVrComposerClient> vrClient = IVrComposerClient::castFrom(mClient);
187         if (vrClient == nullptr) {
188             LOG_ALWAYS_FATAL("failed to create vr composer client");
189         }
190     }
191 }
192 
getCapabilities()193 std::vector<IComposer::Capability> Composer::getCapabilities()
194 {
195     std::vector<IComposer::Capability> capabilities;
196     mComposer->getCapabilities(
197             [&](const auto& tmpCapabilities) {
198                 capabilities = tmpCapabilities;
199             });
200 
201     return capabilities;
202 }
203 
dumpDebugInfo()204 std::string Composer::dumpDebugInfo()
205 {
206     std::string info;
207     mComposer->dumpDebugInfo([&](const auto& tmpInfo) {
208         info = tmpInfo.c_str();
209     });
210 
211     return info;
212 }
213 
registerCallback(const sp<IComposerCallback> & callback)214 void Composer::registerCallback(const sp<IComposerCallback>& callback)
215 {
216     auto ret = mClient->registerCallback(callback);
217     if (!ret.isOk()) {
218         ALOGE("failed to register IComposerCallback");
219     }
220 }
221 
isRemote()222 bool Composer::isRemote() {
223     return mClient->isRemote();
224 }
225 
resetCommands()226 void Composer::resetCommands() {
227     mWriter.reset();
228 }
229 
getMaxVirtualDisplayCount()230 uint32_t Composer::getMaxVirtualDisplayCount()
231 {
232     auto ret = mClient->getMaxVirtualDisplayCount();
233     return unwrapRet(ret, 0);
234 }
235 
createVirtualDisplay(uint32_t width,uint32_t height,PixelFormat * format,Display * outDisplay)236 Error Composer::createVirtualDisplay(uint32_t width, uint32_t height,
237             PixelFormat* format, Display* outDisplay)
238 {
239     const uint32_t bufferSlotCount = 1;
240     Error error = kDefaultError;
241     mClient->createVirtualDisplay(width, height, *format, bufferSlotCount,
242             [&](const auto& tmpError, const auto& tmpDisplay,
243                 const auto& tmpFormat) {
244                 error = tmpError;
245                 if (error != Error::NONE) {
246                     return;
247                 }
248 
249                 *outDisplay = tmpDisplay;
250                 *format = tmpFormat;
251             });
252 
253     return error;
254 }
255 
destroyVirtualDisplay(Display display)256 Error Composer::destroyVirtualDisplay(Display display)
257 {
258     auto ret = mClient->destroyVirtualDisplay(display);
259     return unwrapRet(ret);
260 }
261 
acceptDisplayChanges(Display display)262 Error Composer::acceptDisplayChanges(Display display)
263 {
264     mWriter.selectDisplay(display);
265     mWriter.acceptDisplayChanges();
266     return Error::NONE;
267 }
268 
createLayer(Display display,Layer * outLayer)269 Error Composer::createLayer(Display display, Layer* outLayer)
270 {
271     Error error = kDefaultError;
272     mClient->createLayer(display, BufferQueue::NUM_BUFFER_SLOTS,
273             [&](const auto& tmpError, const auto& tmpLayer) {
274                 error = tmpError;
275                 if (error != Error::NONE) {
276                     return;
277                 }
278 
279                 *outLayer = tmpLayer;
280             });
281 
282     return error;
283 }
284 
destroyLayer(Display display,Layer layer)285 Error Composer::destroyLayer(Display display, Layer layer)
286 {
287     auto ret = mClient->destroyLayer(display, layer);
288     return unwrapRet(ret);
289 }
290 
getActiveConfig(Display display,Config * outConfig)291 Error Composer::getActiveConfig(Display display, Config* outConfig)
292 {
293     Error error = kDefaultError;
294     mClient->getActiveConfig(display,
295             [&](const auto& tmpError, const auto& tmpConfig) {
296                 error = tmpError;
297                 if (error != Error::NONE) {
298                     return;
299                 }
300 
301                 *outConfig = tmpConfig;
302             });
303 
304     return error;
305 }
306 
getChangedCompositionTypes(Display display,std::vector<Layer> * outLayers,std::vector<IComposerClient::Composition> * outTypes)307 Error Composer::getChangedCompositionTypes(Display display,
308         std::vector<Layer>* outLayers,
309         std::vector<IComposerClient::Composition>* outTypes)
310 {
311     mReader.takeChangedCompositionTypes(display, outLayers, outTypes);
312     return Error::NONE;
313 }
314 
getColorModes(Display display,std::vector<ColorMode> * outModes)315 Error Composer::getColorModes(Display display,
316         std::vector<ColorMode>* outModes)
317 {
318     Error error = kDefaultError;
319     mClient->getColorModes(display,
320             [&](const auto& tmpError, const auto& tmpModes) {
321                 error = tmpError;
322                 if (error != Error::NONE) {
323                     return;
324                 }
325 
326                 *outModes = tmpModes;
327             });
328 
329     return error;
330 }
331 
getDisplayAttribute(Display display,Config config,IComposerClient::Attribute attribute,int32_t * outValue)332 Error Composer::getDisplayAttribute(Display display, Config config,
333         IComposerClient::Attribute attribute, int32_t* outValue)
334 {
335     Error error = kDefaultError;
336     mClient->getDisplayAttribute(display, config, attribute,
337             [&](const auto& tmpError, const auto& tmpValue) {
338                 error = tmpError;
339                 if (error != Error::NONE) {
340                     return;
341                 }
342 
343                 *outValue = tmpValue;
344             });
345 
346     return error;
347 }
348 
getDisplayConfigs(Display display,std::vector<Config> * outConfigs)349 Error Composer::getDisplayConfigs(Display display,
350         std::vector<Config>* outConfigs)
351 {
352     Error error = kDefaultError;
353     mClient->getDisplayConfigs(display,
354             [&](const auto& tmpError, const auto& tmpConfigs) {
355                 error = tmpError;
356                 if (error != Error::NONE) {
357                     return;
358                 }
359 
360                 *outConfigs = tmpConfigs;
361             });
362 
363     return error;
364 }
365 
getDisplayName(Display display,std::string * outName)366 Error Composer::getDisplayName(Display display, std::string* outName)
367 {
368     Error error = kDefaultError;
369     mClient->getDisplayName(display,
370             [&](const auto& tmpError, const auto& tmpName) {
371                 error = tmpError;
372                 if (error != Error::NONE) {
373                     return;
374                 }
375 
376                 *outName = tmpName.c_str();
377             });
378 
379     return error;
380 }
381 
getDisplayRequests(Display display,uint32_t * outDisplayRequestMask,std::vector<Layer> * outLayers,std::vector<uint32_t> * outLayerRequestMasks)382 Error Composer::getDisplayRequests(Display display,
383         uint32_t* outDisplayRequestMask, std::vector<Layer>* outLayers,
384         std::vector<uint32_t>* outLayerRequestMasks)
385 {
386     mReader.takeDisplayRequests(display, outDisplayRequestMask,
387             outLayers, outLayerRequestMasks);
388     return Error::NONE;
389 }
390 
getDisplayType(Display display,IComposerClient::DisplayType * outType)391 Error Composer::getDisplayType(Display display,
392         IComposerClient::DisplayType* outType)
393 {
394     Error error = kDefaultError;
395     mClient->getDisplayType(display,
396             [&](const auto& tmpError, const auto& tmpType) {
397                 error = tmpError;
398                 if (error != Error::NONE) {
399                     return;
400                 }
401 
402                 *outType = tmpType;
403             });
404 
405     return error;
406 }
407 
getDozeSupport(Display display,bool * outSupport)408 Error Composer::getDozeSupport(Display display, bool* outSupport)
409 {
410     Error error = kDefaultError;
411     mClient->getDozeSupport(display,
412             [&](const auto& tmpError, const auto& tmpSupport) {
413                 error = tmpError;
414                 if (error != Error::NONE) {
415                     return;
416                 }
417 
418                 *outSupport = tmpSupport;
419             });
420 
421     return error;
422 }
423 
getHdrCapabilities(Display display,std::vector<Hdr> * outTypes,float * outMaxLuminance,float * outMaxAverageLuminance,float * outMinLuminance)424 Error Composer::getHdrCapabilities(Display display,
425         std::vector<Hdr>* outTypes, float* outMaxLuminance,
426         float* outMaxAverageLuminance, float* outMinLuminance)
427 {
428     Error error = kDefaultError;
429     mClient->getHdrCapabilities(display,
430             [&](const auto& tmpError, const auto& tmpTypes,
431                 const auto& tmpMaxLuminance,
432                 const auto& tmpMaxAverageLuminance,
433                 const auto& tmpMinLuminance) {
434                 error = tmpError;
435                 if (error != Error::NONE) {
436                     return;
437                 }
438 
439                 *outTypes = tmpTypes;
440                 *outMaxLuminance = tmpMaxLuminance;
441                 *outMaxAverageLuminance = tmpMaxAverageLuminance;
442                 *outMinLuminance = tmpMinLuminance;
443             });
444 
445     return error;
446 }
447 
getReleaseFences(Display display,std::vector<Layer> * outLayers,std::vector<int> * outReleaseFences)448 Error Composer::getReleaseFences(Display display,
449         std::vector<Layer>* outLayers, std::vector<int>* outReleaseFences)
450 {
451     mReader.takeReleaseFences(display, outLayers, outReleaseFences);
452     return Error::NONE;
453 }
454 
presentDisplay(Display display,int * outPresentFence)455 Error Composer::presentDisplay(Display display, int* outPresentFence)
456 {
457     mWriter.selectDisplay(display);
458     mWriter.presentDisplay();
459 
460     Error error = execute();
461     if (error != Error::NONE) {
462         return error;
463     }
464 
465     mReader.takePresentFence(display, outPresentFence);
466 
467     return Error::NONE;
468 }
469 
setActiveConfig(Display display,Config config)470 Error Composer::setActiveConfig(Display display, Config config)
471 {
472     auto ret = mClient->setActiveConfig(display, config);
473     return unwrapRet(ret);
474 }
475 
setClientTarget(Display display,uint32_t slot,const sp<GraphicBuffer> & target,int acquireFence,Dataspace dataspace,const std::vector<IComposerClient::Rect> & damage)476 Error Composer::setClientTarget(Display display, uint32_t slot,
477         const sp<GraphicBuffer>& target,
478         int acquireFence, Dataspace dataspace,
479         const std::vector<IComposerClient::Rect>& damage)
480 {
481     mWriter.selectDisplay(display);
482     if (mIsUsingVrComposer && target.get()) {
483         IVrComposerClient::BufferMetadata metadata = {
484             .width = target->getWidth(),
485             .height = target->getHeight(),
486             .stride = target->getStride(),
487             .layerCount = target->getLayerCount(),
488             .format = static_cast<PixelFormat>(target->getPixelFormat()),
489             .usage = target->getUsage(),
490         };
491         mWriter.setClientTargetMetadata(metadata);
492     }
493 
494     const native_handle_t* handle = nullptr;
495     if (target.get()) {
496         handle = target->getNativeBuffer()->handle;
497     }
498 
499     mWriter.setClientTarget(slot, handle, acquireFence, dataspace, damage);
500     return Error::NONE;
501 }
502 
setColorMode(Display display,ColorMode mode)503 Error Composer::setColorMode(Display display, ColorMode mode)
504 {
505     auto ret = mClient->setColorMode(display, mode);
506     return unwrapRet(ret);
507 }
508 
setColorTransform(Display display,const float * matrix,ColorTransform hint)509 Error Composer::setColorTransform(Display display, const float* matrix,
510         ColorTransform hint)
511 {
512     mWriter.selectDisplay(display);
513     mWriter.setColorTransform(matrix, hint);
514     return Error::NONE;
515 }
516 
setOutputBuffer(Display display,const native_handle_t * buffer,int releaseFence)517 Error Composer::setOutputBuffer(Display display, const native_handle_t* buffer,
518         int releaseFence)
519 {
520     mWriter.selectDisplay(display);
521     mWriter.setOutputBuffer(0, buffer, dup(releaseFence));
522     return Error::NONE;
523 }
524 
setPowerMode(Display display,IComposerClient::PowerMode mode)525 Error Composer::setPowerMode(Display display, IComposerClient::PowerMode mode)
526 {
527     auto ret = mClient->setPowerMode(display, mode);
528     return unwrapRet(ret);
529 }
530 
setVsyncEnabled(Display display,IComposerClient::Vsync enabled)531 Error Composer::setVsyncEnabled(Display display, IComposerClient::Vsync enabled)
532 {
533     auto ret = mClient->setVsyncEnabled(display, enabled);
534     return unwrapRet(ret);
535 }
536 
setClientTargetSlotCount(Display display)537 Error Composer::setClientTargetSlotCount(Display display)
538 {
539     const uint32_t bufferSlotCount = BufferQueue::NUM_BUFFER_SLOTS;
540     auto ret = mClient->setClientTargetSlotCount(display, bufferSlotCount);
541     return unwrapRet(ret);
542 }
543 
validateDisplay(Display display,uint32_t * outNumTypes,uint32_t * outNumRequests)544 Error Composer::validateDisplay(Display display, uint32_t* outNumTypes,
545         uint32_t* outNumRequests)
546 {
547     mWriter.selectDisplay(display);
548     mWriter.validateDisplay();
549 
550     Error error = execute();
551     if (error != Error::NONE) {
552         return error;
553     }
554 
555     mReader.hasChanges(display, outNumTypes, outNumRequests);
556 
557     return Error::NONE;
558 }
559 
presentOrValidateDisplay(Display display,uint32_t * outNumTypes,uint32_t * outNumRequests,int * outPresentFence,uint32_t * state)560 Error Composer::presentOrValidateDisplay(Display display, uint32_t* outNumTypes,
561                                uint32_t* outNumRequests, int* outPresentFence, uint32_t* state) {
562    mWriter.selectDisplay(display);
563    mWriter.presentOrvalidateDisplay();
564 
565    Error error = execute();
566    if (error != Error::NONE) {
567        return error;
568    }
569 
570    mReader.takePresentOrValidateStage(display, state);
571 
572    if (*state == 1) { // Present succeeded
573        mReader.takePresentFence(display, outPresentFence);
574    }
575 
576    if (*state == 0) { // Validate succeeded.
577        mReader.hasChanges(display, outNumTypes, outNumRequests);
578    }
579 
580    return Error::NONE;
581 }
582 
setCursorPosition(Display display,Layer layer,int32_t x,int32_t y)583 Error Composer::setCursorPosition(Display display, Layer layer,
584         int32_t x, int32_t y)
585 {
586     mWriter.selectDisplay(display);
587     mWriter.selectLayer(layer);
588     mWriter.setLayerCursorPosition(x, y);
589     return Error::NONE;
590 }
591 
setLayerBuffer(Display display,Layer layer,uint32_t slot,const sp<GraphicBuffer> & buffer,int acquireFence)592 Error Composer::setLayerBuffer(Display display, Layer layer,
593         uint32_t slot, const sp<GraphicBuffer>& buffer, int acquireFence)
594 {
595     mWriter.selectDisplay(display);
596     mWriter.selectLayer(layer);
597     if (mIsUsingVrComposer && buffer.get()) {
598         IVrComposerClient::BufferMetadata metadata = {
599             .width = buffer->getWidth(),
600             .height = buffer->getHeight(),
601             .stride = buffer->getStride(),
602             .layerCount = buffer->getLayerCount(),
603             .format = static_cast<PixelFormat>(buffer->getPixelFormat()),
604             .usage = buffer->getUsage(),
605         };
606         mWriter.setLayerBufferMetadata(metadata);
607     }
608 
609     const native_handle_t* handle = nullptr;
610     if (buffer.get()) {
611         handle = buffer->getNativeBuffer()->handle;
612     }
613 
614     mWriter.setLayerBuffer(slot, handle, acquireFence);
615     return Error::NONE;
616 }
617 
setLayerSurfaceDamage(Display display,Layer layer,const std::vector<IComposerClient::Rect> & damage)618 Error Composer::setLayerSurfaceDamage(Display display, Layer layer,
619         const std::vector<IComposerClient::Rect>& damage)
620 {
621     mWriter.selectDisplay(display);
622     mWriter.selectLayer(layer);
623     mWriter.setLayerSurfaceDamage(damage);
624     return Error::NONE;
625 }
626 
setLayerBlendMode(Display display,Layer layer,IComposerClient::BlendMode mode)627 Error Composer::setLayerBlendMode(Display display, Layer layer,
628         IComposerClient::BlendMode mode)
629 {
630     mWriter.selectDisplay(display);
631     mWriter.selectLayer(layer);
632     mWriter.setLayerBlendMode(mode);
633     return Error::NONE;
634 }
635 
setLayerColor(Display display,Layer layer,const IComposerClient::Color & color)636 Error Composer::setLayerColor(Display display, Layer layer,
637         const IComposerClient::Color& color)
638 {
639     mWriter.selectDisplay(display);
640     mWriter.selectLayer(layer);
641     mWriter.setLayerColor(color);
642     return Error::NONE;
643 }
644 
setLayerCompositionType(Display display,Layer layer,IComposerClient::Composition type)645 Error Composer::setLayerCompositionType(Display display, Layer layer,
646         IComposerClient::Composition type)
647 {
648     mWriter.selectDisplay(display);
649     mWriter.selectLayer(layer);
650     mWriter.setLayerCompositionType(type);
651     return Error::NONE;
652 }
653 
setLayerDataspace(Display display,Layer layer,Dataspace dataspace)654 Error Composer::setLayerDataspace(Display display, Layer layer,
655         Dataspace dataspace)
656 {
657     mWriter.selectDisplay(display);
658     mWriter.selectLayer(layer);
659     mWriter.setLayerDataspace(dataspace);
660     return Error::NONE;
661 }
662 
setLayerDisplayFrame(Display display,Layer layer,const IComposerClient::Rect & frame)663 Error Composer::setLayerDisplayFrame(Display display, Layer layer,
664         const IComposerClient::Rect& frame)
665 {
666     mWriter.selectDisplay(display);
667     mWriter.selectLayer(layer);
668     mWriter.setLayerDisplayFrame(frame);
669     return Error::NONE;
670 }
671 
setLayerPlaneAlpha(Display display,Layer layer,float alpha)672 Error Composer::setLayerPlaneAlpha(Display display, Layer layer,
673         float alpha)
674 {
675     mWriter.selectDisplay(display);
676     mWriter.selectLayer(layer);
677     mWriter.setLayerPlaneAlpha(alpha);
678     return Error::NONE;
679 }
680 
setLayerSidebandStream(Display display,Layer layer,const native_handle_t * stream)681 Error Composer::setLayerSidebandStream(Display display, Layer layer,
682         const native_handle_t* stream)
683 {
684     mWriter.selectDisplay(display);
685     mWriter.selectLayer(layer);
686     mWriter.setLayerSidebandStream(stream);
687     return Error::NONE;
688 }
689 
setLayerSourceCrop(Display display,Layer layer,const IComposerClient::FRect & crop)690 Error Composer::setLayerSourceCrop(Display display, Layer layer,
691         const IComposerClient::FRect& crop)
692 {
693     mWriter.selectDisplay(display);
694     mWriter.selectLayer(layer);
695     mWriter.setLayerSourceCrop(crop);
696     return Error::NONE;
697 }
698 
setLayerTransform(Display display,Layer layer,Transform transform)699 Error Composer::setLayerTransform(Display display, Layer layer,
700         Transform transform)
701 {
702     mWriter.selectDisplay(display);
703     mWriter.selectLayer(layer);
704     mWriter.setLayerTransform(transform);
705     return Error::NONE;
706 }
707 
setLayerVisibleRegion(Display display,Layer layer,const std::vector<IComposerClient::Rect> & visible)708 Error Composer::setLayerVisibleRegion(Display display, Layer layer,
709         const std::vector<IComposerClient::Rect>& visible)
710 {
711     mWriter.selectDisplay(display);
712     mWriter.selectLayer(layer);
713     mWriter.setLayerVisibleRegion(visible);
714     return Error::NONE;
715 }
716 
setLayerZOrder(Display display,Layer layer,uint32_t z)717 Error Composer::setLayerZOrder(Display display, Layer layer, uint32_t z)
718 {
719     mWriter.selectDisplay(display);
720     mWriter.selectLayer(layer);
721     mWriter.setLayerZOrder(z);
722     return Error::NONE;
723 }
724 
setLayerInfo(Display display,Layer layer,uint32_t type,uint32_t appId)725 Error Composer::setLayerInfo(Display display, Layer layer, uint32_t type,
726                              uint32_t appId)
727 {
728     if (mIsUsingVrComposer) {
729         mWriter.selectDisplay(display);
730         mWriter.selectLayer(layer);
731         mWriter.setLayerInfo(type, appId);
732     }
733     return Error::NONE;
734 }
735 
execute()736 Error Composer::execute()
737 {
738     // prepare input command queue
739     bool queueChanged = false;
740     uint32_t commandLength = 0;
741     hidl_vec<hidl_handle> commandHandles;
742     if (!mWriter.writeQueue(&queueChanged, &commandLength, &commandHandles)) {
743         mWriter.reset();
744         return Error::NO_RESOURCES;
745     }
746 
747     // set up new input command queue if necessary
748     if (queueChanged) {
749         auto ret = mClient->setInputCommandQueue(*mWriter.getMQDescriptor());
750         auto error = unwrapRet(ret);
751         if (error != Error::NONE) {
752             mWriter.reset();
753             return error;
754         }
755     }
756 
757     Error error = kDefaultError;
758     auto ret = mClient->executeCommands(commandLength, commandHandles,
759             [&](const auto& tmpError, const auto& tmpOutChanged,
760                 const auto& tmpOutLength, const auto& tmpOutHandles)
761             {
762                 error = tmpError;
763 
764                 // set up new output command queue if necessary
765                 if (error == Error::NONE && tmpOutChanged) {
766                     error = kDefaultError;
767                     mClient->getOutputCommandQueue(
768                             [&](const auto& tmpError,
769                                 const auto& tmpDescriptor)
770                             {
771                                 error = tmpError;
772                                 if (error != Error::NONE) {
773                                     return;
774                                 }
775 
776                                 mReader.setMQDescriptor(tmpDescriptor);
777                             });
778                 }
779 
780                 if (error != Error::NONE) {
781                     return;
782                 }
783 
784                 if (mReader.readQueue(tmpOutLength, tmpOutHandles)) {
785                     error = mReader.parse();
786                     mReader.reset();
787                 } else {
788                     error = Error::NO_RESOURCES;
789                 }
790             });
791     // executeCommands can fail because of out-of-fd and we do not want to
792     // abort() in that case
793     if (!ret.isOk()) {
794         ALOGE("executeCommands failed because of %s", ret.description().c_str());
795     }
796 
797     if (error == Error::NONE) {
798         std::vector<CommandReader::CommandError> commandErrors =
799             mReader.takeErrors();
800 
801         for (const auto& cmdErr : commandErrors) {
802             auto command = mWriter.getCommand(cmdErr.location);
803 
804             if (command == IComposerClient::Command::VALIDATE_DISPLAY ||
805                 command == IComposerClient::Command::PRESENT_DISPLAY ||
806                 command == IComposerClient::Command::PRESENT_OR_VALIDATE_DISPLAY) {
807                 error = cmdErr.error;
808             } else {
809                 ALOGW("command 0x%x generated error %d",
810                         command, cmdErr.error);
811             }
812         }
813     }
814 
815     mWriter.reset();
816 
817     return error;
818 }
819 
~CommandReader()820 CommandReader::~CommandReader()
821 {
822     resetData();
823 }
824 
parse()825 Error CommandReader::parse()
826 {
827     resetData();
828 
829     IComposerClient::Command command;
830     uint16_t length = 0;
831 
832     while (!isEmpty()) {
833         if (!beginCommand(&command, &length)) {
834             break;
835         }
836 
837         bool parsed = false;
838         switch (command) {
839         case IComposerClient::Command::SELECT_DISPLAY:
840             parsed = parseSelectDisplay(length);
841             break;
842         case IComposerClient::Command::SET_ERROR:
843             parsed = parseSetError(length);
844             break;
845         case IComposerClient::Command::SET_CHANGED_COMPOSITION_TYPES:
846             parsed = parseSetChangedCompositionTypes(length);
847             break;
848         case IComposerClient::Command::SET_DISPLAY_REQUESTS:
849             parsed = parseSetDisplayRequests(length);
850             break;
851         case IComposerClient::Command::SET_PRESENT_FENCE:
852             parsed = parseSetPresentFence(length);
853             break;
854         case IComposerClient::Command::SET_RELEASE_FENCES:
855             parsed = parseSetReleaseFences(length);
856             break;
857         case IComposerClient::Command ::SET_PRESENT_OR_VALIDATE_DISPLAY_RESULT:
858             parsed = parseSetPresentOrValidateDisplayResult(length);
859             break;
860         default:
861             parsed = false;
862             break;
863         }
864 
865         endCommand();
866 
867         if (!parsed) {
868             ALOGE("failed to parse command 0x%x length %" PRIu16,
869                     command, length);
870             break;
871         }
872     }
873 
874     return isEmpty() ? Error::NONE : Error::NO_RESOURCES;
875 }
876 
parseSelectDisplay(uint16_t length)877 bool CommandReader::parseSelectDisplay(uint16_t length)
878 {
879     if (length != CommandWriterBase::kSelectDisplayLength) {
880         return false;
881     }
882 
883     mCurrentReturnData = &mReturnData[read64()];
884 
885     return true;
886 }
887 
parseSetError(uint16_t length)888 bool CommandReader::parseSetError(uint16_t length)
889 {
890     if (length != CommandWriterBase::kSetErrorLength) {
891         return false;
892     }
893 
894     auto location = read();
895     auto error = static_cast<Error>(readSigned());
896 
897     mErrors.emplace_back(CommandError{location, error});
898 
899     return true;
900 }
901 
parseSetChangedCompositionTypes(uint16_t length)902 bool CommandReader::parseSetChangedCompositionTypes(uint16_t length)
903 {
904     // (layer id, composition type) pairs
905     if (length % 3 != 0 || !mCurrentReturnData) {
906         return false;
907     }
908 
909     uint32_t count = length / 3;
910     mCurrentReturnData->changedLayers.reserve(count);
911     mCurrentReturnData->compositionTypes.reserve(count);
912     while (count > 0) {
913         auto layer = read64();
914         auto type = static_cast<IComposerClient::Composition>(readSigned());
915 
916         mCurrentReturnData->changedLayers.push_back(layer);
917         mCurrentReturnData->compositionTypes.push_back(type);
918 
919         count--;
920     }
921 
922     return true;
923 }
924 
parseSetDisplayRequests(uint16_t length)925 bool CommandReader::parseSetDisplayRequests(uint16_t length)
926 {
927     // display requests followed by (layer id, layer requests) pairs
928     if (length % 3 != 1 || !mCurrentReturnData) {
929         return false;
930     }
931 
932     mCurrentReturnData->displayRequests = read();
933 
934     uint32_t count = (length - 1) / 3;
935     mCurrentReturnData->requestedLayers.reserve(count);
936     mCurrentReturnData->requestMasks.reserve(count);
937     while (count > 0) {
938         auto layer = read64();
939         auto layerRequestMask = read();
940 
941         mCurrentReturnData->requestedLayers.push_back(layer);
942         mCurrentReturnData->requestMasks.push_back(layerRequestMask);
943 
944         count--;
945     }
946 
947     return true;
948 }
949 
parseSetPresentFence(uint16_t length)950 bool CommandReader::parseSetPresentFence(uint16_t length)
951 {
952     if (length != CommandWriterBase::kSetPresentFenceLength ||
953             !mCurrentReturnData) {
954         return false;
955     }
956 
957     if (mCurrentReturnData->presentFence >= 0) {
958         close(mCurrentReturnData->presentFence);
959     }
960     mCurrentReturnData->presentFence = readFence();
961 
962     return true;
963 }
964 
parseSetReleaseFences(uint16_t length)965 bool CommandReader::parseSetReleaseFences(uint16_t length)
966 {
967     // (layer id, release fence index) pairs
968     if (length % 3 != 0 || !mCurrentReturnData) {
969         return false;
970     }
971 
972     uint32_t count = length / 3;
973     mCurrentReturnData->releasedLayers.reserve(count);
974     mCurrentReturnData->releaseFences.reserve(count);
975     while (count > 0) {
976         auto layer = read64();
977         auto fence = readFence();
978 
979         mCurrentReturnData->releasedLayers.push_back(layer);
980         mCurrentReturnData->releaseFences.push_back(fence);
981 
982         count--;
983     }
984 
985     return true;
986 }
987 
parseSetPresentOrValidateDisplayResult(uint16_t length)988 bool CommandReader::parseSetPresentOrValidateDisplayResult(uint16_t length)
989 {
990     if (length != CommandWriterBase::kPresentOrValidateDisplayResultLength || !mCurrentReturnData) {
991         return false;
992     }
993     mCurrentReturnData->presentOrValidateState = read();
994     return true;
995 }
996 
resetData()997 void CommandReader::resetData()
998 {
999     mErrors.clear();
1000 
1001     for (auto& data : mReturnData) {
1002         if (data.second.presentFence >= 0) {
1003             close(data.second.presentFence);
1004         }
1005         for (auto fence : data.second.releaseFences) {
1006             if (fence >= 0) {
1007                 close(fence);
1008             }
1009         }
1010     }
1011 
1012     mReturnData.clear();
1013     mCurrentReturnData = nullptr;
1014 }
1015 
takeErrors()1016 std::vector<CommandReader::CommandError> CommandReader::takeErrors()
1017 {
1018     return std::move(mErrors);
1019 }
1020 
hasChanges(Display display,uint32_t * outNumChangedCompositionTypes,uint32_t * outNumLayerRequestMasks) const1021 bool CommandReader::hasChanges(Display display,
1022         uint32_t* outNumChangedCompositionTypes,
1023         uint32_t* outNumLayerRequestMasks) const
1024 {
1025     auto found = mReturnData.find(display);
1026     if (found == mReturnData.end()) {
1027         *outNumChangedCompositionTypes = 0;
1028         *outNumLayerRequestMasks = 0;
1029         return false;
1030     }
1031 
1032     const ReturnData& data = found->second;
1033 
1034     *outNumChangedCompositionTypes = data.compositionTypes.size();
1035     *outNumLayerRequestMasks = data.requestMasks.size();
1036 
1037     return !(data.compositionTypes.empty() && data.requestMasks.empty());
1038 }
1039 
takeChangedCompositionTypes(Display display,std::vector<Layer> * outLayers,std::vector<IComposerClient::Composition> * outTypes)1040 void CommandReader::takeChangedCompositionTypes(Display display,
1041         std::vector<Layer>* outLayers,
1042         std::vector<IComposerClient::Composition>* outTypes)
1043 {
1044     auto found = mReturnData.find(display);
1045     if (found == mReturnData.end()) {
1046         outLayers->clear();
1047         outTypes->clear();
1048         return;
1049     }
1050 
1051     ReturnData& data = found->second;
1052 
1053     *outLayers = std::move(data.changedLayers);
1054     *outTypes = std::move(data.compositionTypes);
1055 }
1056 
takeDisplayRequests(Display display,uint32_t * outDisplayRequestMask,std::vector<Layer> * outLayers,std::vector<uint32_t> * outLayerRequestMasks)1057 void CommandReader::takeDisplayRequests(Display display,
1058         uint32_t* outDisplayRequestMask, std::vector<Layer>* outLayers,
1059         std::vector<uint32_t>* outLayerRequestMasks)
1060 {
1061     auto found = mReturnData.find(display);
1062     if (found == mReturnData.end()) {
1063         *outDisplayRequestMask = 0;
1064         outLayers->clear();
1065         outLayerRequestMasks->clear();
1066         return;
1067     }
1068 
1069     ReturnData& data = found->second;
1070 
1071     *outDisplayRequestMask = data.displayRequests;
1072     *outLayers = std::move(data.requestedLayers);
1073     *outLayerRequestMasks = std::move(data.requestMasks);
1074 }
1075 
takeReleaseFences(Display display,std::vector<Layer> * outLayers,std::vector<int> * outReleaseFences)1076 void CommandReader::takeReleaseFences(Display display,
1077         std::vector<Layer>* outLayers, std::vector<int>* outReleaseFences)
1078 {
1079     auto found = mReturnData.find(display);
1080     if (found == mReturnData.end()) {
1081         outLayers->clear();
1082         outReleaseFences->clear();
1083         return;
1084     }
1085 
1086     ReturnData& data = found->second;
1087 
1088     *outLayers = std::move(data.releasedLayers);
1089     *outReleaseFences = std::move(data.releaseFences);
1090 }
1091 
takePresentFence(Display display,int * outPresentFence)1092 void CommandReader::takePresentFence(Display display, int* outPresentFence)
1093 {
1094     auto found = mReturnData.find(display);
1095     if (found == mReturnData.end()) {
1096         *outPresentFence = -1;
1097         return;
1098     }
1099 
1100     ReturnData& data = found->second;
1101 
1102     *outPresentFence = data.presentFence;
1103     data.presentFence = -1;
1104 }
1105 
takePresentOrValidateStage(Display display,uint32_t * state)1106 void CommandReader::takePresentOrValidateStage(Display display, uint32_t* state) {
1107     auto found = mReturnData.find(display);
1108     if (found == mReturnData.end()) {
1109         *state= -1;
1110         return;
1111     }
1112     ReturnData& data = found->second;
1113     *state = data.presentOrValidateState;
1114 }
1115 
1116 } // namespace Hwc2
1117 
1118 } // namespace android
1119