1 /*
2  * Copyright (C) 2018 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.h>
18 
19 #define LOG_TAG "EffectHAL"
20 #define ATRACE_TAG ATRACE_TAG_AUDIO
21 
22 #include "Conversions.h"
23 #include "Effect.h"
24 #include "common/all-versions/default/EffectMap.h"
25 
26 #include <memory.h>
27 
28 #define ATRACE_TAG ATRACE_TAG_AUDIO
29 
30 #include <android/log.h>
31 #include <media/EffectsFactoryApi.h>
32 #include <utils/Trace.h>
33 
34 #include "VersionUtils.h"
35 
36 namespace android {
37 namespace hardware {
38 namespace audio {
39 namespace effect {
40 namespace CPP_VERSION {
41 namespace implementation {
42 
43 using ::android::hardware::audio::common::CPP_VERSION::implementation::AudioChannelBitfield;
44 
45 namespace {
46 
47 class ProcessThread : public Thread {
48    public:
49     // ProcessThread's lifespan never exceeds Effect's lifespan.
ProcessThread(std::atomic<bool> * stop,effect_handle_t effect,std::atomic<audio_buffer_t * > * inBuffer,std::atomic<audio_buffer_t * > * outBuffer,Effect::StatusMQ * statusMQ,EventFlag * efGroup)50     ProcessThread(std::atomic<bool>* stop, effect_handle_t effect,
51                   std::atomic<audio_buffer_t*>* inBuffer, std::atomic<audio_buffer_t*>* outBuffer,
52                   Effect::StatusMQ* statusMQ, EventFlag* efGroup)
53         : Thread(false /*canCallJava*/),
54           mStop(stop),
55           mEffect(effect),
56           mHasProcessReverse((*mEffect)->process_reverse != NULL),
57           mInBuffer(inBuffer),
58           mOutBuffer(outBuffer),
59           mStatusMQ(statusMQ),
60           mEfGroup(efGroup) {}
~ProcessThread()61     virtual ~ProcessThread() {}
62 
63    private:
64     std::atomic<bool>* mStop;
65     effect_handle_t mEffect;
66     bool mHasProcessReverse;
67     std::atomic<audio_buffer_t*>* mInBuffer;
68     std::atomic<audio_buffer_t*>* mOutBuffer;
69     Effect::StatusMQ* mStatusMQ;
70     EventFlag* mEfGroup;
71 
72     bool threadLoop() override;
73 };
74 
threadLoop()75 bool ProcessThread::threadLoop() {
76     // This implementation doesn't return control back to the Thread until it decides to stop,
77     // as the Thread uses mutexes, and this can lead to priority inversion.
78     while (!std::atomic_load_explicit(mStop, std::memory_order_acquire)) {
79         uint32_t efState = 0;
80         mEfGroup->wait(static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS_ALL), &efState);
81         if (!(efState & static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS_ALL)) ||
82             (efState & static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_QUIT))) {
83             continue;  // Nothing to do or time to quit.
84         }
85         Result retval = Result::OK;
86         if (efState & static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS_REVERSE) &&
87             !mHasProcessReverse) {
88             retval = Result::NOT_SUPPORTED;
89         }
90 
91         if (retval == Result::OK) {
92             // affects both buffer pointers and their contents.
93             std::atomic_thread_fence(std::memory_order_acquire);
94             int32_t processResult;
95             audio_buffer_t* inBuffer =
96                 std::atomic_load_explicit(mInBuffer, std::memory_order_relaxed);
97             audio_buffer_t* outBuffer =
98                 std::atomic_load_explicit(mOutBuffer, std::memory_order_relaxed);
99             if (inBuffer != nullptr && outBuffer != nullptr) {
100                 if (efState & static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS)) {
101                     processResult = (*mEffect)->process(mEffect, inBuffer, outBuffer);
102                 } else {
103                     processResult = (*mEffect)->process_reverse(mEffect, inBuffer, outBuffer);
104                 }
105                 std::atomic_thread_fence(std::memory_order_release);
106             } else {
107                 ALOGE("processing buffers were not set before calling 'process'");
108                 processResult = -ENODEV;
109             }
110             switch (processResult) {
111                 case 0:
112                     retval = Result::OK;
113                     break;
114                 case -ENODATA:
115                     retval = Result::INVALID_STATE;
116                     break;
117                 case -EINVAL:
118                     retval = Result::INVALID_ARGUMENTS;
119                     break;
120                 default:
121                     retval = Result::NOT_INITIALIZED;
122             }
123         }
124         if (!mStatusMQ->write(&retval)) {
125             ALOGW("status message queue write failed");
126         }
127         mEfGroup->wake(static_cast<uint32_t>(MessageQueueFlagBits::DONE_PROCESSING));
128     }
129 
130     return false;
131 }
132 
133 }  // namespace
134 
135 // static
136 const char* Effect::sContextResultOfCommand = "returned status";
137 const char* Effect::sContextCallToCommand = "error";
138 const char* Effect::sContextCallFunction = sContextCallToCommand;
139 
Effect(effect_handle_t handle)140 Effect::Effect(effect_handle_t handle)
141     : mHandle(handle), mEfGroup(nullptr), mStopProcessThread(false) {}
142 
~Effect()143 Effect::~Effect() {
144     ATRACE_CALL();
145     (void)close();
146     if (mProcessThread.get()) {
147         ATRACE_NAME("mProcessThread->join");
148         status_t status = mProcessThread->join();
149         ALOGE_IF(status, "processing thread exit error: %s", strerror(-status));
150     }
151     if (mEfGroup) {
152         status_t status = EventFlag::deleteEventFlag(&mEfGroup);
153         ALOGE_IF(status, "processing MQ event flag deletion error: %s", strerror(-status));
154     }
155     mInBuffer.clear();
156     mOutBuffer.clear();
157 #if MAJOR_VERSION <= 5
158     int status = EffectRelease(mHandle);
159     ALOGW_IF(status, "Error releasing effect %p: %s", mHandle, strerror(-status));
160 #endif
161     EffectMap::getInstance().remove(mHandle);
162     mHandle = 0;
163 }
164 
165 // static
166 template <typename T>
alignedSizeIn(size_t s)167 size_t Effect::alignedSizeIn(size_t s) {
168     return (s + sizeof(T) - 1) / sizeof(T);
169 }
170 
171 // static
172 template <typename T>
hidlVecToHal(const hidl_vec<T> & vec,uint32_t * halDataSize)173 std::unique_ptr<uint8_t[]> Effect::hidlVecToHal(const hidl_vec<T>& vec, uint32_t* halDataSize) {
174     // Due to bugs in HAL, they may attempt to write into the provided
175     // input buffer. The original binder buffer is r/o, thus it is needed
176     // to create a r/w version.
177     *halDataSize = vec.size() * sizeof(T);
178     std::unique_ptr<uint8_t[]> halData(new uint8_t[*halDataSize]);
179     memcpy(&halData[0], &vec[0], *halDataSize);
180     return halData;
181 }
182 
183 // static
effectAuxChannelsConfigFromHal(const channel_config_t & halConfig,EffectAuxChannelsConfig * config)184 void Effect::effectAuxChannelsConfigFromHal(const channel_config_t& halConfig,
185                                             EffectAuxChannelsConfig* config) {
186     config->mainChannels = AudioChannelBitfield(halConfig.main_channels);
187     config->auxChannels = AudioChannelBitfield(halConfig.aux_channels);
188 }
189 
190 // static
effectAuxChannelsConfigToHal(const EffectAuxChannelsConfig & config,channel_config_t * halConfig)191 void Effect::effectAuxChannelsConfigToHal(const EffectAuxChannelsConfig& config,
192                                           channel_config_t* halConfig) {
193     halConfig->main_channels = static_cast<audio_channel_mask_t>(config.mainChannels);
194     halConfig->aux_channels = static_cast<audio_channel_mask_t>(config.auxChannels);
195 }
196 
197 // static
effectBufferConfigFromHal(const buffer_config_t & halConfig,EffectBufferConfig * config)198 void Effect::effectBufferConfigFromHal(const buffer_config_t& halConfig,
199                                        EffectBufferConfig* config) {
200     config->buffer.id = 0;
201     config->buffer.frameCount = 0;
202     config->samplingRateHz = halConfig.samplingRate;
203     config->channels = AudioChannelBitfield(halConfig.channels);
204     config->format = AudioFormat(halConfig.format);
205     config->accessMode = EffectBufferAccess(halConfig.accessMode);
206     config->mask = static_cast<decltype(config->mask)>(halConfig.mask);
207 }
208 
209 // static
effectBufferConfigToHal(const EffectBufferConfig & config,buffer_config_t * halConfig)210 void Effect::effectBufferConfigToHal(const EffectBufferConfig& config, buffer_config_t* halConfig) {
211     // Note: setting the buffers directly is considered obsolete. They need to be set
212     // using 'setProcessBuffers'.
213     halConfig->buffer.frameCount = 0;
214     halConfig->buffer.raw = NULL;
215     halConfig->samplingRate = config.samplingRateHz;
216     halConfig->channels = static_cast<uint32_t>(config.channels);
217     // Note: The framework code does not use BP.
218     halConfig->bufferProvider.cookie = NULL;
219     halConfig->bufferProvider.getBuffer = NULL;
220     halConfig->bufferProvider.releaseBuffer = NULL;
221     halConfig->format = static_cast<uint8_t>(config.format);
222     halConfig->accessMode = static_cast<uint8_t>(config.accessMode);
223     halConfig->mask = static_cast<uint8_t>(config.mask);
224 }
225 
226 // static
effectConfigFromHal(const effect_config_t & halConfig,EffectConfig * config)227 void Effect::effectConfigFromHal(const effect_config_t& halConfig, EffectConfig* config) {
228     effectBufferConfigFromHal(halConfig.inputCfg, &config->inputCfg);
229     effectBufferConfigFromHal(halConfig.outputCfg, &config->outputCfg);
230 }
231 
232 // static
effectConfigToHal(const EffectConfig & config,effect_config_t * halConfig)233 void Effect::effectConfigToHal(const EffectConfig& config, effect_config_t* halConfig) {
234     effectBufferConfigToHal(config.inputCfg, &halConfig->inputCfg);
235     effectBufferConfigToHal(config.outputCfg, &halConfig->outputCfg);
236 }
237 
238 // static
effectOffloadParamToHal(const EffectOffloadParameter & offload,effect_offload_param_t * halOffload)239 void Effect::effectOffloadParamToHal(const EffectOffloadParameter& offload,
240                                      effect_offload_param_t* halOffload) {
241     halOffload->isOffload = offload.isOffload;
242     halOffload->ioHandle = offload.ioHandle;
243 }
244 
245 // static
parameterToHal(uint32_t paramSize,const void * paramData,uint32_t valueSize,const void ** valueData)246 std::vector<uint8_t> Effect::parameterToHal(uint32_t paramSize, const void* paramData,
247                                             uint32_t valueSize, const void** valueData) {
248     size_t valueOffsetFromData = alignedSizeIn<uint32_t>(paramSize) * sizeof(uint32_t);
249     size_t halParamBufferSize = sizeof(effect_param_t) + valueOffsetFromData + valueSize;
250     std::vector<uint8_t> halParamBuffer(halParamBufferSize, 0);
251     effect_param_t* halParam = reinterpret_cast<effect_param_t*>(&halParamBuffer[0]);
252     halParam->psize = paramSize;
253     halParam->vsize = valueSize;
254     memcpy(halParam->data, paramData, paramSize);
255     if (valueData) {
256         if (*valueData) {
257             // Value data is provided.
258             memcpy(halParam->data + valueOffsetFromData, *valueData, valueSize);
259         } else {
260             // The caller needs the pointer to the value data location.
261             *valueData = halParam->data + valueOffsetFromData;
262         }
263     }
264     return halParamBuffer;
265 }
266 
analyzeCommandStatus(const char * commandName,const char * context,status_t status)267 Result Effect::analyzeCommandStatus(const char* commandName, const char* context, status_t status) {
268     return analyzeStatus("command", commandName, context, status);
269 }
270 
analyzeStatus(const char * funcName,const char * subFuncName,const char * contextDescription,status_t status)271 Result Effect::analyzeStatus(const char* funcName, const char* subFuncName,
272                              const char* contextDescription, status_t status) {
273     if (status != OK) {
274         ALOGW("Effect %p %s %s %s: %s", mHandle, funcName, subFuncName, contextDescription,
275               strerror(-status));
276     }
277     switch (status) {
278         case OK:
279             return Result::OK;
280         case -EINVAL:
281             return Result::INVALID_ARGUMENTS;
282         case -ENODATA:
283             return Result::INVALID_STATE;
284         case -ENODEV:
285             return Result::NOT_INITIALIZED;
286         case -ENOMEM:
287             return Result::RESULT_TOO_BIG;
288         case -ENOSYS:
289             return Result::NOT_SUPPORTED;
290         default:
291             return Result::INVALID_STATE;
292     }
293 }
294 
getConfigImpl(int commandCode,const char * commandName,GetConfigCallback cb)295 void Effect::getConfigImpl(int commandCode, const char* commandName, GetConfigCallback cb) {
296     uint32_t halResultSize = sizeof(effect_config_t);
297     effect_config_t halConfig{};
298     status_t status =
299         (*mHandle)->command(mHandle, commandCode, 0, NULL, &halResultSize, &halConfig);
300     EffectConfig config;
301     if (status == OK) {
302         effectConfigFromHal(halConfig, &config);
303     }
304     cb(analyzeCommandStatus(commandName, sContextCallToCommand, status), config);
305 }
306 
getCurrentConfigImpl(uint32_t featureId,uint32_t configSize,GetCurrentConfigSuccessCallback onSuccess)307 Result Effect::getCurrentConfigImpl(uint32_t featureId, uint32_t configSize,
308                                     GetCurrentConfigSuccessCallback onSuccess) {
309     uint32_t halCmd = featureId;
310     uint32_t halResult[alignedSizeIn<uint32_t>(sizeof(uint32_t) + configSize)];
311     memset(halResult, 0, sizeof(halResult));
312     uint32_t halResultSize = 0;
313     return sendCommandReturningStatusAndData(EFFECT_CMD_GET_FEATURE_CONFIG, "GET_FEATURE_CONFIG",
314                                              sizeof(uint32_t), &halCmd, &halResultSize, halResult,
315                                              sizeof(uint32_t), [&] { onSuccess(&halResult[1]); });
316 }
317 
getParameterImpl(uint32_t paramSize,const void * paramData,uint32_t requestValueSize,uint32_t replyValueSize,GetParameterSuccessCallback onSuccess)318 Result Effect::getParameterImpl(uint32_t paramSize, const void* paramData,
319                                 uint32_t requestValueSize, uint32_t replyValueSize,
320                                 GetParameterSuccessCallback onSuccess) {
321     // As it is unknown what method HAL uses for copying the provided parameter data,
322     // it is safer to make sure that input and output buffers do not overlap.
323     std::vector<uint8_t> halCmdBuffer =
324         parameterToHal(paramSize, paramData, requestValueSize, nullptr);
325     const void* valueData = nullptr;
326     std::vector<uint8_t> halParamBuffer =
327         parameterToHal(paramSize, paramData, replyValueSize, &valueData);
328     uint32_t halParamBufferSize = halParamBuffer.size();
329 
330     return sendCommandReturningStatusAndData(
331         EFFECT_CMD_GET_PARAM, "GET_PARAM", halCmdBuffer.size(), &halCmdBuffer[0],
332         &halParamBufferSize, &halParamBuffer[0], sizeof(effect_param_t), [&] {
333             effect_param_t* halParam = reinterpret_cast<effect_param_t*>(&halParamBuffer[0]);
334             onSuccess(halParam->vsize, valueData);
335         });
336 }
337 
getSupportedConfigsImpl(uint32_t featureId,uint32_t maxConfigs,uint32_t configSize,GetSupportedConfigsSuccessCallback onSuccess)338 Result Effect::getSupportedConfigsImpl(uint32_t featureId, uint32_t maxConfigs, uint32_t configSize,
339                                        GetSupportedConfigsSuccessCallback onSuccess) {
340     uint32_t halCmd[2] = {featureId, maxConfigs};
341     uint32_t halResultSize = 2 * sizeof(uint32_t) + maxConfigs * sizeof(configSize);
342     uint8_t halResult[halResultSize];
343     memset(&halResult[0], 0, halResultSize);
344     return sendCommandReturningStatusAndData(
345         EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS, "GET_FEATURE_SUPPORTED_CONFIGS", sizeof(halCmd),
346         halCmd, &halResultSize, &halResult[0], 2 * sizeof(uint32_t), [&] {
347             uint32_t* halResult32 = reinterpret_cast<uint32_t*>(&halResult[0]);
348             uint32_t supportedConfigs = *(++halResult32);  // skip status field
349             if (supportedConfigs > maxConfigs) supportedConfigs = maxConfigs;
350             onSuccess(supportedConfigs, ++halResult32);
351         });
352 }
353 
prepareForProcessing(prepareForProcessing_cb _hidl_cb)354 Return<void> Effect::prepareForProcessing(prepareForProcessing_cb _hidl_cb) {
355     status_t status;
356     // Create message queue.
357     if (mStatusMQ) {
358         ALOGE("the client attempts to call prepareForProcessing_cb twice");
359         _hidl_cb(Result::INVALID_STATE, StatusMQ::Descriptor());
360         return Void();
361     }
362     std::unique_ptr<StatusMQ> tempStatusMQ(new StatusMQ(1, true /*EventFlag*/));
363     if (!tempStatusMQ->isValid()) {
364         ALOGE_IF(!tempStatusMQ->isValid(), "status MQ is invalid");
365         _hidl_cb(Result::INVALID_ARGUMENTS, StatusMQ::Descriptor());
366         return Void();
367     }
368     status = EventFlag::createEventFlag(tempStatusMQ->getEventFlagWord(), &mEfGroup);
369     if (status != OK || !mEfGroup) {
370         ALOGE("failed creating event flag for status MQ: %s", strerror(-status));
371         _hidl_cb(Result::INVALID_ARGUMENTS, StatusMQ::Descriptor());
372         return Void();
373     }
374 
375     // Create and launch the thread.
376     mProcessThread = new ProcessThread(&mStopProcessThread, mHandle, &mHalInBufferPtr,
377                                        &mHalOutBufferPtr, tempStatusMQ.get(), mEfGroup);
378     status = mProcessThread->run("effect", PRIORITY_URGENT_AUDIO);
379     if (status != OK) {
380         ALOGW("failed to start effect processing thread: %s", strerror(-status));
381         _hidl_cb(Result::INVALID_ARGUMENTS, MQDescriptorSync<Result>());
382         return Void();
383     }
384 
385     mStatusMQ = std::move(tempStatusMQ);
386     _hidl_cb(Result::OK, *mStatusMQ->getDesc());
387     return Void();
388 }
389 
setProcessBuffers(const AudioBuffer & inBuffer,const AudioBuffer & outBuffer)390 Return<Result> Effect::setProcessBuffers(const AudioBuffer& inBuffer,
391                                          const AudioBuffer& outBuffer) {
392     AudioBufferManager& manager = AudioBufferManager::getInstance();
393     sp<AudioBufferWrapper> tempInBuffer, tempOutBuffer;
394     if (!manager.wrap(inBuffer, &tempInBuffer)) {
395         ALOGE("Could not map memory of the input buffer");
396         return Result::INVALID_ARGUMENTS;
397     }
398     if (!manager.wrap(outBuffer, &tempOutBuffer)) {
399         ALOGE("Could not map memory of the output buffer");
400         return Result::INVALID_ARGUMENTS;
401     }
402     mInBuffer = tempInBuffer;
403     mOutBuffer = tempOutBuffer;
404     // The processing thread only reads these pointers after waking up by an event flag,
405     // so it's OK to update the pair non-atomically.
406     mHalInBufferPtr.store(mInBuffer->getHalBuffer(), std::memory_order_release);
407     mHalOutBufferPtr.store(mOutBuffer->getHalBuffer(), std::memory_order_release);
408     return Result::OK;
409 }
410 
sendCommand(int commandCode,const char * commandName)411 Result Effect::sendCommand(int commandCode, const char* commandName) {
412     return sendCommand(commandCode, commandName, 0, NULL);
413 }
414 
sendCommand(int commandCode,const char * commandName,uint32_t size,void * data)415 Result Effect::sendCommand(int commandCode, const char* commandName, uint32_t size, void* data) {
416     status_t status = (*mHandle)->command(mHandle, commandCode, size, data, 0, NULL);
417     return analyzeCommandStatus(commandName, sContextCallToCommand, status);
418 }
419 
sendCommandReturningData(int commandCode,const char * commandName,uint32_t * replySize,void * replyData)420 Result Effect::sendCommandReturningData(int commandCode, const char* commandName,
421                                         uint32_t* replySize, void* replyData) {
422     return sendCommandReturningData(commandCode, commandName, 0, NULL, replySize, replyData);
423 }
424 
sendCommandReturningData(int commandCode,const char * commandName,uint32_t size,void * data,uint32_t * replySize,void * replyData)425 Result Effect::sendCommandReturningData(int commandCode, const char* commandName, uint32_t size,
426                                         void* data, uint32_t* replySize, void* replyData) {
427     uint32_t expectedReplySize = *replySize;
428     status_t status = (*mHandle)->command(mHandle, commandCode, size, data, replySize, replyData);
429     if (status == OK && *replySize != expectedReplySize) {
430         status = -ENODATA;
431     }
432     return analyzeCommandStatus(commandName, sContextCallToCommand, status);
433 }
434 
sendCommandReturningStatus(int commandCode,const char * commandName)435 Result Effect::sendCommandReturningStatus(int commandCode, const char* commandName) {
436     return sendCommandReturningStatus(commandCode, commandName, 0, NULL);
437 }
438 
sendCommandReturningStatus(int commandCode,const char * commandName,uint32_t size,void * data)439 Result Effect::sendCommandReturningStatus(int commandCode, const char* commandName, uint32_t size,
440                                           void* data) {
441     uint32_t replyCmdStatus;
442     uint32_t replySize = sizeof(uint32_t);
443     return sendCommandReturningStatusAndData(commandCode, commandName, size, data, &replySize,
444                                              &replyCmdStatus, replySize, [] {});
445 }
446 
sendCommandReturningStatusAndData(int commandCode,const char * commandName,uint32_t size,void * data,uint32_t * replySize,void * replyData,uint32_t minReplySize,CommandSuccessCallback onSuccess)447 Result Effect::sendCommandReturningStatusAndData(int commandCode, const char* commandName,
448                                                  uint32_t size, void* data, uint32_t* replySize,
449                                                  void* replyData, uint32_t minReplySize,
450                                                  CommandSuccessCallback onSuccess) {
451     status_t status = (*mHandle)->command(mHandle, commandCode, size, data, replySize, replyData);
452     Result retval;
453     if (status == OK && minReplySize >= sizeof(uint32_t) && *replySize >= minReplySize) {
454         uint32_t commandStatus = *reinterpret_cast<uint32_t*>(replyData);
455         retval = analyzeCommandStatus(commandName, sContextResultOfCommand, commandStatus);
456         if (commandStatus == OK) {
457             onSuccess();
458         }
459     } else {
460         retval = analyzeCommandStatus(commandName, sContextCallToCommand, status);
461     }
462     return retval;
463 }
464 
setConfigImpl(int commandCode,const char * commandName,const EffectConfig & config,const sp<IEffectBufferProviderCallback> & inputBufferProvider,const sp<IEffectBufferProviderCallback> & outputBufferProvider)465 Result Effect::setConfigImpl(int commandCode, const char* commandName, const EffectConfig& config,
466                              const sp<IEffectBufferProviderCallback>& inputBufferProvider,
467                              const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
468     effect_config_t halConfig;
469     effectConfigToHal(config, &halConfig);
470     if (inputBufferProvider != 0) {
471         LOG_FATAL("Using input buffer provider is not supported");
472     }
473     if (outputBufferProvider != 0) {
474         LOG_FATAL("Using output buffer provider is not supported");
475     }
476     return sendCommandReturningStatus(commandCode, commandName, sizeof(effect_config_t),
477                                       &halConfig);
478 }
479 
setParameterImpl(uint32_t paramSize,const void * paramData,uint32_t valueSize,const void * valueData)480 Result Effect::setParameterImpl(uint32_t paramSize, const void* paramData, uint32_t valueSize,
481                                 const void* valueData) {
482     std::vector<uint8_t> halParamBuffer =
483         parameterToHal(paramSize, paramData, valueSize, &valueData);
484     return sendCommandReturningStatus(EFFECT_CMD_SET_PARAM, "SET_PARAM", halParamBuffer.size(),
485                                       &halParamBuffer[0]);
486 }
487 
488 // Methods from ::android::hardware::audio::effect::CPP_VERSION::IEffect follow.
init()489 Return<Result> Effect::init() {
490     return sendCommandReturningStatus(EFFECT_CMD_INIT, "INIT");
491 }
492 
setConfig(const EffectConfig & config,const sp<IEffectBufferProviderCallback> & inputBufferProvider,const sp<IEffectBufferProviderCallback> & outputBufferProvider)493 Return<Result> Effect::setConfig(const EffectConfig& config,
494                                  const sp<IEffectBufferProviderCallback>& inputBufferProvider,
495                                  const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
496     return setConfigImpl(EFFECT_CMD_SET_CONFIG, "SET_CONFIG", config, inputBufferProvider,
497                          outputBufferProvider);
498 }
499 
reset()500 Return<Result> Effect::reset() {
501     return sendCommand(EFFECT_CMD_RESET, "RESET");
502 }
503 
enable()504 Return<Result> Effect::enable() {
505     return sendCommandReturningStatus(EFFECT_CMD_ENABLE, "ENABLE");
506 }
507 
disable()508 Return<Result> Effect::disable() {
509     return sendCommandReturningStatus(EFFECT_CMD_DISABLE, "DISABLE");
510 }
511 
setDevice(AudioDeviceBitfield device)512 Return<Result> Effect::setDevice(AudioDeviceBitfield device) {
513     uint32_t halDevice = static_cast<uint32_t>(device);
514     return sendCommand(EFFECT_CMD_SET_DEVICE, "SET_DEVICE", sizeof(uint32_t), &halDevice);
515 }
516 
setAndGetVolume(const hidl_vec<uint32_t> & volumes,setAndGetVolume_cb _hidl_cb)517 Return<void> Effect::setAndGetVolume(const hidl_vec<uint32_t>& volumes,
518                                      setAndGetVolume_cb _hidl_cb) {
519     uint32_t halDataSize;
520     std::unique_ptr<uint8_t[]> halData = hidlVecToHal(volumes, &halDataSize);
521     uint32_t halResultSize = halDataSize;
522     uint32_t halResult[volumes.size()];
523     Result retval = sendCommandReturningData(EFFECT_CMD_SET_VOLUME, "SET_VOLUME", halDataSize,
524                                              &halData[0], &halResultSize, halResult);
525     hidl_vec<uint32_t> result;
526     if (retval == Result::OK) {
527         result.setToExternal(&halResult[0], halResultSize);
528     }
529     _hidl_cb(retval, result);
530     return Void();
531 }
532 
volumeChangeNotification(const hidl_vec<uint32_t> & volumes)533 Return<Result> Effect::volumeChangeNotification(const hidl_vec<uint32_t>& volumes) {
534     uint32_t halDataSize;
535     std::unique_ptr<uint8_t[]> halData = hidlVecToHal(volumes, &halDataSize);
536     return sendCommand(EFFECT_CMD_SET_VOLUME, "SET_VOLUME", halDataSize, &halData[0]);
537 }
538 
setAudioMode(AudioMode mode)539 Return<Result> Effect::setAudioMode(AudioMode mode) {
540     uint32_t halMode = static_cast<uint32_t>(mode);
541     return sendCommand(EFFECT_CMD_SET_AUDIO_MODE, "SET_AUDIO_MODE", sizeof(uint32_t), &halMode);
542 }
543 
setConfigReverse(const EffectConfig & config,const sp<IEffectBufferProviderCallback> & inputBufferProvider,const sp<IEffectBufferProviderCallback> & outputBufferProvider)544 Return<Result> Effect::setConfigReverse(
545     const EffectConfig& config, const sp<IEffectBufferProviderCallback>& inputBufferProvider,
546     const sp<IEffectBufferProviderCallback>& outputBufferProvider) {
547     return setConfigImpl(EFFECT_CMD_SET_CONFIG_REVERSE, "SET_CONFIG_REVERSE", config,
548                          inputBufferProvider, outputBufferProvider);
549 }
550 
setInputDevice(AudioDeviceBitfield device)551 Return<Result> Effect::setInputDevice(AudioDeviceBitfield device) {
552     uint32_t halDevice = static_cast<uint32_t>(device);
553     return sendCommand(EFFECT_CMD_SET_INPUT_DEVICE, "SET_INPUT_DEVICE", sizeof(uint32_t),
554                        &halDevice);
555 }
556 
getConfig(getConfig_cb _hidl_cb)557 Return<void> Effect::getConfig(getConfig_cb _hidl_cb) {
558     getConfigImpl(EFFECT_CMD_GET_CONFIG, "GET_CONFIG", _hidl_cb);
559     return Void();
560 }
561 
getConfigReverse(getConfigReverse_cb _hidl_cb)562 Return<void> Effect::getConfigReverse(getConfigReverse_cb _hidl_cb) {
563     getConfigImpl(EFFECT_CMD_GET_CONFIG_REVERSE, "GET_CONFIG_REVERSE", _hidl_cb);
564     return Void();
565 }
566 
getSupportedAuxChannelsConfigs(uint32_t maxConfigs,getSupportedAuxChannelsConfigs_cb _hidl_cb)567 Return<void> Effect::getSupportedAuxChannelsConfigs(uint32_t maxConfigs,
568                                                     getSupportedAuxChannelsConfigs_cb _hidl_cb) {
569     hidl_vec<EffectAuxChannelsConfig> result;
570     Result retval = getSupportedConfigsImpl(
571         EFFECT_FEATURE_AUX_CHANNELS, maxConfigs, sizeof(channel_config_t),
572         [&](uint32_t supportedConfigs, void* configsData) {
573             result.resize(supportedConfigs);
574             channel_config_t* config = reinterpret_cast<channel_config_t*>(configsData);
575             for (size_t i = 0; i < result.size(); ++i) {
576                 effectAuxChannelsConfigFromHal(*config++, &result[i]);
577             }
578         });
579     _hidl_cb(retval, result);
580     return Void();
581 }
582 
getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb)583 Return<void> Effect::getAuxChannelsConfig(getAuxChannelsConfig_cb _hidl_cb) {
584     uint32_t halResult[alignedSizeIn<uint32_t>(sizeof(uint32_t) + sizeof(channel_config_t))];
585     memset(halResult, 0, sizeof(halResult));
586     EffectAuxChannelsConfig result;
587     Result retval = getCurrentConfigImpl(
588         EFFECT_FEATURE_AUX_CHANNELS, sizeof(channel_config_t), [&](void* configData) {
589             effectAuxChannelsConfigFromHal(*reinterpret_cast<channel_config_t*>(configData),
590                                            &result);
591         });
592     _hidl_cb(retval, result);
593     return Void();
594 }
595 
setAuxChannelsConfig(const EffectAuxChannelsConfig & config)596 Return<Result> Effect::setAuxChannelsConfig(const EffectAuxChannelsConfig& config) {
597     uint32_t halCmd[alignedSizeIn<uint32_t>(sizeof(uint32_t) + sizeof(channel_config_t))];
598     halCmd[0] = EFFECT_FEATURE_AUX_CHANNELS;
599     effectAuxChannelsConfigToHal(config, reinterpret_cast<channel_config_t*>(&halCmd[1]));
600     return sendCommandReturningStatus(EFFECT_CMD_SET_FEATURE_CONFIG,
601                                       "SET_FEATURE_CONFIG AUX_CHANNELS", sizeof(halCmd), halCmd);
602 }
603 
setAudioSource(AudioSource source)604 Return<Result> Effect::setAudioSource(AudioSource source) {
605     uint32_t halSource = static_cast<uint32_t>(source);
606     return sendCommand(EFFECT_CMD_SET_AUDIO_SOURCE, "SET_AUDIO_SOURCE", sizeof(uint32_t),
607                        &halSource);
608 }
609 
offload(const EffectOffloadParameter & param)610 Return<Result> Effect::offload(const EffectOffloadParameter& param) {
611     effect_offload_param_t halParam;
612     effectOffloadParamToHal(param, &halParam);
613     return sendCommandReturningStatus(EFFECT_CMD_OFFLOAD, "OFFLOAD", sizeof(effect_offload_param_t),
614                                       &halParam);
615 }
616 
getDescriptor(getDescriptor_cb _hidl_cb)617 Return<void> Effect::getDescriptor(getDescriptor_cb _hidl_cb) {
618     effect_descriptor_t halDescriptor;
619     memset(&halDescriptor, 0, sizeof(effect_descriptor_t));
620     status_t status = (*mHandle)->get_descriptor(mHandle, &halDescriptor);
621     EffectDescriptor descriptor;
622     if (status == OK) {
623         effectDescriptorFromHal(halDescriptor, &descriptor);
624     }
625     _hidl_cb(analyzeStatus("get_descriptor", "", sContextCallFunction, status), descriptor);
626     return Void();
627 }
628 
command(uint32_t commandId,const hidl_vec<uint8_t> & data,uint32_t resultMaxSize,command_cb _hidl_cb)629 Return<void> Effect::command(uint32_t commandId, const hidl_vec<uint8_t>& data,
630                              uint32_t resultMaxSize, command_cb _hidl_cb) {
631     uint32_t halDataSize;
632     std::unique_ptr<uint8_t[]> halData = hidlVecToHal(data, &halDataSize);
633     uint32_t halResultSize = resultMaxSize;
634     std::unique_ptr<uint8_t[]> halResult(new uint8_t[halResultSize]);
635     memset(&halResult[0], 0, halResultSize);
636 
637     void* dataPtr = halDataSize > 0 ? &halData[0] : NULL;
638     void* resultPtr = halResultSize > 0 ? &halResult[0] : NULL;
639     status_t status =
640         (*mHandle)->command(mHandle, commandId, halDataSize, dataPtr, &halResultSize, resultPtr);
641     hidl_vec<uint8_t> result;
642     if (status == OK && resultPtr != NULL) {
643         result.setToExternal(&halResult[0], halResultSize);
644     }
645     _hidl_cb(status, result);
646     return Void();
647 }
648 
setParameter(const hidl_vec<uint8_t> & parameter,const hidl_vec<uint8_t> & value)649 Return<Result> Effect::setParameter(const hidl_vec<uint8_t>& parameter,
650                                     const hidl_vec<uint8_t>& value) {
651     return setParameterImpl(parameter.size(), &parameter[0], value.size(), &value[0]);
652 }
653 
getParameter(const hidl_vec<uint8_t> & parameter,uint32_t valueMaxSize,getParameter_cb _hidl_cb)654 Return<void> Effect::getParameter(const hidl_vec<uint8_t>& parameter, uint32_t valueMaxSize,
655                                   getParameter_cb _hidl_cb) {
656     hidl_vec<uint8_t> value;
657     Result retval = getParameterImpl(
658         parameter.size(), &parameter[0], valueMaxSize,
659         [&](uint32_t valueSize, const void* valueData) {
660             value.setToExternal(reinterpret_cast<uint8_t*>(const_cast<void*>(valueData)),
661                                 valueSize);
662         });
663     _hidl_cb(retval, value);
664     return Void();
665 }
666 
getSupportedConfigsForFeature(uint32_t featureId,uint32_t maxConfigs,uint32_t configSize,getSupportedConfigsForFeature_cb _hidl_cb)667 Return<void> Effect::getSupportedConfigsForFeature(uint32_t featureId, uint32_t maxConfigs,
668                                                    uint32_t configSize,
669                                                    getSupportedConfigsForFeature_cb _hidl_cb) {
670     uint32_t configCount = 0;
671     hidl_vec<uint8_t> result;
672     Result retval = getSupportedConfigsImpl(featureId, maxConfigs, configSize,
673                                             [&](uint32_t supportedConfigs, void* configsData) {
674                                                 configCount = supportedConfigs;
675                                                 result.resize(configCount * configSize);
676                                                 memcpy(&result[0], configsData, result.size());
677                                             });
678     _hidl_cb(retval, configCount, result);
679     return Void();
680 }
681 
getCurrentConfigForFeature(uint32_t featureId,uint32_t configSize,getCurrentConfigForFeature_cb _hidl_cb)682 Return<void> Effect::getCurrentConfigForFeature(uint32_t featureId, uint32_t configSize,
683                                                 getCurrentConfigForFeature_cb _hidl_cb) {
684     hidl_vec<uint8_t> result;
685     Result retval = getCurrentConfigImpl(featureId, configSize, [&](void* configData) {
686         result.resize(configSize);
687         memcpy(&result[0], configData, result.size());
688     });
689     _hidl_cb(retval, result);
690     return Void();
691 }
692 
setCurrentConfigForFeature(uint32_t featureId,const hidl_vec<uint8_t> & configData)693 Return<Result> Effect::setCurrentConfigForFeature(uint32_t featureId,
694                                                   const hidl_vec<uint8_t>& configData) {
695     uint32_t halCmd[alignedSizeIn<uint32_t>(sizeof(uint32_t) + configData.size())];
696     memset(halCmd, 0, sizeof(halCmd));
697     halCmd[0] = featureId;
698     memcpy(&halCmd[1], &configData[0], configData.size());
699     return sendCommandReturningStatus(EFFECT_CMD_SET_FEATURE_CONFIG, "SET_FEATURE_CONFIG",
700                                       sizeof(halCmd), halCmd);
701 }
702 
close()703 Return<Result> Effect::close() {
704     if (mStopProcessThread.load(std::memory_order_relaxed)) {  // only this thread modifies
705         return Result::INVALID_STATE;
706     }
707     mStopProcessThread.store(true, std::memory_order_release);
708     if (mEfGroup) {
709         mEfGroup->wake(static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_QUIT));
710     }
711 #if MAJOR_VERSION <= 5
712     return Result::OK;
713 #elif MAJOR_VERSION >= 6
714     // No need to join the processing thread, it is part of the API contract that the client
715     // must finish processing before closing the effect.
716     Result retval =
717             analyzeStatus("EffectRelease", "", sContextCallFunction, EffectRelease(mHandle));
718     EffectMap::getInstance().remove(mHandle);
719     return retval;
720 #endif
721 }
722 
debug(const hidl_handle & fd,const hidl_vec<hidl_string> &)723 Return<void> Effect::debug(const hidl_handle& fd, const hidl_vec<hidl_string>& /* options */) {
724     if (fd.getNativeHandle() != nullptr && fd->numFds == 1) {
725         uint32_t cmdData = fd->data[0];
726         (void)sendCommand(EFFECT_CMD_DUMP, "DUMP", sizeof(cmdData), &cmdData);
727     }
728     return Void();
729 }
730 
731 }  // namespace implementation
732 }  // namespace CPP_VERSION
733 }  // namespace effect
734 }  // namespace audio
735 }  // namespace hardware
736 }  // namespace android
737