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