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 <android/hidl/manager/1.0/IServiceManager.h>
21 #include <android-base/stringprintf.h>
22 #include <common/all-versions/VersionUtils.h>
23 #include <cutils/native_handle.h>
24 #include <cutils/properties.h>
25 #include <hwbinder/IPCThreadState.h>
26 #include <media/EffectsFactoryApi.h>
27 #include <mediautils/SchedulingPolicyService.h>
28 #include <mediautils/TimeCheck.h>
29 #include <system/audio_effects/effect_spatializer.h>
30 #include <utils/Log.h>
31
32 #include <util/EffectUtils.h>
33
34 #include "EffectBufferHalHidl.h"
35 #include "EffectHalHidl.h"
36
37 using ::android::hardware::audio::common::utils::EnumBitfield;
38 using ::android::hardware::audio::effect::CPP_VERSION::implementation::EffectUtils;
39 using ::android::hardware::hidl_vec;
40 using ::android::hardware::MQDescriptorSync;
41 using ::android::hardware::Return;
42
43 namespace android {
44 namespace effect {
45
46 using namespace ::android::hardware::audio::common::CPP_VERSION;
47 using namespace ::android::hardware::audio::effect::CPP_VERSION;
48
EffectHalHidl(const sp<IEffect> & effect,uint64_t effectId)49 EffectHalHidl::EffectHalHidl(const sp<IEffect>& effect, uint64_t effectId)
50 : EffectConversionHelperHidl("EffectHalHidl"),
51 mEffect(effect), mEffectId(effectId), mBuffersChanged(true), mEfGroup(nullptr) {
52 effect_descriptor_t halDescriptor{};
53 if (EffectHalHidl::getDescriptor(&halDescriptor) == NO_ERROR) {
54 mIsInput = (halDescriptor.flags & EFFECT_FLAG_TYPE_PRE_PROC) == EFFECT_FLAG_TYPE_PRE_PROC;
55 const bool isSpatializer =
56 memcmp(&halDescriptor.type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0;
57 if (isSpatializer) {
58 constexpr int32_t kRTPriorityMin = 1;
59 constexpr int32_t kRTPriorityMax = 3;
60 const int32_t priorityBoost = property_get_int32("audio.spatializer.priority", 1);
61 if (priorityBoost >= kRTPriorityMin && priorityBoost <= kRTPriorityMax) {
62 ALOGD("%s: audio.spatializer.priority %d on effect %lld",
63 __func__, priorityBoost, (long long)effectId);
64 mHalThreadPriority = priorityBoost;
65 }
66 }
67 }
68 }
69
~EffectHalHidl()70 EffectHalHidl::~EffectHalHidl() {
71 if (mEffect != 0) {
72 close();
73 mEffect.clear();
74 hardware::IPCThreadState::self()->flushCommands();
75 }
76 if (mEfGroup) {
77 EventFlag::deleteEventFlag(&mEfGroup);
78 }
79 }
80
setInBuffer(const sp<EffectBufferHalInterface> & buffer)81 status_t EffectHalHidl::setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
82 TIME_CHECK();
83
84 if (!mBuffersChanged) {
85 if (buffer.get() == nullptr || mInBuffer.get() == nullptr) {
86 mBuffersChanged = buffer.get() != mInBuffer.get();
87 } else {
88 mBuffersChanged = buffer->audioBuffer() != mInBuffer->audioBuffer();
89 }
90 }
91 mInBuffer = buffer;
92 return OK;
93 }
94
setOutBuffer(const sp<EffectBufferHalInterface> & buffer)95 status_t EffectHalHidl::setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
96 TIME_CHECK();
97
98 if (!mBuffersChanged) {
99 if (buffer.get() == nullptr || mOutBuffer.get() == nullptr) {
100 mBuffersChanged = buffer.get() != mOutBuffer.get();
101 } else {
102 mBuffersChanged = buffer->audioBuffer() != mOutBuffer->audioBuffer();
103 }
104 }
105 mOutBuffer = buffer;
106 return OK;
107 }
108
process()109 status_t EffectHalHidl::process() {
110 // TIME_CHECK(); // TODO(b/243839867) reenable only when optimized.
111
112 return processImpl(static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS));
113 }
114
processReverse()115 status_t EffectHalHidl::processReverse() {
116 // TIME_CHECK(); // TODO(b/243839867) reenable only when optimized.
117
118 return processImpl(static_cast<uint32_t>(MessageQueueFlagBits::REQUEST_PROCESS_REVERSE));
119 }
120
prepareForProcessing()121 status_t EffectHalHidl::prepareForProcessing() {
122 std::unique_ptr<StatusMQ> tempStatusMQ;
123 Result retval;
124 Return<void> ret = mEffect->prepareForProcessing(
125 [&](Result r, const MQDescriptorSync<Result>& statusMQ) {
126 retval = r;
127 if (retval == Result::OK) {
128 tempStatusMQ.reset(new StatusMQ(statusMQ));
129 if (tempStatusMQ->isValid() && tempStatusMQ->getEventFlagWord()) {
130 EventFlag::createEventFlag(tempStatusMQ->getEventFlagWord(), &mEfGroup);
131 }
132 }
133 });
134 if (!ret.isOk() || retval != Result::OK) {
135 return ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
136 }
137 if (!tempStatusMQ || !tempStatusMQ->isValid() || !mEfGroup) {
138 ALOGE_IF(!tempStatusMQ, "Failed to obtain status message queue for effects");
139 ALOGE_IF(tempStatusMQ && !tempStatusMQ->isValid(),
140 "Status message queue for effects is invalid");
141 ALOGE_IF(!mEfGroup, "Event flag creation for effects failed");
142 return NO_INIT;
143 }
144
145 (void)checkHalThreadPriority();
146 mStatusMQ = std::move(tempStatusMQ);
147 return OK;
148 }
149
needToResetBuffers()150 bool EffectHalHidl::needToResetBuffers() {
151 if (mBuffersChanged) return true;
152 bool inBufferFrameCountUpdated = mInBuffer->checkFrameCountChange();
153 bool outBufferFrameCountUpdated = mOutBuffer->checkFrameCountChange();
154 return inBufferFrameCountUpdated || outBufferFrameCountUpdated;
155 }
156
processImpl(uint32_t mqFlag)157 status_t EffectHalHidl::processImpl(uint32_t mqFlag) {
158 if (mEffect == 0 || mInBuffer == 0 || mOutBuffer == 0) return NO_INIT;
159 status_t status;
160 if (!mStatusMQ && (status = prepareForProcessing()) != OK) {
161 return status;
162 }
163 if (needToResetBuffers() && (status = setProcessBuffers()) != OK) {
164 return status;
165 }
166 // The data is already in the buffers, just need to flush it and wake up the server side.
167 std::atomic_thread_fence(std::memory_order_release);
168 mEfGroup->wake(mqFlag);
169 uint32_t efState = 0;
170 retry:
171 status_t ret = mEfGroup->wait(
172 static_cast<uint32_t>(MessageQueueFlagBits::DONE_PROCESSING), &efState);
173 if (efState & static_cast<uint32_t>(MessageQueueFlagBits::DONE_PROCESSING)) {
174 Result retval = Result::NOT_INITIALIZED;
175 mStatusMQ->read(&retval);
176 if (retval == Result::OK || retval == Result::INVALID_STATE) {
177 // Sync back the changed contents of the buffer.
178 std::atomic_thread_fence(std::memory_order_acquire);
179 }
180 return analyzeResult(retval);
181 }
182 if (ret == -EAGAIN || ret == -EINTR) {
183 // Spurious wakeup. This normally retries no more than once.
184 goto retry;
185 }
186 return ret;
187 }
188
setProcessBuffers()189 status_t EffectHalHidl::setProcessBuffers() {
190 Return<Result> ret = mEffect->setProcessBuffers(
191 static_cast<EffectBufferHalHidl*>(mInBuffer.get())->hidlBuffer(),
192 static_cast<EffectBufferHalHidl*>(mOutBuffer.get())->hidlBuffer());
193 if (ret.isOk() && ret == Result::OK) {
194 mBuffersChanged = false;
195 return OK;
196 }
197 return ret.isOk() ? analyzeResult(ret) : FAILED_TRANSACTION;
198 }
199
command(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)200 status_t EffectHalHidl::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData,
201 uint32_t *replySize, void *pReplyData) {
202 TIME_CHECK();
203
204 if (mEffect == 0) return NO_INIT;
205
206 // Special cases.
207 if (cmdCode == EFFECT_CMD_SET_CONFIG || cmdCode == EFFECT_CMD_SET_CONFIG_REVERSE) {
208 return setConfigImpl(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
209 } else if (cmdCode == EFFECT_CMD_GET_CONFIG || cmdCode == EFFECT_CMD_GET_CONFIG_REVERSE) {
210 return getConfigImpl(cmdCode, replySize, pReplyData);
211 }
212
213 // Common case.
214 hidl_vec<uint8_t> hidlData;
215 if (pCmdData != nullptr && cmdSize > 0) {
216 hidlData.setToExternal(reinterpret_cast<uint8_t*>(pCmdData), cmdSize);
217 }
218 status_t status;
219 uint32_t replySizeStub = 0;
220 if (replySize == nullptr || pReplyData == nullptr) replySize = &replySizeStub;
221 Return<void> ret = mEffect->command(cmdCode, hidlData, *replySize,
222 [&](int32_t s, const hidl_vec<uint8_t>& result) {
223 status = s;
224 if (status == 0) {
225 if (*replySize > result.size()) *replySize = result.size();
226 if (pReplyData != nullptr && *replySize > 0) {
227 memcpy(pReplyData, &result[0], *replySize);
228 }
229 }
230 });
231 return ret.isOk() ? status : FAILED_TRANSACTION;
232 }
233
getDescriptor(effect_descriptor_t * pDescriptor)234 status_t EffectHalHidl::getDescriptor(effect_descriptor_t *pDescriptor) {
235 TIME_CHECK();
236
237 if (mEffect == 0) return NO_INIT;
238 Result retval = Result::NOT_INITIALIZED;
239 Return<void> ret = mEffect->getDescriptor(
240 [&](Result r, const EffectDescriptor& result) {
241 retval = r;
242 if (retval == Result::OK) {
243 EffectUtils::effectDescriptorToHal(result, pDescriptor);
244 }
245 });
246 return ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
247 }
248
close()249 status_t EffectHalHidl::close() {
250 TIME_CHECK();
251
252 if (mEffect == 0) return NO_INIT;
253 Return<Result> ret = mEffect->close();
254 return ret.isOk() ? analyzeResult(ret) : FAILED_TRANSACTION;
255 }
256
dump(int fd)257 status_t EffectHalHidl::dump(int fd) {
258 TIME_CHECK();
259
260 if (mEffect == 0) return NO_INIT;
261 native_handle_t* hidlHandle = native_handle_create(1, 0);
262 hidlHandle->data[0] = fd;
263 Return<void> ret = mEffect->debug(hidlHandle, {} /* options */);
264 native_handle_delete(hidlHandle);
265
266 // TODO(b/111997867, b/177271958) Workaround - remove when fixed.
267 // A Binder transmitted fd may not close immediately due to a race condition b/111997867
268 // when the remote binder thread removes the last refcount to the fd blocks in the
269 // kernel for binder activity. We send a Binder ping() command to unblock the thread
270 // and complete the fd close / release.
271 //
272 // See DeviceHalHidl::dump(), EffectHalHidl::dump(), StreamHalHidl::dump(),
273 // EffectsFactoryHalHidl::dumpEffects().
274
275 (void)mEffect->ping(); // synchronous Binder call
276
277 return ret.isOk() ? OK : FAILED_TRANSACTION;
278 }
279
getConfigImpl(uint32_t cmdCode,uint32_t * replySize,void * pReplyData)280 status_t EffectHalHidl::getConfigImpl(
281 uint32_t cmdCode, uint32_t *replySize, void *pReplyData) {
282 if (replySize == NULL || *replySize != sizeof(effect_config_t) || pReplyData == NULL) {
283 return BAD_VALUE;
284 }
285 status_t result = FAILED_TRANSACTION;
286 Return<void> ret;
287 if (cmdCode == EFFECT_CMD_GET_CONFIG) {
288 ret = mEffect->getConfig([&] (Result r, const EffectConfig &hidlConfig) {
289 result = analyzeResult(r);
290 if (r == Result::OK) {
291 EffectUtils::effectConfigToHal(
292 hidlConfig, static_cast<effect_config_t*>(pReplyData));
293 }
294 });
295 } else {
296 ret = mEffect->getConfigReverse([&] (Result r, const EffectConfig &hidlConfig) {
297 result = analyzeResult(r);
298 if (r == Result::OK) {
299 EffectUtils::effectConfigToHal(
300 hidlConfig, static_cast<effect_config_t*>(pReplyData));
301 }
302 });
303 }
304 if (!ret.isOk()) {
305 result = FAILED_TRANSACTION;
306 }
307 return result;
308 }
309
setConfigImpl(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)310 status_t EffectHalHidl::setConfigImpl(
311 uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) {
312 if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
313 replySize == NULL || *replySize != sizeof(int32_t) || pReplyData == NULL) {
314 return BAD_VALUE;
315 }
316 const effect_config_t *halConfig = static_cast<effect_config_t*>(pCmdData);
317 if (halConfig->inputCfg.bufferProvider.getBuffer != NULL ||
318 halConfig->inputCfg.bufferProvider.releaseBuffer != NULL ||
319 halConfig->outputCfg.bufferProvider.getBuffer != NULL ||
320 halConfig->outputCfg.bufferProvider.releaseBuffer != NULL) {
321 ALOGE("Buffer provider callbacks are not supported");
322 }
323 EffectConfig hidlConfig;
324 EffectUtils::effectConfigFromHal(*halConfig, mIsInput, &hidlConfig);
325 Return<Result> ret = cmdCode == EFFECT_CMD_SET_CONFIG ?
326 mEffect->setConfig(hidlConfig, nullptr, nullptr) :
327 mEffect->setConfigReverse(hidlConfig, nullptr, nullptr);
328 status_t result = FAILED_TRANSACTION;
329 if (ret.isOk()) {
330 result = analyzeResult(ret);
331 *static_cast<int32_t*>(pReplyData) = result;
332 }
333 return result;
334 }
335
getHalPid(pid_t * pid) const336 status_t EffectHalHidl::getHalPid(pid_t *pid) const {
337 using ::android::hidl::base::V1_0::DebugInfo;
338 using ::android::hidl::manager::V1_0::IServiceManager;
339 DebugInfo debugInfo;
340 const auto ret = mEffect->getDebugInfo([&] (const auto &info) {
341 debugInfo = info;
342 });
343 if (!ret.isOk()) {
344 ALOGW("%s: cannot get effect debug info", __func__);
345 return INVALID_OPERATION;
346 }
347 if (debugInfo.pid != (int)IServiceManager::PidConstant::NO_PID) {
348 *pid = debugInfo.pid;
349 return NO_ERROR;
350 }
351 ALOGW("%s: effect debug info does not contain pid", __func__);
352 return NAME_NOT_FOUND;
353 }
354
getHalWorkerTid(pid_t * tid)355 status_t EffectHalHidl::getHalWorkerTid(pid_t *tid) {
356 int32_t reply = -1;
357 uint32_t replySize = sizeof(reply);
358 const status_t status =
359 command('gtid', 0 /* cmdSize */, nullptr /* pCmdData */, &replySize, &reply);
360 if (status == OK) {
361 *tid = (pid_t)reply;
362 } else {
363 ALOGW("%s: failed with status:%d", __func__, status);
364 }
365 return status;
366 }
367
requestHalThreadPriority(pid_t threadPid,pid_t threadId)368 bool EffectHalHidl::requestHalThreadPriority(pid_t threadPid, pid_t threadId) {
369 if (mHalThreadPriority == kRTPriorityDisabled) {
370 return true;
371 }
372 const int err = requestPriority(
373 threadPid, threadId,
374 mHalThreadPriority, false /*isForApp*/, true /*asynchronous*/);
375 ALOGW_IF(err, "%s: failed to set RT priority %d for pid %d tid %d; error %d",
376 __func__, mHalThreadPriority, threadPid, threadId, err);
377 // Audio will still work, but may be more susceptible to glitches.
378 return err == 0;
379 }
380
checkHalThreadPriority()381 status_t EffectHalHidl::checkHalThreadPriority() {
382 if (mHalThreadPriority == kRTPriorityDisabled) return OK;
383 if (mHalThreadPriority < kRTPriorityMin
384 || mHalThreadPriority > kRTPriorityMax) return BAD_VALUE;
385
386 pid_t halPid, halWorkerTid;
387 const status_t status = getHalPid(&halPid) ?: getHalWorkerTid(&halWorkerTid);
388 const bool success = status == OK && requestHalThreadPriority(halPid, halWorkerTid);
389 ALOGD("%s: effectId %lld RT priority(%d) request %s%s",
390 __func__, (long long)mEffectId, mHalThreadPriority,
391 success ? "succeeded" : "failed",
392 status == OK
393 ? base::StringPrintf(" for pid:%d tid:%d", halPid, halWorkerTid).c_str()
394 : " (pid / tid cannot be read)");
395 return success ? OK : status != OK ? status : INVALID_OPERATION /* request failed */;
396 }
397
398 } // namespace effect
399 } // namespace android
400