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