summaryrefslogtreecommitdiffstats
blob: 5432c07eb161c6f8097c5deff3aac43ae20da92b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
/*
 * Copyright (C) 2013 Texas Instruments
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "AudioHw"
// #define LOG_NDEBUG 0
// #define VERY_VERBOSE_LOGGING
#ifdef VERY_VERBOSE_LOGGING
#define ALOGVV ALOGV
#else
#define ALOGVV(...) do { } while(0)
#endif

#include <cutils/log.h>

#include <media/AudioParameter.h>

#include <AudioHw.h>

namespace android {

AudioStreamOut::AudioStreamOut(AudioHwDevice *hwDev,
                               PcmWriter *writer,
                               const PcmParams &params,
                               const SlotMap &map,
                               audio_devices_t devices)
    : mHwDev(hwDev), mNullWriter(&mNullPort, params), mWriter(writer),
      mParams(params), mDevices(devices), mStandby(true), mUsedForVoiceCall(false)
{
    if (mWriter)
        mStream = new AdaptedOutStream(params, map);
}

int AudioStreamOut::initCheck() const
{
    int ret = 0;

    if (!mHwDev) {
        ALOGE("AudioStreamOut: initCheck() invalid AudioHwDevice");
        ret = -ENODEV;
    }
    else if (!mWriter || !mWriter->initCheck()) {
        ALOGE("AudioStreamOut: initCheck() invalid PCM writer");
        ret = -ENODEV;
    }
    else if (mStream == NULL || !mStream->initCheck()) {
        ALOGE("AudioStreamOut: initCheck() invalid Out Stream");
        ret = -ENODEV;
    }

    ALOGV("AudioStreamOut: init check %d", ret);

    return ret;
}

uint32_t AudioStreamOut::getSampleRate() const
{
    uint32_t rate = mParams.sampleRate;

    ALOGVV("AudioStreamOut: getSampleRate() %u Hz", rate);

    return rate;
}

int AudioStreamOut::setSampleRate(uint32_t rate)
{
    ALOGV("AudioStreamOut: setSampleRate() %u Hz", rate);

    return 0;
}

size_t AudioStreamOut::getBufferSize() const
{
    size_t size;

    /* Take resampling ratio into account and align to the nearest
     * 16 frames as required by the AudioFlinger */
    size = (mParams.frameCount * mParams.sampleRate) / mWriter->getParams().sampleRate;
    size = ((size + 15) & ~15) * mParams.frameSize();

    ALOGVV("AudioStreamOut: getBufferSize() %u bytes", size);

    return size;
}

audio_channel_mask_t AudioStreamOut::getChannels() const
{
    uint32_t channels = mParams.channels;

    ALOGVV("AudioStreamOut: getChannels() %u channels", channels);

    return audio_channel_out_mask_from_count(channels);
}

audio_format_t AudioStreamOut::getFormat() const
{
    uint32_t sampleBits = mParams.sampleBits;

    ALOGVV("AudioStreamOut: getFormat() %u bits/sample", sampleBits);

    switch (sampleBits) {
    case 8:
        return AUDIO_FORMAT_PCM_8_BIT;
    case 24:
        return AUDIO_FORMAT_PCM_8_24_BIT;
    case 32:
        return AUDIO_FORMAT_PCM_32_BIT;
    case 16:
    default:
        return AUDIO_FORMAT_PCM_16_BIT;
    }
}

int AudioStreamOut::setFormat(audio_format_t format)
{
    ALOGV("AudioStreamOut: setFormat() %u bits/sample",
          audio_bytes_per_sample(format) * 8);

    return 0;
}

/* must be called with mLock */
int AudioStreamOut::resume()
{
    ALOGV("AudioStreamOut: resume using %s writer",
          mUsedForVoiceCall ? "null" : "regular");

    /*
     * Switching PCM writers is done under the assumption that the non-null
     * writer (mWriter) is always open (but possibly in standby), which is
     * achieved by using the primary output for voice calls.
     */
    PcmWriter *writer;
    if (mUsedForVoiceCall)
        writer = &mNullWriter;
    else
        writer = mWriter;

    int ret = writer->registerStream(mStream);
    if (ret) {
        ALOGE("AudioStreamOut: failed to register stream %d", ret);
        return ret;
    }

    ret = mStream->start();
    if (ret) {
        ALOGE("AudioStreamOut: failed to start stream %d", ret);
        writer->unregisterStream(mStream);
    }

    return ret;
}

/* must be called with mLock */
void AudioStreamOut::idle()
{
    ALOGV("AudioStreamOut: idle using %s writer",
          mUsedForVoiceCall ? "null" : "regular");

    PcmWriter *writer;
    if (mUsedForVoiceCall)
        writer = &mNullWriter;
    else
        writer = mWriter;

    mStream->stop();
    writer->unregisterStream(mStream);
}

