Threads.h revision 1035194cee4fbd57e35ea15c56e66cd09b63d56e
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 18#ifndef INCLUDING_FROM_AUDIOFLINGER_H 19 #error This header file should only be included from AudioFlinger.h 20#endif 21 22class ThreadBase : public Thread { 23public: 24 25#include "TrackBase.h" 26 27 enum type_t { 28 MIXER, // Thread class is MixerThread 29 DIRECT, // Thread class is DirectOutputThread 30 DUPLICATING, // Thread class is DuplicatingThread 31 RECORD, // Thread class is RecordThread 32 OFFLOAD // Thread class is OffloadThread 33 }; 34 35 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 36 audio_devices_t outDevice, audio_devices_t inDevice, type_t type); 37 virtual ~ThreadBase(); 38 39 virtual status_t readyToRun(); 40 41 void dumpBase(int fd, const Vector<String16>& args); 42 void dumpEffectChains(int fd, const Vector<String16>& args); 43 44 void clearPowerManager(); 45 46 // base for record and playback 47 enum { 48 CFG_EVENT_IO, 49 CFG_EVENT_PRIO, 50 CFG_EVENT_SET_PARAMETER, 51 }; 52 53 class ConfigEventData: public RefBase { 54 public: 55 virtual ~ConfigEventData() {} 56 57 virtual void dump(char *buffer, size_t size) = 0; 58 protected: 59 ConfigEventData() {} 60 }; 61 62 // Config event sequence by client if status needed (e.g binder thread calling setParameters()): 63 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event 64 // 2. Lock mLock 65 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal 66 // 4. sendConfigEvent_l() reads status from event->mStatus; 67 // 5. sendConfigEvent_l() returns status 68 // 6. Unlock 69 // 70 // Parameter sequence by server: threadLoop calling processConfigEvents_l(): 71 // 1. Lock mLock 72 // 2. If there is an entry in mConfigEvents proceed ... 73 // 3. Read first entry in mConfigEvents 74 // 4. Remove first entry from mConfigEvents 75 // 5. Process 76 // 6. Set event->mStatus 77 // 7. event->mCond.signal 78 // 8. Unlock 79 80 class ConfigEvent: public RefBase { 81 public: 82 virtual ~ConfigEvent() {} 83 84 void dump(char *buffer, size_t size) { mData->dump(buffer, size); } 85 86 const int mType; // event type e.g. CFG_EVENT_IO 87 Mutex mLock; // mutex associated with mCond 88 Condition mCond; // condition for status return 89 status_t mStatus; // status communicated to sender 90 bool mWaitStatus; // true if sender is waiting for status 91 sp<ConfigEventData> mData; // event specific parameter data 92 93 protected: 94 ConfigEvent(int type) : mType(type), mStatus(NO_ERROR), mWaitStatus(false), mData(NULL) {} 95 }; 96 97 class IoConfigEventData : public ConfigEventData { 98 public: 99 IoConfigEventData(int event, int param) : 100 mEvent(event), mParam(param) {} 101 102 virtual void dump(char *buffer, size_t size) { 103 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam); 104 } 105 106 const int mEvent; 107 const int mParam; 108 }; 109 110 class IoConfigEvent : public ConfigEvent { 111 public: 112 IoConfigEvent(int event, int param) : 113 ConfigEvent(CFG_EVENT_IO) { 114 mData = new IoConfigEventData(event, param); 115 } 116 virtual ~IoConfigEvent() {} 117 }; 118 119 class PrioConfigEventData : public ConfigEventData { 120 public: 121 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) : 122 mPid(pid), mTid(tid), mPrio(prio) {} 123 124 virtual void dump(char *buffer, size_t size) { 125 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio); 126 } 127 128 const pid_t mPid; 129 const pid_t mTid; 130 const int32_t mPrio; 131 }; 132 133 class PrioConfigEvent : public ConfigEvent { 134 public: 135 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) : 136 ConfigEvent(CFG_EVENT_PRIO) { 137 mData = new PrioConfigEventData(pid, tid, prio); 138 } 139 virtual ~PrioConfigEvent() {} 140 }; 141 142 class SetParameterConfigEventData : public ConfigEventData { 143 public: 144 SetParameterConfigEventData(String8 keyValuePairs) : 145 mKeyValuePairs(keyValuePairs) {} 146 147 virtual void dump(char *buffer, size_t size) { 148 snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string()); 149 } 150 151 const String8 mKeyValuePairs; 152 }; 153 154 class SetParameterConfigEvent : public ConfigEvent { 155 public: 156 SetParameterConfigEvent(String8 keyValuePairs) : 157 ConfigEvent(CFG_EVENT_SET_PARAMETER) { 158 mData = new SetParameterConfigEventData(keyValuePairs); 159 mWaitStatus = true; 160 } 161 virtual ~SetParameterConfigEvent() {} 162 }; 163 164 165 class PMDeathRecipient : public IBinder::DeathRecipient { 166 public: 167 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {} 168 virtual ~PMDeathRecipient() {} 169 170 // IBinder::DeathRecipient 171 virtual void binderDied(const wp<IBinder>& who); 172 173 private: 174 PMDeathRecipient(const PMDeathRecipient&); 175 PMDeathRecipient& operator = (const PMDeathRecipient&); 176 177 wp<ThreadBase> mThread; 178 }; 179 180 virtual status_t initCheck() const = 0; 181 182 // static externally-visible 183 type_t type() const { return mType; } 184 audio_io_handle_t id() const { return mId;} 185 186 // dynamic externally-visible 187 uint32_t sampleRate() const { return mSampleRate; } 188 uint32_t channelCount() const { return mChannelCount; } 189 audio_channel_mask_t channelMask() const { return mChannelMask; } 190 audio_format_t format() const { return mFormat; } 191 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects, 192 // and returns the [normal mix] buffer's frame count. 193 virtual size_t frameCount() const = 0; 194 size_t frameSize() const { return mFrameSize; } 195 196 // Should be "virtual status_t requestExitAndWait()" and override same 197 // method in Thread, but Thread::requestExitAndWait() is not yet virtual. 198 void exit(); 199 virtual bool checkForNewParameter_l(const String8& keyValuePair, 200 status_t& status) = 0; 201 virtual status_t setParameters(const String8& keyValuePairs); 202 virtual String8 getParameters(const String8& keys) = 0; 203 virtual void audioConfigChanged_l( 204 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients, 205 int event, 206 int param = 0) = 0; 207 // sendConfigEvent_l() must be called with ThreadBase::mLock held 208 // Can temporarily release the lock if waiting for a reply from 209 // processConfigEvents_l(). 210 status_t sendConfigEvent_l(sp<ConfigEvent>& event); 211 void sendIoConfigEvent(int event, int param = 0); 212 void sendIoConfigEvent_l(int event, int param = 0); 213 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio); 214 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair); 215 void processConfigEvents_l( 216 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients); 217 virtual void cacheParameters_l() = 0; 218 219 // see note at declaration of mStandby, mOutDevice and mInDevice 220 bool standby() const { return mStandby; } 221 audio_devices_t outDevice() const { return mOutDevice; } 222 audio_devices_t inDevice() const { return mInDevice; } 223 224 virtual audio_stream_t* stream() const = 0; 225 226 sp<EffectHandle> createEffect_l( 227 const sp<AudioFlinger::Client>& client, 228 const sp<IEffectClient>& effectClient, 229 int32_t priority, 230 int sessionId, 231 effect_descriptor_t *desc, 232 int *enabled, 233 status_t *status /*non-NULL*/); 234 void disconnectEffect(const sp< EffectModule>& effect, 235 EffectHandle *handle, 236 bool unpinIfLast); 237 238 // return values for hasAudioSession (bit field) 239 enum effect_state { 240 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one 241 // effect 242 TRACK_SESSION = 0x2 // the audio session corresponds to at least one 243 // track 244 }; 245 246 // get effect chain corresponding to session Id. 247 sp<EffectChain> getEffectChain(int sessionId); 248 // same as getEffectChain() but must be called with ThreadBase mutex locked 249 sp<EffectChain> getEffectChain_l(int sessionId) const; 250 // add an effect chain to the chain list (mEffectChains) 251 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0; 252 // remove an effect chain from the chain list (mEffectChains) 253 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0; 254 // lock all effect chains Mutexes. Must be called before releasing the 255 // ThreadBase mutex before processing the mixer and effects. This guarantees the 256 // integrity of the chains during the process. 257 // Also sets the parameter 'effectChains' to current value of mEffectChains. 258 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains); 259 // unlock effect chains after process 260 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains); 261 // get a copy of mEffectChains vector 262 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; }; 263 // set audio mode to all effect chains 264 void setMode(audio_mode_t mode); 265 // get effect module with corresponding ID on specified audio session 266 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId); 267 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId); 268 // add and effect module. Also creates the effect chain is none exists for 269 // the effects audio session 270 status_t addEffect_l(const sp< EffectModule>& effect); 271 // remove and effect module. Also removes the effect chain is this was the last 272 // effect 273 void removeEffect_l(const sp< EffectModule>& effect); 274 // detach all tracks connected to an auxiliary effect 275 virtual void detachAuxEffect_l(int effectId __unused) {} 276 // returns either EFFECT_SESSION if effects on this audio session exist in one 277 // chain, or TRACK_SESSION if tracks on this audio session exist, or both 278 virtual uint32_t hasAudioSession(int sessionId) const = 0; 279 // the value returned by default implementation is not important as the 280 // strategy is only meaningful for PlaybackThread which implements this method 281 virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; } 282 283 // suspend or restore effect according to the type of effect passed. a NULL 284 // type pointer means suspend all effects in the session 285 void setEffectSuspended(const effect_uuid_t *type, 286 bool suspend, 287 int sessionId = AUDIO_SESSION_OUTPUT_MIX); 288 // check if some effects must be suspended/restored when an effect is enabled 289 // or disabled 290 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 291 bool enabled, 292 int sessionId = AUDIO_SESSION_OUTPUT_MIX); 293 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 294 bool enabled, 295 int sessionId = AUDIO_SESSION_OUTPUT_MIX); 296 297 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0; 298 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0; 299 300 // Return a reference to a per-thread heap which can be used to allocate IMemory 301 // objects that will be read-only to client processes, read/write to mediaserver, 302 // and shared by all client processes of the thread. 303 // The heap is per-thread rather than common across all threads, because 304 // clients can't be trusted not to modify the offset of the IMemory they receive. 305 // If a thread does not have such a heap, this method returns 0. 306 virtual sp<MemoryDealer> readOnlyHeap() const { return 0; } 307 308 mutable Mutex mLock; 309 310protected: 311 312 // entry describing an effect being suspended in mSuspendedSessions keyed vector 313 class SuspendedSessionDesc : public RefBase { 314 public: 315 SuspendedSessionDesc() : mRefCount(0) {} 316 317 int mRefCount; // number of active suspend requests 318 effect_uuid_t mType; // effect type UUID 319 }; 320 321 void acquireWakeLock(int uid = -1); 322 void acquireWakeLock_l(int uid = -1); 323 void releaseWakeLock(); 324 void releaseWakeLock_l(); 325 void updateWakeLockUids(const SortedVector<int> &uids); 326 void updateWakeLockUids_l(const SortedVector<int> &uids); 327 void getPowerManager_l(); 328 void setEffectSuspended_l(const effect_uuid_t *type, 329 bool suspend, 330 int sessionId); 331 // updated mSuspendedSessions when an effect suspended or restored 332 void updateSuspendedSessions_l(const effect_uuid_t *type, 333 bool suspend, 334 int sessionId); 335 // check if some effects must be suspended when an effect chain is added 336 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain); 337 338 String16 getWakeLockTag(); 339 340 virtual void preExit() { } 341 342 friend class AudioFlinger; // for mEffectChains 343 344 const type_t mType; 345 346 // Used by parameters, config events, addTrack_l, exit 347 Condition mWaitWorkCV; 348 349 const sp<AudioFlinger> mAudioFlinger; 350 351 // updated by PlaybackThread::readOutputParameters_l() or 352 // RecordThread::readInputParameters_l() 353 uint32_t mSampleRate; 354 size_t mFrameCount; // output HAL, direct output, record 355 audio_channel_mask_t mChannelMask; 356 uint32_t mChannelCount; 357 size_t mFrameSize; 358 audio_format_t mFormat; 359 size_t mBufferSize; // HAL buffer size for read() or write() 360 361 Vector< sp<ConfigEvent> > mConfigEvents; 362 363 // These fields are written and read by thread itself without lock or barrier, 364 // and read by other threads without lock or barrier via standby(), outDevice() 365 // and inDevice(). 366 // Because of the absence of a lock or barrier, any other thread that reads 367 // these fields must use the information in isolation, or be prepared to deal 368 // with possibility that it might be inconsistent with other information. 369 bool mStandby; // Whether thread is currently in standby. 370 audio_devices_t mOutDevice; // output device 371 audio_devices_t mInDevice; // input device 372 audio_source_t mAudioSource; // (see audio.h, audio_source_t) 373 374 const audio_io_handle_t mId; 375 Vector< sp<EffectChain> > mEffectChains; 376 377 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit 378 char mName[kNameLength]; 379 sp<IPowerManager> mPowerManager; 380 sp<IBinder> mWakeLockToken; 381 const sp<PMDeathRecipient> mDeathRecipient; 382 // list of suspended effects per session and per type. The first vector is 383 // keyed by session ID, the second by type UUID timeLow field 384 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > > 385 mSuspendedSessions; 386 static const size_t kLogSize = 4 * 1024; 387 sp<NBLog::Writer> mNBLogWriter; 388}; 389 390// --- PlaybackThread --- 391class PlaybackThread : public ThreadBase { 392public: 393 394#include "PlaybackTracks.h" 395 396 enum mixer_state { 397 MIXER_IDLE, // no active tracks 398 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready 399 MIXER_TRACKS_READY, // at least one active track, and at least one track has data 400 MIXER_DRAIN_TRACK, // drain currently playing track 401 MIXER_DRAIN_ALL, // fully drain the hardware 402 // standby mode does not have an enum value 403 // suspend by audio policy manager is orthogonal to mixer state 404 }; 405 406 // retry count before removing active track in case of underrun on offloaded thread: 407 // we need to make sure that AudioTrack client has enough time to send large buffers 408//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled 409 // for offloaded tracks 410 static const int8_t kMaxTrackRetriesOffload = 20; 411 412 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 413 audio_io_handle_t id, audio_devices_t device, type_t type); 414 virtual ~PlaybackThread(); 415 416 void dump(int fd, const Vector<String16>& args); 417 418 // Thread virtuals 419 virtual bool threadLoop(); 420 421 // RefBase 422 virtual void onFirstRef(); 423 424protected: 425 // Code snippets that were lifted up out of threadLoop() 426 virtual void threadLoop_mix() = 0; 427 virtual void threadLoop_sleepTime() = 0; 428 virtual ssize_t threadLoop_write(); 429 virtual void threadLoop_drain(); 430 virtual void threadLoop_standby(); 431 virtual void threadLoop_exit(); 432 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove); 433 434 // prepareTracks_l reads and writes mActiveTracks, and returns 435 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller 436 // is responsible for clearing or destroying this Vector later on, when it 437 // is safe to do so. That will drop the final ref count and destroy the tracks. 438 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0; 439 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove); 440 441 void writeCallback(); 442 void resetWriteBlocked(uint32_t sequence); 443 void drainCallback(); 444 void resetDraining(uint32_t sequence); 445 446 static int asyncCallback(stream_callback_event_t event, void *param, void *cookie); 447 448 virtual bool waitingAsyncCallback(); 449 virtual bool waitingAsyncCallback_l(); 450 virtual bool shouldStandby_l(); 451 virtual void onAddNewTrack_l(); 452 453 // ThreadBase virtuals 454 virtual void preExit(); 455 456public: 457 458 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; } 459 460 // return estimated latency in milliseconds, as reported by HAL 461 uint32_t latency() const; 462 // same, but lock must already be held 463 uint32_t latency_l() const; 464 465 void setMasterVolume(float value); 466 void setMasterMute(bool muted); 467 468 void setStreamVolume(audio_stream_type_t stream, float value); 469 void setStreamMute(audio_stream_type_t stream, bool muted); 470 471 float streamVolume(audio_stream_type_t stream) const; 472 473 sp<Track> createTrack_l( 474 const sp<AudioFlinger::Client>& client, 475 audio_stream_type_t streamType, 476 uint32_t sampleRate, 477 audio_format_t format, 478 audio_channel_mask_t channelMask, 479 size_t *pFrameCount, 480 const sp<IMemory>& sharedBuffer, 481 int sessionId, 482 IAudioFlinger::track_flags_t *flags, 483 pid_t tid, 484 int uid, 485 status_t *status /*non-NULL*/); 486 487 AudioStreamOut* getOutput() const; 488 AudioStreamOut* clearOutput(); 489 virtual audio_stream_t* stream() const; 490 491 // a very large number of suspend() will eventually wraparound, but unlikely 492 void suspend() { (void) android_atomic_inc(&mSuspended); } 493 void restore() 494 { 495 // if restore() is done without suspend(), get back into 496 // range so that the next suspend() will operate correctly 497 if (android_atomic_dec(&mSuspended) <= 0) { 498 android_atomic_release_store(0, &mSuspended); 499 } 500 } 501 bool isSuspended() const 502 { return android_atomic_acquire_load(&mSuspended) > 0; } 503 504 virtual String8 getParameters(const String8& keys); 505 virtual void audioConfigChanged_l( 506 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients, 507 int event, 508 int param = 0); 509 status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames); 510 // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency. 511 // Consider also removing and passing an explicit mMainBuffer initialization 512 // parameter to AF::PlaybackThread::Track::Track(). 513 int16_t *mixBuffer() const { 514 return reinterpret_cast<int16_t *>(mSinkBuffer); }; 515 516 virtual void detachAuxEffect_l(int effectId); 517 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track, 518 int EffectId); 519 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track, 520 int EffectId); 521 522 virtual status_t addEffectChain_l(const sp<EffectChain>& chain); 523 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain); 524 virtual uint32_t hasAudioSession(int sessionId) const; 525 virtual uint32_t getStrategyForSession_l(int sessionId); 526 527 528 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 529 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const; 530 531 // called with AudioFlinger lock held 532 void invalidateTracks(audio_stream_type_t streamType); 533 534 virtual size_t frameCount() const { return mNormalFrameCount; } 535 536 // Return's the HAL's frame count i.e. fast mixer buffer size. 537 size_t frameCountHAL() const { return mFrameCount; } 538 539 status_t getTimestamp_l(AudioTimestamp& timestamp); 540 541protected: 542 // updated by readOutputParameters_l() 543 size_t mNormalFrameCount; // normal mixer and effects 544 545 void* mSinkBuffer; // frame size aligned sink buffer 546 547 // TODO: 548 // Rearrange the buffer info into a struct/class with 549 // clear, copy, construction, destruction methods. 550 // 551 // mSinkBuffer also has associated with it: 552 // 553 // mSinkBufferSize: Sink Buffer Size 554 // mFormat: Sink Buffer Format 555 556 // Mixer Buffer (mMixerBuffer*) 557 // 558 // In the case of floating point or multichannel data, which is not in the 559 // sink format, it is required to accumulate in a higher precision or greater channel count 560 // buffer before downmixing or data conversion to the sink buffer. 561 562 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer. 563 bool mMixerBufferEnabled; 564 565 // Storage, 32 byte aligned (may make this alignment a requirement later). 566 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames. 567 void* mMixerBuffer; 568 569 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize. 570 size_t mMixerBufferSize; 571 572 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only. 573 audio_format_t mMixerBufferFormat; 574 575 // An internal flag set to true by MixerThread::prepareTracks_l() 576 // when mMixerBuffer contains valid data after mixing. 577 bool mMixerBufferValid; 578 579 // Effects Buffer (mEffectsBuffer*) 580 // 581 // In the case of effects data, which is not in the sink format, 582 // it is required to accumulate in a different buffer before data conversion 583 // to the sink buffer. 584 585 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer. 586 bool mEffectBufferEnabled; 587 588 // Storage, 32 byte aligned (may make this alignment a requirement later). 589 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames. 590 void* mEffectBuffer; 591 592 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize. 593 size_t mEffectBufferSize; 594 595 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only. 596 audio_format_t mEffectBufferFormat; 597 598 // An internal flag set to true by MixerThread::prepareTracks_l() 599 // when mEffectsBuffer contains valid data after mixing. 600 // 601 // When this is set, all mixer data is routed into the effects buffer 602 // for any processing (including output processing). 603 bool mEffectBufferValid; 604 605 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from 606 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle 607 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to 608 // workaround that restriction. 609 // 'volatile' means accessed via atomic operations and no lock. 610 volatile int32_t mSuspended; 611 612 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples 613 // mFramesWritten would be better, or 64-bit even better 614 size_t mBytesWritten; 615private: 616 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a 617 // PlaybackThread needs to find out if master-muted, it checks it's local 618 // copy rather than the one in AudioFlinger. This optimization saves a lock. 619 bool mMasterMute; 620 void setMasterMute_l(bool muted) { mMasterMute = muted; } 621protected: 622 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<> 623 SortedVector<int> mWakeLockUids; 624 int mActiveTracksGeneration; 625 wp<Track> mLatestActiveTrack; // latest track added to mActiveTracks 626 627 // Allocate a track name for a given channel mask. 628 // Returns name >= 0 if successful, -1 on failure. 629 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0; 630 virtual void deleteTrackName_l(int name) = 0; 631 632 // Time to sleep between cycles when: 633 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED 634 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE 635 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us 636 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write() 637 // No sleep in standby mode; waits on a condition 638 639 // Code snippets that are temporarily lifted up out of threadLoop() until the merge 640 void checkSilentMode_l(); 641 642 // Non-trivial for DUPLICATING only 643 virtual void saveOutputTracks() { } 644 virtual void clearOutputTracks() { } 645 646 // Cache various calculated values, at threadLoop() entry and after a parameter change 647 virtual void cacheParameters_l(); 648 649 virtual uint32_t correctLatency_l(uint32_t latency) const; 650 651private: 652 653 friend class AudioFlinger; // for numerous 654 655 PlaybackThread(const Client&); 656 PlaybackThread& operator = (const PlaybackThread&); 657 658 status_t addTrack_l(const sp<Track>& track); 659 bool destroyTrack_l(const sp<Track>& track); 660 void removeTrack_l(const sp<Track>& track); 661 void broadcast_l(); 662 663 void readOutputParameters_l(); 664 665 virtual void dumpInternals(int fd, const Vector<String16>& args); 666 void dumpTracks(int fd, const Vector<String16>& args); 667 668 SortedVector< sp<Track> > mTracks; 669 // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by 670 // DuplicatingThread 671 stream_type_t mStreamTypes[AUDIO_STREAM_CNT + 1]; 672 AudioStreamOut *mOutput; 673 674 float mMasterVolume; 675 nsecs_t mLastWriteTime; 676 int mNumWrites; 677 int mNumDelayedWrites; 678 bool mInWrite; 679 680 // FIXME rename these former local variables of threadLoop to standard "m" names 681 nsecs_t standbyTime; 682 size_t mSinkBufferSize; 683 684 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l() 685 uint32_t activeSleepTime; 686 uint32_t idleSleepTime; 687 688 uint32_t sleepTime; 689 690 // mixer status returned by prepareTracks_l() 691 mixer_state mMixerStatus; // current cycle 692 // previous cycle when in prepareTracks_l() 693 mixer_state mMixerStatusIgnoringFastTracks; 694 // FIXME or a separate ready state per track 695 696 // FIXME move these declarations into the specific sub-class that needs them 697 // MIXER only 698 uint32_t sleepTimeShift; 699 700 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value 701 nsecs_t standbyDelay; 702 703 // MIXER only 704 nsecs_t maxPeriod; 705 706 // DUPLICATING only 707 uint32_t writeFrames; 708 709 size_t mBytesRemaining; 710 size_t mCurrentWriteLength; 711 bool mUseAsyncWrite; 712 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is 713 // incremented each time a write(), a flush() or a standby() occurs. 714 // Bit 0 is set when a write blocks and indicates a callback is expected. 715 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence 716 // callbacks are ignored. 717 uint32_t mWriteAckSequence; 718 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is 719 // incremented each time a drain is requested or a flush() or standby() occurs. 720 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is 721 // expected. 722 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence 723 // callbacks are ignored. 724 uint32_t mDrainSequence; 725 // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait 726 // for async write callback in the thread loop before evaluating it 727 bool mSignalPending; 728 sp<AsyncCallbackThread> mCallbackThread; 729 730private: 731 // The HAL output sink is treated as non-blocking, but current implementation is blocking 732 sp<NBAIO_Sink> mOutputSink; 733 // If a fast mixer is present, the blocking pipe sink, otherwise clear 734 sp<NBAIO_Sink> mPipeSink; 735 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink 736 sp<NBAIO_Sink> mNormalSink; 737#ifdef TEE_SINK 738 // For dumpsys 739 sp<NBAIO_Sink> mTeeSink; 740 sp<NBAIO_Source> mTeeSource; 741#endif 742 uint32_t mScreenState; // cached copy of gScreenState 743 static const size_t kFastMixerLogSize = 4 * 1024; 744 sp<NBLog::Writer> mFastMixerNBLogWriter; 745public: 746 virtual bool hasFastMixer() const = 0; 747 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const 748 { FastTrackUnderruns dummy; return dummy; } 749 750protected: 751 // accessed by both binder threads and within threadLoop(), lock on mutex needed 752 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available 753 754private: 755 // timestamp latch: 756 // D input is written by threadLoop_write while mutex is unlocked, and read while locked 757 // Q output is written while locked, and read while locked 758 struct { 759 AudioTimestamp mTimestamp; 760 uint32_t mUnpresentedFrames; 761 } mLatchD, mLatchQ; 762 bool mLatchDValid; // true means mLatchD is valid, and clock it into latch at next opportunity 763 bool mLatchQValid; // true means mLatchQ is valid 764}; 765 766class MixerThread : public PlaybackThread { 767public: 768 MixerThread(const sp<AudioFlinger>& audioFlinger, 769 AudioStreamOut* output, 770 audio_io_handle_t id, 771 audio_devices_t device, 772 type_t type = MIXER); 773 virtual ~MixerThread(); 774 775 // Thread virtuals 776 777 virtual bool checkForNewParameter_l(const String8& keyValuePair, 778 status_t& status); 779 virtual void dumpInternals(int fd, const Vector<String16>& args); 780 781protected: 782 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove); 783 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId); 784 virtual void deleteTrackName_l(int name); 785 virtual uint32_t idleSleepTimeUs() const; 786 virtual uint32_t suspendSleepTimeUs() const; 787 virtual void cacheParameters_l(); 788 789 // threadLoop snippets 790 virtual ssize_t threadLoop_write(); 791 virtual void threadLoop_standby(); 792 virtual void threadLoop_mix(); 793 virtual void threadLoop_sleepTime(); 794 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove); 795 virtual uint32_t correctLatency_l(uint32_t latency) const; 796 797 AudioMixer* mAudioMixer; // normal mixer 798private: 799 // one-time initialization, no locks required 800 FastMixer* mFastMixer; // non-NULL if there is also a fast mixer 801 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread 802 803 // contents are not guaranteed to be consistent, no locks required 804 FastMixerDumpState mFastMixerDumpState; 805#ifdef STATE_QUEUE_DUMP 806 StateQueueObserverDump mStateQueueObserverDump; 807 StateQueueMutatorDump mStateQueueMutatorDump; 808#endif 809 AudioWatchdogDump mAudioWatchdogDump; 810 811 // accessible only within the threadLoop(), no locks required 812 // mFastMixer->sq() // for mutating and pushing state 813 int32_t mFastMixerFutex; // for cold idle 814 815public: 816 virtual bool hasFastMixer() const { return mFastMixer != NULL; } 817 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const { 818 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks); 819 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns; 820 } 821}; 822 823class DirectOutputThread : public PlaybackThread { 824public: 825 826 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 827 audio_io_handle_t id, audio_devices_t device); 828 virtual ~DirectOutputThread(); 829 830 // Thread virtuals 831 832 virtual bool checkForNewParameter_l(const String8& keyValuePair, 833 status_t& status); 834 835protected: 836 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId); 837 virtual void deleteTrackName_l(int name); 838 virtual uint32_t activeSleepTimeUs() const; 839 virtual uint32_t idleSleepTimeUs() const; 840 virtual uint32_t suspendSleepTimeUs() const; 841 virtual void cacheParameters_l(); 842 843 // threadLoop snippets 844 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove); 845 virtual void threadLoop_mix(); 846 virtual void threadLoop_sleepTime(); 847 848 // volumes last sent to audio HAL with stream->set_volume() 849 float mLeftVolFloat; 850 float mRightVolFloat; 851 852 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 853 audio_io_handle_t id, uint32_t device, ThreadBase::type_t type); 854 void processVolume_l(Track *track, bool lastTrack); 855 856 // prepareTracks_l() tells threadLoop_mix() the name of the single active track 857 sp<Track> mActiveTrack; 858public: 859 virtual bool hasFastMixer() const { return false; } 860}; 861 862class OffloadThread : public DirectOutputThread { 863public: 864 865 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 866 audio_io_handle_t id, uint32_t device); 867 virtual ~OffloadThread() {}; 868 869protected: 870 // threadLoop snippets 871 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove); 872 virtual void threadLoop_exit(); 873 874 virtual bool waitingAsyncCallback(); 875 virtual bool waitingAsyncCallback_l(); 876 virtual bool shouldStandby_l(); 877 virtual void onAddNewTrack_l(); 878 879private: 880 void flushHw_l(); 881 882private: 883 bool mHwPaused; 884 bool mFlushPending; 885 size_t mPausedWriteLength; // length in bytes of write interrupted by pause 886 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume 887 wp<Track> mPreviousTrack; // used to detect track switch 888}; 889 890class AsyncCallbackThread : public Thread { 891public: 892 893 AsyncCallbackThread(const wp<PlaybackThread>& playbackThread); 894 895 virtual ~AsyncCallbackThread(); 896 897 // Thread virtuals 898 virtual bool threadLoop(); 899 900 // RefBase 901 virtual void onFirstRef(); 902 903 void exit(); 904 void setWriteBlocked(uint32_t sequence); 905 void resetWriteBlocked(); 906 void setDraining(uint32_t sequence); 907 void resetDraining(); 908 909private: 910 const wp<PlaybackThread> mPlaybackThread; 911 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via 912 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used 913 // to indicate that the callback has been received via resetWriteBlocked() 914 uint32_t mWriteAckSequence; 915 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via 916 // setDraining(). The sequence is shifted one bit to the left and the lsb is used 917 // to indicate that the callback has been received via resetDraining() 918 uint32_t mDrainSequence; 919 Condition mWaitWorkCV; 920 Mutex mLock; 921}; 922 923class DuplicatingThread : public MixerThread { 924public: 925 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread, 926 audio_io_handle_t id); 927 virtual ~DuplicatingThread(); 928 929 // Thread virtuals 930 void addOutputTrack(MixerThread* thread); 931 void removeOutputTrack(MixerThread* thread); 932 uint32_t waitTimeMs() const { return mWaitTimeMs; } 933protected: 934 virtual uint32_t activeSleepTimeUs() const; 935 936private: 937 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks); 938protected: 939 // threadLoop snippets 940 virtual void threadLoop_mix(); 941 virtual void threadLoop_sleepTime(); 942 virtual ssize_t threadLoop_write(); 943 virtual void threadLoop_standby(); 944 virtual void cacheParameters_l(); 945 946private: 947 // called from threadLoop, addOutputTrack, removeOutputTrack 948 virtual void updateWaitTime_l(); 949protected: 950 virtual void saveOutputTracks(); 951 virtual void clearOutputTracks(); 952private: 953 954 uint32_t mWaitTimeMs; 955 SortedVector < sp<OutputTrack> > outputTracks; 956 SortedVector < sp<OutputTrack> > mOutputTracks; 957public: 958 virtual bool hasFastMixer() const { return false; } 959}; 960 961 962// record thread 963class RecordThread : public ThreadBase 964{ 965public: 966 967 class RecordTrack; 968 class ResamplerBufferProvider : public AudioBufferProvider 969 // derives from AudioBufferProvider interface for use by resampler 970 { 971 public: 972 ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { } 973 virtual ~ResamplerBufferProvider() { } 974 // AudioBufferProvider interface 975 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts); 976 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); 977 private: 978 RecordTrack * const mRecordTrack; 979 }; 980 981#include "RecordTracks.h" 982 983 RecordThread(const sp<AudioFlinger>& audioFlinger, 984 AudioStreamIn *input, 985 audio_io_handle_t id, 986 audio_devices_t outDevice, 987 audio_devices_t inDevice 988#ifdef TEE_SINK 989 , const sp<NBAIO_Sink>& teeSink 990#endif 991 ); 992 virtual ~RecordThread(); 993 994 // no addTrack_l ? 995 void destroyTrack_l(const sp<RecordTrack>& track); 996 void removeTrack_l(const sp<RecordTrack>& track); 997 998 void dumpInternals(int fd, const Vector<String16>& args); 999 void dumpTracks(int fd, const Vector<String16>& args); 1000 1001 // Thread virtuals 1002 virtual bool threadLoop(); 1003 1004 // RefBase 1005 virtual void onFirstRef(); 1006 1007 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; } 1008 1009 virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; } 1010 1011 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l( 1012 const sp<AudioFlinger::Client>& client, 1013 uint32_t sampleRate, 1014 audio_format_t format, 1015 audio_channel_mask_t channelMask, 1016 size_t *pFrameCount, 1017 int sessionId, 1018 int uid, 1019 IAudioFlinger::track_flags_t *flags, 1020 pid_t tid, 1021 status_t *status /*non-NULL*/); 1022 1023 status_t start(RecordTrack* recordTrack, 1024 AudioSystem::sync_event_t event, 1025 int triggerSession); 1026 1027 // ask the thread to stop the specified track, and 1028 // return true if the caller should then do it's part of the stopping process 1029 bool stop(RecordTrack* recordTrack); 1030 1031 void dump(int fd, const Vector<String16>& args); 1032 AudioStreamIn* clearInput(); 1033 virtual audio_stream_t* stream() const; 1034 1035 1036 virtual bool checkForNewParameter_l(const String8& keyValuePair, 1037 status_t& status); 1038 virtual void cacheParameters_l() {} 1039 virtual String8 getParameters(const String8& keys); 1040 virtual void audioConfigChanged_l( 1041 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients, 1042 int event, 1043 int param = 0); 1044 void readInputParameters_l(); 1045 virtual uint32_t getInputFramesLost(); 1046 1047 virtual status_t addEffectChain_l(const sp<EffectChain>& chain); 1048 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain); 1049 virtual uint32_t hasAudioSession(int sessionId) const; 1050 1051 // Return the set of unique session IDs across all tracks. 1052 // The keys are the session IDs, and the associated values are meaningless. 1053 // FIXME replace by Set [and implement Bag/Multiset for other uses]. 1054 KeyedVector<int, bool> sessionIds() const; 1055 1056 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 1057 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const; 1058 1059 static void syncStartEventCallback(const wp<SyncEvent>& event); 1060 1061 virtual size_t frameCount() const { return mFrameCount; } 1062 bool hasFastCapture() const { return false; } 1063 1064private: 1065 // Enter standby if not already in standby, and set mStandby flag 1066 void standbyIfNotAlreadyInStandby(); 1067 1068 // Call the HAL standby method unconditionally, and don't change mStandby flag 1069 void inputStandBy(); 1070 1071 AudioStreamIn *mInput; 1072 SortedVector < sp<RecordTrack> > mTracks; 1073 // mActiveTracks has dual roles: it indicates the current active track(s), and 1074 // is used together with mStartStopCond to indicate start()/stop() progress 1075 SortedVector< sp<RecordTrack> > mActiveTracks; 1076 // generation counter for mActiveTracks 1077 int mActiveTracksGen; 1078 Condition mStartStopCond; 1079 1080 // resampler converts input at HAL Hz to output at AudioRecord client Hz 1081 int16_t *mRsmpInBuffer; // see new[] for details on the size 1082 size_t mRsmpInFrames; // size of resampler input in frames 1083 size_t mRsmpInFramesP2;// size rounded up to a power-of-2 1084 1085 // rolling index that is never cleared 1086 int32_t mRsmpInRear; // last filled frame + 1 1087 1088 // For dumpsys 1089 const sp<NBAIO_Sink> mTeeSink; 1090 1091 const sp<MemoryDealer> mReadOnlyHeap; 1092}; 1093