Threads.h 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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. #ifndef INCLUDING_FROM_AUDIOFLINGER_H
  18. #error This header file should only be included from AudioFlinger.h
  19. #endif
  20. class ThreadBase : public Thread {
  21. public:
  22. #include "TrackBase.h"
  23. enum type_t {
  24. MIXER, // Thread class is MixerThread
  25. DIRECT, // Thread class is DirectOutputThread
  26. DUPLICATING, // Thread class is DuplicatingThread
  27. RECORD, // Thread class is RecordThread
  28. OFFLOAD, // Thread class is OffloadThread
  29. MMAP // control thread for MMAP stream
  30. // If you add any values here, also update ThreadBase::threadTypeToString()
  31. };
  32. static const char *threadTypeToString(type_t type);
  33. ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
  34. audio_devices_t outDevice, audio_devices_t inDevice, type_t type,
  35. bool systemReady);
  36. virtual ~ThreadBase();
  37. virtual status_t readyToRun();
  38. void clearPowerManager();
  39. // base for record and playback
  40. enum {
  41. CFG_EVENT_IO,
  42. CFG_EVENT_PRIO,
  43. CFG_EVENT_SET_PARAMETER,
  44. CFG_EVENT_CREATE_AUDIO_PATCH,
  45. CFG_EVENT_RELEASE_AUDIO_PATCH,
  46. };
  47. class ConfigEventData: public RefBase {
  48. public:
  49. virtual ~ConfigEventData() {}
  50. virtual void dump(char *buffer, size_t size) = 0;
  51. protected:
  52. ConfigEventData() {}
  53. };
  54. // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
  55. // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
  56. // 2. Lock mLock
  57. // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
  58. // 4. sendConfigEvent_l() reads status from event->mStatus;
  59. // 5. sendConfigEvent_l() returns status
  60. // 6. Unlock
  61. //
  62. // Parameter sequence by server: threadLoop calling processConfigEvents_l():
  63. // 1. Lock mLock
  64. // 2. If there is an entry in mConfigEvents proceed ...
  65. // 3. Read first entry in mConfigEvents
  66. // 4. Remove first entry from mConfigEvents
  67. // 5. Process
  68. // 6. Set event->mStatus
  69. // 7. event->mCond.signal
  70. // 8. Unlock
  71. class ConfigEvent: public RefBase {
  72. public:
  73. virtual ~ConfigEvent() {}
  74. void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
  75. const int mType; // event type e.g. CFG_EVENT_IO
  76. Mutex mLock; // mutex associated with mCond
  77. Condition mCond; // condition for status return
  78. status_t mStatus; // status communicated to sender
  79. bool mWaitStatus; // true if sender is waiting for status
  80. bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
  81. sp<ConfigEventData> mData; // event specific parameter data
  82. protected:
  83. explicit ConfigEvent(int type, bool requiresSystemReady = false) :
  84. mType(type), mStatus(NO_ERROR), mWaitStatus(false),
  85. mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
  86. };
  87. class IoConfigEventData : public ConfigEventData {
  88. public:
  89. IoConfigEventData(audio_io_config_event event, pid_t pid,
  90. audio_port_handle_t portId) :
  91. mEvent(event), mPid(pid), mPortId(portId) {}
  92. virtual void dump(char *buffer, size_t size) {
  93. snprintf(buffer, size, "IO event: event %d\n", mEvent);
  94. }
  95. const audio_io_config_event mEvent;
  96. const pid_t mPid;
  97. const audio_port_handle_t mPortId;
  98. };
  99. class IoConfigEvent : public ConfigEvent {
  100. public:
  101. IoConfigEvent(audio_io_config_event event, pid_t pid, audio_port_handle_t portId) :
  102. ConfigEvent(CFG_EVENT_IO) {
  103. mData = new IoConfigEventData(event, pid, portId);
  104. }
  105. virtual ~IoConfigEvent() {}
  106. };
  107. class PrioConfigEventData : public ConfigEventData {
  108. public:
  109. PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
  110. mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
  111. virtual void dump(char *buffer, size_t size) {
  112. snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d, for app? %d\n",
  113. mPid, mTid, mPrio, mForApp);
  114. }
  115. const pid_t mPid;
  116. const pid_t mTid;
  117. const int32_t mPrio;
  118. const bool mForApp;
  119. };
  120. class PrioConfigEvent : public ConfigEvent {
  121. public:
  122. PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
  123. ConfigEvent(CFG_EVENT_PRIO, true) {
  124. mData = new PrioConfigEventData(pid, tid, prio, forApp);
  125. }
  126. virtual ~PrioConfigEvent() {}
  127. };
  128. class SetParameterConfigEventData : public ConfigEventData {
  129. public:
  130. explicit SetParameterConfigEventData(String8 keyValuePairs) :
  131. mKeyValuePairs(keyValuePairs) {}
  132. virtual void dump(char *buffer, size_t size) {
  133. snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
  134. }
  135. const String8 mKeyValuePairs;
  136. };
  137. class SetParameterConfigEvent : public ConfigEvent {
  138. public:
  139. explicit SetParameterConfigEvent(String8 keyValuePairs) :
  140. ConfigEvent(CFG_EVENT_SET_PARAMETER) {
  141. mData = new SetParameterConfigEventData(keyValuePairs);
  142. mWaitStatus = true;
  143. }
  144. virtual ~SetParameterConfigEvent() {}
  145. };
  146. class CreateAudioPatchConfigEventData : public ConfigEventData {
  147. public:
  148. CreateAudioPatchConfigEventData(const struct audio_patch patch,
  149. audio_patch_handle_t handle) :
  150. mPatch(patch), mHandle(handle) {}
  151. virtual void dump(char *buffer, size_t size) {
  152. snprintf(buffer, size, "Patch handle: %u\n", mHandle);
  153. }
  154. const struct audio_patch mPatch;
  155. audio_patch_handle_t mHandle;
  156. };
  157. class CreateAudioPatchConfigEvent : public ConfigEvent {
  158. public:
  159. CreateAudioPatchConfigEvent(const struct audio_patch patch,
  160. audio_patch_handle_t handle) :
  161. ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
  162. mData = new CreateAudioPatchConfigEventData(patch, handle);
  163. mWaitStatus = true;
  164. }
  165. virtual ~CreateAudioPatchConfigEvent() {}
  166. };
  167. class ReleaseAudioPatchConfigEventData : public ConfigEventData {
  168. public:
  169. explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
  170. mHandle(handle) {}
  171. virtual void dump(char *buffer, size_t size) {
  172. snprintf(buffer, size, "Patch handle: %u\n", mHandle);
  173. }
  174. audio_patch_handle_t mHandle;
  175. };
  176. class ReleaseAudioPatchConfigEvent : public ConfigEvent {
  177. public:
  178. explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
  179. ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
  180. mData = new ReleaseAudioPatchConfigEventData(handle);
  181. mWaitStatus = true;
  182. }
  183. virtual ~ReleaseAudioPatchConfigEvent() {}
  184. };
  185. class PMDeathRecipient : public IBinder::DeathRecipient {
  186. public:
  187. explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
  188. virtual ~PMDeathRecipient() {}
  189. // IBinder::DeathRecipient
  190. virtual void binderDied(const wp<IBinder>& who);
  191. private:
  192. DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
  193. wp<ThreadBase> mThread;
  194. };
  195. virtual status_t initCheck() const = 0;
  196. // static externally-visible
  197. type_t type() const { return mType; }
  198. bool isDuplicating() const { return (mType == DUPLICATING); }
  199. audio_io_handle_t id() const { return mId;}
  200. // dynamic externally-visible
  201. uint32_t sampleRate() const { return mSampleRate; }
  202. audio_channel_mask_t channelMask() const { return mChannelMask; }
  203. audio_format_t format() const { return mHALFormat; }
  204. uint32_t channelCount() const { return mChannelCount; }
  205. // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
  206. // and returns the [normal mix] buffer's frame count.
  207. virtual size_t frameCount() const = 0;
  208. // Return's the HAL's frame count i.e. fast mixer buffer size.
  209. size_t frameCountHAL() const { return mFrameCount; }
  210. size_t frameSize() const { return mFrameSize; }
  211. // Should be "virtual status_t requestExitAndWait()" and override same
  212. // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
  213. void exit();
  214. virtual bool checkForNewParameter_l(const String8& keyValuePair,
  215. status_t& status) = 0;
  216. virtual status_t setParameters(const String8& keyValuePairs);
  217. virtual String8 getParameters(const String8& keys) = 0;
  218. virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0,
  219. audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) = 0;
  220. // sendConfigEvent_l() must be called with ThreadBase::mLock held
  221. // Can temporarily release the lock if waiting for a reply from
  222. // processConfigEvents_l().
  223. status_t sendConfigEvent_l(sp<ConfigEvent>& event);
  224. void sendIoConfigEvent(audio_io_config_event event, pid_t pid = 0,
  225. audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
  226. void sendIoConfigEvent_l(audio_io_config_event event, pid_t pid = 0,
  227. audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
  228. void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp);
  229. void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp);
  230. status_t sendSetParameterConfigEvent_l(const String8& keyValuePair);
  231. status_t sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
  232. audio_patch_handle_t *handle);
  233. status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
  234. void processConfigEvents_l();
  235. virtual void cacheParameters_l() = 0;
  236. virtual status_t createAudioPatch_l(const struct audio_patch *patch,
  237. audio_patch_handle_t *handle) = 0;
  238. virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
  239. virtual void toAudioPortConfig(struct audio_port_config *config) = 0;
  240. // see note at declaration of mStandby, mOutDevice and mInDevice
  241. bool standby() const { return mStandby; }
  242. audio_devices_t outDevice() const { return mOutDevice; }
  243. audio_devices_t inDevice() const { return mInDevice; }
  244. audio_devices_t getDevice() const { return isOutput() ? mOutDevice : mInDevice; }
  245. virtual bool isOutput() const = 0;
  246. virtual sp<StreamHalInterface> stream() const = 0;
  247. sp<EffectHandle> createEffect_l(
  248. const sp<AudioFlinger::Client>& client,
  249. const sp<IEffectClient>& effectClient,
  250. int32_t priority,
  251. audio_session_t sessionId,
  252. effect_descriptor_t *desc,
  253. int *enabled,
  254. status_t *status /*non-NULL*/,
  255. bool pinned);
  256. // return values for hasAudioSession (bit field)
  257. enum effect_state {
  258. EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
  259. // effect
  260. TRACK_SESSION = 0x2, // the audio session corresponds to at least one
  261. // track
  262. FAST_SESSION = 0x4 // the audio session corresponds to at least one
  263. // fast track
  264. };
  265. // get effect chain corresponding to session Id.
  266. sp<EffectChain> getEffectChain(audio_session_t sessionId);
  267. // same as getEffectChain() but must be called with ThreadBase mutex locked
  268. sp<EffectChain> getEffectChain_l(audio_session_t sessionId) const;
  269. std::vector<int> getEffectIds_l(audio_session_t sessionId);
  270. // add an effect chain to the chain list (mEffectChains)
  271. virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
  272. // remove an effect chain from the chain list (mEffectChains)
  273. virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
  274. // lock all effect chains Mutexes. Must be called before releasing the
  275. // ThreadBase mutex before processing the mixer and effects. This guarantees the
  276. // integrity of the chains during the process.
  277. // Also sets the parameter 'effectChains' to current value of mEffectChains.
  278. void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
  279. // unlock effect chains after process
  280. void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
  281. // get a copy of mEffectChains vector
  282. Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
  283. // set audio mode to all effect chains
  284. void setMode(audio_mode_t mode);
  285. // get effect module with corresponding ID on specified audio session
  286. sp<AudioFlinger::EffectModule> getEffect(audio_session_t sessionId, int effectId);
  287. sp<AudioFlinger::EffectModule> getEffect_l(audio_session_t sessionId, int effectId);
  288. // add and effect module. Also creates the effect chain is none exists for
  289. // the effects audio session. Only called in a context of moving an effect
  290. // from one thread to another
  291. status_t addEffect_l(const sp< EffectModule>& effect);
  292. // remove and effect module. Also removes the effect chain is this was the last
  293. // effect
  294. void removeEffect_l(const sp< EffectModule>& effect, bool release = false);
  295. // disconnect an effect handle from module and destroy module if last handle
  296. void disconnectEffectHandle(EffectHandle *handle, bool unpinIfLast);
  297. // detach all tracks connected to an auxiliary effect
  298. virtual void detachAuxEffect_l(int effectId __unused) {}
  299. // returns a combination of:
  300. // - EFFECT_SESSION if effects on this audio session exist in one chain
  301. // - TRACK_SESSION if tracks on this audio session exist
  302. // - FAST_SESSION if fast tracks on this audio session exist
  303. virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const = 0;
  304. uint32_t hasAudioSession(audio_session_t sessionId) const {
  305. Mutex::Autolock _l(mLock);
  306. return hasAudioSession_l(sessionId);
  307. }
  308. template <typename T>
  309. uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
  310. uint32_t result = 0;
  311. if (getEffectChain_l(sessionId) != 0) {
  312. result = EFFECT_SESSION;
  313. }
  314. for (size_t i = 0; i < tracks.size(); ++i) {
  315. const sp<TrackBase>& track = tracks[i];
  316. if (sessionId == track->sessionId()
  317. && !track->isInvalid() // not yet removed from tracks.
  318. && !track->isTerminated()) {
  319. result |= TRACK_SESSION;
  320. if (track->isFastTrack()) {
  321. result |= FAST_SESSION; // caution, only represents first track.
  322. }
  323. break;
  324. }
  325. }
  326. return result;
  327. }
  328. // the value returned by default implementation is not important as the
  329. // strategy is only meaningful for PlaybackThread which implements this method
  330. virtual uint32_t getStrategyForSession_l(audio_session_t sessionId __unused)
  331. { return 0; }
  332. // check if some effects must be suspended/restored when an effect is enabled
  333. // or disabled
  334. void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
  335. bool enabled,
  336. audio_session_t sessionId =
  337. AUDIO_SESSION_OUTPUT_MIX);
  338. void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
  339. bool enabled,
  340. audio_session_t sessionId =
  341. AUDIO_SESSION_OUTPUT_MIX);
  342. virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
  343. virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
  344. // Return a reference to a per-thread heap which can be used to allocate IMemory
  345. // objects that will be read-only to client processes, read/write to mediaserver,
  346. // and shared by all client processes of the thread.
  347. // The heap is per-thread rather than common across all threads, because
  348. // clients can't be trusted not to modify the offset of the IMemory they receive.
  349. // If a thread does not have such a heap, this method returns 0.
  350. virtual sp<MemoryDealer> readOnlyHeap() const { return 0; }
  351. virtual sp<IMemory> pipeMemory() const { return 0; }
  352. void systemReady();
  353. // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
  354. virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
  355. audio_session_t sessionId) = 0;
  356. void broadcast_l();
  357. virtual bool isTimestampCorrectionEnabled() const { return false; }
  358. bool isMsdDevice() const { return mIsMsdDevice; }
  359. void dump(int fd, const Vector<String16>& args);
  360. // deliver stats to mediametrics.
  361. void sendStatistics(bool force);
  362. mutable Mutex mLock;
  363. protected:
  364. // entry describing an effect being suspended in mSuspendedSessions keyed vector
  365. class SuspendedSessionDesc : public RefBase {
  366. public:
  367. SuspendedSessionDesc() : mRefCount(0) {}
  368. int mRefCount; // number of active suspend requests
  369. effect_uuid_t mType; // effect type UUID
  370. };
  371. void acquireWakeLock();
  372. virtual void acquireWakeLock_l();
  373. void releaseWakeLock();
  374. void releaseWakeLock_l();
  375. void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
  376. void getPowerManager_l();
  377. // suspend or restore effects of the specified type (or all if type is NULL)
  378. // on a given session. The number of suspend requests is counted and restore
  379. // occurs when all suspend requests are cancelled.
  380. void setEffectSuspended_l(const effect_uuid_t *type,
  381. bool suspend,
  382. audio_session_t sessionId);
  383. // updated mSuspendedSessions when an effect is suspended or restored
  384. void updateSuspendedSessions_l(const effect_uuid_t *type,
  385. bool suspend,
  386. audio_session_t sessionId);
  387. // check if some effects must be suspended when an effect chain is added
  388. void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
  389. // sends the metadata of the active tracks to the HAL
  390. virtual void updateMetadata_l() = 0;
  391. String16 getWakeLockTag();
  392. virtual void preExit() { }
  393. virtual void setMasterMono_l(bool mono __unused) { }
  394. virtual bool requireMonoBlend() { return false; }
  395. // called within the threadLoop to obtain timestamp from the HAL.
  396. virtual status_t threadloop_getHalTimestamp_l(
  397. ExtendedTimestamp *timestamp __unused) const {
  398. return INVALID_OPERATION;
  399. }
  400. virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
  401. { }
  402. virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
  403. friend class AudioFlinger; // for mEffectChains
  404. const type_t mType;
  405. // Used by parameters, config events, addTrack_l, exit
  406. Condition mWaitWorkCV;
  407. const sp<AudioFlinger> mAudioFlinger;
  408. // updated by PlaybackThread::readOutputParameters_l() or
  409. // RecordThread::readInputParameters_l()
  410. uint32_t mSampleRate;
  411. size_t mFrameCount; // output HAL, direct output, record
  412. audio_channel_mask_t mChannelMask;
  413. uint32_t mChannelCount;
  414. size_t mFrameSize;
  415. // not HAL frame size, this is for output sink (to pipe to fast mixer)
  416. audio_format_t mFormat; // Source format for Recording and
  417. // Sink format for Playback.
  418. // Sink format may be different than
  419. // HAL format if Fastmixer is used.
  420. audio_format_t mHALFormat;
  421. size_t mBufferSize; // HAL buffer size for read() or write()
  422. Vector< sp<ConfigEvent> > mConfigEvents;
  423. Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
  424. // These fields are written and read by thread itself without lock or barrier,
  425. // and read by other threads without lock or barrier via standby(), outDevice()
  426. // and inDevice().
  427. // Because of the absence of a lock or barrier, any other thread that reads
  428. // these fields must use the information in isolation, or be prepared to deal
  429. // with possibility that it might be inconsistent with other information.
  430. bool mStandby; // Whether thread is currently in standby.
  431. audio_devices_t mOutDevice; // output device
  432. audio_devices_t mInDevice; // input device
  433. audio_devices_t mPrevOutDevice; // previous output device
  434. audio_devices_t mPrevInDevice; // previous input device
  435. struct audio_patch mPatch;
  436. /**
  437. * @brief mDeviceId current device port unique identifier
  438. */
  439. audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
  440. audio_source_t mAudioSource;
  441. const audio_io_handle_t mId;
  442. Vector< sp<EffectChain> > mEffectChains;
  443. static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
  444. char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
  445. sp<IPowerManager> mPowerManager;
  446. sp<IBinder> mWakeLockToken;
  447. const sp<PMDeathRecipient> mDeathRecipient;
  448. // list of suspended effects per session and per type. The first (outer) vector is
  449. // keyed by session ID, the second (inner) by type UUID timeLow field
  450. // Updated by updateSuspendedSessions_l() only.
  451. KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
  452. mSuspendedSessions;
  453. // TODO: add comment and adjust size as needed
  454. static const size_t kLogSize = 4 * 1024;
  455. sp<NBLog::Writer> mNBLogWriter;
  456. bool mSystemReady;
  457. ExtendedTimestamp mTimestamp;
  458. TimestampVerifier< // For timestamp statistics.
  459. int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
  460. audio_devices_t mTimestampCorrectedDevices = AUDIO_DEVICE_NONE;
  461. // ThreadLoop statistics per iteration.
  462. int64_t mLastIoBeginNs = -1;
  463. int64_t mLastIoEndNs = -1;
  464. // This should be read under ThreadBase lock (if not on the threadLoop thread).
  465. audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
  466. audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
  467. audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
  468. // Save the last count when we delivered statistics to mediametrics.
  469. int64_t mLastRecordedTimestampVerifierN = 0;
  470. int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
  471. bool mIsMsdDevice = false;
  472. // A condition that must be evaluated by the thread loop has changed and
  473. // we must not wait for async write callback in the thread loop before evaluating it
  474. bool mSignalPending;
  475. #ifdef TEE_SINK
  476. NBAIO_Tee mTee;
  477. #endif
  478. // ActiveTracks is a sorted vector of track type T representing the
  479. // active tracks of threadLoop() to be considered by the locked prepare portion.
  480. // ActiveTracks should be accessed with the ThreadBase lock held.
  481. //
  482. // During processing and I/O, the threadLoop does not hold the lock;
  483. // hence it does not directly use ActiveTracks. Care should be taken
  484. // to hold local strong references or defer removal of tracks
  485. // if the threadLoop may still be accessing those tracks due to mix, etc.
  486. //
  487. // This class updates power information appropriately.
  488. //
  489. template <typename T>
  490. class ActiveTracks {
  491. public:
  492. explicit ActiveTracks(SimpleLog *localLog = nullptr)
  493. : mActiveTracksGeneration(0)
  494. , mLastActiveTracksGeneration(0)
  495. , mLocalLog(localLog)
  496. { }
  497. ~ActiveTracks() {
  498. ALOGW_IF(!mActiveTracks.isEmpty(),
  499. "ActiveTracks should be empty in destructor");
  500. }
  501. // returns the last track added (even though it may have been
  502. // subsequently removed from ActiveTracks).
  503. //
  504. // Used for DirectOutputThread to ensure a flush is called when transitioning
  505. // to a new track (even though it may be on the same session).
  506. // Used for OffloadThread to ensure that volume and mixer state is
  507. // taken from the latest track added.
  508. //
  509. // The latest track is saved with a weak pointer to prevent keeping an
  510. // otherwise useless track alive. Thus the function will return nullptr
  511. // if the latest track has subsequently been removed and destroyed.
  512. sp<T> getLatest() {
  513. return mLatestActiveTrack.promote();
  514. }
  515. // SortedVector methods
  516. ssize_t add(const sp<T> &track);
  517. ssize_t remove(const sp<T> &track);
  518. size_t size() const {
  519. return mActiveTracks.size();
  520. }
  521. bool isEmpty() const {
  522. return mActiveTracks.isEmpty();
  523. }
  524. ssize_t indexOf(const sp<T>& item) {
  525. return mActiveTracks.indexOf(item);
  526. }
  527. sp<T> operator[](size_t index) const {
  528. return mActiveTracks[index];
  529. }
  530. typename SortedVector<sp<T>>::iterator begin() {
  531. return mActiveTracks.begin();
  532. }
  533. typename SortedVector<sp<T>>::iterator end() {
  534. return mActiveTracks.end();
  535. }
  536. // Due to Binder recursion optimization, clear() and updatePowerState()
  537. // cannot be called from a Binder thread because they may call back into
  538. // the original calling process (system server) for BatteryNotifier
  539. // (which requires a Java environment that may not be present).
  540. // Hence, call clear() and updatePowerState() only from the
  541. // ThreadBase thread.
  542. void clear();
  543. // periodically called in the threadLoop() to update power state uids.
  544. void updatePowerState(sp<ThreadBase> thread, bool force = false);
  545. /** @return true if one or move active tracks was added or removed since the
  546. * last time this function was called or the vector was created. */
  547. bool readAndClearHasChanged();
  548. private:
  549. void logTrack(const char *funcName, const sp<T> &track) const;
  550. SortedVector<uid_t> getWakeLockUids() {
  551. SortedVector<uid_t> wakeLockUids;
  552. for (const sp<T> &track : mActiveTracks) {
  553. wakeLockUids.add(track->uid());
  554. }
  555. return wakeLockUids; // moved by underlying SharedBuffer
  556. }
  557. std::map<uid_t, std::pair<ssize_t /* previous */, ssize_t /* current */>>
  558. mBatteryCounter;
  559. SortedVector<sp<T>> mActiveTracks;
  560. int mActiveTracksGeneration;
  561. int mLastActiveTracksGeneration;
  562. wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
  563. SimpleLog * const mLocalLog;
  564. // If the vector has changed since last call to readAndClearHasChanged
  565. bool mHasChanged = false;
  566. };
  567. SimpleLog mLocalLog;
  568. private:
  569. void dumpBase_l(int fd, const Vector<String16>& args);
  570. void dumpEffectChains_l(int fd, const Vector<String16>& args);
  571. };
  572. class VolumeInterface {
  573. public:
  574. virtual ~VolumeInterface() {}
  575. virtual void setMasterVolume(float value) = 0;
  576. virtual void setMasterMute(bool muted) = 0;
  577. virtual void setStreamVolume(audio_stream_type_t stream, float value) = 0;
  578. virtual void setStreamMute(audio_stream_type_t stream, bool muted) = 0;
  579. virtual float streamVolume(audio_stream_type_t stream) const = 0;
  580. };
  581. // --- PlaybackThread ---
  582. class PlaybackThread : public ThreadBase, public StreamOutHalInterfaceCallback,
  583. public VolumeInterface {
  584. public:
  585. #include "PlaybackTracks.h"
  586. enum mixer_state {
  587. MIXER_IDLE, // no active tracks
  588. MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
  589. MIXER_TRACKS_READY, // at least one active track, and at least one track has data
  590. MIXER_DRAIN_TRACK, // drain currently playing track
  591. MIXER_DRAIN_ALL, // fully drain the hardware
  592. // standby mode does not have an enum value
  593. // suspend by audio policy manager is orthogonal to mixer state
  594. };
  595. // retry count before removing active track in case of underrun on offloaded thread:
  596. // we need to make sure that AudioTrack client has enough time to send large buffers
  597. //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
  598. // handled for offloaded tracks
  599. static const int8_t kMaxTrackRetriesOffload = 20;
  600. static const int8_t kMaxTrackStartupRetriesOffload = 100;
  601. static const int8_t kMaxTrackStopRetriesOffload = 2;
  602. static constexpr uint32_t kMaxTracksPerUid = 40;
  603. static constexpr size_t kMaxTracks = 256;
  604. // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
  605. // if delay is greater, the estimated time for timeLoopNextNs is reset.
  606. // This allows for catch-up to be done for small delays, while resetting the estimate
  607. // for initial conditions or large delays.
  608. static const nsecs_t kMaxNextBufferDelayNs = 100000000;
  609. PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
  610. audio_io_handle_t id, audio_devices_t device, type_t type, bool systemReady);
  611. virtual ~PlaybackThread();
  612. // Thread virtuals
  613. virtual bool threadLoop();
  614. // RefBase
  615. virtual void onFirstRef();
  616. virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
  617. audio_session_t sessionId);
  618. protected:
  619. // Code snippets that were lifted up out of threadLoop()
  620. virtual void threadLoop_mix() = 0;
  621. virtual void threadLoop_sleepTime() = 0;
  622. virtual ssize_t threadLoop_write();
  623. virtual void threadLoop_drain();
  624. virtual void threadLoop_standby();
  625. virtual void threadLoop_exit();
  626. virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
  627. // prepareTracks_l reads and writes mActiveTracks, and returns
  628. // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
  629. // is responsible for clearing or destroying this Vector later on, when it
  630. // is safe to do so. That will drop the final ref count and destroy the tracks.
  631. virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
  632. void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
  633. status_t handleVoipVolume_l(float *volume);
  634. // StreamOutHalInterfaceCallback implementation
  635. virtual void onWriteReady();
  636. virtual void onDrainReady();
  637. virtual void onError();
  638. void resetWriteBlocked(uint32_t sequence);
  639. void resetDraining(uint32_t sequence);
  640. virtual bool waitingAsyncCallback();
  641. virtual bool waitingAsyncCallback_l();
  642. virtual bool shouldStandby_l();
  643. virtual void onAddNewTrack_l();
  644. void onAsyncError(); // error reported by AsyncCallbackThread
  645. // ThreadBase virtuals
  646. virtual void preExit();
  647. virtual bool keepWakeLock() const { return true; }
  648. virtual void acquireWakeLock_l() {
  649. ThreadBase::acquireWakeLock_l();
  650. mActiveTracks.updatePowerState(this, true /* force */);
  651. }
  652. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  653. void dumpTracks_l(int fd, const Vector<String16>& args) override;
  654. public:
  655. virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
  656. // return estimated latency in milliseconds, as reported by HAL
  657. uint32_t latency() const;
  658. // same, but lock must already be held
  659. uint32_t latency_l() const;
  660. // VolumeInterface
  661. virtual void setMasterVolume(float value);
  662. virtual void setMasterBalance(float balance);
  663. virtual void setMasterMute(bool muted);
  664. virtual void setStreamVolume(audio_stream_type_t stream, float value);
  665. virtual void setStreamMute(audio_stream_type_t stream, bool muted);
  666. virtual float streamVolume(audio_stream_type_t stream) const;
  667. void setVolumeForOutput_l(float left, float right) const;
  668. sp<Track> createTrack_l(
  669. const sp<AudioFlinger::Client>& client,
  670. audio_stream_type_t streamType,
  671. const audio_attributes_t& attr,
  672. uint32_t *sampleRate,
  673. audio_format_t format,
  674. audio_channel_mask_t channelMask,
  675. size_t *pFrameCount,
  676. size_t *pNotificationFrameCount,
  677. uint32_t notificationsPerBuffer,
  678. float speed,
  679. const sp<IMemory>& sharedBuffer,
  680. audio_session_t sessionId,
  681. audio_output_flags_t *flags,
  682. pid_t creatorPid,
  683. pid_t tid,
  684. uid_t uid,
  685. status_t *status /*non-NULL*/,
  686. audio_port_handle_t portId);
  687. AudioStreamOut* getOutput() const;
  688. AudioStreamOut* clearOutput();
  689. virtual sp<StreamHalInterface> stream() const;
  690. // a very large number of suspend() will eventually wraparound, but unlikely
  691. void suspend() { (void) android_atomic_inc(&mSuspended); }
  692. void restore()
  693. {
  694. // if restore() is done without suspend(), get back into
  695. // range so that the next suspend() will operate correctly
  696. if (android_atomic_dec(&mSuspended) <= 0) {
  697. android_atomic_release_store(0, &mSuspended);
  698. }
  699. }
  700. bool isSuspended() const
  701. { return android_atomic_acquire_load(&mSuspended) > 0; }
  702. virtual String8 getParameters(const String8& keys);
  703. virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0,
  704. audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
  705. status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
  706. // Consider also removing and passing an explicit mMainBuffer initialization
  707. // parameter to AF::PlaybackThread::Track::Track().
  708. effect_buffer_t *sinkBuffer() const {
  709. return reinterpret_cast<effect_buffer_t *>(mSinkBuffer); };
  710. virtual void detachAuxEffect_l(int effectId);
  711. status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track>& track,
  712. int EffectId);
  713. status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track>& track,
  714. int EffectId);
  715. virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
  716. virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
  717. uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
  718. return ThreadBase::hasAudioSession_l(sessionId, mTracks);
  719. }
  720. virtual uint32_t getStrategyForSession_l(audio_session_t sessionId);
  721. virtual status_t setSyncEvent(const sp<SyncEvent>& event);
  722. virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
  723. // called with AudioFlinger lock held
  724. bool invalidateTracks_l(audio_stream_type_t streamType);
  725. virtual void invalidateTracks(audio_stream_type_t streamType);
  726. virtual size_t frameCount() const { return mNormalFrameCount; }
  727. status_t getTimestamp_l(AudioTimestamp& timestamp);
  728. void addPatchTrack(const sp<PatchTrack>& track);
  729. void deletePatchTrack(const sp<PatchTrack>& track);
  730. virtual void toAudioPortConfig(struct audio_port_config *config);
  731. // Return the asynchronous signal wait time.
  732. virtual int64_t computeWaitTimeNs_l() const { return INT64_MAX; }
  733. virtual bool isOutput() const override { return true; }
  734. // returns true if the track is allowed to be added to the thread.
  735. virtual bool isTrackAllowed_l(
  736. audio_channel_mask_t channelMask __unused,
  737. audio_format_t format __unused,
  738. audio_session_t sessionId __unused,
  739. uid_t uid) const {
  740. return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
  741. && mTracks.size() < PlaybackThread::kMaxTracks;
  742. }
  743. bool isTimestampCorrectionEnabled() const override {
  744. const audio_devices_t device =
  745. mOutDevice & mTimestampCorrectedDevices;
  746. return audio_is_output_devices(device) && popcount(device) > 0;
  747. }
  748. protected:
  749. // updated by readOutputParameters_l()
  750. size_t mNormalFrameCount; // normal mixer and effects
  751. bool mThreadThrottle; // throttle the thread processing
  752. uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
  753. uint32_t mThreadThrottleEndMs; // notify once per throttling
  754. uint32_t mHalfBufferMs; // half the buffer size in milliseconds
  755. void* mSinkBuffer; // frame size aligned sink buffer
  756. // TODO:
  757. // Rearrange the buffer info into a struct/class with
  758. // clear, copy, construction, destruction methods.
  759. //
  760. // mSinkBuffer also has associated with it:
  761. //
  762. // mSinkBufferSize: Sink Buffer Size
  763. // mFormat: Sink Buffer Format
  764. // Mixer Buffer (mMixerBuffer*)
  765. //
  766. // In the case of floating point or multichannel data, which is not in the
  767. // sink format, it is required to accumulate in a higher precision or greater channel count
  768. // buffer before downmixing or data conversion to the sink buffer.
  769. // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
  770. bool mMixerBufferEnabled;
  771. // Storage, 32 byte aligned (may make this alignment a requirement later).
  772. // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
  773. void* mMixerBuffer;
  774. // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
  775. size_t mMixerBufferSize;
  776. // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
  777. audio_format_t mMixerBufferFormat;
  778. // An internal flag set to true by MixerThread::prepareTracks_l()
  779. // when mMixerBuffer contains valid data after mixing.
  780. bool mMixerBufferValid;
  781. // Effects Buffer (mEffectsBuffer*)
  782. //
  783. // In the case of effects data, which is not in the sink format,
  784. // it is required to accumulate in a different buffer before data conversion
  785. // to the sink buffer.
  786. // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
  787. bool mEffectBufferEnabled;
  788. // Storage, 32 byte aligned (may make this alignment a requirement later).
  789. // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
  790. void* mEffectBuffer;
  791. // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
  792. size_t mEffectBufferSize;
  793. // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
  794. audio_format_t mEffectBufferFormat;
  795. // An internal flag set to true by MixerThread::prepareTracks_l()
  796. // when mEffectsBuffer contains valid data after mixing.
  797. //
  798. // When this is set, all mixer data is routed into the effects buffer
  799. // for any processing (including output processing).
  800. bool mEffectBufferValid;
  801. // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
  802. // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
  803. // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
  804. // workaround that restriction.
  805. // 'volatile' means accessed via atomic operations and no lock.
  806. volatile int32_t mSuspended;
  807. int64_t mBytesWritten;
  808. int64_t mFramesWritten; // not reset on standby
  809. int64_t mSuspendedFrames; // not reset on standby
  810. // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
  811. // haptic playback.
  812. audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
  813. uint32_t mHapticChannelCount = 0;
  814. private:
  815. // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
  816. // PlaybackThread needs to find out if master-muted, it checks it's local
  817. // copy rather than the one in AudioFlinger. This optimization saves a lock.
  818. bool mMasterMute;
  819. void setMasterMute_l(bool muted) { mMasterMute = muted; }
  820. protected:
  821. ActiveTracks<Track> mActiveTracks;
  822. // Time to sleep between cycles when:
  823. virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
  824. virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
  825. virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
  826. // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
  827. // No sleep in standby mode; waits on a condition
  828. // Code snippets that are temporarily lifted up out of threadLoop() until the merge
  829. void checkSilentMode_l();
  830. // Non-trivial for DUPLICATING only
  831. virtual void saveOutputTracks() { }
  832. virtual void clearOutputTracks() { }
  833. // Cache various calculated values, at threadLoop() entry and after a parameter change
  834. virtual void cacheParameters_l();
  835. virtual uint32_t correctLatency_l(uint32_t latency) const;
  836. virtual status_t createAudioPatch_l(const struct audio_patch *patch,
  837. audio_patch_handle_t *handle);
  838. virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
  839. bool usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL)
  840. && mHwSupportsPause
  841. && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
  842. uint32_t trackCountForUid_l(uid_t uid) const;
  843. private:
  844. friend class AudioFlinger; // for numerous
  845. DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
  846. status_t addTrack_l(const sp<Track>& track);
  847. bool destroyTrack_l(const sp<Track>& track);
  848. void removeTrack_l(const sp<Track>& track);
  849. void readOutputParameters_l();
  850. void updateMetadata_l() final;
  851. virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
  852. // The Tracks class manages tracks added and removed from the Thread.
  853. template <typename T>
  854. class Tracks {
  855. public:
  856. Tracks(bool saveDeletedTrackIds) :
  857. mSaveDeletedTrackIds(saveDeletedTrackIds) { }
  858. // SortedVector methods
  859. ssize_t add(const sp<T> &track) {
  860. const ssize_t index = mTracks.add(track);
  861. LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
  862. return index;
  863. }
  864. ssize_t remove(const sp<T> &track);
  865. size_t size() const {
  866. return mTracks.size();
  867. }
  868. bool isEmpty() const {
  869. return mTracks.isEmpty();
  870. }
  871. ssize_t indexOf(const sp<T> &item) {
  872. return mTracks.indexOf(item);
  873. }
  874. sp<T> operator[](size_t index) const {
  875. return mTracks[index];
  876. }
  877. typename SortedVector<sp<T>>::iterator begin() {
  878. return mTracks.begin();
  879. }
  880. typename SortedVector<sp<T>>::iterator end() {
  881. return mTracks.end();
  882. }
  883. size_t processDeletedTrackIds(std::function<void(int)> f) {
  884. for (const int trackId : mDeletedTrackIds) {
  885. f(trackId);
  886. }
  887. return mDeletedTrackIds.size();
  888. }
  889. void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
  890. private:
  891. // Tracks pending deletion for MIXER type threads
  892. const bool mSaveDeletedTrackIds; // true to enable tracking
  893. std::set<int> mDeletedTrackIds;
  894. SortedVector<sp<T>> mTracks; // wrapped SortedVector.
  895. };
  896. Tracks<Track> mTracks;
  897. stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
  898. AudioStreamOut *mOutput;
  899. float mMasterVolume;
  900. std::atomic<float> mMasterBalance{};
  901. audio_utils::Balance mBalance;
  902. int mNumWrites;
  903. int mNumDelayedWrites;
  904. bool mInWrite;
  905. // FIXME rename these former local variables of threadLoop to standard "m" names
  906. nsecs_t mStandbyTimeNs;
  907. size_t mSinkBufferSize;
  908. // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
  909. uint32_t mActiveSleepTimeUs;
  910. uint32_t mIdleSleepTimeUs;
  911. uint32_t mSleepTimeUs;
  912. // mixer status returned by prepareTracks_l()
  913. mixer_state mMixerStatus; // current cycle
  914. // previous cycle when in prepareTracks_l()
  915. mixer_state mMixerStatusIgnoringFastTracks;
  916. // FIXME or a separate ready state per track
  917. // FIXME move these declarations into the specific sub-class that needs them
  918. // MIXER only
  919. uint32_t sleepTimeShift;
  920. // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
  921. nsecs_t mStandbyDelayNs;
  922. // MIXER only
  923. nsecs_t maxPeriod;
  924. // DUPLICATING only
  925. uint32_t writeFrames;
  926. size_t mBytesRemaining;
  927. size_t mCurrentWriteLength;
  928. bool mUseAsyncWrite;
  929. // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
  930. // incremented each time a write(), a flush() or a standby() occurs.
  931. // Bit 0 is set when a write blocks and indicates a callback is expected.
  932. // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
  933. // callbacks are ignored.
  934. uint32_t mWriteAckSequence;
  935. // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
  936. // incremented each time a drain is requested or a flush() or standby() occurs.
  937. // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
  938. // expected.
  939. // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
  940. // callbacks are ignored.
  941. uint32_t mDrainSequence;
  942. sp<AsyncCallbackThread> mCallbackThread;
  943. private:
  944. // The HAL output sink is treated as non-blocking, but current implementation is blocking
  945. sp<NBAIO_Sink> mOutputSink;
  946. // If a fast mixer is present, the blocking pipe sink, otherwise clear
  947. sp<NBAIO_Sink> mPipeSink;
  948. // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
  949. sp<NBAIO_Sink> mNormalSink;
  950. uint32_t mScreenState; // cached copy of gScreenState
  951. // TODO: add comment and adjust size as needed
  952. static const size_t kFastMixerLogSize = 8 * 1024;
  953. sp<NBLog::Writer> mFastMixerNBLogWriter;
  954. // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
  955. audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
  956. public:
  957. virtual bool hasFastMixer() const = 0;
  958. virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
  959. { FastTrackUnderruns dummy; return dummy; }
  960. protected:
  961. // accessed by both binder threads and within threadLoop(), lock on mutex needed
  962. unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
  963. bool mHwSupportsPause;
  964. bool mHwPaused;
  965. bool mFlushPending;
  966. // volumes last sent to audio HAL with stream->setVolume()
  967. float mLeftVolFloat;
  968. float mRightVolFloat;
  969. };
  970. class MixerThread : public PlaybackThread {
  971. public:
  972. MixerThread(const sp<AudioFlinger>& audioFlinger,
  973. AudioStreamOut* output,
  974. audio_io_handle_t id,
  975. audio_devices_t device,
  976. bool systemReady,
  977. type_t type = MIXER);
  978. virtual ~MixerThread();
  979. // Thread virtuals
  980. virtual bool checkForNewParameter_l(const String8& keyValuePair,
  981. status_t& status);
  982. virtual bool isTrackAllowed_l(
  983. audio_channel_mask_t channelMask, audio_format_t format,
  984. audio_session_t sessionId, uid_t uid) const override;
  985. protected:
  986. virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
  987. virtual uint32_t idleSleepTimeUs() const;
  988. virtual uint32_t suspendSleepTimeUs() const;
  989. virtual void cacheParameters_l();
  990. virtual void acquireWakeLock_l() {
  991. PlaybackThread::acquireWakeLock_l();
  992. if (hasFastMixer()) {
  993. mFastMixer->setBoottimeOffset(
  994. mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
  995. }
  996. }
  997. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  998. // threadLoop snippets
  999. virtual ssize_t threadLoop_write();
  1000. virtual void threadLoop_standby();
  1001. virtual void threadLoop_mix();
  1002. virtual void threadLoop_sleepTime();
  1003. virtual uint32_t correctLatency_l(uint32_t latency) const;
  1004. virtual status_t createAudioPatch_l(const struct audio_patch *patch,
  1005. audio_patch_handle_t *handle);
  1006. virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
  1007. AudioMixer* mAudioMixer; // normal mixer
  1008. private:
  1009. // one-time initialization, no locks required
  1010. sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
  1011. sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
  1012. // contents are not guaranteed to be consistent, no locks required
  1013. FastMixerDumpState mFastMixerDumpState;
  1014. #ifdef STATE_QUEUE_DUMP
  1015. StateQueueObserverDump mStateQueueObserverDump;
  1016. StateQueueMutatorDump mStateQueueMutatorDump;
  1017. #endif
  1018. AudioWatchdogDump mAudioWatchdogDump;
  1019. // accessible only within the threadLoop(), no locks required
  1020. // mFastMixer->sq() // for mutating and pushing state
  1021. int32_t mFastMixerFutex; // for cold idle
  1022. std::atomic_bool mMasterMono;
  1023. public:
  1024. virtual bool hasFastMixer() const { return mFastMixer != 0; }
  1025. virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
  1026. ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
  1027. return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
  1028. }
  1029. status_t threadloop_getHalTimestamp_l(
  1030. ExtendedTimestamp *timestamp) const override {
  1031. if (mNormalSink.get() != nullptr) {
  1032. return mNormalSink->getTimestamp(*timestamp);
  1033. }
  1034. return INVALID_OPERATION;
  1035. }
  1036. protected:
  1037. virtual void setMasterMono_l(bool mono) {
  1038. mMasterMono.store(mono);
  1039. if (mFastMixer != nullptr) { /* hasFastMixer() */
  1040. mFastMixer->setMasterMono(mMasterMono);
  1041. }
  1042. }
  1043. // the FastMixer performs mono blend if it exists.
  1044. // Blending with limiter is not idempotent,
  1045. // and blending without limiter is idempotent but inefficient to do twice.
  1046. virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
  1047. void setMasterBalance(float balance) override {
  1048. mMasterBalance.store(balance);
  1049. if (hasFastMixer()) {
  1050. mFastMixer->setMasterBalance(balance);
  1051. }
  1052. }
  1053. };
  1054. class DirectOutputThread : public PlaybackThread {
  1055. public:
  1056. DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
  1057. audio_io_handle_t id, audio_devices_t device, bool systemReady)
  1058. : DirectOutputThread(audioFlinger, output, id, device, DIRECT, systemReady) { }
  1059. virtual ~DirectOutputThread();
  1060. status_t selectPresentation(int presentationId, int programId);
  1061. // Thread virtuals
  1062. virtual bool checkForNewParameter_l(const String8& keyValuePair,
  1063. status_t& status);
  1064. virtual void flushHw_l();
  1065. void setMasterBalance(float balance) override;
  1066. protected:
  1067. virtual uint32_t activeSleepTimeUs() const;
  1068. virtual uint32_t idleSleepTimeUs() const;
  1069. virtual uint32_t suspendSleepTimeUs() const;
  1070. virtual void cacheParameters_l();
  1071. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  1072. // threadLoop snippets
  1073. virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
  1074. virtual void threadLoop_mix();
  1075. virtual void threadLoop_sleepTime();
  1076. virtual void threadLoop_exit();
  1077. virtual bool shouldStandby_l();
  1078. virtual void onAddNewTrack_l();
  1079. bool mVolumeShaperActive = false;
  1080. DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
  1081. audio_io_handle_t id, audio_devices_t device, ThreadBase::type_t type,
  1082. bool systemReady);
  1083. void processVolume_l(Track *track, bool lastTrack);
  1084. // prepareTracks_l() tells threadLoop_mix() the name of the single active track
  1085. sp<Track> mActiveTrack;
  1086. wp<Track> mPreviousTrack; // used to detect track switch
  1087. // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
  1088. float mMasterBalanceLeft = 1.f;
  1089. float mMasterBalanceRight = 1.f;
  1090. public:
  1091. virtual bool hasFastMixer() const { return false; }
  1092. virtual int64_t computeWaitTimeNs_l() const override;
  1093. status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
  1094. // For DIRECT and OFFLOAD threads, query the output sink directly.
  1095. if (mOutput != nullptr) {
  1096. uint64_t uposition64;
  1097. struct timespec time;
  1098. if (mOutput->getPresentationPosition(
  1099. &uposition64, &time) == OK) {
  1100. timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
  1101. = (int64_t)uposition64;
  1102. timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
  1103. = audio_utils_ns_from_timespec(&time);
  1104. return NO_ERROR;
  1105. }
  1106. }
  1107. return INVALID_OPERATION;
  1108. }
  1109. };
  1110. class OffloadThread : public DirectOutputThread {
  1111. public:
  1112. OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
  1113. audio_io_handle_t id, uint32_t device, bool systemReady);
  1114. virtual ~OffloadThread() {};
  1115. virtual void flushHw_l();
  1116. protected:
  1117. // threadLoop snippets
  1118. virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
  1119. virtual void threadLoop_exit();
  1120. virtual bool waitingAsyncCallback();
  1121. virtual bool waitingAsyncCallback_l();
  1122. virtual void invalidateTracks(audio_stream_type_t streamType);
  1123. virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
  1124. private:
  1125. size_t mPausedWriteLength; // length in bytes of write interrupted by pause
  1126. size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
  1127. bool mKeepWakeLock; // keep wake lock while waiting for write callback
  1128. uint64_t mOffloadUnderrunPosition; // Current frame position for offloaded playback
  1129. // used and valid only during underrun. ~0 if
  1130. // no underrun has occurred during playback and
  1131. // is not reset on standby.
  1132. };
  1133. class AsyncCallbackThread : public Thread {
  1134. public:
  1135. explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
  1136. virtual ~AsyncCallbackThread();
  1137. // Thread virtuals
  1138. virtual bool threadLoop();
  1139. // RefBase
  1140. virtual void onFirstRef();
  1141. void exit();
  1142. void setWriteBlocked(uint32_t sequence);
  1143. void resetWriteBlocked();
  1144. void setDraining(uint32_t sequence);
  1145. void resetDraining();
  1146. void setAsyncError();
  1147. private:
  1148. const wp<PlaybackThread> mPlaybackThread;
  1149. // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
  1150. // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
  1151. // to indicate that the callback has been received via resetWriteBlocked()
  1152. uint32_t mWriteAckSequence;
  1153. // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
  1154. // setDraining(). The sequence is shifted one bit to the left and the lsb is used
  1155. // to indicate that the callback has been received via resetDraining()
  1156. uint32_t mDrainSequence;
  1157. Condition mWaitWorkCV;
  1158. Mutex mLock;
  1159. bool mAsyncError;
  1160. };
  1161. class DuplicatingThread : public MixerThread {
  1162. public:
  1163. DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
  1164. audio_io_handle_t id, bool systemReady);
  1165. virtual ~DuplicatingThread();
  1166. // Thread virtuals
  1167. void addOutputTrack(MixerThread* thread);
  1168. void removeOutputTrack(MixerThread* thread);
  1169. uint32_t waitTimeMs() const { return mWaitTimeMs; }
  1170. void sendMetadataToBackend_l(
  1171. const StreamOutHalInterface::SourceMetadata& metadata) override;
  1172. protected:
  1173. virtual uint32_t activeSleepTimeUs() const;
  1174. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  1175. private:
  1176. bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
  1177. protected:
  1178. // threadLoop snippets
  1179. virtual void threadLoop_mix();
  1180. virtual void threadLoop_sleepTime();
  1181. virtual ssize_t threadLoop_write();
  1182. virtual void threadLoop_standby();
  1183. virtual void cacheParameters_l();
  1184. private:
  1185. // called from threadLoop, addOutputTrack, removeOutputTrack
  1186. virtual void updateWaitTime_l();
  1187. protected:
  1188. virtual void saveOutputTracks();
  1189. virtual void clearOutputTracks();
  1190. private:
  1191. uint32_t mWaitTimeMs;
  1192. SortedVector < sp<OutputTrack> > outputTracks;
  1193. SortedVector < sp<OutputTrack> > mOutputTracks;
  1194. public:
  1195. virtual bool hasFastMixer() const { return false; }
  1196. status_t threadloop_getHalTimestamp_l(
  1197. ExtendedTimestamp *timestamp) const override {
  1198. if (mOutputTracks.size() > 0) {
  1199. // forward the first OutputTrack's kernel information for timestamp.
  1200. const ExtendedTimestamp trackTimestamp =
  1201. mOutputTracks[0]->getClientProxyTimestamp();
  1202. if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
  1203. timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
  1204. trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
  1205. timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
  1206. trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
  1207. return OK; // discard server timestamp - that's ignored.
  1208. }
  1209. }
  1210. return INVALID_OPERATION;
  1211. }
  1212. };
  1213. // record thread
  1214. class RecordThread : public ThreadBase
  1215. {
  1216. public:
  1217. class RecordTrack;
  1218. /* The ResamplerBufferProvider is used to retrieve recorded input data from the
  1219. * RecordThread. It maintains local state on the relative position of the read
  1220. * position of the RecordTrack compared with the RecordThread.
  1221. */
  1222. class ResamplerBufferProvider : public AudioBufferProvider
  1223. {
  1224. public:
  1225. explicit ResamplerBufferProvider(RecordTrack* recordTrack) :
  1226. mRecordTrack(recordTrack),
  1227. mRsmpInUnrel(0), mRsmpInFront(0) { }
  1228. virtual ~ResamplerBufferProvider() { }
  1229. // called to set the ResamplerBufferProvider to head of the RecordThread data buffer,
  1230. // skipping any previous data read from the hal.
  1231. virtual void reset();
  1232. /* Synchronizes RecordTrack position with the RecordThread.
  1233. * Calculates available frames and handle overruns if the RecordThread
  1234. * has advanced faster than the ResamplerBufferProvider has retrieved data.
  1235. * TODO: why not do this for every getNextBuffer?
  1236. *
  1237. * Parameters
  1238. * framesAvailable: pointer to optional output size_t to store record track
  1239. * frames available.
  1240. * hasOverrun: pointer to optional boolean, returns true if track has overrun.
  1241. */
  1242. virtual void sync(size_t *framesAvailable = NULL, bool *hasOverrun = NULL);
  1243. // AudioBufferProvider interface
  1244. virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
  1245. virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
  1246. private:
  1247. RecordTrack * const mRecordTrack;
  1248. size_t mRsmpInUnrel; // unreleased frames remaining from
  1249. // most recent getNextBuffer
  1250. // for debug only
  1251. int32_t mRsmpInFront; // next available frame
  1252. // rolling counter that is never cleared
  1253. };
  1254. #include "RecordTracks.h"
  1255. RecordThread(const sp<AudioFlinger>& audioFlinger,
  1256. AudioStreamIn *input,
  1257. audio_io_handle_t id,
  1258. audio_devices_t outDevice,
  1259. audio_devices_t inDevice,
  1260. bool systemReady
  1261. );
  1262. virtual ~RecordThread();
  1263. // no addTrack_l ?
  1264. void destroyTrack_l(const sp<RecordTrack>& track);
  1265. void removeTrack_l(const sp<RecordTrack>& track);
  1266. // Thread virtuals
  1267. virtual bool threadLoop();
  1268. virtual void preExit();
  1269. // RefBase
  1270. virtual void onFirstRef();
  1271. virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
  1272. virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; }
  1273. virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
  1274. sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
  1275. const sp<AudioFlinger::Client>& client,
  1276. const audio_attributes_t& attr,
  1277. uint32_t *pSampleRate,
  1278. audio_format_t format,
  1279. audio_channel_mask_t channelMask,
  1280. size_t *pFrameCount,
  1281. audio_session_t sessionId,
  1282. size_t *pNotificationFrameCount,
  1283. pid_t creatorPid,
  1284. uid_t uid,
  1285. audio_input_flags_t *flags,
  1286. pid_t tid,
  1287. status_t *status /*non-NULL*/,
  1288. audio_port_handle_t portId,
  1289. const String16& opPackageName);
  1290. status_t start(RecordTrack* recordTrack,
  1291. AudioSystem::sync_event_t event,
  1292. audio_session_t triggerSession);
  1293. // ask the thread to stop the specified track, and
  1294. // return true if the caller should then do it's part of the stopping process
  1295. bool stop(RecordTrack* recordTrack);
  1296. AudioStreamIn* clearInput();
  1297. virtual sp<StreamHalInterface> stream() const;
  1298. virtual bool checkForNewParameter_l(const String8& keyValuePair,
  1299. status_t& status);
  1300. virtual void cacheParameters_l() {}
  1301. virtual String8 getParameters(const String8& keys);
  1302. virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0,
  1303. audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
  1304. virtual status_t createAudioPatch_l(const struct audio_patch *patch,
  1305. audio_patch_handle_t *handle);
  1306. virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
  1307. void addPatchTrack(const sp<PatchRecord>& record);
  1308. void deletePatchTrack(const sp<PatchRecord>& record);
  1309. void readInputParameters_l();
  1310. virtual uint32_t getInputFramesLost();
  1311. virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
  1312. virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
  1313. uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
  1314. return ThreadBase::hasAudioSession_l(sessionId, mTracks);
  1315. }
  1316. // Return the set of unique session IDs across all tracks.
  1317. // The keys are the session IDs, and the associated values are meaningless.
  1318. // FIXME replace by Set [and implement Bag/Multiset for other uses].
  1319. KeyedVector<audio_session_t, bool> sessionIds() const;
  1320. virtual status_t setSyncEvent(const sp<SyncEvent>& event);
  1321. virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
  1322. static void syncStartEventCallback(const wp<SyncEvent>& event);
  1323. virtual size_t frameCount() const { return mFrameCount; }
  1324. bool hasFastCapture() const { return mFastCapture != 0; }
  1325. virtual void toAudioPortConfig(struct audio_port_config *config);
  1326. virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
  1327. audio_session_t sessionId);
  1328. virtual void acquireWakeLock_l() {
  1329. ThreadBase::acquireWakeLock_l();
  1330. mActiveTracks.updatePowerState(this, true /* force */);
  1331. }
  1332. virtual bool isOutput() const override { return false; }
  1333. void checkBtNrec();
  1334. // Sets the UID records silence
  1335. void setRecordSilenced(uid_t uid, bool silenced);
  1336. status_t getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones);
  1337. status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
  1338. status_t setPreferredMicrophoneFieldDimension(float zoom);
  1339. void updateMetadata_l() override;
  1340. bool fastTrackAvailable() const { return mFastTrackAvail; }
  1341. bool isTimestampCorrectionEnabled() const override {
  1342. // checks popcount for exactly one device.
  1343. return audio_is_input_device(
  1344. mInDevice & mTimestampCorrectedDevices);
  1345. }
  1346. protected:
  1347. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  1348. void dumpTracks_l(int fd, const Vector<String16>& args) override;
  1349. private:
  1350. // Enter standby if not already in standby, and set mStandby flag
  1351. void standbyIfNotAlreadyInStandby();
  1352. // Call the HAL standby method unconditionally, and don't change mStandby flag
  1353. void inputStandBy();
  1354. void checkBtNrec_l();
  1355. AudioStreamIn *mInput;
  1356. SortedVector < sp<RecordTrack> > mTracks;
  1357. // mActiveTracks has dual roles: it indicates the current active track(s), and
  1358. // is used together with mStartStopCond to indicate start()/stop() progress
  1359. ActiveTracks<RecordTrack> mActiveTracks;
  1360. Condition mStartStopCond;
  1361. // resampler converts input at HAL Hz to output at AudioRecord client Hz
  1362. void *mRsmpInBuffer; // size = mRsmpInFramesOA
  1363. size_t mRsmpInFrames; // size of resampler input in frames
  1364. size_t mRsmpInFramesP2;// size rounded up to a power-of-2
  1365. size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
  1366. // rolling index that is never cleared
  1367. int32_t mRsmpInRear; // last filled frame + 1
  1368. // For dumpsys
  1369. const sp<MemoryDealer> mReadOnlyHeap;
  1370. // one-time initialization, no locks required
  1371. sp<FastCapture> mFastCapture; // non-0 if there is also
  1372. // a fast capture
  1373. // FIXME audio watchdog thread
  1374. // contents are not guaranteed to be consistent, no locks required
  1375. FastCaptureDumpState mFastCaptureDumpState;
  1376. #ifdef STATE_QUEUE_DUMP
  1377. // FIXME StateQueue observer and mutator dump fields
  1378. #endif
  1379. // FIXME audio watchdog dump
  1380. // accessible only within the threadLoop(), no locks required
  1381. // mFastCapture->sq() // for mutating and pushing state
  1382. int32_t mFastCaptureFutex; // for cold idle
  1383. // The HAL input source is treated as non-blocking,
  1384. // but current implementation is blocking
  1385. sp<NBAIO_Source> mInputSource;
  1386. // The source for the normal capture thread to read from: mInputSource or mPipeSource
  1387. sp<NBAIO_Source> mNormalSource;
  1388. // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
  1389. // otherwise clear
  1390. sp<NBAIO_Sink> mPipeSink;
  1391. // If a fast capture is present, the non-blocking pipe source read by normal thread,
  1392. // otherwise clear
  1393. sp<NBAIO_Source> mPipeSource;
  1394. // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
  1395. size_t mPipeFramesP2;
  1396. // If a fast capture is present, the Pipe as IMemory, otherwise clear
  1397. sp<IMemory> mPipeMemory;
  1398. // TODO: add comment and adjust size as needed
  1399. static const size_t kFastCaptureLogSize = 4 * 1024;
  1400. sp<NBLog::Writer> mFastCaptureNBLogWriter;
  1401. bool mFastTrackAvail; // true if fast track available
  1402. // common state to all record threads
  1403. std::atomic_bool mBtNrecSuspended;
  1404. int64_t mFramesRead = 0; // continuous running counter.
  1405. };
  1406. class MmapThread : public ThreadBase
  1407. {
  1408. public:
  1409. #include "MmapTracks.h"
  1410. MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
  1411. AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
  1412. audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
  1413. virtual ~MmapThread();
  1414. virtual void configure(const audio_attributes_t *attr,
  1415. audio_stream_type_t streamType,
  1416. audio_session_t sessionId,
  1417. const sp<MmapStreamCallback>& callback,
  1418. audio_port_handle_t deviceId,
  1419. audio_port_handle_t portId);
  1420. void disconnect();
  1421. // MmapStreamInterface
  1422. status_t createMmapBuffer(int32_t minSizeFrames,
  1423. struct audio_mmap_buffer_info *info);
  1424. status_t getMmapPosition(struct audio_mmap_position *position);
  1425. status_t start(const AudioClient& client, audio_port_handle_t *handle);
  1426. status_t stop(audio_port_handle_t handle);
  1427. status_t standby();
  1428. // RefBase
  1429. virtual void onFirstRef();
  1430. // Thread virtuals
  1431. virtual bool threadLoop();
  1432. virtual void threadLoop_exit();
  1433. virtual void threadLoop_standby();
  1434. virtual bool shouldStandby_l() { return false; }
  1435. virtual status_t exitStandby();
  1436. virtual status_t initCheck() const { return (mHalStream == 0) ? NO_INIT : NO_ERROR; }
  1437. virtual size_t frameCount() const { return mFrameCount; }
  1438. virtual bool checkForNewParameter_l(const String8& keyValuePair,
  1439. status_t& status);
  1440. virtual String8 getParameters(const String8& keys);
  1441. virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0,
  1442. audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
  1443. void readHalParameters_l();
  1444. virtual void cacheParameters_l() {}
  1445. virtual status_t createAudioPatch_l(const struct audio_patch *patch,
  1446. audio_patch_handle_t *handle);
  1447. virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
  1448. virtual void toAudioPortConfig(struct audio_port_config *config);
  1449. virtual sp<StreamHalInterface> stream() const { return mHalStream; }
  1450. virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
  1451. virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
  1452. virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
  1453. audio_session_t sessionId);
  1454. uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
  1455. // Note: using mActiveTracks as no mTracks here.
  1456. return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
  1457. }
  1458. virtual status_t setSyncEvent(const sp<SyncEvent>& event);
  1459. virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
  1460. virtual void checkSilentMode_l() {}
  1461. virtual void processVolume_l() {}
  1462. void checkInvalidTracks_l();
  1463. virtual audio_stream_type_t streamType() { return AUDIO_STREAM_DEFAULT; }
  1464. virtual void invalidateTracks(audio_stream_type_t streamType __unused) {}
  1465. // Sets the UID records silence
  1466. virtual void setRecordSilenced(uid_t uid __unused, bool silenced __unused) {}
  1467. protected:
  1468. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  1469. void dumpTracks_l(int fd, const Vector<String16>& args) override;
  1470. audio_attributes_t mAttr;
  1471. audio_session_t mSessionId;
  1472. audio_port_handle_t mPortId;
  1473. wp<MmapStreamCallback> mCallback;
  1474. sp<StreamHalInterface> mHalStream;
  1475. sp<DeviceHalInterface> mHalDevice;
  1476. AudioHwDevice* const mAudioHwDev;
  1477. ActiveTracks<MmapTrack> mActiveTracks;
  1478. float mHalVolFloat;
  1479. int32_t mNoCallbackWarningCount;
  1480. static constexpr int32_t kMaxNoCallbackWarnings = 5;
  1481. };
  1482. class MmapPlaybackThread : public MmapThread, public VolumeInterface
  1483. {
  1484. public:
  1485. MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
  1486. AudioHwDevice *hwDev, AudioStreamOut *output,
  1487. audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
  1488. virtual ~MmapPlaybackThread() {}
  1489. virtual void configure(const audio_attributes_t *attr,
  1490. audio_stream_type_t streamType,
  1491. audio_session_t sessionId,
  1492. const sp<MmapStreamCallback>& callback,
  1493. audio_port_handle_t deviceId,
  1494. audio_port_handle_t portId);
  1495. AudioStreamOut* clearOutput();
  1496. // VolumeInterface
  1497. virtual void setMasterVolume(float value);
  1498. virtual void setMasterMute(bool muted);
  1499. virtual void setStreamVolume(audio_stream_type_t stream, float value);
  1500. virtual void setStreamMute(audio_stream_type_t stream, bool muted);
  1501. virtual float streamVolume(audio_stream_type_t stream) const;
  1502. void setMasterMute_l(bool muted) { mMasterMute = muted; }
  1503. virtual void invalidateTracks(audio_stream_type_t streamType);
  1504. virtual audio_stream_type_t streamType() { return mStreamType; }
  1505. virtual void checkSilentMode_l();
  1506. void processVolume_l() override;
  1507. virtual bool isOutput() const override { return true; }
  1508. void updateMetadata_l() override;
  1509. virtual void toAudioPortConfig(struct audio_port_config *config);
  1510. protected:
  1511. void dumpInternals_l(int fd, const Vector<String16>& args) override;
  1512. audio_stream_type_t mStreamType;
  1513. float mMasterVolume;
  1514. float mStreamVolume;
  1515. bool mMasterMute;
  1516. bool mStreamMute;
  1517. AudioStreamOut* mOutput;
  1518. };
  1519. class MmapCaptureThread : public MmapThread
  1520. {
  1521. public:
  1522. MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
  1523. AudioHwDevice *hwDev, AudioStreamIn *input,
  1524. audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
  1525. virtual ~MmapCaptureThread() {}
  1526. AudioStreamIn* clearInput();
  1527. status_t exitStandby() override;
  1528. virtual bool isOutput() const override { return false; }
  1529. void updateMetadata_l() override;
  1530. void processVolume_l() override;
  1531. void setRecordSilenced(uid_t uid, bool silenced) override;
  1532. virtual void toAudioPortConfig(struct audio_port_config *config);
  1533. protected:
  1534. AudioStreamIn* mInput;
  1535. };