int AudioStreamOut::standby()
{
    ALOGV("AudioStreamOut: standby()");

    AutoMutex lock(mLock);

    if (!mStandby) {
        idle();
        mStandby = true;
    }

    return 0;
}

void AudioStreamOut::setVoiceCall(bool on)
{
    ALOGV("AudioStreamOut: setVoiceCall() %s", on ? "enter" : "leave");

    AutoMutex lock(mLock);

    /*
     * Voice call reuses one of the PCM writers that is otherwise used
     * for media. Media has to be re-routed to a null writer (that only
     * consumes the data but doesn't write it to the hardware) when the
     * voice call starts and routed back to the actual writer when the
     * voice call stops.
     * Temporarily entering standby helps transitioning to the null writer
     * the next time that data is written to the stream if the voice call
     * occurs at mid-stream.
     */
    if (mUsedForVoiceCall != on) {
        if (!mStandby) {
            idle();
            mStandby = true;
        }
        mUsedForVoiceCall = on;
    }
}

int AudioStreamOut::dump(int fd) const
{
    ALOGV("AudioStreamOut: dump()");
    return 0;
}

audio_devices_t AudioStreamOut::getDevice() const
{
    ALOGV("AudioStreamOut: getDevice()");
    return mDevices;
}

int AudioStreamOut::setParameters(const char *kv_pairs)
{
    ALOGV("AudioStreamOut: setParameters() '%s'", kv_pairs ? kv_pairs : "");

    int ret;

    AudioParameter parms = AudioParameter(String8(kv_pairs));
    String8 key = String8(AudioParameter::keyRouting);
    int device;

    if ((ret = parms.getInt(key, device)) == NO_ERROR) {
        if ((mDevices & AUDIO_DEVICE_OUT_ALL) != (unsigned int)device) {
            standby();
        }
        if (device & ~(mHwDev->getSupportedDevices())) {
            ALOGW("AudioStreamOut: setParameters() device(s) not supported, "
                  "will use default devices");
        }
        else
            mDevices = device;
    }

    return ret;
}

char *AudioStreamOut::getParameters(const char *keys) const
{
    ALOGV("AudioStreamOut::getParameters()");
    return NULL;
}

int AudioStreamOut::addAudioEffect(effect_handle_t effect) const
{
    ALOGV("AudioStreamOut: addAudioEffects()");
    return 0;
}

int AudioStreamOut::removeAudioEffect(effect_handle_t effect) const
{
    ALOGV("AudioStreamOut: removeAudioEffects()");
    return 0;
}

uint32_t AudioStreamOut::getLatency() const
{
    uint32_t latency = (1000 * getBufferSize()) / mWriter->getParams().sampleRate;

    ALOGVV("AudioStreamOut: getLatency() %u ms", latency);

    return latency;
}

int AudioStreamOut::setVolume(float left, float right)
{
    ALOGV("AudioStreamOut: setVolume() left=%.4f right=%.4f", left, right);
    return -ENOSYS;
}

ssize_t AudioStreamOut::write(const void* buffer, size_t bytes)
{
    uint32_t frames = mParams.bytesToFrames(bytes);
    int ret = 0;
    uint32_t usecs = (frames * 1000000) / mParams.sampleRate;

    ALOGVV("AudioStreamOut: write %u frames (%u bytes) buffer %p",
           frames, bytes, buffer);

    AutoMutex lock(mLock);

    if (mStandby) {
        ret = resume();
        if (ret) {
            ALOGE("AudioStreamOut: failed to resume stream %d", ret);
            usleep(usecs); /* limits the rate of error messages */
            return ret;
        }
        mStandby = false;
    }

    ret = mStream->write(buffer, frames);
    if (ret < 0) {
        ALOGE("AudioStreamOut: failed to write data %d", ret);
        usleep(usecs);
    } else {
        ALOGW_IF(ret != (int)frames,
                 "AudioStreamOut: wrote only %d out of %d requested frames",
                 ret, frames);
        bytes = mParams.framesToBytes(ret);
    }

    return bytes;
}

int AudioStreamOut::getRenderPosition(uint32_t *dsp_frames) const
{
    ALOGV("AudioStreamOut: getRenderPosition()");

    return -EINVAL;
}

int AudioStreamOut::getNextWriteTimestamp(int64_t *timestamp) const
{
    ALOGVV("AudioStreamOut: getNextWriteTimestamp()");

    return -EINVAL;
}

/* ---------------------------------------------------------------------------------------- */

