1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * Copyright (C) 2011 Texas Instruments Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 * This module is a derived work from the original contribution of
17 * the /device/samsung/tuna/audio/audio_hw.c by Simon Wilson
18 *
19 */
20
21#define LOG_TAG "audio_hw_primary"
22/*#define LOG_NDEBUG 0*/
23/*#define LOG_NDEBUG_FUNCTION*/
24#ifndef LOG_NDEBUG_FUNCTION
25#define LOGFUNC(...) ((void)0)
26#else
27#define LOGFUNC(...) (ALOGV(__VA_ARGS__))
28#endif
29
30#include <errno.h>
31#include <pthread.h>
32#include <stdint.h>
33#include <sys/time.h>
34#include <stdlib.h>
35
36#include <cutils/log.h>
37#include <cutils/str_parms.h>
38#include <cutils/properties.h>
39
40#include <hardware/hardware.h>
41#include <system/audio.h>
42#include <hardware/audio.h>
43
44#include <tinyalsa/asoundlib.h>
45#include <audio_utils/resampler.h>
46#include <audio_utils/echo_reference.h>
47#include <hardware/audio_effect.h>
48#include <audio_effects/effect_aec.h>
49
50/* Mixer control names */
51#define MIXER_DL1_EQUALIZER                 "DL1 Equalizer"
52#define MIXER_DL2_LEFT_EQUALIZER            "DL2 Left Equalizer"
53#define MIXER_DL2_RIGHT_EQUALIZER           "DL2 Right Equalizer"
54#define MIXER_DL1_MEDIA_PLAYBACK_VOLUME     "DL1 Media Playback Volume"
55#define MIXER_DL1_VOICE_PLAYBACK_VOLUME     "DL1 Voice Playback Volume"
56#define MIXER_DL2_MEDIA_PLAYBACK_VOLUME     "DL2 Media Playback Volume"
57#define MIXER_DL2_VOICE_PLAYBACK_VOLUME     "DL2 Voice Playback Volume"
58#define MIXER_SDT_DL_VOLUME                 "SDT DL Volume"
59#define MIXER_SDT_UL_VOLUME                 "SDT UL Volume"
60
61#define MIXER_DL1_CAPTURE_PLAYBACK_VOLUME   "DL1 Capture Playback Volume"
62#define MIXER_DL2_CAPTURE_PLAYBACK_VOLUME   "DL2 Capture Playback Volume"
63#define MIXER_HEADSET_PLAYBACK_VOLUME       "Headset Playback Volume"
64#define MIXER_HANDSFREE_PLAYBACK_VOLUME     "Handsfree Playback Volume"
65#define MIXER_EARPHONE_PLAYBACK_VOLUME      "Earphone Playback Volume"
66#define MIXER_BT_UL_VOLUME                  "BT UL Volume"
67
68#define MIXER_DL1_EQUALIZER                 "DL1 Equalizer"
69#define MIXER_DL1_MIXER_MULTIMEDIA          "DL1 Mixer Multimedia"
70#define MIXER_DL1_MIXER_VOICE               "DL1 Mixer Voice"
71#define MIXER_DL1_MONO_MIXER                "DL1 Mono Mixer"
72#define MIXER_DL2_MIXER_MULTIMEDIA          "DL2 Mixer Multimedia"
73#define MIXER_DL2_MIXER_VOICE               "DL2 Mixer Voice"
74#define MIXER_DL2_MONO_MIXER                "DL2 Mono Mixer"
75#define MIXER_SIDETONE_MIXER_PLAYBACK       "Sidetone Mixer Playback"
76#define MIXER_SIDETONE_MIXER_CAPTURE        "Sidetone Mixer Capture"
77#define MIXER_DL1_PDM_SWITCH                "DL1 PDM Switch"
78#define MIXER_DL1_BT_VX_SWITCH              "DL1 BT_VX Switch"
79#define MIXER_DL1_MM_EXT_SWITCH             "DL1 MM_EXT Switch"
80#define MIXER_VOICE_CAPTURE_MIXER_CAPTURE   "Voice Capture Mixer Capture"
81
82#define MIXER_HS_LEFT_PLAYBACK              "HS Left Playback"
83#define MIXER_HS_RIGHT_PLAYBACK             "HS Right Playback"
84#define MIXER_HF_LEFT_PLAYBACK              "HF Left Playback"
85#define MIXER_HF_RIGHT_PLAYBACK             "HF Right Playback"
86#define MIXER_EARPHONE_ENABLE_SWITCH        "Earphone Enable Switch"
87
88#define MIXER_ANALOG_LEFT_CAPTURE_ROUTE     "Analog Left Capture Route"
89#define MIXER_ANALOG_RIGHT_CAPTURE_ROUTE    "Analog Right Capture Route"
90#define MIXER_CAPTURE_PREAMPLIFIER_VOLUME   "Capture Preamplifier Volume"
91#define MIXER_CAPTURE_VOLUME                "Capture Volume"
92#define MIXER_AMIC_UL_VOLUME                "AMIC UL Volume"
93#define MIXER_AUDUL_VOICE_UL_VOLUME         "AUDUL Voice UL Volume"
94#define MIXER_DMIC1_UL_VOLUME               "DMIC1 UL Volume"
95#define MIXER_MUX_VX0                       "MUX_VX0"
96#define MIXER_MUX_VX1                       "MUX_VX1"
97#define MIXER_MUX_UL10                      "MUX_UL10"
98#define MIXER_MUX_UL11                      "MUX_UL11"
99
100/* Mixer control gain and route values */
101#define MIXER_ABE_GAIN_0DB                  120
102#define MIXER_PLAYBACK_HS_DAC               "HS DAC"
103#define MIXER_PLAYBACK_HF_DAC               "HF DAC"
104#define MIXER_MAIN_MIC                      "Main Mic"
105#define MIXER_SUB_MIC                       "Sub Mic"
106#define MIXER_HS_MIC                        "Headset Mic"
107#define MIXER_AMIC0                         "AMic0"
108#define MIXER_AMIC1                         "AMic1"
109#define MIXER_DMIC0L                        "DMic0L"
110#define MIXER_DMIC0R                        "DMic0R"
111#define MIXER_BT_LEFT                       "BT Left"
112#define MIXER_BT_RIGHT                      "BT Right"
113#define MIXER_AUX_LEFT                      "Aux/FM Left"
114#define MIXER_AUX_RIGHT                     "Aux/FM Right"
115#define MIXER_450HZ_HIGH_PASS               "450Hz High-pass"
116#define MIXER_0DB_HIGH_PASS                 "High-pass 0dB"
117#define MIXER_FLAT_RESPONSE                 "Flat Response"
118#define MIXER_4KHZ_LPF_0DB                  "4Khz LPF   0dB"
119
120
121/* ALSA cards for OMAP4 */
122#define CARD_OMAP4_ABE 0
123#define CARD_OMAP4_HDMI 1
124#define CARD_OMAP4_USB 2
125#define CARD_BLAZE_DEFAULT CARD_OMAP4_ABE
126
127/* ALSA ports for OMAP4 */
128#define PORT_MM 0
129#define PORT_MM2_UL 1
130#define PORT_VX 2
131#define PORT_TONES 3
132#define PORT_VIBRA 4
133#define PORT_MODEM 5
134#define PORT_MM_LP 6
135
136/* constraint imposed by ABE for CBPr mode: all period sizes must be multiples of 24 */
137#define ABE_BASE_FRAME_COUNT 24
138/* number of base blocks in a short period (low latency) */
139#define SHORT_PERIOD_MULTIPLIER 80  /* 40 ms */
140/* number of frames per short period (low latency) */
141#define SHORT_PERIOD_SIZE (ABE_BASE_FRAME_COUNT * SHORT_PERIOD_MULTIPLIER)
142/* number of short periods in a long period (low power) */
143#define LONG_PERIOD_MULTIPLIER 1  /* 40 ms */
144/* number of frames per long period (low power) */
145#define LONG_PERIOD_SIZE (SHORT_PERIOD_SIZE * LONG_PERIOD_MULTIPLIER)
146/* number of periods for playback */
147#define PLAYBACK_PERIOD_COUNT 4
148/* number of periods for capture */
149#define CAPTURE_PERIOD_COUNT 2
150/* minimum sleep time in out_write() when write threshold is not reached */
151#define MIN_WRITE_SLEEP_US 5000
152
153#define RESAMPLER_BUFFER_FRAMES (SHORT_PERIOD_SIZE * 2)
154#define RESAMPLER_BUFFER_SIZE (4 * RESAMPLER_BUFFER_FRAMES)
155
156#define DEFAULT_OUT_SAMPLING_RATE 44100
157
158/* sampling rate when using MM low power port */
159#define MM_LOW_POWER_SAMPLING_RATE 44100
160/* sampling rate when using MM full power port */
161#define MM_FULL_POWER_SAMPLING_RATE 48000
162/* sampling rate when using VX port for narrow band */
163#define VX_NB_SAMPLING_RATE 8000
164/* sampling rate when using VX port for wide band */
165#define VX_WB_SAMPLING_RATE 16000
166
167/* conversions from dB to ABE and codec gains */
168#define DB_TO_ABE_GAIN(x) ((x) + MIXER_ABE_GAIN_0DB)
169#define DB_TO_CAPTURE_PREAMPLIFIER_VOLUME(x) (((x) + 6) / 6)
170#define DB_TO_CAPTURE_VOLUME(x) (((x) - 6) / 6)
171#define DB_TO_HEADSET_VOLUME(x) (((x) + 30) / 2)
172#define DB_TO_SPEAKER_VOLUME(x) (((x) + 52) / 2)
173#define DB_TO_EARPIECE_VOLUME(x) (((x) + 24) / 2)
174
175/* use-case specific mic volumes, all in dB */
176#define CAPTURE_DIGITAL_MIC_VOLUME            26
177#define CAPTURE_MAIN_MIC_VOLUME               15
178#define CAPTURE_SUB_MIC_VOLUME                15
179#define CAPTURE_HEADSET_MIC_VOLUME            15
180
181#define VOICE_RECOGNITION_MAIN_MIC_VOLUME     25
182#define VOICE_RECOGNITION_SUB_MIC_VOLUME      25
183#define VOICE_RECOGNITION_HEADSET_MIC_VOLUME  25
184
185#define CAMCORDER_MAIN_MIC_VOLUME             15
186#define CAMCORDER_SUB_MIC_VOLUME              15
187#define CAMCORDER_HEADSET_MIC_VOLUME          15
188
189#define VOIP_MAIN_MIC_VOLUME                  15
190#define VOIP_SUB_MIC_VOLUME                   15
191#define VOIP_HEADSET_MIC_VOLUME               15
192
193#define VOICE_CALL_MAIN_MIC_VOLUME            15
194#define VOICE_CALL_SUB_MIC_VOLUME             15
195#define VOICE_CALL_HEADSET_MIC_VOLUME         15
196
197/* use-case specific output volumes */
198#define NORMAL_SPEAKER_VOLUME                 0
199#define VOICE_CALL_SPEAKER_VOLUME             0
200
201#define HEADSET_VOLUME                        0
202#define HEADPHONE_VOLUME                      0 /* allow louder output for headphones */
203
204/* product-specific defines */
205#define PRODUCT_DEVICE_PROPERTY "ro.product.device"
206#define PRODUCT_DEVICE_BLAZE    "blaze"
207#define PRODUCT_DEVICE_TABLET   "blaze_tablet"
208#define PRODUCT_DEVICE_PANDA    "panda"
209
210enum supported_boards {
211    BLAZE,
212    TABLET,
213    PANDA
214};
215
216enum tty_modes {
217    TTY_MODE_OFF,
218    TTY_MODE_VCO,
219    TTY_MODE_HCO,
220    TTY_MODE_FULL
221};
222
223struct pcm_config pcm_config_mm = {
224    .channels = 2,
225    .rate = DEFAULT_OUT_SAMPLING_RATE,
226    .period_size = LONG_PERIOD_SIZE,
227    .period_count = PLAYBACK_PERIOD_COUNT,
228    .format = PCM_FORMAT_S16_LE,
229};
230
231struct pcm_config pcm_config_mm_ul = {
232    .channels = 2,
233    .rate = MM_FULL_POWER_SAMPLING_RATE,
234    .period_size = SHORT_PERIOD_SIZE,
235    .period_count = CAPTURE_PERIOD_COUNT,
236    .format = PCM_FORMAT_S16_LE,
237};
238
239struct pcm_config pcm_config_vx = {
240    .channels = 2,
241    .rate = VX_WB_SAMPLING_RATE,
242    .period_size = 160,
243    .period_count = 2,
244    .format = PCM_FORMAT_S16_LE,
245};
246
247#define MIN(x, y) ((x) > (y) ? (y) : (x))
248
249struct route_setting
250{
251    char *ctl_name;
252    int intval;
253    char *strval;
254};
255
256/* These are values that never change */
257struct route_setting defaults[] = {
258    /* general */
259    {
260        .ctl_name = MIXER_DL2_LEFT_EQUALIZER,
261        .strval = MIXER_0DB_HIGH_PASS,
262    },
263    {
264        .ctl_name = MIXER_DL2_RIGHT_EQUALIZER,
265        .strval = MIXER_0DB_HIGH_PASS,
266    },
267    {
268        .ctl_name = MIXER_DL1_EQUALIZER,
269        .strval = MIXER_FLAT_RESPONSE,
270    },
271    {
272        .ctl_name = MIXER_DL1_MEDIA_PLAYBACK_VOLUME,
273        .intval = MIXER_ABE_GAIN_0DB - 2,
274    },
275    {
276        .ctl_name = MIXER_DL2_MEDIA_PLAYBACK_VOLUME,
277        .intval = MIXER_ABE_GAIN_0DB - 2,
278    },
279    {
280        .ctl_name = MIXER_DL1_VOICE_PLAYBACK_VOLUME,
281        .intval = MIXER_ABE_GAIN_0DB,
282    },
283    {
284        .ctl_name = MIXER_DL2_VOICE_PLAYBACK_VOLUME,
285        .intval = MIXER_ABE_GAIN_0DB,
286    },
287    {
288        .ctl_name = MIXER_SDT_DL_VOLUME,
289        .intval = MIXER_ABE_GAIN_0DB,
290    },
291    {
292        .ctl_name = MIXER_EARPHONE_PLAYBACK_VOLUME,
293        .intval = DB_TO_EARPIECE_VOLUME(6),
294    },
295    {
296        .ctl_name = MIXER_AUDUL_VOICE_UL_VOLUME,
297        .intval = MIXER_ABE_GAIN_0DB,
298    },
299    {
300        .ctl_name = MIXER_CAPTURE_PREAMPLIFIER_VOLUME,
301        .intval = DB_TO_CAPTURE_PREAMPLIFIER_VOLUME(0),
302    },
303    {
304        .ctl_name = MIXER_CAPTURE_VOLUME,
305        .intval = DB_TO_CAPTURE_VOLUME(30),
306    },
307    {
308        .ctl_name = MIXER_SDT_UL_VOLUME,
309        .intval = MIXER_ABE_GAIN_0DB - 19,
310    },
311    {
312        .ctl_name = MIXER_SIDETONE_MIXER_CAPTURE,
313        .intval = 0,
314    },
315
316    /* headset */
317    {
318        .ctl_name = MIXER_SIDETONE_MIXER_PLAYBACK,
319        .intval = 1,
320    },
321    {
322        .ctl_name = MIXER_DL1_PDM_SWITCH,
323        .intval = 1,
324    },
325
326    /* bt */
327    {
328        .ctl_name = MIXER_BT_UL_VOLUME,
329        .intval = MIXER_ABE_GAIN_0DB,
330    },
331    {
332        .ctl_name = NULL,
333    },
334};
335
336struct route_setting hf_output[] = {
337    {
338        .ctl_name = MIXER_HF_LEFT_PLAYBACK,
339        .strval = MIXER_PLAYBACK_HF_DAC,
340    },
341    {
342        .ctl_name = MIXER_HF_RIGHT_PLAYBACK,
343        .strval = MIXER_PLAYBACK_HF_DAC,
344    },
345    {
346        .ctl_name = NULL,
347    },
348};
349
350struct route_setting hs_output[] = {
351    {
352        .ctl_name = MIXER_HS_LEFT_PLAYBACK,
353        .strval = MIXER_PLAYBACK_HS_DAC,
354    },
355    {
356        .ctl_name = MIXER_HS_RIGHT_PLAYBACK,
357        .strval = MIXER_PLAYBACK_HS_DAC,
358    },
359    {
360        .ctl_name = NULL,
361    },
362};
363
364struct route_setting fmtx_output_on[] ={
365   {
366        .ctl_name = MIXER_DL1_MM_EXT_SWITCH,
367        .intval = 1,
368   },
369   {
370        .ctl_name = MIXER_DL1_PDM_SWITCH,
371        .intval = 0,
372   },
373   {
374        .ctl_name = NULL,
375   },
376};
377
378struct route_setting fmtx_output_off[] ={
379   {
380        .ctl_name = MIXER_DL1_MM_EXT_SWITCH,
381        .intval = 0,
382   },
383   {
384        .ctl_name = MIXER_DL1_PDM_SWITCH,
385        .intval = 1,
386   },
387   {
388        .ctl_name = NULL,
389   },
390};
391
392/* MM UL front-end paths */
393struct route_setting mm_ul2_bt[] = {
394    {
395        .ctl_name = MIXER_MUX_UL10,
396        .strval = MIXER_BT_LEFT,
397    },
398    {
399        .ctl_name = MIXER_MUX_UL11,
400        .strval = MIXER_BT_LEFT,
401    },
402    {
403        .ctl_name = NULL,
404    },
405};
406
407struct route_setting mm_ul2_fmradio[] = {
408     {
409        .ctl_name = MIXER_MUX_UL10,
410        .strval = MIXER_AMIC1,
411     },
412     {
413        .ctl_name = MIXER_MUX_UL11,
414        .strval = MIXER_AMIC0,
415     },
416     {
417        .ctl_name =  MIXER_DL1_CAPTURE_PLAYBACK_VOLUME,  // Enable FM on wired headset only.
418        .intval = MIXER_ABE_GAIN_0DB,
419     },
420     {
421        .ctl_name = NULL,
422     },
423};
424
425struct route_setting mm_ul2_amic_left[] = {
426    {
427        .ctl_name = MIXER_MUX_UL10,
428        .strval = MIXER_AMIC0,
429    },
430    {
431        .ctl_name = MIXER_MUX_UL11,
432        .strval = MIXER_AMIC0,
433    },
434    {
435        .ctl_name = NULL,
436    },
437};
438
439struct route_setting mm_ul2_amic_right[] = {
440    {
441        .ctl_name = MIXER_MUX_UL10,
442        .strval = MIXER_AMIC1,
443    },
444    {
445        .ctl_name = MIXER_MUX_UL11,
446        .strval = MIXER_AMIC1,
447    },
448    {
449        .ctl_name = NULL,
450    },
451};
452
453struct route_setting mm_ul2_dmic0[] = {
454    {
455        .ctl_name = MIXER_MUX_UL10,
456        .strval = MIXER_DMIC0L,
457    },
458    {
459        .ctl_name = MIXER_MUX_UL11,
460        .strval = MIXER_DMIC0L,
461    },
462    {
463        .ctl_name = NULL,
464    },
465};
466
467/* VX UL front-end paths */
468struct route_setting vx_ul_amic_left[] = {
469    {
470        .ctl_name = MIXER_MUX_VX0,
471        .strval = MIXER_AMIC0,
472    },
473    {
474        .ctl_name = MIXER_MUX_VX1,
475        .strval = MIXER_AMIC0,
476    },
477    {
478        .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
479        .intval = 1,
480    },
481    {
482        .ctl_name = NULL,
483    },
484};
485
486struct route_setting vx_ul_amic_right[] = {
487    {
488        .ctl_name = MIXER_MUX_VX0,
489        .strval = MIXER_AMIC1,
490    },
491    {
492        .ctl_name = MIXER_MUX_VX1,
493        .strval = MIXER_AMIC1,
494    },
495    {
496        .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
497        .intval = 1,
498    },
499    {
500        .ctl_name = NULL,
501    },
502};
503struct route_setting vx_ul_dmic0[] = {
504    {
505        .ctl_name = MIXER_MUX_VX0,
506        .strval = MIXER_DMIC0L,
507    },
508    {
509        .ctl_name = MIXER_MUX_VX1,
510        .strval = MIXER_DMIC0L,
511    },
512    {
513        .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
514        .intval = 1,
515    },
516    {
517        .ctl_name = NULL,
518    },
519};
520
521struct route_setting vx_ul_bt[] = {
522    {
523        .ctl_name = MIXER_MUX_VX0,
524        .strval = MIXER_BT_LEFT,
525    },
526    {
527        .ctl_name = MIXER_MUX_VX1,
528        .strval = MIXER_BT_LEFT,
529    },
530    {
531        .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
532        .intval = 1,
533    },
534    {
535        .ctl_name = NULL,
536    },
537};
538
539struct buffer_remix;
540
541/* buffer_remix: functor for doing in-place buffer manipulations.
542 *
543 * NB. When remix_func is called, the memory at `buf` must be at least
544 * as large as frames * sample_size * MAX(in_chans, out_chans).
545 */
546struct buffer_remix {
547    void (*remix_func)(struct buffer_remix *data, void *buf, size_t frames);
548    size_t sample_size; /* size of one audio sample, in bytes */
549    size_t in_chans;    /* number of input channels */
550    size_t out_chans;   /* number of output channels */
551};
552
553
554struct mixer_ctls
555{
556    struct mixer_ctl *dl1_eq;
557    struct mixer_ctl *mm_dl1;
558    struct mixer_ctl *mm_dl2;
559    struct mixer_ctl *vx_dl1;
560    struct mixer_ctl *vx_dl2;
561    struct mixer_ctl *earpiece_enable;
562    struct mixer_ctl *dl2_mono;
563    struct mixer_ctl *dl1_mono;
564    struct mixer_ctl *dl1_headset;
565    struct mixer_ctl *dl1_bt;
566    struct mixer_ctl *left_capture;
567    struct mixer_ctl *right_capture;
568    struct mixer_ctl *amic_ul_volume;
569    struct mixer_ctl *dmic1_ul_volume;
570    struct mixer_ctl *voice_ul_volume;
571    struct mixer_ctl *sidetone_capture;
572    struct mixer_ctl *headset_volume;
573    struct mixer_ctl *speaker_volume;
574};
575
576struct omap4_audio_device {
577    struct audio_hw_device hw_device;
578
579    pthread_mutex_t lock;       /* see note below on mutex acquisition order */
580    struct mixer *mixer;
581    struct mixer_ctls mixer_ctls;
582    int mode;
583    int devices;
584    struct pcm *pcm_modem_dl;
585    struct pcm *pcm_modem_ul;
586    int in_call;
587    float voice_volume;
588    struct omap4_stream_in *active_input;
589    struct omap4_stream_out *active_output;
590    bool mic_mute;
591    int tty_mode;
592    int sidetone_capture;
593    int board_type;
594    struct echo_reference_itfe *echo_reference;
595    int input_requires_stereo;
596    bool low_power;
597    bool bluetooth_nrec;
598};
599
600struct omap4_stream_out {
601    struct audio_stream_out stream;
602
603    pthread_mutex_t lock;       /* see note below on mutex acquisition order */
604    struct pcm_config config;
605    struct pcm *pcm;
606    struct resampler_itfe *resampler;
607    char *buffer;
608    int standby;
609    struct echo_reference_itfe *echo_reference;
610    int write_threshold;
611    bool low_power;
612
613    struct omap4_audio_device *dev;
614};
615
616#define MAX_PREPROCESSORS 3 /* maximum one AGC + one NS + one AEC per input stream */
617
618struct omap4_stream_in {
619    struct audio_stream_in stream;
620
621    pthread_mutex_t lock;       /* see note below on mutex acquisition order */
622    struct pcm_config config;
623    struct pcm *pcm;
624    int device;
625    struct resampler_itfe *resampler;
626    struct resampler_buffer_provider buf_provider;
627    int16_t *buffer;
628    size_t frames_in;
629    unsigned int requested_rate;
630    int standby;
631    int source;
632    struct echo_reference_itfe *echo_reference;
633    bool need_echo_reference;
634    effect_handle_t preprocessors[MAX_PREPROCESSORS];
635    int num_preprocessors;
636    int16_t *proc_buf;
637    size_t proc_buf_size;
638    size_t proc_frames_in;
639    int16_t *ref_buf;
640    size_t ref_buf_size;
641    size_t ref_frames_in;
642    int read_status;
643    struct buffer_remix *remix_at_driver; /* adapt hw chan count to client */
644
645    struct omap4_audio_device *dev;
646};
647
648/**
649 * NOTE: when multiple mutexes have to be acquired, always respect the following order:
650 *        hw device > in stream > out stream
651 */
652
653
654static void select_output_device(struct omap4_audio_device *adev);
655static void select_input_device(struct omap4_audio_device *adev);
656static int adev_set_voice_volume(struct audio_hw_device *dev, float volume);
657static int do_input_standby(struct omap4_stream_in *in);
658static int do_output_standby(struct omap4_stream_out *out);
659
660/* Implementation of buffer_remix::remix_func that removes
661 * channels in place without doing any other processing.  The
662 * extra channels are truncated.
663 */
664static void remove_channels_from_buf(struct buffer_remix *data, void *buf, size_t frames)
665{
666    size_t samp_size, in_frame, out_frame;
667    size_t N, c;
668    char *s, *d;
669
670    LOGFUNC("%s(%p, %p, %d)", __FUNCTION__, data, buf, frames);
671    if (frames == 0)
672        return;
673
674
675    samp_size = data->sample_size;
676    in_frame = data->in_chans * samp_size;
677    out_frame = data->out_chans * samp_size;
678
679    if (out_frame >= in_frame) {
680        ALOGE("BUG: remove_channels_from_buf() can not add channels to a buffer.\n");
681        return;
682    }
683
684    N = frames - 1;
685    d = (char*)buf + out_frame;
686    s = (char*)buf + in_frame;
687
688    /* take the first several channels and
689     * truncate the rest
690     */
691    while (N--) {
692        for (c=0 ; c < out_frame ; ++c)
693            d[c] = s[c];
694        d += out_frame;
695        s += in_frame;
696    }
697}
698
699static void setup_stereo_to_mono_input_remix(struct omap4_stream_in *in)
700{
701    struct buffer_remix *br = (struct buffer_remix *)malloc(sizeof(struct buffer_remix));
702
703    LOGFUNC("%s(%p)", __FUNCTION__, in);
704
705
706    if (br) {
707        br->remix_func = remove_channels_from_buf;
708        br->sample_size = audio_stream_frame_size(&in->stream.common) / in->config.channels;
709        br->in_chans = 2;
710        br->out_chans = 1;
711    } else
712        ALOGE("Could not allocate memory for struct buffer_remix\n");
713
714    if (in->buffer) {
715        size_t chans = (br->in_chans > br->out_chans) ? br->in_chans : br->out_chans;
716        free(in->buffer);
717        in->buffer = malloc(in->config.period_size * br->sample_size * chans);
718        if (!in->buffer)
719            ALOGE("Could not reallocate memory for input buffer\n");
720    }
721
722    if (in->remix_at_driver)
723        free(in->remix_at_driver);
724    in->remix_at_driver = br;
725}
726
727static int get_boardtype(struct omap4_audio_device *adev)
728{
729    char board[PROPERTY_VALUE_MAX];
730    int status = 0;
731    int board_type = 0;
732
733    LOGFUNC("%s(%p)", __FUNCTION__, adev);
734
735    property_get(PRODUCT_DEVICE_PROPERTY, board, PRODUCT_DEVICE_BLAZE);
736    /* return true if the property matches the given value */
737    if(!strcmp(board, PRODUCT_DEVICE_BLAZE)) {
738            adev->board_type = BLAZE;
739          /*true on devices that must use sidetone capture */
740            adev->sidetone_capture = 1;
741    }
742    else if(!strcmp(board, PRODUCT_DEVICE_TABLET)) {
743            adev->board_type = TABLET;
744            adev->sidetone_capture = 0;
745    }
746    else if(!strcmp(board, PRODUCT_DEVICE_PANDA)) {
747            adev->board_type = PANDA;
748            adev->sidetone_capture = 0;
749    }
750    else
751        return -EINVAL;
752
753    return 0;
754}
755/* The enable flag when 0 makes the assumption that enums are disabled by
756 * "Off" and integers/booleans by 0 */
757
758static int set_route_by_array(struct mixer *mixer, struct route_setting *route,
759                              int enable)
760{
761    struct mixer_ctl *ctl;
762    unsigned int i, j;
763
764    LOGFUNC("%s(%p, %p, %d)", __FUNCTION__, mixer, route, enable);
765
766    /* Go through the route array and set each value */
767    i = 0;
768    while (route[i].ctl_name) {
769        ctl = mixer_get_ctl_by_name(mixer, route[i].ctl_name);
770        if (!ctl)
771            return -EINVAL;
772
773        if (route[i].strval) {
774            if (enable)
775                mixer_ctl_set_enum_by_string(ctl, route[i].strval);
776            else
777                mixer_ctl_set_enum_by_string(ctl, "Off");
778        } else {
779            /* This ensures multiple (i.e. stereo) values are set jointly */
780            for (j = 0; j < mixer_ctl_get_num_values(ctl); j++) {
781                if (enable)
782                    mixer_ctl_set_value(ctl, j, route[i].intval);
783                else
784                    mixer_ctl_set_value(ctl, j, 0);
785            }
786        }
787        i++;
788    }
789
790    return 0;
791}
792
793static int start_call(struct omap4_audio_device *adev)
794{
795    ALOGE("Opening modem PCMs");
796    LOGFUNC("%s(%p)", __FUNCTION__, adev);
797
798    pcm_config_vx.rate = VX_NB_SAMPLING_RATE;
799
800    /* Open modem PCM channels */
801    if (adev->pcm_modem_dl == NULL) {
802        adev->pcm_modem_dl = pcm_open(0, PORT_MODEM, PCM_OUT, &pcm_config_vx);
803        if (!pcm_is_ready(adev->pcm_modem_dl)) {
804            ALOGE("cannot open PCM modem DL stream: %s", pcm_get_error(adev->pcm_modem_dl));
805            goto err_open_dl;
806        }
807    }
808
809    if (adev->pcm_modem_ul == NULL) {
810        adev->pcm_modem_ul = pcm_open(0, PORT_MODEM, PCM_IN, &pcm_config_vx);
811        if (!pcm_is_ready(adev->pcm_modem_ul)) {
812            ALOGE("cannot open PCM modem UL stream: %s", pcm_get_error(adev->pcm_modem_ul));
813            goto err_open_ul;
814        }
815    }
816
817    pcm_start(adev->pcm_modem_dl);
818    pcm_start(adev->pcm_modem_ul);
819
820    return 0;
821
822err_open_ul:
823    pcm_close(adev->pcm_modem_ul);
824    adev->pcm_modem_ul = NULL;
825err_open_dl:
826    pcm_close(adev->pcm_modem_dl);
827    adev->pcm_modem_dl = NULL;
828
829    return -ENOMEM;
830}
831
832static void end_call(struct omap4_audio_device *adev)
833{
834    ALOGE("Closing modem PCMs");
835    LOGFUNC("%s(%p)", __FUNCTION__, adev);
836
837    pcm_stop(adev->pcm_modem_dl);
838    pcm_stop(adev->pcm_modem_ul);
839    pcm_close(adev->pcm_modem_dl);
840    pcm_close(adev->pcm_modem_ul);
841    adev->pcm_modem_dl = NULL;
842    adev->pcm_modem_ul = NULL;
843}
844
845static void set_eq_filter(struct omap4_audio_device *adev)
846{
847    LOGFUNC("%s(%p)", __FUNCTION__, adev);
848}
849
850static void set_incall_device(struct omap4_audio_device *adev)
851{
852	return;
853}
854
855static void set_input_volumes(struct omap4_audio_device *adev, int main_mic_on,
856                              int headset_mic_on, int sub_mic_on)
857{
858    unsigned int channel;
859    int volume = MIXER_ABE_GAIN_0DB;
860
861    LOGFUNC("%s(%p, %d, %d, %d)", __FUNCTION__, adev, main_mic_on,
862                                headset_mic_on, sub_mic_on);
863
864    if (adev->mode == AUDIO_MODE_IN_CALL) {
865        /* special case: don't look at input source for IN_CALL state */
866        volume = DB_TO_ABE_GAIN(main_mic_on ? VOICE_CALL_MAIN_MIC_VOLUME :
867                (headset_mic_on ? VOICE_CALL_HEADSET_MIC_VOLUME :
868                (sub_mic_on ? VOICE_CALL_SUB_MIC_VOLUME : 0)));
869    } else if (adev->active_input) {
870        /* determine input volume by use case */
871        switch (adev->active_input->source) {
872        case AUDIO_SOURCE_MIC: /* general capture */
873            if(adev->board_type == BLAZE) {
874                volume = DB_TO_ABE_GAIN(main_mic_on ? CAPTURE_MAIN_MIC_VOLUME :
875                    (headset_mic_on ? CAPTURE_HEADSET_MIC_VOLUME :
876                    (sub_mic_on ? CAPTURE_SUB_MIC_VOLUME : 0)));
877            }else if(adev->board_type == TABLET) {
878                volume = DB_TO_ABE_GAIN(main_mic_on ? CAPTURE_DIGITAL_MIC_VOLUME :
879                    (headset_mic_on ? CAPTURE_HEADSET_MIC_VOLUME :
880                     (sub_mic_on ? CAPTURE_SUB_MIC_VOLUME : 0)));
881            }
882            break;
883
884        case AUDIO_SOURCE_CAMCORDER:
885            volume = DB_TO_ABE_GAIN(main_mic_on ? CAMCORDER_MAIN_MIC_VOLUME :
886                    (headset_mic_on ? CAMCORDER_HEADSET_MIC_VOLUME :
887                    (sub_mic_on ? CAMCORDER_SUB_MIC_VOLUME : 0)));
888            break;
889
890        case AUDIO_SOURCE_VOICE_RECOGNITION:
891            volume = DB_TO_ABE_GAIN(main_mic_on ? VOICE_RECOGNITION_MAIN_MIC_VOLUME :
892                    (headset_mic_on ? VOICE_RECOGNITION_HEADSET_MIC_VOLUME :
893                    (sub_mic_on ? VOICE_RECOGNITION_SUB_MIC_VOLUME : 0)));
894            break;
895
896        case AUDIO_SOURCE_VOICE_COMMUNICATION: /* VoIP */
897            volume = DB_TO_ABE_GAIN(main_mic_on ? VOIP_MAIN_MIC_VOLUME :
898                    (headset_mic_on ? VOIP_HEADSET_MIC_VOLUME :
899                    (sub_mic_on ? VOIP_SUB_MIC_VOLUME : 0)));
900            break;
901
902        default:
903            /* nothing to do */
904            break;
905        }
906    }
907
908    for (channel = 0; channel < 2; channel++) {
909        if(adev->board_type == BLAZE) {
910            mixer_ctl_set_value(adev->mixer_ctls.amic_ul_volume, channel, volume);
911        }else if(adev->board_type == TABLET) {
912            if (headset_mic_on)
913                mixer_ctl_set_value(adev->mixer_ctls.amic_ul_volume, channel, volume);
914            else
915                mixer_ctl_set_value(adev->mixer_ctls.dmic1_ul_volume, channel, volume);
916        }
917    }
918}
919
920static void set_output_volumes(struct omap4_audio_device *adev)
921{
922    unsigned int channel;
923    int speaker_volume;
924    int headset_volume;
925
926    speaker_volume = adev->mode == AUDIO_MODE_IN_CALL ? VOICE_CALL_SPEAKER_VOLUME :
927                                                        NORMAL_SPEAKER_VOLUME;
928    headset_volume = adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADSET ?
929                                                        HEADSET_VOLUME :
930                                                        HEADPHONE_VOLUME;
931
932    for (channel = 0; channel < 2; channel++) {
933        mixer_ctl_set_value(adev->mixer_ctls.speaker_volume, channel,
934            DB_TO_SPEAKER_VOLUME(speaker_volume));
935        mixer_ctl_set_value(adev->mixer_ctls.headset_volume, channel,
936            DB_TO_HEADSET_VOLUME(headset_volume));
937    }
938}
939
940static void force_all_standby(struct omap4_audio_device *adev)
941{
942    struct omap4_stream_in *in;
943    struct omap4_stream_out *out;
944
945    LOGFUNC("%s(%p)", __FUNCTION__, adev);
946
947    if (adev->active_output) {
948        out = adev->active_output;
949        pthread_mutex_lock(&out->lock);
950        do_output_standby(out);
951        pthread_mutex_unlock(&out->lock);
952    }
953    if (adev->active_input) {
954        in = adev->active_input;
955        pthread_mutex_lock(&in->lock);
956        do_input_standby(in);
957        pthread_mutex_unlock(&in->lock);
958    }
959}
960
961static void select_mode(struct omap4_audio_device *adev)
962{
963    LOGFUNC("%s(%p)", __FUNCTION__, adev);
964
965    if (adev->mode == AUDIO_MODE_IN_CALL) {
966        ALOGE("Entering IN_CALL state, in_call=%d", adev->in_call);
967        if (!adev->in_call) {
968            force_all_standby(adev);
969            /* force earpiece route for in call state if speaker is the
970            only currently selected route. This prevents having to tear
971            down the modem PCMs to change route from speaker to earpiece
972            after the ringtone is played, but doesn't cause a route
973            change if a headset or bt device is already connected. If
974            speaker is not the only thing active, just remove it from
975            the route. We'll assume it'll never be used initally during
976            a call. This works because we're sure that the audio policy
977            manager will update the output device after the audio mode
978            change, even if the device selection did not change. */
979            if ((adev->devices & AUDIO_DEVICE_OUT_ALL) == AUDIO_DEVICE_OUT_SPEAKER)
980                adev->devices = AUDIO_DEVICE_OUT_EARPIECE |
981                                AUDIO_DEVICE_IN_BUILTIN_MIC;
982            else
983                adev->devices &= ~AUDIO_DEVICE_OUT_SPEAKER;
984            select_output_device(adev);
985            start_call(adev);
986            adev_set_voice_volume(&adev->hw_device, adev->voice_volume);
987            adev->in_call = 1;
988        }
989    } else {
990        ALOGE("Leaving IN_CALL state, in_call=%d, mode=%d",
991             adev->in_call, adev->mode);
992        if (adev->in_call) {
993            adev->in_call = 0;
994            end_call(adev);
995            force_all_standby(adev);
996            select_output_device(adev);
997            select_input_device(adev);
998        }
999    }
1000}
1001
1002static void select_output_device(struct omap4_audio_device *adev)
1003{
1004    int headset_on;
1005    int headphone_on;
1006    int speaker_on;
1007    int earpiece_on;
1008    int bt_on;
1009    int dl1_on;
1010    int fmtx_on;
1011    int sidetone_capture_on = 0;
1012    unsigned int channel, voice_ul_volume[2];
1013
1014    LOGFUNC("%s(%p)", __FUNCTION__, adev);
1015
1016    if(adev->board_type ==  PANDA) {
1017        headset_on = 0;
1018        speaker_on = 1;
1019        mixer_ctl_set_value(adev->mixer_ctls.mm_dl1, 0, 1);
1020        set_route_by_array(adev->mixer, hs_output, 1);
1021        set_input_volumes(adev, 0,
1022                        headset_on, speaker_on);
1023    } else {
1024        headset_on = adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
1025        headphone_on = adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
1026        speaker_on = adev->devices & AUDIO_DEVICE_OUT_SPEAKER;
1027        earpiece_on = adev->devices & AUDIO_DEVICE_OUT_EARPIECE;
1028        bt_on = adev->devices & AUDIO_DEVICE_OUT_ALL_SCO;
1029
1030        /* force rx path according to TTY mode when in call */
1031        if (adev->mode == AUDIO_MODE_IN_CALL && !bt_on) {
1032            switch(adev->tty_mode) {
1033                case TTY_MODE_FULL:
1034                case TTY_MODE_VCO:
1035                    /* rx path to headphones */
1036                    headphone_on = 1;
1037                    headset_on = 0;
1038                    speaker_on = 0;
1039                    earpiece_on = 0;
1040                    break;
1041                case TTY_MODE_HCO:
1042                    /* rx path to device speaker */
1043                    headphone_on = 0;
1044                    headset_on = 0;
1045                    speaker_on = 1;
1046                    earpiece_on = 0;
1047                    break;
1048                case TTY_MODE_OFF:
1049                default:
1050                    /* force speaker on when in call and HDMI is selected as voice DL audio
1051                     * cannot be routed to HDMI by ABE */
1052                    if (adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
1053                        speaker_on = 1;
1054                    break;
1055            }
1056        }
1057
1058        dl1_on = headset_on | headphone_on | earpiece_on | bt_on;
1059
1060        /* Select front end */
1061        mixer_ctl_set_value(adev->mixer_ctls.mm_dl2, 0, speaker_on);
1062        mixer_ctl_set_value(adev->mixer_ctls.vx_dl2, 0,
1063                            speaker_on && (adev->mode == AUDIO_MODE_IN_CALL));
1064        mixer_ctl_set_value(adev->mixer_ctls.mm_dl1, 0, dl1_on);
1065        mixer_ctl_set_value(adev->mixer_ctls.vx_dl1, 0,
1066                            dl1_on && (adev->mode == AUDIO_MODE_IN_CALL));
1067        /* Select back end */
1068        mixer_ctl_set_value(adev->mixer_ctls.dl1_headset, 0,
1069                            headset_on | headphone_on | earpiece_on);
1070        mixer_ctl_set_value(adev->mixer_ctls.dl1_bt, 0, bt_on);
1071        mixer_ctl_set_value(adev->mixer_ctls.earpiece_enable, 0, earpiece_on);
1072
1073        /* select output stage */
1074        set_route_by_array(adev->mixer, hs_output, headset_on | headphone_on);
1075        set_route_by_array(adev->mixer, hf_output, speaker_on);
1076
1077        set_route_by_array(adev->mixer, fmtx_output_off, 1);
1078
1079        set_output_volumes(adev);
1080        /* Special case: select input path if in a call, otherwise
1081           in_set_parameters is used to update the input route
1082           todo: use sub mic for handsfree case */
1083        if (adev->mode == AUDIO_MODE_IN_CALL) {
1084            if (bt_on)
1085                set_route_by_array(adev->mixer, vx_ul_bt, bt_on);
1086            else {
1087                /* force tx path according to TTY mode when in call */
1088                switch(adev->tty_mode) {
1089                    case TTY_MODE_FULL:
1090                    case TTY_MODE_VCO:
1091                        /* rx path to headphones */
1092                        headphone_on = 1;
1093                        headset_on = 0;
1094                        speaker_on = 0;
1095                        earpiece_on = 0;
1096                        break;
1097                    case TTY_MODE_HCO:
1098                        /* rx path to device speaker */
1099                        headphone_on = 0;
1100                        headset_on = 0;
1101                        speaker_on = 1;
1102                        earpiece_on = 0;
1103                        break;
1104                    case TTY_MODE_OFF:
1105                    default:
1106                        /* force speaker on when in call and HDMI is selected as voice DL audio
1107                         * cannot be routed to HDMI by ABE */
1108                        if (adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
1109                            speaker_on = 1;
1110                        break;
1111                }
1112            }
1113
1114            dl1_on = headset_on | headphone_on | earpiece_on | bt_on;
1115
1116            /* Select front end */
1117            mixer_ctl_set_value(adev->mixer_ctls.mm_dl2, 0, speaker_on);
1118            mixer_ctl_set_value(adev->mixer_ctls.vx_dl2, 0,
1119                    speaker_on && (adev->mode == AUDIO_MODE_IN_CALL));
1120            mixer_ctl_set_value(adev->mixer_ctls.mm_dl1, 0, dl1_on);
1121            mixer_ctl_set_value(adev->mixer_ctls.vx_dl1, 0,
1122                    dl1_on && (adev->mode == AUDIO_MODE_IN_CALL));
1123            /* Select back end */
1124            mixer_ctl_set_value(adev->mixer_ctls.dl1_headset, 0,
1125                    headset_on | headphone_on | earpiece_on);
1126            mixer_ctl_set_value(adev->mixer_ctls.dl1_bt, 0, bt_on);
1127            mixer_ctl_set_value(adev->mixer_ctls.earpiece_enable, 0, earpiece_on);
1128
1129            /* select output stage */
1130            set_route_by_array(adev->mixer, hs_output, headset_on | headphone_on);
1131            set_route_by_array(adev->mixer, hf_output, speaker_on);
1132
1133            set_output_volumes(adev);
1134            /* Special case: select input path if in a call, otherwise
1135               in_set_parameters is used to update the input route
1136               todo: use sub mic for handsfree case */
1137            if (adev->mode == AUDIO_MODE_IN_CALL) {
1138                if (bt_on)
1139                    set_route_by_array(adev->mixer, vx_ul_bt, bt_on);
1140                else {
1141                    /* force tx path according to TTY mode when in call */
1142                    switch(adev->tty_mode) {
1143                        case TTY_MODE_FULL:
1144                        case TTY_MODE_HCO:
1145                            /* tx path from headset mic */
1146                            headphone_on = 0;
1147                            headset_on = 1;
1148                            speaker_on = 0;
1149                            earpiece_on = 0;
1150                            break;
1151                        case TTY_MODE_VCO:
1152                            /* tx path from device sub mic */
1153                            headphone_on = 0;
1154                            headset_on = 0;
1155                            speaker_on = 1;
1156                            earpiece_on = 0;
1157                            break;
1158                        case TTY_MODE_OFF:
1159                        default:
1160                            break;
1161                    }
1162
1163                    if (headset_on || headphone_on || earpiece_on)
1164                        set_route_by_array(adev->mixer, vx_ul_amic_left, 1);
1165                    else if (speaker_on) {
1166                        if(adev->board_type == BLAZE)
1167                            set_route_by_array(adev->mixer, vx_ul_amic_right, 1);
1168                        else if(adev->board_type == TABLET)
1169                            set_route_by_array(adev->mixer, vx_ul_dmic0,1);
1170                    }
1171                    else {
1172                        if(adev->board_type == BLAZE)
1173                            set_route_by_array(adev->mixer, vx_ul_amic_left, 0);
1174                        else if(adev->board_type == TABLET)
1175                            set_route_by_array(adev->mixer, vx_ul_dmic0,0);
1176                    }
1177                    if(adev->board_type == BLAZE) {
1178                        mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture,
1179                                (earpiece_on || headphone_on) ? MIXER_MAIN_MIC :
1180                                (headset_on ? MIXER_HS_MIC : "Off"));
1181                        mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture,
1182                                speaker_on ? MIXER_SUB_MIC : "Off");
1183                    } else if(adev->board_type == TABLET) {
1184                        mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture,
1185                                (headset_on ? MIXER_HS_MIC : "Off"));
1186                        mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture, "off");
1187                    }
1188
1189                    set_input_volumes(adev, earpiece_on || headphone_on,
1190                            headset_on, speaker_on);
1191
1192                    /* enable sidetone mixer capture if needed */
1193                    sidetone_capture_on = earpiece_on && adev->sidetone_capture;
1194                }
1195                set_incall_device(adev);
1196            }
1197
1198            mixer_ctl_set_value(adev->mixer_ctls.sidetone_capture, 0, sidetone_capture_on);
1199        }
1200    }
1201}
1202
1203static void select_input_device(struct omap4_audio_device *adev)
1204{
1205    int headset_on = 0;
1206    int main_mic_on = 0;
1207    int sub_mic_on = 0;
1208    int bt_on = adev->devices & AUDIO_DEVICE_IN_ALL_SCO;
1209    int hw_is_stereo_only = 0;
1210
1211    LOGFUNC("%s(%p)", __FUNCTION__, adev);
1212
1213    if(adev->board_type == PANDA) {
1214        /*panda only supports headset mic */
1215        main_mic_on = 0;
1216        headset_on = 1;
1217        sub_mic_on = 0;
1218        set_route_by_array(adev->mixer, mm_ul2_amic_left, 1);
1219        /* Select back end */
1220        mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture, MIXER_HS_MIC);
1221        mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture, MIXER_HS_MIC);
1222        set_input_volumes(adev, main_mic_on, headset_on, sub_mic_on);
1223    } else {
1224        if (!bt_on) {
1225            if ((adev->mode != AUDIO_MODE_IN_CALL) && (adev->active_input != 0)) {
1226                /* sub mic is used for camcorder or VoIP on speaker phone */
1227                sub_mic_on = (adev->active_input->source == AUDIO_SOURCE_CAMCORDER) ||
1228                    ((adev->devices & AUDIO_DEVICE_OUT_SPEAKER) &&
1229                     (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION));
1230            }
1231            if (!sub_mic_on) {
1232                headset_on = adev->devices & AUDIO_DEVICE_IN_WIRED_HEADSET;
1233                main_mic_on = adev->devices & AUDIO_DEVICE_IN_BUILTIN_MIC;
1234            }
1235        }
1236
1237        /* TODO: check how capture is possible during voice calls or if
1238         * both use cases are mutually exclusive.
1239         */
1240        if (bt_on)
1241            set_route_by_array(adev->mixer, mm_ul2_bt, 1);
1242        else {
1243            if(adev->board_type == BLAZE) {
1244                /* Select front end */
1245                if (main_mic_on || headset_on)
1246                    set_route_by_array(adev->mixer, mm_ul2_amic_left, 1);
1247                else if (sub_mic_on)
1248                    set_route_by_array(adev->mixer, mm_ul2_amic_right, 1);
1249                else
1250                    set_route_by_array(adev->mixer, mm_ul2_amic_left, 0);
1251                /* Select back end */
1252                mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture,
1253                        sub_mic_on ? MIXER_SUB_MIC : "Off");
1254                mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture,
1255                        main_mic_on ? MIXER_MAIN_MIC :
1256                        (headset_on ? MIXER_HS_MIC : "Off"));
1257            } else if(adev->board_type == TABLET) {
1258                /* Select front end */
1259                if (headset_on)
1260                    set_route_by_array(adev->mixer, mm_ul2_amic_left, 1);
1261                else if (main_mic_on || sub_mic_on) {
1262                    set_route_by_array(adev->mixer, mm_ul2_dmic0, 1);
1263                    hw_is_stereo_only = 1;
1264                } else {
1265                    set_route_by_array(adev->mixer, mm_ul2_dmic0, 0);
1266                    hw_is_stereo_only = 1;
1267                }
1268
1269                /* Select back end */
1270                mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture, "off");
1271                mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture,
1272                        main_mic_on ? "off" :
1273                        (headset_on ? MIXER_HS_MIC : "Off"));
1274            }
1275        }
1276
1277        adev->input_requires_stereo = hw_is_stereo_only;
1278
1279        set_input_volumes(adev, main_mic_on, headset_on, sub_mic_on);
1280    }
1281}
1282
1283/* must be called with hw device and output stream mutexes locked */
1284static int start_output_stream(struct omap4_stream_out *out)
1285{
1286    struct omap4_audio_device *adev = out->dev;
1287    unsigned int card = CARD_BLAZE_DEFAULT;
1288    unsigned int port = PORT_MM_LP;
1289
1290    LOGFUNC("%s(%p)", __FUNCTION__, adev);
1291
1292    adev->active_output = out;
1293    if (adev->devices & AUDIO_DEVICE_OUT_ALL_SCO)
1294        out->config.rate = MM_FULL_POWER_SAMPLING_RATE;
1295    else
1296        out->config.rate = DEFAULT_OUT_SAMPLING_RATE;
1297
1298    if (adev->mode != AUDIO_MODE_IN_CALL) {
1299        /* FIXME: only works if only one output can be active at a time */
1300        select_output_device(adev);
1301    }
1302
1303    /* in the case of multiple devices, this will cause use of HDMI only */
1304    if(adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
1305        card = CARD_OMAP4_HDMI;
1306        port = PORT_MM;
1307    }
1308    if((adev->devices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET) ||
1309        (adev->devices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
1310        card = CARD_OMAP4_USB;
1311        port = PORT_MM;
1312    }
1313    /* default to low power:
1314     *  NOTE: PCM_NOIRQ mode is required to dynamically scale avail_min
1315     */
1316    out->write_threshold = PLAYBACK_PERIOD_COUNT * LONG_PERIOD_SIZE;
1317    out->config.start_threshold = SHORT_PERIOD_SIZE * 2;
1318    out->config.avail_min = LONG_PERIOD_SIZE,
1319    out->low_power = 1;
1320
1321    out->pcm = pcm_open(card, port, PCM_OUT | PCM_MMAP, &out->config);
1322
1323    if (!pcm_is_ready(out->pcm)) {
1324        ALOGE("cannot open pcm_out driver: %s", pcm_get_error(out->pcm));
1325        pcm_close(out->pcm);
1326        adev->active_output = NULL;
1327        return -ENOMEM;
1328    }
1329
1330    if (adev->echo_reference != NULL)
1331        out->echo_reference = adev->echo_reference;
1332    if (out->resampler)
1333        out->resampler->reset(out->resampler);
1334
1335    return 0;
1336}
1337
1338static int check_input_parameters(uint32_t sample_rate, int format, int channel_count)
1339{
1340    LOGFUNC("%s(%d, %d, %d)", __FUNCTION__, sample_rate, format, channel_count);
1341
1342    if (format != AUDIO_FORMAT_PCM_16_BIT) {
1343        return -EINVAL;
1344    }
1345
1346    if ((channel_count < 1) || (channel_count > 2)) {
1347        return -EINVAL;
1348    }
1349
1350    switch(sample_rate) {
1351    case 8000:
1352    case 11025:
1353    case 16000:
1354    case 22050:
1355    case 24000:
1356    case 32000:
1357    case 44100:
1358    case 48000:
1359        break;
1360    default:
1361        return -EINVAL;
1362    }
1363
1364    return 0;
1365}
1366
1367static size_t get_input_buffer_size(uint32_t sample_rate, int format, int channel_count)
1368{
1369    size_t size;
1370    size_t device_rate;
1371
1372    LOGFUNC("%s(%d, %d, %d)", __FUNCTION__, sample_rate, format, channel_count);
1373
1374    if (check_input_parameters(sample_rate, format, channel_count) != 0)
1375        return 0;
1376
1377    /* take resampling into account and return the closest majoring
1378    multiple of 16 frames, as audioflinger expects audio buffers to
1379    be a multiple of 16 frames */
1380    size = (pcm_config_mm_ul.period_size * sample_rate) / pcm_config_mm_ul.rate;
1381    size = ((size + 15) / 16) * 16;
1382
1383    return size * channel_count * sizeof(short);
1384}
1385
1386static void add_echo_reference(struct omap4_stream_out *out,
1387                               struct echo_reference_itfe *reference)
1388{
1389    LOGFUNC("%s(%p, %p)", __FUNCTION__, out, reference);
1390
1391    pthread_mutex_lock(&out->lock);
1392    out->echo_reference = reference;
1393    pthread_mutex_unlock(&out->lock);
1394}
1395
1396static void remove_echo_reference(struct omap4_stream_out *out,
1397                                  struct echo_reference_itfe *reference)
1398{
1399    LOGFUNC("%s(%p, %p)", __FUNCTION__, out, reference);
1400
1401    pthread_mutex_lock(&out->lock);
1402    if (out->echo_reference == reference) {
1403        /* stop writing to echo reference */
1404        reference->write(reference, NULL);
1405        out->echo_reference = NULL;
1406    }
1407    pthread_mutex_unlock(&out->lock);
1408}
1409
1410static void put_echo_reference(struct omap4_audio_device *adev,
1411                          struct echo_reference_itfe *reference)
1412{
1413    LOGFUNC("%s(%p, %p)", __FUNCTION__, adev, reference);
1414
1415    if (adev->echo_reference != NULL &&
1416            reference == adev->echo_reference) {
1417        if (adev->active_output != NULL)
1418            remove_echo_reference(adev->active_output, reference);
1419        release_echo_reference(reference);
1420        adev->echo_reference = NULL;
1421    }
1422}
1423
1424static struct echo_reference_itfe *get_echo_reference(struct omap4_audio_device *adev,
1425                                               audio_format_t format,
1426                                               uint32_t channel_count,
1427                                               uint32_t sampling_rate)
1428{
1429    LOGFUNC("%s(%p, 0x%08x, 0x%04x, %d)", __FUNCTION__, adev, format,
1430                                                channel_count, sampling_rate);
1431
1432    put_echo_reference(adev, adev->echo_reference);
1433    if (adev->active_output != NULL) {
1434        struct audio_stream *stream = &adev->active_output->stream.common;
1435        uint32_t wr_channel_count = popcount(stream->get_channels(stream));
1436        uint32_t wr_sampling_rate = stream->get_sample_rate(stream);
1437
1438        int status = create_echo_reference(AUDIO_FORMAT_PCM_16_BIT,
1439                                           channel_count,
1440                                           sampling_rate,
1441                                           AUDIO_FORMAT_PCM_16_BIT,
1442                                           wr_channel_count,
1443                                           wr_sampling_rate,
1444                                           &adev->echo_reference);
1445        if (status == 0)
1446            add_echo_reference(adev->active_output, adev->echo_reference);
1447    }
1448    return adev->echo_reference;
1449}
1450
1451static int get_playback_delay(struct omap4_stream_out *out,
1452                       size_t frames,
1453                       struct echo_reference_buffer *buffer)
1454{
1455    size_t kernel_frames;
1456    int status;
1457
1458    LOGFUNC("%s(%p, %ul, %p)", __FUNCTION__, out, frames, buffer);
1459
1460    status = pcm_get_htimestamp(out->pcm, &kernel_frames, &buffer->time_stamp);
1461    if (status < 0) {
1462        buffer->time_stamp.tv_sec  = 0;
1463        buffer->time_stamp.tv_nsec = 0;
1464        buffer->delay_ns           = 0;
1465        ALOGV("get_playback_delay(): pcm_get_htimestamp error,"
1466                "setting playbackTimestamp to 0");
1467        return status;
1468    }
1469
1470    kernel_frames = pcm_get_buffer_size(out->pcm) - kernel_frames;
1471
1472    /* adjust render time stamp with delay added by current driver buffer.
1473     * Add the duration of current frame as we want the render time of the last
1474     * sample being written. */
1475    buffer->delay_ns = (long)(((int64_t)(kernel_frames + frames)* 1000000000)/
1476                            MM_FULL_POWER_SAMPLING_RATE);
1477
1478    return 0;
1479}
1480
1481static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1482{
1483    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1484
1485    return DEFAULT_OUT_SAMPLING_RATE;
1486}
1487
1488static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1489{
1490    LOGFUNC("%s(%p, %d)", __FUNCTION__, stream, rate);
1491
1492    return 0;
1493}
1494
1495static size_t out_get_buffer_size(const struct audio_stream *stream)
1496{
1497    struct omap4_stream_out *out = (struct omap4_stream_out *)stream;
1498
1499    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1500
1501    /* take resampling into account and return the closest majoring
1502    multiple of 16 frames, as audioflinger expects audio buffers to
1503    be a multiple of 16 frames */
1504    size_t size = (SHORT_PERIOD_SIZE * DEFAULT_OUT_SAMPLING_RATE) / out->config.rate;
1505    size = ((size + 15) / 16) * 16;
1506    return size * audio_stream_frame_size((struct audio_stream *)stream);
1507}
1508
1509static audio_channel_mask_t out_get_channels(const struct audio_stream *stream)
1510{
1511    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1512
1513    return AUDIO_CHANNEL_OUT_STEREO;
1514}
1515
1516static audio_format_t out_get_format(const struct audio_stream *stream)
1517{
1518    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1519
1520    return AUDIO_FORMAT_PCM_16_BIT;
1521}
1522
1523static int out_set_format(struct audio_stream *stream, audio_format_t format)
1524{
1525    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1526
1527    return 0;
1528}
1529
1530/* must be called with hw device and output stream mutexes locked */
1531static int do_output_standby(struct omap4_stream_out *out)
1532{
1533    struct omap4_audio_device *adev = out->dev;
1534
1535    LOGFUNC("%s(%p)", __FUNCTION__, out);
1536
1537    if (!out->standby) {
1538        pcm_close(out->pcm);
1539        out->pcm = NULL;
1540
1541        adev->active_output = 0;
1542
1543        /* if in call, don't turn off the output stage. This will
1544        be done when the call is ended */
1545        if (adev->mode != AUDIO_MODE_IN_CALL) {
1546            /* FIXME: only works if only one output can be active at a time */
1547            set_route_by_array(adev->mixer, hs_output, 0);
1548            set_route_by_array(adev->mixer, hf_output, 0);
1549        }
1550
1551        /* stop writing to echo reference */
1552        if (out->echo_reference != NULL) {
1553            out->echo_reference->write(out->echo_reference, NULL);
1554            out->echo_reference = NULL;
1555        }
1556        out->standby = 1;
1557    }
1558
1559    return 0;
1560}
1561
1562static int out_standby(struct audio_stream *stream)
1563{
1564    struct omap4_stream_out *out = (struct omap4_stream_out *)stream;
1565    int status;
1566
1567    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1568
1569    pthread_mutex_lock(&out->dev->lock);
1570    pthread_mutex_lock(&out->lock);
1571    status = do_output_standby(out);
1572    pthread_mutex_unlock(&out->lock);
1573    pthread_mutex_unlock(&out->dev->lock);
1574    return status;
1575}
1576
1577static int out_dump(const struct audio_stream *stream, int fd)
1578{
1579    LOGFUNC("%s(%p, %d)", __FUNCTION__, stream, fd);
1580
1581    return 0;
1582}
1583
1584static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1585{
1586    struct omap4_stream_out *out = (struct omap4_stream_out *)stream;
1587    struct omap4_audio_device *adev = out->dev;
1588    struct omap4_stream_in *in;
1589    struct str_parms *parms;
1590    char *str;
1591    char value[32];
1592    int ret, val = 0;
1593    bool force_input_standby = false;
1594
1595    LOGFUNC("%s(%p, %s)", __FUNCTION__, stream, kvpairs);
1596
1597    parms = str_parms_create_str(kvpairs);
1598
1599    ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
1600    if (ret >= 0) {
1601        val = atoi(value);
1602        pthread_mutex_lock(&adev->lock);
1603        pthread_mutex_lock(&out->lock);
1604        if (((adev->devices & AUDIO_DEVICE_OUT_ALL) != val) && (val != 0)) {
1605            if (out == adev->active_output) {
1606                do_output_standby(out);
1607                /* a change in output device may change the microphone selection */
1608                if (adev->active_input &&
1609                        adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
1610                    force_input_standby = true;
1611                }
1612                /* force standby if moving to/from HDMI */
1613                if ((val & AUDIO_DEVICE_OUT_AUX_DIGITAL) ^
1614                    (adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL))
1615                        do_output_standby(out);
1616            }
1617            adev->devices &= ~AUDIO_DEVICE_OUT_ALL;
1618            adev->devices |= val;
1619            select_output_device(adev);
1620        }
1621
1622        pthread_mutex_unlock(&out->lock);
1623        if (force_input_standby) {
1624            in = adev->active_input;
1625            pthread_mutex_lock(&in->lock);
1626            do_input_standby(in);
1627            pthread_mutex_unlock(&in->lock);
1628        }
1629        pthread_mutex_unlock(&adev->lock);
1630    }
1631
1632    str_parms_destroy(parms);
1633    return ret;
1634}
1635
1636static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
1637{
1638    LOGFUNC("%s(%p, %s)", __FUNCTION__, stream, keys);
1639
1640    return strdup("");
1641}
1642
1643static uint32_t out_get_latency(const struct audio_stream_out *stream)
1644{
1645    struct omap4_stream_out *out = (struct omap4_stream_out *)stream;
1646
1647    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1648    return (SHORT_PERIOD_SIZE * PLAYBACK_PERIOD_COUNT * 1000) / out->config.rate;
1649}
1650
1651static int out_set_volume(struct audio_stream_out *stream, float left,
1652                          float right)
1653{
1654    LOGFUNC("%s(%p, %f, %f)", __FUNCTION__, stream, left, right);
1655
1656    return -ENOSYS;
1657}
1658
1659static ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
1660                         size_t bytes)
1661{
1662    int ret;
1663    struct omap4_stream_out *out = (struct omap4_stream_out *)stream;
1664    struct omap4_audio_device *adev = out->dev;
1665    size_t frame_size = audio_stream_frame_size(&out->stream.common);
1666    size_t in_frames = bytes / frame_size;
1667    size_t out_frames = RESAMPLER_BUFFER_SIZE / frame_size;
1668    bool force_input_standby = false;
1669    struct omap4_stream_in *in;
1670    int kernel_frames;
1671    void *buf;
1672
1673    LOGFUNC("%s(%p, %p, %d)", __FUNCTION__, stream, buffer, bytes);
1674
1675    /* acquiring hw device mutex systematically is useful if a low priority thread is waiting
1676     * on the output stream mutex - e.g. executing select_mode() while holding the hw device
1677     * mutex
1678     */
1679    pthread_mutex_lock(&adev->lock);
1680    pthread_mutex_lock(&out->lock);
1681    if (out->standby) {
1682        ret = start_output_stream(out);
1683        if (ret != 0) {
1684            pthread_mutex_unlock(&adev->lock);
1685            goto exit;
1686        }
1687        out->standby = 0;
1688        /* a change in output device may change the microphone selection */
1689        if (adev->active_input &&
1690                adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION)
1691            force_input_standby = true;
1692    }
1693    pthread_mutex_unlock(&adev->lock);
1694
1695    /* only use resampler if required */
1696    if (out->config.rate != DEFAULT_OUT_SAMPLING_RATE) {
1697        if (!out->resampler) {
1698            ret = create_resampler(DEFAULT_OUT_SAMPLING_RATE,
1699                    MM_FULL_POWER_SAMPLING_RATE,
1700                    2,
1701                    RESAMPLER_QUALITY_DEFAULT,
1702                    NULL,
1703                    &out->resampler);
1704            if (ret != 0)
1705                goto exit;
1706            out->buffer = malloc(RESAMPLER_BUFFER_SIZE); /* todo: allow for reallocing */
1707        }
1708        out->resampler->resample_from_input(out->resampler,
1709                (int16_t *)buffer,
1710                &in_frames,
1711                (int16_t *)out->buffer,
1712                &out_frames);
1713        buf = out->buffer;
1714    } else {
1715        out_frames = in_frames;
1716        buf = (void *)buffer;
1717    }
1718    if (out->echo_reference != NULL) {
1719        struct echo_reference_buffer b;
1720        b.raw = (void *)buffer;
1721        b.frame_count = in_frames;
1722
1723        get_playback_delay(out, out_frames, &b);
1724        out->echo_reference->write(out->echo_reference, &b);
1725    }
1726
1727    /* do not allow more than out->write_threshold frames in kernel pcm driver buffer */
1728    do {
1729        struct timespec time_stamp;
1730
1731        if (pcm_get_htimestamp(out->pcm, (unsigned int *)&kernel_frames, &time_stamp) < 0)
1732            break;
1733        kernel_frames = pcm_get_buffer_size(out->pcm) - kernel_frames;
1734        if (kernel_frames > out->write_threshold) {
1735            unsigned long time = (unsigned long)
1736                    (((int64_t)(kernel_frames - out->write_threshold) * 1000000) /
1737                            MM_FULL_POWER_SAMPLING_RATE);
1738            if (time < MIN_WRITE_SLEEP_US)
1739                time = MIN_WRITE_SLEEP_US;
1740            usleep(time);
1741        }
1742    } while (kernel_frames > out->write_threshold);
1743
1744    ret = pcm_mmap_write(out->pcm, (void *)buf, out_frames * frame_size);
1745
1746exit:
1747    pthread_mutex_unlock(&out->lock);
1748
1749    if (ret != 0) {
1750        usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
1751               out_get_sample_rate(&stream->common));
1752    }
1753
1754    if (force_input_standby) {
1755        pthread_mutex_lock(&adev->lock);
1756        if (adev->active_input) {
1757            in = adev->active_input;
1758            pthread_mutex_lock(&in->lock);
1759            do_input_standby(in);
1760            pthread_mutex_unlock(&in->lock);
1761        }
1762        pthread_mutex_unlock(&adev->lock);
1763    }
1764
1765    return bytes;
1766}
1767
1768static int out_get_render_position(const struct audio_stream_out *stream,
1769                                   uint32_t *dsp_frames)
1770{
1771    LOGFUNC("%s(%p, %p)", __FUNCTION__, stream, dsp_frames);
1772
1773    return -EINVAL;
1774}
1775
1776static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1777{
1778    LOGFUNC("%s(%p, %p)", __FUNCTION__, stream, effect);
1779
1780    return 0;
1781}
1782
1783static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1784{
1785    LOGFUNC("%s(%p, %p)", __FUNCTION__, stream, effect);
1786
1787    return 0;
1788}
1789
1790/** audio_stream_in implementation **/
1791
1792/* must be called with hw device and input stream mutexes locked */
1793static int start_input_stream(struct omap4_stream_in *in)
1794{
1795    int ret = 0;
1796    unsigned int card = CARD_BLAZE_DEFAULT;
1797    unsigned int device = PORT_MM2_UL;
1798    struct omap4_audio_device *adev = in->dev;
1799
1800    LOGFUNC("%s(%p)", __FUNCTION__, in);
1801
1802    adev->active_input = in;
1803
1804    if (adev->mode != AUDIO_MODE_IN_CALL) {
1805        adev->devices &= ~AUDIO_DEVICE_IN_ALL;
1806        adev->devices |= in->device;
1807        select_input_device(adev);
1808    }
1809
1810    if (adev->input_requires_stereo && (in->config.channels == 1))
1811        setup_stereo_to_mono_input_remix(in);
1812
1813    if (in->need_echo_reference && in->echo_reference == NULL)
1814        in->echo_reference = get_echo_reference(adev,
1815                                        AUDIO_FORMAT_PCM_16_BIT,
1816                                        in->config.channels,
1817                                        in->requested_rate);
1818
1819    /* this assumes routing is done previously */
1820    if (in->remix_at_driver)
1821        in->config.channels = in->remix_at_driver->in_chans;
1822
1823    in->pcm = pcm_open(card, device, PCM_IN, &in->config);
1824    if (in->remix_at_driver)
1825        in->config.channels = in->remix_at_driver->out_chans;
1826    if (!pcm_is_ready(in->pcm)) {
1827        ALOGE("cannot open pcm_in driver: %s", pcm_get_error(in->pcm));
1828        pcm_close(in->pcm);
1829        adev->active_input = NULL;
1830        return -ENOMEM;
1831    }
1832
1833    /* if no supported sample rate is available, use the resampler */
1834    if (in->resampler) {
1835        in->resampler->reset(in->resampler);
1836        in->frames_in = 0;
1837    }
1838    return 0;
1839}
1840
1841static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1842{
1843    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
1844
1845    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1846
1847    return in->requested_rate;
1848}
1849
1850static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1851{
1852    LOGFUNC("%s(%p, %d)", __FUNCTION__, stream, rate);
1853
1854    return 0;
1855}
1856
1857static size_t in_get_buffer_size(const struct audio_stream *stream)
1858{
1859    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
1860
1861    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1862
1863    return get_input_buffer_size(in->requested_rate,
1864                                 AUDIO_FORMAT_PCM_16_BIT,
1865                                 in->config.channels);
1866}
1867
1868static audio_channel_mask_t in_get_channels(const struct audio_stream *stream)
1869{
1870    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
1871
1872    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1873
1874    if (in->config.channels == 1) {
1875        return AUDIO_CHANNEL_IN_MONO;
1876    } else {
1877        return AUDIO_CHANNEL_IN_STEREO;
1878    }
1879}
1880
1881static audio_format_t in_get_format(const struct audio_stream *stream)
1882{
1883    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1884
1885    return AUDIO_FORMAT_PCM_16_BIT;
1886}
1887
1888static int in_set_format(struct audio_stream *stream, audio_format_t format)
1889{
1890    LOGFUNC("%s(%p, %d)", __FUNCTION__, stream, format);
1891
1892    return 0;
1893}
1894
1895/* must be called with hw device and input stream mutexes locked */
1896static int do_input_standby(struct omap4_stream_in *in)
1897{
1898    struct omap4_audio_device *adev = in->dev;
1899
1900    LOGFUNC("%s(%p)", __FUNCTION__, in);
1901
1902    if (!in->standby) {
1903        pcm_close(in->pcm);
1904        in->pcm = NULL;
1905
1906        adev->active_input = 0;
1907        if (adev->mode != AUDIO_MODE_IN_CALL) {
1908            adev->devices &= ~AUDIO_DEVICE_IN_ALL;
1909            select_input_device(adev);
1910        }
1911
1912        if (in->echo_reference != NULL) {
1913            /* stop reading from echo reference */
1914            in->echo_reference->read(in->echo_reference, NULL);
1915            put_echo_reference(adev, in->echo_reference);
1916            in->echo_reference = NULL;
1917        }
1918        in->standby = 1;
1919    }
1920    return 0;
1921}
1922
1923static int in_standby(struct audio_stream *stream)
1924{
1925    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
1926    int status;
1927
1928    LOGFUNC("%s(%p)", __FUNCTION__, stream);
1929
1930    pthread_mutex_lock(&in->dev->lock);
1931    pthread_mutex_lock(&in->lock);
1932    status = do_input_standby(in);
1933    pthread_mutex_unlock(&in->lock);
1934    pthread_mutex_unlock(&in->dev->lock);
1935    return status;
1936}
1937
1938static int in_dump(const struct audio_stream *stream, int fd)
1939{
1940    LOGFUNC("%s(%p, %d)", __FUNCTION__, stream, fd);
1941
1942    return 0;
1943}
1944static int in_fm_routing(struct audio_stream *stream)
1945{
1946    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
1947    int ret;
1948
1949   LOGFUNC("%s(%p)", __FUNCTION__, stream);
1950
1951    if (in->standby) {
1952        ret = start_input_stream(in);
1953        if (ret == 0)
1954            in->standby = 0;
1955    }
1956    return 0;
1957}
1958
1959static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1960{
1961    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
1962    struct omap4_audio_device *adev = in->dev;
1963    struct str_parms *parms;
1964    char *str;
1965    char value[32];
1966    int ret, val = 0;
1967    bool do_standby = false;
1968
1969    LOGFUNC("%s(%p, %s)", __FUNCTION__, stream, kvpairs);
1970
1971    parms = str_parms_create_str(kvpairs);
1972
1973    ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
1974
1975    pthread_mutex_lock(&adev->lock);
1976    pthread_mutex_lock(&in->lock);
1977    if (ret >= 0) {
1978        val = atoi(value);
1979        /* no audio source uses val == 0 */
1980        if ((in->source != val) && (val != 0)) {
1981            in->source = val;
1982            do_standby = true;
1983        }
1984    }
1985
1986    ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
1987    if (ret >= 0) {
1988        val = atoi(value);
1989        if ((in->device != val) && (val != 0)) {
1990            in->device = val;
1991            do_standby = true;
1992        }
1993    }
1994
1995    if (do_standby)
1996        do_input_standby(in);
1997
1998    pthread_mutex_unlock(&in->lock);
1999    pthread_mutex_unlock(&adev->lock);
2000
2001    str_parms_destroy(parms);
2002    return ret;
2003}
2004
2005static char * in_get_parameters(const struct audio_stream *stream,
2006                                const char *keys)
2007{
2008    LOGFUNC("%s(%p, %s)", __FUNCTION__, stream, keys);
2009
2010    return strdup("");
2011}
2012
2013static int in_set_gain(struct audio_stream_in *stream, float gain)
2014{
2015    LOGFUNC("%s(%p, %f)", __FUNCTION__, stream, gain);
2016
2017    return 0;
2018}
2019
2020static void get_capture_delay(struct omap4_stream_in *in,
2021                       size_t frames,
2022                       struct echo_reference_buffer *buffer)
2023{
2024
2025    /* read frames available in kernel driver buffer */
2026    size_t kernel_frames;
2027    struct timespec tstamp;
2028    long buf_delay;
2029    long rsmp_delay;
2030    long kernel_delay;
2031    long delay_ns;
2032
2033    LOGFUNC("%s(%p, %ul, %p)", __FUNCTION__, in, frames, buffer);
2034
2035    if (pcm_get_htimestamp(in->pcm, &kernel_frames, &tstamp) < 0) {
2036        buffer->time_stamp.tv_sec  = 0;
2037        buffer->time_stamp.tv_nsec = 0;
2038        buffer->delay_ns           = 0;
2039        ALOGW("read get_capture_delay(): pcm_htimestamp error");
2040        return;
2041    }
2042
2043    /* read frames available in audio HAL input buffer
2044     * add number of frames being read as we want the capture time of first sample
2045     * in current buffer */
2046    buf_delay = (long)(((int64_t)(in->frames_in + in->proc_frames_in) * 1000000000)
2047                                    / in->config.rate);
2048    /* add delay introduced by resampler */
2049    rsmp_delay = 0;
2050    if (in->resampler) {
2051        rsmp_delay = in->resampler->delay_ns(in->resampler);
2052    }
2053
2054    kernel_delay = (long)(((int64_t)kernel_frames * 1000000000) / in->config.rate);
2055
2056    delay_ns = kernel_delay + buf_delay + rsmp_delay;
2057
2058    buffer->time_stamp = tstamp;
2059    buffer->delay_ns   = delay_ns;
2060    ALOGV("get_capture_delay time_stamp = [%ld].[%ld], delay_ns: [%d],"
2061         " kernel_delay:[%ld], buf_delay:[%ld], rsmp_delay:[%ld], kernel_frames:[%d], "
2062         "in->frames_in:[%d], in->proc_frames_in:[%d], frames:[%d]",
2063         buffer->time_stamp.tv_sec , buffer->time_stamp.tv_nsec, buffer->delay_ns,
2064         kernel_delay, buf_delay, rsmp_delay, kernel_frames,
2065         in->frames_in, in->proc_frames_in, frames);
2066
2067}
2068
2069static int32_t update_echo_reference(struct omap4_stream_in *in, size_t frames)
2070{
2071    struct echo_reference_buffer b;
2072    b.delay_ns = 0;
2073
2074    LOGFUNC("%s(%p, %ul)", __FUNCTION__, in, frames);
2075
2076    ALOGV("update_echo_reference, frames = [%d], in->ref_frames_in = [%d],  "
2077          "b.frame_count = [%d]",
2078         frames, in->ref_frames_in, frames - in->ref_frames_in);
2079    if (in->ref_frames_in < frames) {
2080        if (in->ref_buf_size < frames) {
2081            in->ref_buf_size = frames;
2082            in->ref_buf = (int16_t *)realloc(in->ref_buf,
2083                                             in->ref_buf_size *
2084                                                 in->config.channels * sizeof(int16_t));
2085        }
2086
2087        b.frame_count = frames - in->ref_frames_in;
2088        b.raw = (void *)(in->ref_buf + in->ref_frames_in * in->config.channels);
2089
2090        get_capture_delay(in, frames, &b);
2091
2092        if (in->echo_reference->read(in->echo_reference, &b) == 0)
2093        {
2094            in->ref_frames_in += b.frame_count;
2095            ALOGV("update_echo_reference: in->ref_frames_in:[%d], "
2096                    "in->ref_buf_size:[%d], frames:[%d], b.frame_count:[%d]",
2097                 in->ref_frames_in, in->ref_buf_size, frames, b.frame_count);
2098        }
2099    } else
2100        ALOGW("update_echo_reference: NOT enough frames to read ref buffer");
2101    return b.delay_ns;
2102}
2103
2104static int set_preprocessor_param(effect_handle_t handle,
2105                           effect_param_t *param)
2106{
2107    uint32_t size = sizeof(int);
2108    uint32_t psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
2109                        param->vsize;
2110
2111    LOGFUNC("%s(%p, %p)", __FUNCTION__, handle, param);
2112
2113    int status = (*handle)->command(handle,
2114                                   EFFECT_CMD_SET_PARAM,
2115                                   sizeof (effect_param_t) + psize,
2116                                   param,
2117                                   &size,
2118                                   &param->status);
2119    if (status == 0)
2120        status = param->status;
2121
2122    return status;
2123}
2124
2125static int set_preprocessor_echo_delay(effect_handle_t handle,
2126                                     int32_t delay_us)
2127{
2128    uint32_t buf[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
2129    effect_param_t *param = (effect_param_t *)buf;
2130
2131    LOGFUNC("%s(%p, %d)", __FUNCTION__, handle, delay_us);
2132
2133    param->psize = sizeof(uint32_t);
2134    param->vsize = sizeof(uint32_t);
2135    *(uint32_t *)param->data = AEC_PARAM_ECHO_DELAY;
2136    *((int32_t *)param->data + 1) = delay_us;
2137
2138    return set_preprocessor_param(handle, param);
2139}
2140
2141static void push_echo_reference(struct omap4_stream_in *in, size_t frames)
2142{
2143    /* read frames from echo reference buffer and update echo delay
2144     * in->ref_frames_in is updated with frames available in in->ref_buf */
2145    int32_t delay_us = update_echo_reference(in, frames)/1000;
2146    int i;
2147    audio_buffer_t buf;
2148
2149    LOGFUNC("%s(%p, %ul)", __FUNCTION__, in, frames);
2150
2151    if (in->ref_frames_in < frames)
2152        frames = in->ref_frames_in;
2153
2154    buf.frameCount = frames;
2155    buf.raw = in->ref_buf;
2156
2157    for (i = 0; i < in->num_preprocessors; i++) {
2158        if ((*in->preprocessors[i])->process_reverse == NULL)
2159            continue;
2160
2161        (*in->preprocessors[i])->process_reverse(in->preprocessors[i],
2162                                               &buf,
2163                                               NULL);
2164        set_preprocessor_echo_delay(in->preprocessors[i], delay_us);
2165    }
2166
2167    in->ref_frames_in -= buf.frameCount;
2168    if (in->ref_frames_in) {
2169        memcpy(in->ref_buf,
2170               in->ref_buf + buf.frameCount * in->config.channels,
2171               in->ref_frames_in * in->config.channels * sizeof(int16_t));
2172    }
2173}
2174
2175static int get_next_buffer(struct resampler_buffer_provider *buffer_provider,
2176                                   struct resampler_buffer* buffer)
2177{
2178    struct omap4_stream_in *in;
2179    struct buffer_remix *remix;
2180    size_t hw_frame_size;
2181
2182    LOGFUNC("%s(%p, %p)", __FUNCTION__, buffer_provider, buffer);
2183
2184    if (buffer_provider == NULL || buffer == NULL)
2185        return -EINVAL;
2186
2187    in = (struct omap4_stream_in *)((char *)buffer_provider -
2188                                   offsetof(struct omap4_stream_in, buf_provider));
2189    remix = in->remix_at_driver;
2190
2191    if (in->pcm == NULL) {
2192        buffer->raw = NULL;
2193        buffer->frame_count = 0;
2194        in->read_status = -ENODEV;
2195        return -ENODEV;
2196    }
2197
2198    if (remix)
2199        hw_frame_size = remix->in_chans * remix->sample_size;
2200    else
2201        hw_frame_size = audio_stream_frame_size(&in->stream.common);
2202
2203    if (in->frames_in == 0) {
2204        in->read_status = pcm_read(in->pcm,
2205                                   (void*)in->buffer,
2206                                   in->config.period_size * hw_frame_size);
2207        if (in->read_status != 0) {
2208            ALOGE("get_next_buffer() pcm_read error %d", in->read_status);
2209            buffer->raw = NULL;
2210            buffer->frame_count = 0;
2211            return in->read_status;
2212        }
2213        in->frames_in = in->config.period_size;
2214
2215        if (remix)
2216            remix->remix_func(remix, in->buffer, in->frames_in);
2217    }
2218
2219    buffer->frame_count = (buffer->frame_count > in->frames_in) ?
2220                                in->frames_in : buffer->frame_count;
2221    buffer->i16 = in->buffer + (in->config.period_size - in->frames_in) *
2222                                                in->config.channels;
2223
2224    return in->read_status;
2225
2226}
2227
2228static void release_buffer(struct resampler_buffer_provider *buffer_provider,
2229                                  struct resampler_buffer* buffer)
2230{
2231    struct omap4_stream_in *in;
2232
2233    LOGFUNC("%s(%p, %p)", __FUNCTION__, buffer_provider, buffer);
2234
2235    if (buffer_provider == NULL || buffer == NULL)
2236        return;
2237
2238    in = (struct omap4_stream_in *)((char *)buffer_provider -
2239                                   offsetof(struct omap4_stream_in, buf_provider));
2240
2241    in->frames_in -= buffer->frame_count;
2242}
2243
2244/* read_frames() reads frames from kernel driver, down samples to capture rate
2245 * if necessary and output the number of frames requested to the buffer specified */
2246static ssize_t read_frames(struct omap4_stream_in *in, void *buffer, ssize_t frames)
2247{
2248    ssize_t frames_wr = 0;
2249    size_t frame_size;
2250
2251    LOGFUNC("%s(%p, %p, %ld)", __FUNCTION__, in, buffer, frames);
2252
2253    if (in->remix_at_driver)
2254        frame_size = in->remix_at_driver->out_chans * in->remix_at_driver->sample_size;
2255    else
2256        frame_size = audio_stream_frame_size(&in->stream.common);
2257
2258    while (frames_wr < frames) {
2259        size_t frames_rd = frames - frames_wr;
2260        if (in->resampler != NULL) {
2261            in->resampler->resample_from_provider(in->resampler,
2262                    (int16_t *)((char *)buffer + frames_wr * frame_size),
2263                    &frames_rd);
2264        } else {
2265            struct resampler_buffer buf = {
2266                    { raw : NULL, },
2267                    frame_count : frames_rd,
2268            };
2269            get_next_buffer(&in->buf_provider, &buf);
2270            if (buf.raw != NULL) {
2271                memcpy((char *)buffer +
2272                        frames_wr * frame_size,
2273                        buf.raw,
2274                        buf.frame_count * frame_size);
2275                frames_rd = buf.frame_count;
2276            }
2277            release_buffer(&in->buf_provider, &buf);
2278        }
2279        /* in->read_status is updated by getNextBuffer() also called by
2280         * in->resampler->resample_from_provider() */
2281        if (in->read_status != 0)
2282            return in->read_status;
2283
2284        frames_wr += frames_rd;
2285    }
2286    return frames_wr;
2287}
2288
2289/* process_frames() reads frames from kernel driver (via read_frames()),
2290 * calls the active audio pre processings and output the number of frames requested
2291 * to the buffer specified */
2292static ssize_t process_frames(struct omap4_stream_in *in, void* buffer, ssize_t frames)
2293{
2294    ssize_t frames_wr = 0;
2295    audio_buffer_t in_buf;
2296    audio_buffer_t out_buf;
2297    int i;
2298
2299    LOGFUNC("%s(%p, %p, %ld)", __FUNCTION__, in, buffer, frames);
2300
2301    while (frames_wr < frames) {
2302        /* first reload enough frames at the end of process input buffer */
2303        if (in->proc_frames_in < (size_t)frames) {
2304            ssize_t frames_rd;
2305
2306            if (in->proc_buf_size < (size_t)frames) {
2307                in->proc_buf_size = (size_t)frames;
2308                in->proc_buf = (int16_t *)realloc(in->proc_buf,
2309                                         in->proc_buf_size *
2310                                             in->config.channels * sizeof(int16_t));
2311                ALOGV("process_frames(): in->proc_buf %p size extended to %d frames",
2312                     in->proc_buf, in->proc_buf_size);
2313            }
2314            frames_rd = read_frames(in,
2315                                    in->proc_buf +
2316                                        in->proc_frames_in * in->config.channels,
2317                                    frames - in->proc_frames_in);
2318            if (frames_rd < 0) {
2319                frames_wr = frames_rd;
2320                break;
2321            }
2322            in->proc_frames_in += frames_rd;
2323        }
2324
2325        if (in->echo_reference != NULL)
2326            push_echo_reference(in, in->proc_frames_in);
2327
2328         /* in_buf.frameCount and out_buf.frameCount indicate respectively
2329          * the maximum number of frames to be consumed and produced by process() */
2330        in_buf.frameCount = in->proc_frames_in;
2331        in_buf.s16 = in->proc_buf;
2332        out_buf.frameCount = frames - frames_wr;
2333        out_buf.s16 = (int16_t *)buffer + frames_wr * in->config.channels;
2334
2335        for (i = 0; i < in->num_preprocessors; i++)
2336            (*in->preprocessors[i])->process(in->preprocessors[i],
2337                                               &in_buf,
2338                                               &out_buf);
2339
2340        /* process() has updated the number of frames consumed and produced in
2341         * in_buf.frameCount and out_buf.frameCount respectively
2342         * move remaining frames to the beginning of in->proc_buf */
2343        in->proc_frames_in -= in_buf.frameCount;
2344        if (in->proc_frames_in) {
2345            memcpy(in->proc_buf,
2346                   in->proc_buf + in_buf.frameCount * in->config.channels,
2347                   in->proc_frames_in * in->config.channels * sizeof(int16_t));
2348        }
2349
2350        /* if not enough frames were passed to process(), read more and retry. */
2351        if (out_buf.frameCount == 0)
2352            continue;
2353
2354        frames_wr += out_buf.frameCount;
2355    }
2356    return frames_wr;
2357}
2358
2359static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
2360                       size_t bytes)
2361{
2362    int ret = 0;
2363    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
2364    struct omap4_audio_device *adev = in->dev;
2365    size_t frames_rq = bytes / audio_stream_frame_size(&stream->common);
2366
2367    LOGFUNC("%s(%p, %p, %d)", __FUNCTION__, stream, buffer, bytes);
2368
2369    /* acquiring hw device mutex systematically is useful if a low priority thread is waiting
2370     * on the input stream mutex - e.g. executing select_mode() while holding the hw device
2371     * mutex
2372     */
2373    pthread_mutex_lock(&adev->lock);
2374    pthread_mutex_lock(&in->lock);
2375    if (in->standby) {
2376        ret = start_input_stream(in);
2377        if (ret == 0)
2378            in->standby = 0;
2379    }
2380    pthread_mutex_unlock(&adev->lock);
2381
2382    if (ret < 0)
2383        goto exit;
2384
2385    if (in->num_preprocessors != 0)
2386        ret = process_frames(in, buffer, frames_rq);
2387    else if (in->resampler != NULL || in->remix_at_driver)
2388        ret = read_frames(in, buffer, frames_rq);
2389    else
2390        ret = pcm_read(in->pcm, buffer, bytes);
2391
2392    if (ret > 0)
2393        ret = 0;
2394
2395    if (ret == 0 && adev->mic_mute)
2396        memset(buffer, 0, bytes);
2397
2398exit:
2399    if (ret < 0)
2400        usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
2401               in_get_sample_rate(&stream->common));
2402
2403    pthread_mutex_unlock(&in->lock);
2404    return bytes;
2405}
2406
2407static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
2408{
2409    LOGFUNC("%s(%p)", __FUNCTION__, stream);
2410
2411    return 0;
2412}
2413
2414static int in_add_audio_effect(const struct audio_stream *stream,
2415                               effect_handle_t effect)
2416{
2417    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
2418    int status;
2419    effect_descriptor_t desc;
2420
2421    LOGFUNC("%s(%p, %p)", __FUNCTION__, stream, effect);
2422
2423    pthread_mutex_lock(&in->dev->lock);
2424    pthread_mutex_lock(&in->lock);
2425    if (in->num_preprocessors >= MAX_PREPROCESSORS) {
2426        status = -ENOSYS;
2427        goto exit;
2428    }
2429
2430    status = (*effect)->get_descriptor(effect, &desc);
2431    if (status != 0)
2432        goto exit;
2433
2434    in->preprocessors[in->num_preprocessors++] = effect;
2435
2436    if (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
2437        in->need_echo_reference = true;
2438        do_input_standby(in);
2439    }
2440
2441exit:
2442
2443    pthread_mutex_unlock(&in->lock);
2444    pthread_mutex_unlock(&in->dev->lock);
2445    return status;
2446}
2447
2448static int in_remove_audio_effect(const struct audio_stream *stream,
2449                                  effect_handle_t effect)
2450{
2451    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
2452    int i;
2453    int status = -EINVAL;
2454    bool found = false;
2455    effect_descriptor_t desc;
2456
2457    LOGFUNC("%s(%p, %p)", __FUNCTION__, stream, effect);
2458
2459    pthread_mutex_lock(&in->dev->lock);
2460    pthread_mutex_lock(&in->lock);
2461    if (in->num_preprocessors <= 0) {
2462        status = -ENOSYS;
2463        goto exit;
2464    }
2465
2466    for (i = 0; i < in->num_preprocessors; i++) {
2467        if (found) {
2468            in->preprocessors[i - 1] = in->preprocessors[i];
2469            continue;
2470        }
2471        if (in->preprocessors[i] == effect) {
2472            in->preprocessors[i] = NULL;
2473            status = 0;
2474            found = true;
2475        }
2476    }
2477
2478    if (status != 0)
2479        goto exit;
2480
2481    in->num_preprocessors--;
2482
2483    status = (*effect)->get_descriptor(effect, &desc);
2484    if (status != 0)
2485        goto exit;
2486    if (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
2487        in->need_echo_reference = false;
2488        do_input_standby(in);
2489    }
2490
2491exit:
2492
2493    pthread_mutex_unlock(&in->lock);
2494    pthread_mutex_unlock(&in->dev->lock);
2495    return status;
2496}
2497
2498
2499static int adev_open_output_stream(struct audio_hw_device *dev,
2500                                   audio_io_handle_t handle,
2501                                   audio_devices_t devices,
2502                                   audio_output_flags_t flags,
2503                                   struct audio_config *config,
2504                                   struct audio_stream_out **stream_out)
2505{
2506    struct omap4_audio_device *ladev = (struct omap4_audio_device *)dev;
2507    struct omap4_stream_out *out;
2508    int ret;
2509
2510    LOGFUNC("%s(%p, 0x%04x,%d, 0x%04x, %d, %p)", __FUNCTION__, dev, devices,
2511                        *format, *channels, *sample_rate, stream_out);
2512
2513    out = (struct omap4_stream_out *)calloc(1, sizeof(struct omap4_stream_out));
2514    if (!out)
2515        return -ENOMEM;
2516    if (devices & AUDIO_DEVICE_OUT_ALL_SCO) {
2517        ret = create_resampler(DEFAULT_OUT_SAMPLING_RATE,
2518                MM_FULL_POWER_SAMPLING_RATE,
2519                2,
2520                RESAMPLER_QUALITY_DEFAULT,
2521                NULL,
2522                &out->resampler);
2523        if (ret != 0)
2524            goto err_open;
2525        out->buffer = malloc(RESAMPLER_BUFFER_SIZE); /* todo: allow for reallocing */
2526    } else
2527       out->resampler = NULL;
2528
2529    out->stream.common.get_sample_rate = out_get_sample_rate;
2530    out->stream.common.set_sample_rate = out_set_sample_rate;
2531    out->stream.common.get_buffer_size = out_get_buffer_size;
2532    out->stream.common.get_channels = out_get_channels;
2533    out->stream.common.get_format = out_get_format;
2534    out->stream.common.set_format = out_set_format;
2535    out->stream.common.standby = out_standby;
2536    out->stream.common.dump = out_dump;
2537    out->stream.common.set_parameters = out_set_parameters;
2538    out->stream.common.get_parameters = out_get_parameters;
2539    out->stream.common.add_audio_effect = out_add_audio_effect;
2540    out->stream.common.remove_audio_effect = out_remove_audio_effect;
2541    out->stream.get_latency = out_get_latency;
2542    out->stream.set_volume = out_set_volume;
2543    out->stream.write = out_write;
2544    out->stream.get_render_position = out_get_render_position;
2545
2546    out->config = pcm_config_mm;
2547
2548    out->dev = ladev;
2549    out->standby = 1;
2550
2551    /* FIXME: when we support multiple output devices, we will want to
2552     * do the following:
2553     * adev->devices &= ~AUDIO_DEVICE_OUT_ALL;
2554     * adev->devices |= out->device;
2555     * select_output_device(adev);
2556     * This is because out_set_parameters() with a route is not
2557     * guaranteed to be called after an output stream is opened. */
2558
2559    config->format = out_get_format(&out->stream.common);
2560    config->channel_mask = out_get_channels(&out->stream.common);
2561    config->sample_rate = out_get_sample_rate(&out->stream.common);
2562
2563    *stream_out = &out->stream;
2564    return 0;
2565
2566err_open:
2567    free(out);
2568    *stream_out = NULL;
2569    return ret;
2570}
2571
2572static void adev_close_output_stream(struct audio_hw_device *dev,
2573                                     struct audio_stream_out *stream)
2574{
2575    struct omap4_stream_out *out = (struct omap4_stream_out *)stream;
2576
2577    LOGFUNC("%s(%p, %p)", __FUNCTION__, dev, stream);
2578
2579    out_standby(&stream->common);
2580    if (out->buffer)
2581        free(out->buffer);
2582    if (out->resampler)
2583        release_resampler(out->resampler);
2584    free(stream);
2585}
2586
2587static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
2588{
2589    struct omap4_audio_device *adev = (struct omap4_audio_device *)dev;
2590    struct str_parms *parms;
2591    char *str;
2592    char value[32];
2593    int ret;
2594
2595    LOGFUNC("%s(%p, %s)", __FUNCTION__, dev, kvpairs);
2596
2597    parms = str_parms_create_str(kvpairs);
2598    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_TTY_MODE, value, sizeof(value));
2599    if (ret >= 0) {
2600        int tty_mode;
2601
2602        if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_OFF) == 0)
2603            tty_mode = TTY_MODE_OFF;
2604        else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_VCO) == 0)
2605            tty_mode = TTY_MODE_VCO;
2606        else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_HCO) == 0)
2607            tty_mode = TTY_MODE_HCO;
2608        else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_FULL) == 0)
2609            tty_mode = TTY_MODE_FULL;
2610        else
2611            return -EINVAL;
2612
2613        pthread_mutex_lock(&adev->lock);
2614        if (tty_mode != adev->tty_mode) {
2615            adev->tty_mode = tty_mode;
2616            if (adev->mode == AUDIO_MODE_IN_CALL)
2617                select_output_device(adev);
2618        }
2619        pthread_mutex_unlock(&adev->lock);
2620    }
2621
2622    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
2623    if (ret >= 0) {
2624        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
2625            adev->bluetooth_nrec = true;
2626        else
2627            adev->bluetooth_nrec = false;
2628
2629    }
2630
2631    ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
2632    if (ret >= 0) {
2633        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
2634            adev->low_power = false;
2635        else
2636            adev->low_power = true;
2637    }
2638
2639    str_parms_destroy(parms);
2640    return ret;
2641}
2642
2643static char * adev_get_parameters(const struct audio_hw_device *dev,
2644                                  const char *keys)
2645{
2646    LOGFUNC("%s(%p, %s)", __FUNCTION__, dev, keys);
2647
2648    return strdup("");
2649}
2650
2651static int adev_init_check(const struct audio_hw_device *dev)
2652{
2653    LOGFUNC("%s(%p)", __FUNCTION__, dev);
2654    return 0;
2655}
2656
2657static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
2658{
2659    struct omap4_audio_device *adev = (struct omap4_audio_device *)dev;
2660
2661    LOGFUNC("%s(%p, %f)", __FUNCTION__, dev, volume);
2662    adev->voice_volume = volume;
2663
2664    return 0;
2665}
2666
2667static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
2668{
2669    LOGFUNC("%s(%p, %f)", __FUNCTION__, dev, volume);
2670
2671    return -ENOSYS;
2672}
2673
2674static int adev_set_mode(struct audio_hw_device *dev, int mode)
2675{
2676    struct omap4_audio_device *adev = (struct omap4_audio_device *)dev;
2677
2678    LOGFUNC("%s(%p, %d)", __FUNCTION__, dev, mode);
2679
2680    pthread_mutex_lock(&adev->lock);
2681    if (adev->mode != mode) {
2682        adev->mode = mode;
2683        select_mode(adev);
2684    }
2685    pthread_mutex_unlock(&adev->lock);
2686
2687    return 0;
2688}
2689
2690static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
2691{
2692    struct omap4_audio_device *adev = (struct omap4_audio_device *)dev;
2693
2694    LOGFUNC("%s(%p, %d)", __FUNCTION__, dev, state);
2695
2696    adev->mic_mute = state;
2697
2698    return 0;
2699}
2700
2701static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
2702{
2703    struct omap4_audio_device *adev = (struct omap4_audio_device *)dev;
2704
2705    LOGFUNC("%s(%p, %p)", __FUNCTION__, dev, state);
2706
2707    *state = adev->mic_mute;
2708
2709    return 0;
2710}
2711
2712static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
2713                                         const struct audio_config *config)
2714{
2715    size_t size;
2716    int channel_count = popcount(config->channel_mask);
2717    LOGFUNC("%s(%p, %d, %d, %d)", __FUNCTION__, dev, sample_rate,
2718                                format, channel_count);
2719
2720    if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0) {
2721        return 0;
2722    }
2723
2724    return get_input_buffer_size(config->sample_rate, config->format, channel_count);
2725}
2726
2727static int adev_open_input_stream(struct audio_hw_device *dev,
2728                                  audio_io_handle_t handle,
2729                                  audio_devices_t devices,
2730                                  struct audio_config *config,
2731                                  struct audio_stream_in **stream_in)
2732{
2733    struct omap4_audio_device *ladev = (struct omap4_audio_device *)dev;
2734    struct omap4_stream_in *in;
2735    int ret;
2736    int channel_count = popcount(config->channel_mask);
2737    /*audioflinger expects return variable to be NULL incase of failure */
2738    *stream_in = NULL;
2739    LOGFUNC("%s(%p, 0x%04x, %d, 0x%04x, %d, 0x%04x, %p)", __FUNCTION__, dev,
2740        devices, *format, *channel_mask, *sample_rate, acoustics, stream_in);
2741
2742    if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0)
2743        return -EINVAL;
2744
2745    in = (struct omap4_stream_in *)calloc(1, sizeof(struct omap4_stream_in));
2746    if (!in)
2747        return -ENOMEM;
2748
2749    in->stream.common.get_sample_rate = in_get_sample_rate;
2750    in->stream.common.set_sample_rate = in_set_sample_rate;
2751    in->stream.common.get_buffer_size = in_get_buffer_size;
2752    in->stream.common.get_channels = in_get_channels;
2753    in->stream.common.get_format = in_get_format;
2754    in->stream.common.set_format = in_set_format;
2755    in->stream.common.standby = in_standby;
2756    in->stream.common.dump = in_dump;
2757    in->stream.common.set_parameters = in_set_parameters;
2758    in->stream.common.get_parameters = in_get_parameters;
2759    in->stream.common.add_audio_effect = in_add_audio_effect;
2760    in->stream.common.remove_audio_effect = in_remove_audio_effect;
2761    in->stream.set_gain = in_set_gain;
2762    in->stream.read = in_read;
2763    in->stream.get_input_frames_lost = in_get_input_frames_lost;
2764    in->remix_at_driver = NULL;
2765
2766    in->requested_rate = config->sample_rate;
2767
2768    memcpy(&in->config, &pcm_config_mm_ul, sizeof(pcm_config_mm_ul));
2769    in->config.channels = channel_count;
2770
2771    in->buffer = malloc(2 * in->config.period_size * audio_stream_frame_size(&in->stream.common));
2772    if (!in->buffer) {
2773        ret = -ENOMEM;
2774        goto err;
2775    }
2776
2777    if (in->requested_rate != in->config.rate) {
2778        in->buf_provider.get_next_buffer = get_next_buffer;
2779        in->buf_provider.release_buffer = release_buffer;
2780        ret = create_resampler(in->config.rate,
2781                               in->requested_rate,
2782                               in->config.channels,
2783                               RESAMPLER_QUALITY_DEFAULT,
2784                               &in->buf_provider,
2785                               &in->resampler);
2786        if (ret != 0) {
2787            ret = -EINVAL;
2788            goto err;
2789        }
2790    }
2791
2792    in->dev = ladev;
2793    in->standby = 1;
2794    in->device = devices;
2795
2796    *stream_in = &in->stream;
2797    return 0;
2798
2799err:
2800    if (in->resampler)
2801        release_resampler(in->resampler);
2802
2803    free(in);
2804    *stream_in = NULL;
2805    return ret;
2806}
2807
2808static void adev_close_input_stream(struct audio_hw_device *dev,
2809                                   struct audio_stream_in *stream)
2810{
2811    struct omap4_stream_in *in = (struct omap4_stream_in *)stream;
2812
2813    LOGFUNC("%s(%p, %p)", __FUNCTION__, dev, stream);
2814
2815    in_standby(&stream->common);
2816
2817    if (in->resampler) {
2818        free(in->buffer);
2819        release_resampler(in->resampler);
2820    }
2821
2822    if (in->remix_at_driver)
2823        free(in->remix_at_driver);
2824
2825    free(stream);
2826    return;
2827}
2828
2829static int adev_dump(const audio_hw_device_t *device, int fd)
2830{
2831    LOGFUNC("%s(%p, %d)", __FUNCTION__, device, fd);
2832
2833    return 0;
2834}
2835
2836static int adev_close(hw_device_t *device)
2837{
2838    struct omap4_audio_device *adev = (struct omap4_audio_device *)device;
2839
2840    LOGFUNC("%s(%p)", __FUNCTION__, device);
2841
2842    mixer_close(adev->mixer);
2843    free(device);
2844    return 0;
2845}
2846
2847static uint32_t adev_get_supported_devices(const struct audio_hw_device *dev)
2848{
2849    LOGFUNC("%s(%p)", __FUNCTION__, dev);
2850
2851    return (/* OUT */
2852            AUDIO_DEVICE_OUT_EARPIECE |
2853            AUDIO_DEVICE_OUT_SPEAKER |
2854            AUDIO_DEVICE_OUT_WIRED_HEADSET |
2855            AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
2856            AUDIO_DEVICE_OUT_AUX_DIGITAL |
2857            AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
2858            AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
2859            AUDIO_DEVICE_OUT_ALL_SCO |
2860            AUDIO_DEVICE_OUT_DEFAULT |
2861            /* IN */
2862            AUDIO_DEVICE_IN_COMMUNICATION |
2863            AUDIO_DEVICE_IN_AMBIENT |
2864            AUDIO_DEVICE_IN_BUILTIN_MIC |
2865            AUDIO_DEVICE_IN_WIRED_HEADSET |
2866            AUDIO_DEVICE_IN_AUX_DIGITAL |
2867            AUDIO_DEVICE_IN_BACK_MIC |
2868            AUDIO_DEVICE_IN_ALL_SCO |
2869            AUDIO_DEVICE_IN_DEFAULT);
2870}
2871
2872static int adev_open(const hw_module_t* module, const char* name,
2873                     hw_device_t** device)
2874{
2875    struct omap4_audio_device *adev;
2876    int ret;
2877    pthread_mutexattr_t mta;
2878
2879    LOGFUNC("%s(%p, %s, %p)", __FUNCTION__, module, name, device);
2880
2881    if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
2882        return -EINVAL;
2883
2884    adev = calloc(1, sizeof(struct omap4_audio_device));
2885    if (!adev)
2886        return -ENOMEM;
2887
2888    adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
2889    adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_1_0;
2890    adev->hw_device.common.module = (struct hw_module_t *) module;
2891    adev->hw_device.common.close = adev_close;
2892
2893    adev->hw_device.get_supported_devices = adev_get_supported_devices;
2894    adev->hw_device.init_check = adev_init_check;
2895    adev->hw_device.set_voice_volume = adev_set_voice_volume;
2896    adev->hw_device.set_master_volume = adev_set_master_volume;
2897    adev->hw_device.set_mode = adev_set_mode;
2898    adev->hw_device.set_mic_mute = adev_set_mic_mute;
2899    adev->hw_device.get_mic_mute = adev_get_mic_mute;
2900    adev->hw_device.set_parameters = adev_set_parameters;
2901    adev->hw_device.get_parameters = adev_get_parameters;
2902    adev->hw_device.get_input_buffer_size = adev_get_input_buffer_size;
2903    adev->hw_device.open_output_stream = adev_open_output_stream;
2904    adev->hw_device.close_output_stream = adev_close_output_stream;
2905    adev->hw_device.open_input_stream = adev_open_input_stream;
2906    adev->hw_device.close_input_stream = adev_close_input_stream;
2907    adev->hw_device.dump = adev_dump;
2908
2909    adev->mixer = mixer_open(0);
2910    if (!adev->mixer) {
2911        free(adev);
2912        ALOGE("Unable to open the mixer, aborting.");
2913        return -EINVAL;
2914    }
2915
2916    adev->mixer_ctls.dl1_eq = mixer_get_ctl_by_name(adev->mixer,
2917                                           MIXER_DL1_EQUALIZER);
2918    adev->mixer_ctls.mm_dl1 = mixer_get_ctl_by_name(adev->mixer,
2919                                           MIXER_DL1_MIXER_MULTIMEDIA);
2920    adev->mixer_ctls.vx_dl1 = mixer_get_ctl_by_name(adev->mixer,
2921                                           MIXER_DL1_MIXER_VOICE);
2922    adev->mixer_ctls.mm_dl2 = mixer_get_ctl_by_name(adev->mixer,
2923                                           MIXER_DL2_MIXER_MULTIMEDIA);
2924    adev->mixer_ctls.vx_dl2 = mixer_get_ctl_by_name(adev->mixer,
2925                                           MIXER_DL2_MIXER_VOICE);
2926    adev->mixer_ctls.dl2_mono = mixer_get_ctl_by_name(adev->mixer,
2927                                           MIXER_DL2_MONO_MIXER);
2928    adev->mixer_ctls.dl1_mono = mixer_get_ctl_by_name(adev->mixer,
2929                                           MIXER_DL1_MONO_MIXER);
2930    adev->mixer_ctls.dl1_headset = mixer_get_ctl_by_name(adev->mixer,
2931                                           MIXER_DL1_PDM_SWITCH);
2932    adev->mixer_ctls.dl1_bt = mixer_get_ctl_by_name(adev->mixer,
2933                                           MIXER_DL1_BT_VX_SWITCH);
2934    adev->mixer_ctls.earpiece_enable = mixer_get_ctl_by_name(adev->mixer,
2935                                           MIXER_EARPHONE_ENABLE_SWITCH);
2936    adev->mixer_ctls.left_capture = mixer_get_ctl_by_name(adev->mixer,
2937                                           MIXER_ANALOG_LEFT_CAPTURE_ROUTE);
2938    adev->mixer_ctls.right_capture = mixer_get_ctl_by_name(adev->mixer,
2939                                           MIXER_ANALOG_RIGHT_CAPTURE_ROUTE);
2940    adev->mixer_ctls.amic_ul_volume = mixer_get_ctl_by_name(adev->mixer,
2941                                           MIXER_AMIC_UL_VOLUME);
2942    adev->mixer_ctls.dmic1_ul_volume = mixer_get_ctl_by_name(adev->mixer,
2943                                           MIXER_DMIC1_UL_VOLUME);
2944    adev->mixer_ctls.voice_ul_volume = mixer_get_ctl_by_name(adev->mixer,
2945                                           MIXER_AUDUL_VOICE_UL_VOLUME);
2946    adev->mixer_ctls.sidetone_capture = mixer_get_ctl_by_name(adev->mixer,
2947                                           MIXER_SIDETONE_MIXER_CAPTURE);
2948    adev->mixer_ctls.headset_volume = mixer_get_ctl_by_name(adev->mixer,
2949                                           MIXER_HEADSET_PLAYBACK_VOLUME);
2950    adev->mixer_ctls.speaker_volume = mixer_get_ctl_by_name(adev->mixer,
2951                                           MIXER_HANDSFREE_PLAYBACK_VOLUME);
2952
2953    if (!adev->mixer_ctls.mm_dl1 || !adev->mixer_ctls.vx_dl1 ||
2954        !adev->mixer_ctls.mm_dl2 || !adev->mixer_ctls.vx_dl2 ||
2955        !adev->mixer_ctls.dl2_mono || !adev->mixer_ctls.dl1_mono ||
2956        !adev->mixer_ctls.dl1_headset || !adev->mixer_ctls.dl1_bt ||
2957        !adev->mixer_ctls.earpiece_enable || !adev->mixer_ctls.left_capture ||
2958        !adev->mixer_ctls.right_capture || !adev->mixer_ctls.amic_ul_volume ||
2959        !adev->mixer_ctls.sidetone_capture || !adev->mixer_ctls.headset_volume ||
2960        !adev->mixer_ctls.speaker_volume || !adev->mixer_ctls.dmic1_ul_volume ||
2961        !adev->mixer_ctls.dl1_eq || !adev->mixer_ctls.voice_ul_volume) {
2962        mixer_close(adev->mixer);
2963        free(adev);
2964        ALOGE("Unable to locate all mixer controls, aborting.");
2965        return -EINVAL;
2966    }
2967
2968    pthread_mutexattr_init(&mta);
2969    pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_NORMAL);
2970    pthread_mutex_init(&adev->lock, &mta);
2971    pthread_mutexattr_destroy(&mta);
2972
2973    /* Set the default route before the PCM stream is opened */
2974    pthread_mutex_lock(&adev->lock);
2975    set_route_by_array(adev->mixer, defaults, 1);
2976    adev->mode = AUDIO_MODE_NORMAL;
2977    adev->devices = AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_IN_BUILTIN_MIC;
2978    select_output_device(adev);
2979
2980    adev->pcm_modem_dl = NULL;
2981    adev->pcm_modem_ul = NULL;
2982    adev->voice_volume = 1.0f;
2983    adev->tty_mode = TTY_MODE_OFF;
2984    if(get_boardtype(adev)) {
2985        pthread_mutex_unlock(&adev->lock);
2986        mixer_close(adev->mixer);
2987        free(adev);
2988        ALOGE("Unsupported boardtype, aborting.");
2989        return -EINVAL;
2990    }
2991
2992    adev->input_requires_stereo = 0;
2993    adev->bluetooth_nrec = true;
2994    pthread_mutex_unlock(&adev->lock);
2995    *device = &adev->hw_device.common;
2996
2997    return 0;
2998}
2999
3000static struct hw_module_methods_t hal_module_methods = {
3001    .open = adev_open,
3002};
3003
3004struct audio_module HAL_MODULE_INFO_SYM = {
3005    .common = {
3006        .tag = HARDWARE_MODULE_TAG,
3007        .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
3008        .hal_api_version = HARDWARE_HAL_API_VERSION,
3009        .id = AUDIO_HARDWARE_MODULE_ID,
3010        .name = "OMAP4 audio HW HAL",
3011        .author = "Texas Instruments",
3012        .methods = &hal_module_methods,
3013    },
3014};
3015