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