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