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