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