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