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