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