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