Effects.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723
  1. /*
  2. **
  3. ** Copyright 2012, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #define LOG_TAG "AudioFlinger"
  18. //#define LOG_NDEBUG 0
  19. #include <algorithm>
  20. #include "Configuration.h"
  21. #include <utils/Log.h>
  22. #include <system/audio_effects/effect_aec.h>
  23. #include <system/audio_effects/effect_dynamicsprocessing.h>
  24. #include <system/audio_effects/effect_ns.h>
  25. #include <system/audio_effects/effect_visualizer.h>
  26. #include <audio_utils/channels.h>
  27. #include <audio_utils/primitives.h>
  28. #include <media/AudioEffect.h>
  29. #include <media/audiohal/EffectHalInterface.h>
  30. #include <media/audiohal/EffectsFactoryHalInterface.h>
  31. #include <mediautils/ServiceUtilities.h>
  32. #include "AudioFlinger.h"
  33. // ----------------------------------------------------------------------------
  34. // Note: the following macro is used for extremely verbose logging message. In
  35. // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
  36. // 0; but one side effect of this is to turn all LOGV's as well. Some messages
  37. // are so verbose that we want to suppress them even when we have ALOG_ASSERT
  38. // turned on. Do not uncomment the #def below unless you really know what you
  39. // are doing and want to see all of the extremely verbose messages.
  40. //#define VERY_VERY_VERBOSE_LOGGING
  41. #ifdef VERY_VERY_VERBOSE_LOGGING
  42. #define ALOGVV ALOGV
  43. #else
  44. #define ALOGVV(a...) do { } while(0)
  45. #endif
  46. #define DEFAULT_OUTPUT_SAMPLE_RATE 48000
  47. namespace android {
  48. // ----------------------------------------------------------------------------
  49. // EffectModule implementation
  50. // ----------------------------------------------------------------------------
  51. #undef LOG_TAG
  52. #define LOG_TAG "AudioFlinger::EffectModule"
  53. AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
  54. const wp<AudioFlinger::EffectChain>& chain,
  55. effect_descriptor_t *desc,
  56. int id,
  57. audio_session_t sessionId,
  58. bool pinned)
  59. : mPinned(pinned),
  60. mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
  61. mDescriptor(*desc),
  62. // clear mConfig to ensure consistent initial value of buffer framecount
  63. // in case buffers are associated by setInBuffer() or setOutBuffer()
  64. // prior to configure().
  65. mConfig{{}, {}},
  66. mStatus(NO_INIT), mState(IDLE),
  67. mMaxDisableWaitCnt(1), // set by configure(), should be >= 1
  68. mDisableWaitCnt(0), // set by process() and updateState()
  69. mSuspended(false),
  70. mOffloaded(false),
  71. mAudioFlinger(thread->mAudioFlinger)
  72. #ifdef FLOAT_EFFECT_CHAIN
  73. , mSupportsFloat(false)
  74. #endif
  75. {
  76. ALOGV("Constructor %p pinned %d", this, pinned);
  77. int lStatus;
  78. // create effect engine from effect factory
  79. mStatus = -ENODEV;
  80. sp<AudioFlinger> audioFlinger = mAudioFlinger.promote();
  81. if (audioFlinger != 0) {
  82. sp<EffectsFactoryHalInterface> effectsFactory = audioFlinger->getEffectsFactory();
  83. if (effectsFactory != 0) {
  84. mStatus = effectsFactory->createEffect(
  85. &desc->uuid, sessionId, thread->id(), &mEffectInterface);
  86. }
  87. }
  88. if (mStatus != NO_ERROR) {
  89. return;
  90. }
  91. lStatus = init();
  92. if (lStatus < 0) {
  93. mStatus = lStatus;
  94. goto Error;
  95. }
  96. setOffloaded(thread->type() == ThreadBase::OFFLOAD, thread->id());
  97. ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface.get());
  98. return;
  99. Error:
  100. mEffectInterface.clear();
  101. ALOGV("Constructor Error %d", mStatus);
  102. }
  103. AudioFlinger::EffectModule::~EffectModule()
  104. {
  105. ALOGV("Destructor %p", this);
  106. if (mEffectInterface != 0) {
  107. char uuidStr[64];
  108. AudioEffect::guidToString(&mDescriptor.uuid, uuidStr, sizeof(uuidStr));
  109. ALOGW("EffectModule %p destructor called with unreleased interface, effect %s",
  110. this, uuidStr);
  111. release_l();
  112. }
  113. }
  114. status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
  115. {
  116. status_t status;
  117. Mutex::Autolock _l(mLock);
  118. int priority = handle->priority();
  119. size_t size = mHandles.size();
  120. EffectHandle *controlHandle = NULL;
  121. size_t i;
  122. for (i = 0; i < size; i++) {
  123. EffectHandle *h = mHandles[i];
  124. if (h == NULL || h->disconnected()) {
  125. continue;
  126. }
  127. // first non destroyed handle is considered in control
  128. if (controlHandle == NULL) {
  129. controlHandle = h;
  130. }
  131. if (h->priority() <= priority) {
  132. break;
  133. }
  134. }
  135. // if inserted in first place, move effect control from previous owner to this handle
  136. if (i == 0) {
  137. bool enabled = false;
  138. if (controlHandle != NULL) {
  139. enabled = controlHandle->enabled();
  140. controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
  141. }
  142. handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
  143. status = NO_ERROR;
  144. } else {
  145. status = ALREADY_EXISTS;
  146. }
  147. ALOGV("addHandle() %p added handle %p in position %zu", this, handle, i);
  148. mHandles.insertAt(handle, i);
  149. return status;
  150. }
  151. status_t AudioFlinger::EffectModule::updatePolicyState()
  152. {
  153. status_t status = NO_ERROR;
  154. bool doRegister = false;
  155. bool registered = false;
  156. bool doEnable = false;
  157. bool enabled = false;
  158. audio_io_handle_t io;
  159. uint32_t strategy;
  160. {
  161. Mutex::Autolock _l(mLock);
  162. // register effect when first handle is attached and unregister when last handle is removed
  163. if (mPolicyRegistered != mHandles.size() > 0) {
  164. doRegister = true;
  165. mPolicyRegistered = mHandles.size() > 0;
  166. if (mPolicyRegistered) {
  167. sp <EffectChain> chain = mChain.promote();
  168. sp <ThreadBase> thread = mThread.promote();
  169. if (thread == nullptr || chain == nullptr) {
  170. return INVALID_OPERATION;
  171. }
  172. io = thread->id();
  173. strategy = chain->strategy();
  174. }
  175. }
  176. // enable effect when registered according to enable state requested by controlling handle
  177. if (mHandles.size() > 0) {
  178. EffectHandle *handle = controlHandle_l();
  179. if (handle != nullptr && mPolicyEnabled != handle->enabled()) {
  180. doEnable = true;
  181. mPolicyEnabled = handle->enabled();
  182. }
  183. }
  184. registered = mPolicyRegistered;
  185. enabled = mPolicyEnabled;
  186. mPolicyLock.lock();
  187. }
  188. ALOGV("%s name %s id %d session %d doRegister %d registered %d doEnable %d enabled %d",
  189. __func__, mDescriptor.name, mId, mSessionId, doRegister, registered, doEnable, enabled);
  190. if (doRegister) {
  191. if (registered) {
  192. status = AudioSystem::registerEffect(
  193. &mDescriptor,
  194. io,
  195. strategy,
  196. mSessionId,
  197. mId);
  198. } else {
  199. status = AudioSystem::unregisterEffect(mId);
  200. }
  201. }
  202. if (registered && doEnable) {
  203. status = AudioSystem::setEffectEnabled(mId, enabled);
  204. }
  205. mPolicyLock.unlock();
  206. return status;
  207. }
  208. ssize_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
  209. {
  210. Mutex::Autolock _l(mLock);
  211. return removeHandle_l(handle);
  212. }
  213. ssize_t AudioFlinger::EffectModule::removeHandle_l(EffectHandle *handle)
  214. {
  215. size_t size = mHandles.size();
  216. size_t i;
  217. for (i = 0; i < size; i++) {
  218. if (mHandles[i] == handle) {
  219. break;
  220. }
  221. }
  222. if (i == size) {
  223. ALOGW("%s %p handle not found %p", __FUNCTION__, this, handle);
  224. return BAD_VALUE;
  225. }
  226. ALOGV("removeHandle_l() %p removed handle %p in position %zu", this, handle, i);
  227. mHandles.removeAt(i);
  228. // if removed from first place, move effect control from this handle to next in line
  229. if (i == 0) {
  230. EffectHandle *h = controlHandle_l();
  231. if (h != NULL) {
  232. h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
  233. }
  234. }
  235. // Prevent calls to process() and other functions on effect interface from now on.
  236. // The effect engine will be released by the destructor when the last strong reference on
  237. // this object is released which can happen after next process is called.
  238. if (mHandles.size() == 0 && !mPinned) {
  239. mState = DESTROYED;
  240. mEffectInterface->close();
  241. }
  242. return mHandles.size();
  243. }
  244. // must be called with EffectModule::mLock held
  245. AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
  246. {
  247. // the first valid handle in the list has control over the module
  248. for (size_t i = 0; i < mHandles.size(); i++) {
  249. EffectHandle *h = mHandles[i];
  250. if (h != NULL && !h->disconnected()) {
  251. return h;
  252. }
  253. }
  254. return NULL;
  255. }
  256. // unsafe method called when the effect parent thread has been destroyed
  257. ssize_t AudioFlinger::EffectModule::disconnectHandle(EffectHandle *handle, bool unpinIfLast)
  258. {
  259. ALOGV("disconnect() %p handle %p", this, handle);
  260. Mutex::Autolock _l(mLock);
  261. ssize_t numHandles = removeHandle_l(handle);
  262. if ((numHandles == 0) && (!mPinned || unpinIfLast)) {
  263. sp<AudioFlinger> af = mAudioFlinger.promote();
  264. if (af != 0) {
  265. mLock.unlock();
  266. af->updateOrphanEffectChains(this);
  267. mLock.lock();
  268. }
  269. }
  270. return numHandles;
  271. }
  272. bool AudioFlinger::EffectModule::updateState() {
  273. Mutex::Autolock _l(mLock);
  274. bool started = false;
  275. switch (mState) {
  276. case RESTART:
  277. reset_l();
  278. FALLTHROUGH_INTENDED;
  279. case STARTING:
  280. // clear auxiliary effect input buffer for next accumulation
  281. if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
  282. memset(mConfig.inputCfg.buffer.raw,
  283. 0,
  284. mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
  285. }
  286. if (start_l() == NO_ERROR) {
  287. mState = ACTIVE;
  288. started = true;
  289. } else {
  290. mState = IDLE;
  291. }
  292. break;
  293. case STOPPING:
  294. // volume control for offload and direct threads must take effect immediately.
  295. if (stop_l() == NO_ERROR
  296. && !(isVolumeControl() && isOffloadedOrDirect())) {
  297. mDisableWaitCnt = mMaxDisableWaitCnt;
  298. } else {
  299. mDisableWaitCnt = 1; // will cause immediate transition to IDLE
  300. }
  301. mState = STOPPED;
  302. break;
  303. case STOPPED:
  304. // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
  305. // turn off sequence.
  306. if (--mDisableWaitCnt == 0) {
  307. reset_l();
  308. mState = IDLE;
  309. }
  310. break;
  311. default: //IDLE , ACTIVE, DESTROYED
  312. break;
  313. }
  314. return started;
  315. }
  316. void AudioFlinger::EffectModule::process()
  317. {
  318. Mutex::Autolock _l(mLock);
  319. if (mState == DESTROYED || mEffectInterface == 0 || mInBuffer == 0 || mOutBuffer == 0) {
  320. return;
  321. }
  322. const uint32_t inChannelCount =
  323. audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
  324. const uint32_t outChannelCount =
  325. audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
  326. const bool auxType =
  327. (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
  328. // safeInputOutputSampleCount is 0 if the channel count between input and output
  329. // buffers do not match. This prevents automatic accumulation or copying between the
  330. // input and output effect buffers without an intermediary effect process.
  331. // TODO: consider implementing channel conversion.
  332. const size_t safeInputOutputSampleCount =
  333. mInChannelCountRequested != mOutChannelCountRequested ? 0
  334. : mOutChannelCountRequested * std::min(
  335. mConfig.inputCfg.buffer.frameCount,
  336. mConfig.outputCfg.buffer.frameCount);
  337. const auto accumulateInputToOutput = [this, safeInputOutputSampleCount]() {
  338. #ifdef FLOAT_EFFECT_CHAIN
  339. accumulate_float(
  340. mConfig.outputCfg.buffer.f32,
  341. mConfig.inputCfg.buffer.f32,
  342. safeInputOutputSampleCount);
  343. #else
  344. accumulate_i16(
  345. mConfig.outputCfg.buffer.s16,
  346. mConfig.inputCfg.buffer.s16,
  347. safeInputOutputSampleCount);
  348. #endif
  349. };
  350. const auto copyInputToOutput = [this, safeInputOutputSampleCount]() {
  351. #ifdef FLOAT_EFFECT_CHAIN
  352. memcpy(
  353. mConfig.outputCfg.buffer.f32,
  354. mConfig.inputCfg.buffer.f32,
  355. safeInputOutputSampleCount * sizeof(*mConfig.outputCfg.buffer.f32));
  356. #else
  357. memcpy(
  358. mConfig.outputCfg.buffer.s16,
  359. mConfig.inputCfg.buffer.s16,
  360. safeInputOutputSampleCount * sizeof(*mConfig.outputCfg.buffer.s16));
  361. #endif
  362. };
  363. if (isProcessEnabled()) {
  364. int ret;
  365. if (isProcessImplemented()) {
  366. if (auxType) {
  367. // We overwrite the aux input buffer here and clear after processing.
  368. // aux input is always mono.
  369. #ifdef FLOAT_EFFECT_CHAIN
  370. if (mSupportsFloat) {
  371. #ifndef FLOAT_AUX
  372. // Do in-place float conversion for auxiliary effect input buffer.
  373. static_assert(sizeof(float) <= sizeof(int32_t),
  374. "in-place conversion requires sizeof(float) <= sizeof(int32_t)");
  375. memcpy_to_float_from_q4_27(
  376. mConfig.inputCfg.buffer.f32,
  377. mConfig.inputCfg.buffer.s32,
  378. mConfig.inputCfg.buffer.frameCount);
  379. #endif // !FLOAT_AUX
  380. } else
  381. #endif // FLOAT_EFFECT_CHAIN
  382. {
  383. #ifdef FLOAT_AUX
  384. memcpy_to_i16_from_float(
  385. mConfig.inputCfg.buffer.s16,
  386. mConfig.inputCfg.buffer.f32,
  387. mConfig.inputCfg.buffer.frameCount);
  388. #else
  389. memcpy_to_i16_from_q4_27(
  390. mConfig.inputCfg.buffer.s16,
  391. mConfig.inputCfg.buffer.s32,
  392. mConfig.inputCfg.buffer.frameCount);
  393. #endif
  394. }
  395. }
  396. #ifdef FLOAT_EFFECT_CHAIN
  397. sp<EffectBufferHalInterface> inBuffer = mInBuffer;
  398. sp<EffectBufferHalInterface> outBuffer = mOutBuffer;
  399. if (!auxType && mInChannelCountRequested != inChannelCount) {
  400. adjust_channels(
  401. inBuffer->audioBuffer()->f32, mInChannelCountRequested,
  402. mInConversionBuffer->audioBuffer()->f32, inChannelCount,
  403. sizeof(float),
  404. sizeof(float)
  405. * mInChannelCountRequested * mConfig.inputCfg.buffer.frameCount);
  406. inBuffer = mInConversionBuffer;
  407. }
  408. if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE
  409. && mOutChannelCountRequested != outChannelCount) {
  410. adjust_selected_channels(
  411. outBuffer->audioBuffer()->f32, mOutChannelCountRequested,
  412. mOutConversionBuffer->audioBuffer()->f32, outChannelCount,
  413. sizeof(float),
  414. sizeof(float)
  415. * mOutChannelCountRequested * mConfig.outputCfg.buffer.frameCount);
  416. outBuffer = mOutConversionBuffer;
  417. }
  418. if (!mSupportsFloat) { // convert input to int16_t as effect doesn't support float.
  419. if (!auxType) {
  420. if (mInConversionBuffer.get() == nullptr) {
  421. ALOGW("%s: mInConversionBuffer is null, bypassing", __func__);
  422. goto data_bypass;
  423. }
  424. memcpy_to_i16_from_float(
  425. mInConversionBuffer->audioBuffer()->s16,
  426. inBuffer->audioBuffer()->f32,
  427. inChannelCount * mConfig.inputCfg.buffer.frameCount);
  428. inBuffer = mInConversionBuffer;
  429. }
  430. if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
  431. if (mOutConversionBuffer.get() == nullptr) {
  432. ALOGW("%s: mOutConversionBuffer is null, bypassing", __func__);
  433. goto data_bypass;
  434. }
  435. memcpy_to_i16_from_float(
  436. mOutConversionBuffer->audioBuffer()->s16,
  437. outBuffer->audioBuffer()->f32,
  438. outChannelCount * mConfig.outputCfg.buffer.frameCount);
  439. outBuffer = mOutConversionBuffer;
  440. }
  441. }
  442. #endif
  443. ret = mEffectInterface->process();
  444. #ifdef FLOAT_EFFECT_CHAIN
  445. if (!mSupportsFloat) { // convert output int16_t back to float.
  446. sp<EffectBufferHalInterface> target =
  447. mOutChannelCountRequested != outChannelCount
  448. ? mOutConversionBuffer : mOutBuffer;
  449. memcpy_to_float_from_i16(
  450. target->audioBuffer()->f32,
  451. mOutConversionBuffer->audioBuffer()->s16,
  452. outChannelCount * mConfig.outputCfg.buffer.frameCount);
  453. }
  454. if (mOutChannelCountRequested != outChannelCount) {
  455. adjust_selected_channels(mOutConversionBuffer->audioBuffer()->f32, outChannelCount,
  456. mOutBuffer->audioBuffer()->f32, mOutChannelCountRequested,
  457. sizeof(float),
  458. sizeof(float) * outChannelCount * mConfig.outputCfg.buffer.frameCount);
  459. }
  460. #endif
  461. } else {
  462. #ifdef FLOAT_EFFECT_CHAIN
  463. data_bypass:
  464. #endif
  465. if (!auxType /* aux effects do not require data bypass */
  466. && mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
  467. if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
  468. accumulateInputToOutput();
  469. } else {
  470. copyInputToOutput();
  471. }
  472. }
  473. ret = -ENODATA;
  474. }
  475. // force transition to IDLE state when engine is ready
  476. if (mState == STOPPED && ret == -ENODATA) {
  477. mDisableWaitCnt = 1;
  478. }
  479. // clear auxiliary effect input buffer for next accumulation
  480. if (auxType) {
  481. #ifdef FLOAT_AUX
  482. const size_t size =
  483. mConfig.inputCfg.buffer.frameCount * inChannelCount * sizeof(float);
  484. #else
  485. const size_t size =
  486. mConfig.inputCfg.buffer.frameCount * inChannelCount * sizeof(int32_t);
  487. #endif
  488. memset(mConfig.inputCfg.buffer.raw, 0, size);
  489. }
  490. } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
  491. // mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw
  492. mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
  493. // If an insert effect is idle and input buffer is different from output buffer,
  494. // accumulate input onto output
  495. sp<EffectChain> chain = mChain.promote();
  496. if (chain.get() != nullptr && chain->activeTrackCnt() != 0) {
  497. // similar handling with data_bypass above.
  498. if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
  499. accumulateInputToOutput();
  500. } else { // EFFECT_BUFFER_ACCESS_WRITE
  501. copyInputToOutput();
  502. }
  503. }
  504. }
  505. }
  506. void AudioFlinger::EffectModule::reset_l()
  507. {
  508. if (mStatus != NO_ERROR || mEffectInterface == 0) {
  509. return;
  510. }
  511. mEffectInterface->command(EFFECT_CMD_RESET, 0, NULL, 0, NULL);
  512. }
  513. status_t AudioFlinger::EffectModule::configure()
  514. {
  515. ALOGVV("configure() started");
  516. status_t status;
  517. sp<ThreadBase> thread;
  518. uint32_t size;
  519. audio_channel_mask_t channelMask;
  520. if (mEffectInterface == 0) {
  521. status = NO_INIT;
  522. goto exit;
  523. }
  524. thread = mThread.promote();
  525. if (thread == 0) {
  526. status = DEAD_OBJECT;
  527. goto exit;
  528. }
  529. // TODO: handle configuration of effects replacing track process
  530. // TODO: handle configuration of input (record) SW effects above the HAL,
  531. // similar to output EFFECT_FLAG_TYPE_INSERT/REPLACE,
  532. // in which case input channel masks should be used here.
  533. channelMask = thread->channelMask();
  534. mConfig.inputCfg.channels = channelMask;
  535. mConfig.outputCfg.channels = channelMask;
  536. if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
  537. if (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_MONO) {
  538. mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
  539. ALOGV("Overriding auxiliary effect input channels %#x as MONO",
  540. mConfig.inputCfg.channels);
  541. }
  542. #ifndef MULTICHANNEL_EFFECT_CHAIN
  543. if (mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO) {
  544. mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
  545. ALOGV("Overriding auxiliary effect output channels %#x as STEREO",
  546. mConfig.outputCfg.channels);
  547. }
  548. #endif
  549. } else {
  550. #ifndef MULTICHANNEL_EFFECT_CHAIN
  551. // TODO: Update this logic when multichannel effects are implemented.
  552. // For offloaded tracks consider mono output as stereo for proper effect initialization
  553. if (channelMask == AUDIO_CHANNEL_OUT_MONO) {
  554. mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
  555. mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
  556. ALOGV("Overriding effect input and output as STEREO");
  557. }
  558. #endif
  559. }
  560. mInChannelCountRequested =
  561. audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
  562. mOutChannelCountRequested =
  563. audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
  564. mConfig.inputCfg.format = EFFECT_BUFFER_FORMAT;
  565. mConfig.outputCfg.format = EFFECT_BUFFER_FORMAT;
  566. // Don't use sample rate for thread if effect isn't offloadable.
  567. if ((thread->type() == ThreadBase::OFFLOAD) && !isOffloaded()) {
  568. mConfig.inputCfg.samplingRate = DEFAULT_OUTPUT_SAMPLE_RATE;
  569. ALOGV("Overriding effect input as 48kHz");
  570. } else {
  571. mConfig.inputCfg.samplingRate = thread->sampleRate();
  572. }
  573. mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
  574. mConfig.inputCfg.bufferProvider.cookie = NULL;
  575. mConfig.inputCfg.bufferProvider.getBuffer = NULL;
  576. mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
  577. mConfig.outputCfg.bufferProvider.cookie = NULL;
  578. mConfig.outputCfg.bufferProvider.getBuffer = NULL;
  579. mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
  580. mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
  581. // Insert effect:
  582. // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
  583. // always overwrites output buffer: input buffer == output buffer
  584. // - in other sessions:
  585. // last effect in the chain accumulates in output buffer: input buffer != output buffer
  586. // other effect: overwrites output buffer: input buffer == output buffer
  587. // Auxiliary effect:
  588. // accumulates in output buffer: input buffer != output buffer
  589. // Therefore: accumulate <=> input buffer != output buffer
  590. if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
  591. mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
  592. } else {
  593. mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
  594. }
  595. mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
  596. mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
  597. mConfig.inputCfg.buffer.frameCount = thread->frameCount();
  598. mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
  599. ALOGV("configure() %p thread %p buffer %p framecount %zu",
  600. this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
  601. status_t cmdStatus;
  602. size = sizeof(int);
  603. status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
  604. sizeof(mConfig),
  605. &mConfig,
  606. &size,
  607. &cmdStatus);
  608. if (status == NO_ERROR) {
  609. status = cmdStatus;
  610. }
  611. #ifdef MULTICHANNEL_EFFECT_CHAIN
  612. if (status != NO_ERROR &&
  613. thread->isOutput() &&
  614. (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO
  615. || mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO)) {
  616. // Older effects may require exact STEREO position mask.
  617. if (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO
  618. && (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
  619. ALOGV("Overriding effect input channels %#x as STEREO", mConfig.inputCfg.channels);
  620. mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
  621. }
  622. if (mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO) {
  623. ALOGV("Overriding effect output channels %#x as STEREO", mConfig.outputCfg.channels);
  624. mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
  625. }
  626. size = sizeof(int);
  627. status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
  628. sizeof(mConfig),
  629. &mConfig,
  630. &size,
  631. &cmdStatus);
  632. if (status == NO_ERROR) {
  633. status = cmdStatus;
  634. }
  635. }
  636. #endif
  637. #ifdef FLOAT_EFFECT_CHAIN
  638. if (status == NO_ERROR) {
  639. mSupportsFloat = true;
  640. }
  641. if (status != NO_ERROR) {
  642. ALOGV("EFFECT_CMD_SET_CONFIG failed with float format, retry with int16_t.");
  643. mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
  644. mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
  645. size = sizeof(int);
  646. status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
  647. sizeof(mConfig),
  648. &mConfig,
  649. &size,
  650. &cmdStatus);
  651. if (status == NO_ERROR) {
  652. status = cmdStatus;
  653. }
  654. if (status == NO_ERROR) {
  655. mSupportsFloat = false;
  656. ALOGVV("config worked with 16 bit");
  657. } else {
  658. ALOGE("%s failed %d with int16_t (as well as float)", __func__, status);
  659. }
  660. }
  661. #endif
  662. if (status == NO_ERROR) {
  663. // Establish Buffer strategy
  664. setInBuffer(mInBuffer);
  665. setOutBuffer(mOutBuffer);
  666. // Update visualizer latency
  667. if (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) {
  668. uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
  669. effect_param_t *p = (effect_param_t *)buf32;
  670. p->psize = sizeof(uint32_t);
  671. p->vsize = sizeof(uint32_t);
  672. size = sizeof(int);
  673. *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
  674. uint32_t latency = 0;
  675. PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
  676. if (pbt != NULL) {
  677. latency = pbt->latency_l();
  678. }
  679. *((int32_t *)p->data + 1)= latency;
  680. mEffectInterface->command(EFFECT_CMD_SET_PARAM,
  681. sizeof(effect_param_t) + 8,
  682. &buf32,
  683. &size,
  684. &cmdStatus);
  685. }
  686. }
  687. // mConfig.outputCfg.buffer.frameCount cannot be zero.
  688. mMaxDisableWaitCnt = (uint32_t)std::max(
  689. (uint64_t)1, // mMaxDisableWaitCnt must be greater than zero.
  690. (uint64_t)MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate
  691. / ((uint64_t)1000 * mConfig.outputCfg.buffer.frameCount));
  692. exit:
  693. // TODO: consider clearing mConfig on error.
  694. mStatus = status;
  695. ALOGVV("configure ended");
  696. return status;
  697. }
  698. status_t AudioFlinger::EffectModule::init()
  699. {
  700. Mutex::Autolock _l(mLock);
  701. if (mEffectInterface == 0) {
  702. return NO_INIT;
  703. }
  704. status_t cmdStatus;
  705. uint32_t size = sizeof(status_t);
  706. status_t status = mEffectInterface->command(EFFECT_CMD_INIT,
  707. 0,
  708. NULL,
  709. &size,
  710. &cmdStatus);
  711. if (status == 0) {
  712. status = cmdStatus;
  713. }
  714. return status;
  715. }
  716. void AudioFlinger::EffectModule::addEffectToHal_l()
  717. {
  718. if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
  719. (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
  720. sp<ThreadBase> thread = mThread.promote();
  721. if (thread != 0) {
  722. sp<StreamHalInterface> stream = thread->stream();
  723. if (stream != 0) {
  724. status_t result = stream->addEffect(mEffectInterface);
  725. ALOGE_IF(result != OK, "Error when adding effect: %d", result);
  726. }
  727. }
  728. }
  729. }
  730. // start() must be called with PlaybackThread::mLock or EffectChain::mLock held
  731. status_t AudioFlinger::EffectModule::start()
  732. {
  733. sp<EffectChain> chain;
  734. status_t status;
  735. {
  736. Mutex::Autolock _l(mLock);
  737. status = start_l();
  738. if (status == NO_ERROR) {
  739. chain = mChain.promote();
  740. }
  741. }
  742. if (chain != 0) {
  743. chain->resetVolume_l();
  744. }
  745. return status;
  746. }
  747. status_t AudioFlinger::EffectModule::start_l()
  748. {
  749. if (mEffectInterface == 0) {
  750. return NO_INIT;
  751. }
  752. if (mStatus != NO_ERROR) {
  753. return mStatus;
  754. }
  755. status_t cmdStatus;
  756. uint32_t size = sizeof(status_t);
  757. status_t status = mEffectInterface->command(EFFECT_CMD_ENABLE,
  758. 0,
  759. NULL,
  760. &size,
  761. &cmdStatus);
  762. if (status == 0) {
  763. status = cmdStatus;
  764. }
  765. if (status == 0) {
  766. addEffectToHal_l();
  767. }
  768. return status;
  769. }
  770. status_t AudioFlinger::EffectModule::stop()
  771. {
  772. Mutex::Autolock _l(mLock);
  773. return stop_l();
  774. }
  775. status_t AudioFlinger::EffectModule::stop_l()
  776. {
  777. if (mEffectInterface == 0) {
  778. return NO_INIT;
  779. }
  780. if (mStatus != NO_ERROR) {
  781. return mStatus;
  782. }
  783. status_t cmdStatus = NO_ERROR;
  784. uint32_t size = sizeof(status_t);
  785. if (isVolumeControl() && isOffloadedOrDirect()) {
  786. sp<EffectChain>chain = mChain.promote();
  787. // We have the EffectChain and EffectModule lock, permit a reentrant call to setVolume:
  788. // resetVolume_l --> setVolume_l --> EffectModule::setVolume
  789. mSetVolumeReentrantTid = gettid();
  790. chain->resetVolume_l();
  791. mSetVolumeReentrantTid = INVALID_PID;
  792. }
  793. status_t status = mEffectInterface->command(EFFECT_CMD_DISABLE,
  794. 0,
  795. NULL,
  796. &size,
  797. &cmdStatus);
  798. if (status == NO_ERROR) {
  799. status = cmdStatus;
  800. }
  801. if (status == NO_ERROR) {
  802. status = remove_effect_from_hal_l();
  803. }
  804. return status;
  805. }
  806. // must be called with EffectChain::mLock held
  807. void AudioFlinger::EffectModule::release_l()
  808. {
  809. if (mEffectInterface != 0) {
  810. remove_effect_from_hal_l();
  811. // release effect engine
  812. mEffectInterface->close();
  813. mEffectInterface.clear();
  814. }
  815. }
  816. status_t AudioFlinger::EffectModule::remove_effect_from_hal_l()
  817. {
  818. if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
  819. (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
  820. sp<ThreadBase> thread = mThread.promote();
  821. if (thread != 0) {
  822. sp<StreamHalInterface> stream = thread->stream();
  823. if (stream != 0) {
  824. status_t result = stream->removeEffect(mEffectInterface);
  825. ALOGE_IF(result != OK, "Error when removing effect: %d", result);
  826. }
  827. }
  828. }
  829. return NO_ERROR;
  830. }
  831. // round up delta valid if value and divisor are positive.
  832. template <typename T>
  833. static T roundUpDelta(const T &value, const T &divisor) {
  834. T remainder = value % divisor;
  835. return remainder == 0 ? 0 : divisor - remainder;
  836. }
  837. status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
  838. uint32_t cmdSize,
  839. void *pCmdData,
  840. uint32_t *replySize,
  841. void *pReplyData)
  842. {
  843. Mutex::Autolock _l(mLock);
  844. ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface.get());
  845. if (mState == DESTROYED || mEffectInterface == 0) {
  846. return NO_INIT;
  847. }
  848. if (mStatus != NO_ERROR) {
  849. return mStatus;
  850. }
  851. if (cmdCode == EFFECT_CMD_GET_PARAM &&
  852. (sizeof(effect_param_t) > cmdSize ||
  853. ((effect_param_t *)pCmdData)->psize > cmdSize
  854. - sizeof(effect_param_t))) {
  855. android_errorWriteLog(0x534e4554, "32438594");
  856. android_errorWriteLog(0x534e4554, "33003822");
  857. return -EINVAL;
  858. }
  859. if (cmdCode == EFFECT_CMD_GET_PARAM &&
  860. (*replySize < sizeof(effect_param_t) ||
  861. ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
  862. android_errorWriteLog(0x534e4554, "29251553");
  863. return -EINVAL;
  864. }
  865. if (cmdCode == EFFECT_CMD_GET_PARAM &&
  866. (sizeof(effect_param_t) > *replySize
  867. || ((effect_param_t *)pCmdData)->psize > *replySize
  868. - sizeof(effect_param_t)
  869. || ((effect_param_t *)pCmdData)->vsize > *replySize
  870. - sizeof(effect_param_t)
  871. - ((effect_param_t *)pCmdData)->psize
  872. || roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) >
  873. *replySize
  874. - sizeof(effect_param_t)
  875. - ((effect_param_t *)pCmdData)->psize
  876. - ((effect_param_t *)pCmdData)->vsize)) {
  877. ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: reply size inconsistent");
  878. android_errorWriteLog(0x534e4554, "32705438");
  879. return -EINVAL;
  880. }
  881. if ((cmdCode == EFFECT_CMD_SET_PARAM
  882. || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used
  883. (sizeof(effect_param_t) > cmdSize
  884. || ((effect_param_t *)pCmdData)->psize > cmdSize
  885. - sizeof(effect_param_t)
  886. || ((effect_param_t *)pCmdData)->vsize > cmdSize
  887. - sizeof(effect_param_t)
  888. - ((effect_param_t *)pCmdData)->psize
  889. || roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) >
  890. cmdSize
  891. - sizeof(effect_param_t)
  892. - ((effect_param_t *)pCmdData)->psize
  893. - ((effect_param_t *)pCmdData)->vsize)) {
  894. android_errorWriteLog(0x534e4554, "30204301");
  895. return -EINVAL;
  896. }
  897. status_t status = mEffectInterface->command(cmdCode,
  898. cmdSize,
  899. pCmdData,
  900. replySize,
  901. pReplyData);
  902. if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
  903. uint32_t size = (replySize == NULL) ? 0 : *replySize;
  904. for (size_t i = 1; i < mHandles.size(); i++) {
  905. EffectHandle *h = mHandles[i];
  906. if (h != NULL && !h->disconnected()) {
  907. h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
  908. }
  909. }
  910. }
  911. return status;
  912. }
  913. status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
  914. {
  915. Mutex::Autolock _l(mLock);
  916. return setEnabled_l(enabled);
  917. }
  918. // must be called with EffectModule::mLock held
  919. status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
  920. {
  921. ALOGV("setEnabled %p enabled %d", this, enabled);
  922. if (enabled != isEnabled()) {
  923. switch (mState) {
  924. // going from disabled to enabled
  925. case IDLE:
  926. mState = STARTING;
  927. break;
  928. case STOPPED:
  929. mState = RESTART;
  930. break;
  931. case STOPPING:
  932. mState = ACTIVE;
  933. break;
  934. // going from enabled to disabled
  935. case RESTART:
  936. mState = STOPPED;
  937. break;
  938. case STARTING:
  939. mState = IDLE;
  940. break;
  941. case ACTIVE:
  942. mState = STOPPING;
  943. break;
  944. case DESTROYED:
  945. return NO_ERROR; // simply ignore as we are being destroyed
  946. }
  947. for (size_t i = 1; i < mHandles.size(); i++) {
  948. EffectHandle *h = mHandles[i];
  949. if (h != NULL && !h->disconnected()) {
  950. h->setEnabled(enabled);
  951. }
  952. }
  953. }
  954. return NO_ERROR;
  955. }
  956. bool AudioFlinger::EffectModule::isEnabled() const
  957. {
  958. switch (mState) {
  959. case RESTART:
  960. case STARTING:
  961. case ACTIVE:
  962. return true;
  963. case IDLE:
  964. case STOPPING:
  965. case STOPPED:
  966. case DESTROYED:
  967. default:
  968. return false;
  969. }
  970. }
  971. bool AudioFlinger::EffectModule::isProcessEnabled() const
  972. {
  973. if (mStatus != NO_ERROR) {
  974. return false;
  975. }
  976. switch (mState) {
  977. case RESTART:
  978. case ACTIVE:
  979. case STOPPING:
  980. case STOPPED:
  981. return true;
  982. case IDLE:
  983. case STARTING:
  984. case DESTROYED:
  985. default:
  986. return false;
  987. }
  988. }
  989. bool AudioFlinger::EffectModule::isOffloadedOrDirect() const
  990. {
  991. return (mThreadType == ThreadBase::OFFLOAD || mThreadType == ThreadBase::DIRECT);
  992. }
  993. bool AudioFlinger::EffectModule::isVolumeControlEnabled() const
  994. {
  995. return (isVolumeControl() && (isOffloadedOrDirect() ? isEnabled() : isProcessEnabled()));
  996. }
  997. void AudioFlinger::EffectModule::setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
  998. ALOGVV("setInBuffer %p",(&buffer));
  999. // mConfig.inputCfg.buffer.frameCount may be zero if configure() is not called yet.
  1000. if (buffer != 0) {
  1001. mConfig.inputCfg.buffer.raw = buffer->audioBuffer()->raw;
  1002. buffer->setFrameCount(mConfig.inputCfg.buffer.frameCount);
  1003. } else {
  1004. mConfig.inputCfg.buffer.raw = NULL;
  1005. }
  1006. mInBuffer = buffer;
  1007. mEffectInterface->setInBuffer(buffer);
  1008. #ifdef FLOAT_EFFECT_CHAIN
  1009. // aux effects do in place conversion to float - we don't allocate mInConversionBuffer.
  1010. // Theoretically insert effects can also do in-place conversions (destroying
  1011. // the original buffer) when the output buffer is identical to the input buffer,
  1012. // but we don't optimize for it here.
  1013. const bool auxType = (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
  1014. const uint32_t inChannelCount =
  1015. audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
  1016. const bool formatMismatch = !mSupportsFloat || mInChannelCountRequested != inChannelCount;
  1017. if (!auxType && formatMismatch && mInBuffer.get() != nullptr) {
  1018. // we need to translate - create hidl shared buffer and intercept
  1019. const size_t inFrameCount = mConfig.inputCfg.buffer.frameCount;
  1020. // Use FCC_2 in case mInChannelCountRequested is mono and the effect is stereo.
  1021. const uint32_t inChannels = std::max((uint32_t)FCC_2, mInChannelCountRequested);
  1022. const size_t size = inChannels * inFrameCount * std::max(sizeof(int16_t), sizeof(float));
  1023. ALOGV("%s: setInBuffer updating for inChannels:%d inFrameCount:%zu total size:%zu",
  1024. __func__, inChannels, inFrameCount, size);
  1025. if (size > 0 && (mInConversionBuffer.get() == nullptr
  1026. || size > mInConversionBuffer->getSize())) {
  1027. mInConversionBuffer.clear();
  1028. ALOGV("%s: allocating mInConversionBuffer %zu", __func__, size);
  1029. sp<AudioFlinger> audioFlinger = mAudioFlinger.promote();
  1030. LOG_ALWAYS_FATAL_IF(audioFlinger == nullptr, "EM could not retrieved audioFlinger");
  1031. (void)audioFlinger->mEffectsFactoryHal->allocateBuffer(size, &mInConversionBuffer);
  1032. }
  1033. if (mInConversionBuffer.get() != nullptr) {
  1034. mInConversionBuffer->setFrameCount(inFrameCount);
  1035. mEffectInterface->setInBuffer(mInConversionBuffer);
  1036. } else if (size > 0) {
  1037. ALOGE("%s cannot create mInConversionBuffer", __func__);
  1038. }
  1039. }
  1040. #endif
  1041. }
  1042. void AudioFlinger::EffectModule::setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
  1043. ALOGVV("setOutBuffer %p",(&buffer));
  1044. // mConfig.outputCfg.buffer.frameCount may be zero if configure() is not called yet.
  1045. if (buffer != 0) {
  1046. mConfig.outputCfg.buffer.raw = buffer->audioBuffer()->raw;
  1047. buffer->setFrameCount(mConfig.outputCfg.buffer.frameCount);
  1048. } else {
  1049. mConfig.outputCfg.buffer.raw = NULL;
  1050. }
  1051. mOutBuffer = buffer;
  1052. mEffectInterface->setOutBuffer(buffer);
  1053. #ifdef FLOAT_EFFECT_CHAIN
  1054. // Note: Any effect that does not accumulate does not need mOutConversionBuffer and
  1055. // can do in-place conversion from int16_t to float. We don't optimize here.
  1056. const uint32_t outChannelCount =
  1057. audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
  1058. const bool formatMismatch = !mSupportsFloat || mOutChannelCountRequested != outChannelCount;
  1059. if (formatMismatch && mOutBuffer.get() != nullptr) {
  1060. const size_t outFrameCount = mConfig.outputCfg.buffer.frameCount;
  1061. // Use FCC_2 in case mOutChannelCountRequested is mono and the effect is stereo.
  1062. const uint32_t outChannels = std::max((uint32_t)FCC_2, mOutChannelCountRequested);
  1063. const size_t size = outChannels * outFrameCount * std::max(sizeof(int16_t), sizeof(float));
  1064. ALOGV("%s: setOutBuffer updating for outChannels:%d outFrameCount:%zu total size:%zu",
  1065. __func__, outChannels, outFrameCount, size);
  1066. if (size > 0 && (mOutConversionBuffer.get() == nullptr
  1067. || size > mOutConversionBuffer->getSize())) {
  1068. mOutConversionBuffer.clear();
  1069. ALOGV("%s: allocating mOutConversionBuffer %zu", __func__, size);
  1070. sp<AudioFlinger> audioFlinger = mAudioFlinger.promote();
  1071. LOG_ALWAYS_FATAL_IF(audioFlinger == nullptr, "EM could not retrieved audioFlinger");
  1072. (void)audioFlinger->mEffectsFactoryHal->allocateBuffer(size, &mOutConversionBuffer);
  1073. }
  1074. if (mOutConversionBuffer.get() != nullptr) {
  1075. mOutConversionBuffer->setFrameCount(outFrameCount);
  1076. mEffectInterface->setOutBuffer(mOutConversionBuffer);
  1077. } else if (size > 0) {
  1078. ALOGE("%s cannot create mOutConversionBuffer", __func__);
  1079. }
  1080. }
  1081. #endif
  1082. }
  1083. status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
  1084. {
  1085. AutoLockReentrant _l(mLock, mSetVolumeReentrantTid);
  1086. if (mStatus != NO_ERROR) {
  1087. return mStatus;
  1088. }
  1089. status_t status = NO_ERROR;
  1090. // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
  1091. // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
  1092. if (isProcessEnabled() &&
  1093. ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
  1094. (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND ||
  1095. (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_MONITOR)) {
  1096. uint32_t volume[2];
  1097. uint32_t *pVolume = NULL;
  1098. uint32_t size = sizeof(volume);
  1099. volume[0] = *left;
  1100. volume[1] = *right;
  1101. if (controller) {
  1102. pVolume = volume;
  1103. }
  1104. status = mEffectInterface->command(EFFECT_CMD_SET_VOLUME,
  1105. size,
  1106. volume,
  1107. &size,
  1108. pVolume);
  1109. if (controller && status == NO_ERROR && size == sizeof(volume)) {
  1110. *left = volume[0];
  1111. *right = volume[1];
  1112. }
  1113. }
  1114. return status;
  1115. }
  1116. void AudioFlinger::EffectChain::setVolumeForOutput_l(uint32_t left, uint32_t right)
  1117. {
  1118. sp<ThreadBase> thread = mThread.promote();
  1119. if (thread != 0 &&
  1120. (thread->type() == ThreadBase::OFFLOAD || thread->type() == ThreadBase::DIRECT) &&
  1121. !isNonOffloadableEnabled_l()) {
  1122. PlaybackThread *t = (PlaybackThread *)thread.get();
  1123. float vol_l = (float)left / (1 << 24);
  1124. float vol_r = (float)right / (1 << 24);
  1125. t->setVolumeForOutput_l(vol_l, vol_r);
  1126. }
  1127. }
  1128. status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
  1129. {
  1130. if (device == AUDIO_DEVICE_NONE) {
  1131. return NO_ERROR;
  1132. }
  1133. Mutex::Autolock _l(mLock);
  1134. if (mStatus != NO_ERROR) {
  1135. return mStatus;
  1136. }
  1137. status_t status = NO_ERROR;
  1138. if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
  1139. status_t cmdStatus;
  1140. uint32_t size = sizeof(status_t);
  1141. uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
  1142. EFFECT_CMD_SET_INPUT_DEVICE;
  1143. status = mEffectInterface->command(cmd,
  1144. sizeof(uint32_t),
  1145. &device,
  1146. &size,
  1147. &cmdStatus);
  1148. }
  1149. return status;
  1150. }
  1151. status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
  1152. {
  1153. Mutex::Autolock _l(mLock);
  1154. if (mStatus != NO_ERROR) {
  1155. return mStatus;
  1156. }
  1157. status_t status = NO_ERROR;
  1158. if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
  1159. status_t cmdStatus;
  1160. uint32_t size = sizeof(status_t);
  1161. status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_MODE,
  1162. sizeof(audio_mode_t),
  1163. &mode,
  1164. &size,
  1165. &cmdStatus);
  1166. if (status == NO_ERROR) {
  1167. status = cmdStatus;
  1168. }
  1169. }
  1170. return status;
  1171. }
  1172. status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
  1173. {
  1174. Mutex::Autolock _l(mLock);
  1175. if (mStatus != NO_ERROR) {
  1176. return mStatus;
  1177. }
  1178. status_t status = NO_ERROR;
  1179. if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
  1180. uint32_t size = 0;
  1181. status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_SOURCE,
  1182. sizeof(audio_source_t),
  1183. &source,
  1184. &size,
  1185. NULL);
  1186. }
  1187. return status;
  1188. }
  1189. void AudioFlinger::EffectModule::setSuspended(bool suspended)
  1190. {
  1191. Mutex::Autolock _l(mLock);
  1192. mSuspended = suspended;
  1193. }
  1194. bool AudioFlinger::EffectModule::suspended() const
  1195. {
  1196. Mutex::Autolock _l(mLock);
  1197. return mSuspended;
  1198. }
  1199. bool AudioFlinger::EffectModule::purgeHandles()
  1200. {
  1201. bool enabled = false;
  1202. Mutex::Autolock _l(mLock);
  1203. EffectHandle *handle = controlHandle_l();
  1204. if (handle != NULL) {
  1205. enabled = handle->enabled();
  1206. }
  1207. mHandles.clear();
  1208. return enabled;
  1209. }
  1210. status_t AudioFlinger::EffectModule::setOffloaded(bool offloaded, audio_io_handle_t io)
  1211. {
  1212. Mutex::Autolock _l(mLock);
  1213. if (mStatus != NO_ERROR) {
  1214. return mStatus;
  1215. }
  1216. status_t status = NO_ERROR;
  1217. if ((mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0) {
  1218. status_t cmdStatus;
  1219. uint32_t size = sizeof(status_t);
  1220. effect_offload_param_t cmd;
  1221. cmd.isOffload = offloaded;
  1222. cmd.ioHandle = io;
  1223. status = mEffectInterface->command(EFFECT_CMD_OFFLOAD,
  1224. sizeof(effect_offload_param_t),
  1225. &cmd,
  1226. &size,
  1227. &cmdStatus);
  1228. if (status == NO_ERROR) {
  1229. status = cmdStatus;
  1230. }
  1231. mOffloaded = (status == NO_ERROR) ? offloaded : false;
  1232. } else {
  1233. if (offloaded) {
  1234. status = INVALID_OPERATION;
  1235. }
  1236. mOffloaded = false;
  1237. }
  1238. ALOGV("setOffloaded() offloaded %d io %d status %d", offloaded, io, status);
  1239. return status;
  1240. }
  1241. bool AudioFlinger::EffectModule::isOffloaded() const
  1242. {
  1243. Mutex::Autolock _l(mLock);
  1244. return mOffloaded;
  1245. }
  1246. String8 effectFlagsToString(uint32_t flags) {
  1247. String8 s;
  1248. s.append("conn. mode: ");
  1249. switch (flags & EFFECT_FLAG_TYPE_MASK) {
  1250. case EFFECT_FLAG_TYPE_INSERT: s.append("insert"); break;
  1251. case EFFECT_FLAG_TYPE_AUXILIARY: s.append("auxiliary"); break;
  1252. case EFFECT_FLAG_TYPE_REPLACE: s.append("replace"); break;
  1253. case EFFECT_FLAG_TYPE_PRE_PROC: s.append("preproc"); break;
  1254. case EFFECT_FLAG_TYPE_POST_PROC: s.append("postproc"); break;
  1255. default: s.append("unknown/reserved"); break;
  1256. }
  1257. s.append(", ");
  1258. s.append("insert pref: ");
  1259. switch (flags & EFFECT_FLAG_INSERT_MASK) {
  1260. case EFFECT_FLAG_INSERT_ANY: s.append("any"); break;
  1261. case EFFECT_FLAG_INSERT_FIRST: s.append("first"); break;
  1262. case EFFECT_FLAG_INSERT_LAST: s.append("last"); break;
  1263. case EFFECT_FLAG_INSERT_EXCLUSIVE: s.append("exclusive"); break;
  1264. default: s.append("unknown/reserved"); break;
  1265. }
  1266. s.append(", ");
  1267. s.append("volume mgmt: ");
  1268. switch (flags & EFFECT_FLAG_VOLUME_MASK) {
  1269. case EFFECT_FLAG_VOLUME_NONE: s.append("none"); break;
  1270. case EFFECT_FLAG_VOLUME_CTRL: s.append("implements control"); break;
  1271. case EFFECT_FLAG_VOLUME_IND: s.append("requires indication"); break;
  1272. case EFFECT_FLAG_VOLUME_MONITOR: s.append("monitors volume"); break;
  1273. default: s.append("unknown/reserved"); break;
  1274. }
  1275. s.append(", ");
  1276. uint32_t devind = flags & EFFECT_FLAG_DEVICE_MASK;
  1277. if (devind) {
  1278. s.append("device indication: ");
  1279. switch (devind) {
  1280. case EFFECT_FLAG_DEVICE_IND: s.append("requires updates"); break;
  1281. default: s.append("unknown/reserved"); break;
  1282. }
  1283. s.append(", ");
  1284. }
  1285. s.append("input mode: ");
  1286. switch (flags & EFFECT_FLAG_INPUT_MASK) {
  1287. case EFFECT_FLAG_INPUT_DIRECT: s.append("direct"); break;
  1288. case EFFECT_FLAG_INPUT_PROVIDER: s.append("provider"); break;
  1289. case EFFECT_FLAG_INPUT_BOTH: s.append("direct+provider"); break;
  1290. default: s.append("not set"); break;
  1291. }
  1292. s.append(", ");
  1293. s.append("output mode: ");
  1294. switch (flags & EFFECT_FLAG_OUTPUT_MASK) {
  1295. case EFFECT_FLAG_OUTPUT_DIRECT: s.append("direct"); break;
  1296. case EFFECT_FLAG_OUTPUT_PROVIDER: s.append("provider"); break;
  1297. case EFFECT_FLAG_OUTPUT_BOTH: s.append("direct+provider"); break;
  1298. default: s.append("not set"); break;
  1299. }
  1300. s.append(", ");
  1301. uint32_t accel = flags & EFFECT_FLAG_HW_ACC_MASK;
  1302. if (accel) {
  1303. s.append("hardware acceleration: ");
  1304. switch (accel) {
  1305. case EFFECT_FLAG_HW_ACC_SIMPLE: s.append("non-tunneled"); break;
  1306. case EFFECT_FLAG_HW_ACC_TUNNEL: s.append("tunneled"); break;
  1307. default: s.append("unknown/reserved"); break;
  1308. }
  1309. s.append(", ");
  1310. }
  1311. uint32_t modeind = flags & EFFECT_FLAG_AUDIO_MODE_MASK;
  1312. if (modeind) {
  1313. s.append("mode indication: ");
  1314. switch (modeind) {
  1315. case EFFECT_FLAG_AUDIO_MODE_IND: s.append("required"); break;
  1316. default: s.append("unknown/reserved"); break;
  1317. }
  1318. s.append(", ");
  1319. }
  1320. uint32_t srcind = flags & EFFECT_FLAG_AUDIO_SOURCE_MASK;
  1321. if (srcind) {
  1322. s.append("source indication: ");
  1323. switch (srcind) {
  1324. case EFFECT_FLAG_AUDIO_SOURCE_IND: s.append("required"); break;
  1325. default: s.append("unknown/reserved"); break;
  1326. }
  1327. s.append(", ");
  1328. }
  1329. if (flags & EFFECT_FLAG_OFFLOAD_MASK) {
  1330. s.append("offloadable, ");
  1331. }
  1332. int len = s.length();
  1333. if (s.length() > 2) {
  1334. (void) s.lockBuffer(len);
  1335. s.unlockBuffer(len - 2);
  1336. }
  1337. return s;
  1338. }
  1339. static std::string dumpInOutBuffer(bool isInput, const sp<EffectBufferHalInterface> &buffer) {
  1340. std::stringstream ss;
  1341. if (buffer.get() == nullptr) {
  1342. return "nullptr"; // make different than below
  1343. } else if (buffer->externalData() != nullptr) {
  1344. ss << (isInput ? buffer->externalData() : buffer->audioBuffer()->raw)
  1345. << " -> "
  1346. << (isInput ? buffer->audioBuffer()->raw : buffer->externalData());
  1347. } else {
  1348. ss << buffer->audioBuffer()->raw;
  1349. }
  1350. return ss.str();
  1351. }
  1352. void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args __unused)
  1353. {
  1354. String8 result;
  1355. result.appendFormat("\tEffect ID %d:\n", mId);
  1356. bool locked = AudioFlinger::dumpTryLock(mLock);
  1357. // failed to lock - AudioFlinger is probably deadlocked
  1358. if (!locked) {
  1359. result.append("\t\tCould not lock Fx mutex:\n");
  1360. }
  1361. result.append("\t\tSession Status State Registered Enabled Suspended Engine:\n");
  1362. result.appendFormat("\t\t%05d %03d %03d %s %s %s %p\n",
  1363. mSessionId, mStatus, mState, mPolicyRegistered ? "y" : "n", mPolicyEnabled ? "y" : "n",
  1364. mSuspended ? "y" : "n", mEffectInterface.get());
  1365. result.append("\t\tDescriptor:\n");
  1366. char uuidStr[64];
  1367. AudioEffect::guidToString(&mDescriptor.uuid, uuidStr, sizeof(uuidStr));
  1368. result.appendFormat("\t\t- UUID: %s\n", uuidStr);
  1369. AudioEffect::guidToString(&mDescriptor.type, uuidStr, sizeof(uuidStr));
  1370. result.appendFormat("\t\t- TYPE: %s\n", uuidStr);
  1371. result.appendFormat("\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n",
  1372. mDescriptor.apiVersion,
  1373. mDescriptor.flags,
  1374. effectFlagsToString(mDescriptor.flags).string());
  1375. result.appendFormat("\t\t- name: %s\n",
  1376. mDescriptor.name);
  1377. result.appendFormat("\t\t- implementor: %s\n",
  1378. mDescriptor.implementor);
  1379. result.appendFormat("\t\t- data: %s\n", mSupportsFloat ? "float" : "int16");
  1380. result.append("\t\t- Input configuration:\n");
  1381. result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
  1382. result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
  1383. mConfig.inputCfg.buffer.raw,
  1384. mConfig.inputCfg.buffer.frameCount,
  1385. mConfig.inputCfg.samplingRate,
  1386. mConfig.inputCfg.channels,
  1387. mConfig.inputCfg.format,
  1388. formatToString((audio_format_t)mConfig.inputCfg.format).c_str());
  1389. result.append("\t\t- Output configuration:\n");
  1390. result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
  1391. result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
  1392. mConfig.outputCfg.buffer.raw,
  1393. mConfig.outputCfg.buffer.frameCount,
  1394. mConfig.outputCfg.samplingRate,
  1395. mConfig.outputCfg.channels,
  1396. mConfig.outputCfg.format,
  1397. formatToString((audio_format_t)mConfig.outputCfg.format).c_str());
  1398. #ifdef FLOAT_EFFECT_CHAIN
  1399. result.appendFormat("\t\t- HAL buffers:\n"
  1400. "\t\t\tIn(%s) InConversion(%s) Out(%s) OutConversion(%s)\n",
  1401. dumpInOutBuffer(true /* isInput */, mInBuffer).c_str(),
  1402. dumpInOutBuffer(true /* isInput */, mInConversionBuffer).c_str(),
  1403. dumpInOutBuffer(false /* isInput */, mOutBuffer).c_str(),
  1404. dumpInOutBuffer(false /* isInput */, mOutConversionBuffer).c_str());
  1405. #endif
  1406. result.appendFormat("\t\t%zu Clients:\n", mHandles.size());
  1407. result.append("\t\t\t Pid Priority Ctrl Locked client server\n");
  1408. char buffer[256];
  1409. for (size_t i = 0; i < mHandles.size(); ++i) {
  1410. EffectHandle *handle = mHandles[i];
  1411. if (handle != NULL && !handle->disconnected()) {
  1412. handle->dumpToBuffer(buffer, sizeof(buffer));
  1413. result.append(buffer);
  1414. }
  1415. }
  1416. write(fd, result.string(), result.length());
  1417. if (mEffectInterface != 0) {
  1418. dprintf(fd, "\tEffect ID %d HAL dump:\n", mId);
  1419. (void)mEffectInterface->dump(fd);
  1420. }
  1421. if (locked) {
  1422. mLock.unlock();
  1423. }
  1424. }
  1425. // ----------------------------------------------------------------------------
  1426. // EffectHandle implementation
  1427. // ----------------------------------------------------------------------------
  1428. #undef LOG_TAG
  1429. #define LOG_TAG "AudioFlinger::EffectHandle"
  1430. AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
  1431. const sp<AudioFlinger::Client>& client,
  1432. const sp<IEffectClient>& effectClient,
  1433. int32_t priority)
  1434. : BnEffect(),
  1435. mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
  1436. mPriority(priority), mHasControl(false), mEnabled(false), mDisconnected(false)
  1437. {
  1438. ALOGV("constructor %p", this);
  1439. if (client == 0) {
  1440. return;
  1441. }
  1442. int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
  1443. mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
  1444. if (mCblkMemory == 0 ||
  1445. (mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer())) == NULL) {
  1446. ALOGE("not enough memory for Effect size=%zu", EFFECT_PARAM_BUFFER_SIZE +
  1447. sizeof(effect_param_cblk_t));
  1448. mCblkMemory.clear();
  1449. return;
  1450. }
  1451. new(mCblk) effect_param_cblk_t();
  1452. mBuffer = (uint8_t *)mCblk + bufOffset;
  1453. }
  1454. AudioFlinger::EffectHandle::~EffectHandle()
  1455. {
  1456. ALOGV("Destructor %p", this);
  1457. disconnect(false);
  1458. }
  1459. status_t AudioFlinger::EffectHandle::initCheck()
  1460. {
  1461. return mClient == 0 || mCblkMemory != 0 ? OK : NO_MEMORY;
  1462. }
  1463. status_t AudioFlinger::EffectHandle::enable()
  1464. {
  1465. AutoMutex _l(mLock);
  1466. ALOGV("enable %p", this);
  1467. sp<EffectModule> effect = mEffect.promote();
  1468. if (effect == 0 || mDisconnected) {
  1469. return DEAD_OBJECT;
  1470. }
  1471. if (!mHasControl) {
  1472. return INVALID_OPERATION;
  1473. }
  1474. if (mEnabled) {
  1475. return NO_ERROR;
  1476. }
  1477. mEnabled = true;
  1478. status_t status = effect->updatePolicyState();
  1479. if (status != NO_ERROR) {
  1480. mEnabled = false;
  1481. return status;
  1482. }
  1483. sp<ThreadBase> thread = effect->thread().promote();
  1484. if (thread != 0) {
  1485. thread->checkSuspendOnEffectEnabled(effect, true, effect->sessionId());
  1486. }
  1487. // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
  1488. if (effect->suspended()) {
  1489. return NO_ERROR;
  1490. }
  1491. status = effect->setEnabled(true);
  1492. if (status != NO_ERROR) {
  1493. if (thread != 0) {
  1494. thread->checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
  1495. }
  1496. mEnabled = false;
  1497. } else {
  1498. if (thread != 0) {
  1499. if (thread->type() == ThreadBase::OFFLOAD || thread->type() == ThreadBase::MMAP) {
  1500. Mutex::Autolock _l(thread->mLock);
  1501. thread->broadcast_l();
  1502. }
  1503. if (!effect->isOffloadable()) {
  1504. if (thread->type() == ThreadBase::OFFLOAD) {
  1505. PlaybackThread *t = (PlaybackThread *)thread.get();
  1506. t->invalidateTracks(AUDIO_STREAM_MUSIC);
  1507. }
  1508. if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
  1509. thread->mAudioFlinger->onNonOffloadableGlobalEffectEnable();
  1510. }
  1511. }
  1512. }
  1513. }
  1514. return status;
  1515. }
  1516. status_t AudioFlinger::EffectHandle::disable()
  1517. {
  1518. ALOGV("disable %p", this);
  1519. AutoMutex _l(mLock);
  1520. sp<EffectModule> effect = mEffect.promote();
  1521. if (effect == 0 || mDisconnected) {
  1522. return DEAD_OBJECT;
  1523. }
  1524. if (!mHasControl) {
  1525. return INVALID_OPERATION;
  1526. }
  1527. if (!mEnabled) {
  1528. return NO_ERROR;
  1529. }
  1530. mEnabled = false;
  1531. effect->updatePolicyState();
  1532. if (effect->suspended()) {
  1533. return NO_ERROR;
  1534. }
  1535. status_t status = effect->setEnabled(false);
  1536. sp<ThreadBase> thread = effect->thread().promote();
  1537. if (thread != 0) {
  1538. thread->checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
  1539. if (thread->type() == ThreadBase::OFFLOAD || thread->type() == ThreadBase::MMAP) {
  1540. Mutex::Autolock _l(thread->mLock);
  1541. thread->broadcast_l();
  1542. }
  1543. }
  1544. return status;
  1545. }
  1546. void AudioFlinger::EffectHandle::disconnect()
  1547. {
  1548. ALOGV("%s %p", __FUNCTION__, this);
  1549. disconnect(true);
  1550. }
  1551. void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
  1552. {
  1553. AutoMutex _l(mLock);
  1554. ALOGV("disconnect(%s) %p", unpinIfLast ? "true" : "false", this);
  1555. if (mDisconnected) {
  1556. if (unpinIfLast) {
  1557. android_errorWriteLog(0x534e4554, "32707507");
  1558. }
  1559. return;
  1560. }
  1561. mDisconnected = true;
  1562. {
  1563. sp<EffectModule> effect = mEffect.promote();
  1564. if (effect != 0) {
  1565. sp<ThreadBase> thread = effect->thread().promote();
  1566. if (thread != 0) {
  1567. thread->disconnectEffectHandle(this, unpinIfLast);
  1568. } else if (effect->disconnectHandle(this, unpinIfLast) > 0) {
  1569. ALOGW("%s Effect handle %p disconnected after thread destruction",
  1570. __func__, this);
  1571. }
  1572. effect->updatePolicyState();
  1573. }
  1574. }
  1575. if (mClient != 0) {
  1576. if (mCblk != NULL) {
  1577. // unlike ~TrackBase(), mCblk is never a local new, so don't delete
  1578. mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
  1579. }
  1580. mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
  1581. // Client destructor must run with AudioFlinger client mutex locked
  1582. Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
  1583. mClient.clear();
  1584. }
  1585. }
  1586. status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
  1587. uint32_t cmdSize,
  1588. void *pCmdData,
  1589. uint32_t *replySize,
  1590. void *pReplyData)
  1591. {
  1592. ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
  1593. cmdCode, mHasControl, mEffect.unsafe_get());
  1594. // reject commands reserved for internal use by audio framework if coming from outside
  1595. // of audioserver
  1596. switch(cmdCode) {
  1597. case EFFECT_CMD_ENABLE:
  1598. case EFFECT_CMD_DISABLE:
  1599. case EFFECT_CMD_SET_PARAM:
  1600. case EFFECT_CMD_SET_PARAM_DEFERRED:
  1601. case EFFECT_CMD_SET_PARAM_COMMIT:
  1602. case EFFECT_CMD_GET_PARAM:
  1603. break;
  1604. default:
  1605. if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY) {
  1606. break;
  1607. }
  1608. android_errorWriteLog(0x534e4554, "62019992");
  1609. return BAD_VALUE;
  1610. }
  1611. if (cmdCode == EFFECT_CMD_ENABLE) {
  1612. if (*replySize < sizeof(int)) {
  1613. android_errorWriteLog(0x534e4554, "32095713");
  1614. return BAD_VALUE;
  1615. }
  1616. *(int *)pReplyData = NO_ERROR;
  1617. *replySize = sizeof(int);
  1618. return enable();
  1619. } else if (cmdCode == EFFECT_CMD_DISABLE) {
  1620. if (*replySize < sizeof(int)) {
  1621. android_errorWriteLog(0x534e4554, "32095713");
  1622. return BAD_VALUE;
  1623. }
  1624. *(int *)pReplyData = NO_ERROR;
  1625. *replySize = sizeof(int);
  1626. return disable();
  1627. }
  1628. AutoMutex _l(mLock);
  1629. sp<EffectModule> effect = mEffect.promote();
  1630. if (effect == 0 || mDisconnected) {
  1631. return DEAD_OBJECT;
  1632. }
  1633. // only get parameter command is permitted for applications not controlling the effect
  1634. if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
  1635. return INVALID_OPERATION;
  1636. }
  1637. if (mClient == 0) {
  1638. return INVALID_OPERATION;
  1639. }
  1640. // handle commands that are not forwarded transparently to effect engine
  1641. if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
  1642. if (*replySize < sizeof(int)) {
  1643. android_errorWriteLog(0x534e4554, "32095713");
  1644. return BAD_VALUE;
  1645. }
  1646. *(int *)pReplyData = NO_ERROR;
  1647. *replySize = sizeof(int);
  1648. // No need to trylock() here as this function is executed in the binder thread serving a
  1649. // particular client process: no risk to block the whole media server process or mixer
  1650. // threads if we are stuck here
  1651. Mutex::Autolock _l(mCblk->lock);
  1652. // keep local copy of index in case of client corruption b/32220769
  1653. const uint32_t clientIndex = mCblk->clientIndex;
  1654. const uint32_t serverIndex = mCblk->serverIndex;
  1655. if (clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
  1656. serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
  1657. mCblk->serverIndex = 0;
  1658. mCblk->clientIndex = 0;
  1659. return BAD_VALUE;
  1660. }
  1661. status_t status = NO_ERROR;
  1662. effect_param_t *param = NULL;
  1663. for (uint32_t index = serverIndex; index < clientIndex;) {
  1664. int *p = (int *)(mBuffer + index);
  1665. const int size = *p++;
  1666. if (size < 0
  1667. || size > EFFECT_PARAM_BUFFER_SIZE
  1668. || ((uint8_t *)p + size) > mBuffer + clientIndex) {
  1669. ALOGW("command(): invalid parameter block size");
  1670. status = BAD_VALUE;
  1671. break;
  1672. }
  1673. // copy to local memory in case of client corruption b/32220769
  1674. param = (effect_param_t *)realloc(param, size);
  1675. if (param == NULL) {
  1676. ALOGW("command(): out of memory");
  1677. status = NO_MEMORY;
  1678. break;
  1679. }
  1680. memcpy(param, p, size);
  1681. int reply = 0;
  1682. uint32_t rsize = sizeof(reply);
  1683. status_t ret = effect->command(EFFECT_CMD_SET_PARAM,
  1684. size,
  1685. param,
  1686. &rsize,
  1687. &reply);
  1688. // verify shared memory: server index shouldn't change; client index can't go back.
  1689. if (serverIndex != mCblk->serverIndex
  1690. || clientIndex > mCblk->clientIndex) {
  1691. android_errorWriteLog(0x534e4554, "32220769");
  1692. status = BAD_VALUE;
  1693. break;
  1694. }
  1695. // stop at first error encountered
  1696. if (ret != NO_ERROR) {
  1697. status = ret;
  1698. *(int *)pReplyData = reply;
  1699. break;
  1700. } else if (reply != NO_ERROR) {
  1701. *(int *)pReplyData = reply;
  1702. break;
  1703. }
  1704. index += size;
  1705. }
  1706. free(param);
  1707. mCblk->serverIndex = 0;
  1708. mCblk->clientIndex = 0;
  1709. return status;
  1710. }
  1711. return effect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
  1712. }
  1713. void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
  1714. {
  1715. ALOGV("setControl %p control %d", this, hasControl);
  1716. mHasControl = hasControl;
  1717. mEnabled = enabled;
  1718. if (signal && mEffectClient != 0) {
  1719. mEffectClient->controlStatusChanged(hasControl);
  1720. }
  1721. }
  1722. void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
  1723. uint32_t cmdSize,
  1724. void *pCmdData,
  1725. uint32_t replySize,
  1726. void *pReplyData)
  1727. {
  1728. if (mEffectClient != 0) {
  1729. mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
  1730. }
  1731. }
  1732. void AudioFlinger::EffectHandle::setEnabled(bool enabled)
  1733. {
  1734. if (mEffectClient != 0) {
  1735. mEffectClient->enableStatusChanged(enabled);
  1736. }
  1737. }
  1738. status_t AudioFlinger::EffectHandle::onTransact(
  1739. uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
  1740. {
  1741. return BnEffect::onTransact(code, data, reply, flags);
  1742. }
  1743. void AudioFlinger::EffectHandle::dumpToBuffer(char* buffer, size_t size)
  1744. {
  1745. bool locked = mCblk != NULL && AudioFlinger::dumpTryLock(mCblk->lock);
  1746. snprintf(buffer, size, "\t\t\t%5d %5d %3s %3s %5u %5u\n",
  1747. (mClient == 0) ? getpid() : mClient->pid(),
  1748. mPriority,
  1749. mHasControl ? "yes" : "no",
  1750. locked ? "yes" : "no",
  1751. mCblk ? mCblk->clientIndex : 0,
  1752. mCblk ? mCblk->serverIndex : 0
  1753. );
  1754. if (locked) {
  1755. mCblk->lock.unlock();
  1756. }
  1757. }
  1758. #undef LOG_TAG
  1759. #define LOG_TAG "AudioFlinger::EffectChain"
  1760. AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
  1761. audio_session_t sessionId)
  1762. : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
  1763. mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
  1764. mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
  1765. {
  1766. mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
  1767. if (thread == NULL) {
  1768. return;
  1769. }
  1770. mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
  1771. thread->frameCount();
  1772. }
  1773. AudioFlinger::EffectChain::~EffectChain()
  1774. {
  1775. }
  1776. // getEffectFromDesc_l() must be called with ThreadBase::mLock held
  1777. sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
  1778. effect_descriptor_t *descriptor)
  1779. {
  1780. size_t size = mEffects.size();
  1781. for (size_t i = 0; i < size; i++) {
  1782. if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
  1783. return mEffects[i];
  1784. }
  1785. }
  1786. return 0;
  1787. }
  1788. // getEffectFromId_l() must be called with ThreadBase::mLock held
  1789. sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
  1790. {
  1791. size_t size = mEffects.size();
  1792. for (size_t i = 0; i < size; i++) {
  1793. // by convention, return first effect if id provided is 0 (0 is never a valid id)
  1794. if (id == 0 || mEffects[i]->id() == id) {
  1795. return mEffects[i];
  1796. }
  1797. }
  1798. return 0;
  1799. }
  1800. // getEffectFromType_l() must be called with ThreadBase::mLock held
  1801. sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
  1802. const effect_uuid_t *type)
  1803. {
  1804. size_t size = mEffects.size();
  1805. for (size_t i = 0; i < size; i++) {
  1806. if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
  1807. return mEffects[i];
  1808. }
  1809. }
  1810. return 0;
  1811. }
  1812. std::vector<int> AudioFlinger::EffectChain::getEffectIds()
  1813. {
  1814. std::vector<int> ids;
  1815. Mutex::Autolock _l(mLock);
  1816. for (size_t i = 0; i < mEffects.size(); i++) {
  1817. ids.push_back(mEffects[i]->id());
  1818. }
  1819. return ids;
  1820. }
  1821. void AudioFlinger::EffectChain::clearInputBuffer()
  1822. {
  1823. Mutex::Autolock _l(mLock);
  1824. sp<ThreadBase> thread = mThread.promote();
  1825. if (thread == 0) {
  1826. ALOGW("clearInputBuffer(): cannot promote mixer thread");
  1827. return;
  1828. }
  1829. clearInputBuffer_l(thread);
  1830. }
  1831. // Must be called with EffectChain::mLock locked
  1832. void AudioFlinger::EffectChain::clearInputBuffer_l(const sp<ThreadBase>& thread)
  1833. {
  1834. if (mInBuffer == NULL) {
  1835. return;
  1836. }
  1837. const size_t frameSize =
  1838. audio_bytes_per_sample(EFFECT_BUFFER_FORMAT) * thread->channelCount();
  1839. memset(mInBuffer->audioBuffer()->raw, 0, thread->frameCount() * frameSize);
  1840. mInBuffer->commit();
  1841. }
  1842. // Must be called with EffectChain::mLock locked
  1843. void AudioFlinger::EffectChain::process_l()
  1844. {
  1845. sp<ThreadBase> thread = mThread.promote();
  1846. if (thread == 0) {
  1847. ALOGW("process_l(): cannot promote mixer thread");
  1848. return;
  1849. }
  1850. bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
  1851. (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
  1852. // never process effects when:
  1853. // - on an OFFLOAD thread
  1854. // - no more tracks are on the session and the effect tail has been rendered
  1855. bool doProcess = (thread->type() != ThreadBase::OFFLOAD)
  1856. && (thread->type() != ThreadBase::MMAP);
  1857. if (!isGlobalSession) {
  1858. bool tracksOnSession = (trackCnt() != 0);
  1859. if (!tracksOnSession && mTailBufferCount == 0) {
  1860. doProcess = false;
  1861. }
  1862. if (activeTrackCnt() == 0) {
  1863. // if no track is active and the effect tail has not been rendered,
  1864. // the input buffer must be cleared here as the mixer process will not do it
  1865. if (tracksOnSession || mTailBufferCount > 0) {
  1866. clearInputBuffer_l(thread);
  1867. if (mTailBufferCount > 0) {
  1868. mTailBufferCount--;
  1869. }
  1870. }
  1871. }
  1872. }
  1873. size_t size = mEffects.size();
  1874. if (doProcess) {
  1875. // Only the input and output buffers of the chain can be external,
  1876. // and 'update' / 'commit' do nothing for allocated buffers, thus
  1877. // it's not needed to consider any other buffers here.
  1878. mInBuffer->update();
  1879. if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
  1880. mOutBuffer->update();
  1881. }
  1882. for (size_t i = 0; i < size; i++) {
  1883. mEffects[i]->process();
  1884. }
  1885. mInBuffer->commit();
  1886. if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
  1887. mOutBuffer->commit();
  1888. }
  1889. }
  1890. bool doResetVolume = false;
  1891. for (size_t i = 0; i < size; i++) {
  1892. doResetVolume = mEffects[i]->updateState() || doResetVolume;
  1893. }
  1894. if (doResetVolume) {
  1895. resetVolume_l();
  1896. }
  1897. }
  1898. // createEffect_l() must be called with ThreadBase::mLock held
  1899. status_t AudioFlinger::EffectChain::createEffect_l(sp<EffectModule>& effect,
  1900. ThreadBase *thread,
  1901. effect_descriptor_t *desc,
  1902. int id,
  1903. audio_session_t sessionId,
  1904. bool pinned)
  1905. {
  1906. Mutex::Autolock _l(mLock);
  1907. effect = new EffectModule(thread, this, desc, id, sessionId, pinned);
  1908. status_t lStatus = effect->status();
  1909. if (lStatus == NO_ERROR) {
  1910. lStatus = addEffect_ll(effect);
  1911. }
  1912. if (lStatus != NO_ERROR) {
  1913. effect.clear();
  1914. }
  1915. return lStatus;
  1916. }
  1917. // addEffect_l() must be called with ThreadBase::mLock held
  1918. status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
  1919. {
  1920. Mutex::Autolock _l(mLock);
  1921. return addEffect_ll(effect);
  1922. }
  1923. // addEffect_l() must be called with ThreadBase::mLock and EffectChain::mLock held
  1924. status_t AudioFlinger::EffectChain::addEffect_ll(const sp<EffectModule>& effect)
  1925. {
  1926. effect_descriptor_t desc = effect->desc();
  1927. uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
  1928. effect->setChain(this);
  1929. sp<ThreadBase> thread = mThread.promote();
  1930. if (thread == 0) {
  1931. return NO_INIT;
  1932. }
  1933. effect->setThread(thread);
  1934. if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
  1935. // Auxiliary effects are inserted at the beginning of mEffects vector as
  1936. // they are processed first and accumulated in chain input buffer
  1937. mEffects.insertAt(effect, 0);
  1938. // the input buffer for auxiliary effect contains mono samples in
  1939. // 32 bit format. This is to avoid saturation in AudoMixer
  1940. // accumulation stage. Saturation is done in EffectModule::process() before
  1941. // calling the process in effect engine
  1942. size_t numSamples = thread->frameCount();
  1943. sp<EffectBufferHalInterface> halBuffer;
  1944. #ifdef FLOAT_EFFECT_CHAIN
  1945. status_t result = thread->mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
  1946. numSamples * sizeof(float), &halBuffer);
  1947. #else
  1948. status_t result = thread->mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
  1949. numSamples * sizeof(int32_t), &halBuffer);
  1950. #endif
  1951. if (result != OK) return result;
  1952. effect->setInBuffer(halBuffer);
  1953. // auxiliary effects output samples to chain input buffer for further processing
  1954. // by insert effects
  1955. effect->setOutBuffer(mInBuffer);
  1956. } else {
  1957. // Insert effects are inserted at the end of mEffects vector as they are processed
  1958. // after track and auxiliary effects.
  1959. // Insert effect order as a function of indicated preference:
  1960. // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
  1961. // another effect is present
  1962. // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
  1963. // last effect claiming first position
  1964. // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
  1965. // first effect claiming last position
  1966. // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
  1967. // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
  1968. // already present
  1969. size_t size = mEffects.size();
  1970. size_t idx_insert = size;
  1971. ssize_t idx_insert_first = -1;
  1972. ssize_t idx_insert_last = -1;
  1973. for (size_t i = 0; i < size; i++) {
  1974. effect_descriptor_t d = mEffects[i]->desc();
  1975. uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
  1976. uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
  1977. if (iMode == EFFECT_FLAG_TYPE_INSERT) {
  1978. // check invalid effect chaining combinations
  1979. if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
  1980. iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
  1981. ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
  1982. desc.name, d.name);
  1983. return INVALID_OPERATION;
  1984. }
  1985. // remember position of first insert effect and by default
  1986. // select this as insert position for new effect
  1987. if (idx_insert == size) {
  1988. idx_insert = i;
  1989. }
  1990. // remember position of last insert effect claiming
  1991. // first position
  1992. if (iPref == EFFECT_FLAG_INSERT_FIRST) {
  1993. idx_insert_first = i;
  1994. }
  1995. // remember position of first insert effect claiming
  1996. // last position
  1997. if (iPref == EFFECT_FLAG_INSERT_LAST &&
  1998. idx_insert_last == -1) {
  1999. idx_insert_last = i;
  2000. }
  2001. }
  2002. }
  2003. // modify idx_insert from first position if needed
  2004. if (insertPref == EFFECT_FLAG_INSERT_LAST) {
  2005. if (idx_insert_last != -1) {
  2006. idx_insert = idx_insert_last;
  2007. } else {
  2008. idx_insert = size;
  2009. }
  2010. } else {
  2011. if (idx_insert_first != -1) {
  2012. idx_insert = idx_insert_first + 1;
  2013. }
  2014. }
  2015. // always read samples from chain input buffer
  2016. effect->setInBuffer(mInBuffer);
  2017. // if last effect in the chain, output samples to chain
  2018. // output buffer, otherwise to chain input buffer
  2019. if (idx_insert == size) {
  2020. if (idx_insert != 0) {
  2021. mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
  2022. mEffects[idx_insert-1]->configure();
  2023. }
  2024. effect->setOutBuffer(mOutBuffer);
  2025. } else {
  2026. effect->setOutBuffer(mInBuffer);
  2027. }
  2028. mEffects.insertAt(effect, idx_insert);
  2029. ALOGV("addEffect_l() effect %p, added in chain %p at rank %zu", effect.get(), this,
  2030. idx_insert);
  2031. }
  2032. effect->configure();
  2033. return NO_ERROR;
  2034. }
  2035. // removeEffect_l() must be called with ThreadBase::mLock held
  2036. size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect,
  2037. bool release)
  2038. {
  2039. Mutex::Autolock _l(mLock);
  2040. size_t size = mEffects.size();
  2041. uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
  2042. for (size_t i = 0; i < size; i++) {
  2043. if (effect == mEffects[i]) {
  2044. // calling stop here will remove pre-processing effect from the audio HAL.
  2045. // This is safe as we hold the EffectChain mutex which guarantees that we are not in
  2046. // the middle of a read from audio HAL
  2047. if (mEffects[i]->state() == EffectModule::ACTIVE ||
  2048. mEffects[i]->state() == EffectModule::STOPPING) {
  2049. mEffects[i]->stop();
  2050. }
  2051. if (release) {
  2052. mEffects[i]->release_l();
  2053. }
  2054. if (type != EFFECT_FLAG_TYPE_AUXILIARY) {
  2055. if (i == size - 1 && i != 0) {
  2056. mEffects[i - 1]->setOutBuffer(mOutBuffer);
  2057. mEffects[i - 1]->configure();
  2058. }
  2059. }
  2060. mEffects.removeAt(i);
  2061. ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %zu", effect.get(),
  2062. this, i);
  2063. break;
  2064. }
  2065. }
  2066. return mEffects.size();
  2067. }
  2068. // setDevice_l() must be called with ThreadBase::mLock held
  2069. void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
  2070. {
  2071. size_t size = mEffects.size();
  2072. for (size_t i = 0; i < size; i++) {
  2073. mEffects[i]->setDevice(device);
  2074. }
  2075. }
  2076. // setMode_l() must be called with ThreadBase::mLock held
  2077. void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
  2078. {
  2079. size_t size = mEffects.size();
  2080. for (size_t i = 0; i < size; i++) {
  2081. mEffects[i]->setMode(mode);
  2082. }
  2083. }
  2084. // setAudioSource_l() must be called with ThreadBase::mLock held
  2085. void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
  2086. {
  2087. size_t size = mEffects.size();
  2088. for (size_t i = 0; i < size; i++) {
  2089. mEffects[i]->setAudioSource(source);
  2090. }
  2091. }
  2092. // setVolume_l() must be called with ThreadBase::mLock or EffectChain::mLock held
  2093. bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right, bool force)
  2094. {
  2095. uint32_t newLeft = *left;
  2096. uint32_t newRight = *right;
  2097. bool hasControl = false;
  2098. int ctrlIdx = -1;
  2099. size_t size = mEffects.size();
  2100. // first update volume controller
  2101. for (size_t i = size; i > 0; i--) {
  2102. if (mEffects[i - 1]->isVolumeControlEnabled()) {
  2103. ctrlIdx = i - 1;
  2104. hasControl = true;
  2105. break;
  2106. }
  2107. }
  2108. if (!force && ctrlIdx == mVolumeCtrlIdx &&
  2109. *left == mLeftVolume && *right == mRightVolume) {
  2110. if (hasControl) {
  2111. *left = mNewLeftVolume;
  2112. *right = mNewRightVolume;
  2113. }
  2114. return hasControl;
  2115. }
  2116. mVolumeCtrlIdx = ctrlIdx;
  2117. mLeftVolume = newLeft;
  2118. mRightVolume = newRight;
  2119. // second get volume update from volume controller
  2120. if (ctrlIdx >= 0) {
  2121. mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
  2122. mNewLeftVolume = newLeft;
  2123. mNewRightVolume = newRight;
  2124. }
  2125. // then indicate volume to all other effects in chain.
  2126. // Pass altered volume to effects before volume controller
  2127. // and requested volume to effects after controller or with volume monitor flag
  2128. uint32_t lVol = newLeft;
  2129. uint32_t rVol = newRight;
  2130. for (size_t i = 0; i < size; i++) {
  2131. if ((int)i == ctrlIdx) {
  2132. continue;
  2133. }
  2134. // this also works for ctrlIdx == -1 when there is no volume controller
  2135. if ((int)i > ctrlIdx) {
  2136. lVol = *left;
  2137. rVol = *right;
  2138. }
  2139. // Pass requested volume directly if this is volume monitor module
  2140. if (mEffects[i]->isVolumeMonitor()) {
  2141. mEffects[i]->setVolume(left, right, false);
  2142. } else {
  2143. mEffects[i]->setVolume(&lVol, &rVol, false);
  2144. }
  2145. }
  2146. *left = newLeft;
  2147. *right = newRight;
  2148. setVolumeForOutput_l(*left, *right);
  2149. return hasControl;
  2150. }
  2151. // resetVolume_l() must be called with ThreadBase::mLock or EffectChain::mLock held
  2152. void AudioFlinger::EffectChain::resetVolume_l()
  2153. {
  2154. if ((mLeftVolume != UINT_MAX) && (mRightVolume != UINT_MAX)) {
  2155. uint32_t left = mLeftVolume;
  2156. uint32_t right = mRightVolume;
  2157. (void)setVolume_l(&left, &right, true);
  2158. }
  2159. }
  2160. void AudioFlinger::EffectChain::syncHalEffectsState()
  2161. {
  2162. Mutex::Autolock _l(mLock);
  2163. for (size_t i = 0; i < mEffects.size(); i++) {
  2164. if (mEffects[i]->state() == EffectModule::ACTIVE ||
  2165. mEffects[i]->state() == EffectModule::STOPPING) {
  2166. mEffects[i]->addEffectToHal_l();
  2167. }
  2168. }
  2169. }
  2170. void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
  2171. {
  2172. String8 result;
  2173. const size_t numEffects = mEffects.size();
  2174. result.appendFormat(" %zu effects for session %d\n", numEffects, mSessionId);
  2175. if (numEffects) {
  2176. bool locked = AudioFlinger::dumpTryLock(mLock);
  2177. // failed to lock - AudioFlinger is probably deadlocked
  2178. if (!locked) {
  2179. result.append("\tCould not lock mutex:\n");
  2180. }
  2181. const std::string inBufferStr = dumpInOutBuffer(true /* isInput */, mInBuffer);
  2182. const std::string outBufferStr = dumpInOutBuffer(false /* isInput */, mOutBuffer);
  2183. result.appendFormat("\t%-*s%-*s Active tracks:\n",
  2184. (int)inBufferStr.size(), "In buffer ",
  2185. (int)outBufferStr.size(), "Out buffer ");
  2186. result.appendFormat("\t%s %s %d\n",
  2187. inBufferStr.c_str(), outBufferStr.c_str(), mActiveTrackCnt);
  2188. write(fd, result.string(), result.size());
  2189. for (size_t i = 0; i < numEffects; ++i) {
  2190. sp<EffectModule> effect = mEffects[i];
  2191. if (effect != 0) {
  2192. effect->dump(fd, args);
  2193. }
  2194. }
  2195. if (locked) {
  2196. mLock.unlock();
  2197. }
  2198. } else {
  2199. write(fd, result.string(), result.size());
  2200. }
  2201. }
  2202. // must be called with ThreadBase::mLock held
  2203. void AudioFlinger::EffectChain::setEffectSuspended_l(
  2204. const effect_uuid_t *type, bool suspend)
  2205. {
  2206. sp<SuspendedEffectDesc> desc;
  2207. // use effect type UUID timelow as key as there is no real risk of identical
  2208. // timeLow fields among effect type UUIDs.
  2209. ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
  2210. if (suspend) {
  2211. if (index >= 0) {
  2212. desc = mSuspendedEffects.valueAt(index);
  2213. } else {
  2214. desc = new SuspendedEffectDesc();
  2215. desc->mType = *type;
  2216. mSuspendedEffects.add(type->timeLow, desc);
  2217. ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
  2218. }
  2219. if (desc->mRefCount++ == 0) {
  2220. sp<EffectModule> effect = getEffectIfEnabled(type);
  2221. if (effect != 0) {
  2222. desc->mEffect = effect;
  2223. effect->setSuspended(true);
  2224. effect->setEnabled(false);
  2225. }
  2226. }
  2227. } else {
  2228. if (index < 0) {
  2229. return;
  2230. }
  2231. desc = mSuspendedEffects.valueAt(index);
  2232. if (desc->mRefCount <= 0) {
  2233. ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
  2234. desc->mRefCount = 0;
  2235. return;
  2236. }
  2237. if (--desc->mRefCount == 0) {
  2238. ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
  2239. if (desc->mEffect != 0) {
  2240. sp<EffectModule> effect = desc->mEffect.promote();
  2241. if (effect != 0) {
  2242. effect->setSuspended(false);
  2243. effect->lock();
  2244. EffectHandle *handle = effect->controlHandle_l();
  2245. if (handle != NULL && !handle->disconnected()) {
  2246. effect->setEnabled_l(handle->enabled());
  2247. }
  2248. effect->unlock();
  2249. }
  2250. desc->mEffect.clear();
  2251. }
  2252. mSuspendedEffects.removeItemsAt(index);
  2253. }
  2254. }
  2255. }
  2256. // must be called with ThreadBase::mLock held
  2257. void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
  2258. {
  2259. sp<SuspendedEffectDesc> desc;
  2260. ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
  2261. if (suspend) {
  2262. if (index >= 0) {
  2263. desc = mSuspendedEffects.valueAt(index);
  2264. } else {
  2265. desc = new SuspendedEffectDesc();
  2266. mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
  2267. ALOGV("setEffectSuspendedAll_l() add entry for 0");
  2268. }
  2269. if (desc->mRefCount++ == 0) {
  2270. Vector< sp<EffectModule> > effects;
  2271. getSuspendEligibleEffects(effects);
  2272. for (size_t i = 0; i < effects.size(); i++) {
  2273. setEffectSuspended_l(&effects[i]->desc().type, true);
  2274. }
  2275. }
  2276. } else {
  2277. if (index < 0) {
  2278. return;
  2279. }
  2280. desc = mSuspendedEffects.valueAt(index);
  2281. if (desc->mRefCount <= 0) {
  2282. ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
  2283. desc->mRefCount = 1;
  2284. }
  2285. if (--desc->mRefCount == 0) {
  2286. Vector<const effect_uuid_t *> types;
  2287. for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
  2288. if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
  2289. continue;
  2290. }
  2291. types.add(&mSuspendedEffects.valueAt(i)->mType);
  2292. }
  2293. for (size_t i = 0; i < types.size(); i++) {
  2294. setEffectSuspended_l(types[i], false);
  2295. }
  2296. ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
  2297. mSuspendedEffects.keyAt(index));
  2298. mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
  2299. }
  2300. }
  2301. }
  2302. // The volume effect is used for automated tests only
  2303. #ifndef OPENSL_ES_H_
  2304. static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
  2305. { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
  2306. const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
  2307. #endif //OPENSL_ES_H_
  2308. /* static */
  2309. bool AudioFlinger::EffectChain::isEffectEligibleForBtNrecSuspend(const effect_uuid_t *type)
  2310. {
  2311. // Only NS and AEC are suspended when BtNRec is off
  2312. if ((memcmp(type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) ||
  2313. (memcmp(type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
  2314. return true;
  2315. }
  2316. return false;
  2317. }
  2318. bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
  2319. {
  2320. // auxiliary effects and visualizer are never suspended on output mix
  2321. if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
  2322. (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
  2323. (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
  2324. (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0) ||
  2325. (memcmp(&desc.type, SL_IID_DYNAMICSPROCESSING, sizeof(effect_uuid_t)) == 0))) {
  2326. return false;
  2327. }
  2328. return true;
  2329. }
  2330. void AudioFlinger::EffectChain::getSuspendEligibleEffects(
  2331. Vector< sp<AudioFlinger::EffectModule> > &effects)
  2332. {
  2333. effects.clear();
  2334. for (size_t i = 0; i < mEffects.size(); i++) {
  2335. if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
  2336. effects.add(mEffects[i]);
  2337. }
  2338. }
  2339. }
  2340. sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
  2341. const effect_uuid_t *type)
  2342. {
  2343. sp<EffectModule> effect = getEffectFromType_l(type);
  2344. return effect != 0 && effect->isEnabled() ? effect : 0;
  2345. }
  2346. void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
  2347. bool enabled)
  2348. {
  2349. ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
  2350. if (enabled) {
  2351. if (index < 0) {
  2352. // if the effect is not suspend check if all effects are suspended
  2353. index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
  2354. if (index < 0) {
  2355. return;
  2356. }
  2357. if (!isEffectEligibleForSuspend(effect->desc())) {
  2358. return;
  2359. }
  2360. setEffectSuspended_l(&effect->desc().type, enabled);
  2361. index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
  2362. if (index < 0) {
  2363. ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
  2364. return;
  2365. }
  2366. }
  2367. ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
  2368. effect->desc().type.timeLow);
  2369. sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
  2370. // if effect is requested to suspended but was not yet enabled, suspend it now.
  2371. if (desc->mEffect == 0) {
  2372. desc->mEffect = effect;
  2373. effect->setEnabled(false);
  2374. effect->setSuspended(true);
  2375. }
  2376. } else {
  2377. if (index < 0) {
  2378. return;
  2379. }
  2380. ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
  2381. effect->desc().type.timeLow);
  2382. sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
  2383. desc->mEffect.clear();
  2384. effect->setSuspended(false);
  2385. }
  2386. }
  2387. bool AudioFlinger::EffectChain::isNonOffloadableEnabled()
  2388. {
  2389. Mutex::Autolock _l(mLock);
  2390. return isNonOffloadableEnabled_l();
  2391. }
  2392. bool AudioFlinger::EffectChain::isNonOffloadableEnabled_l()
  2393. {
  2394. size_t size = mEffects.size();
  2395. for (size_t i = 0; i < size; i++) {
  2396. if (mEffects[i]->isEnabled() && !mEffects[i]->isOffloadable()) {
  2397. return true;
  2398. }
  2399. }
  2400. return false;
  2401. }
  2402. void AudioFlinger::EffectChain::setThread(const sp<ThreadBase>& thread)
  2403. {
  2404. Mutex::Autolock _l(mLock);
  2405. mThread = thread;
  2406. for (size_t i = 0; i < mEffects.size(); i++) {
  2407. mEffects[i]->setThread(thread);
  2408. }
  2409. }
  2410. void AudioFlinger::EffectChain::checkOutputFlagCompatibility(audio_output_flags_t *flags) const
  2411. {
  2412. if ((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
  2413. *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
  2414. }
  2415. if ((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
  2416. *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
  2417. }
  2418. }
  2419. void AudioFlinger::EffectChain::checkInputFlagCompatibility(audio_input_flags_t *flags) const
  2420. {
  2421. if ((*flags & AUDIO_INPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
  2422. *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
  2423. }
  2424. if ((*flags & AUDIO_INPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
  2425. *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
  2426. }
  2427. }
  2428. bool AudioFlinger::EffectChain::isRawCompatible() const
  2429. {
  2430. Mutex::Autolock _l(mLock);
  2431. for (const auto &effect : mEffects) {
  2432. if (effect->isProcessImplemented()) {
  2433. return false;
  2434. }
  2435. }
  2436. // Allow effects without processing.
  2437. return true;
  2438. }
  2439. bool AudioFlinger::EffectChain::isFastCompatible() const
  2440. {
  2441. Mutex::Autolock _l(mLock);
  2442. for (const auto &effect : mEffects) {
  2443. if (effect->isProcessImplemented()
  2444. && effect->isImplementationSoftware()) {
  2445. return false;
  2446. }
  2447. }
  2448. // Allow effects without processing or hw accelerated effects.
  2449. return true;
  2450. }
  2451. // isCompatibleWithThread_l() must be called with thread->mLock held
  2452. bool AudioFlinger::EffectChain::isCompatibleWithThread_l(const sp<ThreadBase>& thread) const
  2453. {
  2454. Mutex::Autolock _l(mLock);
  2455. for (size_t i = 0; i < mEffects.size(); i++) {
  2456. if (thread->checkEffectCompatibility_l(&(mEffects[i]->desc()), mSessionId) != NO_ERROR) {
  2457. return false;
  2458. }
  2459. }
  2460. return true;
  2461. }
  2462. } // namespace android