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