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