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