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