AudioFlinger.cpp revision f1da96d8cf60842538e00a9c950cc451f7da2c10
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 19#define LOG_TAG "AudioFlinger" 20//#define LOG_NDEBUG 0 21 22#include <math.h> 23#include <signal.h> 24#include <sys/time.h> 25#include <sys/resource.h> 26 27#include <binder/IPCThreadState.h> 28#include <binder/IServiceManager.h> 29#include <utils/Log.h> 30#include <utils/Trace.h> 31#include <binder/Parcel.h> 32#include <binder/IPCThreadState.h> 33#include <utils/String16.h> 34#include <utils/threads.h> 35#include <utils/Atomic.h> 36 37#include <cutils/bitops.h> 38#include <cutils/properties.h> 39#include <cutils/compiler.h> 40 41#undef ADD_BATTERY_DATA 42 43#ifdef ADD_BATTERY_DATA 44#include <media/IMediaPlayerService.h> 45#include <media/IMediaDeathNotifier.h> 46#endif 47 48#include <private/media/AudioTrackShared.h> 49#include <private/media/AudioEffectShared.h> 50 51#include <system/audio.h> 52#include <hardware/audio.h> 53 54#include "AudioMixer.h" 55#include "AudioFlinger.h" 56#include "ServiceUtilities.h" 57 58#include <media/EffectsFactoryApi.h> 59#include <audio_effects/effect_visualizer.h> 60#include <audio_effects/effect_ns.h> 61#include <audio_effects/effect_aec.h> 62 63#include <audio_utils/primitives.h> 64 65#include <powermanager/PowerManager.h> 66 67// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds 68#ifdef DEBUG_CPU_USAGE 69#include <cpustats/CentralTendencyStatistics.h> 70#include <cpustats/ThreadCpuUsage.h> 71#endif 72 73#include <common_time/cc_helper.h> 74#include <common_time/local_clock.h> 75 76#include "FastMixer.h" 77 78// NBAIO implementations 79#include "AudioStreamOutSink.h" 80#include "MonoPipe.h" 81#include "MonoPipeReader.h" 82#include "Pipe.h" 83#include "PipeReader.h" 84#include "SourceAudioBufferProvider.h" 85 86#ifdef HAVE_REQUEST_PRIORITY 87#include "SchedulingPolicyService.h" 88#endif 89 90#ifdef SOAKER 91#include "Soaker.h" 92#endif 93 94// ---------------------------------------------------------------------------- 95 96// Note: the following macro is used for extremely verbose logging message. In 97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 98// 0; but one side effect of this is to turn all LOGV's as well. Some messages 99// are so verbose that we want to suppress them even when we have ALOG_ASSERT 100// turned on. Do not uncomment the #def below unless you really know what you 101// are doing and want to see all of the extremely verbose messages. 102//#define VERY_VERY_VERBOSE_LOGGING 103#ifdef VERY_VERY_VERBOSE_LOGGING 104#define ALOGVV ALOGV 105#else 106#define ALOGVV(a...) do { } while(0) 107#endif 108 109namespace android { 110 111static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 112static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 113 114static const float MAX_GAIN = 4096.0f; 115static const uint32_t MAX_GAIN_INT = 0x1000; 116 117// retry counts for buffer fill timeout 118// 50 * ~20msecs = 1 second 119static const int8_t kMaxTrackRetries = 50; 120static const int8_t kMaxTrackStartupRetries = 50; 121// allow less retry attempts on direct output thread. 122// direct outputs can be a scarce resource in audio hardware and should 123// be released as quickly as possible. 124static const int8_t kMaxTrackRetriesDirect = 2; 125 126static const int kDumpLockRetries = 50; 127static const int kDumpLockSleepUs = 20000; 128 129// don't warn about blocked writes or record buffer overflows more often than this 130static const nsecs_t kWarningThrottleNs = seconds(5); 131 132// RecordThread loop sleep time upon application overrun or audio HAL read error 133static const int kRecordThreadSleepUs = 5000; 134 135// maximum time to wait for setParameters to complete 136static const nsecs_t kSetParametersTimeoutNs = seconds(2); 137 138// minimum sleep time for the mixer thread loop when tracks are active but in underrun 139static const uint32_t kMinThreadSleepTimeUs = 5000; 140// maximum divider applied to the active sleep time in the mixer thread loop 141static const uint32_t kMaxThreadSleepTimeShift = 2; 142 143// minimum normal mix buffer size, expressed in milliseconds rather than frames 144static const uint32_t kMinNormalMixBufferSizeMs = 20; 145// maximum normal mix buffer size 146static const uint32_t kMaxNormalMixBufferSizeMs = 24; 147 148nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 149 150// Whether to use fast mixer 151static const enum { 152 FastMixer_Never, // never initialize or use: for debugging only 153 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 154 // normal mixer multiplier is 1 155 FastMixer_Static, // initialize if needed, then use all the time if initialized, 156 // multiplier is calculated based on min & max normal mixer buffer size 157 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 158 // multiplier is calculated based on min & max normal mixer buffer size 159 // FIXME for FastMixer_Dynamic: 160 // Supporting this option will require fixing HALs that can't handle large writes. 161 // For example, one HAL implementation returns an error from a large write, 162 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 163 // We could either fix the HAL implementations, or provide a wrapper that breaks 164 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 165} kUseFastMixer = FastMixer_Static; 166 167static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off" 168 // AudioFlinger::setParameters() updates, other threads read w/o lock 169 170// ---------------------------------------------------------------------------- 171 172#ifdef ADD_BATTERY_DATA 173// To collect the amplifier usage 174static void addBatteryData(uint32_t params) { 175 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 176 if (service == NULL) { 177 // it already logged 178 return; 179 } 180 181 service->addBatteryData(params); 182} 183#endif 184 185static int load_audio_interface(const char *if_name, audio_hw_device_t **dev) 186{ 187 const hw_module_t *mod; 188 int rc; 189 190 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod); 191 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__, 192 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 193 if (rc) { 194 goto out; 195 } 196 rc = audio_hw_device_open(mod, dev); 197 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__, 198 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 199 if (rc) { 200 goto out; 201 } 202 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) { 203 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version); 204 rc = BAD_VALUE; 205 goto out; 206 } 207 return 0; 208 209out: 210 *dev = NULL; 211 return rc; 212} 213 214// ---------------------------------------------------------------------------- 215 216AudioFlinger::AudioFlinger() 217 : BnAudioFlinger(), 218 mPrimaryHardwareDev(NULL), 219 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef() 220 mMasterVolume(1.0f), 221 mMasterVolumeSupportLvl(MVS_NONE), 222 mMasterMute(false), 223 mNextUniqueId(1), 224 mMode(AUDIO_MODE_INVALID), 225 mBtNrecIsOff(false) 226{ 227} 228 229void AudioFlinger::onFirstRef() 230{ 231 int rc = 0; 232 233 Mutex::Autolock _l(mLock); 234 235 /* TODO: move all this work into an Init() function */ 236 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 237 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 238 uint32_t int_val; 239 if (1 == sscanf(val_str, "%u", &int_val)) { 240 mStandbyTimeInNsecs = milliseconds(int_val); 241 ALOGI("Using %u mSec as standby time.", int_val); 242 } else { 243 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 244 ALOGI("Using default %u mSec as standby time.", 245 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 246 } 247 } 248 249 mMode = AUDIO_MODE_NORMAL; 250 mMasterVolumeSW = 1.0; 251 mMasterVolume = 1.0; 252 mHardwareStatus = AUDIO_HW_IDLE; 253} 254 255AudioFlinger::~AudioFlinger() 256{ 257 258 while (!mRecordThreads.isEmpty()) { 259 // closeInput() will remove first entry from mRecordThreads 260 closeInput(mRecordThreads.keyAt(0)); 261 } 262 while (!mPlaybackThreads.isEmpty()) { 263 // closeOutput() will remove first entry from mPlaybackThreads 264 closeOutput(mPlaybackThreads.keyAt(0)); 265 } 266 267 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 268 // no mHardwareLock needed, as there are no other references to this 269 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice()); 270 delete mAudioHwDevs.valueAt(i); 271 } 272} 273 274static const char * const audio_interfaces[] = { 275 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 276 AUDIO_HARDWARE_MODULE_ID_A2DP, 277 AUDIO_HARDWARE_MODULE_ID_USB, 278}; 279#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 280 281audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices) 282{ 283 // if module is 0, the request comes from an old policy manager and we should load 284 // well known modules 285 if (module == 0) { 286 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 287 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 288 loadHwModule_l(audio_interfaces[i]); 289 } 290 } else { 291 // check a match for the requested module handle 292 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module); 293 if (audioHwdevice != NULL) { 294 return audioHwdevice->hwDevice(); 295 } 296 } 297 // then try to find a module supporting the requested device. 298 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 299 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 300 if ((dev->get_supported_devices(dev) & devices) == devices) 301 return dev; 302 } 303 304 return NULL; 305} 306 307status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args) 308{ 309 const size_t SIZE = 256; 310 char buffer[SIZE]; 311 String8 result; 312 313 result.append("Clients:\n"); 314 for (size_t i = 0; i < mClients.size(); ++i) { 315 sp<Client> client = mClients.valueAt(i).promote(); 316 if (client != 0) { 317 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 318 result.append(buffer); 319 } 320 } 321 322 result.append("Global session refs:\n"); 323 result.append(" session pid count\n"); 324 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 325 AudioSessionRef *r = mAudioSessionRefs[i]; 326 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt); 327 result.append(buffer); 328 } 329 write(fd, result.string(), result.size()); 330 return NO_ERROR; 331} 332 333 334status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args) 335{ 336 const size_t SIZE = 256; 337 char buffer[SIZE]; 338 String8 result; 339 hardware_call_state hardwareStatus = mHardwareStatus; 340 341 snprintf(buffer, SIZE, "Hardware status: %d\n" 342 "Standby Time mSec: %u\n", 343 hardwareStatus, 344 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 345 result.append(buffer); 346 write(fd, result.string(), result.size()); 347 return NO_ERROR; 348} 349 350status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args) 351{ 352 const size_t SIZE = 256; 353 char buffer[SIZE]; 354 String8 result; 355 snprintf(buffer, SIZE, "Permission Denial: " 356 "can't dump AudioFlinger from pid=%d, uid=%d\n", 357 IPCThreadState::self()->getCallingPid(), 358 IPCThreadState::self()->getCallingUid()); 359 result.append(buffer); 360 write(fd, result.string(), result.size()); 361 return NO_ERROR; 362} 363 364static bool tryLock(Mutex& mutex) 365{ 366 bool locked = false; 367 for (int i = 0; i < kDumpLockRetries; ++i) { 368 if (mutex.tryLock() == NO_ERROR) { 369 locked = true; 370 break; 371 } 372 usleep(kDumpLockSleepUs); 373 } 374 return locked; 375} 376 377status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 378{ 379 if (!dumpAllowed()) { 380 dumpPermissionDenial(fd, args); 381 } else { 382 // get state of hardware lock 383 bool hardwareLocked = tryLock(mHardwareLock); 384 if (!hardwareLocked) { 385 String8 result(kHardwareLockedString); 386 write(fd, result.string(), result.size()); 387 } else { 388 mHardwareLock.unlock(); 389 } 390 391 bool locked = tryLock(mLock); 392 393 // failed to lock - AudioFlinger is probably deadlocked 394 if (!locked) { 395 String8 result(kDeadlockedString); 396 write(fd, result.string(), result.size()); 397 } 398 399 dumpClients(fd, args); 400 dumpInternals(fd, args); 401 402 // dump playback threads 403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 404 mPlaybackThreads.valueAt(i)->dump(fd, args); 405 } 406 407 // dump record threads 408 for (size_t i = 0; i < mRecordThreads.size(); i++) { 409 mRecordThreads.valueAt(i)->dump(fd, args); 410 } 411 412 // dump all hardware devs 413 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 414 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 415 dev->dump(dev, fd); 416 } 417 if (locked) mLock.unlock(); 418 } 419 return NO_ERROR; 420} 421 422sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid) 423{ 424 // If pid is already in the mClients wp<> map, then use that entry 425 // (for which promote() is always != 0), otherwise create a new entry and Client. 426 sp<Client> client = mClients.valueFor(pid).promote(); 427 if (client == 0) { 428 client = new Client(this, pid); 429 mClients.add(pid, client); 430 } 431 432 return client; 433} 434 435// IAudioFlinger interface 436 437 438sp<IAudioTrack> AudioFlinger::createTrack( 439 pid_t pid, 440 audio_stream_type_t streamType, 441 uint32_t sampleRate, 442 audio_format_t format, 443 uint32_t channelMask, 444 int frameCount, 445 IAudioFlinger::track_flags_t flags, 446 const sp<IMemory>& sharedBuffer, 447 audio_io_handle_t output, 448 pid_t tid, 449 int *sessionId, 450 status_t *status) 451{ 452 sp<PlaybackThread::Track> track; 453 sp<TrackHandle> trackHandle; 454 sp<Client> client; 455 status_t lStatus; 456 int lSessionId; 457 458 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 459 // but if someone uses binder directly they could bypass that and cause us to crash 460 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 461 ALOGE("createTrack() invalid stream type %d", streamType); 462 lStatus = BAD_VALUE; 463 goto Exit; 464 } 465 466 { 467 Mutex::Autolock _l(mLock); 468 PlaybackThread *thread = checkPlaybackThread_l(output); 469 PlaybackThread *effectThread = NULL; 470 if (thread == NULL) { 471 ALOGE("unknown output thread"); 472 lStatus = BAD_VALUE; 473 goto Exit; 474 } 475 476 client = registerPid_l(pid); 477 478 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 479 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 480 // check if an effect chain with the same session ID is present on another 481 // output thread and move it here. 482 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 483 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 484 if (mPlaybackThreads.keyAt(i) != output) { 485 uint32_t sessions = t->hasAudioSession(*sessionId); 486 if (sessions & PlaybackThread::EFFECT_SESSION) { 487 effectThread = t.get(); 488 break; 489 } 490 } 491 } 492 lSessionId = *sessionId; 493 } else { 494 // if no audio session id is provided, create one here 495 lSessionId = nextUniqueId(); 496 if (sessionId != NULL) { 497 *sessionId = lSessionId; 498 } 499 } 500 ALOGV("createTrack() lSessionId: %d", lSessionId); 501 502 track = thread->createTrack_l(client, streamType, sampleRate, format, 503 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus); 504 505 // move effect chain to this output thread if an effect on same session was waiting 506 // for a track to be created 507 if (lStatus == NO_ERROR && effectThread != NULL) { 508 Mutex::Autolock _dl(thread->mLock); 509 Mutex::Autolock _sl(effectThread->mLock); 510 moveEffectChain_l(lSessionId, effectThread, thread, true); 511 } 512 513 // Look for sync events awaiting for a session to be used. 514 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 515 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 516 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 517 if (lStatus == NO_ERROR) { 518 track->setSyncEvent(mPendingSyncEvents[i]); 519 } else { 520 mPendingSyncEvents[i]->cancel(); 521 } 522 mPendingSyncEvents.removeAt(i); 523 i--; 524 } 525 } 526 } 527 } 528 if (lStatus == NO_ERROR) { 529 trackHandle = new TrackHandle(track); 530 } else { 531 // remove local strong reference to Client before deleting the Track so that the Client 532 // destructor is called by the TrackBase destructor with mLock held 533 client.clear(); 534 track.clear(); 535 } 536 537Exit: 538 if (status != NULL) { 539 *status = lStatus; 540 } 541 return trackHandle; 542} 543 544uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 545{ 546 Mutex::Autolock _l(mLock); 547 PlaybackThread *thread = checkPlaybackThread_l(output); 548 if (thread == NULL) { 549 ALOGW("sampleRate() unknown thread %d", output); 550 return 0; 551 } 552 return thread->sampleRate(); 553} 554 555int AudioFlinger::channelCount(audio_io_handle_t output) const 556{ 557 Mutex::Autolock _l(mLock); 558 PlaybackThread *thread = checkPlaybackThread_l(output); 559 if (thread == NULL) { 560 ALOGW("channelCount() unknown thread %d", output); 561 return 0; 562 } 563 return thread->channelCount(); 564} 565 566audio_format_t AudioFlinger::format(audio_io_handle_t output) const 567{ 568 Mutex::Autolock _l(mLock); 569 PlaybackThread *thread = checkPlaybackThread_l(output); 570 if (thread == NULL) { 571 ALOGW("format() unknown thread %d", output); 572 return AUDIO_FORMAT_INVALID; 573 } 574 return thread->format(); 575} 576 577size_t AudioFlinger::frameCount(audio_io_handle_t output) const 578{ 579 Mutex::Autolock _l(mLock); 580 PlaybackThread *thread = checkPlaybackThread_l(output); 581 if (thread == NULL) { 582 ALOGW("frameCount() unknown thread %d", output); 583 return 0; 584 } 585 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 586 // should examine all callers and fix them to handle smaller counts 587 return thread->frameCount(); 588} 589 590uint32_t AudioFlinger::latency(audio_io_handle_t output) const 591{ 592 Mutex::Autolock _l(mLock); 593 PlaybackThread *thread = checkPlaybackThread_l(output); 594 if (thread == NULL) { 595 ALOGW("latency() unknown thread %d", output); 596 return 0; 597 } 598 return thread->latency(); 599} 600 601status_t AudioFlinger::setMasterVolume(float value) 602{ 603 status_t ret = initCheck(); 604 if (ret != NO_ERROR) { 605 return ret; 606 } 607 608 // check calling permissions 609 if (!settingsAllowed()) { 610 return PERMISSION_DENIED; 611 } 612 613 float swmv = value; 614 615 Mutex::Autolock _l(mLock); 616 617 // when hw supports master volume, don't scale in sw mixer 618 if (MVS_NONE != mMasterVolumeSupportLvl) { 619 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 620 AutoMutex lock(mHardwareLock); 621 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 622 623 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 624 if (NULL != dev->set_master_volume) { 625 dev->set_master_volume(dev, value); 626 } 627 mHardwareStatus = AUDIO_HW_IDLE; 628 } 629 630 swmv = 1.0; 631 } 632 633 mMasterVolume = value; 634 mMasterVolumeSW = swmv; 635 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 636 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv); 637 638 return NO_ERROR; 639} 640 641status_t AudioFlinger::setMode(audio_mode_t mode) 642{ 643 status_t ret = initCheck(); 644 if (ret != NO_ERROR) { 645 return ret; 646 } 647 648 // check calling permissions 649 if (!settingsAllowed()) { 650 return PERMISSION_DENIED; 651 } 652 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 653 ALOGW("Illegal value: setMode(%d)", mode); 654 return BAD_VALUE; 655 } 656 657 { // scope for the lock 658 AutoMutex lock(mHardwareLock); 659 mHardwareStatus = AUDIO_HW_SET_MODE; 660 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode); 661 mHardwareStatus = AUDIO_HW_IDLE; 662 } 663 664 if (NO_ERROR == ret) { 665 Mutex::Autolock _l(mLock); 666 mMode = mode; 667 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 668 mPlaybackThreads.valueAt(i)->setMode(mode); 669 } 670 671 return ret; 672} 673 674status_t AudioFlinger::setMicMute(bool state) 675{ 676 status_t ret = initCheck(); 677 if (ret != NO_ERROR) { 678 return ret; 679 } 680 681 // check calling permissions 682 if (!settingsAllowed()) { 683 return PERMISSION_DENIED; 684 } 685 686 AutoMutex lock(mHardwareLock); 687 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 688 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state); 689 mHardwareStatus = AUDIO_HW_IDLE; 690 return ret; 691} 692 693bool AudioFlinger::getMicMute() const 694{ 695 status_t ret = initCheck(); 696 if (ret != NO_ERROR) { 697 return false; 698 } 699 700 bool state = AUDIO_MODE_INVALID; 701 AutoMutex lock(mHardwareLock); 702 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 703 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state); 704 mHardwareStatus = AUDIO_HW_IDLE; 705 return state; 706} 707 708status_t AudioFlinger::setMasterMute(bool muted) 709{ 710 // check calling permissions 711 if (!settingsAllowed()) { 712 return PERMISSION_DENIED; 713 } 714 715 Mutex::Autolock _l(mLock); 716 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger 717 mMasterMute = muted; 718 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 719 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 720 721 return NO_ERROR; 722} 723 724float AudioFlinger::masterVolume() const 725{ 726 Mutex::Autolock _l(mLock); 727 return masterVolume_l(); 728} 729 730float AudioFlinger::masterVolumeSW() const 731{ 732 Mutex::Autolock _l(mLock); 733 return masterVolumeSW_l(); 734} 735 736bool AudioFlinger::masterMute() const 737{ 738 Mutex::Autolock _l(mLock); 739 return masterMute_l(); 740} 741 742float AudioFlinger::masterVolume_l() const 743{ 744 if (MVS_FULL == mMasterVolumeSupportLvl) { 745 float ret_val; 746 AutoMutex lock(mHardwareLock); 747 748 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 749 ALOG_ASSERT((NULL != mPrimaryHardwareDev) && 750 (NULL != mPrimaryHardwareDev->get_master_volume), 751 "can't get master volume"); 752 753 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val); 754 mHardwareStatus = AUDIO_HW_IDLE; 755 return ret_val; 756 } 757 758 return mMasterVolume; 759} 760 761status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 762 audio_io_handle_t output) 763{ 764 // check calling permissions 765 if (!settingsAllowed()) { 766 return PERMISSION_DENIED; 767 } 768 769 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 770 ALOGE("setStreamVolume() invalid stream %d", stream); 771 return BAD_VALUE; 772 } 773 774 AutoMutex lock(mLock); 775 PlaybackThread *thread = NULL; 776 if (output) { 777 thread = checkPlaybackThread_l(output); 778 if (thread == NULL) { 779 return BAD_VALUE; 780 } 781 } 782 783 mStreamTypes[stream].volume = value; 784 785 if (thread == NULL) { 786 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 787 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 788 } 789 } else { 790 thread->setStreamVolume(stream, value); 791 } 792 793 return NO_ERROR; 794} 795 796status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 797{ 798 // check calling permissions 799 if (!settingsAllowed()) { 800 return PERMISSION_DENIED; 801 } 802 803 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 804 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 805 ALOGE("setStreamMute() invalid stream %d", stream); 806 return BAD_VALUE; 807 } 808 809 AutoMutex lock(mLock); 810 mStreamTypes[stream].mute = muted; 811 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 812 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 813 814 return NO_ERROR; 815} 816 817float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 818{ 819 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 820 return 0.0f; 821 } 822 823 AutoMutex lock(mLock); 824 float volume; 825 if (output) { 826 PlaybackThread *thread = checkPlaybackThread_l(output); 827 if (thread == NULL) { 828 return 0.0f; 829 } 830 volume = thread->streamVolume(stream); 831 } else { 832 volume = streamVolume_l(stream); 833 } 834 835 return volume; 836} 837 838bool AudioFlinger::streamMute(audio_stream_type_t stream) const 839{ 840 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 841 return true; 842 } 843 844 AutoMutex lock(mLock); 845 return streamMute_l(stream); 846} 847 848status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 849{ 850 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d", 851 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid()); 852 // check calling permissions 853 if (!settingsAllowed()) { 854 return PERMISSION_DENIED; 855 } 856 857 // ioHandle == 0 means the parameters are global to the audio hardware interface 858 if (ioHandle == 0) { 859 Mutex::Autolock _l(mLock); 860 status_t final_result = NO_ERROR; 861 { 862 AutoMutex lock(mHardwareLock); 863 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 864 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 865 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 866 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 867 final_result = result ?: final_result; 868 } 869 mHardwareStatus = AUDIO_HW_IDLE; 870 } 871 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 872 AudioParameter param = AudioParameter(keyValuePairs); 873 String8 value; 874 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 875 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 876 if (mBtNrecIsOff != btNrecIsOff) { 877 for (size_t i = 0; i < mRecordThreads.size(); i++) { 878 sp<RecordThread> thread = mRecordThreads.valueAt(i); 879 RecordThread::RecordTrack *track = thread->track(); 880 if (track != NULL) { 881 audio_devices_t device = (audio_devices_t)( 882 thread->device() & AUDIO_DEVICE_IN_ALL); 883 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 884 thread->setEffectSuspended(FX_IID_AEC, 885 suspend, 886 track->sessionId()); 887 thread->setEffectSuspended(FX_IID_NS, 888 suspend, 889 track->sessionId()); 890 } 891 } 892 mBtNrecIsOff = btNrecIsOff; 893 } 894 } 895 String8 screenState; 896 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 897 bool isOff = screenState == "off"; 898 if (isOff != (gScreenState & 1)) { 899 gScreenState = ((gScreenState & ~1) + 2) | isOff; 900 } 901 } 902 return final_result; 903 } 904 905 // hold a strong ref on thread in case closeOutput() or closeInput() is called 906 // and the thread is exited once the lock is released 907 sp<ThreadBase> thread; 908 { 909 Mutex::Autolock _l(mLock); 910 thread = checkPlaybackThread_l(ioHandle); 911 if (thread == 0) { 912 thread = checkRecordThread_l(ioHandle); 913 } else if (thread == primaryPlaybackThread_l()) { 914 // indicate output device change to all input threads for pre processing 915 AudioParameter param = AudioParameter(keyValuePairs); 916 int value; 917 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 918 (value != 0)) { 919 for (size_t i = 0; i < mRecordThreads.size(); i++) { 920 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 921 } 922 } 923 } 924 } 925 if (thread != 0) { 926 return thread->setParameters(keyValuePairs); 927 } 928 return BAD_VALUE; 929} 930 931String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 932{ 933// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d", 934// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid()); 935 936 Mutex::Autolock _l(mLock); 937 938 if (ioHandle == 0) { 939 String8 out_s8; 940 941 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 942 char *s; 943 { 944 AutoMutex lock(mHardwareLock); 945 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 946 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 947 s = dev->get_parameters(dev, keys.string()); 948 mHardwareStatus = AUDIO_HW_IDLE; 949 } 950 out_s8 += String8(s ? s : ""); 951 free(s); 952 } 953 return out_s8; 954 } 955 956 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 957 if (playbackThread != NULL) { 958 return playbackThread->getParameters(keys); 959 } 960 RecordThread *recordThread = checkRecordThread_l(ioHandle); 961 if (recordThread != NULL) { 962 return recordThread->getParameters(keys); 963 } 964 return String8(""); 965} 966 967size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const 968{ 969 status_t ret = initCheck(); 970 if (ret != NO_ERROR) { 971 return 0; 972 } 973 974 AutoMutex lock(mHardwareLock); 975 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 976 struct audio_config config = { 977 sample_rate: sampleRate, 978 channel_mask: audio_channel_in_mask_from_count(channelCount), 979 format: format, 980 }; 981 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config); 982 mHardwareStatus = AUDIO_HW_IDLE; 983 return size; 984} 985 986unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 987{ 988 if (ioHandle == 0) { 989 return 0; 990 } 991 992 Mutex::Autolock _l(mLock); 993 994 RecordThread *recordThread = checkRecordThread_l(ioHandle); 995 if (recordThread != NULL) { 996 return recordThread->getInputFramesLost(); 997 } 998 return 0; 999} 1000 1001status_t AudioFlinger::setVoiceVolume(float value) 1002{ 1003 status_t ret = initCheck(); 1004 if (ret != NO_ERROR) { 1005 return ret; 1006 } 1007 1008 // check calling permissions 1009 if (!settingsAllowed()) { 1010 return PERMISSION_DENIED; 1011 } 1012 1013 AutoMutex lock(mHardwareLock); 1014 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1015 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value); 1016 mHardwareStatus = AUDIO_HW_IDLE; 1017 1018 return ret; 1019} 1020 1021status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 1022 audio_io_handle_t output) const 1023{ 1024 status_t status; 1025 1026 Mutex::Autolock _l(mLock); 1027 1028 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1029 if (playbackThread != NULL) { 1030 return playbackThread->getRenderPosition(halFrames, dspFrames); 1031 } 1032 1033 return BAD_VALUE; 1034} 1035 1036void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1037{ 1038 1039 Mutex::Autolock _l(mLock); 1040 1041 pid_t pid = IPCThreadState::self()->getCallingPid(); 1042 if (mNotificationClients.indexOfKey(pid) < 0) { 1043 sp<NotificationClient> notificationClient = new NotificationClient(this, 1044 client, 1045 pid); 1046 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1047 1048 mNotificationClients.add(pid, notificationClient); 1049 1050 sp<IBinder> binder = client->asBinder(); 1051 binder->linkToDeath(notificationClient); 1052 1053 // the config change is always sent from playback or record threads to avoid deadlock 1054 // with AudioSystem::gLock 1055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1056 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED); 1057 } 1058 1059 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1060 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED); 1061 } 1062 } 1063} 1064 1065void AudioFlinger::removeNotificationClient(pid_t pid) 1066{ 1067 Mutex::Autolock _l(mLock); 1068 1069 mNotificationClients.removeItem(pid); 1070 1071 ALOGV("%d died, releasing its sessions", pid); 1072 size_t num = mAudioSessionRefs.size(); 1073 bool removed = false; 1074 for (size_t i = 0; i< num; ) { 1075 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1076 ALOGV(" pid %d @ %d", ref->mPid, i); 1077 if (ref->mPid == pid) { 1078 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1079 mAudioSessionRefs.removeAt(i); 1080 delete ref; 1081 removed = true; 1082 num--; 1083 } else { 1084 i++; 1085 } 1086 } 1087 if (removed) { 1088 purgeStaleEffects_l(); 1089 } 1090} 1091 1092// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1093void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1094{ 1095 size_t size = mNotificationClients.size(); 1096 for (size_t i = 0; i < size; i++) { 1097 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1098 param2); 1099 } 1100} 1101 1102// removeClient_l() must be called with AudioFlinger::mLock held 1103void AudioFlinger::removeClient_l(pid_t pid) 1104{ 1105 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid()); 1106 mClients.removeItem(pid); 1107} 1108 1109// getEffectThread_l() must be called with AudioFlinger::mLock held 1110sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1111{ 1112 sp<PlaybackThread> thread; 1113 1114 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1115 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1116 ALOG_ASSERT(thread == 0); 1117 thread = mPlaybackThreads.valueAt(i); 1118 } 1119 } 1120 1121 return thread; 1122} 1123 1124// ---------------------------------------------------------------------------- 1125 1126AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 1127 uint32_t device, type_t type) 1128 : Thread(false), 1129 mType(type), 1130 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0), 1131 // mChannelMask 1132 mChannelCount(0), 1133 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), 1134 mParamStatus(NO_ERROR), 1135 mStandby(false), mId(id), 1136 mDevice(device), 1137 mDeathRecipient(new PMDeathRecipient(this)) 1138{ 1139} 1140 1141AudioFlinger::ThreadBase::~ThreadBase() 1142{ 1143 mParamCond.broadcast(); 1144 // do not lock the mutex in destructor 1145 releaseWakeLock_l(); 1146 if (mPowerManager != 0) { 1147 sp<IBinder> binder = mPowerManager->asBinder(); 1148 binder->unlinkToDeath(mDeathRecipient); 1149 } 1150} 1151 1152void AudioFlinger::ThreadBase::exit() 1153{ 1154 ALOGV("ThreadBase::exit"); 1155 { 1156 // This lock prevents the following race in thread (uniprocessor for illustration): 1157 // if (!exitPending()) { 1158 // // context switch from here to exit() 1159 // // exit() calls requestExit(), what exitPending() observes 1160 // // exit() calls signal(), which is dropped since no waiters 1161 // // context switch back from exit() to here 1162 // mWaitWorkCV.wait(...); 1163 // // now thread is hung 1164 // } 1165 AutoMutex lock(mLock); 1166 requestExit(); 1167 mWaitWorkCV.signal(); 1168 } 1169 // When Thread::requestExitAndWait is made virtual and this method is renamed to 1170 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 1171 requestExitAndWait(); 1172} 1173 1174status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 1175{ 1176 status_t status; 1177 1178 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 1179 Mutex::Autolock _l(mLock); 1180 1181 mNewParameters.add(keyValuePairs); 1182 mWaitWorkCV.signal(); 1183 // wait condition with timeout in case the thread loop has exited 1184 // before the request could be processed 1185 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { 1186 status = mParamStatus; 1187 mWaitWorkCV.signal(); 1188 } else { 1189 status = TIMED_OUT; 1190 } 1191 return status; 1192} 1193 1194void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param) 1195{ 1196 Mutex::Autolock _l(mLock); 1197 sendConfigEvent_l(event, param); 1198} 1199 1200// sendConfigEvent_l() must be called with ThreadBase::mLock held 1201void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param) 1202{ 1203 ConfigEvent configEvent; 1204 configEvent.mEvent = event; 1205 configEvent.mParam = param; 1206 mConfigEvents.add(configEvent); 1207 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param); 1208 mWaitWorkCV.signal(); 1209} 1210 1211void AudioFlinger::ThreadBase::processConfigEvents() 1212{ 1213 mLock.lock(); 1214 while (!mConfigEvents.isEmpty()) { 1215 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); 1216 ConfigEvent configEvent = mConfigEvents[0]; 1217 mConfigEvents.removeAt(0); 1218 // release mLock before locking AudioFlinger mLock: lock order is always 1219 // AudioFlinger then ThreadBase to avoid cross deadlock 1220 mLock.unlock(); 1221 mAudioFlinger->mLock.lock(); 1222 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam); 1223 mAudioFlinger->mLock.unlock(); 1224 mLock.lock(); 1225 } 1226 mLock.unlock(); 1227} 1228 1229status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) 1230{ 1231 const size_t SIZE = 256; 1232 char buffer[SIZE]; 1233 String8 result; 1234 1235 bool locked = tryLock(mLock); 1236 if (!locked) { 1237 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); 1238 write(fd, buffer, strlen(buffer)); 1239 } 1240 1241 snprintf(buffer, SIZE, "io handle: %d\n", mId); 1242 result.append(buffer); 1243 snprintf(buffer, SIZE, "TID: %d\n", getTid()); 1244 result.append(buffer); 1245 snprintf(buffer, SIZE, "standby: %d\n", mStandby); 1246 result.append(buffer); 1247 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate); 1248 result.append(buffer); 1249 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount); 1250 result.append(buffer); 1251 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount); 1252 result.append(buffer); 1253 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount); 1254 result.append(buffer); 1255 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); 1256 result.append(buffer); 1257 snprintf(buffer, SIZE, "Format: %d\n", mFormat); 1258 result.append(buffer); 1259 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); 1260 result.append(buffer); 1261 1262 snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); 1263 result.append(buffer); 1264 result.append(" Index Command"); 1265 for (size_t i = 0; i < mNewParameters.size(); ++i) { 1266 snprintf(buffer, SIZE, "\n %02d ", i); 1267 result.append(buffer); 1268 result.append(mNewParameters[i]); 1269 } 1270 1271 snprintf(buffer, SIZE, "\n\nPending config events: \n"); 1272 result.append(buffer); 1273 snprintf(buffer, SIZE, " Index event param\n"); 1274 result.append(buffer); 1275 for (size_t i = 0; i < mConfigEvents.size(); i++) { 1276 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam); 1277 result.append(buffer); 1278 } 1279 result.append("\n"); 1280 1281 write(fd, result.string(), result.size()); 1282 1283 if (locked) { 1284 mLock.unlock(); 1285 } 1286 return NO_ERROR; 1287} 1288 1289status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 1290{ 1291 const size_t SIZE = 256; 1292 char buffer[SIZE]; 1293 String8 result; 1294 1295 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); 1296 write(fd, buffer, strlen(buffer)); 1297 1298 for (size_t i = 0; i < mEffectChains.size(); ++i) { 1299 sp<EffectChain> chain = mEffectChains[i]; 1300 if (chain != 0) { 1301 chain->dump(fd, args); 1302 } 1303 } 1304 return NO_ERROR; 1305} 1306 1307void AudioFlinger::ThreadBase::acquireWakeLock() 1308{ 1309 Mutex::Autolock _l(mLock); 1310 acquireWakeLock_l(); 1311} 1312 1313void AudioFlinger::ThreadBase::acquireWakeLock_l() 1314{ 1315 if (mPowerManager == 0) { 1316 // use checkService() to avoid blocking if power service is not up yet 1317 sp<IBinder> binder = 1318 defaultServiceManager()->checkService(String16("power")); 1319 if (binder == 0) { 1320 ALOGW("Thread %s cannot connect to the power manager service", mName); 1321 } else { 1322 mPowerManager = interface_cast<IPowerManager>(binder); 1323 binder->linkToDeath(mDeathRecipient); 1324 } 1325 } 1326 if (mPowerManager != 0) { 1327 sp<IBinder> binder = new BBinder(); 1328 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 1329 binder, 1330 String16(mName)); 1331 if (status == NO_ERROR) { 1332 mWakeLockToken = binder; 1333 } 1334 ALOGV("acquireWakeLock_l() %s status %d", mName, status); 1335 } 1336} 1337 1338void AudioFlinger::ThreadBase::releaseWakeLock() 1339{ 1340 Mutex::Autolock _l(mLock); 1341 releaseWakeLock_l(); 1342} 1343 1344void AudioFlinger::ThreadBase::releaseWakeLock_l() 1345{ 1346 if (mWakeLockToken != 0) { 1347 ALOGV("releaseWakeLock_l() %s", mName); 1348 if (mPowerManager != 0) { 1349 mPowerManager->releaseWakeLock(mWakeLockToken, 0); 1350 } 1351 mWakeLockToken.clear(); 1352 } 1353} 1354 1355void AudioFlinger::ThreadBase::clearPowerManager() 1356{ 1357 Mutex::Autolock _l(mLock); 1358 releaseWakeLock_l(); 1359 mPowerManager.clear(); 1360} 1361 1362void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) 1363{ 1364 sp<ThreadBase> thread = mThread.promote(); 1365 if (thread != 0) { 1366 thread->clearPowerManager(); 1367 } 1368 ALOGW("power manager service died !!!"); 1369} 1370 1371void AudioFlinger::ThreadBase::setEffectSuspended( 1372 const effect_uuid_t *type, bool suspend, int sessionId) 1373{ 1374 Mutex::Autolock _l(mLock); 1375 setEffectSuspended_l(type, suspend, sessionId); 1376} 1377 1378void AudioFlinger::ThreadBase::setEffectSuspended_l( 1379 const effect_uuid_t *type, bool suspend, int sessionId) 1380{ 1381 sp<EffectChain> chain = getEffectChain_l(sessionId); 1382 if (chain != 0) { 1383 if (type != NULL) { 1384 chain->setEffectSuspended_l(type, suspend); 1385 } else { 1386 chain->setEffectSuspendedAll_l(suspend); 1387 } 1388 } 1389 1390 updateSuspendedSessions_l(type, suspend, sessionId); 1391} 1392 1393void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 1394{ 1395 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 1396 if (index < 0) { 1397 return; 1398 } 1399 1400 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects = 1401 mSuspendedSessions.editValueAt(index); 1402 1403 for (size_t i = 0; i < sessionEffects.size(); i++) { 1404 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i); 1405 for (int j = 0; j < desc->mRefCount; j++) { 1406 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 1407 chain->setEffectSuspendedAll_l(true); 1408 } else { 1409 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 1410 desc->mType.timeLow); 1411 chain->setEffectSuspended_l(&desc->mType, true); 1412 } 1413 } 1414 } 1415} 1416 1417void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 1418 bool suspend, 1419 int sessionId) 1420{ 1421 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 1422 1423 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 1424 1425 if (suspend) { 1426 if (index >= 0) { 1427 sessionEffects = mSuspendedSessions.editValueAt(index); 1428 } else { 1429 mSuspendedSessions.add(sessionId, sessionEffects); 1430 } 1431 } else { 1432 if (index < 0) { 1433 return; 1434 } 1435 sessionEffects = mSuspendedSessions.editValueAt(index); 1436 } 1437 1438 1439 int key = EffectChain::kKeyForSuspendAll; 1440 if (type != NULL) { 1441 key = type->timeLow; 1442 } 1443 index = sessionEffects.indexOfKey(key); 1444 1445 sp<SuspendedSessionDesc> desc; 1446 if (suspend) { 1447 if (index >= 0) { 1448 desc = sessionEffects.valueAt(index); 1449 } else { 1450 desc = new SuspendedSessionDesc(); 1451 if (type != NULL) { 1452 memcpy(&desc->mType, type, sizeof(effect_uuid_t)); 1453 } 1454 sessionEffects.add(key, desc); 1455 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 1456 } 1457 desc->mRefCount++; 1458 } else { 1459 if (index < 0) { 1460 return; 1461 } 1462 desc = sessionEffects.valueAt(index); 1463 if (--desc->mRefCount == 0) { 1464 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 1465 sessionEffects.removeItemsAt(index); 1466 if (sessionEffects.isEmpty()) { 1467 ALOGV("updateSuspendedSessions_l() restore removing session %d", 1468 sessionId); 1469 mSuspendedSessions.removeItem(sessionId); 1470 } 1471 } 1472 } 1473 if (!sessionEffects.isEmpty()) { 1474 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 1475 } 1476} 1477 1478void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1479 bool enabled, 1480 int sessionId) 1481{ 1482 Mutex::Autolock _l(mLock); 1483 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 1484} 1485 1486void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 1487 bool enabled, 1488 int sessionId) 1489{ 1490 if (mType != RECORD) { 1491 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 1492 // another session. This gives the priority to well behaved effect control panels 1493 // and applications not using global effects. 1494 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 1495 // global effects 1496 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 1497 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 1498 } 1499 } 1500 1501 sp<EffectChain> chain = getEffectChain_l(sessionId); 1502 if (chain != 0) { 1503 chain->checkSuspendOnEffectEnabled(effect, enabled); 1504 } 1505} 1506 1507// ---------------------------------------------------------------------------- 1508 1509AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1510 AudioStreamOut* output, 1511 audio_io_handle_t id, 1512 uint32_t device, 1513 type_t type) 1514 : ThreadBase(audioFlinger, id, device, type), 1515 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), 1516 // Assumes constructor is called by AudioFlinger with it's mLock held, 1517 // but it would be safer to explicitly pass initial masterMute as parameter 1518 mMasterMute(audioFlinger->masterMute_l()), 1519 // mStreamTypes[] initialized in constructor body 1520 mOutput(output), 1521 // Assumes constructor is called by AudioFlinger with it's mLock held, 1522 // but it would be safer to explicitly pass initial masterVolume as parameter 1523 mMasterVolume(audioFlinger->masterVolumeSW_l()), 1524 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 1525 mMixerStatus(MIXER_IDLE), 1526 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 1527 standbyDelay(AudioFlinger::mStandbyTimeInNsecs), 1528 mScreenState(gScreenState), 1529 // index 0 is reserved for normal mixer's submix 1530 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1) 1531{ 1532 snprintf(mName, kNameLength, "AudioOut_%X", id); 1533 1534 readOutputParameters(); 1535 1536 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 1537 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile 1538 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; 1539 stream = (audio_stream_type_t) (stream + 1)) { 1540 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 1541 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1542 } 1543 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, 1544 // because mAudioFlinger doesn't have one to copy from 1545} 1546 1547AudioFlinger::PlaybackThread::~PlaybackThread() 1548{ 1549 delete [] mMixBuffer; 1550} 1551 1552status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1553{ 1554 dumpInternals(fd, args); 1555 dumpTracks(fd, args); 1556 dumpEffectChains(fd, args); 1557 return NO_ERROR; 1558} 1559 1560status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) 1561{ 1562 const size_t SIZE = 256; 1563 char buffer[SIZE]; 1564 String8 result; 1565 1566 result.appendFormat("Output thread %p stream volumes in dB:\n ", this); 1567 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1568 const stream_type_t *st = &mStreamTypes[i]; 1569 if (i > 0) { 1570 result.appendFormat(", "); 1571 } 1572 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1573 if (st->mute) { 1574 result.append("M"); 1575 } 1576 } 1577 result.append("\n"); 1578 write(fd, result.string(), result.length()); 1579 result.clear(); 1580 1581 snprintf(buffer, SIZE, "Output thread %p tracks\n", this); 1582 result.append(buffer); 1583 Track::appendDumpHeader(result); 1584 for (size_t i = 0; i < mTracks.size(); ++i) { 1585 sp<Track> track = mTracks[i]; 1586 if (track != 0) { 1587 track->dump(buffer, SIZE); 1588 result.append(buffer); 1589 } 1590 } 1591 1592 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); 1593 result.append(buffer); 1594 Track::appendDumpHeader(result); 1595 for (size_t i = 0; i < mActiveTracks.size(); ++i) { 1596 sp<Track> track = mActiveTracks[i].promote(); 1597 if (track != 0) { 1598 track->dump(buffer, SIZE); 1599 result.append(buffer); 1600 } 1601 } 1602 write(fd, result.string(), result.size()); 1603 1604 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1605 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1606 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n", 1607 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1608 1609 return NO_ERROR; 1610} 1611 1612status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1613{ 1614 const size_t SIZE = 256; 1615 char buffer[SIZE]; 1616 String8 result; 1617 1618 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); 1619 result.append(buffer); 1620 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime)); 1621 result.append(buffer); 1622 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); 1623 result.append(buffer); 1624 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); 1625 result.append(buffer); 1626 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); 1627 result.append(buffer); 1628 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); 1629 result.append(buffer); 1630 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); 1631 result.append(buffer); 1632 write(fd, result.string(), result.size()); 1633 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask); 1634 1635 dumpBase(fd, args); 1636 1637 return NO_ERROR; 1638} 1639 1640// Thread virtuals 1641status_t AudioFlinger::PlaybackThread::readyToRun() 1642{ 1643 status_t status = initCheck(); 1644 if (status == NO_ERROR) { 1645 ALOGI("AudioFlinger's thread %p ready to run", this); 1646 } else { 1647 ALOGE("No working audio driver found."); 1648 } 1649 return status; 1650} 1651 1652void AudioFlinger::PlaybackThread::onFirstRef() 1653{ 1654 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1655} 1656 1657// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1658sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1659 const sp<AudioFlinger::Client>& client, 1660 audio_stream_type_t streamType, 1661 uint32_t sampleRate, 1662 audio_format_t format, 1663 uint32_t channelMask, 1664 int frameCount, 1665 const sp<IMemory>& sharedBuffer, 1666 int sessionId, 1667 IAudioFlinger::track_flags_t flags, 1668 pid_t tid, 1669 status_t *status) 1670{ 1671 sp<Track> track; 1672 status_t lStatus; 1673 1674 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0; 1675 1676 // client expresses a preference for FAST, but we get the final say 1677 if (flags & IAudioFlinger::TRACK_FAST) { 1678 if ( 1679 // not timed 1680 (!isTimed) && 1681 // either of these use cases: 1682 ( 1683 // use case 1: shared buffer with any frame count 1684 ( 1685 (sharedBuffer != 0) 1686 ) || 1687 // use case 2: callback handler and frame count is default or at least as large as HAL 1688 ( 1689 (tid != -1) && 1690 ((frameCount == 0) || 1691 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below 1692 ) 1693 ) && 1694 // PCM data 1695 audio_is_linear_pcm(format) && 1696 // mono or stereo 1697 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 1698 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 1699#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE 1700 // hardware sample rate 1701 (sampleRate == mSampleRate) && 1702#endif 1703 // normal mixer has an associated fast mixer 1704 hasFastMixer() && 1705 // there are sufficient fast track slots available 1706 (mFastTrackAvailMask != 0) 1707 // FIXME test that MixerThread for this fast track has a capable output HAL 1708 // FIXME add a permission test also? 1709 ) { 1710 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count 1711 if (frameCount == 0) { 1712 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed 1713 } 1714 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 1715 frameCount, mFrameCount); 1716 } else { 1717 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " 1718 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d " 1719 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1720 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, 1721 audio_is_linear_pcm(format), 1722 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1723 flags &= ~IAudioFlinger::TRACK_FAST; 1724 // For compatibility with AudioTrack calculation, buffer depth is forced 1725 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1726 // This is probably too conservative, but legacy application code may depend on it. 1727 // If you change this calculation, also review the start threshold which is related. 1728 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); 1729 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1730 if (minBufCount < 2) { 1731 minBufCount = 2; 1732 } 1733 int minFrameCount = mNormalFrameCount * minBufCount; 1734 if (frameCount < minFrameCount) { 1735 frameCount = minFrameCount; 1736 } 1737 } 1738 } 1739 1740 if (mType == DIRECT) { 1741 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { 1742 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1743 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \"" 1744 "for output %p with format %d", 1745 sampleRate, format, channelMask, mOutput, mFormat); 1746 lStatus = BAD_VALUE; 1747 goto Exit; 1748 } 1749 } 1750 } else { 1751 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 1752 if (sampleRate > mSampleRate*2) { 1753 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate); 1754 lStatus = BAD_VALUE; 1755 goto Exit; 1756 } 1757 } 1758 1759 lStatus = initCheck(); 1760 if (lStatus != NO_ERROR) { 1761 ALOGE("Audio driver not initialized."); 1762 goto Exit; 1763 } 1764 1765 { // scope for mLock 1766 Mutex::Autolock _l(mLock); 1767 1768 // all tracks in same audio session must share the same routing strategy otherwise 1769 // conflicts will happen when tracks are moved from one output to another by audio policy 1770 // manager 1771 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1772 for (size_t i = 0; i < mTracks.size(); ++i) { 1773 sp<Track> t = mTracks[i]; 1774 if (t != 0 && !t->isOutputTrack()) { 1775 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1776 if (sessionId == t->sessionId() && strategy != actual) { 1777 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1778 strategy, actual); 1779 lStatus = BAD_VALUE; 1780 goto Exit; 1781 } 1782 } 1783 } 1784 1785 if (!isTimed) { 1786 track = new Track(this, client, streamType, sampleRate, format, 1787 channelMask, frameCount, sharedBuffer, sessionId, flags); 1788 } else { 1789 track = TimedTrack::create(this, client, streamType, sampleRate, format, 1790 channelMask, frameCount, sharedBuffer, sessionId); 1791 } 1792 if (track == 0 || track->getCblk() == NULL || track->name() < 0) { 1793 lStatus = NO_MEMORY; 1794 goto Exit; 1795 } 1796 mTracks.add(track); 1797 1798 sp<EffectChain> chain = getEffectChain_l(sessionId); 1799 if (chain != 0) { 1800 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1801 track->setMainBuffer(chain->inBuffer()); 1802 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 1803 chain->incTrackCnt(); 1804 } 1805 } 1806 1807#ifdef HAVE_REQUEST_PRIORITY 1808 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 1809 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1810 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 1811 // so ask activity manager to do this on our behalf 1812 int err = requestPriority(callingPid, tid, 1); 1813 if (err != 0) { 1814 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 1815 1, callingPid, tid, err); 1816 } 1817 } 1818#endif 1819 1820 lStatus = NO_ERROR; 1821 1822Exit: 1823 if (status) { 1824 *status = lStatus; 1825 } 1826 return track; 1827} 1828 1829uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const 1830{ 1831 if (mFastMixer != NULL) { 1832 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 1833 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 1834 } 1835 return latency; 1836} 1837 1838uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const 1839{ 1840 return latency; 1841} 1842 1843uint32_t AudioFlinger::PlaybackThread::latency() const 1844{ 1845 Mutex::Autolock _l(mLock); 1846 return latency_l(); 1847} 1848uint32_t AudioFlinger::PlaybackThread::latency_l() const 1849{ 1850 if (initCheck() == NO_ERROR) { 1851 return correctLatency(mOutput->stream->get_latency(mOutput->stream)); 1852 } else { 1853 return 0; 1854 } 1855} 1856 1857void AudioFlinger::PlaybackThread::setMasterVolume(float value) 1858{ 1859 Mutex::Autolock _l(mLock); 1860 mMasterVolume = value; 1861} 1862 1863void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1864{ 1865 Mutex::Autolock _l(mLock); 1866 setMasterMute_l(muted); 1867} 1868 1869void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1870{ 1871 Mutex::Autolock _l(mLock); 1872 mStreamTypes[stream].volume = value; 1873} 1874 1875void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1876{ 1877 Mutex::Autolock _l(mLock); 1878 mStreamTypes[stream].mute = muted; 1879} 1880 1881float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1882{ 1883 Mutex::Autolock _l(mLock); 1884 return mStreamTypes[stream].volume; 1885} 1886 1887// addTrack_l() must be called with ThreadBase::mLock held 1888status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1889{ 1890 status_t status = ALREADY_EXISTS; 1891 1892 // set retry count for buffer fill 1893 track->mRetryCount = kMaxTrackStartupRetries; 1894 if (mActiveTracks.indexOf(track) < 0) { 1895 // the track is newly added, make sure it fills up all its 1896 // buffers before playing. This is to ensure the client will 1897 // effectively get the latency it requested. 1898 track->mFillingUpStatus = Track::FS_FILLING; 1899 track->mResetDone = false; 1900 track->mPresentationCompleteFrames = 0; 1901 mActiveTracks.add(track); 1902 if (track->mainBuffer() != mMixBuffer) { 1903 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1904 if (chain != 0) { 1905 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId()); 1906 chain->incActiveTrackCnt(); 1907 } 1908 } 1909 1910 status = NO_ERROR; 1911 } 1912 1913 ALOGV("mWaitWorkCV.broadcast"); 1914 mWaitWorkCV.broadcast(); 1915 1916 return status; 1917} 1918 1919// destroyTrack_l() must be called with ThreadBase::mLock held 1920void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 1921{ 1922 track->mState = TrackBase::TERMINATED; 1923 // active tracks are removed by threadLoop() 1924 if (mActiveTracks.indexOf(track) < 0) { 1925 removeTrack_l(track); 1926 } 1927} 1928 1929void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 1930{ 1931 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 1932 mTracks.remove(track); 1933 deleteTrackName_l(track->name()); 1934 // redundant as track is about to be destroyed, for dumpsys only 1935 track->mName = -1; 1936 if (track->isFastTrack()) { 1937 int index = track->mFastIndex; 1938 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks); 1939 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 1940 mFastTrackAvailMask |= 1 << index; 1941 // redundant as track is about to be destroyed, for dumpsys only 1942 track->mFastIndex = -1; 1943 } 1944 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1945 if (chain != 0) { 1946 chain->decTrackCnt(); 1947 } 1948} 1949 1950String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 1951{ 1952 String8 out_s8 = String8(""); 1953 char *s; 1954 1955 Mutex::Autolock _l(mLock); 1956 if (initCheck() != NO_ERROR) { 1957 return out_s8; 1958 } 1959 1960 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); 1961 out_s8 = String8(s); 1962 free(s); 1963 return out_s8; 1964} 1965 1966// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1967void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { 1968 AudioSystem::OutputDescriptor desc; 1969 void *param2 = NULL; 1970 1971 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param); 1972 1973 switch (event) { 1974 case AudioSystem::OUTPUT_OPENED: 1975 case AudioSystem::OUTPUT_CONFIG_CHANGED: 1976 desc.channels = mChannelMask; 1977 desc.samplingRate = mSampleRate; 1978 desc.format = mFormat; 1979 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t) 1980 desc.latency = latency(); 1981 param2 = &desc; 1982 break; 1983 1984 case AudioSystem::STREAM_CONFIG_CHANGED: 1985 param2 = ¶m; 1986 case AudioSystem::OUTPUT_CLOSED: 1987 default: 1988 break; 1989 } 1990 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 1991} 1992 1993void AudioFlinger::PlaybackThread::readOutputParameters() 1994{ 1995 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); 1996 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); 1997 mChannelCount = (uint16_t)popcount(mChannelMask); 1998 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); 1999 mFrameSize = audio_stream_frame_size(&mOutput->stream->common); 2000 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize; 2001 if (mFrameCount & 15) { 2002 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames", 2003 mFrameCount); 2004 } 2005 2006 // Calculate size of normal mix buffer relative to the HAL output buffer size 2007 double multiplier = 1.0; 2008 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) { 2009 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000; 2010 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000; 2011 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 2012 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 2013 maxNormalFrameCount = maxNormalFrameCount & ~15; 2014 if (maxNormalFrameCount < minNormalFrameCount) { 2015 maxNormalFrameCount = minNormalFrameCount; 2016 } 2017 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 2018 if (multiplier <= 1.0) { 2019 multiplier = 1.0; 2020 } else if (multiplier <= 2.0) { 2021 if (2 * mFrameCount <= maxNormalFrameCount) { 2022 multiplier = 2.0; 2023 } else { 2024 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 2025 } 2026 } else { 2027 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC 2028 // (it would be unusual for the normal mix buffer size to not be a multiple of fast 2029 // track, but we sometimes have to do this to satisfy the maximum frame count constraint) 2030 // FIXME this rounding up should not be done if no HAL SRC 2031 uint32_t truncMult = (uint32_t) multiplier; 2032 if ((truncMult & 1)) { 2033 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { 2034 ++truncMult; 2035 } 2036 } 2037 multiplier = (double) truncMult; 2038 } 2039 } 2040 mNormalFrameCount = multiplier * mFrameCount; 2041 // round up to nearest 16 frames to satisfy AudioMixer 2042 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 2043 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount); 2044 2045 delete[] mMixBuffer; 2046 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount]; 2047 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 2048 2049 // force reconfiguration of effect chains and engines to take new buffer size and audio 2050 // parameters into account 2051 // Note that mLock is not held when readOutputParameters() is called from the constructor 2052 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 2053 // matter. 2054 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 2055 Vector< sp<EffectChain> > effectChains = mEffectChains; 2056 for (size_t i = 0; i < effectChains.size(); i ++) { 2057 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 2058 } 2059} 2060 2061 2062status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 2063{ 2064 if (halFrames == NULL || dspFrames == NULL) { 2065 return BAD_VALUE; 2066 } 2067 Mutex::Autolock _l(mLock); 2068 if (initCheck() != NO_ERROR) { 2069 return INVALID_OPERATION; 2070 } 2071 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 2072 2073 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 2074} 2075 2076uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) 2077{ 2078 Mutex::Autolock _l(mLock); 2079 uint32_t result = 0; 2080 if (getEffectChain_l(sessionId) != 0) { 2081 result = EFFECT_SESSION; 2082 } 2083 2084 for (size_t i = 0; i < mTracks.size(); ++i) { 2085 sp<Track> track = mTracks[i]; 2086 if (sessionId == track->sessionId() && 2087 !(track->mCblk->flags & CBLK_INVALID_MSK)) { 2088 result |= TRACK_SESSION; 2089 break; 2090 } 2091 } 2092 2093 return result; 2094} 2095 2096uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 2097{ 2098 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2099 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2100 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2101 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2102 } 2103 for (size_t i = 0; i < mTracks.size(); i++) { 2104 sp<Track> track = mTracks[i]; 2105 if (sessionId == track->sessionId() && 2106 !(track->mCblk->flags & CBLK_INVALID_MSK)) { 2107 return AudioSystem::getStrategyForStream(track->streamType()); 2108 } 2109 } 2110 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2111} 2112 2113 2114AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2115{ 2116 Mutex::Autolock _l(mLock); 2117 return mOutput; 2118} 2119 2120AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2121{ 2122 Mutex::Autolock _l(mLock); 2123 AudioStreamOut *output = mOutput; 2124 mOutput = NULL; 2125 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2126 // must push a NULL and wait for ack 2127 mOutputSink.clear(); 2128 mPipeSink.clear(); 2129 mNormalSink.clear(); 2130 return output; 2131} 2132 2133// this method must always be called either with ThreadBase mLock held or inside the thread loop 2134audio_stream_t* AudioFlinger::PlaybackThread::stream() const 2135{ 2136 if (mOutput == NULL) { 2137 return NULL; 2138 } 2139 return &mOutput->stream->common; 2140} 2141 2142uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2143{ 2144 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2145} 2146 2147status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2148{ 2149 if (!isValidSyncEvent(event)) { 2150 return BAD_VALUE; 2151 } 2152 2153 Mutex::Autolock _l(mLock); 2154 2155 for (size_t i = 0; i < mTracks.size(); ++i) { 2156 sp<Track> track = mTracks[i]; 2157 if (event->triggerSession() == track->sessionId()) { 2158 track->setSyncEvent(event); 2159 return NO_ERROR; 2160 } 2161 } 2162 2163 return NAME_NOT_FOUND; 2164} 2165 2166bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) 2167{ 2168 switch (event->type()) { 2169 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE: 2170 return true; 2171 default: 2172 break; 2173 } 2174 return false; 2175} 2176 2177void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2178{ 2179 size_t count = tracksToRemove.size(); 2180 if (CC_UNLIKELY(count)) { 2181 for (size_t i = 0 ; i < count ; i++) { 2182 const sp<Track>& track = tracksToRemove.itemAt(i); 2183 if ((track->sharedBuffer() != 0) && 2184 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) { 2185 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 2186 } 2187 } 2188 } 2189 2190} 2191 2192// ---------------------------------------------------------------------------- 2193 2194AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2195 audio_io_handle_t id, uint32_t device, type_t type) 2196 : PlaybackThread(audioFlinger, output, id, device, type), 2197 // mAudioMixer below 2198#ifdef SOAKER 2199 mSoaker(NULL), 2200#endif 2201 // mFastMixer below 2202 mFastMixerFutex(0) 2203 // mOutputSink below 2204 // mPipeSink below 2205 // mNormalSink below 2206{ 2207 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type); 2208 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, " 2209 "mFrameCount=%d, mNormalFrameCount=%d", 2210 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2211 mNormalFrameCount); 2212 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2213 2214 // FIXME - Current mixer implementation only supports stereo output 2215 if (mChannelCount == 1) { 2216 ALOGE("Invalid audio hardware channel count"); 2217 } 2218 2219 // create an NBAIO sink for the HAL output stream, and negotiate 2220 mOutputSink = new AudioStreamOutSink(output->stream); 2221 size_t numCounterOffers = 0; 2222 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2223 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2224 ALOG_ASSERT(index == 0); 2225 2226 // initialize fast mixer depending on configuration 2227 bool initFastMixer; 2228 switch (kUseFastMixer) { 2229 case FastMixer_Never: 2230 initFastMixer = false; 2231 break; 2232 case FastMixer_Always: 2233 initFastMixer = true; 2234 break; 2235 case FastMixer_Static: 2236 case FastMixer_Dynamic: 2237 initFastMixer = mFrameCount < mNormalFrameCount; 2238 break; 2239 } 2240 if (initFastMixer) { 2241 2242 // create a MonoPipe to connect our submix to FastMixer 2243 NBAIO_Format format = mOutputSink->format(); 2244 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2245 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2246 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2247 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2248 const NBAIO_Format offers[1] = {format}; 2249 size_t numCounterOffers = 0; 2250 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2251 ALOG_ASSERT(index == 0); 2252 monoPipe->setAvgFrames((mScreenState & 1) ? 2253 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2254 mPipeSink = monoPipe; 2255 2256#ifdef TEE_SINK_FRAMES 2257 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2258 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format); 2259 numCounterOffers = 0; 2260 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2261 ALOG_ASSERT(index == 0); 2262 mTeeSink = teeSink; 2263 PipeReader *teeSource = new PipeReader(*teeSink); 2264 numCounterOffers = 0; 2265 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2266 ALOG_ASSERT(index == 0); 2267 mTeeSource = teeSource; 2268#endif 2269 2270#ifdef SOAKER 2271 // create a soaker as workaround for governor issues 2272 mSoaker = new Soaker(); 2273 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE 2274 mSoaker->run("Soaker", PRIORITY_LOWEST); 2275#endif 2276 2277 // create fast mixer and configure it initially with just one fast track for our submix 2278 mFastMixer = new FastMixer(); 2279 FastMixerStateQueue *sq = mFastMixer->sq(); 2280#ifdef STATE_QUEUE_DUMP 2281 sq->setObserverDump(&mStateQueueObserverDump); 2282 sq->setMutatorDump(&mStateQueueMutatorDump); 2283#endif 2284 FastMixerState *state = sq->begin(); 2285 FastTrack *fastTrack = &state->mFastTracks[0]; 2286 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2287 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2288 fastTrack->mVolumeProvider = NULL; 2289 fastTrack->mGeneration++; 2290 state->mFastTracksGen++; 2291 state->mTrackMask = 1; 2292 // fast mixer will use the HAL output sink 2293 state->mOutputSink = mOutputSink.get(); 2294 state->mOutputSinkGen++; 2295 state->mFrameCount = mFrameCount; 2296 state->mCommand = FastMixerState::COLD_IDLE; 2297 // already done in constructor initialization list 2298 //mFastMixerFutex = 0; 2299 state->mColdFutexAddr = &mFastMixerFutex; 2300 state->mColdGen++; 2301 state->mDumpState = &mFastMixerDumpState; 2302 state->mTeeSink = mTeeSink.get(); 2303 sq->end(); 2304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2305 2306 // start the fast mixer 2307 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2308#ifdef HAVE_REQUEST_PRIORITY 2309 pid_t tid = mFastMixer->getTid(); 2310 int err = requestPriority(getpid_cached, tid, 2); 2311 if (err != 0) { 2312 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2313 2, getpid_cached, tid, err); 2314 } 2315#endif 2316 2317#ifdef AUDIO_WATCHDOG 2318 // create and start the watchdog 2319 mAudioWatchdog = new AudioWatchdog(); 2320 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2321 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2322 tid = mAudioWatchdog->getTid(); 2323 err = requestPriority(getpid_cached, tid, 1); 2324 if (err != 0) { 2325 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2326 1, getpid_cached, tid, err); 2327 } 2328#endif 2329 2330 } else { 2331 mFastMixer = NULL; 2332 } 2333 2334 switch (kUseFastMixer) { 2335 case FastMixer_Never: 2336 case FastMixer_Dynamic: 2337 mNormalSink = mOutputSink; 2338 break; 2339 case FastMixer_Always: 2340 mNormalSink = mPipeSink; 2341 break; 2342 case FastMixer_Static: 2343 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2344 break; 2345 } 2346} 2347 2348AudioFlinger::MixerThread::~MixerThread() 2349{ 2350 if (mFastMixer != NULL) { 2351 FastMixerStateQueue *sq = mFastMixer->sq(); 2352 FastMixerState *state = sq->begin(); 2353 if (state->mCommand == FastMixerState::COLD_IDLE) { 2354 int32_t old = android_atomic_inc(&mFastMixerFutex); 2355 if (old == -1) { 2356 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2357 } 2358 } 2359 state->mCommand = FastMixerState::EXIT; 2360 sq->end(); 2361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2362 mFastMixer->join(); 2363 // Though the fast mixer thread has exited, it's state queue is still valid. 2364 // We'll use that extract the final state which contains one remaining fast track 2365 // corresponding to our sub-mix. 2366 state = sq->begin(); 2367 ALOG_ASSERT(state->mTrackMask == 1); 2368 FastTrack *fastTrack = &state->mFastTracks[0]; 2369 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2370 delete fastTrack->mBufferProvider; 2371 sq->end(false /*didModify*/); 2372 delete mFastMixer; 2373#ifdef SOAKER 2374 if (mSoaker != NULL) { 2375 mSoaker->requestExitAndWait(); 2376 } 2377 delete mSoaker; 2378#endif 2379 if (mAudioWatchdog != 0) { 2380 mAudioWatchdog->requestExit(); 2381 mAudioWatchdog->requestExitAndWait(); 2382 mAudioWatchdog.clear(); 2383 } 2384 } 2385 delete mAudioMixer; 2386} 2387 2388class CpuStats { 2389public: 2390 CpuStats(); 2391 void sample(const String8 &title); 2392#ifdef DEBUG_CPU_USAGE 2393private: 2394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 2395 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 2396 2397 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 2398 2399 int mCpuNum; // thread's current CPU number 2400 int mCpukHz; // frequency of thread's current CPU in kHz 2401#endif 2402}; 2403 2404CpuStats::CpuStats() 2405#ifdef DEBUG_CPU_USAGE 2406 : mCpuNum(-1), mCpukHz(-1) 2407#endif 2408{ 2409} 2410 2411void CpuStats::sample(const String8 &title) { 2412#ifdef DEBUG_CPU_USAGE 2413 // get current thread's delta CPU time in wall clock ns 2414 double wcNs; 2415 bool valid = mCpuUsage.sampleAndEnable(wcNs); 2416 2417 // record sample for wall clock statistics 2418 if (valid) { 2419 mWcStats.sample(wcNs); 2420 } 2421 2422 // get the current CPU number 2423 int cpuNum = sched_getcpu(); 2424 2425 // get the current CPU frequency in kHz 2426 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 2427 2428 // check if either CPU number or frequency changed 2429 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 2430 mCpuNum = cpuNum; 2431 mCpukHz = cpukHz; 2432 // ignore sample for purposes of cycles 2433 valid = false; 2434 } 2435 2436 // if no change in CPU number or frequency, then record sample for cycle statistics 2437 if (valid && mCpukHz > 0) { 2438 double cycles = wcNs * cpukHz * 0.000001; 2439 mHzStats.sample(cycles); 2440 } 2441 2442 unsigned n = mWcStats.n(); 2443 // mCpuUsage.elapsed() is expensive, so don't call it every loop 2444 if ((n & 127) == 1) { 2445 long long elapsed = mCpuUsage.elapsed(); 2446 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 2447 double perLoop = elapsed / (double) n; 2448 double perLoop100 = perLoop * 0.01; 2449 double perLoop1k = perLoop * 0.001; 2450 double mean = mWcStats.mean(); 2451 double stddev = mWcStats.stddev(); 2452 double minimum = mWcStats.minimum(); 2453 double maximum = mWcStats.maximum(); 2454 double meanCycles = mHzStats.mean(); 2455 double stddevCycles = mHzStats.stddev(); 2456 double minCycles = mHzStats.minimum(); 2457 double maxCycles = mHzStats.maximum(); 2458 mCpuUsage.resetElapsed(); 2459 mWcStats.reset(); 2460 mHzStats.reset(); 2461 ALOGD("CPU usage for %s over past %.1f secs\n" 2462 " (%u mixer loops at %.1f mean ms per loop):\n" 2463 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 2464 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 2465 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 2466 title.string(), 2467 elapsed * .000000001, n, perLoop * .000001, 2468 mean * .001, 2469 stddev * .001, 2470 minimum * .001, 2471 maximum * .001, 2472 mean / perLoop100, 2473 stddev / perLoop100, 2474 minimum / perLoop100, 2475 maximum / perLoop100, 2476 meanCycles / perLoop1k, 2477 stddevCycles / perLoop1k, 2478 minCycles / perLoop1k, 2479 maxCycles / perLoop1k); 2480 2481 } 2482 } 2483#endif 2484}; 2485 2486void AudioFlinger::PlaybackThread::checkSilentMode_l() 2487{ 2488 if (!mMasterMute) { 2489 char value[PROPERTY_VALUE_MAX]; 2490 if (property_get("ro.audio.silent", value, "0") > 0) { 2491 char *endptr; 2492 unsigned long ul = strtoul(value, &endptr, 0); 2493 if (*endptr == '\0' && ul != 0) { 2494 ALOGD("Silence is golden"); 2495 // The setprop command will not allow a property to be changed after 2496 // the first time it is set, so we don't have to worry about un-muting. 2497 setMasterMute_l(true); 2498 } 2499 } 2500 } 2501} 2502 2503bool AudioFlinger::PlaybackThread::threadLoop() 2504{ 2505 Vector< sp<Track> > tracksToRemove; 2506 2507 standbyTime = systemTime(); 2508 2509 // MIXER 2510 nsecs_t lastWarning = 0; 2511 2512 // DUPLICATING 2513 // FIXME could this be made local to while loop? 2514 writeFrames = 0; 2515 2516 cacheParameters_l(); 2517 sleepTime = idleSleepTime; 2518 2519if (mType == MIXER) { 2520 sleepTimeShift = 0; 2521} 2522 2523 CpuStats cpuStats; 2524 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2525 2526 acquireWakeLock(); 2527 2528 while (!exitPending()) 2529 { 2530 cpuStats.sample(myName); 2531 2532 Vector< sp<EffectChain> > effectChains; 2533 2534 processConfigEvents(); 2535 2536 { // scope for mLock 2537 2538 Mutex::Autolock _l(mLock); 2539 2540 if (checkForNewParameters_l()) { 2541 cacheParameters_l(); 2542 } 2543 2544 saveOutputTracks(); 2545 2546 // put audio hardware into standby after short delay 2547 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) || 2548 mSuspended > 0)) { 2549 if (!mStandby) { 2550 2551 threadLoop_standby(); 2552 2553 mStandby = true; 2554 mBytesWritten = 0; 2555 } 2556 2557 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2558 // we're about to wait, flush the binder command buffer 2559 IPCThreadState::self()->flushCommands(); 2560 2561 clearOutputTracks(); 2562 2563 if (exitPending()) break; 2564 2565 releaseWakeLock_l(); 2566 // wait until we have something to do... 2567 ALOGV("%s going to sleep", myName.string()); 2568 mWaitWorkCV.wait(mLock); 2569 ALOGV("%s waking up", myName.string()); 2570 acquireWakeLock_l(); 2571 2572 mMixerStatus = MIXER_IDLE; 2573 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2574 2575 checkSilentMode_l(); 2576 2577 standbyTime = systemTime() + standbyDelay; 2578 sleepTime = idleSleepTime; 2579 if (mType == MIXER) { 2580 sleepTimeShift = 0; 2581 } 2582 2583 continue; 2584 } 2585 } 2586 2587 // mMixerStatusIgnoringFastTracks is also updated internally 2588 mMixerStatus = prepareTracks_l(&tracksToRemove); 2589 2590 // prevent any changes in effect chain list and in each effect chain 2591 // during mixing and effect process as the audio buffers could be deleted 2592 // or modified if an effect is created or deleted 2593 lockEffectChains_l(effectChains); 2594 } 2595 2596 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) { 2597 threadLoop_mix(); 2598 } else { 2599 threadLoop_sleepTime(); 2600 } 2601 2602 if (mSuspended > 0) { 2603 sleepTime = suspendSleepTimeUs(); 2604 } 2605 2606 // only process effects if we're going to write 2607 if (sleepTime == 0) { 2608 for (size_t i = 0; i < effectChains.size(); i ++) { 2609 effectChains[i]->process_l(); 2610 } 2611 } 2612 2613 // enable changes in effect chain 2614 unlockEffectChains(effectChains); 2615 2616 // sleepTime == 0 means we must write to audio hardware 2617 if (sleepTime == 0) { 2618 2619 threadLoop_write(); 2620 2621if (mType == MIXER) { 2622 // write blocked detection 2623 nsecs_t now = systemTime(); 2624 nsecs_t delta = now - mLastWriteTime; 2625 if (!mStandby && delta > maxPeriod) { 2626 mNumDelayedWrites++; 2627 if ((now - lastWarning) > kWarningThrottleNs) { 2628#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) 2629 ScopedTrace st(ATRACE_TAG, "underrun"); 2630#endif 2631 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2632 ns2ms(delta), mNumDelayedWrites, this); 2633 lastWarning = now; 2634 } 2635 } 2636} 2637 2638 mStandby = false; 2639 } else { 2640 usleep(sleepTime); 2641 } 2642 2643 // Finally let go of removed track(s), without the lock held 2644 // since we can't guarantee the destructors won't acquire that 2645 // same lock. This will also mutate and push a new fast mixer state. 2646 threadLoop_removeTracks(tracksToRemove); 2647 tracksToRemove.clear(); 2648 2649 // FIXME I don't understand the need for this here; 2650 // it was in the original code but maybe the 2651 // assignment in saveOutputTracks() makes this unnecessary? 2652 clearOutputTracks(); 2653 2654 // Effect chains will be actually deleted here if they were removed from 2655 // mEffectChains list during mixing or effects processing 2656 effectChains.clear(); 2657 2658 // FIXME Note that the above .clear() is no longer necessary since effectChains 2659 // is now local to this block, but will keep it for now (at least until merge done). 2660 } 2661 2662if (mType == MIXER || mType == DIRECT) { 2663 // put output stream into standby mode 2664 if (!mStandby) { 2665 mOutput->stream->common.standby(&mOutput->stream->common); 2666 } 2667} 2668if (mType == DUPLICATING) { 2669 // for DuplicatingThread, standby mode is handled by the outputTracks 2670} 2671 2672 releaseWakeLock(); 2673 2674 ALOGV("Thread %p type %d exiting", this, mType); 2675 return false; 2676} 2677 2678void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2679{ 2680 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2681} 2682 2683void AudioFlinger::MixerThread::threadLoop_write() 2684{ 2685 // FIXME we should only do one push per cycle; confirm this is true 2686 // Start the fast mixer if it's not already running 2687 if (mFastMixer != NULL) { 2688 FastMixerStateQueue *sq = mFastMixer->sq(); 2689 FastMixerState *state = sq->begin(); 2690 if (state->mCommand != FastMixerState::MIX_WRITE && 2691 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2692 if (state->mCommand == FastMixerState::COLD_IDLE) { 2693 int32_t old = android_atomic_inc(&mFastMixerFutex); 2694 if (old == -1) { 2695 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2696 } 2697 if (mAudioWatchdog != 0) { 2698 mAudioWatchdog->resume(); 2699 } 2700 } 2701 state->mCommand = FastMixerState::MIX_WRITE; 2702 sq->end(); 2703 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2704 if (kUseFastMixer == FastMixer_Dynamic) { 2705 mNormalSink = mPipeSink; 2706 } 2707 } else { 2708 sq->end(false /*didModify*/); 2709 } 2710 } 2711 PlaybackThread::threadLoop_write(); 2712} 2713 2714// shared by MIXER and DIRECT, overridden by DUPLICATING 2715void AudioFlinger::PlaybackThread::threadLoop_write() 2716{ 2717 // FIXME rewrite to reduce number of system calls 2718 mLastWriteTime = systemTime(); 2719 mInWrite = true; 2720 int bytesWritten; 2721 2722 // If an NBAIO sink is present, use it to write the normal mixer's submix 2723 if (mNormalSink != 0) { 2724#define mBitShift 2 // FIXME 2725 size_t count = mixBufferSize >> mBitShift; 2726#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) 2727 Tracer::traceBegin(ATRACE_TAG, "write"); 2728#endif 2729 // update the setpoint when gScreenState changes 2730 uint32_t screenState = gScreenState; 2731 if (screenState != mScreenState) { 2732 mScreenState = screenState; 2733 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2734 if (pipe != NULL) { 2735 pipe->setAvgFrames((mScreenState & 1) ? 2736 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2737 } 2738 } 2739 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count); 2740#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) 2741 Tracer::traceEnd(ATRACE_TAG); 2742#endif 2743 if (framesWritten > 0) { 2744 bytesWritten = framesWritten << mBitShift; 2745 } else { 2746 bytesWritten = framesWritten; 2747 } 2748 // otherwise use the HAL / AudioStreamOut directly 2749 } else { 2750 // Direct output thread. 2751 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize); 2752 } 2753 2754 if (bytesWritten > 0) mBytesWritten += mixBufferSize; 2755 mNumWrites++; 2756 mInWrite = false; 2757} 2758 2759void AudioFlinger::MixerThread::threadLoop_standby() 2760{ 2761 // Idle the fast mixer if it's currently running 2762 if (mFastMixer != NULL) { 2763 FastMixerStateQueue *sq = mFastMixer->sq(); 2764 FastMixerState *state = sq->begin(); 2765 if (!(state->mCommand & FastMixerState::IDLE)) { 2766 state->mCommand = FastMixerState::COLD_IDLE; 2767 state->mColdFutexAddr = &mFastMixerFutex; 2768 state->mColdGen++; 2769 mFastMixerFutex = 0; 2770 sq->end(); 2771 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2772 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2773 if (kUseFastMixer == FastMixer_Dynamic) { 2774 mNormalSink = mOutputSink; 2775 } 2776 if (mAudioWatchdog != 0) { 2777 mAudioWatchdog->pause(); 2778 } 2779 } else { 2780 sq->end(false /*didModify*/); 2781 } 2782 } 2783 PlaybackThread::threadLoop_standby(); 2784} 2785 2786// shared by MIXER and DIRECT, overridden by DUPLICATING 2787void AudioFlinger::PlaybackThread::threadLoop_standby() 2788{ 2789 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended); 2790 mOutput->stream->common.standby(&mOutput->stream->common); 2791} 2792 2793void AudioFlinger::MixerThread::threadLoop_mix() 2794{ 2795 // obtain the presentation timestamp of the next output buffer 2796 int64_t pts; 2797 status_t status = INVALID_OPERATION; 2798 2799 if (NULL != mOutput->stream->get_next_write_timestamp) { 2800 status = mOutput->stream->get_next_write_timestamp( 2801 mOutput->stream, &pts); 2802 } 2803 2804 if (status != NO_ERROR) { 2805 pts = AudioBufferProvider::kInvalidPTS; 2806 } 2807 2808 // mix buffers... 2809 mAudioMixer->process(pts); 2810 // increase sleep time progressively when application underrun condition clears. 2811 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2812 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2813 // such that we would underrun the audio HAL. 2814 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2815 sleepTimeShift--; 2816 } 2817 sleepTime = 0; 2818 standbyTime = systemTime() + standbyDelay; 2819 //TODO: delay standby when effects have a tail 2820} 2821 2822void AudioFlinger::MixerThread::threadLoop_sleepTime() 2823{ 2824 // If no tracks are ready, sleep once for the duration of an output 2825 // buffer size, then write 0s to the output 2826 if (sleepTime == 0) { 2827 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2828 sleepTime = activeSleepTime >> sleepTimeShift; 2829 if (sleepTime < kMinThreadSleepTimeUs) { 2830 sleepTime = kMinThreadSleepTimeUs; 2831 } 2832 // reduce sleep time in case of consecutive application underruns to avoid 2833 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2834 // duration we would end up writing less data than needed by the audio HAL if 2835 // the condition persists. 2836 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2837 sleepTimeShift++; 2838 } 2839 } else { 2840 sleepTime = idleSleepTime; 2841 } 2842 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2843 memset (mMixBuffer, 0, mixBufferSize); 2844 sleepTime = 0; 2845 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start"); 2846 } 2847 // TODO add standby time extension fct of effect tail 2848} 2849 2850// prepareTracks_l() must be called with ThreadBase::mLock held 2851AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2852 Vector< sp<Track> > *tracksToRemove) 2853{ 2854 2855 mixer_state mixerStatus = MIXER_IDLE; 2856 // find out which tracks need to be processed 2857 size_t count = mActiveTracks.size(); 2858 size_t mixedTracks = 0; 2859 size_t tracksWithEffect = 0; 2860 // counts only _active_ fast tracks 2861 size_t fastTracks = 0; 2862 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2863 2864 float masterVolume = mMasterVolume; 2865 bool masterMute = mMasterMute; 2866 2867 if (masterMute) { 2868 masterVolume = 0; 2869 } 2870 // Delegate master volume control to effect in output mix effect chain if needed 2871 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2872 if (chain != 0) { 2873 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2874 chain->setVolume_l(&v, &v); 2875 masterVolume = (float)((v + (1 << 23)) >> 24); 2876 chain.clear(); 2877 } 2878 2879 // prepare a new state to push 2880 FastMixerStateQueue *sq = NULL; 2881 FastMixerState *state = NULL; 2882 bool didModify = false; 2883 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2884 if (mFastMixer != NULL) { 2885 sq = mFastMixer->sq(); 2886 state = sq->begin(); 2887 } 2888 2889 for (size_t i=0 ; i<count ; i++) { 2890 sp<Track> t = mActiveTracks[i].promote(); 2891 if (t == 0) continue; 2892 2893 // this const just means the local variable doesn't change 2894 Track* const track = t.get(); 2895 2896 // process fast tracks 2897 if (track->isFastTrack()) { 2898 2899 // It's theoretically possible (though unlikely) for a fast track to be created 2900 // and then removed within the same normal mix cycle. This is not a problem, as 2901 // the track never becomes active so it's fast mixer slot is never touched. 2902 // The converse, of removing an (active) track and then creating a new track 2903 // at the identical fast mixer slot within the same normal mix cycle, 2904 // is impossible because the slot isn't marked available until the end of each cycle. 2905 int j = track->mFastIndex; 2906 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2907 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2908 FastTrack *fastTrack = &state->mFastTracks[j]; 2909 2910 // Determine whether the track is currently in underrun condition, 2911 // and whether it had a recent underrun. 2912 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2913 FastTrackUnderruns underruns = ftDump->mUnderruns; 2914 uint32_t recentFull = (underruns.mBitFields.mFull - 2915 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2916 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2917 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2918 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2919 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2920 uint32_t recentUnderruns = recentPartial + recentEmpty; 2921 track->mObservedUnderruns = underruns; 2922 // don't count underruns that occur while stopping or pausing 2923 // or stopped which can occur when flush() is called while active 2924 if (!(track->isStopping() || track->isPausing() || track->isStopped())) { 2925 track->mUnderrunCount += recentUnderruns; 2926 } 2927 2928 // This is similar to the state machine for normal tracks, 2929 // with a few modifications for fast tracks. 2930 bool isActive = true; 2931 switch (track->mState) { 2932 case TrackBase::STOPPING_1: 2933 // track stays active in STOPPING_1 state until first underrun 2934 if (recentUnderruns > 0) { 2935 track->mState = TrackBase::STOPPING_2; 2936 } 2937 break; 2938 case TrackBase::PAUSING: 2939 // ramp down is not yet implemented 2940 track->setPaused(); 2941 break; 2942 case TrackBase::RESUMING: 2943 // ramp up is not yet implemented 2944 track->mState = TrackBase::ACTIVE; 2945 break; 2946 case TrackBase::ACTIVE: 2947 if (recentFull > 0 || recentPartial > 0) { 2948 // track has provided at least some frames recently: reset retry count 2949 track->mRetryCount = kMaxTrackRetries; 2950 } 2951 if (recentUnderruns == 0) { 2952 // no recent underruns: stay active 2953 break; 2954 } 2955 // there has recently been an underrun of some kind 2956 if (track->sharedBuffer() == 0) { 2957 // were any of the recent underruns "empty" (no frames available)? 2958 if (recentEmpty == 0) { 2959 // no, then ignore the partial underruns as they are allowed indefinitely 2960 break; 2961 } 2962 // there has recently been an "empty" underrun: decrement the retry counter 2963 if (--(track->mRetryCount) > 0) { 2964 break; 2965 } 2966 // indicate to client process that the track was disabled because of underrun; 2967 // it will then automatically call start() when data is available 2968 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags); 2969 // remove from active list, but state remains ACTIVE [confusing but true] 2970 isActive = false; 2971 break; 2972 } 2973 // fall through 2974 case TrackBase::STOPPING_2: 2975 case TrackBase::PAUSED: 2976 case TrackBase::TERMINATED: 2977 case TrackBase::STOPPED: 2978 case TrackBase::FLUSHED: // flush() while active 2979 // Check for presentation complete if track is inactive 2980 // We have consumed all the buffers of this track. 2981 // This would be incomplete if we auto-paused on underrun 2982 { 2983 size_t audioHALFrames = 2984 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 2985 size_t framesWritten = 2986 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 2987 if (!track->presentationComplete(framesWritten, audioHALFrames)) { 2988 // track stays in active list until presentation is complete 2989 break; 2990 } 2991 } 2992 if (track->isStopping_2()) { 2993 track->mState = TrackBase::STOPPED; 2994 } 2995 if (track->isStopped()) { 2996 // Can't reset directly, as fast mixer is still polling this track 2997 // track->reset(); 2998 // So instead mark this track as needing to be reset after push with ack 2999 resetMask |= 1 << i; 3000 } 3001 isActive = false; 3002 break; 3003 case TrackBase::IDLE: 3004 default: 3005 LOG_FATAL("unexpected track state %d", track->mState); 3006 } 3007 3008 if (isActive) { 3009 // was it previously inactive? 3010 if (!(state->mTrackMask & (1 << j))) { 3011 ExtendedAudioBufferProvider *eabp = track; 3012 VolumeProvider *vp = track; 3013 fastTrack->mBufferProvider = eabp; 3014 fastTrack->mVolumeProvider = vp; 3015 fastTrack->mSampleRate = track->mSampleRate; 3016 fastTrack->mChannelMask = track->mChannelMask; 3017 fastTrack->mGeneration++; 3018 state->mTrackMask |= 1 << j; 3019 didModify = true; 3020 // no acknowledgement required for newly active tracks 3021 } 3022 // cache the combined master volume and stream type volume for fast mixer; this 3023 // lacks any synchronization or barrier so VolumeProvider may read a stale value 3024 track->mCachedVolume = track->isMuted() ? 3025 0 : masterVolume * mStreamTypes[track->streamType()].volume; 3026 ++fastTracks; 3027 } else { 3028 // was it previously active? 3029 if (state->mTrackMask & (1 << j)) { 3030 fastTrack->mBufferProvider = NULL; 3031 fastTrack->mGeneration++; 3032 state->mTrackMask &= ~(1 << j); 3033 didModify = true; 3034 // If any fast tracks were removed, we must wait for acknowledgement 3035 // because we're about to decrement the last sp<> on those tracks. 3036 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3037 } else { 3038 LOG_FATAL("fast track %d should have been active", j); 3039 } 3040 tracksToRemove->add(track); 3041 // Avoids a misleading display in dumpsys 3042 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 3043 } 3044 continue; 3045 } 3046 3047 { // local variable scope to avoid goto warning 3048 3049 audio_track_cblk_t* cblk = track->cblk(); 3050 3051 // The first time a track is added we wait 3052 // for all its buffers to be filled before processing it 3053 int name = track->name(); 3054 // make sure that we have enough frames to mix one full buffer. 3055 // enforce this condition only once to enable draining the buffer in case the client 3056 // app does not call stop() and relies on underrun to stop: 3057 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 3058 // during last round 3059 uint32_t minFrames = 1; 3060 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 3061 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 3062 if (t->sampleRate() == (int)mSampleRate) { 3063 minFrames = mNormalFrameCount; 3064 } else { 3065 // +1 for rounding and +1 for additional sample needed for interpolation 3066 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1; 3067 // add frames already consumed but not yet released by the resampler 3068 // because cblk->framesReady() will include these frames 3069 minFrames += mAudioMixer->getUnreleasedFrames(track->name()); 3070 // the minimum track buffer size is normally twice the number of frames necessary 3071 // to fill one buffer and the resampler should not leave more than one buffer worth 3072 // of unreleased frames after each pass, but just in case... 3073 ALOG_ASSERT(minFrames <= cblk->frameCount); 3074 } 3075 } 3076 if ((track->framesReady() >= minFrames) && track->isReady() && 3077 !track->isPaused() && !track->isTerminated()) 3078 { 3079 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this); 3080 3081 mixedTracks++; 3082 3083 // track->mainBuffer() != mMixBuffer means there is an effect chain 3084 // connected to the track 3085 chain.clear(); 3086 if (track->mainBuffer() != mMixBuffer) { 3087 chain = getEffectChain_l(track->sessionId()); 3088 // Delegate volume control to effect in track effect chain if needed 3089 if (chain != 0) { 3090 tracksWithEffect++; 3091 } else { 3092 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d", 3093 name, track->sessionId()); 3094 } 3095 } 3096 3097 3098 int param = AudioMixer::VOLUME; 3099 if (track->mFillingUpStatus == Track::FS_FILLED) { 3100 // no ramp for the first volume setting 3101 track->mFillingUpStatus = Track::FS_ACTIVE; 3102 if (track->mState == TrackBase::RESUMING) { 3103 track->mState = TrackBase::ACTIVE; 3104 param = AudioMixer::RAMP_VOLUME; 3105 } 3106 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3107 } else if (cblk->server != 0) { 3108 // If the track is stopped before the first frame was mixed, 3109 // do not apply ramp 3110 param = AudioMixer::RAMP_VOLUME; 3111 } 3112 3113 // compute volume for this track 3114 uint32_t vl, vr, va; 3115 if (track->isMuted() || track->isPausing() || 3116 mStreamTypes[track->streamType()].mute) { 3117 vl = vr = va = 0; 3118 if (track->isPausing()) { 3119 track->setPaused(); 3120 } 3121 } else { 3122 3123 // read original volumes with volume control 3124 float typeVolume = mStreamTypes[track->streamType()].volume; 3125 float v = masterVolume * typeVolume; 3126 uint32_t vlr = cblk->getVolumeLR(); 3127 vl = vlr & 0xFFFF; 3128 vr = vlr >> 16; 3129 // track volumes come from shared memory, so can't be trusted and must be clamped 3130 if (vl > MAX_GAIN_INT) { 3131 ALOGV("Track left volume out of range: %04X", vl); 3132 vl = MAX_GAIN_INT; 3133 } 3134 if (vr > MAX_GAIN_INT) { 3135 ALOGV("Track right volume out of range: %04X", vr); 3136 vr = MAX_GAIN_INT; 3137 } 3138 // now apply the master volume and stream type volume 3139 vl = (uint32_t)(v * vl) << 12; 3140 vr = (uint32_t)(v * vr) << 12; 3141 // assuming master volume and stream type volume each go up to 1.0, 3142 // vl and vr are now in 8.24 format 3143 3144 uint16_t sendLevel = cblk->getSendLevel_U4_12(); 3145 // send level comes from shared memory and so may be corrupt 3146 if (sendLevel > MAX_GAIN_INT) { 3147 ALOGV("Track send level out of range: %04X", sendLevel); 3148 sendLevel = MAX_GAIN_INT; 3149 } 3150 va = (uint32_t)(v * sendLevel); 3151 } 3152 // Delegate volume control to effect in track effect chain if needed 3153 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3154 // Do not ramp volume if volume is controlled by effect 3155 param = AudioMixer::VOLUME; 3156 track->mHasVolumeController = true; 3157 } else { 3158 // force no volume ramp when volume controller was just disabled or removed 3159 // from effect chain to avoid volume spike 3160 if (track->mHasVolumeController) { 3161 param = AudioMixer::VOLUME; 3162 } 3163 track->mHasVolumeController = false; 3164 } 3165 3166 // Convert volumes from 8.24 to 4.12 format 3167 // This additional clamping is needed in case chain->setVolume_l() overshot 3168 vl = (vl + (1 << 11)) >> 12; 3169 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT; 3170 vr = (vr + (1 << 11)) >> 12; 3171 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT; 3172 3173 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3174 3175 // XXX: these things DON'T need to be done each time 3176 mAudioMixer->setBufferProvider(name, track); 3177 mAudioMixer->enable(name); 3178 3179 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3180 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3181 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3182 mAudioMixer->setParameter( 3183 name, 3184 AudioMixer::TRACK, 3185 AudioMixer::FORMAT, (void *)track->format()); 3186 mAudioMixer->setParameter( 3187 name, 3188 AudioMixer::TRACK, 3189 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3190 mAudioMixer->setParameter( 3191 name, 3192 AudioMixer::RESAMPLE, 3193 AudioMixer::SAMPLE_RATE, 3194 (void *)(cblk->sampleRate)); 3195 mAudioMixer->setParameter( 3196 name, 3197 AudioMixer::TRACK, 3198 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3199 mAudioMixer->setParameter( 3200 name, 3201 AudioMixer::TRACK, 3202 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3203 3204 // reset retry count 3205 track->mRetryCount = kMaxTrackRetries; 3206 3207 // If one track is ready, set the mixer ready if: 3208 // - the mixer was not ready during previous round OR 3209 // - no other track is not ready 3210 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3211 mixerStatus != MIXER_TRACKS_ENABLED) { 3212 mixerStatus = MIXER_TRACKS_READY; 3213 } 3214 } else { 3215 // clear effect chain input buffer if an active track underruns to avoid sending 3216 // previous audio buffer again to effects 3217 chain = getEffectChain_l(track->sessionId()); 3218 if (chain != 0) { 3219 chain->clearInputBuffer(); 3220 } 3221 3222 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this); 3223 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3224 track->isStopped() || track->isPaused()) { 3225 // We have consumed all the buffers of this track. 3226 // Remove it from the list of active tracks. 3227 // TODO: use actual buffer filling status instead of latency when available from 3228 // audio HAL 3229 size_t audioHALFrames = 3230 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3231 size_t framesWritten = 3232 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 3233 if (track->presentationComplete(framesWritten, audioHALFrames)) { 3234 if (track->isStopped()) { 3235 track->reset(); 3236 } 3237 tracksToRemove->add(track); 3238 } 3239 } else { 3240 track->mUnderrunCount++; 3241 // No buffers for this track. Give it a few chances to 3242 // fill a buffer, then remove it from active list. 3243 if (--(track->mRetryCount) <= 0) { 3244 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3245 tracksToRemove->add(track); 3246 // indicate to client process that the track was disabled because of underrun; 3247 // it will then automatically call start() when data is available 3248 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags); 3249 // If one track is not ready, mark the mixer also not ready if: 3250 // - the mixer was ready during previous round OR 3251 // - no other track is ready 3252 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3253 mixerStatus != MIXER_TRACKS_READY) { 3254 mixerStatus = MIXER_TRACKS_ENABLED; 3255 } 3256 } 3257 mAudioMixer->disable(name); 3258 } 3259 3260 } // local variable scope to avoid goto warning 3261track_is_ready: ; 3262 3263 } 3264 3265 // Push the new FastMixer state if necessary 3266 bool pauseAudioWatchdog = false; 3267 if (didModify) { 3268 state->mFastTracksGen++; 3269 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3270 if (kUseFastMixer == FastMixer_Dynamic && 3271 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3272 state->mCommand = FastMixerState::COLD_IDLE; 3273 state->mColdFutexAddr = &mFastMixerFutex; 3274 state->mColdGen++; 3275 mFastMixerFutex = 0; 3276 if (kUseFastMixer == FastMixer_Dynamic) { 3277 mNormalSink = mOutputSink; 3278 } 3279 // If we go into cold idle, need to wait for acknowledgement 3280 // so that fast mixer stops doing I/O. 3281 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3282 pauseAudioWatchdog = true; 3283 } 3284 sq->end(); 3285 } 3286 if (sq != NULL) { 3287 sq->end(didModify); 3288 sq->push(block); 3289 } 3290 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3291 mAudioWatchdog->pause(); 3292 } 3293 3294 // Now perform the deferred reset on fast tracks that have stopped 3295 while (resetMask != 0) { 3296 size_t i = __builtin_ctz(resetMask); 3297 ALOG_ASSERT(i < count); 3298 resetMask &= ~(1 << i); 3299 sp<Track> t = mActiveTracks[i].promote(); 3300 if (t == 0) continue; 3301 Track* track = t.get(); 3302 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3303 track->reset(); 3304 } 3305 3306 // remove all the tracks that need to be... 3307 count = tracksToRemove->size(); 3308 if (CC_UNLIKELY(count)) { 3309 for (size_t i=0 ; i<count ; i++) { 3310 const sp<Track>& track = tracksToRemove->itemAt(i); 3311 mActiveTracks.remove(track); 3312 if (track->mainBuffer() != mMixBuffer) { 3313 chain = getEffectChain_l(track->sessionId()); 3314 if (chain != 0) { 3315 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId()); 3316 chain->decActiveTrackCnt(); 3317 } 3318 } 3319 if (track->isTerminated()) { 3320 removeTrack_l(track); 3321 } 3322 } 3323 } 3324 3325 // mix buffer must be cleared if all tracks are connected to an 3326 // effect chain as in this case the mixer will not write to 3327 // mix buffer and track effects will accumulate into it 3328 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) { 3329 // FIXME as a performance optimization, should remember previous zero status 3330 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3331 } 3332 3333 // if any fast tracks, then status is ready 3334 mMixerStatusIgnoringFastTracks = mixerStatus; 3335 if (fastTracks > 0) { 3336 mixerStatus = MIXER_TRACKS_READY; 3337 } 3338 return mixerStatus; 3339} 3340 3341/* 3342The derived values that are cached: 3343 - mixBufferSize from frame count * frame size 3344 - activeSleepTime from activeSleepTimeUs() 3345 - idleSleepTime from idleSleepTimeUs() 3346 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 3347 - maxPeriod from frame count and sample rate (MIXER only) 3348 3349The parameters that affect these derived values are: 3350 - frame count 3351 - frame size 3352 - sample rate 3353 - device type: A2DP or not 3354 - device latency 3355 - format: PCM or not 3356 - active sleep time 3357 - idle sleep time 3358*/ 3359 3360void AudioFlinger::PlaybackThread::cacheParameters_l() 3361{ 3362 mixBufferSize = mNormalFrameCount * mFrameSize; 3363 activeSleepTime = activeSleepTimeUs(); 3364 idleSleepTime = idleSleepTimeUs(); 3365} 3366 3367void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 3368{ 3369 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 3370 this, streamType, mTracks.size()); 3371 Mutex::Autolock _l(mLock); 3372 3373 size_t size = mTracks.size(); 3374 for (size_t i = 0; i < size; i++) { 3375 sp<Track> t = mTracks[i]; 3376 if (t->streamType() == streamType) { 3377 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags); 3378 t->mCblk->cv.signal(); 3379 } 3380 } 3381} 3382 3383// getTrackName_l() must be called with ThreadBase::mLock held 3384int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask) 3385{ 3386 return mAudioMixer->getTrackName(channelMask); 3387} 3388 3389// deleteTrackName_l() must be called with ThreadBase::mLock held 3390void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3391{ 3392 ALOGV("remove track (%d) and delete from mixer", name); 3393 mAudioMixer->deleteTrackName(name); 3394} 3395 3396// checkForNewParameters_l() must be called with ThreadBase::mLock held 3397bool AudioFlinger::MixerThread::checkForNewParameters_l() 3398{ 3399 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3400 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3401 bool reconfig = false; 3402 3403 while (!mNewParameters.isEmpty()) { 3404 3405 if (mFastMixer != NULL) { 3406 FastMixerStateQueue *sq = mFastMixer->sq(); 3407 FastMixerState *state = sq->begin(); 3408 if (!(state->mCommand & FastMixerState::IDLE)) { 3409 previousCommand = state->mCommand; 3410 state->mCommand = FastMixerState::HOT_IDLE; 3411 sq->end(); 3412 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3413 } else { 3414 sq->end(false /*didModify*/); 3415 } 3416 } 3417 3418 status_t status = NO_ERROR; 3419 String8 keyValuePair = mNewParameters[0]; 3420 AudioParameter param = AudioParameter(keyValuePair); 3421 int value; 3422 3423 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3424 reconfig = true; 3425 } 3426 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3427 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3428 status = BAD_VALUE; 3429 } else { 3430 reconfig = true; 3431 } 3432 } 3433 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3434 if (value != AUDIO_CHANNEL_OUT_STEREO) { 3435 status = BAD_VALUE; 3436 } else { 3437 reconfig = true; 3438 } 3439 } 3440 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3441 // do not accept frame count changes if tracks are open as the track buffer 3442 // size depends on frame count and correct behavior would not be guaranteed 3443 // if frame count is changed after track creation 3444 if (!mTracks.isEmpty()) { 3445 status = INVALID_OPERATION; 3446 } else { 3447 reconfig = true; 3448 } 3449 } 3450 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3451#ifdef ADD_BATTERY_DATA 3452 // when changing the audio output device, call addBatteryData to notify 3453 // the change 3454 if ((int)mDevice != value) { 3455 uint32_t params = 0; 3456 // check whether speaker is on 3457 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3458 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3459 } 3460 3461 int deviceWithoutSpeaker 3462 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3463 // check if any other device (except speaker) is on 3464 if (value & deviceWithoutSpeaker ) { 3465 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3466 } 3467 3468 if (params != 0) { 3469 addBatteryData(params); 3470 } 3471 } 3472#endif 3473 3474 // forward device change to effects that have requested to be 3475 // aware of attached audio device. 3476 mDevice = (uint32_t)value; 3477 for (size_t i = 0; i < mEffectChains.size(); i++) { 3478 mEffectChains[i]->setDevice_l(mDevice); 3479 } 3480 } 3481 3482 if (status == NO_ERROR) { 3483 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3484 keyValuePair.string()); 3485 if (!mStandby && status == INVALID_OPERATION) { 3486 mOutput->stream->common.standby(&mOutput->stream->common); 3487 mStandby = true; 3488 mBytesWritten = 0; 3489 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3490 keyValuePair.string()); 3491 } 3492 if (status == NO_ERROR && reconfig) { 3493 delete mAudioMixer; 3494 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't) 3495 mAudioMixer = NULL; 3496 readOutputParameters(); 3497 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3498 for (size_t i = 0; i < mTracks.size() ; i++) { 3499 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask); 3500 if (name < 0) break; 3501 mTracks[i]->mName = name; 3502 // limit track sample rate to 2 x new output sample rate 3503 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) { 3504 mTracks[i]->mCblk->sampleRate = 2 * sampleRate(); 3505 } 3506 } 3507 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3508 } 3509 } 3510 3511 mNewParameters.removeAt(0); 3512 3513 mParamStatus = status; 3514 mParamCond.signal(); 3515 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3516 // already timed out waiting for the status and will never signal the condition. 3517 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3518 } 3519 3520 if (!(previousCommand & FastMixerState::IDLE)) { 3521 ALOG_ASSERT(mFastMixer != NULL); 3522 FastMixerStateQueue *sq = mFastMixer->sq(); 3523 FastMixerState *state = sq->begin(); 3524 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3525 state->mCommand = previousCommand; 3526 sq->end(); 3527 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3528 } 3529 3530 return reconfig; 3531} 3532 3533status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3534{ 3535 const size_t SIZE = 256; 3536 char buffer[SIZE]; 3537 String8 result; 3538 3539 PlaybackThread::dumpInternals(fd, args); 3540 3541 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 3542 result.append(buffer); 3543 write(fd, result.string(), result.size()); 3544 3545 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3546 FastMixerDumpState copy = mFastMixerDumpState; 3547 copy.dump(fd); 3548 3549#ifdef STATE_QUEUE_DUMP 3550 // Similar for state queue 3551 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3552 observerCopy.dump(fd); 3553 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3554 mutatorCopy.dump(fd); 3555#endif 3556 3557 // Write the tee output to a .wav file 3558 NBAIO_Source *teeSource = mTeeSource.get(); 3559 if (teeSource != NULL) { 3560 char teePath[64]; 3561 struct timeval tv; 3562 gettimeofday(&tv, NULL); 3563 struct tm tm; 3564 localtime_r(&tv.tv_sec, &tm); 3565 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm); 3566 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); 3567 if (teeFd >= 0) { 3568 char wavHeader[44]; 3569 memcpy(wavHeader, 3570 "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", 3571 sizeof(wavHeader)); 3572 NBAIO_Format format = teeSource->format(); 3573 unsigned channelCount = Format_channelCount(format); 3574 ALOG_ASSERT(channelCount <= FCC_2); 3575 unsigned sampleRate = Format_sampleRate(format); 3576 wavHeader[22] = channelCount; // number of channels 3577 wavHeader[24] = sampleRate; // sample rate 3578 wavHeader[25] = sampleRate >> 8; 3579 wavHeader[32] = channelCount * 2; // block alignment 3580 write(teeFd, wavHeader, sizeof(wavHeader)); 3581 size_t total = 0; 3582 bool firstRead = true; 3583 for (;;) { 3584#define TEE_SINK_READ 1024 3585 short buffer[TEE_SINK_READ * FCC_2]; 3586 size_t count = TEE_SINK_READ; 3587 ssize_t actual = teeSource->read(buffer, count); 3588 bool wasFirstRead = firstRead; 3589 firstRead = false; 3590 if (actual <= 0) { 3591 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 3592 continue; 3593 } 3594 break; 3595 } 3596 ALOG_ASSERT(actual <= count); 3597 write(teeFd, buffer, actual * channelCount * sizeof(short)); 3598 total += actual; 3599 } 3600 lseek(teeFd, (off_t) 4, SEEK_SET); 3601 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 3602 write(teeFd, &temp, sizeof(temp)); 3603 lseek(teeFd, (off_t) 40, SEEK_SET); 3604 temp = total * channelCount * sizeof(short); 3605 write(teeFd, &temp, sizeof(temp)); 3606 close(teeFd); 3607 fdprintf(fd, "FastMixer tee copied to %s\n", teePath); 3608 } else { 3609 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno)); 3610 } 3611 } 3612 3613 if (mAudioWatchdog != 0) { 3614 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3615 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3616 wdCopy.dump(fd); 3617 } 3618 3619 return NO_ERROR; 3620} 3621 3622uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3623{ 3624 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3625} 3626 3627uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3628{ 3629 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3630} 3631 3632void AudioFlinger::MixerThread::cacheParameters_l() 3633{ 3634 PlaybackThread::cacheParameters_l(); 3635 3636 // FIXME: Relaxed timing because of a certain device that can't meet latency 3637 // Should be reduced to 2x after the vendor fixes the driver issue 3638 // increase threshold again due to low power audio mode. The way this warning 3639 // threshold is calculated and its usefulness should be reconsidered anyway. 3640 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3641} 3642 3643// ---------------------------------------------------------------------------- 3644AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3645 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 3646 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3647 // mLeftVolFloat, mRightVolFloat 3648{ 3649} 3650 3651AudioFlinger::DirectOutputThread::~DirectOutputThread() 3652{ 3653} 3654 3655AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3656 Vector< sp<Track> > *tracksToRemove 3657) 3658{ 3659 sp<Track> trackToRemove; 3660 3661 mixer_state mixerStatus = MIXER_IDLE; 3662 3663 // find out which tracks need to be processed 3664 if (mActiveTracks.size() != 0) { 3665 sp<Track> t = mActiveTracks[0].promote(); 3666 // The track died recently 3667 if (t == 0) return MIXER_IDLE; 3668 3669 Track* const track = t.get(); 3670 audio_track_cblk_t* cblk = track->cblk(); 3671 3672 // The first time a track is added we wait 3673 // for all its buffers to be filled before processing it 3674 uint32_t minFrames; 3675 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3676 minFrames = mNormalFrameCount; 3677 } else { 3678 minFrames = 1; 3679 } 3680 if ((track->framesReady() >= minFrames) && track->isReady() && 3681 !track->isPaused() && !track->isTerminated()) 3682 { 3683 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server); 3684 3685 if (track->mFillingUpStatus == Track::FS_FILLED) { 3686 track->mFillingUpStatus = Track::FS_ACTIVE; 3687 mLeftVolFloat = mRightVolFloat = 0; 3688 if (track->mState == TrackBase::RESUMING) { 3689 track->mState = TrackBase::ACTIVE; 3690 } 3691 } 3692 3693 // compute volume for this track 3694 float left, right; 3695 if (track->isMuted() || mMasterMute || track->isPausing() || 3696 mStreamTypes[track->streamType()].mute) { 3697 left = right = 0; 3698 if (track->isPausing()) { 3699 track->setPaused(); 3700 } 3701 } else { 3702 float typeVolume = mStreamTypes[track->streamType()].volume; 3703 float v = mMasterVolume * typeVolume; 3704 uint32_t vlr = cblk->getVolumeLR(); 3705 float v_clamped = v * (vlr & 0xFFFF); 3706 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3707 left = v_clamped/MAX_GAIN; 3708 v_clamped = v * (vlr >> 16); 3709 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3710 right = v_clamped/MAX_GAIN; 3711 } 3712 3713 if (left != mLeftVolFloat || right != mRightVolFloat) { 3714 mLeftVolFloat = left; 3715 mRightVolFloat = right; 3716 3717 // Convert volumes from float to 8.24 3718 uint32_t vl = (uint32_t)(left * (1 << 24)); 3719 uint32_t vr = (uint32_t)(right * (1 << 24)); 3720 3721 // Delegate volume control to effect in track effect chain if needed 3722 // only one effect chain can be present on DirectOutputThread, so if 3723 // there is one, the track is connected to it 3724 if (!mEffectChains.isEmpty()) { 3725 // Do not ramp volume if volume is controlled by effect 3726 mEffectChains[0]->setVolume_l(&vl, &vr); 3727 left = (float)vl / (1 << 24); 3728 right = (float)vr / (1 << 24); 3729 } 3730 mOutput->stream->set_volume(mOutput->stream, left, right); 3731 } 3732 3733 // reset retry count 3734 track->mRetryCount = kMaxTrackRetriesDirect; 3735 mActiveTrack = t; 3736 mixerStatus = MIXER_TRACKS_READY; 3737 } else { 3738 // clear effect chain input buffer if an active track underruns to avoid sending 3739 // previous audio buffer again to effects 3740 if (!mEffectChains.isEmpty()) { 3741 mEffectChains[0]->clearInputBuffer(); 3742 } 3743 3744 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server); 3745 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3746 track->isStopped() || track->isPaused()) { 3747 // We have consumed all the buffers of this track. 3748 // Remove it from the list of active tracks. 3749 // TODO: implement behavior for compressed audio 3750 size_t audioHALFrames = 3751 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3752 size_t framesWritten = 3753 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 3754 if (track->presentationComplete(framesWritten, audioHALFrames)) { 3755 if (track->isStopped()) { 3756 track->reset(); 3757 } 3758 trackToRemove = track; 3759 } 3760 } else { 3761 // No buffers for this track. Give it a few chances to 3762 // fill a buffer, then remove it from active list. 3763 if (--(track->mRetryCount) <= 0) { 3764 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3765 trackToRemove = track; 3766 } else { 3767 mixerStatus = MIXER_TRACKS_ENABLED; 3768 } 3769 } 3770 } 3771 } 3772 3773 // FIXME merge this with similar code for removing multiple tracks 3774 // remove all the tracks that need to be... 3775 if (CC_UNLIKELY(trackToRemove != 0)) { 3776 tracksToRemove->add(trackToRemove); 3777 mActiveTracks.remove(trackToRemove); 3778 if (!mEffectChains.isEmpty()) { 3779 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(), 3780 trackToRemove->sessionId()); 3781 mEffectChains[0]->decActiveTrackCnt(); 3782 } 3783 if (trackToRemove->isTerminated()) { 3784 removeTrack_l(trackToRemove); 3785 } 3786 } 3787 3788 return mixerStatus; 3789} 3790 3791void AudioFlinger::DirectOutputThread::threadLoop_mix() 3792{ 3793 AudioBufferProvider::Buffer buffer; 3794 size_t frameCount = mFrameCount; 3795 int8_t *curBuf = (int8_t *)mMixBuffer; 3796 // output audio to hardware 3797 while (frameCount) { 3798 buffer.frameCount = frameCount; 3799 mActiveTrack->getNextBuffer(&buffer); 3800 if (CC_UNLIKELY(buffer.raw == NULL)) { 3801 memset(curBuf, 0, frameCount * mFrameSize); 3802 break; 3803 } 3804 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3805 frameCount -= buffer.frameCount; 3806 curBuf += buffer.frameCount * mFrameSize; 3807 mActiveTrack->releaseBuffer(&buffer); 3808 } 3809 sleepTime = 0; 3810 standbyTime = systemTime() + standbyDelay; 3811 mActiveTrack.clear(); 3812 3813} 3814 3815void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3816{ 3817 if (sleepTime == 0) { 3818 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3819 sleepTime = activeSleepTime; 3820 } else { 3821 sleepTime = idleSleepTime; 3822 } 3823 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3824 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3825 sleepTime = 0; 3826 } 3827} 3828 3829// getTrackName_l() must be called with ThreadBase::mLock held 3830int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask) 3831{ 3832 return 0; 3833} 3834 3835// deleteTrackName_l() must be called with ThreadBase::mLock held 3836void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 3837{ 3838} 3839 3840// checkForNewParameters_l() must be called with ThreadBase::mLock held 3841bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3842{ 3843 bool reconfig = false; 3844 3845 while (!mNewParameters.isEmpty()) { 3846 status_t status = NO_ERROR; 3847 String8 keyValuePair = mNewParameters[0]; 3848 AudioParameter param = AudioParameter(keyValuePair); 3849 int value; 3850 3851 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3852 // do not accept frame count changes if tracks are open as the track buffer 3853 // size depends on frame count and correct behavior would not be garantied 3854 // if frame count is changed after track creation 3855 if (!mTracks.isEmpty()) { 3856 status = INVALID_OPERATION; 3857 } else { 3858 reconfig = true; 3859 } 3860 } 3861 if (status == NO_ERROR) { 3862 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3863 keyValuePair.string()); 3864 if (!mStandby && status == INVALID_OPERATION) { 3865 mOutput->stream->common.standby(&mOutput->stream->common); 3866 mStandby = true; 3867 mBytesWritten = 0; 3868 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3869 keyValuePair.string()); 3870 } 3871 if (status == NO_ERROR && reconfig) { 3872 readOutputParameters(); 3873 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3874 } 3875 } 3876 3877 mNewParameters.removeAt(0); 3878 3879 mParamStatus = status; 3880 mParamCond.signal(); 3881 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3882 // already timed out waiting for the status and will never signal the condition. 3883 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3884 } 3885 return reconfig; 3886} 3887 3888uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3889{ 3890 uint32_t time; 3891 if (audio_is_linear_pcm(mFormat)) { 3892 time = PlaybackThread::activeSleepTimeUs(); 3893 } else { 3894 time = 10000; 3895 } 3896 return time; 3897} 3898 3899uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3900{ 3901 uint32_t time; 3902 if (audio_is_linear_pcm(mFormat)) { 3903 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3904 } else { 3905 time = 10000; 3906 } 3907 return time; 3908} 3909 3910uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3911{ 3912 uint32_t time; 3913 if (audio_is_linear_pcm(mFormat)) { 3914 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3915 } else { 3916 time = 10000; 3917 } 3918 return time; 3919} 3920 3921void AudioFlinger::DirectOutputThread::cacheParameters_l() 3922{ 3923 PlaybackThread::cacheParameters_l(); 3924 3925 // use shorter standby delay as on normal output to release 3926 // hardware resources as soon as possible 3927 standbyDelay = microseconds(activeSleepTime*2); 3928} 3929 3930// ---------------------------------------------------------------------------- 3931 3932AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 3933 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 3934 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING), 3935 mWaitTimeMs(UINT_MAX) 3936{ 3937 addOutputTrack(mainThread); 3938} 3939 3940AudioFlinger::DuplicatingThread::~DuplicatingThread() 3941{ 3942 for (size_t i = 0; i < mOutputTracks.size(); i++) { 3943 mOutputTracks[i]->destroy(); 3944 } 3945} 3946 3947void AudioFlinger::DuplicatingThread::threadLoop_mix() 3948{ 3949 // mix buffers... 3950 if (outputsReady(outputTracks)) { 3951 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 3952 } else { 3953 memset(mMixBuffer, 0, mixBufferSize); 3954 } 3955 sleepTime = 0; 3956 writeFrames = mNormalFrameCount; 3957 standbyTime = systemTime() + standbyDelay; 3958} 3959 3960void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 3961{ 3962 if (sleepTime == 0) { 3963 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3964 sleepTime = activeSleepTime; 3965 } else { 3966 sleepTime = idleSleepTime; 3967 } 3968 } else if (mBytesWritten != 0) { 3969 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3970 writeFrames = mNormalFrameCount; 3971 memset(mMixBuffer, 0, mixBufferSize); 3972 } else { 3973 // flush remaining overflow buffers in output tracks 3974 writeFrames = 0; 3975 } 3976 sleepTime = 0; 3977 } 3978} 3979 3980void AudioFlinger::DuplicatingThread::threadLoop_write() 3981{ 3982 for (size_t i = 0; i < outputTracks.size(); i++) { 3983 outputTracks[i]->write(mMixBuffer, writeFrames); 3984 } 3985 mBytesWritten += mixBufferSize; 3986} 3987 3988void AudioFlinger::DuplicatingThread::threadLoop_standby() 3989{ 3990 // DuplicatingThread implements standby by stopping all tracks 3991 for (size_t i = 0; i < outputTracks.size(); i++) { 3992 outputTracks[i]->stop(); 3993 } 3994} 3995 3996void AudioFlinger::DuplicatingThread::saveOutputTracks() 3997{ 3998 outputTracks = mOutputTracks; 3999} 4000 4001void AudioFlinger::DuplicatingThread::clearOutputTracks() 4002{ 4003 outputTracks.clear(); 4004} 4005 4006void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4007{ 4008 Mutex::Autolock _l(mLock); 4009 // FIXME explain this formula 4010 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4011 OutputTrack *outputTrack = new OutputTrack(thread, 4012 this, 4013 mSampleRate, 4014 mFormat, 4015 mChannelMask, 4016 frameCount); 4017 if (outputTrack->cblk() != NULL) { 4018 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4019 mOutputTracks.add(outputTrack); 4020 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4021 updateWaitTime_l(); 4022 } 4023} 4024 4025void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4026{ 4027 Mutex::Autolock _l(mLock); 4028 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4029 if (mOutputTracks[i]->thread() == thread) { 4030 mOutputTracks[i]->destroy(); 4031 mOutputTracks.removeAt(i); 4032 updateWaitTime_l(); 4033 return; 4034 } 4035 } 4036 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4037} 4038 4039// caller must hold mLock 4040void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4041{ 4042 mWaitTimeMs = UINT_MAX; 4043 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4044 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4045 if (strong != 0) { 4046 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4047 if (waitTimeMs < mWaitTimeMs) { 4048 mWaitTimeMs = waitTimeMs; 4049 } 4050 } 4051 } 4052} 4053 4054 4055bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks) 4056{ 4057 for (size_t i = 0; i < outputTracks.size(); i++) { 4058 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4059 if (thread == 0) { 4060 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get()); 4061 return false; 4062 } 4063 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4064 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4065 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get()); 4066 return false; 4067 } 4068 } 4069 return true; 4070} 4071 4072uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4073{ 4074 return (mWaitTimeMs * 1000) / 2; 4075} 4076 4077void AudioFlinger::DuplicatingThread::cacheParameters_l() 4078{ 4079 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4080 updateWaitTime_l(); 4081 4082 MixerThread::cacheParameters_l(); 4083} 4084 4085// ---------------------------------------------------------------------------- 4086 4087// TrackBase constructor must be called with AudioFlinger::mLock held 4088AudioFlinger::ThreadBase::TrackBase::TrackBase( 4089 ThreadBase *thread, 4090 const sp<Client>& client, 4091 uint32_t sampleRate, 4092 audio_format_t format, 4093 uint32_t channelMask, 4094 int frameCount, 4095 const sp<IMemory>& sharedBuffer, 4096 int sessionId) 4097 : RefBase(), 4098 mThread(thread), 4099 mClient(client), 4100 mCblk(NULL), 4101 // mBuffer 4102 // mBufferEnd 4103 mFrameCount(0), 4104 mState(IDLE), 4105 mSampleRate(sampleRate), 4106 mFormat(format), 4107 mStepServerFailed(false), 4108 mSessionId(sessionId) 4109 // mChannelCount 4110 // mChannelMask 4111{ 4112 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size()); 4113 4114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize); 4115 size_t size = sizeof(audio_track_cblk_t); 4116 uint8_t channelCount = popcount(channelMask); 4117 size_t bufferSize = frameCount*channelCount*sizeof(int16_t); 4118 if (sharedBuffer == 0) { 4119 size += bufferSize; 4120 } 4121 4122 if (client != NULL) { 4123 mCblkMemory = client->heap()->allocate(size); 4124 if (mCblkMemory != 0) { 4125 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer()); 4126 if (mCblk != NULL) { // construct the shared structure in-place. 4127 new(mCblk) audio_track_cblk_t(); 4128 // clear all buffers 4129 mCblk->frameCount = frameCount; 4130 mCblk->sampleRate = sampleRate; 4131// uncomment the following lines to quickly test 32-bit wraparound 4132// mCblk->user = 0xffff0000; 4133// mCblk->server = 0xffff0000; 4134// mCblk->userBase = 0xffff0000; 4135// mCblk->serverBase = 0xffff0000; 4136 mChannelCount = channelCount; 4137 mChannelMask = channelMask; 4138 if (sharedBuffer == 0) { 4139 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 4140 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); 4141 // Force underrun condition to avoid false underrun callback until first data is 4142 // written to buffer (other flags are cleared) 4143 mCblk->flags = CBLK_UNDERRUN_ON; 4144 } else { 4145 mBuffer = sharedBuffer->pointer(); 4146 } 4147 mBufferEnd = (uint8_t *)mBuffer + bufferSize; 4148 } 4149 } else { 4150 ALOGE("not enough memory for AudioTrack size=%u", size); 4151 client->heap()->dump("AudioTrack"); 4152 return; 4153 } 4154 } else { 4155 mCblk = (audio_track_cblk_t *)(new uint8_t[size]); 4156 // construct the shared structure in-place. 4157 new(mCblk) audio_track_cblk_t(); 4158 // clear all buffers 4159 mCblk->frameCount = frameCount; 4160 mCblk->sampleRate = sampleRate; 4161// uncomment the following lines to quickly test 32-bit wraparound 4162// mCblk->user = 0xffff0000; 4163// mCblk->server = 0xffff0000; 4164// mCblk->userBase = 0xffff0000; 4165// mCblk->serverBase = 0xffff0000; 4166 mChannelCount = channelCount; 4167 mChannelMask = channelMask; 4168 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 4169 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); 4170 // Force underrun condition to avoid false underrun callback until first data is 4171 // written to buffer (other flags are cleared) 4172 mCblk->flags = CBLK_UNDERRUN_ON; 4173 mBufferEnd = (uint8_t *)mBuffer + bufferSize; 4174 } 4175} 4176 4177AudioFlinger::ThreadBase::TrackBase::~TrackBase() 4178{ 4179 if (mCblk != NULL) { 4180 if (mClient == 0) { 4181 delete mCblk; 4182 } else { 4183 mCblk->~audio_track_cblk_t(); // destroy our shared-structure. 4184 } 4185 } 4186 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 4187 if (mClient != 0) { 4188 // Client destructor must run with AudioFlinger mutex locked 4189 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 4190 // If the client's reference count drops to zero, the associated destructor 4191 // must run with AudioFlinger lock held. Thus the explicit clear() rather than 4192 // relying on the automatic clear() at end of scope. 4193 mClient.clear(); 4194 } 4195} 4196 4197// AudioBufferProvider interface 4198// getNextBuffer() = 0; 4199// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack 4200void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4201{ 4202 buffer->raw = NULL; 4203 mFrameCount = buffer->frameCount; 4204 // FIXME See note at getNextBuffer() 4205 (void) step(); // ignore return value of step() 4206 buffer->frameCount = 0; 4207} 4208 4209bool AudioFlinger::ThreadBase::TrackBase::step() { 4210 bool result; 4211 audio_track_cblk_t* cblk = this->cblk(); 4212 4213 result = cblk->stepServer(mFrameCount); 4214 if (!result) { 4215 ALOGV("stepServer failed acquiring cblk mutex"); 4216 mStepServerFailed = true; 4217 } 4218 return result; 4219} 4220 4221void AudioFlinger::ThreadBase::TrackBase::reset() { 4222 audio_track_cblk_t* cblk = this->cblk(); 4223 4224 cblk->user = 0; 4225 cblk->server = 0; 4226 cblk->userBase = 0; 4227 cblk->serverBase = 0; 4228 mStepServerFailed = false; 4229 ALOGV("TrackBase::reset"); 4230} 4231 4232int AudioFlinger::ThreadBase::TrackBase::sampleRate() const { 4233 return (int)mCblk->sampleRate; 4234} 4235 4236void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const { 4237 audio_track_cblk_t* cblk = this->cblk(); 4238 size_t frameSize = cblk->frameSize; 4239 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize; 4240 int8_t *bufferEnd = bufferStart + frames * frameSize; 4241 4242 // Check validity of returned pointer in case the track control block would have been corrupted. 4243 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd), 4244 "TrackBase::getBuffer buffer out of range:\n" 4245 " start: %p, end %p , mBuffer %p mBufferEnd %p\n" 4246 " server %u, serverBase %u, user %u, userBase %u, frameSize %d", 4247 bufferStart, bufferEnd, mBuffer, mBufferEnd, 4248 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize); 4249 4250 return bufferStart; 4251} 4252 4253status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event) 4254{ 4255 mSyncEvents.add(event); 4256 return NO_ERROR; 4257} 4258 4259// ---------------------------------------------------------------------------- 4260 4261// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 4262AudioFlinger::PlaybackThread::Track::Track( 4263 PlaybackThread *thread, 4264 const sp<Client>& client, 4265 audio_stream_type_t streamType, 4266 uint32_t sampleRate, 4267 audio_format_t format, 4268 uint32_t channelMask, 4269 int frameCount, 4270 const sp<IMemory>& sharedBuffer, 4271 int sessionId, 4272 IAudioFlinger::track_flags_t flags) 4273 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId), 4274 mMute(false), 4275 mFillingUpStatus(FS_INVALID), 4276 // mRetryCount initialized later when needed 4277 mSharedBuffer(sharedBuffer), 4278 mStreamType(streamType), 4279 mName(-1), // see note below 4280 mMainBuffer(thread->mixBuffer()), 4281 mAuxBuffer(NULL), 4282 mAuxEffectId(0), mHasVolumeController(false), 4283 mPresentationCompleteFrames(0), 4284 mFlags(flags), 4285 mFastIndex(-1), 4286 mUnderrunCount(0), 4287 mCachedVolume(1.0) 4288{ 4289 if (mCblk != NULL) { 4290 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of 4291 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack 4292 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t); 4293 // to avoid leaking a track name, do not allocate one unless there is an mCblk 4294 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask); 4295 mCblk->mName = mName; 4296 if (mName < 0) { 4297 ALOGE("no more track names available"); 4298 return; 4299 } 4300 // only allocate a fast track index if we were able to allocate a normal track name 4301 if (flags & IAudioFlinger::TRACK_FAST) { 4302 mCblk->flags |= CBLK_FAST; // atomic op not needed yet 4303 ALOG_ASSERT(thread->mFastTrackAvailMask != 0); 4304 int i = __builtin_ctz(thread->mFastTrackAvailMask); 4305 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks); 4306 // FIXME This is too eager. We allocate a fast track index before the 4307 // fast track becomes active. Since fast tracks are a scarce resource, 4308 // this means we are potentially denying other more important fast tracks from 4309 // being created. It would be better to allocate the index dynamically. 4310 mFastIndex = i; 4311 mCblk->mName = i; 4312 // Read the initial underruns because this field is never cleared by the fast mixer 4313 mObservedUnderruns = thread->getFastTrackUnderruns(i); 4314 thread->mFastTrackAvailMask &= ~(1 << i); 4315 } 4316 } 4317 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 4318} 4319 4320AudioFlinger::PlaybackThread::Track::~Track() 4321{ 4322 ALOGV("PlaybackThread::Track destructor"); 4323 sp<ThreadBase> thread = mThread.promote(); 4324 if (thread != 0) { 4325 Mutex::Autolock _l(thread->mLock); 4326 mState = TERMINATED; 4327 } 4328} 4329 4330void AudioFlinger::PlaybackThread::Track::destroy() 4331{ 4332 // NOTE: destroyTrack_l() can remove a strong reference to this Track 4333 // by removing it from mTracks vector, so there is a risk that this Tracks's 4334 // destructor is called. As the destructor needs to lock mLock, 4335 // we must acquire a strong reference on this Track before locking mLock 4336 // here so that the destructor is called only when exiting this function. 4337 // On the other hand, as long as Track::destroy() is only called by 4338 // TrackHandle destructor, the TrackHandle still holds a strong ref on 4339 // this Track with its member mTrack. 4340 sp<Track> keep(this); 4341 { // scope for mLock 4342 sp<ThreadBase> thread = mThread.promote(); 4343 if (thread != 0) { 4344 if (!isOutputTrack()) { 4345 if (mState == ACTIVE || mState == RESUMING) { 4346 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId); 4347 4348#ifdef ADD_BATTERY_DATA 4349 // to track the speaker usage 4350 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 4351#endif 4352 } 4353 AudioSystem::releaseOutput(thread->id()); 4354 } 4355 Mutex::Autolock _l(thread->mLock); 4356 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4357 playbackThread->destroyTrack_l(this); 4358 } 4359 } 4360} 4361 4362/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result) 4363{ 4364 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB " 4365 " Server User Main buf Aux Buf Flags Underruns\n"); 4366} 4367 4368void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 4369{ 4370 uint32_t vlr = mCblk->getVolumeLR(); 4371 if (isFastTrack()) { 4372 sprintf(buffer, " F %2d", mFastIndex); 4373 } else { 4374 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0); 4375 } 4376 track_state state = mState; 4377 char stateChar; 4378 switch (state) { 4379 case IDLE: 4380 stateChar = 'I'; 4381 break; 4382 case TERMINATED: 4383 stateChar = 'T'; 4384 break; 4385 case STOPPING_1: 4386 stateChar = 's'; 4387 break; 4388 case STOPPING_2: 4389 stateChar = '5'; 4390 break; 4391 case STOPPED: 4392 stateChar = 'S'; 4393 break; 4394 case RESUMING: 4395 stateChar = 'R'; 4396 break; 4397 case ACTIVE: 4398 stateChar = 'A'; 4399 break; 4400 case PAUSING: 4401 stateChar = 'p'; 4402 break; 4403 case PAUSED: 4404 stateChar = 'P'; 4405 break; 4406 case FLUSHED: 4407 stateChar = 'F'; 4408 break; 4409 default: 4410 stateChar = '?'; 4411 break; 4412 } 4413 char nowInUnderrun; 4414 switch (mObservedUnderruns.mBitFields.mMostRecent) { 4415 case UNDERRUN_FULL: 4416 nowInUnderrun = ' '; 4417 break; 4418 case UNDERRUN_PARTIAL: 4419 nowInUnderrun = '<'; 4420 break; 4421 case UNDERRUN_EMPTY: 4422 nowInUnderrun = '*'; 4423 break; 4424 default: 4425 nowInUnderrun = '?'; 4426 break; 4427 } 4428 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g " 4429 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n", 4430 (mClient == 0) ? getpid_cached : mClient->pid(), 4431 mStreamType, 4432 mFormat, 4433 mChannelMask, 4434 mSessionId, 4435 mFrameCount, 4436 mCblk->frameCount, 4437 stateChar, 4438 mMute, 4439 mFillingUpStatus, 4440 mCblk->sampleRate, 4441 20.0 * log10((vlr & 0xFFFF) / 4096.0), 4442 20.0 * log10((vlr >> 16) / 4096.0), 4443 mCblk->server, 4444 mCblk->user, 4445 (int)mMainBuffer, 4446 (int)mAuxBuffer, 4447 mCblk->flags, 4448 mUnderrunCount, 4449 nowInUnderrun); 4450} 4451 4452// AudioBufferProvider interface 4453status_t AudioFlinger::PlaybackThread::Track::getNextBuffer( 4454 AudioBufferProvider::Buffer* buffer, int64_t pts) 4455{ 4456 audio_track_cblk_t* cblk = this->cblk(); 4457 uint32_t framesReady; 4458 uint32_t framesReq = buffer->frameCount; 4459 4460 // Check if last stepServer failed, try to step now 4461 if (mStepServerFailed) { 4462 // FIXME When called by fast mixer, this takes a mutex with tryLock(). 4463 // Since the fast mixer is higher priority than client callback thread, 4464 // it does not result in priority inversion for client. 4465 // But a non-blocking solution would be preferable to avoid 4466 // fast mixer being unable to tryLock(), and 4467 // to avoid the extra context switches if the client wakes up, 4468 // discovers the mutex is locked, then has to wait for fast mixer to unlock. 4469 if (!step()) goto getNextBuffer_exit; 4470 ALOGV("stepServer recovered"); 4471 mStepServerFailed = false; 4472 } 4473 4474 // FIXME Same as above 4475 framesReady = cblk->framesReady(); 4476 4477 if (CC_LIKELY(framesReady)) { 4478 uint32_t s = cblk->server; 4479 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 4480 4481 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd; 4482 if (framesReq > framesReady) { 4483 framesReq = framesReady; 4484 } 4485 if (framesReq > bufferEnd - s) { 4486 framesReq = bufferEnd - s; 4487 } 4488 4489 buffer->raw = getBuffer(s, framesReq); 4490 if (buffer->raw == NULL) goto getNextBuffer_exit; 4491 4492 buffer->frameCount = framesReq; 4493 return NO_ERROR; 4494 } 4495 4496getNextBuffer_exit: 4497 buffer->raw = NULL; 4498 buffer->frameCount = 0; 4499 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get()); 4500 return NOT_ENOUGH_DATA; 4501} 4502 4503// Note that framesReady() takes a mutex on the control block using tryLock(). 4504// This could result in priority inversion if framesReady() is called by the normal mixer, 4505// as the normal mixer thread runs at lower 4506// priority than the client's callback thread: there is a short window within framesReady() 4507// during which the normal mixer could be preempted, and the client callback would block. 4508// Another problem can occur if framesReady() is called by the fast mixer: 4509// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer. 4510// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue. 4511size_t AudioFlinger::PlaybackThread::Track::framesReady() const { 4512 return mCblk->framesReady(); 4513} 4514 4515// Don't call for fast tracks; the framesReady() could result in priority inversion 4516bool AudioFlinger::PlaybackThread::Track::isReady() const { 4517 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true; 4518 4519 if (framesReady() >= mCblk->frameCount || 4520 (mCblk->flags & CBLK_FORCEREADY_MSK)) { 4521 mFillingUpStatus = FS_FILLED; 4522 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 4523 return true; 4524 } 4525 return false; 4526} 4527 4528status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event, 4529 int triggerSession) 4530{ 4531 status_t status = NO_ERROR; 4532 ALOGV("start(%d), calling pid %d session %d", 4533 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 4534 4535 sp<ThreadBase> thread = mThread.promote(); 4536 if (thread != 0) { 4537 Mutex::Autolock _l(thread->mLock); 4538 track_state state = mState; 4539 // here the track could be either new, or restarted 4540 // in both cases "unstop" the track 4541 if (mState == PAUSED) { 4542 mState = TrackBase::RESUMING; 4543 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 4544 } else { 4545 mState = TrackBase::ACTIVE; 4546 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 4547 } 4548 4549 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) { 4550 thread->mLock.unlock(); 4551 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId); 4552 thread->mLock.lock(); 4553 4554#ifdef ADD_BATTERY_DATA 4555 // to track the speaker usage 4556 if (status == NO_ERROR) { 4557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 4558 } 4559#endif 4560 } 4561 if (status == NO_ERROR) { 4562 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4563 playbackThread->addTrack_l(this); 4564 } else { 4565 mState = state; 4566 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 4567 } 4568 } else { 4569 status = BAD_VALUE; 4570 } 4571 return status; 4572} 4573 4574void AudioFlinger::PlaybackThread::Track::stop() 4575{ 4576 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 4577 sp<ThreadBase> thread = mThread.promote(); 4578 if (thread != 0) { 4579 Mutex::Autolock _l(thread->mLock); 4580 track_state state = mState; 4581 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) { 4582 // If the track is not active (PAUSED and buffers full), flush buffers 4583 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4584 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 4585 reset(); 4586 mState = STOPPED; 4587 } else if (!isFastTrack()) { 4588 mState = STOPPED; 4589 } else { 4590 // prepareTracks_l() will set state to STOPPING_2 after next underrun, 4591 // and then to STOPPED and reset() when presentation is complete 4592 mState = STOPPING_1; 4593 } 4594 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread); 4595 } 4596 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) { 4597 thread->mLock.unlock(); 4598 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId); 4599 thread->mLock.lock(); 4600 4601#ifdef ADD_BATTERY_DATA 4602 // to track the speaker usage 4603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 4604#endif 4605 } 4606 } 4607} 4608 4609void AudioFlinger::PlaybackThread::Track::pause() 4610{ 4611 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 4612 sp<ThreadBase> thread = mThread.promote(); 4613 if (thread != 0) { 4614 Mutex::Autolock _l(thread->mLock); 4615 if (mState == ACTIVE || mState == RESUMING) { 4616 mState = PAUSING; 4617 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 4618 if (!isOutputTrack()) { 4619 thread->mLock.unlock(); 4620 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId); 4621 thread->mLock.lock(); 4622 4623#ifdef ADD_BATTERY_DATA 4624 // to track the speaker usage 4625 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 4626#endif 4627 } 4628 } 4629 } 4630} 4631 4632void AudioFlinger::PlaybackThread::Track::flush() 4633{ 4634 ALOGV("flush(%d)", mName); 4635 sp<ThreadBase> thread = mThread.promote(); 4636 if (thread != 0) { 4637 Mutex::Autolock _l(thread->mLock); 4638 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED && 4639 mState != PAUSING) { 4640 return; 4641 } 4642 // No point remaining in PAUSED state after a flush => go to 4643 // FLUSHED state 4644 mState = FLUSHED; 4645 // do not reset the track if it is still in the process of being stopped or paused. 4646 // this will be done by prepareTracks_l() when the track is stopped. 4647 // prepareTracks_l() will see mState == FLUSHED, then 4648 // remove from active track list, reset(), and trigger presentation complete 4649 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4650 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 4651 reset(); 4652 } 4653 } 4654} 4655 4656void AudioFlinger::PlaybackThread::Track::reset() 4657{ 4658 // Do not reset twice to avoid discarding data written just after a flush and before 4659 // the audioflinger thread detects the track is stopped. 4660 if (!mResetDone) { 4661 TrackBase::reset(); 4662 // Force underrun condition to avoid false underrun callback until first data is 4663 // written to buffer 4664 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 4665 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 4666 mFillingUpStatus = FS_FILLING; 4667 mResetDone = true; 4668 if (mState == FLUSHED) { 4669 mState = IDLE; 4670 } 4671 } 4672} 4673 4674void AudioFlinger::PlaybackThread::Track::mute(bool muted) 4675{ 4676 mMute = muted; 4677} 4678 4679status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 4680{ 4681 status_t status = DEAD_OBJECT; 4682 sp<ThreadBase> thread = mThread.promote(); 4683 if (thread != 0) { 4684 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4685 sp<AudioFlinger> af = mClient->audioFlinger(); 4686 4687 Mutex::Autolock _l(af->mLock); 4688 4689 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 4690 4691 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) { 4692 Mutex::Autolock _dl(playbackThread->mLock); 4693 Mutex::Autolock _sl(srcThread->mLock); 4694 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 4695 if (chain == 0) { 4696 return INVALID_OPERATION; 4697 } 4698 4699 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId); 4700 if (effect == 0) { 4701 return INVALID_OPERATION; 4702 } 4703 srcThread->removeEffect_l(effect); 4704 playbackThread->addEffect_l(effect); 4705 // removeEffect_l() has stopped the effect if it was active so it must be restarted 4706 if (effect->state() == EffectModule::ACTIVE || 4707 effect->state() == EffectModule::STOPPING) { 4708 effect->start(); 4709 } 4710 4711 sp<EffectChain> dstChain = effect->chain().promote(); 4712 if (dstChain == 0) { 4713 srcThread->addEffect_l(effect); 4714 return INVALID_OPERATION; 4715 } 4716 AudioSystem::unregisterEffect(effect->id()); 4717 AudioSystem::registerEffect(&effect->desc(), 4718 srcThread->id(), 4719 dstChain->strategy(), 4720 AUDIO_SESSION_OUTPUT_MIX, 4721 effect->id()); 4722 } 4723 status = playbackThread->attachAuxEffect(this, EffectId); 4724 } 4725 return status; 4726} 4727 4728void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 4729{ 4730 mAuxEffectId = EffectId; 4731 mAuxBuffer = buffer; 4732} 4733 4734bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten, 4735 size_t audioHalFrames) 4736{ 4737 // a track is considered presented when the total number of frames written to audio HAL 4738 // corresponds to the number of frames written when presentationComplete() is called for the 4739 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time. 4740 if (mPresentationCompleteFrames == 0) { 4741 mPresentationCompleteFrames = framesWritten + audioHalFrames; 4742 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d", 4743 mPresentationCompleteFrames, audioHalFrames); 4744 } 4745 if (framesWritten >= mPresentationCompleteFrames) { 4746 ALOGV("presentationComplete() session %d complete: framesWritten %d", 4747 mSessionId, framesWritten); 4748 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 4749 return true; 4750 } 4751 return false; 4752} 4753 4754void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type) 4755{ 4756 for (int i = 0; i < (int)mSyncEvents.size(); i++) { 4757 if (mSyncEvents[i]->type() == type) { 4758 mSyncEvents[i]->trigger(); 4759 mSyncEvents.removeAt(i); 4760 i--; 4761 } 4762 } 4763} 4764 4765// implement VolumeBufferProvider interface 4766 4767uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR() 4768{ 4769 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs 4770 ALOG_ASSERT(isFastTrack() && (mCblk != NULL)); 4771 uint32_t vlr = mCblk->getVolumeLR(); 4772 uint32_t vl = vlr & 0xFFFF; 4773 uint32_t vr = vlr >> 16; 4774 // track volumes come from shared memory, so can't be trusted and must be clamped 4775 if (vl > MAX_GAIN_INT) { 4776 vl = MAX_GAIN_INT; 4777 } 4778 if (vr > MAX_GAIN_INT) { 4779 vr = MAX_GAIN_INT; 4780 } 4781 // now apply the cached master volume and stream type volume; 4782 // this is trusted but lacks any synchronization or barrier so may be stale 4783 float v = mCachedVolume; 4784 vl *= v; 4785 vr *= v; 4786 // re-combine into U4.16 4787 vlr = (vr << 16) | (vl & 0xFFFF); 4788 // FIXME look at mute, pause, and stop flags 4789 return vlr; 4790} 4791 4792status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event) 4793{ 4794 if (mState == TERMINATED || mState == PAUSED || 4795 ((framesReady() == 0) && ((mSharedBuffer != 0) || 4796 (mState == STOPPED)))) { 4797 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ", 4798 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady()); 4799 event->cancel(); 4800 return INVALID_OPERATION; 4801 } 4802 TrackBase::setSyncEvent(event); 4803 return NO_ERROR; 4804} 4805 4806// timed audio tracks 4807 4808sp<AudioFlinger::PlaybackThread::TimedTrack> 4809AudioFlinger::PlaybackThread::TimedTrack::create( 4810 PlaybackThread *thread, 4811 const sp<Client>& client, 4812 audio_stream_type_t streamType, 4813 uint32_t sampleRate, 4814 audio_format_t format, 4815 uint32_t channelMask, 4816 int frameCount, 4817 const sp<IMemory>& sharedBuffer, 4818 int sessionId) { 4819 if (!client->reserveTimedTrack()) 4820 return 0; 4821 4822 return new TimedTrack( 4823 thread, client, streamType, sampleRate, format, channelMask, frameCount, 4824 sharedBuffer, sessionId); 4825} 4826 4827AudioFlinger::PlaybackThread::TimedTrack::TimedTrack( 4828 PlaybackThread *thread, 4829 const sp<Client>& client, 4830 audio_stream_type_t streamType, 4831 uint32_t sampleRate, 4832 audio_format_t format, 4833 uint32_t channelMask, 4834 int frameCount, 4835 const sp<IMemory>& sharedBuffer, 4836 int sessionId) 4837 : Track(thread, client, streamType, sampleRate, format, channelMask, 4838 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED), 4839 mQueueHeadInFlight(false), 4840 mTrimQueueHeadOnRelease(false), 4841 mFramesPendingInQueue(0), 4842 mTimedSilenceBuffer(NULL), 4843 mTimedSilenceBufferSize(0), 4844 mTimedAudioOutputOnTime(false), 4845 mMediaTimeTransformValid(false) 4846{ 4847 LocalClock lc; 4848 mLocalTimeFreq = lc.getLocalFreq(); 4849 4850 mLocalTimeToSampleTransform.a_zero = 0; 4851 mLocalTimeToSampleTransform.b_zero = 0; 4852 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate; 4853 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq; 4854 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer, 4855 &mLocalTimeToSampleTransform.a_to_b_denom); 4856 4857 mMediaTimeToSampleTransform.a_zero = 0; 4858 mMediaTimeToSampleTransform.b_zero = 0; 4859 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate; 4860 mMediaTimeToSampleTransform.a_to_b_denom = 1000000; 4861 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer, 4862 &mMediaTimeToSampleTransform.a_to_b_denom); 4863} 4864 4865AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() { 4866 mClient->releaseTimedTrack(); 4867 delete [] mTimedSilenceBuffer; 4868} 4869 4870status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer( 4871 size_t size, sp<IMemory>* buffer) { 4872 4873 Mutex::Autolock _l(mTimedBufferQueueLock); 4874 4875 trimTimedBufferQueue_l(); 4876 4877 // lazily initialize the shared memory heap for timed buffers 4878 if (mTimedMemoryDealer == NULL) { 4879 const int kTimedBufferHeapSize = 512 << 10; 4880 4881 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize, 4882 "AudioFlingerTimed"); 4883 if (mTimedMemoryDealer == NULL) 4884 return NO_MEMORY; 4885 } 4886 4887 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size); 4888 if (newBuffer == NULL) { 4889 newBuffer = mTimedMemoryDealer->allocate(size); 4890 if (newBuffer == NULL) 4891 return NO_MEMORY; 4892 } 4893 4894 *buffer = newBuffer; 4895 return NO_ERROR; 4896} 4897 4898// caller must hold mTimedBufferQueueLock 4899void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() { 4900 int64_t mediaTimeNow; 4901 { 4902 Mutex::Autolock mttLock(mMediaTimeTransformLock); 4903 if (!mMediaTimeTransformValid) 4904 return; 4905 4906 int64_t targetTimeNow; 4907 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) 4908 ? mCCHelper.getCommonTime(&targetTimeNow) 4909 : mCCHelper.getLocalTime(&targetTimeNow); 4910 4911 if (OK != res) 4912 return; 4913 4914 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow, 4915 &mediaTimeNow)) { 4916 return; 4917 } 4918 } 4919 4920 size_t trimEnd; 4921 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) { 4922 int64_t bufEnd; 4923 4924 if ((trimEnd + 1) < mTimedBufferQueue.size()) { 4925 // We have a next buffer. Just use its PTS as the PTS of the frame 4926 // following the last frame in this buffer. If the stream is sparse 4927 // (ie, there are deliberate gaps left in the stream which should be 4928 // filled with silence by the TimedAudioTrack), then this can result 4929 // in one extra buffer being left un-trimmed when it could have 4930 // been. In general, this is not typical, and we would rather 4931 // optimized away the TS calculation below for the more common case 4932 // where PTSes are contiguous. 4933 bufEnd = mTimedBufferQueue[trimEnd + 1].pts(); 4934 } else { 4935 // We have no next buffer. Compute the PTS of the frame following 4936 // the last frame in this buffer by computing the duration of of 4937 // this frame in media time units and adding it to the PTS of the 4938 // buffer. 4939 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size() 4940 / mCblk->frameSize; 4941 4942 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount, 4943 &bufEnd)) { 4944 ALOGE("Failed to convert frame count of %lld to media time" 4945 " duration" " (scale factor %d/%u) in %s", 4946 frameCount, 4947 mMediaTimeToSampleTransform.a_to_b_numer, 4948 mMediaTimeToSampleTransform.a_to_b_denom, 4949 __PRETTY_FUNCTION__); 4950 break; 4951 } 4952 bufEnd += mTimedBufferQueue[trimEnd].pts(); 4953 } 4954 4955 if (bufEnd > mediaTimeNow) 4956 break; 4957 4958 // Is the buffer we want to use in the middle of a mix operation right 4959 // now? If so, don't actually trim it. Just wait for the releaseBuffer 4960 // from the mixer which should be coming back shortly. 4961 if (!trimEnd && mQueueHeadInFlight) { 4962 mTrimQueueHeadOnRelease = true; 4963 } 4964 } 4965 4966 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0; 4967 if (trimStart < trimEnd) { 4968 // Update the bookkeeping for framesReady() 4969 for (size_t i = trimStart; i < trimEnd; ++i) { 4970 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim"); 4971 } 4972 4973 // Now actually remove the buffers from the queue. 4974 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd); 4975 } 4976} 4977 4978void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l( 4979 const char* logTag) { 4980 ALOG_ASSERT(mTimedBufferQueue.size() > 0, 4981 "%s called (reason \"%s\"), but timed buffer queue has no" 4982 " elements to trim.", __FUNCTION__, logTag); 4983 4984 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag); 4985 mTimedBufferQueue.removeAt(0); 4986} 4987 4988void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l( 4989 const TimedBuffer& buf, 4990 const char* logTag) { 4991 uint32_t bufBytes = buf.buffer()->size(); 4992 uint32_t consumedAlready = buf.position(); 4993 4994 ALOG_ASSERT(consumedAlready <= bufBytes, 4995 "Bad bookkeeping while updating frames pending. Timed buffer is" 4996 " only %u bytes long, but claims to have consumed %u" 4997 " bytes. (update reason: \"%s\")", 4998 bufBytes, consumedAlready, logTag); 4999 5000 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize; 5001 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames, 5002 "Bad bookkeeping while updating frames pending. Should have at" 5003 " least %u queued frames, but we think we have only %u. (update" 5004 " reason: \"%s\")", 5005 bufFrames, mFramesPendingInQueue, logTag); 5006 5007 mFramesPendingInQueue -= bufFrames; 5008} 5009 5010status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer( 5011 const sp<IMemory>& buffer, int64_t pts) { 5012 5013 { 5014 Mutex::Autolock mttLock(mMediaTimeTransformLock); 5015 if (!mMediaTimeTransformValid) 5016 return INVALID_OPERATION; 5017 } 5018 5019 Mutex::Autolock _l(mTimedBufferQueueLock); 5020 5021 uint32_t bufFrames = buffer->size() / mCblk->frameSize; 5022 mFramesPendingInQueue += bufFrames; 5023 mTimedBufferQueue.add(TimedBuffer(buffer, pts)); 5024 5025 return NO_ERROR; 5026} 5027 5028status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform( 5029 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) { 5030 5031 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d", 5032 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom, 5033 target); 5034 5035 if (!(target == TimedAudioTrack::LOCAL_TIME || 5036 target == TimedAudioTrack::COMMON_TIME)) { 5037 return BAD_VALUE; 5038 } 5039 5040 Mutex::Autolock lock(mMediaTimeTransformLock); 5041 mMediaTimeTransform = xform; 5042 mMediaTimeTransformTarget = target; 5043 mMediaTimeTransformValid = true; 5044 5045 return NO_ERROR; 5046} 5047 5048#define min(a, b) ((a) < (b) ? (a) : (b)) 5049 5050// implementation of getNextBuffer for tracks whose buffers have timestamps 5051status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer( 5052 AudioBufferProvider::Buffer* buffer, int64_t pts) 5053{ 5054 if (pts == AudioBufferProvider::kInvalidPTS) { 5055 buffer->raw = NULL; 5056 buffer->frameCount = 0; 5057 mTimedAudioOutputOnTime = false; 5058 return INVALID_OPERATION; 5059 } 5060 5061 Mutex::Autolock _l(mTimedBufferQueueLock); 5062 5063 ALOG_ASSERT(!mQueueHeadInFlight, 5064 "getNextBuffer called without releaseBuffer!"); 5065 5066 while (true) { 5067 5068 // if we have no timed buffers, then fail 5069 if (mTimedBufferQueue.isEmpty()) { 5070 buffer->raw = NULL; 5071 buffer->frameCount = 0; 5072 return NOT_ENOUGH_DATA; 5073 } 5074 5075 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 5076 5077 // calculate the PTS of the head of the timed buffer queue expressed in 5078 // local time 5079 int64_t headLocalPTS; 5080 { 5081 Mutex::Autolock mttLock(mMediaTimeTransformLock); 5082 5083 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid"); 5084 5085 if (mMediaTimeTransform.a_to_b_denom == 0) { 5086 // the transform represents a pause, so yield silence 5087 timedYieldSilence_l(buffer->frameCount, buffer); 5088 return NO_ERROR; 5089 } 5090 5091 int64_t transformedPTS; 5092 if (!mMediaTimeTransform.doForwardTransform(head.pts(), 5093 &transformedPTS)) { 5094 // the transform failed. this shouldn't happen, but if it does 5095 // then just drop this buffer 5096 ALOGW("timedGetNextBuffer transform failed"); 5097 buffer->raw = NULL; 5098 buffer->frameCount = 0; 5099 trimTimedBufferQueueHead_l("getNextBuffer; no transform"); 5100 return NO_ERROR; 5101 } 5102 5103 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) { 5104 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS, 5105 &headLocalPTS)) { 5106 buffer->raw = NULL; 5107 buffer->frameCount = 0; 5108 return INVALID_OPERATION; 5109 } 5110 } else { 5111 headLocalPTS = transformedPTS; 5112 } 5113 } 5114 5115 // adjust the head buffer's PTS to reflect the portion of the head buffer 5116 // that has already been consumed 5117 int64_t effectivePTS = headLocalPTS + 5118 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate()); 5119 5120 // Calculate the delta in samples between the head of the input buffer 5121 // queue and the start of the next output buffer that will be written. 5122 // If the transformation fails because of over or underflow, it means 5123 // that the sample's position in the output stream is so far out of 5124 // whack that it should just be dropped. 5125 int64_t sampleDelta; 5126 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) { 5127 ALOGV("*** head buffer is too far from PTS: dropped buffer"); 5128 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from" 5129 " mix"); 5130 continue; 5131 } 5132 if (!mLocalTimeToSampleTransform.doForwardTransform( 5133 (effectivePTS - pts) << 32, &sampleDelta)) { 5134 ALOGV("*** too late during sample rate transform: dropped buffer"); 5135 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample"); 5136 continue; 5137 } 5138 5139 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld" 5140 " sampleDelta=[%d.%08x]", 5141 head.pts(), head.position(), pts, 5142 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) 5143 + (sampleDelta >> 32)), 5144 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF)); 5145 5146 // if the delta between the ideal placement for the next input sample and 5147 // the current output position is within this threshold, then we will 5148 // concatenate the next input samples to the previous output 5149 const int64_t kSampleContinuityThreshold = 5150 (static_cast<int64_t>(sampleRate()) << 32) / 250; 5151 5152 // if this is the first buffer of audio that we're emitting from this track 5153 // then it should be almost exactly on time. 5154 const int64_t kSampleStartupThreshold = 1LL << 32; 5155 5156 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) || 5157 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) { 5158 // the next input is close enough to being on time, so concatenate it 5159 // with the last output 5160 timedYieldSamples_l(buffer); 5161 5162 ALOGVV("*** on time: head.pos=%d frameCount=%u", 5163 head.position(), buffer->frameCount); 5164 return NO_ERROR; 5165 } 5166 5167 // Looks like our output is not on time. Reset our on timed status. 5168 // Next time we mix samples from our input queue, then should be within 5169 // the StartupThreshold. 5170 mTimedAudioOutputOnTime = false; 5171 if (sampleDelta > 0) { 5172 // the gap between the current output position and the proper start of 5173 // the next input sample is too big, so fill it with silence 5174 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32; 5175 5176 timedYieldSilence_l(framesUntilNextInput, buffer); 5177 ALOGV("*** silence: frameCount=%u", buffer->frameCount); 5178 return NO_ERROR; 5179 } else { 5180 // the next input sample is late 5181 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32)); 5182 size_t onTimeSamplePosition = 5183 head.position() + lateFrames * mCblk->frameSize; 5184 5185 if (onTimeSamplePosition > head.buffer()->size()) { 5186 // all the remaining samples in the head are too late, so 5187 // drop it and move on 5188 ALOGV("*** too late: dropped buffer"); 5189 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer"); 5190 continue; 5191 } else { 5192 // skip over the late samples 5193 head.setPosition(onTimeSamplePosition); 5194 5195 // yield the available samples 5196 timedYieldSamples_l(buffer); 5197 5198 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount); 5199 return NO_ERROR; 5200 } 5201 } 5202 } 5203} 5204 5205// Yield samples from the timed buffer queue head up to the given output 5206// buffer's capacity. 5207// 5208// Caller must hold mTimedBufferQueueLock 5209void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l( 5210 AudioBufferProvider::Buffer* buffer) { 5211 5212 const TimedBuffer& head = mTimedBufferQueue[0]; 5213 5214 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) + 5215 head.position()); 5216 5217 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) / 5218 mCblk->frameSize); 5219 size_t framesRequested = buffer->frameCount; 5220 buffer->frameCount = min(framesLeftInHead, framesRequested); 5221 5222 mQueueHeadInFlight = true; 5223 mTimedAudioOutputOnTime = true; 5224} 5225 5226// Yield samples of silence up to the given output buffer's capacity 5227// 5228// Caller must hold mTimedBufferQueueLock 5229void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l( 5230 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) { 5231 5232 // lazily allocate a buffer filled with silence 5233 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) { 5234 delete [] mTimedSilenceBuffer; 5235 mTimedSilenceBufferSize = numFrames * mCblk->frameSize; 5236 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize]; 5237 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize); 5238 } 5239 5240 buffer->raw = mTimedSilenceBuffer; 5241 size_t framesRequested = buffer->frameCount; 5242 buffer->frameCount = min(numFrames, framesRequested); 5243 5244 mTimedAudioOutputOnTime = false; 5245} 5246 5247// AudioBufferProvider interface 5248void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer( 5249 AudioBufferProvider::Buffer* buffer) { 5250 5251 Mutex::Autolock _l(mTimedBufferQueueLock); 5252 5253 // If the buffer which was just released is part of the buffer at the head 5254 // of the queue, be sure to update the amt of the buffer which has been 5255 // consumed. If the buffer being returned is not part of the head of the 5256 // queue, its either because the buffer is part of the silence buffer, or 5257 // because the head of the timed queue was trimmed after the mixer called 5258 // getNextBuffer but before the mixer called releaseBuffer. 5259 if (buffer->raw == mTimedSilenceBuffer) { 5260 ALOG_ASSERT(!mQueueHeadInFlight, 5261 "Queue head in flight during release of silence buffer!"); 5262 goto done; 5263 } 5264 5265 ALOG_ASSERT(mQueueHeadInFlight, 5266 "TimedTrack::releaseBuffer of non-silence buffer, but no queue" 5267 " head in flight."); 5268 5269 if (mTimedBufferQueue.size()) { 5270 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 5271 5272 void* start = head.buffer()->pointer(); 5273 void* end = reinterpret_cast<void*>( 5274 reinterpret_cast<uint8_t*>(head.buffer()->pointer()) 5275 + head.buffer()->size()); 5276 5277 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end), 5278 "released buffer not within the head of the timed buffer" 5279 " queue; qHead = [%p, %p], released buffer = %p", 5280 start, end, buffer->raw); 5281 5282 head.setPosition(head.position() + 5283 (buffer->frameCount * mCblk->frameSize)); 5284 mQueueHeadInFlight = false; 5285 5286 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount, 5287 "Bad bookkeeping during releaseBuffer! Should have at" 5288 " least %u queued frames, but we think we have only %u", 5289 buffer->frameCount, mFramesPendingInQueue); 5290 5291 mFramesPendingInQueue -= buffer->frameCount; 5292 5293 if ((static_cast<size_t>(head.position()) >= head.buffer()->size()) 5294 || mTrimQueueHeadOnRelease) { 5295 trimTimedBufferQueueHead_l("releaseBuffer"); 5296 mTrimQueueHeadOnRelease = false; 5297 } 5298 } else { 5299 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no" 5300 " buffers in the timed buffer queue"); 5301 } 5302 5303done: 5304 buffer->raw = 0; 5305 buffer->frameCount = 0; 5306} 5307 5308size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const { 5309 Mutex::Autolock _l(mTimedBufferQueueLock); 5310 return mFramesPendingInQueue; 5311} 5312 5313AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer() 5314 : mPTS(0), mPosition(0) {} 5315 5316AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer( 5317 const sp<IMemory>& buffer, int64_t pts) 5318 : mBuffer(buffer), mPTS(pts), mPosition(0) {} 5319 5320// ---------------------------------------------------------------------------- 5321 5322// RecordTrack constructor must be called with AudioFlinger::mLock held 5323AudioFlinger::RecordThread::RecordTrack::RecordTrack( 5324 RecordThread *thread, 5325 const sp<Client>& client, 5326 uint32_t sampleRate, 5327 audio_format_t format, 5328 uint32_t channelMask, 5329 int frameCount, 5330 int sessionId) 5331 : TrackBase(thread, client, sampleRate, format, 5332 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId), 5333 mOverflow(false) 5334{ 5335 if (mCblk != NULL) { 5336 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer); 5337 if (format == AUDIO_FORMAT_PCM_16_BIT) { 5338 mCblk->frameSize = mChannelCount * sizeof(int16_t); 5339 } else if (format == AUDIO_FORMAT_PCM_8_BIT) { 5340 mCblk->frameSize = mChannelCount * sizeof(int8_t); 5341 } else { 5342 mCblk->frameSize = sizeof(int8_t); 5343 } 5344 } 5345} 5346 5347AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 5348{ 5349 sp<ThreadBase> thread = mThread.promote(); 5350 if (thread != 0) { 5351 AudioSystem::releaseInput(thread->id()); 5352 } 5353} 5354 5355// AudioBufferProvider interface 5356status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 5357{ 5358 audio_track_cblk_t* cblk = this->cblk(); 5359 uint32_t framesAvail; 5360 uint32_t framesReq = buffer->frameCount; 5361 5362 // Check if last stepServer failed, try to step now 5363 if (mStepServerFailed) { 5364 if (!step()) goto getNextBuffer_exit; 5365 ALOGV("stepServer recovered"); 5366 mStepServerFailed = false; 5367 } 5368 5369 framesAvail = cblk->framesAvailable_l(); 5370 5371 if (CC_LIKELY(framesAvail)) { 5372 uint32_t s = cblk->server; 5373 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 5374 5375 if (framesReq > framesAvail) { 5376 framesReq = framesAvail; 5377 } 5378 if (framesReq > bufferEnd - s) { 5379 framesReq = bufferEnd - s; 5380 } 5381 5382 buffer->raw = getBuffer(s, framesReq); 5383 if (buffer->raw == NULL) goto getNextBuffer_exit; 5384 5385 buffer->frameCount = framesReq; 5386 return NO_ERROR; 5387 } 5388 5389getNextBuffer_exit: 5390 buffer->raw = NULL; 5391 buffer->frameCount = 0; 5392 return NOT_ENOUGH_DATA; 5393} 5394 5395status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event, 5396 int triggerSession) 5397{ 5398 sp<ThreadBase> thread = mThread.promote(); 5399 if (thread != 0) { 5400 RecordThread *recordThread = (RecordThread *)thread.get(); 5401 return recordThread->start(this, event, triggerSession); 5402 } else { 5403 return BAD_VALUE; 5404 } 5405} 5406 5407void AudioFlinger::RecordThread::RecordTrack::stop() 5408{ 5409 sp<ThreadBase> thread = mThread.promote(); 5410 if (thread != 0) { 5411 RecordThread *recordThread = (RecordThread *)thread.get(); 5412 recordThread->stop(this); 5413 TrackBase::reset(); 5414 // Force overrun condition to avoid false overrun callback until first data is 5415 // read from buffer 5416 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 5417 } 5418} 5419 5420void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 5421{ 5422 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n", 5423 (mClient == 0) ? getpid_cached : mClient->pid(), 5424 mFormat, 5425 mChannelMask, 5426 mSessionId, 5427 mFrameCount, 5428 mState, 5429 mCblk->sampleRate, 5430 mCblk->server, 5431 mCblk->user); 5432} 5433 5434 5435// ---------------------------------------------------------------------------- 5436 5437AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 5438 PlaybackThread *playbackThread, 5439 DuplicatingThread *sourceThread, 5440 uint32_t sampleRate, 5441 audio_format_t format, 5442 uint32_t channelMask, 5443 int frameCount) 5444 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, 5445 NULL, 0, IAudioFlinger::TRACK_DEFAULT), 5446 mActive(false), mSourceThread(sourceThread) 5447{ 5448 5449 if (mCblk != NULL) { 5450 mCblk->flags |= CBLK_DIRECTION_OUT; 5451 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); 5452 mOutBuffer.frameCount = 0; 5453 playbackThread->mTracks.add(this); 5454 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \ 5455 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p", 5456 mCblk, mBuffer, mCblk->buffers, 5457 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd); 5458 } else { 5459 ALOGW("Error creating output track on thread %p", playbackThread); 5460 } 5461} 5462 5463AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 5464{ 5465 clearBufferQueue(); 5466} 5467 5468status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event, 5469 int triggerSession) 5470{ 5471 status_t status = Track::start(event, triggerSession); 5472 if (status != NO_ERROR) { 5473 return status; 5474 } 5475 5476 mActive = true; 5477 mRetryCount = 127; 5478 return status; 5479} 5480 5481void AudioFlinger::PlaybackThread::OutputTrack::stop() 5482{ 5483 Track::stop(); 5484 clearBufferQueue(); 5485 mOutBuffer.frameCount = 0; 5486 mActive = false; 5487} 5488 5489bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 5490{ 5491 Buffer *pInBuffer; 5492 Buffer inBuffer; 5493 uint32_t channelCount = mChannelCount; 5494 bool outputBufferFull = false; 5495 inBuffer.frameCount = frames; 5496 inBuffer.i16 = data; 5497 5498 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 5499 5500 if (!mActive && frames != 0) { 5501 start(); 5502 sp<ThreadBase> thread = mThread.promote(); 5503 if (thread != 0) { 5504 MixerThread *mixerThread = (MixerThread *)thread.get(); 5505 if (mCblk->frameCount > frames){ 5506 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 5507 uint32_t startFrames = (mCblk->frameCount - frames); 5508 pInBuffer = new Buffer; 5509 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 5510 pInBuffer->frameCount = startFrames; 5511 pInBuffer->i16 = pInBuffer->mBuffer; 5512 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 5513 mBufferQueue.add(pInBuffer); 5514 } else { 5515 ALOGW ("OutputTrack::write() %p no more buffers in queue", this); 5516 } 5517 } 5518 } 5519 } 5520 5521 while (waitTimeLeftMs) { 5522 // First write pending buffers, then new data 5523 if (mBufferQueue.size()) { 5524 pInBuffer = mBufferQueue.itemAt(0); 5525 } else { 5526 pInBuffer = &inBuffer; 5527 } 5528 5529 if (pInBuffer->frameCount == 0) { 5530 break; 5531 } 5532 5533 if (mOutBuffer.frameCount == 0) { 5534 mOutBuffer.frameCount = pInBuffer->frameCount; 5535 nsecs_t startTime = systemTime(); 5536 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) { 5537 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get()); 5538 outputBufferFull = true; 5539 break; 5540 } 5541 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 5542 if (waitTimeLeftMs >= waitTimeMs) { 5543 waitTimeLeftMs -= waitTimeMs; 5544 } else { 5545 waitTimeLeftMs = 0; 5546 } 5547 } 5548 5549 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount; 5550 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 5551 mCblk->stepUser(outFrames); 5552 pInBuffer->frameCount -= outFrames; 5553 pInBuffer->i16 += outFrames * channelCount; 5554 mOutBuffer.frameCount -= outFrames; 5555 mOutBuffer.i16 += outFrames * channelCount; 5556 5557 if (pInBuffer->frameCount == 0) { 5558 if (mBufferQueue.size()) { 5559 mBufferQueue.removeAt(0); 5560 delete [] pInBuffer->mBuffer; 5561 delete pInBuffer; 5562 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 5563 } else { 5564 break; 5565 } 5566 } 5567 } 5568 5569 // If we could not write all frames, allocate a buffer and queue it for next time. 5570 if (inBuffer.frameCount) { 5571 sp<ThreadBase> thread = mThread.promote(); 5572 if (thread != 0 && !thread->standby()) { 5573 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 5574 pInBuffer = new Buffer; 5575 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 5576 pInBuffer->frameCount = inBuffer.frameCount; 5577 pInBuffer->i16 = pInBuffer->mBuffer; 5578 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t)); 5579 mBufferQueue.add(pInBuffer); 5580 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 5581 } else { 5582 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this); 5583 } 5584 } 5585 } 5586 5587 // Calling write() with a 0 length buffer, means that no more data will be written: 5588 // If no more buffers are pending, fill output track buffer to make sure it is started 5589 // by output mixer. 5590 if (frames == 0 && mBufferQueue.size() == 0) { 5591 if (mCblk->user < mCblk->frameCount) { 5592 frames = mCblk->frameCount - mCblk->user; 5593 pInBuffer = new Buffer; 5594 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 5595 pInBuffer->frameCount = frames; 5596 pInBuffer->i16 = pInBuffer->mBuffer; 5597 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 5598 mBufferQueue.add(pInBuffer); 5599 } else if (mActive) { 5600 stop(); 5601 } 5602 } 5603 5604 return outputBufferFull; 5605} 5606 5607status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 5608{ 5609 int active; 5610 status_t result; 5611 audio_track_cblk_t* cblk = mCblk; 5612 uint32_t framesReq = buffer->frameCount; 5613 5614// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server); 5615 buffer->frameCount = 0; 5616 5617 uint32_t framesAvail = cblk->framesAvailable(); 5618 5619 5620 if (framesAvail == 0) { 5621 Mutex::Autolock _l(cblk->lock); 5622 goto start_loop_here; 5623 while (framesAvail == 0) { 5624 active = mActive; 5625 if (CC_UNLIKELY(!active)) { 5626 ALOGV("Not active and NO_MORE_BUFFERS"); 5627 return NO_MORE_BUFFERS; 5628 } 5629 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 5630 if (result != NO_ERROR) { 5631 return NO_MORE_BUFFERS; 5632 } 5633 // read the server count again 5634 start_loop_here: 5635 framesAvail = cblk->framesAvailable_l(); 5636 } 5637 } 5638 5639// if (framesAvail < framesReq) { 5640// return NO_MORE_BUFFERS; 5641// } 5642 5643 if (framesReq > framesAvail) { 5644 framesReq = framesAvail; 5645 } 5646 5647 uint32_t u = cblk->user; 5648 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 5649 5650 if (framesReq > bufferEnd - u) { 5651 framesReq = bufferEnd - u; 5652 } 5653 5654 buffer->frameCount = framesReq; 5655 buffer->raw = (void *)cblk->buffer(u); 5656 return NO_ERROR; 5657} 5658 5659 5660void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 5661{ 5662 size_t size = mBufferQueue.size(); 5663 5664 for (size_t i = 0; i < size; i++) { 5665 Buffer *pBuffer = mBufferQueue.itemAt(i); 5666 delete [] pBuffer->mBuffer; 5667 delete pBuffer; 5668 } 5669 mBufferQueue.clear(); 5670} 5671 5672// ---------------------------------------------------------------------------- 5673 5674AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 5675 : RefBase(), 5676 mAudioFlinger(audioFlinger), 5677 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 5678 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 5679 mPid(pid), 5680 mTimedTrackCount(0) 5681{ 5682 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 5683} 5684 5685// Client destructor must be called with AudioFlinger::mLock held 5686AudioFlinger::Client::~Client() 5687{ 5688 mAudioFlinger->removeClient_l(mPid); 5689} 5690 5691sp<MemoryDealer> AudioFlinger::Client::heap() const 5692{ 5693 return mMemoryDealer; 5694} 5695 5696// Reserve one of the limited slots for a timed audio track associated 5697// with this client 5698bool AudioFlinger::Client::reserveTimedTrack() 5699{ 5700 const int kMaxTimedTracksPerClient = 4; 5701 5702 Mutex::Autolock _l(mTimedTrackLock); 5703 5704 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 5705 ALOGW("can not create timed track - pid %d has exceeded the limit", 5706 mPid); 5707 return false; 5708 } 5709 5710 mTimedTrackCount++; 5711 return true; 5712} 5713 5714// Release a slot for a timed audio track 5715void AudioFlinger::Client::releaseTimedTrack() 5716{ 5717 Mutex::Autolock _l(mTimedTrackLock); 5718 mTimedTrackCount--; 5719} 5720 5721// ---------------------------------------------------------------------------- 5722 5723AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 5724 const sp<IAudioFlingerClient>& client, 5725 pid_t pid) 5726 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 5727{ 5728} 5729 5730AudioFlinger::NotificationClient::~NotificationClient() 5731{ 5732} 5733 5734void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 5735{ 5736 sp<NotificationClient> keep(this); 5737 mAudioFlinger->removeNotificationClient(mPid); 5738} 5739 5740// ---------------------------------------------------------------------------- 5741 5742AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 5743 : BnAudioTrack(), 5744 mTrack(track) 5745{ 5746} 5747 5748AudioFlinger::TrackHandle::~TrackHandle() { 5749 // just stop the track on deletion, associated resources 5750 // will be freed from the main thread once all pending buffers have 5751 // been played. Unless it's not in the active track list, in which 5752 // case we free everything now... 5753 mTrack->destroy(); 5754} 5755 5756sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 5757 return mTrack->getCblk(); 5758} 5759 5760status_t AudioFlinger::TrackHandle::start() { 5761 return mTrack->start(); 5762} 5763 5764void AudioFlinger::TrackHandle::stop() { 5765 mTrack->stop(); 5766} 5767 5768void AudioFlinger::TrackHandle::flush() { 5769 mTrack->flush(); 5770} 5771 5772void AudioFlinger::TrackHandle::mute(bool e) { 5773 mTrack->mute(e); 5774} 5775 5776void AudioFlinger::TrackHandle::pause() { 5777 mTrack->pause(); 5778} 5779 5780status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 5781{ 5782 return mTrack->attachAuxEffect(EffectId); 5783} 5784 5785status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size, 5786 sp<IMemory>* buffer) { 5787 if (!mTrack->isTimedTrack()) 5788 return INVALID_OPERATION; 5789 5790 PlaybackThread::TimedTrack* tt = 5791 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 5792 return tt->allocateTimedBuffer(size, buffer); 5793} 5794 5795status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer, 5796 int64_t pts) { 5797 if (!mTrack->isTimedTrack()) 5798 return INVALID_OPERATION; 5799 5800 PlaybackThread::TimedTrack* tt = 5801 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 5802 return tt->queueTimedBuffer(buffer, pts); 5803} 5804 5805status_t AudioFlinger::TrackHandle::setMediaTimeTransform( 5806 const LinearTransform& xform, int target) { 5807 5808 if (!mTrack->isTimedTrack()) 5809 return INVALID_OPERATION; 5810 5811 PlaybackThread::TimedTrack* tt = 5812 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 5813 return tt->setMediaTimeTransform( 5814 xform, static_cast<TimedAudioTrack::TargetTimeline>(target)); 5815} 5816 5817status_t AudioFlinger::TrackHandle::onTransact( 5818 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 5819{ 5820 return BnAudioTrack::onTransact(code, data, reply, flags); 5821} 5822 5823// ---------------------------------------------------------------------------- 5824 5825sp<IAudioRecord> AudioFlinger::openRecord( 5826 pid_t pid, 5827 audio_io_handle_t input, 5828 uint32_t sampleRate, 5829 audio_format_t format, 5830 uint32_t channelMask, 5831 int frameCount, 5832 IAudioFlinger::track_flags_t flags, 5833 int *sessionId, 5834 status_t *status) 5835{ 5836 sp<RecordThread::RecordTrack> recordTrack; 5837 sp<RecordHandle> recordHandle; 5838 sp<Client> client; 5839 status_t lStatus; 5840 RecordThread *thread; 5841 size_t inFrameCount; 5842 int lSessionId; 5843 5844 // check calling permissions 5845 if (!recordingAllowed()) { 5846 lStatus = PERMISSION_DENIED; 5847 goto Exit; 5848 } 5849 5850 // add client to list 5851 { // scope for mLock 5852 Mutex::Autolock _l(mLock); 5853 thread = checkRecordThread_l(input); 5854 if (thread == NULL) { 5855 lStatus = BAD_VALUE; 5856 goto Exit; 5857 } 5858 5859 client = registerPid_l(pid); 5860 5861 // If no audio session id is provided, create one here 5862 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 5863 lSessionId = *sessionId; 5864 } else { 5865 lSessionId = nextUniqueId(); 5866 if (sessionId != NULL) { 5867 *sessionId = lSessionId; 5868 } 5869 } 5870 // create new record track. The record track uses one track in mHardwareMixerThread by convention. 5871 recordTrack = thread->createRecordTrack_l(client, 5872 sampleRate, 5873 format, 5874 channelMask, 5875 frameCount, 5876 lSessionId, 5877 &lStatus); 5878 } 5879 if (lStatus != NO_ERROR) { 5880 // remove local strong reference to Client before deleting the RecordTrack so that the Client 5881 // destructor is called by the TrackBase destructor with mLock held 5882 client.clear(); 5883 recordTrack.clear(); 5884 goto Exit; 5885 } 5886 5887 // return to handle to client 5888 recordHandle = new RecordHandle(recordTrack); 5889 lStatus = NO_ERROR; 5890 5891Exit: 5892 if (status) { 5893 *status = lStatus; 5894 } 5895 return recordHandle; 5896} 5897 5898// ---------------------------------------------------------------------------- 5899 5900AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 5901 : BnAudioRecord(), 5902 mRecordTrack(recordTrack) 5903{ 5904} 5905 5906AudioFlinger::RecordHandle::~RecordHandle() { 5907 stop(); 5908} 5909 5910sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 5911 return mRecordTrack->getCblk(); 5912} 5913 5914status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) { 5915 ALOGV("RecordHandle::start()"); 5916 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession); 5917} 5918 5919void AudioFlinger::RecordHandle::stop() { 5920 ALOGV("RecordHandle::stop()"); 5921 mRecordTrack->stop(); 5922} 5923 5924status_t AudioFlinger::RecordHandle::onTransact( 5925 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 5926{ 5927 return BnAudioRecord::onTransact(code, data, reply, flags); 5928} 5929 5930// ---------------------------------------------------------------------------- 5931 5932AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 5933 AudioStreamIn *input, 5934 uint32_t sampleRate, 5935 uint32_t channels, 5936 audio_io_handle_t id, 5937 uint32_t device) : 5938 ThreadBase(audioFlinger, id, device, RECORD), 5939 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 5940 // mRsmpInIndex and mInputBytes set by readInputParameters() 5941 mReqChannelCount(popcount(channels)), 5942 mReqSampleRate(sampleRate) 5943 // mBytesRead is only meaningful while active, and so is cleared in start() 5944 // (but might be better to also clear here for dump?) 5945{ 5946 snprintf(mName, kNameLength, "AudioIn_%X", id); 5947 5948 readInputParameters(); 5949} 5950 5951 5952AudioFlinger::RecordThread::~RecordThread() 5953{ 5954 delete[] mRsmpInBuffer; 5955 delete mResampler; 5956 delete[] mRsmpOutBuffer; 5957} 5958 5959void AudioFlinger::RecordThread::onFirstRef() 5960{ 5961 run(mName, PRIORITY_URGENT_AUDIO); 5962} 5963 5964status_t AudioFlinger::RecordThread::readyToRun() 5965{ 5966 status_t status = initCheck(); 5967 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); 5968 return status; 5969} 5970 5971bool AudioFlinger::RecordThread::threadLoop() 5972{ 5973 AudioBufferProvider::Buffer buffer; 5974 sp<RecordTrack> activeTrack; 5975 Vector< sp<EffectChain> > effectChains; 5976 5977 nsecs_t lastWarning = 0; 5978 5979 acquireWakeLock(); 5980 5981 // start recording 5982 while (!exitPending()) { 5983 5984 processConfigEvents(); 5985 5986 { // scope for mLock 5987 Mutex::Autolock _l(mLock); 5988 checkForNewParameters_l(); 5989 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 5990 if (!mStandby) { 5991 mInput->stream->common.standby(&mInput->stream->common); 5992 mStandby = true; 5993 } 5994 5995 if (exitPending()) break; 5996 5997 releaseWakeLock_l(); 5998 ALOGV("RecordThread: loop stopping"); 5999 // go to sleep 6000 mWaitWorkCV.wait(mLock); 6001 ALOGV("RecordThread: loop starting"); 6002 acquireWakeLock_l(); 6003 continue; 6004 } 6005 if (mActiveTrack != 0) { 6006 if (mActiveTrack->mState == TrackBase::PAUSING) { 6007 if (!mStandby) { 6008 mInput->stream->common.standby(&mInput->stream->common); 6009 mStandby = true; 6010 } 6011 mActiveTrack.clear(); 6012 mStartStopCond.broadcast(); 6013 } else if (mActiveTrack->mState == TrackBase::RESUMING) { 6014 if (mReqChannelCount != mActiveTrack->channelCount()) { 6015 mActiveTrack.clear(); 6016 mStartStopCond.broadcast(); 6017 } else if (mBytesRead != 0) { 6018 // record start succeeds only if first read from audio input 6019 // succeeds 6020 if (mBytesRead > 0) { 6021 mActiveTrack->mState = TrackBase::ACTIVE; 6022 } else { 6023 mActiveTrack.clear(); 6024 } 6025 mStartStopCond.broadcast(); 6026 } 6027 mStandby = false; 6028 } 6029 } 6030 lockEffectChains_l(effectChains); 6031 } 6032 6033 if (mActiveTrack != 0) { 6034 if (mActiveTrack->mState != TrackBase::ACTIVE && 6035 mActiveTrack->mState != TrackBase::RESUMING) { 6036 unlockEffectChains(effectChains); 6037 usleep(kRecordThreadSleepUs); 6038 continue; 6039 } 6040 for (size_t i = 0; i < effectChains.size(); i ++) { 6041 effectChains[i]->process_l(); 6042 } 6043 6044 buffer.frameCount = mFrameCount; 6045 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) { 6046 size_t framesOut = buffer.frameCount; 6047 if (mResampler == NULL) { 6048 // no resampling 6049 while (framesOut) { 6050 size_t framesIn = mFrameCount - mRsmpInIndex; 6051 if (framesIn) { 6052 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 6053 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize; 6054 if (framesIn > framesOut) 6055 framesIn = framesOut; 6056 mRsmpInIndex += framesIn; 6057 framesOut -= framesIn; 6058 if ((int)mChannelCount == mReqChannelCount || 6059 mFormat != AUDIO_FORMAT_PCM_16_BIT) { 6060 memcpy(dst, src, framesIn * mFrameSize); 6061 } else { 6062 int16_t *src16 = (int16_t *)src; 6063 int16_t *dst16 = (int16_t *)dst; 6064 if (mChannelCount == 1) { 6065 while (framesIn--) { 6066 *dst16++ = *src16; 6067 *dst16++ = *src16++; 6068 } 6069 } else { 6070 while (framesIn--) { 6071 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1); 6072 src16 += 2; 6073 } 6074 } 6075 } 6076 } 6077 if (framesOut && mFrameCount == mRsmpInIndex) { 6078 if (framesOut == mFrameCount && 6079 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) { 6080 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes); 6081 framesOut = 0; 6082 } else { 6083 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 6084 mRsmpInIndex = 0; 6085 } 6086 if (mBytesRead < 0) { 6087 ALOGE("Error reading audio input"); 6088 if (mActiveTrack->mState == TrackBase::ACTIVE) { 6089 // Force input into standby so that it tries to 6090 // recover at next read attempt 6091 mInput->stream->common.standby(&mInput->stream->common); 6092 usleep(kRecordThreadSleepUs); 6093 } 6094 mRsmpInIndex = mFrameCount; 6095 framesOut = 0; 6096 buffer.frameCount = 0; 6097 } 6098 } 6099 } 6100 } else { 6101 // resampling 6102 6103 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t)); 6104 // alter output frame count as if we were expecting stereo samples 6105 if (mChannelCount == 1 && mReqChannelCount == 1) { 6106 framesOut >>= 1; 6107 } 6108 mResampler->resample(mRsmpOutBuffer, framesOut, this); 6109 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer() 6110 // are 32 bit aligned which should be always true. 6111 if (mChannelCount == 2 && mReqChannelCount == 1) { 6112 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 6113 // the resampler always outputs stereo samples: do post stereo to mono conversion 6114 int16_t *src = (int16_t *)mRsmpOutBuffer; 6115 int16_t *dst = buffer.i16; 6116 while (framesOut--) { 6117 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1); 6118 src += 2; 6119 } 6120 } else { 6121 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 6122 } 6123 6124 } 6125 if (mFramestoDrop == 0) { 6126 mActiveTrack->releaseBuffer(&buffer); 6127 } else { 6128 if (mFramestoDrop > 0) { 6129 mFramestoDrop -= buffer.frameCount; 6130 if (mFramestoDrop <= 0) { 6131 clearSyncStartEvent(); 6132 } 6133 } else { 6134 mFramestoDrop += buffer.frameCount; 6135 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 6136 mSyncStartEvent->isCancelled()) { 6137 ALOGW("Synced record %s, session %d, trigger session %d", 6138 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 6139 mActiveTrack->sessionId(), 6140 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 6141 clearSyncStartEvent(); 6142 } 6143 } 6144 } 6145 mActiveTrack->overflow(); 6146 } 6147 // client isn't retrieving buffers fast enough 6148 else { 6149 if (!mActiveTrack->setOverflow()) { 6150 nsecs_t now = systemTime(); 6151 if ((now - lastWarning) > kWarningThrottleNs) { 6152 ALOGW("RecordThread: buffer overflow"); 6153 lastWarning = now; 6154 } 6155 } 6156 // Release the processor for a while before asking for a new buffer. 6157 // This will give the application more chance to read from the buffer and 6158 // clear the overflow. 6159 usleep(kRecordThreadSleepUs); 6160 } 6161 } 6162 // enable changes in effect chain 6163 unlockEffectChains(effectChains); 6164 effectChains.clear(); 6165 } 6166 6167 if (!mStandby) { 6168 mInput->stream->common.standby(&mInput->stream->common); 6169 } 6170 mActiveTrack.clear(); 6171 6172 mStartStopCond.broadcast(); 6173 6174 releaseWakeLock(); 6175 6176 ALOGV("RecordThread %p exiting", this); 6177 return false; 6178} 6179 6180 6181sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 6182 const sp<AudioFlinger::Client>& client, 6183 uint32_t sampleRate, 6184 audio_format_t format, 6185 int channelMask, 6186 int frameCount, 6187 int sessionId, 6188 status_t *status) 6189{ 6190 sp<RecordTrack> track; 6191 status_t lStatus; 6192 6193 lStatus = initCheck(); 6194 if (lStatus != NO_ERROR) { 6195 ALOGE("Audio driver not initialized."); 6196 goto Exit; 6197 } 6198 6199 { // scope for mLock 6200 Mutex::Autolock _l(mLock); 6201 6202 track = new RecordTrack(this, client, sampleRate, 6203 format, channelMask, frameCount, sessionId); 6204 6205 if (track->getCblk() == 0) { 6206 lStatus = NO_MEMORY; 6207 goto Exit; 6208 } 6209 6210 mTrack = track.get(); 6211 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6212 bool suspend = audio_is_bluetooth_sco_device( 6213 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff(); 6214 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 6215 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 6216 } 6217 lStatus = NO_ERROR; 6218 6219Exit: 6220 if (status) { 6221 *status = lStatus; 6222 } 6223 return track; 6224} 6225 6226status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 6227 AudioSystem::sync_event_t event, 6228 int triggerSession) 6229{ 6230 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 6231 sp<ThreadBase> strongMe = this; 6232 status_t status = NO_ERROR; 6233 6234 if (event == AudioSystem::SYNC_EVENT_NONE) { 6235 clearSyncStartEvent(); 6236 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 6237 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 6238 triggerSession, 6239 recordTrack->sessionId(), 6240 syncStartEventCallback, 6241 this); 6242 // Sync event can be cancelled by the trigger session if the track is not in a 6243 // compatible state in which case we start record immediately 6244 if (mSyncStartEvent->isCancelled()) { 6245 clearSyncStartEvent(); 6246 } else { 6247 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 6248 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 6249 } 6250 } 6251 6252 { 6253 AutoMutex lock(mLock); 6254 if (mActiveTrack != 0) { 6255 if (recordTrack != mActiveTrack.get()) { 6256 status = -EBUSY; 6257 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 6258 mActiveTrack->mState = TrackBase::ACTIVE; 6259 } 6260 return status; 6261 } 6262 6263 recordTrack->mState = TrackBase::IDLE; 6264 mActiveTrack = recordTrack; 6265 mLock.unlock(); 6266 status_t status = AudioSystem::startInput(mId); 6267 mLock.lock(); 6268 if (status != NO_ERROR) { 6269 mActiveTrack.clear(); 6270 clearSyncStartEvent(); 6271 return status; 6272 } 6273 mRsmpInIndex = mFrameCount; 6274 mBytesRead = 0; 6275 if (mResampler != NULL) { 6276 mResampler->reset(); 6277 } 6278 mActiveTrack->mState = TrackBase::RESUMING; 6279 // signal thread to start 6280 ALOGV("Signal record thread"); 6281 mWaitWorkCV.signal(); 6282 // do not wait for mStartStopCond if exiting 6283 if (exitPending()) { 6284 mActiveTrack.clear(); 6285 status = INVALID_OPERATION; 6286 goto startError; 6287 } 6288 mStartStopCond.wait(mLock); 6289 if (mActiveTrack == 0) { 6290 ALOGV("Record failed to start"); 6291 status = BAD_VALUE; 6292 goto startError; 6293 } 6294 ALOGV("Record started OK"); 6295 return status; 6296 } 6297startError: 6298 AudioSystem::stopInput(mId); 6299 clearSyncStartEvent(); 6300 return status; 6301} 6302 6303void AudioFlinger::RecordThread::clearSyncStartEvent() 6304{ 6305 if (mSyncStartEvent != 0) { 6306 mSyncStartEvent->cancel(); 6307 } 6308 mSyncStartEvent.clear(); 6309 mFramestoDrop = 0; 6310} 6311 6312void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 6313{ 6314 sp<SyncEvent> strongEvent = event.promote(); 6315 6316 if (strongEvent != 0) { 6317 RecordThread *me = (RecordThread *)strongEvent->cookie(); 6318 me->handleSyncStartEvent(strongEvent); 6319 } 6320} 6321 6322void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 6323{ 6324 if (event == mSyncStartEvent) { 6325 // TODO: use actual buffer filling status instead of 2 buffers when info is available 6326 // from audio HAL 6327 mFramestoDrop = mFrameCount * 2; 6328 } 6329} 6330 6331void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 6332 ALOGV("RecordThread::stop"); 6333 sp<ThreadBase> strongMe = this; 6334 { 6335 AutoMutex lock(mLock); 6336 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) { 6337 mActiveTrack->mState = TrackBase::PAUSING; 6338 // do not wait for mStartStopCond if exiting 6339 if (exitPending()) { 6340 return; 6341 } 6342 mStartStopCond.wait(mLock); 6343 // if we have been restarted, recordTrack == mActiveTrack.get() here 6344 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) { 6345 mLock.unlock(); 6346 AudioSystem::stopInput(mId); 6347 mLock.lock(); 6348 ALOGV("Record stopped OK"); 6349 } 6350 } 6351 } 6352} 6353 6354bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) 6355{ 6356 return false; 6357} 6358 6359status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) 6360{ 6361 if (!isValidSyncEvent(event)) { 6362 return BAD_VALUE; 6363 } 6364 6365 Mutex::Autolock _l(mLock); 6366 6367 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) { 6368 mTrack->setSyncEvent(event); 6369 return NO_ERROR; 6370 } 6371 return NAME_NOT_FOUND; 6372} 6373 6374status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 6375{ 6376 const size_t SIZE = 256; 6377 char buffer[SIZE]; 6378 String8 result; 6379 6380 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 6381 result.append(buffer); 6382 6383 if (mActiveTrack != 0) { 6384 result.append("Active Track:\n"); 6385 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n"); 6386 mActiveTrack->dump(buffer, SIZE); 6387 result.append(buffer); 6388 6389 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 6390 result.append(buffer); 6391 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes); 6392 result.append(buffer); 6393 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 6394 result.append(buffer); 6395 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount); 6396 result.append(buffer); 6397 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate); 6398 result.append(buffer); 6399 6400 6401 } else { 6402 result.append("No record client\n"); 6403 } 6404 write(fd, result.string(), result.size()); 6405 6406 dumpBase(fd, args); 6407 dumpEffectChains(fd, args); 6408 6409 return NO_ERROR; 6410} 6411 6412// AudioBufferProvider interface 6413status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 6414{ 6415 size_t framesReq = buffer->frameCount; 6416 size_t framesReady = mFrameCount - mRsmpInIndex; 6417 int channelCount; 6418 6419 if (framesReady == 0) { 6420 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 6421 if (mBytesRead < 0) { 6422 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 6423 if (mActiveTrack->mState == TrackBase::ACTIVE) { 6424 // Force input into standby so that it tries to 6425 // recover at next read attempt 6426 mInput->stream->common.standby(&mInput->stream->common); 6427 usleep(kRecordThreadSleepUs); 6428 } 6429 buffer->raw = NULL; 6430 buffer->frameCount = 0; 6431 return NOT_ENOUGH_DATA; 6432 } 6433 mRsmpInIndex = 0; 6434 framesReady = mFrameCount; 6435 } 6436 6437 if (framesReq > framesReady) { 6438 framesReq = framesReady; 6439 } 6440 6441 if (mChannelCount == 1 && mReqChannelCount == 2) { 6442 channelCount = 1; 6443 } else { 6444 channelCount = 2; 6445 } 6446 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 6447 buffer->frameCount = framesReq; 6448 return NO_ERROR; 6449} 6450 6451// AudioBufferProvider interface 6452void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 6453{ 6454 mRsmpInIndex += buffer->frameCount; 6455 buffer->frameCount = 0; 6456} 6457 6458bool AudioFlinger::RecordThread::checkForNewParameters_l() 6459{ 6460 bool reconfig = false; 6461 6462 while (!mNewParameters.isEmpty()) { 6463 status_t status = NO_ERROR; 6464 String8 keyValuePair = mNewParameters[0]; 6465 AudioParameter param = AudioParameter(keyValuePair); 6466 int value; 6467 audio_format_t reqFormat = mFormat; 6468 int reqSamplingRate = mReqSampleRate; 6469 int reqChannelCount = mReqChannelCount; 6470 6471 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 6472 reqSamplingRate = value; 6473 reconfig = true; 6474 } 6475 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 6476 reqFormat = (audio_format_t) value; 6477 reconfig = true; 6478 } 6479 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 6480 reqChannelCount = popcount(value); 6481 reconfig = true; 6482 } 6483 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 6484 // do not accept frame count changes if tracks are open as the track buffer 6485 // size depends on frame count and correct behavior would not be guaranteed 6486 // if frame count is changed after track creation 6487 if (mActiveTrack != 0) { 6488 status = INVALID_OPERATION; 6489 } else { 6490 reconfig = true; 6491 } 6492 } 6493 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 6494 // forward device change to effects that have requested to be 6495 // aware of attached audio device. 6496 for (size_t i = 0; i < mEffectChains.size(); i++) { 6497 mEffectChains[i]->setDevice_l(value); 6498 } 6499 // store input device and output device but do not forward output device to audio HAL. 6500 // Note that status is ignored by the caller for output device 6501 // (see AudioFlinger::setParameters() 6502 if (value & AUDIO_DEVICE_OUT_ALL) { 6503 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL); 6504 status = BAD_VALUE; 6505 } else { 6506 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL); 6507 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6508 if (mTrack != NULL) { 6509 bool suspend = audio_is_bluetooth_sco_device( 6510 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff(); 6511 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId()); 6512 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId()); 6513 } 6514 } 6515 mDevice |= (uint32_t)value; 6516 } 6517 if (status == NO_ERROR) { 6518 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 6519 if (status == INVALID_OPERATION) { 6520 mInput->stream->common.standby(&mInput->stream->common); 6521 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6522 keyValuePair.string()); 6523 } 6524 if (reconfig) { 6525 if (status == BAD_VALUE && 6526 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 6527 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 6528 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) && 6529 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 && 6530 (reqChannelCount <= FCC_2)) { 6531 status = NO_ERROR; 6532 } 6533 if (status == NO_ERROR) { 6534 readInputParameters(); 6535 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 6536 } 6537 } 6538 } 6539 6540 mNewParameters.removeAt(0); 6541 6542 mParamStatus = status; 6543 mParamCond.signal(); 6544 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 6545 // already timed out waiting for the status and will never signal the condition. 6546 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 6547 } 6548 return reconfig; 6549} 6550 6551String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 6552{ 6553 char *s; 6554 String8 out_s8 = String8(); 6555 6556 Mutex::Autolock _l(mLock); 6557 if (initCheck() != NO_ERROR) { 6558 return out_s8; 6559 } 6560 6561 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 6562 out_s8 = String8(s); 6563 free(s); 6564 return out_s8; 6565} 6566 6567void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 6568 AudioSystem::OutputDescriptor desc; 6569 void *param2 = NULL; 6570 6571 switch (event) { 6572 case AudioSystem::INPUT_OPENED: 6573 case AudioSystem::INPUT_CONFIG_CHANGED: 6574 desc.channels = mChannelMask; 6575 desc.samplingRate = mSampleRate; 6576 desc.format = mFormat; 6577 desc.frameCount = mFrameCount; 6578 desc.latency = 0; 6579 param2 = &desc; 6580 break; 6581 6582 case AudioSystem::INPUT_CLOSED: 6583 default: 6584 break; 6585 } 6586 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 6587} 6588 6589void AudioFlinger::RecordThread::readInputParameters() 6590{ 6591 delete mRsmpInBuffer; 6592 // mRsmpInBuffer is always assigned a new[] below 6593 delete mRsmpOutBuffer; 6594 mRsmpOutBuffer = NULL; 6595 delete mResampler; 6596 mResampler = NULL; 6597 6598 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 6599 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 6600 mChannelCount = (uint16_t)popcount(mChannelMask); 6601 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 6602 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 6603 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common); 6604 mFrameCount = mInputBytes / mFrameSize; 6605 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects 6606 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 6607 6608 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) 6609 { 6610 int channelCount; 6611 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid 6612 // stereo to mono post process as the resampler always outputs stereo. 6613 if (mChannelCount == 1 && mReqChannelCount == 2) { 6614 channelCount = 1; 6615 } else { 6616 channelCount = 2; 6617 } 6618 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 6619 mResampler->setSampleRate(mSampleRate); 6620 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 6621 mRsmpOutBuffer = new int32_t[mFrameCount * 2]; 6622 6623 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples 6624 if (mChannelCount == 1 && mReqChannelCount == 1) { 6625 mFrameCount >>= 1; 6626 } 6627 6628 } 6629 mRsmpInIndex = mFrameCount; 6630} 6631 6632unsigned int AudioFlinger::RecordThread::getInputFramesLost() 6633{ 6634 Mutex::Autolock _l(mLock); 6635 if (initCheck() != NO_ERROR) { 6636 return 0; 6637 } 6638 6639 return mInput->stream->get_input_frames_lost(mInput->stream); 6640} 6641 6642uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) 6643{ 6644 Mutex::Autolock _l(mLock); 6645 uint32_t result = 0; 6646 if (getEffectChain_l(sessionId) != 0) { 6647 result = EFFECT_SESSION; 6648 } 6649 6650 if (mTrack != NULL && sessionId == mTrack->sessionId()) { 6651 result |= TRACK_SESSION; 6652 } 6653 6654 return result; 6655} 6656 6657AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track() 6658{ 6659 Mutex::Autolock _l(mLock); 6660 return mTrack; 6661} 6662 6663AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const 6664{ 6665 Mutex::Autolock _l(mLock); 6666 return mInput; 6667} 6668 6669AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 6670{ 6671 Mutex::Autolock _l(mLock); 6672 AudioStreamIn *input = mInput; 6673 mInput = NULL; 6674 return input; 6675} 6676 6677// this method must always be called either with ThreadBase mLock held or inside the thread loop 6678audio_stream_t* AudioFlinger::RecordThread::stream() const 6679{ 6680 if (mInput == NULL) { 6681 return NULL; 6682 } 6683 return &mInput->stream->common; 6684} 6685 6686 6687// ---------------------------------------------------------------------------- 6688 6689audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 6690{ 6691 if (!settingsAllowed()) { 6692 return 0; 6693 } 6694 Mutex::Autolock _l(mLock); 6695 return loadHwModule_l(name); 6696} 6697 6698// loadHwModule_l() must be called with AudioFlinger::mLock held 6699audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 6700{ 6701 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 6702 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 6703 ALOGW("loadHwModule() module %s already loaded", name); 6704 return mAudioHwDevs.keyAt(i); 6705 } 6706 } 6707 6708 audio_hw_device_t *dev; 6709 6710 int rc = load_audio_interface(name, &dev); 6711 if (rc) { 6712 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 6713 return 0; 6714 } 6715 6716 mHardwareStatus = AUDIO_HW_INIT; 6717 rc = dev->init_check(dev); 6718 mHardwareStatus = AUDIO_HW_IDLE; 6719 if (rc) { 6720 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 6721 return 0; 6722 } 6723 6724 if ((mMasterVolumeSupportLvl != MVS_NONE) && 6725 (NULL != dev->set_master_volume)) { 6726 AutoMutex lock(mHardwareLock); 6727 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 6728 dev->set_master_volume(dev, mMasterVolume); 6729 mHardwareStatus = AUDIO_HW_IDLE; 6730 } 6731 6732 audio_module_handle_t handle = nextUniqueId(); 6733 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev)); 6734 6735 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 6736 name, dev->common.module->name, dev->common.module->id, handle); 6737 6738 return handle; 6739 6740} 6741 6742audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 6743 audio_devices_t *pDevices, 6744 uint32_t *pSamplingRate, 6745 audio_format_t *pFormat, 6746 audio_channel_mask_t *pChannelMask, 6747 uint32_t *pLatencyMs, 6748 audio_output_flags_t flags) 6749{ 6750 status_t status; 6751 PlaybackThread *thread = NULL; 6752 struct audio_config config = { 6753 sample_rate: pSamplingRate ? *pSamplingRate : 0, 6754 channel_mask: pChannelMask ? *pChannelMask : 0, 6755 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT, 6756 }; 6757 audio_stream_out_t *outStream = NULL; 6758 audio_hw_device_t *outHwDev; 6759 6760 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x", 6761 module, 6762 (pDevices != NULL) ? (int)*pDevices : 0, 6763 config.sample_rate, 6764 config.format, 6765 config.channel_mask, 6766 flags); 6767 6768 if (pDevices == NULL || *pDevices == 0) { 6769 return 0; 6770 } 6771 6772 Mutex::Autolock _l(mLock); 6773 6774 outHwDev = findSuitableHwDev_l(module, *pDevices); 6775 if (outHwDev == NULL) 6776 return 0; 6777 6778 audio_io_handle_t id = nextUniqueId(); 6779 6780 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 6781 6782 status = outHwDev->open_output_stream(outHwDev, 6783 id, 6784 *pDevices, 6785 (audio_output_flags_t)flags, 6786 &config, 6787 &outStream); 6788 6789 mHardwareStatus = AUDIO_HW_IDLE; 6790 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d", 6791 outStream, 6792 config.sample_rate, 6793 config.format, 6794 config.channel_mask, 6795 status); 6796 6797 if (status == NO_ERROR && outStream != NULL) { 6798 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream); 6799 6800 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 6801 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 6802 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 6803 thread = new DirectOutputThread(this, output, id, *pDevices); 6804 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 6805 } else { 6806 thread = new MixerThread(this, output, id, *pDevices); 6807 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 6808 } 6809 mPlaybackThreads.add(id, thread); 6810 6811 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate; 6812 if (pFormat != NULL) *pFormat = config.format; 6813 if (pChannelMask != NULL) *pChannelMask = config.channel_mask; 6814 if (pLatencyMs != NULL) *pLatencyMs = thread->latency(); 6815 6816 // notify client processes of the new output creation 6817 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 6818 6819 // the first primary output opened designates the primary hw device 6820 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 6821 ALOGI("Using module %d has the primary audio interface", module); 6822 mPrimaryHardwareDev = outHwDev; 6823 6824 AutoMutex lock(mHardwareLock); 6825 mHardwareStatus = AUDIO_HW_SET_MODE; 6826 outHwDev->set_mode(outHwDev, mMode); 6827 6828 // Determine the level of master volume support the primary audio HAL has, 6829 // and set the initial master volume at the same time. 6830 float initialVolume = 1.0; 6831 mMasterVolumeSupportLvl = MVS_NONE; 6832 6833 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 6834 if ((NULL != outHwDev->get_master_volume) && 6835 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) { 6836 mMasterVolumeSupportLvl = MVS_FULL; 6837 } else { 6838 mMasterVolumeSupportLvl = MVS_SETONLY; 6839 initialVolume = 1.0; 6840 } 6841 6842 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 6843 if ((NULL == outHwDev->set_master_volume) || 6844 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) { 6845 mMasterVolumeSupportLvl = MVS_NONE; 6846 } 6847 // now that we have a primary device, initialize master volume on other devices 6848 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 6849 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 6850 6851 if ((dev != mPrimaryHardwareDev) && 6852 (NULL != dev->set_master_volume)) { 6853 dev->set_master_volume(dev, initialVolume); 6854 } 6855 } 6856 mHardwareStatus = AUDIO_HW_IDLE; 6857 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl) 6858 ? initialVolume 6859 : 1.0; 6860 mMasterVolume = initialVolume; 6861 } 6862 return id; 6863 } 6864 6865 return 0; 6866} 6867 6868audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 6869 audio_io_handle_t output2) 6870{ 6871 Mutex::Autolock _l(mLock); 6872 MixerThread *thread1 = checkMixerThread_l(output1); 6873 MixerThread *thread2 = checkMixerThread_l(output2); 6874 6875 if (thread1 == NULL || thread2 == NULL) { 6876 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2); 6877 return 0; 6878 } 6879 6880 audio_io_handle_t id = nextUniqueId(); 6881 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 6882 thread->addOutputTrack(thread2); 6883 mPlaybackThreads.add(id, thread); 6884 // notify client processes of the new output creation 6885 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 6886 return id; 6887} 6888 6889status_t AudioFlinger::closeOutput(audio_io_handle_t output) 6890{ 6891 // keep strong reference on the playback thread so that 6892 // it is not destroyed while exit() is executed 6893 sp<PlaybackThread> thread; 6894 { 6895 Mutex::Autolock _l(mLock); 6896 thread = checkPlaybackThread_l(output); 6897 if (thread == NULL) { 6898 return BAD_VALUE; 6899 } 6900 6901 ALOGV("closeOutput() %d", output); 6902 6903 if (thread->type() == ThreadBase::MIXER) { 6904 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 6905 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 6906 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 6907 dupThread->removeOutputTrack((MixerThread *)thread.get()); 6908 } 6909 } 6910 } 6911 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 6912 mPlaybackThreads.removeItem(output); 6913 } 6914 thread->exit(); 6915 // The thread entity (active unit of execution) is no longer running here, 6916 // but the ThreadBase container still exists. 6917 6918 if (thread->type() != ThreadBase::DUPLICATING) { 6919 AudioStreamOut *out = thread->clearOutput(); 6920 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 6921 // from now on thread->mOutput is NULL 6922 out->hwDev->close_output_stream(out->hwDev, out->stream); 6923 delete out; 6924 } 6925 return NO_ERROR; 6926} 6927 6928status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 6929{ 6930 Mutex::Autolock _l(mLock); 6931 PlaybackThread *thread = checkPlaybackThread_l(output); 6932 6933 if (thread == NULL) { 6934 return BAD_VALUE; 6935 } 6936 6937 ALOGV("suspendOutput() %d", output); 6938 thread->suspend(); 6939 6940 return NO_ERROR; 6941} 6942 6943status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 6944{ 6945 Mutex::Autolock _l(mLock); 6946 PlaybackThread *thread = checkPlaybackThread_l(output); 6947 6948 if (thread == NULL) { 6949 return BAD_VALUE; 6950 } 6951 6952 ALOGV("restoreOutput() %d", output); 6953 6954 thread->restore(); 6955 6956 return NO_ERROR; 6957} 6958 6959audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 6960 audio_devices_t *pDevices, 6961 uint32_t *pSamplingRate, 6962 audio_format_t *pFormat, 6963 uint32_t *pChannelMask) 6964{ 6965 status_t status; 6966 RecordThread *thread = NULL; 6967 struct audio_config config = { 6968 sample_rate: pSamplingRate ? *pSamplingRate : 0, 6969 channel_mask: pChannelMask ? *pChannelMask : 0, 6970 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT, 6971 }; 6972 uint32_t reqSamplingRate = config.sample_rate; 6973 audio_format_t reqFormat = config.format; 6974 audio_channel_mask_t reqChannels = config.channel_mask; 6975 audio_stream_in_t *inStream = NULL; 6976 audio_hw_device_t *inHwDev; 6977 6978 if (pDevices == NULL || *pDevices == 0) { 6979 return 0; 6980 } 6981 6982 Mutex::Autolock _l(mLock); 6983 6984 inHwDev = findSuitableHwDev_l(module, *pDevices); 6985 if (inHwDev == NULL) 6986 return 0; 6987 6988 audio_io_handle_t id = nextUniqueId(); 6989 6990 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, 6991 &inStream); 6992 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d", 6993 inStream, 6994 config.sample_rate, 6995 config.format, 6996 config.channel_mask, 6997 status); 6998 6999 // If the input could not be opened with the requested parameters and we can handle the conversion internally, 7000 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo 7001 // or stereo to mono conversions on 16 bit PCM inputs. 7002 if (status == BAD_VALUE && 7003 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 7004 (config.sample_rate <= 2 * reqSamplingRate) && 7005 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) { 7006 ALOGV("openInput() reopening with proposed sampling rate and channels"); 7007 inStream = NULL; 7008 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream); 7009 } 7010 7011 if (status == NO_ERROR && inStream != NULL) { 7012 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 7013 7014 // Start record thread 7015 // RecorThread require both input and output device indication to forward to audio 7016 // pre processing modules 7017 uint32_t device = (*pDevices) | primaryOutputDevice_l(); 7018 thread = new RecordThread(this, 7019 input, 7020 reqSamplingRate, 7021 reqChannels, 7022 id, 7023 device); 7024 mRecordThreads.add(id, thread); 7025 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 7026 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate; 7027 if (pFormat != NULL) *pFormat = config.format; 7028 if (pChannelMask != NULL) *pChannelMask = reqChannels; 7029 7030 input->stream->common.standby(&input->stream->common); 7031 7032 // notify client processes of the new input creation 7033 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 7034 return id; 7035 } 7036 7037 return 0; 7038} 7039 7040status_t AudioFlinger::closeInput(audio_io_handle_t input) 7041{ 7042 // keep strong reference on the record thread so that 7043 // it is not destroyed while exit() is executed 7044 sp<RecordThread> thread; 7045 { 7046 Mutex::Autolock _l(mLock); 7047 thread = checkRecordThread_l(input); 7048 if (thread == 0) { 7049 return BAD_VALUE; 7050 } 7051 7052 ALOGV("closeInput() %d", input); 7053 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 7054 mRecordThreads.removeItem(input); 7055 } 7056 thread->exit(); 7057 // The thread entity (active unit of execution) is no longer running here, 7058 // but the ThreadBase container still exists. 7059 7060 AudioStreamIn *in = thread->clearInput(); 7061 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 7062 // from now on thread->mInput is NULL 7063 in->hwDev->close_input_stream(in->hwDev, in->stream); 7064 delete in; 7065 7066 return NO_ERROR; 7067} 7068 7069status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 7070{ 7071 Mutex::Autolock _l(mLock); 7072 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 7073 7074 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7075 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 7076 thread->invalidateTracks(stream); 7077 } 7078 7079 return NO_ERROR; 7080} 7081 7082 7083int AudioFlinger::newAudioSessionId() 7084{ 7085 return nextUniqueId(); 7086} 7087 7088void AudioFlinger::acquireAudioSessionId(int audioSession) 7089{ 7090 Mutex::Autolock _l(mLock); 7091 pid_t caller = IPCThreadState::self()->getCallingPid(); 7092 ALOGV("acquiring %d from %d", audioSession, caller); 7093 size_t num = mAudioSessionRefs.size(); 7094 for (size_t i = 0; i< num; i++) { 7095 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 7096 if (ref->mSessionid == audioSession && ref->mPid == caller) { 7097 ref->mCnt++; 7098 ALOGV(" incremented refcount to %d", ref->mCnt); 7099 return; 7100 } 7101 } 7102 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 7103 ALOGV(" added new entry for %d", audioSession); 7104} 7105 7106void AudioFlinger::releaseAudioSessionId(int audioSession) 7107{ 7108 Mutex::Autolock _l(mLock); 7109 pid_t caller = IPCThreadState::self()->getCallingPid(); 7110 ALOGV("releasing %d from %d", audioSession, caller); 7111 size_t num = mAudioSessionRefs.size(); 7112 for (size_t i = 0; i< num; i++) { 7113 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 7114 if (ref->mSessionid == audioSession && ref->mPid == caller) { 7115 ref->mCnt--; 7116 ALOGV(" decremented refcount to %d", ref->mCnt); 7117 if (ref->mCnt == 0) { 7118 mAudioSessionRefs.removeAt(i); 7119 delete ref; 7120 purgeStaleEffects_l(); 7121 } 7122 return; 7123 } 7124 } 7125 ALOGW("session id %d not found for pid %d", audioSession, caller); 7126} 7127 7128void AudioFlinger::purgeStaleEffects_l() { 7129 7130 ALOGV("purging stale effects"); 7131 7132 Vector< sp<EffectChain> > chains; 7133 7134 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7135 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 7136 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 7137 sp<EffectChain> ec = t->mEffectChains[j]; 7138 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 7139 chains.push(ec); 7140 } 7141 } 7142 } 7143 for (size_t i = 0; i < mRecordThreads.size(); i++) { 7144 sp<RecordThread> t = mRecordThreads.valueAt(i); 7145 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 7146 sp<EffectChain> ec = t->mEffectChains[j]; 7147 chains.push(ec); 7148 } 7149 } 7150 7151 for (size_t i = 0; i < chains.size(); i++) { 7152 sp<EffectChain> ec = chains[i]; 7153 int sessionid = ec->sessionId(); 7154 sp<ThreadBase> t = ec->mThread.promote(); 7155 if (t == 0) { 7156 continue; 7157 } 7158 size_t numsessionrefs = mAudioSessionRefs.size(); 7159 bool found = false; 7160 for (size_t k = 0; k < numsessionrefs; k++) { 7161 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 7162 if (ref->mSessionid == sessionid) { 7163 ALOGV(" session %d still exists for %d with %d refs", 7164 sessionid, ref->mPid, ref->mCnt); 7165 found = true; 7166 break; 7167 } 7168 } 7169 if (!found) { 7170 // remove all effects from the chain 7171 while (ec->mEffects.size()) { 7172 sp<EffectModule> effect = ec->mEffects[0]; 7173 effect->unPin(); 7174 Mutex::Autolock _l (t->mLock); 7175 t->removeEffect_l(effect); 7176 for (size_t j = 0; j < effect->mHandles.size(); j++) { 7177 sp<EffectHandle> handle = effect->mHandles[j].promote(); 7178 if (handle != 0) { 7179 handle->mEffect.clear(); 7180 if (handle->mHasControl && handle->mEnabled) { 7181 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 7182 } 7183 } 7184 } 7185 AudioSystem::unregisterEffect(effect->id()); 7186 } 7187 } 7188 } 7189 return; 7190} 7191 7192// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 7193AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 7194{ 7195 return mPlaybackThreads.valueFor(output).get(); 7196} 7197 7198// checkMixerThread_l() must be called with AudioFlinger::mLock held 7199AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 7200{ 7201 PlaybackThread *thread = checkPlaybackThread_l(output); 7202 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 7203} 7204 7205// checkRecordThread_l() must be called with AudioFlinger::mLock held 7206AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 7207{ 7208 return mRecordThreads.valueFor(input).get(); 7209} 7210 7211uint32_t AudioFlinger::nextUniqueId() 7212{ 7213 return android_atomic_inc(&mNextUniqueId); 7214} 7215 7216AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 7217{ 7218 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7219 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 7220 AudioStreamOut *output = thread->getOutput(); 7221 if (output != NULL && output->hwDev == mPrimaryHardwareDev) { 7222 return thread; 7223 } 7224 } 7225 return NULL; 7226} 7227 7228uint32_t AudioFlinger::primaryOutputDevice_l() const 7229{ 7230 PlaybackThread *thread = primaryPlaybackThread_l(); 7231 7232 if (thread == NULL) { 7233 return 0; 7234 } 7235 7236 return thread->device(); 7237} 7238 7239sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 7240 int triggerSession, 7241 int listenerSession, 7242 sync_event_callback_t callBack, 7243 void *cookie) 7244{ 7245 Mutex::Autolock _l(mLock); 7246 7247 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 7248 status_t playStatus = NAME_NOT_FOUND; 7249 status_t recStatus = NAME_NOT_FOUND; 7250 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7251 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 7252 if (playStatus == NO_ERROR) { 7253 return event; 7254 } 7255 } 7256 for (size_t i = 0; i < mRecordThreads.size(); i++) { 7257 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 7258 if (recStatus == NO_ERROR) { 7259 return event; 7260 } 7261 } 7262 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 7263 mPendingSyncEvents.add(event); 7264 } else { 7265 ALOGV("createSyncEvent() invalid event %d", event->type()); 7266 event.clear(); 7267 } 7268 return event; 7269} 7270 7271// ---------------------------------------------------------------------------- 7272// Effect management 7273// ---------------------------------------------------------------------------- 7274 7275 7276status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 7277{ 7278 Mutex::Autolock _l(mLock); 7279 return EffectQueryNumberEffects(numEffects); 7280} 7281 7282status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 7283{ 7284 Mutex::Autolock _l(mLock); 7285 return EffectQueryEffect(index, descriptor); 7286} 7287 7288status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 7289 effect_descriptor_t *descriptor) const 7290{ 7291 Mutex::Autolock _l(mLock); 7292 return EffectGetDescriptor(pUuid, descriptor); 7293} 7294 7295 7296sp<IEffect> AudioFlinger::createEffect(pid_t pid, 7297 effect_descriptor_t *pDesc, 7298 const sp<IEffectClient>& effectClient, 7299 int32_t priority, 7300 audio_io_handle_t io, 7301 int sessionId, 7302 status_t *status, 7303 int *id, 7304 int *enabled) 7305{ 7306 status_t lStatus = NO_ERROR; 7307 sp<EffectHandle> handle; 7308 effect_descriptor_t desc; 7309 7310 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 7311 pid, effectClient.get(), priority, sessionId, io); 7312 7313 if (pDesc == NULL) { 7314 lStatus = BAD_VALUE; 7315 goto Exit; 7316 } 7317 7318 // check audio settings permission for global effects 7319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 7320 lStatus = PERMISSION_DENIED; 7321 goto Exit; 7322 } 7323 7324 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 7325 // that can only be created by audio policy manager (running in same process) 7326 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 7327 lStatus = PERMISSION_DENIED; 7328 goto Exit; 7329 } 7330 7331 if (io == 0) { 7332 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 7333 // output must be specified by AudioPolicyManager when using session 7334 // AUDIO_SESSION_OUTPUT_STAGE 7335 lStatus = BAD_VALUE; 7336 goto Exit; 7337 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 7338 // if the output returned by getOutputForEffect() is removed before we lock the 7339 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 7340 // and we will exit safely 7341 io = AudioSystem::getOutputForEffect(&desc); 7342 } 7343 } 7344 7345 { 7346 Mutex::Autolock _l(mLock); 7347 7348 7349 if (!EffectIsNullUuid(&pDesc->uuid)) { 7350 // if uuid is specified, request effect descriptor 7351 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 7352 if (lStatus < 0) { 7353 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 7354 goto Exit; 7355 } 7356 } else { 7357 // if uuid is not specified, look for an available implementation 7358 // of the required type in effect factory 7359 if (EffectIsNullUuid(&pDesc->type)) { 7360 ALOGW("createEffect() no effect type"); 7361 lStatus = BAD_VALUE; 7362 goto Exit; 7363 } 7364 uint32_t numEffects = 0; 7365 effect_descriptor_t d; 7366 d.flags = 0; // prevent compiler warning 7367 bool found = false; 7368 7369 lStatus = EffectQueryNumberEffects(&numEffects); 7370 if (lStatus < 0) { 7371 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 7372 goto Exit; 7373 } 7374 for (uint32_t i = 0; i < numEffects; i++) { 7375 lStatus = EffectQueryEffect(i, &desc); 7376 if (lStatus < 0) { 7377 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 7378 continue; 7379 } 7380 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 7381 // If matching type found save effect descriptor. If the session is 7382 // 0 and the effect is not auxiliary, continue enumeration in case 7383 // an auxiliary version of this effect type is available 7384 found = true; 7385 memcpy(&d, &desc, sizeof(effect_descriptor_t)); 7386 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 7387 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7388 break; 7389 } 7390 } 7391 } 7392 if (!found) { 7393 lStatus = BAD_VALUE; 7394 ALOGW("createEffect() effect not found"); 7395 goto Exit; 7396 } 7397 // For same effect type, chose auxiliary version over insert version if 7398 // connect to output mix (Compliance to OpenSL ES) 7399 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 7400 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 7401 memcpy(&desc, &d, sizeof(effect_descriptor_t)); 7402 } 7403 } 7404 7405 // Do not allow auxiliary effects on a session different from 0 (output mix) 7406 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 7407 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7408 lStatus = INVALID_OPERATION; 7409 goto Exit; 7410 } 7411 7412 // check recording permission for visualizer 7413 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 7414 !recordingAllowed()) { 7415 lStatus = PERMISSION_DENIED; 7416 goto Exit; 7417 } 7418 7419 // return effect descriptor 7420 memcpy(pDesc, &desc, sizeof(effect_descriptor_t)); 7421 7422 // If output is not specified try to find a matching audio session ID in one of the 7423 // output threads. 7424 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 7425 // because of code checking output when entering the function. 7426 // Note: io is never 0 when creating an effect on an input 7427 if (io == 0) { 7428 // look for the thread where the specified audio session is present 7429 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7430 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 7431 io = mPlaybackThreads.keyAt(i); 7432 break; 7433 } 7434 } 7435 if (io == 0) { 7436 for (size_t i = 0; i < mRecordThreads.size(); i++) { 7437 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 7438 io = mRecordThreads.keyAt(i); 7439 break; 7440 } 7441 } 7442 } 7443 // If no output thread contains the requested session ID, default to 7444 // first output. The effect chain will be moved to the correct output 7445 // thread when a track with the same session ID is created 7446 if (io == 0 && mPlaybackThreads.size()) { 7447 io = mPlaybackThreads.keyAt(0); 7448 } 7449 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 7450 } 7451 ThreadBase *thread = checkRecordThread_l(io); 7452 if (thread == NULL) { 7453 thread = checkPlaybackThread_l(io); 7454 if (thread == NULL) { 7455 ALOGE("createEffect() unknown output thread"); 7456 lStatus = BAD_VALUE; 7457 goto Exit; 7458 } 7459 } 7460 7461 sp<Client> client = registerPid_l(pid); 7462 7463 // create effect on selected output thread 7464 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 7465 &desc, enabled, &lStatus); 7466 if (handle != 0 && id != NULL) { 7467 *id = handle->id(); 7468 } 7469 } 7470 7471Exit: 7472 if (status != NULL) { 7473 *status = lStatus; 7474 } 7475 return handle; 7476} 7477 7478status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 7479 audio_io_handle_t dstOutput) 7480{ 7481 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 7482 sessionId, srcOutput, dstOutput); 7483 Mutex::Autolock _l(mLock); 7484 if (srcOutput == dstOutput) { 7485 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 7486 return NO_ERROR; 7487 } 7488 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 7489 if (srcThread == NULL) { 7490 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 7491 return BAD_VALUE; 7492 } 7493 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 7494 if (dstThread == NULL) { 7495 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 7496 return BAD_VALUE; 7497 } 7498 7499 Mutex::Autolock _dl(dstThread->mLock); 7500 Mutex::Autolock _sl(srcThread->mLock); 7501 moveEffectChain_l(sessionId, srcThread, dstThread, false); 7502 7503 return NO_ERROR; 7504} 7505 7506// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 7507status_t AudioFlinger::moveEffectChain_l(int sessionId, 7508 AudioFlinger::PlaybackThread *srcThread, 7509 AudioFlinger::PlaybackThread *dstThread, 7510 bool reRegister) 7511{ 7512 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 7513 sessionId, srcThread, dstThread); 7514 7515 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 7516 if (chain == 0) { 7517 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 7518 sessionId, srcThread); 7519 return INVALID_OPERATION; 7520 } 7521 7522 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 7523 // so that a new chain is created with correct parameters when first effect is added. This is 7524 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 7525 // removed. 7526 srcThread->removeEffectChain_l(chain); 7527 7528 // transfer all effects one by one so that new effect chain is created on new thread with 7529 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 7530 audio_io_handle_t dstOutput = dstThread->id(); 7531 sp<EffectChain> dstChain; 7532 uint32_t strategy = 0; // prevent compiler warning 7533 sp<EffectModule> effect = chain->getEffectFromId_l(0); 7534 while (effect != 0) { 7535 srcThread->removeEffect_l(effect); 7536 dstThread->addEffect_l(effect); 7537 // removeEffect_l() has stopped the effect if it was active so it must be restarted 7538 if (effect->state() == EffectModule::ACTIVE || 7539 effect->state() == EffectModule::STOPPING) { 7540 effect->start(); 7541 } 7542 // if the move request is not received from audio policy manager, the effect must be 7543 // re-registered with the new strategy and output 7544 if (dstChain == 0) { 7545 dstChain = effect->chain().promote(); 7546 if (dstChain == 0) { 7547 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 7548 srcThread->addEffect_l(effect); 7549 return NO_INIT; 7550 } 7551 strategy = dstChain->strategy(); 7552 } 7553 if (reRegister) { 7554 AudioSystem::unregisterEffect(effect->id()); 7555 AudioSystem::registerEffect(&effect->desc(), 7556 dstOutput, 7557 strategy, 7558 sessionId, 7559 effect->id()); 7560 } 7561 effect = chain->getEffectFromId_l(0); 7562 } 7563 7564 return NO_ERROR; 7565} 7566 7567 7568// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held 7569sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 7570 const sp<AudioFlinger::Client>& client, 7571 const sp<IEffectClient>& effectClient, 7572 int32_t priority, 7573 int sessionId, 7574 effect_descriptor_t *desc, 7575 int *enabled, 7576 status_t *status 7577 ) 7578{ 7579 sp<EffectModule> effect; 7580 sp<EffectHandle> handle; 7581 status_t lStatus; 7582 sp<EffectChain> chain; 7583 bool chainCreated = false; 7584 bool effectCreated = false; 7585 bool effectRegistered = false; 7586 7587 lStatus = initCheck(); 7588 if (lStatus != NO_ERROR) { 7589 ALOGW("createEffect_l() Audio driver not initialized."); 7590 goto Exit; 7591 } 7592 7593 // Do not allow effects with session ID 0 on direct output or duplicating threads 7594 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format 7595 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { 7596 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", 7597 desc->name, sessionId); 7598 lStatus = BAD_VALUE; 7599 goto Exit; 7600 } 7601 // Only Pre processor effects are allowed on input threads and only on input threads 7602 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 7603 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 7604 desc->name, desc->flags, mType); 7605 lStatus = BAD_VALUE; 7606 goto Exit; 7607 } 7608 7609 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 7610 7611 { // scope for mLock 7612 Mutex::Autolock _l(mLock); 7613 7614 // check for existing effect chain with the requested audio session 7615 chain = getEffectChain_l(sessionId); 7616 if (chain == 0) { 7617 // create a new chain for this session 7618 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 7619 chain = new EffectChain(this, sessionId); 7620 addEffectChain_l(chain); 7621 chain->setStrategy(getStrategyForSession_l(sessionId)); 7622 chainCreated = true; 7623 } else { 7624 effect = chain->getEffectFromDesc_l(desc); 7625 } 7626 7627 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 7628 7629 if (effect == 0) { 7630 int id = mAudioFlinger->nextUniqueId(); 7631 // Check CPU and memory usage 7632 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 7633 if (lStatus != NO_ERROR) { 7634 goto Exit; 7635 } 7636 effectRegistered = true; 7637 // create a new effect module if none present in the chain 7638 effect = new EffectModule(this, chain, desc, id, sessionId); 7639 lStatus = effect->status(); 7640 if (lStatus != NO_ERROR) { 7641 goto Exit; 7642 } 7643 lStatus = chain->addEffect_l(effect); 7644 if (lStatus != NO_ERROR) { 7645 goto Exit; 7646 } 7647 effectCreated = true; 7648 7649 effect->setDevice(mDevice); 7650 effect->setMode(mAudioFlinger->getMode()); 7651 } 7652 // create effect handle and connect it to effect module 7653 handle = new EffectHandle(effect, client, effectClient, priority); 7654 lStatus = effect->addHandle(handle); 7655 if (enabled != NULL) { 7656 *enabled = (int)effect->isEnabled(); 7657 } 7658 } 7659 7660Exit: 7661 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 7662 Mutex::Autolock _l(mLock); 7663 if (effectCreated) { 7664 chain->removeEffect_l(effect); 7665 } 7666 if (effectRegistered) { 7667 AudioSystem::unregisterEffect(effect->id()); 7668 } 7669 if (chainCreated) { 7670 removeEffectChain_l(chain); 7671 } 7672 handle.clear(); 7673 } 7674 7675 if (status != NULL) { 7676 *status = lStatus; 7677 } 7678 return handle; 7679} 7680 7681sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId) 7682{ 7683 Mutex::Autolock _l(mLock); 7684 return getEffect_l(sessionId, effectId); 7685} 7686 7687sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 7688{ 7689 sp<EffectChain> chain = getEffectChain_l(sessionId); 7690 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 7691} 7692 7693// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 7694// PlaybackThread::mLock held 7695status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 7696{ 7697 // check for existing effect chain with the requested audio session 7698 int sessionId = effect->sessionId(); 7699 sp<EffectChain> chain = getEffectChain_l(sessionId); 7700 bool chainCreated = false; 7701 7702 if (chain == 0) { 7703 // create a new chain for this session 7704 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 7705 chain = new EffectChain(this, sessionId); 7706 addEffectChain_l(chain); 7707 chain->setStrategy(getStrategyForSession_l(sessionId)); 7708 chainCreated = true; 7709 } 7710 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 7711 7712 if (chain->getEffectFromId_l(effect->id()) != 0) { 7713 ALOGW("addEffect_l() %p effect %s already present in chain %p", 7714 this, effect->desc().name, chain.get()); 7715 return BAD_VALUE; 7716 } 7717 7718 status_t status = chain->addEffect_l(effect); 7719 if (status != NO_ERROR) { 7720 if (chainCreated) { 7721 removeEffectChain_l(chain); 7722 } 7723 return status; 7724 } 7725 7726 effect->setDevice(mDevice); 7727 effect->setMode(mAudioFlinger->getMode()); 7728 return NO_ERROR; 7729} 7730 7731void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 7732 7733 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 7734 effect_descriptor_t desc = effect->desc(); 7735 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7736 detachAuxEffect_l(effect->id()); 7737 } 7738 7739 sp<EffectChain> chain = effect->chain().promote(); 7740 if (chain != 0) { 7741 // remove effect chain if removing last effect 7742 if (chain->removeEffect_l(effect) == 0) { 7743 removeEffectChain_l(chain); 7744 } 7745 } else { 7746 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 7747 } 7748} 7749 7750void AudioFlinger::ThreadBase::lockEffectChains_l( 7751 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 7752{ 7753 effectChains = mEffectChains; 7754 for (size_t i = 0; i < mEffectChains.size(); i++) { 7755 mEffectChains[i]->lock(); 7756 } 7757} 7758 7759void AudioFlinger::ThreadBase::unlockEffectChains( 7760 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 7761{ 7762 for (size_t i = 0; i < effectChains.size(); i++) { 7763 effectChains[i]->unlock(); 7764 } 7765} 7766 7767sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 7768{ 7769 Mutex::Autolock _l(mLock); 7770 return getEffectChain_l(sessionId); 7771} 7772 7773sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) 7774{ 7775 size_t size = mEffectChains.size(); 7776 for (size_t i = 0; i < size; i++) { 7777 if (mEffectChains[i]->sessionId() == sessionId) { 7778 return mEffectChains[i]; 7779 } 7780 } 7781 return 0; 7782} 7783 7784void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 7785{ 7786 Mutex::Autolock _l(mLock); 7787 size_t size = mEffectChains.size(); 7788 for (size_t i = 0; i < size; i++) { 7789 mEffectChains[i]->setMode_l(mode); 7790 } 7791} 7792 7793void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 7794 const wp<EffectHandle>& handle, 7795 bool unpinIfLast) { 7796 7797 Mutex::Autolock _l(mLock); 7798 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 7799 // delete the effect module if removing last handle on it 7800 if (effect->removeHandle(handle) == 0) { 7801 if (!effect->isPinned() || unpinIfLast) { 7802 removeEffect_l(effect); 7803 AudioSystem::unregisterEffect(effect->id()); 7804 } 7805 } 7806} 7807 7808status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 7809{ 7810 int session = chain->sessionId(); 7811 int16_t *buffer = mMixBuffer; 7812 bool ownsBuffer = false; 7813 7814 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 7815 if (session > 0) { 7816 // Only one effect chain can be present in direct output thread and it uses 7817 // the mix buffer as input 7818 if (mType != DIRECT) { 7819 size_t numSamples = mNormalFrameCount * mChannelCount; 7820 buffer = new int16_t[numSamples]; 7821 memset(buffer, 0, numSamples * sizeof(int16_t)); 7822 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 7823 ownsBuffer = true; 7824 } 7825 7826 // Attach all tracks with same session ID to this chain. 7827 for (size_t i = 0; i < mTracks.size(); ++i) { 7828 sp<Track> track = mTracks[i]; 7829 if (session == track->sessionId()) { 7830 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer); 7831 track->setMainBuffer(buffer); 7832 chain->incTrackCnt(); 7833 } 7834 } 7835 7836 // indicate all active tracks in the chain 7837 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 7838 sp<Track> track = mActiveTracks[i].promote(); 7839 if (track == 0) continue; 7840 if (session == track->sessionId()) { 7841 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 7842 chain->incActiveTrackCnt(); 7843 } 7844 } 7845 } 7846 7847 chain->setInBuffer(buffer, ownsBuffer); 7848 chain->setOutBuffer(mMixBuffer); 7849 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 7850 // chains list in order to be processed last as it contains output stage effects 7851 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 7852 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 7853 // after track specific effects and before output stage 7854 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 7855 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 7856 // Effect chain for other sessions are inserted at beginning of effect 7857 // chains list to be processed before output mix effects. Relative order between other 7858 // sessions is not important 7859 size_t size = mEffectChains.size(); 7860 size_t i = 0; 7861 for (i = 0; i < size; i++) { 7862 if (mEffectChains[i]->sessionId() < session) break; 7863 } 7864 mEffectChains.insertAt(chain, i); 7865 checkSuspendOnAddEffectChain_l(chain); 7866 7867 return NO_ERROR; 7868} 7869 7870size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 7871{ 7872 int session = chain->sessionId(); 7873 7874 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 7875 7876 for (size_t i = 0; i < mEffectChains.size(); i++) { 7877 if (chain == mEffectChains[i]) { 7878 mEffectChains.removeAt(i); 7879 // detach all active tracks from the chain 7880 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 7881 sp<Track> track = mActiveTracks[i].promote(); 7882 if (track == 0) continue; 7883 if (session == track->sessionId()) { 7884 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 7885 chain.get(), session); 7886 chain->decActiveTrackCnt(); 7887 } 7888 } 7889 7890 // detach all tracks with same session ID from this chain 7891 for (size_t i = 0; i < mTracks.size(); ++i) { 7892 sp<Track> track = mTracks[i]; 7893 if (session == track->sessionId()) { 7894 track->setMainBuffer(mMixBuffer); 7895 chain->decTrackCnt(); 7896 } 7897 } 7898 break; 7899 } 7900 } 7901 return mEffectChains.size(); 7902} 7903 7904status_t AudioFlinger::PlaybackThread::attachAuxEffect( 7905 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 7906{ 7907 Mutex::Autolock _l(mLock); 7908 return attachAuxEffect_l(track, EffectId); 7909} 7910 7911status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 7912 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 7913{ 7914 status_t status = NO_ERROR; 7915 7916 if (EffectId == 0) { 7917 track->setAuxBuffer(0, NULL); 7918 } else { 7919 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 7920 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 7921 if (effect != 0) { 7922 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7923 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 7924 } else { 7925 status = INVALID_OPERATION; 7926 } 7927 } else { 7928 status = BAD_VALUE; 7929 } 7930 } 7931 return status; 7932} 7933 7934void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 7935{ 7936 for (size_t i = 0; i < mTracks.size(); ++i) { 7937 sp<Track> track = mTracks[i]; 7938 if (track->auxEffectId() == effectId) { 7939 attachAuxEffect_l(track, 0); 7940 } 7941 } 7942} 7943 7944status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 7945{ 7946 // only one chain per input thread 7947 if (mEffectChains.size() != 0) { 7948 return INVALID_OPERATION; 7949 } 7950 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 7951 7952 chain->setInBuffer(NULL); 7953 chain->setOutBuffer(NULL); 7954 7955 checkSuspendOnAddEffectChain_l(chain); 7956 7957 mEffectChains.add(chain); 7958 7959 return NO_ERROR; 7960} 7961 7962size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 7963{ 7964 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 7965 ALOGW_IF(mEffectChains.size() != 1, 7966 "removeEffectChain_l() %p invalid chain size %d on thread %p", 7967 chain.get(), mEffectChains.size(), this); 7968 if (mEffectChains.size() == 1) { 7969 mEffectChains.removeAt(0); 7970 } 7971 return 0; 7972} 7973 7974// ---------------------------------------------------------------------------- 7975// EffectModule implementation 7976// ---------------------------------------------------------------------------- 7977 7978#undef LOG_TAG 7979#define LOG_TAG "AudioFlinger::EffectModule" 7980 7981AudioFlinger::EffectModule::EffectModule(ThreadBase *thread, 7982 const wp<AudioFlinger::EffectChain>& chain, 7983 effect_descriptor_t *desc, 7984 int id, 7985 int sessionId) 7986 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX), 7987 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), 7988 // mDescriptor is set below 7989 // mConfig is set by configure() and not used before then 7990 mEffectInterface(NULL), 7991 mStatus(NO_INIT), mState(IDLE), 7992 // mMaxDisableWaitCnt is set by configure() and not used before then 7993 // mDisableWaitCnt is set by process() and updateState() and not used before then 7994 mSuspended(false) 7995{ 7996 ALOGV("Constructor %p", this); 7997 int lStatus; 7998 if (thread == NULL) { 7999 return; 8000 } 8001 8002 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t)); 8003 8004 // create effect engine from effect factory 8005 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface); 8006 8007 if (mStatus != NO_ERROR) { 8008 return; 8009 } 8010 lStatus = init(); 8011 if (lStatus < 0) { 8012 mStatus = lStatus; 8013 goto Error; 8014 } 8015 8016 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface); 8017 return; 8018Error: 8019 EffectRelease(mEffectInterface); 8020 mEffectInterface = NULL; 8021 ALOGV("Constructor Error %d", mStatus); 8022} 8023 8024AudioFlinger::EffectModule::~EffectModule() 8025{ 8026 ALOGV("Destructor %p", this); 8027 if (mEffectInterface != NULL) { 8028 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 8029 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 8030 sp<ThreadBase> thread = mThread.promote(); 8031 if (thread != 0) { 8032 audio_stream_t *stream = thread->stream(); 8033 if (stream != NULL) { 8034 stream->remove_audio_effect(stream, mEffectInterface); 8035 } 8036 } 8037 } 8038 // release effect engine 8039 EffectRelease(mEffectInterface); 8040 } 8041} 8042 8043status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle) 8044{ 8045 status_t status; 8046 8047 Mutex::Autolock _l(mLock); 8048 int priority = handle->priority(); 8049 size_t size = mHandles.size(); 8050 sp<EffectHandle> h; 8051 size_t i; 8052 for (i = 0; i < size; i++) { 8053 h = mHandles[i].promote(); 8054 if (h == 0) continue; 8055 if (h->priority() <= priority) break; 8056 } 8057 // if inserted in first place, move effect control from previous owner to this handle 8058 if (i == 0) { 8059 bool enabled = false; 8060 if (h != 0) { 8061 enabled = h->enabled(); 8062 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/); 8063 } 8064 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/); 8065 status = NO_ERROR; 8066 } else { 8067 status = ALREADY_EXISTS; 8068 } 8069 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i); 8070 mHandles.insertAt(handle, i); 8071 return status; 8072} 8073 8074size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle) 8075{ 8076 Mutex::Autolock _l(mLock); 8077 size_t size = mHandles.size(); 8078 size_t i; 8079 for (i = 0; i < size; i++) { 8080 if (mHandles[i] == handle) break; 8081 } 8082 if (i == size) { 8083 return size; 8084 } 8085 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i); 8086 8087 bool enabled = false; 8088 EffectHandle *hdl = handle.unsafe_get(); 8089 if (hdl != NULL) { 8090 ALOGV("removeHandle() unsafe_get OK"); 8091 enabled = hdl->enabled(); 8092 } 8093 mHandles.removeAt(i); 8094 size = mHandles.size(); 8095 // if removed from first place, move effect control from this handle to next in line 8096 if (i == 0 && size != 0) { 8097 sp<EffectHandle> h = mHandles[0].promote(); 8098 if (h != 0) { 8099 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/); 8100 } 8101 } 8102 8103 // Prevent calls to process() and other functions on effect interface from now on. 8104 // The effect engine will be released by the destructor when the last strong reference on 8105 // this object is released which can happen after next process is called. 8106 if (size == 0 && !mPinned) { 8107 mState = DESTROYED; 8108 } 8109 8110 return size; 8111} 8112 8113sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle() 8114{ 8115 Mutex::Autolock _l(mLock); 8116 return mHandles.size() != 0 ? mHandles[0].promote() : 0; 8117} 8118 8119void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast) 8120{ 8121 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get()); 8122 // keep a strong reference on this EffectModule to avoid calling the 8123 // destructor before we exit 8124 sp<EffectModule> keep(this); 8125 { 8126 sp<ThreadBase> thread = mThread.promote(); 8127 if (thread != 0) { 8128 thread->disconnectEffect(keep, handle, unpinIfLast); 8129 } 8130 } 8131} 8132 8133void AudioFlinger::EffectModule::updateState() { 8134 Mutex::Autolock _l(mLock); 8135 8136 switch (mState) { 8137 case RESTART: 8138 reset_l(); 8139 // FALL THROUGH 8140 8141 case STARTING: 8142 // clear auxiliary effect input buffer for next accumulation 8143 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8144 memset(mConfig.inputCfg.buffer.raw, 8145 0, 8146 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 8147 } 8148 start_l(); 8149 mState = ACTIVE; 8150 break; 8151 case STOPPING: 8152 stop_l(); 8153 mDisableWaitCnt = mMaxDisableWaitCnt; 8154 mState = STOPPED; 8155 break; 8156 case STOPPED: 8157 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the 8158 // turn off sequence. 8159 if (--mDisableWaitCnt == 0) { 8160 reset_l(); 8161 mState = IDLE; 8162 } 8163 break; 8164 default: //IDLE , ACTIVE, DESTROYED 8165 break; 8166 } 8167} 8168 8169void AudioFlinger::EffectModule::process() 8170{ 8171 Mutex::Autolock _l(mLock); 8172 8173 if (mState == DESTROYED || mEffectInterface == NULL || 8174 mConfig.inputCfg.buffer.raw == NULL || 8175 mConfig.outputCfg.buffer.raw == NULL) { 8176 return; 8177 } 8178 8179 if (isProcessEnabled()) { 8180 // do 32 bit to 16 bit conversion for auxiliary effect input buffer 8181 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8182 ditherAndClamp(mConfig.inputCfg.buffer.s32, 8183 mConfig.inputCfg.buffer.s32, 8184 mConfig.inputCfg.buffer.frameCount/2); 8185 } 8186 8187 // do the actual processing in the effect engine 8188 int ret = (*mEffectInterface)->process(mEffectInterface, 8189 &mConfig.inputCfg.buffer, 8190 &mConfig.outputCfg.buffer); 8191 8192 // force transition to IDLE state when engine is ready 8193 if (mState == STOPPED && ret == -ENODATA) { 8194 mDisableWaitCnt = 1; 8195 } 8196 8197 // clear auxiliary effect input buffer for next accumulation 8198 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8199 memset(mConfig.inputCfg.buffer.raw, 0, 8200 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 8201 } 8202 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT && 8203 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 8204 // If an insert effect is idle and input buffer is different from output buffer, 8205 // accumulate input onto output 8206 sp<EffectChain> chain = mChain.promote(); 8207 if (chain != 0 && chain->activeTrackCnt() != 0) { 8208 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here 8209 int16_t *in = mConfig.inputCfg.buffer.s16; 8210 int16_t *out = mConfig.outputCfg.buffer.s16; 8211 for (size_t i = 0; i < frameCnt; i++) { 8212 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]); 8213 } 8214 } 8215 } 8216} 8217 8218void AudioFlinger::EffectModule::reset_l() 8219{ 8220 if (mEffectInterface == NULL) { 8221 return; 8222 } 8223 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL); 8224} 8225 8226status_t AudioFlinger::EffectModule::configure() 8227{ 8228 uint32_t channels; 8229 if (mEffectInterface == NULL) { 8230 return NO_INIT; 8231 } 8232 8233 sp<ThreadBase> thread = mThread.promote(); 8234 if (thread == 0) { 8235 return DEAD_OBJECT; 8236 } 8237 8238 // TODO: handle configuration of effects replacing track process 8239 if (thread->channelCount() == 1) { 8240 channels = AUDIO_CHANNEL_OUT_MONO; 8241 } else { 8242 channels = AUDIO_CHANNEL_OUT_STEREO; 8243 } 8244 8245 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8246 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; 8247 } else { 8248 mConfig.inputCfg.channels = channels; 8249 } 8250 mConfig.outputCfg.channels = channels; 8251 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 8252 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 8253 mConfig.inputCfg.samplingRate = thread->sampleRate(); 8254 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; 8255 mConfig.inputCfg.bufferProvider.cookie = NULL; 8256 mConfig.inputCfg.bufferProvider.getBuffer = NULL; 8257 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; 8258 mConfig.outputCfg.bufferProvider.cookie = NULL; 8259 mConfig.outputCfg.bufferProvider.getBuffer = NULL; 8260 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; 8261 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; 8262 // Insert effect: 8263 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE, 8264 // always overwrites output buffer: input buffer == output buffer 8265 // - in other sessions: 8266 // last effect in the chain accumulates in output buffer: input buffer != output buffer 8267 // other effect: overwrites output buffer: input buffer == output buffer 8268 // Auxiliary effect: 8269 // accumulates in output buffer: input buffer != output buffer 8270 // Therefore: accumulate <=> input buffer != output buffer 8271 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 8272 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; 8273 } else { 8274 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; 8275 } 8276 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; 8277 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; 8278 mConfig.inputCfg.buffer.frameCount = thread->frameCount(); 8279 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; 8280 8281 ALOGV("configure() %p thread %p buffer %p framecount %d", 8282 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); 8283 8284 status_t cmdStatus; 8285 uint32_t size = sizeof(int); 8286 status_t status = (*mEffectInterface)->command(mEffectInterface, 8287 EFFECT_CMD_SET_CONFIG, 8288 sizeof(effect_config_t), 8289 &mConfig, 8290 &size, 8291 &cmdStatus); 8292 if (status == 0) { 8293 status = cmdStatus; 8294 } 8295 8296 if (status == 0 && 8297 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) { 8298 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2]; 8299 effect_param_t *p = (effect_param_t *)buf32; 8300 8301 p->psize = sizeof(uint32_t); 8302 p->vsize = sizeof(uint32_t); 8303 size = sizeof(int); 8304 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY; 8305 8306 uint32_t latency = 0; 8307 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId); 8308 if (pbt != NULL) { 8309 latency = pbt->latency_l(); 8310 } 8311 8312 *((int32_t *)p->data + 1)= latency; 8313 (*mEffectInterface)->command(mEffectInterface, 8314 EFFECT_CMD_SET_PARAM, 8315 sizeof(effect_param_t) + 8, 8316 &buf32, 8317 &size, 8318 &cmdStatus); 8319 } 8320 8321 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / 8322 (1000 * mConfig.outputCfg.buffer.frameCount); 8323 8324 return status; 8325} 8326 8327status_t AudioFlinger::EffectModule::init() 8328{ 8329 Mutex::Autolock _l(mLock); 8330 if (mEffectInterface == NULL) { 8331 return NO_INIT; 8332 } 8333 status_t cmdStatus; 8334 uint32_t size = sizeof(status_t); 8335 status_t status = (*mEffectInterface)->command(mEffectInterface, 8336 EFFECT_CMD_INIT, 8337 0, 8338 NULL, 8339 &size, 8340 &cmdStatus); 8341 if (status == 0) { 8342 status = cmdStatus; 8343 } 8344 return status; 8345} 8346 8347status_t AudioFlinger::EffectModule::start() 8348{ 8349 Mutex::Autolock _l(mLock); 8350 return start_l(); 8351} 8352 8353status_t AudioFlinger::EffectModule::start_l() 8354{ 8355 if (mEffectInterface == NULL) { 8356 return NO_INIT; 8357 } 8358 status_t cmdStatus; 8359 uint32_t size = sizeof(status_t); 8360 status_t status = (*mEffectInterface)->command(mEffectInterface, 8361 EFFECT_CMD_ENABLE, 8362 0, 8363 NULL, 8364 &size, 8365 &cmdStatus); 8366 if (status == 0) { 8367 status = cmdStatus; 8368 } 8369 if (status == 0 && 8370 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 8371 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 8372 sp<ThreadBase> thread = mThread.promote(); 8373 if (thread != 0) { 8374 audio_stream_t *stream = thread->stream(); 8375 if (stream != NULL) { 8376 stream->add_audio_effect(stream, mEffectInterface); 8377 } 8378 } 8379 } 8380 return status; 8381} 8382 8383status_t AudioFlinger::EffectModule::stop() 8384{ 8385 Mutex::Autolock _l(mLock); 8386 return stop_l(); 8387} 8388 8389status_t AudioFlinger::EffectModule::stop_l() 8390{ 8391 if (mEffectInterface == NULL) { 8392 return NO_INIT; 8393 } 8394 status_t cmdStatus; 8395 uint32_t size = sizeof(status_t); 8396 status_t status = (*mEffectInterface)->command(mEffectInterface, 8397 EFFECT_CMD_DISABLE, 8398 0, 8399 NULL, 8400 &size, 8401 &cmdStatus); 8402 if (status == 0) { 8403 status = cmdStatus; 8404 } 8405 if (status == 0 && 8406 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 8407 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 8408 sp<ThreadBase> thread = mThread.promote(); 8409 if (thread != 0) { 8410 audio_stream_t *stream = thread->stream(); 8411 if (stream != NULL) { 8412 stream->remove_audio_effect(stream, mEffectInterface); 8413 } 8414 } 8415 } 8416 return status; 8417} 8418 8419status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, 8420 uint32_t cmdSize, 8421 void *pCmdData, 8422 uint32_t *replySize, 8423 void *pReplyData) 8424{ 8425 Mutex::Autolock _l(mLock); 8426// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); 8427 8428 if (mState == DESTROYED || mEffectInterface == NULL) { 8429 return NO_INIT; 8430 } 8431 status_t status = (*mEffectInterface)->command(mEffectInterface, 8432 cmdCode, 8433 cmdSize, 8434 pCmdData, 8435 replySize, 8436 pReplyData); 8437 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { 8438 uint32_t size = (replySize == NULL) ? 0 : *replySize; 8439 for (size_t i = 1; i < mHandles.size(); i++) { 8440 sp<EffectHandle> h = mHandles[i].promote(); 8441 if (h != 0) { 8442 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); 8443 } 8444 } 8445 } 8446 return status; 8447} 8448 8449status_t AudioFlinger::EffectModule::setEnabled(bool enabled) 8450{ 8451 8452 Mutex::Autolock _l(mLock); 8453 ALOGV("setEnabled %p enabled %d", this, enabled); 8454 8455 if (enabled != isEnabled()) { 8456 status_t status = AudioSystem::setEffectEnabled(mId, enabled); 8457 if (enabled && status != NO_ERROR) { 8458 return status; 8459 } 8460 8461 switch (mState) { 8462 // going from disabled to enabled 8463 case IDLE: 8464 mState = STARTING; 8465 break; 8466 case STOPPED: 8467 mState = RESTART; 8468 break; 8469 case STOPPING: 8470 mState = ACTIVE; 8471 break; 8472 8473 // going from enabled to disabled 8474 case RESTART: 8475 mState = STOPPED; 8476 break; 8477 case STARTING: 8478 mState = IDLE; 8479 break; 8480 case ACTIVE: 8481 mState = STOPPING; 8482 break; 8483 case DESTROYED: 8484 return NO_ERROR; // simply ignore as we are being destroyed 8485 } 8486 for (size_t i = 1; i < mHandles.size(); i++) { 8487 sp<EffectHandle> h = mHandles[i].promote(); 8488 if (h != 0) { 8489 h->setEnabled(enabled); 8490 } 8491 } 8492 } 8493 return NO_ERROR; 8494} 8495 8496bool AudioFlinger::EffectModule::isEnabled() const 8497{ 8498 switch (mState) { 8499 case RESTART: 8500 case STARTING: 8501 case ACTIVE: 8502 return true; 8503 case IDLE: 8504 case STOPPING: 8505 case STOPPED: 8506 case DESTROYED: 8507 default: 8508 return false; 8509 } 8510} 8511 8512bool AudioFlinger::EffectModule::isProcessEnabled() const 8513{ 8514 switch (mState) { 8515 case RESTART: 8516 case ACTIVE: 8517 case STOPPING: 8518 case STOPPED: 8519 return true; 8520 case IDLE: 8521 case STARTING: 8522 case DESTROYED: 8523 default: 8524 return false; 8525 } 8526} 8527 8528status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller) 8529{ 8530 Mutex::Autolock _l(mLock); 8531 status_t status = NO_ERROR; 8532 8533 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume 8534 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set) 8535 if (isProcessEnabled() && 8536 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL || 8537 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) { 8538 status_t cmdStatus; 8539 uint32_t volume[2]; 8540 uint32_t *pVolume = NULL; 8541 uint32_t size = sizeof(volume); 8542 volume[0] = *left; 8543 volume[1] = *right; 8544 if (controller) { 8545 pVolume = volume; 8546 } 8547 status = (*mEffectInterface)->command(mEffectInterface, 8548 EFFECT_CMD_SET_VOLUME, 8549 size, 8550 volume, 8551 &size, 8552 pVolume); 8553 if (controller && status == NO_ERROR && size == sizeof(volume)) { 8554 *left = volume[0]; 8555 *right = volume[1]; 8556 } 8557 } 8558 return status; 8559} 8560 8561status_t AudioFlinger::EffectModule::setDevice(uint32_t device) 8562{ 8563 Mutex::Autolock _l(mLock); 8564 status_t status = NO_ERROR; 8565 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) { 8566 // audio pre processing modules on RecordThread can receive both output and 8567 // input device indication in the same call 8568 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL; 8569 if (dev) { 8570 status_t cmdStatus; 8571 uint32_t size = sizeof(status_t); 8572 8573 status = (*mEffectInterface)->command(mEffectInterface, 8574 EFFECT_CMD_SET_DEVICE, 8575 sizeof(uint32_t), 8576 &dev, 8577 &size, 8578 &cmdStatus); 8579 if (status == NO_ERROR) { 8580 status = cmdStatus; 8581 } 8582 } 8583 dev = device & AUDIO_DEVICE_IN_ALL; 8584 if (dev) { 8585 status_t cmdStatus; 8586 uint32_t size = sizeof(status_t); 8587 8588 status_t status2 = (*mEffectInterface)->command(mEffectInterface, 8589 EFFECT_CMD_SET_INPUT_DEVICE, 8590 sizeof(uint32_t), 8591 &dev, 8592 &size, 8593 &cmdStatus); 8594 if (status2 == NO_ERROR) { 8595 status2 = cmdStatus; 8596 } 8597 if (status == NO_ERROR) { 8598 status = status2; 8599 } 8600 } 8601 } 8602 return status; 8603} 8604 8605status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode) 8606{ 8607 Mutex::Autolock _l(mLock); 8608 status_t status = NO_ERROR; 8609 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) { 8610 status_t cmdStatus; 8611 uint32_t size = sizeof(status_t); 8612 status = (*mEffectInterface)->command(mEffectInterface, 8613 EFFECT_CMD_SET_AUDIO_MODE, 8614 sizeof(audio_mode_t), 8615 &mode, 8616 &size, 8617 &cmdStatus); 8618 if (status == NO_ERROR) { 8619 status = cmdStatus; 8620 } 8621 } 8622 return status; 8623} 8624 8625void AudioFlinger::EffectModule::setSuspended(bool suspended) 8626{ 8627 Mutex::Autolock _l(mLock); 8628 mSuspended = suspended; 8629} 8630 8631bool AudioFlinger::EffectModule::suspended() const 8632{ 8633 Mutex::Autolock _l(mLock); 8634 return mSuspended; 8635} 8636 8637status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args) 8638{ 8639 const size_t SIZE = 256; 8640 char buffer[SIZE]; 8641 String8 result; 8642 8643 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId); 8644 result.append(buffer); 8645 8646 bool locked = tryLock(mLock); 8647 // failed to lock - AudioFlinger is probably deadlocked 8648 if (!locked) { 8649 result.append("\t\tCould not lock Fx mutex:\n"); 8650 } 8651 8652 result.append("\t\tSession Status State Engine:\n"); 8653 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n", 8654 mSessionId, mStatus, mState, (uint32_t)mEffectInterface); 8655 result.append(buffer); 8656 8657 result.append("\t\tDescriptor:\n"); 8658 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 8659 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, 8660 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2], 8661 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); 8662 result.append(buffer); 8663 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 8664 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion, 8665 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2], 8666 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); 8667 result.append(buffer); 8668 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n", 8669 mDescriptor.apiVersion, 8670 mDescriptor.flags); 8671 result.append(buffer); 8672 snprintf(buffer, SIZE, "\t\t- name: %s\n", 8673 mDescriptor.name); 8674 result.append(buffer); 8675 snprintf(buffer, SIZE, "\t\t- implementor: %s\n", 8676 mDescriptor.implementor); 8677 result.append(buffer); 8678 8679 result.append("\t\t- Input configuration:\n"); 8680 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 8681 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 8682 (uint32_t)mConfig.inputCfg.buffer.raw, 8683 mConfig.inputCfg.buffer.frameCount, 8684 mConfig.inputCfg.samplingRate, 8685 mConfig.inputCfg.channels, 8686 mConfig.inputCfg.format); 8687 result.append(buffer); 8688 8689 result.append("\t\t- Output configuration:\n"); 8690 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 8691 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 8692 (uint32_t)mConfig.outputCfg.buffer.raw, 8693 mConfig.outputCfg.buffer.frameCount, 8694 mConfig.outputCfg.samplingRate, 8695 mConfig.outputCfg.channels, 8696 mConfig.outputCfg.format); 8697 result.append(buffer); 8698 8699 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size()); 8700 result.append(buffer); 8701 result.append("\t\t\tPid Priority Ctrl Locked client server\n"); 8702 for (size_t i = 0; i < mHandles.size(); ++i) { 8703 sp<EffectHandle> handle = mHandles[i].promote(); 8704 if (handle != 0) { 8705 handle->dump(buffer, SIZE); 8706 result.append(buffer); 8707 } 8708 } 8709 8710 result.append("\n"); 8711 8712 write(fd, result.string(), result.length()); 8713 8714 if (locked) { 8715 mLock.unlock(); 8716 } 8717 8718 return NO_ERROR; 8719} 8720 8721// ---------------------------------------------------------------------------- 8722// EffectHandle implementation 8723// ---------------------------------------------------------------------------- 8724 8725#undef LOG_TAG 8726#define LOG_TAG "AudioFlinger::EffectHandle" 8727 8728AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect, 8729 const sp<AudioFlinger::Client>& client, 8730 const sp<IEffectClient>& effectClient, 8731 int32_t priority) 8732 : BnEffect(), 8733 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL), 8734 mPriority(priority), mHasControl(false), mEnabled(false) 8735{ 8736 ALOGV("constructor %p", this); 8737 8738 if (client == 0) { 8739 return; 8740 } 8741 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int); 8742 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset); 8743 if (mCblkMemory != 0) { 8744 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer()); 8745 8746 if (mCblk != NULL) { 8747 new(mCblk) effect_param_cblk_t(); 8748 mBuffer = (uint8_t *)mCblk + bufOffset; 8749 } 8750 } else { 8751 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t)); 8752 return; 8753 } 8754} 8755 8756AudioFlinger::EffectHandle::~EffectHandle() 8757{ 8758 ALOGV("Destructor %p", this); 8759 disconnect(false); 8760 ALOGV("Destructor DONE %p", this); 8761} 8762 8763status_t AudioFlinger::EffectHandle::enable() 8764{ 8765 ALOGV("enable %p", this); 8766 if (!mHasControl) return INVALID_OPERATION; 8767 if (mEffect == 0) return DEAD_OBJECT; 8768 8769 if (mEnabled) { 8770 return NO_ERROR; 8771 } 8772 8773 mEnabled = true; 8774 8775 sp<ThreadBase> thread = mEffect->thread().promote(); 8776 if (thread != 0) { 8777 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId()); 8778 } 8779 8780 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled 8781 if (mEffect->suspended()) { 8782 return NO_ERROR; 8783 } 8784 8785 status_t status = mEffect->setEnabled(true); 8786 if (status != NO_ERROR) { 8787 if (thread != 0) { 8788 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 8789 } 8790 mEnabled = false; 8791 } 8792 return status; 8793} 8794 8795status_t AudioFlinger::EffectHandle::disable() 8796{ 8797 ALOGV("disable %p", this); 8798 if (!mHasControl) return INVALID_OPERATION; 8799 if (mEffect == 0) return DEAD_OBJECT; 8800 8801 if (!mEnabled) { 8802 return NO_ERROR; 8803 } 8804 mEnabled = false; 8805 8806 if (mEffect->suspended()) { 8807 return NO_ERROR; 8808 } 8809 8810 status_t status = mEffect->setEnabled(false); 8811 8812 sp<ThreadBase> thread = mEffect->thread().promote(); 8813 if (thread != 0) { 8814 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 8815 } 8816 8817 return status; 8818} 8819 8820void AudioFlinger::EffectHandle::disconnect() 8821{ 8822 disconnect(true); 8823} 8824 8825void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast) 8826{ 8827 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false"); 8828 if (mEffect == 0) { 8829 return; 8830 } 8831 mEffect->disconnect(this, unpinIfLast); 8832 8833 if (mHasControl && mEnabled) { 8834 sp<ThreadBase> thread = mEffect->thread().promote(); 8835 if (thread != 0) { 8836 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 8837 } 8838 } 8839 8840 // release sp on module => module destructor can be called now 8841 mEffect.clear(); 8842 if (mClient != 0) { 8843 if (mCblk != NULL) { 8844 // unlike ~TrackBase(), mCblk is never a local new, so don't delete 8845 mCblk->~effect_param_cblk_t(); // destroy our shared-structure. 8846 } 8847 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 8848 // Client destructor must run with AudioFlinger mutex locked 8849 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 8850 mClient.clear(); 8851 } 8852} 8853 8854status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode, 8855 uint32_t cmdSize, 8856 void *pCmdData, 8857 uint32_t *replySize, 8858 void *pReplyData) 8859{ 8860// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", 8861// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get()); 8862 8863 // only get parameter command is permitted for applications not controlling the effect 8864 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) { 8865 return INVALID_OPERATION; 8866 } 8867 if (mEffect == 0) return DEAD_OBJECT; 8868 if (mClient == 0) return INVALID_OPERATION; 8869 8870 // handle commands that are not forwarded transparently to effect engine 8871 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) { 8872 // No need to trylock() here as this function is executed in the binder thread serving a particular client process: 8873 // no risk to block the whole media server process or mixer threads is we are stuck here 8874 Mutex::Autolock _l(mCblk->lock); 8875 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE || 8876 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) { 8877 mCblk->serverIndex = 0; 8878 mCblk->clientIndex = 0; 8879 return BAD_VALUE; 8880 } 8881 status_t status = NO_ERROR; 8882 while (mCblk->serverIndex < mCblk->clientIndex) { 8883 int reply; 8884 uint32_t rsize = sizeof(int); 8885 int *p = (int *)(mBuffer + mCblk->serverIndex); 8886 int size = *p++; 8887 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) { 8888 ALOGW("command(): invalid parameter block size"); 8889 break; 8890 } 8891 effect_param_t *param = (effect_param_t *)p; 8892 if (param->psize == 0 || param->vsize == 0) { 8893 ALOGW("command(): null parameter or value size"); 8894 mCblk->serverIndex += size; 8895 continue; 8896 } 8897 uint32_t psize = sizeof(effect_param_t) + 8898 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + 8899 param->vsize; 8900 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, 8901 psize, 8902 p, 8903 &rsize, 8904 &reply); 8905 // stop at first error encountered 8906 if (ret != NO_ERROR) { 8907 status = ret; 8908 *(int *)pReplyData = reply; 8909 break; 8910 } else if (reply != NO_ERROR) { 8911 *(int *)pReplyData = reply; 8912 break; 8913 } 8914 mCblk->serverIndex += size; 8915 } 8916 mCblk->serverIndex = 0; 8917 mCblk->clientIndex = 0; 8918 return status; 8919 } else if (cmdCode == EFFECT_CMD_ENABLE) { 8920 *(int *)pReplyData = NO_ERROR; 8921 return enable(); 8922 } else if (cmdCode == EFFECT_CMD_DISABLE) { 8923 *(int *)pReplyData = NO_ERROR; 8924 return disable(); 8925 } 8926 8927 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 8928} 8929 8930void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled) 8931{ 8932 ALOGV("setControl %p control %d", this, hasControl); 8933 8934 mHasControl = hasControl; 8935 mEnabled = enabled; 8936 8937 if (signal && mEffectClient != 0) { 8938 mEffectClient->controlStatusChanged(hasControl); 8939 } 8940} 8941 8942void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode, 8943 uint32_t cmdSize, 8944 void *pCmdData, 8945 uint32_t replySize, 8946 void *pReplyData) 8947{ 8948 if (mEffectClient != 0) { 8949 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 8950 } 8951} 8952 8953 8954 8955void AudioFlinger::EffectHandle::setEnabled(bool enabled) 8956{ 8957 if (mEffectClient != 0) { 8958 mEffectClient->enableStatusChanged(enabled); 8959 } 8960} 8961 8962status_t AudioFlinger::EffectHandle::onTransact( 8963 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 8964{ 8965 return BnEffect::onTransact(code, data, reply, flags); 8966} 8967 8968 8969void AudioFlinger::EffectHandle::dump(char* buffer, size_t size) 8970{ 8971 bool locked = mCblk != NULL && tryLock(mCblk->lock); 8972 8973 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n", 8974 (mClient == 0) ? getpid_cached : mClient->pid(), 8975 mPriority, 8976 mHasControl, 8977 !locked, 8978 mCblk ? mCblk->clientIndex : 0, 8979 mCblk ? mCblk->serverIndex : 0 8980 ); 8981 8982 if (locked) { 8983 mCblk->lock.unlock(); 8984 } 8985} 8986 8987#undef LOG_TAG 8988#define LOG_TAG "AudioFlinger::EffectChain" 8989 8990AudioFlinger::EffectChain::EffectChain(ThreadBase *thread, 8991 int sessionId) 8992 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0), 8993 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX), 8994 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX) 8995{ 8996 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 8997 if (thread == NULL) { 8998 return; 8999 } 9000 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) / 9001 thread->frameCount(); 9002} 9003 9004AudioFlinger::EffectChain::~EffectChain() 9005{ 9006 if (mOwnInBuffer) { 9007 delete mInBuffer; 9008 } 9009 9010} 9011 9012// getEffectFromDesc_l() must be called with ThreadBase::mLock held 9013sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor) 9014{ 9015 size_t size = mEffects.size(); 9016 9017 for (size_t i = 0; i < size; i++) { 9018 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) { 9019 return mEffects[i]; 9020 } 9021 } 9022 return 0; 9023} 9024 9025// getEffectFromId_l() must be called with ThreadBase::mLock held 9026sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id) 9027{ 9028 size_t size = mEffects.size(); 9029 9030 for (size_t i = 0; i < size; i++) { 9031 // by convention, return first effect if id provided is 0 (0 is never a valid id) 9032 if (id == 0 || mEffects[i]->id() == id) { 9033 return mEffects[i]; 9034 } 9035 } 9036 return 0; 9037} 9038 9039// getEffectFromType_l() must be called with ThreadBase::mLock held 9040sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l( 9041 const effect_uuid_t *type) 9042{ 9043 size_t size = mEffects.size(); 9044 9045 for (size_t i = 0; i < size; i++) { 9046 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) { 9047 return mEffects[i]; 9048 } 9049 } 9050 return 0; 9051} 9052 9053void AudioFlinger::EffectChain::clearInputBuffer() 9054{ 9055 Mutex::Autolock _l(mLock); 9056 sp<ThreadBase> thread = mThread.promote(); 9057 if (thread == 0) { 9058 ALOGW("clearInputBuffer(): cannot promote mixer thread"); 9059 return; 9060 } 9061 clearInputBuffer_l(thread); 9062} 9063 9064// Must be called with EffectChain::mLock locked 9065void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread) 9066{ 9067 size_t numSamples = thread->frameCount() * thread->channelCount(); 9068 memset(mInBuffer, 0, numSamples * sizeof(int16_t)); 9069 9070} 9071 9072// Must be called with EffectChain::mLock locked 9073void AudioFlinger::EffectChain::process_l() 9074{ 9075 sp<ThreadBase> thread = mThread.promote(); 9076 if (thread == 0) { 9077 ALOGW("process_l(): cannot promote mixer thread"); 9078 return; 9079 } 9080 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) || 9081 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE); 9082 // always process effects unless no more tracks are on the session and the effect tail 9083 // has been rendered 9084 bool doProcess = true; 9085 if (!isGlobalSession) { 9086 bool tracksOnSession = (trackCnt() != 0); 9087 9088 if (!tracksOnSession && mTailBufferCount == 0) { 9089 doProcess = false; 9090 } 9091 9092 if (activeTrackCnt() == 0) { 9093 // if no track is active and the effect tail has not been rendered, 9094 // the input buffer must be cleared here as the mixer process will not do it 9095 if (tracksOnSession || mTailBufferCount > 0) { 9096 clearInputBuffer_l(thread); 9097 if (mTailBufferCount > 0) { 9098 mTailBufferCount--; 9099 } 9100 } 9101 } 9102 } 9103 9104 size_t size = mEffects.size(); 9105 if (doProcess) { 9106 for (size_t i = 0; i < size; i++) { 9107 mEffects[i]->process(); 9108 } 9109 } 9110 for (size_t i = 0; i < size; i++) { 9111 mEffects[i]->updateState(); 9112 } 9113} 9114 9115// addEffect_l() must be called with PlaybackThread::mLock held 9116status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect) 9117{ 9118 effect_descriptor_t desc = effect->desc(); 9119 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK; 9120 9121 Mutex::Autolock _l(mLock); 9122 effect->setChain(this); 9123 sp<ThreadBase> thread = mThread.promote(); 9124 if (thread == 0) { 9125 return NO_INIT; 9126 } 9127 effect->setThread(thread); 9128 9129 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 9130 // Auxiliary effects are inserted at the beginning of mEffects vector as 9131 // they are processed first and accumulated in chain input buffer 9132 mEffects.insertAt(effect, 0); 9133 9134 // the input buffer for auxiliary effect contains mono samples in 9135 // 32 bit format. This is to avoid saturation in AudoMixer 9136 // accumulation stage. Saturation is done in EffectModule::process() before 9137 // calling the process in effect engine 9138 size_t numSamples = thread->frameCount(); 9139 int32_t *buffer = new int32_t[numSamples]; 9140 memset(buffer, 0, numSamples * sizeof(int32_t)); 9141 effect->setInBuffer((int16_t *)buffer); 9142 // auxiliary effects output samples to chain input buffer for further processing 9143 // by insert effects 9144 effect->setOutBuffer(mInBuffer); 9145 } else { 9146 // Insert effects are inserted at the end of mEffects vector as they are processed 9147 // after track and auxiliary effects. 9148 // Insert effect order as a function of indicated preference: 9149 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if 9150 // another effect is present 9151 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the 9152 // last effect claiming first position 9153 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the 9154 // first effect claiming last position 9155 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last 9156 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is 9157 // already present 9158 9159 size_t size = mEffects.size(); 9160 size_t idx_insert = size; 9161 ssize_t idx_insert_first = -1; 9162 ssize_t idx_insert_last = -1; 9163 9164 for (size_t i = 0; i < size; i++) { 9165 effect_descriptor_t d = mEffects[i]->desc(); 9166 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK; 9167 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK; 9168 if (iMode == EFFECT_FLAG_TYPE_INSERT) { 9169 // check invalid effect chaining combinations 9170 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE || 9171 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) { 9172 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name); 9173 return INVALID_OPERATION; 9174 } 9175 // remember position of first insert effect and by default 9176 // select this as insert position for new effect 9177 if (idx_insert == size) { 9178 idx_insert = i; 9179 } 9180 // remember position of last insert effect claiming 9181 // first position 9182 if (iPref == EFFECT_FLAG_INSERT_FIRST) { 9183 idx_insert_first = i; 9184 } 9185 // remember position of first insert effect claiming 9186 // last position 9187 if (iPref == EFFECT_FLAG_INSERT_LAST && 9188 idx_insert_last == -1) { 9189 idx_insert_last = i; 9190 } 9191 } 9192 } 9193 9194 // modify idx_insert from first position if needed 9195 if (insertPref == EFFECT_FLAG_INSERT_LAST) { 9196 if (idx_insert_last != -1) { 9197 idx_insert = idx_insert_last; 9198 } else { 9199 idx_insert = size; 9200 } 9201 } else { 9202 if (idx_insert_first != -1) { 9203 idx_insert = idx_insert_first + 1; 9204 } 9205 } 9206 9207 // always read samples from chain input buffer 9208 effect->setInBuffer(mInBuffer); 9209 9210 // if last effect in the chain, output samples to chain 9211 // output buffer, otherwise to chain input buffer 9212 if (idx_insert == size) { 9213 if (idx_insert != 0) { 9214 mEffects[idx_insert-1]->setOutBuffer(mInBuffer); 9215 mEffects[idx_insert-1]->configure(); 9216 } 9217 effect->setOutBuffer(mOutBuffer); 9218 } else { 9219 effect->setOutBuffer(mInBuffer); 9220 } 9221 mEffects.insertAt(effect, idx_insert); 9222 9223 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert); 9224 } 9225 effect->configure(); 9226 return NO_ERROR; 9227} 9228 9229// removeEffect_l() must be called with PlaybackThread::mLock held 9230size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect) 9231{ 9232 Mutex::Autolock _l(mLock); 9233 size_t size = mEffects.size(); 9234 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK; 9235 9236 for (size_t i = 0; i < size; i++) { 9237 if (effect == mEffects[i]) { 9238 // calling stop here will remove pre-processing effect from the audio HAL. 9239 // This is safe as we hold the EffectChain mutex which guarantees that we are not in 9240 // the middle of a read from audio HAL 9241 if (mEffects[i]->state() == EffectModule::ACTIVE || 9242 mEffects[i]->state() == EffectModule::STOPPING) { 9243 mEffects[i]->stop(); 9244 } 9245 if (type == EFFECT_FLAG_TYPE_AUXILIARY) { 9246 delete[] effect->inBuffer(); 9247 } else { 9248 if (i == size - 1 && i != 0) { 9249 mEffects[i - 1]->setOutBuffer(mOutBuffer); 9250 mEffects[i - 1]->configure(); 9251 } 9252 } 9253 mEffects.removeAt(i); 9254 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i); 9255 break; 9256 } 9257 } 9258 9259 return mEffects.size(); 9260} 9261 9262// setDevice_l() must be called with PlaybackThread::mLock held 9263void AudioFlinger::EffectChain::setDevice_l(uint32_t device) 9264{ 9265 size_t size = mEffects.size(); 9266 for (size_t i = 0; i < size; i++) { 9267 mEffects[i]->setDevice(device); 9268 } 9269} 9270 9271// setMode_l() must be called with PlaybackThread::mLock held 9272void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode) 9273{ 9274 size_t size = mEffects.size(); 9275 for (size_t i = 0; i < size; i++) { 9276 mEffects[i]->setMode(mode); 9277 } 9278} 9279 9280// setVolume_l() must be called with PlaybackThread::mLock held 9281bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right) 9282{ 9283 uint32_t newLeft = *left; 9284 uint32_t newRight = *right; 9285 bool hasControl = false; 9286 int ctrlIdx = -1; 9287 size_t size = mEffects.size(); 9288 9289 // first update volume controller 9290 for (size_t i = size; i > 0; i--) { 9291 if (mEffects[i - 1]->isProcessEnabled() && 9292 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) { 9293 ctrlIdx = i - 1; 9294 hasControl = true; 9295 break; 9296 } 9297 } 9298 9299 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) { 9300 if (hasControl) { 9301 *left = mNewLeftVolume; 9302 *right = mNewRightVolume; 9303 } 9304 return hasControl; 9305 } 9306 9307 mVolumeCtrlIdx = ctrlIdx; 9308 mLeftVolume = newLeft; 9309 mRightVolume = newRight; 9310 9311 // second get volume update from volume controller 9312 if (ctrlIdx >= 0) { 9313 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true); 9314 mNewLeftVolume = newLeft; 9315 mNewRightVolume = newRight; 9316 } 9317 // then indicate volume to all other effects in chain. 9318 // Pass altered volume to effects before volume controller 9319 // and requested volume to effects after controller 9320 uint32_t lVol = newLeft; 9321 uint32_t rVol = newRight; 9322 9323 for (size_t i = 0; i < size; i++) { 9324 if ((int)i == ctrlIdx) continue; 9325 // this also works for ctrlIdx == -1 when there is no volume controller 9326 if ((int)i > ctrlIdx) { 9327 lVol = *left; 9328 rVol = *right; 9329 } 9330 mEffects[i]->setVolume(&lVol, &rVol, false); 9331 } 9332 *left = newLeft; 9333 *right = newRight; 9334 9335 return hasControl; 9336} 9337 9338status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args) 9339{ 9340 const size_t SIZE = 256; 9341 char buffer[SIZE]; 9342 String8 result; 9343 9344 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId); 9345 result.append(buffer); 9346 9347 bool locked = tryLock(mLock); 9348 // failed to lock - AudioFlinger is probably deadlocked 9349 if (!locked) { 9350 result.append("\tCould not lock mutex:\n"); 9351 } 9352 9353 result.append("\tNum fx In buffer Out buffer Active tracks:\n"); 9354 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n", 9355 mEffects.size(), 9356 (uint32_t)mInBuffer, 9357 (uint32_t)mOutBuffer, 9358 mActiveTrackCnt); 9359 result.append(buffer); 9360 write(fd, result.string(), result.size()); 9361 9362 for (size_t i = 0; i < mEffects.size(); ++i) { 9363 sp<EffectModule> effect = mEffects[i]; 9364 if (effect != 0) { 9365 effect->dump(fd, args); 9366 } 9367 } 9368 9369 if (locked) { 9370 mLock.unlock(); 9371 } 9372 9373 return NO_ERROR; 9374} 9375 9376// must be called with ThreadBase::mLock held 9377void AudioFlinger::EffectChain::setEffectSuspended_l( 9378 const effect_uuid_t *type, bool suspend) 9379{ 9380 sp<SuspendedEffectDesc> desc; 9381 // use effect type UUID timelow as key as there is no real risk of identical 9382 // timeLow fields among effect type UUIDs. 9383 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow); 9384 if (suspend) { 9385 if (index >= 0) { 9386 desc = mSuspendedEffects.valueAt(index); 9387 } else { 9388 desc = new SuspendedEffectDesc(); 9389 memcpy(&desc->mType, type, sizeof(effect_uuid_t)); 9390 mSuspendedEffects.add(type->timeLow, desc); 9391 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow); 9392 } 9393 if (desc->mRefCount++ == 0) { 9394 sp<EffectModule> effect = getEffectIfEnabled(type); 9395 if (effect != 0) { 9396 desc->mEffect = effect; 9397 effect->setSuspended(true); 9398 effect->setEnabled(false); 9399 } 9400 } 9401 } else { 9402 if (index < 0) { 9403 return; 9404 } 9405 desc = mSuspendedEffects.valueAt(index); 9406 if (desc->mRefCount <= 0) { 9407 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount); 9408 desc->mRefCount = 1; 9409 } 9410 if (--desc->mRefCount == 0) { 9411 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 9412 if (desc->mEffect != 0) { 9413 sp<EffectModule> effect = desc->mEffect.promote(); 9414 if (effect != 0) { 9415 effect->setSuspended(false); 9416 sp<EffectHandle> handle = effect->controlHandle(); 9417 if (handle != 0) { 9418 effect->setEnabled(handle->enabled()); 9419 } 9420 } 9421 desc->mEffect.clear(); 9422 } 9423 mSuspendedEffects.removeItemsAt(index); 9424 } 9425 } 9426} 9427 9428// must be called with ThreadBase::mLock held 9429void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend) 9430{ 9431 sp<SuspendedEffectDesc> desc; 9432 9433 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 9434 if (suspend) { 9435 if (index >= 0) { 9436 desc = mSuspendedEffects.valueAt(index); 9437 } else { 9438 desc = new SuspendedEffectDesc(); 9439 mSuspendedEffects.add((int)kKeyForSuspendAll, desc); 9440 ALOGV("setEffectSuspendedAll_l() add entry for 0"); 9441 } 9442 if (desc->mRefCount++ == 0) { 9443 Vector< sp<EffectModule> > effects; 9444 getSuspendEligibleEffects(effects); 9445 for (size_t i = 0; i < effects.size(); i++) { 9446 setEffectSuspended_l(&effects[i]->desc().type, true); 9447 } 9448 } 9449 } else { 9450 if (index < 0) { 9451 return; 9452 } 9453 desc = mSuspendedEffects.valueAt(index); 9454 if (desc->mRefCount <= 0) { 9455 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount); 9456 desc->mRefCount = 1; 9457 } 9458 if (--desc->mRefCount == 0) { 9459 Vector<const effect_uuid_t *> types; 9460 for (size_t i = 0; i < mSuspendedEffects.size(); i++) { 9461 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) { 9462 continue; 9463 } 9464 types.add(&mSuspendedEffects.valueAt(i)->mType); 9465 } 9466 for (size_t i = 0; i < types.size(); i++) { 9467 setEffectSuspended_l(types[i], false); 9468 } 9469 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 9470 mSuspendedEffects.removeItem((int)kKeyForSuspendAll); 9471 } 9472 } 9473} 9474 9475 9476// The volume effect is used for automated tests only 9477#ifndef OPENSL_ES_H_ 9478static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6, 9479 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }; 9480const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_; 9481#endif //OPENSL_ES_H_ 9482 9483bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc) 9484{ 9485 // auxiliary effects and visualizer are never suspended on output mix 9486 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && 9487 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) || 9488 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) || 9489 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) { 9490 return false; 9491 } 9492 return true; 9493} 9494 9495void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects) 9496{ 9497 effects.clear(); 9498 for (size_t i = 0; i < mEffects.size(); i++) { 9499 if (isEffectEligibleForSuspend(mEffects[i]->desc())) { 9500 effects.add(mEffects[i]); 9501 } 9502 } 9503} 9504 9505sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled( 9506 const effect_uuid_t *type) 9507{ 9508 sp<EffectModule> effect = getEffectFromType_l(type); 9509 return effect != 0 && effect->isEnabled() ? effect : 0; 9510} 9511 9512void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 9513 bool enabled) 9514{ 9515 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 9516 if (enabled) { 9517 if (index < 0) { 9518 // if the effect is not suspend check if all effects are suspended 9519 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 9520 if (index < 0) { 9521 return; 9522 } 9523 if (!isEffectEligibleForSuspend(effect->desc())) { 9524 return; 9525 } 9526 setEffectSuspended_l(&effect->desc().type, enabled); 9527 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 9528 if (index < 0) { 9529 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!"); 9530 return; 9531 } 9532 } 9533 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x", 9534 effect->desc().type.timeLow); 9535 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 9536 // if effect is requested to suspended but was not yet enabled, supend it now. 9537 if (desc->mEffect == 0) { 9538 desc->mEffect = effect; 9539 effect->setEnabled(false); 9540 effect->setSuspended(true); 9541 } 9542 } else { 9543 if (index < 0) { 9544 return; 9545 } 9546 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x", 9547 effect->desc().type.timeLow); 9548 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 9549 desc->mEffect.clear(); 9550 effect->setSuspended(false); 9551 } 9552} 9553 9554#undef LOG_TAG 9555#define LOG_TAG "AudioFlinger" 9556 9557// ---------------------------------------------------------------------------- 9558 9559status_t AudioFlinger::onTransact( 9560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 9561{ 9562 return BnAudioFlinger::onTransact(code, data, reply, flags); 9563} 9564 9565}; // namespace android 9566