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