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