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