Home | History | Annotate | Download | only in libaudio-qsd8k
      1 /*
      2 ** Copyright 2008, 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 1
     20 #define LOG_TAG "AudioHardwareQSD"
     21 #include <utils/Log.h>
     22 #include <utils/String8.h>
     23 #include <hardware_legacy/power.h>
     24 
     25 #include <stdio.h>
     26 #include <unistd.h>
     27 #include <sys/ioctl.h>
     28 #include <sys/types.h>
     29 #include <sys/stat.h>
     30 #include <dlfcn.h>
     31 #include <fcntl.h>
     32 
     33 #include <cutils/properties.h> // for property_get for the voice recognition mode switch
     34 
     35 // hardware specific functions
     36 
     37 #include "AudioHardware.h"
     38 #include <media/AudioRecord.h>
     39 
     40 extern "C" {
     41 #include "msm_audio.h"
     42 #include <linux/a1026.h>
     43 #include <linux/tpa2018d1.h>
     44 }
     45 
     46 #define LOG_SND_RPC 0  // Set to 1 to log sound RPC's
     47 #define TX_PATH (1)
     48 
     49 static const uint32_t SND_DEVICE_CURRENT = 256;
     50 static const uint32_t SND_DEVICE_HANDSET = 0;
     51 static const uint32_t SND_DEVICE_SPEAKER = 1;
     52 static const uint32_t SND_DEVICE_BT = 3;
     53 static const uint32_t SND_DEVICE_CARKIT = 4;
     54 static const uint32_t SND_DEVICE_BT_EC_OFF = 45;
     55 static const uint32_t SND_DEVICE_HEADSET = 2;
     56 static const uint32_t SND_DEVICE_HEADSET_AND_SPEAKER = 10;
     57 static const uint32_t SND_DEVICE_FM_HEADSET = 9;
     58 static const uint32_t SND_DEVICE_FM_SPEAKER = 11;
     59 static const uint32_t SND_DEVICE_NO_MIC_HEADSET = 8;
     60 static const uint32_t SND_DEVICE_TTY_FULL = 5;
     61 static const uint32_t SND_DEVICE_TTY_VCO = 6;
     62 static const uint32_t SND_DEVICE_TTY_HCO = 7;
     63 static const uint32_t SND_DEVICE_HANDSET_BACK_MIC = 20;
     64 static const uint32_t SND_DEVICE_SPEAKER_BACK_MIC = 21;
     65 static const uint32_t SND_DEVICE_NO_MIC_HEADSET_BACK_MIC = 28;
     66 static const uint32_t SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC = 30;
     67 namespace android {
     68 static int support_a1026 = 1;
     69 static bool support_tpa2018d1 = true;
     70 static int fd_a1026 = -1;
     71 static int old_pathid = -1;
     72 static int new_pathid = -1;
     73 static int curr_out_device = -1;
     74 static int curr_mic_device = -1;
     75 static int voice_started = 0;
     76 static int fd_fm_device = -1;
     77 static int stream_volume = -300;
     78 // use VR mode on inputs: 1 == VR mode enabled when selected, 0 = VR mode disabled when selected
     79 static int vr_mode_enabled;
     80 static bool vr_mode_change = false;
     81 static int vr_uses_ns = 0;
     82 static int alt_enable = 0;
     83 static int hac_enable = 0;
     84 // enable or disable 2-mic noise suppression in call on receiver mode
     85 static int enable1026 = 1;
     86 //FIXME add new settings in A1026 driver for an incall no ns mode, based on the current vr no ns
     87 #define A1026_PATH_INCALL_NO_NS_RECEIVER A1026_PATH_VR_NO_NS_RECEIVER
     88 
     89 int errCount = 0;
     90 static void * acoustic;
     91 const uint32_t AudioHardware::inputSamplingRates[] = {
     92         8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000
     93 };
     94 
     95 // ID string for audio wakelock
     96 static const char kOutputWakelockStr[] = "AudioHardwareQSDOut";
     97 static const char kInputWakelockStr[] = "AudioHardwareQSDIn";
     98 
     99 // ----------------------------------------------------------------------------
    100 
    101 AudioHardware::AudioHardware() :
    102     mA1026Init(false), mInit(false), mMicMute(true),
    103     mBluetoothNrec(true),
    104     mHACSetting(false),
    105     mBluetoothIdTx(0), mBluetoothIdRx(0),
    106     mOutput(0),
    107     mNoiseSuppressionState(A1026_NS_STATE_AUTO),
    108     mVoiceVolume(VOICE_VOLUME_MAX), mTTYMode(TTY_MODE_OFF)
    109 {
    110     int (*snd_get_num)();
    111     int (*snd_get_bt_endpoint)(msm_bt_endpoint *);
    112     int (*set_acoustic_parameters)();
    113     int (*set_tpa2018d1_parameters)();
    114 
    115     struct msm_bt_endpoint *ept;
    116 
    117     doA1026_init();
    118 
    119     acoustic =:: dlopen("/system/lib/libhtc_acoustic.so", RTLD_NOW);
    120     if (acoustic == NULL ) {
    121         LOGD("Could not open libhtc_acoustic.so");
    122         /* this is not really an error on non-htc devices... */
    123         mNumBTEndpoints = 0;
    124         mInit = true;
    125         return;
    126     }
    127     set_acoustic_parameters = (int (*)(void))::dlsym(acoustic, "set_acoustic_parameters");
    128     if ((*set_acoustic_parameters) == 0 ) {
    129         LOGE("Could not open set_acoustic_parameters()");
    130         return;
    131     }
    132 
    133     set_tpa2018d1_parameters = (int (*)(void))::dlsym(acoustic, "set_tpa2018d1_parameters");
    134     if ((*set_tpa2018d1_parameters) == 0) {
    135         LOGD("set_tpa2018d1_parameters() not present");
    136         support_tpa2018d1 = false;
    137     }
    138 
    139     int rc = set_acoustic_parameters();
    140     if (rc < 0) {
    141         LOGD("Could not set acoustic parameters to share memory: %d", rc);
    142     }
    143 
    144     if (support_tpa2018d1) {
    145        rc = set_tpa2018d1_parameters();
    146        if (rc < 0) {
    147            support_tpa2018d1 = false;
    148            LOGD("speaker amplifier tpa2018 is not supported\n");
    149        }
    150     }
    151 
    152     snd_get_num = (int (*)(void))::dlsym(acoustic, "snd_get_num");
    153     if ((*snd_get_num) == 0 ) {
    154         LOGD("Could not open snd_get_num()");
    155     }
    156 
    157     mNumBTEndpoints = snd_get_num();
    158     LOGV("mNumBTEndpoints = %d", mNumBTEndpoints);
    159     mBTEndpoints = new msm_bt_endpoint[mNumBTEndpoints];
    160     mInit = true;
    161     LOGV("constructed %d SND endpoints)", mNumBTEndpoints);
    162     ept = mBTEndpoints;
    163     snd_get_bt_endpoint = (int (*)(msm_bt_endpoint *))::dlsym(acoustic, "snd_get_bt_endpoint");
    164     if ((*snd_get_bt_endpoint) == 0 ) {
    165         LOGE("Could not open snd_get_bt_endpoint()");
    166         return;
    167     }
    168     snd_get_bt_endpoint(mBTEndpoints);
    169 
    170     for (int i = 0; i < mNumBTEndpoints; i++) {
    171         LOGV("BT name %s (tx,rx)=(%d,%d)", mBTEndpoints[i].name, mBTEndpoints[i].tx, mBTEndpoints[i].rx);
    172     }
    173 
    174     // reset voice mode in case media_server crashed and restarted while in call
    175     int fd = open("/dev/msm_audio_ctl", O_RDWR);
    176     if (fd >= 0) {
    177         ioctl(fd, AUDIO_STOP_VOICE, NULL);
    178         close(fd);
    179     }
    180 
    181     vr_mode_change = false;
    182     vr_mode_enabled = 0;
    183     enable1026 = 1;
    184     char value[PROPERTY_VALUE_MAX];
    185     // Check the system property to enable or not the special recording modes
    186     property_get("media.a1026.enableA1026", value, "1");
    187     enable1026 = atoi(value);
    188     LOGV("Enable mode selection for A1026 is %d", enable1026);
    189     // Check the system property for which VR mode to use
    190     property_get("media.a1026.nsForVoiceRec", value, "0");
    191     vr_uses_ns = atoi(value);
    192     LOGV("Using Noise Suppression for Voice Rec is %d", vr_uses_ns);
    193 
    194     // Check the system property for enable or not the ALT function
    195     property_get("htc.audio.alt.enable", value, "0");
    196     alt_enable = atoi(value);
    197     LOGV("Enable ALT function: %d", alt_enable);
    198 
    199     // Check the system property for enable or not the HAC function
    200     property_get("htc.audio.hac.enable", value, "0");
    201     hac_enable = atoi(value);
    202     LOGV("Enable HAC function: %d", hac_enable);
    203 
    204     mInit = true;
    205 }
    206 
    207 AudioHardware::~AudioHardware()
    208 {
    209     for (size_t index = 0; index < mInputs.size(); index++) {
    210         closeInputStream((AudioStreamIn*)mInputs[index]);
    211     }
    212     mInputs.clear();
    213     closeOutputStream((AudioStreamOut*)mOutput);
    214     mInit = false;
    215 }
    216 
    217 status_t AudioHardware::initCheck()
    218 {
    219     return mInit ? NO_ERROR : NO_INIT;
    220 }
    221 
    222 AudioStreamOut* AudioHardware::openOutputStream(
    223         uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
    224 {
    225     { // scope for the lock
    226         Mutex::Autolock lock(mLock);
    227 
    228         // only one output stream allowed
    229         if (mOutput) {
    230             if (status) {
    231                 *status = INVALID_OPERATION;
    232             }
    233             return 0;
    234         }
    235 
    236         // create new output stream
    237         AudioStreamOutMSM72xx* out = new AudioStreamOutMSM72xx();
    238         status_t lStatus = out->set(this, devices, format, channels, sampleRate);
    239         if (status) {
    240             *status = lStatus;
    241         }
    242         if (lStatus == NO_ERROR) {
    243             mOutput = out;
    244         } else {
    245             delete out;
    246         }
    247     }
    248     return mOutput;
    249 }
    250 
    251 void AudioHardware::closeOutputStream(AudioStreamOut* out) {
    252     Mutex::Autolock lock(mLock);
    253     if (mOutput == 0 || mOutput != out) {
    254         LOGW("Attempt to close invalid output stream");
    255     }
    256     else {
    257         delete mOutput;
    258         mOutput = 0;
    259     }
    260 }
    261 
    262 AudioStreamIn* AudioHardware::openInputStream(
    263         uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status,
    264         AudioSystem::audio_in_acoustics acoustic_flags)
    265 {
    266     // check for valid input source
    267     if (!AudioSystem::isInputDevice((AudioSystem::audio_devices)devices)) {
    268         return 0;
    269     }
    270 
    271     mLock.lock();
    272 
    273     AudioStreamInMSM72xx* in = new AudioStreamInMSM72xx();
    274     status_t lStatus = in->set(this, devices, format, channels, sampleRate, acoustic_flags);
    275     if (status) {
    276         *status = lStatus;
    277     }
    278     if (lStatus != NO_ERROR) {
    279         mLock.unlock();
    280         delete in;
    281         return 0;
    282     }
    283 
    284     mInputs.add(in);
    285     mLock.unlock();
    286 
    287     return in;
    288 }
    289 
    290 void AudioHardware::closeInputStream(AudioStreamIn* in) {
    291     Mutex::Autolock lock(mLock);
    292 
    293     ssize_t index = mInputs.indexOf((AudioStreamInMSM72xx *)in);
    294     if (index < 0) {
    295         LOGW("Attempt to close invalid input stream");
    296     } else {
    297         mLock.unlock();
    298         delete mInputs[index];
    299         mLock.lock();
    300         mInputs.removeAt(index);
    301     }
    302 }
    303 
    304 status_t AudioHardware::setMode(int mode)
    305 {
    306     // VR mode is never used in a call and must be cleared when entering the IN_CALL mode
    307     if (mode == AudioSystem::MODE_IN_CALL) {
    308         vr_mode_enabled = 0;
    309     }
    310 
    311     if (support_tpa2018d1)
    312         do_tpa2018_control(mode);
    313 
    314     int prevMode = mMode;
    315     status_t status = AudioHardwareBase::setMode(mode);
    316     if (status == NO_ERROR) {
    317         // make sure that doAudioRouteOrMute() is called by doRouting()
    318         // when entering or exiting in call mode even if the new device
    319         // selected is the same as current one.
    320         if (((prevMode != AudioSystem::MODE_IN_CALL) && (mMode == AudioSystem::MODE_IN_CALL)) ||
    321             ((prevMode == AudioSystem::MODE_IN_CALL) && (mMode != AudioSystem::MODE_IN_CALL))) {
    322             clearCurDevice();
    323         }
    324     }
    325 
    326     return status;
    327 }
    328 
    329 bool AudioHardware::checkOutputStandby()
    330 {
    331     if (mOutput)
    332         if (!mOutput->checkStandby())
    333             return false;
    334 
    335     return true;
    336 }
    337 static status_t set_mic_mute(bool _mute)
    338 {
    339     uint32_t mute = _mute;
    340     int fd = -1;
    341     fd = open("/dev/msm_audio_ctl", O_RDWR);
    342     if (fd < 0) {
    343         LOGE("Cannot open msm_audio_ctl device\n");
    344         return -1;
    345     }
    346     LOGD("Setting mic mute to %d\n", mute);
    347     if (ioctl(fd, AUDIO_SET_MUTE, &mute)) {
    348         LOGE("Cannot set mic mute on current device\n");
    349         close(fd);
    350         return -1;
    351     }
    352     close(fd);
    353     return NO_ERROR;
    354 }
    355 
    356 status_t AudioHardware::setMicMute(bool state)
    357 {
    358     Mutex::Autolock lock(mLock);
    359     return setMicMute_nosync(state);
    360 }
    361 
    362 // always call with mutex held
    363 status_t AudioHardware::setMicMute_nosync(bool state)
    364 {
    365     if (mMicMute != state) {
    366         mMicMute = state;
    367         return set_mic_mute(mMicMute); //always set current TX device
    368     }
    369     return NO_ERROR;
    370 }
    371 
    372 status_t AudioHardware::getMicMute(bool* state)
    373 {
    374     *state = mMicMute;
    375     return NO_ERROR;
    376 }
    377 
    378 status_t AudioHardware::setParameters(const String8& keyValuePairs)
    379 {
    380     AudioParameter param = AudioParameter(keyValuePairs);
    381     String8 value;
    382     String8 key;
    383     const char BT_NREC_KEY[] = "bt_headset_nrec";
    384     const char BT_NAME_KEY[] = "bt_headset_name";
    385     const char HAC_KEY[] = "HACSetting";
    386     const char BT_NREC_VALUE_ON[] = "on";
    387     const char HAC_VALUE_ON[] = "ON";
    388 
    389 
    390     LOGV("setParameters() %s", keyValuePairs.string());
    391 
    392     if (keyValuePairs.length() == 0) return BAD_VALUE;
    393 
    394     if(hac_enable) {
    395         key = String8(HAC_KEY);
    396         if (param.get(key, value) == NO_ERROR) {
    397             if (value == HAC_VALUE_ON) {
    398                 mHACSetting = true;
    399                 LOGD("Enable HAC");
    400             } else {
    401                 mHACSetting = false;
    402                 LOGD("Disable HAC");
    403             }
    404         }
    405     }
    406 
    407     key = String8(BT_NREC_KEY);
    408     if (param.get(key, value) == NO_ERROR) {
    409         if (value == BT_NREC_VALUE_ON) {
    410             mBluetoothNrec = true;
    411         } else {
    412             mBluetoothNrec = false;
    413             LOGD("Turning noise reduction and echo cancellation off for BT "
    414                  "headset");
    415         }
    416     }
    417     key = String8(BT_NAME_KEY);
    418     if (param.get(key, value) == NO_ERROR) {
    419         mBluetoothIdTx = 0;
    420         mBluetoothIdRx = 0;
    421         for (int i = 0; i < mNumBTEndpoints; i++) {
    422             if (!strcasecmp(value.string(), mBTEndpoints[i].name)) {
    423                 mBluetoothIdTx = mBTEndpoints[i].tx;
    424                 mBluetoothIdRx = mBTEndpoints[i].rx;
    425                 LOGD("Using custom acoustic parameters for %s", value.string());
    426                 break;
    427             }
    428         }
    429         if (mBluetoothIdTx == 0) {
    430             LOGD("Using default acoustic parameters "
    431                  "(%s not in acoustic database)", value.string());
    432         }
    433         doRouting();
    434     }
    435     key = String8("noise_suppression");
    436     if (param.get(key, value) == NO_ERROR) {
    437         if (support_a1026 == 1) {
    438             int noiseSuppressionState;
    439             if (value == "off") {
    440                 noiseSuppressionState = A1026_NS_STATE_OFF;
    441             } else if (value == "auto") {
    442                 noiseSuppressionState = A1026_NS_STATE_AUTO;
    443             } else if (value == "far_talk") {
    444                 noiseSuppressionState = A1026_NS_STATE_FT;
    445             } else if (value == "close_talk") {
    446                 noiseSuppressionState = A1026_NS_STATE_CT;
    447             } else {
    448                 return BAD_VALUE;
    449             }
    450 
    451             if (noiseSuppressionState != mNoiseSuppressionState) {
    452                 if (!mA1026Init) {
    453                     LOGW("Audience A1026 not initialized.\n");
    454                     return INVALID_OPERATION;
    455                 }
    456 
    457                 mA1026Lock.lock();
    458                 if (fd_a1026 < 0) {
    459                     fd_a1026 = open("/dev/audience_a1026", O_RDWR);
    460                     if (fd_a1026 < 0) {
    461                         LOGE("Cannot open audience_a1026 device (%d)\n", fd_a1026);
    462                         mA1026Lock.unlock();
    463                         return -1;
    464                     }
    465                 }
    466                 LOGV("Setting noise suppression %s", value.string());
    467 
    468                 int rc = ioctl(fd_a1026, A1026_SET_NS_STATE, &noiseSuppressionState);
    469                 if (!rc) {
    470                     mNoiseSuppressionState = noiseSuppressionState;
    471                 } else {
    472                     LOGE("Failed to set noise suppression %s", value.string());
    473                 }
    474                 close(fd_a1026);
    475                 fd_a1026 = -1;
    476                 mA1026Lock.unlock();
    477             }
    478         } else {
    479             return INVALID_OPERATION;
    480         }
    481      }
    482 
    483     key = String8("tty_mode");
    484     if (param.get(key, value) == NO_ERROR) {
    485         int ttyMode;
    486         if (value == "tty_off") {
    487             ttyMode = TTY_MODE_OFF;
    488         } else if (value == "tty_full") {
    489             ttyMode = TTY_MODE_FULL;
    490         } else if (value == "tty_vco") {
    491             ttyMode = TTY_MODE_VCO;
    492         } else if (value == "tty_hco") {
    493             ttyMode = TTY_MODE_HCO;
    494         } else {
    495             return BAD_VALUE;
    496         }
    497 
    498         if (ttyMode != mTTYMode) {
    499             LOGV("new tty mode %d", ttyMode);
    500             mTTYMode = ttyMode;
    501             doRouting();
    502         }
    503      }
    504 
    505     return NO_ERROR;
    506 }
    507 
    508 String8 AudioHardware::getParameters(const String8& keys)
    509 {
    510     AudioParameter request = AudioParameter(keys);
    511     AudioParameter reply = AudioParameter();
    512     String8 value;
    513     String8 key;
    514 
    515     LOGV("getParameters() %s", keys.string());
    516 
    517     key = "noise_suppression";
    518     if (request.get(key, value) == NO_ERROR) {
    519         switch(mNoiseSuppressionState) {
    520         case A1026_NS_STATE_OFF:
    521             value = "off";
    522             break;
    523         case A1026_NS_STATE_AUTO:
    524             value = "auto";
    525             break;
    526         case A1026_NS_STATE_FT:
    527             value = "far_talk";
    528             break;
    529         case A1026_NS_STATE_CT:
    530             value = "close_talk";
    531             break;
    532         }
    533         reply.add(key, value);
    534     }
    535 
    536     return reply.toString();
    537 }
    538 
    539 
    540 static unsigned calculate_audpre_table_index(unsigned index)
    541 {
    542     switch (index) {
    543         case 48000:    return SAMP_RATE_INDX_48000;
    544         case 44100:    return SAMP_RATE_INDX_44100;
    545         case 32000:    return SAMP_RATE_INDX_32000;
    546         case 24000:    return SAMP_RATE_INDX_24000;
    547         case 22050:    return SAMP_RATE_INDX_22050;
    548         case 16000:    return SAMP_RATE_INDX_16000;
    549         case 12000:    return SAMP_RATE_INDX_12000;
    550         case 11025:    return SAMP_RATE_INDX_11025;
    551         case 8000:    return SAMP_RATE_INDX_8000;
    552         default:     return -1;
    553     }
    554 }
    555 
    556 size_t AudioHardware::getBufferSize(uint32_t sampleRate, int channelCount)
    557 {
    558     size_t bufSize;
    559 
    560     if (sampleRate < 11025) {
    561         bufSize = 256;
    562     } else if (sampleRate < 22050) {
    563         bufSize = 512;
    564     } else if (sampleRate < 32000) {
    565         bufSize = 768;
    566     } else if (sampleRate < 44100) {
    567         bufSize = 1024;
    568     } else {
    569         bufSize = 1536;
    570     }
    571 
    572     return bufSize*channelCount;
    573 }
    574 
    575 
    576 size_t AudioHardware::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
    577 {
    578     if (format != AudioSystem::PCM_16_BIT) {
    579         LOGW("getInputBufferSize bad format: %d", format);
    580         return 0;
    581     }
    582     if (channelCount < 1 || channelCount > 2) {
    583         LOGW("getInputBufferSize bad channel count: %d", channelCount);
    584         return 0;
    585     }
    586     if (sampleRate < 8000 || sampleRate > 48000) {
    587         LOGW("getInputBufferSize bad sample rate: %d", sampleRate);
    588         return 0;
    589     }
    590 
    591     return getBufferSize(sampleRate, channelCount);
    592 }
    593 
    594 static status_t set_volume_rpc(uint32_t volume)
    595 {
    596     int fd = -1;
    597     fd = open("/dev/msm_audio_ctl", O_RDWR);
    598     if (fd < 0) {
    599         LOGE("Cannot open msm_audio_ctl device\n");
    600         return -1;
    601     }
    602     volume *= 20; //percentage
    603     LOGD("Setting in-call volume to %d\n", volume);
    604     if (ioctl(fd, AUDIO_SET_VOLUME, &volume)) {
    605         LOGW("Cannot set volume on current device\n");
    606     }
    607     close(fd);
    608     return NO_ERROR;
    609 }
    610 
    611 status_t AudioHardware::setVoiceVolume(float v)
    612 {
    613     if (v < 0.0) {
    614         LOGW("setVoiceVolume(%f) under 0.0, assuming 0.0", v);
    615         v = 0.0;
    616     } else if (v > 1.0) {
    617         LOGW("setVoiceVolume(%f) over 1.0, assuming 1.0", v);
    618         v = 1.0;
    619     }
    620 
    621     int vol = lrint(v * VOICE_VOLUME_MAX);
    622 
    623     Mutex::Autolock lock(mLock);
    624     if (mHACSetting && hac_enable && mCurSndDevice == (int) SND_DEVICE_HANDSET) {
    625         LOGD("HAC enable: Setting in-call volume to maximum.\n");
    626         set_volume_rpc(VOICE_VOLUME_MAX);
    627     } else {
    628         LOGI("voice volume %f (range is 0 to %d)", vol, VOICE_VOLUME_MAX);
    629         set_volume_rpc(vol); //always set current device
    630     }
    631     mVoiceVolume = vol;
    632     return NO_ERROR;
    633 }
    634 
    635 status_t AudioHardware::setMasterVolume(float v)
    636 {
    637     LOGI("Set master volume to %f", v);
    638     // We return an error code here to let the audioflinger do in-software
    639     // volume on top of the maximum volume that we set through the SND API.
    640     // return error - software mixer will handle it
    641     return -1;
    642 }
    643 
    644 static status_t do_route_audio_dev_ctrl(uint32_t device, bool inCall, uint32_t rx_acdb_id, uint32_t tx_acdb_id)
    645 {
    646     uint32_t out_device = 0, mic_device = 0;
    647     uint32_t path[2];
    648     int fd = 0;
    649 
    650     if (device == SND_DEVICE_CURRENT)
    651         goto Incall;
    652 
    653     // hack -- kernel needs to put these in include file
    654     LOGD("Switching audio device to ");
    655     if (device == SND_DEVICE_HANDSET) {
    656            out_device = HANDSET_SPKR;
    657            mic_device = HANDSET_MIC;
    658            LOGD("Handset");
    659     } else if ((device  == SND_DEVICE_BT) || (device == SND_DEVICE_BT_EC_OFF)) {
    660            out_device = BT_SCO_SPKR;
    661            mic_device = BT_SCO_MIC;
    662            LOGD("BT Headset");
    663     } else if (device == SND_DEVICE_SPEAKER ||
    664                device == SND_DEVICE_SPEAKER_BACK_MIC) {
    665            out_device = SPKR_PHONE_MONO;
    666            mic_device = SPKR_PHONE_MIC;
    667            LOGD("Speakerphone");
    668     } else if (device == SND_DEVICE_HEADSET) {
    669            out_device = HEADSET_SPKR_STEREO;
    670            mic_device = HEADSET_MIC;
    671            LOGD("Stereo Headset");
    672     } else if (device == SND_DEVICE_HEADSET_AND_SPEAKER) {
    673            out_device = SPKR_PHONE_HEADSET_STEREO;
    674            mic_device = HEADSET_MIC;
    675            LOGD("Stereo Headset + Speaker");
    676     } else if (device == SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC) {
    677            out_device = SPKR_PHONE_HEADSET_STEREO;
    678            mic_device = SPKR_PHONE_MIC;
    679            LOGD("Stereo Headset + Speaker and back mic");
    680     } else if (device == SND_DEVICE_NO_MIC_HEADSET) {
    681            out_device = HEADSET_SPKR_STEREO;
    682            mic_device = HANDSET_MIC;
    683            LOGD("No microphone Wired Headset");
    684     } else if (device == SND_DEVICE_NO_MIC_HEADSET_BACK_MIC) {
    685            out_device = HEADSET_SPKR_STEREO;
    686            mic_device = SPKR_PHONE_MIC;
    687            LOGD("No microphone Wired Headset and back mic");
    688     } else if (device == SND_DEVICE_HANDSET_BACK_MIC) {
    689            out_device = HANDSET_SPKR;
    690            mic_device = SPKR_PHONE_MIC;
    691            LOGD("Handset and back mic");
    692     } else if (device == SND_DEVICE_FM_HEADSET) {
    693            out_device = FM_HEADSET;
    694            mic_device = HEADSET_MIC;
    695            LOGD("Stereo FM headset");
    696     } else if (device == SND_DEVICE_FM_SPEAKER) {
    697            out_device = FM_SPKR;
    698            mic_device = HEADSET_MIC;
    699            LOGD("Stereo FM speaker");
    700     } else if (device == SND_DEVICE_CARKIT) {
    701            out_device = BT_SCO_SPKR;
    702            mic_device = BT_SCO_MIC;
    703            LOGD("Carkit");
    704     } else if (device == SND_DEVICE_TTY_FULL) {
    705         out_device = TTY_HEADSET_SPKR;
    706         mic_device = TTY_HEADSET_MIC;
    707         LOGD("TTY FULL headset");
    708     } else if (device == SND_DEVICE_TTY_VCO) {
    709         out_device = TTY_HEADSET_SPKR;
    710         mic_device = SPKR_PHONE_MIC;
    711         LOGD("TTY VCO headset");
    712     } else if (device == SND_DEVICE_TTY_HCO) {
    713         out_device = SPKR_PHONE_MONO;
    714         mic_device = TTY_HEADSET_MIC;
    715         LOGD("TTY HCO headset");
    716     } else {
    717         LOGE("unknown device %d", device);
    718         return -1;
    719     }
    720 
    721 #if 0 //Add for FM support
    722     if (out_device == FM_HEADSET ||
    723         out_device == FM_SPKR) {
    724         if (fd_fm_device < 0) {
    725             fd_fm_device = open("/dev/msm_htc_fm", O_RDWR);
    726             if (fd_fm_device < 0) {
    727                 LOGE("Cannot open msm_htc_fm device");
    728                 return -1;
    729             }
    730             LOGD("Opened msm_htc_fm for FM radio");
    731         }
    732     } else if (fd_fm_device >= 0) {
    733         close(fd_fm_device);
    734         fd_fm_device = -1;
    735         LOGD("Closed msm_htc_fm after FM radio");
    736     }
    737 #endif
    738 
    739     fd = open("/dev/msm_audio_ctl", O_RDWR);
    740     if (fd < 0)        {
    741        LOGE("Cannot open msm_audio_ctl");
    742        return -1;
    743     }
    744     path[0] = out_device;
    745     path[1] = rx_acdb_id;
    746     if (ioctl(fd, AUDIO_SWITCH_DEVICE, &path)) {
    747        LOGE("Cannot switch audio device");
    748        close(fd);
    749        return -1;
    750     }
    751     path[0] = mic_device;
    752     path[1] = tx_acdb_id;
    753     if (ioctl(fd, AUDIO_SWITCH_DEVICE, &path)) {
    754        LOGE("Cannot switch mic device");
    755        close(fd);
    756        return -1;
    757     }
    758     curr_out_device = out_device;
    759     curr_mic_device = mic_device;
    760 
    761 Incall:
    762     if (inCall == true && !voice_started) {
    763         if (fd < 0) {
    764             fd = open("/dev/msm_audio_ctl", O_RDWR);
    765 
    766             if (fd < 0) {
    767                 LOGE("Cannot open msm_audio_ctl");
    768                 return -1;
    769             }
    770         }
    771         path[0] = rx_acdb_id;
    772         path[1] = tx_acdb_id;
    773         if (ioctl(fd, AUDIO_START_VOICE, &path)) {
    774             LOGE("Cannot start voice");
    775             close(fd);
    776             return -1;
    777         }
    778         LOGD("Voice Started!!");
    779         voice_started = 1;
    780     }
    781     else if (inCall == false && voice_started) {
    782         if (fd < 0) {
    783             fd = open("/dev/msm_audio_ctl", O_RDWR);
    784 
    785             if (fd < 0) {
    786                 LOGE("Cannot open msm_audio_ctl");
    787                 return -1;
    788             }
    789         }
    790         if (ioctl(fd, AUDIO_STOP_VOICE, NULL)) {
    791                LOGE("Cannot stop voice");
    792                close(fd);
    793                return -1;
    794         }
    795         LOGD("Voice Stopped!!");
    796         voice_started = 0;
    797     }
    798 
    799     close(fd);
    800     return NO_ERROR;
    801 }
    802 
    803 
    804 // always call with mutex held
    805 status_t AudioHardware::doAudioRouteOrMute(uint32_t device)
    806 {
    807     uint32_t rx_acdb_id = 0;
    808     uint32_t tx_acdb_id = 0;
    809 
    810     if (support_a1026 == 1)
    811             doAudience_A1026_Control(mMode, mRecordState, device);
    812 
    813     if (device == (uint32_t)SND_DEVICE_BT) {
    814         if (!mBluetoothNrec) {
    815             device = SND_DEVICE_BT_EC_OFF;
    816         }
    817     }
    818 
    819 
    820     if (device == (int) SND_DEVICE_BT) {
    821         if (mBluetoothIdTx != 0) {
    822             rx_acdb_id = mBluetoothIdRx;
    823             tx_acdb_id = mBluetoothIdTx;
    824         } else {
    825             /* use default BT entry defined in AudioBTID.csv */
    826             rx_acdb_id = mBTEndpoints[0].rx;
    827             tx_acdb_id = mBTEndpoints[0].tx;
    828             LOGD("Update ACDB ID to default BT setting\n");
    829         }
    830     }  else if (device == (int) SND_DEVICE_CARKIT
    831                 || device == (int) SND_DEVICE_BT_EC_OFF) {
    832         if (mBluetoothIdTx != 0) {
    833             rx_acdb_id = mBluetoothIdRx;
    834             tx_acdb_id = mBluetoothIdTx;
    835         } else {
    836             /* use default carkit entry defined in AudioBTID.csv */
    837             rx_acdb_id = mBTEndpoints[1].rx;
    838             tx_acdb_id = mBTEndpoints[1].tx;
    839             LOGD("Update ACDB ID to default carkit setting");
    840         }
    841     } else if (mMode == AudioSystem::MODE_IN_CALL
    842                && hac_enable && mHACSetting &&
    843                device == (int) SND_DEVICE_HANDSET) {
    844         LOGD("Update acdb id to hac profile.");
    845         rx_acdb_id = ACDB_ID_HAC_HANDSET_SPKR;
    846         tx_acdb_id = ACDB_ID_HAC_HANDSET_MIC;
    847     } else {
    848         if (!checkOutputStandby() || mMode != AudioSystem::MODE_IN_CALL)
    849             rx_acdb_id = getACDB(MOD_PLAY, device);
    850         if (mRecordState)
    851             tx_acdb_id = getACDB(MOD_REC, device);
    852     }
    853     LOGV("doAudioRouteOrMute: rx acdb %d, tx acdb %d\n", rx_acdb_id, tx_acdb_id);
    854 
    855     return do_route_audio_dev_ctrl(device, mMode == AudioSystem::MODE_IN_CALL, rx_acdb_id, tx_acdb_id);
    856 }
    857 
    858 status_t AudioHardware::get_mMode(void)
    859 {
    860     return mMode;
    861 }
    862 
    863 status_t AudioHardware::get_mRoutes(void)
    864 {
    865     return mRoutes[mMode];
    866 }
    867 
    868 status_t AudioHardware::set_mRecordState(bool onoff)
    869 {
    870     mRecordState = onoff;
    871     return 0;
    872 }
    873 
    874 status_t AudioHardware::get_batt_temp(int *batt_temp)
    875 {
    876     int fd, len;
    877     const char *fn =
    878             "/sys/devices/platform/ds2784-battery/power_supply/battery/temp";
    879     char get_batt_temp[6] = { 0 };
    880 
    881     if ((fd = open(fn, O_RDONLY)) < 0) {
    882         LOGE("%s: cannot open %s: %s\n", __FUNCTION__, fn, strerror(errno));
    883         return UNKNOWN_ERROR;
    884     }
    885 
    886     if ((len = read(fd, get_batt_temp, sizeof(get_batt_temp))) <= 1) {
    887         LOGE("read battery temp fail: %s\n", strerror(errno));
    888         close(fd);
    889         return BAD_VALUE;
    890     }
    891 
    892     *batt_temp = strtol(get_batt_temp, NULL, 10);
    893     close(fd);
    894     return NO_ERROR;
    895 }
    896 
    897 /*
    898  * Note: upon exiting doA1026_init(), fd_a1026 will be -1
    899  */
    900 status_t AudioHardware::doA1026_init(void)
    901 {
    902     struct a1026img fwimg;
    903     char char_tmp = 0;
    904     unsigned char local_vpimg_buf[A1026_MAX_FW_SIZE], *ptr = local_vpimg_buf;
    905     int rc = 0, fw_fd = -1;
    906     ssize_t nr;
    907     size_t remaining;
    908     struct stat fw_stat;
    909 
    910     static const char *const fn = "/system/etc/vpimg";
    911     static const char *const path = "/dev/audience_a1026";
    912 
    913     if (fd_a1026 < 0)
    914         fd_a1026 = open(path, O_RDWR | O_NONBLOCK, 0);
    915 
    916     if (fd_a1026 < 0) {
    917         LOGE("Cannot open %s %d\n", path, fd_a1026);
    918         support_a1026 = 0;
    919         goto open_drv_err;
    920     }
    921 
    922     fw_fd = open(fn, O_RDONLY);
    923     if (fw_fd < 0) {
    924         LOGE("Fail to open %s\n", fn);
    925         goto ld_img_error;
    926     } else {
    927         LOGD("open %s success\n", fn);
    928     }
    929 
    930     rc = fstat(fw_fd, &fw_stat);
    931     if (rc < 0) {
    932         LOGE("Cannot stat file %s: %s\n", fn, strerror(errno));
    933         goto ld_img_error;
    934     }
    935 
    936     remaining = (int)fw_stat.st_size;
    937 
    938     LOGD("Firmware %s size %d\n", fn, remaining);
    939 
    940     if (remaining > sizeof(local_vpimg_buf)) {
    941         LOGE("File %s size %d exceeds internal limit %d\n",
    942              fn, remaining, sizeof(local_vpimg_buf));
    943         goto ld_img_error;
    944     }
    945 
    946     while (remaining) {
    947         nr = read(fw_fd, ptr, remaining);
    948         if (nr < 0) {
    949             LOGE("Error reading firmware: %s\n", strerror(errno));
    950             goto ld_img_error;
    951         }
    952         else if (!nr) {
    953             if (remaining)
    954                 LOGW("EOF reading firmware %s while %d bytes remain\n",
    955                      fn, remaining);
    956             break;
    957         }
    958         remaining -= nr;
    959         ptr += nr;
    960     }
    961 
    962     close (fw_fd);
    963     fw_fd = -1;
    964 
    965     fwimg.buf = local_vpimg_buf;
    966     fwimg.img_size = (int)(fw_stat.st_size - remaining);
    967     LOGD("Total %d bytes put to user space buffer.\n", fwimg.img_size);
    968 
    969     rc = ioctl(fd_a1026, A1026_BOOTUP_INIT, &fwimg);
    970     if (!rc) {
    971         LOGD("audience_a1026 init OK\n");
    972         mA1026Init = 1;
    973     } else
    974         LOGE("audience_a1026 init failed\n");
    975 
    976 ld_img_error:
    977     if (fw_fd >= 0)
    978         close(fw_fd);
    979     close(fd_a1026);
    980 open_drv_err:
    981     fd_a1026 = -1;
    982     return rc;
    983 }
    984 
    985 status_t AudioHardware::get_snd_dev(void)
    986 {
    987     Mutex::Autolock lock(mLock);
    988     return mCurSndDevice;
    989 }
    990 
    991 uint32_t AudioHardware::getACDB(int mode, int device)
    992 {
    993     uint32_t acdb_id = 0;
    994     int batt_temp = 0;
    995     if (mMode == AudioSystem::MODE_IN_CALL) {
    996         LOGD("skip update ACDB due to in-call");
    997         return 0;
    998     }
    999 
   1000     if (mode == MOD_PLAY) {
   1001         switch (device) {
   1002             case SND_DEVICE_HEADSET:
   1003             case SND_DEVICE_NO_MIC_HEADSET:
   1004             case SND_DEVICE_NO_MIC_HEADSET_BACK_MIC:
   1005             case SND_DEVICE_FM_HEADSET:
   1006                 acdb_id = ACDB_ID_HEADSET_PLAYBACK;
   1007                 break;
   1008             case SND_DEVICE_SPEAKER:
   1009             case SND_DEVICE_FM_SPEAKER:
   1010             case SND_DEVICE_SPEAKER_BACK_MIC:
   1011                 acdb_id = ACDB_ID_SPKR_PLAYBACK;
   1012                 if(alt_enable) {
   1013                     LOGD("Enable ALT for speaker\n");
   1014                     if (get_batt_temp(&batt_temp) == NO_ERROR) {
   1015                         if (batt_temp < 50)
   1016                             acdb_id = ACDB_ID_ALT_SPKR_PLAYBACK;
   1017                         LOGD("ALT batt temp = %d\n", batt_temp);
   1018                     }
   1019                 }
   1020                 break;
   1021             case SND_DEVICE_HEADSET_AND_SPEAKER:
   1022             case SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC:
   1023                 acdb_id = ACDB_ID_HEADSET_RINGTONE_PLAYBACK;
   1024                 break;
   1025             default:
   1026                 break;
   1027         }
   1028     } else if (mode == MOD_REC) {
   1029         switch (device) {
   1030             case SND_DEVICE_HEADSET:
   1031             case SND_DEVICE_FM_HEADSET:
   1032             case SND_DEVICE_FM_SPEAKER:
   1033             case SND_DEVICE_HEADSET_AND_SPEAKER:
   1034                 acdb_id = ACDB_ID_EXT_MIC_REC;
   1035                 break;
   1036             case SND_DEVICE_HANDSET:
   1037             case SND_DEVICE_NO_MIC_HEADSET:
   1038             case SND_DEVICE_SPEAKER:
   1039                 if (vr_mode_enabled == 0) {
   1040                     acdb_id = ACDB_ID_INT_MIC_REC;
   1041                 } else {
   1042                     acdb_id = ACDB_ID_INT_MIC_VR;
   1043                 }
   1044                 break;
   1045             case SND_DEVICE_SPEAKER_BACK_MIC:
   1046             case SND_DEVICE_NO_MIC_HEADSET_BACK_MIC:
   1047             case SND_DEVICE_HANDSET_BACK_MIC:
   1048             case SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC:
   1049                 acdb_id = ACDB_ID_CAMCORDER;
   1050                 break;
   1051             default:
   1052                 break;
   1053         }
   1054     }
   1055     LOGV("getACDB, return ID %d\n", acdb_id);
   1056     return acdb_id;
   1057 }
   1058 
   1059 status_t AudioHardware::do_tpa2018_control(int mode)
   1060 {
   1061     if (curr_out_device == HANDSET_SPKR ||
   1062         curr_out_device == SPKR_PHONE_MONO ||
   1063         curr_out_device == HEADSET_SPKR_STEREO ||
   1064         curr_out_device == SPKR_PHONE_HEADSET_STEREO ||
   1065         curr_out_device == FM_SPKR) {
   1066 
   1067 	int fd, rc;
   1068         int retry = 3;
   1069 
   1070         switch (mode) {
   1071         case AudioSystem::MODE_NORMAL:
   1072             mode = TPA2018_MODE_PLAYBACK;
   1073             break;
   1074         case AudioSystem::MODE_RINGTONE:
   1075             mode = TPA2018_MODE_RINGTONE;
   1076             break;
   1077         case AudioSystem::MODE_IN_CALL:
   1078             mode = TPA2018_MODE_VOICE_CALL;
   1079             break;
   1080         default:
   1081             return 0;
   1082         }
   1083 
   1084         fd = open("/dev/tpa2018d1", O_RDWR);
   1085         if (fd < 0) {
   1086             LOGE("can't open /dev/tpa2018d1 %d", fd);
   1087             return -1;
   1088         }
   1089 
   1090         do {
   1091             rc = ioctl(fd, TPA2018_SET_MODE, &mode);
   1092             if (!rc)
   1093                 break;
   1094         } while (--retry);
   1095 
   1096         if (rc < 0) {
   1097             LOGE("ioctl TPA2018_SET_MODE failed: %s", strerror(errno));
   1098         } else
   1099             LOGD("Update TPA2018_SET_MODE to mode %d success", mode);
   1100 
   1101         close(fd);
   1102     }
   1103     return 0;
   1104 }
   1105 
   1106 status_t AudioHardware::doAudience_A1026_Control(int Mode, bool Record, uint32_t Routes)
   1107 {
   1108     int rc = 0;
   1109     int retry = 4;
   1110 
   1111     if (!mA1026Init) {
   1112         LOGW("Audience A1026 not initialized.\n");
   1113         return NO_INIT;
   1114     }
   1115 
   1116     mA1026Lock.lock();
   1117     if (fd_a1026 < 0) {
   1118         fd_a1026 = open("/dev/audience_a1026", O_RDWR);
   1119         if (fd_a1026 < 0) {
   1120             LOGE("Cannot open audience_a1026 device (%d)\n", fd_a1026);
   1121             mA1026Lock.unlock();
   1122             return -1;
   1123         }
   1124     }
   1125 
   1126     if ((Mode < AudioSystem::MODE_CURRENT) || (Mode >= AudioSystem::NUM_MODES)) {
   1127         LOGW("Illegal value: doAudience_A1026_Control(%d, %u, %u)", Mode, Record, Routes);
   1128         mA1026Lock.unlock();
   1129         return BAD_VALUE;
   1130     }
   1131 
   1132     if (Mode == AudioSystem::MODE_IN_CALL) {
   1133         if (Record == 1) {
   1134 	    switch (Routes) {
   1135 	        case SND_DEVICE_HANDSET:
   1136 	        case SND_DEVICE_NO_MIC_HEADSET:
   1137 	            //TODO: what do we do for camcorder when in call?
   1138 	        case SND_DEVICE_NO_MIC_HEADSET_BACK_MIC:
   1139 	        case SND_DEVICE_HANDSET_BACK_MIC:
   1140 	        case SND_DEVICE_TTY_VCO:
   1141 	            if (enable1026) {
   1142                     new_pathid = A1026_PATH_INCALL_RECEIVER;
   1143                     LOGV("A1026 control: new path is A1026_PATH_INCALL_RECEIVER");
   1144 	            } else {
   1145 	                new_pathid = A1026_PATH_INCALL_NO_NS_RECEIVER;
   1146 	                LOGV("A1026 control: new path is A1026_PATH_INCALL_NO_NS_RECEIVER");
   1147 	            }
   1148 	            break;
   1149 	        case SND_DEVICE_HEADSET:
   1150 	        case SND_DEVICE_HEADSET_AND_SPEAKER:
   1151 	        case SND_DEVICE_FM_HEADSET:
   1152 	        case SND_DEVICE_FM_SPEAKER:
   1153 	        case SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC:
   1154 	            new_pathid = A1026_PATH_INCALL_HEADSET;
   1155 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_HEADSET");
   1156 	            break;
   1157 	        case SND_DEVICE_SPEAKER:
   1158 	            //TODO: what do we do for camcorder when in call?
   1159 	        case SND_DEVICE_SPEAKER_BACK_MIC:
   1160 	            new_pathid = A1026_PATH_INCALL_SPEAKER;
   1161 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_SPEAKER");
   1162 	            break;
   1163 	        case SND_DEVICE_BT:
   1164 	        case SND_DEVICE_BT_EC_OFF:
   1165 	        case SND_DEVICE_CARKIT:
   1166 	            new_pathid = A1026_PATH_INCALL_BT;
   1167 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_BT");
   1168 	            break;
   1169 	        case SND_DEVICE_TTY_HCO:
   1170 	        case SND_DEVICE_TTY_FULL:
   1171 	            new_pathid = A1026_PATH_INCALL_TTY;
   1172 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_TTY");
   1173 	            break;
   1174 	        default:
   1175 	            break;
   1176             }
   1177        } else {
   1178            switch (Routes) {
   1179 	        case SND_DEVICE_HANDSET:
   1180 	        case SND_DEVICE_NO_MIC_HEADSET:
   1181 	        case SND_DEVICE_TTY_VCO:
   1182 	            if (enable1026) {
   1183 	                new_pathid = A1026_PATH_INCALL_RECEIVER; /* NS CT mode, Dual MIC */
   1184                     LOGV("A1026 control: new path is A1026_PATH_INCALL_RECEIVER");
   1185 	            } else {
   1186 	                new_pathid = A1026_PATH_INCALL_NO_NS_RECEIVER;
   1187 	                LOGV("A1026 control: new path is A1026_PATH_INCALL_NO_NS_RECEIVER");
   1188 	            }
   1189 	            break;
   1190 	        case SND_DEVICE_HEADSET:
   1191 	        case SND_DEVICE_HEADSET_AND_SPEAKER:
   1192 	        case SND_DEVICE_FM_HEADSET:
   1193 	        case SND_DEVICE_FM_SPEAKER:
   1194 	            new_pathid = A1026_PATH_INCALL_HEADSET; /* NS disable, Headset MIC */
   1195 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_HEADSET");
   1196 	            break;
   1197 	        case SND_DEVICE_SPEAKER:
   1198 	            new_pathid = A1026_PATH_INCALL_SPEAKER; /* NS FT mode, Main MIC */
   1199 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_SPEAKER");
   1200 	            break;
   1201 	        case SND_DEVICE_BT:
   1202 	        case SND_DEVICE_BT_EC_OFF:
   1203 	        case SND_DEVICE_CARKIT:
   1204 	            new_pathid = A1026_PATH_INCALL_BT; /* QCOM NS, BT MIC */
   1205 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_BT");
   1206 	            break;
   1207 	        case SND_DEVICE_TTY_HCO:
   1208 	        case SND_DEVICE_TTY_FULL:
   1209 	            new_pathid = A1026_PATH_INCALL_TTY;
   1210 	            LOGV("A1026 control: new path is A1026_PATH_INCALL_TTY");
   1211 	            break;
   1212 	        default:
   1213 	            break;
   1214             }
   1215        }
   1216     } else if (Record == 1) {
   1217         switch (Routes) {
   1218         case SND_DEVICE_SPEAKER:
   1219             // default output is speaker, recording from phone mic, user RECEIVER configuration
   1220         case SND_DEVICE_HANDSET:
   1221         case SND_DEVICE_NO_MIC_HEADSET:
   1222 	        if (vr_mode_enabled) {
   1223 	            if (vr_uses_ns) {
   1224 	                new_pathid = A1026_PATH_VR_NS_RECEIVER;
   1225 	                LOGV("A1026 control: new path is A1026_PATH_VR_NS_RECEIVER");
   1226 	            } else {
   1227 	                new_pathid = A1026_PATH_VR_NO_NS_RECEIVER;
   1228 	                LOGV("A1026 control: new path is A1026_PATH_VR_NO_NS_RECEIVER");
   1229 	            }
   1230 	        } else {
   1231 	            new_pathid = A1026_PATH_RECORD_RECEIVER; /* INT-MIC Recording: NS disable, Main MIC */
   1232                 LOGV("A1026 control: new path is A1026_PATH_RECORD_RECEIVER");
   1233 	        }
   1234 	        break;
   1235         case SND_DEVICE_HEADSET:
   1236         case SND_DEVICE_HEADSET_AND_SPEAKER:
   1237         case SND_DEVICE_FM_HEADSET:
   1238         case SND_DEVICE_FM_SPEAKER:
   1239 	        if (vr_mode_enabled) {
   1240 	            if (vr_uses_ns) {
   1241 	                new_pathid = A1026_PATH_VR_NS_HEADSET;
   1242 	                LOGV("A1026 control: new path is A1026_PATH_VR_NS_HEADSET");
   1243 	            } else {
   1244 	                new_pathid = A1026_PATH_VR_NO_NS_HEADSET;
   1245 	                LOGV("A1026 control: new path is A1026_PATH_VR_NO_NS_HEADSET");
   1246 	            }
   1247 	        } else {
   1248 	            new_pathid = A1026_PATH_RECORD_HEADSET; /* EXT-MIC Recording: NS disable, Headset MIC */
   1249 	            LOGV("A1026 control: new path is A1026_PATH_RECORD_HEADSET");
   1250 	        }
   1251 	        break;
   1252         case SND_DEVICE_SPEAKER_BACK_MIC:
   1253         case SND_DEVICE_NO_MIC_HEADSET_BACK_MIC:
   1254         case SND_DEVICE_HANDSET_BACK_MIC:
   1255         case SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC:
   1256 	        new_pathid = A1026_PATH_CAMCORDER; /* CAM-Coder: NS FT mode, Back MIC */
   1257 	        LOGV("A1026 control: new path is A1026_PATH_CAMCORDER");
   1258 	        break;
   1259         case SND_DEVICE_BT:
   1260         case SND_DEVICE_BT_EC_OFF:
   1261         case SND_DEVICE_CARKIT:
   1262 	        if (vr_mode_enabled) {
   1263 	            if (vr_uses_ns) {
   1264 	                new_pathid = A1026_PATH_VR_NS_BT;
   1265 	                LOGV("A1026 control: new path is A1026_PATH_VR_NS_BT");
   1266 	            } else {
   1267 	                new_pathid = A1026_PATH_VR_NO_NS_BT;
   1268 	                LOGV("A1026 control: new path is A1026_PATH_VR_NO_NS_BT");
   1269 	            }
   1270 	        } else {
   1271 	            new_pathid = A1026_PATH_RECORD_BT; /* BT MIC */
   1272 	            LOGV("A1026 control: new path is A1026_PATH_RECORD_BT");
   1273 	        }
   1274 	        break;
   1275         default:
   1276 	        break;
   1277         }
   1278     }
   1279     else {
   1280         switch (Routes) {
   1281         case SND_DEVICE_BT:
   1282         case SND_DEVICE_BT_EC_OFF:
   1283         case SND_DEVICE_CARKIT:
   1284             new_pathid = A1026_PATH_RECORD_BT; /* BT MIC */
   1285             LOGV("A1026 control: new path is A1026_PATH_RECORD_BT");
   1286             break;
   1287         default:
   1288             new_pathid = A1026_PATH_SUSPEND;
   1289             break;
   1290         }
   1291     }
   1292 
   1293     if (old_pathid != new_pathid) {
   1294         //LOGI("A1026: do ioctl(A1026_SET_CONFIG) to %d\n", new_pathid);
   1295         do {
   1296             rc = ioctl(fd_a1026, A1026_SET_CONFIG, &new_pathid);
   1297             if (!rc) {
   1298                 old_pathid = new_pathid;
   1299                 break;
   1300             }
   1301         } while (--retry);
   1302 
   1303         if (rc < 0) {
   1304             LOGW("A1026 do hard reset to recover from error!\n");
   1305             rc = doA1026_init(); /* A1026 needs to do hard reset! */
   1306             if (!rc) {
   1307                 /* after doA1026_init(), fd_a1026 is -1*/
   1308                 fd_a1026 = open("/dev/audience_a1026", O_RDWR);
   1309                 if (fd_a1026 < 0) {
   1310                     LOGE("A1026 Fatal Error: unable to open A1026 after hard reset\n");
   1311                 } else {
   1312                     rc = ioctl(fd_a1026, A1026_SET_CONFIG, &new_pathid);
   1313                     if (!rc) {
   1314                         old_pathid = new_pathid;
   1315                     } else {
   1316                         LOGE("A1026 Fatal Error: unable to A1026_SET_CONFIG after hard reset\n");
   1317                     }
   1318                 }
   1319             } else
   1320                 LOGE("A1026 Fatal Error: Re-init A1026 Failed\n");
   1321         }
   1322     }
   1323 
   1324     if (fd_a1026 >= 0) {
   1325         close(fd_a1026);
   1326     }
   1327     fd_a1026 = -1;
   1328     mA1026Lock.unlock();
   1329 
   1330     return rc;
   1331 }
   1332 
   1333 
   1334 status_t AudioHardware::doRouting()
   1335 {
   1336     Mutex::Autolock lock(mLock);
   1337     uint32_t outputDevices = mOutput->devices();
   1338     status_t ret = NO_ERROR;
   1339     AudioStreamInMSM72xx *input = getActiveInput_l();
   1340     uint32_t inputDevice = (input == NULL) ? 0 : input->devices();
   1341     int sndDevice = -1;
   1342 
   1343     if (mMode == AudioSystem::MODE_IN_CALL && mTTYMode != TTY_MODE_OFF) {
   1344         if ((outputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET) ||
   1345             (outputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) {
   1346             switch (mTTYMode) {
   1347             case TTY_MODE_FULL:
   1348                 sndDevice = SND_DEVICE_TTY_FULL;
   1349                 break;
   1350             case TTY_MODE_VCO:
   1351                 sndDevice = SND_DEVICE_TTY_VCO;
   1352                 break;
   1353             case TTY_MODE_HCO:
   1354                 sndDevice = SND_DEVICE_TTY_HCO;
   1355                 break;
   1356             }
   1357         }
   1358     }
   1359 
   1360     if (sndDevice == -1 && inputDevice != 0) {
   1361         LOGI("do input routing device %x\n", inputDevice);
   1362         if (inputDevice & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
   1363             LOGI("Routing audio to Bluetooth PCM\n");
   1364             sndDevice = SND_DEVICE_BT;
   1365         } else if (inputDevice & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
   1366             LOGI("Routing audio to Bluetooth car kit\n");
   1367             sndDevice = SND_DEVICE_CARKIT;
   1368         } else if (inputDevice & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
   1369             if ((outputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET) &&
   1370                     (outputDevices & AudioSystem::DEVICE_OUT_SPEAKER)) {
   1371                         LOGI("Routing audio to Wired Headset and Speaker\n");
   1372                         sndDevice = SND_DEVICE_HEADSET_AND_SPEAKER;
   1373             } else {
   1374                 LOGI("Routing audio to Wired Headset\n");
   1375                 sndDevice = SND_DEVICE_HEADSET;
   1376             }
   1377         } else if (inputDevice & AudioSystem::DEVICE_IN_BACK_MIC) {
   1378             if (outputDevices & (AudioSystem:: DEVICE_OUT_WIRED_HEADSET) &&
   1379                    (outputDevices & AudioSystem:: DEVICE_OUT_SPEAKER)) {
   1380                 LOGI("Routing audio to Wired Headset and Speaker with back mic\n");
   1381                 sndDevice = SND_DEVICE_HEADSET_AND_SPEAKER_BACK_MIC;
   1382             } else if (outputDevices & AudioSystem::DEVICE_OUT_SPEAKER) {
   1383                 LOGI("Routing audio to Speakerphone with back mic\n");
   1384                 sndDevice = SND_DEVICE_SPEAKER_BACK_MIC;
   1385             } else if (outputDevices == AudioSystem::DEVICE_OUT_EARPIECE) {
   1386                 LOGI("Routing audio to Handset with back mic\n");
   1387                 sndDevice = SND_DEVICE_HANDSET_BACK_MIC;
   1388             } else {
   1389                 LOGI("Routing audio to Headset with back mic\n");
   1390                 sndDevice = SND_DEVICE_NO_MIC_HEADSET_BACK_MIC;
   1391             }
   1392         } else {
   1393             if (outputDevices & AudioSystem::DEVICE_OUT_SPEAKER) {
   1394                 LOGI("Routing audio to Speakerphone\n");
   1395                 sndDevice = SND_DEVICE_SPEAKER;
   1396             } else if (outputDevices == AudioSystem::DEVICE_OUT_WIRED_HEADPHONE) {
   1397                 LOGI("Routing audio to Speakerphone\n");
   1398                 sndDevice = SND_DEVICE_NO_MIC_HEADSET;
   1399             } else {
   1400                 LOGI("Routing audio to Handset\n");
   1401                 sndDevice = SND_DEVICE_HANDSET;
   1402             }
   1403         }
   1404     }
   1405     // if inputDevice == 0, restore output routing
   1406 
   1407     if (sndDevice == -1) {
   1408         if (outputDevices & (outputDevices - 1)) {
   1409             if ((outputDevices & AudioSystem::DEVICE_OUT_SPEAKER) == 0) {
   1410                 LOGW("Hardware does not support requested route combination (%#X),"
   1411                         " picking closest possible route...", outputDevices);
   1412             }
   1413         }
   1414 
   1415         if (outputDevices &
   1416                 (AudioSystem::DEVICE_OUT_BLUETOOTH_SCO | AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET)) {
   1417                     LOGI("Routing audio to Bluetooth PCM\n");
   1418                     sndDevice = SND_DEVICE_BT;
   1419         } else if (outputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
   1420             LOGI("Routing audio to Bluetooth PCM\n");
   1421             sndDevice = SND_DEVICE_CARKIT;
   1422         } else if ((outputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET) &&
   1423                 (outputDevices & AudioSystem::DEVICE_OUT_SPEAKER)) {
   1424                     LOGI("Routing audio to Wired Headset and Speaker\n");
   1425                     sndDevice = SND_DEVICE_HEADSET_AND_SPEAKER;
   1426         } else if (outputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE) {
   1427             if (outputDevices & AudioSystem::DEVICE_OUT_SPEAKER) {
   1428                 LOGI("Routing audio to No microphone Wired Headset and Speaker (%d,%x)\n", mMode, outputDevices);
   1429                 sndDevice = SND_DEVICE_HEADSET_AND_SPEAKER;
   1430             } else {
   1431                 LOGI("Routing audio to No microphone Wired Headset (%d,%x)\n", mMode, outputDevices);
   1432                 sndDevice = SND_DEVICE_NO_MIC_HEADSET;
   1433             }
   1434         } else if (outputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
   1435             LOGI("Routing audio to Wired Headset\n");
   1436             sndDevice = SND_DEVICE_HEADSET;
   1437         } else if (outputDevices & AudioSystem::DEVICE_OUT_SPEAKER) {
   1438             LOGI("Routing audio to Speakerphone\n");
   1439             sndDevice = SND_DEVICE_SPEAKER;
   1440         } else {
   1441             LOGI("Routing audio to Handset\n");
   1442             sndDevice = SND_DEVICE_HANDSET;
   1443         }
   1444     }
   1445 
   1446     if ((vr_mode_change) || (sndDevice != -1 && sndDevice != mCurSndDevice)) {
   1447         ret = doAudioRouteOrMute(sndDevice);
   1448         mCurSndDevice = sndDevice;
   1449         if (mMode == AudioSystem::MODE_IN_CALL) {
   1450             if (mHACSetting && hac_enable && mCurSndDevice == (int) SND_DEVICE_HANDSET) {
   1451                 LOGD("HAC enable: Setting in-call volume to maximum.\n");
   1452                 set_volume_rpc(VOICE_VOLUME_MAX);
   1453             } else {
   1454                 set_volume_rpc(mVoiceVolume);
   1455             }
   1456         }
   1457     }
   1458 
   1459     return ret;
   1460 }
   1461 
   1462 status_t AudioHardware::checkMicMute()
   1463 {
   1464     Mutex::Autolock lock(mLock);
   1465     if (mMode != AudioSystem::MODE_IN_CALL) {
   1466         setMicMute_nosync(true);
   1467     }
   1468 
   1469     return NO_ERROR;
   1470 }
   1471 
   1472 status_t AudioHardware::dumpInternals(int fd, const Vector<String16>& args)
   1473 {
   1474     const size_t SIZE = 256;
   1475     char buffer[SIZE];
   1476     String8 result;
   1477     result.append("AudioHardware::dumpInternals\n");
   1478     snprintf(buffer, SIZE, "\tmInit: %s\n", mInit? "true": "false");
   1479     result.append(buffer);
   1480     snprintf(buffer, SIZE, "\tmMicMute: %s\n", mMicMute? "true": "false");
   1481     result.append(buffer);
   1482     snprintf(buffer, SIZE, "\tmBluetoothNrec: %s\n", mBluetoothNrec? "true": "false");
   1483     result.append(buffer);
   1484     snprintf(buffer, SIZE, "\tmBluetoothIdtx: %d\n", mBluetoothIdTx);
   1485     result.append(buffer);
   1486     snprintf(buffer, SIZE, "\tmBluetoothIdrx: %d\n", mBluetoothIdRx);
   1487     result.append(buffer);
   1488     ::write(fd, result.string(), result.size());
   1489     return NO_ERROR;
   1490 }
   1491 
   1492 status_t AudioHardware::dump(int fd, const Vector<String16>& args)
   1493 {
   1494     dumpInternals(fd, args);
   1495     for (size_t index = 0; index < mInputs.size(); index++) {
   1496         mInputs[index]->dump(fd, args);
   1497     }
   1498 
   1499     if (mOutput) {
   1500         mOutput->dump(fd, args);
   1501     }
   1502     return NO_ERROR;
   1503 }
   1504 
   1505 uint32_t AudioHardware::getInputSampleRate(uint32_t sampleRate)
   1506 {
   1507     uint32_t i;
   1508     uint32_t prevDelta;
   1509     uint32_t delta;
   1510 
   1511     for (i = 0, prevDelta = 0xFFFFFFFF; i < sizeof(inputSamplingRates)/sizeof(uint32_t); i++, prevDelta = delta) {
   1512         delta = abs(sampleRate - inputSamplingRates[i]);
   1513         if (delta > prevDelta) break;
   1514     }
   1515     // i is always > 0 here
   1516     return inputSamplingRates[i-1];
   1517 }
   1518 
   1519 // getActiveInput_l() must be called with mLock held
   1520 AudioHardware::AudioStreamInMSM72xx *AudioHardware::getActiveInput_l()
   1521 {
   1522     for (size_t i = 0; i < mInputs.size(); i++) {
   1523         // return first input found not being in standby mode
   1524         // as only one input can be in this state
   1525         if (mInputs[i]->state() > AudioStreamInMSM72xx::AUDIO_INPUT_CLOSED) {
   1526             return mInputs[i];
   1527         }
   1528     }
   1529 
   1530     return NULL;
   1531 }
   1532 // ----------------------------------------------------------------------------
   1533 
   1534 AudioHardware::AudioStreamOutMSM72xx::AudioStreamOutMSM72xx() :
   1535     mHardware(0), mFd(-1), mStartCount(0), mRetryCount(0), mStandby(true),
   1536     mDevices(0), mChannels(AUDIO_HW_OUT_CHANNELS), mSampleRate(AUDIO_HW_OUT_SAMPLERATE),
   1537     mBufferSize(AUDIO_HW_OUT_BUFSZ)
   1538 {
   1539 }
   1540 
   1541 status_t AudioHardware::AudioStreamOutMSM72xx::set(
   1542         AudioHardware* hw, uint32_t devices, int *pFormat, uint32_t *pChannels, uint32_t *pRate)
   1543 {
   1544     int lFormat = pFormat ? *pFormat : 0;
   1545     uint32_t lChannels = pChannels ? *pChannels : 0;
   1546     uint32_t lRate = pRate ? *pRate : 0;
   1547 
   1548     mHardware = hw;
   1549     mDevices = devices;
   1550 
   1551     // fix up defaults
   1552     if (lFormat == 0) lFormat = format();
   1553     if (lChannels == 0) lChannels = channels();
   1554     if (lRate == 0) lRate = sampleRate();
   1555 
   1556     // check values
   1557     if ((lFormat != format()) ||
   1558         (lChannels != channels()) ||
   1559         (lRate != sampleRate())) {
   1560         if (pFormat) *pFormat = format();
   1561         if (pChannels) *pChannels = channels();
   1562         if (pRate) *pRate = sampleRate();
   1563         return BAD_VALUE;
   1564     }
   1565 
   1566     if (pFormat) *pFormat = lFormat;
   1567     if (pChannels) *pChannels = lChannels;
   1568     if (pRate) *pRate = lRate;
   1569 
   1570     mChannels = lChannels;
   1571     mSampleRate = lRate;
   1572     mBufferSize = hw->getBufferSize(lRate, AudioSystem::popCount(lChannels));
   1573 
   1574     return NO_ERROR;
   1575 }
   1576 
   1577 AudioHardware::AudioStreamOutMSM72xx::~AudioStreamOutMSM72xx()
   1578 {
   1579     standby();
   1580 }
   1581 
   1582 ssize_t AudioHardware::AudioStreamOutMSM72xx::write(const void* buffer, size_t bytes)
   1583 {
   1584     // LOGD("AudioStreamOutMSM72xx::write(%p, %u)", buffer, bytes);
   1585     status_t status = NO_INIT;
   1586     size_t count = bytes;
   1587     const uint8_t* p = static_cast<const uint8_t*>(buffer);
   1588 
   1589     if (mStandby) {
   1590 
   1591         LOGV("acquire output wakelock");
   1592         acquire_wake_lock(PARTIAL_WAKE_LOCK, kOutputWakelockStr);
   1593 
   1594         // open driver
   1595         LOGV("open pcm_out driver");
   1596         status = ::open("/dev/msm_pcm_out", O_RDWR);
   1597         if (status < 0) {
   1598             if (errCount++ < 10) {
   1599                 LOGE("Cannot open /dev/msm_pcm_out errno: %d", errno);
   1600             }
   1601             goto Error;
   1602         }
   1603         mFd = status;
   1604 
   1605         // configuration
   1606         LOGV("get config");
   1607         struct msm_audio_config config;
   1608         status = ioctl(mFd, AUDIO_GET_CONFIG, &config);
   1609         if (status < 0) {
   1610             LOGE("Cannot read pcm_out config");
   1611             goto Error;
   1612         }
   1613 
   1614         LOGV("set pcm_out config");
   1615         config.channel_count = AudioSystem::popCount(channels());
   1616         config.sample_rate = mSampleRate;
   1617         config.buffer_size = mBufferSize;
   1618         config.buffer_count = AUDIO_HW_NUM_OUT_BUF;
   1619         config.codec_type = CODEC_TYPE_PCM;
   1620         status = ioctl(mFd, AUDIO_SET_CONFIG, &config);
   1621         if (status < 0) {
   1622             LOGE("Cannot set config");
   1623             goto Error;
   1624         }
   1625 
   1626         LOGV("buffer_size: %u", config.buffer_size);
   1627         LOGV("buffer_count: %u", config.buffer_count);
   1628         LOGV("channel_count: %u", config.channel_count);
   1629         LOGV("sample_rate: %u", config.sample_rate);
   1630 
   1631         uint32_t acdb_id = mHardware->getACDB(MOD_PLAY, mHardware->get_snd_dev());
   1632         status = ioctl(mFd, AUDIO_START, &acdb_id);
   1633         if (status < 0) {
   1634             LOGE("Cannot start pcm playback");
   1635             goto Error;
   1636         }
   1637 
   1638         status = ioctl(mFd, AUDIO_SET_VOLUME, &stream_volume);
   1639         if (status < 0) {
   1640             LOGE("Cannot start pcm playback");
   1641             goto Error;
   1642         }
   1643 
   1644         mStandby = false;
   1645     }
   1646 
   1647     while (count) {
   1648         ssize_t written = ::write(mFd, p, count);
   1649         if (written >= 0) {
   1650             count -= written;
   1651             p += written;
   1652         } else {
   1653             if (errno != EAGAIN) return written;
   1654             mRetryCount++;
   1655             LOGD("EAGAIN - retry");
   1656         }
   1657     }
   1658 
   1659     return bytes;
   1660 
   1661 Error:
   1662     if (mFd >= 0) {
   1663         ::close(mFd);
   1664         mFd = -1;
   1665     }
   1666     // Simulate audio output timing in case of error
   1667     usleep(bytes * 1000000 / frameSize() / sampleRate());
   1668     release_wake_lock(kOutputWakelockStr);
   1669     return status;
   1670 }
   1671 
   1672 status_t AudioHardware::AudioStreamOutMSM72xx::standby()
   1673 {
   1674     status_t status = NO_ERROR;
   1675     if (!mStandby && mFd >= 0) {
   1676         ::close(mFd);
   1677         mFd = -1;
   1678         LOGV("release output wakelock");
   1679         release_wake_lock(kOutputWakelockStr);
   1680     }
   1681     mStandby = true;
   1682     LOGD("AudioHardware pcm playback is going to standby.");
   1683     return status;
   1684 }
   1685 
   1686 status_t AudioHardware::AudioStreamOutMSM72xx::dump(int fd, const Vector<String16>& args)
   1687 {
   1688     const size_t SIZE = 256;
   1689     char buffer[SIZE];
   1690     String8 result;
   1691     result.append("AudioStreamOutMSM72xx::dump\n");
   1692     snprintf(buffer, SIZE, "\tsample rate: %d\n", sampleRate());
   1693     result.append(buffer);
   1694     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
   1695     result.append(buffer);
   1696     snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
   1697     result.append(buffer);
   1698     snprintf(buffer, SIZE, "\tformat: %d\n", format());
   1699     result.append(buffer);
   1700     snprintf(buffer, SIZE, "\tmHardware: %p\n", mHardware);
   1701     result.append(buffer);
   1702     snprintf(buffer, SIZE, "\tmFd: %d\n", mFd);
   1703     result.append(buffer);
   1704     snprintf(buffer, SIZE, "\tmStartCount: %d\n", mStartCount);
   1705     result.append(buffer);
   1706     snprintf(buffer, SIZE, "\tmRetryCount: %d\n", mRetryCount);
   1707     result.append(buffer);
   1708     snprintf(buffer, SIZE, "\tmStandby: %s\n", mStandby? "true": "false");
   1709     result.append(buffer);
   1710     ::write(fd, result.string(), result.size());
   1711     return NO_ERROR;
   1712 }
   1713 
   1714 bool AudioHardware::AudioStreamOutMSM72xx::checkStandby()
   1715 {
   1716     return mStandby;
   1717 }
   1718 
   1719 
   1720 status_t AudioHardware::AudioStreamOutMSM72xx::setParameters(const String8& keyValuePairs)
   1721 {
   1722     AudioParameter param = AudioParameter(keyValuePairs);
   1723     String8 key = String8(AudioParameter::keyRouting);
   1724     status_t status = NO_ERROR;
   1725     int device;
   1726     LOGV("AudioStreamOutMSM72xx::setParameters() %s", keyValuePairs.string());
   1727 
   1728     if (param.getInt(key, device) == NO_ERROR) {
   1729         mDevices = device;
   1730         LOGV("set output routing %x", mDevices);
   1731         status = mHardware->doRouting();
   1732         param.remove(key);
   1733     }
   1734 
   1735     if (param.size()) {
   1736         status = BAD_VALUE;
   1737     }
   1738     return status;
   1739 }
   1740 
   1741 String8 AudioHardware::AudioStreamOutMSM72xx::getParameters(const String8& keys)
   1742 {
   1743     AudioParameter param = AudioParameter(keys);
   1744     String8 value;
   1745     String8 key = String8(AudioParameter::keyRouting);
   1746 
   1747     if (param.get(key, value) == NO_ERROR) {
   1748         LOGV("get routing %x", mDevices);
   1749         param.addInt(key, (int)mDevices);
   1750     }
   1751 
   1752     LOGV("AudioStreamOutMSM72xx::getParameters() %s", param.toString().string());
   1753     return param.toString();
   1754 }
   1755 
   1756 status_t AudioHardware::AudioStreamOutMSM72xx::getRenderPosition(uint32_t *dspFrames)
   1757 {
   1758     //TODO: enable when supported by driver
   1759     return INVALID_OPERATION;
   1760 }
   1761 
   1762 // ----------------------------------------------------------------------------
   1763 
   1764 AudioHardware::AudioStreamInMSM72xx::AudioStreamInMSM72xx() :
   1765     mHardware(0), mFd(-1), mState(AUDIO_INPUT_CLOSED), mRetryCount(0),
   1766     mFormat(AUDIO_HW_IN_FORMAT), mChannels(AUDIO_HW_IN_CHANNELS),
   1767     mSampleRate(AUDIO_HW_IN_SAMPLERATE), mBufferSize(AUDIO_HW_IN_BUFSZ),
   1768     mAcoustics((AudioSystem::audio_in_acoustics)0), mDevices(0)
   1769 {
   1770 }
   1771 
   1772 status_t AudioHardware::AudioStreamInMSM72xx::set(
   1773         AudioHardware* hw, uint32_t devices, int *pFormat, uint32_t *pChannels, uint32_t *pRate,
   1774         AudioSystem::audio_in_acoustics acoustic_flags)
   1775 {
   1776     if (pFormat == 0 || *pFormat != AUDIO_HW_IN_FORMAT) {
   1777         *pFormat = AUDIO_HW_IN_FORMAT;
   1778         return BAD_VALUE;
   1779     }
   1780     if (pRate == 0) {
   1781         return BAD_VALUE;
   1782     }
   1783     uint32_t rate = hw->getInputSampleRate(*pRate);
   1784     if (rate != *pRate) {
   1785         *pRate = rate;
   1786         return BAD_VALUE;
   1787     }
   1788 
   1789     if (pChannels == 0 || (*pChannels != AudioSystem::CHANNEL_IN_MONO &&
   1790         *pChannels != AudioSystem::CHANNEL_IN_STEREO)) {
   1791         *pChannels = AUDIO_HW_IN_CHANNELS;
   1792         return BAD_VALUE;
   1793     }
   1794 
   1795     mHardware = hw;
   1796 
   1797     LOGV("AudioStreamInMSM72xx::set(%d, %d, %u)", *pFormat, *pChannels, *pRate);
   1798     if (mFd >= 0) {
   1799         LOGE("Audio record already open");
   1800         return -EPERM;
   1801     }
   1802 
   1803     // open audio input device
   1804     status_t status = ::open("/dev/msm_pcm_in", O_RDWR);
   1805     if (status < 0) {
   1806         LOGE("Cannot open /dev/msm_pcm_in errno: %d", errno);
   1807         goto Error;
   1808     }
   1809     mFd = status;
   1810     mBufferSize = hw->getBufferSize(*pRate, AudioSystem::popCount(*pChannels));
   1811 
   1812     // configuration
   1813     LOGV("get config");
   1814     struct msm_audio_config config;
   1815     status = ioctl(mFd, AUDIO_GET_CONFIG, &config);
   1816     if (status < 0) {
   1817         LOGE("Cannot read config");
   1818         goto Error;
   1819     }
   1820 
   1821     LOGV("set config");
   1822     config.channel_count = AudioSystem::popCount(*pChannels);
   1823     config.sample_rate = *pRate;
   1824     config.buffer_size = mBufferSize;
   1825     config.buffer_count = 2;
   1826     config.codec_type = CODEC_TYPE_PCM;
   1827     status = ioctl(mFd, AUDIO_SET_CONFIG, &config);
   1828     if (status < 0) {
   1829         LOGE("Cannot set config");
   1830         if (ioctl(mFd, AUDIO_GET_CONFIG, &config) == 0) {
   1831             if (config.channel_count == 1) {
   1832                 *pChannels = AudioSystem::CHANNEL_IN_MONO;
   1833             } else {
   1834                 *pChannels = AudioSystem::CHANNEL_IN_STEREO;
   1835             }
   1836             *pRate = config.sample_rate;
   1837         }
   1838         goto Error;
   1839     }
   1840 
   1841     LOGV("confirm config");
   1842     status = ioctl(mFd, AUDIO_GET_CONFIG, &config);
   1843     if (status < 0) {
   1844         LOGE("Cannot read config");
   1845         goto Error;
   1846     }
   1847     LOGV("buffer_size: %u", config.buffer_size);
   1848     LOGV("buffer_count: %u", config.buffer_count);
   1849     LOGV("channel_count: %u", config.channel_count);
   1850     LOGV("sample_rate: %u", config.sample_rate);
   1851 
   1852     mDevices = devices;
   1853     mFormat = AUDIO_HW_IN_FORMAT;
   1854     mChannels = *pChannels;
   1855     mSampleRate = config.sample_rate;
   1856     mBufferSize = config.buffer_size;
   1857 
   1858     //mHardware->setMicMute_nosync(false);
   1859     mState = AUDIO_INPUT_OPENED;
   1860 
   1861     return NO_ERROR;
   1862 
   1863 Error:
   1864     if (mFd >= 0) {
   1865         ::close(mFd);
   1866         mFd = -1;
   1867     }
   1868     return status;
   1869 }
   1870 
   1871 AudioHardware::AudioStreamInMSM72xx::~AudioStreamInMSM72xx()
   1872 {
   1873     LOGV("AudioStreamInMSM72xx destructor");
   1874     standby();
   1875 }
   1876 
   1877 ssize_t AudioHardware::AudioStreamInMSM72xx::read( void* buffer, ssize_t bytes)
   1878 {
   1879     LOGV("AudioStreamInMSM72xx::read(%p, %ld)", buffer, bytes);
   1880     if (!mHardware) return -1;
   1881 
   1882     size_t count = bytes;
   1883     uint8_t* p = static_cast<uint8_t*>(buffer);
   1884 
   1885     if (mState < AUDIO_INPUT_OPENED) {
   1886         Mutex::Autolock lock(mHardware->mLock);
   1887         if (set(mHardware, mDevices, &mFormat, &mChannels, &mSampleRate, mAcoustics) != NO_ERROR) {
   1888             return -1;
   1889         }
   1890     }
   1891 
   1892     if (mState < AUDIO_INPUT_STARTED) {
   1893         mState = AUDIO_INPUT_STARTED;
   1894         mHardware->set_mRecordState(1);
   1895         // make sure a1026 config is re-applied even is input device is not changed
   1896         mHardware->clearCurDevice();
   1897         mHardware->doRouting();
   1898 
   1899         LOGV("acquire input wakelock");
   1900         acquire_wake_lock(PARTIAL_WAKE_LOCK, kInputWakelockStr);
   1901         uint32_t acdb_id = mHardware->getACDB(MOD_REC, mHardware->get_snd_dev());
   1902         if (ioctl(mFd, AUDIO_START, &acdb_id)) {
   1903             LOGE("Error starting record");
   1904             standby();
   1905             return -1;
   1906         }
   1907     }
   1908 
   1909     while (count) {
   1910         ssize_t bytesRead = ::read(mFd, buffer, count);
   1911         if (bytesRead >= 0) {
   1912             count -= bytesRead;
   1913             p += bytesRead;
   1914         } else {
   1915             if (errno != EAGAIN) return bytesRead;
   1916             mRetryCount++;
   1917             LOGD("EAGAIN - retrying");
   1918         }
   1919     }
   1920     return bytes;
   1921 }
   1922 
   1923 status_t AudioHardware::AudioStreamInMSM72xx::standby()
   1924 {
   1925     if (mState > AUDIO_INPUT_CLOSED) {
   1926         if (mFd >= 0) {
   1927             ::close(mFd);
   1928             mFd = -1;
   1929         }
   1930         mState = AUDIO_INPUT_CLOSED;
   1931         LOGV("release input wakelock");
   1932         release_wake_lock(kInputWakelockStr);
   1933     }
   1934 
   1935     if (!mHardware) return -1;
   1936 
   1937     mHardware->set_mRecordState(0);
   1938     // make sure a1026 config is re-applied even is input device is not changed
   1939     mHardware->clearCurDevice();
   1940     mHardware->doRouting();
   1941 
   1942     LOGD("AudioHardware PCM record is going to standby.");
   1943     return NO_ERROR;
   1944 }
   1945 
   1946 status_t AudioHardware::AudioStreamInMSM72xx::dump(int fd, const Vector<String16>& args)
   1947 {
   1948     const size_t SIZE = 256;
   1949     char buffer[SIZE];
   1950     String8 result;
   1951     result.append("AudioStreamInMSM72xx::dump\n");
   1952     snprintf(buffer, SIZE, "\tsample rate: %d\n", sampleRate());
   1953     result.append(buffer);
   1954     snprintf(buffer, SIZE, "\tbuffer size: %d\n", bufferSize());
   1955     result.append(buffer);
   1956     snprintf(buffer, SIZE, "\tchannels: %d\n", channels());
   1957     result.append(buffer);
   1958     snprintf(buffer, SIZE, "\tformat: %d\n", format());
   1959     result.append(buffer);
   1960     snprintf(buffer, SIZE, "\tmHardware: %p\n", mHardware);
   1961     result.append(buffer);
   1962     snprintf(buffer, SIZE, "\tmFd count: %d\n", mFd);
   1963     result.append(buffer);
   1964     snprintf(buffer, SIZE, "\tmState: %d\n", mState);
   1965     result.append(buffer);
   1966     snprintf(buffer, SIZE, "\tmRetryCount: %d\n", mRetryCount);
   1967     result.append(buffer);
   1968     ::write(fd, result.string(), result.size());
   1969     return NO_ERROR;
   1970 }
   1971 
   1972 status_t AudioHardware::AudioStreamInMSM72xx::setParameters(const String8& keyValuePairs)
   1973 {
   1974     AudioParameter param = AudioParameter(keyValuePairs);
   1975     status_t status = NO_ERROR;
   1976     int device;
   1977     String8 key = String8(KEY_A1026_VR_MODE);
   1978     int enabled;
   1979     LOGV("AudioStreamInMSM72xx::setParameters() %s", keyValuePairs.string());
   1980 
   1981     // reading voice recognition mode parameter
   1982     if (param.getInt(key, enabled) == NO_ERROR) {
   1983         LOGV("set vr_mode_enabled to %d", enabled);
   1984         vr_mode_change = (vr_mode_enabled != enabled);
   1985         vr_mode_enabled = enabled;
   1986         param.remove(key);
   1987     }
   1988 
   1989     // reading routing parameter
   1990     key = String8(AudioParameter::keyRouting);
   1991     if (param.getInt(key, device) == NO_ERROR) {
   1992         LOGV("set input routing %x", device);
   1993         if (device & (device - 1)) {
   1994             status = BAD_VALUE;
   1995         } else {
   1996             mDevices = device;
   1997             status = mHardware->doRouting();
   1998         }
   1999         param.remove(key);
   2000     }
   2001 
   2002     if (param.size()) {
   2003         status = BAD_VALUE;
   2004     }
   2005     return status;
   2006 }
   2007 
   2008 String8 AudioHardware::AudioStreamInMSM72xx::getParameters(const String8& keys)
   2009 {
   2010     AudioParameter param = AudioParameter(keys);
   2011     String8 value;
   2012     String8 key = String8(AudioParameter::keyRouting);
   2013 
   2014     if (param.get(key, value) == NO_ERROR) {
   2015         LOGV("get routing %x", mDevices);
   2016         param.addInt(key, (int)mDevices);
   2017     }
   2018 
   2019     LOGV("AudioStreamInMSM72xx::getParameters() %s", param.toString().string());
   2020     return param.toString();
   2021 }
   2022 
   2023 // ----------------------------------------------------------------------------
   2024 
   2025 extern "C" AudioHardwareInterface* createAudioHardware(void) {
   2026     return new AudioHardware();
   2027 }
   2028 
   2029 }; // namespace android
   2030