AudioStreamIn::AudioStreamIn(AudioHwDevice *hwDev,
                             PcmReader *reader,
                             const PcmParams &params,
                             const SlotMap &map,
                             audio_devices_t devices)
    : mHwDev(hwDev), mReader(reader), mParams(params), mDevices(devices),
      mSource(AUDIO_SOURCE_DEFAULT), mStandby(true)
{
    if (mReader)
        mStream = new AdaptedInStream(params, map);
}

int AudioStreamIn::initCheck() const
{
    int ret = 0;

    if (!mHwDev) {
        ALOGE("AudioStreamIn: initCheck() invalid AudioHwDevice");
        ret = -ENODEV;
    }
    else if (!mReader || !mReader->initCheck()) {
        ALOGE("AudioStreamIn: initCheck() invalid PCM reader");
        ret = -ENODEV;
    }
    else if (mStream == NULL || !mStream->initCheck()) {
        ALOGE("AudioStreamIn: initCheck() invalid In Stream");
        ret = -ENODEV;
    }

    ALOGV("AudioStreamIn: init check %d", ret);

    return ret;
}

uint32_t AudioStreamIn::getSampleRate() const
{
    ALOGV("AudioStreamIn: getSampleRate()");

    uint32_t rate = mParams.sampleRate;

    return rate;
}

int AudioStreamIn::setSampleRate(uint32_t rate)
{
    ALOGV("AudioStreamIn: setSampleRate() %u Hz", rate);

    return 0;
}

size_t AudioStreamIn::getBufferSize() const
{
    size_t size;

    /* Take resampling ratio into account and align to the nearest
     * 16 frames as required by the AudioFlinger */
    size = (mParams.frameCount * mParams.sampleRate) / mReader->getParams().sampleRate;
    size = ((size + 15) & ~15) * mParams.frameSize();

    ALOGVV("AudioStreamIn: getBufferSize() %u bytes", size);

    return size;
}

audio_channel_mask_t AudioStreamIn::getChannels() const
{
    ALOGV("AudioStreamIn: getChannels()");

    return audio_channel_in_mask_from_count(mParams.channels);
}

audio_format_t AudioStreamIn::getFormat() const
{
    ALOGV("AudioStreamIn: getFormat()");

    return AUDIO_FORMAT_PCM_16_BIT;
}

int AudioStreamIn::setFormat(audio_format_t format)
{
    ALOGV("AudioStreamIn: setFormat()");

    return 0;
}

/* must be called with mLock */
int AudioStreamIn::resume()
{
    mHwDev->mMixer.setPath(mDevices, true);

    int ret = mReader->registerStream(mStream);
    if (ret) {
        ALOGE("AudioStreamIn: failed to register Dest %d", ret);
        return ret;
    }

    ret = mStream->start();
    if (ret) {
        ALOGE("AudioStreamIn: failed to start stream %d", ret);
        mReader->unregisterStream(mStream);
    }

    return ret;
}

/* must be called with mLock */
void AudioStreamIn::idle()
{
    mStream->stop();
    mReader->unregisterStream(mStream);
    mHwDev->mMixer.setPath(mDevices, false);
}

int AudioStreamIn::standby()
{
    ALOGV("AudioStreamIn: standby()");

    AutoMutex lock(mLock);

    if (!mStandby) {
        idle();
        mStandby = true;
    }

    return 0;
}

int AudioStreamIn::dump(int fd) const
{
    ALOGV("AudioStreamIn: dump()");

    return 0;
}

audio_devices_t AudioStreamIn::getDevice() const
{
    ALOGV("AudioStreamIn: getDevice()");

    return mDevices;
}

int AudioStreamIn::setParameters(const char *kv_pairs)
{
    ALOGV("AudioStreamIn: setParameters() '%s'", kv_pairs ? kv_pairs : "");

    int ret;

    AudioParameter parms = AudioParameter(String8(kv_pairs));
    String8 source_key = String8(AudioParameter::keyInputSource);
    String8 device_key = String8(AudioParameter::keyRouting);
    int source, device;

    if ((ret = parms.getInt(source_key, source)) == NO_ERROR) {
        /* no audio source uses 0 */
        if ((mSource != (unsigned int)source) &&
            (source != 0) &&
            (source < AUDIO_SOURCE_CNT)) {
            ALOGV("AudioStreamIn: setParameters() source changed [%d]->[%d]",
                  mSource, source);
            mSource = (audio_source_t)source;
            /* Nothing to do for AUDIO_PARAMETER_STREAM_INPUT_SOURCE, so only
             * record the source and continue */
        }
    }

    if ((ret = parms.getInt(device_key, device)) == NO_ERROR) {
        if ((mDevices & AUDIO_DEVICE_IN_ALL) != (unsigned int)device) {
            standby();
        }
        if (device & ~(mHwDev->getSupportedDevices())) {
            ALOGW("AudioStreamIn: setParameters() device(s) not supported, "
                  "will use default devices");
        }
        else {
            mDevices = device;
            ALOGV("AudioStreamIn: setParameters() device set to [0x%x]",
                  mDevices);
        }
    }

    return 0;
}

