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