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