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