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