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