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