Home | History | Annotate | Download | only in libaudio
      1 /*
      2 ** Copyright 2008-2010, The Android Open-Source Project
      3 **
      4 ** Licensed under the Apache License, Version 2.0 (the "License");
      5 ** you may not use this file except in compliance with the License.
      6 ** You may obtain a copy of the License at
      7 **
      8 **     http://www.apache.org/licenses/LICENSE-2.0
      9 **
     10 ** Unless required by applicable law or agreed to in writing, software
     11 ** distributed under the License is distributed on an "AS IS" BASIS,
     12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13 ** See the License for the specific language governing permissions and
     14 ** limitations under the License.
     15 */
     16 
     17 #include <math.h>
     18 
     19 //#define LOG_NDEBUG 0
     20 #define LOG_TAG "AudioHardwareTegra"
     21 #include <utils/Log.h>
     22 #include <utils/String8.h>
     23 
     24 #include <stdio.h>
     25 #include <unistd.h>
     26 #include <sys/ioctl.h>
     27 #include <sys/types.h>
     28 #include <sys/stat.h>
     29 #include <dlfcn.h>
     30 #include <fcntl.h>
     31 
     32 #include "AudioHardware.h"
     33 #include <media/AudioRecord.h>
     34 #include <audio_effects/effect_aec.h>
     35 #include <audio_effects/effect_ns.h>
     36 
     37 namespace android_audio_legacy {
     38 const uint32_t AudioHardware::inputSamplingRates[] = {
     39     8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000
     40 };
     41 
     42 // number of times to attempt init() before giving up
     43 const uint32_t MAX_INIT_TRIES = 10;
     44 
     45 // When another thread wants to acquire the Mutex on the input or output stream, a short sleep
     46 // period is forced in the read or write function to release the processor before acquiring the
     47 // Mutex. Otherwise, as the read/write thread sleeps most of the time waiting for DMA buffers with
     48 // the Mutex locked, the other thread could wait quite long before being able to acquire the Mutex.
     49 #define FORCED_SLEEP_TIME_US  10000
     50 
     51 // ----------------------------------------------------------------------------
     52 
     53 // always succeeds, must call init() immediately after
     54 AudioHardware::AudioHardware() :
     55     mInit(false), mMicMute(false), mBluetoothNrec(true), mBluetoothId(0),
     56     mOutput(0), /*mCurOut/InDevice*/ mCpcapCtlFd(-1), mHwOutRate(0), mHwInRate(0),
     57     mMasterVol(1.0), mVoiceVol(1.0),
     58     /*mCpcapGain*/
     59     mSpkrVolume(-1), mMicVolume(-1), mEcnsEnabled(0), mEcnsRequested(0), mBtScoOn(false)
     60 {
     61     LOGV("AudioHardware constructor");
     62 }
     63 
     64 // designed to be called multiple times for retries
     65 status_t AudioHardware::init() {
     66 
     67     if (mInit) {
     68         return NO_ERROR;
     69     }
     70 
     71     mCpcapCtlFd = ::open("/dev/audio_ctl", O_RDWR);
     72     if (mCpcapCtlFd < 0) {
     73         LOGE("open /dev/audio_ctl failed: %s", strerror(errno));
     74         goto error;
     75     }
     76 
     77     if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_OUT_GET_OUTPUT, &mCurOutDevice) < 0) {
     78         LOGE("could not get output device: %s", strerror(errno));
     79         goto error;
     80     }
     81     if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_IN_GET_INPUT, &mCurInDevice) < 0) {
     82         LOGE("could not get input device: %s", strerror(errno));
     83         goto error;
     84     }
     85     // For bookkeeping only
     86     if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_OUT_GET_RATE, &mHwOutRate) < 0) {
     87         LOGE("could not get output rate: %s", strerror(errno));
     88         goto error;
     89     }
     90     if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_IN_GET_RATE, &mHwInRate) < 0) {
     91         LOGE("could not get input rate: %s", strerror(errno));
     92         goto error;
     93     }
     94 
     95 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
     96     // Init the MM Audio Post Processing
     97     mAudioPP.setAudioDev(&mCurOutDevice, &mCurInDevice, false, false, false);
     98 #endif
     99 
    100     readHwGainFile();
    101 
    102     mInit = true;
    103     return NO_ERROR;
    104 
    105 error:
    106     if (mCpcapCtlFd >= 0) {
    107         (void) ::close(mCpcapCtlFd);
    108         mCpcapCtlFd = -1;
    109     }
    110     return NO_INIT;
    111 }
    112 
    113 AudioHardware::~AudioHardware()
    114 {
    115     LOGV("AudioHardware destructor");
    116     for (size_t index = 0; index < mInputs.size(); index++) {
    117         closeInputStream((AudioStreamIn*)mInputs[index]);
    118     }
    119     mInputs.clear();
    120     closeOutputStream((AudioStreamOut*)mOutput);
    121     if (mCpcapCtlFd >= 0) {
    122         (void) ::close(mCpcapCtlFd);
    123         mCpcapCtlFd = -1;
    124     }
    125 }
    126 
    127 void AudioHardware::readHwGainFile()
    128 {
    129     int fd;
    130     int rc=0;
    131     int i;
    132     uint32_t format, version, barker;
    133     fd = open("/system/etc/cpcap_gain.bin", O_RDONLY);
    134     if (fd>=0) {
    135         ::read(fd, &format, sizeof(uint32_t));
    136         ::read(fd, &version, sizeof(uint32_t));
    137         ::read(fd, &barker, sizeof(uint32_t));
    138         rc = ::read(fd, mCpcapGain, sizeof(mCpcapGain));
    139         LOGD("Read gain file, format %X version %X", format, version);
    140         ::close(fd);
    141     }
    142     if (rc != sizeof(mCpcapGain) || format != 0x30303032) {
    143         int gain;
    144         LOGE("CPCAP gain file not valid. Using defaults.");
    145         for (int i=0; i<AUDIO_HW_GAIN_NUM_DIRECTIONS; i++) {
    146             if (i==AUDIO_HW_GAIN_SPKR_GAIN)
    147                 gain = 11;
    148             else
    149                 gain = 31;
    150             for (int j=0; j<AUDIO_HW_GAIN_NUM_USECASES; j++)
    151                 for (int k=0; k<AUDIO_HW_GAIN_NUM_PATHS; k++)
    152                     mCpcapGain[i][j][k]=gain;
    153         }
    154     }
    155     return;
    156 }
    157 
    158 status_t AudioHardware::initCheck()
    159 {
    160     return mInit ? NO_ERROR : NO_INIT;
    161 }
    162 
    163 AudioStreamOut* AudioHardware::openOutputStream(
    164         uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
    165 {
    166     { // scope for the lock
    167         Mutex::Autolock lock(mLock);
    168 
    169         // only one output stream allowed
    170         if (mOutput) {
    171             if (status) {
    172                 *status = INVALID_OPERATION;
    173             }
    174             return 0;
    175         }
    176 
    177         // create new output stream
    178         AudioStreamOutTegra* out = new AudioStreamOutTegra();
    179         for (unsigned tries = 0; tries < MAX_INIT_TRIES; ++tries) {
    180             if (NO_ERROR == out->init())
    181                 break;
    182             LOGW("AudioStreamOutTegra::init failed soft, retrying");
    183             sleep(1);
    184         }
    185         status_t lStatus;
    186         lStatus = out->initCheck();
    187         if (NO_ERROR != lStatus) {
    188             LOGE("AudioStreamOutTegra::init failed hard");
    189         } else {
    190             lStatus = out->set(this, devices, format, channels, sampleRate);
    191         }
    192         if (status) {
    193             *status = lStatus;
    194         }
    195         if (lStatus == NO_ERROR) {
    196             mOutput = out;
    197         } else {
    198             mLock.unlock();
    199             delete out;
    200             out = NULL;
    201             mLock.lock();
    202         }
    203     }
    204     return mOutput;
    205 }
    206 
    207 void AudioHardware::closeOutputStream(AudioStreamOut* out) {
    208     Mutex::Autolock lock(mLock);
    209     if (mOutput == 0 || mOutput != out) {
    210         LOGW("Attempt to close invalid output stream");
    211     }
    212     else {
    213         // AudioStreamOutTegra destructor calls standby which locks
    214         mOutput = 0;
    215         mLock.unlock();
    216         delete out;
    217         mLock.lock();
    218     }
    219 }
    220 
    221 AudioStreamIn* AudioHardware::openInputStream(
    222         uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status,
    223         AudioSystem::audio_in_acoustics acoustic_flags)
    224 {
    225     // check for valid input source
    226     if (!AudioSystem::isInputDevice((AudioSystem::audio_devices)devices)) {
    227         return 0;
    228     }
    229 
    230     Mutex::Autolock lock(mLock);
    231 
    232     AudioStreamInTegra* in = new AudioStreamInTegra();
    233     // this serves a similar purpose as init()
    234     status_t lStatus = in->set(this, devices, format, channels, sampleRate, acoustic_flags);
    235     if (status) {
    236         *status = lStatus;
    237     }
    238     if (lStatus != NO_ERROR) {
    239         mLock.unlock();
    240         delete in;
    241         mLock.lock();
    242         return 0;
    243     }
    244 
    245     mInputs.add(in);
    246 
    247     return in;
    248 }
    249 
    250 void AudioHardware::closeInputStream(AudioStreamIn* in)
    251 {
    252     Mutex::Autolock lock(mLock);
    253 
    254     ssize_t index = mInputs.indexOf((AudioStreamInTegra *)in);
    255     if (index < 0) {
    256         LOGW("Attempt to close invalid input stream");
    257     } else {
    258         mInputs.removeAt(index);
    259         mLock.unlock();
    260         delete in;
    261         mLock.lock();
    262     }
    263 }
    264 
    265 status_t AudioHardware::setMode(int mode)
    266 {
    267     AutoMutex lock(mLock);
    268     bool wasInCall = isInCall();
    269     LOGV("setMode() : new %d, old %d", mode, mMode);
    270     status_t status = AudioHardwareBase::setMode(mode);
    271     if (status == NO_ERROR) {
    272         if (wasInCall ^ isInCall()) {
    273             doRouting_l();
    274             if (wasInCall) {
    275                 setMicMute_l(false);
    276             }
    277         }
    278     }
    279 
    280     return status;
    281 }
    282 
    283 // Must be called with mLock held
    284 status_t AudioHardware::doStandby(int stop_fd, bool output, bool enable)
    285 {
    286     status_t status = NO_ERROR;
    287     struct cpcap_audio_stream standby;
    288 
    289     LOGV("AudioHardware::doStandby() putting %s in %s mode",
    290             output ? "output" : "input",
    291             enable ? "standby" : "online" );
    292 
    293 // Debug code
    294     if (!mLock.tryLock()) {
    295         LOGE("doStandby called without mLock held.");
    296         mLock.unlock();
    297     }
    298 // end Debug code
    299 
    300     if (output) {
    301         standby.id = CPCAP_AUDIO_OUT_STANDBY;
    302         standby.on = enable;
    303 
    304         if (enable) {
    305             /* Flush the queued playback data.  Putting the output in standby
    306              * will cause CPCAP to not drive the i2s interface, and write()
    307              * will block until playback is resumed.
    308              */
    309             if (mOutput)
    310                 mOutput->flush();
    311         }
    312 
    313         if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_OUT_SET_OUTPUT, &standby) < 0) {
    314             LOGE("could not turn off current output device: %s",
    315                  strerror(errno));
    316             status = errno;
    317         }
    318 
    319         if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_OUT_GET_OUTPUT, &mCurOutDevice) < 0) {
    320             LOGE("could not get current output device after standby: %s",
    321                  strerror(errno));
    322         }
    323         LOGV("%s: after standby %s, output device %d is %s", __FUNCTION__,
    324              enable ? "enable" : "disable", mCurOutDevice.id,
    325              mCurOutDevice.on ? "on" : "off");
    326     } else {
    327         standby.id = CPCAP_AUDIO_IN_STANDBY;
    328         standby.on = enable;
    329 
    330         if (enable && stop_fd >= 0) {
    331             /* Stop recording, if ongoing.  Muting the microphone will cause
    332              * CPCAP to not send data through the i2s interface, and read()
    333              * will block until recording is resumed.
    334              */
    335             LOGV("%s: stop recording", __FUNCTION__);
    336             if (::ioctl(stop_fd, TEGRA_AUDIO_IN_STOP) < 0) {
    337                 LOGE("could not stop recording: %s",
    338                      strerror(errno));
    339             }
    340         }
    341 
    342         if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_IN_SET_INPUT, &standby) < 0) {
    343             LOGE("could not turn off current input device: %s",
    344                  strerror(errno));
    345             status = errno;
    346         }
    347         ::ioctl(mCpcapCtlFd, CPCAP_AUDIO_IN_GET_INPUT, &mCurInDevice);
    348         LOGV("%s: after standby %s, input device %d is %s", __FUNCTION__,
    349              enable ? "enable" : "disable", mCurInDevice.id,
    350              mCurInDevice.on ? "on" : "off");
    351     }
    352 
    353     return status;
    354 }
    355 
    356 status_t AudioHardware::setMicMute(bool state)
    357 {
    358     Mutex::Autolock lock(mLock);
    359     return setMicMute_l(state);
    360 }
    361 
    362 status_t AudioHardware::setMicMute_l(bool state)
    363 {
    364     if (mMicMute != state) {
    365         mMicMute = state;
    366         LOGV("setMicMute() %s", (state)?"ON":"OFF");
    367     }
    368     return NO_ERROR;
    369 }
    370 
    371 status_t AudioHardware::getMicMute(bool* state)
    372 {
    373     *state = mMicMute;
    374     return NO_ERROR;
    375 }
    376 
    377 status_t AudioHardware::setParameters(const String8& keyValuePairs)
    378 {
    379     AudioParameter param = AudioParameter(keyValuePairs);
    380     String8 value;
    381     String8 key;
    382     const char BT_NREC_KEY[] = "bt_headset_nrec";
    383     const char BT_NAME_KEY[] = "bt_headset_name";
    384     const char BT_NREC_VALUE_ON[] = "on";
    385 
    386 
    387     LOGV("setParameters() %s", keyValuePairs.string());
    388 
    389     if (keyValuePairs.length() == 0) return BAD_VALUE;
    390 
    391     key = String8(BT_NREC_KEY);
    392     if (param.get(key, value) == NO_ERROR) {
    393         if (value == BT_NREC_VALUE_ON) {
    394             mBluetoothNrec = true;
    395             LOGD("Turn on bluetooth NREC");
    396         } else {
    397             mBluetoothNrec = false;
    398             LOGD("Turning noise reduction and echo cancellation off for BT "
    399                  "headset");
    400         }
    401         doRouting();
    402     }
    403     key = String8(BT_NAME_KEY);
    404     if (param.get(key, value) == NO_ERROR) {
    405         mBluetoothId = 0;
    406 #if 0
    407         for (int i = 0; i < mNumSndEndpoints; i++) {
    408             if (!strcasecmp(value.string(), mSndEndpoints[i].name)) {
    409                 mBluetoothId = mSndEndpoints[i].id;
    410                 LOGD("Using custom acoustic parameters for %s", value.string());
    411                 break;
    412             }
    413         }
    414 #endif
    415         if (mBluetoothId == 0) {
    416             LOGD("Using default acoustic parameters "
    417                  "(%s not in acoustic database)", value.string());
    418             doRouting();
    419         }
    420     }
    421     return NO_ERROR;
    422 }
    423 
    424 String8 AudioHardware::getParameters(const String8& keys)
    425 {
    426     AudioParameter request = AudioParameter(keys);
    427     AudioParameter reply = AudioParameter();
    428     String8 value;
    429     String8 key;
    430 
    431     LOGV("getParameters() %s", keys.string());
    432 
    433 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
    434     key = "ec_supported";
    435     if (request.get(key, value) == NO_ERROR) {
    436         value = "yes";
    437         reply.add(key, value);
    438     }
    439 #endif
    440 
    441     return reply.toString();
    442 }
    443 
    444 size_t AudioHardware::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
    445 {
    446     size_t bufsize;
    447 
    448     if (format != AudioSystem::PCM_16_BIT) {
    449         LOGW("getInputBufferSize bad format: %d", format);
    450         return 0;
    451     }
    452     if (channelCount < 1 || channelCount > 2) {
    453         LOGW("getInputBufferSize bad channel count: %d", channelCount);
    454         return 0;
    455     }
    456 
    457     // Return 20 msec input buffer size.
    458     bufsize = sampleRate * sizeof(int16_t) * channelCount / 50;
    459     if (bufsize & 0x7) {
    460        // Not divisible by 8.
    461        bufsize +=8;
    462        bufsize &= ~0x7;
    463     }
    464     LOGV("%s: returns %d for rate %d", __FUNCTION__, bufsize, sampleRate);
    465     return bufsize;
    466 }
    467 
    468 //setVoiceVolume is only useful for setting sidetone gains with a baseband
    469 //controlling volume.  Don't adjust hardware volume with this API.
    470 //
    471 //(On Stingray, don't use mVoiceVol for anything.)
    472 status_t AudioHardware::setVoiceVolume(float v)
    473 {
    474     if (v < 0.0)
    475         v = 0.0;
    476     else if (v > 1.0)
    477         v = 1.0;
    478 
    479     LOGV("Setting unused in-call vol to %f",v);
    480     mVoiceVol = v;
    481 
    482     return NO_ERROR;
    483 }
    484 
    485 status_t AudioHardware::setMasterVolume(float v)
    486 {
    487     if (v < 0.0)
    488         v = 0.0;
    489     else if (v > 1.0)
    490         v = 1.0;
    491 
    492     LOGV("Set master vol to %f.", v);
    493     mMasterVol = v;
    494     Mutex::Autolock lock(mLock);
    495     int useCase = AUDIO_HW_GAIN_USECASE_MM;
    496     AudioStreamInTegra *input = getActiveInput_l();
    497     if (input) {
    498         if (isInCall() && mOutput && !mOutput->getStandby() &&
    499                 input->source() == AUDIO_SOURCE_VOICE_COMMUNICATION) {
    500             useCase = AUDIO_HW_GAIN_USECASE_VOICE;
    501         } else if (input->source() == AUDIO_SOURCE_VOICE_RECOGNITION) {
    502             useCase = AUDIO_HW_GAIN_USECASE_VOICE_REC;
    503         }
    504     }
    505     setVolume_l(v, useCase);
    506     return NO_ERROR;
    507 }
    508 
    509 // Call with mLock held.
    510 status_t AudioHardware::setVolume_l(float v, int usecase)
    511 {
    512     int spkr = getGain(AUDIO_HW_GAIN_SPKR_GAIN, usecase);
    513     int mic = getGain(AUDIO_HW_GAIN_MIC_GAIN, usecase);
    514 
    515     if (spkr==0) {
    516        // no device to set volume on.  Ignore request.
    517        return -1;
    518     }
    519 
    520     spkr = ceil(v * spkr);
    521     if (mSpkrVolume != spkr) {
    522         LOGV("Set tx volume to %d", spkr);
    523         int ret = ::ioctl(mCpcapCtlFd, CPCAP_AUDIO_OUT_SET_VOLUME, spkr);
    524         if (ret < 0) {
    525             LOGE("could not set spkr volume: %s", strerror(errno));
    526             return ret;
    527         }
    528         mSpkrVolume = spkr;
    529     }
    530     if (mMicVolume != mic) {
    531         LOGV("Set rx volume to %d", mic);
    532         int ret = ::ioctl(mCpcapCtlFd, CPCAP_AUDIO_IN_SET_VOLUME, mic);
    533         if (ret < 0) {
    534             LOGE("could not set mic volume: %s", strerror(errno));
    535             return ret;
    536         }
    537         mMicVolume = mic;
    538     }
    539 
    540     return NO_ERROR;
    541 }
    542 
    543 uint8_t AudioHardware::getGain(int direction, int usecase)
    544 {
    545     int path;
    546     AudioStreamInTegra *input = getActiveInput_l();
    547     uint32_t inDev = (input == NULL) ? 0 : input->devices();
    548     if (!mOutput) {
    549        LOGE("No output device.");
    550        return 0;
    551     }
    552     uint32_t outDev = mOutput->devices();
    553 
    554 // In case of an actual phone, with an actual earpiece, uncomment.
    555 //    if (outDev & AudioSystem::DEVICE_OUT_EARPIECE)
    556 //        path = AUDIO_HW_GAIN_EARPIECE;
    557 //    else
    558     if (outDev & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)
    559         path = AUDIO_HW_GAIN_HEADSET_NO_MIC;
    560     else if (outDev & AudioSystem::DEVICE_OUT_WIRED_HEADSET)
    561         path = AUDIO_HW_GAIN_HEADSET_W_MIC;
    562     else if (outDev & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET)
    563         path = AUDIO_HW_GAIN_EMU_DEVICE;
    564     else
    565        path = AUDIO_HW_GAIN_SPEAKERPHONE;
    566 
    567     LOGV("Picked gain[%d][%d][%d] which is %d.",direction, usecase, path,
    568           mCpcapGain[direction][usecase][path]);
    569 
    570     return mCpcapGain[direction][usecase][path];
    571 }
    572 
    573 int AudioHardware::getActiveInputRate()
    574 {
    575     AudioStreamInTegra *input = getActiveInput_l();
    576     return (input != NULL) ? input->sampleRate() : 0;
    577 }
    578 
    579 status_t AudioHardware::doRouting()
    580 {
    581     Mutex::Autolock lock(mLock);
    582     return doRouting_l();
    583 }
    584 
    585 // Call this with mLock held.
    586 status_t AudioHardware::doRouting_l()
    587 {
    588     if (!mOutput) {
    589         return NO_ERROR;
    590     }
    591     uint32_t outputDevices = mOutput->devices();
    592     AudioStreamInTegra *input = getActiveInput_l();
    593     uint32_t inputDevice = (input == NULL) ? 0 : input->devices();
    594     uint32_t btScoOutDevices = outputDevices & (
    595                            AudioSystem::DEVICE_OUT_BLUETOOTH_SCO |
    596                            AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
    597                            AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT );
    598     uint32_t spdifOutDevices = outputDevices & (
    599                            AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET |
    600                            AudioSystem::DEVICE_OUT_AUX_DIGITAL );
    601     uint32_t speakerOutDevices = outputDevices ^ btScoOutDevices ^ spdifOutDevices;
    602     uint32_t btScoInDevice = inputDevice & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
    603     uint32_t micInDevice   = inputDevice ^ btScoInDevice;
    604     int sndOutDevice = -1;
    605     int sndInDevice = -1;
    606     bool btScoOn = btScoOutDevices||btScoInDevice;
    607 
    608     LOGV("%s: inputDevice %x, outputDevices %x", __FUNCTION__,
    609          inputDevice, outputDevices);
    610 
    611     switch (inputDevice) {
    612     case AudioSystem::DEVICE_IN_DEFAULT:
    613     case AudioSystem::DEVICE_IN_BUILTIN_MIC:
    614         sndInDevice = CPCAP_AUDIO_IN_MIC1;
    615         break;
    616     case AudioSystem::DEVICE_IN_WIRED_HEADSET:
    617         sndInDevice = CPCAP_AUDIO_IN_MIC2;
    618         break;
    619     default:
    620         break;
    621     }
    622 
    623     switch (speakerOutDevices) {
    624     case AudioSystem::DEVICE_OUT_EARPIECE:
    625     case AudioSystem::DEVICE_OUT_DEFAULT:
    626     case AudioSystem::DEVICE_OUT_SPEAKER:
    627         sndOutDevice = CPCAP_AUDIO_OUT_SPEAKER;
    628         break;
    629     case AudioSystem::DEVICE_OUT_WIRED_HEADSET:
    630     case AudioSystem::DEVICE_OUT_WIRED_HEADPHONE:
    631         sndOutDevice = CPCAP_AUDIO_OUT_HEADSET;
    632         break;
    633     case AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADSET:
    634     case AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADPHONE:
    635         sndOutDevice = CPCAP_AUDIO_OUT_HEADSET_AND_SPEAKER;
    636         break;
    637     case AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET:
    638         sndOutDevice = CPCAP_AUDIO_OUT_ANLG_DOCK_HEADSET;
    639         break;
    640     case AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET:
    641       // To be implemented
    642         break;
    643     default:
    644         break;
    645     }
    646 
    647     if (sndInDevice != (int)mCurInDevice.id) {
    648         if (sndInDevice == -1) {
    649             LOGV("input device set %x not supported, defaulting to on-board mic",
    650                  inputDevice);
    651             mCurInDevice.id = CPCAP_AUDIO_IN_MIC1;
    652         }
    653         else
    654             mCurInDevice.id = sndInDevice;
    655 
    656         if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_IN_SET_INPUT,
    657                   &mCurInDevice) < 0)
    658             LOGE("could not set input (%d, on %d): %s",
    659                  mCurInDevice.id, mCurInDevice.on, strerror(errno));
    660 
    661         LOGV("current input %d, %s",
    662              mCurInDevice.id,
    663              mCurInDevice.on ? "on" : "off");
    664     }
    665 
    666     if (sndOutDevice != (int)mCurOutDevice.id) {
    667         if (sndOutDevice == -1) {
    668             LOGW("output device set %x not supported, defaulting to speaker",
    669                  outputDevices);
    670             mCurOutDevice.id = CPCAP_AUDIO_OUT_SPEAKER;
    671         }
    672         else
    673             mCurOutDevice.id = sndOutDevice;
    674 
    675         if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_OUT_SET_OUTPUT,
    676                   &mCurOutDevice) < 0)
    677             LOGE("could not set output (%d, on %d): %s",
    678                  mCurOutDevice.id, mCurOutDevice.on,
    679                  strerror(errno));
    680 
    681         LOGV("current output %d, %s",
    682              mCurOutDevice.id,
    683              mCurOutDevice.on ? "on" : "off");
    684     }
    685 
    686     // enable EC if:
    687     // - mEcnsRequested AND
    688     // - the output stream is active
    689     mEcnsEnabled = mEcnsRequested;
    690     if (mOutput->getStandby()) {
    691         mEcnsEnabled &= ~PREPROC_AEC;
    692     }
    693 
    694 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
    695     int ecnsRate = (btScoOn || (getActiveInputRate() < 16000)) ? 8000 : 16000;
    696     // Check input/output rates for HW.
    697     if (mEcnsEnabled) {
    698         mHwInRate = ecnsRate;
    699         // rx path is altered only if AEC is enabled
    700         if (mEcnsEnabled & PREPROC_AEC) {
    701             mHwOutRate = mHwInRate;
    702         } else {
    703             mHwOutRate = AUDIO_HW_OUT_SAMPLERATE;
    704         }
    705         LOGD("EC/NS active, requests rate as %d for in/out", mHwInRate);
    706     }
    707     else
    708 #endif
    709     {
    710         if (input) {
    711             mHwInRate = getActiveInputRate();
    712         }
    713         mHwOutRate = AUDIO_HW_OUT_SAMPLERATE;
    714         LOGV("No EC/NS, set input rate %d, output %d.", mHwInRate, mHwOutRate);
    715     }
    716     if (btScoOn) {
    717         mHwOutRate = 8000;
    718         mHwInRate = 8000;
    719         LOGD("Bluetooth SCO active, rate forced to 8K");
    720     }
    721 
    722     if (input) {
    723         // acquire mutex if not already locked by read()
    724         if (!input->isLocked()) {
    725             input->lock();
    726         }
    727     }
    728     // acquire mutex if not already locked by write()
    729     if (!mOutput->isLocked()) {
    730         mOutput->lock();
    731     }
    732 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
    733     mAudioPP.setAudioDev(&mCurOutDevice, &mCurInDevice,
    734                          btScoOn, mBluetoothNrec,
    735                          spdifOutDevices?true:false);
    736     mAudioPP.enableEcns(mEcnsEnabled);
    737 #endif
    738 
    739     mOutput->setDriver_l(speakerOutDevices?true:false,
    740                        btScoOn,
    741                        spdifOutDevices?true:false, mHwOutRate);
    742 
    743     if (input) {
    744         input->setDriver_l(micInDevice?true:false,
    745                 btScoOn, mHwInRate);
    746     }
    747 
    748     // Changing I2S to port connection when bluetooth starts or stopS must be done simultaneously
    749     // for input and output while both DMAs are stopped
    750     if (btScoOn != mBtScoOn) {
    751         if (input) {
    752 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
    753             if (mEcnsEnabled) {
    754                 mAudioPP.enableEcns(0);
    755                 mAudioPP.enableEcns(mEcnsEnabled);
    756             }
    757 #endif
    758             input->lockFd();
    759             input->stop_l();
    760         }
    761         mOutput->lockFd();
    762         mOutput->flush_l();
    763 
    764         int bit_format = TEGRA_AUDIO_BIT_FORMAT_DEFAULT;
    765         bool is_bt_bypass = false;
    766         if (btScoOn) {
    767             bit_format = TEGRA_AUDIO_BIT_FORMAT_DSP;
    768             is_bt_bypass = true;
    769         }
    770         LOGV("%s: bluetooth state changed. is_bt_bypass %d bit_format %d",
    771              __FUNCTION__, is_bt_bypass, bit_format);
    772         // Setup the I2S2-> DAP2/4 capture/playback path.
    773         if (::ioctl(mOutput->mBtFdIoCtl, TEGRA_AUDIO_SET_BIT_FORMAT, &bit_format) < 0) {
    774             LOGE("could not set bit format %s", strerror(errno));
    775         }
    776         if (::ioctl(mCpcapCtlFd, CPCAP_AUDIO_SET_BLUETOOTH_BYPASS, is_bt_bypass) < 0) {
    777             LOGE("could not set bluetooth bypass %s", strerror(errno));
    778         }
    779 
    780         mBtScoOn = btScoOn;
    781         mOutput->unlockFd();
    782         if (input) {
    783             input->unlockFd();
    784         }
    785     }
    786 
    787     if (!mOutput->isLocked()) {
    788         mOutput->unlock();
    789     }
    790     if (input && !input->isLocked()) {
    791         input->unlock();
    792     }
    793 
    794     // Since HW path may have changed, set the hardware gains.
    795     int useCase = AUDIO_HW_GAIN_USECASE_MM;
    796     if (mEcnsEnabled) {
    797         useCase = AUDIO_HW_GAIN_USECASE_VOICE;
    798     } else if (input && input->source() == AUDIO_SOURCE_VOICE_RECOGNITION) {
    799         useCase = AUDIO_HW_GAIN_USECASE_VOICE_REC;
    800     }
    801     setVolume_l(mMasterVol, useCase);
    802 
    803     return NO_ERROR;
    804 }
    805 
    806 status_t AudioHardware::dumpInternals(int fd, const Vector<String16>& args)
    807 {
    808     const size_t SIZE = 256;
    809     char buffer[SIZE];
    810     String8 result;
    811     result.append("AudioHardware::dumpInternals\n");
    812     snprintf(buffer, SIZE, "\tmInit: %s\n", mInit? "true": "false");
    813     result.append(buffer);
    814     snprintf(buffer, SIZE, "\tmMicMute: %s\n", mMicMute? "true": "false");
    815     result.append(buffer);
    816     snprintf(buffer, SIZE, "\tmBluetoothNrec: %s\n", mBluetoothNrec? "true": "false");
    817     result.append(buffer);
    818     snprintf(buffer, SIZE, "\tmBluetoothId: %d\n", mBluetoothId);
    819     result.append(buffer);
    820     ::write(fd, result.string(), result.size());
    821     return NO_ERROR;
    822 }
    823 
    824 status_t AudioHardware::dump(int fd, const Vector<String16>& args)
    825 {
    826     dumpInternals(fd, args);
    827     for (size_t index = 0; index < mInputs.size(); index++) {
    828         mInputs[index]->dump(fd, args);
    829     }
    830 
    831     if (mOutput) {
    832         mOutput->dump(fd, args);
    833     }
    834     return NO_ERROR;
    835 }
    836 
    837 uint32_t AudioHardware::getInputSampleRate(uint32_t sampleRate)
    838 {
    839     uint32_t i;
    840     uint32_t prevDelta;
    841     uint32_t delta;
    842 
    843     for (i = 0, prevDelta = 0xFFFFFFFF; i < sizeof(inputSamplingRates)/sizeof(uint32_t); i++, prevDelta = delta) {
    844         delta = abs(sampleRate - inputSamplingRates[i]);
    845         if (delta > prevDelta) break;
    846     }
    847     // i is always > 0 here
    848     return inputSamplingRates[i-1];
    849 }
    850 
    851 // getActiveInput_l() must be called with mLock held
    852 AudioHardware::AudioStreamInTegra *AudioHardware::getActiveInput_l()
    853 {
    854     for (size_t i = 0; i < mInputs.size(); i++) {
    855         // return first input found not being in standby mode
    856         // as only one input can be in this state
    857         if (!mInputs[i]->getStandby()) {
    858             return mInputs[i];
    859         }
    860     }
    861 
    862     return NULL;
    863 }
    864 
    865 void AudioHardware::setEcnsRequested_l(int ecns, bool enabled)
    866 {
    867     if (enabled) {
    868         mEcnsRequested |= ecns;
    869     } else {
    870         mEcnsRequested &= ~ecns;
    871     }
    872 }
    873 
    874 // ----------------------------------------------------------------------------
    875 // Sample Rate Converter wrapper
    876 //
    877 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
    878 AudioHardware::AudioStreamSrc::AudioStreamSrc() :
    879         mSrcBuffer(NULL), mSrcInitted(false)
    880 {
    881 }
    882 AudioHardware::AudioStreamSrc::~AudioStreamSrc()
    883 {
    884     if (mSrcBuffer != NULL) {
    885         delete[] mSrcBuffer;
    886     }
    887 }
    888 
    889 void AudioHardware::AudioStreamSrc::init(int inRate, int outRate)
    890 {
    891     if (mSrcBuffer == NULL) {
    892         mSrcBuffer = new char[src_memory_required_stereo(MAX_FRAME_LEN, MAX_CONVERT_RATIO)];
    893     }
    894     if (mSrcBuffer == NULL) {
    895         LOGE("Failed to allocate memory for sample rate converter.");
    896         return;
    897     }
    898     mSrcInit.memory = (SRC16*)(mSrcBuffer);
    899     mSrcInit.input_rate = inRate;
    900     mSrcInit.output_rate = outRate;
    901     mSrcInit.frame_length = MAX_FRAME_LEN;
    902     mSrcInit.stereo_flag = SRC_OFF;
    903     mSrcInit.input_interleaved = SRC_OFF;
    904     mSrcInit.output_interleaved = SRC_OFF;
    905     rate_convert_init(&mSrcInit, &mSrcObj);
    906 
    907     mSrcInitted = true;
    908     mSrcInRate = inRate;
    909     mSrcOutRate = outRate;
    910 }
    911 #endif
    912 
    913 // ----------------------------------------------------------------------------
    914 
    915 // always succeeds, must call init() immediately after
    916 AudioHardware::AudioStreamOutTegra::AudioStreamOutTegra() :
    917     mBtFdIoCtl(-1), mHardware(0), mFd(-1), mFdCtl(-1),
    918     mBtFd(-1), mBtFdCtl(-1),
    919     mSpdifFd(-1), mSpdifFdCtl(-1),
    920     mStartCount(0), mRetryCount(0), mDevices(0),
    921     mIsSpkrEnabled(false), mIsBtEnabled(false), mIsSpdifEnabled(false),
    922     mIsSpkrEnabledReq(false), mIsBtEnabledReq(false), mIsSpdifEnabledReq(false),
    923     mSpareSample(0), mHaveSpareSample(false),
    924     mState(AUDIO_STREAM_IDLE), /*mSrc*/ mLocked(false), mDriverRate(AUDIO_HW_OUT_SAMPLERATE),
    925     mInit(false)
    926 {
    927     LOGV("AudioStreamOutTegra constructor");
    928 }
    929 
    930 // designed to be called multiple times for retries
    931 status_t AudioHardware::AudioStreamOutTegra::init()
    932 {
    933     if (mInit) {
    934         return NO_ERROR;
    935     }
    936 
    937 #define OPEN_FD(fd, dev)    fd = ::open(dev, O_RDWR);                              \
    938                             if (fd < 0) {                                          \
    939                                 LOGE("open " dev " failed: %s", strerror(errno));   \
    940                                 goto error;                                         \
    941                             }
    942     OPEN_FD(mFd, "/dev/audio0_out")
    943     OPEN_FD(mFdCtl, "/dev/audio0_out_ctl")
    944     OPEN_FD(mBtFd, "/dev/audio1_out")
    945     OPEN_FD(mBtFdCtl, "/dev/audio1_out_ctl")
    946     OPEN_FD(mBtFdIoCtl, "/dev/audio1_ctl")
    947     // may need to be changed to warnings
    948     OPEN_FD(mSpdifFd, "/dev/spdif_out")
    949     OPEN_FD(mSpdifFdCtl, "/dev/spdif_out_ctl")
    950 #undef OPEN_FD
    951 
    952     setNumBufs(AUDIO_HW_NUM_OUT_BUF_LONG);
    953 
    954     mInit = true;
    955     return NO_ERROR;
    956 
    957 error:
    958 #define CLOSE_FD(fd)    if (fd >= 0) {          \
    959                             (void) ::close(fd); \
    960                             fd = -1;            \
    961                         }
    962     CLOSE_FD(mFd)
    963     CLOSE_FD(mFdCtl)
    964     CLOSE_FD(mBtFd)
    965     CLOSE_FD(mBtFdCtl)
    966     CLOSE_FD(mBtFdIoCtl)
    967     CLOSE_FD(mSpdifFd)
    968     CLOSE_FD(mSpdifFdCtl)
    969 #undef CLOSE_FD
    970     return NO_INIT;
    971 }
    972 
    973 status_t AudioHardware::AudioStreamOutTegra::initCheck()
    974 {
    975     return mInit ? NO_ERROR : NO_INIT;
    976 }
    977 
    978 // Called with mHardware->mLock and mLock held.
    979 void AudioHardware::AudioStreamOutTegra::setDriver_l(
    980         bool speaker, bool bluetooth, bool spdif, int sampleRate)
    981 {
    982     LOGV("Out setDriver_l() Analog speaker? %s. Bluetooth? %s. S/PDIF? %s. sampleRate %d",
    983         speaker?"yes":"no", bluetooth?"yes":"no", spdif?"yes":"no", sampleRate);
    984 
    985     // force some reconfiguration at next write()
    986     if (mState == AUDIO_STREAM_CONFIGURED) {
    987         if (mIsSpkrEnabled != speaker || mIsBtEnabled != bluetooth || mIsSpdifEnabled != spdif) {
    988             mState = AUDIO_STREAM_CONFIG_REQ;
    989         } else if (sampleRate != mDriverRate) {
    990             mState = AUDIO_STREAM_NEW_RATE_REQ;
    991         }
    992     }
    993 
    994     mIsSpkrEnabledReq = speaker;
    995     mIsBtEnabledReq = bluetooth;
    996     mIsSpdifEnabledReq = spdif;
    997 
    998 }
    999 
   1000 status_t AudioHardware::AudioStreamOutTegra::set(
   1001         AudioHardware* hw, uint32_t devices, int *pFormat, uint32_t *pChannels, uint32_t *pRate)
   1002 {
   1003     int lFormat = pFormat ? *pFormat : 0;
   1004     uint32_t lChannels = pChannels ? *pChannels : 0;
   1005     uint32_t lRate = pRate ? *pRate : 0;
   1006 
   1007     mHardware = hw;
   1008 
   1009     // fix up defaults
   1010     if (lFormat == 0) lFormat = format();
   1011     if (lChannels == 0) lChannels = channels();
   1012     if (lRate == 0) lRate = sampleRate();
   1013 
   1014     // check values
   1015     if ((lFormat != format()) ||
   1016         (lChannels != channels()) ||
   1017         (lRate != sampleRate())) {
   1018         if (pFormat) *pFormat = format();
   1019         if (pChannels) *pChannels = channels();
   1020         if (pRate) *pRate = sampleRate();
   1021         return BAD_VALUE;
   1022     }
   1023 
   1024 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1025     mHardware->mAudioPP.setPlayAudioRate(lRate);
   1026 #endif
   1027 
   1028     if (pFormat) *pFormat = lFormat;
   1029     if (pChannels) *pChannels = lChannels;
   1030     if (pRate) *pRate = lRate;
   1031 
   1032     mDevices = devices;
   1033     if (mFd >= 0 && mFdCtl >= 0 &&
   1034                 mBtFd >= 0 &&
   1035                 mBtFdCtl >= 0 &&
   1036                 mBtFdIoCtl >= 0) {
   1037         if (mSpdifFd < 0 || mSpdifFdCtl < 0)
   1038             LOGW("s/pdif driver not present");
   1039         return NO_ERROR;
   1040     } else {
   1041         LOGE("Problem opening device files - Is your kernel compatible?");
   1042         return NO_INIT;
   1043     }
   1044 }
   1045 
   1046 AudioHardware::AudioStreamOutTegra::~AudioStreamOutTegra()
   1047 {
   1048     standby();
   1049     // Prevent someone from flushing the fd during a close.
   1050     Mutex::Autolock lock(mFdLock);
   1051     if (mFd >= 0)         { ::close(mFd);         mFd = -1;         }
   1052     if (mFdCtl >= 0)      { ::close(mFdCtl);      mFdCtl = -1;      }
   1053     if (mBtFd >= 0)       { ::close(mBtFd);       mBtFd = -1;       }
   1054     if (mBtFdCtl >= 0)    { ::close(mBtFdCtl);    mBtFdCtl = -1;    }
   1055     if (mBtFdIoCtl >= 0)  { ::close(mBtFdIoCtl);  mBtFdIoCtl = -1;  }
   1056     if (mSpdifFd >= 0)    { ::close(mSpdifFd);    mSpdifFd = -1;    }
   1057     if (mSpdifFdCtl >= 0) { ::close(mSpdifFdCtl); mSpdifFdCtl = -1; }
   1058 }
   1059 
   1060 ssize_t AudioHardware::AudioStreamOutTegra::write(const void* buffer, size_t bytes)
   1061 {
   1062     status_t status;
   1063     if (!mHardware) {
   1064         LOGE("%s: mHardware is null", __FUNCTION__);
   1065         return NO_INIT;
   1066     }
   1067     // LOGD("AudioStreamOutTegra::write(%p, %u) TID %d", buffer, bytes, gettid());
   1068     // Protect output state during the write process.
   1069 
   1070     if (mSleepReq) {
   1071         // sleep a few milliseconds so that the processor can be given to the thread attempting to
   1072         // lock mLock before we sleep with mLock held while writing below
   1073         usleep(FORCED_SLEEP_TIME_US);
   1074     }
   1075 
   1076     bool needsOnline = false;
   1077     if (mState < AUDIO_STREAM_CONFIGURED) {
   1078         mHardware->mLock.lock();
   1079         if (mState < AUDIO_STREAM_CONFIGURED) {
   1080             needsOnline = true;
   1081         } else {
   1082             mHardware->mLock.unlock();
   1083         }
   1084     }
   1085 
   1086     { // scope for the lock
   1087         Mutex::Autolock lock(mLock);
   1088 
   1089         ssize_t written = 0;
   1090         const uint8_t* p = static_cast<const uint8_t*>(buffer);
   1091         size_t outsize = bytes;
   1092         int outFd = mFd;
   1093         bool stereo;
   1094         ssize_t writtenToSpdif = 0;
   1095 
   1096         if (needsOnline) {
   1097             status = online_l();
   1098             mHardware->mLock.unlock();
   1099             if (status < 0) {
   1100                 goto error;
   1101             }
   1102         }
   1103         stereo = mIsBtEnabled ? false : (channels() == AudioSystem::CHANNEL_OUT_STEREO);
   1104 
   1105 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1106         // Do Multimedia processing if appropriate for device and usecase.
   1107         mHardware->mAudioPP.doMmProcessing((void *)buffer, bytes / frameSize());
   1108 #endif
   1109 
   1110         if (mIsSpkrEnabled && mIsBtEnabled) {
   1111             // When dual routing to CPCAP and Bluetooth, piggyback CPCAP audio now,
   1112             // and then down convert for the BT.
   1113             // CPCAP is always 44.1 in this case.
   1114             // This also works in the three-way routing case.
   1115             Mutex::Autolock lock2(mFdLock);
   1116             ::write(outFd, buffer, outsize);
   1117         }
   1118         if (mIsSpdifEnabled) {
   1119             // When dual routing to Speaker and HDMI, piggyback HDMI now, since it
   1120             // has no mic we'll leave the rest of the acoustic processing for the
   1121             // CPCAP hardware path.
   1122             // This also works in the three-way routing case, except the acoustic
   1123             // tuning will be done on Bluetooth, since it has the exclusive mic amd
   1124             // it also needs the sample rate conversion
   1125             Mutex::Autolock lock2(mFdLock);
   1126             if (mSpdifFd >= 0) {
   1127                 writtenToSpdif = ::write(mSpdifFd, buffer, outsize);
   1128                 LOGV("%s: written %d bytes to SPDIF", __FUNCTION__, (int)writtenToSpdif);
   1129             } else {
   1130                 LOGW("s/pdif enabled but unavailable");
   1131             }
   1132         }
   1133         if (mIsBtEnabled) {
   1134             outFd = mBtFd;
   1135         } else if (mIsSpdifEnabled && !mIsSpkrEnabled) {
   1136             outFd = -1;
   1137         }
   1138 
   1139 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1140         // Check if sample rate conversion or ECNS are required.
   1141         // Caution: Upconversion (from 44.1 to 48) would require a new output buffer larger than the
   1142         // original one.
   1143         if (mDriverRate != (int)sampleRate()) {
   1144             if (!mSrc.initted() ||
   1145                  mSrc.inRate() != (int)sampleRate() ||
   1146                  mSrc.outRate() != mDriverRate) {
   1147                 LOGD("%s: downconvert started from %d to %d",__FUNCTION__,
   1148                      sampleRate(), mDriverRate);
   1149                 mSrc.init(sampleRate(), mDriverRate);
   1150                 if (!mSrc.initted()) {
   1151                     status = -1;
   1152                     goto error;
   1153                 }
   1154                 // Workaround to give multiple of 4 bytes to driver: Keep one sample
   1155                 // buffered in case SRC returns an odd number of samples.
   1156                 mHaveSpareSample = false;
   1157             }
   1158         } else {
   1159             mSrc.deinit();
   1160         }
   1161 
   1162         if (mHardware->mAudioPP.isEcEnabled() || mSrc.initted())
   1163         {
   1164             // cut audio down to Mono for SRC or ECNS
   1165             if (channels() == AudioSystem::CHANNEL_OUT_STEREO)
   1166             {
   1167                 // Do stereo-to-mono downmix before SRC, in-place
   1168                 int16_t *destBuf = (int16_t *) buffer;
   1169                 for (int i = 0; i < (int)bytes/2; i++) {
   1170                      destBuf[i] = (destBuf[i*2]>>1) + (destBuf[i*2+1]>>1);
   1171                 }
   1172                 outsize >>= 1;
   1173             }
   1174         }
   1175 
   1176         if (mSrc.initted()) {
   1177             // Apply the sample rate conversion.
   1178             mSrc.mIoData.in_buf_ch1 = (SRC16 *) (buffer);
   1179             mSrc.mIoData.in_buf_ch2 = 0;
   1180             mSrc.mIoData.input_count = outsize / sizeof(SRC16);
   1181             mSrc.mIoData.out_buf_ch1 = (SRC16 *) (buffer);
   1182             mSrc.mIoData.out_buf_ch2 = 0;
   1183             mSrc.mIoData.output_count = outsize / sizeof(SRC16);
   1184             if (mHaveSpareSample) {
   1185                 // Leave room for placing the spare.
   1186                 mSrc.mIoData.out_buf_ch1++;
   1187                 mSrc.mIoData.output_count--;
   1188             }
   1189             mSrc.srcConvert();
   1190             LOGV("Converted %d bytes at %d to %d bytes at %d",
   1191                  outsize, sampleRate(), mSrc.mIoData.output_count*2, mDriverRate);
   1192             if (mHaveSpareSample) {
   1193                 int16_t *bufp = (int16_t*)buffer;
   1194                 bufp[0]=mSpareSample;
   1195                 mSrc.mIoData.output_count++;
   1196                 mHaveSpareSample = false;
   1197             }
   1198             outsize = mSrc.mIoData.output_count*2;
   1199             LOGV("Outsize is now %d", outsize);
   1200         }
   1201         if (mHardware->mAudioPP.isEcEnabled()) {
   1202             // EC/NS is a blocking interface, to synchronise with read.
   1203             // It also consumes data when EC/NS is running.
   1204             // It expects MONO data.
   1205             // If EC/NS is not running, it will return 0, and we need to write this data to the
   1206             // driver ourselves.
   1207 
   1208             // Indicate that it is safe to call setDriver_l() without locking mLock: if the input
   1209             // stream is started, doRouting_l() will not block when setDriver_l() is called.
   1210             mLocked = true;
   1211             LOGV("writeDownlinkEcns size %d", outsize);
   1212             written = mHardware->mAudioPP.writeDownlinkEcns(outFd,(void *)buffer,
   1213                                                             stereo, outsize, &mFdLock);
   1214             mLocked = false;
   1215         }
   1216         if (mHardware->mAudioPP.isEcEnabled() || mSrc.initted()) {
   1217             // Move audio back up to Stereo, if the EC/NS wasn't in fact running and we're
   1218             // writing to a stereo device.
   1219             if (stereo &&
   1220                 written != (ssize_t)outsize) {
   1221                 // Back up to stereo, in place.
   1222                 int16_t *destBuf = (int16_t *) buffer;
   1223                 for (int i = outsize/2-1; i >= 0; i--) {
   1224                     destBuf[i*2] = destBuf[i];
   1225                     destBuf[i*2+1] = destBuf[i];
   1226                 }
   1227                 outsize <<= 1;
   1228             }
   1229         }
   1230 #endif
   1231 
   1232         if (written != (ssize_t)outsize) {
   1233             // The sample rate conversion modifies the output size.
   1234             if (outsize&0x3) {
   1235                 int16_t* bufp = (int16_t *)buffer;
   1236 //                LOGV("Keep the spare sample away from the driver.");
   1237                 mHaveSpareSample = true;
   1238                 mSpareSample = bufp[outsize/2 - 1];
   1239             }
   1240 
   1241             if (outFd >= 0) {
   1242                 Mutex::Autolock lock2(mFdLock);
   1243                 written = ::write(outFd, buffer, outsize&(~0x3));
   1244                 if (written != ((ssize_t)outsize&(~0x3))) {
   1245                     status = written;
   1246                     goto error;
   1247                 }
   1248             } else {
   1249                 written = writtenToSpdif;
   1250             }
   1251         }
   1252         if (written < 0) {
   1253             LOGE("Error writing %d bytes to output: %s", outsize, strerror(errno));
   1254             status = written;
   1255             goto error;
   1256         }
   1257 
   1258         // Sample rate converter may be stashing a couple of bytes here or there,
   1259         // so just report that all bytes were consumed. (it would be a bug not to.)
   1260         LOGV("write() written %d", bytes);
   1261         return bytes;
   1262 
   1263     }
   1264 error:
   1265     LOGE("write(): error, return %d", status);
   1266     standby();
   1267     usleep(bytes * 1000 / frameSize() / sampleRate() * 1000);
   1268 
   1269     return status;
   1270 }
   1271 
   1272 void AudioHardware::AudioStreamOutTegra::flush()
   1273 {
   1274     // Prevent someone from writing the fd while we flush
   1275     Mutex::Autolock lock(mFdLock);
   1276     flush_l();
   1277 }
   1278 
   1279 void AudioHardware::AudioStreamOutTegra::flush_l()
   1280 {
   1281     LOGV("AudioStreamOutTegra::flush()");
   1282     if (::ioctl(mFdCtl, TEGRA_AUDIO_OUT_FLUSH) < 0)
   1283        LOGE("could not flush playback: %s", strerror(errno));
   1284     if (::ioctl(mBtFdCtl, TEGRA_AUDIO_OUT_FLUSH) < 0)
   1285        LOGE("could not flush bluetooth: %s", strerror(errno));
   1286     if (mSpdifFdCtl >= 0 && ::ioctl(mSpdifFdCtl, TEGRA_AUDIO_OUT_FLUSH) < 0)
   1287        LOGE("could not flush spdif: %s", strerror(errno));
   1288     LOGV("AudioStreamOutTegra::flush() returns");
   1289 }
   1290 
   1291 // FIXME: this is a workaround for issue 3387419 with impact on latency
   1292 // to be removed when root cause is fixed
   1293 void AudioHardware::AudioStreamOutTegra::setNumBufs(int numBufs)
   1294 {
   1295     Mutex::Autolock lock(mFdLock);
   1296     LOGV("AudioStreamOutTegra::setNumBufs(%d)", numBufs);
   1297     if (::ioctl(mFdCtl, TEGRA_AUDIO_OUT_SET_NUM_BUFS, &numBufs) < 0)
   1298        LOGE("could not set number of output buffers: %s", strerror(errno));
   1299 }
   1300 
   1301 // Called with mLock and mHardware->mLock held
   1302 status_t AudioHardware::AudioStreamOutTegra::online_l()
   1303 {
   1304     status_t status = NO_ERROR;
   1305 
   1306     if (mState < AUDIO_STREAM_NEW_RATE_REQ) {
   1307         if (mState == AUDIO_STREAM_IDLE) {
   1308             LOGV("output %p going online", this);
   1309             mState = AUDIO_STREAM_CONFIG_REQ;
   1310             // update EC state if necessary
   1311             if (mHardware->getActiveInput_l() && mHardware->isEcRequested()) {
   1312                 // doRouting_l() will not try to lock mLock when calling setDriver_l()
   1313                 mLocked = true;
   1314                 mHardware->doRouting_l();
   1315                 mLocked = false;
   1316             }
   1317         }
   1318 
   1319         // If there's no hardware speaker, leave the HW alone. (i.e. SCO/SPDIF is on)
   1320         if (mIsSpkrEnabledReq) {
   1321             status = mHardware->doStandby(mFdCtl, true, false); // output, online
   1322         } else {
   1323             status = mHardware->doStandby(mFdCtl, true, true); // output, standby
   1324         }
   1325         mIsSpkrEnabled = mIsSpkrEnabledReq;
   1326 
   1327         mIsBtEnabled = mIsBtEnabledReq;
   1328         mIsSpdifEnabled = mIsSpdifEnabledReq;
   1329 
   1330     }
   1331 
   1332     // Flush old data (wrong rate) from I2S driver before changing rate.
   1333     flush();
   1334     if (mHardware->mEcnsEnabled) {
   1335         setNumBufs(AUDIO_HW_NUM_OUT_BUF);
   1336     } else {
   1337         setNumBufs(AUDIO_HW_NUM_OUT_BUF_LONG);
   1338     }
   1339     int speaker_rate = mHardware->mHwOutRate;
   1340     if (mIsBtEnabled) {
   1341         speaker_rate = AUDIO_HW_OUT_SAMPLERATE;
   1342     }
   1343     // Now the DMA is empty, change the rate.
   1344     if (::ioctl(mHardware->mCpcapCtlFd, CPCAP_AUDIO_OUT_SET_RATE,
   1345               speaker_rate) < 0)
   1346         LOGE("could not set output rate(%d): %s",
   1347               speaker_rate, strerror(errno));
   1348 
   1349     mDriverRate = mHardware->mHwOutRate;
   1350 
   1351     // If EC is on, pre load one DMA buffer with 20ms of silence to limit underruns
   1352     if (mHardware->mEcnsEnabled) {
   1353         int fd = -1;
   1354         if (mIsBtEnabled) {
   1355             fd = mBtFd;
   1356         } else if (mIsSpkrEnabled) {
   1357             fd = mFd;
   1358         }
   1359         if (fd >= 0) {
   1360             size_t bufSize = (mDriverRate * 2 /* stereo */ * sizeof(int16_t))/ 50;
   1361             char buf[bufSize];
   1362             memset(buf, 0, bufSize);
   1363             Mutex::Autolock lock2(mFdLock);
   1364             ::write(fd, buf, bufSize);
   1365         }
   1366     }
   1367 
   1368     mState = AUDIO_STREAM_CONFIGURED;
   1369 
   1370     return status;
   1371 }
   1372 
   1373 status_t AudioHardware::AudioStreamOutTegra::standby()
   1374 {
   1375     if (!mHardware) {
   1376         return NO_INIT;
   1377     }
   1378 
   1379     status_t status = NO_ERROR;
   1380     Mutex::Autolock lock(mHardware->mLock);
   1381     Mutex::Autolock lock2(mLock);
   1382 
   1383     if (mState != AUDIO_STREAM_IDLE) {
   1384         LOGV("output %p going into standby", this);
   1385         mState = AUDIO_STREAM_IDLE;
   1386 
   1387         // update EC state if necessary
   1388         if (mHardware->getActiveInput_l() && mHardware->isEcRequested()) {
   1389             // doRouting_l will not try to lock mLock when calling setDriver_l()
   1390             mLocked = true;
   1391             mHardware->doRouting_l();
   1392             mLocked = false;
   1393         }
   1394 
   1395 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1396     // Prevent EC/NS from writing to the file anymore.
   1397         mHardware->mAudioPP.writeDownlinkEcns(-1,0,false,0,&mFdLock);
   1398 #endif
   1399         if (mIsSpkrEnabled) {
   1400             // doStandby() calls flush() which also handles the case where multiple devices
   1401             // including bluetooth or SPDIF are selected
   1402             status = mHardware->doStandby(mFdCtl, true, true); // output, standby
   1403         } else if (mIsBtEnabled || mIsSpdifEnabled) {
   1404             flush();
   1405         }
   1406     }
   1407 
   1408     return status;
   1409 }
   1410 
   1411 status_t AudioHardware::AudioStreamOutTegra::dump(int fd, const Vector<String16>& args)
   1412 {
   1413     const size_t SIZE = 256;
   1414     char buffer[SIZE];
   1415     String8 result;
   1416     result.append("AudioStreamOutTegra::dump\n");
   1417     snprintf(buffer, SIZE, "\tsample rate: %d\n", sampleRate());
   1418     result.append(buffer);
   1419     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
   1420     result.append(buffer);
   1421     snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
   1422     result.append(buffer);
   1423     snprintf(buffer, SIZE, "\tformat: %d\n", format());
   1424     result.append(buffer);
   1425     snprintf(buffer, SIZE, "\tmHardware: %p\n", mHardware);
   1426     result.append(buffer);
   1427     snprintf(buffer, SIZE, "\tmFd: %d\n", mFd);
   1428     result.append(buffer);
   1429     snprintf(buffer, SIZE, "\tmStartCount: %d\n", mStartCount);
   1430     result.append(buffer);
   1431     snprintf(buffer, SIZE, "\tmRetryCount: %d\n", mRetryCount);
   1432     result.append(buffer);
   1433     if (mHardware)
   1434         snprintf(buffer, SIZE, "\tmStandby: %s\n",
   1435                  mHardware->mCurOutDevice.on ? "false": "true");
   1436     else
   1437         snprintf(buffer, SIZE, "\tmStandby: unknown\n");
   1438 
   1439     result.append(buffer);
   1440     ::write(fd, result.string(), result.size());
   1441     return NO_ERROR;
   1442 }
   1443 
   1444 bool AudioHardware::AudioStreamOutTegra::getStandby()
   1445 {
   1446     return mState == AUDIO_STREAM_IDLE;;
   1447 }
   1448 
   1449 status_t AudioHardware::AudioStreamOutTegra::setParameters(const String8& keyValuePairs)
   1450 {
   1451     AudioParameter param = AudioParameter(keyValuePairs);
   1452     String8 key = String8(AudioParameter::keyRouting);
   1453     status_t status = NO_ERROR;
   1454     int device;
   1455     LOGV("AudioStreamOutTegra::setParameters() %s", keyValuePairs.string());
   1456 
   1457     if (param.getInt(key, device) == NO_ERROR) {
   1458         if (device != 0) {
   1459             mDevices = device;
   1460             LOGV("set output routing %x", mDevices);
   1461             status = mHardware->doRouting();
   1462         }
   1463         param.remove(key);
   1464     }
   1465 
   1466     if (param.size()) {
   1467         status = BAD_VALUE;
   1468     }
   1469     return status;
   1470 }
   1471 
   1472 String8 AudioHardware::AudioStreamOutTegra::getParameters(const String8& keys)
   1473 {
   1474     AudioParameter param = AudioParameter(keys);
   1475     String8 value;
   1476     String8 key = String8(AudioParameter::keyRouting);
   1477 
   1478     if (param.get(key, value) == NO_ERROR) {
   1479         LOGV("get routing %x", mDevices);
   1480         param.addInt(key, (int)mDevices);
   1481     }
   1482 
   1483     LOGV("AudioStreamOutTegra::getParameters() %s", param.toString().string());
   1484     return param.toString();
   1485 }
   1486 
   1487 status_t AudioHardware::AudioStreamOutTegra::getRenderPosition(uint32_t *dspFrames)
   1488 {
   1489     //TODO: enable when supported by driver
   1490     return INVALID_OPERATION;
   1491 }
   1492 
   1493 // ----------------------------------------------------------------------------
   1494 
   1495 // always succeeds, must call set() immediately after
   1496 AudioHardware::AudioStreamInTegra::AudioStreamInTegra() :
   1497     mHardware(0), mFd(-1), mFdCtl(-1), mState(AUDIO_STREAM_IDLE), mRetryCount(0),
   1498     mFormat(AUDIO_HW_IN_FORMAT), mChannels(AUDIO_HW_IN_CHANNELS),
   1499     mSampleRate(AUDIO_HW_IN_SAMPLERATE), mBufferSize(AUDIO_HW_IN_BUFFERSIZE),
   1500     mAcoustics((AudioSystem::audio_in_acoustics)0), mDevices(0),
   1501     mIsMicEnabled(0), mIsBtEnabled(0),
   1502     mSource(AUDIO_SOURCE_DEFAULT), mLocked(false), mTotalBuffersRead(0),
   1503     mDriverRate(AUDIO_HW_IN_SAMPLERATE), mEcnsRequested(0)
   1504 {
   1505     LOGV("AudioStreamInTegra constructor");
   1506 }
   1507 
   1508 // serves a similar purpose as init()
   1509 status_t AudioHardware::AudioStreamInTegra::set(
   1510         AudioHardware* hw, uint32_t devices, int *pFormat, uint32_t *pChannels, uint32_t *pRate,
   1511         AudioSystem::audio_in_acoustics acoustic_flags)
   1512 {
   1513     Mutex::Autolock lock(mLock);
   1514     status_t status = BAD_VALUE;
   1515     mHardware = hw;
   1516     if (pFormat == 0)
   1517         return status;
   1518     if (*pFormat != AUDIO_HW_IN_FORMAT) {
   1519         LOGE("wrong in format %d, expecting %lld", *pFormat, AUDIO_HW_IN_FORMAT);
   1520         *pFormat = AUDIO_HW_IN_FORMAT;
   1521         return status;
   1522     }
   1523 
   1524     if (pRate == 0)
   1525         return status;
   1526 
   1527     uint32_t rate = hw->getInputSampleRate(*pRate);
   1528     if (rate != *pRate) {
   1529         LOGE("wrong sample rate %d, expecting %d", *pRate, rate);
   1530         *pRate = rate;
   1531         return status;
   1532     }
   1533 
   1534     if (pChannels == 0)
   1535         return status;
   1536 
   1537     if (*pChannels != AudioSystem::CHANNEL_IN_MONO &&
   1538         *pChannels != AudioSystem::CHANNEL_IN_STEREO) {
   1539         LOGE("wrong number of channels %d", *pChannels);
   1540         *pChannels = AUDIO_HW_IN_CHANNELS;
   1541         return status;
   1542     }
   1543 
   1544     LOGV("AudioStreamInTegra::set(%d, %d, %u)", *pFormat, *pChannels, *pRate);
   1545 
   1546     mDevices = devices;
   1547     mFormat = AUDIO_HW_IN_FORMAT;
   1548     mChannels = *pChannels;
   1549     mSampleRate = *pRate;
   1550     mBufferSize = mHardware->getInputBufferSize(mSampleRate, AudioSystem::PCM_16_BIT,
   1551                                                 AudioSystem::popCount(mChannels));
   1552     return NO_ERROR;
   1553 }
   1554 
   1555 AudioHardware::AudioStreamInTegra::~AudioStreamInTegra()
   1556 {
   1557     LOGV("AudioStreamInTegra destructor");
   1558 
   1559     standby();
   1560 
   1561 }
   1562 
   1563 // Called with mHardware->mLock and mLock held.
   1564 void AudioHardware::AudioStreamInTegra::setDriver_l(bool mic, bool bluetooth, int sampleRate)
   1565 {
   1566     LOGV("In setDriver_l() Analog mic? %s. Bluetooth? %s.", mic?"yes":"no", bluetooth?"yes":"no");
   1567 
   1568     // force some reconfiguration at next read()
   1569     // Note: mState always == AUDIO_STREAM_CONFIGURED when setDriver_l() is called on an input
   1570     if (mic != mIsMicEnabled || bluetooth != mIsBtEnabled) {
   1571         mState = AUDIO_STREAM_CONFIG_REQ;
   1572     } else if (sampleRate != mDriverRate) {
   1573         mState = AUDIO_STREAM_NEW_RATE_REQ;
   1574     }
   1575 
   1576     mIsMicEnabled = mic;
   1577     mIsBtEnabled = bluetooth;
   1578 
   1579 }
   1580 
   1581 ssize_t AudioHardware::AudioStreamInTegra::read(void* buffer, ssize_t bytes)
   1582 {
   1583     status_t status;
   1584     if (!mHardware) {
   1585         LOGE("%s: mHardware is null", __FUNCTION__);
   1586         return NO_INIT;
   1587     }
   1588     //
   1589     LOGV("AudioStreamInTegra::read(%p, %ld) TID %d", buffer, bytes, gettid());
   1590 
   1591     if (mSleepReq) {
   1592         // sleep a few milliseconds so that the processor can be given to the thread attempting to
   1593         // lock mLock before we sleep with mLock held while reading below
   1594         usleep(FORCED_SLEEP_TIME_US);
   1595     }
   1596 
   1597     bool needsOnline = false;
   1598     if (mState < AUDIO_STREAM_CONFIGURED) {
   1599         mHardware->mLock.lock();
   1600         if (mState < AUDIO_STREAM_CONFIGURED) {
   1601             needsOnline = true;
   1602         } else {
   1603             mHardware->mLock.unlock();
   1604         }
   1605     }
   1606 
   1607     {   // scope for mLock
   1608         Mutex::Autolock lock(mLock);
   1609 
   1610         ssize_t ret;
   1611         bool srcReqd;
   1612         int  hwReadBytes;
   1613         int16_t * inbuf;
   1614 
   1615         if (needsOnline) {
   1616             status = online_l();
   1617             mHardware->mLock.unlock();
   1618             if (status != NO_ERROR) {
   1619                LOGE("%s: Problem switching to online.",__FUNCTION__);
   1620                goto error;
   1621             }
   1622         }
   1623 
   1624         srcReqd = (mDriverRate != (int)mSampleRate);
   1625 
   1626 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1627         if (srcReqd) {
   1628             hwReadBytes = ( bytes*mDriverRate/mSampleRate ) & (~0x7);
   1629             LOGV("Running capture SRC.  HW=%d bytes at %d, Flinger=%d bytes at %d",
   1630                   hwReadBytes, mDriverRate, (int)bytes, mSampleRate);
   1631             inbuf = mInScratch;
   1632             if ((size_t)bytes > sizeof(mInScratch)) {
   1633                 LOGE("read: buf size problem. %d>%d",(int)bytes,sizeof(mInScratch));
   1634                 status = BAD_VALUE;
   1635                 goto error;
   1636             }
   1637             // Check if we need to init the rate converter
   1638             if (!mSrc.initted() ||
   1639                  mSrc.inRate() != mDriverRate ||
   1640                  mSrc.outRate() != (int)mSampleRate) {
   1641                 LOGD ("%s: Upconvert started from %d to %d", __FUNCTION__,
   1642                        mDriverRate, mSampleRate);
   1643                 mSrc.init(mDriverRate, mSampleRate);
   1644                 if (!mSrc.initted()) {
   1645                     status = NO_INIT;
   1646                     goto error;
   1647                 }
   1648             }
   1649         } else {
   1650             hwReadBytes = bytes;
   1651             inbuf = (int16_t *)buffer;
   1652             mSrc.deinit();
   1653         }
   1654         // Read from driver, or ECNS thread, as appropriate.
   1655         {
   1656             Mutex::Autolock dfl(mFdLock);
   1657             ret = mHardware->mAudioPP.read(mFd, inbuf, hwReadBytes, mDriverRate);
   1658         }
   1659         if (ret>0 && srcReqd) {
   1660             mSrc.mIoData.in_buf_ch1 = (SRC16 *) (inbuf);
   1661             mSrc.mIoData.in_buf_ch2 = 0;
   1662             mSrc.mIoData.input_count = hwReadBytes / sizeof(SRC16);
   1663             mSrc.mIoData.out_buf_ch1 = (SRC16 *) (buffer);
   1664             mSrc.mIoData.out_buf_ch2 = 0;
   1665             mSrc.mIoData.output_count = bytes/sizeof(SRC16);
   1666             mSrc.srcConvert();
   1667             ret = mSrc.mIoData.output_count*sizeof(SRC16);
   1668             if (ret > bytes) {
   1669                 LOGE("read: buffer overrun");
   1670             }
   1671         }
   1672 #else
   1673         if (srcReqd) {
   1674             LOGE("%s: sample rate mismatch HAL %d, driver %d",
   1675                  __FUNCTION__, mSampleRate, mDriverRate);
   1676             status = INVALID_OPERATION;
   1677             goto error;
   1678         }
   1679         {
   1680             Mutex::Autolock dfl(mFdLock);
   1681             ret = ::read(mFd, buffer, bytes);
   1682         }
   1683 #endif
   1684 
   1685         // It is not optimal to mute after all the above processing but it is necessary to
   1686         // keep the clock sync from input device. It also avoids glitches on output streams due
   1687         // to EC being turned on and off
   1688         bool muted;
   1689         mHardware->getMicMute(&muted);
   1690         if (muted) {
   1691             LOGV("%s muted",__FUNCTION__);
   1692             memset(buffer, 0, bytes);
   1693         }
   1694 
   1695         LOGV("%s returns %d.",__FUNCTION__, (int)ret);
   1696         if (ret < 0) {
   1697             status = ret;
   1698             goto error;
   1699         }
   1700 
   1701         {
   1702             Mutex::Autolock _fl(mFramesLock);
   1703             mTotalBuffersRead++;
   1704         }
   1705         return ret;
   1706     }
   1707 
   1708 error:
   1709     LOGE("read(): error, return %d", status);
   1710     standby();
   1711     usleep(bytes * 1000 / frameSize() / sampleRate() * 1000);
   1712     return status;
   1713 }
   1714 
   1715 bool AudioHardware::AudioStreamInTegra::getStandby() const
   1716 {
   1717     return mState == AUDIO_STREAM_IDLE;
   1718 }
   1719 
   1720 status_t AudioHardware::AudioStreamInTegra::standby()
   1721 {
   1722     if (!mHardware) {
   1723         return NO_INIT;
   1724     }
   1725 
   1726     Mutex::Autolock lock(mHardware->mLock);
   1727     Mutex::Autolock lock2(mLock);
   1728     status_t status = NO_ERROR;
   1729     if (mState != AUDIO_STREAM_IDLE) {
   1730         LOGV("input %p going into standby", this);
   1731         mState = AUDIO_STREAM_IDLE;
   1732         // stopping capture now so that the input stream state (AUDIO_STREAM_IDLE)
   1733         // is consistent with the driver state when doRouting_l() is executed.
   1734         // Not doing so makes that I2S reconfiguration fails  when switching from
   1735         // BT SCO to built-in mic.
   1736         stop_l();
   1737         // reset global pre processing state before disabling the input
   1738         mHardware->setEcnsRequested_l(PREPROC_AEC|PREPROC_NS, false);
   1739         // setDriver_l() will not try to lock mLock when called by doRouting_l()
   1740         mLocked = true;
   1741         mHardware->doRouting_l();
   1742         mLocked = false;
   1743         status = mHardware->doStandby(mFdCtl, false, true); // input, standby
   1744         if (mFd >= 0) {
   1745             ::close(mFd);
   1746             mFd = -1;
   1747         }
   1748         if (mFdCtl >= 0) {
   1749             ::close(mFdCtl);
   1750             mFdCtl = -1;
   1751         }
   1752     }
   1753 
   1754     return status;
   1755 }
   1756 
   1757 // Called with mLock and mHardware->mLock held
   1758 status_t AudioHardware::AudioStreamInTegra::online_l()
   1759 {
   1760     status_t status = NO_ERROR;
   1761 
   1762     reopenReconfigDriver();
   1763 
   1764     if (mState < AUDIO_STREAM_NEW_RATE_REQ) {
   1765 
   1766         // Use standby to flush the driver.  mHardware->mLock should already be held
   1767 
   1768         mHardware->doStandby(mFdCtl, false, true);
   1769         if (mDevices & ~AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
   1770             status = mHardware->doStandby(mFdCtl, false, false);
   1771         }
   1772 
   1773         if (mState == AUDIO_STREAM_IDLE) {
   1774             mState = AUDIO_STREAM_CONFIG_REQ;
   1775             LOGV("input %p going online", this);
   1776             // apply pre processing requested for this input
   1777             mHardware->setEcnsRequested_l(mEcnsRequested, true);
   1778             // setDriver_l() will not try to lock mLock when called by doRouting_l()
   1779             mLocked = true;
   1780             mHardware->doRouting_l();
   1781             mLocked = false;
   1782             {
   1783                 Mutex::Autolock _fl(mFramesLock);
   1784                 mTotalBuffersRead = 0;
   1785                 mStartTimeNs = systemTime();
   1786             }
   1787         }
   1788 
   1789         // configuration
   1790         struct tegra_audio_in_config config;
   1791         status = ::ioctl(mFdCtl, TEGRA_AUDIO_IN_GET_CONFIG, &config);
   1792         if (status < 0) {
   1793             LOGE("cannot read input config: %s", strerror(errno));
   1794             return status;
   1795         }
   1796         config.stereo = AudioSystem::popCount(mChannels) == 2;
   1797         config.rate = mHardware->mHwInRate;
   1798         status = ::ioctl(mFdCtl, TEGRA_AUDIO_IN_SET_CONFIG, &config);
   1799 
   1800         if (status < 0) {
   1801             LOGE("cannot set input config: %s", strerror(errno));
   1802             if (::ioctl(mFdCtl, TEGRA_AUDIO_IN_GET_CONFIG, &config) == 0) {
   1803                 if (config.stereo) {
   1804                     mChannels = AudioSystem::CHANNEL_IN_STEREO;
   1805                 } else {
   1806                     mChannels = AudioSystem::CHANNEL_IN_MONO;
   1807                 }
   1808             }
   1809         }
   1810 
   1811 
   1812     }
   1813 
   1814     mDriverRate = mHardware->mHwInRate;
   1815 
   1816     if (::ioctl(mHardware->mCpcapCtlFd, CPCAP_AUDIO_IN_SET_RATE,
   1817                 mDriverRate) < 0)
   1818         LOGE("could not set input rate(%d): %s", mDriverRate, strerror(errno));
   1819 
   1820     mState = AUDIO_STREAM_CONFIGURED;
   1821 
   1822     return status;
   1823 }
   1824 
   1825 // serves a similar purpose as the init() method of other classes
   1826 void AudioHardware::AudioStreamInTegra::reopenReconfigDriver()
   1827 {
   1828 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1829     if (mHardware->mEcnsEnabled) {
   1830         mHardware->mAudioPP.enableEcns(0);
   1831         mHardware->mAudioPP.enableEcns(mHardware->mEcnsEnabled);
   1832     }
   1833 #endif
   1834     // Need to "restart" the driver when changing the buffer configuration.
   1835     if (mFdCtl >= 0 && ::ioctl(mFdCtl, TEGRA_AUDIO_IN_STOP) < 0) {
   1836         LOGE("%s: could not stop recording: %s", __FUNCTION__, strerror(errno));
   1837     }
   1838     if (mFd >= 0) {
   1839         ::close(mFd);
   1840         mFd = -1;
   1841     }
   1842     if (mFdCtl >= 0) {
   1843         ::close(mFdCtl);
   1844         mFdCtl = -1;
   1845     }
   1846 
   1847     // This does not have a retry loop to avoid blocking if another record session already in progress
   1848     mFd = ::open("/dev/audio1_in", O_RDWR);
   1849     if (mFd < 0) {
   1850         LOGE("open /dev/audio1_in failed: %s", strerror(errno));
   1851     }
   1852     mFdCtl = ::open("/dev/audio1_in_ctl", O_RDWR);
   1853     if (mFdCtl < 0) {
   1854         LOGE("open /dev/audio1_in_ctl failed: %s", strerror(errno));
   1855         if (mFd >= 0) {
   1856             ::close(mFd);
   1857             mFd = -1;
   1858         }
   1859     } else {
   1860         // here we would set mInit = true;
   1861     }
   1862 }
   1863 
   1864 
   1865 status_t AudioHardware::AudioStreamInTegra::dump(int fd, const Vector<String16>& args)
   1866 {
   1867     const size_t SIZE = 256;
   1868     char buffer[SIZE];
   1869     String8 result;
   1870     result.append("AudioStreamInTegra::dump\n");
   1871     snprintf(buffer, SIZE, "\tsample rate: %d\n", sampleRate());
   1872     result.append(buffer);
   1873     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
   1874     result.append(buffer);
   1875     snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
   1876     result.append(buffer);
   1877     snprintf(buffer, SIZE, "\tformat: %d\n", format());
   1878     result.append(buffer);
   1879     snprintf(buffer, SIZE, "\tmHardware: %p\n", mHardware);
   1880     result.append(buffer);
   1881     snprintf(buffer, SIZE, "\tmFd count: %d\n", mFd);
   1882     result.append(buffer);
   1883     snprintf(buffer, SIZE, "\tmState: %d\n", mState);
   1884     result.append(buffer);
   1885     snprintf(buffer, SIZE, "\tmRetryCount: %d\n", mRetryCount);
   1886     result.append(buffer);
   1887     ::write(fd, result.string(), result.size());
   1888     return NO_ERROR;
   1889 }
   1890 
   1891 status_t AudioHardware::AudioStreamInTegra::setParameters(const String8& keyValuePairs)
   1892 {
   1893     AudioParameter param = AudioParameter(keyValuePairs);
   1894     String8 key = String8(AudioParameter::keyRouting);
   1895     status_t status = NO_ERROR;
   1896     int device;
   1897     int source;
   1898     LOGV("AudioStreamInTegra::setParameters() %s", keyValuePairs.string());
   1899 
   1900     // read source before device so that it is upto date when doRouting() is called
   1901     if (param.getInt(String8(AudioParameter::keyInputSource), source) == NO_ERROR) {
   1902         mSource = source;
   1903         param.remove(String8(AudioParameter::keyInputSource));
   1904     }
   1905 
   1906     if (param.getInt(key, device) == NO_ERROR) {
   1907         LOGV("set input routing %x", device);
   1908         if (device & (device - 1)) {
   1909             status = BAD_VALUE;
   1910         } else {
   1911             mDevices = device;
   1912             if (!getStandby() && device != 0) {
   1913                 status = mHardware->doRouting();
   1914             }
   1915         }
   1916         param.remove(key);
   1917     }
   1918 
   1919     if (param.size()) {
   1920         status = BAD_VALUE;
   1921     }
   1922     return status;
   1923 }
   1924 
   1925 String8 AudioHardware::AudioStreamInTegra::getParameters(const String8& keys)
   1926 {
   1927     AudioParameter param = AudioParameter(keys);
   1928     String8 value;
   1929     String8 key = String8(AudioParameter::keyRouting);
   1930 
   1931     if (param.get(key, value) == NO_ERROR) {
   1932         LOGV("get routing %x", mDevices);
   1933         param.addInt(key, (int)mDevices);
   1934     }
   1935 
   1936     LOGV("AudioStreamInTegra::getParameters() %s", param.toString().string());
   1937     return param.toString();
   1938 }
   1939 
   1940 unsigned int  AudioHardware::AudioStreamInTegra::getInputFramesLost() const
   1941 {
   1942     Mutex::Autolock _l(mFramesLock);
   1943     unsigned int lostFrames = 0;
   1944     if (!getStandby()) {
   1945         unsigned int framesPerBuffer = bufferSize() / frameSize();
   1946         uint64_t expectedFrames = ((systemTime() - mStartTimeNs) * mSampleRate) / 1000000000;
   1947         expectedFrames = (expectedFrames / framesPerBuffer) * framesPerBuffer;
   1948         uint64_t actualFrames = (uint64_t)mTotalBuffersRead * framesPerBuffer;
   1949         if (expectedFrames > actualFrames) {
   1950             lostFrames = (unsigned int)(expectedFrames - actualFrames);
   1951             LOGW("getInputFramesLost() expected %d actual %d lost %d",
   1952                  (unsigned int)expectedFrames, (unsigned int)actualFrames, lostFrames);
   1953         }
   1954     }
   1955 
   1956     mTotalBuffersRead = 0;
   1957     mStartTimeNs = systemTime();
   1958 
   1959     return lostFrames;
   1960 }
   1961 
   1962 // must be called with mLock and mFdLock held
   1963 void AudioHardware::AudioStreamInTegra::stop_l()
   1964 {
   1965     LOGV("AudioStreamInTegra::stop_l() starts");
   1966     if (::ioctl(mFdCtl, TEGRA_AUDIO_IN_STOP) < 0) {
   1967         LOGE("could not stop recording: %d %s", errno, strerror(errno));
   1968     }
   1969     LOGV("AudioStreamInTegra::stop_l() returns");
   1970 }
   1971 
   1972 void AudioHardware::AudioStreamInTegra::updateEcnsRequested(effect_handle_t effect, bool enabled)
   1973 {
   1974 #ifdef USE_PROPRIETARY_AUDIO_EXTENSIONS
   1975     effect_descriptor_t desc;
   1976     status_t status = (*effect)->get_descriptor(effect, &desc);
   1977     if (status == 0) {
   1978         int ecns = 0;
   1979         if (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
   1980             ecns = PREPROC_AEC;
   1981         } else if (memcmp(&desc.type, FX_IID_NS, sizeof(effect_uuid_t)) == 0) {
   1982             ecns = PREPROC_NS;
   1983         }
   1984         LOGV("AudioStreamInTegra::updateEcnsRequested() %s effect %s",
   1985              enabled ? "enabling" : "disabling", desc.name);
   1986         if (enabled) {
   1987             mEcnsRequested |= ecns;
   1988         } else {
   1989             mEcnsRequested &= ~ecns;
   1990         }
   1991         standby();
   1992     }
   1993 #endif
   1994 }
   1995 
   1996 status_t AudioHardware::AudioStreamInTegra::addAudioEffect(effect_handle_t effect)
   1997 {
   1998     updateEcnsRequested(effect, true);
   1999     return NO_ERROR;
   2000 }
   2001 
   2002 status_t AudioHardware::AudioStreamInTegra::removeAudioEffect(effect_handle_t effect)
   2003 {
   2004     updateEcnsRequested(effect, false);
   2005     return NO_ERROR;
   2006 }
   2007 
   2008 // ----------------------------------------------------------------------------
   2009 
   2010 extern "C" AudioHardwareInterface* createAudioHardware(void) {
   2011     AudioHardware *hw = new AudioHardware();
   2012     for (unsigned tries = 0; tries < MAX_INIT_TRIES; ++tries) {
   2013         if (NO_ERROR == hw->init())
   2014             break;
   2015         LOGW("AudioHardware::init failed soft, retrying");
   2016         sleep(1);
   2017     }
   2018     if (NO_ERROR != hw->initCheck()) {
   2019         LOGE("AudioHardware::init failed hard");
   2020         delete hw;
   2021         hw = NULL;
   2022     }
   2023     return hw;
   2024 }
   2025 
   2026 }; // namespace android
   2027