AudioFlinger.cpp revision b61ec89bb0c701b3bd06eb658f854230681f8b39
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 if (mClient == 0) { 3295 delete mCblk; 3296 } else { 3297 mCblk->~audio_track_cblk_t(); // destroy our shared-structure. 3298 } 3299 } 3300 mCblkMemory.clear(); // and free the shared memory 3301 if (mClient != 0) { 3302 // Client destructor must run with AudioFlinger mutex locked 3303 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 3304 // If the client's reference count drops to zero, the associated destructor 3305 // must run with AudioFlinger lock held. Thus the explicit clear() rather than 3306 // relying on the automatic clear() at end of scope. 3307 mClient.clear(); 3308 } 3309} 3310 3311void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) 3312{ 3313 buffer->raw = NULL; 3314 mFrameCount = buffer->frameCount; 3315 step(); 3316 buffer->frameCount = 0; 3317} 3318 3319bool AudioFlinger::ThreadBase::TrackBase::step() { 3320 bool result; 3321 audio_track_cblk_t* cblk = this->cblk(); 3322 3323 result = cblk->stepServer(mFrameCount); 3324 if (!result) { 3325 ALOGV("stepServer failed acquiring cblk mutex"); 3326 mFlags |= STEPSERVER_FAILED; 3327 } 3328 return result; 3329} 3330 3331void AudioFlinger::ThreadBase::TrackBase::reset() { 3332 audio_track_cblk_t* cblk = this->cblk(); 3333 3334 cblk->user = 0; 3335 cblk->server = 0; 3336 cblk->userBase = 0; 3337 cblk->serverBase = 0; 3338 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK); 3339 ALOGV("TrackBase::reset"); 3340} 3341 3342int AudioFlinger::ThreadBase::TrackBase::sampleRate() const { 3343 return (int)mCblk->sampleRate; 3344} 3345 3346void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const { 3347 audio_track_cblk_t* cblk = this->cblk(); 3348 size_t frameSize = cblk->frameSize; 3349 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize; 3350 int8_t *bufferEnd = bufferStart + frames * frameSize; 3351 3352 // Check validity of returned pointer in case the track control block would have been corrupted. 3353 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd || 3354 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) { 3355 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \ 3356 server %d, serverBase %d, user %d, userBase %d", 3357 bufferStart, bufferEnd, mBuffer, mBufferEnd, 3358 cblk->server, cblk->serverBase, cblk->user, cblk->userBase); 3359 return NULL; 3360 } 3361 3362 return bufferStart; 3363} 3364 3365// ---------------------------------------------------------------------------- 3366 3367// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 3368AudioFlinger::PlaybackThread::Track::Track( 3369 const wp<ThreadBase>& thread, 3370 const sp<Client>& client, 3371 audio_stream_type_t streamType, 3372 uint32_t sampleRate, 3373 audio_format_t format, 3374 uint32_t channelMask, 3375 int frameCount, 3376 const sp<IMemory>& sharedBuffer, 3377 int sessionId) 3378 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId), 3379 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), 3380 mAuxEffectId(0), mHasVolumeController(false) 3381{ 3382 if (mCblk != NULL) { 3383 sp<ThreadBase> baseThread = thread.promote(); 3384 if (baseThread != 0) { 3385 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get(); 3386 mName = playbackThread->getTrackName_l(); 3387 mMainBuffer = playbackThread->mixBuffer(); 3388 } 3389 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3390 if (mName < 0) { 3391 ALOGE("no more track names available"); 3392 } 3393 mStreamType = streamType; 3394 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of 3395 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack 3396 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t); 3397 } 3398} 3399 3400AudioFlinger::PlaybackThread::Track::~Track() 3401{ 3402 ALOGV("PlaybackThread::Track destructor"); 3403 sp<ThreadBase> thread = mThread.promote(); 3404 if (thread != 0) { 3405 Mutex::Autolock _l(thread->mLock); 3406 mState = TERMINATED; 3407 } 3408} 3409 3410void AudioFlinger::PlaybackThread::Track::destroy() 3411{ 3412 // NOTE: destroyTrack_l() can remove a strong reference to this Track 3413 // by removing it from mTracks vector, so there is a risk that this Tracks's 3414 // desctructor is called. As the destructor needs to lock mLock, 3415 // we must acquire a strong reference on this Track before locking mLock 3416 // here so that the destructor is called only when exiting this function. 3417 // On the other hand, as long as Track::destroy() is only called by 3418 // TrackHandle destructor, the TrackHandle still holds a strong ref on 3419 // this Track with its member mTrack. 3420 sp<Track> keep(this); 3421 { // scope for mLock 3422 sp<ThreadBase> thread = mThread.promote(); 3423 if (thread != 0) { 3424 if (!isOutputTrack()) { 3425 if (mState == ACTIVE || mState == RESUMING) { 3426 AudioSystem::stopOutput(thread->id(), 3427 (audio_stream_type_t)mStreamType, 3428 mSessionId); 3429 3430 // to track the speaker usage 3431 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3432 } 3433 AudioSystem::releaseOutput(thread->id()); 3434 } 3435 Mutex::Autolock _l(thread->mLock); 3436 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3437 playbackThread->destroyTrack_l(this); 3438 } 3439 } 3440} 3441 3442void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 3443{ 3444 uint32_t vlr = mCblk->getVolumeLR(); 3445 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", 3446 mName - AudioMixer::TRACK0, 3447 (mClient == 0) ? getpid() : mClient->pid(), 3448 mStreamType, 3449 mFormat, 3450 mChannelMask, 3451 mSessionId, 3452 mFrameCount, 3453 mState, 3454 mMute, 3455 mFillingUpStatus, 3456 mCblk->sampleRate, 3457 vlr & 0xFFFF, 3458 vlr >> 16, 3459 mCblk->server, 3460 mCblk->user, 3461 (int)mMainBuffer, 3462 (int)mAuxBuffer); 3463} 3464 3465status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer) 3466{ 3467 audio_track_cblk_t* cblk = this->cblk(); 3468 uint32_t framesReady; 3469 uint32_t framesReq = buffer->frameCount; 3470 3471 // Check if last stepServer failed, try to step now 3472 if (mFlags & TrackBase::STEPSERVER_FAILED) { 3473 if (!step()) goto getNextBuffer_exit; 3474 ALOGV("stepServer recovered"); 3475 mFlags &= ~TrackBase::STEPSERVER_FAILED; 3476 } 3477 3478 framesReady = cblk->framesReady(); 3479 3480 if (CC_LIKELY(framesReady)) { 3481 uint32_t s = cblk->server; 3482 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 3483 3484 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd; 3485 if (framesReq > framesReady) { 3486 framesReq = framesReady; 3487 } 3488 if (s + framesReq > bufferEnd) { 3489 framesReq = bufferEnd - s; 3490 } 3491 3492 buffer->raw = getBuffer(s, framesReq); 3493 if (buffer->raw == NULL) goto getNextBuffer_exit; 3494 3495 buffer->frameCount = framesReq; 3496 return NO_ERROR; 3497 } 3498 3499getNextBuffer_exit: 3500 buffer->raw = NULL; 3501 buffer->frameCount = 0; 3502 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get()); 3503 return NOT_ENOUGH_DATA; 3504} 3505 3506bool AudioFlinger::PlaybackThread::Track::isReady() const { 3507 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true; 3508 3509 if (mCblk->framesReady() >= mCblk->frameCount || 3510 (mCblk->flags & CBLK_FORCEREADY_MSK)) { 3511 mFillingUpStatus = FS_FILLED; 3512 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 3513 return true; 3514 } 3515 return false; 3516} 3517 3518status_t AudioFlinger::PlaybackThread::Track::start() 3519{ 3520 status_t status = NO_ERROR; 3521 ALOGV("start(%d), calling thread %d session %d", 3522 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 3523 sp<ThreadBase> thread = mThread.promote(); 3524 if (thread != 0) { 3525 Mutex::Autolock _l(thread->mLock); 3526 track_state state = mState; 3527 // here the track could be either new, or restarted 3528 // in both cases "unstop" the track 3529 if (mState == PAUSED) { 3530 mState = TrackBase::RESUMING; 3531 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 3532 } else { 3533 mState = TrackBase::ACTIVE; 3534 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 3535 } 3536 3537 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) { 3538 thread->mLock.unlock(); 3539 status = AudioSystem::startOutput(thread->id(), 3540 (audio_stream_type_t)mStreamType, 3541 mSessionId); 3542 thread->mLock.lock(); 3543 3544 // to track the speaker usage 3545 if (status == NO_ERROR) { 3546 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 3547 } 3548 } 3549 if (status == NO_ERROR) { 3550 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3551 playbackThread->addTrack_l(this); 3552 } else { 3553 mState = state; 3554 } 3555 } else { 3556 status = BAD_VALUE; 3557 } 3558 return status; 3559} 3560 3561void AudioFlinger::PlaybackThread::Track::stop() 3562{ 3563 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3564 sp<ThreadBase> thread = mThread.promote(); 3565 if (thread != 0) { 3566 Mutex::Autolock _l(thread->mLock); 3567 track_state state = mState; 3568 if (mState > STOPPED) { 3569 mState = STOPPED; 3570 // If the track is not active (PAUSED and buffers full), flush buffers 3571 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3572 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 3573 reset(); 3574 } 3575 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread); 3576 } 3577 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) { 3578 thread->mLock.unlock(); 3579 AudioSystem::stopOutput(thread->id(), 3580 (audio_stream_type_t)mStreamType, 3581 mSessionId); 3582 thread->mLock.lock(); 3583 3584 // to track the speaker usage 3585 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3586 } 3587 } 3588} 3589 3590void AudioFlinger::PlaybackThread::Track::pause() 3591{ 3592 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3593 sp<ThreadBase> thread = mThread.promote(); 3594 if (thread != 0) { 3595 Mutex::Autolock _l(thread->mLock); 3596 if (mState == ACTIVE || mState == RESUMING) { 3597 mState = PAUSING; 3598 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 3599 if (!isOutputTrack()) { 3600 thread->mLock.unlock(); 3601 AudioSystem::stopOutput(thread->id(), 3602 (audio_stream_type_t)mStreamType, 3603 mSessionId); 3604 thread->mLock.lock(); 3605 3606 // to track the speaker usage 3607 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3608 } 3609 } 3610 } 3611} 3612 3613void AudioFlinger::PlaybackThread::Track::flush() 3614{ 3615 ALOGV("flush(%d)", mName); 3616 sp<ThreadBase> thread = mThread.promote(); 3617 if (thread != 0) { 3618 Mutex::Autolock _l(thread->mLock); 3619 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) { 3620 return; 3621 } 3622 // No point remaining in PAUSED state after a flush => go to 3623 // STOPPED state 3624 mState = STOPPED; 3625 3626 // do not reset the track if it is still in the process of being stopped or paused. 3627 // this will be done by prepareTracks_l() when the track is stopped. 3628 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3629 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 3630 reset(); 3631 } 3632 } 3633} 3634 3635void AudioFlinger::PlaybackThread::Track::reset() 3636{ 3637 // Do not reset twice to avoid discarding data written just after a flush and before 3638 // the audioflinger thread detects the track is stopped. 3639 if (!mResetDone) { 3640 TrackBase::reset(); 3641 // Force underrun condition to avoid false underrun callback until first data is 3642 // written to buffer 3643 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 3644 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 3645 mFillingUpStatus = FS_FILLING; 3646 mResetDone = true; 3647 } 3648} 3649 3650void AudioFlinger::PlaybackThread::Track::mute(bool muted) 3651{ 3652 mMute = muted; 3653} 3654 3655status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 3656{ 3657 status_t status = DEAD_OBJECT; 3658 sp<ThreadBase> thread = mThread.promote(); 3659 if (thread != 0) { 3660 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3661 status = playbackThread->attachAuxEffect(this, EffectId); 3662 } 3663 return status; 3664} 3665 3666void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 3667{ 3668 mAuxEffectId = EffectId; 3669 mAuxBuffer = buffer; 3670} 3671 3672// ---------------------------------------------------------------------------- 3673 3674// RecordTrack constructor must be called with AudioFlinger::mLock held 3675AudioFlinger::RecordThread::RecordTrack::RecordTrack( 3676 const wp<ThreadBase>& thread, 3677 const sp<Client>& client, 3678 uint32_t sampleRate, 3679 audio_format_t format, 3680 uint32_t channelMask, 3681 int frameCount, 3682 uint32_t flags, 3683 int sessionId) 3684 : TrackBase(thread, client, sampleRate, format, 3685 channelMask, frameCount, flags, 0, sessionId), 3686 mOverflow(false) 3687{ 3688 if (mCblk != NULL) { 3689 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer); 3690 if (format == AUDIO_FORMAT_PCM_16_BIT) { 3691 mCblk->frameSize = mChannelCount * sizeof(int16_t); 3692 } else if (format == AUDIO_FORMAT_PCM_8_BIT) { 3693 mCblk->frameSize = mChannelCount * sizeof(int8_t); 3694 } else { 3695 mCblk->frameSize = sizeof(int8_t); 3696 } 3697 } 3698} 3699 3700AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 3701{ 3702 sp<ThreadBase> thread = mThread.promote(); 3703 if (thread != 0) { 3704 AudioSystem::releaseInput(thread->id()); 3705 } 3706} 3707 3708status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer) 3709{ 3710 audio_track_cblk_t* cblk = this->cblk(); 3711 uint32_t framesAvail; 3712 uint32_t framesReq = buffer->frameCount; 3713 3714 // Check if last stepServer failed, try to step now 3715 if (mFlags & TrackBase::STEPSERVER_FAILED) { 3716 if (!step()) goto getNextBuffer_exit; 3717 ALOGV("stepServer recovered"); 3718 mFlags &= ~TrackBase::STEPSERVER_FAILED; 3719 } 3720 3721 framesAvail = cblk->framesAvailable_l(); 3722 3723 if (CC_LIKELY(framesAvail)) { 3724 uint32_t s = cblk->server; 3725 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 3726 3727 if (framesReq > framesAvail) { 3728 framesReq = framesAvail; 3729 } 3730 if (s + framesReq > bufferEnd) { 3731 framesReq = bufferEnd - s; 3732 } 3733 3734 buffer->raw = getBuffer(s, framesReq); 3735 if (buffer->raw == NULL) goto getNextBuffer_exit; 3736 3737 buffer->frameCount = framesReq; 3738 return NO_ERROR; 3739 } 3740 3741getNextBuffer_exit: 3742 buffer->raw = NULL; 3743 buffer->frameCount = 0; 3744 return NOT_ENOUGH_DATA; 3745} 3746 3747status_t AudioFlinger::RecordThread::RecordTrack::start() 3748{ 3749 sp<ThreadBase> thread = mThread.promote(); 3750 if (thread != 0) { 3751 RecordThread *recordThread = (RecordThread *)thread.get(); 3752 return recordThread->start(this); 3753 } else { 3754 return BAD_VALUE; 3755 } 3756} 3757 3758void AudioFlinger::RecordThread::RecordTrack::stop() 3759{ 3760 sp<ThreadBase> thread = mThread.promote(); 3761 if (thread != 0) { 3762 RecordThread *recordThread = (RecordThread *)thread.get(); 3763 recordThread->stop(this); 3764 TrackBase::reset(); 3765 // Force overerrun condition to avoid false overrun callback until first data is 3766 // read from buffer 3767 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 3768 } 3769} 3770 3771void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 3772{ 3773 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n", 3774 (mClient == 0) ? getpid() : mClient->pid(), 3775 mFormat, 3776 mChannelMask, 3777 mSessionId, 3778 mFrameCount, 3779 mState, 3780 mCblk->sampleRate, 3781 mCblk->server, 3782 mCblk->user); 3783} 3784 3785 3786// ---------------------------------------------------------------------------- 3787 3788AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 3789 const wp<ThreadBase>& thread, 3790 DuplicatingThread *sourceThread, 3791 uint32_t sampleRate, 3792 audio_format_t format, 3793 uint32_t channelMask, 3794 int frameCount) 3795 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0), 3796 mActive(false), mSourceThread(sourceThread) 3797{ 3798 3799 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get(); 3800 if (mCblk != NULL) { 3801 mCblk->flags |= CBLK_DIRECTION_OUT; 3802 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); 3803 mOutBuffer.frameCount = 0; 3804 playbackThread->mTracks.add(this); 3805 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \ 3806 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p", 3807 mCblk, mBuffer, mCblk->buffers, 3808 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd); 3809 } else { 3810 ALOGW("Error creating output track on thread %p", playbackThread); 3811 } 3812} 3813 3814AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 3815{ 3816 clearBufferQueue(); 3817} 3818 3819status_t AudioFlinger::PlaybackThread::OutputTrack::start() 3820{ 3821 status_t status = Track::start(); 3822 if (status != NO_ERROR) { 3823 return status; 3824 } 3825 3826 mActive = true; 3827 mRetryCount = 127; 3828 return status; 3829} 3830 3831void AudioFlinger::PlaybackThread::OutputTrack::stop() 3832{ 3833 Track::stop(); 3834 clearBufferQueue(); 3835 mOutBuffer.frameCount = 0; 3836 mActive = false; 3837} 3838 3839bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 3840{ 3841 Buffer *pInBuffer; 3842 Buffer inBuffer; 3843 uint32_t channelCount = mChannelCount; 3844 bool outputBufferFull = false; 3845 inBuffer.frameCount = frames; 3846 inBuffer.i16 = data; 3847 3848 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 3849 3850 if (!mActive && frames != 0) { 3851 start(); 3852 sp<ThreadBase> thread = mThread.promote(); 3853 if (thread != 0) { 3854 MixerThread *mixerThread = (MixerThread *)thread.get(); 3855 if (mCblk->frameCount > frames){ 3856 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 3857 uint32_t startFrames = (mCblk->frameCount - frames); 3858 pInBuffer = new Buffer; 3859 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 3860 pInBuffer->frameCount = startFrames; 3861 pInBuffer->i16 = pInBuffer->mBuffer; 3862 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 3863 mBufferQueue.add(pInBuffer); 3864 } else { 3865 ALOGW ("OutputTrack::write() %p no more buffers in queue", this); 3866 } 3867 } 3868 } 3869 } 3870 3871 while (waitTimeLeftMs) { 3872 // First write pending buffers, then new data 3873 if (mBufferQueue.size()) { 3874 pInBuffer = mBufferQueue.itemAt(0); 3875 } else { 3876 pInBuffer = &inBuffer; 3877 } 3878 3879 if (pInBuffer->frameCount == 0) { 3880 break; 3881 } 3882 3883 if (mOutBuffer.frameCount == 0) { 3884 mOutBuffer.frameCount = pInBuffer->frameCount; 3885 nsecs_t startTime = systemTime(); 3886 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) { 3887 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get()); 3888 outputBufferFull = true; 3889 break; 3890 } 3891 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 3892 if (waitTimeLeftMs >= waitTimeMs) { 3893 waitTimeLeftMs -= waitTimeMs; 3894 } else { 3895 waitTimeLeftMs = 0; 3896 } 3897 } 3898 3899 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount; 3900 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 3901 mCblk->stepUser(outFrames); 3902 pInBuffer->frameCount -= outFrames; 3903 pInBuffer->i16 += outFrames * channelCount; 3904 mOutBuffer.frameCount -= outFrames; 3905 mOutBuffer.i16 += outFrames * channelCount; 3906 3907 if (pInBuffer->frameCount == 0) { 3908 if (mBufferQueue.size()) { 3909 mBufferQueue.removeAt(0); 3910 delete [] pInBuffer->mBuffer; 3911 delete pInBuffer; 3912 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 3913 } else { 3914 break; 3915 } 3916 } 3917 } 3918 3919 // If we could not write all frames, allocate a buffer and queue it for next time. 3920 if (inBuffer.frameCount) { 3921 sp<ThreadBase> thread = mThread.promote(); 3922 if (thread != 0 && !thread->standby()) { 3923 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 3924 pInBuffer = new Buffer; 3925 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 3926 pInBuffer->frameCount = inBuffer.frameCount; 3927 pInBuffer->i16 = pInBuffer->mBuffer; 3928 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t)); 3929 mBufferQueue.add(pInBuffer); 3930 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 3931 } else { 3932 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this); 3933 } 3934 } 3935 } 3936 3937 // Calling write() with a 0 length buffer, means that no more data will be written: 3938 // If no more buffers are pending, fill output track buffer to make sure it is started 3939 // by output mixer. 3940 if (frames == 0 && mBufferQueue.size() == 0) { 3941 if (mCblk->user < mCblk->frameCount) { 3942 frames = mCblk->frameCount - mCblk->user; 3943 pInBuffer = new Buffer; 3944 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 3945 pInBuffer->frameCount = frames; 3946 pInBuffer->i16 = pInBuffer->mBuffer; 3947 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 3948 mBufferQueue.add(pInBuffer); 3949 } else if (mActive) { 3950 stop(); 3951 } 3952 } 3953 3954 return outputBufferFull; 3955} 3956 3957status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 3958{ 3959 int active; 3960 status_t result; 3961 audio_track_cblk_t* cblk = mCblk; 3962 uint32_t framesReq = buffer->frameCount; 3963 3964// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server); 3965 buffer->frameCount = 0; 3966 3967 uint32_t framesAvail = cblk->framesAvailable(); 3968 3969 3970 if (framesAvail == 0) { 3971 Mutex::Autolock _l(cblk->lock); 3972 goto start_loop_here; 3973 while (framesAvail == 0) { 3974 active = mActive; 3975 if (CC_UNLIKELY(!active)) { 3976 ALOGV("Not active and NO_MORE_BUFFERS"); 3977 return NO_MORE_BUFFERS; 3978 } 3979 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 3980 if (result != NO_ERROR) { 3981 return NO_MORE_BUFFERS; 3982 } 3983 // read the server count again 3984 start_loop_here: 3985 framesAvail = cblk->framesAvailable_l(); 3986 } 3987 } 3988 3989// if (framesAvail < framesReq) { 3990// return NO_MORE_BUFFERS; 3991// } 3992 3993 if (framesReq > framesAvail) { 3994 framesReq = framesAvail; 3995 } 3996 3997 uint32_t u = cblk->user; 3998 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 3999 4000 if (u + framesReq > bufferEnd) { 4001 framesReq = bufferEnd - u; 4002 } 4003 4004 buffer->frameCount = framesReq; 4005 buffer->raw = (void *)cblk->buffer(u); 4006 return NO_ERROR; 4007} 4008 4009 4010void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 4011{ 4012 size_t size = mBufferQueue.size(); 4013 Buffer *pBuffer; 4014 4015 for (size_t i = 0; i < size; i++) { 4016 pBuffer = mBufferQueue.itemAt(i); 4017 delete [] pBuffer->mBuffer; 4018 delete pBuffer; 4019 } 4020 mBufferQueue.clear(); 4021} 4022 4023// ---------------------------------------------------------------------------- 4024 4025AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 4026 : RefBase(), 4027 mAudioFlinger(audioFlinger), 4028 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 4029 mPid(pid) 4030{ 4031 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 4032} 4033 4034// Client destructor must be called with AudioFlinger::mLock held 4035AudioFlinger::Client::~Client() 4036{ 4037 mAudioFlinger->removeClient_l(mPid); 4038} 4039 4040sp<MemoryDealer> AudioFlinger::Client::heap() const 4041{ 4042 return mMemoryDealer; 4043} 4044 4045// ---------------------------------------------------------------------------- 4046 4047AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 4048 const sp<IAudioFlingerClient>& client, 4049 pid_t pid) 4050 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 4051{ 4052} 4053 4054AudioFlinger::NotificationClient::~NotificationClient() 4055{ 4056} 4057 4058void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 4059{ 4060 sp<NotificationClient> keep(this); 4061 { 4062 mAudioFlinger->removeNotificationClient(mPid); 4063 } 4064} 4065 4066// ---------------------------------------------------------------------------- 4067 4068AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 4069 : BnAudioTrack(), 4070 mTrack(track) 4071{ 4072} 4073 4074AudioFlinger::TrackHandle::~TrackHandle() { 4075 // just stop the track on deletion, associated resources 4076 // will be freed from the main thread once all pending buffers have 4077 // been played. Unless it's not in the active track list, in which 4078 // case we free everything now... 4079 mTrack->destroy(); 4080} 4081 4082sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 4083 return mTrack->getCblk(); 4084} 4085 4086status_t AudioFlinger::TrackHandle::start() { 4087 return mTrack->start(); 4088} 4089 4090void AudioFlinger::TrackHandle::stop() { 4091 mTrack->stop(); 4092} 4093 4094void AudioFlinger::TrackHandle::flush() { 4095 mTrack->flush(); 4096} 4097 4098void AudioFlinger::TrackHandle::mute(bool e) { 4099 mTrack->mute(e); 4100} 4101 4102void AudioFlinger::TrackHandle::pause() { 4103 mTrack->pause(); 4104} 4105 4106status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 4107{ 4108 return mTrack->attachAuxEffect(EffectId); 4109} 4110 4111status_t AudioFlinger::TrackHandle::onTransact( 4112 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 4113{ 4114 return BnAudioTrack::onTransact(code, data, reply, flags); 4115} 4116 4117// ---------------------------------------------------------------------------- 4118 4119sp<IAudioRecord> AudioFlinger::openRecord( 4120 pid_t pid, 4121 int input, 4122 uint32_t sampleRate, 4123 audio_format_t format, 4124 uint32_t channelMask, 4125 int frameCount, 4126 uint32_t flags, 4127 int *sessionId, 4128 status_t *status) 4129{ 4130 sp<RecordThread::RecordTrack> recordTrack; 4131 sp<RecordHandle> recordHandle; 4132 sp<Client> client; 4133 wp<Client> wclient; 4134 status_t lStatus; 4135 RecordThread *thread; 4136 size_t inFrameCount; 4137 int lSessionId; 4138 4139 // check calling permissions 4140 if (!recordingAllowed()) { 4141 lStatus = PERMISSION_DENIED; 4142 goto Exit; 4143 } 4144 4145 // add client to list 4146 { // scope for mLock 4147 Mutex::Autolock _l(mLock); 4148 thread = checkRecordThread_l(input); 4149 if (thread == NULL) { 4150 lStatus = BAD_VALUE; 4151 goto Exit; 4152 } 4153 4154 wclient = mClients.valueFor(pid); 4155 if (wclient != NULL) { 4156 client = wclient.promote(); 4157 } else { 4158 client = new Client(this, pid); 4159 mClients.add(pid, client); 4160 } 4161 4162 // If no audio session id is provided, create one here 4163 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 4164 lSessionId = *sessionId; 4165 } else { 4166 lSessionId = nextUniqueId(); 4167 if (sessionId != NULL) { 4168 *sessionId = lSessionId; 4169 } 4170 } 4171 // create new record track. The record track uses one track in mHardwareMixerThread by convention. 4172 recordTrack = thread->createRecordTrack_l(client, 4173 sampleRate, 4174 format, 4175 channelMask, 4176 frameCount, 4177 flags, 4178 lSessionId, 4179 &lStatus); 4180 } 4181 if (lStatus != NO_ERROR) { 4182 // remove local strong reference to Client before deleting the RecordTrack so that the Client 4183 // destructor is called by the TrackBase destructor with mLock held 4184 client.clear(); 4185 recordTrack.clear(); 4186 goto Exit; 4187 } 4188 4189 // return to handle to client 4190 recordHandle = new RecordHandle(recordTrack); 4191 lStatus = NO_ERROR; 4192 4193Exit: 4194 if (status) { 4195 *status = lStatus; 4196 } 4197 return recordHandle; 4198} 4199 4200// ---------------------------------------------------------------------------- 4201 4202AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 4203 : BnAudioRecord(), 4204 mRecordTrack(recordTrack) 4205{ 4206} 4207 4208AudioFlinger::RecordHandle::~RecordHandle() { 4209 stop(); 4210} 4211 4212sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 4213 return mRecordTrack->getCblk(); 4214} 4215 4216status_t AudioFlinger::RecordHandle::start() { 4217 ALOGV("RecordHandle::start()"); 4218 return mRecordTrack->start(); 4219} 4220 4221void AudioFlinger::RecordHandle::stop() { 4222 ALOGV("RecordHandle::stop()"); 4223 mRecordTrack->stop(); 4224} 4225 4226status_t AudioFlinger::RecordHandle::onTransact( 4227 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 4228{ 4229 return BnAudioRecord::onTransact(code, data, reply, flags); 4230} 4231 4232// ---------------------------------------------------------------------------- 4233 4234AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4235 AudioStreamIn *input, 4236 uint32_t sampleRate, 4237 uint32_t channels, 4238 int id, 4239 uint32_t device) : 4240 ThreadBase(audioFlinger, id, device, RECORD), 4241 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4242 // mRsmpInIndex and mInputBytes set by readInputParameters() 4243 mReqChannelCount(popcount(channels)), 4244 mReqSampleRate(sampleRate) 4245 // mBytesRead is only meaningful while active, and so is cleared in start() 4246 // (but might be better to also clear here for dump?) 4247{ 4248 snprintf(mName, kNameLength, "AudioIn_%d", id); 4249 4250 readInputParameters(); 4251} 4252 4253 4254AudioFlinger::RecordThread::~RecordThread() 4255{ 4256 delete[] mRsmpInBuffer; 4257 delete mResampler; 4258 delete[] mRsmpOutBuffer; 4259} 4260 4261void AudioFlinger::RecordThread::onFirstRef() 4262{ 4263 run(mName, PRIORITY_URGENT_AUDIO); 4264} 4265 4266status_t AudioFlinger::RecordThread::readyToRun() 4267{ 4268 status_t status = initCheck(); 4269 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); 4270 return status; 4271} 4272 4273bool AudioFlinger::RecordThread::threadLoop() 4274{ 4275 AudioBufferProvider::Buffer buffer; 4276 sp<RecordTrack> activeTrack; 4277 Vector< sp<EffectChain> > effectChains; 4278 4279 nsecs_t lastWarning = 0; 4280 4281 acquireWakeLock(); 4282 4283 // start recording 4284 while (!exitPending()) { 4285 4286 processConfigEvents(); 4287 4288 { // scope for mLock 4289 Mutex::Autolock _l(mLock); 4290 checkForNewParameters_l(); 4291 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 4292 if (!mStandby) { 4293 mInput->stream->common.standby(&mInput->stream->common); 4294 mStandby = true; 4295 } 4296 4297 if (exitPending()) break; 4298 4299 releaseWakeLock_l(); 4300 ALOGV("RecordThread: loop stopping"); 4301 // go to sleep 4302 mWaitWorkCV.wait(mLock); 4303 ALOGV("RecordThread: loop starting"); 4304 acquireWakeLock_l(); 4305 continue; 4306 } 4307 if (mActiveTrack != 0) { 4308 if (mActiveTrack->mState == TrackBase::PAUSING) { 4309 if (!mStandby) { 4310 mInput->stream->common.standby(&mInput->stream->common); 4311 mStandby = true; 4312 } 4313 mActiveTrack.clear(); 4314 mStartStopCond.broadcast(); 4315 } else if (mActiveTrack->mState == TrackBase::RESUMING) { 4316 if (mReqChannelCount != mActiveTrack->channelCount()) { 4317 mActiveTrack.clear(); 4318 mStartStopCond.broadcast(); 4319 } else if (mBytesRead != 0) { 4320 // record start succeeds only if first read from audio input 4321 // succeeds 4322 if (mBytesRead > 0) { 4323 mActiveTrack->mState = TrackBase::ACTIVE; 4324 } else { 4325 mActiveTrack.clear(); 4326 } 4327 mStartStopCond.broadcast(); 4328 } 4329 mStandby = false; 4330 } 4331 } 4332 lockEffectChains_l(effectChains); 4333 } 4334 4335 if (mActiveTrack != 0) { 4336 if (mActiveTrack->mState != TrackBase::ACTIVE && 4337 mActiveTrack->mState != TrackBase::RESUMING) { 4338 unlockEffectChains(effectChains); 4339 usleep(kRecordThreadSleepUs); 4340 continue; 4341 } 4342 for (size_t i = 0; i < effectChains.size(); i ++) { 4343 effectChains[i]->process_l(); 4344 } 4345 4346 buffer.frameCount = mFrameCount; 4347 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) { 4348 size_t framesOut = buffer.frameCount; 4349 if (mResampler == NULL) { 4350 // no resampling 4351 while (framesOut) { 4352 size_t framesIn = mFrameCount - mRsmpInIndex; 4353 if (framesIn) { 4354 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4355 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize; 4356 if (framesIn > framesOut) 4357 framesIn = framesOut; 4358 mRsmpInIndex += framesIn; 4359 framesOut -= framesIn; 4360 if ((int)mChannelCount == mReqChannelCount || 4361 mFormat != AUDIO_FORMAT_PCM_16_BIT) { 4362 memcpy(dst, src, framesIn * mFrameSize); 4363 } else { 4364 int16_t *src16 = (int16_t *)src; 4365 int16_t *dst16 = (int16_t *)dst; 4366 if (mChannelCount == 1) { 4367 while (framesIn--) { 4368 *dst16++ = *src16; 4369 *dst16++ = *src16++; 4370 } 4371 } else { 4372 while (framesIn--) { 4373 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1); 4374 src16 += 2; 4375 } 4376 } 4377 } 4378 } 4379 if (framesOut && mFrameCount == mRsmpInIndex) { 4380 if (framesOut == mFrameCount && 4381 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) { 4382 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes); 4383 framesOut = 0; 4384 } else { 4385 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 4386 mRsmpInIndex = 0; 4387 } 4388 if (mBytesRead < 0) { 4389 ALOGE("Error reading audio input"); 4390 if (mActiveTrack->mState == TrackBase::ACTIVE) { 4391 // Force input into standby so that it tries to 4392 // recover at next read attempt 4393 mInput->stream->common.standby(&mInput->stream->common); 4394 usleep(kRecordThreadSleepUs); 4395 } 4396 mRsmpInIndex = mFrameCount; 4397 framesOut = 0; 4398 buffer.frameCount = 0; 4399 } 4400 } 4401 } 4402 } else { 4403 // resampling 4404 4405 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t)); 4406 // alter output frame count as if we were expecting stereo samples 4407 if (mChannelCount == 1 && mReqChannelCount == 1) { 4408 framesOut >>= 1; 4409 } 4410 mResampler->resample(mRsmpOutBuffer, framesOut, this); 4411 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer() 4412 // are 32 bit aligned which should be always true. 4413 if (mChannelCount == 2 && mReqChannelCount == 1) { 4414 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4415 // the resampler always outputs stereo samples: do post stereo to mono conversion 4416 int16_t *src = (int16_t *)mRsmpOutBuffer; 4417 int16_t *dst = buffer.i16; 4418 while (framesOut--) { 4419 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1); 4420 src += 2; 4421 } 4422 } else { 4423 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4424 } 4425 4426 } 4427 mActiveTrack->releaseBuffer(&buffer); 4428 mActiveTrack->overflow(); 4429 } 4430 // client isn't retrieving buffers fast enough 4431 else { 4432 if (!mActiveTrack->setOverflow()) { 4433 nsecs_t now = systemTime(); 4434 if ((now - lastWarning) > kWarningThrottleNs) { 4435 ALOGW("RecordThread: buffer overflow"); 4436 lastWarning = now; 4437 } 4438 } 4439 // Release the processor for a while before asking for a new buffer. 4440 // This will give the application more chance to read from the buffer and 4441 // clear the overflow. 4442 usleep(kRecordThreadSleepUs); 4443 } 4444 } 4445 // enable changes in effect chain 4446 unlockEffectChains(effectChains); 4447 effectChains.clear(); 4448 } 4449 4450 if (!mStandby) { 4451 mInput->stream->common.standby(&mInput->stream->common); 4452 } 4453 mActiveTrack.clear(); 4454 4455 mStartStopCond.broadcast(); 4456 4457 releaseWakeLock(); 4458 4459 ALOGV("RecordThread %p exiting", this); 4460 return false; 4461} 4462 4463 4464sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4465 const sp<AudioFlinger::Client>& client, 4466 uint32_t sampleRate, 4467 audio_format_t format, 4468 int channelMask, 4469 int frameCount, 4470 uint32_t flags, 4471 int sessionId, 4472 status_t *status) 4473{ 4474 sp<RecordTrack> track; 4475 status_t lStatus; 4476 4477 lStatus = initCheck(); 4478 if (lStatus != NO_ERROR) { 4479 ALOGE("Audio driver not initialized."); 4480 goto Exit; 4481 } 4482 4483 { // scope for mLock 4484 Mutex::Autolock _l(mLock); 4485 4486 track = new RecordTrack(this, client, sampleRate, 4487 format, channelMask, frameCount, flags, sessionId); 4488 4489 if (track->getCblk() == 0) { 4490 lStatus = NO_MEMORY; 4491 goto Exit; 4492 } 4493 4494 mTrack = track.get(); 4495 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4496 bool suspend = audio_is_bluetooth_sco_device( 4497 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff(); 4498 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4499 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4500 } 4501 lStatus = NO_ERROR; 4502 4503Exit: 4504 if (status) { 4505 *status = lStatus; 4506 } 4507 return track; 4508} 4509 4510status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack) 4511{ 4512 ALOGV("RecordThread::start"); 4513 sp <ThreadBase> strongMe = this; 4514 status_t status = NO_ERROR; 4515 { 4516 AutoMutex lock(mLock); 4517 if (mActiveTrack != 0) { 4518 if (recordTrack != mActiveTrack.get()) { 4519 status = -EBUSY; 4520 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4521 mActiveTrack->mState = TrackBase::ACTIVE; 4522 } 4523 return status; 4524 } 4525 4526 recordTrack->mState = TrackBase::IDLE; 4527 mActiveTrack = recordTrack; 4528 mLock.unlock(); 4529 status_t status = AudioSystem::startInput(mId); 4530 mLock.lock(); 4531 if (status != NO_ERROR) { 4532 mActiveTrack.clear(); 4533 return status; 4534 } 4535 mRsmpInIndex = mFrameCount; 4536 mBytesRead = 0; 4537 if (mResampler != NULL) { 4538 mResampler->reset(); 4539 } 4540 mActiveTrack->mState = TrackBase::RESUMING; 4541 // signal thread to start 4542 ALOGV("Signal record thread"); 4543 mWaitWorkCV.signal(); 4544 // do not wait for mStartStopCond if exiting 4545 if (mExiting) { 4546 mActiveTrack.clear(); 4547 status = INVALID_OPERATION; 4548 goto startError; 4549 } 4550 mStartStopCond.wait(mLock); 4551 if (mActiveTrack == 0) { 4552 ALOGV("Record failed to start"); 4553 status = BAD_VALUE; 4554 goto startError; 4555 } 4556 ALOGV("Record started OK"); 4557 return status; 4558 } 4559startError: 4560 AudioSystem::stopInput(mId); 4561 return status; 4562} 4563 4564void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 4565 ALOGV("RecordThread::stop"); 4566 sp <ThreadBase> strongMe = this; 4567 { 4568 AutoMutex lock(mLock); 4569 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) { 4570 mActiveTrack->mState = TrackBase::PAUSING; 4571 // do not wait for mStartStopCond if exiting 4572 if (mExiting) { 4573 return; 4574 } 4575 mStartStopCond.wait(mLock); 4576 // if we have been restarted, recordTrack == mActiveTrack.get() here 4577 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) { 4578 mLock.unlock(); 4579 AudioSystem::stopInput(mId); 4580 mLock.lock(); 4581 ALOGV("Record stopped OK"); 4582 } 4583 } 4584 } 4585} 4586 4587status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 4588{ 4589 const size_t SIZE = 256; 4590 char buffer[SIZE]; 4591 String8 result; 4592 4593 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 4594 result.append(buffer); 4595 4596 if (mActiveTrack != 0) { 4597 result.append("Active Track:\n"); 4598 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n"); 4599 mActiveTrack->dump(buffer, SIZE); 4600 result.append(buffer); 4601 4602 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 4603 result.append(buffer); 4604 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes); 4605 result.append(buffer); 4606 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 4607 result.append(buffer); 4608 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount); 4609 result.append(buffer); 4610 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate); 4611 result.append(buffer); 4612 4613 4614 } else { 4615 result.append("No record client\n"); 4616 } 4617 write(fd, result.string(), result.size()); 4618 4619 dumpBase(fd, args); 4620 dumpEffectChains(fd, args); 4621 4622 return NO_ERROR; 4623} 4624 4625status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer) 4626{ 4627 size_t framesReq = buffer->frameCount; 4628 size_t framesReady = mFrameCount - mRsmpInIndex; 4629 int channelCount; 4630 4631 if (framesReady == 0) { 4632 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 4633 if (mBytesRead < 0) { 4634 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 4635 if (mActiveTrack->mState == TrackBase::ACTIVE) { 4636 // Force input into standby so that it tries to 4637 // recover at next read attempt 4638 mInput->stream->common.standby(&mInput->stream->common); 4639 usleep(kRecordThreadSleepUs); 4640 } 4641 buffer->raw = NULL; 4642 buffer->frameCount = 0; 4643 return NOT_ENOUGH_DATA; 4644 } 4645 mRsmpInIndex = 0; 4646 framesReady = mFrameCount; 4647 } 4648 4649 if (framesReq > framesReady) { 4650 framesReq = framesReady; 4651 } 4652 4653 if (mChannelCount == 1 && mReqChannelCount == 2) { 4654 channelCount = 1; 4655 } else { 4656 channelCount = 2; 4657 } 4658 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 4659 buffer->frameCount = framesReq; 4660 return NO_ERROR; 4661} 4662 4663void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4664{ 4665 mRsmpInIndex += buffer->frameCount; 4666 buffer->frameCount = 0; 4667} 4668 4669bool AudioFlinger::RecordThread::checkForNewParameters_l() 4670{ 4671 bool reconfig = false; 4672 4673 while (!mNewParameters.isEmpty()) { 4674 status_t status = NO_ERROR; 4675 String8 keyValuePair = mNewParameters[0]; 4676 AudioParameter param = AudioParameter(keyValuePair); 4677 int value; 4678 audio_format_t reqFormat = mFormat; 4679 int reqSamplingRate = mReqSampleRate; 4680 int reqChannelCount = mReqChannelCount; 4681 4682 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4683 reqSamplingRate = value; 4684 reconfig = true; 4685 } 4686 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4687 reqFormat = (audio_format_t) value; 4688 reconfig = true; 4689 } 4690 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4691 reqChannelCount = popcount(value); 4692 reconfig = true; 4693 } 4694 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4695 // do not accept frame count changes if tracks are open as the track buffer 4696 // size depends on frame count and correct behavior would not be garantied 4697 // if frame count is changed after track creation 4698 if (mActiveTrack != 0) { 4699 status = INVALID_OPERATION; 4700 } else { 4701 reconfig = true; 4702 } 4703 } 4704 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4705 // forward device change to effects that have requested to be 4706 // aware of attached audio device. 4707 for (size_t i = 0; i < mEffectChains.size(); i++) { 4708 mEffectChains[i]->setDevice_l(value); 4709 } 4710 // store input device and output device but do not forward output device to audio HAL. 4711 // Note that status is ignored by the caller for output device 4712 // (see AudioFlinger::setParameters() 4713 if (value & AUDIO_DEVICE_OUT_ALL) { 4714 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL); 4715 status = BAD_VALUE; 4716 } else { 4717 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL); 4718 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4719 if (mTrack != NULL) { 4720 bool suspend = audio_is_bluetooth_sco_device( 4721 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff(); 4722 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId()); 4723 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId()); 4724 } 4725 } 4726 mDevice |= (uint32_t)value; 4727 } 4728 if (status == NO_ERROR) { 4729 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 4730 if (status == INVALID_OPERATION) { 4731 mInput->stream->common.standby(&mInput->stream->common); 4732 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 4733 } 4734 if (reconfig) { 4735 if (status == BAD_VALUE && 4736 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 4737 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 4738 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) && 4739 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) && 4740 (reqChannelCount < 3)) { 4741 status = NO_ERROR; 4742 } 4743 if (status == NO_ERROR) { 4744 readInputParameters(); 4745 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 4746 } 4747 } 4748 } 4749 4750 mNewParameters.removeAt(0); 4751 4752 mParamStatus = status; 4753 mParamCond.signal(); 4754 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 4755 // already timed out waiting for the status and will never signal the condition. 4756 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 4757 } 4758 return reconfig; 4759} 4760 4761String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 4762{ 4763 char *s; 4764 String8 out_s8 = String8(); 4765 4766 Mutex::Autolock _l(mLock); 4767 if (initCheck() != NO_ERROR) { 4768 return out_s8; 4769 } 4770 4771 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 4772 out_s8 = String8(s); 4773 free(s); 4774 return out_s8; 4775} 4776 4777void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 4778 AudioSystem::OutputDescriptor desc; 4779 void *param2 = NULL; 4780 4781 switch (event) { 4782 case AudioSystem::INPUT_OPENED: 4783 case AudioSystem::INPUT_CONFIG_CHANGED: 4784 desc.channels = mChannelMask; 4785 desc.samplingRate = mSampleRate; 4786 desc.format = mFormat; 4787 desc.frameCount = mFrameCount; 4788 desc.latency = 0; 4789 param2 = &desc; 4790 break; 4791 4792 case AudioSystem::INPUT_CLOSED: 4793 default: 4794 break; 4795 } 4796 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 4797} 4798 4799void AudioFlinger::RecordThread::readInputParameters() 4800{ 4801 delete mRsmpInBuffer; 4802 // mRsmpInBuffer is always assigned a new[] below 4803 delete mRsmpOutBuffer; 4804 mRsmpOutBuffer = NULL; 4805 delete mResampler; 4806 mResampler = NULL; 4807 4808 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 4809 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 4810 mChannelCount = (uint16_t)popcount(mChannelMask); 4811 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 4812 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 4813 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common); 4814 mFrameCount = mInputBytes / mFrameSize; 4815 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 4816 4817 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3) 4818 { 4819 int channelCount; 4820 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid 4821 // stereo to mono post process as the resampler always outputs stereo. 4822 if (mChannelCount == 1 && mReqChannelCount == 2) { 4823 channelCount = 1; 4824 } else { 4825 channelCount = 2; 4826 } 4827 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 4828 mResampler->setSampleRate(mSampleRate); 4829 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 4830 mRsmpOutBuffer = new int32_t[mFrameCount * 2]; 4831 4832 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples 4833 if (mChannelCount == 1 && mReqChannelCount == 1) { 4834 mFrameCount >>= 1; 4835 } 4836 4837 } 4838 mRsmpInIndex = mFrameCount; 4839} 4840 4841unsigned int AudioFlinger::RecordThread::getInputFramesLost() 4842{ 4843 Mutex::Autolock _l(mLock); 4844 if (initCheck() != NO_ERROR) { 4845 return 0; 4846 } 4847 4848 return mInput->stream->get_input_frames_lost(mInput->stream); 4849} 4850 4851uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) 4852{ 4853 Mutex::Autolock _l(mLock); 4854 uint32_t result = 0; 4855 if (getEffectChain_l(sessionId) != 0) { 4856 result = EFFECT_SESSION; 4857 } 4858 4859 if (mTrack != NULL && sessionId == mTrack->sessionId()) { 4860 result |= TRACK_SESSION; 4861 } 4862 4863 return result; 4864} 4865 4866AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track() 4867{ 4868 Mutex::Autolock _l(mLock); 4869 return mTrack; 4870} 4871 4872AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const 4873{ 4874 Mutex::Autolock _l(mLock); 4875 return mInput; 4876} 4877 4878AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 4879{ 4880 Mutex::Autolock _l(mLock); 4881 AudioStreamIn *input = mInput; 4882 mInput = NULL; 4883 return input; 4884} 4885 4886// this method must always be called either with ThreadBase mLock held or inside the thread loop 4887audio_stream_t* AudioFlinger::RecordThread::stream() 4888{ 4889 if (mInput == NULL) { 4890 return NULL; 4891 } 4892 return &mInput->stream->common; 4893} 4894 4895 4896// ---------------------------------------------------------------------------- 4897 4898int AudioFlinger::openOutput(uint32_t *pDevices, 4899 uint32_t *pSamplingRate, 4900 audio_format_t *pFormat, 4901 uint32_t *pChannels, 4902 uint32_t *pLatencyMs, 4903 uint32_t flags) 4904{ 4905 status_t status; 4906 PlaybackThread *thread = NULL; 4907 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 4908 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0; 4909 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT; 4910 uint32_t channels = pChannels ? *pChannels : 0; 4911 uint32_t latency = pLatencyMs ? *pLatencyMs : 0; 4912 audio_stream_out_t *outStream; 4913 audio_hw_device_t *outHwDev; 4914 4915 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x", 4916 pDevices ? *pDevices : 0, 4917 samplingRate, 4918 format, 4919 channels, 4920 flags); 4921 4922 if (pDevices == NULL || *pDevices == 0) { 4923 return 0; 4924 } 4925 4926 Mutex::Autolock _l(mLock); 4927 4928 outHwDev = findSuitableHwDev_l(*pDevices); 4929 if (outHwDev == NULL) 4930 return 0; 4931 4932 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format, 4933 &channels, &samplingRate, &outStream); 4934 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d", 4935 outStream, 4936 samplingRate, 4937 format, 4938 channels, 4939 status); 4940 4941 mHardwareStatus = AUDIO_HW_IDLE; 4942 if (outStream != NULL) { 4943 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream); 4944 int id = nextUniqueId(); 4945 4946 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) || 4947 (format != AUDIO_FORMAT_PCM_16_BIT) || 4948 (channels != AUDIO_CHANNEL_OUT_STEREO)) { 4949 thread = new DirectOutputThread(this, output, id, *pDevices); 4950 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 4951 } else { 4952 thread = new MixerThread(this, output, id, *pDevices); 4953 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 4954 } 4955 mPlaybackThreads.add(id, thread); 4956 4957 if (pSamplingRate != NULL) *pSamplingRate = samplingRate; 4958 if (pFormat != NULL) *pFormat = format; 4959 if (pChannels != NULL) *pChannels = channels; 4960 if (pLatencyMs != NULL) *pLatencyMs = thread->latency(); 4961 4962 // notify client processes of the new output creation 4963 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 4964 return id; 4965 } 4966 4967 return 0; 4968} 4969 4970int AudioFlinger::openDuplicateOutput(int output1, int output2) 4971{ 4972 Mutex::Autolock _l(mLock); 4973 MixerThread *thread1 = checkMixerThread_l(output1); 4974 MixerThread *thread2 = checkMixerThread_l(output2); 4975 4976 if (thread1 == NULL || thread2 == NULL) { 4977 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2); 4978 return 0; 4979 } 4980 4981 int id = nextUniqueId(); 4982 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 4983 thread->addOutputTrack(thread2); 4984 mPlaybackThreads.add(id, thread); 4985 // notify client processes of the new output creation 4986 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 4987 return id; 4988} 4989 4990status_t AudioFlinger::closeOutput(int output) 4991{ 4992 // keep strong reference on the playback thread so that 4993 // it is not destroyed while exit() is executed 4994 sp <PlaybackThread> thread; 4995 { 4996 Mutex::Autolock _l(mLock); 4997 thread = checkPlaybackThread_l(output); 4998 if (thread == NULL) { 4999 return BAD_VALUE; 5000 } 5001 5002 ALOGV("closeOutput() %d", output); 5003 5004 if (thread->type() == ThreadBase::MIXER) { 5005 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5006 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 5007 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 5008 dupThread->removeOutputTrack((MixerThread *)thread.get()); 5009 } 5010 } 5011 } 5012 void *param2 = NULL; 5013 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2); 5014 mPlaybackThreads.removeItem(output); 5015 } 5016 thread->exit(); 5017 5018 if (thread->type() != ThreadBase::DUPLICATING) { 5019 AudioStreamOut *out = thread->clearOutput(); 5020 assert(out != NULL); 5021 // from now on thread->mOutput is NULL 5022 out->hwDev->close_output_stream(out->hwDev, out->stream); 5023 delete out; 5024 } 5025 return NO_ERROR; 5026} 5027 5028status_t AudioFlinger::suspendOutput(int output) 5029{ 5030 Mutex::Autolock _l(mLock); 5031 PlaybackThread *thread = checkPlaybackThread_l(output); 5032 5033 if (thread == NULL) { 5034 return BAD_VALUE; 5035 } 5036 5037 ALOGV("suspendOutput() %d", output); 5038 thread->suspend(); 5039 5040 return NO_ERROR; 5041} 5042 5043status_t AudioFlinger::restoreOutput(int output) 5044{ 5045 Mutex::Autolock _l(mLock); 5046 PlaybackThread *thread = checkPlaybackThread_l(output); 5047 5048 if (thread == NULL) { 5049 return BAD_VALUE; 5050 } 5051 5052 ALOGV("restoreOutput() %d", output); 5053 5054 thread->restore(); 5055 5056 return NO_ERROR; 5057} 5058 5059int AudioFlinger::openInput(uint32_t *pDevices, 5060 uint32_t *pSamplingRate, 5061 audio_format_t *pFormat, 5062 uint32_t *pChannels, 5063 audio_in_acoustics_t acoustics) 5064{ 5065 status_t status; 5066 RecordThread *thread = NULL; 5067 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0; 5068 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT; 5069 uint32_t channels = pChannels ? *pChannels : 0; 5070 uint32_t reqSamplingRate = samplingRate; 5071 audio_format_t reqFormat = format; 5072 uint32_t reqChannels = channels; 5073 audio_stream_in_t *inStream; 5074 audio_hw_device_t *inHwDev; 5075 5076 if (pDevices == NULL || *pDevices == 0) { 5077 return 0; 5078 } 5079 5080 Mutex::Autolock _l(mLock); 5081 5082 inHwDev = findSuitableHwDev_l(*pDevices); 5083 if (inHwDev == NULL) 5084 return 0; 5085 5086 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format, 5087 &channels, &samplingRate, 5088 acoustics, 5089 &inStream); 5090 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d", 5091 inStream, 5092 samplingRate, 5093 format, 5094 channels, 5095 acoustics, 5096 status); 5097 5098 // If the input could not be opened with the requested parameters and we can handle the conversion internally, 5099 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo 5100 // or stereo to mono conversions on 16 bit PCM inputs. 5101 if (inStream == NULL && status == BAD_VALUE && 5102 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT && 5103 (samplingRate <= 2 * reqSamplingRate) && 5104 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) { 5105 ALOGV("openInput() reopening with proposed sampling rate and channels"); 5106 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format, 5107 &channels, &samplingRate, 5108 acoustics, 5109 &inStream); 5110 } 5111 5112 if (inStream != NULL) { 5113 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 5114 5115 int id = nextUniqueId(); 5116 // Start record thread 5117 // RecorThread require both input and output device indication to forward to audio 5118 // pre processing modules 5119 uint32_t device = (*pDevices) | primaryOutputDevice_l(); 5120 thread = new RecordThread(this, 5121 input, 5122 reqSamplingRate, 5123 reqChannels, 5124 id, 5125 device); 5126 mRecordThreads.add(id, thread); 5127 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 5128 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate; 5129 if (pFormat != NULL) *pFormat = format; 5130 if (pChannels != NULL) *pChannels = reqChannels; 5131 5132 input->stream->common.standby(&input->stream->common); 5133 5134 // notify client processes of the new input creation 5135 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 5136 return id; 5137 } 5138 5139 return 0; 5140} 5141 5142status_t AudioFlinger::closeInput(int input) 5143{ 5144 // keep strong reference on the record thread so that 5145 // it is not destroyed while exit() is executed 5146 sp <RecordThread> thread; 5147 { 5148 Mutex::Autolock _l(mLock); 5149 thread = checkRecordThread_l(input); 5150 if (thread == NULL) { 5151 return BAD_VALUE; 5152 } 5153 5154 ALOGV("closeInput() %d", input); 5155 void *param2 = NULL; 5156 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2); 5157 mRecordThreads.removeItem(input); 5158 } 5159 thread->exit(); 5160 5161 AudioStreamIn *in = thread->clearInput(); 5162 assert(in != NULL); 5163 // from now on thread->mInput is NULL 5164 in->hwDev->close_input_stream(in->hwDev, in->stream); 5165 delete in; 5166 5167 return NO_ERROR; 5168} 5169 5170status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output) 5171{ 5172 Mutex::Autolock _l(mLock); 5173 MixerThread *dstThread = checkMixerThread_l(output); 5174 if (dstThread == NULL) { 5175 ALOGW("setStreamOutput() bad output id %d", output); 5176 return BAD_VALUE; 5177 } 5178 5179 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 5180 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream); 5181 5182 dstThread->setStreamValid(stream, true); 5183 5184 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5185 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 5186 if (thread != dstThread && 5187 thread->type() != ThreadBase::DIRECT) { 5188 MixerThread *srcThread = (MixerThread *)thread; 5189 srcThread->setStreamValid(stream, false); 5190 srcThread->invalidateTracks(stream); 5191 } 5192 } 5193 5194 return NO_ERROR; 5195} 5196 5197 5198int AudioFlinger::newAudioSessionId() 5199{ 5200 return nextUniqueId(); 5201} 5202 5203void AudioFlinger::acquireAudioSessionId(int audioSession) 5204{ 5205 Mutex::Autolock _l(mLock); 5206 int caller = IPCThreadState::self()->getCallingPid(); 5207 ALOGV("acquiring %d from %d", audioSession, caller); 5208 int num = mAudioSessionRefs.size(); 5209 for (int i = 0; i< num; i++) { 5210 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 5211 if (ref->sessionid == audioSession && ref->pid == caller) { 5212 ref->cnt++; 5213 ALOGV(" incremented refcount to %d", ref->cnt); 5214 return; 5215 } 5216 } 5217 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 5218 ALOGV(" added new entry for %d", audioSession); 5219} 5220 5221void AudioFlinger::releaseAudioSessionId(int audioSession) 5222{ 5223 Mutex::Autolock _l(mLock); 5224 int caller = IPCThreadState::self()->getCallingPid(); 5225 ALOGV("releasing %d from %d", audioSession, caller); 5226 int num = mAudioSessionRefs.size(); 5227 for (int i = 0; i< num; i++) { 5228 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 5229 if (ref->sessionid == audioSession && ref->pid == caller) { 5230 ref->cnt--; 5231 ALOGV(" decremented refcount to %d", ref->cnt); 5232 if (ref->cnt == 0) { 5233 mAudioSessionRefs.removeAt(i); 5234 delete ref; 5235 purgeStaleEffects_l(); 5236 } 5237 return; 5238 } 5239 } 5240 ALOGW("session id %d not found for pid %d", audioSession, caller); 5241} 5242 5243void AudioFlinger::purgeStaleEffects_l() { 5244 5245 ALOGV("purging stale effects"); 5246 5247 Vector< sp<EffectChain> > chains; 5248 5249 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5250 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 5251 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 5252 sp<EffectChain> ec = t->mEffectChains[j]; 5253 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 5254 chains.push(ec); 5255 } 5256 } 5257 } 5258 for (size_t i = 0; i < mRecordThreads.size(); i++) { 5259 sp<RecordThread> t = mRecordThreads.valueAt(i); 5260 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 5261 sp<EffectChain> ec = t->mEffectChains[j]; 5262 chains.push(ec); 5263 } 5264 } 5265 5266 for (size_t i = 0; i < chains.size(); i++) { 5267 sp<EffectChain> ec = chains[i]; 5268 int sessionid = ec->sessionId(); 5269 sp<ThreadBase> t = ec->mThread.promote(); 5270 if (t == 0) { 5271 continue; 5272 } 5273 size_t numsessionrefs = mAudioSessionRefs.size(); 5274 bool found = false; 5275 for (size_t k = 0; k < numsessionrefs; k++) { 5276 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 5277 if (ref->sessionid == sessionid) { 5278 ALOGV(" session %d still exists for %d with %d refs", 5279 sessionid, ref->pid, ref->cnt); 5280 found = true; 5281 break; 5282 } 5283 } 5284 if (!found) { 5285 // remove all effects from the chain 5286 while (ec->mEffects.size()) { 5287 sp<EffectModule> effect = ec->mEffects[0]; 5288 effect->unPin(); 5289 Mutex::Autolock _l (t->mLock); 5290 t->removeEffect_l(effect); 5291 for (size_t j = 0; j < effect->mHandles.size(); j++) { 5292 sp<EffectHandle> handle = effect->mHandles[j].promote(); 5293 if (handle != 0) { 5294 handle->mEffect.clear(); 5295 if (handle->mHasControl && handle->mEnabled) { 5296 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 5297 } 5298 } 5299 } 5300 AudioSystem::unregisterEffect(effect->id()); 5301 } 5302 } 5303 } 5304 return; 5305} 5306 5307// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 5308AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const 5309{ 5310 PlaybackThread *thread = NULL; 5311 if (mPlaybackThreads.indexOfKey(output) >= 0) { 5312 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get(); 5313 } 5314 return thread; 5315} 5316 5317// checkMixerThread_l() must be called with AudioFlinger::mLock held 5318AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const 5319{ 5320 PlaybackThread *thread = checkPlaybackThread_l(output); 5321 if (thread != NULL) { 5322 if (thread->type() == ThreadBase::DIRECT) { 5323 thread = NULL; 5324 } 5325 } 5326 return (MixerThread *)thread; 5327} 5328 5329// checkRecordThread_l() must be called with AudioFlinger::mLock held 5330AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const 5331{ 5332 RecordThread *thread = NULL; 5333 if (mRecordThreads.indexOfKey(input) >= 0) { 5334 thread = (RecordThread *)mRecordThreads.valueFor(input).get(); 5335 } 5336 return thread; 5337} 5338 5339uint32_t AudioFlinger::nextUniqueId() 5340{ 5341 return android_atomic_inc(&mNextUniqueId); 5342} 5343 5344AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() 5345{ 5346 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5347 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 5348 AudioStreamOut *output = thread->getOutput(); 5349 if (output != NULL && output->hwDev == mPrimaryHardwareDev) { 5350 return thread; 5351 } 5352 } 5353 return NULL; 5354} 5355 5356uint32_t AudioFlinger::primaryOutputDevice_l() 5357{ 5358 PlaybackThread *thread = primaryPlaybackThread_l(); 5359 5360 if (thread == NULL) { 5361 return 0; 5362 } 5363 5364 return thread->device(); 5365} 5366 5367 5368// ---------------------------------------------------------------------------- 5369// Effect management 5370// ---------------------------------------------------------------------------- 5371 5372 5373status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 5374{ 5375 Mutex::Autolock _l(mLock); 5376 return EffectQueryNumberEffects(numEffects); 5377} 5378 5379status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 5380{ 5381 Mutex::Autolock _l(mLock); 5382 return EffectQueryEffect(index, descriptor); 5383} 5384 5385status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, 5386 effect_descriptor_t *descriptor) const 5387{ 5388 Mutex::Autolock _l(mLock); 5389 return EffectGetDescriptor(pUuid, descriptor); 5390} 5391 5392 5393sp<IEffect> AudioFlinger::createEffect(pid_t pid, 5394 effect_descriptor_t *pDesc, 5395 const sp<IEffectClient>& effectClient, 5396 int32_t priority, 5397 int io, 5398 int sessionId, 5399 status_t *status, 5400 int *id, 5401 int *enabled) 5402{ 5403 status_t lStatus = NO_ERROR; 5404 sp<EffectHandle> handle; 5405 effect_descriptor_t desc; 5406 sp<Client> client; 5407 wp<Client> wclient; 5408 5409 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d", 5410 pid, effectClient.get(), priority, sessionId, io); 5411 5412 if (pDesc == NULL) { 5413 lStatus = BAD_VALUE; 5414 goto Exit; 5415 } 5416 5417 // check audio settings permission for global effects 5418 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 5419 lStatus = PERMISSION_DENIED; 5420 goto Exit; 5421 } 5422 5423 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 5424 // that can only be created by audio policy manager (running in same process) 5425 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) { 5426 lStatus = PERMISSION_DENIED; 5427 goto Exit; 5428 } 5429 5430 if (io == 0) { 5431 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 5432 // output must be specified by AudioPolicyManager when using session 5433 // AUDIO_SESSION_OUTPUT_STAGE 5434 lStatus = BAD_VALUE; 5435 goto Exit; 5436 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 5437 // if the output returned by getOutputForEffect() is removed before we lock the 5438 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 5439 // and we will exit safely 5440 io = AudioSystem::getOutputForEffect(&desc); 5441 } 5442 } 5443 5444 { 5445 Mutex::Autolock _l(mLock); 5446 5447 5448 if (!EffectIsNullUuid(&pDesc->uuid)) { 5449 // if uuid is specified, request effect descriptor 5450 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 5451 if (lStatus < 0) { 5452 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 5453 goto Exit; 5454 } 5455 } else { 5456 // if uuid is not specified, look for an available implementation 5457 // of the required type in effect factory 5458 if (EffectIsNullUuid(&pDesc->type)) { 5459 ALOGW("createEffect() no effect type"); 5460 lStatus = BAD_VALUE; 5461 goto Exit; 5462 } 5463 uint32_t numEffects = 0; 5464 effect_descriptor_t d; 5465 d.flags = 0; // prevent compiler warning 5466 bool found = false; 5467 5468 lStatus = EffectQueryNumberEffects(&numEffects); 5469 if (lStatus < 0) { 5470 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 5471 goto Exit; 5472 } 5473 for (uint32_t i = 0; i < numEffects; i++) { 5474 lStatus = EffectQueryEffect(i, &desc); 5475 if (lStatus < 0) { 5476 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 5477 continue; 5478 } 5479 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 5480 // If matching type found save effect descriptor. If the session is 5481 // 0 and the effect is not auxiliary, continue enumeration in case 5482 // an auxiliary version of this effect type is available 5483 found = true; 5484 memcpy(&d, &desc, sizeof(effect_descriptor_t)); 5485 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 5486 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5487 break; 5488 } 5489 } 5490 } 5491 if (!found) { 5492 lStatus = BAD_VALUE; 5493 ALOGW("createEffect() effect not found"); 5494 goto Exit; 5495 } 5496 // For same effect type, chose auxiliary version over insert version if 5497 // connect to output mix (Compliance to OpenSL ES) 5498 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 5499 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 5500 memcpy(&desc, &d, sizeof(effect_descriptor_t)); 5501 } 5502 } 5503 5504 // Do not allow auxiliary effects on a session different from 0 (output mix) 5505 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 5506 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5507 lStatus = INVALID_OPERATION; 5508 goto Exit; 5509 } 5510 5511 // check recording permission for visualizer 5512 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 5513 !recordingAllowed()) { 5514 lStatus = PERMISSION_DENIED; 5515 goto Exit; 5516 } 5517 5518 // return effect descriptor 5519 memcpy(pDesc, &desc, sizeof(effect_descriptor_t)); 5520 5521 // If output is not specified try to find a matching audio session ID in one of the 5522 // output threads. 5523 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 5524 // because of code checking output when entering the function. 5525 // Note: io is never 0 when creating an effect on an input 5526 if (io == 0) { 5527 // look for the thread where the specified audio session is present 5528 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5529 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 5530 io = mPlaybackThreads.keyAt(i); 5531 break; 5532 } 5533 } 5534 if (io == 0) { 5535 for (size_t i = 0; i < mRecordThreads.size(); i++) { 5536 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 5537 io = mRecordThreads.keyAt(i); 5538 break; 5539 } 5540 } 5541 } 5542 // If no output thread contains the requested session ID, default to 5543 // first output. The effect chain will be moved to the correct output 5544 // thread when a track with the same session ID is created 5545 if (io == 0 && mPlaybackThreads.size()) { 5546 io = mPlaybackThreads.keyAt(0); 5547 } 5548 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 5549 } 5550 ThreadBase *thread = checkRecordThread_l(io); 5551 if (thread == NULL) { 5552 thread = checkPlaybackThread_l(io); 5553 if (thread == NULL) { 5554 ALOGE("createEffect() unknown output thread"); 5555 lStatus = BAD_VALUE; 5556 goto Exit; 5557 } 5558 } 5559 5560 wclient = mClients.valueFor(pid); 5561 5562 if (wclient != NULL) { 5563 client = wclient.promote(); 5564 } else { 5565 client = new Client(this, pid); 5566 mClients.add(pid, client); 5567 } 5568 5569 // create effect on selected output thread 5570 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 5571 &desc, enabled, &lStatus); 5572 if (handle != 0 && id != NULL) { 5573 *id = handle->id(); 5574 } 5575 } 5576 5577Exit: 5578 if(status) { 5579 *status = lStatus; 5580 } 5581 return handle; 5582} 5583 5584status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput) 5585{ 5586 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 5587 sessionId, srcOutput, dstOutput); 5588 Mutex::Autolock _l(mLock); 5589 if (srcOutput == dstOutput) { 5590 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 5591 return NO_ERROR; 5592 } 5593 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 5594 if (srcThread == NULL) { 5595 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 5596 return BAD_VALUE; 5597 } 5598 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 5599 if (dstThread == NULL) { 5600 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 5601 return BAD_VALUE; 5602 } 5603 5604 Mutex::Autolock _dl(dstThread->mLock); 5605 Mutex::Autolock _sl(srcThread->mLock); 5606 moveEffectChain_l(sessionId, srcThread, dstThread, false); 5607 5608 return NO_ERROR; 5609} 5610 5611// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 5612status_t AudioFlinger::moveEffectChain_l(int sessionId, 5613 AudioFlinger::PlaybackThread *srcThread, 5614 AudioFlinger::PlaybackThread *dstThread, 5615 bool reRegister) 5616{ 5617 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 5618 sessionId, srcThread, dstThread); 5619 5620 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 5621 if (chain == 0) { 5622 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 5623 sessionId, srcThread); 5624 return INVALID_OPERATION; 5625 } 5626 5627 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 5628 // so that a new chain is created with correct parameters when first effect is added. This is 5629 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 5630 // removed. 5631 srcThread->removeEffectChain_l(chain); 5632 5633 // transfer all effects one by one so that new effect chain is created on new thread with 5634 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 5635 int dstOutput = dstThread->id(); 5636 sp<EffectChain> dstChain; 5637 uint32_t strategy = 0; // prevent compiler warning 5638 sp<EffectModule> effect = chain->getEffectFromId_l(0); 5639 while (effect != 0) { 5640 srcThread->removeEffect_l(effect); 5641 dstThread->addEffect_l(effect); 5642 // removeEffect_l() has stopped the effect if it was active so it must be restarted 5643 if (effect->state() == EffectModule::ACTIVE || 5644 effect->state() == EffectModule::STOPPING) { 5645 effect->start(); 5646 } 5647 // if the move request is not received from audio policy manager, the effect must be 5648 // re-registered with the new strategy and output 5649 if (dstChain == 0) { 5650 dstChain = effect->chain().promote(); 5651 if (dstChain == 0) { 5652 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 5653 srcThread->addEffect_l(effect); 5654 return NO_INIT; 5655 } 5656 strategy = dstChain->strategy(); 5657 } 5658 if (reRegister) { 5659 AudioSystem::unregisterEffect(effect->id()); 5660 AudioSystem::registerEffect(&effect->desc(), 5661 dstOutput, 5662 strategy, 5663 sessionId, 5664 effect->id()); 5665 } 5666 effect = chain->getEffectFromId_l(0); 5667 } 5668 5669 return NO_ERROR; 5670} 5671 5672 5673// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held 5674sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 5675 const sp<AudioFlinger::Client>& client, 5676 const sp<IEffectClient>& effectClient, 5677 int32_t priority, 5678 int sessionId, 5679 effect_descriptor_t *desc, 5680 int *enabled, 5681 status_t *status 5682 ) 5683{ 5684 sp<EffectModule> effect; 5685 sp<EffectHandle> handle; 5686 status_t lStatus; 5687 sp<EffectChain> chain; 5688 bool chainCreated = false; 5689 bool effectCreated = false; 5690 bool effectRegistered = false; 5691 5692 lStatus = initCheck(); 5693 if (lStatus != NO_ERROR) { 5694 ALOGW("createEffect_l() Audio driver not initialized."); 5695 goto Exit; 5696 } 5697 5698 // Do not allow effects with session ID 0 on direct output or duplicating threads 5699 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format 5700 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { 5701 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", 5702 desc->name, sessionId); 5703 lStatus = BAD_VALUE; 5704 goto Exit; 5705 } 5706 // Only Pre processor effects are allowed on input threads and only on input threads 5707 if ((mType == RECORD && 5708 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) || 5709 (mType != RECORD && 5710 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 5711 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 5712 desc->name, desc->flags, mType); 5713 lStatus = BAD_VALUE; 5714 goto Exit; 5715 } 5716 5717 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 5718 5719 { // scope for mLock 5720 Mutex::Autolock _l(mLock); 5721 5722 // check for existing effect chain with the requested audio session 5723 chain = getEffectChain_l(sessionId); 5724 if (chain == 0) { 5725 // create a new chain for this session 5726 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 5727 chain = new EffectChain(this, sessionId); 5728 addEffectChain_l(chain); 5729 chain->setStrategy(getStrategyForSession_l(sessionId)); 5730 chainCreated = true; 5731 } else { 5732 effect = chain->getEffectFromDesc_l(desc); 5733 } 5734 5735 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 5736 5737 if (effect == 0) { 5738 int id = mAudioFlinger->nextUniqueId(); 5739 // Check CPU and memory usage 5740 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 5741 if (lStatus != NO_ERROR) { 5742 goto Exit; 5743 } 5744 effectRegistered = true; 5745 // create a new effect module if none present in the chain 5746 effect = new EffectModule(this, chain, desc, id, sessionId); 5747 lStatus = effect->status(); 5748 if (lStatus != NO_ERROR) { 5749 goto Exit; 5750 } 5751 lStatus = chain->addEffect_l(effect); 5752 if (lStatus != NO_ERROR) { 5753 goto Exit; 5754 } 5755 effectCreated = true; 5756 5757 effect->setDevice(mDevice); 5758 effect->setMode(mAudioFlinger->getMode()); 5759 } 5760 // create effect handle and connect it to effect module 5761 handle = new EffectHandle(effect, client, effectClient, priority); 5762 lStatus = effect->addHandle(handle); 5763 if (enabled != NULL) { 5764 *enabled = (int)effect->isEnabled(); 5765 } 5766 } 5767 5768Exit: 5769 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 5770 Mutex::Autolock _l(mLock); 5771 if (effectCreated) { 5772 chain->removeEffect_l(effect); 5773 } 5774 if (effectRegistered) { 5775 AudioSystem::unregisterEffect(effect->id()); 5776 } 5777 if (chainCreated) { 5778 removeEffectChain_l(chain); 5779 } 5780 handle.clear(); 5781 } 5782 5783 if(status) { 5784 *status = lStatus; 5785 } 5786 return handle; 5787} 5788 5789sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 5790{ 5791 sp<EffectChain> chain = getEffectChain_l(sessionId); 5792 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 5793} 5794 5795// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 5796// PlaybackThread::mLock held 5797status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 5798{ 5799 // check for existing effect chain with the requested audio session 5800 int sessionId = effect->sessionId(); 5801 sp<EffectChain> chain = getEffectChain_l(sessionId); 5802 bool chainCreated = false; 5803 5804 if (chain == 0) { 5805 // create a new chain for this session 5806 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 5807 chain = new EffectChain(this, sessionId); 5808 addEffectChain_l(chain); 5809 chain->setStrategy(getStrategyForSession_l(sessionId)); 5810 chainCreated = true; 5811 } 5812 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 5813 5814 if (chain->getEffectFromId_l(effect->id()) != 0) { 5815 ALOGW("addEffect_l() %p effect %s already present in chain %p", 5816 this, effect->desc().name, chain.get()); 5817 return BAD_VALUE; 5818 } 5819 5820 status_t status = chain->addEffect_l(effect); 5821 if (status != NO_ERROR) { 5822 if (chainCreated) { 5823 removeEffectChain_l(chain); 5824 } 5825 return status; 5826 } 5827 5828 effect->setDevice(mDevice); 5829 effect->setMode(mAudioFlinger->getMode()); 5830 return NO_ERROR; 5831} 5832 5833void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 5834 5835 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 5836 effect_descriptor_t desc = effect->desc(); 5837 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5838 detachAuxEffect_l(effect->id()); 5839 } 5840 5841 sp<EffectChain> chain = effect->chain().promote(); 5842 if (chain != 0) { 5843 // remove effect chain if removing last effect 5844 if (chain->removeEffect_l(effect) == 0) { 5845 removeEffectChain_l(chain); 5846 } 5847 } else { 5848 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 5849 } 5850} 5851 5852void AudioFlinger::ThreadBase::lockEffectChains_l( 5853 Vector<sp <AudioFlinger::EffectChain> >& effectChains) 5854{ 5855 effectChains = mEffectChains; 5856 for (size_t i = 0; i < mEffectChains.size(); i++) { 5857 mEffectChains[i]->lock(); 5858 } 5859} 5860 5861void AudioFlinger::ThreadBase::unlockEffectChains( 5862 Vector<sp <AudioFlinger::EffectChain> >& effectChains) 5863{ 5864 for (size_t i = 0; i < effectChains.size(); i++) { 5865 effectChains[i]->unlock(); 5866 } 5867} 5868 5869sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 5870{ 5871 Mutex::Autolock _l(mLock); 5872 return getEffectChain_l(sessionId); 5873} 5874 5875sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) 5876{ 5877 size_t size = mEffectChains.size(); 5878 for (size_t i = 0; i < size; i++) { 5879 if (mEffectChains[i]->sessionId() == sessionId) { 5880 return mEffectChains[i]; 5881 } 5882 } 5883 return 0; 5884} 5885 5886void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 5887{ 5888 Mutex::Autolock _l(mLock); 5889 size_t size = mEffectChains.size(); 5890 for (size_t i = 0; i < size; i++) { 5891 mEffectChains[i]->setMode_l(mode); 5892 } 5893} 5894 5895void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 5896 const wp<EffectHandle>& handle, 5897 bool unpiniflast) { 5898 5899 Mutex::Autolock _l(mLock); 5900 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 5901 // delete the effect module if removing last handle on it 5902 if (effect->removeHandle(handle) == 0) { 5903 if (!effect->isPinned() || unpiniflast) { 5904 removeEffect_l(effect); 5905 AudioSystem::unregisterEffect(effect->id()); 5906 } 5907 } 5908} 5909 5910status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 5911{ 5912 int session = chain->sessionId(); 5913 int16_t *buffer = mMixBuffer; 5914 bool ownsBuffer = false; 5915 5916 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 5917 if (session > 0) { 5918 // Only one effect chain can be present in direct output thread and it uses 5919 // the mix buffer as input 5920 if (mType != DIRECT) { 5921 size_t numSamples = mFrameCount * mChannelCount; 5922 buffer = new int16_t[numSamples]; 5923 memset(buffer, 0, numSamples * sizeof(int16_t)); 5924 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 5925 ownsBuffer = true; 5926 } 5927 5928 // Attach all tracks with same session ID to this chain. 5929 for (size_t i = 0; i < mTracks.size(); ++i) { 5930 sp<Track> track = mTracks[i]; 5931 if (session == track->sessionId()) { 5932 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer); 5933 track->setMainBuffer(buffer); 5934 chain->incTrackCnt(); 5935 } 5936 } 5937 5938 // indicate all active tracks in the chain 5939 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 5940 sp<Track> track = mActiveTracks[i].promote(); 5941 if (track == 0) continue; 5942 if (session == track->sessionId()) { 5943 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 5944 chain->incActiveTrackCnt(); 5945 } 5946 } 5947 } 5948 5949 chain->setInBuffer(buffer, ownsBuffer); 5950 chain->setOutBuffer(mMixBuffer); 5951 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 5952 // chains list in order to be processed last as it contains output stage effects 5953 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 5954 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 5955 // after track specific effects and before output stage 5956 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 5957 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 5958 // Effect chain for other sessions are inserted at beginning of effect 5959 // chains list to be processed before output mix effects. Relative order between other 5960 // sessions is not important 5961 size_t size = mEffectChains.size(); 5962 size_t i = 0; 5963 for (i = 0; i < size; i++) { 5964 if (mEffectChains[i]->sessionId() < session) break; 5965 } 5966 mEffectChains.insertAt(chain, i); 5967 checkSuspendOnAddEffectChain_l(chain); 5968 5969 return NO_ERROR; 5970} 5971 5972size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 5973{ 5974 int session = chain->sessionId(); 5975 5976 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 5977 5978 for (size_t i = 0; i < mEffectChains.size(); i++) { 5979 if (chain == mEffectChains[i]) { 5980 mEffectChains.removeAt(i); 5981 // detach all active tracks from the chain 5982 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 5983 sp<Track> track = mActiveTracks[i].promote(); 5984 if (track == 0) continue; 5985 if (session == track->sessionId()) { 5986 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 5987 chain.get(), session); 5988 chain->decActiveTrackCnt(); 5989 } 5990 } 5991 5992 // detach all tracks with same session ID from this chain 5993 for (size_t i = 0; i < mTracks.size(); ++i) { 5994 sp<Track> track = mTracks[i]; 5995 if (session == track->sessionId()) { 5996 track->setMainBuffer(mMixBuffer); 5997 chain->decTrackCnt(); 5998 } 5999 } 6000 break; 6001 } 6002 } 6003 return mEffectChains.size(); 6004} 6005 6006status_t AudioFlinger::PlaybackThread::attachAuxEffect( 6007 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 6008{ 6009 Mutex::Autolock _l(mLock); 6010 return attachAuxEffect_l(track, EffectId); 6011} 6012 6013status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 6014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 6015{ 6016 status_t status = NO_ERROR; 6017 6018 if (EffectId == 0) { 6019 track->setAuxBuffer(0, NULL); 6020 } else { 6021 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 6022 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 6023 if (effect != 0) { 6024 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6025 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 6026 } else { 6027 status = INVALID_OPERATION; 6028 } 6029 } else { 6030 status = BAD_VALUE; 6031 } 6032 } 6033 return status; 6034} 6035 6036void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 6037{ 6038 for (size_t i = 0; i < mTracks.size(); ++i) { 6039 sp<Track> track = mTracks[i]; 6040 if (track->auxEffectId() == effectId) { 6041 attachAuxEffect_l(track, 0); 6042 } 6043 } 6044} 6045 6046status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 6047{ 6048 // only one chain per input thread 6049 if (mEffectChains.size() != 0) { 6050 return INVALID_OPERATION; 6051 } 6052 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 6053 6054 chain->setInBuffer(NULL); 6055 chain->setOutBuffer(NULL); 6056 6057 checkSuspendOnAddEffectChain_l(chain); 6058 6059 mEffectChains.add(chain); 6060 6061 return NO_ERROR; 6062} 6063 6064size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 6065{ 6066 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 6067 ALOGW_IF(mEffectChains.size() != 1, 6068 "removeEffectChain_l() %p invalid chain size %d on thread %p", 6069 chain.get(), mEffectChains.size(), this); 6070 if (mEffectChains.size() == 1) { 6071 mEffectChains.removeAt(0); 6072 } 6073 return 0; 6074} 6075 6076// ---------------------------------------------------------------------------- 6077// EffectModule implementation 6078// ---------------------------------------------------------------------------- 6079 6080#undef LOG_TAG 6081#define LOG_TAG "AudioFlinger::EffectModule" 6082 6083AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread, 6084 const wp<AudioFlinger::EffectChain>& chain, 6085 effect_descriptor_t *desc, 6086 int id, 6087 int sessionId) 6088 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL), 6089 mStatus(NO_INIT), mState(IDLE), mSuspended(false) 6090{ 6091 ALOGV("Constructor %p", this); 6092 int lStatus; 6093 sp<ThreadBase> thread = mThread.promote(); 6094 if (thread == 0) { 6095 return; 6096 } 6097 6098 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t)); 6099 6100 // create effect engine from effect factory 6101 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface); 6102 6103 if (mStatus != NO_ERROR) { 6104 return; 6105 } 6106 lStatus = init(); 6107 if (lStatus < 0) { 6108 mStatus = lStatus; 6109 goto Error; 6110 } 6111 6112 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) { 6113 mPinned = true; 6114 } 6115 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface); 6116 return; 6117Error: 6118 EffectRelease(mEffectInterface); 6119 mEffectInterface = NULL; 6120 ALOGV("Constructor Error %d", mStatus); 6121} 6122 6123AudioFlinger::EffectModule::~EffectModule() 6124{ 6125 ALOGV("Destructor %p", this); 6126 if (mEffectInterface != NULL) { 6127 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6128 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 6129 sp<ThreadBase> thread = mThread.promote(); 6130 if (thread != 0) { 6131 audio_stream_t *stream = thread->stream(); 6132 if (stream != NULL) { 6133 stream->remove_audio_effect(stream, mEffectInterface); 6134 } 6135 } 6136 } 6137 // release effect engine 6138 EffectRelease(mEffectInterface); 6139 } 6140} 6141 6142status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle) 6143{ 6144 status_t status; 6145 6146 Mutex::Autolock _l(mLock); 6147 // First handle in mHandles has highest priority and controls the effect module 6148 int priority = handle->priority(); 6149 size_t size = mHandles.size(); 6150 sp<EffectHandle> h; 6151 size_t i; 6152 for (i = 0; i < size; i++) { 6153 h = mHandles[i].promote(); 6154 if (h == 0) continue; 6155 if (h->priority() <= priority) break; 6156 } 6157 // if inserted in first place, move effect control from previous owner to this handle 6158 if (i == 0) { 6159 bool enabled = false; 6160 if (h != 0) { 6161 enabled = h->enabled(); 6162 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/); 6163 } 6164 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/); 6165 status = NO_ERROR; 6166 } else { 6167 status = ALREADY_EXISTS; 6168 } 6169 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i); 6170 mHandles.insertAt(handle, i); 6171 return status; 6172} 6173 6174size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle) 6175{ 6176 Mutex::Autolock _l(mLock); 6177 size_t size = mHandles.size(); 6178 size_t i; 6179 for (i = 0; i < size; i++) { 6180 if (mHandles[i] == handle) break; 6181 } 6182 if (i == size) { 6183 return size; 6184 } 6185 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i); 6186 6187 bool enabled = false; 6188 EffectHandle *hdl = handle.unsafe_get(); 6189 if (hdl != NULL) { 6190 ALOGV("removeHandle() unsafe_get OK"); 6191 enabled = hdl->enabled(); 6192 } 6193 mHandles.removeAt(i); 6194 size = mHandles.size(); 6195 // if removed from first place, move effect control from this handle to next in line 6196 if (i == 0 && size != 0) { 6197 sp<EffectHandle> h = mHandles[0].promote(); 6198 if (h != 0) { 6199 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/); 6200 } 6201 } 6202 6203 // Prevent calls to process() and other functions on effect interface from now on. 6204 // The effect engine will be released by the destructor when the last strong reference on 6205 // this object is released which can happen after next process is called. 6206 if (size == 0 && !mPinned) { 6207 mState = DESTROYED; 6208 } 6209 6210 return size; 6211} 6212 6213sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle() 6214{ 6215 Mutex::Autolock _l(mLock); 6216 return mHandles.size() != 0 ? mHandles[0].promote() : 0; 6217} 6218 6219void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast) 6220{ 6221 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get()); 6222 // keep a strong reference on this EffectModule to avoid calling the 6223 // destructor before we exit 6224 sp<EffectModule> keep(this); 6225 { 6226 sp<ThreadBase> thread = mThread.promote(); 6227 if (thread != 0) { 6228 thread->disconnectEffect(keep, handle, unpiniflast); 6229 } 6230 } 6231} 6232 6233void AudioFlinger::EffectModule::updateState() { 6234 Mutex::Autolock _l(mLock); 6235 6236 switch (mState) { 6237 case RESTART: 6238 reset_l(); 6239 // FALL THROUGH 6240 6241 case STARTING: 6242 // clear auxiliary effect input buffer for next accumulation 6243 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6244 memset(mConfig.inputCfg.buffer.raw, 6245 0, 6246 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 6247 } 6248 start_l(); 6249 mState = ACTIVE; 6250 break; 6251 case STOPPING: 6252 stop_l(); 6253 mDisableWaitCnt = mMaxDisableWaitCnt; 6254 mState = STOPPED; 6255 break; 6256 case STOPPED: 6257 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the 6258 // turn off sequence. 6259 if (--mDisableWaitCnt == 0) { 6260 reset_l(); 6261 mState = IDLE; 6262 } 6263 break; 6264 default: //IDLE , ACTIVE, DESTROYED 6265 break; 6266 } 6267} 6268 6269void AudioFlinger::EffectModule::process() 6270{ 6271 Mutex::Autolock _l(mLock); 6272 6273 if (mState == DESTROYED || mEffectInterface == NULL || 6274 mConfig.inputCfg.buffer.raw == NULL || 6275 mConfig.outputCfg.buffer.raw == NULL) { 6276 return; 6277 } 6278 6279 if (isProcessEnabled()) { 6280 // do 32 bit to 16 bit conversion for auxiliary effect input buffer 6281 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6282 ditherAndClamp(mConfig.inputCfg.buffer.s32, 6283 mConfig.inputCfg.buffer.s32, 6284 mConfig.inputCfg.buffer.frameCount/2); 6285 } 6286 6287 // do the actual processing in the effect engine 6288 int ret = (*mEffectInterface)->process(mEffectInterface, 6289 &mConfig.inputCfg.buffer, 6290 &mConfig.outputCfg.buffer); 6291 6292 // force transition to IDLE state when engine is ready 6293 if (mState == STOPPED && ret == -ENODATA) { 6294 mDisableWaitCnt = 1; 6295 } 6296 6297 // clear auxiliary effect input buffer for next accumulation 6298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6299 memset(mConfig.inputCfg.buffer.raw, 0, 6300 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 6301 } 6302 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT && 6303 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 6304 // If an insert effect is idle and input buffer is different from output buffer, 6305 // accumulate input onto output 6306 sp<EffectChain> chain = mChain.promote(); 6307 if (chain != 0 && chain->activeTrackCnt() != 0) { 6308 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here 6309 int16_t *in = mConfig.inputCfg.buffer.s16; 6310 int16_t *out = mConfig.outputCfg.buffer.s16; 6311 for (size_t i = 0; i < frameCnt; i++) { 6312 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]); 6313 } 6314 } 6315 } 6316} 6317 6318void AudioFlinger::EffectModule::reset_l() 6319{ 6320 if (mEffectInterface == NULL) { 6321 return; 6322 } 6323 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL); 6324} 6325 6326status_t AudioFlinger::EffectModule::configure() 6327{ 6328 uint32_t channels; 6329 if (mEffectInterface == NULL) { 6330 return NO_INIT; 6331 } 6332 6333 sp<ThreadBase> thread = mThread.promote(); 6334 if (thread == 0) { 6335 return DEAD_OBJECT; 6336 } 6337 6338 // TODO: handle configuration of effects replacing track process 6339 if (thread->channelCount() == 1) { 6340 channels = AUDIO_CHANNEL_OUT_MONO; 6341 } else { 6342 channels = AUDIO_CHANNEL_OUT_STEREO; 6343 } 6344 6345 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6346 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; 6347 } else { 6348 mConfig.inputCfg.channels = channels; 6349 } 6350 mConfig.outputCfg.channels = channels; 6351 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 6352 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 6353 mConfig.inputCfg.samplingRate = thread->sampleRate(); 6354 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; 6355 mConfig.inputCfg.bufferProvider.cookie = NULL; 6356 mConfig.inputCfg.bufferProvider.getBuffer = NULL; 6357 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; 6358 mConfig.outputCfg.bufferProvider.cookie = NULL; 6359 mConfig.outputCfg.bufferProvider.getBuffer = NULL; 6360 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; 6361 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; 6362 // Insert effect: 6363 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE, 6364 // always overwrites output buffer: input buffer == output buffer 6365 // - in other sessions: 6366 // last effect in the chain accumulates in output buffer: input buffer != output buffer 6367 // other effect: overwrites output buffer: input buffer == output buffer 6368 // Auxiliary effect: 6369 // accumulates in output buffer: input buffer != output buffer 6370 // Therefore: accumulate <=> input buffer != output buffer 6371 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 6372 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; 6373 } else { 6374 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; 6375 } 6376 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; 6377 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; 6378 mConfig.inputCfg.buffer.frameCount = thread->frameCount(); 6379 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; 6380 6381 ALOGV("configure() %p thread %p buffer %p framecount %d", 6382 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); 6383 6384 status_t cmdStatus; 6385 uint32_t size = sizeof(int); 6386 status_t status = (*mEffectInterface)->command(mEffectInterface, 6387 EFFECT_CMD_SET_CONFIG, 6388 sizeof(effect_config_t), 6389 &mConfig, 6390 &size, 6391 &cmdStatus); 6392 if (status == 0) { 6393 status = cmdStatus; 6394 } 6395 6396 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / 6397 (1000 * mConfig.outputCfg.buffer.frameCount); 6398 6399 return status; 6400} 6401 6402status_t AudioFlinger::EffectModule::init() 6403{ 6404 Mutex::Autolock _l(mLock); 6405 if (mEffectInterface == NULL) { 6406 return NO_INIT; 6407 } 6408 status_t cmdStatus; 6409 uint32_t size = sizeof(status_t); 6410 status_t status = (*mEffectInterface)->command(mEffectInterface, 6411 EFFECT_CMD_INIT, 6412 0, 6413 NULL, 6414 &size, 6415 &cmdStatus); 6416 if (status == 0) { 6417 status = cmdStatus; 6418 } 6419 return status; 6420} 6421 6422status_t AudioFlinger::EffectModule::start() 6423{ 6424 Mutex::Autolock _l(mLock); 6425 return start_l(); 6426} 6427 6428status_t AudioFlinger::EffectModule::start_l() 6429{ 6430 if (mEffectInterface == NULL) { 6431 return NO_INIT; 6432 } 6433 status_t cmdStatus; 6434 uint32_t size = sizeof(status_t); 6435 status_t status = (*mEffectInterface)->command(mEffectInterface, 6436 EFFECT_CMD_ENABLE, 6437 0, 6438 NULL, 6439 &size, 6440 &cmdStatus); 6441 if (status == 0) { 6442 status = cmdStatus; 6443 } 6444 if (status == 0 && 6445 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6446 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 6447 sp<ThreadBase> thread = mThread.promote(); 6448 if (thread != 0) { 6449 audio_stream_t *stream = thread->stream(); 6450 if (stream != NULL) { 6451 stream->add_audio_effect(stream, mEffectInterface); 6452 } 6453 } 6454 } 6455 return status; 6456} 6457 6458status_t AudioFlinger::EffectModule::stop() 6459{ 6460 Mutex::Autolock _l(mLock); 6461 return stop_l(); 6462} 6463 6464status_t AudioFlinger::EffectModule::stop_l() 6465{ 6466 if (mEffectInterface == NULL) { 6467 return NO_INIT; 6468 } 6469 status_t cmdStatus; 6470 uint32_t size = sizeof(status_t); 6471 status_t status = (*mEffectInterface)->command(mEffectInterface, 6472 EFFECT_CMD_DISABLE, 6473 0, 6474 NULL, 6475 &size, 6476 &cmdStatus); 6477 if (status == 0) { 6478 status = cmdStatus; 6479 } 6480 if (status == 0 && 6481 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6482 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 6483 sp<ThreadBase> thread = mThread.promote(); 6484 if (thread != 0) { 6485 audio_stream_t *stream = thread->stream(); 6486 if (stream != NULL) { 6487 stream->remove_audio_effect(stream, mEffectInterface); 6488 } 6489 } 6490 } 6491 return status; 6492} 6493 6494status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, 6495 uint32_t cmdSize, 6496 void *pCmdData, 6497 uint32_t *replySize, 6498 void *pReplyData) 6499{ 6500 Mutex::Autolock _l(mLock); 6501// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); 6502 6503 if (mState == DESTROYED || mEffectInterface == NULL) { 6504 return NO_INIT; 6505 } 6506 status_t status = (*mEffectInterface)->command(mEffectInterface, 6507 cmdCode, 6508 cmdSize, 6509 pCmdData, 6510 replySize, 6511 pReplyData); 6512 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { 6513 uint32_t size = (replySize == NULL) ? 0 : *replySize; 6514 for (size_t i = 1; i < mHandles.size(); i++) { 6515 sp<EffectHandle> h = mHandles[i].promote(); 6516 if (h != 0) { 6517 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); 6518 } 6519 } 6520 } 6521 return status; 6522} 6523 6524status_t AudioFlinger::EffectModule::setEnabled(bool enabled) 6525{ 6526 6527 Mutex::Autolock _l(mLock); 6528 ALOGV("setEnabled %p enabled %d", this, enabled); 6529 6530 if (enabled != isEnabled()) { 6531 status_t status = AudioSystem::setEffectEnabled(mId, enabled); 6532 if (enabled && status != NO_ERROR) { 6533 return status; 6534 } 6535 6536 switch (mState) { 6537 // going from disabled to enabled 6538 case IDLE: 6539 mState = STARTING; 6540 break; 6541 case STOPPED: 6542 mState = RESTART; 6543 break; 6544 case STOPPING: 6545 mState = ACTIVE; 6546 break; 6547 6548 // going from enabled to disabled 6549 case RESTART: 6550 mState = STOPPED; 6551 break; 6552 case STARTING: 6553 mState = IDLE; 6554 break; 6555 case ACTIVE: 6556 mState = STOPPING; 6557 break; 6558 case DESTROYED: 6559 return NO_ERROR; // simply ignore as we are being destroyed 6560 } 6561 for (size_t i = 1; i < mHandles.size(); i++) { 6562 sp<EffectHandle> h = mHandles[i].promote(); 6563 if (h != 0) { 6564 h->setEnabled(enabled); 6565 } 6566 } 6567 } 6568 return NO_ERROR; 6569} 6570 6571bool AudioFlinger::EffectModule::isEnabled() const 6572{ 6573 switch (mState) { 6574 case RESTART: 6575 case STARTING: 6576 case ACTIVE: 6577 return true; 6578 case IDLE: 6579 case STOPPING: 6580 case STOPPED: 6581 case DESTROYED: 6582 default: 6583 return false; 6584 } 6585} 6586 6587bool AudioFlinger::EffectModule::isProcessEnabled() const 6588{ 6589 switch (mState) { 6590 case RESTART: 6591 case ACTIVE: 6592 case STOPPING: 6593 case STOPPED: 6594 return true; 6595 case IDLE: 6596 case STARTING: 6597 case DESTROYED: 6598 default: 6599 return false; 6600 } 6601} 6602 6603status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller) 6604{ 6605 Mutex::Autolock _l(mLock); 6606 status_t status = NO_ERROR; 6607 6608 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume 6609 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set) 6610 if (isProcessEnabled() && 6611 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL || 6612 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) { 6613 status_t cmdStatus; 6614 uint32_t volume[2]; 6615 uint32_t *pVolume = NULL; 6616 uint32_t size = sizeof(volume); 6617 volume[0] = *left; 6618 volume[1] = *right; 6619 if (controller) { 6620 pVolume = volume; 6621 } 6622 status = (*mEffectInterface)->command(mEffectInterface, 6623 EFFECT_CMD_SET_VOLUME, 6624 size, 6625 volume, 6626 &size, 6627 pVolume); 6628 if (controller && status == NO_ERROR && size == sizeof(volume)) { 6629 *left = volume[0]; 6630 *right = volume[1]; 6631 } 6632 } 6633 return status; 6634} 6635 6636status_t AudioFlinger::EffectModule::setDevice(uint32_t device) 6637{ 6638 Mutex::Autolock _l(mLock); 6639 status_t status = NO_ERROR; 6640 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) { 6641 // audio pre processing modules on RecordThread can receive both output and 6642 // input device indication in the same call 6643 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL; 6644 if (dev) { 6645 status_t cmdStatus; 6646 uint32_t size = sizeof(status_t); 6647 6648 status = (*mEffectInterface)->command(mEffectInterface, 6649 EFFECT_CMD_SET_DEVICE, 6650 sizeof(uint32_t), 6651 &dev, 6652 &size, 6653 &cmdStatus); 6654 if (status == NO_ERROR) { 6655 status = cmdStatus; 6656 } 6657 } 6658 dev = device & AUDIO_DEVICE_IN_ALL; 6659 if (dev) { 6660 status_t cmdStatus; 6661 uint32_t size = sizeof(status_t); 6662 6663 status_t status2 = (*mEffectInterface)->command(mEffectInterface, 6664 EFFECT_CMD_SET_INPUT_DEVICE, 6665 sizeof(uint32_t), 6666 &dev, 6667 &size, 6668 &cmdStatus); 6669 if (status2 == NO_ERROR) { 6670 status2 = cmdStatus; 6671 } 6672 if (status == NO_ERROR) { 6673 status = status2; 6674 } 6675 } 6676 } 6677 return status; 6678} 6679 6680status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode) 6681{ 6682 Mutex::Autolock _l(mLock); 6683 status_t status = NO_ERROR; 6684 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) { 6685 status_t cmdStatus; 6686 uint32_t size = sizeof(status_t); 6687 status = (*mEffectInterface)->command(mEffectInterface, 6688 EFFECT_CMD_SET_AUDIO_MODE, 6689 sizeof(audio_mode_t), 6690 &mode, 6691 &size, 6692 &cmdStatus); 6693 if (status == NO_ERROR) { 6694 status = cmdStatus; 6695 } 6696 } 6697 return status; 6698} 6699 6700void AudioFlinger::EffectModule::setSuspended(bool suspended) 6701{ 6702 Mutex::Autolock _l(mLock); 6703 mSuspended = suspended; 6704} 6705 6706bool AudioFlinger::EffectModule::suspended() const 6707{ 6708 Mutex::Autolock _l(mLock); 6709 return mSuspended; 6710} 6711 6712status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args) 6713{ 6714 const size_t SIZE = 256; 6715 char buffer[SIZE]; 6716 String8 result; 6717 6718 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId); 6719 result.append(buffer); 6720 6721 bool locked = tryLock(mLock); 6722 // failed to lock - AudioFlinger is probably deadlocked 6723 if (!locked) { 6724 result.append("\t\tCould not lock Fx mutex:\n"); 6725 } 6726 6727 result.append("\t\tSession Status State Engine:\n"); 6728 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n", 6729 mSessionId, mStatus, mState, (uint32_t)mEffectInterface); 6730 result.append(buffer); 6731 6732 result.append("\t\tDescriptor:\n"); 6733 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 6734 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, 6735 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2], 6736 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); 6737 result.append(buffer); 6738 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 6739 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion, 6740 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2], 6741 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); 6742 result.append(buffer); 6743 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n", 6744 mDescriptor.apiVersion, 6745 mDescriptor.flags); 6746 result.append(buffer); 6747 snprintf(buffer, SIZE, "\t\t- name: %s\n", 6748 mDescriptor.name); 6749 result.append(buffer); 6750 snprintf(buffer, SIZE, "\t\t- implementor: %s\n", 6751 mDescriptor.implementor); 6752 result.append(buffer); 6753 6754 result.append("\t\t- Input configuration:\n"); 6755 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 6756 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 6757 (uint32_t)mConfig.inputCfg.buffer.raw, 6758 mConfig.inputCfg.buffer.frameCount, 6759 mConfig.inputCfg.samplingRate, 6760 mConfig.inputCfg.channels, 6761 mConfig.inputCfg.format); 6762 result.append(buffer); 6763 6764 result.append("\t\t- Output configuration:\n"); 6765 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 6766 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 6767 (uint32_t)mConfig.outputCfg.buffer.raw, 6768 mConfig.outputCfg.buffer.frameCount, 6769 mConfig.outputCfg.samplingRate, 6770 mConfig.outputCfg.channels, 6771 mConfig.outputCfg.format); 6772 result.append(buffer); 6773 6774 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size()); 6775 result.append(buffer); 6776 result.append("\t\t\tPid Priority Ctrl Locked client server\n"); 6777 for (size_t i = 0; i < mHandles.size(); ++i) { 6778 sp<EffectHandle> handle = mHandles[i].promote(); 6779 if (handle != 0) { 6780 handle->dump(buffer, SIZE); 6781 result.append(buffer); 6782 } 6783 } 6784 6785 result.append("\n"); 6786 6787 write(fd, result.string(), result.length()); 6788 6789 if (locked) { 6790 mLock.unlock(); 6791 } 6792 6793 return NO_ERROR; 6794} 6795 6796// ---------------------------------------------------------------------------- 6797// EffectHandle implementation 6798// ---------------------------------------------------------------------------- 6799 6800#undef LOG_TAG 6801#define LOG_TAG "AudioFlinger::EffectHandle" 6802 6803AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect, 6804 const sp<AudioFlinger::Client>& client, 6805 const sp<IEffectClient>& effectClient, 6806 int32_t priority) 6807 : BnEffect(), 6808 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL), 6809 mPriority(priority), mHasControl(false), mEnabled(false) 6810{ 6811 ALOGV("constructor %p", this); 6812 6813 if (client == 0) { 6814 return; 6815 } 6816 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int); 6817 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset); 6818 if (mCblkMemory != 0) { 6819 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer()); 6820 6821 if (mCblk != NULL) { 6822 new(mCblk) effect_param_cblk_t(); 6823 mBuffer = (uint8_t *)mCblk + bufOffset; 6824 } 6825 } else { 6826 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t)); 6827 return; 6828 } 6829} 6830 6831AudioFlinger::EffectHandle::~EffectHandle() 6832{ 6833 ALOGV("Destructor %p", this); 6834 disconnect(false); 6835 ALOGV("Destructor DONE %p", this); 6836} 6837 6838status_t AudioFlinger::EffectHandle::enable() 6839{ 6840 ALOGV("enable %p", this); 6841 if (!mHasControl) return INVALID_OPERATION; 6842 if (mEffect == 0) return DEAD_OBJECT; 6843 6844 if (mEnabled) { 6845 return NO_ERROR; 6846 } 6847 6848 mEnabled = true; 6849 6850 sp<ThreadBase> thread = mEffect->thread().promote(); 6851 if (thread != 0) { 6852 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId()); 6853 } 6854 6855 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled 6856 if (mEffect->suspended()) { 6857 return NO_ERROR; 6858 } 6859 6860 status_t status = mEffect->setEnabled(true); 6861 if (status != NO_ERROR) { 6862 if (thread != 0) { 6863 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6864 } 6865 mEnabled = false; 6866 } 6867 return status; 6868} 6869 6870status_t AudioFlinger::EffectHandle::disable() 6871{ 6872 ALOGV("disable %p", this); 6873 if (!mHasControl) return INVALID_OPERATION; 6874 if (mEffect == 0) return DEAD_OBJECT; 6875 6876 if (!mEnabled) { 6877 return NO_ERROR; 6878 } 6879 mEnabled = false; 6880 6881 if (mEffect->suspended()) { 6882 return NO_ERROR; 6883 } 6884 6885 status_t status = mEffect->setEnabled(false); 6886 6887 sp<ThreadBase> thread = mEffect->thread().promote(); 6888 if (thread != 0) { 6889 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6890 } 6891 6892 return status; 6893} 6894 6895void AudioFlinger::EffectHandle::disconnect() 6896{ 6897 disconnect(true); 6898} 6899 6900void AudioFlinger::EffectHandle::disconnect(bool unpiniflast) 6901{ 6902 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false"); 6903 if (mEffect == 0) { 6904 return; 6905 } 6906 mEffect->disconnect(this, unpiniflast); 6907 6908 if (mHasControl && mEnabled) { 6909 sp<ThreadBase> thread = mEffect->thread().promote(); 6910 if (thread != 0) { 6911 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6912 } 6913 } 6914 6915 // release sp on module => module destructor can be called now 6916 mEffect.clear(); 6917 if (mClient != 0) { 6918 if (mCblk != NULL) { 6919 // unlike ~TrackBase(), mCblk is never a local new, so don't delete 6920 mCblk->~effect_param_cblk_t(); // destroy our shared-structure. 6921 } 6922 mCblkMemory.clear(); // and free the shared memory 6923 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 6924 mClient.clear(); 6925 } 6926} 6927 6928status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode, 6929 uint32_t cmdSize, 6930 void *pCmdData, 6931 uint32_t *replySize, 6932 void *pReplyData) 6933{ 6934// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", 6935// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get()); 6936 6937 // only get parameter command is permitted for applications not controlling the effect 6938 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) { 6939 return INVALID_OPERATION; 6940 } 6941 if (mEffect == 0) return DEAD_OBJECT; 6942 if (mClient == 0) return INVALID_OPERATION; 6943 6944 // handle commands that are not forwarded transparently to effect engine 6945 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) { 6946 // No need to trylock() here as this function is executed in the binder thread serving a particular client process: 6947 // no risk to block the whole media server process or mixer threads is we are stuck here 6948 Mutex::Autolock _l(mCblk->lock); 6949 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE || 6950 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) { 6951 mCblk->serverIndex = 0; 6952 mCblk->clientIndex = 0; 6953 return BAD_VALUE; 6954 } 6955 status_t status = NO_ERROR; 6956 while (mCblk->serverIndex < mCblk->clientIndex) { 6957 int reply; 6958 uint32_t rsize = sizeof(int); 6959 int *p = (int *)(mBuffer + mCblk->serverIndex); 6960 int size = *p++; 6961 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) { 6962 ALOGW("command(): invalid parameter block size"); 6963 break; 6964 } 6965 effect_param_t *param = (effect_param_t *)p; 6966 if (param->psize == 0 || param->vsize == 0) { 6967 ALOGW("command(): null parameter or value size"); 6968 mCblk->serverIndex += size; 6969 continue; 6970 } 6971 uint32_t psize = sizeof(effect_param_t) + 6972 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + 6973 param->vsize; 6974 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, 6975 psize, 6976 p, 6977 &rsize, 6978 &reply); 6979 // stop at first error encountered 6980 if (ret != NO_ERROR) { 6981 status = ret; 6982 *(int *)pReplyData = reply; 6983 break; 6984 } else if (reply != NO_ERROR) { 6985 *(int *)pReplyData = reply; 6986 break; 6987 } 6988 mCblk->serverIndex += size; 6989 } 6990 mCblk->serverIndex = 0; 6991 mCblk->clientIndex = 0; 6992 return status; 6993 } else if (cmdCode == EFFECT_CMD_ENABLE) { 6994 *(int *)pReplyData = NO_ERROR; 6995 return enable(); 6996 } else if (cmdCode == EFFECT_CMD_DISABLE) { 6997 *(int *)pReplyData = NO_ERROR; 6998 return disable(); 6999 } 7000 7001 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 7002} 7003 7004void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled) 7005{ 7006 ALOGV("setControl %p control %d", this, hasControl); 7007 7008 mHasControl = hasControl; 7009 mEnabled = enabled; 7010 7011 if (signal && mEffectClient != 0) { 7012 mEffectClient->controlStatusChanged(hasControl); 7013 } 7014} 7015 7016void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode, 7017 uint32_t cmdSize, 7018 void *pCmdData, 7019 uint32_t replySize, 7020 void *pReplyData) 7021{ 7022 if (mEffectClient != 0) { 7023 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 7024 } 7025} 7026 7027 7028 7029void AudioFlinger::EffectHandle::setEnabled(bool enabled) 7030{ 7031 if (mEffectClient != 0) { 7032 mEffectClient->enableStatusChanged(enabled); 7033 } 7034} 7035 7036status_t AudioFlinger::EffectHandle::onTransact( 7037 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 7038{ 7039 return BnEffect::onTransact(code, data, reply, flags); 7040} 7041 7042 7043void AudioFlinger::EffectHandle::dump(char* buffer, size_t size) 7044{ 7045 bool locked = mCblk != NULL && tryLock(mCblk->lock); 7046 7047 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n", 7048 (mClient == 0) ? getpid() : mClient->pid(), 7049 mPriority, 7050 mHasControl, 7051 !locked, 7052 mCblk ? mCblk->clientIndex : 0, 7053 mCblk ? mCblk->serverIndex : 0 7054 ); 7055 7056 if (locked) { 7057 mCblk->lock.unlock(); 7058 } 7059} 7060 7061#undef LOG_TAG 7062#define LOG_TAG "AudioFlinger::EffectChain" 7063 7064AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread, 7065 int sessionId) 7066 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0), 7067 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX), 7068 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX) 7069{ 7070 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 7071 sp<ThreadBase> thread = mThread.promote(); 7072 if (thread == 0) { 7073 return; 7074 } 7075 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) / 7076 thread->frameCount(); 7077} 7078 7079AudioFlinger::EffectChain::~EffectChain() 7080{ 7081 if (mOwnInBuffer) { 7082 delete mInBuffer; 7083 } 7084 7085} 7086 7087// getEffectFromDesc_l() must be called with ThreadBase::mLock held 7088sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor) 7089{ 7090 size_t size = mEffects.size(); 7091 7092 for (size_t i = 0; i < size; i++) { 7093 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) { 7094 return mEffects[i]; 7095 } 7096 } 7097 return 0; 7098} 7099 7100// getEffectFromId_l() must be called with ThreadBase::mLock held 7101sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id) 7102{ 7103 size_t size = mEffects.size(); 7104 7105 for (size_t i = 0; i < size; i++) { 7106 // by convention, return first effect if id provided is 0 (0 is never a valid id) 7107 if (id == 0 || mEffects[i]->id() == id) { 7108 return mEffects[i]; 7109 } 7110 } 7111 return 0; 7112} 7113 7114// getEffectFromType_l() must be called with ThreadBase::mLock held 7115sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l( 7116 const effect_uuid_t *type) 7117{ 7118 size_t size = mEffects.size(); 7119 7120 for (size_t i = 0; i < size; i++) { 7121 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) { 7122 return mEffects[i]; 7123 } 7124 } 7125 return 0; 7126} 7127 7128// Must be called with EffectChain::mLock locked 7129void AudioFlinger::EffectChain::process_l() 7130{ 7131 sp<ThreadBase> thread = mThread.promote(); 7132 if (thread == 0) { 7133 ALOGW("process_l(): cannot promote mixer thread"); 7134 return; 7135 } 7136 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) || 7137 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE); 7138 // always process effects unless no more tracks are on the session and the effect tail 7139 // has been rendered 7140 bool doProcess = true; 7141 if (!isGlobalSession) { 7142 bool tracksOnSession = (trackCnt() != 0); 7143 7144 if (!tracksOnSession && mTailBufferCount == 0) { 7145 doProcess = false; 7146 } 7147 7148 if (activeTrackCnt() == 0) { 7149 // if no track is active and the effect tail has not been rendered, 7150 // the input buffer must be cleared here as the mixer process will not do it 7151 if (tracksOnSession || mTailBufferCount > 0) { 7152 size_t numSamples = thread->frameCount() * thread->channelCount(); 7153 memset(mInBuffer, 0, numSamples * sizeof(int16_t)); 7154 if (mTailBufferCount > 0) { 7155 mTailBufferCount--; 7156 } 7157 } 7158 } 7159 } 7160 7161 size_t size = mEffects.size(); 7162 if (doProcess) { 7163 for (size_t i = 0; i < size; i++) { 7164 mEffects[i]->process(); 7165 } 7166 } 7167 for (size_t i = 0; i < size; i++) { 7168 mEffects[i]->updateState(); 7169 } 7170} 7171 7172// addEffect_l() must be called with PlaybackThread::mLock held 7173status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect) 7174{ 7175 effect_descriptor_t desc = effect->desc(); 7176 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK; 7177 7178 Mutex::Autolock _l(mLock); 7179 effect->setChain(this); 7180 sp<ThreadBase> thread = mThread.promote(); 7181 if (thread == 0) { 7182 return NO_INIT; 7183 } 7184 effect->setThread(thread); 7185 7186 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7187 // Auxiliary effects are inserted at the beginning of mEffects vector as 7188 // they are processed first and accumulated in chain input buffer 7189 mEffects.insertAt(effect, 0); 7190 7191 // the input buffer for auxiliary effect contains mono samples in 7192 // 32 bit format. This is to avoid saturation in AudoMixer 7193 // accumulation stage. Saturation is done in EffectModule::process() before 7194 // calling the process in effect engine 7195 size_t numSamples = thread->frameCount(); 7196 int32_t *buffer = new int32_t[numSamples]; 7197 memset(buffer, 0, numSamples * sizeof(int32_t)); 7198 effect->setInBuffer((int16_t *)buffer); 7199 // auxiliary effects output samples to chain input buffer for further processing 7200 // by insert effects 7201 effect->setOutBuffer(mInBuffer); 7202 } else { 7203 // Insert effects are inserted at the end of mEffects vector as they are processed 7204 // after track and auxiliary effects. 7205 // Insert effect order as a function of indicated preference: 7206 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if 7207 // another effect is present 7208 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the 7209 // last effect claiming first position 7210 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the 7211 // first effect claiming last position 7212 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last 7213 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is 7214 // already present 7215 7216 int size = (int)mEffects.size(); 7217 int idx_insert = size; 7218 int idx_insert_first = -1; 7219 int idx_insert_last = -1; 7220 7221 for (int i = 0; i < size; i++) { 7222 effect_descriptor_t d = mEffects[i]->desc(); 7223 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK; 7224 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK; 7225 if (iMode == EFFECT_FLAG_TYPE_INSERT) { 7226 // check invalid effect chaining combinations 7227 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE || 7228 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) { 7229 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name); 7230 return INVALID_OPERATION; 7231 } 7232 // remember position of first insert effect and by default 7233 // select this as insert position for new effect 7234 if (idx_insert == size) { 7235 idx_insert = i; 7236 } 7237 // remember position of last insert effect claiming 7238 // first position 7239 if (iPref == EFFECT_FLAG_INSERT_FIRST) { 7240 idx_insert_first = i; 7241 } 7242 // remember position of first insert effect claiming 7243 // last position 7244 if (iPref == EFFECT_FLAG_INSERT_LAST && 7245 idx_insert_last == -1) { 7246 idx_insert_last = i; 7247 } 7248 } 7249 } 7250 7251 // modify idx_insert from first position if needed 7252 if (insertPref == EFFECT_FLAG_INSERT_LAST) { 7253 if (idx_insert_last != -1) { 7254 idx_insert = idx_insert_last; 7255 } else { 7256 idx_insert = size; 7257 } 7258 } else { 7259 if (idx_insert_first != -1) { 7260 idx_insert = idx_insert_first + 1; 7261 } 7262 } 7263 7264 // always read samples from chain input buffer 7265 effect->setInBuffer(mInBuffer); 7266 7267 // if last effect in the chain, output samples to chain 7268 // output buffer, otherwise to chain input buffer 7269 if (idx_insert == size) { 7270 if (idx_insert != 0) { 7271 mEffects[idx_insert-1]->setOutBuffer(mInBuffer); 7272 mEffects[idx_insert-1]->configure(); 7273 } 7274 effect->setOutBuffer(mOutBuffer); 7275 } else { 7276 effect->setOutBuffer(mInBuffer); 7277 } 7278 mEffects.insertAt(effect, idx_insert); 7279 7280 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert); 7281 } 7282 effect->configure(); 7283 return NO_ERROR; 7284} 7285 7286// removeEffect_l() must be called with PlaybackThread::mLock held 7287size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect) 7288{ 7289 Mutex::Autolock _l(mLock); 7290 int size = (int)mEffects.size(); 7291 int i; 7292 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK; 7293 7294 for (i = 0; i < size; i++) { 7295 if (effect == mEffects[i]) { 7296 // calling stop here will remove pre-processing effect from the audio HAL. 7297 // This is safe as we hold the EffectChain mutex which guarantees that we are not in 7298 // the middle of a read from audio HAL 7299 if (mEffects[i]->state() == EffectModule::ACTIVE || 7300 mEffects[i]->state() == EffectModule::STOPPING) { 7301 mEffects[i]->stop(); 7302 } 7303 if (type == EFFECT_FLAG_TYPE_AUXILIARY) { 7304 delete[] effect->inBuffer(); 7305 } else { 7306 if (i == size - 1 && i != 0) { 7307 mEffects[i - 1]->setOutBuffer(mOutBuffer); 7308 mEffects[i - 1]->configure(); 7309 } 7310 } 7311 mEffects.removeAt(i); 7312 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i); 7313 break; 7314 } 7315 } 7316 7317 return mEffects.size(); 7318} 7319 7320// setDevice_l() must be called with PlaybackThread::mLock held 7321void AudioFlinger::EffectChain::setDevice_l(uint32_t device) 7322{ 7323 size_t size = mEffects.size(); 7324 for (size_t i = 0; i < size; i++) { 7325 mEffects[i]->setDevice(device); 7326 } 7327} 7328 7329// setMode_l() must be called with PlaybackThread::mLock held 7330void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode) 7331{ 7332 size_t size = mEffects.size(); 7333 for (size_t i = 0; i < size; i++) { 7334 mEffects[i]->setMode(mode); 7335 } 7336} 7337 7338// setVolume_l() must be called with PlaybackThread::mLock held 7339bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right) 7340{ 7341 uint32_t newLeft = *left; 7342 uint32_t newRight = *right; 7343 bool hasControl = false; 7344 int ctrlIdx = -1; 7345 size_t size = mEffects.size(); 7346 7347 // first update volume controller 7348 for (size_t i = size; i > 0; i--) { 7349 if (mEffects[i - 1]->isProcessEnabled() && 7350 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) { 7351 ctrlIdx = i - 1; 7352 hasControl = true; 7353 break; 7354 } 7355 } 7356 7357 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) { 7358 if (hasControl) { 7359 *left = mNewLeftVolume; 7360 *right = mNewRightVolume; 7361 } 7362 return hasControl; 7363 } 7364 7365 mVolumeCtrlIdx = ctrlIdx; 7366 mLeftVolume = newLeft; 7367 mRightVolume = newRight; 7368 7369 // second get volume update from volume controller 7370 if (ctrlIdx >= 0) { 7371 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true); 7372 mNewLeftVolume = newLeft; 7373 mNewRightVolume = newRight; 7374 } 7375 // then indicate volume to all other effects in chain. 7376 // Pass altered volume to effects before volume controller 7377 // and requested volume to effects after controller 7378 uint32_t lVol = newLeft; 7379 uint32_t rVol = newRight; 7380 7381 for (size_t i = 0; i < size; i++) { 7382 if ((int)i == ctrlIdx) continue; 7383 // this also works for ctrlIdx == -1 when there is no volume controller 7384 if ((int)i > ctrlIdx) { 7385 lVol = *left; 7386 rVol = *right; 7387 } 7388 mEffects[i]->setVolume(&lVol, &rVol, false); 7389 } 7390 *left = newLeft; 7391 *right = newRight; 7392 7393 return hasControl; 7394} 7395 7396status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args) 7397{ 7398 const size_t SIZE = 256; 7399 char buffer[SIZE]; 7400 String8 result; 7401 7402 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId); 7403 result.append(buffer); 7404 7405 bool locked = tryLock(mLock); 7406 // failed to lock - AudioFlinger is probably deadlocked 7407 if (!locked) { 7408 result.append("\tCould not lock mutex:\n"); 7409 } 7410 7411 result.append("\tNum fx In buffer Out buffer Active tracks:\n"); 7412 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n", 7413 mEffects.size(), 7414 (uint32_t)mInBuffer, 7415 (uint32_t)mOutBuffer, 7416 mActiveTrackCnt); 7417 result.append(buffer); 7418 write(fd, result.string(), result.size()); 7419 7420 for (size_t i = 0; i < mEffects.size(); ++i) { 7421 sp<EffectModule> effect = mEffects[i]; 7422 if (effect != 0) { 7423 effect->dump(fd, args); 7424 } 7425 } 7426 7427 if (locked) { 7428 mLock.unlock(); 7429 } 7430 7431 return NO_ERROR; 7432} 7433 7434// must be called with ThreadBase::mLock held 7435void AudioFlinger::EffectChain::setEffectSuspended_l( 7436 const effect_uuid_t *type, bool suspend) 7437{ 7438 sp<SuspendedEffectDesc> desc; 7439 // use effect type UUID timelow as key as there is no real risk of identical 7440 // timeLow fields among effect type UUIDs. 7441 int index = mSuspendedEffects.indexOfKey(type->timeLow); 7442 if (suspend) { 7443 if (index >= 0) { 7444 desc = mSuspendedEffects.valueAt(index); 7445 } else { 7446 desc = new SuspendedEffectDesc(); 7447 memcpy(&desc->mType, type, sizeof(effect_uuid_t)); 7448 mSuspendedEffects.add(type->timeLow, desc); 7449 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow); 7450 } 7451 if (desc->mRefCount++ == 0) { 7452 sp<EffectModule> effect = getEffectIfEnabled(type); 7453 if (effect != 0) { 7454 desc->mEffect = effect; 7455 effect->setSuspended(true); 7456 effect->setEnabled(false); 7457 } 7458 } 7459 } else { 7460 if (index < 0) { 7461 return; 7462 } 7463 desc = mSuspendedEffects.valueAt(index); 7464 if (desc->mRefCount <= 0) { 7465 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount); 7466 desc->mRefCount = 1; 7467 } 7468 if (--desc->mRefCount == 0) { 7469 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 7470 if (desc->mEffect != 0) { 7471 sp<EffectModule> effect = desc->mEffect.promote(); 7472 if (effect != 0) { 7473 effect->setSuspended(false); 7474 sp<EffectHandle> handle = effect->controlHandle(); 7475 if (handle != 0) { 7476 effect->setEnabled(handle->enabled()); 7477 } 7478 } 7479 desc->mEffect.clear(); 7480 } 7481 mSuspendedEffects.removeItemsAt(index); 7482 } 7483 } 7484} 7485 7486// must be called with ThreadBase::mLock held 7487void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend) 7488{ 7489 sp<SuspendedEffectDesc> desc; 7490 7491 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 7492 if (suspend) { 7493 if (index >= 0) { 7494 desc = mSuspendedEffects.valueAt(index); 7495 } else { 7496 desc = new SuspendedEffectDesc(); 7497 mSuspendedEffects.add((int)kKeyForSuspendAll, desc); 7498 ALOGV("setEffectSuspendedAll_l() add entry for 0"); 7499 } 7500 if (desc->mRefCount++ == 0) { 7501 Vector< sp<EffectModule> > effects; 7502 getSuspendEligibleEffects(effects); 7503 for (size_t i = 0; i < effects.size(); i++) { 7504 setEffectSuspended_l(&effects[i]->desc().type, true); 7505 } 7506 } 7507 } else { 7508 if (index < 0) { 7509 return; 7510 } 7511 desc = mSuspendedEffects.valueAt(index); 7512 if (desc->mRefCount <= 0) { 7513 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount); 7514 desc->mRefCount = 1; 7515 } 7516 if (--desc->mRefCount == 0) { 7517 Vector<const effect_uuid_t *> types; 7518 for (size_t i = 0; i < mSuspendedEffects.size(); i++) { 7519 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) { 7520 continue; 7521 } 7522 types.add(&mSuspendedEffects.valueAt(i)->mType); 7523 } 7524 for (size_t i = 0; i < types.size(); i++) { 7525 setEffectSuspended_l(types[i], false); 7526 } 7527 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 7528 mSuspendedEffects.removeItem((int)kKeyForSuspendAll); 7529 } 7530 } 7531} 7532 7533 7534// The volume effect is used for automated tests only 7535#ifndef OPENSL_ES_H_ 7536static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6, 7537 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }; 7538const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_; 7539#endif //OPENSL_ES_H_ 7540 7541bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc) 7542{ 7543 // auxiliary effects and visualizer are never suspended on output mix 7544 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && 7545 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) || 7546 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) || 7547 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) { 7548 return false; 7549 } 7550 return true; 7551} 7552 7553void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects) 7554{ 7555 effects.clear(); 7556 for (size_t i = 0; i < mEffects.size(); i++) { 7557 if (isEffectEligibleForSuspend(mEffects[i]->desc())) { 7558 effects.add(mEffects[i]); 7559 } 7560 } 7561} 7562 7563sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled( 7564 const effect_uuid_t *type) 7565{ 7566 sp<EffectModule> effect = getEffectFromType_l(type); 7567 return effect != 0 && effect->isEnabled() ? effect : 0; 7568} 7569 7570void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 7571 bool enabled) 7572{ 7573 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 7574 if (enabled) { 7575 if (index < 0) { 7576 // if the effect is not suspend check if all effects are suspended 7577 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 7578 if (index < 0) { 7579 return; 7580 } 7581 if (!isEffectEligibleForSuspend(effect->desc())) { 7582 return; 7583 } 7584 setEffectSuspended_l(&effect->desc().type, enabled); 7585 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 7586 if (index < 0) { 7587 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!"); 7588 return; 7589 } 7590 } 7591 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x", 7592 effect->desc().type.timeLow); 7593 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 7594 // if effect is requested to suspended but was not yet enabled, supend it now. 7595 if (desc->mEffect == 0) { 7596 desc->mEffect = effect; 7597 effect->setEnabled(false); 7598 effect->setSuspended(true); 7599 } 7600 } else { 7601 if (index < 0) { 7602 return; 7603 } 7604 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x", 7605 effect->desc().type.timeLow); 7606 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 7607 desc->mEffect.clear(); 7608 effect->setSuspended(false); 7609 } 7610} 7611 7612#undef LOG_TAG 7613#define LOG_TAG "AudioFlinger" 7614 7615// ---------------------------------------------------------------------------- 7616 7617status_t AudioFlinger::onTransact( 7618 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 7619{ 7620 return BnAudioFlinger::onTransact(code, data, reply, flags); 7621} 7622 7623}; // namespace android 7624