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