Home | History | Annotate | Download | only in audioflinger
      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/IServiceManager.h>
     28 #include <utils/Log.h>
     29 #include <binder/Parcel.h>
     30 #include <binder/IPCThreadState.h>
     31 #include <utils/String16.h>
     32 #include <utils/threads.h>
     33 
     34 #include <cutils/properties.h>
     35 
     36 #include <media/AudioTrack.h>
     37 #include <media/AudioRecord.h>
     38 
     39 #include <private/media/AudioTrackShared.h>
     40 
     41 #include <hardware_legacy/AudioHardwareInterface.h>
     42 
     43 #include "AudioMixer.h"
     44 #include "AudioFlinger.h"
     45 
     46 #ifdef WITH_A2DP
     47 #include "A2dpAudioInterface.h"
     48 #endif
     49 
     50 #ifdef LVMX
     51 #include "lifevibes.h"
     52 #endif
     53 
     54 // ----------------------------------------------------------------------------
     55 // the sim build doesn't have gettid
     56 
     57 #ifndef HAVE_GETTID
     58 # define gettid getpid
     59 #endif
     60 
     61 // ----------------------------------------------------------------------------
     62 
     63 namespace android {
     64 
     65 static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
     66 static const char* kHardwareLockedString = "Hardware lock is taken\n";
     67 
     68 //static const nsecs_t kStandbyTimeInNsecs = seconds(3);
     69 static const float MAX_GAIN = 4096.0f;
     70 
     71 // retry counts for buffer fill timeout
     72 // 50 * ~20msecs = 1 second
     73 static const int8_t kMaxTrackRetries = 50;
     74 static 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.
     78 static const int8_t kMaxTrackRetriesDirect = 2;
     79 
     80 static const int kDumpLockRetries = 50;
     81 static const int kDumpLockSleep = 20000;
     82 
     83 static const nsecs_t kWarningThrottle = seconds(5);
     84 
     85 
     86 #define AUDIOFLINGER_SECURITY_ENABLED 1
     87 
     88 // ----------------------------------------------------------------------------
     89 
     90 static bool recordingAllowed() {
     91 #ifndef HAVE_ANDROID_OS
     92     return true;
     93 #endif
     94 #if AUDIOFLINGER_SECURITY_ENABLED
     95     if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
     96     bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
     97     if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
     98     return ok;
     99 #else
    100     if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
    101         LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
    102     return true;
    103 #endif
    104 }
    105 
    106 static bool settingsAllowed() {
    107 #ifndef HAVE_ANDROID_OS
    108     return true;
    109 #endif
    110 #if AUDIOFLINGER_SECURITY_ENABLED
    111     if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
    112     bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
    113     if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
    114     return ok;
    115 #else
    116     if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
    117         LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
    118     return true;
    119 #endif
    120 }
    121 
    122 // ----------------------------------------------------------------------------
    123 
    124 AudioFlinger::AudioFlinger()
    125     : BnAudioFlinger(),
    126         mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
    127 {
    128     mHardwareStatus = AUDIO_HW_IDLE;
    129 
    130     mAudioHardware = AudioHardwareInterface::create();
    131 
    132     mHardwareStatus = AUDIO_HW_INIT;
    133     if (mAudioHardware->initCheck() == NO_ERROR) {
    134         // open 16-bit output stream for s/w mixer
    135 
    136         setMode(AudioSystem::MODE_NORMAL);
    137 
    138         setMasterVolume(1.0f);
    139         setMasterMute(false);
    140     } else {
    141         LOGE("Couldn't even initialize the stubbed audio hardware!");
    142     }
    143 #ifdef LVMX
    144     LifeVibes::init();
    145 #endif
    146 }
    147 
    148 AudioFlinger::~AudioFlinger()
    149 {
    150     while (!mRecordThreads.isEmpty()) {
    151         // closeInput() will remove first entry from mRecordThreads
    152         closeInput(mRecordThreads.keyAt(0));
    153     }
    154     while (!mPlaybackThreads.isEmpty()) {
    155         // closeOutput() will remove first entry from mPlaybackThreads
    156         closeOutput(mPlaybackThreads.keyAt(0));
    157     }
    158     if (mAudioHardware) {
    159         delete mAudioHardware;
    160     }
    161 }
    162 
    163 
    164 
    165 status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
    166 {
    167     const size_t SIZE = 256;
    168     char buffer[SIZE];
    169     String8 result;
    170 
    171     result.append("Clients:\n");
    172     for (size_t i = 0; i < mClients.size(); ++i) {
    173         wp<Client> wClient = mClients.valueAt(i);
    174         if (wClient != 0) {
    175             sp<Client> client = wClient.promote();
    176             if (client != 0) {
    177                 snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
    178                 result.append(buffer);
    179             }
    180         }
    181     }
    182     write(fd, result.string(), result.size());
    183     return NO_ERROR;
    184 }
    185 
    186 
    187 status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
    188 {
    189     const size_t SIZE = 256;
    190     char buffer[SIZE];
    191     String8 result;
    192     int hardwareStatus = mHardwareStatus;
    193 
    194     snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
    195     result.append(buffer);
    196     write(fd, result.string(), result.size());
    197     return NO_ERROR;
    198 }
    199 
    200 status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
    201 {
    202     const size_t SIZE = 256;
    203     char buffer[SIZE];
    204     String8 result;
    205     snprintf(buffer, SIZE, "Permission Denial: "
    206             "can't dump AudioFlinger from pid=%d, uid=%d\n",
    207             IPCThreadState::self()->getCallingPid(),
    208             IPCThreadState::self()->getCallingUid());
    209     result.append(buffer);
    210     write(fd, result.string(), result.size());
    211     return NO_ERROR;
    212 }
    213 
    214 static bool tryLock(Mutex& mutex)
    215 {
    216     bool locked = false;
    217     for (int i = 0; i < kDumpLockRetries; ++i) {
    218         if (mutex.tryLock() == NO_ERROR) {
    219             locked = true;
    220             break;
    221         }
    222         usleep(kDumpLockSleep);
    223     }
    224     return locked;
    225 }
    226 
    227 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
    228 {
    229     if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
    230         dumpPermissionDenial(fd, args);
    231     } else {
    232         // get state of hardware lock
    233         bool hardwareLocked = tryLock(mHardwareLock);
    234         if (!hardwareLocked) {
    235             String8 result(kHardwareLockedString);
    236             write(fd, result.string(), result.size());
    237         } else {
    238             mHardwareLock.unlock();
    239         }
    240 
    241         bool locked = tryLock(mLock);
    242 
    243         // failed to lock - AudioFlinger is probably deadlocked
    244         if (!locked) {
    245             String8 result(kDeadlockedString);
    246             write(fd, result.string(), result.size());
    247         }
    248 
    249         dumpClients(fd, args);
    250         dumpInternals(fd, args);
    251 
    252         // dump playback threads
    253         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    254             mPlaybackThreads.valueAt(i)->dump(fd, args);
    255         }
    256 
    257         // dump record threads
    258         for (size_t i = 0; i < mRecordThreads.size(); i++) {
    259             mRecordThreads.valueAt(i)->dump(fd, args);
    260         }
    261 
    262         if (mAudioHardware) {
    263             mAudioHardware->dumpState(fd, args);
    264         }
    265         if (locked) mLock.unlock();
    266     }
    267     return NO_ERROR;
    268 }
    269 
    270 
    271 // IAudioFlinger interface
    272 
    273 
    274 sp<IAudioTrack> AudioFlinger::createTrack(
    275         pid_t pid,
    276         int streamType,
    277         uint32_t sampleRate,
    278         int format,
    279         int channelCount,
    280         int frameCount,
    281         uint32_t flags,
    282         const sp<IMemory>& sharedBuffer,
    283         int output,
    284         status_t *status)
    285 {
    286     sp<PlaybackThread::Track> track;
    287     sp<TrackHandle> trackHandle;
    288     sp<Client> client;
    289     wp<Client> wclient;
    290     status_t lStatus;
    291 
    292     if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
    293         LOGE("invalid stream type");
    294         lStatus = BAD_VALUE;
    295         goto Exit;
    296     }
    297 
    298     {
    299         Mutex::Autolock _l(mLock);
    300         PlaybackThread *thread = checkPlaybackThread_l(output);
    301         if (thread == NULL) {
    302             LOGE("unknown output thread");
    303             lStatus = BAD_VALUE;
    304             goto Exit;
    305         }
    306 
    307         wclient = mClients.valueFor(pid);
    308 
    309         if (wclient != NULL) {
    310             client = wclient.promote();
    311         } else {
    312             client = new Client(this, pid);
    313             mClients.add(pid, client);
    314         }
    315         track = thread->createTrack_l(client, streamType, sampleRate, format,
    316                 channelCount, frameCount, sharedBuffer, &lStatus);
    317     }
    318     if (lStatus == NO_ERROR) {
    319         trackHandle = new TrackHandle(track);
    320     } else {
    321         // remove local strong reference to Client before deleting the Track so that the Client
    322         // destructor is called by the TrackBase destructor with mLock held
    323         client.clear();
    324         track.clear();
    325     }
    326 
    327 Exit:
    328     if(status) {
    329         *status = lStatus;
    330     }
    331     return trackHandle;
    332 }
    333 
    334 uint32_t AudioFlinger::sampleRate(int output) const
    335 {
    336     Mutex::Autolock _l(mLock);
    337     PlaybackThread *thread = checkPlaybackThread_l(output);
    338     if (thread == NULL) {
    339         LOGW("sampleRate() unknown thread %d", output);
    340         return 0;
    341     }
    342     return thread->sampleRate();
    343 }
    344 
    345 int AudioFlinger::channelCount(int output) const
    346 {
    347     Mutex::Autolock _l(mLock);
    348     PlaybackThread *thread = checkPlaybackThread_l(output);
    349     if (thread == NULL) {
    350         LOGW("channelCount() unknown thread %d", output);
    351         return 0;
    352     }
    353     return thread->channelCount();
    354 }
    355 
    356 int AudioFlinger::format(int output) const
    357 {
    358     Mutex::Autolock _l(mLock);
    359     PlaybackThread *thread = checkPlaybackThread_l(output);
    360     if (thread == NULL) {
    361         LOGW("format() unknown thread %d", output);
    362         return 0;
    363     }
    364     return thread->format();
    365 }
    366 
    367 size_t AudioFlinger::frameCount(int output) const
    368 {
    369     Mutex::Autolock _l(mLock);
    370     PlaybackThread *thread = checkPlaybackThread_l(output);
    371     if (thread == NULL) {
    372         LOGW("frameCount() unknown thread %d", output);
    373         return 0;
    374     }
    375     return thread->frameCount();
    376 }
    377 
    378 uint32_t AudioFlinger::latency(int output) const
    379 {
    380     Mutex::Autolock _l(mLock);
    381     PlaybackThread *thread = checkPlaybackThread_l(output);
    382     if (thread == NULL) {
    383         LOGW("latency() unknown thread %d", output);
    384         return 0;
    385     }
    386     return thread->latency();
    387 }
    388 
    389 status_t AudioFlinger::setMasterVolume(float value)
    390 {
    391     // check calling permissions
    392     if (!settingsAllowed()) {
    393         return PERMISSION_DENIED;
    394     }
    395 
    396     // when hw supports master volume, don't scale in sw mixer
    397     AutoMutex lock(mHardwareLock);
    398     mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
    399     if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
    400         value = 1.0f;
    401     }
    402     mHardwareStatus = AUDIO_HW_IDLE;
    403 
    404     mMasterVolume = value;
    405     for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
    406        mPlaybackThreads.valueAt(i)->setMasterVolume(value);
    407 
    408     return NO_ERROR;
    409 }
    410 
    411 status_t AudioFlinger::setMode(int mode)
    412 {
    413     // check calling permissions
    414     if (!settingsAllowed()) {
    415         return PERMISSION_DENIED;
    416     }
    417     if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
    418         LOGW("Illegal value: setMode(%d)", mode);
    419         return BAD_VALUE;
    420     }
    421 
    422     AutoMutex lock(mHardwareLock);
    423     mHardwareStatus = AUDIO_HW_SET_MODE;
    424     status_t ret = mAudioHardware->setMode(mode);
    425 #ifdef LVMX
    426     if (NO_ERROR == ret) {
    427         LifeVibes::setMode(mode);
    428     }
    429 #endif
    430     mHardwareStatus = AUDIO_HW_IDLE;
    431     return ret;
    432 }
    433 
    434 status_t AudioFlinger::setMicMute(bool state)
    435 {
    436     // check calling permissions
    437     if (!settingsAllowed()) {
    438         return PERMISSION_DENIED;
    439     }
    440 
    441     AutoMutex lock(mHardwareLock);
    442     mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
    443     status_t ret = mAudioHardware->setMicMute(state);
    444     mHardwareStatus = AUDIO_HW_IDLE;
    445     return ret;
    446 }
    447 
    448 bool AudioFlinger::getMicMute() const
    449 {
    450     bool state = AudioSystem::MODE_INVALID;
    451     mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
    452     mAudioHardware->getMicMute(&state);
    453     mHardwareStatus = AUDIO_HW_IDLE;
    454     return state;
    455 }
    456 
    457 status_t AudioFlinger::setMasterMute(bool muted)
    458 {
    459     // check calling permissions
    460     if (!settingsAllowed()) {
    461         return PERMISSION_DENIED;
    462     }
    463 
    464     mMasterMute = muted;
    465     for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
    466        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
    467 
    468     return NO_ERROR;
    469 }
    470 
    471 float AudioFlinger::masterVolume() const
    472 {
    473     return mMasterVolume;
    474 }
    475 
    476 bool AudioFlinger::masterMute() const
    477 {
    478     return mMasterMute;
    479 }
    480 
    481 status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
    482 {
    483     // check calling permissions
    484     if (!settingsAllowed()) {
    485         return PERMISSION_DENIED;
    486     }
    487 
    488     if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
    489         return BAD_VALUE;
    490     }
    491 
    492     AutoMutex lock(mLock);
    493     PlaybackThread *thread = NULL;
    494     if (output) {
    495         thread = checkPlaybackThread_l(output);
    496         if (thread == NULL) {
    497             return BAD_VALUE;
    498         }
    499     }
    500 
    501     mStreamTypes[stream].volume = value;
    502 
    503     if (thread == NULL) {
    504         for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
    505            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
    506         }
    507     } else {
    508         thread->setStreamVolume(stream, value);
    509     }
    510 
    511     return NO_ERROR;
    512 }
    513 
    514 status_t AudioFlinger::setStreamMute(int stream, bool muted)
    515 {
    516     // check calling permissions
    517     if (!settingsAllowed()) {
    518         return PERMISSION_DENIED;
    519     }
    520 
    521     if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
    522         uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
    523         return BAD_VALUE;
    524     }
    525 
    526     mStreamTypes[stream].mute = muted;
    527     for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
    528        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
    529 
    530     return NO_ERROR;
    531 }
    532 
    533 float AudioFlinger::streamVolume(int stream, int output) const
    534 {
    535     if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
    536         return 0.0f;
    537     }
    538 
    539     AutoMutex lock(mLock);
    540     float volume;
    541     if (output) {
    542         PlaybackThread *thread = checkPlaybackThread_l(output);
    543         if (thread == NULL) {
    544             return 0.0f;
    545         }
    546         volume = thread->streamVolume(stream);
    547     } else {
    548         volume = mStreamTypes[stream].volume;
    549     }
    550 
    551     return volume;
    552 }
    553 
    554 bool AudioFlinger::streamMute(int stream) const
    555 {
    556     if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
    557         return true;
    558     }
    559 
    560     return mStreamTypes[stream].mute;
    561 }
    562 
    563 bool AudioFlinger::isStreamActive(int stream) const
    564 {
    565     Mutex::Autolock _l(mLock);
    566     for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
    567         if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
    568             return true;
    569         }
    570     }
    571     return false;
    572 }
    573 
    574 status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
    575 {
    576     status_t result;
    577 
    578     LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
    579             ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
    580     // check calling permissions
    581     if (!settingsAllowed()) {
    582         return PERMISSION_DENIED;
    583     }
    584 
    585 #ifdef LVMX
    586     AudioParameter param = AudioParameter(keyValuePairs);
    587     LifeVibes::setParameters(ioHandle,keyValuePairs);
    588     String8 key = String8(AudioParameter::keyRouting);
    589     int device;
    590     if (NO_ERROR != param.getInt(key, device)) {
    591         device = -1;
    592     }
    593 
    594     key = String8(LifevibesTag);
    595     String8 value;
    596     int musicEnabled = -1;
    597     if (NO_ERROR == param.get(key, value)) {
    598         if (value == LifevibesEnable) {
    599             musicEnabled = 1;
    600         } else if (value == LifevibesDisable) {
    601             musicEnabled = 0;
    602         }
    603     }
    604 #endif
    605 
    606     // ioHandle == 0 means the parameters are global to the audio hardware interface
    607     if (ioHandle == 0) {
    608         AutoMutex lock(mHardwareLock);
    609         mHardwareStatus = AUDIO_SET_PARAMETER;
    610         result = mAudioHardware->setParameters(keyValuePairs);
    611 #ifdef LVMX
    612         if ((NO_ERROR == result) && (musicEnabled != -1)) {
    613             LifeVibes::enableMusic((bool) musicEnabled);
    614         }
    615 #endif
    616         mHardwareStatus = AUDIO_HW_IDLE;
    617         return result;
    618     }
    619 
    620     // hold a strong ref on thread in case closeOutput() or closeInput() is called
    621     // and the thread is exited once the lock is released
    622     sp<ThreadBase> thread;
    623     {
    624         Mutex::Autolock _l(mLock);
    625         thread = checkPlaybackThread_l(ioHandle);
    626         if (thread == NULL) {
    627             thread = checkRecordThread_l(ioHandle);
    628         }
    629     }
    630     if (thread != NULL) {
    631         result = thread->setParameters(keyValuePairs);
    632 #ifdef LVMX
    633         if ((NO_ERROR == result) && (device != -1)) {
    634             LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
    635         }
    636 #endif
    637         return result;
    638     }
    639     return BAD_VALUE;
    640 }
    641 
    642 String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
    643 {
    644 //    LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
    645 //            ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
    646 
    647     if (ioHandle == 0) {
    648         return mAudioHardware->getParameters(keys);
    649     }
    650 
    651     Mutex::Autolock _l(mLock);
    652 
    653     PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
    654     if (playbackThread != NULL) {
    655         return playbackThread->getParameters(keys);
    656     }
    657     RecordThread *recordThread = checkRecordThread_l(ioHandle);
    658     if (recordThread != NULL) {
    659         return recordThread->getParameters(keys);
    660     }
    661     return String8("");
    662 }
    663 
    664 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
    665 {
    666     return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
    667 }
    668 
    669 unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
    670 {
    671     if (ioHandle == 0) {
    672         return 0;
    673     }
    674 
    675     Mutex::Autolock _l(mLock);
    676 
    677     RecordThread *recordThread = checkRecordThread_l(ioHandle);
    678     if (recordThread != NULL) {
    679         return recordThread->getInputFramesLost();
    680     }
    681     return 0;
    682 }
    683 
    684 status_t AudioFlinger::setVoiceVolume(float value)
    685 {
    686     // check calling permissions
    687     if (!settingsAllowed()) {
    688         return PERMISSION_DENIED;
    689     }
    690 
    691     AutoMutex lock(mHardwareLock);
    692     mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
    693     status_t ret = mAudioHardware->setVoiceVolume(value);
    694     mHardwareStatus = AUDIO_HW_IDLE;
    695 
    696     return ret;
    697 }
    698 
    699 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
    700 {
    701     status_t status;
    702 
    703     Mutex::Autolock _l(mLock);
    704 
    705     PlaybackThread *playbackThread = checkPlaybackThread_l(output);
    706     if (playbackThread != NULL) {
    707         return playbackThread->getRenderPosition(halFrames, dspFrames);
    708     }
    709 
    710     return BAD_VALUE;
    711 }
    712 
    713 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
    714 {
    715 
    716     LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
    717     Mutex::Autolock _l(mLock);
    718 
    719     sp<IBinder> binder = client->asBinder();
    720     if (mNotificationClients.indexOf(binder) < 0) {
    721         LOGV("Adding notification client %p", binder.get());
    722         binder->linkToDeath(this);
    723         mNotificationClients.add(binder);
    724     }
    725 
    726     // the config change is always sent from playback or record threads to avoid deadlock
    727     // with AudioSystem::gLock
    728     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    729         mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
    730     }
    731 
    732     for (size_t i = 0; i < mRecordThreads.size(); i++) {
    733         mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
    734     }
    735 }
    736 
    737 void AudioFlinger::binderDied(const wp<IBinder>& who) {
    738 
    739     LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
    740     Mutex::Autolock _l(mLock);
    741 
    742     IBinder *binder = who.unsafe_get();
    743 
    744     if (binder != NULL) {
    745         int index = mNotificationClients.indexOf(binder);
    746         if (index >= 0) {
    747             LOGV("Removing notification client %p", binder);
    748             mNotificationClients.removeAt(index);
    749         }
    750     }
    751 }
    752 
    753 // audioConfigChanged_l() must be called with AudioFlinger::mLock held
    754 void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2) {
    755     size_t size = mNotificationClients.size();
    756     for (size_t i = 0; i < size; i++) {
    757         sp<IBinder> binder = mNotificationClients.itemAt(i);
    758         LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
    759         sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
    760         client->ioConfigChanged(event, ioHandle, param2);
    761     }
    762 }
    763 
    764 // removeClient_l() must be called with AudioFlinger::mLock held
    765 void AudioFlinger::removeClient_l(pid_t pid)
    766 {
    767     LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
    768     mClients.removeItem(pid);
    769 }
    770 
    771 // ----------------------------------------------------------------------------
    772 
    773 AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
    774     :   Thread(false),
    775         mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
    776         mFormat(0), mFrameSize(1), mStandby(false), mId(id), mExiting(false)
    777 {
    778 }
    779 
    780 AudioFlinger::ThreadBase::~ThreadBase()
    781 {
    782     mParamCond.broadcast();
    783     mNewParameters.clear();
    784 }
    785 
    786 void AudioFlinger::ThreadBase::exit()
    787 {
    788     // keep a strong ref on ourself so that we wont get
    789     // destroyed in the middle of requestExitAndWait()
    790     sp <ThreadBase> strongMe = this;
    791 
    792     LOGV("ThreadBase::exit");
    793     {
    794         AutoMutex lock(&mLock);
    795         mExiting = true;
    796         requestExit();
    797         mWaitWorkCV.signal();
    798     }
    799     requestExitAndWait();
    800 }
    801 
    802 uint32_t AudioFlinger::ThreadBase::sampleRate() const
    803 {
    804     return mSampleRate;
    805 }
    806 
    807 int AudioFlinger::ThreadBase::channelCount() const
    808 {
    809     return mChannelCount;
    810 }
    811 
    812 int AudioFlinger::ThreadBase::format() const
    813 {
    814     return mFormat;
    815 }
    816 
    817 size_t AudioFlinger::ThreadBase::frameCount() const
    818 {
    819     return mFrameCount;
    820 }
    821 
    822 status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
    823 {
    824     status_t status;
    825 
    826     LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
    827     Mutex::Autolock _l(mLock);
    828 
    829     mNewParameters.add(keyValuePairs);
    830     mWaitWorkCV.signal();
    831     // wait condition with timeout in case the thread loop has exited
    832     // before the request could be processed
    833     if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
    834         status = mParamStatus;
    835         mWaitWorkCV.signal();
    836     } else {
    837         status = TIMED_OUT;
    838     }
    839     return status;
    840 }
    841 
    842 void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
    843 {
    844     Mutex::Autolock _l(mLock);
    845     sendConfigEvent_l(event, param);
    846 }
    847 
    848 // sendConfigEvent_l() must be called with ThreadBase::mLock held
    849 void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
    850 {
    851     ConfigEvent *configEvent = new ConfigEvent();
    852     configEvent->mEvent = event;
    853     configEvent->mParam = param;
    854     mConfigEvents.add(configEvent);
    855     LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
    856     mWaitWorkCV.signal();
    857 }
    858 
    859 void AudioFlinger::ThreadBase::processConfigEvents()
    860 {
    861     mLock.lock();
    862     while(!mConfigEvents.isEmpty()) {
    863         LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
    864         ConfigEvent *configEvent = mConfigEvents[0];
    865         mConfigEvents.removeAt(0);
    866         // release mLock because audioConfigChanged() will lock AudioFlinger mLock
    867         // before calling Audioflinger::audioConfigChanged_l() thus creating
    868         // potential cross deadlock between AudioFlinger::mLock and mLock
    869         mLock.unlock();
    870         audioConfigChanged(configEvent->mEvent, configEvent->mParam);
    871         delete configEvent;
    872         mLock.lock();
    873     }
    874     mLock.unlock();
    875 }
    876 
    877 status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
    878 {
    879     const size_t SIZE = 256;
    880     char buffer[SIZE];
    881     String8 result;
    882 
    883     bool locked = tryLock(mLock);
    884     if (!locked) {
    885         snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
    886         write(fd, buffer, strlen(buffer));
    887     }
    888 
    889     snprintf(buffer, SIZE, "standby: %d\n", mStandby);
    890     result.append(buffer);
    891     snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
    892     result.append(buffer);
    893     snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
    894     result.append(buffer);
    895     snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
    896     result.append(buffer);
    897     snprintf(buffer, SIZE, "Format: %d\n", mFormat);
    898     result.append(buffer);
    899     snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
    900     result.append(buffer);
    901 
    902     snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
    903     result.append(buffer);
    904     result.append(" Index Command");
    905     for (size_t i = 0; i < mNewParameters.size(); ++i) {
    906         snprintf(buffer, SIZE, "\n %02d    ", i);
    907         result.append(buffer);
    908         result.append(mNewParameters[i]);
    909     }
    910 
    911     snprintf(buffer, SIZE, "\n\nPending config events: \n");
    912     result.append(buffer);
    913     snprintf(buffer, SIZE, " Index event param\n");
    914     result.append(buffer);
    915     for (size_t i = 0; i < mConfigEvents.size(); i++) {
    916         snprintf(buffer, SIZE, " %02d    %02d    %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
    917         result.append(buffer);
    918     }
    919     result.append("\n");
    920 
    921     write(fd, result.string(), result.size());
    922 
    923     if (locked) {
    924         mLock.unlock();
    925     }
    926     return NO_ERROR;
    927 }
    928 
    929 
    930 // ----------------------------------------------------------------------------
    931 
    932 AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
    933     :   ThreadBase(audioFlinger, id),
    934         mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
    935         mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
    936 {
    937     readOutputParameters();
    938 
    939     mMasterVolume = mAudioFlinger->masterVolume();
    940     mMasterMute = mAudioFlinger->masterMute();
    941 
    942     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
    943         mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
    944         mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
    945     }
    946     // notify client processes that a new input has been opened
    947     sendConfigEvent(AudioSystem::OUTPUT_OPENED);
    948 }
    949 
    950 AudioFlinger::PlaybackThread::~PlaybackThread()
    951 {
    952     delete [] mMixBuffer;
    953 }
    954 
    955 status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
    956 {
    957     dumpInternals(fd, args);
    958     dumpTracks(fd, args);
    959     return NO_ERROR;
    960 }
    961 
    962 status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
    963 {
    964     const size_t SIZE = 256;
    965     char buffer[SIZE];
    966     String8 result;
    967 
    968     snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
    969     result.append(buffer);
    970     result.append("   Name Clien Typ Fmt Chn Buf  S M F SRate  LeftV RighV Serv     User\n");
    971     for (size_t i = 0; i < mTracks.size(); ++i) {
    972         sp<Track> track = mTracks[i];
    973         if (track != 0) {
    974             track->dump(buffer, SIZE);
    975             result.append(buffer);
    976         }
    977     }
    978 
    979     snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
    980     result.append(buffer);
    981     result.append("   Name Clien Typ Fmt Chn Buf  S M F SRate  LeftV RighV Serv     User\n");
    982     for (size_t i = 0; i < mActiveTracks.size(); ++i) {
    983         wp<Track> wTrack = mActiveTracks[i];
    984         if (wTrack != 0) {
    985             sp<Track> track = wTrack.promote();
    986             if (track != 0) {
    987                 track->dump(buffer, SIZE);
    988                 result.append(buffer);
    989             }
    990         }
    991     }
    992     write(fd, result.string(), result.size());
    993     return NO_ERROR;
    994 }
    995 
    996 status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
    997 {
    998     const size_t SIZE = 256;
    999     char buffer[SIZE];
   1000     String8 result;
   1001 
   1002     snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
   1003     result.append(buffer);
   1004     snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
   1005     result.append(buffer);
   1006     snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
   1007     result.append(buffer);
   1008     snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
   1009     result.append(buffer);
   1010     snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
   1011     result.append(buffer);
   1012     snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
   1013     result.append(buffer);
   1014     write(fd, result.string(), result.size());
   1015 
   1016     dumpBase(fd, args);
   1017 
   1018     return NO_ERROR;
   1019 }
   1020 
   1021 // Thread virtuals
   1022 status_t AudioFlinger::PlaybackThread::readyToRun()
   1023 {
   1024     if (mSampleRate == 0) {
   1025         LOGE("No working audio driver found.");
   1026         return NO_INIT;
   1027     }
   1028     LOGI("AudioFlinger's thread %p ready to run", this);
   1029     return NO_ERROR;
   1030 }
   1031 
   1032 void AudioFlinger::PlaybackThread::onFirstRef()
   1033 {
   1034     const size_t SIZE = 256;
   1035     char buffer[SIZE];
   1036 
   1037     snprintf(buffer, SIZE, "Playback Thread %p", this);
   1038 
   1039     run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
   1040 }
   1041 
   1042 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
   1043 sp<AudioFlinger::PlaybackThread::Track>  AudioFlinger::PlaybackThread::createTrack_l(
   1044         const sp<AudioFlinger::Client>& client,
   1045         int streamType,
   1046         uint32_t sampleRate,
   1047         int format,
   1048         int channelCount,
   1049         int frameCount,
   1050         const sp<IMemory>& sharedBuffer,
   1051         status_t *status)
   1052 {
   1053     sp<Track> track;
   1054     status_t lStatus;
   1055 
   1056     if (mType == DIRECT) {
   1057         if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
   1058             LOGE("createTrack_l() Bad parameter:  sampleRate %d format %d, channelCount %d for output %p",
   1059                  sampleRate, format, channelCount, mOutput);
   1060             lStatus = BAD_VALUE;
   1061             goto Exit;
   1062         }
   1063     } else {
   1064         // Resampler implementation limits input sampling rate to 2 x output sampling rate.
   1065         if (sampleRate > mSampleRate*2) {
   1066             LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
   1067             lStatus = BAD_VALUE;
   1068             goto Exit;
   1069         }
   1070     }
   1071 
   1072     if (mOutput == 0) {
   1073         LOGE("Audio driver not initialized.");
   1074         lStatus = NO_INIT;
   1075         goto Exit;
   1076     }
   1077 
   1078     { // scope for mLock
   1079         Mutex::Autolock _l(mLock);
   1080         track = new Track(this, client, streamType, sampleRate, format,
   1081                 channelCount, frameCount, sharedBuffer);
   1082         if (track->getCblk() == NULL || track->name() < 0) {
   1083             lStatus = NO_MEMORY;
   1084             goto Exit;
   1085         }
   1086         mTracks.add(track);
   1087     }
   1088     lStatus = NO_ERROR;
   1089 
   1090 Exit:
   1091     if(status) {
   1092         *status = lStatus;
   1093     }
   1094     return track;
   1095 }
   1096 
   1097 uint32_t AudioFlinger::PlaybackThread::latency() const
   1098 {
   1099     if (mOutput) {
   1100         return mOutput->latency();
   1101     }
   1102     else {
   1103         return 0;
   1104     }
   1105 }
   1106 
   1107 status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
   1108 {
   1109 #ifdef LVMX
   1110     int audioOutputType = LifeVibes::getMixerType(mId, mType);
   1111     if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
   1112         LifeVibes::setMasterVolume(audioOutputType, value);
   1113     }
   1114 #endif
   1115     mMasterVolume = value;
   1116     return NO_ERROR;
   1117 }
   1118 
   1119 status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
   1120 {
   1121 #ifdef LVMX
   1122     int audioOutputType = LifeVibes::getMixerType(mId, mType);
   1123     if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
   1124         LifeVibes::setMasterMute(audioOutputType, muted);
   1125     }
   1126 #endif
   1127     mMasterMute = muted;
   1128     return NO_ERROR;
   1129 }
   1130 
   1131 float AudioFlinger::PlaybackThread::masterVolume() const
   1132 {
   1133     return mMasterVolume;
   1134 }
   1135 
   1136 bool AudioFlinger::PlaybackThread::masterMute() const
   1137 {
   1138     return mMasterMute;
   1139 }
   1140 
   1141 status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
   1142 {
   1143 #ifdef LVMX
   1144     int audioOutputType = LifeVibes::getMixerType(mId, mType);
   1145     if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
   1146         LifeVibes::setStreamVolume(audioOutputType, stream, value);
   1147     }
   1148 #endif
   1149     mStreamTypes[stream].volume = value;
   1150     return NO_ERROR;
   1151 }
   1152 
   1153 status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
   1154 {
   1155 #ifdef LVMX
   1156     int audioOutputType = LifeVibes::getMixerType(mId, mType);
   1157     if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
   1158         LifeVibes::setStreamMute(audioOutputType, stream, muted);
   1159     }
   1160 #endif
   1161     mStreamTypes[stream].mute = muted;
   1162     return NO_ERROR;
   1163 }
   1164 
   1165 float AudioFlinger::PlaybackThread::streamVolume(int stream) const
   1166 {
   1167     return mStreamTypes[stream].volume;
   1168 }
   1169 
   1170 bool AudioFlinger::PlaybackThread::streamMute(int stream) const
   1171 {
   1172     return mStreamTypes[stream].mute;
   1173 }
   1174 
   1175 bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
   1176 {
   1177     Mutex::Autolock _l(mLock);
   1178     size_t count = mActiveTracks.size();
   1179     for (size_t i = 0 ; i < count ; ++i) {
   1180         sp<Track> t = mActiveTracks[i].promote();
   1181         if (t == 0) continue;
   1182         Track* const track = t.get();
   1183         if (t->type() == stream)
   1184             return true;
   1185     }
   1186     return false;
   1187 }
   1188 
   1189 // addTrack_l() must be called with ThreadBase::mLock held
   1190 status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
   1191 {
   1192     status_t status = ALREADY_EXISTS;
   1193 
   1194     // set retry count for buffer fill
   1195     track->mRetryCount = kMaxTrackStartupRetries;
   1196     if (mActiveTracks.indexOf(track) < 0) {
   1197         // the track is newly added, make sure it fills up all its
   1198         // buffers before playing. This is to ensure the client will
   1199         // effectively get the latency it requested.
   1200         track->mFillingUpStatus = Track::FS_FILLING;
   1201         track->mResetDone = false;
   1202         mActiveTracks.add(track);
   1203         status = NO_ERROR;
   1204     }
   1205 
   1206     LOGV("mWaitWorkCV.broadcast");
   1207     mWaitWorkCV.broadcast();
   1208 
   1209     return status;
   1210 }
   1211 
   1212 // destroyTrack_l() must be called with ThreadBase::mLock held
   1213 void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
   1214 {
   1215     track->mState = TrackBase::TERMINATED;
   1216     if (mActiveTracks.indexOf(track) < 0) {
   1217         mTracks.remove(track);
   1218         deleteTrackName_l(track->name());
   1219     }
   1220 }
   1221 
   1222 String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
   1223 {
   1224     return mOutput->getParameters(keys);
   1225 }
   1226 
   1227 void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
   1228     AudioSystem::OutputDescriptor desc;
   1229     void *param2 = 0;
   1230 
   1231     LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
   1232 
   1233     switch (event) {
   1234     case AudioSystem::OUTPUT_OPENED:
   1235     case AudioSystem::OUTPUT_CONFIG_CHANGED:
   1236         desc.channels = mChannelCount;
   1237         desc.samplingRate = mSampleRate;
   1238         desc.format = mFormat;
   1239         desc.frameCount = mFrameCount;
   1240         desc.latency = latency();
   1241         param2 = &desc;
   1242         break;
   1243 
   1244     case AudioSystem::STREAM_CONFIG_CHANGED:
   1245         param2 = &param;
   1246     case AudioSystem::OUTPUT_CLOSED:
   1247     default:
   1248         break;
   1249     }
   1250     Mutex::Autolock _l(mAudioFlinger->mLock);
   1251     mAudioFlinger->audioConfigChanged_l(event, mId, param2);
   1252 }
   1253 
   1254 void AudioFlinger::PlaybackThread::readOutputParameters()
   1255 {
   1256     mSampleRate = mOutput->sampleRate();
   1257     mChannelCount = AudioSystem::popCount(mOutput->channels());
   1258 
   1259     mFormat = mOutput->format();
   1260     mFrameSize = mOutput->frameSize();
   1261     mFrameCount = mOutput->bufferSize() / mFrameSize;
   1262 
   1263     // FIXME - Current mixer implementation only supports stereo output: Always
   1264     // Allocate a stereo buffer even if HW output is mono.
   1265     if (mMixBuffer != NULL) delete mMixBuffer;
   1266     mMixBuffer = new int16_t[mFrameCount * 2];
   1267     memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
   1268 }
   1269 
   1270 status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
   1271 {
   1272     if (halFrames == 0 || dspFrames == 0) {
   1273         return BAD_VALUE;
   1274     }
   1275     if (mOutput == 0) {
   1276         return INVALID_OPERATION;
   1277     }
   1278     *halFrames = mBytesWritten/mOutput->frameSize();
   1279 
   1280     return mOutput->getRenderPosition(dspFrames);
   1281 }
   1282 
   1283 // ----------------------------------------------------------------------------
   1284 
   1285 AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
   1286     :   PlaybackThread(audioFlinger, output, id),
   1287         mAudioMixer(0)
   1288 {
   1289     mType = PlaybackThread::MIXER;
   1290     mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
   1291 
   1292     // FIXME - Current mixer implementation only supports stereo output
   1293     if (mChannelCount == 1) {
   1294         LOGE("Invalid audio hardware channel count");
   1295     }
   1296 }
   1297 
   1298 AudioFlinger::MixerThread::~MixerThread()
   1299 {
   1300     delete mAudioMixer;
   1301 }
   1302 
   1303 bool AudioFlinger::MixerThread::threadLoop()
   1304 {
   1305     int16_t* curBuf = mMixBuffer;
   1306     Vector< sp<Track> > tracksToRemove;
   1307     uint32_t mixerStatus = MIXER_IDLE;
   1308     nsecs_t standbyTime = systemTime();
   1309     size_t mixBufferSize = mFrameCount * mFrameSize;
   1310     // FIXME: Relaxed timing because of a certain device that can't meet latency
   1311     // Should be reduced to 2x after the vendor fixes the driver issue
   1312     nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
   1313     nsecs_t lastWarning = 0;
   1314     bool longStandbyExit = false;
   1315     uint32_t activeSleepTime = activeSleepTimeUs();
   1316     uint32_t idleSleepTime = idleSleepTimeUs();
   1317     uint32_t sleepTime = idleSleepTime;
   1318 
   1319     while (!exitPending())
   1320     {
   1321         processConfigEvents();
   1322 
   1323         mixerStatus = MIXER_IDLE;
   1324         { // scope for mLock
   1325 
   1326             Mutex::Autolock _l(mLock);
   1327 
   1328             if (checkForNewParameters_l()) {
   1329                 mixBufferSize = mFrameCount * mFrameSize;
   1330                 // FIXME: Relaxed timing because of a certain device that can't meet latency
   1331                 // Should be reduced to 2x after the vendor fixes the driver issue
   1332                 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
   1333                 activeSleepTime = activeSleepTimeUs();
   1334                 idleSleepTime = idleSleepTimeUs();
   1335             }
   1336 
   1337             const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
   1338 
   1339             // put audio hardware into standby after short delay
   1340             if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
   1341                         mSuspended) {
   1342                 if (!mStandby) {
   1343                     LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
   1344                     mOutput->standby();
   1345                     mStandby = true;
   1346                     mBytesWritten = 0;
   1347                 }
   1348 
   1349                 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
   1350                     // we're about to wait, flush the binder command buffer
   1351                     IPCThreadState::self()->flushCommands();
   1352 
   1353                     if (exitPending()) break;
   1354 
   1355                     // wait until we have something to do...
   1356                     LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
   1357                     mWaitWorkCV.wait(mLock);
   1358                     LOGV("MixerThread %p TID %d waking up\n", this, gettid());
   1359 
   1360                     if (mMasterMute == false) {
   1361                         char value[PROPERTY_VALUE_MAX];
   1362                         property_get("ro.audio.silent", value, "0");
   1363                         if (atoi(value)) {
   1364                             LOGD("Silence is golden");
   1365                             setMasterMute(true);
   1366                         }
   1367                     }
   1368 
   1369                     standbyTime = systemTime() + kStandbyTimeInNsecs;
   1370                     sleepTime = idleSleepTime;
   1371                     continue;
   1372                 }
   1373             }
   1374 
   1375             mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
   1376        }
   1377 
   1378         if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
   1379             // mix buffers...
   1380             mAudioMixer->process(curBuf);
   1381             sleepTime = 0;
   1382             standbyTime = systemTime() + kStandbyTimeInNsecs;
   1383         } else {
   1384             // If no tracks are ready, sleep once for the duration of an output
   1385             // buffer size, then write 0s to the output
   1386             if (sleepTime == 0) {
   1387                 if (mixerStatus == MIXER_TRACKS_ENABLED) {
   1388                     sleepTime = activeSleepTime;
   1389                 } else {
   1390                     sleepTime = idleSleepTime;
   1391                 }
   1392             } else if (mBytesWritten != 0 ||
   1393                        (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
   1394                 memset (curBuf, 0, mixBufferSize);
   1395                 sleepTime = 0;
   1396                 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
   1397             }
   1398         }
   1399 
   1400         if (mSuspended) {
   1401             sleepTime = idleSleepTime;
   1402         }
   1403         // sleepTime == 0 means we must write to audio hardware
   1404         if (sleepTime == 0) {
   1405             mLastWriteTime = systemTime();
   1406             mInWrite = true;
   1407             mBytesWritten += mixBufferSize;
   1408 #ifdef LVMX
   1409             int audioOutputType = LifeVibes::getMixerType(mId, mType);
   1410             if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
   1411                LifeVibes::process(audioOutputType, curBuf, mixBufferSize);
   1412             }
   1413 #endif
   1414             int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
   1415             if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
   1416             mNumWrites++;
   1417             mInWrite = false;
   1418             nsecs_t now = systemTime();
   1419             nsecs_t delta = now - mLastWriteTime;
   1420             if (delta > maxPeriod) {
   1421                 mNumDelayedWrites++;
   1422                 if ((now - lastWarning) > kWarningThrottle) {
   1423                     LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
   1424                             ns2ms(delta), mNumDelayedWrites, this);
   1425                     lastWarning = now;
   1426                 }
   1427                 if (mStandby) {
   1428                     longStandbyExit = true;
   1429                 }
   1430             }
   1431             mStandby = false;
   1432         } else {
   1433             usleep(sleepTime);
   1434         }
   1435 
   1436         // finally let go of all our tracks, without the lock held
   1437         // since we can't guarantee the destructors won't acquire that
   1438         // same lock.
   1439         tracksToRemove.clear();
   1440     }
   1441 
   1442     if (!mStandby) {
   1443         mOutput->standby();
   1444     }
   1445 
   1446     LOGV("MixerThread %p exiting", this);
   1447     return false;
   1448 }
   1449 
   1450 // prepareTracks_l() must be called with ThreadBase::mLock held
   1451 uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
   1452 {
   1453 
   1454     uint32_t mixerStatus = MIXER_IDLE;
   1455     // find out which tracks need to be processed
   1456     size_t count = activeTracks.size();
   1457 
   1458     float masterVolume = mMasterVolume;
   1459     bool  masterMute = mMasterMute;
   1460 
   1461 #ifdef LVMX
   1462     bool tracksConnectedChanged = false;
   1463     bool stateChanged = false;
   1464 
   1465     int audioOutputType = LifeVibes::getMixerType(mId, mType);
   1466     if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
   1467     {
   1468         int activeTypes = 0;
   1469         for (size_t i=0 ; i<count ; i++) {
   1470             sp<Track> t = activeTracks[i].promote();
   1471             if (t == 0) continue;
   1472             Track* const track = t.get();
   1473             int iTracktype=track->type();
   1474             activeTypes |= 1<<track->type();
   1475         }
   1476         LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
   1477     }
   1478 #endif
   1479 
   1480     for (size_t i=0 ; i<count ; i++) {
   1481         sp<Track> t = activeTracks[i].promote();
   1482         if (t == 0) continue;
   1483 
   1484         Track* const track = t.get();
   1485         audio_track_cblk_t* cblk = track->cblk();
   1486 
   1487         // The first time a track is added we wait
   1488         // for all its buffers to be filled before processing it
   1489         mAudioMixer->setActiveTrack(track->name());
   1490         if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
   1491                 !track->isPaused() && !track->isTerminated())
   1492         {
   1493             //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
   1494 
   1495             // compute volume for this track
   1496             int16_t left, right;
   1497             if (track->isMuted() || masterMute || track->isPausing() ||
   1498                 mStreamTypes[track->type()].mute) {
   1499                 left = right = 0;
   1500                 if (track->isPausing()) {
   1501                     track->setPaused();
   1502                 }
   1503             } else {
   1504                 // read original volumes with volume control
   1505                 float typeVolume = mStreamTypes[track->type()].volume;
   1506 #ifdef LVMX
   1507                 bool streamMute=false;
   1508                 // read the volume from the LivesVibes audio engine.
   1509                 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
   1510                 {
   1511                     LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
   1512                     if (streamMute) {
   1513                         typeVolume = 0;
   1514                     }
   1515                 }
   1516 #endif
   1517                 float v = masterVolume * typeVolume;
   1518                 float v_clamped = v * cblk->volume[0];
   1519                 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
   1520                 left = int16_t(v_clamped);
   1521                 v_clamped = v * cblk->volume[1];
   1522                 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
   1523                 right = int16_t(v_clamped);
   1524             }
   1525 
   1526             // XXX: these things DON'T need to be done each time
   1527             mAudioMixer->setBufferProvider(track);
   1528             mAudioMixer->enable(AudioMixer::MIXING);
   1529 
   1530             int param = AudioMixer::VOLUME;
   1531             if (track->mFillingUpStatus == Track::FS_FILLED) {
   1532                 // no ramp for the first volume setting
   1533                 track->mFillingUpStatus = Track::FS_ACTIVE;
   1534                 if (track->mState == TrackBase::RESUMING) {
   1535                     track->mState = TrackBase::ACTIVE;
   1536                     param = AudioMixer::RAMP_VOLUME;
   1537                 }
   1538             } else if (cblk->server != 0) {
   1539                 // If the track is stopped before the first frame was mixed,
   1540                 // do not apply ramp
   1541                 param = AudioMixer::RAMP_VOLUME;
   1542             }
   1543 #ifdef LVMX
   1544             if ( tracksConnectedChanged || stateChanged )
   1545             {
   1546                  // only do the ramp when the volume is changed by the user / application
   1547                  param = AudioMixer::VOLUME;
   1548             }
   1549 #endif
   1550             mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
   1551             mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
   1552             mAudioMixer->setParameter(
   1553                 AudioMixer::TRACK,
   1554                 AudioMixer::FORMAT, track->format());
   1555             mAudioMixer->setParameter(
   1556                 AudioMixer::TRACK,
   1557                 AudioMixer::CHANNEL_COUNT, track->channelCount());
   1558             mAudioMixer->setParameter(
   1559                 AudioMixer::RESAMPLE,
   1560                 AudioMixer::SAMPLE_RATE,
   1561                 int(cblk->sampleRate));
   1562 
   1563             // reset retry count
   1564             track->mRetryCount = kMaxTrackRetries;
   1565             mixerStatus = MIXER_TRACKS_READY;
   1566         } else {
   1567             //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
   1568             if (track->isStopped()) {
   1569                 track->reset();
   1570             }
   1571             if (track->isTerminated() || track->isStopped() || track->isPaused()) {
   1572                 // We have consumed all the buffers of this track.
   1573                 // Remove it from the list of active tracks.
   1574                 tracksToRemove->add(track);
   1575                 mAudioMixer->disable(AudioMixer::MIXING);
   1576             } else {
   1577                 // No buffers for this track. Give it a few chances to
   1578                 // fill a buffer, then remove it from active list.
   1579                 if (--(track->mRetryCount) <= 0) {
   1580                     LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
   1581                     tracksToRemove->add(track);
   1582                 } else if (mixerStatus != MIXER_TRACKS_READY) {
   1583                     mixerStatus = MIXER_TRACKS_ENABLED;
   1584                 }
   1585 
   1586                 mAudioMixer->disable(AudioMixer::MIXING);
   1587             }
   1588         }
   1589     }
   1590 
   1591     // remove all the tracks that need to be...
   1592     count = tracksToRemove->size();
   1593     if (UNLIKELY(count)) {
   1594         for (size_t i=0 ; i<count ; i++) {
   1595             const sp<Track>& track = tracksToRemove->itemAt(i);
   1596             mActiveTracks.remove(track);
   1597             if (track->isTerminated()) {
   1598                 mTracks.remove(track);
   1599                 deleteTrackName_l(track->mName);
   1600             }
   1601         }
   1602     }
   1603 
   1604     return mixerStatus;
   1605 }
   1606 
   1607 void AudioFlinger::MixerThread::getTracks(
   1608         SortedVector < sp<Track> >& tracks,
   1609         SortedVector < wp<Track> >& activeTracks,
   1610         int streamType)
   1611 {
   1612     LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this,  mTracks.size(), mActiveTracks.size());
   1613     Mutex::Autolock _l(mLock);
   1614     size_t size = mTracks.size();
   1615     for (size_t i = 0; i < size; i++) {
   1616         sp<Track> t = mTracks[i];
   1617         if (t->type() == streamType) {
   1618             tracks.add(t);
   1619             int j = mActiveTracks.indexOf(t);
   1620             if (j >= 0) {
   1621                 t = mActiveTracks[j].promote();
   1622                 if (t != NULL) {
   1623                     activeTracks.add(t);
   1624                 }
   1625             }
   1626         }
   1627     }
   1628 
   1629     size = activeTracks.size();
   1630     for (size_t i = 0; i < size; i++) {
   1631         mActiveTracks.remove(activeTracks[i]);
   1632     }
   1633 
   1634     size = tracks.size();
   1635     for (size_t i = 0; i < size; i++) {
   1636         sp<Track> t = tracks[i];
   1637         mTracks.remove(t);
   1638         deleteTrackName_l(t->name());
   1639     }
   1640 }
   1641 
   1642 void AudioFlinger::MixerThread::putTracks(
   1643         SortedVector < sp<Track> >& tracks,
   1644         SortedVector < wp<Track> >& activeTracks)
   1645 {
   1646     LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this,  tracks.size(), activeTracks.size());
   1647     Mutex::Autolock _l(mLock);
   1648     size_t size = tracks.size();
   1649     for (size_t i = 0; i < size ; i++) {
   1650         sp<Track> t = tracks[i];
   1651         int name = getTrackName_l();
   1652 
   1653         if (name < 0) return;
   1654 
   1655         t->mName = name;
   1656         t->mThread = this;
   1657         mTracks.add(t);
   1658 
   1659         int j = activeTracks.indexOf(t);
   1660         if (j >= 0) {
   1661             mActiveTracks.add(t);
   1662             // force buffer refilling and no ramp volume when the track is mixed for the first time
   1663             t->mFillingUpStatus = Track::FS_FILLING;
   1664         }
   1665     }
   1666 }
   1667 
   1668 // getTrackName_l() must be called with ThreadBase::mLock held
   1669 int AudioFlinger::MixerThread::getTrackName_l()
   1670 {
   1671     return mAudioMixer->getTrackName();
   1672 }
   1673 
   1674 // deleteTrackName_l() must be called with ThreadBase::mLock held
   1675 void AudioFlinger::MixerThread::deleteTrackName_l(int name)
   1676 {
   1677     LOGV("remove track (%d) and delete from mixer", name);
   1678     mAudioMixer->deleteTrackName(name);
   1679 }
   1680 
   1681 // checkForNewParameters_l() must be called with ThreadBase::mLock held
   1682 bool AudioFlinger::MixerThread::checkForNewParameters_l()
   1683 {
   1684     bool reconfig = false;
   1685 
   1686     while (!mNewParameters.isEmpty()) {
   1687         status_t status = NO_ERROR;
   1688         String8 keyValuePair = mNewParameters[0];
   1689         AudioParameter param = AudioParameter(keyValuePair);
   1690         int value;
   1691 
   1692         if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
   1693             reconfig = true;
   1694         }
   1695         if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
   1696             if (value != AudioSystem::PCM_16_BIT) {
   1697                 status = BAD_VALUE;
   1698             } else {
   1699                 reconfig = true;
   1700             }
   1701         }
   1702         if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
   1703             if (value != AudioSystem::CHANNEL_OUT_STEREO) {
   1704                 status = BAD_VALUE;
   1705             } else {
   1706                 reconfig = true;
   1707             }
   1708         }
   1709         if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
   1710             // do not accept frame count changes if tracks are open as the track buffer
   1711             // size depends on frame count and correct behavior would not be garantied
   1712             // if frame count is changed after track creation
   1713             if (!mTracks.isEmpty()) {
   1714                 status = INVALID_OPERATION;
   1715             } else {
   1716                 reconfig = true;
   1717             }
   1718         }
   1719         if (status == NO_ERROR) {
   1720             status = mOutput->setParameters(keyValuePair);
   1721             if (!mStandby && status == INVALID_OPERATION) {
   1722                mOutput->standby();
   1723                mStandby = true;
   1724                mBytesWritten = 0;
   1725                status = mOutput->setParameters(keyValuePair);
   1726             }
   1727             if (status == NO_ERROR && reconfig) {
   1728                 delete mAudioMixer;
   1729                 readOutputParameters();
   1730                 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
   1731                 for (size_t i = 0; i < mTracks.size() ; i++) {
   1732                     int name = getTrackName_l();
   1733                     if (name < 0) break;
   1734                     mTracks[i]->mName = name;
   1735                     // limit track sample rate to 2 x new output sample rate
   1736                     if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
   1737                         mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
   1738                     }
   1739                 }
   1740                 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
   1741             }
   1742         }
   1743 
   1744         mNewParameters.removeAt(0);
   1745 
   1746         mParamStatus = status;
   1747         mParamCond.signal();
   1748         mWaitWorkCV.wait(mLock);
   1749     }
   1750     return reconfig;
   1751 }
   1752 
   1753 status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
   1754 {
   1755     const size_t SIZE = 256;
   1756     char buffer[SIZE];
   1757     String8 result;
   1758 
   1759     PlaybackThread::dumpInternals(fd, args);
   1760 
   1761     snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
   1762     result.append(buffer);
   1763     write(fd, result.string(), result.size());
   1764     return NO_ERROR;
   1765 }
   1766 
   1767 uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
   1768 {
   1769     return (uint32_t)(mOutput->latency() * 1000) / 2;
   1770 }
   1771 
   1772 uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
   1773 {
   1774     return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
   1775 }
   1776 
   1777 // ----------------------------------------------------------------------------
   1778 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
   1779     :   PlaybackThread(audioFlinger, output, id),
   1780     mLeftVolume (1.0), mRightVolume(1.0)
   1781 {
   1782     mType = PlaybackThread::DIRECT;
   1783 }
   1784 
   1785 AudioFlinger::DirectOutputThread::~DirectOutputThread()
   1786 {
   1787 }
   1788 
   1789 
   1790 bool AudioFlinger::DirectOutputThread::threadLoop()
   1791 {
   1792     uint32_t mixerStatus = MIXER_IDLE;
   1793     sp<Track> trackToRemove;
   1794     sp<Track> activeTrack;
   1795     nsecs_t standbyTime = systemTime();
   1796     int8_t *curBuf;
   1797     size_t mixBufferSize = mFrameCount*mFrameSize;
   1798     uint32_t activeSleepTime = activeSleepTimeUs();
   1799     uint32_t idleSleepTime = idleSleepTimeUs();
   1800     uint32_t sleepTime = idleSleepTime;
   1801     // use shorter standby delay as on normal output to release
   1802     // hardware resources as soon as possible
   1803     nsecs_t standbyDelay = microseconds(activeSleepTime*2);
   1804 
   1805 
   1806     while (!exitPending())
   1807     {
   1808         processConfigEvents();
   1809 
   1810         mixerStatus = MIXER_IDLE;
   1811 
   1812         { // scope for the mLock
   1813 
   1814             Mutex::Autolock _l(mLock);
   1815 
   1816             if (checkForNewParameters_l()) {
   1817                 mixBufferSize = mFrameCount*mFrameSize;
   1818                 activeSleepTime = activeSleepTimeUs();
   1819                 idleSleepTime = idleSleepTimeUs();
   1820                 standbyDelay = microseconds(activeSleepTime*2);
   1821             }
   1822 
   1823             // put audio hardware into standby after short delay
   1824             if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
   1825                         mSuspended) {
   1826                 // wait until we have something to do...
   1827                 if (!mStandby) {
   1828                     LOGV("Audio hardware entering standby, mixer %p\n", this);
   1829                     mOutput->standby();
   1830                     mStandby = true;
   1831                     mBytesWritten = 0;
   1832                 }
   1833 
   1834                 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
   1835                     // we're about to wait, flush the binder command buffer
   1836                     IPCThreadState::self()->flushCommands();
   1837 
   1838                     if (exitPending()) break;
   1839 
   1840                     LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
   1841                     mWaitWorkCV.wait(mLock);
   1842                     LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
   1843 
   1844                     if (mMasterMute == false) {
   1845                         char value[PROPERTY_VALUE_MAX];
   1846                         property_get("ro.audio.silent", value, "0");
   1847                         if (atoi(value)) {
   1848                             LOGD("Silence is golden");
   1849                             setMasterMute(true);
   1850                         }
   1851                     }
   1852 
   1853                     standbyTime = systemTime() + standbyDelay;
   1854                     sleepTime = idleSleepTime;
   1855                     continue;
   1856                 }
   1857             }
   1858 
   1859             // find out which tracks need to be processed
   1860             if (mActiveTracks.size() != 0) {
   1861                 sp<Track> t = mActiveTracks[0].promote();
   1862                 if (t == 0) continue;
   1863 
   1864                 Track* const track = t.get();
   1865                 audio_track_cblk_t* cblk = track->cblk();
   1866 
   1867                 // The first time a track is added we wait
   1868                 // for all its buffers to be filled before processing it
   1869                 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
   1870                         !track->isPaused() && !track->isTerminated())
   1871                 {
   1872                     //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
   1873 
   1874                     // compute volume for this track
   1875                     float left, right;
   1876                     if (track->isMuted() || mMasterMute || track->isPausing() ||
   1877                         mStreamTypes[track->type()].mute) {
   1878                         left = right = 0;
   1879                         if (track->isPausing()) {
   1880                             track->setPaused();
   1881                         }
   1882                     } else {
   1883                         float typeVolume = mStreamTypes[track->type()].volume;
   1884                         float v = mMasterVolume * typeVolume;
   1885                         float v_clamped = v * cblk->volume[0];
   1886                         if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
   1887                         left = v_clamped/MAX_GAIN;
   1888                         v_clamped = v * cblk->volume[1];
   1889                         if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
   1890                         right = v_clamped/MAX_GAIN;
   1891                     }
   1892 
   1893                     if (left != mLeftVolume || right != mRightVolume) {
   1894                         mOutput->setVolume(left, right);
   1895                         left = mLeftVolume;
   1896                         right = mRightVolume;
   1897                     }
   1898 
   1899                     if (track->mFillingUpStatus == Track::FS_FILLED) {
   1900                         track->mFillingUpStatus = Track::FS_ACTIVE;
   1901                         if (track->mState == TrackBase::RESUMING) {
   1902                             track->mState = TrackBase::ACTIVE;
   1903                         }
   1904                     }
   1905 
   1906                     // reset retry count
   1907                     track->mRetryCount = kMaxTrackRetriesDirect;
   1908                     activeTrack = t;
   1909                     mixerStatus = MIXER_TRACKS_READY;
   1910                 } else {
   1911                     //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
   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                         trackToRemove = 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", track->name());
   1924                             trackToRemove = track;
   1925                         } else {
   1926                             mixerStatus = MIXER_TRACKS_ENABLED;
   1927                         }
   1928                     }
   1929                 }
   1930             }
   1931 
   1932             // remove all the tracks that need to be...
   1933             if (UNLIKELY(trackToRemove != 0)) {
   1934                 mActiveTracks.remove(trackToRemove);
   1935                 if (trackToRemove->isTerminated()) {
   1936                     mTracks.remove(trackToRemove);
   1937                     deleteTrackName_l(trackToRemove->mName);
   1938                 }
   1939             }
   1940        }
   1941 
   1942         if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
   1943             AudioBufferProvider::Buffer buffer;
   1944             size_t frameCount = mFrameCount;
   1945             curBuf = (int8_t *)mMixBuffer;
   1946             // output audio to hardware
   1947             while(frameCount) {
   1948                 buffer.frameCount = frameCount;
   1949                 activeTrack->getNextBuffer(&buffer);
   1950                 if (UNLIKELY(buffer.raw == 0)) {
   1951                     memset(curBuf, 0, frameCount * mFrameSize);
   1952                     break;
   1953                 }
   1954                 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
   1955                 frameCount -= buffer.frameCount;
   1956                 curBuf += buffer.frameCount * mFrameSize;
   1957                 activeTrack->releaseBuffer(&buffer);
   1958             }
   1959             sleepTime = 0;
   1960             standbyTime = systemTime() + standbyDelay;
   1961         } else {
   1962             if (sleepTime == 0) {
   1963                 if (mixerStatus == MIXER_TRACKS_ENABLED) {
   1964                     sleepTime = activeSleepTime;
   1965                 } else {
   1966                     sleepTime = idleSleepTime;
   1967                 }
   1968             } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
   1969                 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
   1970                 sleepTime = 0;
   1971             }
   1972         }
   1973 
   1974         if (mSuspended) {
   1975             sleepTime = idleSleepTime;
   1976         }
   1977         // sleepTime == 0 means we must write to audio hardware
   1978         if (sleepTime == 0) {
   1979             mLastWriteTime = systemTime();
   1980             mInWrite = true;
   1981             mBytesWritten += mixBufferSize;
   1982             int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
   1983             if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
   1984             mNumWrites++;
   1985             mInWrite = false;
   1986             mStandby = false;
   1987         } else {
   1988             usleep(sleepTime);
   1989         }
   1990 
   1991         // finally let go of removed track, without the lock held
   1992         // since we can't guarantee the destructors won't acquire that
   1993         // same lock.
   1994         trackToRemove.clear();
   1995         activeTrack.clear();
   1996     }
   1997 
   1998     if (!mStandby) {
   1999         mOutput->standby();
   2000     }
   2001 
   2002     LOGV("DirectOutputThread %p exiting", this);
   2003     return false;
   2004 }
   2005 
   2006 // getTrackName_l() must be called with ThreadBase::mLock held
   2007 int AudioFlinger::DirectOutputThread::getTrackName_l()
   2008 {
   2009     return 0;
   2010 }
   2011 
   2012 // deleteTrackName_l() must be called with ThreadBase::mLock held
   2013 void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
   2014 {
   2015 }
   2016 
   2017 // checkForNewParameters_l() must be called with ThreadBase::mLock held
   2018 bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
   2019 {
   2020     bool reconfig = false;
   2021 
   2022     while (!mNewParameters.isEmpty()) {
   2023         status_t status = NO_ERROR;
   2024         String8 keyValuePair = mNewParameters[0];
   2025         AudioParameter param = AudioParameter(keyValuePair);
   2026         int value;
   2027 
   2028         if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
   2029             // do not accept frame count changes if tracks are open as the track buffer
   2030             // size depends on frame count and correct behavior would not be garantied
   2031             // if frame count is changed after track creation
   2032             if (!mTracks.isEmpty()) {
   2033                 status = INVALID_OPERATION;
   2034             } else {
   2035                 reconfig = true;
   2036             }
   2037         }
   2038         if (status == NO_ERROR) {
   2039             status = mOutput->setParameters(keyValuePair);
   2040             if (!mStandby && status == INVALID_OPERATION) {
   2041                mOutput->standby();
   2042                mStandby = true;
   2043                mBytesWritten = 0;
   2044                status = mOutput->setParameters(keyValuePair);
   2045             }
   2046             if (status == NO_ERROR && reconfig) {
   2047                 readOutputParameters();
   2048                 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
   2049             }
   2050         }
   2051 
   2052         mNewParameters.removeAt(0);
   2053 
   2054         mParamStatus = status;
   2055         mParamCond.signal();
   2056         mWaitWorkCV.wait(mLock);
   2057     }
   2058     return reconfig;
   2059 }
   2060 
   2061 uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
   2062 {
   2063     uint32_t time;
   2064     if (AudioSystem::isLinearPCM(mFormat)) {
   2065         time = (uint32_t)(mOutput->latency() * 1000) / 2;
   2066     } else {
   2067         time = 10000;
   2068     }
   2069     return time;
   2070 }
   2071 
   2072 uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
   2073 {
   2074     uint32_t time;
   2075     if (AudioSystem::isLinearPCM(mFormat)) {
   2076         time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
   2077     } else {
   2078         time = 10000;
   2079     }
   2080     return time;
   2081 }
   2082 
   2083 // ----------------------------------------------------------------------------
   2084 
   2085 AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
   2086     :   MixerThread(audioFlinger, mainThread->getOutput(), id), mWaitTimeMs(UINT_MAX)
   2087 {
   2088     mType = PlaybackThread::DUPLICATING;
   2089     addOutputTrack(mainThread);
   2090 }
   2091 
   2092 AudioFlinger::DuplicatingThread::~DuplicatingThread()
   2093 {
   2094     for (size_t i = 0; i < mOutputTracks.size(); i++) {
   2095         mOutputTracks[i]->destroy();
   2096     }
   2097     mOutputTracks.clear();
   2098 }
   2099 
   2100 bool AudioFlinger::DuplicatingThread::threadLoop()
   2101 {
   2102     int16_t* curBuf = mMixBuffer;
   2103     Vector< sp<Track> > tracksToRemove;
   2104     uint32_t mixerStatus = MIXER_IDLE;
   2105     nsecs_t standbyTime = systemTime();
   2106     size_t mixBufferSize = mFrameCount*mFrameSize;
   2107     SortedVector< sp<OutputTrack> > outputTracks;
   2108     uint32_t writeFrames = 0;
   2109     uint32_t activeSleepTime = activeSleepTimeUs();
   2110     uint32_t idleSleepTime = idleSleepTimeUs();
   2111     uint32_t sleepTime = idleSleepTime;
   2112 
   2113     while (!exitPending())
   2114     {
   2115         processConfigEvents();
   2116 
   2117         mixerStatus = MIXER_IDLE;
   2118         { // scope for the mLock
   2119 
   2120             Mutex::Autolock _l(mLock);
   2121 
   2122             if (checkForNewParameters_l()) {
   2123                 mixBufferSize = mFrameCount*mFrameSize;
   2124                 updateWaitTime();
   2125                 activeSleepTime = activeSleepTimeUs();
   2126                 idleSleepTime = idleSleepTimeUs();
   2127             }
   2128 
   2129             const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
   2130 
   2131             for (size_t i = 0; i < mOutputTracks.size(); i++) {
   2132                 outputTracks.add(mOutputTracks[i]);
   2133             }
   2134 
   2135             // put audio hardware into standby after short delay
   2136             if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
   2137                          mSuspended) {
   2138                 if (!mStandby) {
   2139                     for (size_t i = 0; i < outputTracks.size(); i++) {
   2140                         outputTracks[i]->stop();
   2141                     }
   2142                     mStandby = true;
   2143                     mBytesWritten = 0;
   2144                 }
   2145 
   2146                 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
   2147                     // we're about to wait, flush the binder command buffer
   2148                     IPCThreadState::self()->flushCommands();
   2149                     outputTracks.clear();
   2150 
   2151                     if (exitPending()) break;
   2152 
   2153                     LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
   2154                     mWaitWorkCV.wait(mLock);
   2155                     LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
   2156                     if (mMasterMute == false) {
   2157                         char value[PROPERTY_VALUE_MAX];
   2158                         property_get("ro.audio.silent", value, "0");
   2159                         if (atoi(value)) {
   2160                             LOGD("Silence is golden");
   2161                             setMasterMute(true);
   2162                         }
   2163                     }
   2164 
   2165                     standbyTime = systemTime() + kStandbyTimeInNsecs;
   2166                     sleepTime = idleSleepTime;
   2167                     continue;
   2168                 }
   2169             }
   2170 
   2171             mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
   2172         }
   2173 
   2174         if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
   2175             // mix buffers...
   2176             if (outputsReady(outputTracks)) {
   2177                 mAudioMixer->process(curBuf);
   2178             } else {
   2179                 memset(curBuf, 0, mixBufferSize);
   2180             }
   2181             sleepTime = 0;
   2182             writeFrames = mFrameCount;
   2183         } else {
   2184             if (sleepTime == 0) {
   2185                 if (mixerStatus == MIXER_TRACKS_ENABLED) {
   2186                     sleepTime = activeSleepTime;
   2187                 } else {
   2188                     sleepTime = idleSleepTime;
   2189                 }
   2190             } else if (mBytesWritten != 0) {
   2191                 // flush remaining overflow buffers in output tracks
   2192                 for (size_t i = 0; i < outputTracks.size(); i++) {
   2193                     if (outputTracks[i]->isActive()) {
   2194                         sleepTime = 0;
   2195                         writeFrames = 0;
   2196                         break;
   2197                     }
   2198                 }
   2199             }
   2200         }
   2201 
   2202         if (mSuspended) {
   2203             sleepTime = idleSleepTime;
   2204         }
   2205         // sleepTime == 0 means we must write to audio hardware
   2206         if (sleepTime == 0) {
   2207             standbyTime = systemTime() + kStandbyTimeInNsecs;
   2208             for (size_t i = 0; i < outputTracks.size(); i++) {
   2209                 outputTracks[i]->write(curBuf, writeFrames);
   2210             }
   2211             mStandby = false;
   2212             mBytesWritten += mixBufferSize;
   2213         } else {
   2214             usleep(sleepTime);
   2215         }
   2216 
   2217         // finally let go of all our tracks, without the lock held
   2218         // since we can't guarantee the destructors won't acquire that
   2219         // same lock.
   2220         tracksToRemove.clear();
   2221         outputTracks.clear();
   2222     }
   2223 
   2224     return false;
   2225 }
   2226 
   2227 void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
   2228 {
   2229     int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
   2230     OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
   2231                                             this,
   2232                                             mSampleRate,
   2233                                             mFormat,
   2234                                             mChannelCount,
   2235                                             frameCount);
   2236     if (outputTrack->cblk() != NULL) {
   2237         thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
   2238         mOutputTracks.add(outputTrack);
   2239         LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
   2240         updateWaitTime();
   2241     }
   2242 }
   2243 
   2244 void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
   2245 {
   2246     Mutex::Autolock _l(mLock);
   2247     for (size_t i = 0; i < mOutputTracks.size(); i++) {
   2248         if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
   2249             mOutputTracks[i]->destroy();
   2250             mOutputTracks.removeAt(i);
   2251             updateWaitTime();
   2252             return;
   2253         }
   2254     }
   2255     LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
   2256 }
   2257 
   2258 void AudioFlinger::DuplicatingThread::updateWaitTime()
   2259 {
   2260     mWaitTimeMs = UINT_MAX;
   2261     for (size_t i = 0; i < mOutputTracks.size(); i++) {
   2262         sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
   2263         if (strong != NULL) {
   2264             uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
   2265             if (waitTimeMs < mWaitTimeMs) {
   2266                 mWaitTimeMs = waitTimeMs;
   2267             }
   2268         }
   2269     }
   2270 }
   2271 
   2272 
   2273 bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
   2274 {
   2275     for (size_t i = 0; i < outputTracks.size(); i++) {
   2276         sp <ThreadBase> thread = outputTracks[i]->thread().promote();
   2277         if (thread == 0) {
   2278             LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
   2279             return false;
   2280         }
   2281         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
   2282         if (playbackThread->standby() && !playbackThread->isSuspended()) {
   2283             LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
   2284             return false;
   2285         }
   2286     }
   2287     return true;
   2288 }
   2289 
   2290 uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
   2291 {
   2292     return (mWaitTimeMs * 1000) / 2;
   2293 }
   2294 
   2295 // ----------------------------------------------------------------------------
   2296 
   2297 // TrackBase constructor must be called with AudioFlinger::mLock held
   2298 AudioFlinger::ThreadBase::TrackBase::TrackBase(
   2299             const wp<ThreadBase>& thread,
   2300             const sp<Client>& client,
   2301             uint32_t sampleRate,
   2302             int format,
   2303             int channelCount,
   2304             int frameCount,
   2305             uint32_t flags,
   2306             const sp<IMemory>& sharedBuffer)
   2307     :   RefBase(),
   2308         mThread(thread),
   2309         mClient(client),
   2310         mCblk(0),
   2311         mFrameCount(0),
   2312         mState(IDLE),
   2313         mClientTid(-1),
   2314         mFormat(format),
   2315         mFlags(flags & ~SYSTEM_FLAGS_MASK)
   2316 {
   2317     LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
   2318 
   2319     // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
   2320    size_t size = sizeof(audio_track_cblk_t);
   2321    size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
   2322    if (sharedBuffer == 0) {
   2323        size += bufferSize;
   2324    }
   2325 
   2326    if (client != NULL) {
   2327         mCblkMemory = client->heap()->allocate(size);
   2328         if (mCblkMemory != 0) {
   2329             mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
   2330             if (mCblk) { // construct the shared structure in-place.
   2331                 new(mCblk) audio_track_cblk_t();
   2332                 // clear all buffers
   2333                 mCblk->frameCount = frameCount;
   2334                 mCblk->sampleRate = sampleRate;
   2335                 mCblk->channels = (uint8_t)channelCount;
   2336                 if (sharedBuffer == 0) {
   2337                     mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
   2338                     memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
   2339                     // Force underrun condition to avoid false underrun callback until first data is
   2340                     // written to buffer
   2341                     mCblk->flowControlFlag = 1;
   2342                 } else {
   2343                     mBuffer = sharedBuffer->pointer();
   2344                 }
   2345                 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
   2346             }
   2347         } else {
   2348             LOGE("not enough memory for AudioTrack size=%u", size);
   2349             client->heap()->dump("AudioTrack");
   2350             return;
   2351         }
   2352    } else {
   2353        mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
   2354        if (mCblk) { // construct the shared structure in-place.
   2355            new(mCblk) audio_track_cblk_t();
   2356            // clear all buffers
   2357            mCblk->frameCount = frameCount;
   2358            mCblk->sampleRate = sampleRate;
   2359            mCblk->channels = (uint8_t)channelCount;
   2360            mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
   2361            memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
   2362            // Force underrun condition to avoid false underrun callback until first data is
   2363            // written to buffer
   2364            mCblk->flowControlFlag = 1;
   2365            mBufferEnd = (uint8_t *)mBuffer + bufferSize;
   2366        }
   2367    }
   2368 }
   2369 
   2370 AudioFlinger::ThreadBase::TrackBase::~TrackBase()
   2371 {
   2372     if (mCblk) {
   2373         mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
   2374         if (mClient == NULL) {
   2375             delete mCblk;
   2376         }
   2377     }
   2378     mCblkMemory.clear();            // and free the shared memory
   2379     if (mClient != NULL) {
   2380         Mutex::Autolock _l(mClient->audioFlinger()->mLock);
   2381         mClient.clear();
   2382     }
   2383 }
   2384 
   2385 void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
   2386 {
   2387     buffer->raw = 0;
   2388     mFrameCount = buffer->frameCount;
   2389     step();
   2390     buffer->frameCount = 0;
   2391 }
   2392 
   2393 bool AudioFlinger::ThreadBase::TrackBase::step() {
   2394     bool result;
   2395     audio_track_cblk_t* cblk = this->cblk();
   2396 
   2397     result = cblk->stepServer(mFrameCount);
   2398     if (!result) {
   2399         LOGV("stepServer failed acquiring cblk mutex");
   2400         mFlags |= STEPSERVER_FAILED;
   2401     }
   2402     return result;
   2403 }
   2404 
   2405 void AudioFlinger::ThreadBase::TrackBase::reset() {
   2406     audio_track_cblk_t* cblk = this->cblk();
   2407 
   2408     cblk->user = 0;
   2409     cblk->server = 0;
   2410     cblk->userBase = 0;
   2411     cblk->serverBase = 0;
   2412     mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
   2413     LOGV("TrackBase::reset");
   2414 }
   2415 
   2416 sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
   2417 {
   2418     return mCblkMemory;
   2419 }
   2420 
   2421 int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
   2422     return (int)mCblk->sampleRate;
   2423 }
   2424 
   2425 int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
   2426     return (int)mCblk->channels;
   2427 }
   2428 
   2429 void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
   2430     audio_track_cblk_t* cblk = this->cblk();
   2431     int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
   2432     int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
   2433 
   2434     // Check validity of returned pointer in case the track control block would have been corrupted.
   2435     if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
   2436         ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
   2437         LOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
   2438                 server %d, serverBase %d, user %d, userBase %d, channels %d",
   2439                 bufferStart, bufferEnd, mBuffer, mBufferEnd,
   2440                 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
   2441         return 0;
   2442     }
   2443 
   2444     return bufferStart;
   2445 }
   2446 
   2447 // ----------------------------------------------------------------------------
   2448 
   2449 // Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
   2450 AudioFlinger::PlaybackThread::Track::Track(
   2451             const wp<ThreadBase>& thread,
   2452             const sp<Client>& client,
   2453             int streamType,
   2454             uint32_t sampleRate,
   2455             int format,
   2456             int channelCount,
   2457             int frameCount,
   2458             const sp<IMemory>& sharedBuffer)
   2459     :   TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
   2460     mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
   2461 {
   2462     if (mCblk != NULL) {
   2463         sp<ThreadBase> baseThread = thread.promote();
   2464         if (baseThread != 0) {
   2465             PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
   2466             mName = playbackThread->getTrackName_l();
   2467         }
   2468         LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
   2469         if (mName < 0) {
   2470             LOGE("no more track names available");
   2471         }
   2472         mVolume[0] = 1.0f;
   2473         mVolume[1] = 1.0f;
   2474         mStreamType = streamType;
   2475         // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
   2476         // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
   2477         mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
   2478     }
   2479 }
   2480 
   2481 AudioFlinger::PlaybackThread::Track::~Track()
   2482 {
   2483     LOGV("PlaybackThread::Track destructor");
   2484     sp<ThreadBase> thread = mThread.promote();
   2485     if (thread != 0) {
   2486         Mutex::Autolock _l(thread->mLock);
   2487         mState = TERMINATED;
   2488     }
   2489 }
   2490 
   2491 void AudioFlinger::PlaybackThread::Track::destroy()
   2492 {
   2493     // NOTE: destroyTrack_l() can remove a strong reference to this Track
   2494     // by removing it from mTracks vector, so there is a risk that this Tracks's
   2495     // desctructor is called. As the destructor needs to lock mLock,
   2496     // we must acquire a strong reference on this Track before locking mLock
   2497     // here so that the destructor is called only when exiting this function.
   2498     // On the other hand, as long as Track::destroy() is only called by
   2499     // TrackHandle destructor, the TrackHandle still holds a strong ref on
   2500     // this Track with its member mTrack.
   2501     sp<Track> keep(this);
   2502     { // scope for mLock
   2503         sp<ThreadBase> thread = mThread.promote();
   2504         if (thread != 0) {
   2505             if (!isOutputTrack()) {
   2506                 if (mState == ACTIVE || mState == RESUMING) {
   2507                     AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
   2508                 }
   2509                 AudioSystem::releaseOutput(thread->id());
   2510             }
   2511             Mutex::Autolock _l(thread->mLock);
   2512             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
   2513             playbackThread->destroyTrack_l(this);
   2514         }
   2515     }
   2516 }
   2517 
   2518 void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
   2519 {
   2520     snprintf(buffer, size, "  %5d %5d %3u %3u %3u %04u %1d %1d %1d %5u %5u %5u  %08x %08x\n",
   2521             mName - AudioMixer::TRACK0,
   2522             (mClient == NULL) ? getpid() : mClient->pid(),
   2523             mStreamType,
   2524             mFormat,
   2525             mCblk->channels,
   2526             mFrameCount,
   2527             mState,
   2528             mMute,
   2529             mFillingUpStatus,
   2530             mCblk->sampleRate,
   2531             mCblk->volume[0],
   2532             mCblk->volume[1],
   2533             mCblk->server,
   2534             mCblk->user);
   2535 }
   2536 
   2537 status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
   2538 {
   2539      audio_track_cblk_t* cblk = this->cblk();
   2540      uint32_t framesReady;
   2541      uint32_t framesReq = buffer->frameCount;
   2542 
   2543      // Check if last stepServer failed, try to step now
   2544      if (mFlags & TrackBase::STEPSERVER_FAILED) {
   2545          if (!step())  goto getNextBuffer_exit;
   2546          LOGV("stepServer recovered");
   2547          mFlags &= ~TrackBase::STEPSERVER_FAILED;
   2548      }
   2549 
   2550      framesReady = cblk->framesReady();
   2551 
   2552      if (LIKELY(framesReady)) {
   2553         uint32_t s = cblk->server;
   2554         uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
   2555 
   2556         bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
   2557         if (framesReq > framesReady) {
   2558             framesReq = framesReady;
   2559         }
   2560         if (s + framesReq > bufferEnd) {
   2561             framesReq = bufferEnd - s;
   2562         }
   2563 
   2564          buffer->raw = getBuffer(s, framesReq);
   2565          if (buffer->raw == 0) goto getNextBuffer_exit;
   2566 
   2567          buffer->frameCount = framesReq;
   2568         return NO_ERROR;
   2569      }
   2570 
   2571 getNextBuffer_exit:
   2572      buffer->raw = 0;
   2573      buffer->frameCount = 0;
   2574      LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
   2575      return NOT_ENOUGH_DATA;
   2576 }
   2577 
   2578 bool AudioFlinger::PlaybackThread::Track::isReady() const {
   2579     if (mFillingUpStatus != FS_FILLING) return true;
   2580 
   2581     if (mCblk->framesReady() >= mCblk->frameCount ||
   2582         mCblk->forceReady) {
   2583         mFillingUpStatus = FS_FILLED;
   2584         mCblk->forceReady = 0;
   2585         return true;
   2586     }
   2587     return false;
   2588 }
   2589 
   2590 status_t AudioFlinger::PlaybackThread::Track::start()
   2591 {
   2592     status_t status = NO_ERROR;
   2593     LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
   2594     sp<ThreadBase> thread = mThread.promote();
   2595     if (thread != 0) {
   2596         Mutex::Autolock _l(thread->mLock);
   2597         int state = mState;
   2598         // here the track could be either new, or restarted
   2599         // in both cases "unstop" the track
   2600         if (mState == PAUSED) {
   2601             mState = TrackBase::RESUMING;
   2602             LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
   2603         } else {
   2604             mState = TrackBase::ACTIVE;
   2605             LOGV("? => ACTIVE (%d) on thread %p", mName, this);
   2606         }
   2607 
   2608         if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
   2609             thread->mLock.unlock();
   2610             status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
   2611             thread->mLock.lock();
   2612         }
   2613         if (status == NO_ERROR) {
   2614             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
   2615             playbackThread->addTrack_l(this);
   2616         } else {
   2617             mState = state;
   2618         }
   2619     } else {
   2620         status = BAD_VALUE;
   2621     }
   2622     return status;
   2623 }
   2624 
   2625 void AudioFlinger::PlaybackThread::Track::stop()
   2626 {
   2627     LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
   2628     sp<ThreadBase> thread = mThread.promote();
   2629     if (thread != 0) {
   2630         Mutex::Autolock _l(thread->mLock);
   2631         int state = mState;
   2632         if (mState > STOPPED) {
   2633             mState = STOPPED;
   2634             // If the track is not active (PAUSED and buffers full), flush buffers
   2635             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
   2636             if (playbackThread->mActiveTracks.indexOf(this) < 0) {
   2637                 reset();
   2638             }
   2639             LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
   2640         }
   2641         if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
   2642             thread->mLock.unlock();
   2643             AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
   2644             thread->mLock.lock();
   2645         }
   2646     }
   2647 }
   2648 
   2649 void AudioFlinger::PlaybackThread::Track::pause()
   2650 {
   2651     LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
   2652     sp<ThreadBase> thread = mThread.promote();
   2653     if (thread != 0) {
   2654         Mutex::Autolock _l(thread->mLock);
   2655         if (mState == ACTIVE || mState == RESUMING) {
   2656             mState = PAUSING;
   2657             LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
   2658             if (!isOutputTrack()) {
   2659                 thread->mLock.unlock();
   2660                 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
   2661                 thread->mLock.lock();
   2662             }
   2663         }
   2664     }
   2665 }
   2666 
   2667 void AudioFlinger::PlaybackThread::Track::flush()
   2668 {
   2669     LOGV("flush(%d)", mName);
   2670     sp<ThreadBase> thread = mThread.promote();
   2671     if (thread != 0) {
   2672         Mutex::Autolock _l(thread->mLock);
   2673         if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
   2674             return;
   2675         }
   2676         // No point remaining in PAUSED state after a flush => go to
   2677         // STOPPED state
   2678         mState = STOPPED;
   2679 
   2680         mCblk->lock.lock();
   2681         // NOTE: reset() will reset cblk->user and cblk->server with
   2682         // the risk that at the same time, the AudioMixer is trying to read
   2683         // data. In this case, getNextBuffer() would return a NULL pointer
   2684         // as audio buffer => the AudioMixer code MUST always test that pointer
   2685         // returned by getNextBuffer() is not NULL!
   2686         reset();
   2687         mCblk->lock.unlock();
   2688     }
   2689 }
   2690 
   2691 void AudioFlinger::PlaybackThread::Track::reset()
   2692 {
   2693     // Do not reset twice to avoid discarding data written just after a flush and before
   2694     // the audioflinger thread detects the track is stopped.
   2695     if (!mResetDone) {
   2696         TrackBase::reset();
   2697         // Force underrun condition to avoid false underrun callback until first data is
   2698         // written to buffer
   2699         mCblk->flowControlFlag = 1;
   2700         mCblk->forceReady = 0;
   2701         mFillingUpStatus = FS_FILLING;
   2702         mResetDone = true;
   2703     }
   2704 }
   2705 
   2706 void AudioFlinger::PlaybackThread::Track::mute(bool muted)
   2707 {
   2708     mMute = muted;
   2709 }
   2710 
   2711 void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
   2712 {
   2713     mVolume[0] = left;
   2714     mVolume[1] = right;
   2715 }
   2716 
   2717 // ----------------------------------------------------------------------------
   2718 
   2719 // RecordTrack constructor must be called with AudioFlinger::mLock held
   2720 AudioFlinger::RecordThread::RecordTrack::RecordTrack(
   2721             const wp<ThreadBase>& thread,
   2722             const sp<Client>& client,
   2723             uint32_t sampleRate,
   2724             int format,
   2725             int channelCount,
   2726             int frameCount,
   2727             uint32_t flags)
   2728     :   TrackBase(thread, client, sampleRate, format,
   2729                   channelCount, frameCount, flags, 0),
   2730         mOverflow(false)
   2731 {
   2732     if (mCblk != NULL) {
   2733        LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
   2734        if (format == AudioSystem::PCM_16_BIT) {
   2735            mCblk->frameSize = channelCount * sizeof(int16_t);
   2736        } else if (format == AudioSystem::PCM_8_BIT) {
   2737            mCblk->frameSize = channelCount * sizeof(int8_t);
   2738        } else {
   2739            mCblk->frameSize = sizeof(int8_t);
   2740        }
   2741     }
   2742 }
   2743 
   2744 AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
   2745 {
   2746     sp<ThreadBase> thread = mThread.promote();
   2747     if (thread != 0) {
   2748         AudioSystem::releaseInput(thread->id());
   2749     }
   2750 }
   2751 
   2752 status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
   2753 {
   2754     audio_track_cblk_t* cblk = this->cblk();
   2755     uint32_t framesAvail;
   2756     uint32_t framesReq = buffer->frameCount;
   2757 
   2758      // Check if last stepServer failed, try to step now
   2759     if (mFlags & TrackBase::STEPSERVER_FAILED) {
   2760         if (!step()) goto getNextBuffer_exit;
   2761         LOGV("stepServer recovered");
   2762         mFlags &= ~TrackBase::STEPSERVER_FAILED;
   2763     }
   2764 
   2765     framesAvail = cblk->framesAvailable_l();
   2766 
   2767     if (LIKELY(framesAvail)) {
   2768         uint32_t s = cblk->server;
   2769         uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
   2770 
   2771         if (framesReq > framesAvail) {
   2772             framesReq = framesAvail;
   2773         }
   2774         if (s + framesReq > bufferEnd) {
   2775             framesReq = bufferEnd - s;
   2776         }
   2777 
   2778         buffer->raw = getBuffer(s, framesReq);
   2779         if (buffer->raw == 0) goto getNextBuffer_exit;
   2780 
   2781         buffer->frameCount = framesReq;
   2782         return NO_ERROR;
   2783     }
   2784 
   2785 getNextBuffer_exit:
   2786     buffer->raw = 0;
   2787     buffer->frameCount = 0;
   2788     return NOT_ENOUGH_DATA;
   2789 }
   2790 
   2791 status_t AudioFlinger::RecordThread::RecordTrack::start()
   2792 {
   2793     sp<ThreadBase> thread = mThread.promote();
   2794     if (thread != 0) {
   2795         RecordThread *recordThread = (RecordThread *)thread.get();
   2796         return recordThread->start(this);
   2797     } else {
   2798         return BAD_VALUE;
   2799     }
   2800 }
   2801 
   2802 void AudioFlinger::RecordThread::RecordTrack::stop()
   2803 {
   2804     sp<ThreadBase> thread = mThread.promote();
   2805     if (thread != 0) {
   2806         RecordThread *recordThread = (RecordThread *)thread.get();
   2807         recordThread->stop(this);
   2808         TrackBase::reset();
   2809         // Force overerrun condition to avoid false overrun callback until first data is
   2810         // read from buffer
   2811         mCblk->flowControlFlag = 1;
   2812     }
   2813 }
   2814 
   2815 void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
   2816 {
   2817     snprintf(buffer, size, "   %05d %03u %03u %04u %01d %05u  %08x %08x\n",
   2818             (mClient == NULL) ? getpid() : mClient->pid(),
   2819             mFormat,
   2820             mCblk->channels,
   2821             mFrameCount,
   2822             mState,
   2823             mCblk->sampleRate,
   2824             mCblk->server,
   2825             mCblk->user);
   2826 }
   2827 
   2828 
   2829 // ----------------------------------------------------------------------------
   2830 
   2831 AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
   2832             const wp<ThreadBase>& thread,
   2833             DuplicatingThread *sourceThread,
   2834             uint32_t sampleRate,
   2835             int format,
   2836             int channelCount,
   2837             int frameCount)
   2838     :   Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
   2839     mActive(false), mSourceThread(sourceThread)
   2840 {
   2841 
   2842     PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
   2843     if (mCblk != NULL) {
   2844         mCblk->out = 1;
   2845         mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
   2846         mCblk->volume[0] = mCblk->volume[1] = 0x1000;
   2847         mOutBuffer.frameCount = 0;
   2848         playbackThread->mTracks.add(this);
   2849         LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p",
   2850                 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
   2851     } else {
   2852         LOGW("Error creating output track on thread %p", playbackThread);
   2853     }
   2854 }
   2855 
   2856 AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
   2857 {
   2858     clearBufferQueue();
   2859 }
   2860 
   2861 status_t AudioFlinger::PlaybackThread::OutputTrack::start()
   2862 {
   2863     status_t status = Track::start();
   2864     if (status != NO_ERROR) {
   2865         return status;
   2866     }
   2867 
   2868     mActive = true;
   2869     mRetryCount = 127;
   2870     return status;
   2871 }
   2872 
   2873 void AudioFlinger::PlaybackThread::OutputTrack::stop()
   2874 {
   2875     Track::stop();
   2876     clearBufferQueue();
   2877     mOutBuffer.frameCount = 0;
   2878     mActive = false;
   2879 }
   2880 
   2881 bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
   2882 {
   2883     Buffer *pInBuffer;
   2884     Buffer inBuffer;
   2885     uint32_t channels = mCblk->channels;
   2886     bool outputBufferFull = false;
   2887     inBuffer.frameCount = frames;
   2888     inBuffer.i16 = data;
   2889 
   2890     uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
   2891 
   2892     if (!mActive && frames != 0) {
   2893         start();
   2894         sp<ThreadBase> thread = mThread.promote();
   2895         if (thread != 0) {
   2896             MixerThread *mixerThread = (MixerThread *)thread.get();
   2897             if (mCblk->frameCount > frames){
   2898                 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
   2899                     uint32_t startFrames = (mCblk->frameCount - frames);
   2900                     pInBuffer = new Buffer;
   2901                     pInBuffer->mBuffer = new int16_t[startFrames * channels];
   2902                     pInBuffer->frameCount = startFrames;
   2903                     pInBuffer->i16 = pInBuffer->mBuffer;
   2904                     memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
   2905                     mBufferQueue.add(pInBuffer);
   2906                 } else {
   2907                     LOGW ("OutputTrack::write() %p no more buffers in queue", this);
   2908                 }
   2909             }
   2910         }
   2911     }
   2912 
   2913     while (waitTimeLeftMs) {
   2914         // First write pending buffers, then new data
   2915         if (mBufferQueue.size()) {
   2916             pInBuffer = mBufferQueue.itemAt(0);
   2917         } else {
   2918             pInBuffer = &inBuffer;
   2919         }
   2920 
   2921         if (pInBuffer->frameCount == 0) {
   2922             break;
   2923         }
   2924 
   2925         if (mOutBuffer.frameCount == 0) {
   2926             mOutBuffer.frameCount = pInBuffer->frameCount;
   2927             nsecs_t startTime = systemTime();
   2928             if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
   2929                 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
   2930                 outputBufferFull = true;
   2931                 break;
   2932             }
   2933             uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
   2934             if (waitTimeLeftMs >= waitTimeMs) {
   2935                 waitTimeLeftMs -= waitTimeMs;
   2936             } else {
   2937                 waitTimeLeftMs = 0;
   2938             }
   2939         }
   2940 
   2941         uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
   2942         memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
   2943         mCblk->stepUser(outFrames);
   2944         pInBuffer->frameCount -= outFrames;
   2945         pInBuffer->i16 += outFrames * channels;
   2946         mOutBuffer.frameCount -= outFrames;
   2947         mOutBuffer.i16 += outFrames * channels;
   2948 
   2949         if (pInBuffer->frameCount == 0) {
   2950             if (mBufferQueue.size()) {
   2951                 mBufferQueue.removeAt(0);
   2952                 delete [] pInBuffer->mBuffer;
   2953                 delete pInBuffer;
   2954                 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
   2955             } else {
   2956                 break;
   2957             }
   2958         }
   2959     }
   2960 
   2961     // If we could not write all frames, allocate a buffer and queue it for next time.
   2962     if (inBuffer.frameCount) {
   2963         sp<ThreadBase> thread = mThread.promote();
   2964         if (thread != 0 && !thread->standby()) {
   2965             if (mBufferQueue.size() < kMaxOverFlowBuffers) {
   2966                 pInBuffer = new Buffer;
   2967                 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
   2968                 pInBuffer->frameCount = inBuffer.frameCount;
   2969                 pInBuffer->i16 = pInBuffer->mBuffer;
   2970                 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
   2971                 mBufferQueue.add(pInBuffer);
   2972                 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
   2973             } else {
   2974                 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
   2975             }
   2976         }
   2977     }
   2978 
   2979     // Calling write() with a 0 length buffer, means that no more data will be written:
   2980     // If no more buffers are pending, fill output track buffer to make sure it is started
   2981     // by output mixer.
   2982     if (frames == 0 && mBufferQueue.size() == 0) {
   2983         if (mCblk->user < mCblk->frameCount) {
   2984             frames = mCblk->frameCount - mCblk->user;
   2985             pInBuffer = new Buffer;
   2986             pInBuffer->mBuffer = new int16_t[frames * channels];
   2987             pInBuffer->frameCount = frames;
   2988             pInBuffer->i16 = pInBuffer->mBuffer;
   2989             memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
   2990             mBufferQueue.add(pInBuffer);
   2991         } else if (mActive) {
   2992             stop();
   2993         }
   2994     }
   2995 
   2996     return outputBufferFull;
   2997 }
   2998 
   2999 status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
   3000 {
   3001     int active;
   3002     status_t result;
   3003     audio_track_cblk_t* cblk = mCblk;
   3004     uint32_t framesReq = buffer->frameCount;
   3005 
   3006 //    LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
   3007     buffer->frameCount  = 0;
   3008 
   3009     uint32_t framesAvail = cblk->framesAvailable();
   3010 
   3011 
   3012     if (framesAvail == 0) {
   3013         Mutex::Autolock _l(cblk->lock);
   3014         goto start_loop_here;
   3015         while (framesAvail == 0) {
   3016             active = mActive;
   3017             if (UNLIKELY(!active)) {
   3018                 LOGV("Not active and NO_MORE_BUFFERS");
   3019                 return AudioTrack::NO_MORE_BUFFERS;
   3020             }
   3021             result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
   3022             if (result != NO_ERROR) {
   3023                 return AudioTrack::NO_MORE_BUFFERS;
   3024             }
   3025             // read the server count again
   3026         start_loop_here:
   3027             framesAvail = cblk->framesAvailable_l();
   3028         }
   3029     }
   3030 
   3031 //    if (framesAvail < framesReq) {
   3032 //        return AudioTrack::NO_MORE_BUFFERS;
   3033 //    }
   3034 
   3035     if (framesReq > framesAvail) {
   3036         framesReq = framesAvail;
   3037     }
   3038 
   3039     uint32_t u = cblk->user;
   3040     uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
   3041 
   3042     if (u + framesReq > bufferEnd) {
   3043         framesReq = bufferEnd - u;
   3044     }
   3045 
   3046     buffer->frameCount  = framesReq;
   3047     buffer->raw         = (void *)cblk->buffer(u);
   3048     return NO_ERROR;
   3049 }
   3050 
   3051 
   3052 void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
   3053 {
   3054     size_t size = mBufferQueue.size();
   3055     Buffer *pBuffer;
   3056 
   3057     for (size_t i = 0; i < size; i++) {
   3058         pBuffer = mBufferQueue.itemAt(i);
   3059         delete [] pBuffer->mBuffer;
   3060         delete pBuffer;
   3061     }
   3062     mBufferQueue.clear();
   3063 }
   3064 
   3065 // ----------------------------------------------------------------------------
   3066 
   3067 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
   3068     :   RefBase(),
   3069         mAudioFlinger(audioFlinger),
   3070         mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
   3071         mPid(pid)
   3072 {
   3073     // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
   3074 }
   3075 
   3076 // Client destructor must be called with AudioFlinger::mLock held
   3077 AudioFlinger::Client::~Client()
   3078 {
   3079     mAudioFlinger->removeClient_l(mPid);
   3080 }
   3081 
   3082 const sp<MemoryDealer>& AudioFlinger::Client::heap() const
   3083 {
   3084     return mMemoryDealer;
   3085 }
   3086 
   3087 // ----------------------------------------------------------------------------
   3088 
   3089 AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
   3090     : BnAudioTrack(),
   3091       mTrack(track)
   3092 {
   3093 }
   3094 
   3095 AudioFlinger::TrackHandle::~TrackHandle() {
   3096     // just stop the track on deletion, associated resources
   3097     // will be freed from the main thread once all pending buffers have
   3098     // been played. Unless it's not in the active track list, in which
   3099     // case we free everything now...
   3100     mTrack->destroy();
   3101 }
   3102 
   3103 status_t AudioFlinger::TrackHandle::start() {
   3104     return mTrack->start();
   3105 }
   3106 
   3107 void AudioFlinger::TrackHandle::stop() {
   3108     mTrack->stop();
   3109 }
   3110 
   3111 void AudioFlinger::TrackHandle::flush() {
   3112     mTrack->flush();
   3113 }
   3114 
   3115 void AudioFlinger::TrackHandle::mute(bool e) {
   3116     mTrack->mute(e);
   3117 }
   3118 
   3119 void AudioFlinger::TrackHandle::pause() {
   3120     mTrack->pause();
   3121 }
   3122 
   3123 void AudioFlinger::TrackHandle::setVolume(float left, float right) {
   3124     mTrack->setVolume(left, right);
   3125 }
   3126 
   3127 sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
   3128     return mTrack->getCblk();
   3129 }
   3130 
   3131 status_t AudioFlinger::TrackHandle::onTransact(
   3132     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   3133 {
   3134     return BnAudioTrack::onTransact(code, data, reply, flags);
   3135 }
   3136 
   3137 // ----------------------------------------------------------------------------
   3138 
   3139 sp<IAudioRecord> AudioFlinger::openRecord(
   3140         pid_t pid,
   3141         int input,
   3142         uint32_t sampleRate,
   3143         int format,
   3144         int channelCount,
   3145         int frameCount,
   3146         uint32_t flags,
   3147         status_t *status)
   3148 {
   3149     sp<RecordThread::RecordTrack> recordTrack;
   3150     sp<RecordHandle> recordHandle;
   3151     sp<Client> client;
   3152     wp<Client> wclient;
   3153     status_t lStatus;
   3154     RecordThread *thread;
   3155     size_t inFrameCount;
   3156 
   3157     // check calling permissions
   3158     if (!recordingAllowed()) {
   3159         lStatus = PERMISSION_DENIED;
   3160         goto Exit;
   3161     }
   3162 
   3163     // add client to list
   3164     { // scope for mLock
   3165         Mutex::Autolock _l(mLock);
   3166         thread = checkRecordThread_l(input);
   3167         if (thread == NULL) {
   3168             lStatus = BAD_VALUE;
   3169             goto Exit;
   3170         }
   3171 
   3172         wclient = mClients.valueFor(pid);
   3173         if (wclient != NULL) {
   3174             client = wclient.promote();
   3175         } else {
   3176             client = new Client(this, pid);
   3177             mClients.add(pid, client);
   3178         }
   3179 
   3180         // create new record track. The record track uses one track in mHardwareMixerThread by convention.
   3181         recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
   3182                                                    format, channelCount, frameCount, flags);
   3183     }
   3184     if (recordTrack->getCblk() == NULL) {
   3185         // remove local strong reference to Client before deleting the RecordTrack so that the Client
   3186         // destructor is called by the TrackBase destructor with mLock held
   3187         client.clear();
   3188         recordTrack.clear();
   3189         lStatus = NO_MEMORY;
   3190         goto Exit;
   3191     }
   3192 
   3193     // return to handle to client
   3194     recordHandle = new RecordHandle(recordTrack);
   3195     lStatus = NO_ERROR;
   3196 
   3197 Exit:
   3198     if (status) {
   3199         *status = lStatus;
   3200     }
   3201     return recordHandle;
   3202 }
   3203 
   3204 // ----------------------------------------------------------------------------
   3205 
   3206 AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
   3207     : BnAudioRecord(),
   3208     mRecordTrack(recordTrack)
   3209 {
   3210 }
   3211 
   3212 AudioFlinger::RecordHandle::~RecordHandle() {
   3213     stop();
   3214 }
   3215 
   3216 status_t AudioFlinger::RecordHandle::start() {
   3217     LOGV("RecordHandle::start()");
   3218     return mRecordTrack->start();
   3219 }
   3220 
   3221 void AudioFlinger::RecordHandle::stop() {
   3222     LOGV("RecordHandle::stop()");
   3223     mRecordTrack->stop();
   3224 }
   3225 
   3226 sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
   3227     return mRecordTrack->getCblk();
   3228 }
   3229 
   3230 status_t AudioFlinger::RecordHandle::onTransact(
   3231     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   3232 {
   3233     return BnAudioRecord::onTransact(code, data, reply, flags);
   3234 }
   3235 
   3236 // ----------------------------------------------------------------------------
   3237 
   3238 AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
   3239     ThreadBase(audioFlinger, id),
   3240     mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
   3241 {
   3242     mReqChannelCount = AudioSystem::popCount(channels);
   3243     mReqSampleRate = sampleRate;
   3244     readInputParameters();
   3245     sendConfigEvent(AudioSystem::INPUT_OPENED);
   3246 }
   3247 
   3248 
   3249 AudioFlinger::RecordThread::~RecordThread()
   3250 {
   3251     delete[] mRsmpInBuffer;
   3252     if (mResampler != 0) {
   3253         delete mResampler;
   3254         delete[] mRsmpOutBuffer;
   3255     }
   3256 }
   3257 
   3258 void AudioFlinger::RecordThread::onFirstRef()
   3259 {
   3260     const size_t SIZE = 256;
   3261     char buffer[SIZE];
   3262 
   3263     snprintf(buffer, SIZE, "Record Thread %p", this);
   3264 
   3265     run(buffer, PRIORITY_URGENT_AUDIO);
   3266 }
   3267 
   3268 bool AudioFlinger::RecordThread::threadLoop()
   3269 {
   3270     AudioBufferProvider::Buffer buffer;
   3271     sp<RecordTrack> activeTrack;
   3272 
   3273     // start recording
   3274     while (!exitPending()) {
   3275 
   3276         processConfigEvents();
   3277 
   3278         { // scope for mLock
   3279             Mutex::Autolock _l(mLock);
   3280             checkForNewParameters_l();
   3281             if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
   3282                 if (!mStandby) {
   3283                     mInput->standby();
   3284                     mStandby = true;
   3285                 }
   3286 
   3287                 if (exitPending()) break;
   3288 
   3289                 LOGV("RecordThread: loop stopping");
   3290                 // go to sleep
   3291                 mWaitWorkCV.wait(mLock);
   3292                 LOGV("RecordThread: loop starting");
   3293                 continue;
   3294             }
   3295             if (mActiveTrack != 0) {
   3296                 if (mActiveTrack->mState == TrackBase::PAUSING) {
   3297                     if (!mStandby) {
   3298                         mInput->standby();
   3299                         mStandby = true;
   3300                     }
   3301                     mActiveTrack.clear();
   3302                     mStartStopCond.broadcast();
   3303                 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
   3304                     if (mReqChannelCount != mActiveTrack->channelCount()) {
   3305                         mActiveTrack.clear();
   3306                         mStartStopCond.broadcast();
   3307                     } else if (mBytesRead != 0) {
   3308                         // record start succeeds only if first read from audio input
   3309                         // succeeds
   3310                         if (mBytesRead > 0) {
   3311                             mActiveTrack->mState = TrackBase::ACTIVE;
   3312                         } else {
   3313                             mActiveTrack.clear();
   3314                         }
   3315                         mStartStopCond.broadcast();
   3316                     }
   3317                     mStandby = false;
   3318                 }
   3319             }
   3320         }
   3321 
   3322         if (mActiveTrack != 0) {
   3323             if (mActiveTrack->mState != TrackBase::ACTIVE &&
   3324                 mActiveTrack->mState != TrackBase::RESUMING) {
   3325                 usleep(5000);
   3326                 continue;
   3327             }
   3328             buffer.frameCount = mFrameCount;
   3329             if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
   3330                 size_t framesOut = buffer.frameCount;
   3331                 if (mResampler == 0) {
   3332                     // no resampling
   3333                     while (framesOut) {
   3334                         size_t framesIn = mFrameCount - mRsmpInIndex;
   3335                         if (framesIn) {
   3336                             int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
   3337                             int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
   3338                             if (framesIn > framesOut)
   3339                                 framesIn = framesOut;
   3340                             mRsmpInIndex += framesIn;
   3341                             framesOut -= framesIn;
   3342                             if (mChannelCount == mReqChannelCount ||
   3343                                 mFormat != AudioSystem::PCM_16_BIT) {
   3344                                 memcpy(dst, src, framesIn * mFrameSize);
   3345                             } else {
   3346                                 int16_t *src16 = (int16_t *)src;
   3347                                 int16_t *dst16 = (int16_t *)dst;
   3348                                 if (mChannelCount == 1) {
   3349                                     while (framesIn--) {
   3350                                         *dst16++ = *src16;
   3351                                         *dst16++ = *src16++;
   3352                                     }
   3353                                 } else {
   3354                                     while (framesIn--) {
   3355                                         *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
   3356                                         src16 += 2;
   3357                                     }
   3358                                 }
   3359                             }
   3360                         }
   3361                         if (framesOut && mFrameCount == mRsmpInIndex) {
   3362                             if (framesOut == mFrameCount &&
   3363                                 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
   3364                                 mBytesRead = mInput->read(buffer.raw, mInputBytes);
   3365                                 framesOut = 0;
   3366                             } else {
   3367                                 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
   3368                                 mRsmpInIndex = 0;
   3369                             }
   3370                             if (mBytesRead < 0) {
   3371                                 LOGE("Error reading audio input");
   3372                                 if (mActiveTrack->mState == TrackBase::ACTIVE) {
   3373                                     // Force input into standby so that it tries to
   3374                                     // recover at next read attempt
   3375                                     mInput->standby();
   3376                                     usleep(5000);
   3377                                 }
   3378                                 mRsmpInIndex = mFrameCount;
   3379                                 framesOut = 0;
   3380                                 buffer.frameCount = 0;
   3381                             }
   3382                         }
   3383                     }
   3384                 } else {
   3385                     // resampling
   3386 
   3387                     memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
   3388                     // alter output frame count as if we were expecting stereo samples
   3389                     if (mChannelCount == 1 && mReqChannelCount == 1) {
   3390                         framesOut >>= 1;
   3391                     }
   3392                     mResampler->resample(mRsmpOutBuffer, framesOut, this);
   3393                     // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
   3394                     // are 32 bit aligned which should be always true.
   3395                     if (mChannelCount == 2 && mReqChannelCount == 1) {
   3396                         AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
   3397                         // the resampler always outputs stereo samples: do post stereo to mono conversion
   3398                         int16_t *src = (int16_t *)mRsmpOutBuffer;
   3399                         int16_t *dst = buffer.i16;
   3400                         while (framesOut--) {
   3401                             *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
   3402                             src += 2;
   3403                         }
   3404                     } else {
   3405                         AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
   3406                     }
   3407 
   3408                 }
   3409                 mActiveTrack->releaseBuffer(&buffer);
   3410                 mActiveTrack->overflow();
   3411             }
   3412             // client isn't retrieving buffers fast enough
   3413             else {
   3414                 if (!mActiveTrack->setOverflow())
   3415                     LOGW("RecordThread: buffer overflow");
   3416                 // Release the processor for a while before asking for a new buffer.
   3417                 // This will give the application more chance to read from the buffer and
   3418                 // clear the overflow.
   3419                 usleep(5000);
   3420             }
   3421         }
   3422     }
   3423 
   3424     if (!mStandby) {
   3425         mInput->standby();
   3426     }
   3427     mActiveTrack.clear();
   3428 
   3429     mStartStopCond.broadcast();
   3430 
   3431     LOGV("RecordThread %p exiting", this);
   3432     return false;
   3433 }
   3434 
   3435 status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
   3436 {
   3437     LOGV("RecordThread::start");
   3438     sp <ThreadBase> strongMe = this;
   3439     status_t status = NO_ERROR;
   3440     {
   3441         AutoMutex lock(&mLock);
   3442         if (mActiveTrack != 0) {
   3443             if (recordTrack != mActiveTrack.get()) {
   3444                 status = -EBUSY;
   3445             } else if (mActiveTrack->mState == TrackBase::PAUSING) {
   3446                 mActiveTrack->mState = TrackBase::ACTIVE;
   3447             }
   3448             return status;
   3449         }
   3450 
   3451         recordTrack->mState = TrackBase::IDLE;
   3452         mActiveTrack = recordTrack;
   3453         mLock.unlock();
   3454         status_t status = AudioSystem::startInput(mId);
   3455         mLock.lock();
   3456         if (status != NO_ERROR) {
   3457             mActiveTrack.clear();
   3458             return status;
   3459         }
   3460         mActiveTrack->mState = TrackBase::RESUMING;
   3461         mRsmpInIndex = mFrameCount;
   3462         mBytesRead = 0;
   3463         // signal thread to start
   3464         LOGV("Signal record thread");
   3465         mWaitWorkCV.signal();
   3466         // do not wait for mStartStopCond if exiting
   3467         if (mExiting) {
   3468             mActiveTrack.clear();
   3469             status = INVALID_OPERATION;
   3470             goto startError;
   3471         }
   3472         mStartStopCond.wait(mLock);
   3473         if (mActiveTrack == 0) {
   3474             LOGV("Record failed to start");
   3475             status = BAD_VALUE;
   3476             goto startError;
   3477         }
   3478         LOGV("Record started OK");
   3479         return status;
   3480     }
   3481 startError:
   3482     AudioSystem::stopInput(mId);
   3483     return status;
   3484 }
   3485 
   3486 void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
   3487     LOGV("RecordThread::stop");
   3488     sp <ThreadBase> strongMe = this;
   3489     {
   3490         AutoMutex lock(&mLock);
   3491         if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
   3492             mActiveTrack->mState = TrackBase::PAUSING;
   3493             // do not wait for mStartStopCond if exiting
   3494             if (mExiting) {
   3495                 return;
   3496             }
   3497             mStartStopCond.wait(mLock);
   3498             // if we have been restarted, recordTrack == mActiveTrack.get() here
   3499             if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
   3500                 mLock.unlock();
   3501                 AudioSystem::stopInput(mId);
   3502                 mLock.lock();
   3503                 LOGV("Record stopped OK");
   3504             }
   3505         }
   3506     }
   3507 }
   3508 
   3509 status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
   3510 {
   3511     const size_t SIZE = 256;
   3512     char buffer[SIZE];
   3513     String8 result;
   3514     pid_t pid = 0;
   3515 
   3516     snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
   3517     result.append(buffer);
   3518 
   3519     if (mActiveTrack != 0) {
   3520         result.append("Active Track:\n");
   3521         result.append("   Clien Fmt Chn Buf  S SRate  Serv     User\n");
   3522         mActiveTrack->dump(buffer, SIZE);
   3523         result.append(buffer);
   3524 
   3525         snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
   3526         result.append(buffer);
   3527         snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
   3528         result.append(buffer);
   3529         snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
   3530         result.append(buffer);
   3531         snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
   3532         result.append(buffer);
   3533         snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
   3534         result.append(buffer);
   3535 
   3536 
   3537     } else {
   3538         result.append("No record client\n");
   3539     }
   3540     write(fd, result.string(), result.size());
   3541 
   3542     dumpBase(fd, args);
   3543 
   3544     return NO_ERROR;
   3545 }
   3546 
   3547 status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
   3548 {
   3549     size_t framesReq = buffer->frameCount;
   3550     size_t framesReady = mFrameCount - mRsmpInIndex;
   3551     int channelCount;
   3552 
   3553     if (framesReady == 0) {
   3554         mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
   3555         if (mBytesRead < 0) {
   3556             LOGE("RecordThread::getNextBuffer() Error reading audio input");
   3557             if (mActiveTrack->mState == TrackBase::ACTIVE) {
   3558                 // Force input into standby so that it tries to
   3559                 // recover at next read attempt
   3560                 mInput->standby();
   3561                 usleep(5000);
   3562             }
   3563             buffer->raw = 0;
   3564             buffer->frameCount = 0;
   3565             return NOT_ENOUGH_DATA;
   3566         }
   3567         mRsmpInIndex = 0;
   3568         framesReady = mFrameCount;
   3569     }
   3570 
   3571     if (framesReq > framesReady) {
   3572         framesReq = framesReady;
   3573     }
   3574 
   3575     if (mChannelCount == 1 && mReqChannelCount == 2) {
   3576         channelCount = 1;
   3577     } else {
   3578         channelCount = 2;
   3579     }
   3580     buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
   3581     buffer->frameCount = framesReq;
   3582     return NO_ERROR;
   3583 }
   3584 
   3585 void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
   3586 {
   3587     mRsmpInIndex += buffer->frameCount;
   3588     buffer->frameCount = 0;
   3589 }
   3590 
   3591 bool AudioFlinger::RecordThread::checkForNewParameters_l()
   3592 {
   3593     bool reconfig = false;
   3594 
   3595     while (!mNewParameters.isEmpty()) {
   3596         status_t status = NO_ERROR;
   3597         String8 keyValuePair = mNewParameters[0];
   3598         AudioParameter param = AudioParameter(keyValuePair);
   3599         int value;
   3600         int reqFormat = mFormat;
   3601         int reqSamplingRate = mReqSampleRate;
   3602         int reqChannelCount = mReqChannelCount;
   3603 
   3604         if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
   3605             reqSamplingRate = value;
   3606             reconfig = true;
   3607         }
   3608         if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
   3609             reqFormat = value;
   3610             reconfig = true;
   3611         }
   3612         if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
   3613             reqChannelCount = AudioSystem::popCount(value);
   3614             reconfig = true;
   3615         }
   3616         if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
   3617             // do not accept frame count changes if tracks are open as the track buffer
   3618             // size depends on frame count and correct behavior would not be garantied
   3619             // if frame count is changed after track creation
   3620             if (mActiveTrack != 0) {
   3621                 status = INVALID_OPERATION;
   3622             } else {
   3623                 reconfig = true;
   3624             }
   3625         }
   3626         if (status == NO_ERROR) {
   3627             status = mInput->setParameters(keyValuePair);
   3628             if (status == INVALID_OPERATION) {
   3629                mInput->standby();
   3630                status = mInput->setParameters(keyValuePair);
   3631             }
   3632             if (reconfig) {
   3633                 if (status == BAD_VALUE &&
   3634                     reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
   3635                     ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
   3636                     (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
   3637                     status = NO_ERROR;
   3638                 }
   3639                 if (status == NO_ERROR) {
   3640                     readInputParameters();
   3641                     sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
   3642                 }
   3643             }
   3644         }
   3645 
   3646         mNewParameters.removeAt(0);
   3647 
   3648         mParamStatus = status;
   3649         mParamCond.signal();
   3650         mWaitWorkCV.wait(mLock);
   3651     }
   3652     return reconfig;
   3653 }
   3654 
   3655 String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
   3656 {
   3657     return mInput->getParameters(keys);
   3658 }
   3659 
   3660 void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
   3661     AudioSystem::OutputDescriptor desc;
   3662     void *param2 = 0;
   3663 
   3664     switch (event) {
   3665     case AudioSystem::INPUT_OPENED:
   3666     case AudioSystem::INPUT_CONFIG_CHANGED:
   3667         desc.channels = mChannelCount;
   3668         desc.samplingRate = mSampleRate;
   3669         desc.format = mFormat;
   3670         desc.frameCount = mFrameCount;
   3671         desc.latency = 0;
   3672         param2 = &desc;
   3673         break;
   3674 
   3675     case AudioSystem::INPUT_CLOSED:
   3676     default:
   3677         break;
   3678     }
   3679     Mutex::Autolock _l(mAudioFlinger->mLock);
   3680     mAudioFlinger->audioConfigChanged_l(event, mId, param2);
   3681 }
   3682 
   3683 void AudioFlinger::RecordThread::readInputParameters()
   3684 {
   3685     if (mRsmpInBuffer) delete mRsmpInBuffer;
   3686     if (mRsmpOutBuffer) delete mRsmpOutBuffer;
   3687     if (mResampler) delete mResampler;
   3688     mResampler = 0;
   3689 
   3690     mSampleRate = mInput->sampleRate();
   3691     mChannelCount = AudioSystem::popCount(mInput->channels());
   3692     mFormat = mInput->format();
   3693     mFrameSize = mInput->frameSize();
   3694     mInputBytes = mInput->bufferSize();
   3695     mFrameCount = mInputBytes / mFrameSize;
   3696     mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
   3697 
   3698     if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
   3699     {
   3700         int channelCount;
   3701          // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
   3702          // stereo to mono post process as the resampler always outputs stereo.
   3703         if (mChannelCount == 1 && mReqChannelCount == 2) {
   3704             channelCount = 1;
   3705         } else {
   3706             channelCount = 2;
   3707         }
   3708         mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
   3709         mResampler->setSampleRate(mSampleRate);
   3710         mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
   3711         mRsmpOutBuffer = new int32_t[mFrameCount * 2];
   3712 
   3713         // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
   3714         if (mChannelCount == 1 && mReqChannelCount == 1) {
   3715             mFrameCount >>= 1;
   3716         }
   3717 
   3718     }
   3719     mRsmpInIndex = mFrameCount;
   3720 }
   3721 
   3722 unsigned int AudioFlinger::RecordThread::getInputFramesLost()
   3723 {
   3724     return mInput->getInputFramesLost();
   3725 }
   3726 
   3727 // ----------------------------------------------------------------------------
   3728 
   3729 int AudioFlinger::openOutput(uint32_t *pDevices,
   3730                                 uint32_t *pSamplingRate,
   3731                                 uint32_t *pFormat,
   3732                                 uint32_t *pChannels,
   3733                                 uint32_t *pLatencyMs,
   3734                                 uint32_t flags)
   3735 {
   3736     status_t status;
   3737     PlaybackThread *thread = NULL;
   3738     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
   3739     uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
   3740     uint32_t format = pFormat ? *pFormat : 0;
   3741     uint32_t channels = pChannels ? *pChannels : 0;
   3742     uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
   3743 
   3744     LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
   3745             pDevices ? *pDevices : 0,
   3746             samplingRate,
   3747             format,
   3748             channels,
   3749             flags);
   3750 
   3751     if (pDevices == NULL || *pDevices == 0) {
   3752         return 0;
   3753     }
   3754     Mutex::Autolock _l(mLock);
   3755 
   3756     AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
   3757                                                              (int *)&format,
   3758                                                              &channels,
   3759                                                              &samplingRate,
   3760                                                              &status);
   3761     LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
   3762             output,
   3763             samplingRate,
   3764             format,
   3765             channels,
   3766             status);
   3767 
   3768     mHardwareStatus = AUDIO_HW_IDLE;
   3769     if (output != 0) {
   3770         if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
   3771             (format != AudioSystem::PCM_16_BIT) ||
   3772             (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
   3773             thread = new DirectOutputThread(this, output, ++mNextThreadId);
   3774             LOGV("openOutput() created direct output: ID %d thread %p", mNextThreadId, thread);
   3775         } else {
   3776             thread = new MixerThread(this, output, ++mNextThreadId);
   3777             LOGV("openOutput() created mixer output: ID %d thread %p", mNextThreadId, thread);
   3778 
   3779 #ifdef LVMX
   3780             unsigned bitsPerSample =
   3781                 (format == AudioSystem::PCM_16_BIT) ? 16 :
   3782                     ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
   3783             unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
   3784             int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
   3785 
   3786             LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
   3787             LifeVibes::setDevice(audioOutputType, *pDevices);
   3788 #endif
   3789 
   3790         }
   3791         mPlaybackThreads.add(mNextThreadId, thread);
   3792 
   3793         if (pSamplingRate) *pSamplingRate = samplingRate;
   3794         if (pFormat) *pFormat = format;
   3795         if (pChannels) *pChannels = channels;
   3796         if (pLatencyMs) *pLatencyMs = thread->latency();
   3797 
   3798         return mNextThreadId;
   3799     }
   3800 
   3801     return 0;
   3802 }
   3803 
   3804 int AudioFlinger::openDuplicateOutput(int output1, int output2)
   3805 {
   3806     Mutex::Autolock _l(mLock);
   3807     MixerThread *thread1 = checkMixerThread_l(output1);
   3808     MixerThread *thread2 = checkMixerThread_l(output2);
   3809 
   3810     if (thread1 == NULL || thread2 == NULL) {
   3811         LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
   3812         return 0;
   3813     }
   3814 
   3815 
   3816     DuplicatingThread *thread = new DuplicatingThread(this, thread1, ++mNextThreadId);
   3817     thread->addOutputTrack(thread2);
   3818     mPlaybackThreads.add(mNextThreadId, thread);
   3819     return mNextThreadId;
   3820 }
   3821 
   3822 status_t AudioFlinger::closeOutput(int output)
   3823 {
   3824     // keep strong reference on the playback thread so that
   3825     // it is not destroyed while exit() is executed
   3826     sp <PlaybackThread> thread;
   3827     {
   3828         Mutex::Autolock _l(mLock);
   3829         thread = checkPlaybackThread_l(output);
   3830         if (thread == NULL) {
   3831             return BAD_VALUE;
   3832         }
   3833 
   3834         LOGV("closeOutput() %d", output);
   3835 
   3836         if (thread->type() == PlaybackThread::MIXER) {
   3837             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3838                 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
   3839                     DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
   3840                     dupThread->removeOutputTrack((MixerThread *)thread.get());
   3841                 }
   3842             }
   3843         }
   3844         void *param2 = 0;
   3845         audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
   3846         mPlaybackThreads.removeItem(output);
   3847     }
   3848     thread->exit();
   3849 
   3850     if (thread->type() != PlaybackThread::DUPLICATING) {
   3851         mAudioHardware->closeOutputStream(thread->getOutput());
   3852     }
   3853     return NO_ERROR;
   3854 }
   3855 
   3856 status_t AudioFlinger::suspendOutput(int output)
   3857 {
   3858     Mutex::Autolock _l(mLock);
   3859     PlaybackThread *thread = checkPlaybackThread_l(output);
   3860 
   3861     if (thread == NULL) {
   3862         return BAD_VALUE;
   3863     }
   3864 
   3865     LOGV("suspendOutput() %d", output);
   3866     thread->suspend();
   3867 
   3868     return NO_ERROR;
   3869 }
   3870 
   3871 status_t AudioFlinger::restoreOutput(int output)
   3872 {
   3873     Mutex::Autolock _l(mLock);
   3874     PlaybackThread *thread = checkPlaybackThread_l(output);
   3875 
   3876     if (thread == NULL) {
   3877         return BAD_VALUE;
   3878     }
   3879 
   3880     LOGV("restoreOutput() %d", output);
   3881 
   3882     thread->restore();
   3883 
   3884     return NO_ERROR;
   3885 }
   3886 
   3887 int AudioFlinger::openInput(uint32_t *pDevices,
   3888                                 uint32_t *pSamplingRate,
   3889                                 uint32_t *pFormat,
   3890                                 uint32_t *pChannels,
   3891                                 uint32_t acoustics)
   3892 {
   3893     status_t status;
   3894     RecordThread *thread = NULL;
   3895     uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
   3896     uint32_t format = pFormat ? *pFormat : 0;
   3897     uint32_t channels = pChannels ? *pChannels : 0;
   3898     uint32_t reqSamplingRate = samplingRate;
   3899     uint32_t reqFormat = format;
   3900     uint32_t reqChannels = channels;
   3901 
   3902     if (pDevices == NULL || *pDevices == 0) {
   3903         return 0;
   3904     }
   3905     Mutex::Autolock _l(mLock);
   3906 
   3907     AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
   3908                                                              (int *)&format,
   3909                                                              &channels,
   3910                                                              &samplingRate,
   3911                                                              &status,
   3912                                                              (AudioSystem::audio_in_acoustics)acoustics);
   3913     LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
   3914             input,
   3915             samplingRate,
   3916             format,
   3917             channels,
   3918             acoustics,
   3919             status);
   3920 
   3921     // If the input could not be opened with the requested parameters and we can handle the conversion internally,
   3922     // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
   3923     // or stereo to mono conversions on 16 bit PCM inputs.
   3924     if (input == 0 && status == BAD_VALUE &&
   3925         reqFormat == format && format == AudioSystem::PCM_16_BIT &&
   3926         (samplingRate <= 2 * reqSamplingRate) &&
   3927         (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
   3928         LOGV("openInput() reopening with proposed sampling rate and channels");
   3929         input = mAudioHardware->openInputStream(*pDevices,
   3930                                                  (int *)&format,
   3931                                                  &channels,
   3932                                                  &samplingRate,
   3933                                                  &status,
   3934                                                  (AudioSystem::audio_in_acoustics)acoustics);
   3935     }
   3936 
   3937     if (input != 0) {
   3938          // Start record thread
   3939         thread = new RecordThread(this, input, reqSamplingRate, reqChannels, ++mNextThreadId);
   3940         mRecordThreads.add(mNextThreadId, thread);
   3941         LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
   3942         if (pSamplingRate) *pSamplingRate = reqSamplingRate;
   3943         if (pFormat) *pFormat = format;
   3944         if (pChannels) *pChannels = reqChannels;
   3945 
   3946         input->standby();
   3947 
   3948         return mNextThreadId;
   3949     }
   3950 
   3951     return 0;
   3952 }
   3953 
   3954 status_t AudioFlinger::closeInput(int input)
   3955 {
   3956     // keep strong reference on the record thread so that
   3957     // it is not destroyed while exit() is executed
   3958     sp <RecordThread> thread;
   3959     {
   3960         Mutex::Autolock _l(mLock);
   3961         thread = checkRecordThread_l(input);
   3962         if (thread == NULL) {
   3963             return BAD_VALUE;
   3964         }
   3965 
   3966         LOGV("closeInput() %d", input);
   3967         void *param2 = 0;
   3968         audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
   3969         mRecordThreads.removeItem(input);
   3970     }
   3971     thread->exit();
   3972 
   3973     mAudioHardware->closeInputStream(thread->getInput());
   3974 
   3975     return NO_ERROR;
   3976 }
   3977 
   3978 status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
   3979 {
   3980     Mutex::Autolock _l(mLock);
   3981     MixerThread *dstThread = checkMixerThread_l(output);
   3982     if (dstThread == NULL) {
   3983         LOGW("setStreamOutput() bad output id %d", output);
   3984         return BAD_VALUE;
   3985     }
   3986 
   3987     LOGV("setStreamOutput() stream %d to output %d", stream, output);
   3988 
   3989     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3990         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
   3991         if (thread != dstThread &&
   3992             thread->type() != PlaybackThread::DIRECT) {
   3993             MixerThread *srcThread = (MixerThread *)thread;
   3994             SortedVector < sp<MixerThread::Track> > tracks;
   3995             SortedVector < wp<MixerThread::Track> > activeTracks;
   3996             srcThread->getTracks(tracks, activeTracks, stream);
   3997             if (tracks.size()) {
   3998                 dstThread->putTracks(tracks, activeTracks);
   3999             }
   4000         }
   4001     }
   4002 
   4003     dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
   4004 
   4005     return NO_ERROR;
   4006 }
   4007 
   4008 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
   4009 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
   4010 {
   4011     PlaybackThread *thread = NULL;
   4012     if (mPlaybackThreads.indexOfKey(output) >= 0) {
   4013         thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
   4014     }
   4015     return thread;
   4016 }
   4017 
   4018 // checkMixerThread_l() must be called with AudioFlinger::mLock held
   4019 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
   4020 {
   4021     PlaybackThread *thread = checkPlaybackThread_l(output);
   4022     if (thread != NULL) {
   4023         if (thread->type() == PlaybackThread::DIRECT) {
   4024             thread = NULL;
   4025         }
   4026     }
   4027     return (MixerThread *)thread;
   4028 }
   4029 
   4030 // checkRecordThread_l() must be called with AudioFlinger::mLock held
   4031 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
   4032 {
   4033     RecordThread *thread = NULL;
   4034     if (mRecordThreads.indexOfKey(input) >= 0) {
   4035         thread = (RecordThread *)mRecordThreads.valueFor(input).get();
   4036     }
   4037     return thread;
   4038 }
   4039 
   4040 // ----------------------------------------------------------------------------
   4041 
   4042 status_t AudioFlinger::onTransact(
   4043         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   4044 {
   4045     return BnAudioFlinger::onTransact(code, data, reply, flags);
   4046 }
   4047 
   4048 // ----------------------------------------------------------------------------
   4049 
   4050 void AudioFlinger::instantiate() {
   4051     defaultServiceManager()->addService(
   4052             String16("media.audio_flinger"), new AudioFlinger());
   4053 }
   4054 
   4055 }; // namespace android
   4056