xref: /aosp_15_r20/hardware/interfaces/audio/aidl/default/EffectImpl.cpp (revision 4d7e907c777eeecc4c5bd7cf640a754fac206ff7)
1 /*
2  * Copyright (C) 2022 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 #include <memory>
18 #define ATRACE_TAG ATRACE_TAG_AUDIO
19 #define LOG_TAG "AHAL_EffectImpl"
20 #include <utils/Trace.h>
21 #include "effect-impl/EffectImpl.h"
22 #include "effect-impl/EffectTypes.h"
23 #include "include/effect-impl/EffectTypes.h"
24 
25 using aidl::android::hardware::audio::effect::CommandId;
26 using aidl::android::hardware::audio::effect::Descriptor;
27 using aidl::android::hardware::audio::effect::IEffect;
28 using aidl::android::hardware::audio::effect::kDestroyAnyStateSupportedVersion;
29 using aidl::android::hardware::audio::effect::kEventFlagDataMqNotEmpty;
30 using aidl::android::hardware::audio::effect::kEventFlagNotEmpty;
31 using aidl::android::hardware::audio::effect::kReopenSupportedVersion;
32 using aidl::android::hardware::audio::effect::State;
33 using aidl::android::media::audio::common::PcmType;
34 using ::android::hardware::EventFlag;
35 
destroyEffect(const std::shared_ptr<IEffect> & instanceSp)36 extern "C" binder_exception_t destroyEffect(const std::shared_ptr<IEffect>& instanceSp) {
37     if (!instanceSp) {
38         LOG(ERROR) << __func__ << " nullptr";
39         return EX_ILLEGAL_ARGUMENT;
40     }
41 
42     Descriptor desc;
43     ndk::ScopedAStatus status = instanceSp->getDescriptor(&desc);
44     if (!status.isOk()) {
45         LOG(ERROR) << __func__ << " instance " << instanceSp.get()
46                    << " failed to get descriptor, status: " << status.getDescription();
47         return EX_ILLEGAL_STATE;
48     }
49 
50     State state;
51     status = instanceSp->getState(&state);
52     if (!status.isOk()) {
53         LOG(ERROR) << __func__ << " " << desc.common.name << " instance " << instanceSp.get()
54                    << " in state: " << toString(state) << ", status: " << status.getDescription();
55         return EX_ILLEGAL_STATE;
56     }
57 
58     int effectVersion = 0;
59     if (!instanceSp->getInterfaceVersion(&effectVersion).isOk()) {
60         LOG(WARNING) << __func__ << " " << desc.common.name << " failed to get interface version";
61     }
62 
63     if (effectVersion < kDestroyAnyStateSupportedVersion) {
64         if (State::INIT != state) {
65             LOG(ERROR) << __func__ << " " << desc.common.name << " can not destroy instance "
66                        << instanceSp.get() << " in state: " << toString(state);
67             return EX_ILLEGAL_STATE;
68         }
69     } else {
70         instanceSp->command(CommandId::RESET);
71         instanceSp->close();
72     }
73 
74     LOG(DEBUG) << __func__ << " " << desc.common.name << " instance " << instanceSp.get()
75                << " destroyed";
76     return EX_NONE;
77 }
78 
79 namespace aidl::android::hardware::audio::effect {
80 
open(const Parameter::Common & common,const std::optional<Parameter::Specific> & specific,OpenEffectReturn * ret)81 ndk::ScopedAStatus EffectImpl::open(const Parameter::Common& common,
82                                     const std::optional<Parameter::Specific>& specific,
83                                     OpenEffectReturn* ret) {
84     // effect only support 32bits float
85     RETURN_IF(common.input.base.format.pcm != common.output.base.format.pcm ||
86                       common.input.base.format.pcm != PcmType::FLOAT_32_BIT,
87               EX_ILLEGAL_ARGUMENT, "dataMustBe32BitsFloat");
88 
89     std::lock_guard lg(mImplMutex);
90     RETURN_OK_IF(mState != State::INIT);
91     mImplContext = createContext(common);
92     RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
93 
94     RETURN_IF(!getInterfaceVersion(&mVersion).isOk(), EX_UNSUPPORTED_OPERATION,
95               "FailedToGetInterfaceVersion");
96     mImplContext->setVersion(mVersion);
97     mEventFlag = mImplContext->getStatusEventFlag();
98     mDataMqNotEmptyEf =
99             mVersion >= kReopenSupportedVersion ? kEventFlagDataMqNotEmpty : kEventFlagNotEmpty;
100 
101     if (specific.has_value()) {
102         RETURN_IF_ASTATUS_NOT_OK(setParameterSpecific(specific.value()), "setSpecParamErr");
103     }
104 
105     mState = State::IDLE;
106     mImplContext->dupeFmq(ret);
107     RETURN_IF(createThread(getEffectNameWithVersion()) != RetCode::SUCCESS,
108               EX_UNSUPPORTED_OPERATION, "FailedToCreateWorker");
109     LOG(INFO) << getEffectNameWithVersion() << __func__;
110     return ndk::ScopedAStatus::ok();
111 }
112 
reopen(OpenEffectReturn * ret)113 ndk::ScopedAStatus EffectImpl::reopen(OpenEffectReturn* ret) {
114     std::lock_guard lg(mImplMutex);
115     RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "alreadyClosed");
116 
117     RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
118     mImplContext->dupeFmqWithReopen(ret);
119     return ndk::ScopedAStatus::ok();
120 }
121 
close()122 ndk::ScopedAStatus EffectImpl::close() {
123     {
124         std::lock_guard lg(mImplMutex);
125         RETURN_OK_IF(mState == State::INIT);
126         RETURN_IF(mState == State::PROCESSING, EX_ILLEGAL_STATE, "closeAtProcessing");
127         mState = State::INIT;
128     }
129 
130     RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
131               "notifyEventFlagNotEmptyFailed");
132     // stop the worker thread, ignore the return code
133     RETURN_IF(destroyThread() != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION,
134               "FailedToDestroyWorker");
135 
136     {
137         std::lock_guard lg(mImplMutex);
138         releaseContext();
139         mImplContext.reset();
140     }
141 
142     LOG(INFO) << getEffectNameWithVersion() << __func__;
143     return ndk::ScopedAStatus::ok();
144 }
145 
setParameter(const Parameter & param)146 ndk::ScopedAStatus EffectImpl::setParameter(const Parameter& param) {
147     std::lock_guard lg(mImplMutex);
148     LOG(VERBOSE) << getEffectNameWithVersion() << __func__ << " with: " << param.toString();
149 
150     const auto& tag = param.getTag();
151     switch (tag) {
152         case Parameter::common:
153         case Parameter::deviceDescription:
154         case Parameter::mode:
155         case Parameter::source:
156             FALLTHROUGH_INTENDED;
157         case Parameter::volumeStereo:
158             return setParameterCommon(param);
159         case Parameter::specific: {
160             return setParameterSpecific(param.get<Parameter::specific>());
161         }
162         default: {
163             LOG(ERROR) << getEffectNameWithVersion() << __func__ << " unsupportedParameterTag "
164                        << toString(tag);
165             return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
166                                                                     "ParameterNotSupported");
167         }
168     }
169 }
170 
getParameter(const Parameter::Id & id,Parameter * param)171 ndk::ScopedAStatus EffectImpl::getParameter(const Parameter::Id& id, Parameter* param) {
172     std::lock_guard lg(mImplMutex);
173     switch (id.getTag()) {
174         case Parameter::Id::commonTag: {
175             RETURN_IF_ASTATUS_NOT_OK(getParameterCommon(id.get<Parameter::Id::commonTag>(), param),
176                                      "CommonParamNotSupported");
177             break;
178         }
179         case Parameter::Id::vendorEffectTag:
180             FALLTHROUGH_INTENDED;
181         default: {
182             Parameter::Specific specific;
183             RETURN_IF_ASTATUS_NOT_OK(getParameterSpecific(id, &specific), "SpecParamNotSupported");
184             param->set<Parameter::specific>(specific);
185             break;
186         }
187     }
188     LOG(VERBOSE) << getEffectNameWithVersion() << __func__ << id.toString() << param->toString();
189     return ndk::ScopedAStatus::ok();
190 }
191 
setParameterCommon(const Parameter & param)192 ndk::ScopedAStatus EffectImpl::setParameterCommon(const Parameter& param) {
193     RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
194 
195     const auto& tag = param.getTag();
196     switch (tag) {
197         case Parameter::common:
198             RETURN_IF(mImplContext->setCommon(param.get<Parameter::common>()) != RetCode::SUCCESS,
199                       EX_ILLEGAL_ARGUMENT, "setCommFailed");
200             break;
201         case Parameter::deviceDescription:
202             RETURN_IF(mImplContext->setOutputDevice(param.get<Parameter::deviceDescription>()) !=
203                               RetCode::SUCCESS,
204                       EX_ILLEGAL_ARGUMENT, "setDeviceFailed");
205             break;
206         case Parameter::mode:
207             RETURN_IF(mImplContext->setAudioMode(param.get<Parameter::mode>()) != RetCode::SUCCESS,
208                       EX_ILLEGAL_ARGUMENT, "setModeFailed");
209             break;
210         case Parameter::source:
211             RETURN_IF(mImplContext->setAudioSource(param.get<Parameter::source>()) !=
212                               RetCode::SUCCESS,
213                       EX_ILLEGAL_ARGUMENT, "setSourceFailed");
214             break;
215         case Parameter::volumeStereo:
216             RETURN_IF(mImplContext->setVolumeStereo(param.get<Parameter::volumeStereo>()) !=
217                               RetCode::SUCCESS,
218                       EX_ILLEGAL_ARGUMENT, "setVolumeStereoFailed");
219             break;
220         default: {
221             LOG(ERROR) << getEffectNameWithVersion() << __func__ << " unsupportedParameterTag "
222                        << toString(tag);
223             return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
224                                                                     "commonParamNotSupported");
225         }
226     }
227     return ndk::ScopedAStatus::ok();
228 }
229 
getParameterCommon(const Parameter::Tag & tag,Parameter * param)230 ndk::ScopedAStatus EffectImpl::getParameterCommon(const Parameter::Tag& tag, Parameter* param) {
231     RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
232 
233     switch (tag) {
234         case Parameter::common: {
235             param->set<Parameter::common>(mImplContext->getCommon());
236             break;
237         }
238         case Parameter::deviceDescription: {
239             param->set<Parameter::deviceDescription>(mImplContext->getOutputDevice());
240             break;
241         }
242         case Parameter::mode: {
243             param->set<Parameter::mode>(mImplContext->getAudioMode());
244             break;
245         }
246         case Parameter::source: {
247             param->set<Parameter::source>(mImplContext->getAudioSource());
248             break;
249         }
250         case Parameter::volumeStereo: {
251             param->set<Parameter::volumeStereo>(mImplContext->getVolumeStereo());
252             break;
253         }
254         default: {
255             LOG(DEBUG) << getEffectNameWithVersion() << __func__ << " unsupported tag "
256                        << toString(tag);
257             return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
258                                                                     "tagNotSupported");
259         }
260     }
261     return ndk::ScopedAStatus::ok();
262 }
263 
getState(State * state)264 ndk::ScopedAStatus EffectImpl::getState(State* state) NO_THREAD_SAFETY_ANALYSIS {
265     *state = mState;
266     return ndk::ScopedAStatus::ok();
267 }
268 
command(CommandId command)269 ndk::ScopedAStatus EffectImpl::command(CommandId command) {
270     std::lock_guard lg(mImplMutex);
271     RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "instanceNotOpen");
272 
273     switch (command) {
274         case CommandId::START:
275             RETURN_OK_IF(mState == State::PROCESSING);
276             RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed");
277             mState = State::PROCESSING;
278             RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
279                       "notifyEventFlagNotEmptyFailed");
280             startThread();
281             break;
282         case CommandId::STOP:
283             RETURN_OK_IF(mState == State::IDLE);
284             mState = State::IDLE;
285             RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
286                       "notifyEventFlagNotEmptyFailed");
287             stopThread();
288             RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed");
289             break;
290         case CommandId::RESET:
291             mState = State::IDLE;
292             RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE,
293                       "notifyEventFlagNotEmptyFailed");
294             stopThread();
295             RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed");
296             break;
297         default:
298             LOG(ERROR) << getEffectNameWithVersion() << __func__ << " instance still processing";
299             return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
300                                                                     "CommandIdNotSupported");
301     }
302     LOG(VERBOSE) << getEffectNameWithVersion() << __func__
303                  << " transfer to state: " << toString(mState);
304     return ndk::ScopedAStatus::ok();
305 }
306 
commandImpl(CommandId command)307 ndk::ScopedAStatus EffectImpl::commandImpl(CommandId command) {
308     RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext");
309     switch (command) {
310         case CommandId::START:
311             mImplContext->enable();
312             break;
313         case CommandId::STOP:
314             mImplContext->disable();
315             break;
316         case CommandId::RESET:
317             mImplContext->disable();
318             mImplContext->reset();
319             mImplContext->resetBuffer();
320             break;
321         default:
322             LOG(ERROR) << __func__ << " commandId " << toString(command) << " not supported";
323             return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
324                                                                     "commandIdNotSupported");
325     }
326     return ndk::ScopedAStatus::ok();
327 }
328 
createContext(const Parameter::Common & common)329 std::shared_ptr<EffectContext> EffectImpl::createContext(const Parameter::Common& common) {
330     return std::make_shared<EffectContext>(1 /* statusMqDepth */, common);
331 }
332 
releaseContext()333 RetCode EffectImpl::releaseContext() {
334     if (mImplContext) {
335         mImplContext.reset();
336     }
337     return RetCode::SUCCESS;
338 }
339 
cleanUp()340 void EffectImpl::cleanUp() {
341     command(CommandId::STOP);
342     close();
343 }
344 
notifyEventFlag(uint32_t flag)345 RetCode EffectImpl::notifyEventFlag(uint32_t flag) {
346     if (!mEventFlag) {
347         LOG(ERROR) << getEffectNameWithVersion() << __func__ << ": StatusEventFlag invalid";
348         return RetCode::ERROR_EVENT_FLAG_ERROR;
349     }
350     if (const auto ret = mEventFlag->wake(flag); ret != ::android::OK) {
351         LOG(ERROR) << getEffectNameWithVersion() << __func__ << ": wake failure with ret " << ret;
352         return RetCode::ERROR_EVENT_FLAG_ERROR;
353     }
354     LOG(VERBOSE) << getEffectNameWithVersion() << __func__ << ": " << std::hex << mEventFlag;
355     return RetCode::SUCCESS;
356 }
357 
status(binder_status_t status,size_t consumed,size_t produced)358 IEffect::Status EffectImpl::status(binder_status_t status, size_t consumed, size_t produced) {
359     IEffect::Status ret;
360     ret.status = status;
361     ret.fmqConsumed = consumed;
362     ret.fmqProduced = produced;
363     return ret;
364 }
365 
process()366 void EffectImpl::process() {
367     ATRACE_NAME(getEffectNameWithVersion().c_str());
368     /**
369      * wait for the EventFlag without lock, it's ok because the mEfGroup pointer will not change
370      * in the life cycle of workerThread (threadLoop).
371      */
372     uint32_t efState = 0;
373     if (!mEventFlag ||
374         ::android::OK != mEventFlag->wait(mDataMqNotEmptyEf, &efState, 0 /* no timeout */,
375                                           true /* retry */) ||
376         !(efState & mDataMqNotEmptyEf)) {
377         LOG(ERROR) << getEffectNameWithVersion() << __func__ << ": StatusEventFlag - " << mEventFlag
378                    << " efState - " << std::hex << efState;
379         return;
380     }
381 
382     {
383         std::lock_guard lg(mImplMutex);
384         if (mState != State::PROCESSING && mState != State::DRAINING) {
385             LOG(DEBUG) << getEffectNameWithVersion()
386                        << " skip process in state: " << toString(mState);
387             return;
388         }
389         RETURN_VALUE_IF(!mImplContext, void(), "nullContext");
390         auto statusMQ = mImplContext->getStatusFmq();
391         auto inputMQ = mImplContext->getInputDataFmq();
392         auto outputMQ = mImplContext->getOutputDataFmq();
393         auto buffer = mImplContext->getWorkBuffer();
394         if (!inputMQ || !outputMQ) {
395             return;
396         }
397 
398         assert(mImplContext->getWorkBufferSize() >=
399                std::max(inputMQ->availableToRead(), outputMQ->availableToWrite()));
400         auto processSamples = std::min(inputMQ->availableToRead(), outputMQ->availableToWrite());
401         if (processSamples) {
402             inputMQ->read(buffer, processSamples);
403             IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples);
404             outputMQ->write(buffer, status.fmqProduced);
405             statusMQ->writeBlocking(&status, 1);
406         }
407     }
408 }
409 
410 // A placeholder processing implementation to copy samples from input to output
effectProcessImpl(float * in,float * out,int samples)411 IEffect::Status EffectImpl::effectProcessImpl(float* in, float* out, int samples) {
412     for (int i = 0; i < samples; i++) {
413         *out++ = *in++;
414     }
415     return {STATUS_OK, samples, samples};
416 }
417 
418 }  // namespace aidl::android::hardware::audio::effect
419