char *AudioStreamIn::getParameters(const char *keys) const
{
    ALOGV("AudioStreamIn: getParameters()");

    return NULL;
}

int AudioStreamIn::addAudioEffect(effect_handle_t effect) const
{
    ALOGV("AudioStreamIn: addAudioEffect()");

    return 0;
}

int AudioStreamIn::removeAudioEffect(effect_handle_t effect) const
{
    ALOGV("AudioStreamIn: removeAudioEffect()");

    return 0;
}

int AudioStreamIn::setGain(float gain)
{
    ALOGV("AudioStreamIn: setGain()");

    return 0;
}

ssize_t AudioStreamIn::read(void* buffer, size_t bytes)
{
    uint32_t frames = mParams.bytesToFrames(bytes);
    int ret = 0;
    uint32_t usecs = (frames * 1000000) / mParams.sampleRate;

    ALOGVV("AudioStreamIn: read %u frames (%u bytes) buffer %p",
           frames, bytes, buffer);

    AutoMutex lock(mLock);

    if (mStandby) {
        ret = resume();
        if (ret) {
            ALOGE("AudioStreamIn: failed to resume stream %d", ret);
            usleep(usecs); /* limits the rate of error messages */
            return ret;
        }
        mStandby = false;
    }

    ret = mStream->read(buffer, frames);
    if (ret < 0) {
        ALOGE("AudioStreamIn: failed to read data %d", ret);
        usleep(usecs);
        bytes = ret;
    } else {
        ALOGW_IF(ret != (int)frames,
                 "AudioStreamIn: read only %d out of %d requested frames",
                 ret, frames);
        bytes = mParams.framesToBytes(ret);
        if (mHwDev->mMicMute)
            memset(buffer, 0, bytes);
    }

    return bytes;
}

uint32_t AudioStreamIn::getInputFramesLost()
{
    ALOGVV("AudioStreamIn: getInputFrameLost()");

    return 0;
}

/* ---------------------------------------------------------------------------------------- */

const char *AudioHwDevice::kCabinVolumeHP = "HP DAC Playback Volume";
const char *AudioHwDevice::kCabinVolumeLine = "Line DAC Playback Volume";

AudioHwDevice::AudioHwDevice(uint32_t card)
    : mCardId(card), mMixer(mCardId), mMicMute(false), mMode(AUDIO_MODE_NORMAL)
{
    ALOGI("AudioHwDevice: create hw device for card hw:%u", card);

    /* Mixer for dra7evm and input/output ports for JAMR3 PCM device */
    for (uint32_t i = 0; i < kNumPorts; i++) {
        ALSAInPort *inPort = new ALSAInPort(mCardId, i);
        mInPorts.push_back(inPort);

        ALSAOutPort *outPort = new ALSAOutPort(mCardId, i);
        mOutPorts.push_back(outPort);
    }

    /* PCM parameters for the port associated with on-board audio:
     * 2 channels, 16-bits/sample, 44.1kHz, buffer of 882 frames (capture) */
    PcmParams params0(kCPUNumChannels, kSampleSize, kSampleRate, kCaptureFrameCount);
    PcmReader *reader = new PcmReader(mInPorts[kCPUPortId], params0);
    mReaders.push_back(reader);
    /* 2 channels, 16-bits/sample, 44.1kHz, buffer of 1024 frames (playback) */
    params0.frameCount = kPlaybackFrameCount;
    PcmWriter *writer = new PcmWriter(mOutPorts[kCPUPortId], params0);
    mWriters.push_back(writer);

    /* PCM parameters for the port associated with JAMR3 audio:
     * 8 channels, 16-bits/sample, 44.1kHz, buffer of 882 frames (capture) */
    PcmParams params1(kJAMR3NumChannels, kSampleSize, kSampleRate, kCaptureFrameCount);
    reader = new PcmReader(mInPorts[kJAMR3PortId], params1);
    mReaders.push_back(reader);
    /* 8 channels, 16-bits/sample, 44.1kHz, buffer of 1024 frames (playback) */
    params1.frameCount = kPlaybackFrameCount;
    writer = new PcmWriter(mOutPorts[kJAMR3PortId], params1);
    mWriters.push_back(writer);

    /* Voice call */
    PcmParams paramsBT(kBTNumChannels, kSampleSize, kBTSampleRate, kBTFrameCount);
    writer = new PcmWriter(mOutPorts[kBTPortId], paramsBT);
    mWriters.push_back(writer);
    reader = new PcmReader(mInPorts[kBTPortId], paramsBT);
    mReaders.push_back(reader);

    /* BT is configured as stereo but only the left channel carries data */
    SlotMap slots;
    slots[0] = 0;
    slots[1] = 0;

    /* Voice call uplink */
    mULPipe = new tiaudioutils::MonoPipe(paramsBT,
                              (kVoiceCallPipeMs * paramsBT.sampleRate) / 1000);
    mULPipeWriter = new PipeWriter(mULPipe);
    mULPipeReader = new PipeReader(mULPipe);
    mVoiceULInStream = new InStream(paramsBT, slots, mULPipeWriter);
    mVoiceULOutStream = new OutStream(paramsBT, slots, mULPipeReader);

    /* Voice call downlink */
    mDLPipe = new tiaudioutils::MonoPipe(paramsBT,
                              (kVoiceCallPipeMs * params0.sampleRate) / 1000);
    mDLPipeWriter = new PipeWriter(mDLPipe);
    mDLPipeReader = new PipeReader(mDLPipe);
    mVoiceDLInStream = new InStream(paramsBT, slots, mDLPipeWriter);
    mVoiceDLOutStream = new OutStream(paramsBT, slots, mDLPipeReader);

    mMixer.initRoutes();
}

