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