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