AudioFlinger.h revision 77035d10a740914313500811b31a90ab948bd267
1/* 2** 3** Copyright 2007, 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 ANDROID_AUDIO_FLINGER_H 19#define ANDROID_AUDIO_FLINGER_H 20 21#include <stdint.h> 22#include <sys/types.h> 23#include <limits.h> 24 25#include <common_time/cc_helper.h> 26 27#include <media/IAudioFlinger.h> 28#include <media/IAudioFlingerClient.h> 29#include <media/IAudioTrack.h> 30#include <media/IAudioRecord.h> 31#include <media/AudioSystem.h> 32#include <media/AudioTrack.h> 33 34#include <utils/Atomic.h> 35#include <utils/Errors.h> 36#include <utils/threads.h> 37#include <utils/SortedVector.h> 38#include <utils/TypeHelpers.h> 39#include <utils/Vector.h> 40 41#include <binder/BinderService.h> 42#include <binder/MemoryDealer.h> 43 44#include <system/audio.h> 45#include <hardware/audio.h> 46#include <hardware/audio_policy.h> 47 48#include <media/AudioBufferProvider.h> 49#include <media/ExtendedAudioBufferProvider.h> 50#include "FastMixer.h" 51#include <media/nbaio/NBAIO.h> 52#include "AudioWatchdog.h" 53 54#include <powermanager/IPowerManager.h> 55 56namespace android { 57 58class audio_track_cblk_t; 59class effect_param_cblk_t; 60class AudioMixer; 61class AudioBuffer; 62class AudioResampler; 63class FastMixer; 64 65// ---------------------------------------------------------------------------- 66 67// AudioFlinger has a hard-coded upper limit of 2 channels for capture and playback. 68// There is support for > 2 channel tracks down-mixed to 2 channel output via a down-mix effect. 69// Adding full support for > 2 channel capture or playback would require more than simply changing 70// this #define. There is an independent hard-coded upper limit in AudioMixer; 71// removing that AudioMixer limit would be necessary but insufficient to support > 2 channels. 72// The macro FCC_2 highlights some (but not all) places where there is are 2-channel assumptions. 73// Search also for "2", "left", "right", "[0]", "[1]", ">> 16", "<< 16", etc. 74#define FCC_2 2 // FCC_2 = Fixed Channel Count 2 75 76static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3); 77 78class AudioFlinger : 79 public BinderService<AudioFlinger>, 80 public BnAudioFlinger 81{ 82 friend class BinderService<AudioFlinger>; // for AudioFlinger() 83public: 84 static const char* getServiceName() { return "media.audio_flinger"; } 85 86 virtual status_t dump(int fd, const Vector<String16>& args); 87 88 // IAudioFlinger interface, in binder opcode order 89 virtual sp<IAudioTrack> createTrack( 90 pid_t pid, 91 audio_stream_type_t streamType, 92 uint32_t sampleRate, 93 audio_format_t format, 94 audio_channel_mask_t channelMask, 95 size_t frameCount, 96 IAudioFlinger::track_flags_t *flags, 97 const sp<IMemory>& sharedBuffer, 98 audio_io_handle_t output, 99 pid_t tid, 100 int *sessionId, 101 status_t *status); 102 103 virtual sp<IAudioRecord> openRecord( 104 pid_t pid, 105 audio_io_handle_t input, 106 uint32_t sampleRate, 107 audio_format_t format, 108 audio_channel_mask_t channelMask, 109 size_t frameCount, 110 IAudioFlinger::track_flags_t flags, 111 pid_t tid, 112 int *sessionId, 113 status_t *status); 114 115 virtual uint32_t sampleRate(audio_io_handle_t output) const; 116 virtual int channelCount(audio_io_handle_t output) const; 117 virtual audio_format_t format(audio_io_handle_t output) const; 118 virtual size_t frameCount(audio_io_handle_t output) const; 119 virtual uint32_t latency(audio_io_handle_t output) const; 120 121 virtual status_t setMasterVolume(float value); 122 virtual status_t setMasterMute(bool muted); 123 124 virtual float masterVolume() const; 125 virtual bool masterMute() const; 126 127 virtual status_t setStreamVolume(audio_stream_type_t stream, float value, 128 audio_io_handle_t output); 129 virtual status_t setStreamMute(audio_stream_type_t stream, bool muted); 130 131 virtual float streamVolume(audio_stream_type_t stream, 132 audio_io_handle_t output) const; 133 virtual bool streamMute(audio_stream_type_t stream) const; 134 135 virtual status_t setMode(audio_mode_t mode); 136 137 virtual status_t setMicMute(bool state); 138 virtual bool getMicMute() const; 139 140 virtual status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs); 141 virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) const; 142 143 virtual void registerClient(const sp<IAudioFlingerClient>& client); 144 145 virtual size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 146 audio_channel_mask_t channelMask) const; 147 148 virtual audio_io_handle_t openOutput(audio_module_handle_t module, 149 audio_devices_t *pDevices, 150 uint32_t *pSamplingRate, 151 audio_format_t *pFormat, 152 audio_channel_mask_t *pChannelMask, 153 uint32_t *pLatencyMs, 154 audio_output_flags_t flags); 155 156 virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, 157 audio_io_handle_t output2); 158 159 virtual status_t closeOutput(audio_io_handle_t output); 160 161 virtual status_t suspendOutput(audio_io_handle_t output); 162 163 virtual status_t restoreOutput(audio_io_handle_t output); 164 165 virtual audio_io_handle_t openInput(audio_module_handle_t module, 166 audio_devices_t *pDevices, 167 uint32_t *pSamplingRate, 168 audio_format_t *pFormat, 169 audio_channel_mask_t *pChannelMask); 170 171 virtual status_t closeInput(audio_io_handle_t input); 172 173 virtual status_t setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output); 174 175 virtual status_t setVoiceVolume(float volume); 176 177 virtual status_t getRenderPosition(size_t *halFrames, size_t *dspFrames, 178 audio_io_handle_t output) const; 179 180 virtual unsigned int getInputFramesLost(audio_io_handle_t ioHandle) const; 181 182 virtual int newAudioSessionId(); 183 184 virtual void acquireAudioSessionId(int audioSession); 185 186 virtual void releaseAudioSessionId(int audioSession); 187 188 virtual status_t queryNumberEffects(uint32_t *numEffects) const; 189 190 virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const; 191 192 virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid, 193 effect_descriptor_t *descriptor) const; 194 195 virtual sp<IEffect> createEffect(pid_t pid, 196 effect_descriptor_t *pDesc, 197 const sp<IEffectClient>& effectClient, 198 int32_t priority, 199 audio_io_handle_t io, 200 int sessionId, 201 status_t *status, 202 int *id, 203 int *enabled); 204 205 virtual status_t moveEffects(int sessionId, audio_io_handle_t srcOutput, 206 audio_io_handle_t dstOutput); 207 208 virtual audio_module_handle_t loadHwModule(const char *name); 209 210 virtual uint32_t getPrimaryOutputSamplingRate(); 211 virtual size_t getPrimaryOutputFrameCount(); 212 213 virtual status_t onTransact( 214 uint32_t code, 215 const Parcel& data, 216 Parcel* reply, 217 uint32_t flags); 218 219 // end of IAudioFlinger interface 220 221 class SyncEvent; 222 223 typedef void (*sync_event_callback_t)(const wp<SyncEvent>& event) ; 224 225 class SyncEvent : public RefBase { 226 public: 227 SyncEvent(AudioSystem::sync_event_t type, 228 int triggerSession, 229 int listenerSession, 230 sync_event_callback_t callBack, 231 void *cookie) 232 : mType(type), mTriggerSession(triggerSession), mListenerSession(listenerSession), 233 mCallback(callBack), mCookie(cookie) 234 {} 235 236 virtual ~SyncEvent() {} 237 238 void trigger() { Mutex::Autolock _l(mLock); if (mCallback) mCallback(this); } 239 bool isCancelled() const { Mutex::Autolock _l(mLock); return (mCallback == NULL); } 240 void cancel() { Mutex::Autolock _l(mLock); mCallback = NULL; } 241 AudioSystem::sync_event_t type() const { return mType; } 242 int triggerSession() const { return mTriggerSession; } 243 int listenerSession() const { return mListenerSession; } 244 void *cookie() const { return mCookie; } 245 246 private: 247 const AudioSystem::sync_event_t mType; 248 const int mTriggerSession; 249 const int mListenerSession; 250 sync_event_callback_t mCallback; 251 void * const mCookie; 252 mutable Mutex mLock; 253 }; 254 255 sp<SyncEvent> createSyncEvent(AudioSystem::sync_event_t type, 256 int triggerSession, 257 int listenerSession, 258 sync_event_callback_t callBack, 259 void *cookie); 260 261private: 262 class AudioHwDevice; // fwd declaration for findSuitableHwDev_l 263 264 audio_mode_t getMode() const { return mMode; } 265 266 bool btNrecIsOff() const { return mBtNrecIsOff; } 267 268 AudioFlinger(); 269 virtual ~AudioFlinger(); 270 271 // call in any IAudioFlinger method that accesses mPrimaryHardwareDev 272 status_t initCheck() const { return mPrimaryHardwareDev == NULL ? 273 NO_INIT : NO_ERROR; } 274 275 // RefBase 276 virtual void onFirstRef(); 277 278 AudioHwDevice* findSuitableHwDev_l(audio_module_handle_t module, 279 audio_devices_t devices); 280 void purgeStaleEffects_l(); 281 282 // standby delay for MIXER and DUPLICATING playback threads is read from property 283 // ro.audio.flinger_standbytime_ms or defaults to kDefaultStandbyTimeInNsecs 284 static nsecs_t mStandbyTimeInNsecs; 285 286 // Internal dump utilities. 287 void dumpPermissionDenial(int fd, const Vector<String16>& args); 288 void dumpClients(int fd, const Vector<String16>& args); 289 void dumpInternals(int fd, const Vector<String16>& args); 290 291 // --- Client --- 292 class Client : public RefBase { 293 public: 294 Client(const sp<AudioFlinger>& audioFlinger, pid_t pid); 295 virtual ~Client(); 296 sp<MemoryDealer> heap() const; 297 pid_t pid() const { return mPid; } 298 sp<AudioFlinger> audioFlinger() const { return mAudioFlinger; } 299 300 bool reserveTimedTrack(); 301 void releaseTimedTrack(); 302 303 private: 304 Client(const Client&); 305 Client& operator = (const Client&); 306 const sp<AudioFlinger> mAudioFlinger; 307 const sp<MemoryDealer> mMemoryDealer; 308 const pid_t mPid; 309 310 Mutex mTimedTrackLock; 311 int mTimedTrackCount; 312 }; 313 314 // --- Notification Client --- 315 class NotificationClient : public IBinder::DeathRecipient { 316 public: 317 NotificationClient(const sp<AudioFlinger>& audioFlinger, 318 const sp<IAudioFlingerClient>& client, 319 pid_t pid); 320 virtual ~NotificationClient(); 321 322 sp<IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; } 323 324 // IBinder::DeathRecipient 325 virtual void binderDied(const wp<IBinder>& who); 326 327 private: 328 NotificationClient(const NotificationClient&); 329 NotificationClient& operator = (const NotificationClient&); 330 331 const sp<AudioFlinger> mAudioFlinger; 332 const pid_t mPid; 333 const sp<IAudioFlingerClient> mAudioFlingerClient; 334 }; 335 336 class TrackHandle; 337 class RecordHandle; 338 class RecordThread; 339 class PlaybackThread; 340 class MixerThread; 341 class DirectOutputThread; 342 class DuplicatingThread; 343 class Track; 344 class RecordTrack; 345 class EffectModule; 346 class EffectHandle; 347 class EffectChain; 348 struct AudioStreamOut; 349 struct AudioStreamIn; 350 351 class ThreadBase : public Thread { 352 public: 353 354 enum type_t { 355 MIXER, // Thread class is MixerThread 356 DIRECT, // Thread class is DirectOutputThread 357 DUPLICATING, // Thread class is DuplicatingThread 358 RECORD // Thread class is RecordThread 359 }; 360 361 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 362 audio_devices_t outDevice, audio_devices_t inDevice, type_t type); 363 virtual ~ThreadBase(); 364 365 void dumpBase(int fd, const Vector<String16>& args); 366 void dumpEffectChains(int fd, const Vector<String16>& args); 367 368 void clearPowerManager(); 369 370 // base for record and playback 371 class TrackBase : public ExtendedAudioBufferProvider, public RefBase { 372 373 public: 374 enum track_state { 375 IDLE, 376 TERMINATED, 377 FLUSHED, 378 STOPPED, 379 // next 2 states are currently used for fast tracks only 380 STOPPING_1, // waiting for first underrun 381 STOPPING_2, // waiting for presentation complete 382 RESUMING, 383 ACTIVE, 384 PAUSING, 385 PAUSED 386 }; 387 388 TrackBase(ThreadBase *thread, 389 const sp<Client>& client, 390 uint32_t sampleRate, 391 audio_format_t format, 392 audio_channel_mask_t channelMask, 393 size_t frameCount, 394 const sp<IMemory>& sharedBuffer, 395 int sessionId); 396 virtual ~TrackBase(); 397 398 virtual status_t start(AudioSystem::sync_event_t event, 399 int triggerSession) = 0; 400 virtual void stop() = 0; 401 sp<IMemory> getCblk() const { return mCblkMemory; } 402 audio_track_cblk_t* cblk() const { return mCblk; } 403 int sessionId() const { return mSessionId; } 404 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 405 406 protected: 407 TrackBase(const TrackBase&); 408 TrackBase& operator = (const TrackBase&); 409 410 // AudioBufferProvider interface 411 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) = 0; 412 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); 413 414 // ExtendedAudioBufferProvider interface is only needed for Track, 415 // but putting it in TrackBase avoids the complexity of virtual inheritance 416 virtual size_t framesReady() const { return SIZE_MAX; } 417 418 audio_format_t format() const { 419 return mFormat; 420 } 421 422 int channelCount() const { return mChannelCount; } 423 424 audio_channel_mask_t channelMask() const { return mChannelMask; } 425 426 uint32_t sampleRate() const; // FIXME inline after cblk sr moved 427 428 // Return a pointer to the start of a contiguous slice of the track buffer. 429 // Parameter 'offset' is the requested start position, expressed in 430 // monotonically increasing frame units relative to the track epoch. 431 // Parameter 'frames' is the requested length, also in frame units. 432 // Always returns non-NULL. It is the caller's responsibility to 433 // verify that this will be successful; the result of calling this 434 // function with invalid 'offset' or 'frames' is undefined. 435 void* getBuffer(uint32_t offset, uint32_t frames) const; 436 437 bool isStopped() const { 438 return (mState == STOPPED || mState == FLUSHED); 439 } 440 441 // for fast tracks only 442 bool isStopping() const { 443 return mState == STOPPING_1 || mState == STOPPING_2; 444 } 445 bool isStopping_1() const { 446 return mState == STOPPING_1; 447 } 448 bool isStopping_2() const { 449 return mState == STOPPING_2; 450 } 451 452 bool isTerminated() const { 453 return mState == TERMINATED; 454 } 455 456 bool step(); // mStepCount is an implicit input 457 void reset(); 458 459 virtual bool isOut() const = 0; // true for Track and TimedTrack, false for RecordTrack, 460 // this could be a track type if needed later 461 462 const wp<ThreadBase> mThread; 463 /*const*/ sp<Client> mClient; // see explanation at ~TrackBase() why not const 464 sp<IMemory> mCblkMemory; 465 audio_track_cblk_t* mCblk; 466 void* mBuffer; // start of track buffer, typically in shared memory 467 void* mBufferEnd; // &mBuffer[mFrameCount * frameSize], where frameSize 468 // is based on mChannelCount and 16-bit samples 469 uint32_t mStepCount; // saves AudioBufferProvider::Buffer::frameCount as of 470 // time of releaseBuffer() for later use by step() 471 // we don't really need a lock for these 472 track_state mState; 473 const uint32_t mSampleRate; // initial sample rate only; for tracks which 474 // support dynamic rates, the current value is in control block 475 const audio_format_t mFormat; 476 const audio_channel_mask_t mChannelMask; 477 const uint8_t mChannelCount; 478 const size_t mFrameSize; // AudioFlinger's view of frame size in shared memory, 479 // where for AudioTrack (but not AudioRecord), 480 // 8-bit PCM samples are stored as 16-bit 481 const size_t mFrameCount;// size of track buffer given at createTrack() or 482 // openRecord(), and then adjusted as needed 483 bool mStepServerFailed; 484 const int mSessionId; 485 Vector < sp<SyncEvent> >mSyncEvents; 486 }; 487 488 enum { 489 CFG_EVENT_IO, 490 CFG_EVENT_PRIO 491 }; 492 493 class ConfigEvent { 494 public: 495 ConfigEvent(int type) : mType(type) {} 496 virtual ~ConfigEvent() {} 497 498 int type() const { return mType; } 499 500 virtual void dump(char *buffer, size_t size) = 0; 501 502 private: 503 const int mType; 504 }; 505 506 class IoConfigEvent : public ConfigEvent { 507 public: 508 IoConfigEvent(int event, int param) : 509 ConfigEvent(CFG_EVENT_IO), mEvent(event), mParam(event) {} 510 virtual ~IoConfigEvent() {} 511 512 int event() const { return mEvent; } 513 int param() const { return mParam; } 514 515 virtual void dump(char *buffer, size_t size) { 516 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam); 517 } 518 519 private: 520 const int mEvent; 521 const int mParam; 522 }; 523 524 class PrioConfigEvent : public ConfigEvent { 525 public: 526 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) : 527 ConfigEvent(CFG_EVENT_PRIO), mPid(pid), mTid(tid), mPrio(prio) {} 528 virtual ~PrioConfigEvent() {} 529 530 pid_t pid() const { return mPid; } 531 pid_t tid() const { return mTid; } 532 int32_t prio() const { return mPrio; } 533 534 virtual void dump(char *buffer, size_t size) { 535 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio); 536 } 537 538 private: 539 const pid_t mPid; 540 const pid_t mTid; 541 const int32_t mPrio; 542 }; 543 544 545 class PMDeathRecipient : public IBinder::DeathRecipient { 546 public: 547 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {} 548 virtual ~PMDeathRecipient() {} 549 550 // IBinder::DeathRecipient 551 virtual void binderDied(const wp<IBinder>& who); 552 553 private: 554 PMDeathRecipient(const PMDeathRecipient&); 555 PMDeathRecipient& operator = (const PMDeathRecipient&); 556 557 wp<ThreadBase> mThread; 558 }; 559 560 virtual status_t initCheck() const = 0; 561 562 // static externally-visible 563 type_t type() const { return mType; } 564 audio_io_handle_t id() const { return mId;} 565 566 // dynamic externally-visible 567 uint32_t sampleRate() const { return mSampleRate; } 568 int channelCount() const { return mChannelCount; } 569 audio_channel_mask_t channelMask() const { return mChannelMask; } 570 audio_format_t format() const { return mFormat; } 571 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects, 572 // and returns the normal mix buffer's frame count. 573 size_t frameCount() const { return mNormalFrameCount; } 574 // Return's the HAL's frame count i.e. fast mixer buffer size. 575 size_t frameCountHAL() const { return mFrameCount; } 576 577 // Should be "virtual status_t requestExitAndWait()" and override same 578 // method in Thread, but Thread::requestExitAndWait() is not yet virtual. 579 void exit(); 580 virtual bool checkForNewParameters_l() = 0; 581 virtual status_t setParameters(const String8& keyValuePairs); 582 virtual String8 getParameters(const String8& keys) = 0; 583 virtual void audioConfigChanged_l(int event, int param = 0) = 0; 584 void sendIoConfigEvent(int event, int param = 0); 585 void sendIoConfigEvent_l(int event, int param = 0); 586 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio); 587 void processConfigEvents(); 588 589 // see note at declaration of mStandby, mOutDevice and mInDevice 590 bool standby() const { return mStandby; } 591 audio_devices_t outDevice() const { return mOutDevice; } 592 audio_devices_t inDevice() const { return mInDevice; } 593 594 virtual audio_stream_t* stream() const = 0; 595 596 sp<EffectHandle> createEffect_l( 597 const sp<AudioFlinger::Client>& client, 598 const sp<IEffectClient>& effectClient, 599 int32_t priority, 600 int sessionId, 601 effect_descriptor_t *desc, 602 int *enabled, 603 status_t *status); 604 void disconnectEffect(const sp< EffectModule>& effect, 605 EffectHandle *handle, 606 bool unpinIfLast); 607 608 // return values for hasAudioSession (bit field) 609 enum effect_state { 610 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one 611 // effect 612 TRACK_SESSION = 0x2 // the audio session corresponds to at least one 613 // track 614 }; 615 616 // get effect chain corresponding to session Id. 617 sp<EffectChain> getEffectChain(int sessionId); 618 // same as getEffectChain() but must be called with ThreadBase mutex locked 619 sp<EffectChain> getEffectChain_l(int sessionId) const; 620 // add an effect chain to the chain list (mEffectChains) 621 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0; 622 // remove an effect chain from the chain list (mEffectChains) 623 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0; 624 // lock all effect chains Mutexes. Must be called before releasing the 625 // ThreadBase mutex before processing the mixer and effects. This guarantees the 626 // integrity of the chains during the process. 627 // Also sets the parameter 'effectChains' to current value of mEffectChains. 628 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains); 629 // unlock effect chains after process 630 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains); 631 // set audio mode to all effect chains 632 void setMode(audio_mode_t mode); 633 // get effect module with corresponding ID on specified audio session 634 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId); 635 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId); 636 // add and effect module. Also creates the effect chain is none exists for 637 // the effects audio session 638 status_t addEffect_l(const sp< EffectModule>& effect); 639 // remove and effect module. Also removes the effect chain is this was the last 640 // effect 641 void removeEffect_l(const sp< EffectModule>& effect); 642 // detach all tracks connected to an auxiliary effect 643 virtual void detachAuxEffect_l(int effectId) {} 644 // returns either EFFECT_SESSION if effects on this audio session exist in one 645 // chain, or TRACK_SESSION if tracks on this audio session exist, or both 646 virtual uint32_t hasAudioSession(int sessionId) const = 0; 647 // the value returned by default implementation is not important as the 648 // strategy is only meaningful for PlaybackThread which implements this method 649 virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; } 650 651 // suspend or restore effect according to the type of effect passed. a NULL 652 // type pointer means suspend all effects in the session 653 void setEffectSuspended(const effect_uuid_t *type, 654 bool suspend, 655 int sessionId = AUDIO_SESSION_OUTPUT_MIX); 656 // check if some effects must be suspended/restored when an effect is enabled 657 // or disabled 658 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 659 bool enabled, 660 int sessionId = AUDIO_SESSION_OUTPUT_MIX); 661 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 662 bool enabled, 663 int sessionId = AUDIO_SESSION_OUTPUT_MIX); 664 665 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0; 666 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0; 667 668 669 mutable Mutex mLock; 670 671 protected: 672 673 // entry describing an effect being suspended in mSuspendedSessions keyed vector 674 class SuspendedSessionDesc : public RefBase { 675 public: 676 SuspendedSessionDesc() : mRefCount(0) {} 677 678 int mRefCount; // number of active suspend requests 679 effect_uuid_t mType; // effect type UUID 680 }; 681 682 void acquireWakeLock(); 683 void acquireWakeLock_l(); 684 void releaseWakeLock(); 685 void releaseWakeLock_l(); 686 void setEffectSuspended_l(const effect_uuid_t *type, 687 bool suspend, 688 int sessionId); 689 // updated mSuspendedSessions when an effect suspended or restored 690 void updateSuspendedSessions_l(const effect_uuid_t *type, 691 bool suspend, 692 int sessionId); 693 // check if some effects must be suspended when an effect chain is added 694 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain); 695 696 virtual void preExit() { } 697 698 friend class AudioFlinger; // for mEffectChains 699 700 const type_t mType; 701 702 // Used by parameters, config events, addTrack_l, exit 703 Condition mWaitWorkCV; 704 705 const sp<AudioFlinger> mAudioFlinger; 706 uint32_t mSampleRate; 707 size_t mFrameCount; // output HAL, direct output, record 708 size_t mNormalFrameCount; // normal mixer and effects 709 audio_channel_mask_t mChannelMask; 710 uint16_t mChannelCount; 711 size_t mFrameSize; 712 audio_format_t mFormat; 713 714 // Parameter sequence by client: binder thread calling setParameters(): 715 // 1. Lock mLock 716 // 2. Append to mNewParameters 717 // 3. mWaitWorkCV.signal 718 // 4. mParamCond.waitRelative with timeout 719 // 5. read mParamStatus 720 // 6. mWaitWorkCV.signal 721 // 7. Unlock 722 // 723 // Parameter sequence by server: threadLoop calling checkForNewParameters_l(): 724 // 1. Lock mLock 725 // 2. If there is an entry in mNewParameters proceed ... 726 // 2. Read first entry in mNewParameters 727 // 3. Process 728 // 4. Remove first entry from mNewParameters 729 // 5. Set mParamStatus 730 // 6. mParamCond.signal 731 // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus) 732 // 8. Unlock 733 Condition mParamCond; 734 Vector<String8> mNewParameters; 735 status_t mParamStatus; 736 737 Vector<ConfigEvent *> mConfigEvents; 738 739 // These fields are written and read by thread itself without lock or barrier, 740 // and read by other threads without lock or barrier via standby() , outDevice() 741 // and inDevice(). 742 // Because of the absence of a lock or barrier, any other thread that reads 743 // these fields must use the information in isolation, or be prepared to deal 744 // with possibility that it might be inconsistent with other information. 745 bool mStandby; // Whether thread is currently in standby. 746 audio_devices_t mOutDevice; // output device 747 audio_devices_t mInDevice; // input device 748 audio_source_t mAudioSource; // (see audio.h, audio_source_t) 749 750 const audio_io_handle_t mId; 751 Vector< sp<EffectChain> > mEffectChains; 752 753 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit 754 char mName[kNameLength]; 755 sp<IPowerManager> mPowerManager; 756 sp<IBinder> mWakeLockToken; 757 const sp<PMDeathRecipient> mDeathRecipient; 758 // list of suspended effects per session and per type. The first vector is 759 // keyed by session ID, the second by type UUID timeLow field 760 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > > 761 mSuspendedSessions; 762 }; 763 764 struct stream_type_t { 765 stream_type_t() 766 : volume(1.0f), 767 mute(false) 768 { 769 } 770 float volume; 771 bool mute; 772 }; 773 774 // --- PlaybackThread --- 775 class PlaybackThread : public ThreadBase { 776 public: 777 778 enum mixer_state { 779 MIXER_IDLE, // no active tracks 780 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready 781 MIXER_TRACKS_READY // at least one active track, and at least one track has data 782 // standby mode does not have an enum value 783 // suspend by audio policy manager is orthogonal to mixer state 784 }; 785 786 // playback track 787 class Track : public TrackBase, public VolumeProvider { 788 public: 789 Track( PlaybackThread *thread, 790 const sp<Client>& client, 791 audio_stream_type_t streamType, 792 uint32_t sampleRate, 793 audio_format_t format, 794 audio_channel_mask_t channelMask, 795 size_t frameCount, 796 const sp<IMemory>& sharedBuffer, 797 int sessionId, 798 IAudioFlinger::track_flags_t flags); 799 virtual ~Track(); 800 801 static void appendDumpHeader(String8& result); 802 void dump(char* buffer, size_t size); 803 virtual status_t start(AudioSystem::sync_event_t event = 804 AudioSystem::SYNC_EVENT_NONE, 805 int triggerSession = 0); 806 virtual void stop(); 807 void pause(); 808 809 void flush(); 810 void destroy(); 811 void mute(bool); 812 int name() const { return mName; } 813 814 audio_stream_type_t streamType() const { 815 return mStreamType; 816 } 817 status_t attachAuxEffect(int EffectId); 818 void setAuxBuffer(int EffectId, int32_t *buffer); 819 int32_t *auxBuffer() const { return mAuxBuffer; } 820 void setMainBuffer(int16_t *buffer) { mMainBuffer = buffer; } 821 int16_t *mainBuffer() const { return mMainBuffer; } 822 int auxEffectId() const { return mAuxEffectId; } 823 824 // implement FastMixerState::VolumeProvider interface 825 virtual uint32_t getVolumeLR(); 826 827 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 828 829 protected: 830 // for numerous 831 friend class PlaybackThread; 832 friend class MixerThread; 833 friend class DirectOutputThread; 834 835 Track(const Track&); 836 Track& operator = (const Track&); 837 838 // AudioBufferProvider interface 839 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, 840 int64_t pts = kInvalidPTS); 841 // releaseBuffer() not overridden 842 843 virtual size_t framesReady() const; 844 845 bool isMuted() const { return mMute; } 846 bool isPausing() const { 847 return mState == PAUSING; 848 } 849 bool isPaused() const { 850 return mState == PAUSED; 851 } 852 bool isResuming() const { 853 return mState == RESUMING; 854 } 855 bool isReady() const; 856 void setPaused() { mState = PAUSED; } 857 void reset(); 858 859 bool isOutputTrack() const { 860 return (mStreamType == AUDIO_STREAM_CNT); 861 } 862 863 sp<IMemory> sharedBuffer() const { return mSharedBuffer; } 864 865 // framesWritten is cumulative, never reset, and is shared all tracks 866 // audioHalFrames is derived from output latency 867 // FIXME parameters not needed, could get them from the thread 868 bool presentationComplete(size_t framesWritten, size_t audioHalFrames); 869 870 public: 871 void triggerEvents(AudioSystem::sync_event_t type); 872 virtual bool isTimedTrack() const { return false; } 873 bool isFastTrack() const { return (mFlags & IAudioFlinger::TRACK_FAST) != 0; } 874 virtual bool isOut() const; 875 876 protected: 877 878 // written by Track::mute() called by binder thread(s), without a mutex or barrier. 879 // read by Track::isMuted() called by playback thread, also without a mutex or barrier. 880 // The lack of mutex or barrier is safe because the mute status is only used by itself. 881 bool mMute; 882 883 // FILLED state is used for suppressing volume ramp at begin of playing 884 enum {FS_INVALID, FS_FILLING, FS_FILLED, FS_ACTIVE}; 885 mutable uint8_t mFillingUpStatus; 886 int8_t mRetryCount; 887 const sp<IMemory> mSharedBuffer; 888 bool mResetDone; 889 const audio_stream_type_t mStreamType; 890 int mName; // track name on the normal mixer, 891 // allocated statically at track creation time, 892 // and is even allocated (though unused) for fast tracks 893 // FIXME don't allocate track name for fast tracks 894 int16_t *mMainBuffer; 895 int32_t *mAuxBuffer; 896 int mAuxEffectId; 897 bool mHasVolumeController; 898 size_t mPresentationCompleteFrames; // number of frames written to the 899 // audio HAL when this track will be fully rendered 900 // zero means not monitoring 901 private: 902 IAudioFlinger::track_flags_t mFlags; 903 904 // The following fields are only for fast tracks, and should be in a subclass 905 int mFastIndex; // index within FastMixerState::mFastTracks[]; 906 // either mFastIndex == -1 if not isFastTrack() 907 // or 0 < mFastIndex < FastMixerState::kMaxFast because 908 // index 0 is reserved for normal mixer's submix; 909 // index is allocated statically at track creation time 910 // but the slot is only used if track is active 911 FastTrackUnderruns mObservedUnderruns; // Most recently observed value of 912 // mFastMixerDumpState.mTracks[mFastIndex].mUnderruns 913 uint32_t mUnderrunCount; // Counter of total number of underruns, never reset 914 volatile float mCachedVolume; // combined master volume and stream type volume; 915 // 'volatile' means accessed without lock or 916 // barrier, but is read/written atomically 917 }; // end of Track 918 919 class TimedTrack : public Track { 920 public: 921 static sp<TimedTrack> create(PlaybackThread *thread, 922 const sp<Client>& client, 923 audio_stream_type_t streamType, 924 uint32_t sampleRate, 925 audio_format_t format, 926 audio_channel_mask_t channelMask, 927 size_t frameCount, 928 const sp<IMemory>& sharedBuffer, 929 int sessionId); 930 virtual ~TimedTrack(); 931 932 class TimedBuffer { 933 public: 934 TimedBuffer(); 935 TimedBuffer(const sp<IMemory>& buffer, int64_t pts); 936 const sp<IMemory>& buffer() const { return mBuffer; } 937 int64_t pts() const { return mPTS; } 938 uint32_t position() const { return mPosition; } 939 void setPosition(uint32_t pos) { mPosition = pos; } 940 private: 941 sp<IMemory> mBuffer; 942 int64_t mPTS; 943 uint32_t mPosition; 944 }; 945 946 // Mixer facing methods. 947 virtual bool isTimedTrack() const { return true; } 948 virtual size_t framesReady() const; 949 950 // AudioBufferProvider interface 951 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, 952 int64_t pts); 953 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); 954 955 // Client/App facing methods. 956 status_t allocateTimedBuffer(size_t size, 957 sp<IMemory>* buffer); 958 status_t queueTimedBuffer(const sp<IMemory>& buffer, 959 int64_t pts); 960 status_t setMediaTimeTransform(const LinearTransform& xform, 961 TimedAudioTrack::TargetTimeline target); 962 963 private: 964 TimedTrack(PlaybackThread *thread, 965 const sp<Client>& client, 966 audio_stream_type_t streamType, 967 uint32_t sampleRate, 968 audio_format_t format, 969 audio_channel_mask_t channelMask, 970 size_t frameCount, 971 const sp<IMemory>& sharedBuffer, 972 int sessionId); 973 974 void timedYieldSamples_l(AudioBufferProvider::Buffer* buffer); 975 void timedYieldSilence_l(uint32_t numFrames, 976 AudioBufferProvider::Buffer* buffer); 977 void trimTimedBufferQueue_l(); 978 void trimTimedBufferQueueHead_l(const char* logTag); 979 void updateFramesPendingAfterTrim_l(const TimedBuffer& buf, 980 const char* logTag); 981 982 uint64_t mLocalTimeFreq; 983 LinearTransform mLocalTimeToSampleTransform; 984 LinearTransform mMediaTimeToSampleTransform; 985 sp<MemoryDealer> mTimedMemoryDealer; 986 987 Vector<TimedBuffer> mTimedBufferQueue; 988 bool mQueueHeadInFlight; 989 bool mTrimQueueHeadOnRelease; 990 uint32_t mFramesPendingInQueue; 991 992 uint8_t* mTimedSilenceBuffer; 993 uint32_t mTimedSilenceBufferSize; 994 mutable Mutex mTimedBufferQueueLock; 995 bool mTimedAudioOutputOnTime; 996 CCHelper mCCHelper; 997 998 Mutex mMediaTimeTransformLock; 999 LinearTransform mMediaTimeTransform; 1000 bool mMediaTimeTransformValid; 1001 TimedAudioTrack::TargetTimeline mMediaTimeTransformTarget; 1002 }; 1003 1004 1005 // playback track, used by DuplicatingThread 1006 class OutputTrack : public Track { 1007 public: 1008 1009 class Buffer : public AudioBufferProvider::Buffer { 1010 public: 1011 int16_t *mBuffer; 1012 }; 1013 1014 OutputTrack(PlaybackThread *thread, 1015 DuplicatingThread *sourceThread, 1016 uint32_t sampleRate, 1017 audio_format_t format, 1018 audio_channel_mask_t channelMask, 1019 size_t frameCount); 1020 virtual ~OutputTrack(); 1021 1022 virtual status_t start(AudioSystem::sync_event_t event = 1023 AudioSystem::SYNC_EVENT_NONE, 1024 int triggerSession = 0); 1025 virtual void stop(); 1026 bool write(int16_t* data, uint32_t frames); 1027 bool bufferQueueEmpty() const { return mBufferQueue.size() == 0; } 1028 bool isActive() const { return mActive; } 1029 const wp<ThreadBase>& thread() const { return mThread; } 1030 1031 private: 1032 1033 enum { 1034 NO_MORE_BUFFERS = 0x80000001, // same in AudioTrack.h, ok to be different value 1035 }; 1036 1037 status_t obtainBuffer(AudioBufferProvider::Buffer* buffer, 1038 uint32_t waitTimeMs); 1039 void clearBufferQueue(); 1040 1041 // Maximum number of pending buffers allocated by OutputTrack::write() 1042 static const uint8_t kMaxOverFlowBuffers = 10; 1043 1044 Vector < Buffer* > mBufferQueue; 1045 AudioBufferProvider::Buffer mOutBuffer; 1046 bool mActive; 1047 DuplicatingThread* const mSourceThread; // for waitTimeMs() in write() 1048 void* mBuffers; // starting address of buffers in plain memory 1049 }; // end of OutputTrack 1050 1051 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 1052 audio_io_handle_t id, audio_devices_t device, type_t type); 1053 virtual ~PlaybackThread(); 1054 1055 void dump(int fd, const Vector<String16>& args); 1056 1057 // Thread virtuals 1058 virtual status_t readyToRun(); 1059 virtual bool threadLoop(); 1060 1061 // RefBase 1062 virtual void onFirstRef(); 1063 1064protected: 1065 // Code snippets that were lifted up out of threadLoop() 1066 virtual void threadLoop_mix() = 0; 1067 virtual void threadLoop_sleepTime() = 0; 1068 virtual void threadLoop_write(); 1069 virtual void threadLoop_standby(); 1070 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove); 1071 1072 // prepareTracks_l reads and writes mActiveTracks, and returns 1073 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller 1074 // is responsible for clearing or destroying this Vector later on, when it 1075 // is safe to do so. That will drop the final ref count and destroy the tracks. 1076 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0; 1077 1078 // ThreadBase virtuals 1079 virtual void preExit(); 1080 1081public: 1082 1083 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; } 1084 1085 // return estimated latency in milliseconds, as reported by HAL 1086 uint32_t latency() const; 1087 // same, but lock must already be held 1088 uint32_t latency_l() const; 1089 1090 void setMasterVolume(float value); 1091 void setMasterMute(bool muted); 1092 1093 void setStreamVolume(audio_stream_type_t stream, float value); 1094 void setStreamMute(audio_stream_type_t stream, bool muted); 1095 1096 float streamVolume(audio_stream_type_t stream) const; 1097 1098 sp<Track> createTrack_l( 1099 const sp<AudioFlinger::Client>& client, 1100 audio_stream_type_t streamType, 1101 uint32_t sampleRate, 1102 audio_format_t format, 1103 audio_channel_mask_t channelMask, 1104 size_t frameCount, 1105 const sp<IMemory>& sharedBuffer, 1106 int sessionId, 1107 IAudioFlinger::track_flags_t *flags, 1108 pid_t tid, 1109 status_t *status); 1110 1111 AudioStreamOut* getOutput() const; 1112 AudioStreamOut* clearOutput(); 1113 virtual audio_stream_t* stream() const; 1114 1115 // a very large number of suspend() will eventually wraparound, but unlikely 1116 void suspend() { (void) android_atomic_inc(&mSuspended); } 1117 void restore() 1118 { 1119 // if restore() is done without suspend(), get back into 1120 // range so that the next suspend() will operate correctly 1121 if (android_atomic_dec(&mSuspended) <= 0) { 1122 android_atomic_release_store(0, &mSuspended); 1123 } 1124 } 1125 bool isSuspended() const 1126 { return android_atomic_acquire_load(&mSuspended) > 0; } 1127 1128 virtual String8 getParameters(const String8& keys); 1129 virtual void audioConfigChanged_l(int event, int param = 0); 1130 status_t getRenderPosition(size_t *halFrames, size_t *dspFrames); 1131 int16_t *mixBuffer() const { return mMixBuffer; }; 1132 1133 virtual void detachAuxEffect_l(int effectId); 1134 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track, 1135 int EffectId); 1136 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track, 1137 int EffectId); 1138 1139 virtual status_t addEffectChain_l(const sp<EffectChain>& chain); 1140 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain); 1141 virtual uint32_t hasAudioSession(int sessionId) const; 1142 virtual uint32_t getStrategyForSession_l(int sessionId); 1143 1144 1145 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 1146 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const; 1147 void invalidateTracks(audio_stream_type_t streamType); 1148 1149 1150 protected: 1151 int16_t* mMixBuffer; 1152 1153 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from 1154 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle 1155 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to 1156 // workaround that restriction. 1157 // 'volatile' means accessed via atomic operations and no lock. 1158 volatile int32_t mSuspended; 1159 1160 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples 1161 // mFramesWritten would be better, or 64-bit even better 1162 size_t mBytesWritten; 1163 private: 1164 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a 1165 // PlaybackThread needs to find out if master-muted, it checks it's local 1166 // copy rather than the one in AudioFlinger. This optimization saves a lock. 1167 bool mMasterMute; 1168 void setMasterMute_l(bool muted) { mMasterMute = muted; } 1169 protected: 1170 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<> 1171 1172 // Allocate a track name for a given channel mask. 1173 // Returns name >= 0 if successful, -1 on failure. 1174 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0; 1175 virtual void deleteTrackName_l(int name) = 0; 1176 1177 // Time to sleep between cycles when: 1178 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED 1179 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE 1180 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us 1181 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write() 1182 // No sleep in standby mode; waits on a condition 1183 1184 // Code snippets that are temporarily lifted up out of threadLoop() until the merge 1185 void checkSilentMode_l(); 1186 1187 // Non-trivial for DUPLICATING only 1188 virtual void saveOutputTracks() { } 1189 virtual void clearOutputTracks() { } 1190 1191 // Cache various calculated values, at threadLoop() entry and after a parameter change 1192 virtual void cacheParameters_l(); 1193 1194 virtual uint32_t correctLatency_l(uint32_t latency) const; 1195 1196 private: 1197 1198 friend class AudioFlinger; // for numerous 1199 1200 PlaybackThread(const Client&); 1201 PlaybackThread& operator = (const PlaybackThread&); 1202 1203 status_t addTrack_l(const sp<Track>& track); 1204 void destroyTrack_l(const sp<Track>& track); 1205 void removeTrack_l(const sp<Track>& track); 1206 1207 void readOutputParameters(); 1208 1209 virtual void dumpInternals(int fd, const Vector<String16>& args); 1210 void dumpTracks(int fd, const Vector<String16>& args); 1211 1212 SortedVector< sp<Track> > mTracks; 1213 // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by 1214 // DuplicatingThread 1215 stream_type_t mStreamTypes[AUDIO_STREAM_CNT + 1]; 1216 AudioStreamOut *mOutput; 1217 1218 float mMasterVolume; 1219 nsecs_t mLastWriteTime; 1220 int mNumWrites; 1221 int mNumDelayedWrites; 1222 bool mInWrite; 1223 1224 // FIXME rename these former local variables of threadLoop to standard "m" names 1225 nsecs_t standbyTime; 1226 size_t mixBufferSize; 1227 1228 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l() 1229 uint32_t activeSleepTime; 1230 uint32_t idleSleepTime; 1231 1232 uint32_t sleepTime; 1233 1234 // mixer status returned by prepareTracks_l() 1235 mixer_state mMixerStatus; // current cycle 1236 // previous cycle when in prepareTracks_l() 1237 mixer_state mMixerStatusIgnoringFastTracks; 1238 // FIXME or a separate ready state per track 1239 1240 // FIXME move these declarations into the specific sub-class that needs them 1241 // MIXER only 1242 uint32_t sleepTimeShift; 1243 1244 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value 1245 nsecs_t standbyDelay; 1246 1247 // MIXER only 1248 nsecs_t maxPeriod; 1249 1250 // DUPLICATING only 1251 uint32_t writeFrames; 1252 1253 private: 1254 // The HAL output sink is treated as non-blocking, but current implementation is blocking 1255 sp<NBAIO_Sink> mOutputSink; 1256 // If a fast mixer is present, the blocking pipe sink, otherwise clear 1257 sp<NBAIO_Sink> mPipeSink; 1258 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink 1259 sp<NBAIO_Sink> mNormalSink; 1260 // For dumpsys 1261 sp<NBAIO_Sink> mTeeSink; 1262 sp<NBAIO_Source> mTeeSource; 1263 uint32_t mScreenState; // cached copy of gScreenState 1264 public: 1265 virtual bool hasFastMixer() const = 0; 1266 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const 1267 { FastTrackUnderruns dummy; return dummy; } 1268 1269 protected: 1270 // accessed by both binder threads and within threadLoop(), lock on mutex needed 1271 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available 1272 1273 }; 1274 1275 class MixerThread : public PlaybackThread { 1276 public: 1277 MixerThread(const sp<AudioFlinger>& audioFlinger, 1278 AudioStreamOut* output, 1279 audio_io_handle_t id, 1280 audio_devices_t device, 1281 type_t type = MIXER); 1282 virtual ~MixerThread(); 1283 1284 // Thread virtuals 1285 1286 virtual bool checkForNewParameters_l(); 1287 virtual void dumpInternals(int fd, const Vector<String16>& args); 1288 1289 protected: 1290 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove); 1291 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId); 1292 virtual void deleteTrackName_l(int name); 1293 virtual uint32_t idleSleepTimeUs() const; 1294 virtual uint32_t suspendSleepTimeUs() const; 1295 virtual void cacheParameters_l(); 1296 1297 // threadLoop snippets 1298 virtual void threadLoop_write(); 1299 virtual void threadLoop_standby(); 1300 virtual void threadLoop_mix(); 1301 virtual void threadLoop_sleepTime(); 1302 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove); 1303 virtual uint32_t correctLatency_l(uint32_t latency) const; 1304 1305 AudioMixer* mAudioMixer; // normal mixer 1306 private: 1307 // one-time initialization, no locks required 1308 FastMixer* mFastMixer; // non-NULL if there is also a fast mixer 1309 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread 1310 1311 // contents are not guaranteed to be consistent, no locks required 1312 FastMixerDumpState mFastMixerDumpState; 1313#ifdef STATE_QUEUE_DUMP 1314 StateQueueObserverDump mStateQueueObserverDump; 1315 StateQueueMutatorDump mStateQueueMutatorDump; 1316#endif 1317 AudioWatchdogDump mAudioWatchdogDump; 1318 1319 // accessible only within the threadLoop(), no locks required 1320 // mFastMixer->sq() // for mutating and pushing state 1321 int32_t mFastMixerFutex; // for cold idle 1322 1323 public: 1324 virtual bool hasFastMixer() const { return mFastMixer != NULL; } 1325 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const { 1326 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks); 1327 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns; 1328 } 1329 }; 1330 1331 class DirectOutputThread : public PlaybackThread { 1332 public: 1333 1334 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 1335 audio_io_handle_t id, audio_devices_t device); 1336 virtual ~DirectOutputThread(); 1337 1338 // Thread virtuals 1339 1340 virtual bool checkForNewParameters_l(); 1341 1342 protected: 1343 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId); 1344 virtual void deleteTrackName_l(int name); 1345 virtual uint32_t activeSleepTimeUs() const; 1346 virtual uint32_t idleSleepTimeUs() const; 1347 virtual uint32_t suspendSleepTimeUs() const; 1348 virtual void cacheParameters_l(); 1349 1350 // threadLoop snippets 1351 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove); 1352 virtual void threadLoop_mix(); 1353 virtual void threadLoop_sleepTime(); 1354 1355 private: 1356 // volumes last sent to audio HAL with stream->set_volume() 1357 float mLeftVolFloat; 1358 float mRightVolFloat; 1359 1360 // prepareTracks_l() tells threadLoop_mix() the name of the single active track 1361 sp<Track> mActiveTrack; 1362 public: 1363 virtual bool hasFastMixer() const { return false; } 1364 }; 1365 1366 class DuplicatingThread : public MixerThread { 1367 public: 1368 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread, 1369 audio_io_handle_t id); 1370 virtual ~DuplicatingThread(); 1371 1372 // Thread virtuals 1373 void addOutputTrack(MixerThread* thread); 1374 void removeOutputTrack(MixerThread* thread); 1375 uint32_t waitTimeMs() const { return mWaitTimeMs; } 1376 protected: 1377 virtual uint32_t activeSleepTimeUs() const; 1378 1379 private: 1380 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks); 1381 protected: 1382 // threadLoop snippets 1383 virtual void threadLoop_mix(); 1384 virtual void threadLoop_sleepTime(); 1385 virtual void threadLoop_write(); 1386 virtual void threadLoop_standby(); 1387 virtual void cacheParameters_l(); 1388 1389 private: 1390 // called from threadLoop, addOutputTrack, removeOutputTrack 1391 virtual void updateWaitTime_l(); 1392 protected: 1393 virtual void saveOutputTracks(); 1394 virtual void clearOutputTracks(); 1395 private: 1396 1397 uint32_t mWaitTimeMs; 1398 SortedVector < sp<OutputTrack> > outputTracks; 1399 SortedVector < sp<OutputTrack> > mOutputTracks; 1400 public: 1401 virtual bool hasFastMixer() const { return false; } 1402 }; 1403 1404 PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const; 1405 MixerThread *checkMixerThread_l(audio_io_handle_t output) const; 1406 RecordThread *checkRecordThread_l(audio_io_handle_t input) const; 1407 // no range check, AudioFlinger::mLock held 1408 bool streamMute_l(audio_stream_type_t stream) const 1409 { return mStreamTypes[stream].mute; } 1410 // no range check, doesn't check per-thread stream volume, AudioFlinger::mLock held 1411 float streamVolume_l(audio_stream_type_t stream) const 1412 { return mStreamTypes[stream].volume; } 1413 void audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2); 1414 1415 // allocate an audio_io_handle_t, session ID, or effect ID 1416 uint32_t nextUniqueId(); 1417 1418 status_t moveEffectChain_l(int sessionId, 1419 PlaybackThread *srcThread, 1420 PlaybackThread *dstThread, 1421 bool reRegister); 1422 // return thread associated with primary hardware device, or NULL 1423 PlaybackThread *primaryPlaybackThread_l() const; 1424 audio_devices_t primaryOutputDevice_l() const; 1425 1426 sp<PlaybackThread> getEffectThread_l(int sessionId, int EffectId); 1427 1428 // server side of the client's IAudioTrack 1429 class TrackHandle : public android::BnAudioTrack { 1430 public: 1431 TrackHandle(const sp<PlaybackThread::Track>& track); 1432 virtual ~TrackHandle(); 1433 virtual sp<IMemory> getCblk() const; 1434 virtual status_t start(); 1435 virtual void stop(); 1436 virtual void flush(); 1437 virtual void mute(bool); 1438 virtual void pause(); 1439 virtual status_t attachAuxEffect(int effectId); 1440 virtual status_t allocateTimedBuffer(size_t size, 1441 sp<IMemory>* buffer); 1442 virtual status_t queueTimedBuffer(const sp<IMemory>& buffer, 1443 int64_t pts); 1444 virtual status_t setMediaTimeTransform(const LinearTransform& xform, 1445 int target); 1446 virtual status_t onTransact( 1447 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); 1448 private: 1449 const sp<PlaybackThread::Track> mTrack; 1450 }; 1451 1452 void removeClient_l(pid_t pid); 1453 void removeNotificationClient(pid_t pid); 1454 1455 1456 // record thread 1457 class RecordThread : public ThreadBase, public AudioBufferProvider 1458 // derives from AudioBufferProvider interface for use by resampler 1459 { 1460 public: 1461 1462 // record track 1463 class RecordTrack : public TrackBase { 1464 public: 1465 RecordTrack(RecordThread *thread, 1466 const sp<Client>& client, 1467 uint32_t sampleRate, 1468 audio_format_t format, 1469 audio_channel_mask_t channelMask, 1470 size_t frameCount, 1471 int sessionId); 1472 virtual ~RecordTrack(); 1473 1474 virtual status_t start(AudioSystem::sync_event_t event, int triggerSession); 1475 virtual void stop(); 1476 1477 void destroy(); 1478 1479 // clear the buffer overflow flag 1480 void clearOverflow() { mOverflow = false; } 1481 // set the buffer overflow flag and return previous value 1482 bool setOverflow() { bool tmp = mOverflow; mOverflow = true; 1483 return tmp; } 1484 1485 static void appendDumpHeader(String8& result); 1486 void dump(char* buffer, size_t size); 1487 1488 virtual bool isOut() const; 1489 1490 private: 1491 friend class AudioFlinger; // for mState 1492 1493 RecordTrack(const RecordTrack&); 1494 RecordTrack& operator = (const RecordTrack&); 1495 1496 // AudioBufferProvider interface 1497 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, 1498 int64_t pts = kInvalidPTS); 1499 // releaseBuffer() not overridden 1500 1501 bool mOverflow; // overflow on most recent attempt to fill client buffer 1502 }; 1503 1504 RecordThread(const sp<AudioFlinger>& audioFlinger, 1505 AudioStreamIn *input, 1506 uint32_t sampleRate, 1507 audio_channel_mask_t channelMask, 1508 audio_io_handle_t id, 1509 audio_devices_t device, 1510 const sp<NBAIO_Sink>& teeSink); 1511 virtual ~RecordThread(); 1512 1513 // no addTrack_l ? 1514 void destroyTrack_l(const sp<RecordTrack>& track); 1515 void removeTrack_l(const sp<RecordTrack>& track); 1516 1517 void dumpInternals(int fd, const Vector<String16>& args); 1518 void dumpTracks(int fd, const Vector<String16>& args); 1519 1520 // Thread virtuals 1521 virtual bool threadLoop(); 1522 virtual status_t readyToRun(); 1523 1524 // RefBase 1525 virtual void onFirstRef(); 1526 1527 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; } 1528 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l( 1529 const sp<AudioFlinger::Client>& client, 1530 uint32_t sampleRate, 1531 audio_format_t format, 1532 audio_channel_mask_t channelMask, 1533 size_t frameCount, 1534 int sessionId, 1535 IAudioFlinger::track_flags_t flags, 1536 pid_t tid, 1537 status_t *status); 1538 1539 status_t start(RecordTrack* recordTrack, 1540 AudioSystem::sync_event_t event, 1541 int triggerSession); 1542 1543 // ask the thread to stop the specified track, and 1544 // return true if the caller should then do it's part of the stopping process 1545 bool stop_l(RecordTrack* recordTrack); 1546 1547 void dump(int fd, const Vector<String16>& args); 1548 AudioStreamIn* clearInput(); 1549 virtual audio_stream_t* stream() const; 1550 1551 // AudioBufferProvider interface 1552 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts); 1553 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); 1554 1555 virtual bool checkForNewParameters_l(); 1556 virtual String8 getParameters(const String8& keys); 1557 virtual void audioConfigChanged_l(int event, int param = 0); 1558 void readInputParameters(); 1559 virtual unsigned int getInputFramesLost(); 1560 1561 virtual status_t addEffectChain_l(const sp<EffectChain>& chain); 1562 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain); 1563 virtual uint32_t hasAudioSession(int sessionId) const; 1564 1565 // Return the set of unique session IDs across all tracks. 1566 // The keys are the session IDs, and the associated values are meaningless. 1567 // FIXME replace by Set [and implement Bag/Multiset for other uses]. 1568 KeyedVector<int, bool> sessionIds() const; 1569 1570 virtual status_t setSyncEvent(const sp<SyncEvent>& event); 1571 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const; 1572 1573 static void syncStartEventCallback(const wp<SyncEvent>& event); 1574 void handleSyncStartEvent(const sp<SyncEvent>& event); 1575 1576 private: 1577 void clearSyncStartEvent(); 1578 1579 // Enter standby if not already in standby, and set mStandby flag 1580 void standby(); 1581 1582 // Call the HAL standby method unconditionally, and don't change mStandby flag 1583 void inputStandBy(); 1584 1585 AudioStreamIn *mInput; 1586 SortedVector < sp<RecordTrack> > mTracks; 1587 // mActiveTrack has dual roles: it indicates the current active track, and 1588 // is used together with mStartStopCond to indicate start()/stop() progress 1589 sp<RecordTrack> mActiveTrack; 1590 Condition mStartStopCond; 1591 AudioResampler *mResampler; 1592 int32_t *mRsmpOutBuffer; 1593 int16_t *mRsmpInBuffer; 1594 size_t mRsmpInIndex; 1595 size_t mInputBytes; 1596 const int mReqChannelCount; 1597 const uint32_t mReqSampleRate; 1598 ssize_t mBytesRead; 1599 // sync event triggering actual audio capture. Frames read before this event will 1600 // be dropped and therefore not read by the application. 1601 sp<SyncEvent> mSyncStartEvent; 1602 // number of captured frames to drop after the start sync event has been received. 1603 // when < 0, maximum frames to drop before starting capture even if sync event is 1604 // not received 1605 ssize_t mFramestoDrop; 1606 1607 // For dumpsys 1608 const sp<NBAIO_Sink> mTeeSink; 1609 }; 1610 1611 // server side of the client's IAudioRecord 1612 class RecordHandle : public android::BnAudioRecord { 1613 public: 1614 RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack); 1615 virtual ~RecordHandle(); 1616 virtual sp<IMemory> getCblk() const; 1617 virtual status_t start(int /*AudioSystem::sync_event_t*/ event, int triggerSession); 1618 virtual void stop(); 1619 virtual status_t onTransact( 1620 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); 1621 private: 1622 const sp<RecordThread::RecordTrack> mRecordTrack; 1623 1624 // for use from destructor 1625 void stop_nonvirtual(); 1626 }; 1627 1628 //--- Audio Effect Management 1629 1630 // EffectModule and EffectChain classes both have their own mutex to protect 1631 // state changes or resource modifications. Always respect the following order 1632 // if multiple mutexes must be acquired to avoid cross deadlock: 1633 // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule 1634 1635 // The EffectModule class is a wrapper object controlling the effect engine implementation 1636 // in the effect library. It prevents concurrent calls to process() and command() functions 1637 // from different client threads. It keeps a list of EffectHandle objects corresponding 1638 // to all client applications using this effect and notifies applications of effect state, 1639 // control or parameter changes. It manages the activation state machine to send appropriate 1640 // reset, enable, disable commands to effect engine and provide volume 1641 // ramping when effects are activated/deactivated. 1642 // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by 1643 // the attached track(s) to accumulate their auxiliary channel. 1644 class EffectModule : public RefBase { 1645 public: 1646 EffectModule(ThreadBase *thread, 1647 const wp<AudioFlinger::EffectChain>& chain, 1648 effect_descriptor_t *desc, 1649 int id, 1650 int sessionId); 1651 virtual ~EffectModule(); 1652 1653 enum effect_state { 1654 IDLE, 1655 RESTART, 1656 STARTING, 1657 ACTIVE, 1658 STOPPING, 1659 STOPPED, 1660 DESTROYED 1661 }; 1662 1663 int id() const { return mId; } 1664 void process(); 1665 void updateState(); 1666 status_t command(uint32_t cmdCode, 1667 uint32_t cmdSize, 1668 void *pCmdData, 1669 uint32_t *replySize, 1670 void *pReplyData); 1671 1672 void reset_l(); 1673 status_t configure(); 1674 status_t init(); 1675 effect_state state() const { 1676 return mState; 1677 } 1678 uint32_t status() { 1679 return mStatus; 1680 } 1681 int sessionId() const { 1682 return mSessionId; 1683 } 1684 status_t setEnabled(bool enabled); 1685 status_t setEnabled_l(bool enabled); 1686 bool isEnabled() const; 1687 bool isProcessEnabled() const; 1688 1689 void setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; } 1690 int16_t *inBuffer() { return mConfig.inputCfg.buffer.s16; } 1691 void setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; } 1692 int16_t *outBuffer() { return mConfig.outputCfg.buffer.s16; } 1693 void setChain(const wp<EffectChain>& chain) { mChain = chain; } 1694 void setThread(const wp<ThreadBase>& thread) { mThread = thread; } 1695 const wp<ThreadBase>& thread() { return mThread; } 1696 1697 status_t addHandle(EffectHandle *handle); 1698 size_t disconnect(EffectHandle *handle, bool unpinIfLast); 1699 size_t removeHandle(EffectHandle *handle); 1700 1701 const effect_descriptor_t& desc() const { return mDescriptor; } 1702 wp<EffectChain>& chain() { return mChain; } 1703 1704 status_t setDevice(audio_devices_t device); 1705 status_t setVolume(uint32_t *left, uint32_t *right, bool controller); 1706 status_t setMode(audio_mode_t mode); 1707 status_t setAudioSource(audio_source_t source); 1708 status_t start(); 1709 status_t stop(); 1710 void setSuspended(bool suspended); 1711 bool suspended() const; 1712 1713 EffectHandle* controlHandle_l(); 1714 1715 bool isPinned() const { return mPinned; } 1716 void unPin() { mPinned = false; } 1717 bool purgeHandles(); 1718 void lock() { mLock.lock(); } 1719 void unlock() { mLock.unlock(); } 1720 1721 void dump(int fd, const Vector<String16>& args); 1722 1723 protected: 1724 friend class AudioFlinger; // for mHandles 1725 bool mPinned; 1726 1727 // Maximum time allocated to effect engines to complete the turn off sequence 1728 static const uint32_t MAX_DISABLE_TIME_MS = 10000; 1729 1730 EffectModule(const EffectModule&); 1731 EffectModule& operator = (const EffectModule&); 1732 1733 status_t start_l(); 1734 status_t stop_l(); 1735 1736mutable Mutex mLock; // mutex for process, commands and handles list protection 1737 wp<ThreadBase> mThread; // parent thread 1738 wp<EffectChain> mChain; // parent effect chain 1739 const int mId; // this instance unique ID 1740 const int mSessionId; // audio session ID 1741 const effect_descriptor_t mDescriptor;// effect descriptor received from effect engine 1742 effect_config_t mConfig; // input and output audio configuration 1743 effect_handle_t mEffectInterface; // Effect module C API 1744 status_t mStatus; // initialization status 1745 effect_state mState; // current activation state 1746 Vector<EffectHandle *> mHandles; // list of client handles 1747 // First handle in mHandles has highest priority and controls the effect module 1748 uint32_t mMaxDisableWaitCnt; // maximum grace period before forcing an effect off after 1749 // sending disable command. 1750 uint32_t mDisableWaitCnt; // current process() calls count during disable period. 1751 bool mSuspended; // effect is suspended: temporarily disabled by framework 1752 }; 1753 1754 // The EffectHandle class implements the IEffect interface. It provides resources 1755 // to receive parameter updates, keeps track of effect control 1756 // ownership and state and has a pointer to the EffectModule object it is controlling. 1757 // There is one EffectHandle object for each application controlling (or using) 1758 // an effect module. 1759 // The EffectHandle is obtained by calling AudioFlinger::createEffect(). 1760 class EffectHandle: public android::BnEffect { 1761 public: 1762 1763 EffectHandle(const sp<EffectModule>& effect, 1764 const sp<AudioFlinger::Client>& client, 1765 const sp<IEffectClient>& effectClient, 1766 int32_t priority); 1767 virtual ~EffectHandle(); 1768 1769 // IEffect 1770 virtual status_t enable(); 1771 virtual status_t disable(); 1772 virtual status_t command(uint32_t cmdCode, 1773 uint32_t cmdSize, 1774 void *pCmdData, 1775 uint32_t *replySize, 1776 void *pReplyData); 1777 virtual void disconnect(); 1778 private: 1779 void disconnect(bool unpinIfLast); 1780 public: 1781 virtual sp<IMemory> getCblk() const { return mCblkMemory; } 1782 virtual status_t onTransact(uint32_t code, const Parcel& data, 1783 Parcel* reply, uint32_t flags); 1784 1785 1786 // Give or take control of effect module 1787 // - hasControl: true if control is given, false if removed 1788 // - signal: true client app should be signaled of change, false otherwise 1789 // - enabled: state of the effect when control is passed 1790 void setControl(bool hasControl, bool signal, bool enabled); 1791 void commandExecuted(uint32_t cmdCode, 1792 uint32_t cmdSize, 1793 void *pCmdData, 1794 uint32_t replySize, 1795 void *pReplyData); 1796 void setEnabled(bool enabled); 1797 bool enabled() const { return mEnabled; } 1798 1799 // Getters 1800 int id() const { return mEffect->id(); } 1801 int priority() const { return mPriority; } 1802 bool hasControl() const { return mHasControl; } 1803 sp<EffectModule> effect() const { return mEffect; } 1804 // destroyed_l() must be called with the associated EffectModule mLock held 1805 bool destroyed_l() const { return mDestroyed; } 1806 1807 void dump(char* buffer, size_t size); 1808 1809 protected: 1810 friend class AudioFlinger; // for mEffect, mHasControl, mEnabled 1811 EffectHandle(const EffectHandle&); 1812 EffectHandle& operator =(const EffectHandle&); 1813 1814 sp<EffectModule> mEffect; // pointer to controlled EffectModule 1815 sp<IEffectClient> mEffectClient; // callback interface for client notifications 1816 /*const*/ sp<Client> mClient; // client for shared memory allocation, see disconnect() 1817 sp<IMemory> mCblkMemory; // shared memory for control block 1818 effect_param_cblk_t* mCblk; // control block for deferred parameter setting via 1819 // shared memory 1820 uint8_t* mBuffer; // pointer to parameter area in shared memory 1821 int mPriority; // client application priority to control the effect 1822 bool mHasControl; // true if this handle is controlling the effect 1823 bool mEnabled; // cached enable state: needed when the effect is 1824 // restored after being suspended 1825 bool mDestroyed; // Set to true by destructor. Access with EffectModule 1826 // mLock held 1827 }; 1828 1829 // the EffectChain class represents a group of effects associated to one audio session. 1830 // There can be any number of EffectChain objects per output mixer thread (PlaybackThread). 1831 // The EffecChain with session ID 0 contains global effects applied to the output mix. 1832 // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to 1833 // tracks) are insert only. The EffectChain maintains an ordered list of effect module, the 1834 // order corresponding in the effect process order. When attached to a track (session ID != 0), 1835 // it also provide it's own input buffer used by the track as accumulation buffer. 1836 class EffectChain : public RefBase { 1837 public: 1838 EffectChain(const wp<ThreadBase>& wThread, int sessionId); 1839 EffectChain(ThreadBase *thread, int sessionId); 1840 virtual ~EffectChain(); 1841 1842 // special key used for an entry in mSuspendedEffects keyed vector 1843 // corresponding to a suspend all request. 1844 static const int kKeyForSuspendAll = 0; 1845 1846 // minimum duration during which we force calling effect process when last track on 1847 // a session is stopped or removed to allow effect tail to be rendered 1848 static const int kProcessTailDurationMs = 1000; 1849 1850 void process_l(); 1851 1852 void lock() { 1853 mLock.lock(); 1854 } 1855 void unlock() { 1856 mLock.unlock(); 1857 } 1858 1859 status_t addEffect_l(const sp<EffectModule>& handle); 1860 size_t removeEffect_l(const sp<EffectModule>& handle); 1861 1862 int sessionId() const { return mSessionId; } 1863 void setSessionId(int sessionId) { mSessionId = sessionId; } 1864 1865 sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor); 1866 sp<EffectModule> getEffectFromId_l(int id); 1867 sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type); 1868 bool setVolume_l(uint32_t *left, uint32_t *right); 1869 void setDevice_l(audio_devices_t device); 1870 void setMode_l(audio_mode_t mode); 1871 void setAudioSource_l(audio_source_t source); 1872 1873 void setInBuffer(int16_t *buffer, bool ownsBuffer = false) { 1874 mInBuffer = buffer; 1875 mOwnInBuffer = ownsBuffer; 1876 } 1877 int16_t *inBuffer() const { 1878 return mInBuffer; 1879 } 1880 void setOutBuffer(int16_t *buffer) { 1881 mOutBuffer = buffer; 1882 } 1883 int16_t *outBuffer() const { 1884 return mOutBuffer; 1885 } 1886 1887 void incTrackCnt() { android_atomic_inc(&mTrackCnt); } 1888 void decTrackCnt() { android_atomic_dec(&mTrackCnt); } 1889 int32_t trackCnt() const { return android_atomic_acquire_load(&mTrackCnt); } 1890 1891 void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt); 1892 mTailBufferCount = mMaxTailBuffers; } 1893 void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); } 1894 int32_t activeTrackCnt() const { return android_atomic_acquire_load(&mActiveTrackCnt); } 1895 1896 uint32_t strategy() const { return mStrategy; } 1897 void setStrategy(uint32_t strategy) 1898 { mStrategy = strategy; } 1899 1900 // suspend effect of the given type 1901 void setEffectSuspended_l(const effect_uuid_t *type, 1902 bool suspend); 1903 // suspend all eligible effects 1904 void setEffectSuspendedAll_l(bool suspend); 1905 // check if effects should be suspend or restored when a given effect is enable or disabled 1906 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1907 bool enabled); 1908 1909 void clearInputBuffer(); 1910 1911 void dump(int fd, const Vector<String16>& args); 1912 1913 protected: 1914 friend class AudioFlinger; // for mThread, mEffects 1915 EffectChain(const EffectChain&); 1916 EffectChain& operator =(const EffectChain&); 1917 1918 class SuspendedEffectDesc : public RefBase { 1919 public: 1920 SuspendedEffectDesc() : mRefCount(0) {} 1921 1922 int mRefCount; 1923 effect_uuid_t mType; 1924 wp<EffectModule> mEffect; 1925 }; 1926 1927 // get a list of effect modules to suspend when an effect of the type 1928 // passed is enabled. 1929 void getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects); 1930 1931 // get an effect module if it is currently enable 1932 sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type); 1933 // true if the effect whose descriptor is passed can be suspended 1934 // OEMs can modify the rules implemented in this method to exclude specific effect 1935 // types or implementations from the suspend/restore mechanism. 1936 bool isEffectEligibleForSuspend(const effect_descriptor_t& desc); 1937 1938 void clearInputBuffer_l(sp<ThreadBase> thread); 1939 1940 wp<ThreadBase> mThread; // parent mixer thread 1941 Mutex mLock; // mutex protecting effect list 1942 Vector< sp<EffectModule> > mEffects; // list of effect modules 1943 int mSessionId; // audio session ID 1944 int16_t *mInBuffer; // chain input buffer 1945 int16_t *mOutBuffer; // chain output buffer 1946 1947 // 'volatile' here means these are accessed with atomic operations instead of mutex 1948 volatile int32_t mActiveTrackCnt; // number of active tracks connected 1949 volatile int32_t mTrackCnt; // number of tracks connected 1950 1951 int32_t mTailBufferCount; // current effect tail buffer count 1952 int32_t mMaxTailBuffers; // maximum effect tail buffers 1953 bool mOwnInBuffer; // true if the chain owns its input buffer 1954 int mVolumeCtrlIdx; // index of insert effect having control over volume 1955 uint32_t mLeftVolume; // previous volume on left channel 1956 uint32_t mRightVolume; // previous volume on right channel 1957 uint32_t mNewLeftVolume; // new volume on left channel 1958 uint32_t mNewRightVolume; // new volume on right channel 1959 uint32_t mStrategy; // strategy for this effect chain 1960 // mSuspendedEffects lists all effects currently suspended in the chain. 1961 // Use effect type UUID timelow field as key. There is no real risk of identical 1962 // timeLow fields among effect type UUIDs. 1963 // Updated by updateSuspendedSessions_l() only. 1964 KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects; 1965 }; 1966 1967 class AudioHwDevice { 1968 public: 1969 enum Flags { 1970 AHWD_CAN_SET_MASTER_VOLUME = 0x1, 1971 AHWD_CAN_SET_MASTER_MUTE = 0x2, 1972 }; 1973 1974 AudioHwDevice(const char *moduleName, 1975 audio_hw_device_t *hwDevice, 1976 Flags flags) 1977 : mModuleName(strdup(moduleName)) 1978 , mHwDevice(hwDevice) 1979 , mFlags(flags) { } 1980 /*virtual*/ ~AudioHwDevice() { free((void *)mModuleName); } 1981 1982 bool canSetMasterVolume() const { 1983 return (0 != (mFlags & AHWD_CAN_SET_MASTER_VOLUME)); 1984 } 1985 1986 bool canSetMasterMute() const { 1987 return (0 != (mFlags & AHWD_CAN_SET_MASTER_MUTE)); 1988 } 1989 1990 const char *moduleName() const { return mModuleName; } 1991 audio_hw_device_t *hwDevice() const { return mHwDevice; } 1992 private: 1993 const char * const mModuleName; 1994 audio_hw_device_t * const mHwDevice; 1995 Flags mFlags; 1996 }; 1997 1998 // AudioStreamOut and AudioStreamIn are immutable, so their fields are const. 1999 // For emphasis, we could also make all pointers to them be "const *", 2000 // but that would clutter the code unnecessarily. 2001 2002 struct AudioStreamOut { 2003 AudioHwDevice* const audioHwDev; 2004 audio_stream_out_t* const stream; 2005 2006 audio_hw_device_t* hwDev() const { return audioHwDev->hwDevice(); } 2007 2008 AudioStreamOut(AudioHwDevice *dev, audio_stream_out_t *out) : 2009 audioHwDev(dev), stream(out) {} 2010 }; 2011 2012 struct AudioStreamIn { 2013 AudioHwDevice* const audioHwDev; 2014 audio_stream_in_t* const stream; 2015 2016 audio_hw_device_t* hwDev() const { return audioHwDev->hwDevice(); } 2017 2018 AudioStreamIn(AudioHwDevice *dev, audio_stream_in_t *in) : 2019 audioHwDev(dev), stream(in) {} 2020 }; 2021 2022 // for mAudioSessionRefs only 2023 struct AudioSessionRef { 2024 AudioSessionRef(int sessionid, pid_t pid) : 2025 mSessionid(sessionid), mPid(pid), mCnt(1) {} 2026 const int mSessionid; 2027 const pid_t mPid; 2028 int mCnt; 2029 }; 2030 2031 mutable Mutex mLock; 2032 2033 DefaultKeyedVector< pid_t, wp<Client> > mClients; // see ~Client() 2034 2035 mutable Mutex mHardwareLock; 2036 // NOTE: If both mLock and mHardwareLock mutexes must be held, 2037 // always take mLock before mHardwareLock 2038 2039 // These two fields are immutable after onFirstRef(), so no lock needed to access 2040 AudioHwDevice* mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL 2041 DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*> mAudioHwDevs; 2042 2043 // for dump, indicates which hardware operation is currently in progress (but not stream ops) 2044 enum hardware_call_state { 2045 AUDIO_HW_IDLE = 0, // no operation in progress 2046 AUDIO_HW_INIT, // init_check 2047 AUDIO_HW_OUTPUT_OPEN, // open_output_stream 2048 AUDIO_HW_OUTPUT_CLOSE, // unused 2049 AUDIO_HW_INPUT_OPEN, // unused 2050 AUDIO_HW_INPUT_CLOSE, // unused 2051 AUDIO_HW_STANDBY, // unused 2052 AUDIO_HW_SET_MASTER_VOLUME, // set_master_volume 2053 AUDIO_HW_GET_ROUTING, // unused 2054 AUDIO_HW_SET_ROUTING, // unused 2055 AUDIO_HW_GET_MODE, // unused 2056 AUDIO_HW_SET_MODE, // set_mode 2057 AUDIO_HW_GET_MIC_MUTE, // get_mic_mute 2058 AUDIO_HW_SET_MIC_MUTE, // set_mic_mute 2059 AUDIO_HW_SET_VOICE_VOLUME, // set_voice_volume 2060 AUDIO_HW_SET_PARAMETER, // set_parameters 2061 AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size 2062 AUDIO_HW_GET_MASTER_VOLUME, // get_master_volume 2063 AUDIO_HW_GET_PARAMETER, // get_parameters 2064 AUDIO_HW_SET_MASTER_MUTE, // set_master_mute 2065 AUDIO_HW_GET_MASTER_MUTE, // get_master_mute 2066 }; 2067 2068 mutable hardware_call_state mHardwareStatus; // for dump only 2069 2070 2071 DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> > mPlaybackThreads; 2072 stream_type_t mStreamTypes[AUDIO_STREAM_CNT]; 2073 2074 // member variables below are protected by mLock 2075 float mMasterVolume; 2076 bool mMasterMute; 2077 // end of variables protected by mLock 2078 2079 DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> > mRecordThreads; 2080 2081 DefaultKeyedVector< pid_t, sp<NotificationClient> > mNotificationClients; 2082 volatile int32_t mNextUniqueId; // updated by android_atomic_inc 2083 audio_mode_t mMode; 2084 bool mBtNrecIsOff; 2085 2086 // protected by mLock 2087 Vector<AudioSessionRef*> mAudioSessionRefs; 2088 2089 float masterVolume_l() const; 2090 bool masterMute_l() const; 2091 audio_module_handle_t loadHwModule_l(const char *name); 2092 2093 Vector < sp<SyncEvent> > mPendingSyncEvents; // sync events awaiting for a session 2094 // to be created 2095 2096private: 2097 sp<Client> registerPid_l(pid_t pid); // always returns non-0 2098 2099 // for use from destructor 2100 status_t closeOutput_nonvirtual(audio_io_handle_t output); 2101 status_t closeInput_nonvirtual(audio_io_handle_t input); 2102 2103 // all record threads serially share a common tee sink, which is re-created on format change 2104 sp<NBAIO_Sink> mRecordTeeSink; 2105 sp<NBAIO_Source> mRecordTeeSource; 2106 2107public: 2108 static void dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id = 0); 2109}; 2110 2111 2112// ---------------------------------------------------------------------------- 2113 2114}; // namespace android 2115 2116#endif // ANDROID_AUDIO_FLINGER_H 2117