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