1 /*
2  * Copyright (C) 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 #define LOG_TAG "EffectHalHidl"
18 //#define LOG_NDEBUG 0
19 
20 #include <hwbinder/IPCThreadState.h>
21 #include <media/EffectsFactoryApi.h>
22 #include <utils/Log.h>
23 
24 #include "ConversionHelperHidl.h"
25 #include "EffectBufferHalHidl.h"
26 #include "EffectHalHidl.h"
27 #include "HidlUtils.h"
28 
29 using ::android::hardware::audio::effect::V2_0::AudioBuffer;
30 using ::android::hardware::audio::effect::V2_0::EffectBufferAccess;
31 using ::android::hardware::audio::effect::V2_0::EffectConfigParameters;
32 using ::android::hardware::audio::effect::V2_0::MessageQueueFlagBits;
33 using ::android::hardware::audio::effect::V2_0::Result;
34 using ::android::hardware::audio::common::V2_0::AudioChannelMask;
35 using ::android::hardware::audio::common::V2_0::AudioFormat;
36 using ::android::hardware::hidl_vec;
37 using ::android::hardware::MQDescriptorSync;
38 using ::android::hardware::Return;
39 
40 namespace android {
41 
EffectHalHidl(const sp<IEffect> & effect,uint64_t effectId)42 EffectHalHidl::EffectHalHidl(const sp<IEffect>& effect, uint64_t effectId)
43         : mEffect(effect), mEffectId(effectId), mBuffersChanged(true) {
44 }
45 
~EffectHalHidl()46 EffectHalHidl::~EffectHalHidl() {
47     if (mEffect != 0) {
48         close();
49         mEffect.clear();
50         hardware::IPCThreadState::self()->flushCommands();
51     }
52 }
53 
54 // static
effectDescriptorToHal(const EffectDescriptor & descriptor,effect_descriptor_t * halDescriptor)55 void EffectHalHidl::effectDescriptorToHal(
56         const EffectDescriptor& descriptor, effect_descriptor_t* halDescriptor) {
57     HidlUtils::uuidToHal(descriptor.type, &halDescriptor->type);
58     HidlUtils::uuidToHal(descriptor.uuid, &halDescriptor->uuid);
59     halDescriptor->flags = static_cast<uint32_t>(descriptor.flags);
60     halDescriptor->cpuLoad = descriptor.cpuLoad;
61     halDescriptor->memoryUsage = descriptor.memoryUsage;
62     memcpy(halDescriptor->name, descriptor.name.data(), descriptor.name.size());
63     memcpy(halDescriptor->implementor,
64             descriptor.implementor.data(), descriptor.implementor.size());
65 }
66 
67 // TODO(mnaganov): These buffer conversion functions should be shared with Effect wrapper
68 // via HidlUtils. Move them there when hardware/interfaces will get un-frozen again.
69 
70 // static
effectBufferConfigFromHal(const buffer_config_t & halConfig,EffectBufferConfig * config)71 void EffectHalHidl::effectBufferConfigFromHal(
72         const buffer_config_t& halConfig, EffectBufferConfig* config) {
73     config->samplingRateHz = halConfig.samplingRate;
74     config->channels = AudioChannelMask(halConfig.channels);
75     config->format = AudioFormat(halConfig.format);
76     config->accessMode = EffectBufferAccess(halConfig.accessMode);
77     config->mask = EffectConfigParameters(halConfig.mask);
78 }
79 
80 // static
effectBufferConfigToHal(const EffectBufferConfig & config,buffer_config_t * halConfig)81 void EffectHalHidl::effectBufferConfigToHal(
82         const EffectBufferConfig& config, buffer_config_t* halConfig) {
83     halConfig->buffer.frameCount = 0;
84     halConfig->buffer.raw = NULL;
85     halConfig->samplingRate = config.samplingRateHz;
86     halConfig->channels = static_cast<uint32_t>(config.channels);
87     halConfig->bufferProvider.cookie = NULL;
88     halConfig->bufferProvider.getBuffer = NULL;
89     halConfig->bufferProvider.releaseBuffer = NULL;
90     halConfig->format = static_cast<uint8_t>(config.format);
91     halConfig->accessMode = static_cast<uint8_t>(config.accessMode);
92     halConfig->mask = static_cast<uint8_t>(config.mask);
93 }
94 
95 // static
effectConfigFromHal(const effect_config_t & halConfig,EffectConfig * config)96 void EffectHalHidl::effectConfigFromHal(const effect_config_t& halConfig, EffectConfig* config) {
97     effectBufferConfigFromHal(halConfig.inputCfg, &config->inputCfg);
98     effectBufferConfigFromHal(halConfig.outputCfg, &config->outputCfg);
99 }
100 
101 // static
effectConfigToHal(const EffectConfig & config,effect_config_t * halConfig)102 void EffectHalHidl::effectConfigToHal(const EffectConfig& config, effect_config_t* halConfig) {
103     effectBufferConfigToHal(config.inputCfg, &halConfig->inputCfg);
104     effectBufferConfigToHal(config.outputCfg, &halConfig->outputCfg);
105 }
106 
107 // static
analyzeResult(const Result & result)108 status_t EffectHalHidl::analyzeResult(const Result& result) {
109     switch (result) {
110         case Result::OK: return OK;
111         case Result::INVALID_ARGUMENTS: return BAD_VALUE;
112         case Result::INVALID_STATE: return NOT_ENOUGH_DATA;
113         case Result::NOT_INITIALIZED: return NO_INIT;
114         case Result::NOT_SUPPORTED: return INVALID_OPERATION;
115         case Result::RESULT_TOO_BIG: return NO_MEMORY;
116         default: return NO_INIT;
117     }
118 }
119 
setInBuffer(const sp<EffectBufferHalInterface> & buffer)120 status_t EffectHalHidl::setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
121     if (mInBuffer == 0 || buffer->audioBuffer() != mInBuffer->audioBuffer()) {
122         mBuffersChanged = true;
123     }
124     mInBuffer = buffer;
125     return OK;
126 }
127 
setOutBuffer(const sp<EffectBufferHalInterface> & buffer)128 status_t EffectHalHidl::setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
129     if (mOutBuffer == 0 || buffer->audioBuffer() != mOutBuffer->audioBuffer()) {
130         mBuffersChanged = true;
131     }
132     mOutBuffer = buffer;
133     return OK;
134 }
135 
process()136 status_t EffectHalHidl::process() {
137     return processImpl(static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS));
138 }
139 
processReverse()140 status_t EffectHalHidl::processReverse() {
141     return processImpl(static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS_REVERSE));
142 }
143 
prepareForProcessing()144 status_t EffectHalHidl::prepareForProcessing() {
145     std::unique_ptr<StatusMQ> tempStatusMQ;
146     Result retval;
147     Return<void> ret = mEffect->prepareForProcessing(
148             [&](Result r, const MQDescriptorSync<Result>& statusMQ) {
149                 retval = r;
150                 if (retval == Result::OK) {
151                     tempStatusMQ.reset(new StatusMQ(statusMQ));
152                     if (tempStatusMQ->isValid() && tempStatusMQ->getEventFlagWord()) {
153                         EventFlag::createEventFlag(tempStatusMQ->getEventFlagWord(), &mEfGroup);
154                     }
155                 }
156             });
157     if (!ret.isOk() || retval != Result::OK) {
158         return ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
159     }
160     if (!tempStatusMQ || !tempStatusMQ->isValid() || !mEfGroup) {
161         ALOGE_IF(!tempStatusMQ, "Failed to obtain status message queue for effects");
162         ALOGE_IF(tempStatusMQ && !tempStatusMQ->isValid(),
163                 "Status message queue for effects is invalid");
164         ALOGE_IF(!mEfGroup, "Event flag creation for effects failed");
165         return NO_INIT;
166     }
167     mStatusMQ = std::move(tempStatusMQ);
168     return OK;
169 }
170 
needToResetBuffers()171 bool EffectHalHidl::needToResetBuffers() {
172     if (mBuffersChanged) return true;
173     bool inBufferFrameCountUpdated = mInBuffer->checkFrameCountChange();
174     bool outBufferFrameCountUpdated = mOutBuffer->checkFrameCountChange();
175     return inBufferFrameCountUpdated || outBufferFrameCountUpdated;
176 }
177 
processImpl(uint32_t mqFlag)178 status_t EffectHalHidl::processImpl(uint32_t mqFlag) {
179     if (mEffect == 0 || mInBuffer == 0 || mOutBuffer == 0) return NO_INIT;
180     status_t status;
181     if (!mStatusMQ && (status = prepareForProcessing()) != OK) {
182         return status;
183     }
184     if (needToResetBuffers() && (status = setProcessBuffers()) != OK) {
185         return status;
186     }
187     // The data is already in the buffers, just need to flush it and wake up the server side.
188     std::atomic_thread_fence(std::memory_order_release);
189     mEfGroup->wake(mqFlag);
190     uint32_t efState = 0;
191 retry:
192     status_t ret = mEfGroup->wait(
193             static_cast<uint32_t>(MessageQueueFlagBits::DONE_PROCESSING), &efState);
194     if (efState & static_cast<uint32_t>(MessageQueueFlagBits::DONE_PROCESSING)) {
195         Result retval = Result::NOT_INITIALIZED;
196         mStatusMQ->read(&retval);
197         if (retval == Result::OK || retval == Result::INVALID_STATE) {
198             // Sync back the changed contents of the buffer.
199             std::atomic_thread_fence(std::memory_order_acquire);
200         }
201         return analyzeResult(retval);
202     }
203     if (ret == -EAGAIN || ret == -EINTR) {
204         // Spurious wakeup. This normally retries no more than once.
205         goto retry;
206     }
207     return ret;
208 }
209 
setProcessBuffers()210 status_t EffectHalHidl::setProcessBuffers() {
211     Return<Result> ret = mEffect->setProcessBuffers(
212             static_cast<EffectBufferHalHidl*>(mInBuffer.get())->hidlBuffer(),
213             static_cast<EffectBufferHalHidl*>(mOutBuffer.get())->hidlBuffer());
214     if (ret.isOk() && ret == Result::OK) {
215         mBuffersChanged = false;
216         return OK;
217     }
218     return ret.isOk() ? analyzeResult(ret) : FAILED_TRANSACTION;
219 }
220 
command(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)221 status_t EffectHalHidl::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData,
222         uint32_t *replySize, void *pReplyData) {
223     if (mEffect == 0) return NO_INIT;
224 
225     // Special cases.
226     if (cmdCode == EFFECT_CMD_SET_CONFIG || cmdCode == EFFECT_CMD_SET_CONFIG_REVERSE) {
227         return setConfigImpl(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
228     } else if (cmdCode == EFFECT_CMD_GET_CONFIG || cmdCode == EFFECT_CMD_GET_CONFIG_REVERSE) {
229         return getConfigImpl(cmdCode, replySize, pReplyData);
230     }
231 
232     // Common case.
233     hidl_vec<uint8_t> hidlData;
234     if (pCmdData != nullptr && cmdSize > 0) {
235         hidlData.setToExternal(reinterpret_cast<uint8_t*>(pCmdData), cmdSize);
236     }
237     status_t status;
238     uint32_t replySizeStub = 0;
239     if (replySize == nullptr || pReplyData == nullptr) replySize = &replySizeStub;
240     Return<void> ret = mEffect->command(cmdCode, hidlData, *replySize,
241             [&](int32_t s, const hidl_vec<uint8_t>& result) {
242                 status = s;
243                 if (status == 0) {
244                     if (*replySize > result.size()) *replySize = result.size();
245                     if (pReplyData != nullptr && *replySize > 0) {
246                         memcpy(pReplyData, &result[0], *replySize);
247                     }
248                 }
249             });
250     return ret.isOk() ? status : FAILED_TRANSACTION;
251 }
252 
getDescriptor(effect_descriptor_t * pDescriptor)253 status_t EffectHalHidl::getDescriptor(effect_descriptor_t *pDescriptor) {
254     if (mEffect == 0) return NO_INIT;
255     Result retval = Result::NOT_INITIALIZED;
256     Return<void> ret = mEffect->getDescriptor(
257             [&](Result r, const EffectDescriptor& result) {
258                 retval = r;
259                 if (retval == Result::OK) {
260                     effectDescriptorToHal(result, pDescriptor);
261                 }
262             });
263     return ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
264 }
265 
close()266 status_t EffectHalHidl::close() {
267     if (mEffect == 0) return NO_INIT;
268     Return<Result> ret = mEffect->close();
269     return ret.isOk() ? analyzeResult(ret) : FAILED_TRANSACTION;
270 }
271 
getConfigImpl(uint32_t cmdCode,uint32_t * replySize,void * pReplyData)272 status_t EffectHalHidl::getConfigImpl(
273         uint32_t cmdCode, uint32_t *replySize, void *pReplyData) {
274     if (replySize == NULL || *replySize != sizeof(effect_config_t) || pReplyData == NULL) {
275         return BAD_VALUE;
276     }
277     status_t result = FAILED_TRANSACTION;
278     Return<void> ret;
279     if (cmdCode == EFFECT_CMD_GET_CONFIG) {
280         ret = mEffect->getConfig([&] (Result r, const EffectConfig &hidlConfig) {
281             result = analyzeResult(r);
282             if (r == Result::OK) {
283                 effectConfigToHal(hidlConfig, static_cast<effect_config_t*>(pReplyData));
284             }
285         });
286     } else {
287         ret = mEffect->getConfigReverse([&] (Result r, const EffectConfig &hidlConfig) {
288             result = analyzeResult(r);
289             if (r == Result::OK) {
290                 effectConfigToHal(hidlConfig, static_cast<effect_config_t*>(pReplyData));
291             }
292         });
293     }
294     if (!ret.isOk()) {
295         result = FAILED_TRANSACTION;
296     }
297     return result;
298 }
299 
setConfigImpl(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)300 status_t EffectHalHidl::setConfigImpl(
301         uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) {
302     if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
303             replySize == NULL || *replySize != sizeof(int32_t) || pReplyData == NULL) {
304         return BAD_VALUE;
305     }
306     const effect_config_t *halConfig = static_cast<effect_config_t*>(pCmdData);
307     if (halConfig->inputCfg.bufferProvider.getBuffer != NULL ||
308             halConfig->inputCfg.bufferProvider.releaseBuffer != NULL ||
309             halConfig->outputCfg.bufferProvider.getBuffer != NULL ||
310             halConfig->outputCfg.bufferProvider.releaseBuffer != NULL) {
311         ALOGE("Buffer provider callbacks are not supported");
312     }
313     EffectConfig hidlConfig;
314     effectConfigFromHal(*halConfig, &hidlConfig);
315     Return<Result> ret = cmdCode == EFFECT_CMD_SET_CONFIG ?
316             mEffect->setConfig(hidlConfig, nullptr, nullptr) :
317             mEffect->setConfigReverse(hidlConfig, nullptr, nullptr);
318     status_t result = FAILED_TRANSACTION;
319     if (ret.isOk()) {
320         result = analyzeResult(ret);
321         *static_cast<int32_t*>(pReplyData) = result;
322     }
323     return result;
324 }
325 
326 } // namespace android
327