AudioFlinger.cpp revision f66b42242342017c26eb97de544dae31dd2537ca
12a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/* 22a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)** 32a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)** Copyright 2007, The Android Open Source Project 42a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)** 52a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)** Licensed under the Apache License, Version 2.0 (the "License"); 62a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)** you may not use this file except in compliance with the License. 72a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)** You may obtain a copy of the License at 85d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** 95d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** http://www.apache.org/licenses/LICENSE-2.0 105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** 115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** Unless required by applicable law or agreed to in writing, software 125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** distributed under the License is distributed on an "AS IS" BASIS, 135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** See the License for the specific language governing permissions and 155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)** limitations under the License. 165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)*/ 175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) 192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define LOG_TAG "AudioFlinger" 202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//#define LOG_NDEBUG 0 215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "Configuration.h" 232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <dirent.h> 245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <math.h> 255d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <signal.h> 265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <sys/time.h> 275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <sys/resource.h> 285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 295d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <binder/IPCThreadState.h> 305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <binder/IServiceManager.h> 315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <utils/Log.h> 325d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <utils/Trace.h> 335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <binder/Parcel.h> 345d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <utils/String16.h> 355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <utils/threads.h> 365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <utils/Atomic.h> 375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <cutils/bitops.h> 395d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <cutils/properties.h> 405d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <system/audio.h> 422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <hardware/audio.h> 432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) 442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "AudioMixer.h" 452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "AudioFlinger.h" 46#include "ServiceUtilities.h" 47 48#include <media/EffectsFactoryApi.h> 49#include <audio_effects/effect_visualizer.h> 50#include <audio_effects/effect_ns.h> 51#include <audio_effects/effect_aec.h> 52 53#include <audio_utils/primitives.h> 54 55#include <powermanager/PowerManager.h> 56 57#include <common_time/cc_helper.h> 58 59#include <media/IMediaLogService.h> 60 61#include <media/nbaio/Pipe.h> 62#include <media/nbaio/PipeReader.h> 63#include <media/AudioParameter.h> 64#include <private/android_filesystem_config.h> 65 66// ---------------------------------------------------------------------------- 67 68// Note: the following macro is used for extremely verbose logging message. In 69// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 70// 0; but one side effect of this is to turn all LOGV's as well. Some messages 71// are so verbose that we want to suppress them even when we have ALOG_ASSERT 72// turned on. Do not uncomment the #def below unless you really know what you 73// are doing and want to see all of the extremely verbose messages. 74//#define VERY_VERY_VERBOSE_LOGGING 75#ifdef VERY_VERY_VERBOSE_LOGGING 76#define ALOGVV ALOGV 77#else 78#define ALOGVV(a...) do { } while(0) 79#endif 80 81namespace android { 82 83static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 84static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 85 86 87nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 88 89uint32_t AudioFlinger::mScreenState; 90 91#ifdef TEE_SINK 92bool AudioFlinger::mTeeSinkInputEnabled = false; 93bool AudioFlinger::mTeeSinkOutputEnabled = false; 94bool AudioFlinger::mTeeSinkTrackEnabled = false; 95 96size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault; 97size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault; 98size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault; 99#endif 100 101// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off 102// we define a minimum time during which a global effect is considered enabled. 103static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200); 104 105// ---------------------------------------------------------------------------- 106 107const char *formatToString(audio_format_t format) { 108 switch(format) { 109 case AUDIO_FORMAT_PCM_SUB_8_BIT: return "pcm8"; 110 case AUDIO_FORMAT_PCM_SUB_16_BIT: return "pcm16"; 111 case AUDIO_FORMAT_PCM_SUB_32_BIT: return "pcm32"; 112 case AUDIO_FORMAT_PCM_SUB_8_24_BIT: return "pcm8.24"; 113 case AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED: return "pcm24"; 114 case AUDIO_FORMAT_PCM_SUB_FLOAT: return "pcmfloat"; 115 case AUDIO_FORMAT_MP3: return "mp3"; 116 case AUDIO_FORMAT_AMR_NB: return "amr-nb"; 117 case AUDIO_FORMAT_AMR_WB: return "amr-wb"; 118 case AUDIO_FORMAT_AAC: return "aac"; 119 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1"; 120 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2"; 121 case AUDIO_FORMAT_VORBIS: return "vorbis"; 122 default: 123 break; 124 } 125 return "unknown"; 126} 127 128static int load_audio_interface(const char *if_name, audio_hw_device_t **dev) 129{ 130 const hw_module_t *mod; 131 int rc; 132 133 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod); 134 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__, 135 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 136 if (rc) { 137 goto out; 138 } 139 rc = audio_hw_device_open(mod, dev); 140 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__, 141 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 142 if (rc) { 143 goto out; 144 } 145 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) { 146 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version); 147 rc = BAD_VALUE; 148 goto out; 149 } 150 return 0; 151 152out: 153 *dev = NULL; 154 return rc; 155} 156 157// ---------------------------------------------------------------------------- 158 159AudioFlinger::AudioFlinger() 160 : BnAudioFlinger(), 161 mPrimaryHardwareDev(NULL), 162 mHardwareStatus(AUDIO_HW_IDLE), 163 mMasterVolume(1.0f), 164 mMasterMute(false), 165 mNextUniqueId(1), 166 mMode(AUDIO_MODE_INVALID), 167 mBtNrecIsOff(false), 168 mIsLowRamDevice(true), 169 mIsDeviceTypeKnown(false), 170 mGlobalEffectEnableTime(0) 171{ 172 getpid_cached = getpid(); 173 char value[PROPERTY_VALUE_MAX]; 174 bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1); 175 if (doLog) { 176 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters"); 177 } 178#ifdef TEE_SINK 179 (void) property_get("ro.debuggable", value, "0"); 180 int debuggable = atoi(value); 181 int teeEnabled = 0; 182 if (debuggable) { 183 (void) property_get("af.tee", value, "0"); 184 teeEnabled = atoi(value); 185 } 186 // FIXME symbolic constants here 187 if (teeEnabled & 1) { 188 mTeeSinkInputEnabled = true; 189 } 190 if (teeEnabled & 2) { 191 mTeeSinkOutputEnabled = true; 192 } 193 if (teeEnabled & 4) { 194 mTeeSinkTrackEnabled = true; 195 } 196#endif 197} 198 199void AudioFlinger::onFirstRef() 200{ 201 int rc = 0; 202 203 Mutex::Autolock _l(mLock); 204 205 /* TODO: move all this work into an Init() function */ 206 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 207 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 208 uint32_t int_val; 209 if (1 == sscanf(val_str, "%u", &int_val)) { 210 mStandbyTimeInNsecs = milliseconds(int_val); 211 ALOGI("Using %u mSec as standby time.", int_val); 212 } else { 213 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 214 ALOGI("Using default %u mSec as standby time.", 215 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 216 } 217 } 218 219 mMode = AUDIO_MODE_NORMAL; 220} 221 222AudioFlinger::~AudioFlinger() 223{ 224 while (!mRecordThreads.isEmpty()) { 225 // closeInput_nonvirtual() will remove specified entry from mRecordThreads 226 closeInput_nonvirtual(mRecordThreads.keyAt(0)); 227 } 228 while (!mPlaybackThreads.isEmpty()) { 229 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads 230 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0)); 231 } 232 233 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 234 // no mHardwareLock needed, as there are no other references to this 235 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice()); 236 delete mAudioHwDevs.valueAt(i); 237 } 238 239 // Tell media.log service about any old writers that still need to be unregistered 240 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 241 if (binder != 0) { 242 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 243 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 244 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory()); 245 mUnregisteredWriters.pop(); 246 mediaLogService->unregisterWriter(iMemory); 247 } 248 } 249 250} 251 252static const char * const audio_interfaces[] = { 253 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 254 AUDIO_HARDWARE_MODULE_ID_A2DP, 255 AUDIO_HARDWARE_MODULE_ID_USB, 256}; 257#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 258 259AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l( 260 audio_module_handle_t module, 261 audio_devices_t devices) 262{ 263 // if module is 0, the request comes from an old policy manager and we should load 264 // well known modules 265 if (module == 0) { 266 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 267 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 268 loadHwModule_l(audio_interfaces[i]); 269 } 270 // then try to find a module supporting the requested device. 271 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 272 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i); 273 audio_hw_device_t *dev = audioHwDevice->hwDevice(); 274 if ((dev->get_supported_devices != NULL) && 275 (dev->get_supported_devices(dev) & devices) == devices) 276 return audioHwDevice; 277 } 278 } else { 279 // check a match for the requested module handle 280 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module); 281 if (audioHwDevice != NULL) { 282 return audioHwDevice; 283 } 284 } 285 286 return NULL; 287} 288 289void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused) 290{ 291 const size_t SIZE = 256; 292 char buffer[SIZE]; 293 String8 result; 294 295 result.append("Clients:\n"); 296 for (size_t i = 0; i < mClients.size(); ++i) { 297 sp<Client> client = mClients.valueAt(i).promote(); 298 if (client != 0) { 299 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 300 result.append(buffer); 301 } 302 } 303 304 result.append("Notification Clients:\n"); 305 for (size_t i = 0; i < mNotificationClients.size(); ++i) { 306 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i)); 307 result.append(buffer); 308 } 309 310 result.append("Global session refs:\n"); 311 result.append(" session pid count\n"); 312 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 313 AudioSessionRef *r = mAudioSessionRefs[i]; 314 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt); 315 result.append(buffer); 316 } 317 write(fd, result.string(), result.size()); 318} 319 320 321void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused) 322{ 323 const size_t SIZE = 256; 324 char buffer[SIZE]; 325 String8 result; 326 hardware_call_state hardwareStatus = mHardwareStatus; 327 328 snprintf(buffer, SIZE, "Hardware status: %d\n" 329 "Standby Time mSec: %u\n", 330 hardwareStatus, 331 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 332 result.append(buffer); 333 write(fd, result.string(), result.size()); 334} 335 336void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused) 337{ 338 const size_t SIZE = 256; 339 char buffer[SIZE]; 340 String8 result; 341 snprintf(buffer, SIZE, "Permission Denial: " 342 "can't dump AudioFlinger from pid=%d, uid=%d\n", 343 IPCThreadState::self()->getCallingPid(), 344 IPCThreadState::self()->getCallingUid()); 345 result.append(buffer); 346 write(fd, result.string(), result.size()); 347} 348 349bool AudioFlinger::dumpTryLock(Mutex& mutex) 350{ 351 bool locked = false; 352 for (int i = 0; i < kDumpLockRetries; ++i) { 353 if (mutex.tryLock() == NO_ERROR) { 354 locked = true; 355 break; 356 } 357 usleep(kDumpLockSleepUs); 358 } 359 return locked; 360} 361 362status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 363{ 364 if (!dumpAllowed()) { 365 dumpPermissionDenial(fd, args); 366 } else { 367 // get state of hardware lock 368 bool hardwareLocked = dumpTryLock(mHardwareLock); 369 if (!hardwareLocked) { 370 String8 result(kHardwareLockedString); 371 write(fd, result.string(), result.size()); 372 } else { 373 mHardwareLock.unlock(); 374 } 375 376 bool locked = dumpTryLock(mLock); 377 378 // failed to lock - AudioFlinger is probably deadlocked 379 if (!locked) { 380 String8 result(kDeadlockedString); 381 write(fd, result.string(), result.size()); 382 } 383 384 dumpClients(fd, args); 385 dumpInternals(fd, args); 386 387 // dump playback threads 388 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 389 mPlaybackThreads.valueAt(i)->dump(fd, args); 390 } 391 392 // dump record threads 393 for (size_t i = 0; i < mRecordThreads.size(); i++) { 394 mRecordThreads.valueAt(i)->dump(fd, args); 395 } 396 397 // dump all hardware devs 398 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 399 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 400 dev->dump(dev, fd); 401 } 402 403#ifdef TEE_SINK 404 // dump the serially shared record tee sink 405 if (mRecordTeeSource != 0) { 406 dumpTee(fd, mRecordTeeSource); 407 } 408#endif 409 410 if (locked) { 411 mLock.unlock(); 412 } 413 414 // append a copy of media.log here by forwarding fd to it, but don't attempt 415 // to lookup the service if it's not running, as it will block for a second 416 if (mLogMemoryDealer != 0) { 417 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 418 if (binder != 0) { 419 fdprintf(fd, "\nmedia.log:\n"); 420 Vector<String16> args; 421 binder->dump(fd, args); 422 } 423 } 424 } 425 return NO_ERROR; 426} 427 428sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid) 429{ 430 // If pid is already in the mClients wp<> map, then use that entry 431 // (for which promote() is always != 0), otherwise create a new entry and Client. 432 sp<Client> client = mClients.valueFor(pid).promote(); 433 if (client == 0) { 434 client = new Client(this, pid); 435 mClients.add(pid, client); 436 } 437 438 return client; 439} 440 441sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name) 442{ 443 // If there is no memory allocated for logs, return a dummy writer that does nothing 444 if (mLogMemoryDealer == 0) { 445 return new NBLog::Writer(); 446 } 447 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 448 // Similarly if we can't contact the media.log service, also return a dummy writer 449 if (binder == 0) { 450 return new NBLog::Writer(); 451 } 452 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 453 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 454 // If allocation fails, consult the vector of previously unregistered writers 455 // and garbage-collect one or more them until an allocation succeeds 456 if (shared == 0) { 457 Mutex::Autolock _l(mUnregisteredWritersLock); 458 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 459 { 460 // Pick the oldest stale writer to garbage-collect 461 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory()); 462 mUnregisteredWriters.removeAt(0); 463 mediaLogService->unregisterWriter(iMemory); 464 // Now the media.log remote reference to IMemory is gone. When our last local 465 // reference to IMemory also drops to zero at end of this block, 466 // the IMemory destructor will deallocate the region from mLogMemoryDealer. 467 } 468 // Re-attempt the allocation 469 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 470 if (shared != 0) { 471 goto success; 472 } 473 } 474 // Even after garbage-collecting all old writers, there is still not enough memory, 475 // so return a dummy writer 476 return new NBLog::Writer(); 477 } 478success: 479 mediaLogService->registerWriter(shared, size, name); 480 return new NBLog::Writer(size, shared); 481} 482 483void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer) 484{ 485 if (writer == 0) { 486 return; 487 } 488 sp<IMemory> iMemory(writer->getIMemory()); 489 if (iMemory == 0) { 490 return; 491 } 492 // Rather than removing the writer immediately, append it to a queue of old writers to 493 // be garbage-collected later. This allows us to continue to view old logs for a while. 494 Mutex::Autolock _l(mUnregisteredWritersLock); 495 mUnregisteredWriters.push(writer); 496} 497 498// IAudioFlinger interface 499 500 501sp<IAudioTrack> AudioFlinger::createTrack( 502 audio_stream_type_t streamType, 503 uint32_t sampleRate, 504 audio_format_t format, 505 audio_channel_mask_t channelMask, 506 size_t *frameCount, 507 IAudioFlinger::track_flags_t *flags, 508 const sp<IMemory>& sharedBuffer, 509 audio_io_handle_t output, 510 pid_t tid, 511 int *sessionId, 512 String8& name, 513 int clientUid, 514 status_t *status) 515{ 516 sp<PlaybackThread::Track> track; 517 sp<TrackHandle> trackHandle; 518 sp<Client> client; 519 status_t lStatus; 520 int lSessionId; 521 522 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 523 // but if someone uses binder directly they could bypass that and cause us to crash 524 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 525 ALOGE("createTrack() invalid stream type %d", streamType); 526 lStatus = BAD_VALUE; 527 goto Exit; 528 } 529 530 // client is responsible for conversion of 8-bit PCM to 16-bit PCM, 531 // and we don't yet support 8.24 or 32-bit PCM 532 if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) { 533 ALOGE("createTrack() invalid format %#x", format); 534 lStatus = BAD_VALUE; 535 goto Exit; 536 } 537 538 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) { 539 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()"); 540 lStatus = BAD_VALUE; 541 goto Exit; 542 } 543 544 { 545 Mutex::Autolock _l(mLock); 546 PlaybackThread *thread = checkPlaybackThread_l(output); 547 PlaybackThread *effectThread = NULL; 548 if (thread == NULL) { 549 ALOGE("no playback thread found for output handle %d", output); 550 lStatus = BAD_VALUE; 551 goto Exit; 552 } 553 554 pid_t pid = IPCThreadState::self()->getCallingPid(); 555 556 client = registerPid_l(pid); 557 558 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 559 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 560 // check if an effect chain with the same session ID is present on another 561 // output thread and move it here. 562 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 563 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 564 if (mPlaybackThreads.keyAt(i) != output) { 565 uint32_t sessions = t->hasAudioSession(*sessionId); 566 if (sessions & PlaybackThread::EFFECT_SESSION) { 567 effectThread = t.get(); 568 break; 569 } 570 } 571 } 572 lSessionId = *sessionId; 573 } else { 574 // if no audio session id is provided, create one here 575 lSessionId = nextUniqueId(); 576 if (sessionId != NULL) { 577 *sessionId = lSessionId; 578 } 579 } 580 ALOGV("createTrack() lSessionId: %d", lSessionId); 581 582 track = thread->createTrack_l(client, streamType, sampleRate, format, 583 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus); 584 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0)); 585 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 586 587 // move effect chain to this output thread if an effect on same session was waiting 588 // for a track to be created 589 if (lStatus == NO_ERROR && effectThread != NULL) { 590 // no risk of deadlock because AudioFlinger::mLock is held 591 Mutex::Autolock _dl(thread->mLock); 592 Mutex::Autolock _sl(effectThread->mLock); 593 moveEffectChain_l(lSessionId, effectThread, thread, true); 594 } 595 596 // Look for sync events awaiting for a session to be used. 597 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 598 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 599 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 600 if (lStatus == NO_ERROR) { 601 (void) track->setSyncEvent(mPendingSyncEvents[i]); 602 } else { 603 mPendingSyncEvents[i]->cancel(); 604 } 605 mPendingSyncEvents.removeAt(i); 606 i--; 607 } 608 } 609 } 610 611 } 612 613 if (lStatus == NO_ERROR) { 614 // s for server's pid, n for normal mixer name, f for fast index 615 name = String8::format("s:%d;n:%d;f:%d", getpid_cached, track->name() - AudioMixer::TRACK0, 616 track->fastIndex()); 617 trackHandle = new TrackHandle(track); 618 } else { 619 // remove local strong reference to Client before deleting the Track so that the Client 620 // destructor is called by the TrackBase destructor with mLock held 621 client.clear(); 622 track.clear(); 623 } 624 625Exit: 626 *status = lStatus; 627 return trackHandle; 628} 629 630uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 631{ 632 Mutex::Autolock _l(mLock); 633 PlaybackThread *thread = checkPlaybackThread_l(output); 634 if (thread == NULL) { 635 ALOGW("sampleRate() unknown thread %d", output); 636 return 0; 637 } 638 return thread->sampleRate(); 639} 640 641int AudioFlinger::channelCount(audio_io_handle_t output) const 642{ 643 Mutex::Autolock _l(mLock); 644 PlaybackThread *thread = checkPlaybackThread_l(output); 645 if (thread == NULL) { 646 ALOGW("channelCount() unknown thread %d", output); 647 return 0; 648 } 649 return thread->channelCount(); 650} 651 652audio_format_t AudioFlinger::format(audio_io_handle_t output) const 653{ 654 Mutex::Autolock _l(mLock); 655 PlaybackThread *thread = checkPlaybackThread_l(output); 656 if (thread == NULL) { 657 ALOGW("format() unknown thread %d", output); 658 return AUDIO_FORMAT_INVALID; 659 } 660 return thread->format(); 661} 662 663size_t AudioFlinger::frameCount(audio_io_handle_t output) const 664{ 665 Mutex::Autolock _l(mLock); 666 PlaybackThread *thread = checkPlaybackThread_l(output); 667 if (thread == NULL) { 668 ALOGW("frameCount() unknown thread %d", output); 669 return 0; 670 } 671 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 672 // should examine all callers and fix them to handle smaller counts 673 return thread->frameCount(); 674} 675 676uint32_t AudioFlinger::latency(audio_io_handle_t output) const 677{ 678 Mutex::Autolock _l(mLock); 679 PlaybackThread *thread = checkPlaybackThread_l(output); 680 if (thread == NULL) { 681 ALOGW("latency(): no playback thread found for output handle %d", output); 682 return 0; 683 } 684 return thread->latency(); 685} 686 687status_t AudioFlinger::setMasterVolume(float value) 688{ 689 status_t ret = initCheck(); 690 if (ret != NO_ERROR) { 691 return ret; 692 } 693 694 // check calling permissions 695 if (!settingsAllowed()) { 696 return PERMISSION_DENIED; 697 } 698 699 Mutex::Autolock _l(mLock); 700 mMasterVolume = value; 701 702 // Set master volume in the HALs which support it. 703 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 704 AutoMutex lock(mHardwareLock); 705 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 706 707 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 708 if (dev->canSetMasterVolume()) { 709 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 710 } 711 mHardwareStatus = AUDIO_HW_IDLE; 712 } 713 714 // Now set the master volume in each playback thread. Playback threads 715 // assigned to HALs which do not have master volume support will apply 716 // master volume during the mix operation. Threads with HALs which do 717 // support master volume will simply ignore the setting. 718 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 719 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 720 721 return NO_ERROR; 722} 723 724status_t AudioFlinger::setMode(audio_mode_t mode) 725{ 726 status_t ret = initCheck(); 727 if (ret != NO_ERROR) { 728 return ret; 729 } 730 731 // check calling permissions 732 if (!settingsAllowed()) { 733 return PERMISSION_DENIED; 734 } 735 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 736 ALOGW("Illegal value: setMode(%d)", mode); 737 return BAD_VALUE; 738 } 739 740 { // scope for the lock 741 AutoMutex lock(mHardwareLock); 742 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 743 mHardwareStatus = AUDIO_HW_SET_MODE; 744 ret = dev->set_mode(dev, mode); 745 mHardwareStatus = AUDIO_HW_IDLE; 746 } 747 748 if (NO_ERROR == ret) { 749 Mutex::Autolock _l(mLock); 750 mMode = mode; 751 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 752 mPlaybackThreads.valueAt(i)->setMode(mode); 753 } 754 755 return ret; 756} 757 758status_t AudioFlinger::setMicMute(bool state) 759{ 760 status_t ret = initCheck(); 761 if (ret != NO_ERROR) { 762 return ret; 763 } 764 765 // check calling permissions 766 if (!settingsAllowed()) { 767 return PERMISSION_DENIED; 768 } 769 770 AutoMutex lock(mHardwareLock); 771 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 772 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 773 ret = dev->set_mic_mute(dev, state); 774 mHardwareStatus = AUDIO_HW_IDLE; 775 return ret; 776} 777 778bool AudioFlinger::getMicMute() const 779{ 780 status_t ret = initCheck(); 781 if (ret != NO_ERROR) { 782 return false; 783 } 784 785 bool state = AUDIO_MODE_INVALID; 786 AutoMutex lock(mHardwareLock); 787 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 788 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 789 dev->get_mic_mute(dev, &state); 790 mHardwareStatus = AUDIO_HW_IDLE; 791 return state; 792} 793 794status_t AudioFlinger::setMasterMute(bool muted) 795{ 796 status_t ret = initCheck(); 797 if (ret != NO_ERROR) { 798 return ret; 799 } 800 801 // check calling permissions 802 if (!settingsAllowed()) { 803 return PERMISSION_DENIED; 804 } 805 806 Mutex::Autolock _l(mLock); 807 mMasterMute = muted; 808 809 // Set master mute in the HALs which support it. 810 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 811 AutoMutex lock(mHardwareLock); 812 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 813 814 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 815 if (dev->canSetMasterMute()) { 816 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 817 } 818 mHardwareStatus = AUDIO_HW_IDLE; 819 } 820 821 // Now set the master mute in each playback thread. Playback threads 822 // assigned to HALs which do not have master mute support will apply master 823 // mute during the mix operation. Threads with HALs which do support master 824 // mute will simply ignore the setting. 825 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 826 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 827 828 return NO_ERROR; 829} 830 831float AudioFlinger::masterVolume() const 832{ 833 Mutex::Autolock _l(mLock); 834 return masterVolume_l(); 835} 836 837bool AudioFlinger::masterMute() const 838{ 839 Mutex::Autolock _l(mLock); 840 return masterMute_l(); 841} 842 843float AudioFlinger::masterVolume_l() const 844{ 845 return mMasterVolume; 846} 847 848bool AudioFlinger::masterMute_l() const 849{ 850 return mMasterMute; 851} 852 853status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 854 audio_io_handle_t output) 855{ 856 // check calling permissions 857 if (!settingsAllowed()) { 858 return PERMISSION_DENIED; 859 } 860 861 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 862 ALOGE("setStreamVolume() invalid stream %d", stream); 863 return BAD_VALUE; 864 } 865 866 AutoMutex lock(mLock); 867 PlaybackThread *thread = NULL; 868 if (output) { 869 thread = checkPlaybackThread_l(output); 870 if (thread == NULL) { 871 return BAD_VALUE; 872 } 873 } 874 875 mStreamTypes[stream].volume = value; 876 877 if (thread == NULL) { 878 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 879 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 880 } 881 } else { 882 thread->setStreamVolume(stream, value); 883 } 884 885 return NO_ERROR; 886} 887 888status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 889{ 890 // check calling permissions 891 if (!settingsAllowed()) { 892 return PERMISSION_DENIED; 893 } 894 895 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 896 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 897 ALOGE("setStreamMute() invalid stream %d", stream); 898 return BAD_VALUE; 899 } 900 901 AutoMutex lock(mLock); 902 mStreamTypes[stream].mute = muted; 903 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 904 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 905 906 return NO_ERROR; 907} 908 909float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 910{ 911 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 912 return 0.0f; 913 } 914 915 AutoMutex lock(mLock); 916 float volume; 917 if (output) { 918 PlaybackThread *thread = checkPlaybackThread_l(output); 919 if (thread == NULL) { 920 return 0.0f; 921 } 922 volume = thread->streamVolume(stream); 923 } else { 924 volume = streamVolume_l(stream); 925 } 926 927 return volume; 928} 929 930bool AudioFlinger::streamMute(audio_stream_type_t stream) const 931{ 932 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 933 return true; 934 } 935 936 AutoMutex lock(mLock); 937 return streamMute_l(stream); 938} 939 940status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 941{ 942 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 943 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 944 945 // check calling permissions 946 if (!settingsAllowed()) { 947 return PERMISSION_DENIED; 948 } 949 950 // ioHandle == 0 means the parameters are global to the audio hardware interface 951 if (ioHandle == 0) { 952 Mutex::Autolock _l(mLock); 953 status_t final_result = NO_ERROR; 954 { 955 AutoMutex lock(mHardwareLock); 956 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 957 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 958 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 959 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 960 final_result = result ?: final_result; 961 } 962 mHardwareStatus = AUDIO_HW_IDLE; 963 } 964 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 965 AudioParameter param = AudioParameter(keyValuePairs); 966 String8 value; 967 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 968 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 969 if (mBtNrecIsOff != btNrecIsOff) { 970 for (size_t i = 0; i < mRecordThreads.size(); i++) { 971 sp<RecordThread> thread = mRecordThreads.valueAt(i); 972 audio_devices_t device = thread->inDevice(); 973 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 974 // collect all of the thread's session IDs 975 KeyedVector<int, bool> ids = thread->sessionIds(); 976 // suspend effects associated with those session IDs 977 for (size_t j = 0; j < ids.size(); ++j) { 978 int sessionId = ids.keyAt(j); 979 thread->setEffectSuspended(FX_IID_AEC, 980 suspend, 981 sessionId); 982 thread->setEffectSuspended(FX_IID_NS, 983 suspend, 984 sessionId); 985 } 986 } 987 mBtNrecIsOff = btNrecIsOff; 988 } 989 } 990 String8 screenState; 991 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 992 bool isOff = screenState == "off"; 993 if (isOff != (AudioFlinger::mScreenState & 1)) { 994 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 995 } 996 } 997 return final_result; 998 } 999 1000 // hold a strong ref on thread in case closeOutput() or closeInput() is called 1001 // and the thread is exited once the lock is released 1002 sp<ThreadBase> thread; 1003 { 1004 Mutex::Autolock _l(mLock); 1005 thread = checkPlaybackThread_l(ioHandle); 1006 if (thread == 0) { 1007 thread = checkRecordThread_l(ioHandle); 1008 } else if (thread == primaryPlaybackThread_l()) { 1009 // indicate output device change to all input threads for pre processing 1010 AudioParameter param = AudioParameter(keyValuePairs); 1011 int value; 1012 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 1013 (value != 0)) { 1014 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1015 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 1016 } 1017 } 1018 } 1019 } 1020 if (thread != 0) { 1021 return thread->setParameters(keyValuePairs); 1022 } 1023 return BAD_VALUE; 1024} 1025 1026String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 1027{ 1028 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 1029 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 1030 1031 Mutex::Autolock _l(mLock); 1032 1033 if (ioHandle == 0) { 1034 String8 out_s8; 1035 1036 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1037 char *s; 1038 { 1039 AutoMutex lock(mHardwareLock); 1040 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 1041 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1042 s = dev->get_parameters(dev, keys.string()); 1043 mHardwareStatus = AUDIO_HW_IDLE; 1044 } 1045 out_s8 += String8(s ? s : ""); 1046 free(s); 1047 } 1048 return out_s8; 1049 } 1050 1051 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 1052 if (playbackThread != NULL) { 1053 return playbackThread->getParameters(keys); 1054 } 1055 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1056 if (recordThread != NULL) { 1057 return recordThread->getParameters(keys); 1058 } 1059 return String8(""); 1060} 1061 1062size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 1063 audio_channel_mask_t channelMask) const 1064{ 1065 status_t ret = initCheck(); 1066 if (ret != NO_ERROR) { 1067 return 0; 1068 } 1069 1070 AutoMutex lock(mHardwareLock); 1071 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1072 struct audio_config config; 1073 memset(&config, 0, sizeof(config)); 1074 config.sample_rate = sampleRate; 1075 config.channel_mask = channelMask; 1076 config.format = format; 1077 1078 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1079 size_t size = dev->get_input_buffer_size(dev, &config); 1080 mHardwareStatus = AUDIO_HW_IDLE; 1081 return size; 1082} 1083 1084uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1085{ 1086 Mutex::Autolock _l(mLock); 1087 1088 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1089 if (recordThread != NULL) { 1090 return recordThread->getInputFramesLost(); 1091 } 1092 return 0; 1093} 1094 1095status_t AudioFlinger::setVoiceVolume(float value) 1096{ 1097 status_t ret = initCheck(); 1098 if (ret != NO_ERROR) { 1099 return ret; 1100 } 1101 1102 // check calling permissions 1103 if (!settingsAllowed()) { 1104 return PERMISSION_DENIED; 1105 } 1106 1107 AutoMutex lock(mHardwareLock); 1108 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1109 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1110 ret = dev->set_voice_volume(dev, value); 1111 mHardwareStatus = AUDIO_HW_IDLE; 1112 1113 return ret; 1114} 1115 1116status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 1117 audio_io_handle_t output) const 1118{ 1119 status_t status; 1120 1121 Mutex::Autolock _l(mLock); 1122 1123 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1124 if (playbackThread != NULL) { 1125 return playbackThread->getRenderPosition(halFrames, dspFrames); 1126 } 1127 1128 return BAD_VALUE; 1129} 1130 1131void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1132{ 1133 1134 Mutex::Autolock _l(mLock); 1135 1136 pid_t pid = IPCThreadState::self()->getCallingPid(); 1137 if (mNotificationClients.indexOfKey(pid) < 0) { 1138 sp<NotificationClient> notificationClient = new NotificationClient(this, 1139 client, 1140 pid); 1141 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1142 1143 mNotificationClients.add(pid, notificationClient); 1144 1145 sp<IBinder> binder = client->asBinder(); 1146 binder->linkToDeath(notificationClient); 1147 1148 // the config change is always sent from playback or record threads to avoid deadlock 1149 // with AudioSystem::gLock 1150 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1151 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1152 } 1153 1154 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1155 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1156 } 1157 } 1158} 1159 1160void AudioFlinger::removeNotificationClient(pid_t pid) 1161{ 1162 Mutex::Autolock _l(mLock); 1163 1164 mNotificationClients.removeItem(pid); 1165 1166 ALOGV("%d died, releasing its sessions", pid); 1167 size_t num = mAudioSessionRefs.size(); 1168 bool removed = false; 1169 for (size_t i = 0; i< num; ) { 1170 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1171 ALOGV(" pid %d @ %d", ref->mPid, i); 1172 if (ref->mPid == pid) { 1173 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1174 mAudioSessionRefs.removeAt(i); 1175 delete ref; 1176 removed = true; 1177 num--; 1178 } else { 1179 i++; 1180 } 1181 } 1182 if (removed) { 1183 purgeStaleEffects_l(); 1184 } 1185} 1186 1187// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1188void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1189{ 1190 size_t size = mNotificationClients.size(); 1191 for (size_t i = 0; i < size; i++) { 1192 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1193 param2); 1194 } 1195} 1196 1197// removeClient_l() must be called with AudioFlinger::mLock held 1198void AudioFlinger::removeClient_l(pid_t pid) 1199{ 1200 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1201 IPCThreadState::self()->getCallingPid()); 1202 mClients.removeItem(pid); 1203} 1204 1205// getEffectThread_l() must be called with AudioFlinger::mLock held 1206sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1207{ 1208 sp<PlaybackThread> thread; 1209 1210 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1211 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1212 ALOG_ASSERT(thread == 0); 1213 thread = mPlaybackThreads.valueAt(i); 1214 } 1215 } 1216 1217 return thread; 1218} 1219 1220 1221 1222// ---------------------------------------------------------------------------- 1223 1224AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1225 : RefBase(), 1226 mAudioFlinger(audioFlinger), 1227 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 1228 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 1229 mPid(pid), 1230 mTimedTrackCount(0) 1231{ 1232 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 1233} 1234 1235// Client destructor must be called with AudioFlinger::mLock held 1236AudioFlinger::Client::~Client() 1237{ 1238 mAudioFlinger->removeClient_l(mPid); 1239} 1240 1241sp<MemoryDealer> AudioFlinger::Client::heap() const 1242{ 1243 return mMemoryDealer; 1244} 1245 1246// Reserve one of the limited slots for a timed audio track associated 1247// with this client 1248bool AudioFlinger::Client::reserveTimedTrack() 1249{ 1250 const int kMaxTimedTracksPerClient = 4; 1251 1252 Mutex::Autolock _l(mTimedTrackLock); 1253 1254 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 1255 ALOGW("can not create timed track - pid %d has exceeded the limit", 1256 mPid); 1257 return false; 1258 } 1259 1260 mTimedTrackCount++; 1261 return true; 1262} 1263 1264// Release a slot for a timed audio track 1265void AudioFlinger::Client::releaseTimedTrack() 1266{ 1267 Mutex::Autolock _l(mTimedTrackLock); 1268 mTimedTrackCount--; 1269} 1270 1271// ---------------------------------------------------------------------------- 1272 1273AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1274 const sp<IAudioFlingerClient>& client, 1275 pid_t pid) 1276 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1277{ 1278} 1279 1280AudioFlinger::NotificationClient::~NotificationClient() 1281{ 1282} 1283 1284void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused) 1285{ 1286 sp<NotificationClient> keep(this); 1287 mAudioFlinger->removeNotificationClient(mPid); 1288} 1289 1290 1291// ---------------------------------------------------------------------------- 1292 1293static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) { 1294 return audio_is_remote_submix_device(inDevice); 1295} 1296 1297sp<IAudioRecord> AudioFlinger::openRecord( 1298 audio_io_handle_t input, 1299 uint32_t sampleRate, 1300 audio_format_t format, 1301 audio_channel_mask_t channelMask, 1302 size_t *frameCount, 1303 IAudioFlinger::track_flags_t *flags, 1304 pid_t tid, 1305 int *sessionId, 1306 status_t *status) 1307{ 1308 sp<RecordThread::RecordTrack> recordTrack; 1309 sp<RecordHandle> recordHandle; 1310 sp<Client> client; 1311 status_t lStatus; 1312 RecordThread *thread; 1313 size_t inFrameCount; 1314 int lSessionId; 1315 1316 // check calling permissions 1317 if (!recordingAllowed()) { 1318 ALOGE("openRecord() permission denied: recording not allowed"); 1319 lStatus = PERMISSION_DENIED; 1320 goto Exit; 1321 } 1322 1323 if (format != AUDIO_FORMAT_PCM_16_BIT) { 1324 ALOGE("openRecord() invalid format %#x", format); 1325 lStatus = BAD_VALUE; 1326 goto Exit; 1327 } 1328 1329 // add client to list 1330 { // scope for mLock 1331 Mutex::Autolock _l(mLock); 1332 thread = checkRecordThread_l(input); 1333 if (thread == NULL) { 1334 ALOGE("openRecord() checkRecordThread_l failed"); 1335 lStatus = BAD_VALUE; 1336 goto Exit; 1337 } 1338 1339 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice()) 1340 && !captureAudioOutputAllowed()) { 1341 ALOGE("openRecord() permission denied: capture not allowed"); 1342 lStatus = PERMISSION_DENIED; 1343 goto Exit; 1344 } 1345 1346 pid_t pid = IPCThreadState::self()->getCallingPid(); 1347 client = registerPid_l(pid); 1348 1349 // If no audio session id is provided, create one here 1350 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 1351 lSessionId = *sessionId; 1352 } else { 1353 lSessionId = nextUniqueId(); 1354 if (sessionId != NULL) { 1355 *sessionId = lSessionId; 1356 } 1357 } 1358 // create new record track. 1359 // The record track uses one track in mHardwareMixerThread by convention. 1360 // TODO: the uid should be passed in as a parameter to openRecord 1361 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1362 frameCount, lSessionId, 1363 IPCThreadState::self()->getCallingUid(), 1364 flags, tid, &lStatus); 1365 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0)); 1366 } 1367 1368 if (lStatus != NO_ERROR) { 1369 // remove local strong reference to Client before deleting the RecordTrack so that the 1370 // Client destructor is called by the TrackBase destructor with mLock held 1371 client.clear(); 1372 recordTrack.clear(); 1373 goto Exit; 1374 } 1375 1376 // return handle to client 1377 recordHandle = new RecordHandle(recordTrack); 1378 1379Exit: 1380 *status = lStatus; 1381 return recordHandle; 1382} 1383 1384 1385 1386// ---------------------------------------------------------------------------- 1387 1388audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 1389{ 1390 if (!settingsAllowed()) { 1391 return 0; 1392 } 1393 Mutex::Autolock _l(mLock); 1394 return loadHwModule_l(name); 1395} 1396 1397// loadHwModule_l() must be called with AudioFlinger::mLock held 1398audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 1399{ 1400 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1401 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 1402 ALOGW("loadHwModule() module %s already loaded", name); 1403 return mAudioHwDevs.keyAt(i); 1404 } 1405 } 1406 1407 audio_hw_device_t *dev; 1408 1409 int rc = load_audio_interface(name, &dev); 1410 if (rc) { 1411 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 1412 return 0; 1413 } 1414 1415 mHardwareStatus = AUDIO_HW_INIT; 1416 rc = dev->init_check(dev); 1417 mHardwareStatus = AUDIO_HW_IDLE; 1418 if (rc) { 1419 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 1420 return 0; 1421 } 1422 1423 // Check and cache this HAL's level of support for master mute and master 1424 // volume. If this is the first HAL opened, and it supports the get 1425 // methods, use the initial values provided by the HAL as the current 1426 // master mute and volume settings. 1427 1428 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 1429 { // scope for auto-lock pattern 1430 AutoMutex lock(mHardwareLock); 1431 1432 if (0 == mAudioHwDevs.size()) { 1433 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 1434 if (NULL != dev->get_master_volume) { 1435 float mv; 1436 if (OK == dev->get_master_volume(dev, &mv)) { 1437 mMasterVolume = mv; 1438 } 1439 } 1440 1441 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 1442 if (NULL != dev->get_master_mute) { 1443 bool mm; 1444 if (OK == dev->get_master_mute(dev, &mm)) { 1445 mMasterMute = mm; 1446 } 1447 } 1448 } 1449 1450 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 1451 if ((NULL != dev->set_master_volume) && 1452 (OK == dev->set_master_volume(dev, mMasterVolume))) { 1453 flags = static_cast<AudioHwDevice::Flags>(flags | 1454 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 1455 } 1456 1457 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 1458 if ((NULL != dev->set_master_mute) && 1459 (OK == dev->set_master_mute(dev, mMasterMute))) { 1460 flags = static_cast<AudioHwDevice::Flags>(flags | 1461 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 1462 } 1463 1464 mHardwareStatus = AUDIO_HW_IDLE; 1465 } 1466 1467 audio_module_handle_t handle = nextUniqueId(); 1468 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags)); 1469 1470 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 1471 name, dev->common.module->name, dev->common.module->id, handle); 1472 1473 return handle; 1474 1475} 1476 1477// ---------------------------------------------------------------------------- 1478 1479uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 1480{ 1481 Mutex::Autolock _l(mLock); 1482 PlaybackThread *thread = primaryPlaybackThread_l(); 1483 return thread != NULL ? thread->sampleRate() : 0; 1484} 1485 1486size_t AudioFlinger::getPrimaryOutputFrameCount() 1487{ 1488 Mutex::Autolock _l(mLock); 1489 PlaybackThread *thread = primaryPlaybackThread_l(); 1490 return thread != NULL ? thread->frameCountHAL() : 0; 1491} 1492 1493// ---------------------------------------------------------------------------- 1494 1495status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice) 1496{ 1497 uid_t uid = IPCThreadState::self()->getCallingUid(); 1498 if (uid != AID_SYSTEM) { 1499 return PERMISSION_DENIED; 1500 } 1501 Mutex::Autolock _l(mLock); 1502 if (mIsDeviceTypeKnown) { 1503 return INVALID_OPERATION; 1504 } 1505 mIsLowRamDevice = isLowRamDevice; 1506 mIsDeviceTypeKnown = true; 1507 return NO_ERROR; 1508} 1509 1510// ---------------------------------------------------------------------------- 1511 1512audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 1513 audio_devices_t *pDevices, 1514 uint32_t *pSamplingRate, 1515 audio_format_t *pFormat, 1516 audio_channel_mask_t *pChannelMask, 1517 uint32_t *pLatencyMs, 1518 audio_output_flags_t flags, 1519 const audio_offload_info_t *offloadInfo) 1520{ 1521 struct audio_config config; 1522 memset(&config, 0, sizeof(config)); 1523 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1524 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1525 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1526 if (offloadInfo != NULL) { 1527 config.offload_info = *offloadInfo; 1528 } 1529 1530 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x", 1531 module, 1532 (pDevices != NULL) ? *pDevices : 0, 1533 config.sample_rate, 1534 config.format, 1535 config.channel_mask, 1536 flags); 1537 ALOGV("openOutput(), offloadInfo %p version 0x%04x", 1538 offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version); 1539 1540 if (pDevices == NULL || *pDevices == 0) { 1541 return 0; 1542 } 1543 1544 Mutex::Autolock _l(mLock); 1545 1546 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, *pDevices); 1547 if (outHwDev == NULL) { 1548 return 0; 1549 } 1550 1551 audio_hw_device_t *hwDevHal = outHwDev->hwDevice(); 1552 audio_io_handle_t id = nextUniqueId(); 1553 1554 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 1555 1556 audio_stream_out_t *outStream = NULL; 1557 status_t status = hwDevHal->open_output_stream(hwDevHal, 1558 id, 1559 *pDevices, 1560 (audio_output_flags_t)flags, 1561 &config, 1562 &outStream); 1563 1564 mHardwareStatus = AUDIO_HW_IDLE; 1565 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, " 1566 "Channels %x, status %d", 1567 outStream, 1568 config.sample_rate, 1569 config.format, 1570 config.channel_mask, 1571 status); 1572 1573 if (status == NO_ERROR && outStream != NULL) { 1574 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags); 1575 1576 PlaybackThread *thread; 1577 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1578 thread = new OffloadThread(this, output, id, *pDevices); 1579 ALOGV("openOutput() created offload output: ID %d thread %p", id, thread); 1580 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 1581 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 1582 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 1583 thread = new DirectOutputThread(this, output, id, *pDevices); 1584 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 1585 } else { 1586 thread = new MixerThread(this, output, id, *pDevices); 1587 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 1588 } 1589 mPlaybackThreads.add(id, thread); 1590 1591 if (pSamplingRate != NULL) { 1592 *pSamplingRate = config.sample_rate; 1593 } 1594 if (pFormat != NULL) { 1595 *pFormat = config.format; 1596 } 1597 if (pChannelMask != NULL) { 1598 *pChannelMask = config.channel_mask; 1599 } 1600 if (pLatencyMs != NULL) { 1601 *pLatencyMs = thread->latency(); 1602 } 1603 1604 // notify client processes of the new output creation 1605 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1606 1607 // the first primary output opened designates the primary hw device 1608 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 1609 ALOGI("Using module %d has the primary audio interface", module); 1610 mPrimaryHardwareDev = outHwDev; 1611 1612 AutoMutex lock(mHardwareLock); 1613 mHardwareStatus = AUDIO_HW_SET_MODE; 1614 hwDevHal->set_mode(hwDevHal, mMode); 1615 mHardwareStatus = AUDIO_HW_IDLE; 1616 } 1617 return id; 1618 } 1619 1620 return 0; 1621} 1622 1623audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 1624 audio_io_handle_t output2) 1625{ 1626 Mutex::Autolock _l(mLock); 1627 MixerThread *thread1 = checkMixerThread_l(output1); 1628 MixerThread *thread2 = checkMixerThread_l(output2); 1629 1630 if (thread1 == NULL || thread2 == NULL) { 1631 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 1632 output2); 1633 return 0; 1634 } 1635 1636 audio_io_handle_t id = nextUniqueId(); 1637 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 1638 thread->addOutputTrack(thread2); 1639 mPlaybackThreads.add(id, thread); 1640 // notify client processes of the new output creation 1641 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1642 return id; 1643} 1644 1645status_t AudioFlinger::closeOutput(audio_io_handle_t output) 1646{ 1647 return closeOutput_nonvirtual(output); 1648} 1649 1650status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 1651{ 1652 // keep strong reference on the playback thread so that 1653 // it is not destroyed while exit() is executed 1654 sp<PlaybackThread> thread; 1655 { 1656 Mutex::Autolock _l(mLock); 1657 thread = checkPlaybackThread_l(output); 1658 if (thread == NULL) { 1659 return BAD_VALUE; 1660 } 1661 1662 ALOGV("closeOutput() %d", output); 1663 1664 if (thread->type() == ThreadBase::MIXER) { 1665 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1666 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 1667 DuplicatingThread *dupThread = 1668 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 1669 dupThread->removeOutputTrack((MixerThread *)thread.get()); 1670 1671 } 1672 } 1673 } 1674 1675 1676 mPlaybackThreads.removeItem(output); 1677 // save all effects to the default thread 1678 if (mPlaybackThreads.size()) { 1679 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0)); 1680 if (dstThread != NULL) { 1681 // audioflinger lock is held here so the acquisition order of thread locks does not 1682 // matter 1683 Mutex::Autolock _dl(dstThread->mLock); 1684 Mutex::Autolock _sl(thread->mLock); 1685 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l(); 1686 for (size_t i = 0; i < effectChains.size(); i ++) { 1687 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true); 1688 } 1689 } 1690 } 1691 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 1692 } 1693 thread->exit(); 1694 // The thread entity (active unit of execution) is no longer running here, 1695 // but the ThreadBase container still exists. 1696 1697 if (thread->type() != ThreadBase::DUPLICATING) { 1698 AudioStreamOut *out = thread->clearOutput(); 1699 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 1700 // from now on thread->mOutput is NULL 1701 out->hwDev()->close_output_stream(out->hwDev(), out->stream); 1702 delete out; 1703 } 1704 return NO_ERROR; 1705} 1706 1707status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 1708{ 1709 Mutex::Autolock _l(mLock); 1710 PlaybackThread *thread = checkPlaybackThread_l(output); 1711 1712 if (thread == NULL) { 1713 return BAD_VALUE; 1714 } 1715 1716 ALOGV("suspendOutput() %d", output); 1717 thread->suspend(); 1718 1719 return NO_ERROR; 1720} 1721 1722status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 1723{ 1724 Mutex::Autolock _l(mLock); 1725 PlaybackThread *thread = checkPlaybackThread_l(output); 1726 1727 if (thread == NULL) { 1728 return BAD_VALUE; 1729 } 1730 1731 ALOGV("restoreOutput() %d", output); 1732 1733 thread->restore(); 1734 1735 return NO_ERROR; 1736} 1737 1738audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 1739 audio_devices_t *pDevices, 1740 uint32_t *pSamplingRate, 1741 audio_format_t *pFormat, 1742 audio_channel_mask_t *pChannelMask) 1743{ 1744 struct audio_config config; 1745 memset(&config, 0, sizeof(config)); 1746 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1747 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1748 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1749 1750 uint32_t reqSamplingRate = config.sample_rate; 1751 audio_format_t reqFormat = config.format; 1752 audio_channel_mask_t reqChannelMask = config.channel_mask; 1753 1754 if (pDevices == NULL || *pDevices == 0) { 1755 return 0; 1756 } 1757 1758 Mutex::Autolock _l(mLock); 1759 1760 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, *pDevices); 1761 if (inHwDev == NULL) { 1762 return 0; 1763 } 1764 1765 audio_hw_device_t *inHwHal = inHwDev->hwDevice(); 1766 audio_io_handle_t id = nextUniqueId(); 1767 1768 audio_stream_in_t *inStream = NULL; 1769 status_t status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, 1770 &inStream); 1771 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %#x, Channels %x, " 1772 "status %d", 1773 inStream, 1774 config.sample_rate, 1775 config.format, 1776 config.channel_mask, 1777 status); 1778 1779 // If the input could not be opened with the requested parameters and we can handle the 1780 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can 1781 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs. 1782 if (status == BAD_VALUE && 1783 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 1784 (config.sample_rate <= 2 * reqSamplingRate) && 1785 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannelMask) <= FCC_2)) { 1786 // FIXME describe the change proposed by HAL (save old values so we can log them here) 1787 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 1788 inStream = NULL; 1789 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 1790 // FIXME log this new status; HAL should not propose any further changes 1791 } 1792 1793 if (status == NO_ERROR && inStream != NULL) { 1794 1795#ifdef TEE_SINK 1796 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 1797 // or (re-)create if current Pipe is idle and does not match the new format 1798 sp<NBAIO_Sink> teeSink; 1799 enum { 1800 TEE_SINK_NO, // don't copy input 1801 TEE_SINK_NEW, // copy input using a new pipe 1802 TEE_SINK_OLD, // copy input using an existing pipe 1803 } kind; 1804 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 1805 popcount(inStream->common.get_channels(&inStream->common))); 1806 if (!mTeeSinkInputEnabled) { 1807 kind = TEE_SINK_NO; 1808 } else if (!Format_isValid(format)) { 1809 kind = TEE_SINK_NO; 1810 } else if (mRecordTeeSink == 0) { 1811 kind = TEE_SINK_NEW; 1812 } else if (mRecordTeeSink->getStrongCount() != 1) { 1813 kind = TEE_SINK_NO; 1814 } else if (Format_isEqual(format, mRecordTeeSink->format())) { 1815 kind = TEE_SINK_OLD; 1816 } else { 1817 kind = TEE_SINK_NEW; 1818 } 1819 switch (kind) { 1820 case TEE_SINK_NEW: { 1821 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 1822 size_t numCounterOffers = 0; 1823 const NBAIO_Format offers[1] = {format}; 1824 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 1825 ALOG_ASSERT(index == 0); 1826 PipeReader *pipeReader = new PipeReader(*pipe); 1827 numCounterOffers = 0; 1828 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 1829 ALOG_ASSERT(index == 0); 1830 mRecordTeeSink = pipe; 1831 mRecordTeeSource = pipeReader; 1832 teeSink = pipe; 1833 } 1834 break; 1835 case TEE_SINK_OLD: 1836 teeSink = mRecordTeeSink; 1837 break; 1838 case TEE_SINK_NO: 1839 default: 1840 break; 1841 } 1842#endif 1843 1844 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 1845 1846 // Start record thread 1847 // RecordThread requires both input and output device indication to forward to audio 1848 // pre processing modules 1849 RecordThread *thread = new RecordThread(this, 1850 input, 1851 id, 1852 primaryOutputDevice_l(), 1853 *pDevices 1854#ifdef TEE_SINK 1855 , teeSink 1856#endif 1857 ); 1858 mRecordThreads.add(id, thread); 1859 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 1860 if (pSamplingRate != NULL) { 1861 *pSamplingRate = reqSamplingRate; 1862 } 1863 if (pFormat != NULL) { 1864 *pFormat = config.format; 1865 } 1866 if (pChannelMask != NULL) { 1867 *pChannelMask = reqChannelMask; 1868 } 1869 1870 // notify client processes of the new input creation 1871 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 1872 return id; 1873 } 1874 1875 return 0; 1876} 1877 1878status_t AudioFlinger::closeInput(audio_io_handle_t input) 1879{ 1880 return closeInput_nonvirtual(input); 1881} 1882 1883status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 1884{ 1885 // keep strong reference on the record thread so that 1886 // it is not destroyed while exit() is executed 1887 sp<RecordThread> thread; 1888 { 1889 Mutex::Autolock _l(mLock); 1890 thread = checkRecordThread_l(input); 1891 if (thread == 0) { 1892 return BAD_VALUE; 1893 } 1894 1895 ALOGV("closeInput() %d", input); 1896 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 1897 mRecordThreads.removeItem(input); 1898 } 1899 thread->exit(); 1900 // The thread entity (active unit of execution) is no longer running here, 1901 // but the ThreadBase container still exists. 1902 1903 AudioStreamIn *in = thread->clearInput(); 1904 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 1905 // from now on thread->mInput is NULL 1906 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 1907 delete in; 1908 1909 return NO_ERROR; 1910} 1911 1912status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 1913{ 1914 Mutex::Autolock _l(mLock); 1915 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 1916 1917 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1918 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1919 thread->invalidateTracks(stream); 1920 } 1921 1922 return NO_ERROR; 1923} 1924 1925 1926int AudioFlinger::newAudioSessionId() 1927{ 1928 return nextUniqueId(); 1929} 1930 1931void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid) 1932{ 1933 Mutex::Autolock _l(mLock); 1934 pid_t caller = IPCThreadState::self()->getCallingPid(); 1935 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid); 1936 if (pid != -1 && (caller == getpid_cached)) { 1937 caller = pid; 1938 } 1939 1940 // Ignore requests received from processes not known as notification client. The request 1941 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be 1942 // called from a different pid leaving a stale session reference. Also we don't know how 1943 // to clear this reference if the client process dies. 1944 if (mNotificationClients.indexOfKey(caller) < 0) { 1945 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession); 1946 return; 1947 } 1948 1949 size_t num = mAudioSessionRefs.size(); 1950 for (size_t i = 0; i< num; i++) { 1951 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 1952 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1953 ref->mCnt++; 1954 ALOGV(" incremented refcount to %d", ref->mCnt); 1955 return; 1956 } 1957 } 1958 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 1959 ALOGV(" added new entry for %d", audioSession); 1960} 1961 1962void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid) 1963{ 1964 Mutex::Autolock _l(mLock); 1965 pid_t caller = IPCThreadState::self()->getCallingPid(); 1966 ALOGV("releasing %d from %d for %d", audioSession, caller, pid); 1967 if (pid != -1 && (caller == getpid_cached)) { 1968 caller = pid; 1969 } 1970 size_t num = mAudioSessionRefs.size(); 1971 for (size_t i = 0; i< num; i++) { 1972 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1973 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1974 ref->mCnt--; 1975 ALOGV(" decremented refcount to %d", ref->mCnt); 1976 if (ref->mCnt == 0) { 1977 mAudioSessionRefs.removeAt(i); 1978 delete ref; 1979 purgeStaleEffects_l(); 1980 } 1981 return; 1982 } 1983 } 1984 // If the caller is mediaserver it is likely that the session being released was acquired 1985 // on behalf of a process not in notification clients and we ignore the warning. 1986 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller); 1987} 1988 1989void AudioFlinger::purgeStaleEffects_l() { 1990 1991 ALOGV("purging stale effects"); 1992 1993 Vector< sp<EffectChain> > chains; 1994 1995 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1996 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 1997 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1998 sp<EffectChain> ec = t->mEffectChains[j]; 1999 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 2000 chains.push(ec); 2001 } 2002 } 2003 } 2004 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2005 sp<RecordThread> t = mRecordThreads.valueAt(i); 2006 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2007 sp<EffectChain> ec = t->mEffectChains[j]; 2008 chains.push(ec); 2009 } 2010 } 2011 2012 for (size_t i = 0; i < chains.size(); i++) { 2013 sp<EffectChain> ec = chains[i]; 2014 int sessionid = ec->sessionId(); 2015 sp<ThreadBase> t = ec->mThread.promote(); 2016 if (t == 0) { 2017 continue; 2018 } 2019 size_t numsessionrefs = mAudioSessionRefs.size(); 2020 bool found = false; 2021 for (size_t k = 0; k < numsessionrefs; k++) { 2022 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 2023 if (ref->mSessionid == sessionid) { 2024 ALOGV(" session %d still exists for %d with %d refs", 2025 sessionid, ref->mPid, ref->mCnt); 2026 found = true; 2027 break; 2028 } 2029 } 2030 if (!found) { 2031 Mutex::Autolock _l(t->mLock); 2032 // remove all effects from the chain 2033 while (ec->mEffects.size()) { 2034 sp<EffectModule> effect = ec->mEffects[0]; 2035 effect->unPin(); 2036 t->removeEffect_l(effect); 2037 if (effect->purgeHandles()) { 2038 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 2039 } 2040 AudioSystem::unregisterEffect(effect->id()); 2041 } 2042 } 2043 } 2044 return; 2045} 2046 2047// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2048AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 2049{ 2050 return mPlaybackThreads.valueFor(output).get(); 2051} 2052 2053// checkMixerThread_l() must be called with AudioFlinger::mLock held 2054AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 2055{ 2056 PlaybackThread *thread = checkPlaybackThread_l(output); 2057 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 2058} 2059 2060// checkRecordThread_l() must be called with AudioFlinger::mLock held 2061AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 2062{ 2063 return mRecordThreads.valueFor(input).get(); 2064} 2065 2066uint32_t AudioFlinger::nextUniqueId() 2067{ 2068 return android_atomic_inc(&mNextUniqueId); 2069} 2070 2071AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 2072{ 2073 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2074 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2075 AudioStreamOut *output = thread->getOutput(); 2076 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 2077 return thread; 2078 } 2079 } 2080 return NULL; 2081} 2082 2083audio_devices_t AudioFlinger::primaryOutputDevice_l() const 2084{ 2085 PlaybackThread *thread = primaryPlaybackThread_l(); 2086 2087 if (thread == NULL) { 2088 return 0; 2089 } 2090 2091 return thread->outDevice(); 2092} 2093 2094sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 2095 int triggerSession, 2096 int listenerSession, 2097 sync_event_callback_t callBack, 2098 void *cookie) 2099{ 2100 Mutex::Autolock _l(mLock); 2101 2102 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 2103 status_t playStatus = NAME_NOT_FOUND; 2104 status_t recStatus = NAME_NOT_FOUND; 2105 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2106 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 2107 if (playStatus == NO_ERROR) { 2108 return event; 2109 } 2110 } 2111 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2112 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 2113 if (recStatus == NO_ERROR) { 2114 return event; 2115 } 2116 } 2117 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2118 mPendingSyncEvents.add(event); 2119 } else { 2120 ALOGV("createSyncEvent() invalid event %d", event->type()); 2121 event.clear(); 2122 } 2123 return event; 2124} 2125 2126// ---------------------------------------------------------------------------- 2127// Effect management 2128// ---------------------------------------------------------------------------- 2129 2130 2131status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2132{ 2133 Mutex::Autolock _l(mLock); 2134 return EffectQueryNumberEffects(numEffects); 2135} 2136 2137status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2138{ 2139 Mutex::Autolock _l(mLock); 2140 return EffectQueryEffect(index, descriptor); 2141} 2142 2143status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2144 effect_descriptor_t *descriptor) const 2145{ 2146 Mutex::Autolock _l(mLock); 2147 return EffectGetDescriptor(pUuid, descriptor); 2148} 2149 2150 2151sp<IEffect> AudioFlinger::createEffect( 2152 effect_descriptor_t *pDesc, 2153 const sp<IEffectClient>& effectClient, 2154 int32_t priority, 2155 audio_io_handle_t io, 2156 int sessionId, 2157 status_t *status, 2158 int *id, 2159 int *enabled) 2160{ 2161 status_t lStatus = NO_ERROR; 2162 sp<EffectHandle> handle; 2163 effect_descriptor_t desc; 2164 2165 pid_t pid = IPCThreadState::self()->getCallingPid(); 2166 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 2167 pid, effectClient.get(), priority, sessionId, io); 2168 2169 if (pDesc == NULL) { 2170 lStatus = BAD_VALUE; 2171 goto Exit; 2172 } 2173 2174 // check audio settings permission for global effects 2175 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2176 lStatus = PERMISSION_DENIED; 2177 goto Exit; 2178 } 2179 2180 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2181 // that can only be created by audio policy manager (running in same process) 2182 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2183 lStatus = PERMISSION_DENIED; 2184 goto Exit; 2185 } 2186 2187 { 2188 if (!EffectIsNullUuid(&pDesc->uuid)) { 2189 // if uuid is specified, request effect descriptor 2190 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 2191 if (lStatus < 0) { 2192 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2193 goto Exit; 2194 } 2195 } else { 2196 // if uuid is not specified, look for an available implementation 2197 // of the required type in effect factory 2198 if (EffectIsNullUuid(&pDesc->type)) { 2199 ALOGW("createEffect() no effect type"); 2200 lStatus = BAD_VALUE; 2201 goto Exit; 2202 } 2203 uint32_t numEffects = 0; 2204 effect_descriptor_t d; 2205 d.flags = 0; // prevent compiler warning 2206 bool found = false; 2207 2208 lStatus = EffectQueryNumberEffects(&numEffects); 2209 if (lStatus < 0) { 2210 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2211 goto Exit; 2212 } 2213 for (uint32_t i = 0; i < numEffects; i++) { 2214 lStatus = EffectQueryEffect(i, &desc); 2215 if (lStatus < 0) { 2216 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2217 continue; 2218 } 2219 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2220 // If matching type found save effect descriptor. If the session is 2221 // 0 and the effect is not auxiliary, continue enumeration in case 2222 // an auxiliary version of this effect type is available 2223 found = true; 2224 d = desc; 2225 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2226 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2227 break; 2228 } 2229 } 2230 } 2231 if (!found) { 2232 lStatus = BAD_VALUE; 2233 ALOGW("createEffect() effect not found"); 2234 goto Exit; 2235 } 2236 // For same effect type, chose auxiliary version over insert version if 2237 // connect to output mix (Compliance to OpenSL ES) 2238 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2239 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2240 desc = d; 2241 } 2242 } 2243 2244 // Do not allow auxiliary effects on a session different from 0 (output mix) 2245 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2246 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2247 lStatus = INVALID_OPERATION; 2248 goto Exit; 2249 } 2250 2251 // check recording permission for visualizer 2252 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2253 !recordingAllowed()) { 2254 lStatus = PERMISSION_DENIED; 2255 goto Exit; 2256 } 2257 2258 // return effect descriptor 2259 *pDesc = desc; 2260 if (io == 0 && sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2261 // if the output returned by getOutputForEffect() is removed before we lock the 2262 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2263 // and we will exit safely 2264 io = AudioSystem::getOutputForEffect(&desc); 2265 ALOGV("createEffect got output %d", io); 2266 } 2267 2268 Mutex::Autolock _l(mLock); 2269 2270 // If output is not specified try to find a matching audio session ID in one of the 2271 // output threads. 2272 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2273 // because of code checking output when entering the function. 2274 // Note: io is never 0 when creating an effect on an input 2275 if (io == 0) { 2276 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2277 // output must be specified by AudioPolicyManager when using session 2278 // AUDIO_SESSION_OUTPUT_STAGE 2279 lStatus = BAD_VALUE; 2280 goto Exit; 2281 } 2282 // look for the thread where the specified audio session is present 2283 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2284 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2285 io = mPlaybackThreads.keyAt(i); 2286 break; 2287 } 2288 } 2289 if (io == 0) { 2290 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2291 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2292 io = mRecordThreads.keyAt(i); 2293 break; 2294 } 2295 } 2296 } 2297 // If no output thread contains the requested session ID, default to 2298 // first output. The effect chain will be moved to the correct output 2299 // thread when a track with the same session ID is created 2300 if (io == 0 && mPlaybackThreads.size()) { 2301 io = mPlaybackThreads.keyAt(0); 2302 } 2303 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2304 } 2305 ThreadBase *thread = checkRecordThread_l(io); 2306 if (thread == NULL) { 2307 thread = checkPlaybackThread_l(io); 2308 if (thread == NULL) { 2309 ALOGE("createEffect() unknown output thread"); 2310 lStatus = BAD_VALUE; 2311 goto Exit; 2312 } 2313 } 2314 2315 sp<Client> client = registerPid_l(pid); 2316 2317 // create effect on selected output thread 2318 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 2319 &desc, enabled, &lStatus); 2320 if (handle != 0 && id != NULL) { 2321 *id = handle->id(); 2322 } 2323 } 2324 2325Exit: 2326 *status = lStatus; 2327 return handle; 2328} 2329 2330status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2331 audio_io_handle_t dstOutput) 2332{ 2333 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2334 sessionId, srcOutput, dstOutput); 2335 Mutex::Autolock _l(mLock); 2336 if (srcOutput == dstOutput) { 2337 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2338 return NO_ERROR; 2339 } 2340 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2341 if (srcThread == NULL) { 2342 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2343 return BAD_VALUE; 2344 } 2345 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2346 if (dstThread == NULL) { 2347 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2348 return BAD_VALUE; 2349 } 2350 2351 Mutex::Autolock _dl(dstThread->mLock); 2352 Mutex::Autolock _sl(srcThread->mLock); 2353 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 2354} 2355 2356// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2357status_t AudioFlinger::moveEffectChain_l(int sessionId, 2358 AudioFlinger::PlaybackThread *srcThread, 2359 AudioFlinger::PlaybackThread *dstThread, 2360 bool reRegister) 2361{ 2362 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2363 sessionId, srcThread, dstThread); 2364 2365 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2366 if (chain == 0) { 2367 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2368 sessionId, srcThread); 2369 return INVALID_OPERATION; 2370 } 2371 2372 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2373 // so that a new chain is created with correct parameters when first effect is added. This is 2374 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2375 // removed. 2376 srcThread->removeEffectChain_l(chain); 2377 2378 // transfer all effects one by one so that new effect chain is created on new thread with 2379 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2380 sp<EffectChain> dstChain; 2381 uint32_t strategy = 0; // prevent compiler warning 2382 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2383 Vector< sp<EffectModule> > removed; 2384 status_t status = NO_ERROR; 2385 while (effect != 0) { 2386 srcThread->removeEffect_l(effect); 2387 removed.add(effect); 2388 status = dstThread->addEffect_l(effect); 2389 if (status != NO_ERROR) { 2390 break; 2391 } 2392 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2393 if (effect->state() == EffectModule::ACTIVE || 2394 effect->state() == EffectModule::STOPPING) { 2395 effect->start(); 2396 } 2397 // if the move request is not received from audio policy manager, the effect must be 2398 // re-registered with the new strategy and output 2399 if (dstChain == 0) { 2400 dstChain = effect->chain().promote(); 2401 if (dstChain == 0) { 2402 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2403 status = NO_INIT; 2404 break; 2405 } 2406 strategy = dstChain->strategy(); 2407 } 2408 if (reRegister) { 2409 AudioSystem::unregisterEffect(effect->id()); 2410 AudioSystem::registerEffect(&effect->desc(), 2411 dstThread->id(), 2412 strategy, 2413 sessionId, 2414 effect->id()); 2415 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2416 } 2417 effect = chain->getEffectFromId_l(0); 2418 } 2419 2420 if (status != NO_ERROR) { 2421 for (size_t i = 0; i < removed.size(); i++) { 2422 srcThread->addEffect_l(removed[i]); 2423 if (dstChain != 0 && reRegister) { 2424 AudioSystem::unregisterEffect(removed[i]->id()); 2425 AudioSystem::registerEffect(&removed[i]->desc(), 2426 srcThread->id(), 2427 strategy, 2428 sessionId, 2429 removed[i]->id()); 2430 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2431 } 2432 } 2433 } 2434 2435 return status; 2436} 2437 2438bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 2439{ 2440 if (mGlobalEffectEnableTime != 0 && 2441 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 2442 return true; 2443 } 2444 2445 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2446 sp<EffectChain> ec = 2447 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2448 if (ec != 0 && ec->isNonOffloadableEnabled()) { 2449 return true; 2450 } 2451 } 2452 return false; 2453} 2454 2455void AudioFlinger::onNonOffloadableGlobalEffectEnable() 2456{ 2457 Mutex::Autolock _l(mLock); 2458 2459 mGlobalEffectEnableTime = systemTime(); 2460 2461 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2462 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2463 if (t->mType == ThreadBase::OFFLOAD) { 2464 t->invalidateTracks(AUDIO_STREAM_MUSIC); 2465 } 2466 } 2467 2468} 2469 2470struct Entry { 2471#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2472 char mName[MAX_NAME]; 2473}; 2474 2475int comparEntry(const void *p1, const void *p2) 2476{ 2477 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2478} 2479 2480#ifdef TEE_SINK 2481void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2482{ 2483 NBAIO_Source *teeSource = source.get(); 2484 if (teeSource != NULL) { 2485 // .wav rotation 2486 // There is a benign race condition if 2 threads call this simultaneously. 2487 // They would both traverse the directory, but the result would simply be 2488 // failures at unlink() which are ignored. It's also unlikely since 2489 // normally dumpsys is only done by bugreport or from the command line. 2490 char teePath[32+256]; 2491 strcpy(teePath, "/data/misc/media"); 2492 size_t teePathLen = strlen(teePath); 2493 DIR *dir = opendir(teePath); 2494 teePath[teePathLen++] = '/'; 2495 if (dir != NULL) { 2496#define MAX_SORT 20 // number of entries to sort 2497#define MAX_KEEP 10 // number of entries to keep 2498 struct Entry entries[MAX_SORT]; 2499 size_t entryCount = 0; 2500 while (entryCount < MAX_SORT) { 2501 struct dirent de; 2502 struct dirent *result = NULL; 2503 int rc = readdir_r(dir, &de, &result); 2504 if (rc != 0) { 2505 ALOGW("readdir_r failed %d", rc); 2506 break; 2507 } 2508 if (result == NULL) { 2509 break; 2510 } 2511 if (result != &de) { 2512 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2513 break; 2514 } 2515 // ignore non .wav file entries 2516 size_t nameLen = strlen(de.d_name); 2517 if (nameLen <= 4 || nameLen >= MAX_NAME || 2518 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2519 continue; 2520 } 2521 strcpy(entries[entryCount++].mName, de.d_name); 2522 } 2523 (void) closedir(dir); 2524 if (entryCount > MAX_KEEP) { 2525 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2526 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2527 strcpy(&teePath[teePathLen], entries[i].mName); 2528 (void) unlink(teePath); 2529 } 2530 } 2531 } else { 2532 if (fd >= 0) { 2533 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2534 } 2535 } 2536 char teeTime[16]; 2537 struct timeval tv; 2538 gettimeofday(&tv, NULL); 2539 struct tm tm; 2540 localtime_r(&tv.tv_sec, &tm); 2541 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2542 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2543 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2544 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2545 if (teeFd >= 0) { 2546 char wavHeader[44]; 2547 memcpy(wavHeader, 2548 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0", 2549 sizeof(wavHeader)); 2550 NBAIO_Format format = teeSource->format(); 2551 unsigned channelCount = Format_channelCount(format); 2552 ALOG_ASSERT(channelCount <= FCC_2); 2553 uint32_t sampleRate = Format_sampleRate(format); 2554 wavHeader[22] = channelCount; // number of channels 2555 wavHeader[24] = sampleRate; // sample rate 2556 wavHeader[25] = sampleRate >> 8; 2557 wavHeader[32] = channelCount * 2; // block alignment 2558 write(teeFd, wavHeader, sizeof(wavHeader)); 2559 size_t total = 0; 2560 bool firstRead = true; 2561 for (;;) { 2562#define TEE_SINK_READ 1024 2563 short buffer[TEE_SINK_READ * FCC_2]; 2564 size_t count = TEE_SINK_READ; 2565 ssize_t actual = teeSource->read(buffer, count, 2566 AudioBufferProvider::kInvalidPTS); 2567 bool wasFirstRead = firstRead; 2568 firstRead = false; 2569 if (actual <= 0) { 2570 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2571 continue; 2572 } 2573 break; 2574 } 2575 ALOG_ASSERT(actual <= (ssize_t)count); 2576 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2577 total += actual; 2578 } 2579 lseek(teeFd, (off_t) 4, SEEK_SET); 2580 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2581 write(teeFd, &temp, sizeof(temp)); 2582 lseek(teeFd, (off_t) 40, SEEK_SET); 2583 temp = total * channelCount * sizeof(short); 2584 write(teeFd, &temp, sizeof(temp)); 2585 close(teeFd); 2586 if (fd >= 0) { 2587 fdprintf(fd, "tee copied to %s\n", teePath); 2588 } 2589 } else { 2590 if (fd >= 0) { 2591 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2592 } 2593 } 2594 } 2595} 2596#endif 2597 2598// ---------------------------------------------------------------------------- 2599 2600status_t AudioFlinger::onTransact( 2601 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2602{ 2603 return BnAudioFlinger::onTransact(code, data, reply, flags); 2604} 2605 2606}; // namespace android 2607