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