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