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