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