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