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