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 "Configuration.h" 22 #include <stdint.h> 23 #include <sys/types.h> 24 #include <limits.h> 25 26 #include <cutils/compiler.h> 27 28 #include <media/IAudioFlinger.h> 29 #include <media/IAudioFlingerClient.h> 30 #include <media/IAudioTrack.h> 31 #include <media/IAudioRecord.h> 32 #include <media/AudioSystem.h> 33 #include <media/AudioTrack.h> 34 35 #include <utils/Atomic.h> 36 #include <utils/Errors.h> 37 #include <utils/threads.h> 38 #include <utils/SortedVector.h> 39 #include <utils/TypeHelpers.h> 40 #include <utils/Vector.h> 41 42 #include <binder/BinderService.h> 43 #include <binder/MemoryDealer.h> 44 45 #include <system/audio.h> 46 #include <hardware/audio.h> 47 #include <hardware/audio_policy.h> 48 49 #include <media/AudioBufferProvider.h> 50 #include <media/ExtendedAudioBufferProvider.h> 51 52 #include "FastCapture.h" 53 #include "FastMixer.h" 54 #include <media/nbaio/NBAIO.h> 55 #include "AudioWatchdog.h" 56 #include "AudioMixer.h" 57 #include "AudioStreamOut.h" 58 #include "SpdifStreamOut.h" 59 #include "AudioHwDevice.h" 60 #include "LinearMap.h" 61 62 #include <powermanager/IPowerManager.h> 63 64 #include <media/nbaio/NBLog.h> 65 #include <private/media/AudioTrackShared.h> 66 67 namespace android { 68 69 struct audio_track_cblk_t; 70 struct effect_param_cblk_t; 71 class AudioMixer; 72 class AudioBuffer; 73 class AudioResampler; 74 class FastMixer; 75 class PassthruBufferProvider; 76 class ServerProxy; 77 78 // ---------------------------------------------------------------------------- 79 80 static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3); 81 82 83 // Max shared memory size for audio tracks and audio records per client process 84 static const size_t kClientSharedHeapSizeBytes = 1024*1024; 85 // Shared memory size multiplier for non low ram devices 86 static const size_t kClientSharedHeapSizeMultiplier = 4; 87 88 #define INCLUDING_FROM_AUDIOFLINGER_H 89 90 class AudioFlinger : 91 public BinderService<AudioFlinger>, 92 public BnAudioFlinger 93 { 94 friend class BinderService<AudioFlinger>; // for AudioFlinger() 95 public: getServiceName()96 static const char* getServiceName() ANDROID_API { return "media.audio_flinger"; } 97 98 virtual status_t dump(int fd, const Vector<String16>& args); 99 100 // IAudioFlinger interface, in binder opcode order 101 virtual sp<IAudioTrack> createTrack( 102 audio_stream_type_t streamType, 103 uint32_t sampleRate, 104 audio_format_t format, 105 audio_channel_mask_t channelMask, 106 size_t *pFrameCount, 107 IAudioFlinger::track_flags_t *flags, 108 const sp<IMemory>& sharedBuffer, 109 audio_io_handle_t output, 110 pid_t pid, 111 pid_t tid, 112 audio_session_t *sessionId, 113 int clientUid, 114 status_t *status /*non-NULL*/); 115 116 virtual sp<IAudioRecord> openRecord( 117 audio_io_handle_t input, 118 uint32_t sampleRate, 119 audio_format_t format, 120 audio_channel_mask_t channelMask, 121 const String16& opPackageName, 122 size_t *pFrameCount, 123 IAudioFlinger::track_flags_t *flags, 124 pid_t pid, 125 pid_t tid, 126 int clientUid, 127 audio_session_t *sessionId, 128 size_t *notificationFrames, 129 sp<IMemory>& cblk, 130 sp<IMemory>& buffers, 131 status_t *status /*non-NULL*/); 132 133 virtual uint32_t sampleRate(audio_io_handle_t ioHandle) const; 134 virtual audio_format_t format(audio_io_handle_t output) const; 135 virtual size_t frameCount(audio_io_handle_t ioHandle) const; 136 virtual size_t frameCountHAL(audio_io_handle_t ioHandle) const; 137 virtual uint32_t latency(audio_io_handle_t output) const; 138 139 virtual status_t setMasterVolume(float value); 140 virtual status_t setMasterMute(bool muted); 141 142 virtual float masterVolume() const; 143 virtual bool masterMute() const; 144 145 virtual status_t setStreamVolume(audio_stream_type_t stream, float value, 146 audio_io_handle_t output); 147 virtual status_t setStreamMute(audio_stream_type_t stream, bool muted); 148 149 virtual float streamVolume(audio_stream_type_t stream, 150 audio_io_handle_t output) const; 151 virtual bool streamMute(audio_stream_type_t stream) const; 152 153 virtual status_t setMode(audio_mode_t mode); 154 155 virtual status_t setMicMute(bool state); 156 virtual bool getMicMute() const; 157 158 virtual status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs); 159 virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) const; 160 161 virtual void registerClient(const sp<IAudioFlingerClient>& client); 162 163 virtual size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 164 audio_channel_mask_t channelMask) const; 165 166 virtual status_t openOutput(audio_module_handle_t module, 167 audio_io_handle_t *output, 168 audio_config_t *config, 169 audio_devices_t *devices, 170 const String8& address, 171 uint32_t *latencyMs, 172 audio_output_flags_t flags); 173 174 virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, 175 audio_io_handle_t output2); 176 177 virtual status_t closeOutput(audio_io_handle_t output); 178 179 virtual status_t suspendOutput(audio_io_handle_t output); 180 181 virtual status_t restoreOutput(audio_io_handle_t output); 182 183 virtual status_t openInput(audio_module_handle_t module, 184 audio_io_handle_t *input, 185 audio_config_t *config, 186 audio_devices_t *device, 187 const String8& address, 188 audio_source_t source, 189 audio_input_flags_t flags); 190 191 virtual status_t closeInput(audio_io_handle_t input); 192 193 virtual status_t invalidateStream(audio_stream_type_t stream); 194 195 virtual status_t setVoiceVolume(float volume); 196 197 virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 198 audio_io_handle_t output) const; 199 200 virtual uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const; 201 202 // This is the binder API. For the internal API see nextUniqueId(). 203 virtual audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use); 204 205 virtual void acquireAudioSessionId(audio_session_t audioSession, pid_t pid); 206 207 virtual void releaseAudioSessionId(audio_session_t audioSession, pid_t pid); 208 209 virtual status_t queryNumberEffects(uint32_t *numEffects) const; 210 211 virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const; 212 213 virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid, 214 effect_descriptor_t *descriptor) const; 215 216 virtual sp<IEffect> createEffect( 217 effect_descriptor_t *pDesc, 218 const sp<IEffectClient>& effectClient, 219 int32_t priority, 220 audio_io_handle_t io, 221 audio_session_t sessionId, 222 const String16& opPackageName, 223 status_t *status /*non-NULL*/, 224 int *id, 225 int *enabled); 226 227 virtual status_t moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput, 228 audio_io_handle_t dstOutput); 229 230 virtual audio_module_handle_t loadHwModule(const char *name); 231 232 virtual uint32_t getPrimaryOutputSamplingRate(); 233 virtual size_t getPrimaryOutputFrameCount(); 234 235 virtual status_t setLowRamDevice(bool isLowRamDevice); 236 237 /* List available audio ports and their attributes */ 238 virtual status_t listAudioPorts(unsigned int *num_ports, 239 struct audio_port *ports); 240 241 /* Get attributes for a given audio port */ 242 virtual status_t getAudioPort(struct audio_port *port); 243 244 /* Create an audio patch between several source and sink ports */ 245 virtual status_t createAudioPatch(const struct audio_patch *patch, 246 audio_patch_handle_t *handle); 247 248 /* Release an audio patch */ 249 virtual status_t releaseAudioPatch(audio_patch_handle_t handle); 250 251 /* List existing audio patches */ 252 virtual status_t listAudioPatches(unsigned int *num_patches, 253 struct audio_patch *patches); 254 255 /* Set audio port configuration */ 256 virtual status_t setAudioPortConfig(const struct audio_port_config *config); 257 258 /* Get the HW synchronization source used for an audio session */ 259 virtual audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId); 260 261 /* Indicate JAVA services are ready (scheduling, power management ...) */ 262 virtual status_t systemReady(); 263 264 virtual status_t onTransact( 265 uint32_t code, 266 const Parcel& data, 267 Parcel* reply, 268 uint32_t flags); 269 270 // end of IAudioFlinger interface 271 272 sp<NBLog::Writer> newWriter_l(size_t size, const char *name); 273 void unregisterWriter(const sp<NBLog::Writer>& writer); 274 private: 275 static const size_t kLogMemorySize = 40 * 1024; 276 sp<MemoryDealer> mLogMemoryDealer; // == 0 when NBLog is disabled 277 // When a log writer is unregistered, it is done lazily so that media.log can continue to see it 278 // for as long as possible. The memory is only freed when it is needed for another log writer. 279 Vector< sp<NBLog::Writer> > mUnregisteredWriters; 280 Mutex mUnregisteredWritersLock; 281 public: 282 283 class SyncEvent; 284 285 typedef void (*sync_event_callback_t)(const wp<SyncEvent>& event) ; 286 287 class SyncEvent : public RefBase { 288 public: SyncEvent(AudioSystem::sync_event_t type,audio_session_t triggerSession,audio_session_t listenerSession,sync_event_callback_t callBack,wp<RefBase> cookie)289 SyncEvent(AudioSystem::sync_event_t type, 290 audio_session_t triggerSession, 291 audio_session_t listenerSession, 292 sync_event_callback_t callBack, 293 wp<RefBase> cookie) 294 : mType(type), mTriggerSession(triggerSession), mListenerSession(listenerSession), 295 mCallback(callBack), mCookie(cookie) 296 {} 297 ~SyncEvent()298 virtual ~SyncEvent() {} 299 trigger()300 void trigger() { Mutex::Autolock _l(mLock); if (mCallback) mCallback(this); } isCancelled()301 bool isCancelled() const { Mutex::Autolock _l(mLock); return (mCallback == NULL); } cancel()302 void cancel() { Mutex::Autolock _l(mLock); mCallback = NULL; } type()303 AudioSystem::sync_event_t type() const { return mType; } triggerSession()304 audio_session_t triggerSession() const { return mTriggerSession; } listenerSession()305 audio_session_t listenerSession() const { return mListenerSession; } cookie()306 wp<RefBase> cookie() const { return mCookie; } 307 308 private: 309 const AudioSystem::sync_event_t mType; 310 const audio_session_t mTriggerSession; 311 const audio_session_t mListenerSession; 312 sync_event_callback_t mCallback; 313 const wp<RefBase> mCookie; 314 mutable Mutex mLock; 315 }; 316 317 sp<SyncEvent> createSyncEvent(AudioSystem::sync_event_t type, 318 audio_session_t triggerSession, 319 audio_session_t listenerSession, 320 sync_event_callback_t callBack, 321 wp<RefBase> cookie); 322 323 private: 324 getMode()325 audio_mode_t getMode() const { return mMode; } 326 btNrecIsOff()327 bool btNrecIsOff() const { return mBtNrecIsOff; } 328 329 AudioFlinger() ANDROID_API; 330 virtual ~AudioFlinger(); 331 332 // call in any IAudioFlinger method that accesses mPrimaryHardwareDev initCheck()333 status_t initCheck() const { return mPrimaryHardwareDev == NULL ? 334 NO_INIT : NO_ERROR; } 335 336 // RefBase 337 virtual void onFirstRef(); 338 339 AudioHwDevice* findSuitableHwDev_l(audio_module_handle_t module, 340 audio_devices_t devices); 341 void purgeStaleEffects_l(); 342 343 // Set kEnableExtendedChannels to true to enable greater than stereo output 344 // for the MixerThread and device sink. Number of channels allowed is 345 // FCC_2 <= channels <= AudioMixer::MAX_NUM_CHANNELS. 346 static const bool kEnableExtendedChannels = true; 347 348 // Returns true if channel mask is permitted for the PCM sink in the MixerThread isValidPcmSinkChannelMask(audio_channel_mask_t channelMask)349 static inline bool isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) { 350 switch (audio_channel_mask_get_representation(channelMask)) { 351 case AUDIO_CHANNEL_REPRESENTATION_POSITION: { 352 uint32_t channelCount = FCC_2; // stereo is default 353 if (kEnableExtendedChannels) { 354 channelCount = audio_channel_count_from_out_mask(channelMask); 355 if (channelCount < FCC_2 // mono is not supported at this time 356 || channelCount > AudioMixer::MAX_NUM_CHANNELS) { 357 return false; 358 } 359 } 360 // check that channelMask is the "canonical" one we expect for the channelCount. 361 return channelMask == audio_channel_out_mask_from_count(channelCount); 362 } 363 case AUDIO_CHANNEL_REPRESENTATION_INDEX: 364 if (kEnableExtendedChannels) { 365 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask); 366 if (channelCount >= FCC_2 // mono is not supported at this time 367 && channelCount <= AudioMixer::MAX_NUM_CHANNELS) { 368 return true; 369 } 370 } 371 return false; 372 default: 373 return false; 374 } 375 } 376 377 // Set kEnableExtendedPrecision to true to use extended precision in MixerThread 378 static const bool kEnableExtendedPrecision = true; 379 380 // Returns true if format is permitted for the PCM sink in the MixerThread isValidPcmSinkFormat(audio_format_t format)381 static inline bool isValidPcmSinkFormat(audio_format_t format) { 382 switch (format) { 383 case AUDIO_FORMAT_PCM_16_BIT: 384 return true; 385 case AUDIO_FORMAT_PCM_FLOAT: 386 case AUDIO_FORMAT_PCM_24_BIT_PACKED: 387 case AUDIO_FORMAT_PCM_32_BIT: 388 case AUDIO_FORMAT_PCM_8_24_BIT: 389 return kEnableExtendedPrecision; 390 default: 391 return false; 392 } 393 } 394 395 // standby delay for MIXER and DUPLICATING playback threads is read from property 396 // ro.audio.flinger_standbytime_ms or defaults to kDefaultStandbyTimeInNsecs 397 static nsecs_t mStandbyTimeInNsecs; 398 399 // incremented by 2 when screen state changes, bit 0 == 1 means "off" 400 // AudioFlinger::setParameters() updates, other threads read w/o lock 401 static uint32_t mScreenState; 402 403 // Internal dump utilities. 404 static const int kDumpLockRetries = 50; 405 static const int kDumpLockSleepUs = 20000; 406 static bool dumpTryLock(Mutex& mutex); 407 void dumpPermissionDenial(int fd, const Vector<String16>& args); 408 void dumpClients(int fd, const Vector<String16>& args); 409 void dumpInternals(int fd, const Vector<String16>& args); 410 411 // --- Client --- 412 class Client : public RefBase { 413 public: 414 Client(const sp<AudioFlinger>& audioFlinger, pid_t pid); 415 virtual ~Client(); 416 sp<MemoryDealer> heap() const; pid()417 pid_t pid() const { return mPid; } audioFlinger()418 sp<AudioFlinger> audioFlinger() const { return mAudioFlinger; } 419 420 private: 421 Client(const Client&); 422 Client& operator = (const Client&); 423 const sp<AudioFlinger> mAudioFlinger; 424 sp<MemoryDealer> mMemoryDealer; 425 const pid_t mPid; 426 }; 427 428 // --- Notification Client --- 429 class NotificationClient : public IBinder::DeathRecipient { 430 public: 431 NotificationClient(const sp<AudioFlinger>& audioFlinger, 432 const sp<IAudioFlingerClient>& client, 433 pid_t pid); 434 virtual ~NotificationClient(); 435 audioFlingerClient()436 sp<IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; } 437 438 // IBinder::DeathRecipient 439 virtual void binderDied(const wp<IBinder>& who); 440 441 private: 442 NotificationClient(const NotificationClient&); 443 NotificationClient& operator = (const NotificationClient&); 444 445 const sp<AudioFlinger> mAudioFlinger; 446 const pid_t mPid; 447 const sp<IAudioFlingerClient> mAudioFlingerClient; 448 }; 449 450 class TrackHandle; 451 class RecordHandle; 452 class RecordThread; 453 class PlaybackThread; 454 class MixerThread; 455 class DirectOutputThread; 456 class OffloadThread; 457 class DuplicatingThread; 458 class AsyncCallbackThread; 459 class Track; 460 class RecordTrack; 461 class EffectModule; 462 class EffectHandle; 463 class EffectChain; 464 465 struct AudioStreamIn; 466 467 struct stream_type_t { stream_type_tstream_type_t468 stream_type_t() 469 : volume(1.0f), 470 mute(false) 471 { 472 } 473 float volume; 474 bool mute; 475 }; 476 477 // --- PlaybackThread --- 478 479 #include "Threads.h" 480 481 #include "Effects.h" 482 483 #include "PatchPanel.h" 484 485 // server side of the client's IAudioTrack 486 class TrackHandle : public android::BnAudioTrack { 487 public: 488 TrackHandle(const sp<PlaybackThread::Track>& track); 489 virtual ~TrackHandle(); 490 virtual sp<IMemory> getCblk() const; 491 virtual status_t start(); 492 virtual void stop(); 493 virtual void flush(); 494 virtual void pause(); 495 virtual status_t attachAuxEffect(int effectId); 496 virtual status_t setParameters(const String8& keyValuePairs); 497 virtual status_t getTimestamp(AudioTimestamp& timestamp); 498 virtual void signal(); // signal playback thread for a change in control block 499 500 virtual status_t onTransact( 501 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); 502 503 private: 504 const sp<PlaybackThread::Track> mTrack; 505 }; 506 507 // server side of the client's IAudioRecord 508 class RecordHandle : public android::BnAudioRecord { 509 public: 510 RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack); 511 virtual ~RecordHandle(); 512 virtual status_t start(int /*AudioSystem::sync_event_t*/ event, 513 audio_session_t triggerSession); 514 virtual void stop(); 515 virtual status_t onTransact( 516 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); 517 private: 518 const sp<RecordThread::RecordTrack> mRecordTrack; 519 520 // for use from destructor 521 void stop_nonvirtual(); 522 }; 523 524 525 ThreadBase *checkThread_l(audio_io_handle_t ioHandle) const; 526 PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const; 527 MixerThread *checkMixerThread_l(audio_io_handle_t output) const; 528 RecordThread *checkRecordThread_l(audio_io_handle_t input) const; 529 sp<RecordThread> openInput_l(audio_module_handle_t module, 530 audio_io_handle_t *input, 531 audio_config_t *config, 532 audio_devices_t device, 533 const String8& address, 534 audio_source_t source, 535 audio_input_flags_t flags); 536 sp<PlaybackThread> openOutput_l(audio_module_handle_t module, 537 audio_io_handle_t *output, 538 audio_config_t *config, 539 audio_devices_t devices, 540 const String8& address, 541 audio_output_flags_t flags); 542 543 void closeOutputFinish(sp<PlaybackThread> thread); 544 void closeInputFinish(sp<RecordThread> thread); 545 546 // no range check, AudioFlinger::mLock held streamMute_l(audio_stream_type_t stream)547 bool streamMute_l(audio_stream_type_t stream) const 548 { return mStreamTypes[stream].mute; } 549 // no range check, doesn't check per-thread stream volume, AudioFlinger::mLock held streamVolume_l(audio_stream_type_t stream)550 float streamVolume_l(audio_stream_type_t stream) const 551 { return mStreamTypes[stream].volume; } 552 void ioConfigChanged(audio_io_config_event event, 553 const sp<AudioIoDescriptor>& ioDesc, 554 pid_t pid = 0); 555 556 // Allocate an audio_unique_id_t. 557 // Specific types are audio_io_handle_t, audio_session_t, effect ID (int), 558 // audio_module_handle_t, and audio_patch_handle_t. 559 // They all share the same ID space, but the namespaces are actually independent 560 // because there are separate KeyedVectors for each kind of ID. 561 // The return value is cast to the specific type depending on how the ID will be used. 562 // FIXME This API does not handle rollover to zero (for unsigned IDs), 563 // or from positive to negative (for signed IDs). 564 // Thus it may fail by returning an ID of the wrong sign, 565 // or by returning a non-unique ID. 566 // This is the internal API. For the binder API see newAudioUniqueId(). 567 audio_unique_id_t nextUniqueId(audio_unique_id_use_t use); 568 569 status_t moveEffectChain_l(audio_session_t sessionId, 570 PlaybackThread *srcThread, 571 PlaybackThread *dstThread, 572 bool reRegister); 573 574 // return thread associated with primary hardware device, or NULL 575 PlaybackThread *primaryPlaybackThread_l() const; 576 audio_devices_t primaryOutputDevice_l() const; 577 578 sp<PlaybackThread> getEffectThread_l(audio_session_t sessionId, int EffectId); 579 580 581 void removeClient_l(pid_t pid); 582 void removeNotificationClient(pid_t pid); 583 bool isNonOffloadableGlobalEffectEnabled_l(); 584 void onNonOffloadableGlobalEffectEnable(); 585 586 // Store an effect chain to mOrphanEffectChains keyed vector. 587 // Called when a thread exits and effects are still attached to it. 588 // If effects are later created on the same session, they will reuse the same 589 // effect chain and same instances in the effect library. 590 // return ALREADY_EXISTS if a chain with the same session already exists in 591 // mOrphanEffectChains. Note that this should never happen as there is only one 592 // chain for a given session and it is attached to only one thread at a time. 593 status_t putOrphanEffectChain_l(const sp<EffectChain>& chain); 594 // Get an effect chain for the specified session in mOrphanEffectChains and remove 595 // it if found. Returns 0 if not found (this is the most common case). 596 sp<EffectChain> getOrphanEffectChain_l(audio_session_t session); 597 // Called when the last effect handle on an effect instance is removed. If this 598 // effect belongs to an effect chain in mOrphanEffectChains, the chain is updated 599 // and removed from mOrphanEffectChains if it does not contain any effect. 600 // Return true if the effect was found in mOrphanEffectChains, false otherwise. 601 bool updateOrphanEffectChains(const sp<EffectModule>& effect); 602 603 void broacastParametersToRecordThreads_l(const String8& keyValuePairs); 604 605 // AudioStreamIn is immutable, so their fields are const. 606 // For emphasis, we could also make all pointers to them be "const *", 607 // but that would clutter the code unnecessarily. 608 609 struct AudioStreamIn { 610 AudioHwDevice* const audioHwDev; 611 audio_stream_in_t* const stream; 612 hwDevAudioStreamIn613 audio_hw_device_t* hwDev() const { return audioHwDev->hwDevice(); } 614 AudioStreamInAudioStreamIn615 AudioStreamIn(AudioHwDevice *dev, audio_stream_in_t *in) : 616 audioHwDev(dev), stream(in) {} 617 }; 618 619 // for mAudioSessionRefs only 620 struct AudioSessionRef { AudioSessionRefAudioSessionRef621 AudioSessionRef(audio_session_t sessionid, pid_t pid) : 622 mSessionid(sessionid), mPid(pid), mCnt(1) {} 623 const audio_session_t mSessionid; 624 const pid_t mPid; 625 int mCnt; 626 }; 627 628 mutable Mutex mLock; 629 // protects mClients and mNotificationClients. 630 // must be locked after mLock and ThreadBase::mLock if both must be locked 631 // avoids acquiring AudioFlinger::mLock from inside thread loop. 632 mutable Mutex mClientLock; 633 // protected by mClientLock 634 DefaultKeyedVector< pid_t, wp<Client> > mClients; // see ~Client() 635 636 mutable Mutex mHardwareLock; 637 // NOTE: If both mLock and mHardwareLock mutexes must be held, 638 // always take mLock before mHardwareLock 639 640 // These two fields are immutable after onFirstRef(), so no lock needed to access 641 AudioHwDevice* mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL 642 DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*> mAudioHwDevs; 643 644 // for dump, indicates which hardware operation is currently in progress (but not stream ops) 645 enum hardware_call_state { 646 AUDIO_HW_IDLE = 0, // no operation in progress 647 AUDIO_HW_INIT, // init_check 648 AUDIO_HW_OUTPUT_OPEN, // open_output_stream 649 AUDIO_HW_OUTPUT_CLOSE, // unused 650 AUDIO_HW_INPUT_OPEN, // unused 651 AUDIO_HW_INPUT_CLOSE, // unused 652 AUDIO_HW_STANDBY, // unused 653 AUDIO_HW_SET_MASTER_VOLUME, // set_master_volume 654 AUDIO_HW_GET_ROUTING, // unused 655 AUDIO_HW_SET_ROUTING, // unused 656 AUDIO_HW_GET_MODE, // unused 657 AUDIO_HW_SET_MODE, // set_mode 658 AUDIO_HW_GET_MIC_MUTE, // get_mic_mute 659 AUDIO_HW_SET_MIC_MUTE, // set_mic_mute 660 AUDIO_HW_SET_VOICE_VOLUME, // set_voice_volume 661 AUDIO_HW_SET_PARAMETER, // set_parameters 662 AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size 663 AUDIO_HW_GET_MASTER_VOLUME, // get_master_volume 664 AUDIO_HW_GET_PARAMETER, // get_parameters 665 AUDIO_HW_SET_MASTER_MUTE, // set_master_mute 666 AUDIO_HW_GET_MASTER_MUTE, // get_master_mute 667 }; 668 669 mutable hardware_call_state mHardwareStatus; // for dump only 670 671 672 DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> > mPlaybackThreads; 673 stream_type_t mStreamTypes[AUDIO_STREAM_CNT]; 674 675 // member variables below are protected by mLock 676 float mMasterVolume; 677 bool mMasterMute; 678 // end of variables protected by mLock 679 680 DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> > mRecordThreads; 681 682 // protected by mClientLock 683 DefaultKeyedVector< pid_t, sp<NotificationClient> > mNotificationClients; 684 685 // updated by atomic_fetch_add_explicit 686 volatile atomic_uint_fast32_t mNextUniqueIds[AUDIO_UNIQUE_ID_USE_MAX]; 687 688 audio_mode_t mMode; 689 bool mBtNrecIsOff; 690 691 // protected by mLock 692 Vector<AudioSessionRef*> mAudioSessionRefs; 693 694 float masterVolume_l() const; 695 bool masterMute_l() const; 696 audio_module_handle_t loadHwModule_l(const char *name); 697 698 Vector < sp<SyncEvent> > mPendingSyncEvents; // sync events awaiting for a session 699 // to be created 700 701 // Effect chains without a valid thread 702 DefaultKeyedVector< audio_session_t , sp<EffectChain> > mOrphanEffectChains; 703 704 // list of sessions for which a valid HW A/V sync ID was retrieved from the HAL 705 DefaultKeyedVector< audio_session_t , audio_hw_sync_t >mHwAvSyncIds; 706 private: 707 sp<Client> registerPid(pid_t pid); // always returns non-0 708 709 // for use from destructor 710 status_t closeOutput_nonvirtual(audio_io_handle_t output); 711 void closeOutputInternal_l(sp<PlaybackThread> thread); 712 status_t closeInput_nonvirtual(audio_io_handle_t input); 713 void closeInputInternal_l(sp<RecordThread> thread); 714 void setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId); 715 716 status_t checkStreamType(audio_stream_type_t stream) const; 717 718 #ifdef TEE_SINK 719 // all record threads serially share a common tee sink, which is re-created on format change 720 sp<NBAIO_Sink> mRecordTeeSink; 721 sp<NBAIO_Source> mRecordTeeSource; 722 #endif 723 724 public: 725 726 #ifdef TEE_SINK 727 // tee sink, if enabled by property, allows dumpsys to write most recent audio to .wav file 728 static void dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id = 0); 729 730 // whether tee sink is enabled by property 731 static bool mTeeSinkInputEnabled; 732 static bool mTeeSinkOutputEnabled; 733 static bool mTeeSinkTrackEnabled; 734 735 // runtime configured size of each tee sink pipe, in frames 736 static size_t mTeeSinkInputFrames; 737 static size_t mTeeSinkOutputFrames; 738 static size_t mTeeSinkTrackFrames; 739 740 // compile-time default size of tee sink pipes, in frames 741 // 0x200000 stereo 16-bit PCM frames = 47.5 seconds at 44.1 kHz, 8 megabytes 742 static const size_t kTeeSinkInputFramesDefault = 0x200000; 743 static const size_t kTeeSinkOutputFramesDefault = 0x200000; 744 static const size_t kTeeSinkTrackFramesDefault = 0x200000; 745 #endif 746 747 // This method reads from a variable without mLock, but the variable is updated under mLock. So 748 // we might read a stale value, or a value that's inconsistent with respect to other variables. 749 // In this case, it's safe because the return value isn't used for making an important decision. 750 // The reason we don't want to take mLock is because it could block the caller for a long time. isLowRamDevice()751 bool isLowRamDevice() const { return mIsLowRamDevice; } 752 753 private: 754 bool mIsLowRamDevice; 755 bool mIsDeviceTypeKnown; 756 nsecs_t mGlobalEffectEnableTime; // when a global effect was last enabled 757 758 sp<PatchPanel> mPatchPanel; 759 760 bool mSystemReady; 761 }; 762 763 #undef INCLUDING_FROM_AUDIOFLINGER_H 764 765 const char *formatToString(audio_format_t format); 766 String8 inputFlagsToString(audio_input_flags_t flags); 767 String8 outputFlagsToString(audio_output_flags_t flags); 768 String8 devicesToString(audio_devices_t devices); 769 const char *sourceToString(audio_source_t source); 770 771 // ---------------------------------------------------------------------------- 772 773 } // namespace android 774 775 #endif // ANDROID_AUDIO_FLINGER_H 776