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