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