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