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