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