• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "audio_hw_primary"
18 /*#define LOG_NDEBUG 0*/
19 
20 #include <errno.h>
21 #include <pthread.h>
22 #include <stdint.h>
23 #include <sys/time.h>
24 #include <stdlib.h>
25 
26 #include <cutils/log.h>
27 #include <cutils/str_parms.h>
28 #include <cutils/properties.h>
29 
30 #include <hardware/hardware.h>
31 #include <system/audio.h>
32 #include <hardware/audio.h>
33 
34 #include <tinyalsa/asoundlib.h>
35 #include <audio_utils/resampler.h>
36 #include <audio_utils/echo_reference.h>
37 #include <hardware/audio_effect.h>
38 #include <audio_effects/effect_aec.h>
39 
40 #include "ril_interface.h"
41 
42 
43 /* Mixer control names */
44 #define MIXER_DL2_LEFT_EQUALIZER            "DL2 Left Equalizer"
45 #define MIXER_DL2_RIGHT_EQUALIZER           "DL2 Right Equalizer"
46 #define MIXER_DL1_MEDIA_PLAYBACK_VOLUME     "DL1 Media Playback Volume"
47 #define MIXER_DL1_VOICE_PLAYBACK_VOLUME     "DL1 Voice Playback Volume"
48 #define MIXER_DL1_TONES_PLAYBACK_VOLUME     "DL1 Tones Playback Volume"
49 #define MIXER_DL2_MEDIA_PLAYBACK_VOLUME     "DL2 Media Playback Volume"
50 #define MIXER_DL2_VOICE_PLAYBACK_VOLUME     "DL2 Voice Playback Volume"
51 #define MIXER_DL2_TONES_PLAYBACK_VOLUME     "DL2 Tones Playback Volume"
52 #define MIXER_SDT_DL_VOLUME                 "SDT DL Volume"
53 #define MIXER_SDT_UL_VOLUME                 "SDT UL Volume"
54 
55 #define MIXER_HEADSET_PLAYBACK_VOLUME       "Headset Playback Volume"
56 #define MIXER_HANDSFREE_PLAYBACK_VOLUME     "Handsfree Playback Volume"
57 #define MIXER_EARPHONE_PLAYBACK_VOLUME      "Earphone Playback Volume"
58 #define MIXER_BT_UL_VOLUME                  "BT UL Volume"
59 
60 #define MIXER_DL1_EQUALIZER                 "DL1 Equalizer"
61 #define MIXER_DL1_MIXER_MULTIMEDIA          "DL1 Mixer Multimedia"
62 #define MIXER_DL1_MIXER_VOICE               "DL1 Mixer Voice"
63 #define MIXER_DL1_MIXER_TONES               "DL1 Mixer Tones"
64 #define MIXER_DL2_MIXER_MULTIMEDIA          "DL2 Mixer Multimedia"
65 #define MIXER_DL2_MIXER_VOICE               "DL2 Mixer Voice"
66 #define MIXER_DL2_MIXER_TONES               "DL2 Mixer Tones"
67 #define MIXER_SIDETONE_MIXER_PLAYBACK       "Sidetone Mixer Playback"
68 #define MIXER_SIDETONE_MIXER_CAPTURE        "Sidetone Mixer Capture"
69 #define MIXER_DL2_MONO_MIXER                "DL2 Mono Mixer"
70 #define MIXER_DL1_PDM_SWITCH                "DL1 PDM Switch"
71 #define MIXER_DL1_BT_VX_SWITCH              "DL1 BT_VX Switch"
72 #define MIXER_VOICE_CAPTURE_MIXER_CAPTURE   "Voice Capture Mixer Capture"
73 
74 #define MIXER_HS_LEFT_PLAYBACK              "HS Left Playback"
75 #define MIXER_HS_RIGHT_PLAYBACK             "HS Right Playback"
76 #define MIXER_HF_LEFT_PLAYBACK              "HF Left Playback"
77 #define MIXER_HF_RIGHT_PLAYBACK             "HF Right Playback"
78 #define MIXER_EARPHONE_ENABLE_SWITCH        "Earphone Enable Switch"
79 
80 #define MIXER_ANALOG_LEFT_CAPTURE_ROUTE     "Analog Left Capture Route"
81 #define MIXER_ANALOG_RIGHT_CAPTURE_ROUTE    "Analog Right Capture Route"
82 #define MIXER_CAPTURE_PREAMPLIFIER_VOLUME   "Capture Preamplifier Volume"
83 #define MIXER_CAPTURE_VOLUME                "Capture Volume"
84 #define MIXER_AMIC_UL_VOLUME                "AMIC UL Volume"
85 #define MIXER_AUDUL_VOICE_UL_VOLUME         "AUDUL Voice UL Volume"
86 #define MIXER_MUX_VX0                       "MUX_VX0"
87 #define MIXER_MUX_VX1                       "MUX_VX1"
88 #define MIXER_MUX_UL10                      "MUX_UL10"
89 #define MIXER_MUX_UL11                      "MUX_UL11"
90 
91 /* Mixer control gain and route values */
92 #define MIXER_ABE_GAIN_0DB                  120
93 #define MIXER_PLAYBACK_HS_DAC               "HS DAC"
94 #define MIXER_PLAYBACK_HF_DAC               "HF DAC"
95 #define MIXER_MAIN_MIC                      "Main Mic"
96 #define MIXER_SUB_MIC                       "Sub Mic"
97 #define MIXER_HS_MIC                        "Headset Mic"
98 #define MIXER_AMIC0                         "AMic0"
99 #define MIXER_AMIC1                         "AMic1"
100 #define MIXER_BT_LEFT                       "BT Left"
101 #define MIXER_BT_RIGHT                      "BT Right"
102 #define MIXER_450HZ_HIGH_PASS               "450Hz High-pass"
103 #define MIXER_FLAT_RESPONSE                 "Flat response"
104 #define MIXER_4KHZ_LPF_0DB                  "4Khz LPF   0dB"
105 
106 /* HDMI mixer controls */
107 #define MIXER_MAXIMUM_LPCM_CHANNELS         "Maximum LPCM channels"
108 
109 
110 /* ALSA cards for OMAP4 */
111 #define CARD_OMAP4_ABE 0
112 #define CARD_OMAP4_HDMI 1
113 #define CARD_TUNA_DEFAULT CARD_OMAP4_ABE
114 
115 /* ALSA ports for OMAP4 */
116 #define PORT_MM 0
117 #define PORT_MM2_UL 1
118 #define PORT_VX 2
119 #define PORT_TONES 3
120 #define PORT_VIBRA 4
121 #define PORT_MODEM 5
122 #define PORT_MM_LP 6
123 #define PORT_SPDIF 9
124 #define PORT_HDMI 0
125 
126 /* User serviceable */
127 /* #define to use mmap no-irq mode for playback, #undef for non-mmap irq mode */
128 #undef PLAYBACK_MMAP        // was #define
129 /* short period (aka low latency) in milliseconds */
130 #define SHORT_PERIOD_MS 4   // was 22
131 /* deep buffer short period (screen on) in milliseconds */
132 #define DEEP_BUFFER_SHORT_PERIOD_MS 22
133 /* deep buffer long period (screen off) in milliseconds */
134 #define DEEP_BUFFER_LONG_PERIOD_MS 308
135 
136 /* Constraint imposed by ABE: for playback, all period sizes must be multiples of 24 frames
137  * = 500 us at 48 kHz.  It seems to be either 48 or 96 for capture, or maybe it is because the
138  * limitation is actually a min number of bytes which translates to a different amount of frames
139  * according to the number of channels.
140  */
141 #define ABE_BASE_FRAME_COUNT 24
142 
143 /* Derived from MM_FULL_POWER_SAMPLING_RATE=48000 and ABE_BASE_FRAME_COUNT=24 */
144 #define MULTIPLIER_FACTOR 2
145 
146 /* number of base blocks in a short period (low latency) */
147 #define SHORT_PERIOD_MULTIPLIER (SHORT_PERIOD_MS * MULTIPLIER_FACTOR)
148 /* number of frames per short period (low latency) */
149 #define SHORT_PERIOD_SIZE (ABE_BASE_FRAME_COUNT * SHORT_PERIOD_MULTIPLIER)
150 
151 /* number of base blocks in a short deep buffer period (screen on) */
152 #define DEEP_BUFFER_SHORT_PERIOD_MULTIPLIER (DEEP_BUFFER_SHORT_PERIOD_MS * MULTIPLIER_FACTOR)
153 /* number of frames per short deep buffer period (screen on) */
154 #define DEEP_BUFFER_SHORT_PERIOD_SIZE (ABE_BASE_FRAME_COUNT * DEEP_BUFFER_SHORT_PERIOD_MULTIPLIER)
155 /* number of periods for deep buffer playback (screen on) */
156 #define PLAYBACK_DEEP_BUFFER_SHORT_PERIOD_COUNT 4
157 
158 /* number of short deep buffer periods in a long period */
159 #define DEEP_BUFFER_LONG_PERIOD_MULTIPLIER \
160                             (DEEP_BUFFER_LONG_PERIOD_MS / DEEP_BUFFER_SHORT_PERIOD_MS)
161 /* number of frames per long deep buffer period (screen off) */
162 #define DEEP_BUFFER_LONG_PERIOD_SIZE \
163                             (DEEP_BUFFER_SHORT_PERIOD_SIZE * DEEP_BUFFER_LONG_PERIOD_MULTIPLIER)
164 /* number of periods for deep buffer playback (screen off) */
165 #define PLAYBACK_DEEP_BUFFER_LONG_PERIOD_COUNT 2
166 
167 /* number of frames per period for HDMI multichannel output */
168 #define HDMI_MULTI_PERIOD_SIZE  1024
169 /* number of periods for HDMI multichannel output */
170 #define HDMI_MULTI_PERIOD_COUNT 4
171 /* default number of channels for HDMI multichannel output */
172 #define HDMI_MULTI_DEFAULT_CHANNEL_COUNT 6
173 
174 /* Number of pseudo periods for low latency playback.
175  * These are called "pseudo" periods in that they are not known as periods by ALSA.
176  * Formerly, ALSA was configured in MMAP mode with 2 large periods, and this
177  * number was set to 4 (2 didn't work).
178  * The short periods size and count were only known by the audio HAL.
179  * Now for low latency, we are using non-MMAP mode and can set this to 2.
180  */
181 #ifdef PLAYBACK_MMAP
182 #define PLAYBACK_SHORT_PERIOD_COUNT 4
183 #else
184 #define PLAYBACK_SHORT_PERIOD_COUNT 2
185 #endif
186 
187 /* write function */
188 #ifdef PLAYBACK_MMAP
189 #define PCM_WRITE pcm_mmap_write
190 #else
191 #define PCM_WRITE pcm_write
192 #endif
193 
194 /* User serviceable */
195 #define CAPTURE_PERIOD_MS 22
196 
197 /* Number of frames per period for capture.  This cannot be reduced below 96.
198  * Possibly related to the following rule in sound/soc/omap/omap-pcm.c:
199  *  ret = snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 384);
200  *      (where 96 * 4 = 384)
201  * The only constraints I can find are periods_min = 2, period_bytes_min = 32.
202  * If you define RULES_DEBUG in sound/core/pcm_native.c, you can see which rule
203  * caused capture to fail.
204  * Decoupling playback and capture period size may have impacts on echo canceler behavior:
205  * to be verified.  Currently 96 = 4 x 24 but it could be changed without noticing
206  * if we use separate defines.
207  */
208 #define CAPTURE_PERIOD_SIZE (ABE_BASE_FRAME_COUNT * CAPTURE_PERIOD_MS * MULTIPLIER_FACTOR)
209 /* number of periods for capture */
210 #define CAPTURE_PERIOD_COUNT 2
211 /* minimum sleep time in out_write() when write threshold is not reached */
212 #define MIN_WRITE_SLEEP_US 5000
213 
214 #define DEFAULT_OUT_SAMPLING_RATE 44100 // 48000 is possible but interacts poorly with HDMI
215 
216 /* sampling rate when using MM low power port */
217 #define MM_LOW_POWER_SAMPLING_RATE 44100
218 /* sampling rate when using MM full power port */
219 #define MM_FULL_POWER_SAMPLING_RATE 48000   // affects MULTIPLIER_FACTOR
220 /* sampling rate when using VX port for narrow band */
221 #define VX_NB_SAMPLING_RATE 8000
222 /* sampling rate when using VX port for wide band */
223 #define VX_WB_SAMPLING_RATE 16000
224 
225 /* conversions from dB to ABE and codec gains */
226 #define DB_TO_ABE_GAIN(x) ((x) + MIXER_ABE_GAIN_0DB)
227 #define DB_TO_CAPTURE_PREAMPLIFIER_VOLUME(x) (((x) + 6) / 6)
228 #define DB_TO_CAPTURE_VOLUME(x) (((x) - 6) / 6)
229 #define DB_TO_HEADSET_VOLUME(x) (((x) + 30) / 2)
230 #define DB_TO_SPEAKER_VOLUME(x) (((x) + 52) / 2)
231 #define DB_TO_EARPIECE_VOLUME(x) (((x) + 24) / 2)
232 
233 /* conversions from codec and ABE gains to dB */
234 #define DB_FROM_SPEAKER_VOLUME(x) ((x) * 2 - 52)
235 
236 /* use-case specific mic volumes, all in dB */
237 #define CAPTURE_MAIN_MIC_VOLUME 16
238 #define CAPTURE_SUB_MIC_VOLUME 18
239 #define CAPTURE_HEADSET_MIC_VOLUME 12
240 
241 #define VOICE_RECOGNITION_MAIN_MIC_VOLUME 5
242 #define VOICE_RECOGNITION_SUB_MIC_VOLUME 18
243 #define VOICE_RECOGNITION_HEADSET_MIC_VOLUME 14
244 
245 #define CAMCORDER_MAIN_MIC_VOLUME 13
246 #define CAMCORDER_SUB_MIC_VOLUME 10
247 #define CAMCORDER_HEADSET_MIC_VOLUME 12
248 
249 #define VOIP_MAIN_MIC_VOLUME 13
250 #define VOIP_SUB_MIC_VOLUME 20
251 #define VOIP_HEADSET_MIC_VOLUME 12
252 
253 #define VOICE_CALL_MAIN_MIC_VOLUME 0
254 #define VOICE_CALL_SUB_MIC_VOLUME_MAGURO -4
255 #define VOICE_CALL_SUB_MIC_VOLUME_TORO -2
256 #define VOICE_CALL_HEADSET_MIC_VOLUME 8
257 
258 /* use-case specific output volumes */
259 #define NORMAL_SPEAKER_VOLUME_TORO 4
260 #define NORMAL_SPEAKER_VOLUME_MAGURO 2
261 #define NORMAL_HEADSET_VOLUME_TORO -12
262 #define NORMAL_HEADSET_VOLUME_MAGURO -12
263 #define NORMAL_HEADPHONE_VOLUME_TORO -6 /* allow louder output for headphones */
264 #define NORMAL_HEADPHONE_VOLUME_MAGURO -6
265 #define NORMAL_EARPIECE_VOLUME_TORO -2
266 #define NORMAL_EARPIECE_VOLUME_MAGURO -2
267 
268 #define VOICE_CALL_SPEAKER_VOLUME_TORO 9
269 #define VOICE_CALL_SPEAKER_VOLUME_MAGURO 6
270 #define VOICE_CALL_HEADSET_VOLUME_TORO -6
271 #define VOICE_CALL_HEADSET_VOLUME_MAGURO 0
272 #define VOICE_CALL_EARPIECE_VOLUME_TORO 2
273 #define VOICE_CALL_EARPIECE_VOLUME_MAGURO 6
274 
275 #define VOIP_SPEAKER_VOLUME_TORO 9
276 #define VOIP_SPEAKER_VOLUME_MAGURO 7
277 #define VOIP_HEADSET_VOLUME_TORO -6
278 #define VOIP_HEADSET_VOLUME_MAGURO -6
279 #define VOIP_EARPIECE_VOLUME_TORO 6
280 #define VOIP_EARPIECE_VOLUME_MAGURO 6
281 
282 #define HEADPHONE_VOLUME_TTY -2
283 #define RINGTONE_HEADSET_VOLUME_OFFSET -14
284 
285 /* product-specific defines */
286 #define PRODUCT_DEVICE_PROPERTY "ro.product.device"
287 #define PRODUCT_NAME_PROPERTY   "ro.product.name"
288 #define PRODUCT_DEVICE_TORO     "toro"
289 #define PRODUCT_NAME_YAKJU      "yakju"
290 
291 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
292 
293 enum tty_modes {
294     TTY_MODE_OFF,
295     TTY_MODE_VCO,
296     TTY_MODE_HCO,
297     TTY_MODE_FULL
298 };
299 
300 struct pcm_config pcm_config_mm = {
301     .channels = 2,
302     .rate = MM_FULL_POWER_SAMPLING_RATE,
303     .period_size = DEEP_BUFFER_LONG_PERIOD_SIZE,
304     .period_count = PLAYBACK_DEEP_BUFFER_LONG_PERIOD_COUNT,
305     .format = PCM_FORMAT_S16_LE,
306     .start_threshold = DEEP_BUFFER_SHORT_PERIOD_SIZE * 2,
307     .avail_min = DEEP_BUFFER_LONG_PERIOD_SIZE,
308 };
309 
310 struct pcm_config pcm_config_tones = {
311     .channels = 2,
312     .rate = MM_FULL_POWER_SAMPLING_RATE,
313     .period_size = SHORT_PERIOD_SIZE,
314     .period_count = PLAYBACK_SHORT_PERIOD_COUNT,
315     .format = PCM_FORMAT_S16_LE,
316 #ifdef PLAYBACK_MMAP
317     .start_threshold = SHORT_PERIOD_SIZE,
318     .avail_min = SHORT_PERIOD_SIZE,
319 #else
320     .start_threshold = 0,
321     .avail_min = 0,
322 #endif
323 };
324 
325 struct pcm_config pcm_config_hdmi_multi = {
326     .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
327     .rate = MM_FULL_POWER_SAMPLING_RATE, /* changed when the stream is opened */
328     .period_size = HDMI_MULTI_PERIOD_SIZE,
329     .period_count = HDMI_MULTI_PERIOD_COUNT,
330     .format = PCM_FORMAT_S16_LE,
331     .start_threshold = 0,
332     .avail_min = 0,
333 };
334 
335 struct pcm_config pcm_config_mm_ul = {
336     .channels = 2,
337     .rate = MM_FULL_POWER_SAMPLING_RATE,
338     .period_size = CAPTURE_PERIOD_SIZE,
339     .period_count = CAPTURE_PERIOD_COUNT,
340     .format = PCM_FORMAT_S16_LE,
341 };
342 
343 struct pcm_config pcm_config_vx = {
344     .channels = 2,
345     .rate = VX_NB_SAMPLING_RATE,
346     .period_size = 160,
347     .period_count = 2,
348     .format = PCM_FORMAT_S16_LE,
349 };
350 
351 #define MIN(x, y) ((x) > (y) ? (y) : (x))
352 
353 struct route_setting
354 {
355     char *ctl_name;
356     int intval;
357     char *strval;
358 };
359 
360 /* These are values that never change */
361 struct route_setting defaults[] = {
362     /* general */
363     {
364         .ctl_name = MIXER_DL2_LEFT_EQUALIZER,
365         .strval = MIXER_450HZ_HIGH_PASS,
366     },
367     {
368         .ctl_name = MIXER_DL2_RIGHT_EQUALIZER,
369         .strval = MIXER_450HZ_HIGH_PASS,
370     },
371     {
372         .ctl_name = MIXER_DL1_MEDIA_PLAYBACK_VOLUME,
373         .intval = MIXER_ABE_GAIN_0DB,
374     },
375     {
376         .ctl_name = MIXER_DL2_MEDIA_PLAYBACK_VOLUME,
377         .intval = MIXER_ABE_GAIN_0DB,
378     },
379     {
380         .ctl_name = MIXER_DL1_VOICE_PLAYBACK_VOLUME,
381         .intval = MIXER_ABE_GAIN_0DB,
382     },
383     {
384         .ctl_name = MIXER_DL2_VOICE_PLAYBACK_VOLUME,
385         .intval = MIXER_ABE_GAIN_0DB,
386     },
387     {
388         .ctl_name = MIXER_DL1_TONES_PLAYBACK_VOLUME,
389         .intval = MIXER_ABE_GAIN_0DB,
390     },
391     {
392         .ctl_name = MIXER_DL2_TONES_PLAYBACK_VOLUME,
393         .intval = MIXER_ABE_GAIN_0DB,
394     },
395     {
396         .ctl_name = MIXER_SDT_DL_VOLUME,
397         .intval = MIXER_ABE_GAIN_0DB,
398     },
399     {
400         .ctl_name = MIXER_AUDUL_VOICE_UL_VOLUME,
401         .intval = MIXER_ABE_GAIN_0DB,
402     },
403     {
404         .ctl_name = MIXER_CAPTURE_PREAMPLIFIER_VOLUME,
405         .intval = DB_TO_CAPTURE_PREAMPLIFIER_VOLUME(0),
406     },
407     {
408         .ctl_name = MIXER_CAPTURE_VOLUME,
409         .intval = DB_TO_CAPTURE_VOLUME(30),
410     },
411     {
412         .ctl_name = MIXER_SDT_UL_VOLUME,
413         .intval = MIXER_ABE_GAIN_0DB - 17,
414     },
415     {
416         .ctl_name = MIXER_SIDETONE_MIXER_CAPTURE,
417         .intval = 0,
418     },
419 
420     /* headset */
421     {
422         .ctl_name = MIXER_SIDETONE_MIXER_PLAYBACK,
423         .intval = 1,
424     },
425     {
426         .ctl_name = MIXER_DL1_PDM_SWITCH,
427         .intval = 1,
428     },
429 
430     /* bt */
431     {
432         .ctl_name = MIXER_BT_UL_VOLUME,
433         .intval = MIXER_ABE_GAIN_0DB,
434     },
435     {
436         .ctl_name = NULL,
437     },
438 };
439 
440 struct route_setting hf_output[] = {
441     {
442         .ctl_name = MIXER_HF_LEFT_PLAYBACK,
443         .strval = MIXER_PLAYBACK_HF_DAC,
444     },
445     {
446         .ctl_name = MIXER_HF_RIGHT_PLAYBACK,
447         .strval = MIXER_PLAYBACK_HF_DAC,
448     },
449     {
450         .ctl_name = NULL,
451     },
452 };
453 
454 struct route_setting hs_output[] = {
455     {
456         .ctl_name = MIXER_HS_LEFT_PLAYBACK,
457         .strval = MIXER_PLAYBACK_HS_DAC,
458     },
459     {
460         .ctl_name = MIXER_HS_RIGHT_PLAYBACK,
461         .strval = MIXER_PLAYBACK_HS_DAC,
462     },
463     {
464         .ctl_name = NULL,
465     },
466 };
467 
468 /* MM UL front-end paths */
469 struct route_setting mm_ul2_bt[] = {
470     {
471         .ctl_name = MIXER_MUX_UL10,
472         .strval = MIXER_BT_LEFT,
473     },
474     {
475         .ctl_name = MIXER_MUX_UL11,
476         .strval = MIXER_BT_LEFT,
477     },
478     {
479         .ctl_name = NULL,
480     },
481 };
482 
483 struct route_setting mm_ul2_amic_left[] = {
484     {
485         .ctl_name = MIXER_MUX_UL10,
486         .strval = MIXER_AMIC0,
487     },
488     {
489         .ctl_name = MIXER_MUX_UL11,
490         .strval = MIXER_AMIC0,
491     },
492     {
493         .ctl_name = NULL,
494     },
495 };
496 
497 struct route_setting mm_ul2_amic_right[] = {
498     {
499         .ctl_name = MIXER_MUX_UL10,
500         .strval = MIXER_AMIC1,
501     },
502     {
503         .ctl_name = MIXER_MUX_UL11,
504         .strval = MIXER_AMIC1,
505     },
506     {
507         .ctl_name = NULL,
508     },
509 };
510 
511 /* dual mic configuration with main mic on main channel and sub mic on aux channel.
512  * Used for handset mode (near talk)  */
513 struct route_setting mm_ul2_amic_dual_main_sub[] = {
514     {
515         .ctl_name = MIXER_MUX_UL10,
516         .strval = MIXER_AMIC0,
517     },
518     {
519         .ctl_name = MIXER_MUX_UL11,
520         .strval = MIXER_AMIC1,
521     },
522     {
523         .ctl_name = NULL,
524     },
525 };
526 
527 /* dual mic configuration with sub mic on main channel and main mic on aux channel.
528  * Used for speakerphone mode (far talk)  */
529 struct route_setting mm_ul2_amic_dual_sub_main[] = {
530     {
531         .ctl_name = MIXER_MUX_UL10,
532         .strval = MIXER_AMIC1,
533     },
534     {
535         .ctl_name = MIXER_MUX_UL11,
536         .strval = MIXER_AMIC0,
537     },
538     {
539         .ctl_name = NULL,
540     },
541 };
542 
543 /* VX UL front-end paths */
544 struct route_setting vx_ul_amic_left[] = {
545     {
546         .ctl_name = MIXER_MUX_VX0,
547         .strval = MIXER_AMIC0,
548     },
549     {
550         .ctl_name = MIXER_MUX_VX1,
551         .strval = MIXER_AMIC0,
552     },
553     {
554         .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
555         .intval = 1,
556     },
557     {
558         .ctl_name = NULL,
559     },
560 };
561 
562 struct route_setting vx_ul_amic_right[] = {
563     {
564         .ctl_name = MIXER_MUX_VX0,
565         .strval = MIXER_AMIC1,
566     },
567     {
568         .ctl_name = MIXER_MUX_VX1,
569         .strval = MIXER_AMIC1,
570     },
571     {
572         .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
573         .intval = 1,
574     },
575     {
576         .ctl_name = NULL,
577     },
578 };
579 
580 struct route_setting vx_ul_bt[] = {
581     {
582         .ctl_name = MIXER_MUX_VX0,
583         .strval = MIXER_BT_LEFT,
584     },
585     {
586         .ctl_name = MIXER_MUX_VX1,
587         .strval = MIXER_BT_LEFT,
588     },
589     {
590         .ctl_name = MIXER_VOICE_CAPTURE_MIXER_CAPTURE,
591         .intval = 1,
592     },
593     {
594         .ctl_name = NULL,
595     },
596 };
597 
598 struct mixer_ctls
599 {
600     struct mixer_ctl *dl1_eq;
601     struct mixer_ctl *mm_dl1_volume;
602     struct mixer_ctl *tones_dl1_volume;
603     struct mixer_ctl *mm_dl2_volume;
604     struct mixer_ctl *vx_dl2_volume;
605     struct mixer_ctl *tones_dl2_volume;
606     struct mixer_ctl *mm_dl1;
607     struct mixer_ctl *mm_dl2;
608     struct mixer_ctl *vx_dl1;
609     struct mixer_ctl *vx_dl2;
610     struct mixer_ctl *tones_dl1;
611     struct mixer_ctl *tones_dl2;
612     struct mixer_ctl *earpiece_enable;
613     struct mixer_ctl *dl2_mono;
614     struct mixer_ctl *dl1_headset;
615     struct mixer_ctl *dl1_bt;
616     struct mixer_ctl *left_capture;
617     struct mixer_ctl *right_capture;
618     struct mixer_ctl *amic_ul_volume;
619     struct mixer_ctl *voice_ul_volume;
620     struct mixer_ctl *sidetone_capture;
621     struct mixer_ctl *headset_volume;
622     struct mixer_ctl *speaker_volume;
623     struct mixer_ctl *earpiece_volume;
624 };
625 
626 enum output_type {
627     OUTPUT_DEEP_BUF,      // deep PCM buffers output stream
628     OUTPUT_LOW_LATENCY,   // low latency output stream
629     OUTPUT_HDMI,
630     OUTPUT_TOTAL
631 };
632 
633 
634 struct tuna_audio_device {
635     struct audio_hw_device hw_device;
636 
637     pthread_mutex_t lock;       /* see note below on mutex acquisition order */
638     struct mixer *mixer;
639     struct mixer_ctls mixer_ctls;
640     audio_mode_t mode;
641     int devices;
642     struct pcm *pcm_modem_dl;
643     struct pcm *pcm_modem_ul;
644     int in_call;
645     float voice_volume;
646     struct tuna_stream_in *active_input;
647     struct tuna_stream_out *outputs[OUTPUT_TOTAL];
648     bool mic_mute;
649     int tty_mode;
650     struct echo_reference_itfe *echo_reference;
651     bool bluetooth_nrec;
652     bool device_is_toro;
653     int wb_amr;
654     bool screen_off;
655 
656     /* RIL */
657     struct ril_handle ril;
658 };
659 
660 enum pcm_type {
661     PCM_NORMAL = 0,
662     PCM_SPDIF,
663     PCM_HDMI,
664     PCM_TOTAL,
665 };
666 
667 struct tuna_stream_out {
668     struct audio_stream_out stream;
669 
670     pthread_mutex_t lock;       /* see note below on mutex acquisition order */
671     struct pcm_config config[PCM_TOTAL];
672     struct pcm *pcm[PCM_TOTAL];
673     struct resampler_itfe *resampler;
674     char *buffer;
675     size_t buffer_frames;
676     int standby;
677     struct echo_reference_itfe *echo_reference;
678     int write_threshold;
679     bool use_long_periods;
680     audio_channel_mask_t channel_mask;
681     audio_channel_mask_t sup_channel_masks[3];
682 
683     /* FIXME: workaround for HDMI multi channel channel swap on first playback after opening
684      * the output stream: force reopening the pcm driver after writing a few periods. */
685     int restart_periods_cnt;
686 
687     struct tuna_audio_device *dev;
688 };
689 
690 #define MAX_PREPROCESSORS 3 /* maximum one AGC + one NS + one AEC per input stream */
691 
692 struct effect_info_s {
693     effect_handle_t effect_itfe;
694     size_t num_channel_configs;
695     channel_config_t* channel_configs;
696 };
697 
698 #define NUM_IN_AUX_CNL_CONFIGS 2
699 channel_config_t in_aux_cnl_configs[NUM_IN_AUX_CNL_CONFIGS] = {
700     { AUDIO_CHANNEL_IN_FRONT , AUDIO_CHANNEL_IN_BACK},
701     { AUDIO_CHANNEL_IN_STEREO , AUDIO_CHANNEL_IN_RIGHT}
702 };
703 
704 
705 struct tuna_stream_in {
706     struct audio_stream_in stream;
707 
708     pthread_mutex_t lock;       /* see note below on mutex acquisition order */
709     struct pcm_config config;
710     struct pcm *pcm;
711     int device;
712     struct resampler_itfe *resampler;
713     struct resampler_buffer_provider buf_provider;
714     unsigned int requested_rate;
715     int standby;
716     int source;
717     struct echo_reference_itfe *echo_reference;
718     bool need_echo_reference;
719 
720     int16_t *read_buf;
721     size_t read_buf_size;
722     size_t read_buf_frames;
723 
724     int16_t *proc_buf_in;
725     int16_t *proc_buf_out;
726     size_t proc_buf_size;
727     size_t proc_buf_frames;
728 
729     int16_t *ref_buf;
730     size_t ref_buf_size;
731     size_t ref_buf_frames;
732 
733     int read_status;
734 
735     int num_preprocessors;
736     struct effect_info_s preprocessors[MAX_PREPROCESSORS];
737 
738     bool aux_channels_changed;
739     uint32_t main_channels;
740     uint32_t aux_channels;
741     struct tuna_audio_device *dev;
742 };
743 
744 
745 #define STRING_TO_ENUM(string) { #string, string }
746 
747 struct string_to_enum {
748     const char *name;
749     uint32_t value;
750 };
751 
752 const struct string_to_enum out_channels_name_to_enum_table[] = {
753     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
754     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
755     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
756 };
757 
758 
759 /**
760  * NOTE: when multiple mutexes have to be acquired, always respect the following order:
761  *        hw device > in stream > out stream
762  */
763 
764 
765 static void select_output_device(struct tuna_audio_device *adev);
766 static void select_input_device(struct tuna_audio_device *adev);
767 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume);
768 static int do_input_standby(struct tuna_stream_in *in);
769 static int do_output_standby(struct tuna_stream_out *out);
770 static void in_update_aux_channels(struct tuna_stream_in *in, effect_handle_t effect);
771 
772 /* Returns true on devices that are toro, false otherwise */
is_device_toro(void)773 static int is_device_toro(void)
774 {
775     char property[PROPERTY_VALUE_MAX];
776 
777     property_get(PRODUCT_DEVICE_PROPERTY, property, PRODUCT_DEVICE_TORO);
778 
779     /* return true if the property matches the given value */
780     return strcmp(property, PRODUCT_DEVICE_TORO) == 0;
781 }
782 
783 /* The enable flag when 0 makes the assumption that enums are disabled by
784  * "Off" and integers/booleans by 0 */
set_route_by_array(struct mixer * mixer,struct route_setting * route,int enable)785 static int set_route_by_array(struct mixer *mixer, struct route_setting *route,
786                               int enable)
787 {
788     struct mixer_ctl *ctl;
789     unsigned int i, j;
790 
791     /* Go through the route array and set each value */
792     i = 0;
793     while (route[i].ctl_name) {
794         ctl = mixer_get_ctl_by_name(mixer, route[i].ctl_name);
795         if (!ctl)
796             return -EINVAL;
797 
798         if (route[i].strval) {
799             if (enable)
800                 mixer_ctl_set_enum_by_string(ctl, route[i].strval);
801             else
802                 mixer_ctl_set_enum_by_string(ctl, "Off");
803         } else {
804             /* This ensures multiple (i.e. stereo) values are set jointly */
805             for (j = 0; j < mixer_ctl_get_num_values(ctl); j++) {
806                 if (enable)
807                     mixer_ctl_set_value(ctl, j, route[i].intval);
808                 else
809                     mixer_ctl_set_value(ctl, j, 0);
810             }
811         }
812         i++;
813     }
814 
815     return 0;
816 }
817 
start_call(struct tuna_audio_device * adev)818 static int start_call(struct tuna_audio_device *adev)
819 {
820     ALOGE("Opening modem PCMs");
821 
822     pcm_config_vx.rate = adev->wb_amr ? VX_WB_SAMPLING_RATE : VX_NB_SAMPLING_RATE;
823 
824     /* Open modem PCM channels */
825     if (adev->pcm_modem_dl == NULL) {
826         adev->pcm_modem_dl = pcm_open(0, PORT_MODEM, PCM_OUT, &pcm_config_vx);
827         if (!pcm_is_ready(adev->pcm_modem_dl)) {
828             ALOGE("cannot open PCM modem DL stream: %s", pcm_get_error(adev->pcm_modem_dl));
829             goto err_open_dl;
830         }
831     }
832 
833     if (adev->pcm_modem_ul == NULL) {
834         adev->pcm_modem_ul = pcm_open(0, PORT_MODEM, PCM_IN, &pcm_config_vx);
835         if (!pcm_is_ready(adev->pcm_modem_ul)) {
836             ALOGE("cannot open PCM modem UL stream: %s", pcm_get_error(adev->pcm_modem_ul));
837             goto err_open_ul;
838         }
839     }
840 
841     pcm_start(adev->pcm_modem_dl);
842     pcm_start(adev->pcm_modem_ul);
843 
844     return 0;
845 
846 err_open_ul:
847     pcm_close(adev->pcm_modem_ul);
848     adev->pcm_modem_ul = NULL;
849 err_open_dl:
850     pcm_close(adev->pcm_modem_dl);
851     adev->pcm_modem_dl = NULL;
852 
853     return -ENOMEM;
854 }
855 
end_call(struct tuna_audio_device * adev)856 static void end_call(struct tuna_audio_device *adev)
857 {
858     ALOGE("Closing modem PCMs");
859 
860     pcm_stop(adev->pcm_modem_dl);
861     pcm_stop(adev->pcm_modem_ul);
862     pcm_close(adev->pcm_modem_dl);
863     pcm_close(adev->pcm_modem_ul);
864     adev->pcm_modem_dl = NULL;
865     adev->pcm_modem_ul = NULL;
866 }
867 
set_eq_filter(struct tuna_audio_device * adev)868 static void set_eq_filter(struct tuna_audio_device *adev)
869 {
870     /* DL1_EQ can't be used for bt */
871     int dl1_eq_applicable = adev->devices & (AUDIO_DEVICE_OUT_WIRED_HEADSET |
872                     AUDIO_DEVICE_OUT_WIRED_HEADPHONE | AUDIO_DEVICE_OUT_EARPIECE);
873 
874     /* 4Khz LPF is used only in NB-AMR voicecall */
875     if ((adev->mode == AUDIO_MODE_IN_CALL) && dl1_eq_applicable &&
876             (adev->tty_mode == TTY_MODE_OFF) && !adev->wb_amr)
877         mixer_ctl_set_enum_by_string(adev->mixer_ctls.dl1_eq, MIXER_4KHZ_LPF_0DB);
878     else
879         mixer_ctl_set_enum_by_string(adev->mixer_ctls.dl1_eq, MIXER_FLAT_RESPONSE);
880 }
881 
audio_set_wb_amr_callback(void * data,int enable)882 void audio_set_wb_amr_callback(void *data, int enable)
883 {
884     struct tuna_audio_device *adev = (struct tuna_audio_device *)data;
885 
886     pthread_mutex_lock(&adev->lock);
887     if (adev->wb_amr != enable) {
888         adev->wb_amr = enable;
889 
890         /* reopen the modem PCMs at the new rate */
891         if (adev->in_call) {
892             end_call(adev);
893             set_eq_filter(adev);
894             start_call(adev);
895         }
896     }
897     pthread_mutex_unlock(&adev->lock);
898 }
899 
set_incall_device(struct tuna_audio_device * adev)900 static void set_incall_device(struct tuna_audio_device *adev)
901 {
902     int device_type;
903 
904     switch(adev->devices & AUDIO_DEVICE_OUT_ALL) {
905         case AUDIO_DEVICE_OUT_EARPIECE:
906             device_type = SOUND_AUDIO_PATH_HANDSET;
907             break;
908         case AUDIO_DEVICE_OUT_SPEAKER:
909         case AUDIO_DEVICE_OUT_AUX_DIGITAL:
910         case AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET:
911             device_type = SOUND_AUDIO_PATH_SPEAKER;
912             break;
913         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
914             device_type = SOUND_AUDIO_PATH_HEADSET;
915             break;
916         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
917             device_type = SOUND_AUDIO_PATH_HEADPHONE;
918             break;
919         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
920         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
921         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
922             if (adev->bluetooth_nrec)
923                 device_type = SOUND_AUDIO_PATH_BLUETOOTH;
924             else
925                 device_type = SOUND_AUDIO_PATH_BLUETOOTH_NO_NR;
926             break;
927         default:
928             device_type = SOUND_AUDIO_PATH_HANDSET;
929             break;
930     }
931 
932     /* if output device isn't supported, open modem side to handset by default */
933     ril_set_call_audio_path(&adev->ril, device_type);
934 }
935 
set_input_volumes(struct tuna_audio_device * adev,int main_mic_on,int headset_mic_on,int sub_mic_on)936 static void set_input_volumes(struct tuna_audio_device *adev, int main_mic_on,
937                               int headset_mic_on, int sub_mic_on)
938 {
939     unsigned int channel;
940     int volume = MIXER_ABE_GAIN_0DB;
941 
942     if (adev->mode == AUDIO_MODE_IN_CALL) {
943         int sub_mic_volume = is_device_toro() ? VOICE_CALL_SUB_MIC_VOLUME_TORO :
944                                                 VOICE_CALL_SUB_MIC_VOLUME_MAGURO;
945         /* special case: don't look at input source for IN_CALL state */
946         volume = DB_TO_ABE_GAIN(main_mic_on ? VOICE_CALL_MAIN_MIC_VOLUME :
947                 (headset_mic_on ? VOICE_CALL_HEADSET_MIC_VOLUME :
948                 (sub_mic_on ? sub_mic_volume : 0)));
949     } else if (adev->active_input) {
950         /* determine input volume by use case */
951         switch (adev->active_input->source) {
952         case AUDIO_SOURCE_MIC: /* general capture */
953             volume = DB_TO_ABE_GAIN(main_mic_on ? CAPTURE_MAIN_MIC_VOLUME :
954                     (headset_mic_on ? CAPTURE_HEADSET_MIC_VOLUME :
955                     (sub_mic_on ? CAPTURE_SUB_MIC_VOLUME : 0)));
956             break;
957 
958         case AUDIO_SOURCE_CAMCORDER:
959             volume = DB_TO_ABE_GAIN(main_mic_on ? CAMCORDER_MAIN_MIC_VOLUME :
960                     (headset_mic_on ? CAMCORDER_HEADSET_MIC_VOLUME :
961                     (sub_mic_on ? CAMCORDER_SUB_MIC_VOLUME : 0)));
962             break;
963 
964         case AUDIO_SOURCE_VOICE_RECOGNITION:
965             volume = DB_TO_ABE_GAIN(main_mic_on ? VOICE_RECOGNITION_MAIN_MIC_VOLUME :
966                     (headset_mic_on ? VOICE_RECOGNITION_HEADSET_MIC_VOLUME :
967                     (sub_mic_on ? VOICE_RECOGNITION_SUB_MIC_VOLUME : 0)));
968             break;
969 
970         case AUDIO_SOURCE_VOICE_COMMUNICATION: /* VoIP */
971             volume = DB_TO_ABE_GAIN(main_mic_on ? VOIP_MAIN_MIC_VOLUME :
972                     (headset_mic_on ? VOIP_HEADSET_MIC_VOLUME :
973                     (sub_mic_on ? VOIP_SUB_MIC_VOLUME : 0)));
974             break;
975 
976         default:
977             /* nothing to do */
978             break;
979         }
980     }
981 
982     for (channel = 0; channel < 2; channel++)
983         mixer_ctl_set_value(adev->mixer_ctls.amic_ul_volume, channel, volume);
984 }
985 
set_output_volumes(struct tuna_audio_device * adev,bool tty_volume)986 static void set_output_volumes(struct tuna_audio_device *adev, bool tty_volume)
987 {
988     unsigned int channel;
989     int speaker_volume;
990     int headset_volume;
991     int earpiece_volume;
992     bool toro = adev->device_is_toro;
993     int headphone_on = adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
994     int speaker_on = adev->devices & AUDIO_DEVICE_OUT_SPEAKER;
995     int speaker_volume_overrange = MIXER_ABE_GAIN_0DB;
996     int speaker_max_db =
997         DB_FROM_SPEAKER_VOLUME(mixer_ctl_get_range_max(adev->mixer_ctls.speaker_volume));
998     int normal_speaker_volume = toro ? NORMAL_SPEAKER_VOLUME_TORO :
999                             NORMAL_SPEAKER_VOLUME_MAGURO;
1000     int normal_headphone_volume = toro ? NORMAL_HEADPHONE_VOLUME_TORO :
1001                                 NORMAL_HEADPHONE_VOLUME_MAGURO;
1002     int normal_headset_volume = toro ? NORMAL_HEADSET_VOLUME_TORO :
1003                                 NORMAL_HEADSET_VOLUME_MAGURO;
1004     int normal_earpiece_volume = toro ? NORMAL_EARPIECE_VOLUME_TORO :
1005                              NORMAL_EARPIECE_VOLUME_MAGURO;
1006     int dl1_volume_correction = 0;
1007     int dl2_volume_correction = 0;
1008 
1009     if (adev->mode == AUDIO_MODE_IN_CALL) {
1010         /* Voice call */
1011         speaker_volume = toro ? VOICE_CALL_SPEAKER_VOLUME_TORO :
1012                                 VOICE_CALL_SPEAKER_VOLUME_MAGURO;
1013         headset_volume = toro ? VOICE_CALL_HEADSET_VOLUME_TORO :
1014                                 VOICE_CALL_HEADSET_VOLUME_MAGURO;
1015         earpiece_volume = toro ? VOICE_CALL_EARPIECE_VOLUME_TORO :
1016                                  VOICE_CALL_EARPIECE_VOLUME_MAGURO;
1017     } else if (adev->mode == AUDIO_MODE_IN_COMMUNICATION) {
1018         /* VoIP */
1019         speaker_volume = toro ? VOIP_SPEAKER_VOLUME_TORO :
1020                                 VOIP_SPEAKER_VOLUME_MAGURO;
1021         headset_volume = toro ? VOIP_HEADSET_VOLUME_TORO :
1022                                 VOIP_HEADSET_VOLUME_MAGURO;
1023         earpiece_volume = toro ? VOIP_EARPIECE_VOLUME_TORO :
1024                                  VOIP_EARPIECE_VOLUME_MAGURO;
1025     } else {
1026         /* Media */
1027         speaker_volume = normal_speaker_volume;
1028         if (headphone_on)
1029             headset_volume = normal_headphone_volume;
1030         else
1031             headset_volume = normal_headset_volume;
1032         earpiece_volume = normal_earpiece_volume;
1033     }
1034 
1035     if (tty_volume)
1036         headset_volume = HEADPHONE_VOLUME_TTY;
1037     else if (adev->mode == AUDIO_MODE_RINGTONE)
1038         headset_volume += RINGTONE_HEADSET_VOLUME_OFFSET;
1039 
1040     /* apply correction on digital volume to keep the overall volume consistent if the
1041      * analog volume is not driven by media use case
1042      */
1043     if (headphone_on)
1044         dl1_volume_correction = normal_headphone_volume - headset_volume;
1045     else if (adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADSET)
1046         dl1_volume_correction = normal_headset_volume - headset_volume;
1047     else
1048         dl1_volume_correction = normal_earpiece_volume - earpiece_volume;
1049 
1050     if (speaker_on)
1051         dl2_volume_correction = normal_speaker_volume - speaker_volume;
1052 
1053     /* If we have run out of range in the codec (analog) speaker volume,
1054        we have to apply the remainder of the dB increase to the DL2
1055        media/voice mixer volume, which is a digital gain */
1056     if (speaker_volume > speaker_max_db) {
1057         speaker_volume_overrange += (speaker_volume - speaker_max_db);
1058         speaker_volume = speaker_max_db;
1059     }
1060 
1061     for (channel = 0; channel < 2; channel++) {
1062         mixer_ctl_set_value(adev->mixer_ctls.speaker_volume, channel,
1063             DB_TO_SPEAKER_VOLUME(speaker_volume));
1064         mixer_ctl_set_value(adev->mixer_ctls.headset_volume, channel,
1065             DB_TO_HEADSET_VOLUME(headset_volume));
1066     }
1067 
1068     if (!speaker_on)
1069         speaker_volume_overrange = MIXER_ABE_GAIN_0DB;
1070 
1071     if (adev->mode == AUDIO_MODE_IN_CALL) {
1072         mixer_ctl_set_value(adev->mixer_ctls.tones_dl1_volume, 0,
1073                             MIXER_ABE_GAIN_0DB + dl1_volume_correction);
1074         mixer_ctl_set_value(adev->mixer_ctls.vx_dl2_volume, 0,
1075                                 speaker_volume_overrange);
1076         mixer_ctl_set_value(adev->mixer_ctls.tones_dl2_volume, 0,
1077                                 speaker_volume_overrange + dl2_volume_correction);
1078     } else if (adev->mode == AUDIO_MODE_IN_COMMUNICATION) {
1079         mixer_ctl_set_value(adev->mixer_ctls.tones_dl1_volume, 0,
1080                             MIXER_ABE_GAIN_0DB);
1081         mixer_ctl_set_value(adev->mixer_ctls.tones_dl2_volume, 0,
1082                                 speaker_volume_overrange);
1083     } else {
1084         mixer_ctl_set_value(adev->mixer_ctls.tones_dl1_volume, 0,
1085                             MIXER_ABE_GAIN_0DB + dl1_volume_correction);
1086         mixer_ctl_set_value(adev->mixer_ctls.tones_dl2_volume, 0,
1087                                 speaker_volume_overrange + dl2_volume_correction);
1088     }
1089 
1090     mixer_ctl_set_value(adev->mixer_ctls.mm_dl1_volume, 0,
1091                         MIXER_ABE_GAIN_0DB + dl1_volume_correction);
1092     mixer_ctl_set_value(adev->mixer_ctls.mm_dl2_volume, 0,
1093                             speaker_volume_overrange + dl2_volume_correction);
1094 
1095     mixer_ctl_set_value(adev->mixer_ctls.earpiece_volume, 0,
1096         DB_TO_EARPIECE_VOLUME(earpiece_volume));
1097 }
1098 
force_all_standby(struct tuna_audio_device * adev)1099 static void force_all_standby(struct tuna_audio_device *adev)
1100 {
1101     struct tuna_stream_in *in;
1102     struct tuna_stream_out *out;
1103 
1104     /* only needed for low latency output streams as other streams are not used
1105      * for voice use cases */
1106     if (adev->outputs[OUTPUT_LOW_LATENCY] != NULL &&
1107             !adev->outputs[OUTPUT_LOW_LATENCY]->standby) {
1108         out = adev->outputs[OUTPUT_LOW_LATENCY];
1109         pthread_mutex_lock(&out->lock);
1110         do_output_standby(out);
1111         pthread_mutex_unlock(&out->lock);
1112     }
1113 
1114     if (adev->active_input) {
1115         in = adev->active_input;
1116         pthread_mutex_lock(&in->lock);
1117         do_input_standby(in);
1118         pthread_mutex_unlock(&in->lock);
1119     }
1120 }
1121 
select_mode(struct tuna_audio_device * adev)1122 static void select_mode(struct tuna_audio_device *adev)
1123 {
1124     if (adev->mode == AUDIO_MODE_IN_CALL) {
1125         ALOGE("Entering IN_CALL state, in_call=%d", adev->in_call);
1126         if (!adev->in_call) {
1127             force_all_standby(adev);
1128             /* force earpiece route for in call state if speaker is the
1129             only currently selected route. This prevents having to tear
1130             down the modem PCMs to change route from speaker to earpiece
1131             after the ringtone is played, but doesn't cause a route
1132             change if a headset or bt device is already connected. If
1133             speaker is not the only thing active, just remove it from
1134             the route. We'll assume it'll never be used initally during
1135             a call. This works because we're sure that the audio policy
1136             manager will update the output device after the audio mode
1137             change, even if the device selection did not change. */
1138             if ((adev->devices & AUDIO_DEVICE_OUT_ALL) == AUDIO_DEVICE_OUT_SPEAKER)
1139                 adev->devices = AUDIO_DEVICE_OUT_EARPIECE |
1140                                 AUDIO_DEVICE_IN_BUILTIN_MIC;
1141             else
1142                 adev->devices &= ~AUDIO_DEVICE_OUT_SPEAKER;
1143             select_output_device(adev);
1144             start_call(adev);
1145             adev_set_voice_volume(&adev->hw_device, adev->voice_volume);
1146             adev->in_call = 1;
1147         }
1148     } else {
1149         ALOGE("Leaving IN_CALL state, in_call=%d, mode=%d",
1150              adev->in_call, adev->mode);
1151         if (adev->in_call) {
1152             adev->in_call = 0;
1153             end_call(adev);
1154             force_all_standby(adev);
1155             select_output_device(adev);
1156             select_input_device(adev);
1157         }
1158     }
1159 }
1160 
select_output_device(struct tuna_audio_device * adev)1161 static void select_output_device(struct tuna_audio_device *adev)
1162 {
1163     int headset_on;
1164     int headphone_on;
1165     int speaker_on;
1166     int earpiece_on;
1167     int bt_on;
1168     int dl1_on;
1169     int sidetone_capture_on = 0;
1170     bool tty_volume = false;
1171     unsigned int channel;
1172 
1173     /* Mute VX_UL to avoid pop noises in the tx path
1174      * during call before switch changes.
1175      */
1176     if (adev->mode == AUDIO_MODE_IN_CALL) {
1177         for (channel = 0; channel < 2; channel++)
1178             mixer_ctl_set_value(adev->mixer_ctls.voice_ul_volume,
1179                                 channel, 0);
1180     }
1181 
1182     headset_on = adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
1183     headphone_on = adev->devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
1184     speaker_on = adev->devices & AUDIO_DEVICE_OUT_SPEAKER;
1185     earpiece_on = adev->devices & AUDIO_DEVICE_OUT_EARPIECE;
1186     bt_on = adev->devices & AUDIO_DEVICE_OUT_ALL_SCO;
1187 
1188     /* force rx path according to TTY mode when in call */
1189     if (adev->mode == AUDIO_MODE_IN_CALL && !bt_on) {
1190         switch(adev->tty_mode) {
1191             case TTY_MODE_FULL:
1192             case TTY_MODE_VCO:
1193                 /* rx path to headphones */
1194                 headphone_on = 1;
1195                 headset_on = 0;
1196                 speaker_on = 0;
1197                 earpiece_on = 0;
1198                 tty_volume = true;
1199                 break;
1200             case TTY_MODE_HCO:
1201                 /* rx path to device speaker */
1202                 headphone_on = 0;
1203                 headset_on = 0;
1204                 speaker_on = 1;
1205                 earpiece_on = 0;
1206                 break;
1207             case TTY_MODE_OFF:
1208             default:
1209                 /* force speaker on when in call and HDMI or S/PDIF is selected
1210                  * as voice DL audio cannot be routed there by ABE */
1211                 if (adev->devices &
1212                         (AUDIO_DEVICE_OUT_AUX_DIGITAL |
1213                          AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET))
1214                     speaker_on = 1;
1215                 break;
1216         }
1217     }
1218 
1219     dl1_on = headset_on | headphone_on | earpiece_on | bt_on;
1220 
1221     /* Select front end */
1222     mixer_ctl_set_value(adev->mixer_ctls.mm_dl2, 0, speaker_on);
1223     mixer_ctl_set_value(adev->mixer_ctls.tones_dl2, 0, speaker_on);
1224     mixer_ctl_set_value(adev->mixer_ctls.vx_dl2, 0,
1225                         speaker_on && (adev->mode == AUDIO_MODE_IN_CALL));
1226     mixer_ctl_set_value(adev->mixer_ctls.mm_dl1, 0, dl1_on);
1227     mixer_ctl_set_value(adev->mixer_ctls.tones_dl1, 0, dl1_on);
1228     mixer_ctl_set_value(adev->mixer_ctls.vx_dl1, 0,
1229                         dl1_on && (adev->mode == AUDIO_MODE_IN_CALL));
1230     /* Select back end */
1231     mixer_ctl_set_value(adev->mixer_ctls.dl1_headset, 0,
1232                         headset_on | headphone_on | earpiece_on);
1233     mixer_ctl_set_value(adev->mixer_ctls.dl1_bt, 0, bt_on);
1234     mixer_ctl_set_value(adev->mixer_ctls.dl2_mono, 0,
1235                         (adev->mode != AUDIO_MODE_IN_CALL) && speaker_on);
1236     mixer_ctl_set_value(adev->mixer_ctls.earpiece_enable, 0, earpiece_on);
1237 
1238     /* select output stage */
1239     set_route_by_array(adev->mixer, hs_output, headset_on | headphone_on);
1240     set_route_by_array(adev->mixer, hf_output, speaker_on);
1241 
1242     set_eq_filter(adev);
1243     set_output_volumes(adev, tty_volume);
1244 
1245     /* Special case: select input path if in a call, otherwise
1246        in_set_parameters is used to update the input route
1247        todo: use sub mic for handsfree case */
1248     if (adev->mode == AUDIO_MODE_IN_CALL) {
1249         if (bt_on)
1250             set_route_by_array(adev->mixer, vx_ul_bt, bt_on);
1251         else {
1252             /* force tx path according to TTY mode when in call */
1253             switch(adev->tty_mode) {
1254                 case TTY_MODE_FULL:
1255                 case TTY_MODE_HCO:
1256                     /* tx path from headset mic */
1257                     headphone_on = 0;
1258                     headset_on = 1;
1259                     speaker_on = 0;
1260                     earpiece_on = 0;
1261                     break;
1262                 case TTY_MODE_VCO:
1263                     /* tx path from device sub mic */
1264                     headphone_on = 0;
1265                     headset_on = 0;
1266                     speaker_on = 1;
1267                     earpiece_on = 0;
1268                     break;
1269                 case TTY_MODE_OFF:
1270                 default:
1271                     break;
1272             }
1273 
1274             if (headset_on || headphone_on || earpiece_on)
1275                 set_route_by_array(adev->mixer, vx_ul_amic_left, 1);
1276             else if (speaker_on)
1277                 set_route_by_array(adev->mixer, vx_ul_amic_right, 1);
1278             else
1279                 set_route_by_array(adev->mixer, vx_ul_amic_left, 0);
1280 
1281             mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture,
1282                                         (earpiece_on || headphone_on) ? MIXER_MAIN_MIC :
1283                                         (headset_on ? MIXER_HS_MIC : "Off"));
1284             mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture,
1285                                          speaker_on ? MIXER_SUB_MIC : "Off");
1286 
1287             set_input_volumes(adev, earpiece_on || headphone_on,
1288                               headset_on, speaker_on);
1289 
1290             /* enable sidetone mixer capture if needed */
1291             sidetone_capture_on = earpiece_on && adev->device_is_toro;
1292         }
1293 
1294         set_incall_device(adev);
1295 
1296         /* Unmute VX_UL after the switch */
1297         for (channel = 0; channel < 2; channel++) {
1298             mixer_ctl_set_value(adev->mixer_ctls.voice_ul_volume,
1299                                 channel, MIXER_ABE_GAIN_0DB);
1300         }
1301     }
1302 
1303     mixer_ctl_set_value(adev->mixer_ctls.sidetone_capture, 0, sidetone_capture_on);
1304 }
1305 
select_input_device(struct tuna_audio_device * adev)1306 static void select_input_device(struct tuna_audio_device *adev)
1307 {
1308     int headset_on = 0;
1309     int main_mic_on = 0;
1310     int sub_mic_on = 0;
1311     int bt_on = adev->devices & AUDIO_DEVICE_IN_ALL_SCO;
1312 
1313     if (!bt_on) {
1314         if ((adev->mode != AUDIO_MODE_IN_CALL) && (adev->active_input != 0)) {
1315             /* sub mic is used for camcorder or VoIP on speaker phone */
1316             sub_mic_on = (adev->active_input->source == AUDIO_SOURCE_CAMCORDER) ||
1317                          ((adev->devices & AUDIO_DEVICE_OUT_SPEAKER) &&
1318                           (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION));
1319         }
1320         if (!sub_mic_on) {
1321             headset_on = adev->devices & AUDIO_DEVICE_IN_WIRED_HEADSET;
1322             main_mic_on = adev->devices & AUDIO_DEVICE_IN_BUILTIN_MIC;
1323         }
1324     }
1325 
1326    /* TODO: check how capture is possible during voice calls or if
1327     * both use cases are mutually exclusive.
1328     */
1329     if (bt_on)
1330         set_route_by_array(adev->mixer, mm_ul2_bt, 1);
1331     else {
1332         /* Select front end */
1333 
1334 
1335         if ((adev->active_input != 0) && (adev->active_input->aux_channels)) {
1336             ALOGV("select input device(): multi-mic configuration main mic %s sub mic %s",
1337                   main_mic_on ? "ON" : "OFF", sub_mic_on ? "ON" : "OFF");
1338             if (main_mic_on) {
1339                 set_route_by_array(adev->mixer, mm_ul2_amic_dual_main_sub, 1);
1340                 sub_mic_on = 1;
1341             }
1342             else if (sub_mic_on) {
1343                 set_route_by_array(adev->mixer, mm_ul2_amic_dual_sub_main, 1);
1344                 main_mic_on = 1;
1345             }
1346             else {
1347                 set_route_by_array(adev->mixer, mm_ul2_amic_dual_main_sub, 0);
1348             }
1349         } else {
1350             ALOGV("select input device(): single mic configuration");
1351             if (main_mic_on || headset_on)
1352                 set_route_by_array(adev->mixer, mm_ul2_amic_left, 1);
1353             else if (sub_mic_on)
1354                 set_route_by_array(adev->mixer, mm_ul2_amic_right, 1);
1355             else
1356                 set_route_by_array(adev->mixer, mm_ul2_amic_left, 0);
1357         }
1358 
1359 
1360         /* Select back end */
1361         mixer_ctl_set_enum_by_string(adev->mixer_ctls.right_capture,
1362                                      sub_mic_on ? MIXER_SUB_MIC : "Off");
1363         mixer_ctl_set_enum_by_string(adev->mixer_ctls.left_capture,
1364                                      main_mic_on ? MIXER_MAIN_MIC :
1365                                      (headset_on ? MIXER_HS_MIC : "Off"));
1366     }
1367 
1368     set_input_volumes(adev, main_mic_on, headset_on, sub_mic_on);
1369 }
1370 
1371 /* must be called with hw device and output stream mutexes locked */
start_output_stream_low_latency(struct tuna_stream_out * out)1372 static int start_output_stream_low_latency(struct tuna_stream_out *out)
1373 {
1374     struct tuna_audio_device *adev = out->dev;
1375 #ifdef PLAYBACK_MMAP
1376     unsigned int flags = PCM_OUT | PCM_MMAP | PCM_NOIRQ;
1377 #else
1378     unsigned int flags = PCM_OUT;
1379 #endif
1380     int i;
1381     bool success = true;
1382 
1383     if (adev->mode != AUDIO_MODE_IN_CALL) {
1384         select_output_device(adev);
1385     }
1386 
1387     /* default to low power: will be corrected in out_write if necessary before first write to
1388      * tinyalsa.
1389      */
1390 
1391     if (adev->devices & (AUDIO_DEVICE_OUT_ALL &
1392                          ~(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET | AUDIO_DEVICE_OUT_AUX_DIGITAL))) {
1393         /* Something not a dock in use */
1394         out->config[PCM_NORMAL] = pcm_config_tones;
1395         out->config[PCM_NORMAL].rate = MM_FULL_POWER_SAMPLING_RATE;
1396         out->pcm[PCM_NORMAL] = pcm_open(CARD_TUNA_DEFAULT, PORT_TONES,
1397                                             flags, &out->config[PCM_NORMAL]);
1398     }
1399 
1400     if (adev->devices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET) {
1401         /* SPDIF output in use */
1402         out->config[PCM_SPDIF] = pcm_config_tones;
1403         out->config[PCM_SPDIF].rate = MM_FULL_POWER_SAMPLING_RATE;
1404         out->pcm[PCM_SPDIF] = pcm_open(CARD_TUNA_DEFAULT, PORT_SPDIF,
1405                                            flags, &out->config[PCM_SPDIF]);
1406     }
1407 
1408     /* priority is given to multichannel HDMI output */
1409     if ((adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) &&
1410             (adev->outputs[OUTPUT_HDMI] == NULL || adev->outputs[OUTPUT_HDMI]->standby)) {
1411         /* HDMI output in use */
1412         out->config[PCM_HDMI] = pcm_config_tones;
1413         out->config[PCM_HDMI].rate = MM_LOW_POWER_SAMPLING_RATE;
1414         out->pcm[PCM_HDMI] = pcm_open(CARD_OMAP4_HDMI, PORT_HDMI,
1415                                           flags, &out->config[PCM_HDMI]);
1416     }
1417 
1418     /* Close any PCMs that could not be opened properly and return an error */
1419     for (i = 0; i < PCM_TOTAL; i++) {
1420         if (out->pcm[i] && !pcm_is_ready(out->pcm[i])) {
1421             ALOGE("cannot open pcm_out driver %d: %s", i, pcm_get_error(out->pcm[i]));
1422             pcm_close(out->pcm[i]);
1423             out->pcm[i] = NULL;
1424             success = false;
1425         }
1426     }
1427 
1428     if (success) {
1429         out->buffer_frames = pcm_config_tones.period_size * 2;
1430         if (out->buffer == NULL)
1431             out->buffer = malloc(out->buffer_frames * audio_stream_frame_size(&out->stream.common));
1432 
1433         if (adev->echo_reference != NULL)
1434             out->echo_reference = adev->echo_reference;
1435         out->resampler->reset(out->resampler);
1436 
1437         return 0;
1438     }
1439 
1440     return -ENOMEM;
1441 }
1442 
1443 /* must be called with hw device and output stream mutexes locked */
start_output_stream_deep_buffer(struct tuna_stream_out * out)1444 static int start_output_stream_deep_buffer(struct tuna_stream_out *out)
1445 {
1446     struct tuna_audio_device *adev = out->dev;
1447 
1448     if (adev->mode != AUDIO_MODE_IN_CALL) {
1449         select_output_device(adev);
1450     }
1451 
1452     out->write_threshold = PLAYBACK_DEEP_BUFFER_LONG_PERIOD_COUNT * DEEP_BUFFER_LONG_PERIOD_SIZE;
1453     out->use_long_periods = true;
1454 
1455     out->config[PCM_NORMAL] = pcm_config_mm;
1456     out->config[PCM_NORMAL].rate = MM_FULL_POWER_SAMPLING_RATE;
1457     out->pcm[PCM_NORMAL] = pcm_open(CARD_TUNA_DEFAULT, PORT_MM,
1458                                         PCM_OUT | PCM_MMAP | PCM_NOIRQ, &out->config[PCM_NORMAL]);
1459     if (out->pcm[PCM_NORMAL] && !pcm_is_ready(out->pcm[PCM_NORMAL])) {
1460         ALOGE("cannot open pcm_out driver: %s", pcm_get_error(out->pcm[PCM_NORMAL]));
1461         pcm_close(out->pcm[PCM_NORMAL]);
1462         out->pcm[PCM_NORMAL] = NULL;
1463         return -ENOMEM;
1464     }
1465     out->buffer_frames = DEEP_BUFFER_SHORT_PERIOD_SIZE * 2;
1466     if (out->buffer == NULL)
1467         out->buffer = malloc(out->buffer_frames * audio_stream_frame_size(&out->stream.common));
1468 
1469     return 0;
1470 }
1471 
start_output_stream_hdmi(struct tuna_stream_out * out)1472 static int start_output_stream_hdmi(struct tuna_stream_out *out)
1473 {
1474     struct tuna_audio_device *adev = out->dev;
1475 
1476     /* force standby on low latency output stream to close HDMI driver in case it was in use */
1477     if (adev->outputs[OUTPUT_LOW_LATENCY] != NULL &&
1478             !adev->outputs[OUTPUT_LOW_LATENCY]->standby) {
1479         struct tuna_stream_out *ll_out = adev->outputs[OUTPUT_LOW_LATENCY];
1480         pthread_mutex_lock(&ll_out->lock);
1481         do_output_standby(ll_out);
1482         pthread_mutex_unlock(&ll_out->lock);
1483     }
1484 
1485     out->pcm[PCM_HDMI] = pcm_open(CARD_OMAP4_HDMI, PORT_HDMI, PCM_OUT, &out->config[PCM_HDMI]);
1486 
1487     if (out->pcm[PCM_HDMI] && !pcm_is_ready(out->pcm[PCM_HDMI])) {
1488         ALOGE("cannot open pcm_out driver: %s", pcm_get_error(out->pcm[PCM_HDMI]));
1489         pcm_close(out->pcm[PCM_HDMI]);
1490         out->pcm[PCM_HDMI] = NULL;
1491         return -ENOMEM;
1492     }
1493     return 0;
1494 }
1495 
check_input_parameters(uint32_t sample_rate,audio_format_t format,int channel_count)1496 static int check_input_parameters(uint32_t sample_rate, audio_format_t format, int channel_count)
1497 {
1498     if (format != AUDIO_FORMAT_PCM_16_BIT)
1499         return -EINVAL;
1500 
1501     if ((channel_count < 1) || (channel_count > 2))
1502         return -EINVAL;
1503 
1504     switch(sample_rate) {
1505     case 8000:
1506     case 11025:
1507     case 16000:
1508     case 22050:
1509     case 24000:
1510     case 32000:
1511     case 44100:
1512     case 48000:
1513         break;
1514     default:
1515         return -EINVAL;
1516     }
1517 
1518     return 0;
1519 }
1520 
get_input_buffer_size(uint32_t sample_rate,audio_format_t format,int channel_count)1521 static size_t get_input_buffer_size(uint32_t sample_rate, audio_format_t format, int channel_count)
1522 {
1523     size_t size;
1524     size_t device_rate;
1525 
1526     if (check_input_parameters(sample_rate, format, channel_count) != 0)
1527         return 0;
1528 
1529     /* take resampling into account and return the closest majoring
1530     multiple of 16 frames, as audioflinger expects audio buffers to
1531     be a multiple of 16 frames */
1532     size = (pcm_config_mm_ul.period_size * sample_rate) / pcm_config_mm_ul.rate;
1533     size = ((size + 15) / 16) * 16;
1534 
1535     return size * channel_count * sizeof(short);
1536 }
1537 
add_echo_reference(struct tuna_stream_out * out,struct echo_reference_itfe * reference)1538 static void add_echo_reference(struct tuna_stream_out *out,
1539                                struct echo_reference_itfe *reference)
1540 {
1541     pthread_mutex_lock(&out->lock);
1542     out->echo_reference = reference;
1543     pthread_mutex_unlock(&out->lock);
1544 }
1545 
remove_echo_reference(struct tuna_stream_out * out,struct echo_reference_itfe * reference)1546 static void remove_echo_reference(struct tuna_stream_out *out,
1547                                   struct echo_reference_itfe *reference)
1548 {
1549     pthread_mutex_lock(&out->lock);
1550     if (out->echo_reference == reference) {
1551         /* stop writing to echo reference */
1552         reference->write(reference, NULL);
1553         out->echo_reference = NULL;
1554     }
1555     pthread_mutex_unlock(&out->lock);
1556 }
1557 
put_echo_reference(struct tuna_audio_device * adev,struct echo_reference_itfe * reference)1558 static void put_echo_reference(struct tuna_audio_device *adev,
1559                           struct echo_reference_itfe *reference)
1560 {
1561     if (adev->echo_reference != NULL &&
1562             reference == adev->echo_reference) {
1563         /* echo reference is taken from the low latency output stream used
1564          * for voice use cases */
1565         if (adev->outputs[OUTPUT_LOW_LATENCY] != NULL &&
1566                 !adev->outputs[OUTPUT_LOW_LATENCY]->standby)
1567             remove_echo_reference(adev->outputs[OUTPUT_LOW_LATENCY], reference);
1568         release_echo_reference(reference);
1569         adev->echo_reference = NULL;
1570     }
1571 }
1572 
get_echo_reference(struct tuna_audio_device * adev,audio_format_t format,uint32_t channel_count,uint32_t sampling_rate)1573 static struct echo_reference_itfe *get_echo_reference(struct tuna_audio_device *adev,
1574                                                audio_format_t format,
1575                                                uint32_t channel_count,
1576                                                uint32_t sampling_rate)
1577 {
1578     put_echo_reference(adev, adev->echo_reference);
1579     /* echo reference is taken from the low latency output stream used
1580      * for voice use cases */
1581     if (adev->outputs[OUTPUT_LOW_LATENCY] != NULL &&
1582             !adev->outputs[OUTPUT_LOW_LATENCY]->standby) {
1583         struct audio_stream *stream =
1584                 &adev->outputs[OUTPUT_LOW_LATENCY]->stream.common;
1585         uint32_t wr_channel_count = popcount(stream->get_channels(stream));
1586         uint32_t wr_sampling_rate = stream->get_sample_rate(stream);
1587 
1588         int status = create_echo_reference(AUDIO_FORMAT_PCM_16_BIT,
1589                                            channel_count,
1590                                            sampling_rate,
1591                                            AUDIO_FORMAT_PCM_16_BIT,
1592                                            wr_channel_count,
1593                                            wr_sampling_rate,
1594                                            &adev->echo_reference);
1595         if (status == 0)
1596             add_echo_reference(adev->outputs[OUTPUT_LOW_LATENCY],
1597                                adev->echo_reference);
1598     }
1599     return adev->echo_reference;
1600 }
1601 
get_playback_delay(struct tuna_stream_out * out,size_t frames,struct echo_reference_buffer * buffer)1602 static int get_playback_delay(struct tuna_stream_out *out,
1603                        size_t frames,
1604                        struct echo_reference_buffer *buffer)
1605 {
1606     size_t kernel_frames;
1607     int status;
1608     int primary_pcm = 0;
1609 
1610     /* Find the first active PCM to act as primary */
1611     while ((primary_pcm < PCM_TOTAL) && !out->pcm[primary_pcm])
1612         primary_pcm++;
1613 
1614     status = pcm_get_htimestamp(out->pcm[primary_pcm], &kernel_frames, &buffer->time_stamp);
1615     if (status < 0) {
1616         buffer->time_stamp.tv_sec  = 0;
1617         buffer->time_stamp.tv_nsec = 0;
1618         buffer->delay_ns           = 0;
1619         ALOGV("get_playback_delay(): pcm_get_htimestamp error,"
1620                 "setting playbackTimestamp to 0");
1621         return status;
1622     }
1623 
1624     kernel_frames = pcm_get_buffer_size(out->pcm[primary_pcm]) - kernel_frames;
1625 
1626     /* adjust render time stamp with delay added by current driver buffer.
1627      * Add the duration of current frame as we want the render time of the last
1628      * sample being written. */
1629     buffer->delay_ns = (long)(((int64_t)(kernel_frames + frames)* 1000000000)/
1630                             MM_FULL_POWER_SAMPLING_RATE);
1631 
1632     return 0;
1633 }
1634 
out_get_sample_rate(const struct audio_stream * stream)1635 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1636 {
1637     return DEFAULT_OUT_SAMPLING_RATE;
1638 }
1639 
out_get_sample_rate_hdmi(const struct audio_stream * stream)1640 static uint32_t out_get_sample_rate_hdmi(const struct audio_stream *stream)
1641 {
1642     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1643 
1644     return out->config[PCM_HDMI].rate;
1645 }
1646 
out_set_sample_rate(struct audio_stream * stream,uint32_t rate)1647 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1648 {
1649     return 0;
1650 }
1651 
out_get_buffer_size_low_latency(const struct audio_stream * stream)1652 static size_t out_get_buffer_size_low_latency(const struct audio_stream *stream)
1653 {
1654     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1655 
1656     /* take resampling into account and return the closest majoring
1657     multiple of 16 frames, as audioflinger expects audio buffers to
1658     be a multiple of 16 frames. Note: we use the default rate here
1659     from pcm_config_tones.rate. */
1660     size_t size = (SHORT_PERIOD_SIZE * DEFAULT_OUT_SAMPLING_RATE) / pcm_config_tones.rate;
1661     size = ((size + 15) / 16) * 16;
1662     return size * audio_stream_frame_size((struct audio_stream *)stream);
1663 }
1664 
out_get_buffer_size_deep_buffer(const struct audio_stream * stream)1665 static size_t out_get_buffer_size_deep_buffer(const struct audio_stream *stream)
1666 {
1667     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1668 
1669     /* take resampling into account and return the closest majoring
1670     multiple of 16 frames, as audioflinger expects audio buffers to
1671     be a multiple of 16 frames. Note: we use the default rate here
1672     from pcm_config_mm.rate. */
1673     size_t size = (DEEP_BUFFER_SHORT_PERIOD_SIZE * DEFAULT_OUT_SAMPLING_RATE) /
1674                         pcm_config_mm.rate;
1675     size = ((size + 15) / 16) * 16;
1676     return size * audio_stream_frame_size((struct audio_stream *)stream);
1677 }
1678 
out_get_buffer_size_hdmi(const struct audio_stream * stream)1679 static size_t out_get_buffer_size_hdmi(const struct audio_stream *stream)
1680 {
1681     return HDMI_MULTI_PERIOD_SIZE * audio_stream_frame_size((struct audio_stream *)stream);
1682 }
1683 
out_get_channels(const struct audio_stream * stream)1684 static uint32_t out_get_channels(const struct audio_stream *stream)
1685 {
1686     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1687 
1688     return out->channel_mask;
1689 }
1690 
out_get_format(const struct audio_stream * stream)1691 static audio_format_t out_get_format(const struct audio_stream *stream)
1692 {
1693     return AUDIO_FORMAT_PCM_16_BIT;
1694 }
1695 
out_set_format(struct audio_stream * stream,audio_format_t format)1696 static int out_set_format(struct audio_stream *stream, audio_format_t format)
1697 {
1698     return 0;
1699 }
1700 
1701 /* must be called with hw device and output stream mutexes locked */
do_output_standby(struct tuna_stream_out * out)1702 static int do_output_standby(struct tuna_stream_out *out)
1703 {
1704     struct tuna_audio_device *adev = out->dev;
1705     int i;
1706     bool all_outputs_in_standby = true;
1707 
1708     if (!out->standby) {
1709         out->standby = 1;
1710 
1711         for (i = 0; i < PCM_TOTAL; i++) {
1712             if (out->pcm[i]) {
1713                 pcm_close(out->pcm[i]);
1714                 out->pcm[i] = NULL;
1715             }
1716         }
1717 
1718         for (i = 0; i < OUTPUT_TOTAL; i++) {
1719             if (adev->outputs[i] != NULL && !adev->outputs[i]->standby) {
1720                 all_outputs_in_standby = false;
1721                 break;
1722             }
1723         }
1724         /* if in call, don't turn off the output stage. This will
1725         be done when the call is ended */
1726         if (all_outputs_in_standby && adev->mode != AUDIO_MODE_IN_CALL) {
1727             set_route_by_array(adev->mixer, hs_output, 0);
1728             set_route_by_array(adev->mixer, hf_output, 0);
1729         }
1730 
1731         /* force standby on low latency output stream so that it can reuse HDMI driver if
1732          * necessary when restarted */
1733         if (out == adev->outputs[OUTPUT_HDMI]) {
1734             if (adev->outputs[OUTPUT_LOW_LATENCY] != NULL &&
1735                     !adev->outputs[OUTPUT_LOW_LATENCY]->standby) {
1736                 struct tuna_stream_out *ll_out = adev->outputs[OUTPUT_LOW_LATENCY];
1737                 pthread_mutex_lock(&ll_out->lock);
1738                 do_output_standby(ll_out);
1739                 pthread_mutex_unlock(&ll_out->lock);
1740             }
1741         }
1742 
1743         /* stop writing to echo reference */
1744         if (out->echo_reference != NULL) {
1745             out->echo_reference->write(out->echo_reference, NULL);
1746             out->echo_reference = NULL;
1747         }
1748     }
1749     return 0;
1750 }
1751 
out_standby(struct audio_stream * stream)1752 static int out_standby(struct audio_stream *stream)
1753 {
1754     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1755     int status;
1756 
1757     pthread_mutex_lock(&out->dev->lock);
1758     pthread_mutex_lock(&out->lock);
1759     status = do_output_standby(out);
1760     pthread_mutex_unlock(&out->lock);
1761     pthread_mutex_unlock(&out->dev->lock);
1762     return status;
1763 }
1764 
out_dump(const struct audio_stream * stream,int fd)1765 static int out_dump(const struct audio_stream *stream, int fd)
1766 {
1767     return 0;
1768 }
1769 
out_set_parameters(struct audio_stream * stream,const char * kvpairs)1770 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1771 {
1772     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1773     struct tuna_audio_device *adev = out->dev;
1774     struct tuna_stream_in *in;
1775     struct str_parms *parms;
1776     char *str;
1777     char value[32];
1778     int ret, val = 0;
1779     bool force_input_standby = false;
1780 
1781     parms = str_parms_create_str(kvpairs);
1782 
1783     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
1784     if (ret >= 0) {
1785         val = atoi(value);
1786         pthread_mutex_lock(&adev->lock);
1787         pthread_mutex_lock(&out->lock);
1788         if (((adev->devices & AUDIO_DEVICE_OUT_ALL) != val) && (val != 0)) {
1789             /* this is needed only when changing device on low latency output
1790              * as other output streams are not used for voice use cases nor
1791              * handle duplication to HDMI or SPDIF */
1792             if (out == adev->outputs[OUTPUT_LOW_LATENCY] && !out->standby) {
1793                 /* a change in output device may change the microphone selection */
1794                 if (adev->active_input &&
1795                         adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
1796                     force_input_standby = true;
1797                 }
1798                 /* force standby if moving to/from HDMI/SPDIF or if the output
1799                  * device changes when in HDMI/SPDIF mode */
1800                 /* FIXME also force standby when in call as some audio path switches do not work
1801                  * while in call and an output stream is active (e.g BT SCO => earpiece) */
1802 
1803                 /* FIXME workaround for audio being dropped when switching path without forcing standby
1804                  * (several hundred ms of audio can be lost: e.g beginning of a ringtone. We must understand
1805                  * the root cause in audio HAL, driver or ABE.
1806                 if (((val & AUDIO_DEVICE_OUT_AUX_DIGITAL) ^
1807                         (adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)) ||
1808                         ((val & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET) ^
1809                         (adev->devices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) ||
1810                         (adev->devices & (AUDIO_DEVICE_OUT_AUX_DIGITAL |
1811                                          AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)))
1812                 */
1813                 if (((val & AUDIO_DEVICE_OUT_AUX_DIGITAL) ^
1814                         (adev->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)) ||
1815                         ((val & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET) ^
1816                         (adev->devices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) ||
1817                         (adev->devices & (AUDIO_DEVICE_OUT_AUX_DIGITAL |
1818                                          AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) ||
1819                         ((val & AUDIO_DEVICE_OUT_SPEAKER) ^
1820                         (adev->devices & AUDIO_DEVICE_OUT_SPEAKER)) ||
1821                         (adev->mode == AUDIO_MODE_IN_CALL))
1822                     do_output_standby(out);
1823             }
1824             if (out != adev->outputs[OUTPUT_HDMI]) {
1825                 adev->devices &= ~AUDIO_DEVICE_OUT_ALL;
1826                 adev->devices |= val;
1827                 select_output_device(adev);
1828             }
1829         }
1830         pthread_mutex_unlock(&out->lock);
1831         if (force_input_standby) {
1832             in = adev->active_input;
1833             pthread_mutex_lock(&in->lock);
1834             do_input_standby(in);
1835             pthread_mutex_unlock(&in->lock);
1836         }
1837         pthread_mutex_unlock(&adev->lock);
1838     }
1839 
1840     str_parms_destroy(parms);
1841     return ret;
1842 }
1843 
out_get_parameters(const struct audio_stream * stream,const char * keys)1844 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
1845 {
1846     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1847 
1848     struct str_parms *query = str_parms_create_str(keys);
1849     char *str;
1850     char value[256];
1851     struct str_parms *reply = str_parms_create();
1852     size_t i, j;
1853     int ret;
1854     bool first = true;
1855 
1856     ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value, sizeof(value));
1857     if (ret >= 0) {
1858         value[0] = '\0';
1859         i = 0;
1860         while (out->sup_channel_masks[i] != 0) {
1861             for (j = 0; j < ARRAY_SIZE(out_channels_name_to_enum_table); j++) {
1862                 if (out_channels_name_to_enum_table[j].value == out->sup_channel_masks[i]) {
1863                     if (!first) {
1864                         strcat(value, "|");
1865                     }
1866                     strcat(value, out_channels_name_to_enum_table[j].name);
1867                     first = false;
1868                     break;
1869                 }
1870             }
1871             i++;
1872         }
1873         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
1874         str = strdup(str_parms_to_str(reply));
1875     } else {
1876         str = strdup(keys);
1877     }
1878     str_parms_destroy(query);
1879     str_parms_destroy(reply);
1880     return str;
1881 }
1882 
out_get_latency_low_latency(const struct audio_stream_out * stream)1883 static uint32_t out_get_latency_low_latency(const struct audio_stream_out *stream)
1884 {
1885     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1886 
1887     /*  Note: we use the default rate here from pcm_config_mm.rate */
1888     return (SHORT_PERIOD_SIZE * PLAYBACK_SHORT_PERIOD_COUNT * 1000) / pcm_config_tones.rate;
1889 }
1890 
out_get_latency_deep_buffer(const struct audio_stream_out * stream)1891 static uint32_t out_get_latency_deep_buffer(const struct audio_stream_out *stream)
1892 {
1893     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1894 
1895     /*  Note: we use the default rate here from pcm_config_mm.rate */
1896     return (DEEP_BUFFER_LONG_PERIOD_SIZE * PLAYBACK_DEEP_BUFFER_LONG_PERIOD_COUNT * 1000) /
1897                     pcm_config_mm.rate;
1898 }
1899 
out_get_latency_hdmi(const struct audio_stream_out * stream)1900 static uint32_t out_get_latency_hdmi(const struct audio_stream_out *stream)
1901 {
1902     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1903 
1904     return (HDMI_MULTI_PERIOD_SIZE * HDMI_MULTI_PERIOD_COUNT * 1000) / out->config[PCM_HDMI].rate;
1905 }
1906 
out_set_volume(struct audio_stream_out * stream,float left,float right)1907 static int out_set_volume(struct audio_stream_out *stream, float left,
1908                           float right)
1909 {
1910     return -ENOSYS;
1911 }
1912 
out_write_low_latency(struct audio_stream_out * stream,const void * buffer,size_t bytes)1913 static ssize_t out_write_low_latency(struct audio_stream_out *stream, const void* buffer,
1914                          size_t bytes)
1915 {
1916     int ret;
1917     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
1918     struct tuna_audio_device *adev = out->dev;
1919     size_t frame_size = audio_stream_frame_size(&out->stream.common);
1920     size_t in_frames = bytes / frame_size;
1921     size_t out_frames = in_frames;
1922     bool force_input_standby = false;
1923     struct tuna_stream_in *in;
1924     int i;
1925 
1926     /* acquiring hw device mutex systematically is useful if a low priority thread is waiting
1927      * on the output stream mutex - e.g. executing select_mode() while holding the hw device
1928      * mutex
1929      */
1930     pthread_mutex_lock(&adev->lock);
1931     pthread_mutex_lock(&out->lock);
1932     if (out->standby) {
1933         ret = start_output_stream_low_latency(out);
1934         if (ret != 0) {
1935             pthread_mutex_unlock(&adev->lock);
1936             goto exit;
1937         }
1938         out->standby = 0;
1939         /* a change in output device may change the microphone selection */
1940         if (adev->active_input &&
1941                 adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION)
1942             force_input_standby = true;
1943     }
1944     pthread_mutex_unlock(&adev->lock);
1945 
1946     for (i = 0; i < PCM_TOTAL; i++) {
1947         /* only use resampler if required */
1948         if (out->pcm[i] && (out->config[i].rate != DEFAULT_OUT_SAMPLING_RATE)) {
1949             out_frames = out->buffer_frames;
1950             out->resampler->resample_from_input(out->resampler,
1951                                                 (int16_t *)buffer,
1952                                                 &in_frames,
1953                                                 (int16_t *)out->buffer,
1954                                                 &out_frames);
1955             break;
1956         }
1957     }
1958 
1959     if (out->echo_reference != NULL) {
1960         struct echo_reference_buffer b;
1961         b.raw = (void *)buffer;
1962         b.frame_count = in_frames;
1963 
1964         get_playback_delay(out, out_frames, &b);
1965         out->echo_reference->write(out->echo_reference, &b);
1966     }
1967 
1968     /* Write to all active PCMs */
1969     for (i = 0; i < PCM_TOTAL; i++) {
1970         if (out->pcm[i]) {
1971             if (out->config[i].rate == DEFAULT_OUT_SAMPLING_RATE) {
1972                 /* PCM uses native sample rate */
1973                 ret = PCM_WRITE(out->pcm[i], (void *)buffer, bytes);
1974             } else {
1975                 /* PCM needs resampler */
1976                 ret = PCM_WRITE(out->pcm[i], (void *)out->buffer, out_frames * frame_size);
1977             }
1978             if (ret)
1979                 break;
1980         }
1981     }
1982 
1983 exit:
1984     pthread_mutex_unlock(&out->lock);
1985 
1986     if (ret != 0) {
1987         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
1988                out_get_sample_rate(&stream->common));
1989     }
1990 
1991     if (force_input_standby) {
1992         pthread_mutex_lock(&adev->lock);
1993         if (adev->active_input) {
1994             in = adev->active_input;
1995             pthread_mutex_lock(&in->lock);
1996             do_input_standby(in);
1997             pthread_mutex_unlock(&in->lock);
1998         }
1999         pthread_mutex_unlock(&adev->lock);
2000     }
2001 
2002     return bytes;
2003 }
2004 
out_write_deep_buffer(struct audio_stream_out * stream,const void * buffer,size_t bytes)2005 static ssize_t out_write_deep_buffer(struct audio_stream_out *stream, const void* buffer,
2006                          size_t bytes)
2007 {
2008     int ret;
2009     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
2010     struct tuna_audio_device *adev = out->dev;
2011     size_t frame_size = audio_stream_frame_size(&out->stream.common);
2012     size_t in_frames = bytes / frame_size;
2013     size_t out_frames;
2014     bool use_long_periods;
2015     int kernel_frames;
2016     void *buf;
2017 
2018     /* acquiring hw device mutex systematically is useful if a low priority thread is waiting
2019      * on the output stream mutex - e.g. executing select_mode() while holding the hw device
2020      * mutex
2021      */
2022     pthread_mutex_lock(&adev->lock);
2023     pthread_mutex_lock(&out->lock);
2024     if (out->standby) {
2025         ret = start_output_stream_deep_buffer(out);
2026         if (ret != 0) {
2027             pthread_mutex_unlock(&adev->lock);
2028             goto exit;
2029         }
2030         out->standby = 0;
2031     }
2032     use_long_periods = adev->screen_off && !adev->active_input;
2033     pthread_mutex_unlock(&adev->lock);
2034 
2035     if (use_long_periods != out->use_long_periods) {
2036         size_t period_size;
2037         size_t period_count;
2038 
2039         if (use_long_periods) {
2040             period_size = DEEP_BUFFER_LONG_PERIOD_SIZE;
2041             period_count = PLAYBACK_DEEP_BUFFER_LONG_PERIOD_COUNT;
2042         } else {
2043             period_size = DEEP_BUFFER_SHORT_PERIOD_SIZE;
2044             period_count = PLAYBACK_DEEP_BUFFER_SHORT_PERIOD_COUNT;
2045         }
2046         out->write_threshold = period_size * period_count;
2047         pcm_set_avail_min(out->pcm[PCM_NORMAL], period_size);
2048         out->use_long_periods = use_long_periods;
2049     }
2050 
2051     /* only use resampler if required */
2052     if (out->config[PCM_NORMAL].rate != DEFAULT_OUT_SAMPLING_RATE) {
2053         out_frames = out->buffer_frames;
2054         out->resampler->resample_from_input(out->resampler,
2055                                             (int16_t *)buffer,
2056                                             &in_frames,
2057                                             (int16_t *)out->buffer,
2058                                             &out_frames);
2059         buf = (void *)out->buffer;
2060     } else {
2061         out_frames = in_frames;
2062         buf = (void *)buffer;
2063     }
2064 
2065     /* do not allow more than out->write_threshold frames in kernel pcm driver buffer */
2066     do {
2067         struct timespec time_stamp;
2068 
2069         if (pcm_get_htimestamp(out->pcm[PCM_NORMAL],
2070                                (unsigned int *)&kernel_frames, &time_stamp) < 0)
2071             break;
2072         kernel_frames = pcm_get_buffer_size(out->pcm[PCM_NORMAL]) - kernel_frames;
2073 
2074         if (kernel_frames > out->write_threshold) {
2075             unsigned long time = (unsigned long)
2076                     (((int64_t)(kernel_frames - out->write_threshold) * 1000000) /
2077                             MM_FULL_POWER_SAMPLING_RATE);
2078             if (time < MIN_WRITE_SLEEP_US)
2079                 time = MIN_WRITE_SLEEP_US;
2080             usleep(time);
2081         }
2082     } while (kernel_frames > out->write_threshold);
2083 
2084     ret = pcm_mmap_write(out->pcm[PCM_NORMAL], buf, out_frames * frame_size);
2085 
2086 exit:
2087     pthread_mutex_unlock(&out->lock);
2088 
2089     if (ret != 0) {
2090         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
2091                out_get_sample_rate(&stream->common));
2092     }
2093 
2094     return bytes;
2095 }
2096 
out_write_hdmi(struct audio_stream_out * stream,const void * buffer,size_t bytes)2097 static ssize_t out_write_hdmi(struct audio_stream_out *stream, const void* buffer,
2098                          size_t bytes)
2099 {
2100     int ret;
2101     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
2102     struct tuna_audio_device *adev = out->dev;
2103     size_t frame_size = audio_stream_frame_size(&out->stream.common);
2104     size_t in_frames = bytes / frame_size;
2105 
2106     /* acquiring hw device mutex systematically is useful if a low priority thread is waiting
2107      * on the output stream mutex - e.g. executing select_mode() while holding the hw device
2108      * mutex
2109      */
2110     pthread_mutex_lock(&adev->lock);
2111     pthread_mutex_lock(&out->lock);
2112     if (out->standby) {
2113         ret = start_output_stream_hdmi(out);
2114         if (ret != 0) {
2115             pthread_mutex_unlock(&adev->lock);
2116             goto exit;
2117         }
2118         out->standby = 0;
2119     }
2120     pthread_mutex_unlock(&adev->lock);
2121 
2122     ret = pcm_write(out->pcm[PCM_HDMI],
2123                    buffer,
2124                    pcm_frames_to_bytes(out->pcm[PCM_HDMI], in_frames));
2125 
2126 exit:
2127     pthread_mutex_unlock(&out->lock);
2128 
2129     if (ret != 0) {
2130         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
2131                out_get_sample_rate_hdmi(&stream->common));
2132     }
2133     /* FIXME: workaround for HDMI multi channel channel swap on first playback after opening
2134      * the output stream: force reopening the pcm driver after writing a few periods. */
2135     if ((out->restart_periods_cnt > 0) &&
2136             (--out->restart_periods_cnt == 0))
2137         out_standby(&stream->common);
2138 
2139     return bytes;
2140 }
2141 
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)2142 static int out_get_render_position(const struct audio_stream_out *stream,
2143                                    uint32_t *dsp_frames)
2144 {
2145     return -EINVAL;
2146 }
2147 
out_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)2148 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
2149 {
2150     return 0;
2151 }
2152 
out_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)2153 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
2154 {
2155     return 0;
2156 }
2157 
2158 /** audio_stream_in implementation **/
2159 
2160 /* must be called with hw device and input stream mutexes locked */
start_input_stream(struct tuna_stream_in * in)2161 static int start_input_stream(struct tuna_stream_in *in)
2162 {
2163     int ret = 0;
2164     struct tuna_audio_device *adev = in->dev;
2165 
2166     adev->active_input = in;
2167 
2168     if (adev->mode != AUDIO_MODE_IN_CALL) {
2169         adev->devices &= ~AUDIO_DEVICE_IN_ALL;
2170         adev->devices |= in->device;
2171         select_input_device(adev);
2172     }
2173 
2174     if (in->aux_channels_changed)
2175     {
2176         in->aux_channels_changed = false;
2177         in->config.channels = popcount(in->main_channels | in->aux_channels);
2178 
2179         if (in->resampler) {
2180             /* release and recreate the resampler with the new number of channel of the input */
2181             release_resampler(in->resampler);
2182             in->resampler = NULL;
2183             ret = create_resampler(in->config.rate,
2184                                in->requested_rate,
2185                                in->config.channels,
2186                                RESAMPLER_QUALITY_DEFAULT,
2187                                &in->buf_provider,
2188                                &in->resampler);
2189         }
2190         ALOGV("start_input_stream(): New channel configuration, "
2191                 "main_channels = [%04x], aux_channels = [%04x], config.channels = %d",
2192                 in->main_channels, in->aux_channels, in->config.channels);
2193     }
2194 
2195     if (in->need_echo_reference && in->echo_reference == NULL)
2196         in->echo_reference = get_echo_reference(adev,
2197                                         AUDIO_FORMAT_PCM_16_BIT,
2198                                         in->config.channels,
2199                                         in->requested_rate);
2200 
2201     /* this assumes routing is done previously */
2202     in->pcm = pcm_open(0, PORT_MM2_UL, PCM_IN, &in->config);
2203     if (!pcm_is_ready(in->pcm)) {
2204         ALOGE("cannot open pcm_in driver: %s", pcm_get_error(in->pcm));
2205         pcm_close(in->pcm);
2206         adev->active_input = NULL;
2207         return -ENOMEM;
2208     }
2209 
2210     /* force read and proc buf reallocation case of frame size or channel count change */
2211     in->read_buf_frames = 0;
2212     in->read_buf_size = 0;
2213     in->proc_buf_frames = 0;
2214     in->proc_buf_size = 0;
2215     /* if no supported sample rate is available, use the resampler */
2216     if (in->resampler) {
2217         in->resampler->reset(in->resampler);
2218     }
2219     return 0;
2220 }
2221 
in_get_sample_rate(const struct audio_stream * stream)2222 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
2223 {
2224     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
2225 
2226     return in->requested_rate;
2227 }
2228 
in_set_sample_rate(struct audio_stream * stream,uint32_t rate)2229 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
2230 {
2231     return 0;
2232 }
2233 
in_get_buffer_size(const struct audio_stream * stream)2234 static size_t in_get_buffer_size(const struct audio_stream *stream)
2235 {
2236     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
2237 
2238     return get_input_buffer_size(in->requested_rate,
2239                                  AUDIO_FORMAT_PCM_16_BIT,
2240                                  popcount(in->main_channels));
2241 }
2242 
in_get_channels(const struct audio_stream * stream)2243 static uint32_t in_get_channels(const struct audio_stream *stream)
2244 {
2245     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
2246 
2247     return in->main_channels;
2248 }
2249 
in_get_format(const struct audio_stream * stream)2250 static audio_format_t in_get_format(const struct audio_stream *stream)
2251 {
2252     return AUDIO_FORMAT_PCM_16_BIT;
2253 }
2254 
in_set_format(struct audio_stream * stream,audio_format_t format)2255 static int in_set_format(struct audio_stream *stream, audio_format_t format)
2256 {
2257     return 0;
2258 }
2259 
2260 /* must be called with hw device and input stream mutexes locked */
do_input_standby(struct tuna_stream_in * in)2261 static int do_input_standby(struct tuna_stream_in *in)
2262 {
2263     struct tuna_audio_device *adev = in->dev;
2264 
2265     if (!in->standby) {
2266         pcm_close(in->pcm);
2267         in->pcm = NULL;
2268 
2269         adev->active_input = 0;
2270         if (adev->mode != AUDIO_MODE_IN_CALL) {
2271             adev->devices &= ~AUDIO_DEVICE_IN_ALL;
2272             select_input_device(adev);
2273         }
2274 
2275         if (in->echo_reference != NULL) {
2276             /* stop reading from echo reference */
2277             in->echo_reference->read(in->echo_reference, NULL);
2278             put_echo_reference(adev, in->echo_reference);
2279             in->echo_reference = NULL;
2280         }
2281 
2282         in->standby = 1;
2283     }
2284     return 0;
2285 }
2286 
in_standby(struct audio_stream * stream)2287 static int in_standby(struct audio_stream *stream)
2288 {
2289     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
2290     int status;
2291 
2292     pthread_mutex_lock(&in->dev->lock);
2293     pthread_mutex_lock(&in->lock);
2294     status = do_input_standby(in);
2295     pthread_mutex_unlock(&in->lock);
2296     pthread_mutex_unlock(&in->dev->lock);
2297     return status;
2298 }
2299 
in_dump(const struct audio_stream * stream,int fd)2300 static int in_dump(const struct audio_stream *stream, int fd)
2301 {
2302     return 0;
2303 }
2304 
in_set_parameters(struct audio_stream * stream,const char * kvpairs)2305 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
2306 {
2307     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
2308     struct tuna_audio_device *adev = in->dev;
2309     struct str_parms *parms;
2310     char *str;
2311     char value[32];
2312     int ret, val = 0;
2313     bool do_standby = false;
2314 
2315     parms = str_parms_create_str(kvpairs);
2316 
2317     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
2318 
2319     pthread_mutex_lock(&adev->lock);
2320     pthread_mutex_lock(&in->lock);
2321     if (ret >= 0) {
2322         val = atoi(value);
2323         /* no audio source uses val == 0 */
2324         if ((in->source != val) && (val != 0)) {
2325             in->source = val;
2326             do_standby = true;
2327         }
2328     }
2329 
2330     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
2331     if (ret >= 0) {
2332         val = atoi(value);
2333         if ((in->device != val) && (val != 0)) {
2334             in->device = val;
2335             do_standby = true;
2336             /* make sure new device selection is incompatible with multi-mic pre processing
2337              * configuration */
2338             in_update_aux_channels(in, NULL);
2339         }
2340     }
2341 
2342     if (do_standby)
2343         do_input_standby(in);
2344     pthread_mutex_unlock(&in->lock);
2345     pthread_mutex_unlock(&adev->lock);
2346 
2347     str_parms_destroy(parms);
2348     return ret;
2349 }
2350 
in_get_parameters(const struct audio_stream * stream,const char * keys)2351 static char * in_get_parameters(const struct audio_stream *stream,
2352                                 const char *keys)
2353 {
2354     return strdup("");
2355 }
2356 
in_set_gain(struct audio_stream_in * stream,float gain)2357 static int in_set_gain(struct audio_stream_in *stream, float gain)
2358 {
2359     return 0;
2360 }
2361 
get_capture_delay(struct tuna_stream_in * in,size_t frames,struct echo_reference_buffer * buffer)2362 static void get_capture_delay(struct tuna_stream_in *in,
2363                        size_t frames,
2364                        struct echo_reference_buffer *buffer)
2365 {
2366 
2367     /* read frames available in kernel driver buffer */
2368     size_t kernel_frames;
2369     struct timespec tstamp;
2370     long buf_delay;
2371     long rsmp_delay;
2372     long kernel_delay;
2373     long delay_ns;
2374 
2375     if (pcm_get_htimestamp(in->pcm, &kernel_frames, &tstamp) < 0) {
2376         buffer->time_stamp.tv_sec  = 0;
2377         buffer->time_stamp.tv_nsec = 0;
2378         buffer->delay_ns           = 0;
2379         ALOGW("read get_capture_delay(): pcm_htimestamp error");
2380         return;
2381     }
2382 
2383     /* read frames available in audio HAL input buffer
2384      * add number of frames being read as we want the capture time of first sample
2385      * in current buffer */
2386     /* frames in in->buffer are at driver sampling rate while frames in in->proc_buf are
2387      * at requested sampling rate */
2388     buf_delay = (long)(((int64_t)(in->read_buf_frames) * 1000000000) / in->config.rate +
2389                        ((int64_t)(in->proc_buf_frames) * 1000000000) /
2390                            in->requested_rate);
2391 
2392     /* add delay introduced by resampler */
2393     rsmp_delay = 0;
2394     if (in->resampler) {
2395         rsmp_delay = in->resampler->delay_ns(in->resampler);
2396     }
2397 
2398     kernel_delay = (long)(((int64_t)kernel_frames * 1000000000) / in->config.rate);
2399 
2400     delay_ns = kernel_delay + buf_delay + rsmp_delay;
2401 
2402     buffer->time_stamp = tstamp;
2403     buffer->delay_ns   = delay_ns;
2404     ALOGV("get_capture_delay time_stamp = [%ld].[%ld], delay_ns: [%d],"
2405          " kernel_delay:[%ld], buf_delay:[%ld], rsmp_delay:[%ld], kernel_frames:[%d], "
2406          "in->read_buf_frames:[%d], in->proc_buf_frames:[%d], frames:[%d]",
2407          buffer->time_stamp.tv_sec , buffer->time_stamp.tv_nsec, buffer->delay_ns,
2408          kernel_delay, buf_delay, rsmp_delay, kernel_frames,
2409          in->read_buf_frames, in->proc_buf_frames, frames);
2410 
2411 }
2412 
update_echo_reference(struct tuna_stream_in * in,size_t frames)2413 static int32_t update_echo_reference(struct tuna_stream_in *in, size_t frames)
2414 {
2415     struct echo_reference_buffer b;
2416     b.delay_ns = 0;
2417 
2418     ALOGV("update_echo_reference, frames = [%d], in->ref_buf_frames = [%d],  "
2419           "b.frame_count = [%d]",
2420          frames, in->ref_buf_frames, frames - in->ref_buf_frames);
2421     if (in->ref_buf_frames < frames) {
2422         if (in->ref_buf_size < frames) {
2423             in->ref_buf_size = frames;
2424             in->ref_buf = (int16_t *)realloc(in->ref_buf, pcm_frames_to_bytes(in->pcm, frames));
2425             ALOG_ASSERT((in->ref_buf != NULL),
2426                         "update_echo_reference() failed to reallocate ref_buf");
2427             ALOGV("update_echo_reference(): ref_buf %p extended to %d bytes",
2428                       in->ref_buf, pcm_frames_to_bytes(in->pcm, frames));
2429         }
2430         b.frame_count = frames - in->ref_buf_frames;
2431         b.raw = (void *)(in->ref_buf + in->ref_buf_frames * in->config.channels);
2432 
2433         get_capture_delay(in, frames, &b);
2434 
2435         if (in->echo_reference->read(in->echo_reference, &b) == 0)
2436         {
2437             in->ref_buf_frames += b.frame_count;
2438             ALOGV("update_echo_reference(): in->ref_buf_frames:[%d], "
2439                     "in->ref_buf_size:[%d], frames:[%d], b.frame_count:[%d]",
2440                  in->ref_buf_frames, in->ref_buf_size, frames, b.frame_count);
2441         }
2442     } else
2443         ALOGW("update_echo_reference(): NOT enough frames to read ref buffer");
2444     return b.delay_ns;
2445 }
2446 
set_preprocessor_param(effect_handle_t handle,effect_param_t * param)2447 static int set_preprocessor_param(effect_handle_t handle,
2448                            effect_param_t *param)
2449 {
2450     uint32_t size = sizeof(int);
2451     uint32_t psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
2452                         param->vsize;
2453 
2454     int status = (*handle)->command(handle,
2455                                    EFFECT_CMD_SET_PARAM,
2456                                    sizeof (effect_param_t) + psize,
2457                                    param,
2458                                    &size,
2459                                    &param->status);
2460     if (status == 0)
2461         status = param->status;
2462 
2463     return status;
2464 }
2465 
set_preprocessor_echo_delay(effect_handle_t handle,int32_t delay_us)2466 static int set_preprocessor_echo_delay(effect_handle_t handle,
2467                                      int32_t delay_us)
2468 {
2469     uint32_t buf[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
2470     effect_param_t *param = (effect_param_t *)buf;
2471 
2472     param->psize = sizeof(uint32_t);
2473     param->vsize = sizeof(uint32_t);
2474     *(uint32_t *)param->data = AEC_PARAM_ECHO_DELAY;
2475     *((int32_t *)param->data + 1) = delay_us;
2476 
2477     return set_preprocessor_param(handle, param);
2478 }
2479 
push_echo_reference(struct tuna_stream_in * in,size_t frames)2480 static void push_echo_reference(struct tuna_stream_in *in, size_t frames)
2481 {
2482     /* read frames from echo reference buffer and update echo delay
2483      * in->ref_buf_frames is updated with frames available in in->ref_buf */
2484     int32_t delay_us = update_echo_reference(in, frames)/1000;
2485     int i;
2486     audio_buffer_t buf;
2487 
2488     if (in->ref_buf_frames < frames)
2489         frames = in->ref_buf_frames;
2490 
2491     buf.frameCount = frames;
2492     buf.raw = in->ref_buf;
2493 
2494     for (i = 0; i < in->num_preprocessors; i++) {
2495         if ((*in->preprocessors[i].effect_itfe)->process_reverse == NULL)
2496             continue;
2497 
2498         (*in->preprocessors[i].effect_itfe)->process_reverse(in->preprocessors[i].effect_itfe,
2499                                                &buf,
2500                                                NULL);
2501         set_preprocessor_echo_delay(in->preprocessors[i].effect_itfe, delay_us);
2502     }
2503 
2504     in->ref_buf_frames -= buf.frameCount;
2505     if (in->ref_buf_frames) {
2506         memcpy(in->ref_buf,
2507                in->ref_buf + buf.frameCount * in->config.channels,
2508                in->ref_buf_frames * in->config.channels * sizeof(int16_t));
2509     }
2510 }
2511 
get_next_buffer(struct resampler_buffer_provider * buffer_provider,struct resampler_buffer * buffer)2512 static int get_next_buffer(struct resampler_buffer_provider *buffer_provider,
2513                                    struct resampler_buffer* buffer)
2514 {
2515     struct tuna_stream_in *in;
2516 
2517     if (buffer_provider == NULL || buffer == NULL)
2518         return -EINVAL;
2519 
2520     in = (struct tuna_stream_in *)((char *)buffer_provider -
2521                                    offsetof(struct tuna_stream_in, buf_provider));
2522 
2523     if (in->pcm == NULL) {
2524         buffer->raw = NULL;
2525         buffer->frame_count = 0;
2526         in->read_status = -ENODEV;
2527         return -ENODEV;
2528     }
2529 
2530     if (in->read_buf_frames == 0) {
2531         size_t size_in_bytes = pcm_frames_to_bytes(in->pcm, in->config.period_size);
2532         if (in->read_buf_size < in->config.period_size) {
2533             in->read_buf_size = in->config.period_size;
2534             in->read_buf = (int16_t *) realloc(in->read_buf, size_in_bytes);
2535             ALOG_ASSERT((in->read_buf != NULL),
2536                         "get_next_buffer() failed to reallocate read_buf");
2537             ALOGV("get_next_buffer(): read_buf %p extended to %d bytes",
2538                   in->read_buf, size_in_bytes);
2539         }
2540 
2541         in->read_status = pcm_read(in->pcm, (void*)in->read_buf, size_in_bytes);
2542 
2543         if (in->read_status != 0) {
2544             ALOGE("get_next_buffer() pcm_read error %d", in->read_status);
2545             buffer->raw = NULL;
2546             buffer->frame_count = 0;
2547             return in->read_status;
2548         }
2549         in->read_buf_frames = in->config.period_size;
2550     }
2551 
2552     buffer->frame_count = (buffer->frame_count > in->read_buf_frames) ?
2553                                 in->read_buf_frames : buffer->frame_count;
2554     buffer->i16 = in->read_buf + (in->config.period_size - in->read_buf_frames) *
2555                                                 in->config.channels;
2556 
2557     return in->read_status;
2558 
2559 }
2560 
release_buffer(struct resampler_buffer_provider * buffer_provider,struct resampler_buffer * buffer)2561 static void release_buffer(struct resampler_buffer_provider *buffer_provider,
2562                                   struct resampler_buffer* buffer)
2563 {
2564     struct tuna_stream_in *in;
2565 
2566     if (buffer_provider == NULL || buffer == NULL)
2567         return;
2568 
2569     in = (struct tuna_stream_in *)((char *)buffer_provider -
2570                                    offsetof(struct tuna_stream_in, buf_provider));
2571 
2572     in->read_buf_frames -= buffer->frame_count;
2573 }
2574 
2575 /* read_frames() reads frames from kernel driver, down samples to capture rate
2576  * if necessary and output the number of frames requested to the buffer specified */
read_frames(struct tuna_stream_in * in,void * buffer,ssize_t frames)2577 static ssize_t read_frames(struct tuna_stream_in *in, void *buffer, ssize_t frames)
2578 {
2579     ssize_t frames_wr = 0;
2580 
2581     while (frames_wr < frames) {
2582         size_t frames_rd = frames - frames_wr;
2583         if (in->resampler != NULL) {
2584             in->resampler->resample_from_provider(in->resampler,
2585                                                   (int16_t *)((char *)buffer +
2586                                                       pcm_frames_to_bytes(in->pcm ,frames_wr)),
2587                                                   &frames_rd);
2588 
2589         } else {
2590             struct resampler_buffer buf = {
2591                     { raw : NULL, },
2592                     frame_count : frames_rd,
2593             };
2594             get_next_buffer(&in->buf_provider, &buf);
2595             if (buf.raw != NULL) {
2596                 memcpy((char *)buffer +
2597                             pcm_frames_to_bytes(in->pcm, frames_wr),
2598                         buf.raw,
2599                         pcm_frames_to_bytes(in->pcm, buf.frame_count));
2600                 frames_rd = buf.frame_count;
2601             }
2602             release_buffer(&in->buf_provider, &buf);
2603         }
2604         /* in->read_status is updated by getNextBuffer() also called by
2605          * in->resampler->resample_from_provider() */
2606         if (in->read_status != 0)
2607             return in->read_status;
2608 
2609         frames_wr += frames_rd;
2610     }
2611     return frames_wr;
2612 }
2613 
2614 /* process_frames() reads frames from kernel driver (via read_frames()),
2615  * calls the active audio pre processings and output the number of frames requested
2616  * to the buffer specified */
process_frames(struct tuna_stream_in * in,void * buffer,ssize_t frames)2617 static ssize_t process_frames(struct tuna_stream_in *in, void* buffer, ssize_t frames)
2618 {
2619     ssize_t frames_wr = 0;
2620     audio_buffer_t in_buf;
2621     audio_buffer_t out_buf;
2622     int i;
2623     bool has_aux_channels = (~in->main_channels & in->aux_channels);
2624     void *proc_buf_out;
2625 
2626     if (has_aux_channels)
2627         proc_buf_out = in->proc_buf_out;
2628     else
2629         proc_buf_out = buffer;
2630 
2631     /* since all the processing below is done in frames and using the config.channels
2632      * as the number of channels, no changes is required in case aux_channels are present */
2633     while (frames_wr < frames) {
2634         /* first reload enough frames at the end of process input buffer */
2635         if (in->proc_buf_frames < (size_t)frames) {
2636             ssize_t frames_rd;
2637 
2638             if (in->proc_buf_size < (size_t)frames) {
2639                 size_t size_in_bytes = pcm_frames_to_bytes(in->pcm, frames);
2640 
2641                 in->proc_buf_size = (size_t)frames;
2642                 in->proc_buf_in = (int16_t *)realloc(in->proc_buf_in, size_in_bytes);
2643                 ALOG_ASSERT((in->proc_buf_in != NULL),
2644                             "process_frames() failed to reallocate proc_buf_in");
2645                 if (has_aux_channels) {
2646                     in->proc_buf_out = (int16_t *)realloc(in->proc_buf_out, size_in_bytes);
2647                     ALOG_ASSERT((in->proc_buf_out != NULL),
2648                                 "process_frames() failed to reallocate proc_buf_out");
2649                     proc_buf_out = in->proc_buf_out;
2650                 }
2651                 ALOGV("process_frames(): proc_buf_in %p extended to %d bytes",
2652                      in->proc_buf_in, size_in_bytes);
2653             }
2654             frames_rd = read_frames(in,
2655                                     in->proc_buf_in +
2656                                         in->proc_buf_frames * in->config.channels,
2657                                     frames - in->proc_buf_frames);
2658             if (frames_rd < 0) {
2659                 frames_wr = frames_rd;
2660                 break;
2661             }
2662             in->proc_buf_frames += frames_rd;
2663         }
2664 
2665         if (in->echo_reference != NULL)
2666             push_echo_reference(in, in->proc_buf_frames);
2667 
2668          /* in_buf.frameCount and out_buf.frameCount indicate respectively
2669           * the maximum number of frames to be consumed and produced by process() */
2670         in_buf.frameCount = in->proc_buf_frames;
2671         in_buf.s16 = in->proc_buf_in;
2672         out_buf.frameCount = frames - frames_wr;
2673         out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * in->config.channels;
2674 
2675         /* FIXME: this works because of current pre processing library implementation that
2676          * does the actual process only when the last enabled effect process is called.
2677          * The generic solution is to have an output buffer for each effect and pass it as
2678          * input to the next.
2679          */
2680         for (i = 0; i < in->num_preprocessors; i++) {
2681             (*in->preprocessors[i].effect_itfe)->process(in->preprocessors[i].effect_itfe,
2682                                                &in_buf,
2683                                                &out_buf);
2684         }
2685 
2686         /* process() has updated the number of frames consumed and produced in
2687          * in_buf.frameCount and out_buf.frameCount respectively
2688          * move remaining frames to the beginning of in->proc_buf_in */
2689         in->proc_buf_frames -= in_buf.frameCount;
2690 
2691         if (in->proc_buf_frames) {
2692             memcpy(in->proc_buf_in,
2693                    in->proc_buf_in + in_buf.frameCount * in->config.channels,
2694                    in->proc_buf_frames * in->config.channels * sizeof(int16_t));
2695         }
2696 
2697         /* if not enough frames were passed to process(), read more and retry. */
2698         if (out_buf.frameCount == 0) {
2699             ALOGW("No frames produced by preproc");
2700             continue;
2701         }
2702 
2703         if ((frames_wr + (ssize_t)out_buf.frameCount) <= frames) {
2704             frames_wr += out_buf.frameCount;
2705         } else {
2706             /* The effect does not comply to the API. In theory, we should never end up here! */
2707             ALOGE("preprocessing produced too many frames: %d + %d  > %d !",
2708                   (unsigned int)frames_wr, out_buf.frameCount, (unsigned int)frames);
2709             frames_wr = frames;
2710         }
2711     }
2712 
2713     /* Remove aux_channels that have been added on top of main_channels
2714      * Assumption is made that the channels are interleaved and that the main
2715      * channels are first. */
2716     if (has_aux_channels)
2717     {
2718         size_t src_channels = in->config.channels;
2719         size_t dst_channels = popcount(in->main_channels);
2720         int16_t* src_buffer = (int16_t *)proc_buf_out;
2721         int16_t* dst_buffer = (int16_t *)buffer;
2722 
2723         if (dst_channels == 1) {
2724             for (i = frames_wr; i > 0; i--)
2725             {
2726                 *dst_buffer++ = *src_buffer;
2727                 src_buffer += src_channels;
2728             }
2729         } else {
2730             for (i = frames_wr; i > 0; i--)
2731             {
2732                 memcpy(dst_buffer, src_buffer, dst_channels*sizeof(int16_t));
2733                 dst_buffer += dst_channels;
2734                 src_buffer += src_channels;
2735             }
2736         }
2737     }
2738 
2739     return frames_wr;
2740 }
2741 
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)2742 static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
2743 
2744                        size_t bytes)
2745 {
2746     int ret = 0;
2747     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
2748     struct tuna_audio_device *adev = in->dev;
2749     size_t frames_rq = bytes / audio_stream_frame_size(&stream->common);
2750 
2751     /* acquiring hw device mutex systematically is useful if a low priority thread is waiting
2752      * on the input stream mutex - e.g. executing select_mode() while holding the hw device
2753      * mutex
2754      */
2755     pthread_mutex_lock(&adev->lock);
2756     pthread_mutex_lock(&in->lock);
2757     if (in->standby) {
2758         ret = start_input_stream(in);
2759         if (ret == 0)
2760             in->standby = 0;
2761     }
2762     pthread_mutex_unlock(&adev->lock);
2763 
2764     if (ret < 0)
2765         goto exit;
2766 
2767     if (in->num_preprocessors != 0)
2768         ret = process_frames(in, buffer, frames_rq);
2769     else if (in->resampler != NULL)
2770         ret = read_frames(in, buffer, frames_rq);
2771     else
2772         ret = pcm_read(in->pcm, buffer, bytes);
2773 
2774     if (ret > 0)
2775         ret = 0;
2776 
2777     if (ret == 0 && adev->mic_mute)
2778         memset(buffer, 0, bytes);
2779 
2780 exit:
2781     if (ret < 0)
2782         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
2783                in_get_sample_rate(&stream->common));
2784 
2785     pthread_mutex_unlock(&in->lock);
2786     return bytes;
2787 }
2788 
in_get_input_frames_lost(struct audio_stream_in * stream)2789 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
2790 {
2791     return 0;
2792 }
2793 
2794 #define GET_COMMAND_STATUS(status, fct_status, cmd_status) \
2795             do {                                           \
2796                 if (fct_status != 0)                       \
2797                     status = fct_status;                   \
2798                 else if (cmd_status != 0)                  \
2799                     status = cmd_status;                   \
2800             } while(0)
2801 
in_configure_reverse(struct tuna_stream_in * in)2802 static int in_configure_reverse(struct tuna_stream_in *in)
2803 {
2804     int32_t cmd_status;
2805     uint32_t size = sizeof(int);
2806     effect_config_t config;
2807     int32_t status = 0;
2808     int32_t fct_status = 0;
2809     int i;
2810 
2811     if (in->num_preprocessors > 0) {
2812         config.inputCfg.channels = in->main_channels;
2813         config.outputCfg.channels = in->main_channels;
2814         config.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
2815         config.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
2816         config.inputCfg.samplingRate = in->requested_rate;
2817         config.outputCfg.samplingRate = in->requested_rate;
2818         config.inputCfg.mask =
2819                 ( EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT );
2820         config.outputCfg.mask =
2821                 ( EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT );
2822 
2823         for (i = 0; i < in->num_preprocessors; i++)
2824         {
2825             if ((*in->preprocessors[i].effect_itfe)->process_reverse == NULL)
2826                 continue;
2827             fct_status = (*(in->preprocessors[i].effect_itfe))->command(
2828                                                         in->preprocessors[i].effect_itfe,
2829                                                         EFFECT_CMD_SET_CONFIG_REVERSE,
2830                                                         sizeof(effect_config_t),
2831                                                         &config,
2832                                                         &size,
2833                                                         &cmd_status);
2834             GET_COMMAND_STATUS(status, fct_status, cmd_status);
2835         }
2836     }
2837     return status;
2838 }
2839 
2840 #define MAX_NUM_CHANNEL_CONFIGS 10
2841 
in_read_audio_effect_channel_configs(struct tuna_stream_in * in,struct effect_info_s * effect_info)2842 static void in_read_audio_effect_channel_configs(struct tuna_stream_in *in,
2843                                                  struct effect_info_s *effect_info)
2844 {
2845     /* size and format of the cmd are defined in hardware/audio_effect.h */
2846     effect_handle_t effect = effect_info->effect_itfe;
2847     uint32_t cmd_size = 2 * sizeof(uint32_t);
2848     uint32_t cmd[] = { EFFECT_FEATURE_AUX_CHANNELS, MAX_NUM_CHANNEL_CONFIGS };
2849     /* reply = status + number of configs (n) + n x channel_config_t */
2850     uint32_t reply_size =
2851             2 * sizeof(uint32_t) + (MAX_NUM_CHANNEL_CONFIGS * sizeof(channel_config_t));
2852     int32_t reply[reply_size];
2853     int32_t cmd_status;
2854 
2855     ALOG_ASSERT((effect_info->num_channel_configs == 0),
2856                 "in_read_audio_effect_channel_configs() num_channel_configs not cleared");
2857     ALOG_ASSERT((effect_info->channel_configs == NULL),
2858                 "in_read_audio_effect_channel_configs() channel_configs not cleared");
2859 
2860     /* if this command is not supported, then the effect is supposed to return -EINVAL.
2861      * This error will be interpreted as if the effect supports the main_channels but does not
2862      * support any aux_channels */
2863     cmd_status = (*effect)->command(effect,
2864                                 EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS,
2865                                 cmd_size,
2866                                 (void*)&cmd,
2867                                 &reply_size,
2868                                 (void*)&reply);
2869 
2870     if (cmd_status != 0) {
2871         ALOGV("in_read_audio_effect_channel_configs(): "
2872                 "fx->command returned %d", cmd_status);
2873         return;
2874     }
2875 
2876     if (reply[0] != 0) {
2877         ALOGW("in_read_audio_effect_channel_configs(): "
2878                 "command EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS error %d num configs %d",
2879                 reply[0], (reply[0] == -ENOMEM) ? reply[1] : MAX_NUM_CHANNEL_CONFIGS);
2880         return;
2881     }
2882 
2883     /* the feature is not supported */
2884     ALOGV("in_read_audio_effect_channel_configs()(): "
2885             "Feature supported and adding %d channel configs to the list", reply[1]);
2886     effect_info->num_channel_configs = reply[1];
2887     effect_info->channel_configs =
2888             (channel_config_t *) malloc(sizeof(channel_config_t) * reply[1]); /* n x configs */
2889     memcpy(effect_info->channel_configs, (reply + 2), sizeof(channel_config_t) * reply[1]);
2890 }
2891 
2892 
in_get_aux_channels(struct tuna_stream_in * in)2893 static uint32_t in_get_aux_channels(struct tuna_stream_in *in)
2894 {
2895     int i;
2896     channel_config_t new_chcfg = {0, 0};
2897 
2898     if (in->num_preprocessors == 0)
2899         return 0;
2900 
2901     /* do not enable dual mic configurations when capturing from other microphones than
2902      * main or sub */
2903     if (!(in->device & (AUDIO_DEVICE_IN_BUILTIN_MIC | AUDIO_DEVICE_IN_BACK_MIC)))
2904         return 0;
2905 
2906     /* retain most complex aux channels configuration compatible with requested main channels and
2907      * supported by audio driver and all pre processors */
2908     for (i = 0; i < NUM_IN_AUX_CNL_CONFIGS; i++) {
2909         channel_config_t *cur_chcfg = &in_aux_cnl_configs[i];
2910         if (cur_chcfg->main_channels == in->main_channels) {
2911             size_t match_cnt;
2912             size_t idx_preproc;
2913             for (idx_preproc = 0, match_cnt = 0;
2914                  /* no need to continue if at least one preprocessor doesn't match */
2915                  idx_preproc < (size_t)in->num_preprocessors && match_cnt == idx_preproc;
2916                  idx_preproc++) {
2917                 struct effect_info_s *effect_info = &in->preprocessors[idx_preproc];
2918                 size_t idx_chcfg;
2919 
2920                 for (idx_chcfg = 0; idx_chcfg < effect_info->num_channel_configs; idx_chcfg++) {
2921                     if (memcmp(effect_info->channel_configs + idx_chcfg,
2922                                cur_chcfg,
2923                                sizeof(channel_config_t)) == 0) {
2924                         match_cnt++;
2925                         break;
2926                     }
2927                 }
2928             }
2929             /* if all preprocessors match, we have a candidate */
2930             if (match_cnt == (size_t)in->num_preprocessors) {
2931                 /* retain most complex aux channels configuration */
2932                 if (popcount(cur_chcfg->aux_channels) > popcount(new_chcfg.aux_channels)) {
2933                     new_chcfg = *cur_chcfg;
2934                 }
2935             }
2936         }
2937     }
2938 
2939     ALOGV("in_get_aux_channels(): return %04x", new_chcfg.aux_channels);
2940 
2941     return new_chcfg.aux_channels;
2942 }
2943 
in_configure_effect_channels(effect_handle_t effect,channel_config_t * channel_config)2944 static int in_configure_effect_channels(effect_handle_t effect,
2945                                         channel_config_t *channel_config)
2946 {
2947     int status = 0;
2948     int fct_status;
2949     int32_t cmd_status;
2950     uint32_t reply_size;
2951     effect_config_t config;
2952     uint32_t cmd[(sizeof(uint32_t) + sizeof(channel_config_t) - 1) / sizeof(uint32_t) + 1];
2953 
2954     ALOGV("in_configure_effect_channels(): configure effect with channels: [%04x][%04x]",
2955             channel_config->main_channels,
2956             channel_config->aux_channels);
2957 
2958     config.inputCfg.mask = EFFECT_CONFIG_CHANNELS;
2959     config.outputCfg.mask = EFFECT_CONFIG_CHANNELS;
2960     reply_size = sizeof(effect_config_t);
2961     fct_status = (*effect)->command(effect,
2962                                 EFFECT_CMD_GET_CONFIG,
2963                                 0,
2964                                 NULL,
2965                                 &reply_size,
2966                                 &config);
2967     if (fct_status != 0) {
2968         ALOGE("in_configure_effect_channels(): EFFECT_CMD_GET_CONFIG failed");
2969         return fct_status;
2970     }
2971 
2972     config.inputCfg.channels = channel_config->main_channels | channel_config->aux_channels;
2973     config.outputCfg.channels = config.inputCfg.channels;
2974     reply_size = sizeof(uint32_t);
2975     fct_status = (*effect)->command(effect,
2976                                     EFFECT_CMD_SET_CONFIG,
2977                                     sizeof(effect_config_t),
2978                                     &config,
2979                                     &reply_size,
2980                                     &cmd_status);
2981     GET_COMMAND_STATUS(status, fct_status, cmd_status);
2982 
2983     cmd[0] = EFFECT_FEATURE_AUX_CHANNELS;
2984     memcpy(cmd + 1, channel_config, sizeof(channel_config_t));
2985     reply_size = sizeof(uint32_t);
2986     fct_status = (*effect)->command(effect,
2987                                 EFFECT_CMD_SET_FEATURE_CONFIG,
2988                                 sizeof(cmd), //sizeof(uint32_t) + sizeof(channel_config_t),
2989                                 cmd,
2990                                 &reply_size,
2991                                 &cmd_status);
2992     GET_COMMAND_STATUS(status, fct_status, cmd_status);
2993 
2994     /* some implementations need to be re-enabled after a config change */
2995     reply_size = sizeof(uint32_t);
2996     fct_status = (*effect)->command(effect,
2997                                   EFFECT_CMD_ENABLE,
2998                                   0,
2999                                   NULL,
3000                                   &reply_size,
3001                                   &cmd_status);
3002     GET_COMMAND_STATUS(status, fct_status, cmd_status);
3003 
3004     return status;
3005 }
3006 
in_reconfigure_channels(struct tuna_stream_in * in,effect_handle_t effect,channel_config_t * channel_config,bool config_changed)3007 static int in_reconfigure_channels(struct tuna_stream_in *in,
3008                                    effect_handle_t effect,
3009                                    channel_config_t *channel_config,
3010                                    bool config_changed) {
3011 
3012     int status = 0;
3013 
3014     ALOGV("in_reconfigure_channels(): config_changed %d effect %p",
3015           config_changed, effect);
3016 
3017     /* if config changed, reconfigure all previously added effects */
3018     if (config_changed) {
3019         int i;
3020         for (i = 0; i < in->num_preprocessors; i++)
3021         {
3022             int cur_status = in_configure_effect_channels(in->preprocessors[i].effect_itfe,
3023                                                   channel_config);
3024             if (cur_status != 0) {
3025                 ALOGV("in_reconfigure_channels(): error %d configuring effect "
3026                         "%d with channels: [%04x][%04x]",
3027                         cur_status,
3028                         i,
3029                         channel_config->main_channels,
3030                         channel_config->aux_channels);
3031                 status = cur_status;
3032             }
3033         }
3034     } else if (effect != NULL && channel_config->aux_channels) {
3035         /* if aux channels config did not change but aux channels are present,
3036          * we still need to configure the effect being added */
3037         status = in_configure_effect_channels(effect, channel_config);
3038     }
3039     return status;
3040 }
3041 
in_update_aux_channels(struct tuna_stream_in * in,effect_handle_t effect)3042 static void in_update_aux_channels(struct tuna_stream_in *in,
3043                                    effect_handle_t effect)
3044 {
3045     uint32_t aux_channels;
3046     channel_config_t channel_config;
3047     int status;
3048 
3049     aux_channels = in_get_aux_channels(in);
3050 
3051     channel_config.main_channels = in->main_channels;
3052     channel_config.aux_channels = aux_channels;
3053     status = in_reconfigure_channels(in,
3054                                      effect,
3055                                      &channel_config,
3056                                      (aux_channels != in->aux_channels));
3057 
3058     if (status != 0) {
3059         ALOGV("in_update_aux_channels(): in_reconfigure_channels error %d", status);
3060         /* resetting aux channels configuration */
3061         aux_channels = 0;
3062         channel_config.aux_channels = 0;
3063         in_reconfigure_channels(in, effect, &channel_config, true);
3064     }
3065     if (in->aux_channels != aux_channels) {
3066         in->aux_channels_changed = true;
3067         in->aux_channels = aux_channels;
3068         do_input_standby(in);
3069     }
3070 }
3071 
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)3072 static int in_add_audio_effect(const struct audio_stream *stream,
3073                                effect_handle_t effect)
3074 {
3075     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
3076     int status;
3077     effect_descriptor_t desc;
3078 
3079     pthread_mutex_lock(&in->dev->lock);
3080     pthread_mutex_lock(&in->lock);
3081     if (in->num_preprocessors >= MAX_PREPROCESSORS) {
3082         status = -ENOSYS;
3083         goto exit;
3084     }
3085 
3086     status = (*effect)->get_descriptor(effect, &desc);
3087     if (status != 0)
3088         goto exit;
3089 
3090     in->preprocessors[in->num_preprocessors].effect_itfe = effect;
3091     /* add the supported channel of the effect in the channel_configs */
3092     in_read_audio_effect_channel_configs(in, &in->preprocessors[in->num_preprocessors]);
3093 
3094     in->num_preprocessors++;
3095 
3096     /* check compatibility between main channel supported and possible auxiliary channels */
3097     in_update_aux_channels(in, effect);
3098 
3099     ALOGV("in_add_audio_effect(), effect type: %08x", desc.type.timeLow);
3100 
3101     if (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
3102         in->need_echo_reference = true;
3103         do_input_standby(in);
3104         in_configure_reverse(in);
3105     }
3106 
3107 exit:
3108 
3109     ALOGW_IF(status != 0, "in_add_audio_effect() error %d", status);
3110     pthread_mutex_unlock(&in->lock);
3111     pthread_mutex_unlock(&in->dev->lock);
3112     return status;
3113 }
3114 
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)3115 static int in_remove_audio_effect(const struct audio_stream *stream,
3116                                   effect_handle_t effect)
3117 {
3118     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
3119     int i;
3120     int status = -EINVAL;
3121     effect_descriptor_t desc;
3122 
3123     pthread_mutex_lock(&in->dev->lock);
3124     pthread_mutex_lock(&in->lock);
3125     if (in->num_preprocessors <= 0) {
3126         status = -ENOSYS;
3127         goto exit;
3128     }
3129 
3130     for (i = 0; i < in->num_preprocessors; i++) {
3131         if (status == 0) { /* status == 0 means an effect was removed from a previous slot */
3132             in->preprocessors[i - 1].effect_itfe = in->preprocessors[i].effect_itfe;
3133             in->preprocessors[i - 1].channel_configs = in->preprocessors[i].channel_configs;
3134             in->preprocessors[i - 1].num_channel_configs = in->preprocessors[i].num_channel_configs;
3135             ALOGV("in_remove_audio_effect moving fx from %d to %d", i, i - 1);
3136             continue;
3137         }
3138         if (in->preprocessors[i].effect_itfe == effect) {
3139             ALOGV("in_remove_audio_effect found fx at index %d", i);
3140             free(in->preprocessors[i].channel_configs);
3141             status = 0;
3142         }
3143     }
3144 
3145     if (status != 0)
3146         goto exit;
3147 
3148     in->num_preprocessors--;
3149     /* if we remove one effect, at least the last preproc should be reset */
3150     in->preprocessors[in->num_preprocessors].num_channel_configs = 0;
3151     in->preprocessors[in->num_preprocessors].effect_itfe = NULL;
3152     in->preprocessors[in->num_preprocessors].channel_configs = NULL;
3153 
3154 
3155     /* check compatibility between main channel supported and possible auxiliary channels */
3156     in_update_aux_channels(in, NULL);
3157 
3158     status = (*effect)->get_descriptor(effect, &desc);
3159     if (status != 0)
3160         goto exit;
3161 
3162     ALOGV("in_remove_audio_effect(), effect type: %08x", desc.type.timeLow);
3163 
3164     if (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
3165         in->need_echo_reference = false;
3166         do_input_standby(in);
3167     }
3168 
3169 exit:
3170 
3171     ALOGW_IF(status != 0, "in_remove_audio_effect() error %d", status);
3172     pthread_mutex_unlock(&in->lock);
3173     pthread_mutex_unlock(&in->dev->lock);
3174     return status;
3175 }
3176 
out_read_hdmi_channel_masks(struct tuna_stream_out * out)3177 static int out_read_hdmi_channel_masks(struct tuna_stream_out *out) {
3178     int max_channels = 0;
3179     struct mixer *mixer_hdmi;
3180 
3181     mixer_hdmi = mixer_open(CARD_OMAP4_HDMI);
3182     if (mixer_hdmi) {
3183         struct mixer_ctl *ctl;
3184 
3185         ctl = mixer_get_ctl_by_name(mixer_hdmi, MIXER_MAXIMUM_LPCM_CHANNELS);
3186         if (ctl)
3187             max_channels = mixer_ctl_get_value(ctl, 0);
3188         mixer_close(mixer_hdmi);
3189     }
3190 
3191     ALOGV("out_read_hdmi_channel_masks() got %d max channels", max_channels);
3192 
3193     if (max_channels != 6 && max_channels != 8)
3194         return -ENOSYS;
3195 
3196     out->sup_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
3197     if (max_channels == 8)
3198         out->sup_channel_masks[1] = AUDIO_CHANNEL_OUT_7POINT1;
3199 
3200     return 0;
3201 }
3202 
adev_open_output_stream(struct audio_hw_device * dev,audio_io_handle_t handle,audio_devices_t devices,audio_output_flags_t flags,struct audio_config * config,struct audio_stream_out ** stream_out)3203 static int adev_open_output_stream(struct audio_hw_device *dev,
3204                                    audio_io_handle_t handle,
3205                                    audio_devices_t devices,
3206                                    audio_output_flags_t flags,
3207                                    struct audio_config *config,
3208                                    struct audio_stream_out **stream_out)
3209 {
3210     struct tuna_audio_device *ladev = (struct tuna_audio_device *)dev;
3211     struct tuna_stream_out *out;
3212     int ret;
3213     int output_type;
3214 
3215     *stream_out = NULL;
3216 
3217     out = (struct tuna_stream_out *)calloc(1, sizeof(struct tuna_stream_out));
3218     if (!out)
3219         return -ENOMEM;
3220 
3221     out->sup_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
3222     out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3223 
3224     if (flags & AUDIO_OUTPUT_FLAG_DIRECT &&
3225                    devices == AUDIO_DEVICE_OUT_AUX_DIGITAL) {
3226         ALOGV("adev_open_output_stream() HDMI multichannel");
3227         if (ladev->outputs[OUTPUT_HDMI] != NULL) {
3228             ret = -ENOSYS;
3229             goto err_open;
3230         }
3231         ret = out_read_hdmi_channel_masks(out);
3232         if (ret != 0)
3233             goto err_open;
3234         output_type = OUTPUT_HDMI;
3235         if (config->sample_rate == 0)
3236             config->sample_rate = MM_FULL_POWER_SAMPLING_RATE;
3237         if (config->channel_mask == 0)
3238             config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
3239         out->channel_mask = config->channel_mask;
3240         out->stream.common.get_buffer_size = out_get_buffer_size_hdmi;
3241         out->stream.common.get_sample_rate = out_get_sample_rate_hdmi;
3242         out->stream.get_latency = out_get_latency_hdmi;
3243         out->stream.write = out_write_hdmi;
3244         out->config[PCM_HDMI] = pcm_config_hdmi_multi;
3245         out->config[PCM_HDMI].rate = config->sample_rate;
3246         out->config[PCM_HDMI].channels = popcount(config->channel_mask);
3247         /* FIXME: workaround for channel swap on first playback after opening the output */
3248         out->restart_periods_cnt = out->config[PCM_HDMI].period_count * 2;
3249     } else if (flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
3250         ALOGV("adev_open_output_stream() deep buffer");
3251         if (ladev->outputs[OUTPUT_DEEP_BUF] != NULL) {
3252             ret = -ENOSYS;
3253             goto err_open;
3254         }
3255         output_type = OUTPUT_DEEP_BUF;
3256         out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3257         out->stream.common.get_buffer_size = out_get_buffer_size_deep_buffer;
3258         out->stream.common.get_sample_rate = out_get_sample_rate;
3259         out->stream.get_latency = out_get_latency_deep_buffer;
3260         out->stream.write = out_write_deep_buffer;
3261     } else {
3262         ALOGV("adev_open_output_stream() normal buffer");
3263         if (ladev->outputs[OUTPUT_LOW_LATENCY] != NULL) {
3264             ret = -ENOSYS;
3265             goto err_open;
3266         }
3267         output_type = OUTPUT_LOW_LATENCY;
3268         out->stream.common.get_buffer_size = out_get_buffer_size_low_latency;
3269         out->stream.common.get_sample_rate = out_get_sample_rate;
3270         out->stream.get_latency = out_get_latency_low_latency;
3271         out->stream.write = out_write_low_latency;
3272     }
3273 
3274     ret = create_resampler(DEFAULT_OUT_SAMPLING_RATE,
3275                            MM_FULL_POWER_SAMPLING_RATE,
3276                            2,
3277                            RESAMPLER_QUALITY_DEFAULT,
3278                            NULL,
3279                            &out->resampler);
3280     if (ret != 0)
3281         goto err_open;
3282 
3283     out->stream.common.set_sample_rate = out_set_sample_rate;
3284     out->stream.common.get_channels = out_get_channels;
3285     out->stream.common.get_format = out_get_format;
3286     out->stream.common.set_format = out_set_format;
3287     out->stream.common.standby = out_standby;
3288     out->stream.common.dump = out_dump;
3289     out->stream.common.set_parameters = out_set_parameters;
3290     out->stream.common.get_parameters = out_get_parameters;
3291     out->stream.common.add_audio_effect = out_add_audio_effect;
3292     out->stream.common.remove_audio_effect = out_remove_audio_effect;
3293     out->stream.set_volume = out_set_volume;
3294     out->stream.get_render_position = out_get_render_position;
3295 
3296     out->dev = ladev;
3297     out->standby = 1;
3298 
3299     /* FIXME: when we support multiple output devices, we will want to
3300      * do the following:
3301      * adev->devices &= ~AUDIO_DEVICE_OUT_ALL;
3302      * adev->devices |= out->device;
3303      * select_output_device(adev);
3304      * This is because out_set_parameters() with a route is not
3305      * guaranteed to be called after an output stream is opened. */
3306 
3307     config->format = out->stream.common.get_format(&out->stream.common);
3308     config->channel_mask = out->stream.common.get_channels(&out->stream.common);
3309     config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
3310 
3311     *stream_out = &out->stream;
3312     ladev->outputs[output_type] = out;
3313 
3314     return 0;
3315 
3316 err_open:
3317     free(out);
3318     return ret;
3319 }
3320 
adev_close_output_stream(struct audio_hw_device * dev,struct audio_stream_out * stream)3321 static void adev_close_output_stream(struct audio_hw_device *dev,
3322                                      struct audio_stream_out *stream)
3323 {
3324     struct tuna_audio_device *ladev = (struct tuna_audio_device *)dev;
3325     struct tuna_stream_out *out = (struct tuna_stream_out *)stream;
3326     int i;
3327 
3328     out_standby(&stream->common);
3329     for (i = 0; i < OUTPUT_TOTAL; i++) {
3330         if (ladev->outputs[i] == out) {
3331             ladev->outputs[i] = NULL;
3332             break;
3333         }
3334     }
3335 
3336     if (out->buffer)
3337         free(out->buffer);
3338     if (out->resampler)
3339         release_resampler(out->resampler);
3340     free(stream);
3341 }
3342 
adev_set_parameters(struct audio_hw_device * dev,const char * kvpairs)3343 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
3344 {
3345     struct tuna_audio_device *adev = (struct tuna_audio_device *)dev;
3346     struct str_parms *parms;
3347     char *str;
3348     char value[32];
3349     int ret;
3350 
3351     parms = str_parms_create_str(kvpairs);
3352     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_TTY_MODE, value, sizeof(value));
3353     if (ret >= 0) {
3354         int tty_mode;
3355 
3356         if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_OFF) == 0)
3357             tty_mode = TTY_MODE_OFF;
3358         else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_VCO) == 0)
3359             tty_mode = TTY_MODE_VCO;
3360         else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_HCO) == 0)
3361             tty_mode = TTY_MODE_HCO;
3362         else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_FULL) == 0)
3363             tty_mode = TTY_MODE_FULL;
3364         else
3365             return -EINVAL;
3366 
3367         pthread_mutex_lock(&adev->lock);
3368         if (tty_mode != adev->tty_mode) {
3369             adev->tty_mode = tty_mode;
3370             if (adev->mode == AUDIO_MODE_IN_CALL)
3371                 select_output_device(adev);
3372         }
3373         pthread_mutex_unlock(&adev->lock);
3374     }
3375 
3376     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
3377     if (ret >= 0) {
3378         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
3379             adev->bluetooth_nrec = true;
3380         else
3381             adev->bluetooth_nrec = false;
3382     }
3383 
3384     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
3385     if (ret >= 0) {
3386         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
3387             adev->screen_off = false;
3388         else
3389             adev->screen_off = true;
3390     }
3391 
3392     str_parms_destroy(parms);
3393     return ret;
3394 }
3395 
adev_get_parameters(const struct audio_hw_device * dev,const char * keys)3396 static char * adev_get_parameters(const struct audio_hw_device *dev,
3397                                   const char *keys)
3398 {
3399     return strdup("");
3400 }
3401 
adev_init_check(const struct audio_hw_device * dev)3402 static int adev_init_check(const struct audio_hw_device *dev)
3403 {
3404     return 0;
3405 }
3406 
adev_set_voice_volume(struct audio_hw_device * dev,float volume)3407 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
3408 {
3409     struct tuna_audio_device *adev = (struct tuna_audio_device *)dev;
3410 
3411     adev->voice_volume = volume;
3412 
3413     if (adev->mode == AUDIO_MODE_IN_CALL)
3414         ril_set_call_volume(&adev->ril, SOUND_TYPE_VOICE, volume);
3415 
3416     return 0;
3417 }
3418 
adev_set_master_volume(struct audio_hw_device * dev,float volume)3419 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
3420 {
3421     return -ENOSYS;
3422 }
3423 
adev_set_mode(struct audio_hw_device * dev,audio_mode_t mode)3424 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
3425 {
3426     struct tuna_audio_device *adev = (struct tuna_audio_device *)dev;
3427 
3428     pthread_mutex_lock(&adev->lock);
3429     if (adev->mode != mode) {
3430         adev->mode = mode;
3431         select_mode(adev);
3432     }
3433     pthread_mutex_unlock(&adev->lock);
3434 
3435     return 0;
3436 }
3437 
adev_set_mic_mute(struct audio_hw_device * dev,bool state)3438 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
3439 {
3440     struct tuna_audio_device *adev = (struct tuna_audio_device *)dev;
3441 
3442     adev->mic_mute = state;
3443 
3444     return 0;
3445 }
3446 
adev_get_mic_mute(const struct audio_hw_device * dev,bool * state)3447 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
3448 {
3449     struct tuna_audio_device *adev = (struct tuna_audio_device *)dev;
3450 
3451     *state = adev->mic_mute;
3452 
3453     return 0;
3454 }
3455 
adev_get_input_buffer_size(const struct audio_hw_device * dev,const struct audio_config * config)3456 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
3457                                          const struct audio_config *config)
3458 {
3459     size_t size;
3460     int channel_count = popcount(config->channel_mask);
3461     if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0)
3462         return 0;
3463 
3464     return get_input_buffer_size(config->sample_rate, config->format, channel_count);
3465 }
3466 
adev_open_input_stream(struct audio_hw_device * dev,audio_io_handle_t handle,audio_devices_t devices,struct audio_config * config,struct audio_stream_in ** stream_in)3467 static int adev_open_input_stream(struct audio_hw_device *dev,
3468                                   audio_io_handle_t handle,
3469                                   audio_devices_t devices,
3470                                   struct audio_config *config,
3471                                   struct audio_stream_in **stream_in)
3472 {
3473     struct tuna_audio_device *ladev = (struct tuna_audio_device *)dev;
3474     struct tuna_stream_in *in;
3475     int ret;
3476     int channel_count = popcount(config->channel_mask);
3477 
3478     *stream_in = NULL;
3479 
3480     if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0)
3481         return -EINVAL;
3482 
3483     in = (struct tuna_stream_in *)calloc(1, sizeof(struct tuna_stream_in));
3484     if (!in)
3485         return -ENOMEM;
3486 
3487     in->stream.common.get_sample_rate = in_get_sample_rate;
3488     in->stream.common.set_sample_rate = in_set_sample_rate;
3489     in->stream.common.get_buffer_size = in_get_buffer_size;
3490     in->stream.common.get_channels = in_get_channels;
3491     in->stream.common.get_format = in_get_format;
3492     in->stream.common.set_format = in_set_format;
3493     in->stream.common.standby = in_standby;
3494     in->stream.common.dump = in_dump;
3495     in->stream.common.set_parameters = in_set_parameters;
3496     in->stream.common.get_parameters = in_get_parameters;
3497     in->stream.common.add_audio_effect = in_add_audio_effect;
3498     in->stream.common.remove_audio_effect = in_remove_audio_effect;
3499     in->stream.set_gain = in_set_gain;
3500     in->stream.read = in_read;
3501     in->stream.get_input_frames_lost = in_get_input_frames_lost;
3502 
3503     in->requested_rate = config->sample_rate;
3504 
3505     memcpy(&in->config, &pcm_config_mm_ul, sizeof(pcm_config_mm_ul));
3506     in->config.channels = channel_count;
3507 
3508     in->main_channels = config->channel_mask;
3509 
3510     /* initialisation of preprocessor structure array is implicit with the calloc.
3511      * same for in->aux_channels and in->aux_channels_changed */
3512 
3513     if (in->requested_rate != in->config.rate) {
3514         in->buf_provider.get_next_buffer = get_next_buffer;
3515         in->buf_provider.release_buffer = release_buffer;
3516 
3517         ret = create_resampler(in->config.rate,
3518                                in->requested_rate,
3519                                in->config.channels,
3520                                RESAMPLER_QUALITY_DEFAULT,
3521                                &in->buf_provider,
3522                                &in->resampler);
3523         if (ret != 0) {
3524             ret = -EINVAL;
3525             goto err;
3526         }
3527     }
3528 
3529     in->dev = ladev;
3530     in->standby = 1;
3531     in->device = devices;
3532 
3533     *stream_in = &in->stream;
3534     return 0;
3535 
3536 err:
3537     if (in->resampler)
3538         release_resampler(in->resampler);
3539 
3540     free(in);
3541     return ret;
3542 }
3543 
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream)3544 static void adev_close_input_stream(struct audio_hw_device *dev,
3545                                    struct audio_stream_in *stream)
3546 {
3547     struct tuna_stream_in *in = (struct tuna_stream_in *)stream;
3548     int i;
3549 
3550     in_standby(&stream->common);
3551 
3552     for (i = 0; i < in->num_preprocessors; i++) {
3553         free(in->preprocessors[i].channel_configs);
3554     }
3555 
3556     free(in->read_buf);
3557     if (in->resampler) {
3558         release_resampler(in->resampler);
3559     }
3560     if (in->proc_buf_in)
3561         free(in->proc_buf_in);
3562     if (in->proc_buf_out)
3563         free(in->proc_buf_out);
3564     if (in->ref_buf)
3565         free(in->ref_buf);
3566 
3567     free(stream);
3568     return;
3569 }
3570 
adev_dump(const audio_hw_device_t * device,int fd)3571 static int adev_dump(const audio_hw_device_t *device, int fd)
3572 {
3573     return 0;
3574 }
3575 
adev_close(hw_device_t * device)3576 static int adev_close(hw_device_t *device)
3577 {
3578     struct tuna_audio_device *adev = (struct tuna_audio_device *)device;
3579 
3580     /* RIL */
3581     ril_close(&adev->ril);
3582 
3583     mixer_close(adev->mixer);
3584     free(device);
3585     return 0;
3586 }
3587 
adev_get_supported_devices(const struct audio_hw_device * dev)3588 static uint32_t adev_get_supported_devices(const struct audio_hw_device *dev)
3589 {
3590     return (/* OUT */
3591             AUDIO_DEVICE_OUT_EARPIECE |
3592             AUDIO_DEVICE_OUT_SPEAKER |
3593             AUDIO_DEVICE_OUT_WIRED_HEADSET |
3594             AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
3595             AUDIO_DEVICE_OUT_AUX_DIGITAL |
3596             AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
3597             AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
3598             AUDIO_DEVICE_OUT_ALL_SCO |
3599             AUDIO_DEVICE_OUT_DEFAULT |
3600             /* IN */
3601             AUDIO_DEVICE_IN_COMMUNICATION |
3602             AUDIO_DEVICE_IN_AMBIENT |
3603             AUDIO_DEVICE_IN_BUILTIN_MIC |
3604             AUDIO_DEVICE_IN_WIRED_HEADSET |
3605             AUDIO_DEVICE_IN_AUX_DIGITAL |
3606             AUDIO_DEVICE_IN_BACK_MIC |
3607             AUDIO_DEVICE_IN_ALL_SCO |
3608             AUDIO_DEVICE_IN_DEFAULT);
3609 }
3610 
adev_open(const hw_module_t * module,const char * name,hw_device_t ** device)3611 static int adev_open(const hw_module_t* module, const char* name,
3612                      hw_device_t** device)
3613 {
3614     struct tuna_audio_device *adev;
3615     int ret;
3616 
3617     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
3618         return -EINVAL;
3619 
3620     adev = calloc(1, sizeof(struct tuna_audio_device));
3621     if (!adev)
3622         return -ENOMEM;
3623 
3624     adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
3625     adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_1_0;
3626     adev->hw_device.common.module = (struct hw_module_t *) module;
3627     adev->hw_device.common.close = adev_close;
3628 
3629     adev->hw_device.get_supported_devices = adev_get_supported_devices;
3630     adev->hw_device.init_check = adev_init_check;
3631     adev->hw_device.set_voice_volume = adev_set_voice_volume;
3632     adev->hw_device.set_master_volume = adev_set_master_volume;
3633     adev->hw_device.set_mode = adev_set_mode;
3634     adev->hw_device.set_mic_mute = adev_set_mic_mute;
3635     adev->hw_device.get_mic_mute = adev_get_mic_mute;
3636     adev->hw_device.set_parameters = adev_set_parameters;
3637     adev->hw_device.get_parameters = adev_get_parameters;
3638     adev->hw_device.get_input_buffer_size = adev_get_input_buffer_size;
3639     adev->hw_device.open_output_stream = adev_open_output_stream;
3640     adev->hw_device.close_output_stream = adev_close_output_stream;
3641     adev->hw_device.open_input_stream = adev_open_input_stream;
3642     adev->hw_device.close_input_stream = adev_close_input_stream;
3643     adev->hw_device.dump = adev_dump;
3644 
3645     adev->mixer = mixer_open(CARD_OMAP4_ABE);
3646     if (!adev->mixer) {
3647         free(adev);
3648         ALOGE("Unable to open the mixer, aborting.");
3649         return -EINVAL;
3650     }
3651 
3652     adev->mixer_ctls.dl1_eq = mixer_get_ctl_by_name(adev->mixer,
3653                                            MIXER_DL1_EQUALIZER);
3654     adev->mixer_ctls.mm_dl1_volume = mixer_get_ctl_by_name(adev->mixer,
3655                                            MIXER_DL1_MEDIA_PLAYBACK_VOLUME);
3656     adev->mixer_ctls.tones_dl1_volume = mixer_get_ctl_by_name(adev->mixer,
3657                                            MIXER_DL1_TONES_PLAYBACK_VOLUME);
3658     adev->mixer_ctls.mm_dl2_volume = mixer_get_ctl_by_name(adev->mixer,
3659                                            MIXER_DL2_MEDIA_PLAYBACK_VOLUME);
3660     adev->mixer_ctls.vx_dl2_volume = mixer_get_ctl_by_name(adev->mixer,
3661                                            MIXER_DL2_VOICE_PLAYBACK_VOLUME);
3662     adev->mixer_ctls.tones_dl2_volume = mixer_get_ctl_by_name(adev->mixer,
3663                                            MIXER_DL2_TONES_PLAYBACK_VOLUME);
3664     adev->mixer_ctls.mm_dl1 = mixer_get_ctl_by_name(adev->mixer,
3665                                            MIXER_DL1_MIXER_MULTIMEDIA);
3666     adev->mixer_ctls.vx_dl1 = mixer_get_ctl_by_name(adev->mixer,
3667                                            MIXER_DL1_MIXER_VOICE);
3668     adev->mixer_ctls.tones_dl1 = mixer_get_ctl_by_name(adev->mixer,
3669                                            MIXER_DL1_MIXER_TONES);
3670     adev->mixer_ctls.mm_dl2 = mixer_get_ctl_by_name(adev->mixer,
3671                                            MIXER_DL2_MIXER_MULTIMEDIA);
3672     adev->mixer_ctls.vx_dl2 = mixer_get_ctl_by_name(adev->mixer,
3673                                            MIXER_DL2_MIXER_VOICE);
3674     adev->mixer_ctls.tones_dl2 = mixer_get_ctl_by_name(adev->mixer,
3675                                            MIXER_DL2_MIXER_TONES);
3676     adev->mixer_ctls.dl2_mono = mixer_get_ctl_by_name(adev->mixer,
3677                                            MIXER_DL2_MONO_MIXER);
3678     adev->mixer_ctls.dl1_headset = mixer_get_ctl_by_name(adev->mixer,
3679                                            MIXER_DL1_PDM_SWITCH);
3680     adev->mixer_ctls.dl1_bt = mixer_get_ctl_by_name(adev->mixer,
3681                                            MIXER_DL1_BT_VX_SWITCH);
3682     adev->mixer_ctls.earpiece_enable = mixer_get_ctl_by_name(adev->mixer,
3683                                            MIXER_EARPHONE_ENABLE_SWITCH);
3684     adev->mixer_ctls.left_capture = mixer_get_ctl_by_name(adev->mixer,
3685                                            MIXER_ANALOG_LEFT_CAPTURE_ROUTE);
3686     adev->mixer_ctls.right_capture = mixer_get_ctl_by_name(adev->mixer,
3687                                            MIXER_ANALOG_RIGHT_CAPTURE_ROUTE);
3688     adev->mixer_ctls.amic_ul_volume = mixer_get_ctl_by_name(adev->mixer,
3689                                            MIXER_AMIC_UL_VOLUME);
3690     adev->mixer_ctls.voice_ul_volume = mixer_get_ctl_by_name(adev->mixer,
3691                                            MIXER_AUDUL_VOICE_UL_VOLUME);
3692     adev->mixer_ctls.sidetone_capture = mixer_get_ctl_by_name(adev->mixer,
3693                                            MIXER_SIDETONE_MIXER_CAPTURE);
3694     adev->mixer_ctls.headset_volume = mixer_get_ctl_by_name(adev->mixer,
3695                                            MIXER_HEADSET_PLAYBACK_VOLUME);
3696     adev->mixer_ctls.speaker_volume = mixer_get_ctl_by_name(adev->mixer,
3697                                            MIXER_HANDSFREE_PLAYBACK_VOLUME);
3698     adev->mixer_ctls.earpiece_volume = mixer_get_ctl_by_name(adev->mixer,
3699                                            MIXER_EARPHONE_PLAYBACK_VOLUME);
3700 
3701     if (!adev->mixer_ctls.dl1_eq ||
3702         !adev->mixer_ctls.mm_dl1_volume ||
3703         !adev->mixer_ctls.tones_dl1_volume ||
3704         !adev->mixer_ctls.mm_dl2_volume ||
3705         !adev->mixer_ctls.vx_dl2_volume ||
3706         !adev->mixer_ctls.tones_dl2_volume ||
3707         !adev->mixer_ctls.mm_dl1 ||
3708         !adev->mixer_ctls.vx_dl1 ||
3709         !adev->mixer_ctls.tones_dl1 ||
3710         !adev->mixer_ctls.mm_dl2 ||
3711         !adev->mixer_ctls.vx_dl2 ||
3712         !adev->mixer_ctls.tones_dl2 ||
3713         !adev->mixer_ctls.dl2_mono ||
3714         !adev->mixer_ctls.dl1_headset ||
3715         !adev->mixer_ctls.dl1_bt ||
3716         !adev->mixer_ctls.earpiece_enable ||
3717         !adev->mixer_ctls.left_capture ||
3718         !adev->mixer_ctls.right_capture ||
3719         !adev->mixer_ctls.amic_ul_volume ||
3720         !adev->mixer_ctls.voice_ul_volume ||
3721         !adev->mixer_ctls.sidetone_capture ||
3722         !adev->mixer_ctls.headset_volume ||
3723         !adev->mixer_ctls.speaker_volume ||
3724         !adev->mixer_ctls.earpiece_volume) {
3725         mixer_close(adev->mixer);
3726         free(adev);
3727         ALOGE("Unable to locate all mixer controls, aborting.");
3728         return -EINVAL;
3729     }
3730 
3731     /* Set the default route before the PCM stream is opened */
3732     pthread_mutex_lock(&adev->lock);
3733     set_route_by_array(adev->mixer, defaults, 1);
3734     adev->mode = AUDIO_MODE_NORMAL;
3735     adev->devices = AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_IN_BUILTIN_MIC;
3736     select_output_device(adev);
3737 
3738     adev->pcm_modem_dl = NULL;
3739     adev->pcm_modem_ul = NULL;
3740     adev->voice_volume = 1.0f;
3741     adev->tty_mode = TTY_MODE_OFF;
3742     adev->device_is_toro = is_device_toro();
3743     adev->bluetooth_nrec = true;
3744     adev->wb_amr = 0;
3745 
3746     /* RIL */
3747     ril_open(&adev->ril);
3748     pthread_mutex_unlock(&adev->lock);
3749     /* register callback for wideband AMR setting */
3750     ril_register_set_wb_amr_callback(audio_set_wb_amr_callback, (void *)adev);
3751 
3752     *device = &adev->hw_device.common;
3753 
3754     return 0;
3755 }
3756 
3757 static struct hw_module_methods_t hal_module_methods = {
3758     .open = adev_open,
3759 };
3760 
3761 struct audio_module HAL_MODULE_INFO_SYM = {
3762     .common = {
3763         .tag = HARDWARE_MODULE_TAG,
3764         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
3765         .hal_api_version = HARDWARE_HAL_API_VERSION,
3766         .id = AUDIO_HARDWARE_MODULE_ID,
3767         .name = "Tuna audio HW HAL",
3768         .author = "The Android Open Source Project",
3769         .methods = &hal_module_methods,
3770     },
3771 };
3772