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