AudioHwDevice::~AudioHwDevice()
{
    ALOGI("AudioHwDevice: destroy hw device for card hw:%u", mCardId);

    if (mDLPipeWriter)
        delete mDLPipeWriter;

    if (mDLPipeReader)
        delete mDLPipeReader;

    if (mDLPipe)
        delete mDLPipe;

    if (mULPipeWriter)
        delete mULPipeWriter;

    if (mULPipeReader)
        delete mULPipeReader;

    if (mULPipe)
        delete mULPipe;

    for (WriterVect::const_iterator i = mWriters.begin(); i != mWriters.end(); ++i) {
        delete (*i);
    }
    for (ReaderVect::const_iterator i = mReaders.begin(); i != mReaders.end(); ++i) {
        delete (*i);
    }
    for (OutPortVect::iterator i = mOutPorts.begin(); i != mOutPorts.end(); ++i) {
        delete (*i);
    }
    for (InPortVect::iterator i = mInPorts.begin(); i != mInPorts.end(); ++i) {
        delete (*i);
    }
}

uint32_t AudioHwDevice::getSupportedDevices() const
{
    uint32_t devices;

    devices = AUDIO_DEVICE_IN_BUILTIN_MIC |
              AUDIO_DEVICE_IN_BACK_MIC |
              AUDIO_DEVICE_IN_VOICE_CALL |
              AUDIO_DEVICE_OUT_SPEAKER |
              AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
              AUDIO_DEVICE_OUT_WIRED_HEADSET |
              AUDIO_DEVICE_OUT_WIRED_HEADPHONE2;
    ALOGV("AudioHwDevice: supported devices 0x%08x", devices);

    return devices;
}

int AudioHwDevice::initCheck() const
{
    if (!mMixer.initCheck()) {
        ALOGE("AudioHwDevice: ALSA mixer init failed");
        return -ENODEV;
    }

    for (ReaderVect::const_iterator i = mReaders.begin(); i != mReaders.end(); ++i) {
        if (!((*i)->initCheck())) {
            ALOGE("AudioHwDevice: PCM reader initCheck failed");
            return -ENODEV;
        }
    }
    for (WriterVect::const_iterator i = mWriters.begin(); i != mWriters.end(); ++i) {
        if (!((*i)->initCheck())) {
            ALOGE("AudioHwDevice: PCM writer init failed");
            return -ENODEV;
        }
    }

    if ((mULPipe == NULL) || !mULPipe->initCheck() ||
        (mULPipeReader == NULL) || !mULPipeReader->initCheck() ||
        (mULPipeWriter == NULL) || !mULPipeWriter->initCheck()) {
        ALOGE("AudioHwDevice: voice call uplink init check failed");
        return -ENODEV;
    }

    if ((mDLPipe == NULL) || !mDLPipe->initCheck() ||
        (mDLPipeReader == NULL) || !mDLPipeReader->initCheck() ||
        (mDLPipeWriter == NULL) || !mDLPipeWriter->initCheck()) {
        ALOGE("AudioHwDevice: voice call downlink init check failed");
        return -ENODEV;
    }

    if ((mVoiceULInStream == NULL) || !mVoiceULInStream->initCheck() ||
        (mVoiceULOutStream == NULL) || !mVoiceULOutStream->initCheck()) {
        ALOGE("AudioHwDevice: voice call uplink streams init check failed");
        return -ENODEV;
    }

    if ((mVoiceDLInStream == NULL) || !mVoiceDLInStream->initCheck() ||
        (mVoiceDLOutStream == NULL) || !mVoiceDLOutStream->initCheck()) {
        ALOGE("AudioHwDevice: voice call downlink streams init check failed");
        return -ENODEV;
    }

    return 0;
}

