AudioFlinger.cpp revision 613882293184e575a44bff681a3decaefe889e69
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: %u\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 = 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 size_t frameSize = cblk->frameSize; 3336 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize; 3337 int8_t *bufferEnd = bufferStart + frames * frameSize; 3338 3339 // Check validity of returned pointer in case the track control block would have been corrupted. 3340 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd || 3341 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) { 3342 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \ 3343 server %d, serverBase %d, user %d, userBase %d", 3344 bufferStart, bufferEnd, mBuffer, mBufferEnd, 3345 cblk->server, cblk->serverBase, cblk->user, cblk->userBase); 3346 return 0; 3347 } 3348 3349 return bufferStart; 3350} 3351 3352// ---------------------------------------------------------------------------- 3353 3354// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 3355AudioFlinger::PlaybackThread::Track::Track( 3356 const wp<ThreadBase>& thread, 3357 const sp<Client>& client, 3358 audio_stream_type_t streamType, 3359 uint32_t sampleRate, 3360 uint32_t format, 3361 uint32_t channelMask, 3362 int frameCount, 3363 const sp<IMemory>& sharedBuffer, 3364 int sessionId) 3365 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId), 3366 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), 3367 mAuxEffectId(0), mHasVolumeController(false) 3368{ 3369 if (mCblk != NULL) { 3370 sp<ThreadBase> baseThread = thread.promote(); 3371 if (baseThread != 0) { 3372 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get(); 3373 mName = playbackThread->getTrackName_l(); 3374 mMainBuffer = playbackThread->mixBuffer(); 3375 } 3376 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3377 if (mName < 0) { 3378 ALOGE("no more track names available"); 3379 } 3380 mVolume[0] = 1.0f; 3381 mVolume[1] = 1.0f; 3382 mStreamType = streamType; 3383 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of 3384 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack 3385 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t); 3386 } 3387} 3388 3389AudioFlinger::PlaybackThread::Track::~Track() 3390{ 3391 ALOGV("PlaybackThread::Track destructor"); 3392 sp<ThreadBase> thread = mThread.promote(); 3393 if (thread != 0) { 3394 Mutex::Autolock _l(thread->mLock); 3395 mState = TERMINATED; 3396 } 3397} 3398 3399void AudioFlinger::PlaybackThread::Track::destroy() 3400{ 3401 // NOTE: destroyTrack_l() can remove a strong reference to this Track 3402 // by removing it from mTracks vector, so there is a risk that this Tracks's 3403 // desctructor is called. As the destructor needs to lock mLock, 3404 // we must acquire a strong reference on this Track before locking mLock 3405 // here so that the destructor is called only when exiting this function. 3406 // On the other hand, as long as Track::destroy() is only called by 3407 // TrackHandle destructor, the TrackHandle still holds a strong ref on 3408 // this Track with its member mTrack. 3409 sp<Track> keep(this); 3410 { // scope for mLock 3411 sp<ThreadBase> thread = mThread.promote(); 3412 if (thread != 0) { 3413 if (!isOutputTrack()) { 3414 if (mState == ACTIVE || mState == RESUMING) { 3415 AudioSystem::stopOutput(thread->id(), 3416 (audio_stream_type_t)mStreamType, 3417 mSessionId); 3418 3419 // to track the speaker usage 3420 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3421 } 3422 AudioSystem::releaseOutput(thread->id()); 3423 } 3424 Mutex::Autolock _l(thread->mLock); 3425 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3426 playbackThread->destroyTrack_l(this); 3427 } 3428 } 3429} 3430 3431void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 3432{ 3433 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", 3434 mName - AudioMixer::TRACK0, 3435 (mClient == NULL) ? getpid() : mClient->pid(), 3436 mStreamType, 3437 mFormat, 3438 mChannelMask, 3439 mSessionId, 3440 mFrameCount, 3441 mState, 3442 mMute, 3443 mFillingUpStatus, 3444 mCblk->sampleRate, 3445 mCblk->volume[0], 3446 mCblk->volume[1], 3447 mCblk->server, 3448 mCblk->user, 3449 (int)mMainBuffer, 3450 (int)mAuxBuffer); 3451} 3452 3453status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer) 3454{ 3455 audio_track_cblk_t* cblk = this->cblk(); 3456 uint32_t framesReady; 3457 uint32_t framesReq = buffer->frameCount; 3458 3459 // Check if last stepServer failed, try to step now 3460 if (mFlags & TrackBase::STEPSERVER_FAILED) { 3461 if (!step()) goto getNextBuffer_exit; 3462 ALOGV("stepServer recovered"); 3463 mFlags &= ~TrackBase::STEPSERVER_FAILED; 3464 } 3465 3466 framesReady = cblk->framesReady(); 3467 3468 if (CC_LIKELY(framesReady)) { 3469 uint32_t s = cblk->server; 3470 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 3471 3472 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd; 3473 if (framesReq > framesReady) { 3474 framesReq = framesReady; 3475 } 3476 if (s + framesReq > bufferEnd) { 3477 framesReq = bufferEnd - s; 3478 } 3479 3480 buffer->raw = getBuffer(s, framesReq); 3481 if (buffer->raw == NULL) goto getNextBuffer_exit; 3482 3483 buffer->frameCount = framesReq; 3484 return NO_ERROR; 3485 } 3486 3487getNextBuffer_exit: 3488 buffer->raw = NULL; 3489 buffer->frameCount = 0; 3490 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get()); 3491 return NOT_ENOUGH_DATA; 3492} 3493 3494bool AudioFlinger::PlaybackThread::Track::isReady() const { 3495 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true; 3496 3497 if (mCblk->framesReady() >= mCblk->frameCount || 3498 (mCblk->flags & CBLK_FORCEREADY_MSK)) { 3499 mFillingUpStatus = FS_FILLED; 3500 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 3501 return true; 3502 } 3503 return false; 3504} 3505 3506status_t AudioFlinger::PlaybackThread::Track::start() 3507{ 3508 status_t status = NO_ERROR; 3509 ALOGV("start(%d), calling thread %d session %d", 3510 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 3511 sp<ThreadBase> thread = mThread.promote(); 3512 if (thread != 0) { 3513 Mutex::Autolock _l(thread->mLock); 3514 int state = mState; 3515 // here the track could be either new, or restarted 3516 // in both cases "unstop" the track 3517 if (mState == PAUSED) { 3518 mState = TrackBase::RESUMING; 3519 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 3520 } else { 3521 mState = TrackBase::ACTIVE; 3522 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 3523 } 3524 3525 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) { 3526 thread->mLock.unlock(); 3527 status = AudioSystem::startOutput(thread->id(), 3528 (audio_stream_type_t)mStreamType, 3529 mSessionId); 3530 thread->mLock.lock(); 3531 3532 // to track the speaker usage 3533 if (status == NO_ERROR) { 3534 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 3535 } 3536 } 3537 if (status == NO_ERROR) { 3538 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3539 playbackThread->addTrack_l(this); 3540 } else { 3541 mState = state; 3542 } 3543 } else { 3544 status = BAD_VALUE; 3545 } 3546 return status; 3547} 3548 3549void AudioFlinger::PlaybackThread::Track::stop() 3550{ 3551 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3552 sp<ThreadBase> thread = mThread.promote(); 3553 if (thread != 0) { 3554 Mutex::Autolock _l(thread->mLock); 3555 int state = mState; 3556 if (mState > STOPPED) { 3557 mState = STOPPED; 3558 // If the track is not active (PAUSED and buffers full), flush buffers 3559 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3560 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 3561 reset(); 3562 } 3563 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread); 3564 } 3565 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) { 3566 thread->mLock.unlock(); 3567 AudioSystem::stopOutput(thread->id(), 3568 (audio_stream_type_t)mStreamType, 3569 mSessionId); 3570 thread->mLock.lock(); 3571 3572 // to track the speaker usage 3573 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3574 } 3575 } 3576} 3577 3578void AudioFlinger::PlaybackThread::Track::pause() 3579{ 3580 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3581 sp<ThreadBase> thread = mThread.promote(); 3582 if (thread != 0) { 3583 Mutex::Autolock _l(thread->mLock); 3584 if (mState == ACTIVE || mState == RESUMING) { 3585 mState = PAUSING; 3586 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 3587 if (!isOutputTrack()) { 3588 thread->mLock.unlock(); 3589 AudioSystem::stopOutput(thread->id(), 3590 (audio_stream_type_t)mStreamType, 3591 mSessionId); 3592 thread->mLock.lock(); 3593 3594 // to track the speaker usage 3595 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3596 } 3597 } 3598 } 3599} 3600 3601void AudioFlinger::PlaybackThread::Track::flush() 3602{ 3603 ALOGV("flush(%d)", mName); 3604 sp<ThreadBase> thread = mThread.promote(); 3605 if (thread != 0) { 3606 Mutex::Autolock _l(thread->mLock); 3607 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) { 3608 return; 3609 } 3610 // No point remaining in PAUSED state after a flush => go to 3611 // STOPPED state 3612 mState = STOPPED; 3613 3614 // do not reset the track if it is still in the process of being stopped or paused. 3615 // this will be done by prepareTracks_l() when the track is stopped. 3616 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3617 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 3618 reset(); 3619 } 3620 } 3621} 3622 3623void AudioFlinger::PlaybackThread::Track::reset() 3624{ 3625 // Do not reset twice to avoid discarding data written just after a flush and before 3626 // the audioflinger thread detects the track is stopped. 3627 if (!mResetDone) { 3628 TrackBase::reset(); 3629 // Force underrun condition to avoid false underrun callback until first data is 3630 // written to buffer 3631 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 3632 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 3633 mFillingUpStatus = FS_FILLING; 3634 mResetDone = true; 3635 } 3636} 3637 3638void AudioFlinger::PlaybackThread::Track::mute(bool muted) 3639{ 3640 mMute = muted; 3641} 3642 3643void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right) 3644{ 3645 mVolume[0] = left; 3646 mVolume[1] = right; 3647} 3648 3649status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 3650{ 3651 status_t status = DEAD_OBJECT; 3652 sp<ThreadBase> thread = mThread.promote(); 3653 if (thread != 0) { 3654 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3655 status = playbackThread->attachAuxEffect(this, EffectId); 3656 } 3657 return status; 3658} 3659 3660void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 3661{ 3662 mAuxEffectId = EffectId; 3663 mAuxBuffer = buffer; 3664} 3665 3666// ---------------------------------------------------------------------------- 3667 3668// RecordTrack constructor must be called with AudioFlinger::mLock held 3669AudioFlinger::RecordThread::RecordTrack::RecordTrack( 3670 const wp<ThreadBase>& thread, 3671 const sp<Client>& client, 3672 uint32_t sampleRate, 3673 uint32_t format, 3674 uint32_t channelMask, 3675 int frameCount, 3676 uint32_t flags, 3677 int sessionId) 3678 : TrackBase(thread, client, sampleRate, format, 3679 channelMask, frameCount, flags, 0, sessionId), 3680 mOverflow(false) 3681{ 3682 if (mCblk != NULL) { 3683 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer); 3684 if (format == AUDIO_FORMAT_PCM_16_BIT) { 3685 mCblk->frameSize = mChannelCount * sizeof(int16_t); 3686 } else if (format == AUDIO_FORMAT_PCM_8_BIT) { 3687 mCblk->frameSize = mChannelCount * sizeof(int8_t); 3688 } else { 3689 mCblk->frameSize = sizeof(int8_t); 3690 } 3691 } 3692} 3693 3694AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 3695{ 3696 sp<ThreadBase> thread = mThread.promote(); 3697 if (thread != 0) { 3698 AudioSystem::releaseInput(thread->id()); 3699 } 3700} 3701 3702status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer) 3703{ 3704 audio_track_cblk_t* cblk = this->cblk(); 3705 uint32_t framesAvail; 3706 uint32_t framesReq = buffer->frameCount; 3707 3708 // Check if last stepServer failed, try to step now 3709 if (mFlags & TrackBase::STEPSERVER_FAILED) { 3710 if (!step()) goto getNextBuffer_exit; 3711 ALOGV("stepServer recovered"); 3712 mFlags &= ~TrackBase::STEPSERVER_FAILED; 3713 } 3714 3715 framesAvail = cblk->framesAvailable_l(); 3716 3717 if (CC_LIKELY(framesAvail)) { 3718 uint32_t s = cblk->server; 3719 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 3720 3721 if (framesReq > framesAvail) { 3722 framesReq = framesAvail; 3723 } 3724 if (s + framesReq > bufferEnd) { 3725 framesReq = bufferEnd - s; 3726 } 3727 3728 buffer->raw = getBuffer(s, framesReq); 3729 if (buffer->raw == NULL) goto getNextBuffer_exit; 3730 3731 buffer->frameCount = framesReq; 3732 return NO_ERROR; 3733 } 3734 3735getNextBuffer_exit: 3736 buffer->raw = NULL; 3737 buffer->frameCount = 0; 3738 return NOT_ENOUGH_DATA; 3739} 3740 3741status_t AudioFlinger::RecordThread::RecordTrack::start() 3742{ 3743 sp<ThreadBase> thread = mThread.promote(); 3744 if (thread != 0) { 3745 RecordThread *recordThread = (RecordThread *)thread.get(); 3746 return recordThread->start(this); 3747 } else { 3748 return BAD_VALUE; 3749 } 3750} 3751 3752void AudioFlinger::RecordThread::RecordTrack::stop() 3753{ 3754 sp<ThreadBase> thread = mThread.promote(); 3755 if (thread != 0) { 3756 RecordThread *recordThread = (RecordThread *)thread.get(); 3757 recordThread->stop(this); 3758 TrackBase::reset(); 3759 // Force overerrun condition to avoid false overrun callback until first data is 3760 // read from buffer 3761 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 3762 } 3763} 3764 3765void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 3766{ 3767 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n", 3768 (mClient == NULL) ? getpid() : mClient->pid(), 3769 mFormat, 3770 mChannelMask, 3771 mSessionId, 3772 mFrameCount, 3773 mState, 3774 mCblk->sampleRate, 3775 mCblk->server, 3776 mCblk->user); 3777} 3778 3779 3780// ---------------------------------------------------------------------------- 3781 3782AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 3783 const wp<ThreadBase>& thread, 3784 DuplicatingThread *sourceThread, 3785 uint32_t sampleRate, 3786 uint32_t format, 3787 uint32_t channelMask, 3788 int frameCount) 3789 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0), 3790 mActive(false), mSourceThread(sourceThread) 3791{ 3792 3793 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get(); 3794 if (mCblk != NULL) { 3795 mCblk->flags |= CBLK_DIRECTION_OUT; 3796 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); 3797 mCblk->volume[0] = mCblk->volume[1] = 0x1000; 3798 mOutBuffer.frameCount = 0; 3799 playbackThread->mTracks.add(this); 3800 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \ 3801 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p", 3802 mCblk, mBuffer, mCblk->buffers, 3803 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd); 3804 } else { 3805 ALOGW("Error creating output track on thread %p", playbackThread); 3806 } 3807} 3808 3809AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 3810{ 3811 clearBufferQueue(); 3812} 3813 3814status_t AudioFlinger::PlaybackThread::OutputTrack::start() 3815{ 3816 status_t status = Track::start(); 3817 if (status != NO_ERROR) { 3818 return status; 3819 } 3820 3821 mActive = true; 3822 mRetryCount = 127; 3823 return status; 3824} 3825 3826void AudioFlinger::PlaybackThread::OutputTrack::stop() 3827{ 3828 Track::stop(); 3829 clearBufferQueue(); 3830 mOutBuffer.frameCount = 0; 3831 mActive = false; 3832} 3833 3834bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 3835{ 3836 Buffer *pInBuffer; 3837 Buffer inBuffer; 3838 uint32_t channelCount = mChannelCount; 3839 bool outputBufferFull = false; 3840 inBuffer.frameCount = frames; 3841 inBuffer.i16 = data; 3842 3843 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 3844 3845 if (!mActive && frames != 0) { 3846 start(); 3847 sp<ThreadBase> thread = mThread.promote(); 3848 if (thread != 0) { 3849 MixerThread *mixerThread = (MixerThread *)thread.get(); 3850 if (mCblk->frameCount > frames){ 3851 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 3852 uint32_t startFrames = (mCblk->frameCount - frames); 3853 pInBuffer = new Buffer; 3854 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 3855 pInBuffer->frameCount = startFrames; 3856 pInBuffer->i16 = pInBuffer->mBuffer; 3857 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 3858 mBufferQueue.add(pInBuffer); 3859 } else { 3860 ALOGW ("OutputTrack::write() %p no more buffers in queue", this); 3861 } 3862 } 3863 } 3864 } 3865 3866 while (waitTimeLeftMs) { 3867 // First write pending buffers, then new data 3868 if (mBufferQueue.size()) { 3869 pInBuffer = mBufferQueue.itemAt(0); 3870 } else { 3871 pInBuffer = &inBuffer; 3872 } 3873 3874 if (pInBuffer->frameCount == 0) { 3875 break; 3876 } 3877 3878 if (mOutBuffer.frameCount == 0) { 3879 mOutBuffer.frameCount = pInBuffer->frameCount; 3880 nsecs_t startTime = systemTime(); 3881 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) { 3882 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get()); 3883 outputBufferFull = true; 3884 break; 3885 } 3886 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 3887 if (waitTimeLeftMs >= waitTimeMs) { 3888 waitTimeLeftMs -= waitTimeMs; 3889 } else { 3890 waitTimeLeftMs = 0; 3891 } 3892 } 3893 3894 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount; 3895 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 3896 mCblk->stepUser(outFrames); 3897 pInBuffer->frameCount -= outFrames; 3898 pInBuffer->i16 += outFrames * channelCount; 3899 mOutBuffer.frameCount -= outFrames; 3900 mOutBuffer.i16 += outFrames * channelCount; 3901 3902 if (pInBuffer->frameCount == 0) { 3903 if (mBufferQueue.size()) { 3904 mBufferQueue.removeAt(0); 3905 delete [] pInBuffer->mBuffer; 3906 delete pInBuffer; 3907 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 3908 } else { 3909 break; 3910 } 3911 } 3912 } 3913 3914 // If we could not write all frames, allocate a buffer and queue it for next time. 3915 if (inBuffer.frameCount) { 3916 sp<ThreadBase> thread = mThread.promote(); 3917 if (thread != 0 && !thread->standby()) { 3918 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 3919 pInBuffer = new Buffer; 3920 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 3921 pInBuffer->frameCount = inBuffer.frameCount; 3922 pInBuffer->i16 = pInBuffer->mBuffer; 3923 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t)); 3924 mBufferQueue.add(pInBuffer); 3925 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 3926 } else { 3927 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this); 3928 } 3929 } 3930 } 3931 3932 // Calling write() with a 0 length buffer, means that no more data will be written: 3933 // If no more buffers are pending, fill output track buffer to make sure it is started 3934 // by output mixer. 3935 if (frames == 0 && mBufferQueue.size() == 0) { 3936 if (mCblk->user < mCblk->frameCount) { 3937 frames = mCblk->frameCount - mCblk->user; 3938 pInBuffer = new Buffer; 3939 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 3940 pInBuffer->frameCount = frames; 3941 pInBuffer->i16 = pInBuffer->mBuffer; 3942 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 3943 mBufferQueue.add(pInBuffer); 3944 } else if (mActive) { 3945 stop(); 3946 } 3947 } 3948 3949 return outputBufferFull; 3950} 3951 3952status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 3953{ 3954 int active; 3955 status_t result; 3956 audio_track_cblk_t* cblk = mCblk; 3957 uint32_t framesReq = buffer->frameCount; 3958 3959// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server); 3960 buffer->frameCount = 0; 3961 3962 uint32_t framesAvail = cblk->framesAvailable(); 3963 3964 3965 if (framesAvail == 0) { 3966 Mutex::Autolock _l(cblk->lock); 3967 goto start_loop_here; 3968 while (framesAvail == 0) { 3969 active = mActive; 3970 if (CC_UNLIKELY(!active)) { 3971 ALOGV("Not active and NO_MORE_BUFFERS"); 3972 return AudioTrack::NO_MORE_BUFFERS; 3973 } 3974 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 3975 if (result != NO_ERROR) { 3976 return AudioTrack::NO_MORE_BUFFERS; 3977 } 3978 // read the server count again 3979 start_loop_here: 3980 framesAvail = cblk->framesAvailable_l(); 3981 } 3982 } 3983 3984// if (framesAvail < framesReq) { 3985// return AudioTrack::NO_MORE_BUFFERS; 3986// } 3987 3988 if (framesReq > framesAvail) { 3989 framesReq = framesAvail; 3990 } 3991 3992 uint32_t u = cblk->user; 3993 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 3994 3995 if (u + framesReq > bufferEnd) { 3996 framesReq = bufferEnd - u; 3997 } 3998 3999 buffer->frameCount = framesReq; 4000 buffer->raw = (void *)cblk->buffer(u); 4001 return NO_ERROR; 4002} 4003 4004 4005void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 4006{ 4007 size_t size = mBufferQueue.size(); 4008 Buffer *pBuffer; 4009 4010 for (size_t i = 0; i < size; i++) { 4011 pBuffer = mBufferQueue.itemAt(i); 4012 delete [] pBuffer->mBuffer; 4013 delete pBuffer; 4014 } 4015 mBufferQueue.clear(); 4016} 4017 4018// ---------------------------------------------------------------------------- 4019 4020AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 4021 : RefBase(), 4022 mAudioFlinger(audioFlinger), 4023 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 4024 mPid(pid) 4025{ 4026 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 4027} 4028 4029// Client destructor must be called with AudioFlinger::mLock held 4030AudioFlinger::Client::~Client() 4031{ 4032 mAudioFlinger->removeClient_l(mPid); 4033} 4034 4035const sp<MemoryDealer>& AudioFlinger::Client::heap() const 4036{ 4037 return mMemoryDealer; 4038} 4039 4040// ---------------------------------------------------------------------------- 4041 4042AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 4043 const sp<IAudioFlingerClient>& client, 4044 pid_t pid) 4045 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client) 4046{ 4047} 4048 4049AudioFlinger::NotificationClient::~NotificationClient() 4050{ 4051 mClient.clear(); 4052} 4053 4054void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 4055{ 4056 sp<NotificationClient> keep(this); 4057 { 4058 mAudioFlinger->removeNotificationClient(mPid); 4059 } 4060} 4061 4062// ---------------------------------------------------------------------------- 4063 4064AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 4065 : BnAudioTrack(), 4066 mTrack(track) 4067{ 4068} 4069 4070AudioFlinger::TrackHandle::~TrackHandle() { 4071 // just stop the track on deletion, associated resources 4072 // will be freed from the main thread once all pending buffers have 4073 // been played. Unless it's not in the active track list, in which 4074 // case we free everything now... 4075 mTrack->destroy(); 4076} 4077 4078status_t AudioFlinger::TrackHandle::start() { 4079 return mTrack->start(); 4080} 4081 4082void AudioFlinger::TrackHandle::stop() { 4083 mTrack->stop(); 4084} 4085 4086void AudioFlinger::TrackHandle::flush() { 4087 mTrack->flush(); 4088} 4089 4090void AudioFlinger::TrackHandle::mute(bool e) { 4091 mTrack->mute(e); 4092} 4093 4094void AudioFlinger::TrackHandle::pause() { 4095 mTrack->pause(); 4096} 4097 4098void AudioFlinger::TrackHandle::setVolume(float left, float right) { 4099 mTrack->setVolume(left, right); 4100} 4101 4102sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 4103 return mTrack->getCblk(); 4104} 4105 4106status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 4107{ 4108 return mTrack->attachAuxEffect(EffectId); 4109} 4110 4111status_t AudioFlinger::TrackHandle::onTransact( 4112 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 4113{ 4114 return BnAudioTrack::onTransact(code, data, reply, flags); 4115} 4116 4117// ---------------------------------------------------------------------------- 4118 4119sp<IAudioRecord> AudioFlinger::openRecord( 4120 pid_t pid, 4121 int input, 4122 uint32_t sampleRate, 4123 uint32_t format, 4124 uint32_t channelMask, 4125 int frameCount, 4126 uint32_t flags, 4127 int *sessionId, 4128 status_t *status) 4129{ 4130 sp<RecordThread::RecordTrack> recordTrack; 4131 sp<RecordHandle> recordHandle; 4132 sp<Client> client; 4133 wp<Client> wclient; 4134 status_t lStatus; 4135 RecordThread *thread; 4136 size_t inFrameCount; 4137 int lSessionId; 4138 4139 // check calling permissions 4140 if (!recordingAllowed()) { 4141 lStatus = PERMISSION_DENIED; 4142 goto Exit; 4143 } 4144 4145 // add client to list 4146 { // scope for mLock 4147 Mutex::Autolock _l(mLock); 4148 thread = checkRecordThread_l(input); 4149 if (thread == NULL) { 4150 lStatus = BAD_VALUE; 4151 goto Exit; 4152 } 4153 4154 wclient = mClients.valueFor(pid); 4155 if (wclient != NULL) { 4156 client = wclient.promote(); 4157 } else { 4158 client = new Client(this, pid); 4159 mClients.add(pid, client); 4160 } 4161 4162 // If no audio session id is provided, create one here 4163 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 4164 lSessionId = *sessionId; 4165 } else { 4166 lSessionId = nextUniqueId(); 4167 if (sessionId != NULL) { 4168 *sessionId = lSessionId; 4169 } 4170 } 4171 // create new record track. The record track uses one track in mHardwareMixerThread by convention. 4172 recordTrack = thread->createRecordTrack_l(client, 4173 sampleRate, 4174 format, 4175 channelMask, 4176 frameCount, 4177 flags, 4178 lSessionId, 4179 &lStatus); 4180 } 4181 if (lStatus != NO_ERROR) { 4182 // remove local strong reference to Client before deleting the RecordTrack so that the Client 4183 // destructor is called by the TrackBase destructor with mLock held 4184 client.clear(); 4185 recordTrack.clear(); 4186 goto Exit; 4187 } 4188 4189 // return to handle to client 4190 recordHandle = new RecordHandle(recordTrack); 4191 lStatus = NO_ERROR; 4192 4193Exit: 4194 if (status) { 4195 *status = lStatus; 4196 } 4197 return recordHandle; 4198} 4199 4200// ---------------------------------------------------------------------------- 4201 4202AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 4203 : BnAudioRecord(), 4204 mRecordTrack(recordTrack) 4205{ 4206} 4207 4208AudioFlinger::RecordHandle::~RecordHandle() { 4209 stop(); 4210} 4211 4212status_t AudioFlinger::RecordHandle::start() { 4213 ALOGV("RecordHandle::start()"); 4214 return mRecordTrack->start(); 4215} 4216 4217void AudioFlinger::RecordHandle::stop() { 4218 ALOGV("RecordHandle::stop()"); 4219 mRecordTrack->stop(); 4220} 4221 4222sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 4223 return mRecordTrack->getCblk(); 4224} 4225 4226status_t AudioFlinger::RecordHandle::onTransact( 4227 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 4228{ 4229 return BnAudioRecord::onTransact(code, data, reply, flags); 4230} 4231 4232// ---------------------------------------------------------------------------- 4233 4234AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4235 AudioStreamIn *input, 4236 uint32_t sampleRate, 4237 uint32_t channels, 4238 int id, 4239 uint32_t device) : 4240 ThreadBase(audioFlinger, id, device), 4241 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL) 4242{ 4243 mType = ThreadBase::RECORD; 4244 4245 snprintf(mName, kNameLength, "AudioIn_%d", id); 4246 4247 mReqChannelCount = popcount(channels); 4248 mReqSampleRate = sampleRate; 4249 readInputParameters(); 4250} 4251 4252 4253AudioFlinger::RecordThread::~RecordThread() 4254{ 4255 delete[] mRsmpInBuffer; 4256 if (mResampler != NULL) { 4257 delete mResampler; 4258 delete[] mRsmpOutBuffer; 4259 } 4260} 4261 4262void AudioFlinger::RecordThread::onFirstRef() 4263{ 4264 run(mName, PRIORITY_URGENT_AUDIO); 4265} 4266 4267status_t AudioFlinger::RecordThread::readyToRun() 4268{ 4269 status_t status = initCheck(); 4270 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); 4271 return status; 4272} 4273 4274bool AudioFlinger::RecordThread::threadLoop() 4275{ 4276 AudioBufferProvider::Buffer buffer; 4277 sp<RecordTrack> activeTrack; 4278 Vector< sp<EffectChain> > effectChains; 4279 4280 nsecs_t lastWarning = 0; 4281 4282 acquireWakeLock(); 4283 4284 // start recording 4285 while (!exitPending()) { 4286 4287 processConfigEvents(); 4288 4289 { // scope for mLock 4290 Mutex::Autolock _l(mLock); 4291 checkForNewParameters_l(); 4292 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 4293 if (!mStandby) { 4294 mInput->stream->common.standby(&mInput->stream->common); 4295 mStandby = true; 4296 } 4297 4298 if (exitPending()) break; 4299 4300 releaseWakeLock_l(); 4301 ALOGV("RecordThread: loop stopping"); 4302 // go to sleep 4303 mWaitWorkCV.wait(mLock); 4304 ALOGV("RecordThread: loop starting"); 4305 acquireWakeLock_l(); 4306 continue; 4307 } 4308 if (mActiveTrack != 0) { 4309 if (mActiveTrack->mState == TrackBase::PAUSING) { 4310 if (!mStandby) { 4311 mInput->stream->common.standby(&mInput->stream->common); 4312 mStandby = true; 4313 } 4314 mActiveTrack.clear(); 4315 mStartStopCond.broadcast(); 4316 } else if (mActiveTrack->mState == TrackBase::RESUMING) { 4317 if (mReqChannelCount != mActiveTrack->channelCount()) { 4318 mActiveTrack.clear(); 4319 mStartStopCond.broadcast(); 4320 } else if (mBytesRead != 0) { 4321 // record start succeeds only if first read from audio input 4322 // succeeds 4323 if (mBytesRead > 0) { 4324 mActiveTrack->mState = TrackBase::ACTIVE; 4325 } else { 4326 mActiveTrack.clear(); 4327 } 4328 mStartStopCond.broadcast(); 4329 } 4330 mStandby = false; 4331 } 4332 } 4333 lockEffectChains_l(effectChains); 4334 } 4335 4336 if (mActiveTrack != 0) { 4337 if (mActiveTrack->mState != TrackBase::ACTIVE && 4338 mActiveTrack->mState != TrackBase::RESUMING) { 4339 unlockEffectChains(effectChains); 4340 usleep(kRecordThreadSleepUs); 4341 continue; 4342 } 4343 for (size_t i = 0; i < effectChains.size(); i ++) { 4344 effectChains[i]->process_l(); 4345 } 4346 4347 buffer.frameCount = mFrameCount; 4348 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) { 4349 size_t framesOut = buffer.frameCount; 4350 if (mResampler == NULL) { 4351 // no resampling 4352 while (framesOut) { 4353 size_t framesIn = mFrameCount - mRsmpInIndex; 4354 if (framesIn) { 4355 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4356 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize; 4357 if (framesIn > framesOut) 4358 framesIn = framesOut; 4359 mRsmpInIndex += framesIn; 4360 framesOut -= framesIn; 4361 if ((int)mChannelCount == mReqChannelCount || 4362 mFormat != AUDIO_FORMAT_PCM_16_BIT) { 4363 memcpy(dst, src, framesIn * mFrameSize); 4364 } else { 4365 int16_t *src16 = (int16_t *)src; 4366 int16_t *dst16 = (int16_t *)dst; 4367 if (mChannelCount == 1) { 4368 while (framesIn--) { 4369 *dst16++ = *src16; 4370 *dst16++ = *src16++; 4371 } 4372 } else { 4373 while (framesIn--) { 4374 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1); 4375 src16 += 2; 4376 } 4377 } 4378 } 4379 } 4380 if (framesOut && mFrameCount == mRsmpInIndex) { 4381 if (framesOut == mFrameCount && 4382 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) { 4383 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes); 4384 framesOut = 0; 4385 } else { 4386 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 4387 mRsmpInIndex = 0; 4388 } 4389 if (mBytesRead < 0) { 4390 ALOGE("Error reading audio input"); 4391 if (mActiveTrack->mState == TrackBase::ACTIVE) { 4392 // Force input into standby so that it tries to 4393 // recover at next read attempt 4394 mInput->stream->common.standby(&mInput->stream->common); 4395 usleep(kRecordThreadSleepUs); 4396 } 4397 mRsmpInIndex = mFrameCount; 4398 framesOut = 0; 4399 buffer.frameCount = 0; 4400 } 4401 } 4402 } 4403 } else { 4404 // resampling 4405 4406 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t)); 4407 // alter output frame count as if we were expecting stereo samples 4408 if (mChannelCount == 1 && mReqChannelCount == 1) { 4409 framesOut >>= 1; 4410 } 4411 mResampler->resample(mRsmpOutBuffer, framesOut, this); 4412 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer() 4413 // are 32 bit aligned which should be always true. 4414 if (mChannelCount == 2 && mReqChannelCount == 1) { 4415 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4416 // the resampler always outputs stereo samples: do post stereo to mono conversion 4417 int16_t *src = (int16_t *)mRsmpOutBuffer; 4418 int16_t *dst = buffer.i16; 4419 while (framesOut--) { 4420 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1); 4421 src += 2; 4422 } 4423 } else { 4424 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4425 } 4426 4427 } 4428 mActiveTrack->releaseBuffer(&buffer); 4429 mActiveTrack->overflow(); 4430 } 4431 // client isn't retrieving buffers fast enough 4432 else { 4433 if (!mActiveTrack->setOverflow()) { 4434 nsecs_t now = systemTime(); 4435 if ((now - lastWarning) > kWarningThrottleNs) { 4436 ALOGW("RecordThread: buffer overflow"); 4437 lastWarning = now; 4438 } 4439 } 4440 // Release the processor for a while before asking for a new buffer. 4441 // This will give the application more chance to read from the buffer and 4442 // clear the overflow. 4443 usleep(kRecordThreadSleepUs); 4444 } 4445 } 4446 // enable changes in effect chain 4447 unlockEffectChains(effectChains); 4448 effectChains.clear(); 4449 } 4450 4451 if (!mStandby) { 4452 mInput->stream->common.standby(&mInput->stream->common); 4453 } 4454 mActiveTrack.clear(); 4455 4456 mStartStopCond.broadcast(); 4457 4458 releaseWakeLock(); 4459 4460 ALOGV("RecordThread %p exiting", this); 4461 return false; 4462} 4463 4464 4465sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4466 const sp<AudioFlinger::Client>& client, 4467 uint32_t sampleRate, 4468 int format, 4469 int channelMask, 4470 int frameCount, 4471 uint32_t flags, 4472 int sessionId, 4473 status_t *status) 4474{ 4475 sp<RecordTrack> track; 4476 status_t lStatus; 4477 4478 lStatus = initCheck(); 4479 if (lStatus != NO_ERROR) { 4480 ALOGE("Audio driver not initialized."); 4481 goto Exit; 4482 } 4483 4484 { // scope for mLock 4485 Mutex::Autolock _l(mLock); 4486 4487 track = new RecordTrack(this, client, sampleRate, 4488 format, channelMask, frameCount, flags, sessionId); 4489 4490 if (track->getCblk() == NULL) { 4491 lStatus = NO_MEMORY; 4492 goto Exit; 4493 } 4494 4495 mTrack = track.get(); 4496 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4497 bool suspend = audio_is_bluetooth_sco_device( 4498 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff(); 4499 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4500 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4501 } 4502 lStatus = NO_ERROR; 4503 4504Exit: 4505 if (status) { 4506 *status = lStatus; 4507 } 4508 return track; 4509} 4510 4511status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack) 4512{ 4513 ALOGV("RecordThread::start"); 4514 sp <ThreadBase> strongMe = this; 4515 status_t status = NO_ERROR; 4516 { 4517 AutoMutex lock(mLock); 4518 if (mActiveTrack != 0) { 4519 if (recordTrack != mActiveTrack.get()) { 4520 status = -EBUSY; 4521 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4522 mActiveTrack->mState = TrackBase::ACTIVE; 4523 } 4524 return status; 4525 } 4526 4527 recordTrack->mState = TrackBase::IDLE; 4528 mActiveTrack = recordTrack; 4529 mLock.unlock(); 4530 status_t status = AudioSystem::startInput(mId); 4531 mLock.lock(); 4532 if (status != NO_ERROR) { 4533 mActiveTrack.clear(); 4534 return status; 4535 } 4536 mRsmpInIndex = mFrameCount; 4537 mBytesRead = 0; 4538 if (mResampler != NULL) { 4539 mResampler->reset(); 4540 } 4541 mActiveTrack->mState = TrackBase::RESUMING; 4542 // signal thread to start 4543 ALOGV("Signal record thread"); 4544 mWaitWorkCV.signal(); 4545 // do not wait for mStartStopCond if exiting 4546 if (mExiting) { 4547 mActiveTrack.clear(); 4548 status = INVALID_OPERATION; 4549 goto startError; 4550 } 4551 mStartStopCond.wait(mLock); 4552 if (mActiveTrack == 0) { 4553 ALOGV("Record failed to start"); 4554 status = BAD_VALUE; 4555 goto startError; 4556 } 4557 ALOGV("Record started OK"); 4558 return status; 4559 } 4560startError: 4561 AudioSystem::stopInput(mId); 4562 return status; 4563} 4564 4565void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 4566 ALOGV("RecordThread::stop"); 4567 sp <ThreadBase> strongMe = this; 4568 { 4569 AutoMutex lock(mLock); 4570 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) { 4571 mActiveTrack->mState = TrackBase::PAUSING; 4572 // do not wait for mStartStopCond if exiting 4573 if (mExiting) { 4574 return; 4575 } 4576 mStartStopCond.wait(mLock); 4577 // if we have been restarted, recordTrack == mActiveTrack.get() here 4578 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) { 4579 mLock.unlock(); 4580 AudioSystem::stopInput(mId); 4581 mLock.lock(); 4582 ALOGV("Record stopped OK"); 4583 } 4584 } 4585 } 4586} 4587 4588status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 4589{ 4590 const size_t SIZE = 256; 4591 char buffer[SIZE]; 4592 String8 result; 4593 pid_t pid = 0; 4594 4595 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 4596 result.append(buffer); 4597 4598 if (mActiveTrack != 0) { 4599 result.append("Active Track:\n"); 4600 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n"); 4601 mActiveTrack->dump(buffer, SIZE); 4602 result.append(buffer); 4603 4604 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 4605 result.append(buffer); 4606 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes); 4607 result.append(buffer); 4608 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 4609 result.append(buffer); 4610 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount); 4611 result.append(buffer); 4612 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate); 4613 result.append(buffer); 4614 4615 4616 } else { 4617 result.append("No record client\n"); 4618 } 4619 write(fd, result.string(), result.size()); 4620 4621 dumpBase(fd, args); 4622 dumpEffectChains(fd, args); 4623 4624 return NO_ERROR; 4625} 4626 4627status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer) 4628{ 4629 size_t framesReq = buffer->frameCount; 4630 size_t framesReady = mFrameCount - mRsmpInIndex; 4631 int channelCount; 4632 4633 if (framesReady == 0) { 4634 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 4635 if (mBytesRead < 0) { 4636 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 4637 if (mActiveTrack->mState == TrackBase::ACTIVE) { 4638 // Force input into standby so that it tries to 4639 // recover at next read attempt 4640 mInput->stream->common.standby(&mInput->stream->common); 4641 usleep(kRecordThreadSleepUs); 4642 } 4643 buffer->raw = NULL; 4644 buffer->frameCount = 0; 4645 return NOT_ENOUGH_DATA; 4646 } 4647 mRsmpInIndex = 0; 4648 framesReady = mFrameCount; 4649 } 4650 4651 if (framesReq > framesReady) { 4652 framesReq = framesReady; 4653 } 4654 4655 if (mChannelCount == 1 && mReqChannelCount == 2) { 4656 channelCount = 1; 4657 } else { 4658 channelCount = 2; 4659 } 4660 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 4661 buffer->frameCount = framesReq; 4662 return NO_ERROR; 4663} 4664 4665void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4666{ 4667 mRsmpInIndex += buffer->frameCount; 4668 buffer->frameCount = 0; 4669} 4670 4671bool AudioFlinger::RecordThread::checkForNewParameters_l() 4672{ 4673 bool reconfig = false; 4674 4675 while (!mNewParameters.isEmpty()) { 4676 status_t status = NO_ERROR; 4677 String8 keyValuePair = mNewParameters[0]; 4678 AudioParameter param = AudioParameter(keyValuePair); 4679 int value; 4680 int reqFormat = mFormat; 4681 int reqSamplingRate = mReqSampleRate; 4682 int reqChannelCount = mReqChannelCount; 4683 4684 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4685 reqSamplingRate = value; 4686 reconfig = true; 4687 } 4688 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4689 reqFormat = value; 4690 reconfig = true; 4691 } 4692 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4693 reqChannelCount = popcount(value); 4694 reconfig = true; 4695 } 4696 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4697 // do not accept frame count changes if tracks are open as the track buffer 4698 // size depends on frame count and correct behavior would not be garantied 4699 // if frame count is changed after track creation 4700 if (mActiveTrack != 0) { 4701 status = INVALID_OPERATION; 4702 } else { 4703 reconfig = true; 4704 } 4705 } 4706 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4707 // forward device change to effects that have requested to be 4708 // aware of attached audio device. 4709 for (size_t i = 0; i < mEffectChains.size(); i++) { 4710 mEffectChains[i]->setDevice_l(value); 4711 } 4712 // store input device and output device but do not forward output device to audio HAL. 4713 // Note that status is ignored by the caller for output device 4714 // (see AudioFlinger::setParameters() 4715 if (value & AUDIO_DEVICE_OUT_ALL) { 4716 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL); 4717 status = BAD_VALUE; 4718 } else { 4719 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL); 4720 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4721 if (mTrack != NULL) { 4722 bool suspend = audio_is_bluetooth_sco_device( 4723 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff(); 4724 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId()); 4725 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId()); 4726 } 4727 } 4728 mDevice |= (uint32_t)value; 4729 } 4730 if (status == NO_ERROR) { 4731 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 4732 if (status == INVALID_OPERATION) { 4733 mInput->stream->common.standby(&mInput->stream->common); 4734 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 4735 } 4736 if (reconfig) { 4737 if (status == BAD_VALUE && 4738 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 4739 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 4740 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) && 4741 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) && 4742 (reqChannelCount < 3)) { 4743 status = NO_ERROR; 4744 } 4745 if (status == NO_ERROR) { 4746 readInputParameters(); 4747 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 4748 } 4749 } 4750 } 4751 4752 mNewParameters.removeAt(0); 4753 4754 mParamStatus = status; 4755 mParamCond.signal(); 4756 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 4757 // already timed out waiting for the status and will never signal the condition. 4758 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 4759 } 4760 return reconfig; 4761} 4762 4763String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 4764{ 4765 char *s; 4766 String8 out_s8 = String8(); 4767 4768 Mutex::Autolock _l(mLock); 4769 if (initCheck() != NO_ERROR) { 4770 return out_s8; 4771 } 4772 4773 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 4774 out_s8 = String8(s); 4775 free(s); 4776 return out_s8; 4777} 4778 4779void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 4780 AudioSystem::OutputDescriptor desc; 4781 void *param2 = 0; 4782 4783 switch (event) { 4784 case AudioSystem::INPUT_OPENED: 4785 case AudioSystem::INPUT_CONFIG_CHANGED: 4786 desc.channels = mChannelMask; 4787 desc.samplingRate = mSampleRate; 4788 desc.format = mFormat; 4789 desc.frameCount = mFrameCount; 4790 desc.latency = 0; 4791 param2 = &desc; 4792 break; 4793 4794 case AudioSystem::INPUT_CLOSED: 4795 default: 4796 break; 4797 } 4798 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 4799} 4800 4801void AudioFlinger::RecordThread::readInputParameters() 4802{ 4803 if (mRsmpInBuffer) delete mRsmpInBuffer; 4804 if (mRsmpOutBuffer) delete mRsmpOutBuffer; 4805 if (mResampler) delete mResampler; 4806 mResampler = NULL; 4807 4808 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 4809 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 4810 mChannelCount = (uint16_t)popcount(mChannelMask); 4811 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 4812 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 4813 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common); 4814 mFrameCount = mInputBytes / mFrameSize; 4815 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 4816 4817 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3) 4818 { 4819 int channelCount; 4820 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid 4821 // stereo to mono post process as the resampler always outputs stereo. 4822 if (mChannelCount == 1 && mReqChannelCount == 2) { 4823 channelCount = 1; 4824 } else { 4825 channelCount = 2; 4826 } 4827 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 4828 mResampler->setSampleRate(mSampleRate); 4829 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 4830 mRsmpOutBuffer = new int32_t[mFrameCount * 2]; 4831 4832 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples 4833 if (mChannelCount == 1 && mReqChannelCount == 1) { 4834 mFrameCount >>= 1; 4835 } 4836 4837 } 4838 mRsmpInIndex = mFrameCount; 4839} 4840 4841unsigned int AudioFlinger::RecordThread::getInputFramesLost() 4842{ 4843 Mutex::Autolock _l(mLock); 4844 if (initCheck() != NO_ERROR) { 4845 return 0; 4846 } 4847 4848 return mInput->stream->get_input_frames_lost(mInput->stream); 4849} 4850 4851uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) 4852{ 4853 Mutex::Autolock _l(mLock); 4854 uint32_t result = 0; 4855 if (getEffectChain_l(sessionId) != 0) { 4856 result = EFFECT_SESSION; 4857 } 4858 4859 if (mTrack != NULL && sessionId == mTrack->sessionId()) { 4860 result |= TRACK_SESSION; 4861 } 4862 4863 return result; 4864} 4865 4866AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track() 4867{ 4868 Mutex::Autolock _l(mLock); 4869 return mTrack; 4870} 4871 4872AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() 4873{ 4874 Mutex::Autolock _l(mLock); 4875 return mInput; 4876} 4877 4878AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 4879{ 4880 Mutex::Autolock _l(mLock); 4881 AudioStreamIn *input = mInput; 4882 mInput = NULL; 4883 return input; 4884} 4885 4886// this method must always be called either with ThreadBase mLock held or inside the thread loop 4887audio_stream_t* AudioFlinger::RecordThread::stream() 4888{ 4889 if (mInput == NULL) { 4890 return NULL; 4891 } 4892 return &mInput->stream->common; 4893} 4894 4895 4896// ---------------------------------------------------------------------------- 4897 4898int AudioFlinger::openOutput(uint32_t *pDevices, 4899 uint32_t *pSamplingRate, 4900 uint32_t *pFormat, 4901 uint32_t *pChannels, 4902 uint32_t *pLatencyMs, 4903 uint32_t flags) 4904{ 4905 status_t status; 4906 PlaybackThread *thread = NULL; 4907 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 4908 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0; 4909 uint32_t format = pFormat ? *pFormat : 0; 4910 uint32_t channels = pChannels ? *pChannels : 0; 4911 uint32_t latency = pLatencyMs ? *pLatencyMs : 0; 4912 audio_stream_out_t *outStream; 4913 audio_hw_device_t *outHwDev; 4914 4915 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x", 4916 pDevices ? *pDevices : 0, 4917 samplingRate, 4918 format, 4919 channels, 4920 flags); 4921 4922 if (pDevices == NULL || *pDevices == 0) { 4923 return 0; 4924 } 4925 4926 Mutex::Autolock _l(mLock); 4927 4928 outHwDev = findSuitableHwDev_l(*pDevices); 4929 if (outHwDev == NULL) 4930 return 0; 4931 4932 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format, 4933 &channels, &samplingRate, &outStream); 4934 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d", 4935 outStream, 4936 samplingRate, 4937 format, 4938 channels, 4939 status); 4940 4941 mHardwareStatus = AUDIO_HW_IDLE; 4942 if (outStream != NULL) { 4943 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream); 4944 int id = nextUniqueId(); 4945 4946 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) || 4947 (format != AUDIO_FORMAT_PCM_16_BIT) || 4948 (channels != AUDIO_CHANNEL_OUT_STEREO)) { 4949 thread = new DirectOutputThread(this, output, id, *pDevices); 4950 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 4951 } else { 4952 thread = new MixerThread(this, output, id, *pDevices); 4953 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 4954 } 4955 mPlaybackThreads.add(id, thread); 4956 4957 if (pSamplingRate) *pSamplingRate = samplingRate; 4958 if (pFormat) *pFormat = format; 4959 if (pChannels) *pChannels = channels; 4960 if (pLatencyMs) *pLatencyMs = thread->latency(); 4961 4962 // notify client processes of the new output creation 4963 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 4964 return id; 4965 } 4966 4967 return 0; 4968} 4969 4970int AudioFlinger::openDuplicateOutput(int output1, int output2) 4971{ 4972 Mutex::Autolock _l(mLock); 4973 MixerThread *thread1 = checkMixerThread_l(output1); 4974 MixerThread *thread2 = checkMixerThread_l(output2); 4975 4976 if (thread1 == NULL || thread2 == NULL) { 4977 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2); 4978 return 0; 4979 } 4980 4981 int id = nextUniqueId(); 4982 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 4983 thread->addOutputTrack(thread2); 4984 mPlaybackThreads.add(id, thread); 4985 // notify client processes of the new output creation 4986 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 4987 return id; 4988} 4989 4990status_t AudioFlinger::closeOutput(int output) 4991{ 4992 // keep strong reference on the playback thread so that 4993 // it is not destroyed while exit() is executed 4994 sp <PlaybackThread> thread; 4995 { 4996 Mutex::Autolock _l(mLock); 4997 thread = checkPlaybackThread_l(output); 4998 if (thread == NULL) { 4999 return BAD_VALUE; 5000 } 5001 5002 ALOGV("closeOutput() %d", output); 5003 5004 if (thread->type() == ThreadBase::MIXER) { 5005 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5006 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 5007 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 5008 dupThread->removeOutputTrack((MixerThread *)thread.get()); 5009 } 5010 } 5011 } 5012 void *param2 = 0; 5013 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2); 5014 mPlaybackThreads.removeItem(output); 5015 } 5016 thread->exit(); 5017 5018 if (thread->type() != ThreadBase::DUPLICATING) { 5019 AudioStreamOut *out = thread->clearOutput(); 5020 // from now on thread->mOutput is NULL 5021 out->hwDev->close_output_stream(out->hwDev, out->stream); 5022 delete out; 5023 } 5024 return NO_ERROR; 5025} 5026 5027status_t AudioFlinger::suspendOutput(int output) 5028{ 5029 Mutex::Autolock _l(mLock); 5030 PlaybackThread *thread = checkPlaybackThread_l(output); 5031 5032 if (thread == NULL) { 5033 return BAD_VALUE; 5034 } 5035 5036 ALOGV("suspendOutput() %d", output); 5037 thread->suspend(); 5038 5039 return NO_ERROR; 5040} 5041 5042status_t AudioFlinger::restoreOutput(int output) 5043{ 5044 Mutex::Autolock _l(mLock); 5045 PlaybackThread *thread = checkPlaybackThread_l(output); 5046 5047 if (thread == NULL) { 5048 return BAD_VALUE; 5049 } 5050 5051 ALOGV("restoreOutput() %d", output); 5052 5053 thread->restore(); 5054 5055 return NO_ERROR; 5056} 5057 5058int AudioFlinger::openInput(uint32_t *pDevices, 5059 uint32_t *pSamplingRate, 5060 uint32_t *pFormat, 5061 uint32_t *pChannels, 5062 uint32_t acoustics) 5063{ 5064 status_t status; 5065 RecordThread *thread = NULL; 5066 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0; 5067 uint32_t format = pFormat ? *pFormat : 0; 5068 uint32_t channels = pChannels ? *pChannels : 0; 5069 uint32_t reqSamplingRate = samplingRate; 5070 uint32_t reqFormat = format; 5071 uint32_t reqChannels = channels; 5072 audio_stream_in_t *inStream; 5073 audio_hw_device_t *inHwDev; 5074 5075 if (pDevices == NULL || *pDevices == 0) { 5076 return 0; 5077 } 5078 5079 Mutex::Autolock _l(mLock); 5080 5081 inHwDev = findSuitableHwDev_l(*pDevices); 5082 if (inHwDev == NULL) 5083 return 0; 5084 5085 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format, 5086 &channels, &samplingRate, 5087 (audio_in_acoustics_t)acoustics, 5088 &inStream); 5089 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d", 5090 inStream, 5091 samplingRate, 5092 format, 5093 channels, 5094 acoustics, 5095 status); 5096 5097 // If the input could not be opened with the requested parameters and we can handle the conversion internally, 5098 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo 5099 // or stereo to mono conversions on 16 bit PCM inputs. 5100 if (inStream == NULL && status == BAD_VALUE && 5101 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT && 5102 (samplingRate <= 2 * reqSamplingRate) && 5103 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) { 5104 ALOGV("openInput() reopening with proposed sampling rate and channels"); 5105 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format, 5106 &channels, &samplingRate, 5107 (audio_in_acoustics_t)acoustics, 5108 &inStream); 5109 } 5110 5111 if (inStream != NULL) { 5112 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 5113 5114 int id = nextUniqueId(); 5115 // Start record thread 5116 // RecorThread require both input and output device indication to forward to audio 5117 // pre processing modules 5118 uint32_t device = (*pDevices) | primaryOutputDevice_l(); 5119 thread = new RecordThread(this, 5120 input, 5121 reqSamplingRate, 5122 reqChannels, 5123 id, 5124 device); 5125 mRecordThreads.add(id, thread); 5126 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 5127 if (pSamplingRate) *pSamplingRate = reqSamplingRate; 5128 if (pFormat) *pFormat = format; 5129 if (pChannels) *pChannels = reqChannels; 5130 5131 input->stream->common.standby(&input->stream->common); 5132 5133 // notify client processes of the new input creation 5134 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 5135 return id; 5136 } 5137 5138 return 0; 5139} 5140 5141status_t AudioFlinger::closeInput(int input) 5142{ 5143 // keep strong reference on the record thread so that 5144 // it is not destroyed while exit() is executed 5145 sp <RecordThread> thread; 5146 { 5147 Mutex::Autolock _l(mLock); 5148 thread = checkRecordThread_l(input); 5149 if (thread == NULL) { 5150 return BAD_VALUE; 5151 } 5152 5153 ALOGV("closeInput() %d", input); 5154 void *param2 = 0; 5155 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2); 5156 mRecordThreads.removeItem(input); 5157 } 5158 thread->exit(); 5159 5160 AudioStreamIn *in = thread->clearInput(); 5161 // from now on thread->mInput is NULL 5162 in->hwDev->close_input_stream(in->hwDev, in->stream); 5163 delete in; 5164 5165 return NO_ERROR; 5166} 5167 5168status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output) 5169{ 5170 Mutex::Autolock _l(mLock); 5171 MixerThread *dstThread = checkMixerThread_l(output); 5172 if (dstThread == NULL) { 5173 ALOGW("setStreamOutput() bad output id %d", output); 5174 return BAD_VALUE; 5175 } 5176 5177 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 5178 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream); 5179 5180 dstThread->setStreamValid(stream, true); 5181 5182 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5183 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 5184 if (thread != dstThread && 5185 thread->type() != ThreadBase::DIRECT) { 5186 MixerThread *srcThread = (MixerThread *)thread; 5187 srcThread->setStreamValid(stream, false); 5188 srcThread->invalidateTracks(stream); 5189 } 5190 } 5191 5192 return NO_ERROR; 5193} 5194 5195 5196int AudioFlinger::newAudioSessionId() 5197{ 5198 return nextUniqueId(); 5199} 5200 5201void AudioFlinger::acquireAudioSessionId(int audioSession) 5202{ 5203 Mutex::Autolock _l(mLock); 5204 int caller = IPCThreadState::self()->getCallingPid(); 5205 ALOGV("acquiring %d from %d", audioSession, caller); 5206 int num = mAudioSessionRefs.size(); 5207 for (int i = 0; i< num; i++) { 5208 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 5209 if (ref->sessionid == audioSession && ref->pid == caller) { 5210 ref->cnt++; 5211 ALOGV(" incremented refcount to %d", ref->cnt); 5212 return; 5213 } 5214 } 5215 AudioSessionRef *ref = new AudioSessionRef(); 5216 ref->sessionid = audioSession; 5217 ref->pid = caller; 5218 ref->cnt = 1; 5219 mAudioSessionRefs.push(ref); 5220 ALOGV(" added new entry for %d", ref->sessionid); 5221} 5222 5223void AudioFlinger::releaseAudioSessionId(int audioSession) 5224{ 5225 Mutex::Autolock _l(mLock); 5226 int caller = IPCThreadState::self()->getCallingPid(); 5227 ALOGV("releasing %d from %d", audioSession, caller); 5228 int num = mAudioSessionRefs.size(); 5229 for (int i = 0; i< num; i++) { 5230 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 5231 if (ref->sessionid == audioSession && ref->pid == caller) { 5232 ref->cnt--; 5233 ALOGV(" decremented refcount to %d", ref->cnt); 5234 if (ref->cnt == 0) { 5235 mAudioSessionRefs.removeAt(i); 5236 delete ref; 5237 purgeStaleEffects_l(); 5238 } 5239 return; 5240 } 5241 } 5242 ALOGW("session id %d not found for pid %d", audioSession, caller); 5243} 5244 5245void AudioFlinger::purgeStaleEffects_l() { 5246 5247 ALOGV("purging stale effects"); 5248 5249 Vector< sp<EffectChain> > chains; 5250 5251 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5252 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 5253 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 5254 sp<EffectChain> ec = t->mEffectChains[j]; 5255 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 5256 chains.push(ec); 5257 } 5258 } 5259 } 5260 for (size_t i = 0; i < mRecordThreads.size(); i++) { 5261 sp<RecordThread> t = mRecordThreads.valueAt(i); 5262 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 5263 sp<EffectChain> ec = t->mEffectChains[j]; 5264 chains.push(ec); 5265 } 5266 } 5267 5268 for (size_t i = 0; i < chains.size(); i++) { 5269 sp<EffectChain> ec = chains[i]; 5270 int sessionid = ec->sessionId(); 5271 sp<ThreadBase> t = ec->mThread.promote(); 5272 if (t == 0) { 5273 continue; 5274 } 5275 size_t numsessionrefs = mAudioSessionRefs.size(); 5276 bool found = false; 5277 for (size_t k = 0; k < numsessionrefs; k++) { 5278 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 5279 if (ref->sessionid == sessionid) { 5280 ALOGV(" session %d still exists for %d with %d refs", 5281 sessionid, ref->pid, ref->cnt); 5282 found = true; 5283 break; 5284 } 5285 } 5286 if (!found) { 5287 // remove all effects from the chain 5288 while (ec->mEffects.size()) { 5289 sp<EffectModule> effect = ec->mEffects[0]; 5290 effect->unPin(); 5291 Mutex::Autolock _l (t->mLock); 5292 t->removeEffect_l(effect); 5293 for (size_t j = 0; j < effect->mHandles.size(); j++) { 5294 sp<EffectHandle> handle = effect->mHandles[j].promote(); 5295 if (handle != 0) { 5296 handle->mEffect.clear(); 5297 if (handle->mHasControl && handle->mEnabled) { 5298 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 5299 } 5300 } 5301 } 5302 AudioSystem::unregisterEffect(effect->id()); 5303 } 5304 } 5305 } 5306 return; 5307} 5308 5309// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 5310AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const 5311{ 5312 PlaybackThread *thread = NULL; 5313 if (mPlaybackThreads.indexOfKey(output) >= 0) { 5314 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get(); 5315 } 5316 return thread; 5317} 5318 5319// checkMixerThread_l() must be called with AudioFlinger::mLock held 5320AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const 5321{ 5322 PlaybackThread *thread = checkPlaybackThread_l(output); 5323 if (thread != NULL) { 5324 if (thread->type() == ThreadBase::DIRECT) { 5325 thread = NULL; 5326 } 5327 } 5328 return (MixerThread *)thread; 5329} 5330 5331// checkRecordThread_l() must be called with AudioFlinger::mLock held 5332AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const 5333{ 5334 RecordThread *thread = NULL; 5335 if (mRecordThreads.indexOfKey(input) >= 0) { 5336 thread = (RecordThread *)mRecordThreads.valueFor(input).get(); 5337 } 5338 return thread; 5339} 5340 5341uint32_t AudioFlinger::nextUniqueId() 5342{ 5343 return android_atomic_inc(&mNextUniqueId); 5344} 5345 5346AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() 5347{ 5348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5349 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 5350 AudioStreamOut *output = thread->getOutput(); 5351 if (output != NULL && output->hwDev == mPrimaryHardwareDev) { 5352 return thread; 5353 } 5354 } 5355 return NULL; 5356} 5357 5358uint32_t AudioFlinger::primaryOutputDevice_l() 5359{ 5360 PlaybackThread *thread = primaryPlaybackThread_l(); 5361 5362 if (thread == NULL) { 5363 return 0; 5364 } 5365 5366 return thread->device(); 5367} 5368 5369 5370// ---------------------------------------------------------------------------- 5371// Effect management 5372// ---------------------------------------------------------------------------- 5373 5374 5375status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) 5376{ 5377 Mutex::Autolock _l(mLock); 5378 return EffectQueryNumberEffects(numEffects); 5379} 5380 5381status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) 5382{ 5383 Mutex::Autolock _l(mLock); 5384 return EffectQueryEffect(index, descriptor); 5385} 5386 5387status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor) 5388{ 5389 Mutex::Autolock _l(mLock); 5390 return EffectGetDescriptor(pUuid, descriptor); 5391} 5392 5393 5394sp<IEffect> AudioFlinger::createEffect(pid_t pid, 5395 effect_descriptor_t *pDesc, 5396 const sp<IEffectClient>& effectClient, 5397 int32_t priority, 5398 int io, 5399 int sessionId, 5400 status_t *status, 5401 int *id, 5402 int *enabled) 5403{ 5404 status_t lStatus = NO_ERROR; 5405 sp<EffectHandle> handle; 5406 effect_descriptor_t desc; 5407 sp<Client> client; 5408 wp<Client> wclient; 5409 5410 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d", 5411 pid, effectClient.get(), priority, sessionId, io); 5412 5413 if (pDesc == NULL) { 5414 lStatus = BAD_VALUE; 5415 goto Exit; 5416 } 5417 5418 // check audio settings permission for global effects 5419 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 5420 lStatus = PERMISSION_DENIED; 5421 goto Exit; 5422 } 5423 5424 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 5425 // that can only be created by audio policy manager (running in same process) 5426 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) { 5427 lStatus = PERMISSION_DENIED; 5428 goto Exit; 5429 } 5430 5431 if (io == 0) { 5432 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 5433 // output must be specified by AudioPolicyManager when using session 5434 // AUDIO_SESSION_OUTPUT_STAGE 5435 lStatus = BAD_VALUE; 5436 goto Exit; 5437 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 5438 // if the output returned by getOutputForEffect() is removed before we lock the 5439 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 5440 // and we will exit safely 5441 io = AudioSystem::getOutputForEffect(&desc); 5442 } 5443 } 5444 5445 { 5446 Mutex::Autolock _l(mLock); 5447 5448 5449 if (!EffectIsNullUuid(&pDesc->uuid)) { 5450 // if uuid is specified, request effect descriptor 5451 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 5452 if (lStatus < 0) { 5453 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 5454 goto Exit; 5455 } 5456 } else { 5457 // if uuid is not specified, look for an available implementation 5458 // of the required type in effect factory 5459 if (EffectIsNullUuid(&pDesc->type)) { 5460 ALOGW("createEffect() no effect type"); 5461 lStatus = BAD_VALUE; 5462 goto Exit; 5463 } 5464 uint32_t numEffects = 0; 5465 effect_descriptor_t d; 5466 d.flags = 0; // prevent compiler warning 5467 bool found = false; 5468 5469 lStatus = EffectQueryNumberEffects(&numEffects); 5470 if (lStatus < 0) { 5471 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 5472 goto Exit; 5473 } 5474 for (uint32_t i = 0; i < numEffects; i++) { 5475 lStatus = EffectQueryEffect(i, &desc); 5476 if (lStatus < 0) { 5477 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 5478 continue; 5479 } 5480 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 5481 // If matching type found save effect descriptor. If the session is 5482 // 0 and the effect is not auxiliary, continue enumeration in case 5483 // an auxiliary version of this effect type is available 5484 found = true; 5485 memcpy(&d, &desc, sizeof(effect_descriptor_t)); 5486 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 5487 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5488 break; 5489 } 5490 } 5491 } 5492 if (!found) { 5493 lStatus = BAD_VALUE; 5494 ALOGW("createEffect() effect not found"); 5495 goto Exit; 5496 } 5497 // For same effect type, chose auxiliary version over insert version if 5498 // connect to output mix (Compliance to OpenSL ES) 5499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 5500 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 5501 memcpy(&desc, &d, sizeof(effect_descriptor_t)); 5502 } 5503 } 5504 5505 // Do not allow auxiliary effects on a session different from 0 (output mix) 5506 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 5507 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5508 lStatus = INVALID_OPERATION; 5509 goto Exit; 5510 } 5511 5512 // check recording permission for visualizer 5513 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 5514 !recordingAllowed()) { 5515 lStatus = PERMISSION_DENIED; 5516 goto Exit; 5517 } 5518 5519 // return effect descriptor 5520 memcpy(pDesc, &desc, sizeof(effect_descriptor_t)); 5521 5522 // If output is not specified try to find a matching audio session ID in one of the 5523 // output threads. 5524 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 5525 // because of code checking output when entering the function. 5526 // Note: io is never 0 when creating an effect on an input 5527 if (io == 0) { 5528 // look for the thread where the specified audio session is present 5529 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5530 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 5531 io = mPlaybackThreads.keyAt(i); 5532 break; 5533 } 5534 } 5535 if (io == 0) { 5536 for (size_t i = 0; i < mRecordThreads.size(); i++) { 5537 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 5538 io = mRecordThreads.keyAt(i); 5539 break; 5540 } 5541 } 5542 } 5543 // If no output thread contains the requested session ID, default to 5544 // first output. The effect chain will be moved to the correct output 5545 // thread when a track with the same session ID is created 5546 if (io == 0 && mPlaybackThreads.size()) { 5547 io = mPlaybackThreads.keyAt(0); 5548 } 5549 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 5550 } 5551 ThreadBase *thread = checkRecordThread_l(io); 5552 if (thread == NULL) { 5553 thread = checkPlaybackThread_l(io); 5554 if (thread == NULL) { 5555 ALOGE("createEffect() unknown output thread"); 5556 lStatus = BAD_VALUE; 5557 goto Exit; 5558 } 5559 } 5560 5561 wclient = mClients.valueFor(pid); 5562 5563 if (wclient != NULL) { 5564 client = wclient.promote(); 5565 } else { 5566 client = new Client(this, pid); 5567 mClients.add(pid, client); 5568 } 5569 5570 // create effect on selected output thread 5571 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 5572 &desc, enabled, &lStatus); 5573 if (handle != 0 && id != NULL) { 5574 *id = handle->id(); 5575 } 5576 } 5577 5578Exit: 5579 if(status) { 5580 *status = lStatus; 5581 } 5582 return handle; 5583} 5584 5585status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput) 5586{ 5587 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 5588 sessionId, srcOutput, dstOutput); 5589 Mutex::Autolock _l(mLock); 5590 if (srcOutput == dstOutput) { 5591 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 5592 return NO_ERROR; 5593 } 5594 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 5595 if (srcThread == NULL) { 5596 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 5597 return BAD_VALUE; 5598 } 5599 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 5600 if (dstThread == NULL) { 5601 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 5602 return BAD_VALUE; 5603 } 5604 5605 Mutex::Autolock _dl(dstThread->mLock); 5606 Mutex::Autolock _sl(srcThread->mLock); 5607 moveEffectChain_l(sessionId, srcThread, dstThread, false); 5608 5609 return NO_ERROR; 5610} 5611 5612// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 5613status_t AudioFlinger::moveEffectChain_l(int sessionId, 5614 AudioFlinger::PlaybackThread *srcThread, 5615 AudioFlinger::PlaybackThread *dstThread, 5616 bool reRegister) 5617{ 5618 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 5619 sessionId, srcThread, dstThread); 5620 5621 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 5622 if (chain == 0) { 5623 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 5624 sessionId, srcThread); 5625 return INVALID_OPERATION; 5626 } 5627 5628 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 5629 // so that a new chain is created with correct parameters when first effect is added. This is 5630 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 5631 // removed. 5632 srcThread->removeEffectChain_l(chain); 5633 5634 // transfer all effects one by one so that new effect chain is created on new thread with 5635 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 5636 int dstOutput = dstThread->id(); 5637 sp<EffectChain> dstChain; 5638 uint32_t strategy = 0; // prevent compiler warning 5639 sp<EffectModule> effect = chain->getEffectFromId_l(0); 5640 while (effect != 0) { 5641 srcThread->removeEffect_l(effect); 5642 dstThread->addEffect_l(effect); 5643 // removeEffect_l() has stopped the effect if it was active so it must be restarted 5644 if (effect->state() == EffectModule::ACTIVE || 5645 effect->state() == EffectModule::STOPPING) { 5646 effect->start(); 5647 } 5648 // if the move request is not received from audio policy manager, the effect must be 5649 // re-registered with the new strategy and output 5650 if (dstChain == 0) { 5651 dstChain = effect->chain().promote(); 5652 if (dstChain == 0) { 5653 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 5654 srcThread->addEffect_l(effect); 5655 return NO_INIT; 5656 } 5657 strategy = dstChain->strategy(); 5658 } 5659 if (reRegister) { 5660 AudioSystem::unregisterEffect(effect->id()); 5661 AudioSystem::registerEffect(&effect->desc(), 5662 dstOutput, 5663 strategy, 5664 sessionId, 5665 effect->id()); 5666 } 5667 effect = chain->getEffectFromId_l(0); 5668 } 5669 5670 return NO_ERROR; 5671} 5672 5673 5674// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held 5675sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 5676 const sp<AudioFlinger::Client>& client, 5677 const sp<IEffectClient>& effectClient, 5678 int32_t priority, 5679 int sessionId, 5680 effect_descriptor_t *desc, 5681 int *enabled, 5682 status_t *status 5683 ) 5684{ 5685 sp<EffectModule> effect; 5686 sp<EffectHandle> handle; 5687 status_t lStatus; 5688 sp<EffectChain> chain; 5689 bool chainCreated = false; 5690 bool effectCreated = false; 5691 bool effectRegistered = false; 5692 5693 lStatus = initCheck(); 5694 if (lStatus != NO_ERROR) { 5695 ALOGW("createEffect_l() Audio driver not initialized."); 5696 goto Exit; 5697 } 5698 5699 // Do not allow effects with session ID 0 on direct output or duplicating threads 5700 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format 5701 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { 5702 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", 5703 desc->name, sessionId); 5704 lStatus = BAD_VALUE; 5705 goto Exit; 5706 } 5707 // Only Pre processor effects are allowed on input threads and only on input threads 5708 if ((mType == RECORD && 5709 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) || 5710 (mType != RECORD && 5711 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 5712 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 5713 desc->name, desc->flags, mType); 5714 lStatus = BAD_VALUE; 5715 goto Exit; 5716 } 5717 5718 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 5719 5720 { // scope for mLock 5721 Mutex::Autolock _l(mLock); 5722 5723 // check for existing effect chain with the requested audio session 5724 chain = getEffectChain_l(sessionId); 5725 if (chain == 0) { 5726 // create a new chain for this session 5727 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 5728 chain = new EffectChain(this, sessionId); 5729 addEffectChain_l(chain); 5730 chain->setStrategy(getStrategyForSession_l(sessionId)); 5731 chainCreated = true; 5732 } else { 5733 effect = chain->getEffectFromDesc_l(desc); 5734 } 5735 5736 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get()); 5737 5738 if (effect == 0) { 5739 int id = mAudioFlinger->nextUniqueId(); 5740 // Check CPU and memory usage 5741 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 5742 if (lStatus != NO_ERROR) { 5743 goto Exit; 5744 } 5745 effectRegistered = true; 5746 // create a new effect module if none present in the chain 5747 effect = new EffectModule(this, chain, desc, id, sessionId); 5748 lStatus = effect->status(); 5749 if (lStatus != NO_ERROR) { 5750 goto Exit; 5751 } 5752 lStatus = chain->addEffect_l(effect); 5753 if (lStatus != NO_ERROR) { 5754 goto Exit; 5755 } 5756 effectCreated = true; 5757 5758 effect->setDevice(mDevice); 5759 effect->setMode(mAudioFlinger->getMode()); 5760 } 5761 // create effect handle and connect it to effect module 5762 handle = new EffectHandle(effect, client, effectClient, priority); 5763 lStatus = effect->addHandle(handle); 5764 if (enabled) { 5765 *enabled = (int)effect->isEnabled(); 5766 } 5767 } 5768 5769Exit: 5770 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 5771 Mutex::Autolock _l(mLock); 5772 if (effectCreated) { 5773 chain->removeEffect_l(effect); 5774 } 5775 if (effectRegistered) { 5776 AudioSystem::unregisterEffect(effect->id()); 5777 } 5778 if (chainCreated) { 5779 removeEffectChain_l(chain); 5780 } 5781 handle.clear(); 5782 } 5783 5784 if(status) { 5785 *status = lStatus; 5786 } 5787 return handle; 5788} 5789 5790sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 5791{ 5792 sp<EffectModule> effect; 5793 5794 sp<EffectChain> chain = getEffectChain_l(sessionId); 5795 if (chain != 0) { 5796 effect = chain->getEffectFromId_l(effectId); 5797 } 5798 return effect; 5799} 5800 5801// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 5802// PlaybackThread::mLock held 5803status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 5804{ 5805 // check for existing effect chain with the requested audio session 5806 int sessionId = effect->sessionId(); 5807 sp<EffectChain> chain = getEffectChain_l(sessionId); 5808 bool chainCreated = false; 5809 5810 if (chain == 0) { 5811 // create a new chain for this session 5812 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 5813 chain = new EffectChain(this, sessionId); 5814 addEffectChain_l(chain); 5815 chain->setStrategy(getStrategyForSession_l(sessionId)); 5816 chainCreated = true; 5817 } 5818 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 5819 5820 if (chain->getEffectFromId_l(effect->id()) != 0) { 5821 ALOGW("addEffect_l() %p effect %s already present in chain %p", 5822 this, effect->desc().name, chain.get()); 5823 return BAD_VALUE; 5824 } 5825 5826 status_t status = chain->addEffect_l(effect); 5827 if (status != NO_ERROR) { 5828 if (chainCreated) { 5829 removeEffectChain_l(chain); 5830 } 5831 return status; 5832 } 5833 5834 effect->setDevice(mDevice); 5835 effect->setMode(mAudioFlinger->getMode()); 5836 return NO_ERROR; 5837} 5838 5839void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 5840 5841 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 5842 effect_descriptor_t desc = effect->desc(); 5843 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5844 detachAuxEffect_l(effect->id()); 5845 } 5846 5847 sp<EffectChain> chain = effect->chain().promote(); 5848 if (chain != 0) { 5849 // remove effect chain if removing last effect 5850 if (chain->removeEffect_l(effect) == 0) { 5851 removeEffectChain_l(chain); 5852 } 5853 } else { 5854 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 5855 } 5856} 5857 5858void AudioFlinger::ThreadBase::lockEffectChains_l( 5859 Vector<sp <AudioFlinger::EffectChain> >& effectChains) 5860{ 5861 effectChains = mEffectChains; 5862 for (size_t i = 0; i < mEffectChains.size(); i++) { 5863 mEffectChains[i]->lock(); 5864 } 5865} 5866 5867void AudioFlinger::ThreadBase::unlockEffectChains( 5868 Vector<sp <AudioFlinger::EffectChain> >& effectChains) 5869{ 5870 for (size_t i = 0; i < effectChains.size(); i++) { 5871 effectChains[i]->unlock(); 5872 } 5873} 5874 5875sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 5876{ 5877 Mutex::Autolock _l(mLock); 5878 return getEffectChain_l(sessionId); 5879} 5880 5881sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) 5882{ 5883 sp<EffectChain> chain; 5884 5885 size_t size = mEffectChains.size(); 5886 for (size_t i = 0; i < size; i++) { 5887 if (mEffectChains[i]->sessionId() == sessionId) { 5888 chain = mEffectChains[i]; 5889 break; 5890 } 5891 } 5892 return chain; 5893} 5894 5895void AudioFlinger::ThreadBase::setMode(uint32_t mode) 5896{ 5897 Mutex::Autolock _l(mLock); 5898 size_t size = mEffectChains.size(); 5899 for (size_t i = 0; i < size; i++) { 5900 mEffectChains[i]->setMode_l(mode); 5901 } 5902} 5903 5904void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 5905 const wp<EffectHandle>& handle, 5906 bool unpiniflast) { 5907 5908 Mutex::Autolock _l(mLock); 5909 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 5910 // delete the effect module if removing last handle on it 5911 if (effect->removeHandle(handle) == 0) { 5912 if (!effect->isPinned() || unpiniflast) { 5913 removeEffect_l(effect); 5914 AudioSystem::unregisterEffect(effect->id()); 5915 } 5916 } 5917} 5918 5919status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 5920{ 5921 int session = chain->sessionId(); 5922 int16_t *buffer = mMixBuffer; 5923 bool ownsBuffer = false; 5924 5925 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 5926 if (session > 0) { 5927 // Only one effect chain can be present in direct output thread and it uses 5928 // the mix buffer as input 5929 if (mType != DIRECT) { 5930 size_t numSamples = mFrameCount * mChannelCount; 5931 buffer = new int16_t[numSamples]; 5932 memset(buffer, 0, numSamples * sizeof(int16_t)); 5933 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 5934 ownsBuffer = true; 5935 } 5936 5937 // Attach all tracks with same session ID to this chain. 5938 for (size_t i = 0; i < mTracks.size(); ++i) { 5939 sp<Track> track = mTracks[i]; 5940 if (session == track->sessionId()) { 5941 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer); 5942 track->setMainBuffer(buffer); 5943 chain->incTrackCnt(); 5944 } 5945 } 5946 5947 // indicate all active tracks in the chain 5948 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 5949 sp<Track> track = mActiveTracks[i].promote(); 5950 if (track == 0) continue; 5951 if (session == track->sessionId()) { 5952 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 5953 chain->incActiveTrackCnt(); 5954 } 5955 } 5956 } 5957 5958 chain->setInBuffer(buffer, ownsBuffer); 5959 chain->setOutBuffer(mMixBuffer); 5960 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 5961 // chains list in order to be processed last as it contains output stage effects 5962 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 5963 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 5964 // after track specific effects and before output stage 5965 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 5966 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 5967 // Effect chain for other sessions are inserted at beginning of effect 5968 // chains list to be processed before output mix effects. Relative order between other 5969 // sessions is not important 5970 size_t size = mEffectChains.size(); 5971 size_t i = 0; 5972 for (i = 0; i < size; i++) { 5973 if (mEffectChains[i]->sessionId() < session) break; 5974 } 5975 mEffectChains.insertAt(chain, i); 5976 checkSuspendOnAddEffectChain_l(chain); 5977 5978 return NO_ERROR; 5979} 5980 5981size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 5982{ 5983 int session = chain->sessionId(); 5984 5985 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 5986 5987 for (size_t i = 0; i < mEffectChains.size(); i++) { 5988 if (chain == mEffectChains[i]) { 5989 mEffectChains.removeAt(i); 5990 // detach all active tracks from the chain 5991 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 5992 sp<Track> track = mActiveTracks[i].promote(); 5993 if (track == 0) continue; 5994 if (session == track->sessionId()) { 5995 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 5996 chain.get(), session); 5997 chain->decActiveTrackCnt(); 5998 } 5999 } 6000 6001 // detach all tracks with same session ID from this chain 6002 for (size_t i = 0; i < mTracks.size(); ++i) { 6003 sp<Track> track = mTracks[i]; 6004 if (session == track->sessionId()) { 6005 track->setMainBuffer(mMixBuffer); 6006 chain->decTrackCnt(); 6007 } 6008 } 6009 break; 6010 } 6011 } 6012 return mEffectChains.size(); 6013} 6014 6015status_t AudioFlinger::PlaybackThread::attachAuxEffect( 6016 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 6017{ 6018 Mutex::Autolock _l(mLock); 6019 return attachAuxEffect_l(track, EffectId); 6020} 6021 6022status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 6023 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 6024{ 6025 status_t status = NO_ERROR; 6026 6027 if (EffectId == 0) { 6028 track->setAuxBuffer(0, NULL); 6029 } else { 6030 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 6031 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 6032 if (effect != 0) { 6033 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6034 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 6035 } else { 6036 status = INVALID_OPERATION; 6037 } 6038 } else { 6039 status = BAD_VALUE; 6040 } 6041 } 6042 return status; 6043} 6044 6045void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 6046{ 6047 for (size_t i = 0; i < mTracks.size(); ++i) { 6048 sp<Track> track = mTracks[i]; 6049 if (track->auxEffectId() == effectId) { 6050 attachAuxEffect_l(track, 0); 6051 } 6052 } 6053} 6054 6055status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 6056{ 6057 // only one chain per input thread 6058 if (mEffectChains.size() != 0) { 6059 return INVALID_OPERATION; 6060 } 6061 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 6062 6063 chain->setInBuffer(NULL); 6064 chain->setOutBuffer(NULL); 6065 6066 checkSuspendOnAddEffectChain_l(chain); 6067 6068 mEffectChains.add(chain); 6069 6070 return NO_ERROR; 6071} 6072 6073size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 6074{ 6075 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 6076 ALOGW_IF(mEffectChains.size() != 1, 6077 "removeEffectChain_l() %p invalid chain size %d on thread %p", 6078 chain.get(), mEffectChains.size(), this); 6079 if (mEffectChains.size() == 1) { 6080 mEffectChains.removeAt(0); 6081 } 6082 return 0; 6083} 6084 6085// ---------------------------------------------------------------------------- 6086// EffectModule implementation 6087// ---------------------------------------------------------------------------- 6088 6089#undef LOG_TAG 6090#define LOG_TAG "AudioFlinger::EffectModule" 6091 6092AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread, 6093 const wp<AudioFlinger::EffectChain>& chain, 6094 effect_descriptor_t *desc, 6095 int id, 6096 int sessionId) 6097 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL), 6098 mStatus(NO_INIT), mState(IDLE), mSuspended(false) 6099{ 6100 ALOGV("Constructor %p", this); 6101 int lStatus; 6102 sp<ThreadBase> thread = mThread.promote(); 6103 if (thread == 0) { 6104 return; 6105 } 6106 6107 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t)); 6108 6109 // create effect engine from effect factory 6110 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface); 6111 6112 if (mStatus != NO_ERROR) { 6113 return; 6114 } 6115 lStatus = init(); 6116 if (lStatus < 0) { 6117 mStatus = lStatus; 6118 goto Error; 6119 } 6120 6121 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) { 6122 mPinned = true; 6123 } 6124 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface); 6125 return; 6126Error: 6127 EffectRelease(mEffectInterface); 6128 mEffectInterface = NULL; 6129 ALOGV("Constructor Error %d", mStatus); 6130} 6131 6132AudioFlinger::EffectModule::~EffectModule() 6133{ 6134 ALOGV("Destructor %p", this); 6135 if (mEffectInterface != NULL) { 6136 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6137 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 6138 sp<ThreadBase> thread = mThread.promote(); 6139 if (thread != 0) { 6140 audio_stream_t *stream = thread->stream(); 6141 if (stream != NULL) { 6142 stream->remove_audio_effect(stream, mEffectInterface); 6143 } 6144 } 6145 } 6146 // release effect engine 6147 EffectRelease(mEffectInterface); 6148 } 6149} 6150 6151status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle) 6152{ 6153 status_t status; 6154 6155 Mutex::Autolock _l(mLock); 6156 // First handle in mHandles has highest priority and controls the effect module 6157 int priority = handle->priority(); 6158 size_t size = mHandles.size(); 6159 sp<EffectHandle> h; 6160 size_t i; 6161 for (i = 0; i < size; i++) { 6162 h = mHandles[i].promote(); 6163 if (h == 0) continue; 6164 if (h->priority() <= priority) break; 6165 } 6166 // if inserted in first place, move effect control from previous owner to this handle 6167 if (i == 0) { 6168 bool enabled = false; 6169 if (h != 0) { 6170 enabled = h->enabled(); 6171 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/); 6172 } 6173 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/); 6174 status = NO_ERROR; 6175 } else { 6176 status = ALREADY_EXISTS; 6177 } 6178 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i); 6179 mHandles.insertAt(handle, i); 6180 return status; 6181} 6182 6183size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle) 6184{ 6185 Mutex::Autolock _l(mLock); 6186 size_t size = mHandles.size(); 6187 size_t i; 6188 for (i = 0; i < size; i++) { 6189 if (mHandles[i] == handle) break; 6190 } 6191 if (i == size) { 6192 return size; 6193 } 6194 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i); 6195 6196 bool enabled = false; 6197 EffectHandle *hdl = handle.unsafe_get(); 6198 if (hdl) { 6199 ALOGV("removeHandle() unsafe_get OK"); 6200 enabled = hdl->enabled(); 6201 } 6202 mHandles.removeAt(i); 6203 size = mHandles.size(); 6204 // if removed from first place, move effect control from this handle to next in line 6205 if (i == 0 && size != 0) { 6206 sp<EffectHandle> h = mHandles[0].promote(); 6207 if (h != 0) { 6208 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/); 6209 } 6210 } 6211 6212 // Prevent calls to process() and other functions on effect interface from now on. 6213 // The effect engine will be released by the destructor when the last strong reference on 6214 // this object is released which can happen after next process is called. 6215 if (size == 0 && !mPinned) { 6216 mState = DESTROYED; 6217 } 6218 6219 return size; 6220} 6221 6222sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle() 6223{ 6224 Mutex::Autolock _l(mLock); 6225 sp<EffectHandle> handle; 6226 if (mHandles.size() != 0) { 6227 handle = mHandles[0].promote(); 6228 } 6229 return handle; 6230} 6231 6232void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast) 6233{ 6234 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get()); 6235 // keep a strong reference on this EffectModule to avoid calling the 6236 // destructor before we exit 6237 sp<EffectModule> keep(this); 6238 { 6239 sp<ThreadBase> thread = mThread.promote(); 6240 if (thread != 0) { 6241 thread->disconnectEffect(keep, handle, unpiniflast); 6242 } 6243 } 6244} 6245 6246void AudioFlinger::EffectModule::updateState() { 6247 Mutex::Autolock _l(mLock); 6248 6249 switch (mState) { 6250 case RESTART: 6251 reset_l(); 6252 // FALL THROUGH 6253 6254 case STARTING: 6255 // clear auxiliary effect input buffer for next accumulation 6256 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6257 memset(mConfig.inputCfg.buffer.raw, 6258 0, 6259 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 6260 } 6261 start_l(); 6262 mState = ACTIVE; 6263 break; 6264 case STOPPING: 6265 stop_l(); 6266 mDisableWaitCnt = mMaxDisableWaitCnt; 6267 mState = STOPPED; 6268 break; 6269 case STOPPED: 6270 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the 6271 // turn off sequence. 6272 if (--mDisableWaitCnt == 0) { 6273 reset_l(); 6274 mState = IDLE; 6275 } 6276 break; 6277 default: //IDLE , ACTIVE, DESTROYED 6278 break; 6279 } 6280} 6281 6282void AudioFlinger::EffectModule::process() 6283{ 6284 Mutex::Autolock _l(mLock); 6285 6286 if (mState == DESTROYED || mEffectInterface == NULL || 6287 mConfig.inputCfg.buffer.raw == NULL || 6288 mConfig.outputCfg.buffer.raw == NULL) { 6289 return; 6290 } 6291 6292 if (isProcessEnabled()) { 6293 // do 32 bit to 16 bit conversion for auxiliary effect input buffer 6294 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6295 ditherAndClamp(mConfig.inputCfg.buffer.s32, 6296 mConfig.inputCfg.buffer.s32, 6297 mConfig.inputCfg.buffer.frameCount/2); 6298 } 6299 6300 // do the actual processing in the effect engine 6301 int ret = (*mEffectInterface)->process(mEffectInterface, 6302 &mConfig.inputCfg.buffer, 6303 &mConfig.outputCfg.buffer); 6304 6305 // force transition to IDLE state when engine is ready 6306 if (mState == STOPPED && ret == -ENODATA) { 6307 mDisableWaitCnt = 1; 6308 } 6309 6310 // clear auxiliary effect input buffer for next accumulation 6311 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6312 memset(mConfig.inputCfg.buffer.raw, 0, 6313 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 6314 } 6315 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT && 6316 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 6317 // If an insert effect is idle and input buffer is different from output buffer, 6318 // accumulate input onto output 6319 sp<EffectChain> chain = mChain.promote(); 6320 if (chain != 0 && chain->activeTrackCnt() != 0) { 6321 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here 6322 int16_t *in = mConfig.inputCfg.buffer.s16; 6323 int16_t *out = mConfig.outputCfg.buffer.s16; 6324 for (size_t i = 0; i < frameCnt; i++) { 6325 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]); 6326 } 6327 } 6328 } 6329} 6330 6331void AudioFlinger::EffectModule::reset_l() 6332{ 6333 if (mEffectInterface == NULL) { 6334 return; 6335 } 6336 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL); 6337} 6338 6339status_t AudioFlinger::EffectModule::configure() 6340{ 6341 uint32_t channels; 6342 if (mEffectInterface == NULL) { 6343 return NO_INIT; 6344 } 6345 6346 sp<ThreadBase> thread = mThread.promote(); 6347 if (thread == 0) { 6348 return DEAD_OBJECT; 6349 } 6350 6351 // TODO: handle configuration of effects replacing track process 6352 if (thread->channelCount() == 1) { 6353 channels = AUDIO_CHANNEL_OUT_MONO; 6354 } else { 6355 channels = AUDIO_CHANNEL_OUT_STEREO; 6356 } 6357 6358 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6359 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; 6360 } else { 6361 mConfig.inputCfg.channels = channels; 6362 } 6363 mConfig.outputCfg.channels = channels; 6364 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 6365 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 6366 mConfig.inputCfg.samplingRate = thread->sampleRate(); 6367 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; 6368 mConfig.inputCfg.bufferProvider.cookie = NULL; 6369 mConfig.inputCfg.bufferProvider.getBuffer = NULL; 6370 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; 6371 mConfig.outputCfg.bufferProvider.cookie = NULL; 6372 mConfig.outputCfg.bufferProvider.getBuffer = NULL; 6373 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; 6374 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; 6375 // Insert effect: 6376 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE, 6377 // always overwrites output buffer: input buffer == output buffer 6378 // - in other sessions: 6379 // last effect in the chain accumulates in output buffer: input buffer != output buffer 6380 // other effect: overwrites output buffer: input buffer == output buffer 6381 // Auxiliary effect: 6382 // accumulates in output buffer: input buffer != output buffer 6383 // Therefore: accumulate <=> input buffer != output buffer 6384 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 6385 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; 6386 } else { 6387 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; 6388 } 6389 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; 6390 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; 6391 mConfig.inputCfg.buffer.frameCount = thread->frameCount(); 6392 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; 6393 6394 ALOGV("configure() %p thread %p buffer %p framecount %d", 6395 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); 6396 6397 status_t cmdStatus; 6398 uint32_t size = sizeof(int); 6399 status_t status = (*mEffectInterface)->command(mEffectInterface, 6400 EFFECT_CMD_SET_CONFIG, 6401 sizeof(effect_config_t), 6402 &mConfig, 6403 &size, 6404 &cmdStatus); 6405 if (status == 0) { 6406 status = cmdStatus; 6407 } 6408 6409 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / 6410 (1000 * mConfig.outputCfg.buffer.frameCount); 6411 6412 return status; 6413} 6414 6415status_t AudioFlinger::EffectModule::init() 6416{ 6417 Mutex::Autolock _l(mLock); 6418 if (mEffectInterface == NULL) { 6419 return NO_INIT; 6420 } 6421 status_t cmdStatus; 6422 uint32_t size = sizeof(status_t); 6423 status_t status = (*mEffectInterface)->command(mEffectInterface, 6424 EFFECT_CMD_INIT, 6425 0, 6426 NULL, 6427 &size, 6428 &cmdStatus); 6429 if (status == 0) { 6430 status = cmdStatus; 6431 } 6432 return status; 6433} 6434 6435status_t AudioFlinger::EffectModule::start() 6436{ 6437 Mutex::Autolock _l(mLock); 6438 return start_l(); 6439} 6440 6441status_t AudioFlinger::EffectModule::start_l() 6442{ 6443 if (mEffectInterface == NULL) { 6444 return NO_INIT; 6445 } 6446 status_t cmdStatus; 6447 uint32_t size = sizeof(status_t); 6448 status_t status = (*mEffectInterface)->command(mEffectInterface, 6449 EFFECT_CMD_ENABLE, 6450 0, 6451 NULL, 6452 &size, 6453 &cmdStatus); 6454 if (status == 0) { 6455 status = cmdStatus; 6456 } 6457 if (status == 0 && 6458 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6459 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 6460 sp<ThreadBase> thread = mThread.promote(); 6461 if (thread != 0) { 6462 audio_stream_t *stream = thread->stream(); 6463 if (stream != NULL) { 6464 stream->add_audio_effect(stream, mEffectInterface); 6465 } 6466 } 6467 } 6468 return status; 6469} 6470 6471status_t AudioFlinger::EffectModule::stop() 6472{ 6473 Mutex::Autolock _l(mLock); 6474 return stop_l(); 6475} 6476 6477status_t AudioFlinger::EffectModule::stop_l() 6478{ 6479 if (mEffectInterface == NULL) { 6480 return NO_INIT; 6481 } 6482 status_t cmdStatus; 6483 uint32_t size = sizeof(status_t); 6484 status_t status = (*mEffectInterface)->command(mEffectInterface, 6485 EFFECT_CMD_DISABLE, 6486 0, 6487 NULL, 6488 &size, 6489 &cmdStatus); 6490 if (status == 0) { 6491 status = cmdStatus; 6492 } 6493 if (status == 0 && 6494 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6495 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 6496 sp<ThreadBase> thread = mThread.promote(); 6497 if (thread != 0) { 6498 audio_stream_t *stream = thread->stream(); 6499 if (stream != NULL) { 6500 stream->remove_audio_effect(stream, mEffectInterface); 6501 } 6502 } 6503 } 6504 return status; 6505} 6506 6507status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, 6508 uint32_t cmdSize, 6509 void *pCmdData, 6510 uint32_t *replySize, 6511 void *pReplyData) 6512{ 6513 Mutex::Autolock _l(mLock); 6514// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); 6515 6516 if (mState == DESTROYED || mEffectInterface == NULL) { 6517 return NO_INIT; 6518 } 6519 status_t status = (*mEffectInterface)->command(mEffectInterface, 6520 cmdCode, 6521 cmdSize, 6522 pCmdData, 6523 replySize, 6524 pReplyData); 6525 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { 6526 uint32_t size = (replySize == NULL) ? 0 : *replySize; 6527 for (size_t i = 1; i < mHandles.size(); i++) { 6528 sp<EffectHandle> h = mHandles[i].promote(); 6529 if (h != 0) { 6530 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); 6531 } 6532 } 6533 } 6534 return status; 6535} 6536 6537status_t AudioFlinger::EffectModule::setEnabled(bool enabled) 6538{ 6539 6540 Mutex::Autolock _l(mLock); 6541 ALOGV("setEnabled %p enabled %d", this, enabled); 6542 6543 if (enabled != isEnabled()) { 6544 status_t status = AudioSystem::setEffectEnabled(mId, enabled); 6545 if (enabled && status != NO_ERROR) { 6546 return status; 6547 } 6548 6549 switch (mState) { 6550 // going from disabled to enabled 6551 case IDLE: 6552 mState = STARTING; 6553 break; 6554 case STOPPED: 6555 mState = RESTART; 6556 break; 6557 case STOPPING: 6558 mState = ACTIVE; 6559 break; 6560 6561 // going from enabled to disabled 6562 case RESTART: 6563 mState = STOPPED; 6564 break; 6565 case STARTING: 6566 mState = IDLE; 6567 break; 6568 case ACTIVE: 6569 mState = STOPPING; 6570 break; 6571 case DESTROYED: 6572 return NO_ERROR; // simply ignore as we are being destroyed 6573 } 6574 for (size_t i = 1; i < mHandles.size(); i++) { 6575 sp<EffectHandle> h = mHandles[i].promote(); 6576 if (h != 0) { 6577 h->setEnabled(enabled); 6578 } 6579 } 6580 } 6581 return NO_ERROR; 6582} 6583 6584bool AudioFlinger::EffectModule::isEnabled() 6585{ 6586 switch (mState) { 6587 case RESTART: 6588 case STARTING: 6589 case ACTIVE: 6590 return true; 6591 case IDLE: 6592 case STOPPING: 6593 case STOPPED: 6594 case DESTROYED: 6595 default: 6596 return false; 6597 } 6598} 6599 6600bool AudioFlinger::EffectModule::isProcessEnabled() 6601{ 6602 switch (mState) { 6603 case RESTART: 6604 case ACTIVE: 6605 case STOPPING: 6606 case STOPPED: 6607 return true; 6608 case IDLE: 6609 case STARTING: 6610 case DESTROYED: 6611 default: 6612 return false; 6613 } 6614} 6615 6616status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller) 6617{ 6618 Mutex::Autolock _l(mLock); 6619 status_t status = NO_ERROR; 6620 6621 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume 6622 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set) 6623 if (isProcessEnabled() && 6624 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL || 6625 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) { 6626 status_t cmdStatus; 6627 uint32_t volume[2]; 6628 uint32_t *pVolume = NULL; 6629 uint32_t size = sizeof(volume); 6630 volume[0] = *left; 6631 volume[1] = *right; 6632 if (controller) { 6633 pVolume = volume; 6634 } 6635 status = (*mEffectInterface)->command(mEffectInterface, 6636 EFFECT_CMD_SET_VOLUME, 6637 size, 6638 volume, 6639 &size, 6640 pVolume); 6641 if (controller && status == NO_ERROR && size == sizeof(volume)) { 6642 *left = volume[0]; 6643 *right = volume[1]; 6644 } 6645 } 6646 return status; 6647} 6648 6649status_t AudioFlinger::EffectModule::setDevice(uint32_t device) 6650{ 6651 Mutex::Autolock _l(mLock); 6652 status_t status = NO_ERROR; 6653 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) { 6654 // audio pre processing modules on RecordThread can receive both output and 6655 // input device indication in the same call 6656 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL; 6657 if (dev) { 6658 status_t cmdStatus; 6659 uint32_t size = sizeof(status_t); 6660 6661 status = (*mEffectInterface)->command(mEffectInterface, 6662 EFFECT_CMD_SET_DEVICE, 6663 sizeof(uint32_t), 6664 &dev, 6665 &size, 6666 &cmdStatus); 6667 if (status == NO_ERROR) { 6668 status = cmdStatus; 6669 } 6670 } 6671 dev = device & AUDIO_DEVICE_IN_ALL; 6672 if (dev) { 6673 status_t cmdStatus; 6674 uint32_t size = sizeof(status_t); 6675 6676 status_t status2 = (*mEffectInterface)->command(mEffectInterface, 6677 EFFECT_CMD_SET_INPUT_DEVICE, 6678 sizeof(uint32_t), 6679 &dev, 6680 &size, 6681 &cmdStatus); 6682 if (status2 == NO_ERROR) { 6683 status2 = cmdStatus; 6684 } 6685 if (status == NO_ERROR) { 6686 status = status2; 6687 } 6688 } 6689 } 6690 return status; 6691} 6692 6693status_t AudioFlinger::EffectModule::setMode(uint32_t mode) 6694{ 6695 Mutex::Autolock _l(mLock); 6696 status_t status = NO_ERROR; 6697 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) { 6698 status_t cmdStatus; 6699 uint32_t size = sizeof(status_t); 6700 status = (*mEffectInterface)->command(mEffectInterface, 6701 EFFECT_CMD_SET_AUDIO_MODE, 6702 sizeof(int), 6703 &mode, 6704 &size, 6705 &cmdStatus); 6706 if (status == NO_ERROR) { 6707 status = cmdStatus; 6708 } 6709 } 6710 return status; 6711} 6712 6713void AudioFlinger::EffectModule::setSuspended(bool suspended) 6714{ 6715 Mutex::Autolock _l(mLock); 6716 mSuspended = suspended; 6717} 6718 6719bool AudioFlinger::EffectModule::suspended() const 6720{ 6721 Mutex::Autolock _l(mLock); 6722 return mSuspended; 6723} 6724 6725status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args) 6726{ 6727 const size_t SIZE = 256; 6728 char buffer[SIZE]; 6729 String8 result; 6730 6731 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId); 6732 result.append(buffer); 6733 6734 bool locked = tryLock(mLock); 6735 // failed to lock - AudioFlinger is probably deadlocked 6736 if (!locked) { 6737 result.append("\t\tCould not lock Fx mutex:\n"); 6738 } 6739 6740 result.append("\t\tSession Status State Engine:\n"); 6741 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n", 6742 mSessionId, mStatus, mState, (uint32_t)mEffectInterface); 6743 result.append(buffer); 6744 6745 result.append("\t\tDescriptor:\n"); 6746 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 6747 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, 6748 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2], 6749 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); 6750 result.append(buffer); 6751 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 6752 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion, 6753 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2], 6754 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); 6755 result.append(buffer); 6756 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n", 6757 mDescriptor.apiVersion, 6758 mDescriptor.flags); 6759 result.append(buffer); 6760 snprintf(buffer, SIZE, "\t\t- name: %s\n", 6761 mDescriptor.name); 6762 result.append(buffer); 6763 snprintf(buffer, SIZE, "\t\t- implementor: %s\n", 6764 mDescriptor.implementor); 6765 result.append(buffer); 6766 6767 result.append("\t\t- Input configuration:\n"); 6768 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 6769 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 6770 (uint32_t)mConfig.inputCfg.buffer.raw, 6771 mConfig.inputCfg.buffer.frameCount, 6772 mConfig.inputCfg.samplingRate, 6773 mConfig.inputCfg.channels, 6774 mConfig.inputCfg.format); 6775 result.append(buffer); 6776 6777 result.append("\t\t- Output configuration:\n"); 6778 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 6779 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 6780 (uint32_t)mConfig.outputCfg.buffer.raw, 6781 mConfig.outputCfg.buffer.frameCount, 6782 mConfig.outputCfg.samplingRate, 6783 mConfig.outputCfg.channels, 6784 mConfig.outputCfg.format); 6785 result.append(buffer); 6786 6787 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size()); 6788 result.append(buffer); 6789 result.append("\t\t\tPid Priority Ctrl Locked client server\n"); 6790 for (size_t i = 0; i < mHandles.size(); ++i) { 6791 sp<EffectHandle> handle = mHandles[i].promote(); 6792 if (handle != 0) { 6793 handle->dump(buffer, SIZE); 6794 result.append(buffer); 6795 } 6796 } 6797 6798 result.append("\n"); 6799 6800 write(fd, result.string(), result.length()); 6801 6802 if (locked) { 6803 mLock.unlock(); 6804 } 6805 6806 return NO_ERROR; 6807} 6808 6809// ---------------------------------------------------------------------------- 6810// EffectHandle implementation 6811// ---------------------------------------------------------------------------- 6812 6813#undef LOG_TAG 6814#define LOG_TAG "AudioFlinger::EffectHandle" 6815 6816AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect, 6817 const sp<AudioFlinger::Client>& client, 6818 const sp<IEffectClient>& effectClient, 6819 int32_t priority) 6820 : BnEffect(), 6821 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL), 6822 mPriority(priority), mHasControl(false), mEnabled(false) 6823{ 6824 ALOGV("constructor %p", this); 6825 6826 if (client == 0) { 6827 return; 6828 } 6829 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int); 6830 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset); 6831 if (mCblkMemory != 0) { 6832 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer()); 6833 6834 if (mCblk) { 6835 new(mCblk) effect_param_cblk_t(); 6836 mBuffer = (uint8_t *)mCblk + bufOffset; 6837 } 6838 } else { 6839 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t)); 6840 return; 6841 } 6842} 6843 6844AudioFlinger::EffectHandle::~EffectHandle() 6845{ 6846 ALOGV("Destructor %p", this); 6847 disconnect(false); 6848 ALOGV("Destructor DONE %p", this); 6849} 6850 6851status_t AudioFlinger::EffectHandle::enable() 6852{ 6853 ALOGV("enable %p", this); 6854 if (!mHasControl) return INVALID_OPERATION; 6855 if (mEffect == 0) return DEAD_OBJECT; 6856 6857 if (mEnabled) { 6858 return NO_ERROR; 6859 } 6860 6861 mEnabled = true; 6862 6863 sp<ThreadBase> thread = mEffect->thread().promote(); 6864 if (thread != 0) { 6865 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId()); 6866 } 6867 6868 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled 6869 if (mEffect->suspended()) { 6870 return NO_ERROR; 6871 } 6872 6873 status_t status = mEffect->setEnabled(true); 6874 if (status != NO_ERROR) { 6875 if (thread != 0) { 6876 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6877 } 6878 mEnabled = false; 6879 } 6880 return status; 6881} 6882 6883status_t AudioFlinger::EffectHandle::disable() 6884{ 6885 ALOGV("disable %p", this); 6886 if (!mHasControl) return INVALID_OPERATION; 6887 if (mEffect == 0) return DEAD_OBJECT; 6888 6889 if (!mEnabled) { 6890 return NO_ERROR; 6891 } 6892 mEnabled = false; 6893 6894 if (mEffect->suspended()) { 6895 return NO_ERROR; 6896 } 6897 6898 status_t status = mEffect->setEnabled(false); 6899 6900 sp<ThreadBase> thread = mEffect->thread().promote(); 6901 if (thread != 0) { 6902 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6903 } 6904 6905 return status; 6906} 6907 6908void AudioFlinger::EffectHandle::disconnect() 6909{ 6910 disconnect(true); 6911} 6912 6913void AudioFlinger::EffectHandle::disconnect(bool unpiniflast) 6914{ 6915 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false"); 6916 if (mEffect == 0) { 6917 return; 6918 } 6919 mEffect->disconnect(this, unpiniflast); 6920 6921 if (mHasControl && mEnabled) { 6922 sp<ThreadBase> thread = mEffect->thread().promote(); 6923 if (thread != 0) { 6924 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6925 } 6926 } 6927 6928 // release sp on module => module destructor can be called now 6929 mEffect.clear(); 6930 if (mClient != 0) { 6931 if (mCblk) { 6932 mCblk->~effect_param_cblk_t(); // destroy our shared-structure. 6933 } 6934 mCblkMemory.clear(); // and free the shared memory 6935 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 6936 mClient.clear(); 6937 } 6938} 6939 6940status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode, 6941 uint32_t cmdSize, 6942 void *pCmdData, 6943 uint32_t *replySize, 6944 void *pReplyData) 6945{ 6946// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", 6947// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get()); 6948 6949 // only get parameter command is permitted for applications not controlling the effect 6950 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) { 6951 return INVALID_OPERATION; 6952 } 6953 if (mEffect == 0) return DEAD_OBJECT; 6954 if (mClient == 0) return INVALID_OPERATION; 6955 6956 // handle commands that are not forwarded transparently to effect engine 6957 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) { 6958 // No need to trylock() here as this function is executed in the binder thread serving a particular client process: 6959 // no risk to block the whole media server process or mixer threads is we are stuck here 6960 Mutex::Autolock _l(mCblk->lock); 6961 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE || 6962 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) { 6963 mCblk->serverIndex = 0; 6964 mCblk->clientIndex = 0; 6965 return BAD_VALUE; 6966 } 6967 status_t status = NO_ERROR; 6968 while (mCblk->serverIndex < mCblk->clientIndex) { 6969 int reply; 6970 uint32_t rsize = sizeof(int); 6971 int *p = (int *)(mBuffer + mCblk->serverIndex); 6972 int size = *p++; 6973 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) { 6974 ALOGW("command(): invalid parameter block size"); 6975 break; 6976 } 6977 effect_param_t *param = (effect_param_t *)p; 6978 if (param->psize == 0 || param->vsize == 0) { 6979 ALOGW("command(): null parameter or value size"); 6980 mCblk->serverIndex += size; 6981 continue; 6982 } 6983 uint32_t psize = sizeof(effect_param_t) + 6984 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + 6985 param->vsize; 6986 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, 6987 psize, 6988 p, 6989 &rsize, 6990 &reply); 6991 // stop at first error encountered 6992 if (ret != NO_ERROR) { 6993 status = ret; 6994 *(int *)pReplyData = reply; 6995 break; 6996 } else if (reply != NO_ERROR) { 6997 *(int *)pReplyData = reply; 6998 break; 6999 } 7000 mCblk->serverIndex += size; 7001 } 7002 mCblk->serverIndex = 0; 7003 mCblk->clientIndex = 0; 7004 return status; 7005 } else if (cmdCode == EFFECT_CMD_ENABLE) { 7006 *(int *)pReplyData = NO_ERROR; 7007 return enable(); 7008 } else if (cmdCode == EFFECT_CMD_DISABLE) { 7009 *(int *)pReplyData = NO_ERROR; 7010 return disable(); 7011 } 7012 7013 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 7014} 7015 7016sp<IMemory> AudioFlinger::EffectHandle::getCblk() const { 7017 return mCblkMemory; 7018} 7019 7020void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled) 7021{ 7022 ALOGV("setControl %p control %d", this, hasControl); 7023 7024 mHasControl = hasControl; 7025 mEnabled = enabled; 7026 7027 if (signal && mEffectClient != 0) { 7028 mEffectClient->controlStatusChanged(hasControl); 7029 } 7030} 7031 7032void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode, 7033 uint32_t cmdSize, 7034 void *pCmdData, 7035 uint32_t replySize, 7036 void *pReplyData) 7037{ 7038 if (mEffectClient != 0) { 7039 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 7040 } 7041} 7042 7043 7044 7045void AudioFlinger::EffectHandle::setEnabled(bool enabled) 7046{ 7047 if (mEffectClient != 0) { 7048 mEffectClient->enableStatusChanged(enabled); 7049 } 7050} 7051 7052status_t AudioFlinger::EffectHandle::onTransact( 7053 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 7054{ 7055 return BnEffect::onTransact(code, data, reply, flags); 7056} 7057 7058 7059void AudioFlinger::EffectHandle::dump(char* buffer, size_t size) 7060{ 7061 bool locked = mCblk ? tryLock(mCblk->lock) : false; 7062 7063 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n", 7064 (mClient == NULL) ? getpid() : mClient->pid(), 7065 mPriority, 7066 mHasControl, 7067 !locked, 7068 mCblk ? mCblk->clientIndex : 0, 7069 mCblk ? mCblk->serverIndex : 0 7070 ); 7071 7072 if (locked) { 7073 mCblk->lock.unlock(); 7074 } 7075} 7076 7077#undef LOG_TAG 7078#define LOG_TAG "AudioFlinger::EffectChain" 7079 7080AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread, 7081 int sessionId) 7082 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0), 7083 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX), 7084 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX) 7085{ 7086 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 7087 sp<ThreadBase> thread = mThread.promote(); 7088 if (thread == 0) { 7089 return; 7090 } 7091 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) / 7092 thread->frameCount(); 7093} 7094 7095AudioFlinger::EffectChain::~EffectChain() 7096{ 7097 if (mOwnInBuffer) { 7098 delete mInBuffer; 7099 } 7100 7101} 7102 7103// getEffectFromDesc_l() must be called with ThreadBase::mLock held 7104sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor) 7105{ 7106 sp<EffectModule> effect; 7107 size_t size = mEffects.size(); 7108 7109 for (size_t i = 0; i < size; i++) { 7110 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) { 7111 effect = mEffects[i]; 7112 break; 7113 } 7114 } 7115 return effect; 7116} 7117 7118// getEffectFromId_l() must be called with ThreadBase::mLock held 7119sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id) 7120{ 7121 sp<EffectModule> effect; 7122 size_t size = mEffects.size(); 7123 7124 for (size_t i = 0; i < size; i++) { 7125 // by convention, return first effect if id provided is 0 (0 is never a valid id) 7126 if (id == 0 || mEffects[i]->id() == id) { 7127 effect = mEffects[i]; 7128 break; 7129 } 7130 } 7131 return effect; 7132} 7133 7134// getEffectFromType_l() must be called with ThreadBase::mLock held 7135sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l( 7136 const effect_uuid_t *type) 7137{ 7138 sp<EffectModule> effect; 7139 size_t size = mEffects.size(); 7140 7141 for (size_t i = 0; i < size; i++) { 7142 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) { 7143 effect = mEffects[i]; 7144 break; 7145 } 7146 } 7147 return effect; 7148} 7149 7150// Must be called with EffectChain::mLock locked 7151void AudioFlinger::EffectChain::process_l() 7152{ 7153 sp<ThreadBase> thread = mThread.promote(); 7154 if (thread == 0) { 7155 ALOGW("process_l(): cannot promote mixer thread"); 7156 return; 7157 } 7158 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) || 7159 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE); 7160 // always process effects unless no more tracks are on the session and the effect tail 7161 // has been rendered 7162 bool doProcess = true; 7163 if (!isGlobalSession) { 7164 bool tracksOnSession = (trackCnt() != 0); 7165 7166 if (!tracksOnSession && mTailBufferCount == 0) { 7167 doProcess = false; 7168 } 7169 7170 if (activeTrackCnt() == 0) { 7171 // if no track is active and the effect tail has not been rendered, 7172 // the input buffer must be cleared here as the mixer process will not do it 7173 if (tracksOnSession || mTailBufferCount > 0) { 7174 size_t numSamples = thread->frameCount() * thread->channelCount(); 7175 memset(mInBuffer, 0, numSamples * sizeof(int16_t)); 7176 if (mTailBufferCount > 0) { 7177 mTailBufferCount--; 7178 } 7179 } 7180 } 7181 } 7182 7183 size_t size = mEffects.size(); 7184 if (doProcess) { 7185 for (size_t i = 0; i < size; i++) { 7186 mEffects[i]->process(); 7187 } 7188 } 7189 for (size_t i = 0; i < size; i++) { 7190 mEffects[i]->updateState(); 7191 } 7192} 7193 7194// addEffect_l() must be called with PlaybackThread::mLock held 7195status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect) 7196{ 7197 effect_descriptor_t desc = effect->desc(); 7198 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK; 7199 7200 Mutex::Autolock _l(mLock); 7201 effect->setChain(this); 7202 sp<ThreadBase> thread = mThread.promote(); 7203 if (thread == 0) { 7204 return NO_INIT; 7205 } 7206 effect->setThread(thread); 7207 7208 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7209 // Auxiliary effects are inserted at the beginning of mEffects vector as 7210 // they are processed first and accumulated in chain input buffer 7211 mEffects.insertAt(effect, 0); 7212 7213 // the input buffer for auxiliary effect contains mono samples in 7214 // 32 bit format. This is to avoid saturation in AudoMixer 7215 // accumulation stage. Saturation is done in EffectModule::process() before 7216 // calling the process in effect engine 7217 size_t numSamples = thread->frameCount(); 7218 int32_t *buffer = new int32_t[numSamples]; 7219 memset(buffer, 0, numSamples * sizeof(int32_t)); 7220 effect->setInBuffer((int16_t *)buffer); 7221 // auxiliary effects output samples to chain input buffer for further processing 7222 // by insert effects 7223 effect->setOutBuffer(mInBuffer); 7224 } else { 7225 // Insert effects are inserted at the end of mEffects vector as they are processed 7226 // after track and auxiliary effects. 7227 // Insert effect order as a function of indicated preference: 7228 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if 7229 // another effect is present 7230 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the 7231 // last effect claiming first position 7232 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the 7233 // first effect claiming last position 7234 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last 7235 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is 7236 // already present 7237 7238 int size = (int)mEffects.size(); 7239 int idx_insert = size; 7240 int idx_insert_first = -1; 7241 int idx_insert_last = -1; 7242 7243 for (int i = 0; i < size; i++) { 7244 effect_descriptor_t d = mEffects[i]->desc(); 7245 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK; 7246 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK; 7247 if (iMode == EFFECT_FLAG_TYPE_INSERT) { 7248 // check invalid effect chaining combinations 7249 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE || 7250 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) { 7251 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name); 7252 return INVALID_OPERATION; 7253 } 7254 // remember position of first insert effect and by default 7255 // select this as insert position for new effect 7256 if (idx_insert == size) { 7257 idx_insert = i; 7258 } 7259 // remember position of last insert effect claiming 7260 // first position 7261 if (iPref == EFFECT_FLAG_INSERT_FIRST) { 7262 idx_insert_first = i; 7263 } 7264 // remember position of first insert effect claiming 7265 // last position 7266 if (iPref == EFFECT_FLAG_INSERT_LAST && 7267 idx_insert_last == -1) { 7268 idx_insert_last = i; 7269 } 7270 } 7271 } 7272 7273 // modify idx_insert from first position if needed 7274 if (insertPref == EFFECT_FLAG_INSERT_LAST) { 7275 if (idx_insert_last != -1) { 7276 idx_insert = idx_insert_last; 7277 } else { 7278 idx_insert = size; 7279 } 7280 } else { 7281 if (idx_insert_first != -1) { 7282 idx_insert = idx_insert_first + 1; 7283 } 7284 } 7285 7286 // always read samples from chain input buffer 7287 effect->setInBuffer(mInBuffer); 7288 7289 // if last effect in the chain, output samples to chain 7290 // output buffer, otherwise to chain input buffer 7291 if (idx_insert == size) { 7292 if (idx_insert != 0) { 7293 mEffects[idx_insert-1]->setOutBuffer(mInBuffer); 7294 mEffects[idx_insert-1]->configure(); 7295 } 7296 effect->setOutBuffer(mOutBuffer); 7297 } else { 7298 effect->setOutBuffer(mInBuffer); 7299 } 7300 mEffects.insertAt(effect, idx_insert); 7301 7302 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert); 7303 } 7304 effect->configure(); 7305 return NO_ERROR; 7306} 7307 7308// removeEffect_l() must be called with PlaybackThread::mLock held 7309size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect) 7310{ 7311 Mutex::Autolock _l(mLock); 7312 int size = (int)mEffects.size(); 7313 int i; 7314 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK; 7315 7316 for (i = 0; i < size; i++) { 7317 if (effect == mEffects[i]) { 7318 // calling stop here will remove pre-processing effect from the audio HAL. 7319 // This is safe as we hold the EffectChain mutex which guarantees that we are not in 7320 // the middle of a read from audio HAL 7321 if (mEffects[i]->state() == EffectModule::ACTIVE || 7322 mEffects[i]->state() == EffectModule::STOPPING) { 7323 mEffects[i]->stop(); 7324 } 7325 if (type == EFFECT_FLAG_TYPE_AUXILIARY) { 7326 delete[] effect->inBuffer(); 7327 } else { 7328 if (i == size - 1 && i != 0) { 7329 mEffects[i - 1]->setOutBuffer(mOutBuffer); 7330 mEffects[i - 1]->configure(); 7331 } 7332 } 7333 mEffects.removeAt(i); 7334 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i); 7335 break; 7336 } 7337 } 7338 7339 return mEffects.size(); 7340} 7341 7342// setDevice_l() must be called with PlaybackThread::mLock held 7343void AudioFlinger::EffectChain::setDevice_l(uint32_t device) 7344{ 7345 size_t size = mEffects.size(); 7346 for (size_t i = 0; i < size; i++) { 7347 mEffects[i]->setDevice(device); 7348 } 7349} 7350 7351// setMode_l() must be called with PlaybackThread::mLock held 7352void AudioFlinger::EffectChain::setMode_l(uint32_t mode) 7353{ 7354 size_t size = mEffects.size(); 7355 for (size_t i = 0; i < size; i++) { 7356 mEffects[i]->setMode(mode); 7357 } 7358} 7359 7360// setVolume_l() must be called with PlaybackThread::mLock held 7361bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right) 7362{ 7363 uint32_t newLeft = *left; 7364 uint32_t newRight = *right; 7365 bool hasControl = false; 7366 int ctrlIdx = -1; 7367 size_t size = mEffects.size(); 7368 7369 // first update volume controller 7370 for (size_t i = size; i > 0; i--) { 7371 if (mEffects[i - 1]->isProcessEnabled() && 7372 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) { 7373 ctrlIdx = i - 1; 7374 hasControl = true; 7375 break; 7376 } 7377 } 7378 7379 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) { 7380 if (hasControl) { 7381 *left = mNewLeftVolume; 7382 *right = mNewRightVolume; 7383 } 7384 return hasControl; 7385 } 7386 7387 mVolumeCtrlIdx = ctrlIdx; 7388 mLeftVolume = newLeft; 7389 mRightVolume = newRight; 7390 7391 // second get volume update from volume controller 7392 if (ctrlIdx >= 0) { 7393 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true); 7394 mNewLeftVolume = newLeft; 7395 mNewRightVolume = newRight; 7396 } 7397 // then indicate volume to all other effects in chain. 7398 // Pass altered volume to effects before volume controller 7399 // and requested volume to effects after controller 7400 uint32_t lVol = newLeft; 7401 uint32_t rVol = newRight; 7402 7403 for (size_t i = 0; i < size; i++) { 7404 if ((int)i == ctrlIdx) continue; 7405 // this also works for ctrlIdx == -1 when there is no volume controller 7406 if ((int)i > ctrlIdx) { 7407 lVol = *left; 7408 rVol = *right; 7409 } 7410 mEffects[i]->setVolume(&lVol, &rVol, false); 7411 } 7412 *left = newLeft; 7413 *right = newRight; 7414 7415 return hasControl; 7416} 7417 7418status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args) 7419{ 7420 const size_t SIZE = 256; 7421 char buffer[SIZE]; 7422 String8 result; 7423 7424 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId); 7425 result.append(buffer); 7426 7427 bool locked = tryLock(mLock); 7428 // failed to lock - AudioFlinger is probably deadlocked 7429 if (!locked) { 7430 result.append("\tCould not lock mutex:\n"); 7431 } 7432 7433 result.append("\tNum fx In buffer Out buffer Active tracks:\n"); 7434 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n", 7435 mEffects.size(), 7436 (uint32_t)mInBuffer, 7437 (uint32_t)mOutBuffer, 7438 mActiveTrackCnt); 7439 result.append(buffer); 7440 write(fd, result.string(), result.size()); 7441 7442 for (size_t i = 0; i < mEffects.size(); ++i) { 7443 sp<EffectModule> effect = mEffects[i]; 7444 if (effect != 0) { 7445 effect->dump(fd, args); 7446 } 7447 } 7448 7449 if (locked) { 7450 mLock.unlock(); 7451 } 7452 7453 return NO_ERROR; 7454} 7455 7456// must be called with ThreadBase::mLock held 7457void AudioFlinger::EffectChain::setEffectSuspended_l( 7458 const effect_uuid_t *type, bool suspend) 7459{ 7460 sp<SuspendedEffectDesc> desc; 7461 // use effect type UUID timelow as key as there is no real risk of identical 7462 // timeLow fields among effect type UUIDs. 7463 int index = mSuspendedEffects.indexOfKey(type->timeLow); 7464 if (suspend) { 7465 if (index >= 0) { 7466 desc = mSuspendedEffects.valueAt(index); 7467 } else { 7468 desc = new SuspendedEffectDesc(); 7469 memcpy(&desc->mType, type, sizeof(effect_uuid_t)); 7470 mSuspendedEffects.add(type->timeLow, desc); 7471 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow); 7472 } 7473 if (desc->mRefCount++ == 0) { 7474 sp<EffectModule> effect = getEffectIfEnabled(type); 7475 if (effect != 0) { 7476 desc->mEffect = effect; 7477 effect->setSuspended(true); 7478 effect->setEnabled(false); 7479 } 7480 } 7481 } else { 7482 if (index < 0) { 7483 return; 7484 } 7485 desc = mSuspendedEffects.valueAt(index); 7486 if (desc->mRefCount <= 0) { 7487 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount); 7488 desc->mRefCount = 1; 7489 } 7490 if (--desc->mRefCount == 0) { 7491 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 7492 if (desc->mEffect != 0) { 7493 sp<EffectModule> effect = desc->mEffect.promote(); 7494 if (effect != 0) { 7495 effect->setSuspended(false); 7496 sp<EffectHandle> handle = effect->controlHandle(); 7497 if (handle != 0) { 7498 effect->setEnabled(handle->enabled()); 7499 } 7500 } 7501 desc->mEffect.clear(); 7502 } 7503 mSuspendedEffects.removeItemsAt(index); 7504 } 7505 } 7506} 7507 7508// must be called with ThreadBase::mLock held 7509void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend) 7510{ 7511 sp<SuspendedEffectDesc> desc; 7512 7513 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 7514 if (suspend) { 7515 if (index >= 0) { 7516 desc = mSuspendedEffects.valueAt(index); 7517 } else { 7518 desc = new SuspendedEffectDesc(); 7519 mSuspendedEffects.add((int)kKeyForSuspendAll, desc); 7520 ALOGV("setEffectSuspendedAll_l() add entry for 0"); 7521 } 7522 if (desc->mRefCount++ == 0) { 7523 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects(); 7524 for (size_t i = 0; i < effects.size(); i++) { 7525 setEffectSuspended_l(&effects[i]->desc().type, true); 7526 } 7527 } 7528 } else { 7529 if (index < 0) { 7530 return; 7531 } 7532 desc = mSuspendedEffects.valueAt(index); 7533 if (desc->mRefCount <= 0) { 7534 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount); 7535 desc->mRefCount = 1; 7536 } 7537 if (--desc->mRefCount == 0) { 7538 Vector<const effect_uuid_t *> types; 7539 for (size_t i = 0; i < mSuspendedEffects.size(); i++) { 7540 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) { 7541 continue; 7542 } 7543 types.add(&mSuspendedEffects.valueAt(i)->mType); 7544 } 7545 for (size_t i = 0; i < types.size(); i++) { 7546 setEffectSuspended_l(types[i], false); 7547 } 7548 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 7549 mSuspendedEffects.removeItem((int)kKeyForSuspendAll); 7550 } 7551 } 7552} 7553 7554 7555// The volume effect is used for automated tests only 7556#ifndef OPENSL_ES_H_ 7557static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6, 7558 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }; 7559const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_; 7560#endif //OPENSL_ES_H_ 7561 7562bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc) 7563{ 7564 // auxiliary effects and visualizer are never suspended on output mix 7565 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && 7566 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) || 7567 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) || 7568 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) { 7569 return false; 7570 } 7571 return true; 7572} 7573 7574Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects() 7575{ 7576 Vector< sp<EffectModule> > effects; 7577 for (size_t i = 0; i < mEffects.size(); i++) { 7578 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) { 7579 continue; 7580 } 7581 effects.add(mEffects[i]); 7582 } 7583 return effects; 7584} 7585 7586sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled( 7587 const effect_uuid_t *type) 7588{ 7589 sp<EffectModule> effect; 7590 effect = getEffectFromType_l(type); 7591 if (effect != 0 && !effect->isEnabled()) { 7592 effect.clear(); 7593 } 7594 return effect; 7595} 7596 7597void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 7598 bool enabled) 7599{ 7600 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 7601 if (enabled) { 7602 if (index < 0) { 7603 // if the effect is not suspend check if all effects are suspended 7604 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 7605 if (index < 0) { 7606 return; 7607 } 7608 if (!isEffectEligibleForSuspend(effect->desc())) { 7609 return; 7610 } 7611 setEffectSuspended_l(&effect->desc().type, enabled); 7612 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 7613 if (index < 0) { 7614 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!"); 7615 return; 7616 } 7617 } 7618 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x", 7619 effect->desc().type.timeLow); 7620 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 7621 // if effect is requested to suspended but was not yet enabled, supend it now. 7622 if (desc->mEffect == 0) { 7623 desc->mEffect = effect; 7624 effect->setEnabled(false); 7625 effect->setSuspended(true); 7626 } 7627 } else { 7628 if (index < 0) { 7629 return; 7630 } 7631 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x", 7632 effect->desc().type.timeLow); 7633 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 7634 desc->mEffect.clear(); 7635 effect->setSuspended(false); 7636 } 7637} 7638 7639#undef LOG_TAG 7640#define LOG_TAG "AudioFlinger" 7641 7642// ---------------------------------------------------------------------------- 7643 7644status_t AudioFlinger::onTransact( 7645 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 7646{ 7647 return BnAudioFlinger::onTransact(code, data, reply, flags); 7648} 7649 7650}; // namespace android 7651