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