int AudioHwDevice::setVoiceVolume(float volume)
{
    /* Linear interpolation between voice dB limits */
    float dB = (kVoiceDBMax - kVoiceDBMin) * volume + kVoiceDBMin;

    /* Output stage gain (-59.0dB, 0dB) with steps of 0.5dB */
    int val = 2 * (dB + 59.0f);

    ALOGV("AudioHwDevice: setVoiceVolume() vol=%.4f dB=%.4f", volume, dB, val);

    mMixer.set(ALSAControl(kCabinVolumeHP, val), true);
    mMixer.set(ALSAControl(kCabinVolumeLine, val), true);

    return 0;
}

int AudioHwDevice::setMasterVolume(float volume)
{
    ALOGV("AudioHwDevice: setMasterVolume() vol=%.4f", volume);
    return -ENOSYS;
}

const char *AudioHwDevice::getModeName(audio_mode_t mode) const
{
    switch (mode) {
    case AUDIO_MODE_CURRENT:
        return "CURRENT";
    case AUDIO_MODE_NORMAL:
        return "NORMAL";
    case AUDIO_MODE_RINGTONE:
        return "RINGTONE";
    case AUDIO_MODE_IN_CALL:
        return "IN_CALL";
    case AUDIO_MODE_IN_COMMUNICATION:
        return "COMMUNICATION";
    default:
        return "INVALID";
    }
}

int AudioHwDevice::setMode(audio_mode_t mode)
{
    ALOGV("AudioHwDevice: setMode() %s", getModeName(mode));

    AutoMutex lock(mLock);
    if (mMode == mode) {
        ALOGW("AudioHwDevice: already in mode %s", getModeName(mode));
        return 0;
    }

    int ret = 0;
    if (mode == AUDIO_MODE_IN_CALL) {
        ret = enterVoiceCall();
        ALOGE_IF(ret, "AudioHwDevice: failed to enter voice call %d", ret);
    } else {
        leaveVoiceCall();
    }

    if (!ret)
        mMode = mode;

    return ret;
}

int AudioHwDevice::enableVoiceCall()
{
    ALOGV("AudioHwDevice: enable voice call paths");

    sp<AudioStreamOut> outStream = mPrimaryStreamOut.promote();
    if (outStream == NULL) {
        ALOGE("AudioHwDevice: primary output stream is not valid");
        return -ENODEV;
    }

    /* Playback stream will free the writer and switch to a null writer */
    outStream->setVoiceCall(true);

    /* Uplink input stream: Mic -> Pipe */
    int ret = mReaders[kCPUPortId]->registerStream(mVoiceULInStream);
    if (ret) {
        ALOGE("AudioHwDevice: failed to register uplink in stream %d", ret);
        return ret;
    }

    /* Uplink output stream: Pipe -> Bluetooth */
    ret = mWriters[kBTPortId]->registerStream(mVoiceULOutStream);
    if (ret) {
        ALOGE("AudioHwDevice: failed to register uplink out stream %d", ret);
        return ret;
    }

    /* Downlink input stream: Bluetooth -> Pipe */
    ret = mReaders[kBTPortId]->registerStream(mVoiceDLInStream);
    if (ret) {
        ALOGE("AudioHwDevice: failed to register downlink in stream %d", ret);
        return ret;
    }

    /* Downlink output stream: Pipe -> Speaker */
    ret = outStream->mWriter->registerStream(mVoiceDLOutStream);
    if (ret) {
        ALOGE("AudioHwDevice: failed to register downlink out stream %d", ret);
    }

    return ret;
}

void AudioHwDevice::disableVoiceCall()
{
    ALOGV("AudioHwDevice: disable voice call paths");

    sp<AudioStreamOut> outStream = mPrimaryStreamOut.promote();
    if (outStream != NULL) {
        if (outStream->mWriter->isStreamRegistered(mVoiceDLOutStream))
            outStream->mWriter->unregisterStream(mVoiceDLOutStream);
        outStream->setVoiceCall(false);
    } else {
        ALOGE("AudioHwDevice: primary output stream is not valid");
    }

    if (mReaders[kBTPortId]->isStreamRegistered(mVoiceDLInStream))
        mReaders[kBTPortId]->unregisterStream(mVoiceDLInStream);

    if (mWriters[kBTPortId]->isStreamRegistered(mVoiceULOutStream))
        mWriters[kBTPortId]->unregisterStream(mVoiceULOutStream);

    if (mReaders[kCPUPortId]->isStreamRegistered(mVoiceULInStream))
        mReaders[kCPUPortId]->unregisterStream(mVoiceULInStream);
}

