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