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