int AudioHwDevice::enterVoiceCall()
{
    ALOGI("AudioHwDevice: enter voice call");

    /* Setup uplink and downlink pipes */
    int ret = enableVoiceCall();
    if (ret) {
        ALOGE("AudioHwDevice: failed to enable voice call path %d", ret);
        return ret;
    }

    /* Uplink input stream: Mic -> Pipe */
    ret = mVoiceULInStream->start();
    if (ret) {
        ALOGE("AudioHwDevice: failed to start uplink in stream %d", ret);
        return ret;
    }

    /* Downlink input stream: Bluetooth -> Pipe */
    ret = mVoiceDLInStream->start();
    if (ret) {
        ALOGE("AudioHwDevice: failed to start downlink in stream %d", ret);
        return ret;
    }

    /*
     * Wait till pipe is half full to give a head start to the output streams.
     * The time to wait consists of the actual pipe size, the ADC settle time
     * used in the kernel and the time needed to produce a BT audio buffer.
     * Only the pipe size related time contributes to the steady state latency.
     */
    usleep((kVoiceCallPipeMs * 5000) + (kADCSettleMs * 1000) +
           (kBTFrameCount * 1000) / kBTSampleRate);

    /* Downlink output stream: Pipe -> Speaker */
     ret = mVoiceDLOutStream->start();
    if (ret) {
        ALOGE("AudioHwDevice: failed to start downlink out stream %d", ret);
    }

    /* Uplink output stream: Pipe -> Bluetooth */
    ret = mVoiceULOutStream->start();
    if (ret) {
        ALOGE("AudioHwDevice: failed to start uplink out stream %d", ret);
        return ret;
    }

    return ret;
}

void AudioHwDevice::leaveVoiceCall()
{
    ALOGI("AudioHwDevice: leave voice call");

    if (mVoiceDLOutStream->isStarted())
        mVoiceDLOutStream->stop();

    if (mVoiceULInStream->isStarted())
        mVoiceULInStream->stop();

    if (mVoiceULOutStream->isStarted())
        mVoiceULOutStream->stop();

    if (mVoiceDLInStream->isStarted())
        mVoiceDLInStream->stop();

    disableVoiceCall();

    /* Reset the cabin volume for media */
    setVoiceVolume(1.0f);
}

int AudioHwDevice::setMicMute(bool state)
{
    ALOGV("AudioHwDevice: setMicMute() %s", state ? "mute" : "unmute");

    mMicMute = state;

    return 0;
}

int AudioHwDevice::getMicMute(bool *state) const
{
    ALOGV("AudioHwDevice: getMicMute()");

    *state = mMicMute;

    return 0;
}

int AudioHwDevice::setParameters(const char *kv_pairs)
{
    ALOGV("AudioHwDevice: setParameters() '%s'", kv_pairs ? kv_pairs : "");

    return 0;
}

char *AudioHwDevice::getParameters(const char *keys) const
{
    ALOGV("AudioHwDevice: getParameters()");

    return NULL;
}

size_t AudioHwDevice::getInputBufferSize(const struct audio_config *config) const
{
    ALOGV("AudioHwDevice: getInputBufferSize()");

    AutoMutex lock(mLock);
    size_t size;

    /* Take resampling ratio into account and align to the nearest
     * 16 frames as required by the AudioFlinger */
    /* Use port 0 for the calculation, since values for both ports are the same */
    uint32_t frames = mReaders[kCPUPortId]->getParams().frameCount;
    uint32_t rate = mReaders[kCPUPortId]->getParams().sampleRate;

    size = (frames * config->sample_rate) / rate;
    size = ((size + 15) & ~15) * mReaders[kCPUPortId]->getParams().frameSize();

    ALOGV("AudioHwDevice: getInputBufferSize() %d bytes", size);

    return size;
}

int AudioHwDevice::dump(int fd) const
{
    ALOGV("AudioHwDevice: dump()");

    return 0;
}

int AudioHwDevice::setMasterMute(bool mute)
{
    ALOGV("AudioHwDevice: setMasterMute() %s", mute ? "mute" : "unmute");
    return -ENOSYS;
}

AudioStreamIn* AudioHwDevice::openInputStream(audio_io_handle_t handle,
                                              audio_devices_t devices,
                                              struct audio_config *config)
{
    uint32_t port = 0;
    uint32_t channels = popcount(config->channel_mask);

    ALOGV("AudioHwDevice: openInputStream()");

