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