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