    uint32_t srcMask, dstMask;
    switch (devices) {
    case AUDIO_DEVICE_IN_BUILTIN_MIC:
    case AUDIO_DEVICE_IN_VOICE_CALL:
        if (channels == 1) {
            /* Mic is in slots 0&1 (mask = 0x03) on port 0, but AF wants
             * only mono so take only one channel here */
            srcMask = 0x01;
            dstMask = 0x01;
        }
        else {
            srcMask = 0x03;
            dstMask = 0x03;
        }
        port = 0;
        break;
    case AUDIO_DEVICE_IN_BACK_MIC:
        if (channels == 1) {
            srcMask = 0x08;
            dstMask = 0x01;
        }
        else {
            ALOGE("AudioHwDevice: device 0x%08x only supports 1 channel",
                  devices);
            return NULL;
        }
        port = 1;
        break;
    default:
        ALOGE("AudioHwDevice: device 0x%08x is not supported", devices);
        return NULL;
    }

    SlotMap slotMap(srcMask, dstMask);
    if (!slotMap.isValid()) {
        ALOGE("AudioHwDevice: failed to create slot map");
        return NULL;
    }

    AutoMutex lock(mLock);

    /* Set the parameters for the internal input stream. Don't change the
     * parameters for capture. The resampler is used if needed. */
    PcmParams params(*config, mReaders[port]->getParams().frameCount);

    sp<AudioStreamIn> in = new AudioStreamIn(this, mReaders[port], params,
                                             slotMap, devices);
    if ((in == NULL) || in->initCheck()) {
        ALOGE("AudioHwDevice: failed to open input stream on port hw:%u,%u",
              mCardId, port);
        return NULL;
    }

    mInStreams.insert(in);

    return in.get();
}

void AudioHwDevice::closeInputStream(AudioStreamIn *in)
{
    ALOGV("AudioHwDevice: closeInputStream()");

    AutoMutex lock(mLock);

    if (mInStreams.find(in) == mInStreams.end()) {
        ALOGW("AudioHwDevice: input stream %p is not open", in);
        return;
    }

    mInStreams.erase(in);

    in = NULL;
}

AudioStreamOut* AudioHwDevice::openOutputStream(audio_io_handle_t handle,
                                                audio_devices_t devices,
                                                audio_output_flags_t flags,
                                                struct audio_config *config)
{
    uint32_t port = 0;
    PcmParams params;

    ALOGV("AudioHwDevice: openOutputStream()");

    uint32_t destMask;
    switch (devices) {
    case AUDIO_DEVICE_OUT_SPEAKER:
        port = 0;
        destMask = 0x03;
        break;
    case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
    case AUDIO_DEVICE_OUT_WIRED_HEADSET:
        port = 1;
        destMask = 0x0c;
        break;
    case AUDIO_DEVICE_OUT_WIRED_HEADPHONE2:
        port = 1;
        destMask = 0x30;
        break;
    default:
        ALOGE("AudioHwDevice: device 0x%08x is not supported", devices);
        return NULL;
    }

    SlotMap slotMap(0x03, destMask);
    if (!slotMap.isValid()) {
        ALOGE("AudioHwDevice: failed to create slot map");
        return NULL;
    }

    AutoMutex lock(mLock);

    /* Set the parameters for the internal output stream */
    params.frameCount = mWriters[port]->getParams().frameCount;
    params.sampleRate = config->sample_rate; /* Use stream's resampler if needed */
    params.sampleBits = 16;                  /* 16-bits/sample */
    params.channels = 2;                     /* Listening zones are stereo */

    /* Update audio config with granted parameters */
    if (popcount(config->channel_mask) != (int)params.channels) {
        ALOGV("AudioHwDevice: updating audio config channel mask [0x%x]->[0x%x]",
              config->channel_mask,
              audio_channel_out_mask_from_count(params.channels));
    }
    config->channel_mask = audio_channel_out_mask_from_count(params.channels);
    if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
        ALOGV("AudioHwDevice: updating audio config format [0x%x]->[0x%x]",
              config->format, AUDIO_FORMAT_PCM_16_BIT);
    }
    config->format = AUDIO_FORMAT_PCM_16_BIT;

    sp<AudioStreamOut> out = new AudioStreamOut(this, mWriters[port], params,
                                                slotMap, devices);
    if ((out == NULL) || out->initCheck()) {
        ALOGE("AudioHwDevice: failed to open output stream on port hw:%u,%u",
              mCardId, port);
        return NULL;
    }

    if (flags & AUDIO_OUTPUT_FLAG_PRIMARY)
        mPrimaryStreamOut = out;

    mOutStreams.insert(out);

    return out.get();
}

void AudioHwDevice::closeOutputStream(AudioStreamOut *out)
{
    ALOGV("AudioHwDevice: closeOutputStream()");

    AutoMutex lock(mLock);

    if (mOutStreams.find(out) == mOutStreams.end()) {
        ALOGW("AudioHwDevice: output stream %p is not open", out);
        return;
    }

    if (mPrimaryStreamOut == out)
        mPrimaryStreamOut = NULL;

    mOutStreams.erase(out);

    out = NULL;
}

}; /* namespace android */