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