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