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