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