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