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