1 /*
2  * Copyright (C) 2013-2016 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 ATRACE_TAG ATRACE_TAG_AUDIO
19 /*#define LOG_NDEBUG 0*/
20 /*#define VERY_VERY_VERBOSE_LOGGING*/
21 #ifdef VERY_VERY_VERBOSE_LOGGING
22 #define ALOGVV ALOGV
23 #else
24 #define ALOGVV(a...) do { } while(0)
25 #endif
26 
27 #include <errno.h>
28 #include <pthread.h>
29 #include <stdint.h>
30 #include <sys/time.h>
31 #include <stdlib.h>
32 #include <math.h>
33 #include <dlfcn.h>
34 #include <sys/resource.h>
35 #include <sys/prctl.h>
36 #include <limits.h>
37 
38 #include <log/log.h>
39 #include <cutils/trace.h>
40 #include <cutils/str_parms.h>
41 #include <cutils/properties.h>
42 #include <cutils/atomic.h>
43 #include <utils/Timers.h> // systemTime
44 
45 #include <hardware/audio_effect.h>
46 #include <hardware/audio_alsaops.h>
47 #include <processgroup/sched_policy.h>
48 #include <system/thread_defs.h>
49 #include <tinyalsa/asoundlib.h>
50 #include <audio_effects/effect_aec.h>
51 #include <audio_effects/effect_ns.h>
52 #include <audio_utils/clock.h>
53 #include "audio_hw.h"
54 #include "audio_extn.h"
55 #include "audio_perf.h"
56 #include "platform_api.h"
57 #include <platform.h>
58 #include "voice_extn.h"
59 
60 #include "sound/compress_params.h"
61 #include "audio_extn/tfa_98xx.h"
62 #include "audio_extn/maxxaudio.h"
63 #include "audio_extn/audiozoom.h"
64 
65 /* COMPRESS_OFFLOAD_FRAGMENT_SIZE must be more than 8KB and a multiple of 32KB if more than 32KB.
66  * COMPRESS_OFFLOAD_FRAGMENT_SIZE * COMPRESS_OFFLOAD_NUM_FRAGMENTS must be less than 8MB. */
67 #define COMPRESS_OFFLOAD_FRAGMENT_SIZE (256 * 1024)
68 // 2 buffers causes problems with high bitrate files
69 #define COMPRESS_OFFLOAD_NUM_FRAGMENTS 3
70 /* ToDo: Check and update a proper value in msec */
71 #define COMPRESS_OFFLOAD_PLAYBACK_LATENCY 96
72 /* treat as unsigned Q1.13 */
73 #define APP_TYPE_GAIN_DEFAULT         0x2000
74 #define COMPRESS_PLAYBACK_VOLUME_MAX 0x2000
75 
76 /* treat as unsigned Q1.13 */
77 #define VOIP_PLAYBACK_VOLUME_MAX 0x2000
78 
79 #define RECORD_GAIN_MIN 0.0f
80 #define RECORD_GAIN_MAX 1.0f
81 #define RECORD_VOLUME_CTL_MAX 0x2000
82 
83 #define PROXY_OPEN_RETRY_COUNT           100
84 #define PROXY_OPEN_WAIT_TIME             20
85 
86 #define MIN_CHANNEL_COUNT                1
87 #define DEFAULT_CHANNEL_COUNT            2
88 
89 #ifndef MAX_TARGET_SPECIFIC_CHANNEL_CNT
90 #define MAX_CHANNEL_COUNT 1
91 #else
92 #define MAX_CHANNEL_COUNT atoi(XSTR(MAX_TARGET_SPECIFIC_CHANNEL_CNT))
93 #define XSTR(x) STR(x)
94 #define STR(x) #x
95 #endif
96 #define MAX_HIFI_CHANNEL_COUNT 8
97 
98 #define ULL_PERIOD_SIZE (DEFAULT_OUTPUT_SAMPLING_RATE/1000)
99 
100 static unsigned int configured_low_latency_capture_period_size =
101         LOW_LATENCY_CAPTURE_PERIOD_SIZE;
102 
103 
104 #define MMAP_PERIOD_SIZE (DEFAULT_OUTPUT_SAMPLING_RATE/1000)
105 #define MMAP_PERIOD_COUNT_MIN 32
106 #define MMAP_PERIOD_COUNT_MAX 512
107 #define MMAP_PERIOD_COUNT_DEFAULT (MMAP_PERIOD_COUNT_MAX)
108 #define MMAP_MIN_SIZE_FRAMES_MAX 64 * 1024
109 
110 /* This constant enables extended precision handling.
111  * TODO The flag is off until more testing is done.
112  */
113 static const bool k_enable_extended_precision = false;
114 
115 struct pcm_config pcm_config_deep_buffer = {
116     .channels = DEFAULT_CHANNEL_COUNT,
117     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
118     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
119     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
120     .format = PCM_FORMAT_S16_LE,
121     .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
122     .stop_threshold = INT_MAX,
123     .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
124 };
125 
126 struct pcm_config pcm_config_low_latency = {
127     .channels = DEFAULT_CHANNEL_COUNT,
128     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
129     .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
130     .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
131     .format = PCM_FORMAT_S16_LE,
132     .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
133     .stop_threshold = INT_MAX,
134     .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
135 };
136 
137 struct pcm_config pcm_config_haptics_audio = {
138     .channels = 1,
139     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
140     .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
141     .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
142     .format = PCM_FORMAT_S16_LE,
143     .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
144     .stop_threshold = INT_MAX,
145     .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
146 };
147 
148 struct pcm_config pcm_config_haptics = {
149     .channels = 1,
150     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
151     .period_count = 2,
152     .format = PCM_FORMAT_S16_LE,
153     .stop_threshold = INT_MAX,
154     .avail_min = 0,
155 };
156 
157 static int af_period_multiplier = 4;
158 struct pcm_config pcm_config_rt = {
159     .channels = DEFAULT_CHANNEL_COUNT,
160     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
161     .period_size = ULL_PERIOD_SIZE, //1 ms
162     .period_count = 512, //=> buffer size is 512ms
163     .format = PCM_FORMAT_S16_LE,
164     .start_threshold = ULL_PERIOD_SIZE*8, //8ms
165     .stop_threshold = INT_MAX,
166     .silence_threshold = 0,
167     .silence_size = 0,
168     .avail_min = ULL_PERIOD_SIZE, //1 ms
169 };
170 
171 struct pcm_config pcm_config_hdmi_multi = {
172     .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
173     .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
174     .period_size = HDMI_MULTI_PERIOD_SIZE,
175     .period_count = HDMI_MULTI_PERIOD_COUNT,
176     .format = PCM_FORMAT_S16_LE,
177     .start_threshold = 0,
178     .stop_threshold = INT_MAX,
179     .avail_min = 0,
180 };
181 
182 struct pcm_config pcm_config_mmap_playback = {
183     .channels = DEFAULT_CHANNEL_COUNT,
184     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
185     .period_size = MMAP_PERIOD_SIZE,
186     .period_count = MMAP_PERIOD_COUNT_DEFAULT,
187     .format = PCM_FORMAT_S16_LE,
188     .start_threshold = MMAP_PERIOD_SIZE*8,
189     .stop_threshold = INT32_MAX,
190     .silence_threshold = 0,
191     .silence_size = 0,
192     .avail_min = MMAP_PERIOD_SIZE, //1 ms
193 };
194 
195 struct pcm_config pcm_config_hifi = {
196     .channels = DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
197     .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
198     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE, /* change #define */
199     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
200     .format = PCM_FORMAT_S24_3LE,
201     .start_threshold = 0,
202     .stop_threshold = INT_MAX,
203     .avail_min = 0,
204 };
205 
206 struct pcm_config pcm_config_audio_capture = {
207     .channels = DEFAULT_CHANNEL_COUNT,
208     .period_count = AUDIO_CAPTURE_PERIOD_COUNT,
209     .format = PCM_FORMAT_S16_LE,
210     .stop_threshold = INT_MAX,
211     .avail_min = 0,
212 };
213 
214 struct pcm_config pcm_config_audio_capture_rt = {
215     .channels = DEFAULT_CHANNEL_COUNT,
216     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
217     .period_size = ULL_PERIOD_SIZE,
218     .period_count = 512,
219     .format = PCM_FORMAT_S16_LE,
220     .start_threshold = 0,
221     .stop_threshold = INT_MAX,
222     .silence_threshold = 0,
223     .silence_size = 0,
224     .avail_min = ULL_PERIOD_SIZE, //1 ms
225 };
226 
227 struct pcm_config pcm_config_mmap_capture = {
228     .channels = DEFAULT_CHANNEL_COUNT,
229     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
230     .period_size = MMAP_PERIOD_SIZE,
231     .period_count = MMAP_PERIOD_COUNT_DEFAULT,
232     .format = PCM_FORMAT_S16_LE,
233     .start_threshold = 0,
234     .stop_threshold = INT_MAX,
235     .silence_threshold = 0,
236     .silence_size = 0,
237     .avail_min = MMAP_PERIOD_SIZE, //1 ms
238 };
239 
240 struct pcm_config pcm_config_voip = {
241     .channels = 1,
242     .period_count = 2,
243     .format = PCM_FORMAT_S16_LE,
244     .stop_threshold = INT_MAX,
245     .avail_min = 0,
246 };
247 
248 #define AFE_PROXY_CHANNEL_COUNT 2
249 #define AFE_PROXY_SAMPLING_RATE 48000
250 
251 #define AFE_PROXY_PLAYBACK_PERIOD_SIZE  256
252 #define AFE_PROXY_PLAYBACK_PERIOD_COUNT 4
253 
254 struct pcm_config pcm_config_afe_proxy_playback = {
255     .channels = AFE_PROXY_CHANNEL_COUNT,
256     .rate = AFE_PROXY_SAMPLING_RATE,
257     .period_size = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
258     .period_count = AFE_PROXY_PLAYBACK_PERIOD_COUNT,
259     .format = PCM_FORMAT_S16_LE,
260     .start_threshold = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
261     .stop_threshold = INT_MAX,
262     .avail_min = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
263 };
264 
265 #define AFE_PROXY_RECORD_PERIOD_SIZE  256
266 #define AFE_PROXY_RECORD_PERIOD_COUNT 4
267 
268 struct pcm_config pcm_config_afe_proxy_record = {
269     .channels = AFE_PROXY_CHANNEL_COUNT,
270     .rate = AFE_PROXY_SAMPLING_RATE,
271     .period_size = AFE_PROXY_RECORD_PERIOD_SIZE,
272     .period_count = AFE_PROXY_RECORD_PERIOD_COUNT,
273     .format = PCM_FORMAT_S16_LE,
274     .start_threshold = AFE_PROXY_RECORD_PERIOD_SIZE,
275     .stop_threshold = AFE_PROXY_RECORD_PERIOD_SIZE * AFE_PROXY_RECORD_PERIOD_COUNT,
276     .avail_min = AFE_PROXY_RECORD_PERIOD_SIZE,
277 };
278 
279 const char * const use_case_table[AUDIO_USECASE_MAX] = {
280     [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = "deep-buffer-playback",
281     [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = "low-latency-playback",
282     [USECASE_AUDIO_PLAYBACK_WITH_HAPTICS] = "audio-with-haptics-playback",
283     [USECASE_AUDIO_PLAYBACK_HIFI] = "hifi-playback",
284     [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
285     [USECASE_AUDIO_PLAYBACK_TTS] = "audio-tts-playback",
286     [USECASE_AUDIO_PLAYBACK_ULL] = "audio-ull-playback",
287     [USECASE_AUDIO_PLAYBACK_MMAP] = "mmap-playback",
288 
289     [USECASE_AUDIO_RECORD] = "audio-record",
290     [USECASE_AUDIO_RECORD_LOW_LATENCY] = "low-latency-record",
291     [USECASE_AUDIO_RECORD_MMAP] = "mmap-record",
292     [USECASE_AUDIO_RECORD_HIFI] = "hifi-record",
293 
294     [USECASE_AUDIO_HFP_SCO] = "hfp-sco",
295     [USECASE_AUDIO_HFP_SCO_WB] = "hfp-sco-wb",
296 
297     [USECASE_VOICE_CALL] = "voice-call",
298     [USECASE_VOICE2_CALL] = "voice2-call",
299     [USECASE_VOLTE_CALL] = "volte-call",
300     [USECASE_QCHAT_CALL] = "qchat-call",
301     [USECASE_VOWLAN_CALL] = "vowlan-call",
302     [USECASE_VOICEMMODE1_CALL] = "voicemmode1-call",
303     [USECASE_VOICEMMODE2_CALL] = "voicemmode2-call",
304 
305     [USECASE_AUDIO_SPKR_CALIB_RX] = "spkr-rx-calib",
306     [USECASE_AUDIO_SPKR_CALIB_TX] = "spkr-vi-record",
307 
308     [USECASE_AUDIO_PLAYBACK_AFE_PROXY] = "afe-proxy-playback",
309     [USECASE_AUDIO_RECORD_AFE_PROXY] = "afe-proxy-record",
310 
311     [USECASE_INCALL_REC_UPLINK] = "incall-rec-uplink",
312     [USECASE_INCALL_REC_DOWNLINK] = "incall-rec-downlink",
313     [USECASE_INCALL_REC_UPLINK_AND_DOWNLINK] = "incall-rec-uplink-and-downlink",
314 
315     [USECASE_AUDIO_PLAYBACK_VOIP] = "audio-playback-voip",
316     [USECASE_AUDIO_RECORD_VOIP] = "audio-record-voip",
317 
318     [USECASE_INCALL_MUSIC_UPLINK] = "incall-music-uplink",
319     [USECASE_INCALL_MUSIC_UPLINK2] = "incall-music-uplink2",
320 
321     [USECASE_AUDIO_A2DP_ABR_FEEDBACK] = "a2dp-abr-feedback",
322 };
323 
324 
325 #define STRING_TO_ENUM(string) { #string, string }
326 
327 struct string_to_enum {
328     const char *name;
329     uint32_t value;
330 };
331 
332 static const struct string_to_enum channels_name_to_enum_table[] = {
333     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
334     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
335     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
336     STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
337     STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
338     STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
339     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_1),
340     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_2),
341     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_3),
342     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_4),
343     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_5),
344     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_6),
345     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_7),
346     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_8),
347 };
348 
349 struct in_effect_list {
350     struct listnode list;
351     effect_handle_t handle;
352 };
353 
354 static int set_voice_volume_l(struct audio_device *adev, float volume);
355 static struct audio_device *adev = NULL;
356 static pthread_mutex_t adev_init_lock = PTHREAD_MUTEX_INITIALIZER;
357 static unsigned int audio_device_ref_count;
358 //cache last MBDRC cal step level
359 static int last_known_cal_step = -1 ;
360 
361 static int check_a2dp_restore_l(struct audio_device *adev, struct stream_out *out, bool restore);
362 static int set_compr_volume(struct audio_stream_out *stream, float left, float right);
363 
364 static int in_set_microphone_direction(const struct audio_stream_in *stream,
365                                            audio_microphone_direction_t dir);
366 static int in_set_microphone_field_dimension(const struct audio_stream_in *stream, float zoom);
367 
may_use_noirq_mode(struct audio_device * adev,audio_usecase_t uc_id,int flags __unused)368 static bool may_use_noirq_mode(struct audio_device *adev, audio_usecase_t uc_id,
369                                int flags __unused)
370 {
371     int dir = 0;
372     switch (uc_id) {
373     case USECASE_AUDIO_RECORD_LOW_LATENCY:
374         dir = 1;
375     case USECASE_AUDIO_PLAYBACK_ULL:
376         break;
377     default:
378         return false;
379     }
380 
381     int dev_id = platform_get_pcm_device_id(uc_id, dir == 0 ?
382                                             PCM_PLAYBACK : PCM_CAPTURE);
383     if (adev->adm_is_noirq_avail)
384         return adev->adm_is_noirq_avail(adev->adm_data,
385                                         adev->snd_card, dev_id, dir);
386     return false;
387 }
388 
register_out_stream(struct stream_out * out)389 static void register_out_stream(struct stream_out *out)
390 {
391     struct audio_device *adev = out->dev;
392     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
393         return;
394 
395     if (!adev->adm_register_output_stream)
396         return;
397 
398     adev->adm_register_output_stream(adev->adm_data,
399                                      out->handle,
400                                      out->flags);
401 
402     if (!adev->adm_set_config)
403         return;
404 
405     if (out->realtime) {
406         adev->adm_set_config(adev->adm_data,
407                              out->handle,
408                              out->pcm, &out->config);
409     }
410 }
411 
register_in_stream(struct stream_in * in)412 static void register_in_stream(struct stream_in *in)
413 {
414     struct audio_device *adev = in->dev;
415     if (!adev->adm_register_input_stream)
416         return;
417 
418     adev->adm_register_input_stream(adev->adm_data,
419                                     in->capture_handle,
420                                     in->flags);
421 
422     if (!adev->adm_set_config)
423         return;
424 
425     if (in->realtime) {
426         adev->adm_set_config(adev->adm_data,
427                              in->capture_handle,
428                              in->pcm,
429                              &in->config);
430     }
431 }
432 
request_out_focus(struct stream_out * out,long ns)433 static void request_out_focus(struct stream_out *out, long ns)
434 {
435     struct audio_device *adev = out->dev;
436 
437     if (adev->adm_request_focus_v2) {
438         adev->adm_request_focus_v2(adev->adm_data, out->handle, ns);
439     } else if (adev->adm_request_focus) {
440         adev->adm_request_focus(adev->adm_data, out->handle);
441     }
442 }
443 
request_in_focus(struct stream_in * in,long ns)444 static void request_in_focus(struct stream_in *in, long ns)
445 {
446     struct audio_device *adev = in->dev;
447 
448     if (adev->adm_request_focus_v2) {
449         adev->adm_request_focus_v2(adev->adm_data, in->capture_handle, ns);
450     } else if (adev->adm_request_focus) {
451         adev->adm_request_focus(adev->adm_data, in->capture_handle);
452     }
453 }
454 
release_out_focus(struct stream_out * out,long ns __unused)455 static void release_out_focus(struct stream_out *out, long ns __unused)
456 {
457     struct audio_device *adev = out->dev;
458 
459     if (adev->adm_abandon_focus)
460         adev->adm_abandon_focus(adev->adm_data, out->handle);
461 }
462 
release_in_focus(struct stream_in * in,long ns __unused)463 static void release_in_focus(struct stream_in *in, long ns __unused)
464 {
465     struct audio_device *adev = in->dev;
466     if (adev->adm_abandon_focus)
467         adev->adm_abandon_focus(adev->adm_data, in->capture_handle);
468 }
469 
parse_snd_card_status(struct str_parms * parms,int * card,card_status_t * status)470 static int parse_snd_card_status(struct str_parms * parms, int * card,
471                                  card_status_t * status)
472 {
473     char value[32]={0};
474     char state[32]={0};
475 
476     int ret = str_parms_get_str(parms, "SND_CARD_STATUS", value, sizeof(value));
477 
478     if (ret < 0)
479         return -1;
480 
481     // sscanf should be okay as value is of max length 32.
482     // same as sizeof state.
483     if (sscanf(value, "%d,%s", card, state) < 2)
484         return -1;
485 
486     *status = !strcmp(state, "ONLINE") ? CARD_STATUS_ONLINE :
487                                          CARD_STATUS_OFFLINE;
488     return 0;
489 }
490 
491 // always call with adev lock held
send_gain_dep_calibration_l()492 void send_gain_dep_calibration_l() {
493     if (last_known_cal_step >= 0)
494         platform_send_gain_dep_cal(adev->platform, last_known_cal_step);
495 }
496 
497 __attribute__ ((visibility ("default")))
audio_hw_send_gain_dep_calibration(int level)498 bool audio_hw_send_gain_dep_calibration(int level) {
499     bool ret_val = false;
500     ALOGV("%s: enter ... ", __func__);
501 
502     pthread_mutex_lock(&adev_init_lock);
503 
504     if (adev != NULL && adev->platform != NULL) {
505         pthread_mutex_lock(&adev->lock);
506         last_known_cal_step = level;
507         send_gain_dep_calibration_l();
508         pthread_mutex_unlock(&adev->lock);
509     } else {
510         ALOGE("%s: %s is NULL", __func__, adev == NULL ? "adev" : "adev->platform");
511     }
512 
513     pthread_mutex_unlock(&adev_init_lock);
514 
515     ALOGV("%s: exit with ret_val %d ", __func__, ret_val);
516     return ret_val;
517 }
518 
519 #ifdef MAXXAUDIO_QDSP_ENABLED
audio_hw_send_ma_parameter(int stream_type,float vol,bool active)520 bool audio_hw_send_ma_parameter(int stream_type, float vol, bool active)
521 {
522     bool ret = false;
523     ALOGV("%s: enter ...", __func__);
524 
525     pthread_mutex_lock(&adev_init_lock);
526 
527     if (adev != NULL && adev->platform != NULL) {
528         pthread_mutex_lock(&adev->lock);
529         ret = audio_extn_ma_set_state(adev, stream_type, vol, active);
530         pthread_mutex_unlock(&adev->lock);
531     }
532 
533     pthread_mutex_unlock(&adev_init_lock);
534 
535     ALOGV("%s: exit with ret %d", __func__, ret);
536     return ret;
537 }
538 #else
539 #define audio_hw_send_ma_parameter(stream_type, vol, active) (0)
540 #endif
541 
542 __attribute__ ((visibility ("default")))
audio_hw_get_gain_level_mapping(struct amp_db_and_gain_table * mapping_tbl,int table_size)543 int audio_hw_get_gain_level_mapping(struct amp_db_and_gain_table *mapping_tbl,
544                                     int table_size) {
545      int ret_val = 0;
546      ALOGV("%s: enter ... ", __func__);
547 
548      pthread_mutex_lock(&adev_init_lock);
549      if (adev == NULL) {
550          ALOGW("%s: adev is NULL .... ", __func__);
551          goto done;
552      }
553 
554      pthread_mutex_lock(&adev->lock);
555      ret_val = platform_get_gain_level_mapping(mapping_tbl, table_size);
556      pthread_mutex_unlock(&adev->lock);
557 done:
558      pthread_mutex_unlock(&adev_init_lock);
559      ALOGV("%s: exit ... ", __func__);
560      return ret_val;
561 }
562 
is_supported_format(audio_format_t format)563 static bool is_supported_format(audio_format_t format)
564 {
565     switch (format) {
566         case AUDIO_FORMAT_MP3:
567         case AUDIO_FORMAT_AAC_LC:
568         case AUDIO_FORMAT_AAC_HE_V1:
569         case AUDIO_FORMAT_AAC_HE_V2:
570             return true;
571         default:
572             break;
573     }
574     return false;
575 }
576 
is_supported_24bits_audiosource(audio_source_t source)577 static bool is_supported_24bits_audiosource(audio_source_t source)
578 {
579     switch (source) {
580         case AUDIO_SOURCE_UNPROCESSED:
581 #ifdef ENABLED_24BITS_CAMCORDER
582         case AUDIO_SOURCE_CAMCORDER:
583 #endif
584             return true;
585         default:
586             break;
587     }
588     return false;
589 }
590 
is_mmap_usecase(audio_usecase_t uc_id)591 static inline bool is_mmap_usecase(audio_usecase_t uc_id)
592 {
593     return (uc_id == USECASE_AUDIO_RECORD_AFE_PROXY) ||
594            (uc_id == USECASE_AUDIO_PLAYBACK_AFE_PROXY);
595 }
596 
get_snd_codec_id(audio_format_t format)597 static int get_snd_codec_id(audio_format_t format)
598 {
599     int id = 0;
600 
601     switch (format & AUDIO_FORMAT_MAIN_MASK) {
602     case AUDIO_FORMAT_MP3:
603         id = SND_AUDIOCODEC_MP3;
604         break;
605     case AUDIO_FORMAT_AAC:
606         id = SND_AUDIOCODEC_AAC;
607         break;
608     default:
609         ALOGE("%s: Unsupported audio format", __func__);
610     }
611 
612     return id;
613 }
614 
audio_ssr_status(struct audio_device * adev)615 static int audio_ssr_status(struct audio_device *adev)
616 {
617     int ret = 0;
618     struct mixer_ctl *ctl;
619     const char *mixer_ctl_name = "Audio SSR Status";
620 
621     ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
622     ret = mixer_ctl_get_value(ctl, 0);
623     ALOGD("%s: value: %d", __func__, ret);
624     return ret;
625 }
626 
stream_app_type_cfg_init(struct stream_app_type_cfg * cfg)627 static void stream_app_type_cfg_init(struct stream_app_type_cfg *cfg)
628 {
629     cfg->gain[0] = cfg->gain[1] = APP_TYPE_GAIN_DEFAULT;
630 }
631 
is_btsco_device(snd_device_t out_snd_device,snd_device_t in_snd_device)632 static bool is_btsco_device(snd_device_t out_snd_device, snd_device_t in_snd_device)
633 {
634    return out_snd_device == SND_DEVICE_OUT_BT_SCO ||
635           out_snd_device == SND_DEVICE_OUT_BT_SCO_WB ||
636           in_snd_device == SND_DEVICE_IN_BT_SCO_MIC_WB_NREC ||
637           in_snd_device == SND_DEVICE_IN_BT_SCO_MIC_WB ||
638           in_snd_device == SND_DEVICE_IN_BT_SCO_MIC_NREC ||
639           in_snd_device == SND_DEVICE_IN_BT_SCO_MIC;
640 
641 }
642 
is_a2dp_device(snd_device_t out_snd_device)643 static bool is_a2dp_device(snd_device_t out_snd_device)
644 {
645    return out_snd_device == SND_DEVICE_OUT_BT_A2DP;
646 }
647 
enable_audio_route(struct audio_device * adev,struct audio_usecase * usecase)648 int enable_audio_route(struct audio_device *adev,
649                        struct audio_usecase *usecase)
650 {
651     snd_device_t snd_device;
652     char mixer_path[MIXER_PATH_MAX_LENGTH];
653 
654     if (usecase == NULL)
655         return -EINVAL;
656 
657     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
658 
659     audio_extn_sound_trigger_update_stream_status(usecase, ST_EVENT_STREAM_BUSY);
660 
661     if (usecase->type == PCM_CAPTURE) {
662         struct stream_in *in = usecase->stream.in;
663         struct audio_usecase *uinfo;
664         snd_device = usecase->in_snd_device;
665 
666         if (in) {
667             if (in->enable_aec || in->enable_ec_port) {
668                 audio_devices_t out_device = AUDIO_DEVICE_OUT_SPEAKER;
669                 struct listnode *node;
670                 struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
671                                                            USECASE_AUDIO_PLAYBACK_VOIP);
672                 if (voip_usecase) {
673                     out_device = voip_usecase->stream.out->devices;
674                 } else if (adev->primary_output &&
675                               !adev->primary_output->standby) {
676                     out_device = adev->primary_output->devices;
677                 } else {
678                     list_for_each(node, &adev->usecase_list) {
679                         uinfo = node_to_item(node, struct audio_usecase, list);
680                         if (uinfo->type != PCM_CAPTURE) {
681                             out_device = uinfo->stream.out->devices;
682                             break;
683                         }
684                     }
685                 }
686                 platform_set_echo_reference(adev, true, out_device);
687                 in->ec_opened = true;
688             }
689         }
690     } else
691         snd_device = usecase->out_snd_device;
692     audio_extn_utils_send_app_type_cfg(adev, usecase);
693     audio_extn_ma_set_device(usecase);
694     audio_extn_utils_send_audio_calibration(adev, usecase);
695 
696     // we shouldn't truncate mixer_path
697     ALOGW_IF(strlcpy(mixer_path, use_case_table[usecase->id], sizeof(mixer_path))
698             >= sizeof(mixer_path), "%s: truncation on mixer path", __func__);
699     // this also appends to mixer_path
700     platform_add_backend_name(adev->platform, mixer_path, snd_device);
701 
702     ALOGD("%s: usecase(%d) apply and update mixer path: %s", __func__,  usecase->id, mixer_path);
703     audio_route_apply_and_update_path(adev->audio_route, mixer_path);
704 
705     ALOGV("%s: exit", __func__);
706     return 0;
707 }
708 
disable_audio_route(struct audio_device * adev,struct audio_usecase * usecase)709 int disable_audio_route(struct audio_device *adev,
710                         struct audio_usecase *usecase)
711 {
712     snd_device_t snd_device;
713     char mixer_path[MIXER_PATH_MAX_LENGTH];
714 
715     if (usecase == NULL)
716         return -EINVAL;
717 
718     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
719     if (usecase->type == PCM_CAPTURE)
720         snd_device = usecase->in_snd_device;
721     else
722         snd_device = usecase->out_snd_device;
723 
724     // we shouldn't truncate mixer_path
725     ALOGW_IF(strlcpy(mixer_path, use_case_table[usecase->id], sizeof(mixer_path))
726             >= sizeof(mixer_path), "%s: truncation on mixer path", __func__);
727     // this also appends to mixer_path
728     platform_add_backend_name(adev->platform, mixer_path, snd_device);
729     ALOGD("%s: usecase(%d) reset and update mixer path: %s", __func__, usecase->id, mixer_path);
730 
731     audio_route_reset_and_update_path(adev->audio_route, mixer_path);
732     if (usecase->type == PCM_CAPTURE) {
733         struct stream_in *in = usecase->stream.in;
734         if (in && in->ec_opened) {
735             platform_set_echo_reference(in->dev, false, AUDIO_DEVICE_NONE);
736             in->ec_opened = false;
737         }
738     }
739     audio_extn_sound_trigger_update_stream_status(usecase, ST_EVENT_STREAM_FREE);
740 
741     ALOGV("%s: exit", __func__);
742     return 0;
743 }
744 
enable_snd_device(struct audio_device * adev,snd_device_t snd_device)745 int enable_snd_device(struct audio_device *adev,
746                       snd_device_t snd_device)
747 {
748     int i, num_devices = 0;
749     snd_device_t new_snd_devices[2];
750     int ret_val = -EINVAL;
751     if (snd_device < SND_DEVICE_MIN ||
752         snd_device >= SND_DEVICE_MAX) {
753         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
754         goto on_error;
755     }
756 
757     platform_send_audio_calibration(adev->platform, snd_device);
758 
759     if (adev->snd_dev_ref_cnt[snd_device] >= 1) {
760         ALOGV("%s: snd_device(%d: %s) is already active",
761               __func__, snd_device, platform_get_snd_device_name(snd_device));
762         goto on_success;
763     }
764 
765     /* due to the possibility of calibration overwrite between listen
766         and audio, notify sound trigger hal before audio calibration is sent */
767     audio_extn_sound_trigger_update_device_status(snd_device,
768                                     ST_EVENT_SND_DEVICE_BUSY);
769 
770     if (audio_extn_spkr_prot_is_enabled())
771          audio_extn_spkr_prot_calib_cancel(adev);
772 
773     audio_extn_dsm_feedback_enable(adev, snd_device, true);
774 
775     if ((snd_device == SND_DEVICE_OUT_SPEAKER ||
776         snd_device == SND_DEVICE_OUT_SPEAKER_SAFE ||
777         snd_device == SND_DEVICE_OUT_SPEAKER_REVERSE ||
778         snd_device == SND_DEVICE_OUT_VOICE_SPEAKER) &&
779         audio_extn_spkr_prot_is_enabled()) {
780         if (platform_get_snd_device_acdb_id(snd_device) < 0) {
781             goto on_error;
782         }
783         if (audio_extn_spkr_prot_start_processing(snd_device)) {
784             ALOGE("%s: spkr_start_processing failed", __func__);
785             goto on_error;
786         }
787     } else if (platform_can_split_snd_device(snd_device,
788                                              &num_devices,
789                                              new_snd_devices) == 0) {
790         for (i = 0; i < num_devices; i++) {
791             enable_snd_device(adev, new_snd_devices[i]);
792         }
793         platform_set_speaker_gain_in_combo(adev, snd_device, true);
794     } else {
795         char device_name[DEVICE_NAME_MAX_SIZE] = {0};
796         if (platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0 ) {
797             ALOGE(" %s: Invalid sound device returned", __func__);
798             goto on_error;
799         }
800 
801         ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);
802 
803         if (is_a2dp_device(snd_device) &&
804             (audio_extn_a2dp_start_playback() < 0)) {
805                ALOGE("%s: failed to configure A2DP control path", __func__);
806                goto on_error;
807         }
808 
809         audio_route_apply_and_update_path(adev->audio_route, device_name);
810     }
811 on_success:
812     adev->snd_dev_ref_cnt[snd_device]++;
813     ret_val = 0;
814 on_error:
815     return ret_val;
816 }
817 
disable_snd_device(struct audio_device * adev,snd_device_t snd_device)818 int disable_snd_device(struct audio_device *adev,
819                        snd_device_t snd_device)
820 {
821     int i, num_devices = 0;
822     snd_device_t new_snd_devices[2];
823 
824     if (snd_device < SND_DEVICE_MIN ||
825         snd_device >= SND_DEVICE_MAX) {
826         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
827         return -EINVAL;
828     }
829     if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
830         ALOGE("%s: device ref cnt is already 0", __func__);
831         return -EINVAL;
832     }
833     audio_extn_tfa_98xx_disable_speaker(snd_device);
834 
835     adev->snd_dev_ref_cnt[snd_device]--;
836     if (adev->snd_dev_ref_cnt[snd_device] == 0) {
837         audio_extn_dsm_feedback_enable(adev, snd_device, false);
838 
839         if (is_a2dp_device(snd_device))
840             audio_extn_a2dp_stop_playback();
841 
842         if ((snd_device == SND_DEVICE_OUT_SPEAKER ||
843             snd_device == SND_DEVICE_OUT_SPEAKER_SAFE ||
844             snd_device == SND_DEVICE_OUT_SPEAKER_REVERSE ||
845             snd_device == SND_DEVICE_OUT_VOICE_SPEAKER) &&
846             audio_extn_spkr_prot_is_enabled()) {
847             audio_extn_spkr_prot_stop_processing(snd_device);
848 
849             // FIXME b/65363602: bullhead is the only Nexus with audio_extn_spkr_prot_is_enabled()
850             // and does not use speaker swap. As this code causes a problem with device enable ref
851             // counting we remove it for now.
852             // when speaker device is disabled, reset swap.
853             // will be renabled on usecase start
854             // platform_set_swap_channels(adev, false);
855 
856         } else if (platform_can_split_snd_device(snd_device,
857                                                  &num_devices,
858                                                  new_snd_devices) == 0) {
859             for (i = 0; i < num_devices; i++) {
860                 disable_snd_device(adev, new_snd_devices[i]);
861             }
862             platform_set_speaker_gain_in_combo(adev, snd_device, false);
863         } else {
864             char device_name[DEVICE_NAME_MAX_SIZE] = {0};
865             if (platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0 ) {
866                 ALOGE(" %s: Invalid sound device returned", __func__);
867                 return -EINVAL;
868             }
869 
870             ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);
871             audio_route_reset_and_update_path(adev->audio_route, device_name);
872         }
873         audio_extn_sound_trigger_update_device_status(snd_device,
874                                         ST_EVENT_SND_DEVICE_FREE);
875     }
876 
877     return 0;
878 }
879 
880 #ifdef DYNAMIC_ECNS_ENABLED
send_effect_enable_disable_mixer_ctl(struct audio_device * adev,struct stream_in * in,struct audio_effect_config effect_config,unsigned int param_value)881 static int send_effect_enable_disable_mixer_ctl(struct audio_device *adev,
882                           struct stream_in *in,
883                           struct audio_effect_config effect_config,
884                           unsigned int param_value)
885 {
886     char mixer_ctl_name[] = "Audio Effect";
887     long set_values[6];
888 
889     struct mixer_ctl *ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
890     if (!ctl) {
891         ALOGE("%s: Could not get mixer ctl - %s",
892                __func__, mixer_ctl_name);
893         return -EINVAL;
894     }
895 
896     set_values[0] = 1; //0:Rx 1:Tx
897     set_values[1] = in->app_type_cfg.app_type;
898     set_values[2] = (long)effect_config.module_id;
899     set_values[3] = (long)effect_config.instance_id;
900     set_values[4] = (long)effect_config.param_id;
901     set_values[5] = param_value;
902 
903     mixer_ctl_set_array(ctl, set_values, ARRAY_SIZE(set_values));
904 
905     return 0;
906 
907 }
908 
update_effect_param_ecns(struct audio_usecase * usecase,unsigned int module_id,int effect_type,unsigned int * param_value)909 static int update_effect_param_ecns(struct audio_usecase *usecase,
910                                unsigned int module_id, int effect_type,
911                                unsigned int *param_value)
912 {
913     int ret = 0;
914     struct audio_effect_config other_effect_config;
915     struct stream_in *in = NULL;
916 
917     if (!usecase)
918         return -EINVAL;
919 
920     in = usecase->stream.in;
921 
922     /* Get the effect config data of the other effect */
923     ret = platform_get_effect_config_data(usecase->in_snd_device,
924                                           &other_effect_config,
925                                           effect_type == EFFECT_AEC ? EFFECT_NS : EFFECT_AEC);
926     if (ret < 0) {
927         ALOGE("%s Failed to get effect params %d", __func__, ret);
928         return ret;
929     }
930 
931     if (module_id == other_effect_config.module_id) {
932             //Same module id for AEC/NS. Values need to be combined
933             if (((effect_type == EFFECT_AEC) && (in->enable_ns)) ||
934                 ((effect_type == EFFECT_NS) && (in->enable_aec)))
935                 *param_value |= other_effect_config.param_value;
936     }
937 
938     return ret;
939 }
940 
enable_disable_effect(struct audio_device * adev,struct stream_in * in,int effect_type,bool enable)941 static int enable_disable_effect(struct audio_device *adev, struct stream_in *in,
942                                    int effect_type, bool enable)
943 {
944     struct audio_effect_config effect_config;
945     struct audio_usecase *usecase = NULL;
946     int ret = 0;
947     unsigned int param_value = 0;
948 
949     if (!in) {
950         ALOGE("%s: Invalid input stream", __func__);
951         return -EINVAL;
952     }
953 
954     ALOGD("%s: effect_type:%d enable:%d", __func__, effect_type, enable);
955 
956     usecase = get_usecase_from_list(adev, in->usecase);
957 
958     ret = platform_get_effect_config_data(usecase->in_snd_device,
959                                            &effect_config, effect_type);
960     if (ret < 0) {
961         ALOGE("%s Failed to get module id %d", __func__, ret);
962         return ret;
963     }
964     ALOGV("%s: module %d app_type %d usecase->id:%d usecase->in_snd_device:%d",
965            __func__, effect_config.module_id, in->app_type_cfg.app_type,
966           usecase->id, usecase->in_snd_device);
967 
968     if (enable)
969         param_value = effect_config.param_value;
970 
971     /*Special handling for AEC & NS effects Param values need to be
972       updated if module ids are same*/
973 
974     if ((effect_type == EFFECT_AEC) || (effect_type == EFFECT_NS)) {
975         ret = update_effect_param_ecns(usecase, effect_config.module_id,
976                                        effect_type, &param_value);
977         if (ret < 0)
978             return ret;
979     }
980 
981     ret = send_effect_enable_disable_mixer_ctl(adev, in,
982                                                effect_config, param_value);
983 
984     return ret;
985 }
986 
check_and_enable_effect(struct audio_device * adev)987 static int check_and_enable_effect(struct audio_device *adev)
988 {
989     int ret = 0;
990 
991     struct listnode *node;
992     struct stream_in *in = NULL;
993 
994     list_for_each(node, &adev->usecase_list)
995     {
996         struct audio_usecase *usecase = node_to_item(node, struct audio_usecase, list);
997         if (usecase->type == PCM_CAPTURE && usecase->stream.in != NULL) {
998             in = usecase->stream.in;
999 
1000             if (in->standby)
1001                 continue;
1002 
1003             if (in->enable_aec) {
1004                 ret = enable_disable_effect(adev, in, EFFECT_AEC, true);
1005             }
1006 
1007             if (in->enable_ns &&
1008                 in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
1009                 ret = enable_disable_effect(adev, in, EFFECT_NS, true);
1010             }
1011         }
1012     }
1013 
1014     return ret;
1015 }
1016 #else
1017 #define enable_disable_effect(w, x, y, z) -ENOSYS
1018 #define check_and_enable_effect(x) -ENOSYS
1019 #endif
1020 
1021 /*
1022   legend:
1023   uc - existing usecase
1024   new_uc - new usecase
1025   d1, d11, d2 - SND_DEVICE enums
1026   a1, a2 - corresponding ANDROID device enums
1027   B, B1, B2 - backend strings
1028 
1029 case 1
1030   uc->dev  d1 (a1)               B1
1031   new_uc->dev d1 (a1), d2 (a2)   B1, B2
1032 
1033   resolution: disable and enable uc->dev on d1
1034 
1035 case 2
1036   uc->dev d1 (a1)        B1
1037   new_uc->dev d11 (a1)   B1
1038 
1039   resolution: need to switch uc since d1 and d11 are related
1040   (e.g. speaker and voice-speaker)
1041   use ANDROID_DEVICE_OUT enums to match devices since SND_DEVICE enums may vary
1042 
1043 case 3
1044   uc->dev d1 (a1)        B1
1045   new_uc->dev d2 (a2)    B2
1046 
1047   resolution: no need to switch uc
1048 
1049 case 4
1050   uc->dev d1 (a1)      B
1051   new_uc->dev d2 (a2)  B
1052 
1053   resolution: disable enable uc-dev on d2 since backends match
1054   we cannot enable two streams on two different devices if they
1055   share the same backend. e.g. if offload is on speaker device using
1056   QUAD_MI2S backend and a low-latency stream is started on voice-handset
1057   using the same backend, offload must also be switched to voice-handset.
1058 
1059 case 5
1060   uc->dev  d1 (a1)                  B
1061   new_uc->dev d1 (a1), d2 (a2)      B
1062 
1063   resolution: disable enable uc-dev on d2 since backends match
1064   we cannot enable two streams on two different devices if they
1065   share the same backend.
1066 
1067 case 6
1068   uc->dev  d1 a1    B1
1069   new_uc->dev d2 a1 B2
1070 
1071   resolution: no need to switch
1072 
1073 case 7
1074 
1075   uc->dev d1 (a1), d2 (a2)       B1, B2
1076   new_uc->dev d1                 B1
1077 
1078   resolution: no need to switch
1079 
1080 */
derive_playback_snd_device(struct audio_usecase * uc,struct audio_usecase * new_uc,snd_device_t new_snd_device)1081 static snd_device_t derive_playback_snd_device(struct audio_usecase *uc,
1082                                                struct audio_usecase *new_uc,
1083                                                snd_device_t new_snd_device)
1084 {
1085     audio_devices_t a1 = uc->stream.out->devices;
1086     audio_devices_t a2 = new_uc->stream.out->devices;
1087 
1088     snd_device_t d1 = uc->out_snd_device;
1089     snd_device_t d2 = new_snd_device;
1090 
1091     // Treat as a special case when a1 and a2 are not disjoint
1092     if ((a1 != a2) && (a1 & a2)) {
1093         snd_device_t d3[2];
1094         int num_devices = 0;
1095         int ret = platform_can_split_snd_device(popcount(a1) > 1 ? d1 : d2,
1096                                                 &num_devices,
1097                                                 d3);
1098         if (ret < 0) {
1099             if (ret != -ENOSYS) {
1100                 ALOGW("%s failed to split snd_device %d",
1101                       __func__,
1102                       popcount(a1) > 1 ? d1 : d2);
1103             }
1104             goto end;
1105         }
1106 
1107         // NB: case 7 is hypothetical and isn't a practical usecase yet.
1108         // But if it does happen, we need to give priority to d2 if
1109         // the combo devices active on the existing usecase share a backend.
1110         // This is because we cannot have a usecase active on a combo device
1111         // and a new usecase requests one device in this combo pair.
1112         if (platform_check_backends_match(d3[0], d3[1])) {
1113             return d2; // case 5
1114         } else {
1115             return d1; // case 1
1116         }
1117     } else {
1118         if (platform_check_backends_match(d1, d2)) {
1119             return d2; // case 2, 4
1120         } else {
1121             return d1; // case 6, 3
1122         }
1123     }
1124 
1125 end:
1126     return d2; // return whatever was calculated before.
1127 }
1128 
check_and_route_playback_usecases(struct audio_device * adev,struct audio_usecase * uc_info,snd_device_t snd_device)1129 static void check_and_route_playback_usecases(struct audio_device *adev,
1130                                               struct audio_usecase *uc_info,
1131                                               snd_device_t snd_device)
1132 {
1133     struct listnode *node;
1134     struct audio_usecase *usecase;
1135     bool switch_device[AUDIO_USECASE_MAX];
1136     int i, num_uc_to_switch = 0;
1137 
1138     bool force_routing =  platform_check_and_set_playback_backend_cfg(adev,
1139                                                                       uc_info,
1140                                                                       snd_device);
1141 
1142     /* For a2dp device reconfigure all active sessions
1143      * with new AFE encoder format based on a2dp state
1144      */
1145     if ((SND_DEVICE_OUT_BT_A2DP == snd_device ||
1146          SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP == snd_device ||
1147          SND_DEVICE_OUT_SPEAKER_SAFE_AND_BT_A2DP == snd_device) &&
1148          audio_extn_a2dp_is_force_device_switch()) {
1149          force_routing = true;
1150     }
1151 
1152     /*
1153      * This function is to make sure that all the usecases that are active on
1154      * the hardware codec backend are always routed to any one device that is
1155      * handled by the hardware codec.
1156      * For example, if low-latency and deep-buffer usecases are currently active
1157      * on speaker and out_set_parameters(headset) is received on low-latency
1158      * output, then we have to make sure deep-buffer is also switched to headset,
1159      * because of the limitation that both the devices cannot be enabled
1160      * at the same time as they share the same backend.
1161      */
1162     /* Disable all the usecases on the shared backend other than the
1163        specified usecase */
1164     for (i = 0; i < AUDIO_USECASE_MAX; i++)
1165         switch_device[i] = false;
1166 
1167     list_for_each(node, &adev->usecase_list) {
1168         usecase = node_to_item(node, struct audio_usecase, list);
1169         if (usecase->type == PCM_CAPTURE || usecase == uc_info)
1170             continue;
1171 
1172         if (force_routing ||
1173             (usecase->out_snd_device != snd_device &&
1174              (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND ||
1175               usecase->devices & (AUDIO_DEVICE_OUT_USB_DEVICE|AUDIO_DEVICE_OUT_USB_HEADSET)) &&
1176              platform_check_backends_match(snd_device, usecase->out_snd_device))) {
1177             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
1178                   __func__, use_case_table[usecase->id],
1179                   platform_get_snd_device_name(usecase->out_snd_device));
1180             disable_audio_route(adev, usecase);
1181             switch_device[usecase->id] = true;
1182             num_uc_to_switch++;
1183         }
1184     }
1185 
1186     if (num_uc_to_switch) {
1187         list_for_each(node, &adev->usecase_list) {
1188             usecase = node_to_item(node, struct audio_usecase, list);
1189             if (switch_device[usecase->id]) {
1190                 disable_snd_device(adev, usecase->out_snd_device);
1191             }
1192         }
1193 
1194         snd_device_t d_device;
1195         list_for_each(node, &adev->usecase_list) {
1196             usecase = node_to_item(node, struct audio_usecase, list);
1197             if (switch_device[usecase->id]) {
1198                 d_device = derive_playback_snd_device(usecase, uc_info,
1199                                                       snd_device);
1200                 enable_snd_device(adev, d_device);
1201                 /* Update the out_snd_device before enabling the audio route */
1202                 usecase->out_snd_device = d_device;
1203             }
1204         }
1205 
1206         /* Re-route all the usecases on the shared backend other than the
1207            specified usecase to new snd devices */
1208         list_for_each(node, &adev->usecase_list) {
1209             usecase = node_to_item(node, struct audio_usecase, list);
1210             if (switch_device[usecase->id] ) {
1211                 enable_audio_route(adev, usecase);
1212             }
1213         }
1214     }
1215 }
1216 
check_and_route_capture_usecases(struct audio_device * adev,struct audio_usecase * uc_info,snd_device_t snd_device)1217 static void check_and_route_capture_usecases(struct audio_device *adev,
1218                                              struct audio_usecase *uc_info,
1219                                              snd_device_t snd_device)
1220 {
1221     struct listnode *node;
1222     struct audio_usecase *usecase;
1223     bool switch_device[AUDIO_USECASE_MAX];
1224     int i, num_uc_to_switch = 0;
1225 
1226     platform_check_and_set_capture_backend_cfg(adev, uc_info, snd_device);
1227 
1228     /*
1229      * This function is to make sure that all the active capture usecases
1230      * are always routed to the same input sound device.
1231      * For example, if audio-record and voice-call usecases are currently
1232      * active on speaker(rx) and speaker-mic (tx) and out_set_parameters(earpiece)
1233      * is received for voice call then we have to make sure that audio-record
1234      * usecase is also switched to earpiece i.e. voice-dmic-ef,
1235      * because of the limitation that two devices cannot be enabled
1236      * at the same time if they share the same backend.
1237      */
1238     for (i = 0; i < AUDIO_USECASE_MAX; i++)
1239         switch_device[i] = false;
1240 
1241     list_for_each(node, &adev->usecase_list) {
1242         usecase = node_to_item(node, struct audio_usecase, list);
1243         if (usecase->type != PCM_PLAYBACK &&
1244                 usecase != uc_info &&
1245                 usecase->in_snd_device != snd_device &&
1246                 ((uc_info->type == VOICE_CALL &&
1247                   usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL) ||
1248                  platform_check_backends_match(snd_device,\
1249                                               usecase->in_snd_device)) &&
1250                 (usecase->id != USECASE_AUDIO_SPKR_CALIB_TX)) {
1251             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
1252                   __func__, use_case_table[usecase->id],
1253                   platform_get_snd_device_name(usecase->in_snd_device));
1254             disable_audio_route(adev, usecase);
1255             switch_device[usecase->id] = true;
1256             num_uc_to_switch++;
1257         }
1258     }
1259 
1260     if (num_uc_to_switch) {
1261         list_for_each(node, &adev->usecase_list) {
1262             usecase = node_to_item(node, struct audio_usecase, list);
1263             if (switch_device[usecase->id]) {
1264                 disable_snd_device(adev, usecase->in_snd_device);
1265             }
1266         }
1267 
1268         list_for_each(node, &adev->usecase_list) {
1269             usecase = node_to_item(node, struct audio_usecase, list);
1270             if (switch_device[usecase->id]) {
1271                 enable_snd_device(adev, snd_device);
1272             }
1273         }
1274 
1275         /* Re-route all the usecases on the shared backend other than the
1276            specified usecase to new snd devices */
1277         list_for_each(node, &adev->usecase_list) {
1278             usecase = node_to_item(node, struct audio_usecase, list);
1279             /* Update the in_snd_device only before enabling the audio route */
1280             if (switch_device[usecase->id] ) {
1281                 usecase->in_snd_device = snd_device;
1282                 enable_audio_route(adev, usecase);
1283             }
1284         }
1285     }
1286 }
1287 
1288 /* must be called with hw device mutex locked */
read_hdmi_channel_masks(struct stream_out * out)1289 static int read_hdmi_channel_masks(struct stream_out *out)
1290 {
1291     int ret = 0;
1292     int channels = platform_edid_get_max_channels(out->dev->platform);
1293 
1294     switch (channels) {
1295         /*
1296          * Do not handle stereo output in Multi-channel cases
1297          * Stereo case is handled in normal playback path
1298          */
1299     case 6:
1300         ALOGV("%s: HDMI supports 5.1", __func__);
1301         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
1302         break;
1303     case 8:
1304         ALOGV("%s: HDMI supports 5.1 and 7.1 channels", __func__);
1305         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
1306         out->supported_channel_masks[1] = AUDIO_CHANNEL_OUT_7POINT1;
1307         break;
1308     default:
1309         ALOGE("HDMI does not support multi channel playback");
1310         ret = -ENOSYS;
1311         break;
1312     }
1313     return ret;
1314 }
1315 
read_usb_sup_sample_rates(bool is_playback,uint32_t * supported_sample_rates,uint32_t max_rates)1316 static ssize_t read_usb_sup_sample_rates(bool is_playback,
1317                                          uint32_t *supported_sample_rates,
1318                                          uint32_t max_rates)
1319 {
1320     ssize_t count = audio_extn_usb_sup_sample_rates(is_playback,
1321                                                     supported_sample_rates,
1322                                                     max_rates);
1323 #if !LOG_NDEBUG
1324     for (ssize_t i=0; i<count; i++) {
1325         ALOGV("%s %s %d", __func__, is_playback ? "P" : "C",
1326               supported_sample_rates[i]);
1327     }
1328 #endif
1329     return count;
1330 }
1331 
read_usb_sup_channel_masks(bool is_playback,audio_channel_mask_t * supported_channel_masks,uint32_t max_masks)1332 static int read_usb_sup_channel_masks(bool is_playback,
1333                                       audio_channel_mask_t *supported_channel_masks,
1334                                       uint32_t max_masks)
1335 {
1336     int channels = audio_extn_usb_get_max_channels(is_playback);
1337     int channel_count;
1338     uint32_t num_masks = 0;
1339     if (channels > MAX_HIFI_CHANNEL_COUNT) {
1340         channels = MAX_HIFI_CHANNEL_COUNT;
1341     }
1342     if (is_playback) {
1343         // start from 2 channels as framework currently doesn't support mono.
1344         if (channels >= FCC_2) {
1345             supported_channel_masks[num_masks++] = audio_channel_out_mask_from_count(FCC_2);
1346         }
1347         for (channel_count = FCC_2;
1348                 channel_count <= channels && num_masks < max_masks;
1349                 ++channel_count) {
1350             supported_channel_masks[num_masks++] =
1351                     audio_channel_mask_for_index_assignment_from_count(channel_count);
1352         }
1353     } else {
1354         // For capture we report all supported channel masks from 1 channel up.
1355         channel_count = MIN_CHANNEL_COUNT;
1356         // audio_channel_in_mask_from_count() does the right conversion to either positional or
1357         // indexed mask
1358         for ( ; channel_count <= channels && num_masks < max_masks; channel_count++) {
1359             audio_channel_mask_t mask = AUDIO_CHANNEL_NONE;
1360             if (channel_count <= FCC_2) {
1361                 mask = audio_channel_in_mask_from_count(channel_count);
1362                 supported_channel_masks[num_masks++] = mask;
1363             }
1364             const audio_channel_mask_t index_mask =
1365                     audio_channel_mask_for_index_assignment_from_count(channel_count);
1366             if (mask != index_mask && num_masks < max_masks) { // ensure index mask added.
1367                 supported_channel_masks[num_masks++] = index_mask;
1368             }
1369         }
1370     }
1371 #ifdef NDEBUG
1372     for (size_t i = 0; i < num_masks; ++i) {
1373         ALOGV("%s: %s supported ch %d supported_channel_masks[%zu] %08x num_masks %d", __func__,
1374               is_playback ? "P" : "C", channels, i, supported_channel_masks[i], num_masks);
1375     }
1376 #endif
1377     return num_masks;
1378 }
1379 
read_usb_sup_formats(bool is_playback __unused,audio_format_t * supported_formats,uint32_t max_formats __unused)1380 static int read_usb_sup_formats(bool is_playback __unused,
1381                                 audio_format_t *supported_formats,
1382                                 uint32_t max_formats __unused)
1383 {
1384     int bitwidth = audio_extn_usb_get_max_bit_width(is_playback);
1385     switch (bitwidth) {
1386         case 24:
1387             // XXX : usb.c returns 24 for s24 and s24_le?
1388             supported_formats[0] = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1389             break;
1390         case 32:
1391             supported_formats[0] = AUDIO_FORMAT_PCM_32_BIT;
1392             break;
1393         case 16:
1394         default :
1395             supported_formats[0] = AUDIO_FORMAT_PCM_16_BIT;
1396             break;
1397     }
1398     ALOGV("%s: %s supported format %d", __func__,
1399           is_playback ? "P" : "C", bitwidth);
1400     return 1;
1401 }
1402 
read_usb_sup_params_and_compare(bool is_playback,audio_format_t * format,audio_format_t * supported_formats,uint32_t max_formats,audio_channel_mask_t * mask,audio_channel_mask_t * supported_channel_masks,uint32_t max_masks,uint32_t * rate,uint32_t * supported_sample_rates,uint32_t max_rates)1403 static int read_usb_sup_params_and_compare(bool is_playback,
1404                                            audio_format_t *format,
1405                                            audio_format_t *supported_formats,
1406                                            uint32_t max_formats,
1407                                            audio_channel_mask_t *mask,
1408                                            audio_channel_mask_t *supported_channel_masks,
1409                                            uint32_t max_masks,
1410                                            uint32_t *rate,
1411                                            uint32_t *supported_sample_rates,
1412                                            uint32_t max_rates) {
1413     int ret = 0;
1414     int num_formats;
1415     int num_masks;
1416     int num_rates;
1417     int i;
1418 
1419     num_formats = read_usb_sup_formats(is_playback, supported_formats,
1420                                        max_formats);
1421     num_masks = read_usb_sup_channel_masks(is_playback, supported_channel_masks,
1422                                            max_masks);
1423 
1424     num_rates = read_usb_sup_sample_rates(is_playback,
1425                                           supported_sample_rates, max_rates);
1426 
1427 #define LUT(table, len, what, dflt)                  \
1428     for (i=0; i<len && (table[i] != what); i++);    \
1429     if (i==len) { ret |= (what == dflt ? 0 : -1); what=table[0]; }
1430 
1431     LUT(supported_formats, num_formats, *format, AUDIO_FORMAT_DEFAULT);
1432     LUT(supported_channel_masks, num_masks, *mask, AUDIO_CHANNEL_NONE);
1433     LUT(supported_sample_rates, num_rates, *rate, 0);
1434 
1435 #undef LUT
1436     return ret < 0 ? -EINVAL : 0; // HACK TBD
1437 }
1438 
is_usb_ready(struct audio_device * adev,bool is_playback)1439 static bool is_usb_ready(struct audio_device *adev, bool is_playback)
1440 {
1441     // Check if usb is ready.
1442     // The usb device may have been removed quickly after insertion and hence
1443     // no longer available.  This will show up as empty channel masks, or rates.
1444 
1445     pthread_mutex_lock(&adev->lock);
1446     uint32_t supported_sample_rate;
1447 
1448     // we consider usb ready if we can fetch at least one sample rate.
1449     const bool ready = read_usb_sup_sample_rates(
1450             is_playback, &supported_sample_rate, 1 /* max_rates */) > 0;
1451     pthread_mutex_unlock(&adev->lock);
1452     return ready;
1453 }
1454 
get_voice_usecase_id_from_list(struct audio_device * adev)1455 static audio_usecase_t get_voice_usecase_id_from_list(struct audio_device *adev)
1456 {
1457     struct audio_usecase *usecase;
1458     struct listnode *node;
1459 
1460     list_for_each(node, &adev->usecase_list) {
1461         usecase = node_to_item(node, struct audio_usecase, list);
1462         if (usecase->type == VOICE_CALL) {
1463             ALOGV("%s: usecase id %d", __func__, usecase->id);
1464             return usecase->id;
1465         }
1466     }
1467     return USECASE_INVALID;
1468 }
1469 
get_usecase_from_list(struct audio_device * adev,audio_usecase_t uc_id)1470 struct audio_usecase *get_usecase_from_list(struct audio_device *adev,
1471                                             audio_usecase_t uc_id)
1472 {
1473     struct audio_usecase *usecase;
1474     struct listnode *node;
1475 
1476     list_for_each(node, &adev->usecase_list) {
1477         usecase = node_to_item(node, struct audio_usecase, list);
1478         if (usecase->id == uc_id)
1479             return usecase;
1480     }
1481     return NULL;
1482 }
1483 
force_device_switch(struct audio_usecase * usecase)1484 static bool force_device_switch(struct audio_usecase *usecase)
1485 {
1486     if (usecase->type == PCM_CAPTURE || usecase->stream.out == NULL) {
1487         return false;
1488     }
1489 
1490     // Force all A2DP output devices to reconfigure for proper AFE encode format
1491     // Also handle a case where in earlier A2DP start failed as A2DP stream was
1492     // in suspended state, hence try to trigger a retry when we again get a routing request.
1493     if ((usecase->stream.out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
1494         audio_extn_a2dp_is_force_device_switch()) {
1495          ALOGD("%s: Force A2DP device switch to update new encoder config", __func__);
1496          return true;
1497     }
1498 
1499     return false;
1500 }
1501 
adev_get_active_input(const struct audio_device * adev)1502 struct stream_in *adev_get_active_input(const struct audio_device *adev)
1503 {
1504     struct listnode *node;
1505     struct stream_in *last_active_in = NULL;
1506 
1507     /* Get last added active input.
1508      * TODO: We may use a priority mechanism to pick highest priority active source */
1509     list_for_each(node, &adev->usecase_list)
1510     {
1511         struct audio_usecase *usecase = node_to_item(node, struct audio_usecase, list);
1512         if (usecase->type == PCM_CAPTURE && usecase->stream.in != NULL) {
1513             last_active_in =  usecase->stream.in;
1514         }
1515     }
1516 
1517     return last_active_in;
1518 }
1519 
get_voice_communication_input(const struct audio_device * adev)1520 struct stream_in *get_voice_communication_input(const struct audio_device *adev)
1521 {
1522     struct listnode *node;
1523 
1524     /* First check active inputs with voice communication source and then
1525      * any input if audio mode is in communication */
1526     list_for_each(node, &adev->usecase_list)
1527     {
1528         struct audio_usecase *usecase = node_to_item(node, struct audio_usecase, list);
1529         if (usecase->type == PCM_CAPTURE && usecase->stream.in != NULL &&
1530             usecase->stream.in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
1531             return usecase->stream.in;
1532         }
1533     }
1534     if (adev->mode == AUDIO_MODE_IN_COMMUNICATION) {
1535         return adev_get_active_input(adev);
1536     }
1537     return NULL;
1538 }
1539 
1540 /*
1541  * Aligned with policy.h
1542  */
source_priority(int inputSource)1543 static inline int source_priority(int inputSource)
1544 {
1545     switch (inputSource) {
1546     case AUDIO_SOURCE_VOICE_COMMUNICATION:
1547         return 9;
1548     case AUDIO_SOURCE_CAMCORDER:
1549         return 8;
1550     case AUDIO_SOURCE_VOICE_PERFORMANCE:
1551         return 7;
1552     case AUDIO_SOURCE_UNPROCESSED:
1553         return 6;
1554     case AUDIO_SOURCE_MIC:
1555         return 5;
1556     case AUDIO_SOURCE_ECHO_REFERENCE:
1557         return 4;
1558     case AUDIO_SOURCE_FM_TUNER:
1559         return 3;
1560     case AUDIO_SOURCE_VOICE_RECOGNITION:
1561         return 2;
1562     case AUDIO_SOURCE_HOTWORD:
1563         return 1;
1564     default:
1565         break;
1566     }
1567     return 0;
1568 }
1569 
get_priority_input(struct audio_device * adev)1570 static struct stream_in *get_priority_input(struct audio_device *adev)
1571 {
1572     struct listnode *node;
1573     struct audio_usecase *usecase;
1574     int last_priority = 0, priority;
1575     struct stream_in *priority_in = NULL;
1576     struct stream_in *in;
1577 
1578     list_for_each(node, &adev->usecase_list) {
1579         usecase = node_to_item(node, struct audio_usecase, list);
1580         if (usecase->type == PCM_CAPTURE) {
1581             in = usecase->stream.in;
1582             if (!in)
1583                 continue;
1584             priority = source_priority(in->source);
1585 
1586             if (priority > last_priority) {
1587                 last_priority = priority;
1588                 priority_in = in;
1589             }
1590         }
1591     }
1592     return priority_in;
1593 }
1594 
select_devices_with_force_switch(struct audio_device * adev,audio_usecase_t uc_id,bool force_switch)1595 int select_devices_with_force_switch(struct audio_device *adev,
1596                                      audio_usecase_t uc_id,
1597                                      bool force_switch)
1598 {
1599     snd_device_t out_snd_device = SND_DEVICE_NONE;
1600     snd_device_t in_snd_device = SND_DEVICE_NONE;
1601     struct audio_usecase *usecase = NULL;
1602     struct audio_usecase *vc_usecase = NULL;
1603     struct audio_usecase *hfp_usecase = NULL;
1604     audio_usecase_t hfp_ucid;
1605     struct listnode *node;
1606     int status = 0;
1607     struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
1608                                              USECASE_AUDIO_PLAYBACK_VOIP);
1609 
1610     usecase = get_usecase_from_list(adev, uc_id);
1611     if (usecase == NULL) {
1612         ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
1613         return -EINVAL;
1614     }
1615 
1616     if ((usecase->type == VOICE_CALL) ||
1617         (usecase->type == PCM_HFP_CALL)) {
1618         out_snd_device = platform_get_output_snd_device(adev->platform,
1619                                                         usecase->stream.out->devices);
1620         in_snd_device = platform_get_input_snd_device(adev->platform,
1621                                                       NULL,
1622                                                       usecase->stream.out->devices);
1623         usecase->devices = usecase->stream.out->devices;
1624     } else {
1625         /*
1626          * If the voice call is active, use the sound devices of voice call usecase
1627          * so that it would not result any device switch. All the usecases will
1628          * be switched to new device when select_devices() is called for voice call
1629          * usecase. This is to avoid switching devices for voice call when
1630          * check_and_route_playback_usecases() is called below.
1631          */
1632         if (voice_is_in_call(adev)) {
1633             vc_usecase = get_usecase_from_list(adev,
1634                                                get_voice_usecase_id_from_list(adev));
1635             if ((vc_usecase != NULL) &&
1636                 ((vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
1637                  (vc_usecase->devices == AUDIO_DEVICE_OUT_HEARING_AID) ||
1638                  (usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL))) {
1639                 in_snd_device = vc_usecase->in_snd_device;
1640                 out_snd_device = vc_usecase->out_snd_device;
1641             }
1642         } else if (audio_extn_hfp_is_active(adev)) {
1643             hfp_ucid = audio_extn_hfp_get_usecase();
1644             hfp_usecase = get_usecase_from_list(adev, hfp_ucid);
1645             if (hfp_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
1646                    in_snd_device = hfp_usecase->in_snd_device;
1647                    out_snd_device = hfp_usecase->out_snd_device;
1648             }
1649         }
1650         if (usecase->type == PCM_PLAYBACK) {
1651             usecase->devices = usecase->stream.out->devices;
1652             in_snd_device = SND_DEVICE_NONE;
1653             if (out_snd_device == SND_DEVICE_NONE) {
1654                 struct stream_out *voip_out = adev->primary_output;
1655                 struct stream_in *voip_in = get_voice_communication_input(adev);
1656 
1657                 out_snd_device = platform_get_output_snd_device(adev->platform,
1658                                             usecase->stream.out->devices);
1659 
1660                 if (voip_usecase)
1661                     voip_out = voip_usecase->stream.out;
1662 
1663                 if (usecase->stream.out == voip_out && voip_in != NULL) {
1664                     select_devices(adev, voip_in->usecase);
1665                 }
1666             }
1667         } else if (usecase->type == PCM_CAPTURE) {
1668             usecase->devices = usecase->stream.in->device;
1669             out_snd_device = SND_DEVICE_NONE;
1670             if (in_snd_device == SND_DEVICE_NONE) {
1671                 audio_devices_t out_device = AUDIO_DEVICE_NONE;
1672                 struct stream_in *voip_in = get_voice_communication_input(adev);
1673                 struct stream_in *priority_in = NULL;
1674 
1675                 if (voip_in != NULL) {
1676                     struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
1677                                                              USECASE_AUDIO_PLAYBACK_VOIP);
1678 
1679                     usecase->stream.in->enable_ec_port = false;
1680 
1681                     if (usecase->id == USECASE_AUDIO_RECORD_AFE_PROXY) {
1682                         out_device = AUDIO_DEVICE_OUT_TELEPHONY_TX;
1683                     } else if (voip_usecase) {
1684                         out_device = voip_usecase->stream.out->devices;
1685                     } else if (adev->primary_output &&
1686                                   !adev->primary_output->standby) {
1687                         out_device = adev->primary_output->devices;
1688                     } else {
1689                         /* forcing speaker o/p device to get matching i/p pair
1690                            in case o/p is not routed from same primary HAL */
1691                         out_device = AUDIO_DEVICE_OUT_SPEAKER;
1692                     }
1693                     priority_in = voip_in;
1694                 } else {
1695                     /* get the input with the highest priority source*/
1696                     priority_in = get_priority_input(adev);
1697 
1698                     if (!priority_in)
1699                         priority_in = usecase->stream.in;
1700                 }
1701 
1702                 in_snd_device = platform_get_input_snd_device(adev->platform,
1703                                                               priority_in,
1704                                                               out_device);
1705             }
1706         }
1707     }
1708 
1709     if (out_snd_device == usecase->out_snd_device &&
1710         in_snd_device == usecase->in_snd_device) {
1711         if (!force_device_switch(usecase) && !force_switch)
1712             return 0;
1713     }
1714 
1715     if (is_a2dp_device(out_snd_device) && !audio_extn_a2dp_is_ready()) {
1716           ALOGD("SCO/A2DP is selected but they are not connected/ready hence dont route");
1717           return 0;
1718     }
1719 
1720     if ((out_snd_device == SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP ||
1721          out_snd_device == SND_DEVICE_OUT_SPEAKER_SAFE_AND_BT_A2DP) &&
1722         (!audio_extn_a2dp_is_ready())) {
1723         ALOGW("%s: A2DP profile is not ready, routing to speaker only", __func__);
1724         if (out_snd_device == SND_DEVICE_OUT_SPEAKER_SAFE_AND_BT_A2DP)
1725             out_snd_device = SND_DEVICE_OUT_SPEAKER_SAFE;
1726         else
1727             out_snd_device = SND_DEVICE_OUT_SPEAKER;
1728     }
1729 
1730     if (usecase->id == USECASE_INCALL_MUSIC_UPLINK ||
1731         usecase->id == USECASE_INCALL_MUSIC_UPLINK2) {
1732         out_snd_device = SND_DEVICE_OUT_VOICE_MUSIC_TX;
1733     }
1734 
1735     if (out_snd_device != SND_DEVICE_NONE &&
1736             out_snd_device != adev->last_logged_snd_device[uc_id][0]) {
1737         ALOGD("%s: changing use case %s output device from(%d: %s, acdb %d) to (%d: %s, acdb %d)",
1738               __func__,
1739               use_case_table[uc_id],
1740               adev->last_logged_snd_device[uc_id][0],
1741               platform_get_snd_device_name(adev->last_logged_snd_device[uc_id][0]),
1742               adev->last_logged_snd_device[uc_id][0] != SND_DEVICE_NONE ?
1743                       platform_get_snd_device_acdb_id(adev->last_logged_snd_device[uc_id][0]) :
1744                       -1,
1745               out_snd_device,
1746               platform_get_snd_device_name(out_snd_device),
1747               platform_get_snd_device_acdb_id(out_snd_device));
1748         adev->last_logged_snd_device[uc_id][0] = out_snd_device;
1749     }
1750     if (in_snd_device != SND_DEVICE_NONE &&
1751             in_snd_device != adev->last_logged_snd_device[uc_id][1]) {
1752         ALOGD("%s: changing use case %s input device from(%d: %s, acdb %d) to (%d: %s, acdb %d)",
1753               __func__,
1754               use_case_table[uc_id],
1755               adev->last_logged_snd_device[uc_id][1],
1756               platform_get_snd_device_name(adev->last_logged_snd_device[uc_id][1]),
1757               adev->last_logged_snd_device[uc_id][1] != SND_DEVICE_NONE ?
1758                       platform_get_snd_device_acdb_id(adev->last_logged_snd_device[uc_id][1]) :
1759                       -1,
1760               in_snd_device,
1761               platform_get_snd_device_name(in_snd_device),
1762               platform_get_snd_device_acdb_id(in_snd_device));
1763         adev->last_logged_snd_device[uc_id][1] = in_snd_device;
1764     }
1765 
1766     /*
1767      * Limitation: While in call, to do a device switch we need to disable
1768      * and enable both RX and TX devices though one of them is same as current
1769      * device.
1770      */
1771     if ((usecase->type == VOICE_CALL) &&
1772         (usecase->in_snd_device != SND_DEVICE_NONE) &&
1773         (usecase->out_snd_device != SND_DEVICE_NONE)) {
1774         status = platform_switch_voice_call_device_pre(adev->platform);
1775         /* Disable sidetone only if voice call already exists */
1776         if (voice_is_call_state_active(adev))
1777             voice_set_sidetone(adev, usecase->out_snd_device, false);
1778     }
1779 
1780     /* Disable current sound devices */
1781     if (usecase->out_snd_device != SND_DEVICE_NONE) {
1782         disable_audio_route(adev, usecase);
1783         disable_snd_device(adev, usecase->out_snd_device);
1784     }
1785 
1786     if (usecase->in_snd_device != SND_DEVICE_NONE) {
1787         disable_audio_route(adev, usecase);
1788         disable_snd_device(adev, usecase->in_snd_device);
1789     }
1790 
1791     /* Applicable only on the targets that has external modem.
1792      * New device information should be sent to modem before enabling
1793      * the devices to reduce in-call device switch time.
1794      */
1795     if ((usecase->type == VOICE_CALL) &&
1796         (usecase->in_snd_device != SND_DEVICE_NONE) &&
1797         (usecase->out_snd_device != SND_DEVICE_NONE)) {
1798         status = platform_switch_voice_call_enable_device_config(adev->platform,
1799                                                                  out_snd_device,
1800                                                                  in_snd_device);
1801     }
1802 
1803     /* Enable new sound devices */
1804     if (out_snd_device != SND_DEVICE_NONE) {
1805         if ((usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
1806             (usecase->devices & (AUDIO_DEVICE_OUT_USB_DEVICE|AUDIO_DEVICE_OUT_USB_HEADSET)) ||
1807             (usecase->devices & AUDIO_DEVICE_OUT_ALL_A2DP))
1808             check_and_route_playback_usecases(adev, usecase, out_snd_device);
1809         enable_snd_device(adev, out_snd_device);
1810     }
1811 
1812     if (in_snd_device != SND_DEVICE_NONE) {
1813         check_and_route_capture_usecases(adev, usecase, in_snd_device);
1814         enable_snd_device(adev, in_snd_device);
1815     }
1816 
1817     if (usecase->type == VOICE_CALL)
1818         status = platform_switch_voice_call_device_post(adev->platform,
1819                                                         out_snd_device,
1820                                                         in_snd_device);
1821 
1822     usecase->in_snd_device = in_snd_device;
1823     usecase->out_snd_device = out_snd_device;
1824 
1825     audio_extn_tfa_98xx_set_mode();
1826 
1827     enable_audio_route(adev, usecase);
1828 
1829     /* If input stream is already running the effect needs to be
1830        applied on the new input device that's being enabled here.  */
1831     if (in_snd_device != SND_DEVICE_NONE)
1832         check_and_enable_effect(adev);
1833 
1834     /* Applicable only on the targets that has external modem.
1835      * Enable device command should be sent to modem only after
1836      * enabling voice call mixer controls
1837      */
1838     if (usecase->type == VOICE_CALL) {
1839         status = platform_switch_voice_call_usecase_route_post(adev->platform,
1840                                                                out_snd_device,
1841                                                                in_snd_device);
1842          /* Enable sidetone only if voice call already exists */
1843         if (voice_is_call_state_active(adev))
1844             voice_set_sidetone(adev, out_snd_device, true);
1845     }
1846 
1847     if (usecase->type != PCM_CAPTURE && voip_usecase) {
1848         struct stream_out *voip_out = voip_usecase->stream.out;
1849         audio_extn_utils_send_app_type_gain(adev,
1850                                             voip_out->app_type_cfg.app_type,
1851                                             &voip_out->app_type_cfg.gain[0]);
1852     }
1853     return status;
1854 }
1855 
select_devices(struct audio_device * adev,audio_usecase_t uc_id)1856 int select_devices(struct audio_device *adev,
1857                    audio_usecase_t uc_id)
1858 {
1859     return select_devices_with_force_switch(adev, uc_id, false);
1860 }
1861 
stop_input_stream(struct stream_in * in)1862 static int stop_input_stream(struct stream_in *in)
1863 {
1864     int i, ret = 0;
1865     struct audio_usecase *uc_info;
1866     struct audio_device *adev = in->dev;
1867     struct stream_in *priority_in = NULL;
1868 
1869     ALOGV("%s: enter: usecase(%d: %s)", __func__,
1870           in->usecase, use_case_table[in->usecase]);
1871 
1872     uc_info = get_usecase_from_list(adev, in->usecase);
1873     if (uc_info == NULL) {
1874         ALOGE("%s: Could not find the usecase (%d) in the list",
1875               __func__, in->usecase);
1876         return -EINVAL;
1877     }
1878 
1879     priority_in = get_priority_input(adev);
1880 
1881     /* Close in-call recording streams */
1882     voice_check_and_stop_incall_rec_usecase(adev, in);
1883 
1884     /* 1. Disable stream specific mixer controls */
1885     disable_audio_route(adev, uc_info);
1886 
1887     /* 2. Disable the tx device */
1888     disable_snd_device(adev, uc_info->in_snd_device);
1889 
1890     list_remove(&uc_info->list);
1891     free(uc_info);
1892 
1893     if (priority_in == in) {
1894         priority_in = get_priority_input(adev);
1895         if (priority_in)
1896             select_devices(adev, priority_in->usecase);
1897     }
1898 
1899     ALOGV("%s: exit: status(%d)", __func__, ret);
1900     return ret;
1901 }
1902 
start_input_stream(struct stream_in * in)1903 int start_input_stream(struct stream_in *in)
1904 {
1905     /* 1. Enable output device and stream routing controls */
1906     int ret = 0;
1907     struct audio_usecase *uc_info;
1908     struct audio_device *adev = in->dev;
1909 
1910     ALOGV("%s: enter: usecase(%d)", __func__, in->usecase);
1911 
1912     if (audio_extn_tfa_98xx_is_supported() && !audio_ssr_status(adev))
1913         return -EIO;
1914 
1915     if (in->card_status == CARD_STATUS_OFFLINE ||
1916         adev->card_status == CARD_STATUS_OFFLINE) {
1917         ALOGW("in->card_status or adev->card_status offline, try again");
1918         ret = -EAGAIN;
1919         goto error_config;
1920     }
1921 
1922     /* Check if source matches incall recording usecase criteria */
1923     ret = voice_check_and_set_incall_rec_usecase(adev, in);
1924     if (ret)
1925         goto error_config;
1926     else
1927         ALOGV("%s: usecase(%d)", __func__, in->usecase);
1928 
1929     in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
1930     if (in->pcm_device_id < 0) {
1931         ALOGE("%s: Could not find PCM device id for the usecase(%d)",
1932               __func__, in->usecase);
1933         ret = -EINVAL;
1934         goto error_config;
1935     }
1936 
1937     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
1938     uc_info->id = in->usecase;
1939     uc_info->type = PCM_CAPTURE;
1940     uc_info->stream.in = in;
1941     uc_info->devices = in->device;
1942     uc_info->in_snd_device = SND_DEVICE_NONE;
1943     uc_info->out_snd_device = SND_DEVICE_NONE;
1944 
1945     list_add_tail(&adev->usecase_list, &uc_info->list);
1946 
1947     audio_streaming_hint_start();
1948     audio_extn_perf_lock_acquire();
1949 
1950     select_devices(adev, in->usecase);
1951 
1952     if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
1953         if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
1954             ALOGE("%s: pcm stream not ready", __func__);
1955             goto error_open;
1956         }
1957         ret = pcm_start(in->pcm);
1958         if (ret < 0) {
1959             ALOGE("%s: MMAP pcm_start failed ret %d", __func__, ret);
1960             goto error_open;
1961         }
1962     } else {
1963         unsigned int flags = PCM_IN | PCM_MONOTONIC;
1964         unsigned int pcm_open_retry_count = 0;
1965 
1966         if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY) {
1967             flags |= PCM_MMAP | PCM_NOIRQ;
1968             pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
1969         } else if (in->realtime) {
1970             flags |= PCM_MMAP | PCM_NOIRQ;
1971         }
1972 
1973         ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
1974               __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
1975 
1976         while (1) {
1977             in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
1978                                flags, &in->config);
1979             if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
1980                 ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
1981                 if (in->pcm != NULL) {
1982                     pcm_close(in->pcm);
1983                     in->pcm = NULL;
1984                 }
1985                 if (pcm_open_retry_count-- == 0) {
1986                     ret = -EIO;
1987                     goto error_open;
1988                 }
1989                 usleep(PROXY_OPEN_WAIT_TIME * 1000);
1990                 continue;
1991             }
1992             break;
1993         }
1994 
1995         ALOGV("%s: pcm_prepare", __func__);
1996         ret = pcm_prepare(in->pcm);
1997         if (ret < 0) {
1998             ALOGE("%s: pcm_prepare returned %d", __func__, ret);
1999             pcm_close(in->pcm);
2000             in->pcm = NULL;
2001             goto error_open;
2002         }
2003         if (in->realtime) {
2004             ret = pcm_start(in->pcm);
2005             if (ret < 0) {
2006                 ALOGE("%s: RT pcm_start failed ret %d", __func__, ret);
2007                 pcm_close(in->pcm);
2008                 in->pcm = NULL;
2009                 goto error_open;
2010             }
2011         }
2012     }
2013     register_in_stream(in);
2014     check_and_enable_effect(adev);
2015     audio_extn_audiozoom_set_microphone_direction(in, in->zoom);
2016     audio_extn_audiozoom_set_microphone_field_dimension(in, in->direction);
2017     audio_streaming_hint_end();
2018     audio_extn_perf_lock_release();
2019     ALOGV("%s: exit", __func__);
2020 
2021     return 0;
2022 
2023 error_open:
2024     stop_input_stream(in);
2025     audio_streaming_hint_end();
2026     audio_extn_perf_lock_release();
2027 
2028 error_config:
2029     ALOGW("%s: exit: status(%d)", __func__, ret);
2030     return ret;
2031 }
2032 
lock_input_stream(struct stream_in * in)2033 void lock_input_stream(struct stream_in *in)
2034 {
2035     pthread_mutex_lock(&in->pre_lock);
2036     pthread_mutex_lock(&in->lock);
2037     pthread_mutex_unlock(&in->pre_lock);
2038 }
2039 
lock_output_stream(struct stream_out * out)2040 void lock_output_stream(struct stream_out *out)
2041 {
2042     pthread_mutex_lock(&out->pre_lock);
2043     pthread_mutex_lock(&out->lock);
2044     pthread_mutex_unlock(&out->pre_lock);
2045 }
2046 
2047 /* must be called with out->lock locked */
send_offload_cmd_l(struct stream_out * out,int command)2048 static int send_offload_cmd_l(struct stream_out* out, int command)
2049 {
2050     struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));
2051 
2052     ALOGVV("%s %d", __func__, command);
2053 
2054     cmd->cmd = command;
2055     list_add_tail(&out->offload_cmd_list, &cmd->node);
2056     pthread_cond_signal(&out->offload_cond);
2057     return 0;
2058 }
2059 
2060 /* must be called iwth out->lock locked */
stop_compressed_output_l(struct stream_out * out)2061 static void stop_compressed_output_l(struct stream_out *out)
2062 {
2063     out->offload_state = OFFLOAD_STATE_IDLE;
2064     out->playback_started = 0;
2065     out->send_new_metadata = 1;
2066     if (out->compr != NULL) {
2067         compress_stop(out->compr);
2068         while (out->offload_thread_blocked) {
2069             pthread_cond_wait(&out->cond, &out->lock);
2070         }
2071     }
2072 }
2073 
offload_thread_loop(void * context)2074 static void *offload_thread_loop(void *context)
2075 {
2076     struct stream_out *out = (struct stream_out *) context;
2077     struct listnode *item;
2078 
2079     setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
2080     set_sched_policy(0, SP_FOREGROUND);
2081     prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);
2082 
2083     ALOGV("%s", __func__);
2084 
2085     lock_output_stream(out);
2086     out->offload_state = OFFLOAD_STATE_IDLE;
2087     out->playback_started = 0;
2088     for (;;) {
2089         struct offload_cmd *cmd = NULL;
2090         stream_callback_event_t event;
2091         bool send_callback = false;
2092 
2093         ALOGVV("%s offload_cmd_list %d out->offload_state %d",
2094               __func__, list_empty(&out->offload_cmd_list),
2095               out->offload_state);
2096         if (list_empty(&out->offload_cmd_list)) {
2097             ALOGV("%s SLEEPING", __func__);
2098             pthread_cond_wait(&out->offload_cond, &out->lock);
2099             ALOGV("%s RUNNING", __func__);
2100             continue;
2101         }
2102 
2103         item = list_head(&out->offload_cmd_list);
2104         cmd = node_to_item(item, struct offload_cmd, node);
2105         list_remove(item);
2106 
2107         ALOGVV("%s STATE %d CMD %d out->compr %p",
2108                __func__, out->offload_state, cmd->cmd, out->compr);
2109 
2110         if (cmd->cmd == OFFLOAD_CMD_EXIT) {
2111             free(cmd);
2112             break;
2113         }
2114 
2115         if (out->compr == NULL) {
2116             ALOGE("%s: Compress handle is NULL", __func__);
2117             free(cmd);
2118             pthread_cond_signal(&out->cond);
2119             continue;
2120         }
2121         out->offload_thread_blocked = true;
2122         pthread_mutex_unlock(&out->lock);
2123         send_callback = false;
2124         switch (cmd->cmd) {
2125         case OFFLOAD_CMD_WAIT_FOR_BUFFER:
2126             compress_wait(out->compr, -1);
2127             send_callback = true;
2128             event = STREAM_CBK_EVENT_WRITE_READY;
2129             break;
2130         case OFFLOAD_CMD_PARTIAL_DRAIN:
2131             compress_next_track(out->compr);
2132             compress_partial_drain(out->compr);
2133             send_callback = true;
2134             event = STREAM_CBK_EVENT_DRAIN_READY;
2135             /* Resend the metadata for next iteration */
2136             out->send_new_metadata = 1;
2137             break;
2138         case OFFLOAD_CMD_DRAIN:
2139             compress_drain(out->compr);
2140             send_callback = true;
2141             event = STREAM_CBK_EVENT_DRAIN_READY;
2142             break;
2143         case OFFLOAD_CMD_ERROR:
2144             send_callback = true;
2145             event = STREAM_CBK_EVENT_ERROR;
2146             break;
2147         default:
2148             ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
2149             break;
2150         }
2151         lock_output_stream(out);
2152         out->offload_thread_blocked = false;
2153         pthread_cond_signal(&out->cond);
2154         if (send_callback) {
2155             ALOGVV("%s: sending offload_callback event %d", __func__, event);
2156             out->offload_callback(event, NULL, out->offload_cookie);
2157         }
2158         free(cmd);
2159     }
2160 
2161     pthread_cond_signal(&out->cond);
2162     while (!list_empty(&out->offload_cmd_list)) {
2163         item = list_head(&out->offload_cmd_list);
2164         list_remove(item);
2165         free(node_to_item(item, struct offload_cmd, node));
2166     }
2167     pthread_mutex_unlock(&out->lock);
2168 
2169     return NULL;
2170 }
2171 
create_offload_callback_thread(struct stream_out * out)2172 static int create_offload_callback_thread(struct stream_out *out)
2173 {
2174     pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
2175     list_init(&out->offload_cmd_list);
2176     pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
2177                     offload_thread_loop, out);
2178     return 0;
2179 }
2180 
destroy_offload_callback_thread(struct stream_out * out)2181 static int destroy_offload_callback_thread(struct stream_out *out)
2182 {
2183     lock_output_stream(out);
2184     stop_compressed_output_l(out);
2185     send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);
2186 
2187     pthread_mutex_unlock(&out->lock);
2188     pthread_join(out->offload_thread, (void **) NULL);
2189     pthread_cond_destroy(&out->offload_cond);
2190 
2191     return 0;
2192 }
2193 
allow_hdmi_channel_config(struct audio_device * adev)2194 static bool allow_hdmi_channel_config(struct audio_device *adev)
2195 {
2196     struct listnode *node;
2197     struct audio_usecase *usecase;
2198     bool ret = true;
2199 
2200     list_for_each(node, &adev->usecase_list) {
2201         usecase = node_to_item(node, struct audio_usecase, list);
2202         if (usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
2203             /*
2204              * If voice call is already existing, do not proceed further to avoid
2205              * disabling/enabling both RX and TX devices, CSD calls, etc.
2206              * Once the voice call done, the HDMI channels can be configured to
2207              * max channels of remaining use cases.
2208              */
2209             if (usecase->id == USECASE_VOICE_CALL) {
2210                 ALOGV("%s: voice call is active, no change in HDMI channels",
2211                       __func__);
2212                 ret = false;
2213                 break;
2214             } else if (usecase->id == USECASE_AUDIO_PLAYBACK_HIFI) {
2215                 ALOGV("%s: hifi playback is active, "
2216                       "no change in HDMI channels", __func__);
2217                 ret = false;
2218                 break;
2219             }
2220         }
2221     }
2222     return ret;
2223 }
2224 
check_and_set_hdmi_channels(struct audio_device * adev,unsigned int channels)2225 static int check_and_set_hdmi_channels(struct audio_device *adev,
2226                                        unsigned int channels)
2227 {
2228     struct listnode *node;
2229     struct audio_usecase *usecase;
2230 
2231     /* Check if change in HDMI channel config is allowed */
2232     if (!allow_hdmi_channel_config(adev))
2233         return 0;
2234 
2235     if (channels == adev->cur_hdmi_channels) {
2236         ALOGV("%s: Requested channels are same as current", __func__);
2237         return 0;
2238     }
2239 
2240     platform_set_hdmi_channels(adev->platform, channels);
2241     adev->cur_hdmi_channels = channels;
2242 
2243     /*
2244      * Deroute all the playback streams routed to HDMI so that
2245      * the back end is deactivated. Note that backend will not
2246      * be deactivated if any one stream is connected to it.
2247      */
2248     list_for_each(node, &adev->usecase_list) {
2249         usecase = node_to_item(node, struct audio_usecase, list);
2250         if (usecase->type == PCM_PLAYBACK &&
2251                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
2252             disable_audio_route(adev, usecase);
2253         }
2254     }
2255 
2256     /*
2257      * Enable all the streams disabled above. Now the HDMI backend
2258      * will be activated with new channel configuration
2259      */
2260     list_for_each(node, &adev->usecase_list) {
2261         usecase = node_to_item(node, struct audio_usecase, list);
2262         if (usecase->type == PCM_PLAYBACK &&
2263                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
2264             enable_audio_route(adev, usecase);
2265         }
2266     }
2267 
2268     return 0;
2269 }
2270 
check_and_set_usb_service_interval(struct audio_device * adev,struct audio_usecase * uc_info,bool min)2271 static int check_and_set_usb_service_interval(struct audio_device *adev,
2272                                               struct audio_usecase *uc_info,
2273                                               bool min)
2274 {
2275     struct listnode *node;
2276     struct audio_usecase *usecase;
2277     bool switch_usecases = false;
2278     bool reconfig = false;
2279 
2280     if ((uc_info->id != USECASE_AUDIO_PLAYBACK_MMAP) &&
2281         (uc_info->id != USECASE_AUDIO_PLAYBACK_ULL))
2282         return -1;
2283 
2284     /* set if the valid usecase do not already exist */
2285     list_for_each(node, &adev->usecase_list) {
2286         usecase = node_to_item(node, struct audio_usecase, list);
2287         if (usecase->type == PCM_PLAYBACK &&
2288             (audio_is_usb_out_device(usecase->devices & AUDIO_DEVICE_OUT_ALL_USB))) {
2289             switch (usecase->id) {
2290                 case USECASE_AUDIO_PLAYBACK_MMAP:
2291                 case USECASE_AUDIO_PLAYBACK_ULL:
2292                     // cannot reconfig while mmap/ull is present.
2293                     return -1;
2294                 default:
2295                     switch_usecases = true;
2296                     break;
2297             }
2298         }
2299         if (switch_usecases)
2300             break;
2301     }
2302     /*
2303      * client can try to set service interval in start_output_stream
2304      * to min or to 0 (i.e reset) in stop_output_stream .
2305      */
2306     unsigned long service_interval =
2307             audio_extn_usb_find_service_interval(min, true /*playback*/);
2308     int ret = platform_set_usb_service_interval(adev->platform,
2309                                                 true /*playback*/,
2310                                                 service_interval,
2311                                                 &reconfig);
2312     /* no change or not supported or no active usecases */
2313     if (ret || !reconfig || !switch_usecases)
2314         return -1;
2315     return 0;
2316 #undef VALID_USECASE
2317 }
2318 
stop_output_stream(struct stream_out * out)2319 static int stop_output_stream(struct stream_out *out)
2320 {
2321     int i, ret = 0;
2322     struct audio_usecase *uc_info;
2323     struct audio_device *adev = out->dev;
2324 
2325     ALOGV("%s: enter: usecase(%d: %s)", __func__,
2326           out->usecase, use_case_table[out->usecase]);
2327     uc_info = get_usecase_from_list(adev, out->usecase);
2328     if (uc_info == NULL) {
2329         ALOGE("%s: Could not find the usecase (%d) in the list",
2330               __func__, out->usecase);
2331         return -EINVAL;
2332     }
2333 
2334     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2335         if (adev->visualizer_stop_output != NULL)
2336             adev->visualizer_stop_output(out->handle, out->pcm_device_id);
2337         if (adev->offload_effects_stop_output != NULL)
2338             adev->offload_effects_stop_output(out->handle, out->pcm_device_id);
2339     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_ULL ||
2340                out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
2341         audio_low_latency_hint_end();
2342     }
2343 
2344     if (out->usecase == USECASE_INCALL_MUSIC_UPLINK ||
2345         out->usecase == USECASE_INCALL_MUSIC_UPLINK2) {
2346         voice_set_device_mute_flag(adev, false);
2347     }
2348 
2349     /* 1. Get and set stream specific mixer controls */
2350     disable_audio_route(adev, uc_info);
2351 
2352     /* 2. Disable the rx device */
2353     disable_snd_device(adev, uc_info->out_snd_device);
2354 
2355     list_remove(&uc_info->list);
2356 
2357     audio_extn_extspk_update(adev->extspk);
2358 
2359     /* Must be called after removing the usecase from list */
2360     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
2361         check_and_set_hdmi_channels(adev, DEFAULT_HDMI_OUT_CHANNELS);
2362     else if (audio_is_usb_out_device(out->devices & AUDIO_DEVICE_OUT_ALL_USB)) {
2363         ret = check_and_set_usb_service_interval(adev, uc_info, false /*min*/);
2364         if (ret == 0) {
2365             /* default service interval was successfully updated,
2366                reopen USB backend with new service interval */
2367             check_and_route_playback_usecases(adev, uc_info, uc_info->out_snd_device);
2368         }
2369         ret = 0;
2370     }
2371     /* 1) media + voip output routing to handset must route media back to
2372           speaker when voip stops.
2373        2) trigger voip input to reroute when voip output changes to
2374           hearing aid. */
2375     if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP ||
2376         out->devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
2377         struct listnode *node;
2378         struct audio_usecase *usecase;
2379         list_for_each(node, &adev->usecase_list) {
2380             usecase = node_to_item(node, struct audio_usecase, list);
2381             if ((usecase->type == PCM_CAPTURE &&
2382                      usecase->id != USECASE_AUDIO_RECORD_VOIP)
2383                 || usecase == uc_info)
2384                 continue;
2385 
2386             ALOGD("%s: select_devices at usecase(%d: %s) after removing the usecase(%d: %s)",
2387                 __func__, usecase->id, use_case_table[usecase->id],
2388                 out->usecase, use_case_table[out->usecase]);
2389             select_devices(adev, usecase->id);
2390         }
2391     }
2392 
2393     free(uc_info);
2394     ALOGV("%s: exit: status(%d)", __func__, ret);
2395     return ret;
2396 }
2397 
pcm_open_prepare_helper(unsigned int snd_card,unsigned int pcm_device_id,unsigned int flags,unsigned int pcm_open_retry_count,struct pcm_config * config)2398 struct pcm* pcm_open_prepare_helper(unsigned int snd_card, unsigned int pcm_device_id,
2399                                    unsigned int flags, unsigned int pcm_open_retry_count,
2400                                    struct pcm_config *config)
2401 {
2402     struct pcm* pcm = NULL;
2403 
2404     while (1) {
2405         pcm = pcm_open(snd_card, pcm_device_id, flags, config);
2406         if (pcm == NULL || !pcm_is_ready(pcm)) {
2407             ALOGE("%s: %s", __func__, pcm_get_error(pcm));
2408             if (pcm != NULL) {
2409                 pcm_close(pcm);
2410                 pcm = NULL;
2411             }
2412             if (pcm_open_retry_count-- == 0)
2413                 return NULL;
2414 
2415             usleep(PROXY_OPEN_WAIT_TIME * 1000);
2416             continue;
2417         }
2418         break;
2419     }
2420 
2421     if (pcm_is_ready(pcm)) {
2422         int ret = pcm_prepare(pcm);
2423         if (ret < 0) {
2424             ALOGE("%s: pcm_prepare returned %d", __func__, ret);
2425             pcm_close(pcm);
2426             pcm = NULL;
2427         }
2428     }
2429 
2430     return pcm;
2431 }
2432 
start_output_stream(struct stream_out * out)2433 int start_output_stream(struct stream_out *out)
2434 {
2435     int ret = 0;
2436     struct audio_usecase *uc_info;
2437     struct audio_device *adev = out->dev;
2438     bool a2dp_combo = false;
2439 
2440     ALOGV("%s: enter: usecase(%d: %s) %s devices(%#x)",
2441           __func__, out->usecase, use_case_table[out->usecase],
2442           out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS ? "(with haptics)" : "",
2443           out->devices);
2444 
2445     if (out->card_status == CARD_STATUS_OFFLINE ||
2446         adev->card_status == CARD_STATUS_OFFLINE) {
2447         ALOGW("out->card_status or adev->card_status offline, try again");
2448         ret = -EAGAIN;
2449         goto error_config;
2450     }
2451 
2452     //Update incall music usecase to reflect correct voice session
2453     if (out->flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) {
2454         ret = voice_extn_check_and_set_incall_music_usecase(adev, out);
2455         if (ret != 0) {
2456             ALOGE("%s: Incall music delivery usecase cannot be set error:%d",
2457                 __func__, ret);
2458             goto error_config;
2459         }
2460     }
2461 
2462     if (out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) {
2463         if (!audio_extn_a2dp_is_ready()) {
2464             if (out->devices & (AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2465                 a2dp_combo = true;
2466             } else {
2467                 if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
2468                     ALOGE("%s: A2DP profile is not ready, return error", __func__);
2469                     ret = -EAGAIN;
2470                     goto error_config;
2471                 }
2472             }
2473         }
2474     }
2475     out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
2476     if (out->pcm_device_id < 0) {
2477         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
2478               __func__, out->pcm_device_id, out->usecase);
2479         ret = -EINVAL;
2480         goto error_config;
2481     }
2482 
2483     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
2484     uc_info->id = out->usecase;
2485     uc_info->type = PCM_PLAYBACK;
2486     uc_info->stream.out = out;
2487     uc_info->devices = out->devices;
2488     uc_info->in_snd_device = SND_DEVICE_NONE;
2489     uc_info->out_snd_device = SND_DEVICE_NONE;
2490 
2491     /* This must be called before adding this usecase to the list */
2492     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
2493         check_and_set_hdmi_channels(adev, out->config.channels);
2494     else if (audio_is_usb_out_device(out->devices & AUDIO_DEVICE_OUT_ALL_USB)) {
2495         check_and_set_usb_service_interval(adev, uc_info, true /*min*/);
2496         /* USB backend is not reopened immediately.
2497            This is eventually done as part of select_devices */
2498     }
2499 
2500     list_add_tail(&adev->usecase_list, &uc_info->list);
2501 
2502     audio_streaming_hint_start();
2503     audio_extn_perf_lock_acquire();
2504 
2505     if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
2506         (!audio_extn_a2dp_is_ready())) {
2507         if (!a2dp_combo) {
2508             check_a2dp_restore_l(adev, out, false);
2509         } else {
2510             audio_devices_t dev = out->devices;
2511             if (dev & AUDIO_DEVICE_OUT_SPEAKER_SAFE)
2512                 out->devices = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
2513             else
2514                 out->devices = AUDIO_DEVICE_OUT_SPEAKER;
2515             select_devices(adev, out->usecase);
2516             out->devices = dev;
2517         }
2518     } else {
2519          select_devices(adev, out->usecase);
2520     }
2521 
2522     audio_extn_extspk_update(adev->extspk);
2523 
2524     if (out->usecase == USECASE_INCALL_MUSIC_UPLINK ||
2525         out->usecase == USECASE_INCALL_MUSIC_UPLINK2) {
2526         voice_set_device_mute_flag(adev, true);
2527     }
2528 
2529     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d) format(%#x)",
2530           __func__, adev->snd_card, out->pcm_device_id, out->config.format);
2531     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2532         out->pcm = NULL;
2533         out->compr = compress_open(adev->snd_card, out->pcm_device_id,
2534                                    COMPRESS_IN, &out->compr_config);
2535         if (out->compr && !is_compress_ready(out->compr)) {
2536             ALOGE("%s: %s", __func__, compress_get_error(out->compr));
2537             compress_close(out->compr);
2538             out->compr = NULL;
2539             ret = -EIO;
2540             goto error_open;
2541         }
2542         if (out->offload_callback)
2543             compress_nonblock(out->compr, out->non_blocking);
2544 
2545         if (adev->visualizer_start_output != NULL) {
2546             int capture_device_id =
2547                 platform_get_pcm_device_id(USECASE_AUDIO_RECORD_AFE_PROXY,
2548                                            PCM_CAPTURE);
2549             adev->visualizer_start_output(out->handle, out->pcm_device_id,
2550                                           adev->snd_card, capture_device_id);
2551         }
2552         if (adev->offload_effects_start_output != NULL)
2553             adev->offload_effects_start_output(out->handle, out->pcm_device_id);
2554     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
2555         if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
2556             ALOGE("%s: pcm stream not ready", __func__);
2557             goto error_open;
2558         }
2559         ret = pcm_start(out->pcm);
2560         if (ret < 0) {
2561             ALOGE("%s: MMAP pcm_start failed ret %d", __func__, ret);
2562             goto error_open;
2563         }
2564     } else {
2565         unsigned int flags = PCM_OUT | PCM_MONOTONIC;
2566         unsigned int pcm_open_retry_count = 0;
2567 
2568         if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY) {
2569             flags |= PCM_MMAP | PCM_NOIRQ;
2570             pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
2571         } else if (out->realtime) {
2572             flags |= PCM_MMAP | PCM_NOIRQ;
2573         }
2574 
2575         out->pcm = pcm_open_prepare_helper(adev->snd_card, out->pcm_device_id,
2576                                        flags, pcm_open_retry_count,
2577                                        &(out->config));
2578         if (out->pcm == NULL) {
2579            ret = -EIO;
2580            goto error_open;
2581         }
2582 
2583         if (out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS) {
2584             if (adev->haptic_pcm != NULL) {
2585                 pcm_close(adev->haptic_pcm);
2586                 adev->haptic_pcm = NULL;
2587             }
2588             adev->haptic_pcm = pcm_open_prepare_helper(adev->snd_card,
2589                                    adev->haptic_pcm_device_id,
2590                                    flags, pcm_open_retry_count,
2591                                    &(adev->haptics_config));
2592             // failure to open haptics pcm shouldnt stop audio,
2593             // so do not close audio pcm in case of error
2594         }
2595 
2596         if (out->realtime) {
2597             ret = pcm_start(out->pcm);
2598             if (ret < 0) {
2599                 ALOGE("%s: RT pcm_start failed ret %d", __func__, ret);
2600                 pcm_close(out->pcm);
2601                 out->pcm = NULL;
2602                 goto error_open;
2603             }
2604         }
2605     }
2606 
2607     register_out_stream(out);
2608     audio_streaming_hint_end();
2609     audio_extn_perf_lock_release();
2610     audio_extn_tfa_98xx_enable_speaker();
2611 
2612     if (out->usecase == USECASE_AUDIO_PLAYBACK_ULL ||
2613         out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
2614         audio_low_latency_hint_start();
2615     }
2616 
2617     // consider a scenario where on pause lower layers are tear down.
2618     // so on resume, swap mixer control need to be sent only when
2619     // backend is active, hence rather than sending from enable device
2620     // sending it from start of stream
2621 
2622     platform_set_swap_channels(adev, true);
2623 
2624     ALOGV("%s: exit", __func__);
2625     return 0;
2626 error_open:
2627     if (adev->haptic_pcm) {
2628         pcm_close(adev->haptic_pcm);
2629         adev->haptic_pcm = NULL;
2630     }
2631     audio_streaming_hint_end();
2632     audio_extn_perf_lock_release();
2633     stop_output_stream(out);
2634 error_config:
2635     return ret;
2636 }
2637 
check_input_parameters(uint32_t sample_rate,audio_format_t format,int channel_count,bool is_usb_hifi)2638 static int check_input_parameters(uint32_t sample_rate,
2639                                   audio_format_t format,
2640                                   int channel_count, bool is_usb_hifi)
2641 {
2642     if ((format != AUDIO_FORMAT_PCM_16_BIT) &&
2643         (format != AUDIO_FORMAT_PCM_8_24_BIT) &&
2644         (format != AUDIO_FORMAT_PCM_24_BIT_PACKED) &&
2645         !(is_usb_hifi && (format == AUDIO_FORMAT_PCM_32_BIT))) {
2646         ALOGE("%s: unsupported AUDIO FORMAT (%d) ", __func__, format);
2647         return -EINVAL;
2648     }
2649 
2650     int max_channel_count = is_usb_hifi ? MAX_HIFI_CHANNEL_COUNT : MAX_CHANNEL_COUNT;
2651     if ((channel_count < MIN_CHANNEL_COUNT) || (channel_count > max_channel_count)) {
2652         ALOGE("%s: unsupported channel count (%d) passed  Min / Max (%d / %d)", __func__,
2653                channel_count, MIN_CHANNEL_COUNT, max_channel_count);
2654         return -EINVAL;
2655     }
2656 
2657     switch (sample_rate) {
2658     case 8000:
2659     case 11025:
2660     case 12000:
2661     case 16000:
2662     case 22050:
2663     case 24000:
2664     case 32000:
2665     case 44100:
2666     case 48000:
2667     case 96000:
2668         break;
2669     default:
2670         ALOGE("%s: unsupported (%d) samplerate passed ", __func__, sample_rate);
2671         return -EINVAL;
2672     }
2673 
2674     return 0;
2675 }
2676 
2677 /** Add a value in a list if not already present.
2678  * @return true if value was successfully inserted or already present,
2679  *         false if the list is full and does not contain the value.
2680  */
register_uint(uint32_t value,uint32_t * list,size_t list_length)2681 static bool register_uint(uint32_t value, uint32_t* list, size_t list_length) {
2682     for (size_t i = 0; i < list_length; i++) {
2683         if (list[i] == value) return true; // value is already present
2684         if (list[i] == 0) { // no values in this slot
2685             list[i] = value;
2686             return true; // value inserted
2687         }
2688     }
2689     return false; // could not insert value
2690 }
2691 
2692 /** Add channel_mask in supported_channel_masks if not already present.
2693  * @return true if channel_mask was successfully inserted or already present,
2694  *         false if supported_channel_masks is full and does not contain channel_mask.
2695  */
register_channel_mask(audio_channel_mask_t channel_mask,audio_channel_mask_t supported_channel_masks[static MAX_SUPPORTED_CHANNEL_MASKS])2696 static void register_channel_mask(audio_channel_mask_t channel_mask,
2697             audio_channel_mask_t supported_channel_masks[static MAX_SUPPORTED_CHANNEL_MASKS]) {
2698     ALOGE_IF(!register_uint(channel_mask, supported_channel_masks, MAX_SUPPORTED_CHANNEL_MASKS),
2699         "%s: stream can not declare supporting its channel_mask %x", __func__, channel_mask);
2700 }
2701 
2702 /** Add format in supported_formats if not already present.
2703  * @return true if format was successfully inserted or already present,
2704  *         false if supported_formats is full and does not contain format.
2705  */
register_format(audio_format_t format,audio_format_t supported_formats[static MAX_SUPPORTED_FORMATS])2706 static void register_format(audio_format_t format,
2707             audio_format_t supported_formats[static MAX_SUPPORTED_FORMATS]) {
2708     ALOGE_IF(!register_uint(format, supported_formats, MAX_SUPPORTED_FORMATS),
2709              "%s: stream can not declare supporting its format %x", __func__, format);
2710 }
2711 /** Add sample_rate in supported_sample_rates if not already present.
2712  * @return true if sample_rate was successfully inserted or already present,
2713  *         false if supported_sample_rates is full and does not contain sample_rate.
2714  */
register_sample_rate(uint32_t sample_rate,uint32_t supported_sample_rates[static MAX_SUPPORTED_SAMPLE_RATES])2715 static void register_sample_rate(uint32_t sample_rate,
2716             uint32_t supported_sample_rates[static MAX_SUPPORTED_SAMPLE_RATES]) {
2717     ALOGE_IF(!register_uint(sample_rate, supported_sample_rates, MAX_SUPPORTED_SAMPLE_RATES),
2718              "%s: stream can not declare supporting its sample rate %x", __func__, sample_rate);
2719 }
2720 
get_stream_buffer_size(size_t duration_ms,uint32_t sample_rate,audio_format_t format,int channel_count,bool is_low_latency)2721 static size_t get_stream_buffer_size(size_t duration_ms,
2722                                      uint32_t sample_rate,
2723                                      audio_format_t format,
2724                                      int channel_count,
2725                                      bool is_low_latency)
2726 {
2727     size_t size = 0;
2728 
2729     size = (sample_rate * duration_ms) / 1000;
2730     if (is_low_latency)
2731         size = configured_low_latency_capture_period_size;
2732 
2733     size *= channel_count * audio_bytes_per_sample(format);
2734 
2735     /* make sure the size is multiple of 32 bytes
2736      * At 48 kHz mono 16-bit PCM:
2737      *  5.000 ms = 240 frames = 15*16*1*2 = 480, a whole multiple of 32 (15)
2738      *  3.333 ms = 160 frames = 10*16*1*2 = 320, a whole multiple of 32 (10)
2739      */
2740     size += 0x1f;
2741     size &= ~0x1f;
2742 
2743     return size;
2744 }
2745 
out_get_sample_rate(const struct audio_stream * stream)2746 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
2747 {
2748     struct stream_out *out = (struct stream_out *)stream;
2749 
2750     return out->sample_rate;
2751 }
2752 
out_set_sample_rate(struct audio_stream * stream __unused,uint32_t rate __unused)2753 static int out_set_sample_rate(struct audio_stream *stream __unused, uint32_t rate __unused)
2754 {
2755     return -ENOSYS;
2756 }
2757 
out_get_buffer_size(const struct audio_stream * stream)2758 static size_t out_get_buffer_size(const struct audio_stream *stream)
2759 {
2760     struct stream_out *out = (struct stream_out *)stream;
2761 
2762     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2763         return out->compr_config.fragment_size;
2764     }
2765     return out->config.period_size * out->af_period_multiplier *
2766                 audio_stream_out_frame_size((const struct audio_stream_out *)stream);
2767 }
2768 
out_get_channels(const struct audio_stream * stream)2769 static uint32_t out_get_channels(const struct audio_stream *stream)
2770 {
2771     struct stream_out *out = (struct stream_out *)stream;
2772 
2773     return out->channel_mask;
2774 }
2775 
out_get_format(const struct audio_stream * stream)2776 static audio_format_t out_get_format(const struct audio_stream *stream)
2777 {
2778     struct stream_out *out = (struct stream_out *)stream;
2779 
2780     return out->format;
2781 }
2782 
out_set_format(struct audio_stream * stream __unused,audio_format_t format __unused)2783 static int out_set_format(struct audio_stream *stream __unused, audio_format_t format __unused)
2784 {
2785     return -ENOSYS;
2786 }
2787 
2788 /* must be called with out->lock locked */
out_standby_l(struct audio_stream * stream)2789 static int out_standby_l(struct audio_stream *stream)
2790 {
2791     struct stream_out *out = (struct stream_out *)stream;
2792     struct audio_device *adev = out->dev;
2793     bool do_stop = true;
2794 
2795     if (!out->standby) {
2796         if (adev->adm_deregister_stream)
2797             adev->adm_deregister_stream(adev->adm_data, out->handle);
2798         pthread_mutex_lock(&adev->lock);
2799         out->standby = true;
2800         if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2801             if (out->pcm) {
2802                 pcm_close(out->pcm);
2803                 out->pcm = NULL;
2804 
2805                 if (out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS) {
2806                     if (adev->haptic_pcm) {
2807                         pcm_close(adev->haptic_pcm);
2808                         adev->haptic_pcm = NULL;
2809                     }
2810 
2811                     if (adev->haptic_buffer != NULL) {
2812                         free(adev->haptic_buffer);
2813                         adev->haptic_buffer = NULL;
2814                         adev->haptic_buffer_size = 0;
2815                     }
2816                 }
2817             }
2818             if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
2819                 do_stop = out->playback_started;
2820                 out->playback_started = false;
2821 
2822                 if (out->mmap_shared_memory_fd >= 0) {
2823                     ALOGV("%s: closing mmap_shared_memory_fd = %d",
2824                           __func__, out->mmap_shared_memory_fd);
2825                     close(out->mmap_shared_memory_fd);
2826                     out->mmap_shared_memory_fd = -1;
2827                 }
2828 
2829             }
2830         } else {
2831             stop_compressed_output_l(out);
2832             out->gapless_mdata.encoder_delay = 0;
2833             out->gapless_mdata.encoder_padding = 0;
2834             if (out->compr != NULL) {
2835                 compress_close(out->compr);
2836                 out->compr = NULL;
2837             }
2838         }
2839         if (do_stop) {
2840             stop_output_stream(out);
2841         }
2842         pthread_mutex_unlock(&adev->lock);
2843     }
2844     return 0;
2845 }
2846 
out_standby(struct audio_stream * stream)2847 static int out_standby(struct audio_stream *stream)
2848 {
2849     struct stream_out *out = (struct stream_out *)stream;
2850 
2851     ALOGV("%s: enter: usecase(%d: %s)", __func__,
2852           out->usecase, use_case_table[out->usecase]);
2853 
2854     lock_output_stream(out);
2855     out_standby_l(stream);
2856     pthread_mutex_unlock(&out->lock);
2857     ALOGV("%s: exit", __func__);
2858     return 0;
2859 }
2860 
out_on_error(struct audio_stream * stream)2861 static int out_on_error(struct audio_stream *stream)
2862 {
2863     struct stream_out *out = (struct stream_out *)stream;
2864     struct audio_device *adev = out->dev;
2865     bool do_standby = false;
2866 
2867     lock_output_stream(out);
2868     if (!out->standby) {
2869         if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2870             stop_compressed_output_l(out);
2871             send_offload_cmd_l(out, OFFLOAD_CMD_ERROR);
2872         } else
2873             do_standby = true;
2874     }
2875     pthread_mutex_unlock(&out->lock);
2876 
2877     if (do_standby)
2878         return out_standby(&out->stream.common);
2879 
2880     return 0;
2881 }
2882 
out_dump(const struct audio_stream * stream,int fd)2883 static int out_dump(const struct audio_stream *stream, int fd)
2884 {
2885     struct stream_out *out = (struct stream_out *)stream;
2886 
2887     // We try to get the lock for consistency,
2888     // but it isn't necessary for these variables.
2889     // If we're not in standby, we may be blocked on a write.
2890     const bool locked = (pthread_mutex_trylock(&out->lock) == 0);
2891     dprintf(fd, "      Standby: %s\n", out->standby ? "yes" : "no");
2892     dprintf(fd, "      Frames written: %lld\n", (long long)out->written);
2893 
2894     char buffer[256]; // for statistics formatting
2895     simple_stats_to_string(&out->fifo_underruns, buffer, sizeof(buffer));
2896     dprintf(fd, "      Fifo frame underruns: %s\n", buffer);
2897 
2898     if (out->start_latency_ms.n > 0) {
2899         simple_stats_to_string(&out->start_latency_ms, buffer, sizeof(buffer));
2900         dprintf(fd, "      Start latency ms: %s\n", buffer);
2901     }
2902 
2903     if (locked) {
2904         pthread_mutex_unlock(&out->lock);
2905     }
2906 
2907     // dump error info
2908     (void)error_log_dump(
2909             out->error_log, fd, "      " /* prefix */, 0 /* lines */, 0 /* limit_ns */);
2910 
2911     return 0;
2912 }
2913 
parse_compress_metadata(struct stream_out * out,struct str_parms * parms)2914 static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
2915 {
2916     int ret = 0;
2917     char value[32];
2918     struct compr_gapless_mdata tmp_mdata;
2919 
2920     if (!out || !parms) {
2921         return -EINVAL;
2922     }
2923 
2924     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
2925     if (ret >= 0) {
2926         tmp_mdata.encoder_delay = atoi(value); //whats a good limit check?
2927     } else {
2928         return -EINVAL;
2929     }
2930 
2931     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
2932     if (ret >= 0) {
2933         tmp_mdata.encoder_padding = atoi(value);
2934     } else {
2935         return -EINVAL;
2936     }
2937 
2938     out->gapless_mdata = tmp_mdata;
2939     out->send_new_metadata = 1;
2940     ALOGV("%s new encoder delay %u and padding %u", __func__,
2941           out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);
2942 
2943     return 0;
2944 }
2945 
output_drives_call(struct audio_device * adev,struct stream_out * out)2946 static bool output_drives_call(struct audio_device *adev, struct stream_out *out)
2947 {
2948     return out == adev->primary_output || out == adev->voice_tx_output;
2949 }
2950 
get_alive_usb_card(struct str_parms * parms)2951 static int get_alive_usb_card(struct str_parms* parms) {
2952     int card;
2953     if ((str_parms_get_int(parms, "card", &card) >= 0) &&
2954         !audio_extn_usb_alive(card)) {
2955         return card;
2956     }
2957     return -ENODEV;
2958 }
2959 
out_set_parameters(struct audio_stream * stream,const char * kvpairs)2960 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
2961 {
2962     struct stream_out *out = (struct stream_out *)stream;
2963     struct audio_device *adev = out->dev;
2964     struct audio_usecase *usecase;
2965     struct listnode *node;
2966     struct str_parms *parms;
2967     char value[32];
2968     int ret, val = 0;
2969     bool select_new_device = false;
2970     int status = 0;
2971     bool bypass_a2dp = false;
2972 
2973     ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s",
2974           __func__, out->usecase, use_case_table[out->usecase], kvpairs);
2975     parms = str_parms_create_str(kvpairs);
2976     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
2977     if (ret >= 0) {
2978         val = atoi(value);
2979 
2980         lock_output_stream(out);
2981 
2982         // The usb driver needs to be closed after usb device disconnection
2983         // otherwise audio is no longer played on the new usb devices.
2984         // By forcing the stream in standby, the usb stack refcount drops to 0
2985         // and the driver is closed.
2986         if (val == AUDIO_DEVICE_NONE &&
2987                 audio_is_usb_out_device(out->devices)) {
2988             if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2989                 ALOGD("%s() putting the usb device in standby after disconnection", __func__);
2990                 out_standby_l(&out->stream.common);
2991             }
2992             val = AUDIO_DEVICE_OUT_SPEAKER;
2993         }
2994 
2995         pthread_mutex_lock(&adev->lock);
2996 
2997         /*
2998          * When HDMI cable is unplugged the music playback is paused and
2999          * the policy manager sends routing=0. But the audioflinger
3000          * continues to write data until standby time (3sec).
3001          * As the HDMI core is turned off, the write gets blocked.
3002          * Avoid this by routing audio to speaker until standby.
3003          */
3004         if (out->devices == AUDIO_DEVICE_OUT_AUX_DIGITAL &&
3005                 val == AUDIO_DEVICE_NONE) {
3006             val = AUDIO_DEVICE_OUT_SPEAKER;
3007         }
3008 
3009         /*
3010          * When A2DP is disconnected the
3011          * music playback is paused and the policy manager sends routing=0
3012          * But the audioflingercontinues to write data until standby time
3013          * (3sec). As BT is turned off, the write gets blocked.
3014          * Avoid this by routing audio to speaker until standby.
3015          */
3016         if ((out->devices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP) &&
3017                 (val == AUDIO_DEVICE_NONE) &&
3018                 !audio_extn_a2dp_is_ready() &&
3019                 !adev->bt_sco_on) {
3020                 val = AUDIO_DEVICE_OUT_SPEAKER;
3021         }
3022 
3023         /* To avoid a2dp to sco overlapping / BT device improper state
3024          * check with BT lib about a2dp streaming support before routing
3025          */
3026         if (val & AUDIO_DEVICE_OUT_ALL_A2DP) {
3027             if (!audio_extn_a2dp_is_ready()) {
3028                 if (val & (AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3029                     //combo usecase just by pass a2dp
3030                     ALOGW("%s: A2DP profile is not ready,routing to speaker only", __func__);
3031                     bypass_a2dp = true;
3032                 } else {
3033                     ALOGE("%s: A2DP profile is not ready,ignoring routing request", __func__);
3034                     /* update device to a2dp and don't route as BT returned error
3035                      * However it is still possible a2dp routing called because
3036                      * of current active device disconnection (like wired headset)
3037                      */
3038                     out->devices = val;
3039                     pthread_mutex_unlock(&out->lock);
3040                     pthread_mutex_unlock(&adev->lock);
3041                     status = -ENOSYS;
3042                     goto routing_fail;
3043                 }
3044             }
3045         }
3046 
3047         audio_devices_t new_dev = val;
3048 
3049         // Workaround: If routing to an non existing usb device, fail gracefully
3050         // The routing request will otherwise block during 10 second
3051         int card;
3052         if (audio_is_usb_out_device(new_dev) &&
3053             (card = get_alive_usb_card(parms)) >= 0) {
3054 
3055             ALOGW("out_set_parameters() ignoring rerouting to non existing USB card %d", card);
3056             pthread_mutex_unlock(&adev->lock);
3057             pthread_mutex_unlock(&out->lock);
3058             status = -ENOSYS;
3059             goto routing_fail;
3060         }
3061 
3062         /*
3063          * select_devices() call below switches all the usecases on the same
3064          * backend to the new device. Refer to check_and_route_playback_usecases() in
3065          * the select_devices(). But how do we undo this?
3066          *
3067          * For example, music playback is active on headset (deep-buffer usecase)
3068          * and if we go to ringtones and select a ringtone, low-latency usecase
3069          * will be started on headset+speaker. As we can't enable headset+speaker
3070          * and headset devices at the same time, select_devices() switches the music
3071          * playback to headset+speaker while starting low-lateny usecase for ringtone.
3072          * So when the ringtone playback is completed, how do we undo the same?
3073          *
3074          * We are relying on the out_set_parameters() call on deep-buffer output,
3075          * once the ringtone playback is ended.
3076          * NOTE: We should not check if the current devices are same as new devices.
3077          *       Because select_devices() must be called to switch back the music
3078          *       playback to headset.
3079          */
3080         if (new_dev != AUDIO_DEVICE_NONE) {
3081             bool same_dev = out->devices == new_dev;
3082             out->devices = new_dev;
3083 
3084             if (output_drives_call(adev, out)) {
3085                 if (!voice_is_call_state_active(adev)) {
3086                     if (adev->mode == AUDIO_MODE_IN_CALL) {
3087                         adev->current_call_output = out;
3088                         ret = voice_start_call(adev);
3089                     }
3090                 } else {
3091                     adev->current_call_output = out;
3092                     voice_update_devices_for_all_voice_usecases(adev);
3093                 }
3094             }
3095 
3096             if (!out->standby) {
3097                 if (!same_dev) {
3098                     ALOGV("update routing change");
3099                     // inform adm before actual routing to prevent glitches.
3100                     if (adev->adm_on_routing_change) {
3101                         adev->adm_on_routing_change(adev->adm_data,
3102                                                     out->handle);
3103                     }
3104                 }
3105                 if (!bypass_a2dp) {
3106                     select_devices(adev, out->usecase);
3107                 } else {
3108                     if (new_dev & AUDIO_DEVICE_OUT_SPEAKER_SAFE)
3109                         out->devices = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3110                     else
3111                         out->devices = AUDIO_DEVICE_OUT_SPEAKER;
3112                     select_devices(adev, out->usecase);
3113                     out->devices = new_dev;
3114                 }
3115                 audio_extn_tfa_98xx_update();
3116 
3117                 // on device switch force swap, lower functions will make sure
3118                 // to check if swap is allowed or not.
3119 
3120                 if (!same_dev)
3121                     platform_set_swap_channels(adev, true);
3122 
3123                 if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
3124                     out->a2dp_compress_mute &&
3125                     (!(out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) || audio_extn_a2dp_is_ready())) {
3126                     pthread_mutex_lock(&out->compr_mute_lock);
3127                     out->a2dp_compress_mute = false;
3128                     set_compr_volume(&out->stream, out->volume_l, out->volume_r);
3129                     pthread_mutex_unlock(&out->compr_mute_lock);
3130                 }
3131             }
3132 
3133         }
3134 
3135         pthread_mutex_unlock(&adev->lock);
3136         pthread_mutex_unlock(&out->lock);
3137 
3138         /*handles device and call state changes*/
3139         audio_extn_extspk_update(adev->extspk);
3140     }
3141     routing_fail:
3142 
3143     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3144         parse_compress_metadata(out, parms);
3145     }
3146 
3147     str_parms_destroy(parms);
3148     ALOGV("%s: exit: code(%d)", __func__, status);
3149     return status;
3150 }
3151 
stream_get_parameter_channels(struct str_parms * query,struct str_parms * reply,audio_channel_mask_t * supported_channel_masks)3152 static bool stream_get_parameter_channels(struct str_parms *query,
3153                                           struct str_parms *reply,
3154                                           audio_channel_mask_t *supported_channel_masks) {
3155     int ret = -1;
3156     char value[ARRAY_SIZE(channels_name_to_enum_table) * 32 /* max channel name size */];
3157     bool first = true;
3158     size_t i, j;
3159 
3160     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
3161         ret = 0;
3162         value[0] = '\0';
3163         i = 0;
3164         while (supported_channel_masks[i] != 0) {
3165             for (j = 0; j < ARRAY_SIZE(channels_name_to_enum_table); j++) {
3166                 if (channels_name_to_enum_table[j].value == supported_channel_masks[i]) {
3167                     if (!first) {
3168                         strcat(value, "|");
3169                     }
3170                     strcat(value, channels_name_to_enum_table[j].name);
3171                     first = false;
3172                     break;
3173                 }
3174             }
3175             i++;
3176         }
3177         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
3178     }
3179     return ret >= 0;
3180 }
3181 
stream_get_parameter_formats(struct str_parms * query,struct str_parms * reply,audio_format_t * supported_formats)3182 static bool stream_get_parameter_formats(struct str_parms *query,
3183                                          struct str_parms *reply,
3184                                          audio_format_t *supported_formats) {
3185     int ret = -1;
3186     char value[256];
3187     int i;
3188 
3189     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
3190         ret = 0;
3191         value[0] = '\0';
3192         switch (supported_formats[0]) {
3193             case AUDIO_FORMAT_PCM_16_BIT:
3194                 strcat(value, "AUDIO_FORMAT_PCM_16_BIT");
3195                 break;
3196             case AUDIO_FORMAT_PCM_24_BIT_PACKED:
3197                 strcat(value, "AUDIO_FORMAT_PCM_24_BIT_PACKED");
3198                 break;
3199             case AUDIO_FORMAT_PCM_32_BIT:
3200                 strcat(value, "AUDIO_FORMAT_PCM_32_BIT");
3201                 break;
3202             default:
3203                 ALOGE("%s: unsupported format %#x", __func__,
3204                       supported_formats[0]);
3205                 break;
3206         }
3207         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_FORMATS, value);
3208     }
3209     return ret >= 0;
3210 }
3211 
stream_get_parameter_rates(struct str_parms * query,struct str_parms * reply,uint32_t * supported_sample_rates)3212 static bool stream_get_parameter_rates(struct str_parms *query,
3213                                        struct str_parms *reply,
3214                                        uint32_t *supported_sample_rates) {
3215 
3216     int i;
3217     char value[256];
3218     int ret = -1;
3219     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
3220         ret = 0;
3221         value[0] = '\0';
3222         i=0;
3223         int cursor = 0;
3224         while (supported_sample_rates[i]) {
3225             int avail = sizeof(value) - cursor;
3226             ret = snprintf(value + cursor, avail, "%s%d",
3227                            cursor > 0 ? "|" : "",
3228                            supported_sample_rates[i]);
3229             if (ret < 0 || ret >= avail) {
3230                 // if cursor is at the last element of the array
3231                 //    overwrite with \0 is duplicate work as
3232                 //    snprintf already put a \0 in place.
3233                 // else
3234                 //    we had space to write the '|' at value[cursor]
3235                 //    (which will be overwritten) or no space to fill
3236                 //    the first element (=> cursor == 0)
3237                 value[cursor] = '\0';
3238                 break;
3239             }
3240             cursor += ret;
3241             ++i;
3242         }
3243         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES,
3244                           value);
3245     }
3246     return ret >= 0;
3247 }
3248 
out_get_parameters(const struct audio_stream * stream,const char * keys)3249 static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
3250 {
3251     struct stream_out *out = (struct stream_out *)stream;
3252     struct str_parms *query = str_parms_create_str(keys);
3253     char *str;
3254     struct str_parms *reply = str_parms_create();
3255     bool replied = false;
3256     ALOGV("%s: enter: keys - %s", __func__, keys);
3257 
3258     replied |= stream_get_parameter_channels(query, reply,
3259                                              &out->supported_channel_masks[0]);
3260     replied |= stream_get_parameter_formats(query, reply,
3261                                             &out->supported_formats[0]);
3262     replied |= stream_get_parameter_rates(query, reply,
3263                                           &out->supported_sample_rates[0]);
3264     if (replied) {
3265         str = str_parms_to_str(reply);
3266     } else {
3267         str = strdup("");
3268     }
3269     str_parms_destroy(query);
3270     str_parms_destroy(reply);
3271     ALOGV("%s: exit: returns - %s", __func__, str);
3272     return str;
3273 }
3274 
out_get_latency(const struct audio_stream_out * stream)3275 static uint32_t out_get_latency(const struct audio_stream_out *stream)
3276 {
3277     uint32_t hw_delay, period_ms;
3278     struct stream_out *out = (struct stream_out *)stream;
3279     uint32_t latency;
3280 
3281     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
3282         return COMPRESS_OFFLOAD_PLAYBACK_LATENCY;
3283     else if ((out->realtime) ||
3284             (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP)) {
3285         // since the buffer won't be filled up faster than realtime,
3286         // return a smaller number
3287         period_ms = (out->af_period_multiplier * out->config.period_size *
3288                      1000) / (out->config.rate);
3289         hw_delay = platform_render_latency(out->usecase)/1000;
3290         return period_ms + hw_delay;
3291     }
3292 
3293     latency = (out->config.period_count * out->config.period_size * 1000) /
3294               (out->config.rate);
3295 
3296     if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices)
3297         latency += audio_extn_a2dp_get_encoder_latency();
3298 
3299     return latency;
3300 }
3301 
set_compr_volume(struct audio_stream_out * stream,float left,float right)3302 static int set_compr_volume(struct audio_stream_out *stream, float left,
3303                           float right)
3304 {
3305     struct stream_out *out = (struct stream_out *)stream;
3306     int volume[2];
3307     char mixer_ctl_name[128];
3308     struct audio_device *adev = out->dev;
3309     struct mixer_ctl *ctl;
3310     int pcm_device_id = platform_get_pcm_device_id(out->usecase,
3311                                                PCM_PLAYBACK);
3312 
3313     snprintf(mixer_ctl_name, sizeof(mixer_ctl_name),
3314              "Compress Playback %d Volume", pcm_device_id);
3315     ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
3316     if (!ctl) {
3317         ALOGE("%s: Could not get ctl for mixer cmd - %s",
3318               __func__, mixer_ctl_name);
3319         return -EINVAL;
3320     }
3321     ALOGV("%s: ctl for mixer cmd - %s, left %f, right %f",
3322            __func__, mixer_ctl_name, left, right);
3323     volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
3324     volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
3325     mixer_ctl_set_array(ctl, volume, sizeof(volume) / sizeof(volume[0]));
3326 
3327     return 0;
3328 }
3329 
out_set_volume(struct audio_stream_out * stream,float left,float right)3330 static int out_set_volume(struct audio_stream_out *stream, float left,
3331                           float right)
3332 {
3333     struct stream_out *out = (struct stream_out *)stream;
3334     int ret = 0;
3335 
3336     if (out->usecase == USECASE_AUDIO_PLAYBACK_HIFI) {
3337         /* only take left channel into account: the API is for stereo anyway */
3338         out->muted = (left == 0.0f);
3339         return 0;
3340     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3341         pthread_mutex_lock(&out->compr_mute_lock);
3342         ALOGV("%s: compress mute %d", __func__, out->a2dp_compress_mute);
3343         if (!out->a2dp_compress_mute)
3344             ret = set_compr_volume(stream, left, right);
3345         out->volume_l = left;
3346         out->volume_r = right;
3347         pthread_mutex_unlock(&out->compr_mute_lock);
3348         return ret;
3349     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP) {
3350         out->app_type_cfg.gain[0] = (int)(left * VOIP_PLAYBACK_VOLUME_MAX);
3351         out->app_type_cfg.gain[1] = (int)(right * VOIP_PLAYBACK_VOLUME_MAX);
3352         if (!out->standby) {
3353             // if in standby, cached volume will be sent after stream is opened
3354             audio_extn_utils_send_app_type_gain(out->dev,
3355                                                 out->app_type_cfg.app_type,
3356                                                 &out->app_type_cfg.gain[0]);
3357         }
3358         return 0;
3359     }
3360 
3361     return -ENOSYS;
3362 }
3363 
3364 // note: this call is safe only if the stream_cb is
3365 // removed first in close_output_stream (as is done now).
out_snd_mon_cb(void * stream,struct str_parms * parms)3366 static void out_snd_mon_cb(void * stream, struct str_parms * parms)
3367 {
3368     if (!stream || !parms)
3369         return;
3370 
3371     struct stream_out *out = (struct stream_out *)stream;
3372     struct audio_device *adev = out->dev;
3373 
3374     card_status_t status;
3375     int card;
3376     if (parse_snd_card_status(parms, &card, &status) < 0)
3377         return;
3378 
3379     pthread_mutex_lock(&adev->lock);
3380     bool valid_cb = (card == adev->snd_card);
3381     pthread_mutex_unlock(&adev->lock);
3382 
3383     if (!valid_cb)
3384         return;
3385 
3386     lock_output_stream(out);
3387     if (out->card_status != status)
3388         out->card_status = status;
3389     pthread_mutex_unlock(&out->lock);
3390 
3391     ALOGW("out_snd_mon_cb for card %d usecase %s, status %s", card,
3392           use_case_table[out->usecase],
3393           status == CARD_STATUS_OFFLINE ? "offline" : "online");
3394 
3395     if (status == CARD_STATUS_OFFLINE)
3396         out_on_error(stream);
3397 
3398     return;
3399 }
3400 
3401 #ifdef NO_AUDIO_OUT
out_write_for_no_output(struct audio_stream_out * stream,const void * buffer __unused,size_t bytes)3402 static ssize_t out_write_for_no_output(struct audio_stream_out *stream,
3403                                        const void *buffer __unused, size_t bytes)
3404 {
3405     struct stream_out *out = (struct stream_out *)stream;
3406 
3407     /* No Output device supported other than BT for playback.
3408      * Sleep for the amount of buffer duration
3409      */
3410     lock_output_stream(out);
3411     usleep(bytes * 1000000 / audio_stream_out_frame_size(
3412             (const struct audio_stream_out *)&out->stream) /
3413             out_get_sample_rate(&out->stream.common));
3414     pthread_mutex_unlock(&out->lock);
3415     return bytes;
3416 }
3417 #endif
3418 
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)3419 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
3420                          size_t bytes)
3421 {
3422     struct stream_out *out = (struct stream_out *)stream;
3423     struct audio_device *adev = out->dev;
3424     ssize_t ret = 0;
3425     int error_code = ERROR_CODE_STANDBY;
3426 
3427     lock_output_stream(out);
3428     // this is always nonzero
3429     const size_t frame_size = audio_stream_out_frame_size(stream);
3430     const size_t frames = bytes / frame_size;
3431 
3432     if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
3433         error_code = ERROR_CODE_WRITE;
3434         goto exit;
3435     }
3436 
3437     if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
3438         (audio_extn_a2dp_is_suspended())) {
3439         if (!(out->devices & (AUDIO_DEVICE_OUT_SPEAKER | AUDIO_DEVICE_OUT_SPEAKER_SAFE))) {
3440             if (!(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
3441                 ret = -EIO;
3442                 goto exit;
3443             }
3444         }
3445     }
3446 
3447     const bool was_in_standby = out->standby;
3448     if (out->standby) {
3449         out->standby = false;
3450         const int64_t startNs = systemTime(SYSTEM_TIME_MONOTONIC);
3451 
3452         pthread_mutex_lock(&adev->lock);
3453         ret = start_output_stream(out);
3454 
3455         /* ToDo: If use case is compress offload should return 0 */
3456         if (ret != 0) {
3457             out->standby = true;
3458             pthread_mutex_unlock(&adev->lock);
3459             goto exit;
3460         }
3461 
3462         // after standby always force set last known cal step
3463         // dont change level anywhere except at the audio_hw_send_gain_dep_calibration
3464         ALOGD("%s: retry previous failed cal level set", __func__);
3465         send_gain_dep_calibration_l();
3466         pthread_mutex_unlock(&adev->lock);
3467 
3468         // log startup time in ms.
3469         simple_stats_log(
3470                 &out->start_latency_ms, (systemTime(SYSTEM_TIME_MONOTONIC) - startNs) * 1e-6);
3471         out->last_fifo_valid = false; // we're coming out of standby, last_fifo isn't valid.
3472     }
3473 
3474     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3475         ALOGVV("%s: writing buffer (%zu bytes) to compress device", __func__, bytes);
3476         if (out->send_new_metadata) {
3477             ALOGVV("send new gapless metadata");
3478             compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
3479             out->send_new_metadata = 0;
3480         }
3481         unsigned int avail;
3482         struct timespec tstamp;
3483         ret = compress_get_hpointer(out->compr, &avail, &tstamp);
3484         /* Do not limit write size if the available frames count is unknown */
3485         if (ret != 0) {
3486             avail = bytes;
3487         }
3488         if (avail == 0) {
3489             ret = 0;
3490         } else {
3491             // check for compressed format underrun, essentially an empty buffer check
3492             // for a lack of better measurement.
3493             if (!was_in_standby && avail == out->kernel_buffer_size) {
3494                 ALOGW("%s: compressed buffer empty (underrun)", __func__);
3495                 simple_stats_log(&out->fifo_underruns, 1.); // Note: log one frame for compressed.
3496             }
3497 
3498             if (avail > bytes) {
3499                 avail = bytes;
3500             }
3501             ret = compress_write(out->compr, buffer, avail);
3502             ALOGVV("%s: writing buffer (%d bytes) to compress device returned %zd",
3503                    __func__, avail, ret);
3504         }
3505 
3506         if (ret >= 0 && ret < (ssize_t)bytes) {
3507             send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
3508         }
3509         if (ret > 0 && !out->playback_started) {
3510             compress_start(out->compr);
3511             out->playback_started = 1;
3512             out->offload_state = OFFLOAD_STATE_PLAYING;
3513         }
3514         if (ret < 0) {
3515             error_log_log(out->error_log, ERROR_CODE_WRITE, audio_utils_get_real_time_ns());
3516         } else {
3517             out->written += ret; // accumulate bytes written for offload.
3518         }
3519         pthread_mutex_unlock(&out->lock);
3520         // TODO: consider logging offload pcm
3521         return ret;
3522     } else {
3523         error_code = ERROR_CODE_WRITE;
3524         if (out->pcm) {
3525             size_t bytes_to_write = bytes;
3526 
3527             if (out->muted)
3528                 memset((void *)buffer, 0, bytes);
3529             // FIXME: this can be removed once audio flinger mixer supports mono output
3530             if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP ||
3531                 out->usecase == USECASE_INCALL_MUSIC_UPLINK ||
3532                 out->usecase == USECASE_INCALL_MUSIC_UPLINK2) {
3533                 size_t channel_count = audio_channel_count_from_out_mask(out->channel_mask);
3534                 int16_t *src = (int16_t *)buffer;
3535                 int16_t *dst = (int16_t *)buffer;
3536 
3537                 LOG_ALWAYS_FATAL_IF(out->config.channels != 1 || channel_count != 2 ||
3538                                     out->format != AUDIO_FORMAT_PCM_16_BIT,
3539                                     "out_write called for VOIP use case with wrong properties");
3540 
3541                 for (size_t i = 0; i < frames ; i++, dst++, src += 2) {
3542                     *dst = (int16_t)(((int32_t)src[0] + (int32_t)src[1]) >> 1);
3543                 }
3544                 bytes_to_write /= 2;
3545             }
3546 
3547             // Note: since out_get_presentation_position() is called alternating with out_write()
3548             // by AudioFlinger, we can check underruns using the prior timestamp read.
3549             // (Alternately we could check if the buffer is empty using pcm_get_htimestamp().
3550             if (out->last_fifo_valid) {
3551                 // compute drain to see if there is an underrun.
3552                 const int64_t current_ns = systemTime(SYSTEM_TIME_MONOTONIC); // sys call
3553                 const int64_t frames_by_time =
3554                         (current_ns - out->last_fifo_time_ns) * out->config.rate / NANOS_PER_SECOND;
3555                 const int64_t underrun = frames_by_time - out->last_fifo_frames_remaining;
3556 
3557                 if (underrun > 0) {
3558                     simple_stats_log(&out->fifo_underruns, underrun);
3559 
3560                     ALOGW("%s: underrun(%lld) "
3561                             "frames_by_time(%lld) > out->last_fifo_frames_remaining(%lld)",
3562                             __func__,
3563                             (long long)out->fifo_underruns.n,
3564                             (long long)frames_by_time,
3565                             (long long)out->last_fifo_frames_remaining);
3566                 }
3567                 out->last_fifo_valid = false;  // we're writing below, mark fifo info as stale.
3568             }
3569 
3570             long ns = (frames * (int64_t) NANOS_PER_SECOND) / out->config.rate;
3571             request_out_focus(out, ns);
3572 
3573             bool use_mmap = is_mmap_usecase(out->usecase) || out->realtime;
3574             if (use_mmap) {
3575                 ret = pcm_mmap_write(out->pcm, (void *)buffer, bytes_to_write);
3576             } else {
3577                 if (out->usecase == USECASE_AUDIO_PLAYBACK_WITH_HAPTICS) {
3578                     size_t channel_count = audio_channel_count_from_out_mask(out->channel_mask);
3579                     size_t bytes_per_sample = audio_bytes_per_sample(out->format);
3580                     size_t frame_size = channel_count * bytes_per_sample;
3581                     size_t frame_count = bytes_to_write / frame_size;
3582 
3583                     bool force_haptic_path =
3584                          property_get_bool("vendor.audio.test_haptic", false);
3585 
3586                     // extract Haptics data from Audio buffer
3587                     bool   alloc_haptic_buffer = false;
3588                     int    haptic_channel_count = adev->haptics_config.channels;
3589                     size_t haptic_frame_size = bytes_per_sample * haptic_channel_count;
3590                     size_t audio_frame_size = frame_size - haptic_frame_size;
3591                     size_t total_haptic_buffer_size = frame_count * haptic_frame_size;
3592 
3593                     if (adev->haptic_buffer == NULL) {
3594                         alloc_haptic_buffer = true;
3595                     } else if (adev->haptic_buffer_size < total_haptic_buffer_size) {
3596                         free(adev->haptic_buffer);
3597                         adev->haptic_buffer_size = 0;
3598                         alloc_haptic_buffer = true;
3599                     }
3600 
3601                     if (alloc_haptic_buffer) {
3602                         adev->haptic_buffer = (uint8_t *)calloc(1, total_haptic_buffer_size);
3603                         adev->haptic_buffer_size = total_haptic_buffer_size;
3604                     }
3605 
3606                     size_t src_index = 0, aud_index = 0, hap_index = 0;
3607                     uint8_t *audio_buffer = (uint8_t *)buffer;
3608                     uint8_t *haptic_buffer  = adev->haptic_buffer;
3609 
3610                     // This is required for testing only. This works for stereo data only.
3611                     // One channel is fed to audio stream and other to haptic stream for testing.
3612                     if (force_haptic_path) {
3613                        audio_frame_size = haptic_frame_size = bytes_per_sample;
3614                     }
3615 
3616                     for (size_t i = 0; i < frame_count; i++) {
3617                         for (size_t j = 0; j < audio_frame_size; j++)
3618                             audio_buffer[aud_index++] = audio_buffer[src_index++];
3619 
3620                         for (size_t j = 0; j < haptic_frame_size; j++)
3621                             haptic_buffer[hap_index++] = audio_buffer[src_index++];
3622                         }
3623 
3624                         // This is required for testing only.
3625                         // Discard haptic channel data.
3626                         if (force_haptic_path) {
3627                             src_index += haptic_frame_size;
3628                     }
3629 
3630                     // write to audio pipeline
3631                     ret = pcm_write(out->pcm,
3632                                     (void *)audio_buffer,
3633                                     frame_count * audio_frame_size);
3634 
3635                     // write to haptics pipeline
3636                     if (adev->haptic_pcm)
3637                         ret = pcm_write(adev->haptic_pcm,
3638                                         (void *)adev->haptic_buffer,
3639                                         frame_count * haptic_frame_size);
3640 
3641                 } else {
3642                     ret = pcm_write(out->pcm, (void *)buffer, bytes_to_write);
3643                 }
3644             }
3645             release_out_focus(out, ns);
3646         } else {
3647             LOG_ALWAYS_FATAL("out->pcm is NULL after starting output stream");
3648         }
3649     }
3650 
3651 exit:
3652     // For PCM we always consume the buffer and return #bytes regardless of ret.
3653     if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3654         out->written += frames;
3655     }
3656     long long sleeptime_us = 0;
3657 
3658     if (ret != 0) {
3659         error_log_log(out->error_log, error_code, audio_utils_get_real_time_ns());
3660         if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3661             ALOGE_IF(out->pcm != NULL,
3662                     "%s: error %zd - %s", __func__, ret, pcm_get_error(out->pcm));
3663             sleeptime_us = frames * 1000000LL / out_get_sample_rate(&out->stream.common);
3664             // usleep not guaranteed for values over 1 second but we don't limit here.
3665         }
3666     }
3667 
3668     pthread_mutex_unlock(&out->lock);
3669 
3670     if (ret != 0) {
3671         out_on_error(&out->stream.common);
3672         if (sleeptime_us != 0)
3673             usleep(sleeptime_us);
3674     }
3675     return bytes;
3676 }
3677 
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)3678 static int out_get_render_position(const struct audio_stream_out *stream,
3679                                    uint32_t *dsp_frames)
3680 {
3681     struct stream_out *out = (struct stream_out *)stream;
3682     *dsp_frames = 0;
3683     if ((out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) && (dsp_frames != NULL)) {
3684         lock_output_stream(out);
3685         if (out->compr != NULL) {
3686             unsigned long frames = 0;
3687             // TODO: check return value
3688             compress_get_tstamp(out->compr, &frames, &out->sample_rate);
3689             *dsp_frames = (uint32_t)frames;
3690             ALOGVV("%s rendered frames %d sample_rate %d",
3691                    __func__, *dsp_frames, out->sample_rate);
3692         }
3693         pthread_mutex_unlock(&out->lock);
3694         return 0;
3695     } else
3696         return -ENODATA;
3697 }
3698 
out_add_audio_effect(const struct audio_stream * stream __unused,effect_handle_t effect __unused)3699 static int out_add_audio_effect(const struct audio_stream *stream __unused,
3700                                 effect_handle_t effect __unused)
3701 {
3702     return 0;
3703 }
3704 
out_remove_audio_effect(const struct audio_stream * stream __unused,effect_handle_t effect __unused)3705 static int out_remove_audio_effect(const struct audio_stream *stream __unused,
3706                                    effect_handle_t effect __unused)
3707 {
3708     return 0;
3709 }
3710 
out_get_next_write_timestamp(const struct audio_stream_out * stream __unused,int64_t * timestamp __unused)3711 static int out_get_next_write_timestamp(const struct audio_stream_out *stream __unused,
3712                                         int64_t *timestamp __unused)
3713 {
3714     return -ENOSYS;
3715 }
3716 
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)3717 static int out_get_presentation_position(const struct audio_stream_out *stream,
3718                                    uint64_t *frames, struct timespec *timestamp)
3719 {
3720     struct stream_out *out = (struct stream_out *)stream;
3721     int ret = -ENODATA;
3722     unsigned long dsp_frames;
3723 
3724     lock_output_stream(out);
3725 
3726     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3727         if (out->compr != NULL) {
3728             // TODO: check return value
3729             compress_get_tstamp(out->compr, &dsp_frames,
3730                     &out->sample_rate);
3731             // Adjustment accounts for A2DP encoder latency with offload usecases
3732             // Note: Encoder latency is returned in ms.
3733             if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices) {
3734                 unsigned long offset =
3735                             (audio_extn_a2dp_get_encoder_latency() * out->sample_rate / 1000);
3736                 dsp_frames = (dsp_frames > offset) ? (dsp_frames - offset) : 0;
3737             }
3738             ALOGVV("%s rendered frames %ld sample_rate %d",
3739                    __func__, dsp_frames, out->sample_rate);
3740             *frames = dsp_frames;
3741             ret = 0;
3742             /* this is the best we can do */
3743             clock_gettime(CLOCK_MONOTONIC, timestamp);
3744         }
3745     } else {
3746         if (out->pcm) {
3747             unsigned int avail;
3748             if (pcm_get_htimestamp(out->pcm, &avail, timestamp) == 0) {
3749 
3750                 // pcm_get_htimestamp() computes the available frames by comparing
3751                 // the alsa driver hw_ptr and the appl_ptr levels.
3752                 // In underrun, the hw_ptr may keep running and report an excessively
3753                 // large number available number.
3754                 if (avail > out->kernel_buffer_size) {
3755                     ALOGW("%s: avail:%u > kernel_buffer_size:%zu clamping!",
3756                             __func__, avail, out->kernel_buffer_size);
3757                     avail = out->kernel_buffer_size;
3758                     out->last_fifo_frames_remaining = 0;
3759                 } else {
3760                     out->last_fifo_frames_remaining = out->kernel_buffer_size - avail;
3761                 }
3762                 out->last_fifo_valid = true;
3763                 out->last_fifo_time_ns = audio_utils_ns_from_timespec(timestamp);
3764 
3765                 int64_t signed_frames = out->written - out->last_fifo_frames_remaining;
3766 
3767                 ALOGVV("%s: frames:%lld  avail:%u  kernel_buffer_size:%zu",
3768                         __func__, (long long)signed_frames, avail, out->kernel_buffer_size);
3769 
3770                 // This adjustment accounts for buffering after app processor.
3771                 // It is based on estimated DSP latency per use case, rather than exact.
3772                 signed_frames -=
3773                     (platform_render_latency(out->usecase) * out->sample_rate / 1000000LL);
3774 
3775                 // Adjustment accounts for A2DP encoder latency with non-offload usecases
3776                 // Note: Encoder latency is returned in ms, while platform_render_latency in us.
3777                 if (AUDIO_DEVICE_OUT_ALL_A2DP & out->devices) {
3778                     signed_frames -=
3779                             (audio_extn_a2dp_get_encoder_latency() * out->sample_rate / 1000);
3780                 }
3781 
3782                 // It would be unusual for this value to be negative, but check just in case ...
3783                 if (signed_frames >= 0) {
3784                     *frames = signed_frames;
3785                     ret = 0;
3786                 }
3787             }
3788         }
3789     }
3790 
3791     pthread_mutex_unlock(&out->lock);
3792 
3793     return ret;
3794 }
3795 
out_set_callback(struct audio_stream_out * stream,stream_callback_t callback,void * cookie)3796 static int out_set_callback(struct audio_stream_out *stream,
3797             stream_callback_t callback, void *cookie)
3798 {
3799     struct stream_out *out = (struct stream_out *)stream;
3800 
3801     ALOGV("%s", __func__);
3802     lock_output_stream(out);
3803     out->offload_callback = callback;
3804     out->offload_cookie = cookie;
3805     pthread_mutex_unlock(&out->lock);
3806     return 0;
3807 }
3808 
out_pause(struct audio_stream_out * stream)3809 static int out_pause(struct audio_stream_out* stream)
3810 {
3811     struct stream_out *out = (struct stream_out *)stream;
3812     int status = -ENOSYS;
3813     ALOGV("%s", __func__);
3814     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3815         status = -ENODATA;
3816         lock_output_stream(out);
3817         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
3818             status = compress_pause(out->compr);
3819             out->offload_state = OFFLOAD_STATE_PAUSED;
3820         }
3821         pthread_mutex_unlock(&out->lock);
3822     }
3823     return status;
3824 }
3825 
out_resume(struct audio_stream_out * stream)3826 static int out_resume(struct audio_stream_out* stream)
3827 {
3828     struct stream_out *out = (struct stream_out *)stream;
3829     int status = -ENOSYS;
3830     ALOGV("%s", __func__);
3831     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3832         status = -ENODATA;
3833         lock_output_stream(out);
3834         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
3835             status = compress_resume(out->compr);
3836             out->offload_state = OFFLOAD_STATE_PLAYING;
3837         }
3838         pthread_mutex_unlock(&out->lock);
3839     }
3840     return status;
3841 }
3842 
out_drain(struct audio_stream_out * stream,audio_drain_type_t type)3843 static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
3844 {
3845     struct stream_out *out = (struct stream_out *)stream;
3846     int status = -ENOSYS;
3847     ALOGV("%s", __func__);
3848     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3849         lock_output_stream(out);
3850         if (type == AUDIO_DRAIN_EARLY_NOTIFY)
3851             status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
3852         else
3853             status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
3854         pthread_mutex_unlock(&out->lock);
3855     }
3856     return status;
3857 }
3858 
out_flush(struct audio_stream_out * stream)3859 static int out_flush(struct audio_stream_out* stream)
3860 {
3861     struct stream_out *out = (struct stream_out *)stream;
3862     ALOGV("%s", __func__);
3863     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
3864         lock_output_stream(out);
3865         stop_compressed_output_l(out);
3866         pthread_mutex_unlock(&out->lock);
3867         return 0;
3868     }
3869     return -ENOSYS;
3870 }
3871 
out_stop(const struct audio_stream_out * stream)3872 static int out_stop(const struct audio_stream_out* stream)
3873 {
3874     struct stream_out *out = (struct stream_out *)stream;
3875     struct audio_device *adev = out->dev;
3876     int ret = -ENOSYS;
3877 
3878     ALOGV("%s", __func__);
3879     pthread_mutex_lock(&adev->lock);
3880     if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP && !out->standby &&
3881             out->playback_started && out->pcm != NULL) {
3882         pcm_stop(out->pcm);
3883         ret = stop_output_stream(out);
3884         out->playback_started = false;
3885     }
3886     pthread_mutex_unlock(&adev->lock);
3887     return ret;
3888 }
3889 
out_start(const struct audio_stream_out * stream)3890 static int out_start(const struct audio_stream_out* stream)
3891 {
3892     struct stream_out *out = (struct stream_out *)stream;
3893     struct audio_device *adev = out->dev;
3894     int ret = -ENOSYS;
3895 
3896     ALOGV("%s", __func__);
3897     pthread_mutex_lock(&adev->lock);
3898     if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP && !out->standby &&
3899             !out->playback_started && out->pcm != NULL) {
3900         ret = start_output_stream(out);
3901         if (ret == 0) {
3902             out->playback_started = true;
3903         }
3904     }
3905     pthread_mutex_unlock(&adev->lock);
3906     return ret;
3907 }
3908 
3909 /*
3910  * Modify config->period_count based on min_size_frames
3911  */
adjust_mmap_period_count(struct pcm_config * config,int32_t min_size_frames)3912 static void adjust_mmap_period_count(struct pcm_config *config, int32_t min_size_frames)
3913 {
3914     int periodCountRequested = (min_size_frames + config->period_size - 1)
3915                                / config->period_size;
3916     int periodCount = MMAP_PERIOD_COUNT_MIN;
3917 
3918     ALOGV("%s original config.period_size = %d config.period_count = %d",
3919           __func__, config->period_size, config->period_count);
3920 
3921     while (periodCount < periodCountRequested && (periodCount * 2) < MMAP_PERIOD_COUNT_MAX) {
3922         periodCount *= 2;
3923     }
3924     config->period_count = periodCount;
3925 
3926     ALOGV("%s requested config.period_count = %d", __func__, config->period_count);
3927 }
3928 
3929 // Read offset for the positional timestamp from a persistent vendor property.
3930 // This is to workaround apparent inaccuracies in the timing information that
3931 // is used by the AAudio timing model. The inaccuracies can cause glitches.
get_mmap_out_time_offset()3932 static int64_t get_mmap_out_time_offset() {
3933     const int32_t kDefaultOffsetMicros = 0;
3934     int32_t mmap_time_offset_micros = property_get_int32(
3935         "persist.audio.out_mmap_delay_micros", kDefaultOffsetMicros);
3936     ALOGI("mmap_time_offset_micros = %d for output", mmap_time_offset_micros);
3937     return mmap_time_offset_micros * (int64_t)1000;
3938 }
3939 
out_create_mmap_buffer(const struct audio_stream_out * stream,int32_t min_size_frames,struct audio_mmap_buffer_info * info)3940 static int out_create_mmap_buffer(const struct audio_stream_out *stream,
3941                                   int32_t min_size_frames,
3942                                   struct audio_mmap_buffer_info *info)
3943 {
3944     struct stream_out *out = (struct stream_out *)stream;
3945     struct audio_device *adev = out->dev;
3946     int ret = 0;
3947     unsigned int offset1;
3948     unsigned int frames1;
3949     const char *step = "";
3950     uint32_t mmap_size;
3951     uint32_t buffer_size;
3952 
3953     ALOGV("%s", __func__);
3954     lock_output_stream(out);
3955     pthread_mutex_lock(&adev->lock);
3956 
3957     if (info == NULL || min_size_frames <= 0 || min_size_frames > MMAP_MIN_SIZE_FRAMES_MAX) {
3958         ALOGE("%s: info = %p, min_size_frames = %d", __func__, info, min_size_frames);
3959         ret = -EINVAL;
3960         goto exit;
3961     }
3962     if (out->usecase != USECASE_AUDIO_PLAYBACK_MMAP || !out->standby) {
3963         ALOGE("%s: usecase = %d, standby = %d", __func__, out->usecase, out->standby);
3964         ret = -ENOSYS;
3965         goto exit;
3966     }
3967     out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
3968     if (out->pcm_device_id < 0) {
3969         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
3970               __func__, out->pcm_device_id, out->usecase);
3971         ret = -EINVAL;
3972         goto exit;
3973     }
3974 
3975     adjust_mmap_period_count(&out->config, min_size_frames);
3976 
3977     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
3978           __func__, adev->snd_card, out->pcm_device_id, out->config.channels);
3979     out->pcm = pcm_open(adev->snd_card, out->pcm_device_id,
3980                         (PCM_OUT | PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC), &out->config);
3981     if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
3982         step = "open";
3983         ret = -ENODEV;
3984         goto exit;
3985     }
3986     ret = pcm_mmap_begin(out->pcm, &info->shared_memory_address, &offset1, &frames1);
3987     if (ret < 0)  {
3988         step = "begin";
3989         goto exit;
3990     }
3991     info->buffer_size_frames = pcm_get_buffer_size(out->pcm);
3992     buffer_size = pcm_frames_to_bytes(out->pcm, info->buffer_size_frames);
3993     info->burst_size_frames = out->config.period_size;
3994     ret = platform_get_mmap_data_fd(adev->platform,
3995                                     out->pcm_device_id, 0 /*playback*/,
3996                                     &info->shared_memory_fd,
3997                                     &mmap_size);
3998     if (ret < 0) {
3999         // Fall back to non exclusive mode
4000         info->shared_memory_fd = pcm_get_poll_fd(out->pcm);
4001     } else {
4002         out->mmap_shared_memory_fd = info->shared_memory_fd; // for closing later
4003         ALOGV("%s: opened mmap_shared_memory_fd = %d", __func__, out->mmap_shared_memory_fd);
4004 
4005         if (mmap_size < buffer_size) {
4006             step = "mmap";
4007             goto exit;
4008         }
4009         // FIXME: indicate exclusive mode support by returning a negative buffer size
4010         info->buffer_size_frames *= -1;
4011     }
4012     memset(info->shared_memory_address, 0, buffer_size);
4013 
4014     ret = pcm_mmap_commit(out->pcm, 0, MMAP_PERIOD_SIZE);
4015     if (ret < 0) {
4016         step = "commit";
4017         goto exit;
4018     }
4019 
4020     out->mmap_time_offset_nanos = get_mmap_out_time_offset();
4021 
4022     out->standby = false;
4023     ret = 0;
4024 
4025     ALOGV("%s: got mmap buffer address %p info->buffer_size_frames %d",
4026           __func__, info->shared_memory_address, info->buffer_size_frames);
4027 
4028 exit:
4029     if (ret != 0) {
4030         if (out->pcm == NULL) {
4031             ALOGE("%s: %s - %d", __func__, step, ret);
4032         } else {
4033             ALOGE("%s: %s %s", __func__, step, pcm_get_error(out->pcm));
4034             pcm_close(out->pcm);
4035             out->pcm = NULL;
4036         }
4037     }
4038     pthread_mutex_unlock(&adev->lock);
4039     pthread_mutex_unlock(&out->lock);
4040     return ret;
4041 }
4042 
out_get_mmap_position(const struct audio_stream_out * stream,struct audio_mmap_position * position)4043 static int out_get_mmap_position(const struct audio_stream_out *stream,
4044                                   struct audio_mmap_position *position)
4045 {
4046     int ret = 0;
4047     struct stream_out *out = (struct stream_out *)stream;
4048     ALOGVV("%s", __func__);
4049     if (position == NULL) {
4050         return -EINVAL;
4051     }
4052     lock_output_stream(out);
4053     if (out->usecase != USECASE_AUDIO_PLAYBACK_MMAP ||
4054         out->pcm == NULL) {
4055         ret = -ENOSYS;
4056         goto exit;
4057     }
4058 
4059     struct timespec ts = { 0, 0 };
4060     ret = pcm_mmap_get_hw_ptr(out->pcm, (unsigned int *)&position->position_frames, &ts);
4061     if (ret < 0) {
4062         ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
4063         goto exit;
4064     }
4065     position->time_nanoseconds = audio_utils_ns_from_timespec(&ts)
4066             + out->mmap_time_offset_nanos;
4067 
4068 exit:
4069     pthread_mutex_unlock(&out->lock);
4070     return ret;
4071 }
4072 
4073 
4074 /** audio_stream_in implementation **/
in_get_sample_rate(const struct audio_stream * stream)4075 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
4076 {
4077     struct stream_in *in = (struct stream_in *)stream;
4078 
4079     return in->config.rate;
4080 }
4081 
in_set_sample_rate(struct audio_stream * stream __unused,uint32_t rate __unused)4082 static int in_set_sample_rate(struct audio_stream *stream __unused, uint32_t rate __unused)
4083 {
4084     return -ENOSYS;
4085 }
4086 
in_get_buffer_size(const struct audio_stream * stream)4087 static size_t in_get_buffer_size(const struct audio_stream *stream)
4088 {
4089     struct stream_in *in = (struct stream_in *)stream;
4090     return in->config.period_size * in->af_period_multiplier *
4091         audio_stream_in_frame_size((const struct audio_stream_in *)stream);
4092 }
4093 
in_get_channels(const struct audio_stream * stream)4094 static uint32_t in_get_channels(const struct audio_stream *stream)
4095 {
4096     struct stream_in *in = (struct stream_in *)stream;
4097 
4098     return in->channel_mask;
4099 }
4100 
in_get_format(const struct audio_stream * stream)4101 static audio_format_t in_get_format(const struct audio_stream *stream)
4102 {
4103     struct stream_in *in = (struct stream_in *)stream;
4104     return in->format;
4105 }
4106 
in_set_format(struct audio_stream * stream __unused,audio_format_t format __unused)4107 static int in_set_format(struct audio_stream *stream __unused, audio_format_t format __unused)
4108 {
4109     return -ENOSYS;
4110 }
4111 
in_standby(struct audio_stream * stream)4112 static int in_standby(struct audio_stream *stream)
4113 {
4114     struct stream_in *in = (struct stream_in *)stream;
4115     struct audio_device *adev = in->dev;
4116     int status = 0;
4117     bool do_stop = true;
4118 
4119     ALOGV("%s: enter", __func__);
4120 
4121     lock_input_stream(in);
4122 
4123     if (!in->standby && (in->flags & AUDIO_INPUT_FLAG_HW_HOTWORD)) {
4124         ALOGV("%s: sound trigger pcm stop lab", __func__);
4125         audio_extn_sound_trigger_stop_lab(in);
4126         in->standby = true;
4127     }
4128 
4129     if (!in->standby) {
4130         if (adev->adm_deregister_stream)
4131             adev->adm_deregister_stream(adev->adm_data, in->capture_handle);
4132 
4133         pthread_mutex_lock(&adev->lock);
4134         in->standby = true;
4135         if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
4136             do_stop = in->capture_started;
4137             in->capture_started = false;
4138 
4139             if (in->mmap_shared_memory_fd >= 0) {
4140                 ALOGV("%s: closing mmap_shared_memory_fd = %d",
4141                       __func__, in->mmap_shared_memory_fd);
4142                 close(in->mmap_shared_memory_fd);
4143                 in->mmap_shared_memory_fd = -1;
4144             }
4145 
4146         }
4147         if (in->pcm) {
4148             pcm_close(in->pcm);
4149             in->pcm = NULL;
4150         }
4151 
4152         if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION)
4153             adev->enable_voicerx = false;
4154 
4155         if (do_stop) {
4156             status = stop_input_stream(in);
4157         }
4158 
4159         pthread_mutex_unlock(&adev->lock);
4160     }
4161     pthread_mutex_unlock(&in->lock);
4162     ALOGV("%s: exit:  status(%d)", __func__, status);
4163     return status;
4164 }
4165 
in_dump(const struct audio_stream * stream,int fd)4166 static int in_dump(const struct audio_stream *stream, int fd)
4167 {
4168     struct stream_in *in = (struct stream_in *)stream;
4169 
4170     // We try to get the lock for consistency,
4171     // but it isn't necessary for these variables.
4172     // If we're not in standby, we may be blocked on a read.
4173     const bool locked = (pthread_mutex_trylock(&in->lock) == 0);
4174     dprintf(fd, "      Standby: %s\n", in->standby ? "yes" : "no");
4175     dprintf(fd, "      Frames read: %lld\n", (long long)in->frames_read);
4176     dprintf(fd, "      Frames muted: %lld\n", (long long)in->frames_muted);
4177 
4178     char buffer[256]; // for statistics formatting
4179     if (in->start_latency_ms.n > 0) {
4180         simple_stats_to_string(&in->start_latency_ms, buffer, sizeof(buffer));
4181         dprintf(fd, "      Start latency ms: %s\n", buffer);
4182     }
4183 
4184     if (locked) {
4185         pthread_mutex_unlock(&in->lock);
4186     }
4187 
4188     // dump error info
4189     (void)error_log_dump(
4190             in->error_log, fd, "      " /* prefix */, 0 /* lines */, 0 /* limit_ns */);
4191     return 0;
4192 }
4193 
in_set_parameters(struct audio_stream * stream,const char * kvpairs)4194 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
4195 {
4196     struct stream_in *in = (struct stream_in *)stream;
4197     struct audio_device *adev = in->dev;
4198     struct str_parms *parms;
4199     char *str;
4200     char value[32];
4201     int ret, val = 0;
4202     int status = 0;
4203 
4204     ALOGV("%s: enter: kvpairs=%s", __func__, kvpairs);
4205     parms = str_parms_create_str(kvpairs);
4206 
4207     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
4208 
4209     lock_input_stream(in);
4210 
4211     pthread_mutex_lock(&adev->lock);
4212     if (ret >= 0) {
4213         val = atoi(value);
4214         /* no audio source uses val == 0 */
4215         if ((in->source != val) && (val != 0)) {
4216             in->source = val;
4217         }
4218     }
4219 
4220     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
4221 
4222     if (ret >= 0) {
4223         val = atoi(value);
4224         if (((int)in->device != val) && (val != 0) && audio_is_input_device(val) ) {
4225 
4226             // Workaround: If routing to an non existing usb device, fail gracefully
4227             // The routing request will otherwise block during 10 second
4228             int card;
4229             if (audio_is_usb_in_device(val) &&
4230                 (card = get_alive_usb_card(parms)) >= 0) {
4231 
4232                 ALOGW("in_set_parameters() ignoring rerouting to non existing USB card %d", card);
4233                 status = -ENOSYS;
4234             } else {
4235 
4236                 in->device = val;
4237                 /* If recording is in progress, change the tx device to new device */
4238                 if (!in->standby) {
4239                     ALOGV("update input routing change");
4240                     // inform adm before actual routing to prevent glitches.
4241                     if (adev->adm_on_routing_change) {
4242                         adev->adm_on_routing_change(adev->adm_data,
4243                                                     in->capture_handle);
4244                     }
4245                     select_devices(adev, in->usecase);
4246                 }
4247             }
4248         }
4249     }
4250 
4251     pthread_mutex_unlock(&adev->lock);
4252     pthread_mutex_unlock(&in->lock);
4253 
4254     str_parms_destroy(parms);
4255     ALOGV("%s: exit: status(%d)", __func__, status);
4256     return status;
4257 }
4258 
in_get_parameters(const struct audio_stream * stream,const char * keys)4259 static char* in_get_parameters(const struct audio_stream *stream,
4260                                const char *keys)
4261 {
4262     struct stream_in *in = (struct stream_in *)stream;
4263     struct str_parms *query = str_parms_create_str(keys);
4264     char *str;
4265     struct str_parms *reply = str_parms_create();
4266     bool replied = false;
4267 
4268     ALOGV("%s: enter: keys - %s", __func__, keys);
4269     replied |= stream_get_parameter_channels(query, reply,
4270                                              &in->supported_channel_masks[0]);
4271     replied |= stream_get_parameter_formats(query, reply,
4272                                             &in->supported_formats[0]);
4273     replied |= stream_get_parameter_rates(query, reply,
4274                                           &in->supported_sample_rates[0]);
4275     if (replied) {
4276         str = str_parms_to_str(reply);
4277     } else {
4278         str = strdup("");
4279     }
4280     str_parms_destroy(query);
4281     str_parms_destroy(reply);
4282     ALOGV("%s: exit: returns - %s", __func__, str);
4283     return str;
4284 }
4285 
in_set_gain(struct audio_stream_in * stream,float gain)4286 static int in_set_gain(struct audio_stream_in *stream, float gain)
4287 {
4288     struct stream_in *in = (struct stream_in *)stream;
4289     char mixer_ctl_name[128];
4290     struct mixer_ctl *ctl;
4291     int ctl_value;
4292 
4293     ALOGV("%s: gain %f", __func__, gain);
4294 
4295     if (stream == NULL)
4296         return -EINVAL;
4297 
4298     /* in_set_gain() only used to silence MMAP capture for now */
4299     if (in->usecase != USECASE_AUDIO_RECORD_MMAP)
4300         return -ENOSYS;
4301 
4302     snprintf(mixer_ctl_name, sizeof(mixer_ctl_name), "Capture %d Volume", in->pcm_device_id);
4303 
4304     ctl = mixer_get_ctl_by_name(in->dev->mixer, mixer_ctl_name);
4305     if (!ctl) {
4306         ALOGW("%s: Could not get ctl for mixer cmd - %s",
4307               __func__, mixer_ctl_name);
4308         return -ENOSYS;
4309     }
4310 
4311     if (gain < RECORD_GAIN_MIN)
4312         gain  = RECORD_GAIN_MIN;
4313     else if (gain > RECORD_GAIN_MAX)
4314          gain = RECORD_GAIN_MAX;
4315     ctl_value = (int)(RECORD_VOLUME_CTL_MAX * gain);
4316 
4317     mixer_ctl_set_value(ctl, 0, ctl_value);
4318     return 0;
4319 }
4320 
in_snd_mon_cb(void * stream,struct str_parms * parms)4321 static void in_snd_mon_cb(void * stream, struct str_parms * parms)
4322 {
4323     if (!stream || !parms)
4324         return;
4325 
4326     struct stream_in *in = (struct stream_in *)stream;
4327     struct audio_device *adev = in->dev;
4328 
4329     card_status_t status;
4330     int card;
4331     if (parse_snd_card_status(parms, &card, &status) < 0)
4332         return;
4333 
4334     pthread_mutex_lock(&adev->lock);
4335     bool valid_cb = (card == adev->snd_card);
4336     pthread_mutex_unlock(&adev->lock);
4337 
4338     if (!valid_cb)
4339         return;
4340 
4341     lock_input_stream(in);
4342     if (in->card_status != status)
4343         in->card_status = status;
4344     pthread_mutex_unlock(&in->lock);
4345 
4346     ALOGW("in_snd_mon_cb for card %d usecase %s, status %s", card,
4347           use_case_table[in->usecase],
4348           status == CARD_STATUS_OFFLINE ? "offline" : "online");
4349 
4350     // a better solution would be to report error back to AF and let
4351     // it put the stream to standby
4352     if (status == CARD_STATUS_OFFLINE)
4353         in_standby(&in->stream.common);
4354 
4355     return;
4356 }
4357 
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)4358 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
4359                        size_t bytes)
4360 {
4361     struct stream_in *in = (struct stream_in *)stream;
4362     struct audio_device *adev = in->dev;
4363     int i, ret = -1;
4364     int *int_buf_stream = NULL;
4365     int error_code = ERROR_CODE_STANDBY; // initial errors are considered coming out of standby.
4366 
4367     lock_input_stream(in);
4368     const size_t frame_size = audio_stream_in_frame_size(stream);
4369     const size_t frames = bytes / frame_size;
4370 
4371     if (in->flags & AUDIO_INPUT_FLAG_HW_HOTWORD) {
4372         ALOGVV(" %s: reading on st session bytes=%zu", __func__, bytes);
4373         /* Read from sound trigger HAL */
4374         audio_extn_sound_trigger_read(in, buffer, bytes);
4375         pthread_mutex_unlock(&in->lock);
4376         return bytes;
4377     }
4378 
4379     if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
4380         ret = -ENOSYS;
4381         goto exit;
4382     }
4383 
4384     if (in->standby) {
4385         const int64_t startNs = systemTime(SYSTEM_TIME_MONOTONIC);
4386 
4387         pthread_mutex_lock(&adev->lock);
4388         ret = start_input_stream(in);
4389         pthread_mutex_unlock(&adev->lock);
4390         if (ret != 0) {
4391             goto exit;
4392         }
4393         in->standby = 0;
4394 
4395         // log startup time in ms.
4396         simple_stats_log(
4397                 &in->start_latency_ms, (systemTime(SYSTEM_TIME_MONOTONIC) - startNs) * 1e-6);
4398     }
4399 
4400     // errors that occur here are read errors.
4401     error_code = ERROR_CODE_READ;
4402 
4403     //what's the duration requested by the client?
4404     long ns = pcm_bytes_to_frames(in->pcm, bytes)*1000000000LL/
4405                                                 in->config.rate;
4406     request_in_focus(in, ns);
4407 
4408     bool use_mmap = is_mmap_usecase(in->usecase) || in->realtime;
4409     if (in->pcm) {
4410         if (use_mmap) {
4411             ret = pcm_mmap_read(in->pcm, buffer, bytes);
4412         } else {
4413             ret = pcm_read(in->pcm, buffer, bytes);
4414         }
4415         if (ret < 0) {
4416             ALOGE("Failed to read w/err %s", strerror(errno));
4417             ret = -errno;
4418         }
4419         if (!ret && bytes > 0 && (in->format == AUDIO_FORMAT_PCM_8_24_BIT)) {
4420             if (bytes % 4 == 0) {
4421                 /* data from DSP comes in 24_8 format, convert it to 8_24 */
4422                 int_buf_stream = buffer;
4423                 for (size_t itt=0; itt < bytes/4 ; itt++) {
4424                     int_buf_stream[itt] >>= 8;
4425                 }
4426             } else {
4427                 ALOGE("%s: !!! something wrong !!! ... data not 32 bit aligned ", __func__);
4428                 ret = -EINVAL;
4429                 goto exit;
4430             }
4431         }
4432     }
4433 
4434     release_in_focus(in, ns);
4435 
4436     /*
4437      * Instead of writing zeroes here, we could trust the hardware
4438      * to always provide zeroes when muted.
4439      * No need to acquire adev->lock to read mic_muted here as we don't change its state.
4440      */
4441     if (ret == 0 && adev->mic_muted &&
4442         !voice_is_in_call_rec_stream(in) &&
4443         in->usecase != USECASE_AUDIO_RECORD_AFE_PROXY) {
4444         memset(buffer, 0, bytes);
4445         in->frames_muted += frames;
4446     }
4447 
4448 exit:
4449     pthread_mutex_unlock(&in->lock);
4450 
4451     if (ret != 0) {
4452         error_log_log(in->error_log, error_code, audio_utils_get_real_time_ns());
4453         in_standby(&in->stream.common);
4454         ALOGV("%s: read failed - sleeping for buffer duration", __func__);
4455         usleep(frames * 1000000LL / in_get_sample_rate(&in->stream.common));
4456         memset(buffer, 0, bytes); // clear return data
4457         in->frames_muted += frames;
4458     }
4459     if (bytes > 0) {
4460         in->frames_read += frames;
4461     }
4462     return bytes;
4463 }
4464 
in_get_input_frames_lost(struct audio_stream_in * stream __unused)4465 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream __unused)
4466 {
4467     return 0;
4468 }
4469 
in_get_capture_position(const struct audio_stream_in * stream,int64_t * frames,int64_t * time)4470 static int in_get_capture_position(const struct audio_stream_in *stream,
4471                                    int64_t *frames, int64_t *time)
4472 {
4473     if (stream == NULL || frames == NULL || time == NULL) {
4474         return -EINVAL;
4475     }
4476     struct stream_in *in = (struct stream_in *)stream;
4477     int ret = -ENOSYS;
4478 
4479     lock_input_stream(in);
4480     // note: ST sessions do not close the alsa pcm driver synchronously
4481     // on standby. Therefore, we may return an error even though the
4482     // pcm stream is still opened.
4483     if (in->standby) {
4484         ALOGE_IF(in->pcm != NULL && !(in->flags & AUDIO_INPUT_FLAG_HW_HOTWORD),
4485                  "%s stream in standby but pcm not NULL for non ST session", __func__);
4486         goto exit;
4487     }
4488     if (in->pcm) {
4489         struct timespec timestamp;
4490         unsigned int avail;
4491         if (pcm_get_htimestamp(in->pcm, &avail, &timestamp) == 0) {
4492             *frames = in->frames_read + avail;
4493             *time = timestamp.tv_sec * 1000000000LL + timestamp.tv_nsec;
4494             ret = 0;
4495         }
4496     }
4497 exit:
4498     pthread_mutex_unlock(&in->lock);
4499     return ret;
4500 }
4501 
in_update_effect_list(bool add,effect_handle_t effect,struct listnode * head)4502 static int in_update_effect_list(bool add, effect_handle_t effect,
4503                             struct listnode *head)
4504 {
4505     struct listnode *node;
4506     struct in_effect_list *elist = NULL;
4507     struct in_effect_list *target = NULL;
4508     int ret = 0;
4509 
4510     if (!head)
4511         return ret;
4512 
4513     list_for_each(node, head) {
4514         elist = node_to_item(node, struct in_effect_list, list);
4515         if (elist->handle == effect) {
4516             target = elist;
4517             break;
4518         }
4519     }
4520 
4521     if (add) {
4522         if (target) {
4523             ALOGD("effect %p already exist", effect);
4524             return ret;
4525         }
4526 
4527         target = (struct in_effect_list *)
4528                      calloc(1, sizeof(struct in_effect_list));
4529 
4530         if (!target) {
4531             ALOGE("%s:fail to allocate memory", __func__);
4532             return -ENOMEM;
4533         }
4534 
4535         target->handle = effect;
4536         list_add_tail(head, &target->list);
4537     } else {
4538         if (target) {
4539             list_remove(&target->list);
4540             free(target);
4541         }
4542     }
4543 
4544     return ret;
4545 }
4546 
add_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect,bool enable)4547 static int add_remove_audio_effect(const struct audio_stream *stream,
4548                                    effect_handle_t effect,
4549                                    bool enable)
4550 {
4551     struct stream_in *in = (struct stream_in *)stream;
4552     struct audio_device *adev = in->dev;
4553     int status = 0;
4554     effect_descriptor_t desc;
4555 
4556     status = (*effect)->get_descriptor(effect, &desc);
4557     ALOGV("%s: status %d in->standby %d enable:%d", __func__, status, in->standby, enable);
4558 
4559     if (status != 0)
4560         return status;
4561 
4562     lock_input_stream(in);
4563     pthread_mutex_lock(&in->dev->lock);
4564     if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
4565             in->source == AUDIO_SOURCE_VOICE_RECOGNITION ||
4566             adev->mode == AUDIO_MODE_IN_COMMUNICATION) &&
4567             (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
4568 
4569         in_update_effect_list(enable, effect, &in->aec_list);
4570         enable = !list_empty(&in->aec_list);
4571         if (enable == in->enable_aec)
4572             goto exit;
4573 
4574         in->enable_aec = enable;
4575         ALOGD("AEC enable %d", enable);
4576 
4577         if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
4578             adev->mode == AUDIO_MODE_IN_COMMUNICATION) {
4579             adev->enable_voicerx = enable;
4580             struct audio_usecase *usecase;
4581             struct listnode *node;
4582             list_for_each(node, &adev->usecase_list) {
4583                 usecase = node_to_item(node, struct audio_usecase, list);
4584                 if (usecase->type == PCM_PLAYBACK)
4585                     select_devices(adev, usecase->id);
4586             }
4587         }
4588         if (!in->standby
4589             && enable_disable_effect(in->dev, in, EFFECT_AEC, enable) == -ENOSYS)
4590             select_devices(in->dev, in->usecase);
4591     }
4592     if (memcmp(&desc.type, FX_IID_NS, sizeof(effect_uuid_t)) == 0) {
4593 
4594         in_update_effect_list(enable, effect, &in->ns_list);
4595         enable = !list_empty(&in->ns_list);
4596         if (enable == in->enable_ns)
4597             goto exit;
4598 
4599         in->enable_ns = enable;
4600         ALOGD("NS enable %d", enable);
4601         if (!in->standby) {
4602             if (in->source != AUDIO_SOURCE_VOICE_COMMUNICATION
4603                 || enable_disable_effect(in->dev, in, EFFECT_NS, enable) == -ENOSYS)
4604                 select_devices(in->dev, in->usecase);
4605         }
4606     }
4607 exit:
4608     pthread_mutex_unlock(&in->dev->lock);
4609     pthread_mutex_unlock(&in->lock);
4610 
4611     return 0;
4612 }
4613 
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)4614 static int in_add_audio_effect(const struct audio_stream *stream,
4615                                effect_handle_t effect)
4616 {
4617     ALOGV("%s: effect %p", __func__, effect);
4618     return add_remove_audio_effect(stream, effect, true);
4619 }
4620 
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)4621 static int in_remove_audio_effect(const struct audio_stream *stream,
4622                                   effect_handle_t effect)
4623 {
4624     ALOGV("%s: effect %p", __func__, effect);
4625     return add_remove_audio_effect(stream, effect, false);
4626 }
4627 
in_stop(const struct audio_stream_in * stream)4628 static int in_stop(const struct audio_stream_in* stream)
4629 {
4630     struct stream_in *in = (struct stream_in *)stream;
4631     struct audio_device *adev = in->dev;
4632 
4633     int ret = -ENOSYS;
4634     ALOGV("%s", __func__);
4635     pthread_mutex_lock(&adev->lock);
4636     if (in->usecase == USECASE_AUDIO_RECORD_MMAP && !in->standby &&
4637             in->capture_started && in->pcm != NULL) {
4638         pcm_stop(in->pcm);
4639         ret = stop_input_stream(in);
4640         in->capture_started = false;
4641     }
4642     pthread_mutex_unlock(&adev->lock);
4643     return ret;
4644 }
4645 
in_start(const struct audio_stream_in * stream)4646 static int in_start(const struct audio_stream_in* stream)
4647 {
4648     struct stream_in *in = (struct stream_in *)stream;
4649     struct audio_device *adev = in->dev;
4650     int ret = -ENOSYS;
4651 
4652     ALOGV("%s in %p", __func__, in);
4653     pthread_mutex_lock(&adev->lock);
4654     if (in->usecase == USECASE_AUDIO_RECORD_MMAP && !in->standby &&
4655             !in->capture_started && in->pcm != NULL) {
4656         if (!in->capture_started) {
4657             ret = start_input_stream(in);
4658             if (ret == 0) {
4659                 in->capture_started = true;
4660             }
4661         }
4662     }
4663     pthread_mutex_unlock(&adev->lock);
4664     return ret;
4665 }
4666 
4667 // Read offset for the positional timestamp from a persistent vendor property.
4668 // This is to workaround apparent inaccuracies in the timing information that
4669 // is used by the AAudio timing model. The inaccuracies can cause glitches.
in_get_mmap_time_offset()4670 static int64_t in_get_mmap_time_offset() {
4671     const int32_t kDefaultOffsetMicros = 0;
4672     int32_t mmap_time_offset_micros = property_get_int32(
4673             "persist.audio.in_mmap_delay_micros", kDefaultOffsetMicros);
4674     ALOGI("in_get_mmap_time_offset set to %d micros", mmap_time_offset_micros);
4675     return mmap_time_offset_micros * (int64_t)1000;
4676 }
4677 
in_create_mmap_buffer(const struct audio_stream_in * stream,int32_t min_size_frames,struct audio_mmap_buffer_info * info)4678 static int in_create_mmap_buffer(const struct audio_stream_in *stream,
4679                                   int32_t min_size_frames,
4680                                   struct audio_mmap_buffer_info *info)
4681 {
4682     struct stream_in *in = (struct stream_in *)stream;
4683     struct audio_device *adev = in->dev;
4684     int ret = 0;
4685     unsigned int offset1;
4686     unsigned int frames1;
4687     const char *step = "";
4688     uint32_t mmap_size;
4689     uint32_t buffer_size;
4690 
4691     lock_input_stream(in);
4692     pthread_mutex_lock(&adev->lock);
4693     ALOGV("%s in %p", __func__, in);
4694 
4695     if (info == NULL || min_size_frames <= 0 || min_size_frames > MMAP_MIN_SIZE_FRAMES_MAX) {
4696         ALOGE("%s invalid argument info %p min_size_frames %d", __func__, info, min_size_frames);
4697         ret = -EINVAL;
4698         goto exit;
4699     }
4700     if (in->usecase != USECASE_AUDIO_RECORD_MMAP || !in->standby) {
4701         ALOGE("%s: usecase = %d, standby = %d", __func__, in->usecase, in->standby);
4702         ALOGV("%s in %p", __func__, in);
4703         ret = -ENOSYS;
4704         goto exit;
4705     }
4706     in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
4707     if (in->pcm_device_id < 0) {
4708         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
4709               __func__, in->pcm_device_id, in->usecase);
4710         ret = -EINVAL;
4711         goto exit;
4712     }
4713 
4714     adjust_mmap_period_count(&in->config, min_size_frames);
4715 
4716     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
4717           __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
4718     in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
4719                         (PCM_IN | PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC), &in->config);
4720     if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
4721         step = "open";
4722         ret = -ENODEV;
4723         goto exit;
4724     }
4725 
4726     ret = pcm_mmap_begin(in->pcm, &info->shared_memory_address, &offset1, &frames1);
4727     if (ret < 0)  {
4728         step = "begin";
4729         goto exit;
4730     }
4731     info->buffer_size_frames = pcm_get_buffer_size(in->pcm);
4732     buffer_size = pcm_frames_to_bytes(in->pcm, info->buffer_size_frames);
4733     info->burst_size_frames = in->config.period_size;
4734     ret = platform_get_mmap_data_fd(adev->platform,
4735                                     in->pcm_device_id, 1 /*capture*/,
4736                                     &info->shared_memory_fd,
4737                                     &mmap_size);
4738     if (ret < 0) {
4739         // Fall back to non exclusive mode
4740         info->shared_memory_fd = pcm_get_poll_fd(in->pcm);
4741     } else {
4742         in->mmap_shared_memory_fd = info->shared_memory_fd; // for closing later
4743         ALOGV("%s: opened mmap_shared_memory_fd = %d", __func__, in->mmap_shared_memory_fd);
4744 
4745         if (mmap_size < buffer_size) {
4746             step = "mmap";
4747             goto exit;
4748         }
4749         // FIXME: indicate exclusive mode support by returning a negative buffer size
4750         info->buffer_size_frames *= -1;
4751     }
4752 
4753     memset(info->shared_memory_address, 0, buffer_size);
4754 
4755     ret = pcm_mmap_commit(in->pcm, 0, MMAP_PERIOD_SIZE);
4756     if (ret < 0) {
4757         step = "commit";
4758         goto exit;
4759     }
4760 
4761     in->mmap_time_offset_nanos = in_get_mmap_time_offset();
4762 
4763     in->standby = false;
4764     ret = 0;
4765 
4766     ALOGV("%s: got mmap buffer address %p info->buffer_size_frames %d",
4767           __func__, info->shared_memory_address, info->buffer_size_frames);
4768 
4769 exit:
4770     if (ret != 0) {
4771         if (in->pcm == NULL) {
4772             ALOGE("%s: %s - %d", __func__, step, ret);
4773         } else {
4774             ALOGE("%s: %s %s", __func__, step, pcm_get_error(in->pcm));
4775             pcm_close(in->pcm);
4776             in->pcm = NULL;
4777         }
4778     }
4779     pthread_mutex_unlock(&adev->lock);
4780     pthread_mutex_unlock(&in->lock);
4781     return ret;
4782 }
4783 
in_get_mmap_position(const struct audio_stream_in * stream,struct audio_mmap_position * position)4784 static int in_get_mmap_position(const struct audio_stream_in *stream,
4785                                   struct audio_mmap_position *position)
4786 {
4787     int ret = 0;
4788     struct stream_in *in = (struct stream_in *)stream;
4789     ALOGVV("%s", __func__);
4790     if (position == NULL) {
4791         return -EINVAL;
4792     }
4793     lock_input_stream(in);
4794     if (in->usecase != USECASE_AUDIO_RECORD_MMAP ||
4795         in->pcm == NULL) {
4796         ret = -ENOSYS;
4797         goto exit;
4798     }
4799     struct timespec ts = { 0, 0 };
4800     ret = pcm_mmap_get_hw_ptr(in->pcm, (unsigned int *)&position->position_frames, &ts);
4801     if (ret < 0) {
4802         ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
4803         goto exit;
4804     }
4805     position->time_nanoseconds = audio_utils_ns_from_timespec(&ts)
4806             + in->mmap_time_offset_nanos;
4807 
4808 exit:
4809     pthread_mutex_unlock(&in->lock);
4810     return ret;
4811 }
4812 
in_get_active_microphones(const struct audio_stream_in * stream,struct audio_microphone_characteristic_t * mic_array,size_t * mic_count)4813 static int in_get_active_microphones(const struct audio_stream_in *stream,
4814                                      struct audio_microphone_characteristic_t *mic_array,
4815                                      size_t *mic_count) {
4816     struct stream_in *in = (struct stream_in *)stream;
4817     struct audio_device *adev = in->dev;
4818     ALOGVV("%s", __func__);
4819 
4820     lock_input_stream(in);
4821     pthread_mutex_lock(&adev->lock);
4822     int ret = platform_get_active_microphones(adev->platform,
4823                                               audio_channel_count_from_in_mask(in->channel_mask),
4824                                               in->usecase, mic_array, mic_count);
4825     pthread_mutex_unlock(&adev->lock);
4826     pthread_mutex_unlock(&in->lock);
4827 
4828     return ret;
4829 }
4830 
adev_get_microphones(const struct audio_hw_device * dev,struct audio_microphone_characteristic_t * mic_array,size_t * mic_count)4831 static int adev_get_microphones(const struct audio_hw_device *dev,
4832                                 struct audio_microphone_characteristic_t *mic_array,
4833                                 size_t *mic_count) {
4834     struct audio_device *adev = (struct audio_device *)dev;
4835     ALOGVV("%s", __func__);
4836 
4837     pthread_mutex_lock(&adev->lock);
4838     int ret = platform_get_microphones(adev->platform, mic_array, mic_count);
4839     pthread_mutex_unlock(&adev->lock);
4840 
4841     return ret;
4842 }
4843 
in_set_microphone_direction(const struct audio_stream_in * stream,audio_microphone_direction_t dir)4844 static int in_set_microphone_direction(const struct audio_stream_in *stream,
4845                                            audio_microphone_direction_t dir) {
4846     struct stream_in *in = (struct stream_in *)stream;
4847 
4848     ALOGVV("%s: standby %d source %d dir %d", __func__, in->standby, in->source, dir);
4849 
4850     in->direction = dir;
4851 
4852     if (in->standby)
4853         return 0;
4854 
4855     return audio_extn_audiozoom_set_microphone_direction(in, dir);
4856 }
4857 
in_set_microphone_field_dimension(const struct audio_stream_in * stream,float zoom)4858 static int in_set_microphone_field_dimension(const struct audio_stream_in *stream, float zoom) {
4859     struct stream_in *in = (struct stream_in *)stream;
4860 
4861     ALOGVV("%s: standby %d source %d zoom %f", __func__, in->standby, in->source, zoom);
4862 
4863     if (zoom > 1.0 || zoom < -1.0)
4864         return -EINVAL;
4865 
4866     in->zoom = zoom;
4867 
4868     if (in->standby)
4869         return 0;
4870 
4871     return audio_extn_audiozoom_set_microphone_field_dimension(in, zoom);
4872 }
4873 
in_update_sink_metadata(struct audio_stream_in * stream,const struct sink_metadata * sink_metadata)4874 static void in_update_sink_metadata(struct audio_stream_in *stream,
4875                                     const struct sink_metadata *sink_metadata) {
4876 
4877     if (stream == NULL
4878             || sink_metadata == NULL
4879             || sink_metadata->tracks == NULL) {
4880         return;
4881     }
4882 
4883     int error = 0;
4884     struct stream_in *in = (struct stream_in *)stream;
4885     struct audio_device *adev = in->dev;
4886     audio_devices_t device = AUDIO_DEVICE_NONE;
4887 
4888     if (sink_metadata->track_count != 0)
4889         device = sink_metadata->tracks->dest_device;
4890 
4891     lock_input_stream(in);
4892     pthread_mutex_lock(&adev->lock);
4893     ALOGV("%s: in->usecase: %d, device: %x", __func__, in->usecase, device);
4894 
4895     if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY
4896             && device != AUDIO_DEVICE_NONE
4897             && adev->voice_tx_output != NULL) {
4898         /* Use the rx device from afe-proxy record to route voice call because
4899            there is no routing if tx device is on primary hal and rx device
4900            is on other hal during voice call. */
4901         adev->voice_tx_output->devices = device;
4902 
4903         if (!voice_is_call_state_active(adev)) {
4904             if (adev->mode == AUDIO_MODE_IN_CALL) {
4905                 adev->current_call_output = adev->voice_tx_output;
4906                 error = voice_start_call(adev);
4907                 if (error != 0)
4908                     ALOGE("%s: start voice call failed %d", __func__, error);
4909             }
4910         } else {
4911             adev->current_call_output = adev->voice_tx_output;
4912             voice_update_devices_for_all_voice_usecases(adev);
4913         }
4914     }
4915 
4916     pthread_mutex_unlock(&adev->lock);
4917     pthread_mutex_unlock(&in->lock);
4918 }
4919 
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,const char * address __unused)4920 static int adev_open_output_stream(struct audio_hw_device *dev,
4921                                    audio_io_handle_t handle,
4922                                    audio_devices_t devices,
4923                                    audio_output_flags_t flags,
4924                                    struct audio_config *config,
4925                                    struct audio_stream_out **stream_out,
4926                                    const char *address __unused)
4927 {
4928     struct audio_device *adev = (struct audio_device *)dev;
4929     struct stream_out *out;
4930     int i, ret = 0;
4931     bool is_hdmi = devices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
4932     bool is_usb_dev = audio_is_usb_out_device(devices) &&
4933                       (devices != AUDIO_DEVICE_OUT_USB_ACCESSORY);
4934     bool force_haptic_path =
4935             property_get_bool("vendor.audio.test_haptic", false);
4936 
4937     if (is_usb_dev && !is_usb_ready(adev, true /* is_playback */)) {
4938         return -ENOSYS;
4939     }
4940 
4941     ALOGV("%s: enter: format(%#x) sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)",
4942           __func__, config->format, config->sample_rate, config->channel_mask, devices, flags);
4943 
4944     *stream_out = NULL;
4945     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
4946 
4947     pthread_mutex_init(&out->compr_mute_lock, (const pthread_mutexattr_t *) NULL);
4948 
4949     if (devices == AUDIO_DEVICE_NONE)
4950         devices = AUDIO_DEVICE_OUT_SPEAKER;
4951 
4952     out->flags = flags;
4953     out->devices = devices;
4954     out->dev = adev;
4955     out->handle = handle;
4956     out->a2dp_compress_mute = false;
4957     out->mmap_shared_memory_fd = -1; // not open
4958 
4959     /* Init use case and pcm_config */
4960     if ((is_hdmi || is_usb_dev) &&
4961         (audio_is_linear_pcm(config->format) || config->format == AUDIO_FORMAT_DEFAULT) &&
4962         (flags == AUDIO_OUTPUT_FLAG_NONE ||
4963         (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0)) {
4964         audio_format_t req_format = config->format;
4965         audio_channel_mask_t req_channel_mask = config->channel_mask;
4966         uint32_t req_sample_rate = config->sample_rate;
4967 
4968         pthread_mutex_lock(&adev->lock);
4969         if (is_hdmi) {
4970             ret = read_hdmi_channel_masks(out);
4971             if (config->sample_rate == 0)
4972                 config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
4973             if (config->channel_mask == AUDIO_CHANNEL_NONE)
4974                 config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
4975             if (config->format == AUDIO_FORMAT_DEFAULT)
4976                 config->format = AUDIO_FORMAT_PCM_16_BIT;
4977         } else if (is_usb_dev) {
4978             ret = read_usb_sup_params_and_compare(true /*is_playback*/,
4979                                                   &config->format,
4980                                                   &out->supported_formats[0],
4981                                                   MAX_SUPPORTED_FORMATS,
4982                                                   &config->channel_mask,
4983                                                   &out->supported_channel_masks[0],
4984                                                   MAX_SUPPORTED_CHANNEL_MASKS,
4985                                                   &config->sample_rate,
4986                                                   &out->supported_sample_rates[0],
4987                                                   MAX_SUPPORTED_SAMPLE_RATES);
4988             ALOGV("plugged dev USB ret %d", ret);
4989         }
4990         pthread_mutex_unlock(&adev->lock);
4991         if (ret != 0) {
4992             // For MMAP NO IRQ, allow conversions in ADSP
4993             if (is_hdmi || (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0)
4994                 goto error_open;
4995 
4996             if (req_sample_rate != 0 && config->sample_rate != req_sample_rate)
4997                 config->sample_rate = req_sample_rate;
4998             if (req_channel_mask != AUDIO_CHANNEL_NONE && config->channel_mask != req_channel_mask)
4999                 config->channel_mask = req_channel_mask;
5000             if (req_format != AUDIO_FORMAT_DEFAULT && config->format != req_format)
5001                 config->format = req_format;
5002         }
5003 
5004         out->sample_rate = config->sample_rate;
5005         out->channel_mask = config->channel_mask;
5006         out->format = config->format;
5007         if (is_hdmi) {
5008             out->usecase = USECASE_AUDIO_PLAYBACK_HIFI;
5009             out->config = pcm_config_hdmi_multi;
5010         } else if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
5011             out->usecase = USECASE_AUDIO_PLAYBACK_MMAP;
5012             out->config = pcm_config_mmap_playback;
5013             out->stream.start = out_start;
5014             out->stream.stop = out_stop;
5015             out->stream.create_mmap_buffer = out_create_mmap_buffer;
5016             out->stream.get_mmap_position = out_get_mmap_position;
5017         } else {
5018             out->usecase = USECASE_AUDIO_PLAYBACK_HIFI;
5019             out->config = pcm_config_hifi;
5020         }
5021 
5022         out->config.rate = out->sample_rate;
5023         out->config.channels = audio_channel_count_from_out_mask(out->channel_mask);
5024         if (is_hdmi) {
5025             out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels *
5026                                                          audio_bytes_per_sample(out->format));
5027         }
5028         out->config.format = pcm_format_from_audio_format(out->format);
5029     } else if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5030         pthread_mutex_lock(&adev->lock);
5031         bool offline = (adev->card_status == CARD_STATUS_OFFLINE);
5032         pthread_mutex_unlock(&adev->lock);
5033 
5034         // reject offload during card offline to allow
5035         // fallback to s/w paths
5036         if (offline) {
5037             ret = -ENODEV;
5038             goto error_open;
5039         }
5040 
5041         if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
5042             config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
5043             ALOGE("%s: Unsupported Offload information", __func__);
5044             ret = -EINVAL;
5045             goto error_open;
5046         }
5047         if (!is_supported_format(config->offload_info.format)) {
5048             ALOGE("%s: Unsupported audio format", __func__);
5049             ret = -EINVAL;
5050             goto error_open;
5051         }
5052         out->sample_rate = config->offload_info.sample_rate;
5053         if (config->offload_info.channel_mask != AUDIO_CHANNEL_NONE)
5054             out->channel_mask = config->offload_info.channel_mask;
5055         else if (config->channel_mask != AUDIO_CHANNEL_NONE)
5056             out->channel_mask = config->channel_mask;
5057         else
5058             out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5059 
5060         out->format = config->offload_info.format;
5061 
5062         out->compr_config.codec = (struct snd_codec *)
5063                                     calloc(1, sizeof(struct snd_codec));
5064 
5065         out->usecase = USECASE_AUDIO_PLAYBACK_OFFLOAD;
5066 
5067         out->stream.set_callback = out_set_callback;
5068         out->stream.pause = out_pause;
5069         out->stream.resume = out_resume;
5070         out->stream.drain = out_drain;
5071         out->stream.flush = out_flush;
5072 
5073         out->compr_config.codec->id =
5074                 get_snd_codec_id(config->offload_info.format);
5075         out->compr_config.fragment_size = COMPRESS_OFFLOAD_FRAGMENT_SIZE;
5076         out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
5077         out->compr_config.codec->sample_rate = out->sample_rate;
5078         out->compr_config.codec->bit_rate =
5079                     config->offload_info.bit_rate;
5080         out->compr_config.codec->ch_in =
5081                 audio_channel_count_from_out_mask(out->channel_mask);
5082         out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
5083 
5084         if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
5085             out->non_blocking = 1;
5086 
5087         out->send_new_metadata = 1;
5088         create_offload_callback_thread(out);
5089         ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
5090                 __func__, config->offload_info.version,
5091                 config->offload_info.bit_rate);
5092     } else if (out->flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) {
5093         switch (config->sample_rate) {
5094             case 0:
5095                 out->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
5096                 break;
5097             case 8000:
5098             case 16000:
5099             case 48000:
5100                 out->sample_rate = config->sample_rate;
5101                 break;
5102             default:
5103                 ALOGE("%s: Unsupported sampling rate %d for Incall Music", __func__,
5104                       config->sample_rate);
5105                 config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
5106                 ret = -EINVAL;
5107                 goto error_open;
5108         }
5109         //FIXME: add support for MONO stream configuration when audioflinger mixer supports it
5110         switch (config->channel_mask) {
5111             case AUDIO_CHANNEL_NONE:
5112             case AUDIO_CHANNEL_OUT_STEREO:
5113                 out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5114                 break;
5115             default:
5116                 ALOGE("%s: Unsupported channel mask %#x for Incall Music", __func__,
5117                       config->channel_mask);
5118                 config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5119                 ret = -EINVAL;
5120                 goto error_open;
5121         }
5122         switch (config->format) {
5123             case AUDIO_FORMAT_DEFAULT:
5124             case AUDIO_FORMAT_PCM_16_BIT:
5125                 out->format = AUDIO_FORMAT_PCM_16_BIT;
5126                 break;
5127             default:
5128                 ALOGE("%s: Unsupported format %#x for Incall Music", __func__,
5129                       config->format);
5130                 config->format = AUDIO_FORMAT_PCM_16_BIT;
5131                 ret = -EINVAL;
5132                 goto error_open;
5133         }
5134 
5135         voice_extn_check_and_set_incall_music_usecase(adev, out);
5136     } else  if (out->devices == AUDIO_DEVICE_OUT_TELEPHONY_TX) {
5137         switch (config->sample_rate) {
5138             case 0:
5139                 out->sample_rate = AFE_PROXY_SAMPLING_RATE;
5140                 break;
5141             case 8000:
5142             case 16000:
5143             case 48000:
5144                 out->sample_rate = config->sample_rate;
5145                 break;
5146             default:
5147                 ALOGE("%s: Unsupported sampling rate %d for Telephony TX", __func__,
5148                       config->sample_rate);
5149                 config->sample_rate = AFE_PROXY_SAMPLING_RATE;
5150                 ret = -EINVAL;
5151                 break;
5152         }
5153         //FIXME: add support for MONO stream configuration when audioflinger mixer supports it
5154         switch (config->channel_mask) {
5155             case AUDIO_CHANNEL_NONE:
5156                 out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5157                 break;
5158             case AUDIO_CHANNEL_OUT_STEREO:
5159                 out->channel_mask = config->channel_mask;
5160                 break;
5161             default:
5162                 ALOGE("%s: Unsupported channel mask %#x for Telephony TX", __func__,
5163                       config->channel_mask);
5164                 config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5165                 ret = -EINVAL;
5166                 break;
5167         }
5168         switch (config->format) {
5169             case AUDIO_FORMAT_DEFAULT:
5170                 out->format = AUDIO_FORMAT_PCM_16_BIT;
5171                 break;
5172             case AUDIO_FORMAT_PCM_16_BIT:
5173                 out->format = config->format;
5174                 break;
5175             default:
5176                 ALOGE("%s: Unsupported format %#x for Telephony TX", __func__,
5177                       config->format);
5178                 config->format = AUDIO_FORMAT_PCM_16_BIT;
5179                 ret = -EINVAL;
5180                 break;
5181         }
5182         if (ret != 0)
5183             goto error_open;
5184 
5185         out->usecase = USECASE_AUDIO_PLAYBACK_AFE_PROXY;
5186         out->config = pcm_config_afe_proxy_playback;
5187         out->config.rate = out->sample_rate;
5188         out->config.channels =
5189                 audio_channel_count_from_out_mask(out->channel_mask);
5190         out->config.format = pcm_format_from_audio_format(out->format);
5191         adev->voice_tx_output = out;
5192     } else if (flags == AUDIO_OUTPUT_FLAG_VOIP_RX) {
5193         switch (config->sample_rate) {
5194             case 0:
5195                 out->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
5196                 break;
5197             case 8000:
5198             case 16000:
5199             case 32000:
5200             case 48000:
5201                 out->sample_rate = config->sample_rate;
5202                 break;
5203             default:
5204                 ALOGE("%s: Unsupported sampling rate %d for Voip RX", __func__,
5205                       config->sample_rate);
5206                 config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
5207                 ret = -EINVAL;
5208                 break;
5209         }
5210         //FIXME: add support for MONO stream configuration when audioflinger mixer supports it
5211         switch (config->channel_mask) {
5212             case AUDIO_CHANNEL_NONE:
5213                 out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5214                 break;
5215             case AUDIO_CHANNEL_OUT_STEREO:
5216                 out->channel_mask = config->channel_mask;
5217                 break;
5218             default:
5219                 ALOGE("%s: Unsupported channel mask %#x for Voip RX", __func__,
5220                       config->channel_mask);
5221                 config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
5222                 ret = -EINVAL;
5223                 break;
5224         }
5225         switch (config->format) {
5226             case AUDIO_FORMAT_DEFAULT:
5227                 out->format = AUDIO_FORMAT_PCM_16_BIT;
5228                 break;
5229             case AUDIO_FORMAT_PCM_16_BIT:
5230                 out->format = config->format;
5231                 break;
5232             default:
5233                 ALOGE("%s: Unsupported format %#x for Voip RX", __func__,
5234                       config->format);
5235                 config->format = AUDIO_FORMAT_PCM_16_BIT;
5236                 ret = -EINVAL;
5237                 break;
5238         }
5239         if (ret != 0)
5240             goto error_open;
5241 
5242         uint32_t buffer_size, frame_size;
5243         out->usecase = USECASE_AUDIO_PLAYBACK_VOIP;
5244         out->config = pcm_config_voip;
5245         out->config.rate = out->sample_rate;
5246         out->config.format = pcm_format_from_audio_format(out->format);
5247         buffer_size = get_stream_buffer_size(VOIP_PLAYBACK_PERIOD_DURATION_MSEC,
5248                                              out->sample_rate,
5249                                              out->format,
5250                                              out->config.channels,
5251                                              false /*is_low_latency*/);
5252         frame_size = audio_bytes_per_sample(out->format) * out->config.channels;
5253         out->config.period_size = buffer_size / frame_size;
5254         out->config.period_count = VOIP_PLAYBACK_PERIOD_COUNT;
5255         out->af_period_multiplier = 1;
5256     } else {
5257         if (flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
5258             out->usecase = USECASE_AUDIO_PLAYBACK_DEEP_BUFFER;
5259             out->config = pcm_config_deep_buffer;
5260         } else if (flags & AUDIO_OUTPUT_FLAG_TTS) {
5261             out->usecase = USECASE_AUDIO_PLAYBACK_TTS;
5262             out->config = pcm_config_deep_buffer;
5263         } else if (flags & AUDIO_OUTPUT_FLAG_RAW) {
5264             out->usecase = USECASE_AUDIO_PLAYBACK_ULL;
5265             out->realtime = may_use_noirq_mode(adev, USECASE_AUDIO_PLAYBACK_ULL, out->flags);
5266             out->config = out->realtime ? pcm_config_rt : pcm_config_low_latency;
5267         } else if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
5268             out->usecase = USECASE_AUDIO_PLAYBACK_MMAP;
5269             out->config = pcm_config_mmap_playback;
5270             out->stream.start = out_start;
5271             out->stream.stop = out_stop;
5272             out->stream.create_mmap_buffer = out_create_mmap_buffer;
5273             out->stream.get_mmap_position = out_get_mmap_position;
5274         } else {
5275             if (config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL) {
5276                 out->usecase = USECASE_AUDIO_PLAYBACK_WITH_HAPTICS;
5277                 adev->haptic_pcm_device_id = platform_get_haptics_pcm_device_id();
5278                 if (adev->haptic_pcm_device_id < 0) {
5279                     ALOGE("%s: Invalid Haptics pcm device id(%d) for the usecase(%d)",
5280                           __func__, adev->haptic_pcm_device_id, out->usecase);
5281                     ret = -ENOSYS;
5282                     goto error_open;
5283                 }
5284                 out->config = pcm_config_haptics_audio;
5285                 if (force_haptic_path)
5286                     adev->haptics_config = pcm_config_haptics_audio;
5287                 else
5288                     adev->haptics_config = pcm_config_haptics;
5289             } else {
5290                 out->usecase = USECASE_AUDIO_PLAYBACK_LOW_LATENCY;
5291                 out->config = pcm_config_low_latency;
5292             }
5293         }
5294 
5295         if (config->sample_rate == 0) {
5296             out->sample_rate = out->config.rate;
5297         } else {
5298             out->sample_rate = config->sample_rate;
5299         }
5300 
5301         if (config->channel_mask == AUDIO_CHANNEL_NONE) {
5302             out->channel_mask = audio_channel_out_mask_from_count(out->config.channels);
5303         } else {
5304             out->channel_mask = config->channel_mask;
5305         }
5306 
5307         if (config->format == AUDIO_FORMAT_DEFAULT)
5308             out->format = audio_format_from_pcm_format(out->config.format);
5309         else if (!audio_is_linear_pcm(config->format)) {
5310             config->format = AUDIO_FORMAT_PCM_16_BIT;
5311             ret = -EINVAL;
5312             goto error_open;
5313         } else {
5314             out->format = config->format;
5315         }
5316 
5317         out->config.rate = out->sample_rate;
5318 
5319         if (config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL) {
5320              out->config.channels =
5321                 audio_channel_count_from_out_mask(out->channel_mask &
5322                                                   ~AUDIO_CHANNEL_HAPTIC_ALL);
5323 
5324              if (force_haptic_path) {
5325                  out->config.channels = 1;
5326                  adev->haptics_config.channels = 1;
5327              } else {
5328                  adev->haptics_config.channels =
5329                      audio_channel_count_from_out_mask(out->channel_mask &
5330                                                       AUDIO_CHANNEL_HAPTIC_ALL);
5331              }
5332         } else {
5333              out->config.channels =
5334                     audio_channel_count_from_out_mask(out->channel_mask);
5335         }
5336 
5337         if (out->format != audio_format_from_pcm_format(out->config.format)) {
5338             out->config.format = pcm_format_from_audio_format(out->format);
5339         }
5340     }
5341 
5342     if ((config->sample_rate != 0 && config->sample_rate != out->sample_rate) ||
5343         (config->format != AUDIO_FORMAT_DEFAULT && config->format != out->format) ||
5344         (config->channel_mask != AUDIO_CHANNEL_NONE && config->channel_mask != out->channel_mask)) {
5345         ALOGI("%s: Unsupported output config. sample_rate:%u format:%#x channel_mask:%#x",
5346               __func__, config->sample_rate, config->format, config->channel_mask);
5347         config->sample_rate = out->sample_rate;
5348         config->format = out->format;
5349         config->channel_mask = out->channel_mask;
5350         ret = -EINVAL;
5351         goto error_open;
5352     }
5353 
5354     ALOGV("%s: Usecase(%s) config->format %#x  out->config.format %#x\n",
5355             __func__, use_case_table[out->usecase], config->format, out->config.format);
5356 
5357     if (flags & AUDIO_OUTPUT_FLAG_PRIMARY) {
5358         if (adev->primary_output == NULL)
5359             adev->primary_output = out;
5360         else {
5361             ALOGE("%s: Primary output is already opened", __func__);
5362             ret = -EEXIST;
5363             goto error_open;
5364         }
5365     }
5366 
5367     /* Check if this usecase is already existing */
5368     pthread_mutex_lock(&adev->lock);
5369     if (get_usecase_from_list(adev, out->usecase) != NULL) {
5370         ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
5371         pthread_mutex_unlock(&adev->lock);
5372         ret = -EEXIST;
5373         goto error_open;
5374     }
5375     pthread_mutex_unlock(&adev->lock);
5376 
5377     out->stream.common.get_sample_rate = out_get_sample_rate;
5378     out->stream.common.set_sample_rate = out_set_sample_rate;
5379     out->stream.common.get_buffer_size = out_get_buffer_size;
5380     out->stream.common.get_channels = out_get_channels;
5381     out->stream.common.get_format = out_get_format;
5382     out->stream.common.set_format = out_set_format;
5383     out->stream.common.standby = out_standby;
5384     out->stream.common.dump = out_dump;
5385     out->stream.common.set_parameters = out_set_parameters;
5386     out->stream.common.get_parameters = out_get_parameters;
5387     out->stream.common.add_audio_effect = out_add_audio_effect;
5388     out->stream.common.remove_audio_effect = out_remove_audio_effect;
5389     out->stream.get_latency = out_get_latency;
5390     out->stream.set_volume = out_set_volume;
5391 #ifdef NO_AUDIO_OUT
5392     out->stream.write = out_write_for_no_output;
5393 #else
5394     out->stream.write = out_write;
5395 #endif
5396     out->stream.get_render_position = out_get_render_position;
5397     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
5398     out->stream.get_presentation_position = out_get_presentation_position;
5399 
5400     if (out->realtime)
5401         out->af_period_multiplier = af_period_multiplier;
5402     else
5403         out->af_period_multiplier = 1;
5404 
5405     out->kernel_buffer_size = out->config.period_size * out->config.period_count;
5406 
5407     out->standby = 1;
5408     /* out->muted = false; by calloc() */
5409     /* out->written = 0; by calloc() */
5410 
5411     pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
5412     pthread_mutex_init(&out->pre_lock, (const pthread_mutexattr_t *) NULL);
5413     pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);
5414 
5415     config->format = out->stream.common.get_format(&out->stream.common);
5416     config->channel_mask = out->stream.common.get_channels(&out->stream.common);
5417     config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
5418 
5419     register_format(out->format, out->supported_formats);
5420     register_channel_mask(out->channel_mask, out->supported_channel_masks);
5421     register_sample_rate(out->sample_rate, out->supported_sample_rates);
5422 
5423     out->error_log = error_log_create(
5424             ERROR_LOG_ENTRIES,
5425             1000000000 /* aggregate consecutive identical errors within one second in ns */);
5426 
5427     /*
5428        By locking output stream before registering, we allow the callback
5429        to update stream's state only after stream's initial state is set to
5430        adev state.
5431     */
5432     lock_output_stream(out);
5433     audio_extn_snd_mon_register_listener(out, out_snd_mon_cb);
5434     pthread_mutex_lock(&adev->lock);
5435     out->card_status = adev->card_status;
5436     pthread_mutex_unlock(&adev->lock);
5437     pthread_mutex_unlock(&out->lock);
5438 
5439     stream_app_type_cfg_init(&out->app_type_cfg);
5440 
5441     *stream_out = &out->stream;
5442 
5443     ALOGV("%s: exit", __func__);
5444     return 0;
5445 
5446 error_open:
5447     free(out);
5448     *stream_out = NULL;
5449     ALOGW("%s: exit: ret %d", __func__, ret);
5450     return ret;
5451 }
5452 
adev_close_output_stream(struct audio_hw_device * dev __unused,struct audio_stream_out * stream)5453 static void adev_close_output_stream(struct audio_hw_device *dev __unused,
5454                                      struct audio_stream_out *stream)
5455 {
5456     struct stream_out *out = (struct stream_out *)stream;
5457     struct audio_device *adev = out->dev;
5458 
5459     ALOGV("%s: enter", __func__);
5460 
5461     // must deregister from sndmonitor first to prevent races
5462     // between the callback and close_stream
5463     audio_extn_snd_mon_unregister_listener(out);
5464     out_standby(&stream->common);
5465     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
5466         destroy_offload_callback_thread(out);
5467 
5468         if (out->compr_config.codec != NULL)
5469             free(out->compr_config.codec);
5470     }
5471 
5472     out->a2dp_compress_mute = false;
5473 
5474     if (adev->voice_tx_output == out)
5475         adev->voice_tx_output = NULL;
5476 
5477     error_log_destroy(out->error_log);
5478     out->error_log = NULL;
5479 
5480     pthread_cond_destroy(&out->cond);
5481     pthread_mutex_destroy(&out->pre_lock);
5482     pthread_mutex_destroy(&out->lock);
5483     free(stream);
5484     ALOGV("%s: exit", __func__);
5485 }
5486 
adev_set_parameters(struct audio_hw_device * dev,const char * kvpairs)5487 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
5488 {
5489     struct audio_device *adev = (struct audio_device *)dev;
5490     struct str_parms *parms;
5491     char *str;
5492     char value[32];
5493     int val;
5494     int ret;
5495     int status = 0;
5496     bool a2dp_reconfig = false;
5497 
5498     ALOGV("%s: enter: %s", __func__, kvpairs);
5499 
5500     pthread_mutex_lock(&adev->lock);
5501 
5502     parms = str_parms_create_str(kvpairs);
5503     status = voice_set_parameters(adev, parms);
5504     if (status != 0) {
5505         goto done;
5506     }
5507 
5508     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
5509     if (ret >= 0) {
5510         /* When set to false, HAL should disable EC and NS */
5511         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
5512             adev->bluetooth_nrec = true;
5513         else
5514             adev->bluetooth_nrec = false;
5515     }
5516 
5517     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
5518     if (ret >= 0) {
5519         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
5520             adev->screen_off = false;
5521         else
5522             adev->screen_off = true;
5523     }
5524 
5525     ret = str_parms_get_int(parms, "rotation", &val);
5526     if (ret >= 0) {
5527         bool reverse_speakers = false;
5528         int camera_rotation = CAMERA_ROTATION_LANDSCAPE;
5529         switch (val) {
5530         // FIXME: note that the code below assumes that the speakers are in the correct placement
5531         //   relative to the user when the device is rotated 90deg from its default rotation. This
5532         //   assumption is device-specific, not platform-specific like this code.
5533         case 270:
5534             reverse_speakers = true;
5535             camera_rotation = CAMERA_ROTATION_INVERT_LANDSCAPE;
5536             break;
5537         case 0:
5538         case 180:
5539             camera_rotation = CAMERA_ROTATION_PORTRAIT;
5540             break;
5541         case 90:
5542             camera_rotation = CAMERA_ROTATION_LANDSCAPE;
5543             break;
5544         default:
5545             ALOGE("%s: unexpected rotation of %d", __func__, val);
5546             status = -EINVAL;
5547         }
5548         if (status == 0) {
5549             // check and set swap
5550             //   - check if orientation changed and speaker active
5551             //   - set rotation and cache the rotation value
5552             adev->camera_orientation =
5553                            (adev->camera_orientation & ~CAMERA_ROTATION_MASK) | camera_rotation;
5554 #ifndef MAXXAUDIO_QDSP_ENABLED
5555             platform_check_and_set_swap_lr_channels(adev, reverse_speakers);
5556 #endif
5557         }
5558     }
5559 
5560     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value));
5561     if (ret >= 0) {
5562         adev->bt_wb_speech_enabled = !strcmp(value, AUDIO_PARAMETER_VALUE_ON);
5563     }
5564 
5565     ret = str_parms_get_str(parms, "BT_SCO", value, sizeof(value));
5566     if (ret >= 0) {
5567         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
5568             adev->bt_sco_on = true;
5569         else
5570             adev->bt_sco_on = false;
5571     }
5572 
5573     ret = str_parms_get_str(parms, AUDIO_PARAMETER_DEVICE_CONNECT, value, sizeof(value));
5574     if (ret >= 0) {
5575         audio_devices_t device = (audio_devices_t)strtoul(value, NULL, 10);
5576         if (audio_is_usb_out_device(device)) {
5577             ret = str_parms_get_str(parms, "card", value, sizeof(value));
5578             if (ret >= 0) {
5579                 const int card = atoi(value);
5580                 audio_extn_usb_add_device(device, card);
5581             }
5582         } else if (audio_is_usb_in_device(device)) {
5583             ret = str_parms_get_str(parms, "card", value, sizeof(value));
5584             if (ret >= 0) {
5585                 const int card = atoi(value);
5586                 audio_extn_usb_add_device(device, card);
5587             }
5588         }
5589     }
5590 
5591     ret = str_parms_get_str(parms, AUDIO_PARAMETER_DEVICE_DISCONNECT, value, sizeof(value));
5592     if (ret >= 0) {
5593         audio_devices_t device = (audio_devices_t)strtoul(value, NULL, 10);
5594         if (audio_is_usb_out_device(device)) {
5595             ret = str_parms_get_str(parms, "card", value, sizeof(value));
5596             if (ret >= 0) {
5597                 const int card = atoi(value);
5598                 audio_extn_usb_remove_device(device, card);
5599             }
5600         } else if (audio_is_usb_in_device(device)) {
5601             ret = str_parms_get_str(parms, "card", value, sizeof(value));
5602             if (ret >= 0) {
5603                 const int card = atoi(value);
5604                 audio_extn_usb_remove_device(device, card);
5605             }
5606         }
5607     }
5608 
5609     audio_extn_hfp_set_parameters(adev, parms);
5610     audio_extn_ma_set_parameters(adev, parms);
5611 
5612     status = audio_extn_a2dp_set_parameters(parms, &a2dp_reconfig);
5613     if (status >= 0 && a2dp_reconfig) {
5614         struct audio_usecase *usecase;
5615         struct listnode *node;
5616         list_for_each(node, &adev->usecase_list) {
5617             usecase = node_to_item(node, struct audio_usecase, list);
5618             if ((usecase->type == PCM_PLAYBACK) &&
5619                 (usecase->devices & AUDIO_DEVICE_OUT_ALL_A2DP)) {
5620                 ALOGD("%s: reconfigure A2DP... forcing device switch", __func__);
5621 
5622                 pthread_mutex_unlock(&adev->lock);
5623                 lock_output_stream(usecase->stream.out);
5624                 pthread_mutex_lock(&adev->lock);
5625                 audio_extn_a2dp_set_handoff_mode(true);
5626                 // force device switch to reconfigure encoder
5627                 select_devices(adev, usecase->id);
5628                 audio_extn_a2dp_set_handoff_mode(false);
5629                 pthread_mutex_unlock(&usecase->stream.out->lock);
5630                 break;
5631             }
5632         }
5633     }
5634 
5635     //FIXME: to be replaced by proper video capture properties API
5636     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_CAMERA_FACING, value, sizeof(value));
5637     if (ret >= 0) {
5638         int camera_facing = CAMERA_FACING_BACK;
5639         if (strcmp(value, AUDIO_PARAMETER_VALUE_FRONT) == 0)
5640             camera_facing = CAMERA_FACING_FRONT;
5641         else if (strcmp(value, AUDIO_PARAMETER_VALUE_BACK) == 0)
5642             camera_facing = CAMERA_FACING_BACK;
5643         else {
5644             ALOGW("%s: invalid camera facing value: %s", __func__, value);
5645             goto done;
5646         }
5647         adev->camera_orientation =
5648                        (adev->camera_orientation & ~CAMERA_FACING_MASK) | camera_facing;
5649         struct audio_usecase *usecase;
5650         struct listnode *node;
5651         list_for_each(node, &adev->usecase_list) {
5652             usecase = node_to_item(node, struct audio_usecase, list);
5653             struct stream_in *in = usecase->stream.in;
5654             if (usecase->type == PCM_CAPTURE && in != NULL &&
5655                     in->source == AUDIO_SOURCE_CAMCORDER && !in->standby) {
5656                 select_devices(adev, in->usecase);
5657             }
5658         }
5659     }
5660 
5661 done:
5662     str_parms_destroy(parms);
5663     pthread_mutex_unlock(&adev->lock);
5664     ALOGV("%s: exit with code(%d)", __func__, status);
5665     return status;
5666 }
5667 
adev_get_parameters(const struct audio_hw_device * dev,const char * keys)5668 static char* adev_get_parameters(const struct audio_hw_device *dev,
5669                                  const char *keys)
5670 {
5671     struct audio_device *adev = (struct audio_device *)dev;
5672     struct str_parms *reply = str_parms_create();
5673     struct str_parms *query = str_parms_create_str(keys);
5674     char *str;
5675 
5676     pthread_mutex_lock(&adev->lock);
5677 
5678     voice_get_parameters(adev, query, reply);
5679     audio_extn_a2dp_get_parameters(query, reply);
5680 
5681     str = str_parms_to_str(reply);
5682     str_parms_destroy(query);
5683     str_parms_destroy(reply);
5684 
5685     pthread_mutex_unlock(&adev->lock);
5686     ALOGV("%s: exit: returns - %s", __func__, str);
5687     return str;
5688 }
5689 
adev_init_check(const struct audio_hw_device * dev __unused)5690 static int adev_init_check(const struct audio_hw_device *dev __unused)
5691 {
5692     return 0;
5693 }
5694 
adev_set_voice_volume(struct audio_hw_device * dev,float volume)5695 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
5696 {
5697     int ret;
5698     struct audio_device *adev = (struct audio_device *)dev;
5699 
5700     audio_extn_extspk_set_voice_vol(adev->extspk, volume);
5701 
5702     pthread_mutex_lock(&adev->lock);
5703     ret = voice_set_volume(adev, volume);
5704     pthread_mutex_unlock(&adev->lock);
5705 
5706     return ret;
5707 }
5708 
adev_set_master_volume(struct audio_hw_device * dev __unused,float volume __unused)5709 static int adev_set_master_volume(struct audio_hw_device *dev __unused, float volume __unused)
5710 {
5711     return -ENOSYS;
5712 }
5713 
adev_get_master_volume(struct audio_hw_device * dev __unused,float * volume __unused)5714 static int adev_get_master_volume(struct audio_hw_device *dev __unused,
5715                                   float *volume __unused)
5716 {
5717     return -ENOSYS;
5718 }
5719 
adev_set_master_mute(struct audio_hw_device * dev __unused,bool muted __unused)5720 static int adev_set_master_mute(struct audio_hw_device *dev __unused, bool muted __unused)
5721 {
5722     return -ENOSYS;
5723 }
5724 
adev_get_master_mute(struct audio_hw_device * dev __unused,bool * muted __unused)5725 static int adev_get_master_mute(struct audio_hw_device *dev __unused, bool *muted __unused)
5726 {
5727     return -ENOSYS;
5728 }
5729 
adev_set_mode(struct audio_hw_device * dev,audio_mode_t mode)5730 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
5731 {
5732     struct audio_device *adev = (struct audio_device *)dev;
5733 
5734     pthread_mutex_lock(&adev->lock);
5735     if (adev->mode != mode) {
5736         ALOGD("%s: mode %d", __func__, (int)mode);
5737         adev->mode = mode;
5738         if ((mode == AUDIO_MODE_NORMAL || mode == AUDIO_MODE_IN_COMMUNICATION) &&
5739                 voice_is_in_call(adev)) {
5740             voice_stop_call(adev);
5741             adev->current_call_output = NULL;
5742 
5743             /*
5744              * After stopping the call, it must check if any active capture
5745              * activity device needs to be re-selected.
5746              */
5747             struct audio_usecase *usecase;
5748             struct listnode *node;
5749             list_for_each(node, &adev->usecase_list) {
5750                 usecase = node_to_item(node, struct audio_usecase, list);
5751                 if (usecase->type == PCM_CAPTURE && usecase->stream.in != NULL) {
5752                     select_devices_with_force_switch(adev, usecase->id, true);
5753                 }
5754             }
5755         }
5756     }
5757     pthread_mutex_unlock(&adev->lock);
5758 
5759     audio_extn_extspk_set_mode(adev->extspk, mode);
5760 
5761     return 0;
5762 }
5763 
adev_set_mic_mute(struct audio_hw_device * dev,bool state)5764 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
5765 {
5766     int ret;
5767     struct audio_device *adev = (struct audio_device *)dev;
5768 
5769     ALOGD("%s: state %d", __func__, (int)state);
5770     pthread_mutex_lock(&adev->lock);
5771     if (audio_extn_tfa_98xx_is_supported() && adev->enable_hfp) {
5772         ret = audio_extn_hfp_set_mic_mute(adev, state);
5773     } else {
5774         ret = voice_set_mic_mute(adev, state);
5775     }
5776     adev->mic_muted = state;
5777     pthread_mutex_unlock(&adev->lock);
5778 
5779     return ret;
5780 }
5781 
adev_get_mic_mute(const struct audio_hw_device * dev,bool * state)5782 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
5783 {
5784     *state = voice_get_mic_mute((struct audio_device *)dev);
5785     return 0;
5786 }
5787 
adev_get_input_buffer_size(const struct audio_hw_device * dev __unused,const struct audio_config * config)5788 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev __unused,
5789                                          const struct audio_config *config)
5790 {
5791     int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
5792 
5793     /* Don't know if USB HIFI in this context so use true to be conservative */
5794     if (check_input_parameters(config->sample_rate, config->format, channel_count,
5795                                true /*is_usb_hifi */) != 0)
5796         return 0;
5797 
5798     return get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
5799                                  config->sample_rate, config->format,
5800                                  channel_count,
5801                                  false /* is_low_latency: since we don't know, be conservative */);
5802 }
5803 
adev_input_allow_hifi_record(struct audio_device * adev,audio_devices_t devices,audio_input_flags_t flags,audio_source_t source)5804 static bool adev_input_allow_hifi_record(struct audio_device *adev,
5805                                          audio_devices_t devices,
5806                                          audio_input_flags_t flags,
5807                                          audio_source_t source) {
5808     const bool allowed = true;
5809 
5810     if (!audio_is_usb_in_device(devices))
5811         return !allowed;
5812 
5813     switch (flags) {
5814         case AUDIO_INPUT_FLAG_NONE:
5815         case AUDIO_INPUT_FLAG_FAST: // just fast, not fast|raw || fast|mmap
5816             break;
5817         default:
5818             return !allowed;
5819     }
5820 
5821     switch (source) {
5822         case AUDIO_SOURCE_DEFAULT:
5823         case AUDIO_SOURCE_MIC:
5824         case AUDIO_SOURCE_UNPROCESSED:
5825             break;
5826         default:
5827             return !allowed;
5828     }
5829 
5830     switch (adev->mode) {
5831         case 0:
5832             break;
5833         default:
5834             return !allowed;
5835     }
5836 
5837     return allowed;
5838 }
5839 
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,audio_input_flags_t flags,const char * address __unused,audio_source_t source)5840 static int adev_open_input_stream(struct audio_hw_device *dev,
5841                                   audio_io_handle_t handle,
5842                                   audio_devices_t devices,
5843                                   struct audio_config *config,
5844                                   struct audio_stream_in **stream_in,
5845                                   audio_input_flags_t flags,
5846                                   const char *address __unused,
5847                                   audio_source_t source )
5848 {
5849     struct audio_device *adev = (struct audio_device *)dev;
5850     struct stream_in *in;
5851     int ret = 0, buffer_size, frame_size;
5852     int channel_count;
5853     bool is_low_latency = false;
5854     bool is_usb_dev = audio_is_usb_in_device(devices);
5855     bool may_use_hifi_record = adev_input_allow_hifi_record(adev,
5856                                                             devices,
5857                                                             flags,
5858                                                             source);
5859     ALOGV("%s: enter: flags %#x, is_usb_dev %d, may_use_hifi_record %d,"
5860             " sample_rate %u, channel_mask %#x, format %#x",
5861             __func__, flags, is_usb_dev, may_use_hifi_record,
5862             config->sample_rate, config->channel_mask, config->format);
5863     *stream_in = NULL;
5864 
5865     if (is_usb_dev && !is_usb_ready(adev, false /* is_playback */)) {
5866         return -ENOSYS;
5867     }
5868 
5869     if (!(is_usb_dev && may_use_hifi_record)) {
5870         if (config->sample_rate == 0)
5871             config->sample_rate = DEFAULT_INPUT_SAMPLING_RATE;
5872         if (config->channel_mask == AUDIO_CHANNEL_NONE)
5873             config->channel_mask = AUDIO_CHANNEL_IN_MONO;
5874         if (config->format == AUDIO_FORMAT_DEFAULT)
5875             config->format = AUDIO_FORMAT_PCM_16_BIT;
5876 
5877         channel_count = audio_channel_count_from_in_mask(config->channel_mask);
5878 
5879         if (check_input_parameters(config->sample_rate, config->format, channel_count, false) != 0)
5880             return -EINVAL;
5881     }
5882 
5883     if (audio_extn_tfa_98xx_is_supported() &&
5884         (audio_extn_hfp_is_active(adev) || voice_is_in_call(adev)))
5885         return -EINVAL;
5886 
5887     in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
5888 
5889     pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
5890     pthread_mutex_init(&in->pre_lock, (const pthread_mutexattr_t *) NULL);
5891 
5892     in->stream.common.get_sample_rate = in_get_sample_rate;
5893     in->stream.common.set_sample_rate = in_set_sample_rate;
5894     in->stream.common.get_buffer_size = in_get_buffer_size;
5895     in->stream.common.get_channels = in_get_channels;
5896     in->stream.common.get_format = in_get_format;
5897     in->stream.common.set_format = in_set_format;
5898     in->stream.common.standby = in_standby;
5899     in->stream.common.dump = in_dump;
5900     in->stream.common.set_parameters = in_set_parameters;
5901     in->stream.common.get_parameters = in_get_parameters;
5902     in->stream.common.add_audio_effect = in_add_audio_effect;
5903     in->stream.common.remove_audio_effect = in_remove_audio_effect;
5904     in->stream.set_gain = in_set_gain;
5905     in->stream.read = in_read;
5906     in->stream.get_input_frames_lost = in_get_input_frames_lost;
5907     in->stream.get_capture_position = in_get_capture_position;
5908     in->stream.get_active_microphones = in_get_active_microphones;
5909     in->stream.set_microphone_direction = in_set_microphone_direction;
5910     in->stream.set_microphone_field_dimension = in_set_microphone_field_dimension;
5911     in->stream.update_sink_metadata = in_update_sink_metadata;
5912 
5913     in->device = devices;
5914     in->source = source;
5915     in->dev = adev;
5916     in->standby = 1;
5917     in->capture_handle = handle;
5918     in->flags = flags;
5919     in->direction = MIC_DIRECTION_UNSPECIFIED;
5920     in->zoom = 0;
5921     in->mmap_shared_memory_fd = -1; // not open
5922     list_init(&in->aec_list);
5923     list_init(&in->ns_list);
5924 
5925     ALOGV("%s: source %d, config->channel_mask %#x", __func__, source, config->channel_mask);
5926     if (source == AUDIO_SOURCE_VOICE_UPLINK ||
5927          source == AUDIO_SOURCE_VOICE_DOWNLINK) {
5928         /* Force channel config requested to mono if incall
5929            record is being requested for only uplink/downlink */
5930         if (config->channel_mask != AUDIO_CHANNEL_IN_MONO) {
5931             config->channel_mask = AUDIO_CHANNEL_IN_MONO;
5932             ret = -EINVAL;
5933             goto err_open;
5934         }
5935     }
5936 
5937     if (is_usb_dev && may_use_hifi_record) {
5938         /* HiFi record selects an appropriate format, channel, rate combo
5939            depending on sink capabilities*/
5940         ret = read_usb_sup_params_and_compare(false /*is_playback*/,
5941                                               &config->format,
5942                                               &in->supported_formats[0],
5943                                               MAX_SUPPORTED_FORMATS,
5944                                               &config->channel_mask,
5945                                               &in->supported_channel_masks[0],
5946                                               MAX_SUPPORTED_CHANNEL_MASKS,
5947                                               &config->sample_rate,
5948                                               &in->supported_sample_rates[0],
5949                                               MAX_SUPPORTED_SAMPLE_RATES);
5950         if (ret != 0) {
5951             ret = -EINVAL;
5952             goto err_open;
5953         }
5954         channel_count = audio_channel_count_from_in_mask(config->channel_mask);
5955     } else if (config->format == AUDIO_FORMAT_DEFAULT) {
5956         config->format = AUDIO_FORMAT_PCM_16_BIT;
5957     } else if (config->format == AUDIO_FORMAT_PCM_FLOAT ||
5958                config->format == AUDIO_FORMAT_PCM_24_BIT_PACKED ||
5959                config->format == AUDIO_FORMAT_PCM_8_24_BIT) {
5960         bool ret_error = false;
5961         /* 24 bit is restricted to UNPROCESSED source only,also format supported
5962            from HAL is 8_24
5963            *> In case of UNPROCESSED source, for 24 bit, if format requested is other than
5964               8_24 return error indicating supported format is 8_24
5965            *> In case of any other source requesting 24 bit or float return error
5966               indicating format supported is 16 bit only.
5967 
5968            on error flinger will retry with supported format passed
5969          */
5970         if (!is_supported_24bits_audiosource(source)) {
5971             config->format = AUDIO_FORMAT_PCM_16_BIT;
5972             ret_error = true;
5973         } else if (config->format != AUDIO_FORMAT_PCM_8_24_BIT) {
5974             config->format = AUDIO_FORMAT_PCM_8_24_BIT;
5975             ret_error = true;
5976         }
5977 
5978         if (ret_error) {
5979             ret = -EINVAL;
5980             goto err_open;
5981         }
5982     }
5983 
5984     in->format = config->format;
5985     in->channel_mask = config->channel_mask;
5986 
5987     /* Update config params with the requested sample rate and channels */
5988     if (in->device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
5989         if (config->sample_rate == 0)
5990             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
5991         if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
5992                 config->sample_rate != 8000) {
5993             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
5994             ret = -EINVAL;
5995             goto err_open;
5996         }
5997 
5998         if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
5999             config->format = AUDIO_FORMAT_PCM_16_BIT;
6000             ret = -EINVAL;
6001             goto err_open;
6002         }
6003 
6004         in->usecase = USECASE_AUDIO_RECORD_AFE_PROXY;
6005         in->config = pcm_config_afe_proxy_record;
6006         in->af_period_multiplier = 1;
6007     } else if (is_usb_dev && may_use_hifi_record) {
6008         in->usecase = USECASE_AUDIO_RECORD_HIFI;
6009         in->config = pcm_config_audio_capture;
6010         frame_size = audio_stream_in_frame_size(&in->stream);
6011         buffer_size = get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
6012                                              config->sample_rate,
6013                                              config->format,
6014                                              channel_count,
6015                                              false /*is_low_latency*/);
6016         in->config.period_size = buffer_size / frame_size;
6017         in->config.rate = config->sample_rate;
6018         in->af_period_multiplier = 1;
6019         in->config.format = pcm_format_from_audio_format(config->format);
6020     } else {
6021         in->usecase = USECASE_AUDIO_RECORD;
6022         if (config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE &&
6023                 (in->flags & AUDIO_INPUT_FLAG_FAST) != 0) {
6024             is_low_latency = true;
6025 #if LOW_LATENCY_CAPTURE_USE_CASE
6026             in->usecase = USECASE_AUDIO_RECORD_LOW_LATENCY;
6027 #endif
6028             in->realtime = may_use_noirq_mode(adev, in->usecase, in->flags);
6029             if (!in->realtime) {
6030                 in->config = pcm_config_audio_capture;
6031                 frame_size = audio_stream_in_frame_size(&in->stream);
6032                 buffer_size = get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
6033                                                      config->sample_rate,
6034                                                      config->format,
6035                                                      channel_count,
6036                                                      is_low_latency);
6037                 in->config.period_size = buffer_size / frame_size;
6038                 in->config.rate = config->sample_rate;
6039                 in->af_period_multiplier = 1;
6040             } else {
6041                 // period size is left untouched for rt mode playback
6042                 in->config = pcm_config_audio_capture_rt;
6043                 in->af_period_multiplier = af_period_multiplier;
6044             }
6045         } else if ((config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE) &&
6046                 ((in->flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0)) {
6047             // FIXME: Add support for multichannel capture over USB using MMAP
6048             in->usecase = USECASE_AUDIO_RECORD_MMAP;
6049             in->config = pcm_config_mmap_capture;
6050             in->stream.start = in_start;
6051             in->stream.stop = in_stop;
6052             in->stream.create_mmap_buffer = in_create_mmap_buffer;
6053             in->stream.get_mmap_position = in_get_mmap_position;
6054             in->af_period_multiplier = 1;
6055             ALOGV("%s: USECASE_AUDIO_RECORD_MMAP", __func__);
6056         } else if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
6057                    in->flags & AUDIO_INPUT_FLAG_VOIP_TX &&
6058                    (config->sample_rate == 8000 ||
6059                     config->sample_rate == 16000 ||
6060                     config->sample_rate == 32000 ||
6061                     config->sample_rate == 48000) &&
6062                    channel_count == 1) {
6063             in->usecase = USECASE_AUDIO_RECORD_VOIP;
6064             in->config = pcm_config_audio_capture;
6065             frame_size = audio_stream_in_frame_size(&in->stream);
6066             buffer_size = get_stream_buffer_size(VOIP_CAPTURE_PERIOD_DURATION_MSEC,
6067                                                  config->sample_rate,
6068                                                  config->format,
6069                                                  channel_count, false /*is_low_latency*/);
6070             in->config.period_size = buffer_size / frame_size;
6071             in->config.period_count = VOIP_CAPTURE_PERIOD_COUNT;
6072             in->config.rate = config->sample_rate;
6073             in->af_period_multiplier = 1;
6074         } else {
6075             in->config = pcm_config_audio_capture;
6076             frame_size = audio_stream_in_frame_size(&in->stream);
6077             buffer_size = get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
6078                                                  config->sample_rate,
6079                                                  config->format,
6080                                                  channel_count,
6081                                                  is_low_latency);
6082             in->config.period_size = buffer_size / frame_size;
6083             in->config.rate = config->sample_rate;
6084             in->af_period_multiplier = 1;
6085         }
6086         if (config->format == AUDIO_FORMAT_PCM_8_24_BIT)
6087             in->config.format = PCM_FORMAT_S24_LE;
6088     }
6089 
6090     in->config.channels = channel_count;
6091     in->sample_rate  = in->config.rate;
6092 
6093 
6094     register_format(in->format, in->supported_formats);
6095     register_channel_mask(in->channel_mask, in->supported_channel_masks);
6096     register_sample_rate(in->sample_rate, in->supported_sample_rates);
6097 
6098     in->error_log = error_log_create(
6099             ERROR_LOG_ENTRIES,
6100             NANOS_PER_SECOND /* aggregate consecutive identical errors within one second */);
6101 
6102     /* This stream could be for sound trigger lab,
6103        get sound trigger pcm if present */
6104     audio_extn_sound_trigger_check_and_get_session(in);
6105 
6106     if (in->is_st_session)
6107         in->flags |= AUDIO_INPUT_FLAG_HW_HOTWORD;
6108 
6109     lock_input_stream(in);
6110     audio_extn_snd_mon_register_listener(in, in_snd_mon_cb);
6111     pthread_mutex_lock(&adev->lock);
6112     in->card_status = adev->card_status;
6113     pthread_mutex_unlock(&adev->lock);
6114     pthread_mutex_unlock(&in->lock);
6115 
6116     stream_app_type_cfg_init(&in->app_type_cfg);
6117 
6118     *stream_in = &in->stream;
6119     ALOGV("%s: exit", __func__);
6120     return 0;
6121 
6122 err_open:
6123     free(in);
6124     *stream_in = NULL;
6125     return ret;
6126 }
6127 
adev_close_input_stream(struct audio_hw_device * dev __unused,struct audio_stream_in * stream)6128 static void adev_close_input_stream(struct audio_hw_device *dev __unused,
6129                                     struct audio_stream_in *stream)
6130 {
6131     struct stream_in *in = (struct stream_in *)stream;
6132     ALOGV("%s", __func__);
6133 
6134     // must deregister from sndmonitor first to prevent races
6135     // between the callback and close_stream
6136     audio_extn_snd_mon_unregister_listener(stream);
6137     in_standby(&stream->common);
6138 
6139     error_log_destroy(in->error_log);
6140     in->error_log = NULL;
6141 
6142     pthread_mutex_destroy(&in->pre_lock);
6143     pthread_mutex_destroy(&in->lock);
6144 
6145     free(stream);
6146 
6147     return;
6148 }
6149 
adev_dump(const audio_hw_device_t * device __unused,int fd __unused)6150 static int adev_dump(const audio_hw_device_t *device __unused, int fd __unused)
6151 {
6152     return 0;
6153 }
6154 
6155 /* verifies input and output devices and their capabilities.
6156  *
6157  * This verification is required when enabling extended bit-depth or
6158  * sampling rates, as not all qcom products support it.
6159  *
6160  * Suitable for calling only on initialization such as adev_open().
6161  * It fills the audio_device use_case_table[] array.
6162  *
6163  * Has a side-effect that it needs to configure audio routing / devices
6164  * in order to power up the devices and read the device parameters.
6165  * It does not acquire any hw device lock. Should restore the devices
6166  * back to "normal state" upon completion.
6167  */
adev_verify_devices(struct audio_device * adev)6168 static int adev_verify_devices(struct audio_device *adev)
6169 {
6170     /* enumeration is a bit difficult because one really wants to pull
6171      * the use_case, device id, etc from the hidden pcm_device_table[].
6172      * In this case there are the following use cases and device ids.
6173      *
6174      * [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = {0, 0},
6175      * [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = {15, 15},
6176      * [USECASE_AUDIO_PLAYBACK_HIFI] = {1, 1},
6177      * [USECASE_AUDIO_PLAYBACK_OFFLOAD] = {9, 9},
6178      * [USECASE_AUDIO_RECORD] = {0, 0},
6179      * [USECASE_AUDIO_RECORD_LOW_LATENCY] = {15, 15},
6180      * [USECASE_VOICE_CALL] = {2, 2},
6181      *
6182      * USECASE_AUDIO_PLAYBACK_OFFLOAD, USECASE_AUDIO_PLAYBACK_HIFI omitted.
6183      * USECASE_VOICE_CALL omitted, but possible for either input or output.
6184      */
6185 
6186     /* should be the usecases enabled in adev_open_input_stream() */
6187     static const int test_in_usecases[] = {
6188              USECASE_AUDIO_RECORD,
6189              USECASE_AUDIO_RECORD_LOW_LATENCY, /* does not appear to be used */
6190     };
6191     /* should be the usecases enabled in adev_open_output_stream()*/
6192     static const int test_out_usecases[] = {
6193             USECASE_AUDIO_PLAYBACK_DEEP_BUFFER,
6194             USECASE_AUDIO_PLAYBACK_LOW_LATENCY,
6195     };
6196     static const usecase_type_t usecase_type_by_dir[] = {
6197             PCM_PLAYBACK,
6198             PCM_CAPTURE,
6199     };
6200     static const unsigned flags_by_dir[] = {
6201             PCM_OUT,
6202             PCM_IN,
6203     };
6204 
6205     size_t i;
6206     unsigned dir;
6207     const unsigned card_id = adev->snd_card;
6208     char info[512]; /* for possible debug info */
6209 
6210     for (dir = 0; dir < 2; ++dir) {
6211         const usecase_type_t usecase_type = usecase_type_by_dir[dir];
6212         const unsigned flags_dir = flags_by_dir[dir];
6213         const size_t testsize =
6214                 dir ? ARRAY_SIZE(test_in_usecases) : ARRAY_SIZE(test_out_usecases);
6215         const int *testcases =
6216                 dir ? test_in_usecases : test_out_usecases;
6217         const audio_devices_t audio_device =
6218                 dir ? AUDIO_DEVICE_IN_BUILTIN_MIC : AUDIO_DEVICE_OUT_SPEAKER;
6219 
6220         for (i = 0; i < testsize; ++i) {
6221             const audio_usecase_t audio_usecase = testcases[i];
6222             int device_id;
6223             snd_device_t snd_device;
6224             struct pcm_params **pparams;
6225             struct stream_out out;
6226             struct stream_in in;
6227             struct audio_usecase uc_info;
6228             int retval;
6229 
6230             pparams = &adev->use_case_table[audio_usecase];
6231             pcm_params_free(*pparams); /* can accept null input */
6232             *pparams = NULL;
6233 
6234             /* find the device ID for the use case (signed, for error) */
6235             device_id = platform_get_pcm_device_id(audio_usecase, usecase_type);
6236             if (device_id < 0)
6237                 continue;
6238 
6239             /* prepare structures for device probing */
6240             memset(&uc_info, 0, sizeof(uc_info));
6241             uc_info.id = audio_usecase;
6242             uc_info.type = usecase_type;
6243             if (dir) {
6244                 memset(&in, 0, sizeof(in));
6245                 in.device = audio_device;
6246                 in.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
6247                 uc_info.stream.in = &in;
6248             }
6249             memset(&out, 0, sizeof(out));
6250             out.devices = audio_device; /* only field needed in select_devices */
6251             uc_info.stream.out = &out;
6252             uc_info.devices = audio_device;
6253             uc_info.in_snd_device = SND_DEVICE_NONE;
6254             uc_info.out_snd_device = SND_DEVICE_NONE;
6255             list_add_tail(&adev->usecase_list, &uc_info.list);
6256 
6257             /* select device - similar to start_(in/out)put_stream() */
6258             retval = select_devices(adev, audio_usecase);
6259             if (retval >= 0) {
6260                 *pparams = pcm_params_get(card_id, device_id, flags_dir);
6261 #if LOG_NDEBUG == 0
6262                 if (*pparams) {
6263                     ALOGV("%s: (%s) card %d  device %d", __func__,
6264                             dir ? "input" : "output", card_id, device_id);
6265                     pcm_params_to_string(*pparams, info, ARRAY_SIZE(info));
6266                 } else {
6267                     ALOGV("%s: cannot locate card %d  device %d", __func__, card_id, device_id);
6268                 }
6269 #endif
6270             }
6271 
6272             /* deselect device - similar to stop_(in/out)put_stream() */
6273             /* 1. Get and set stream specific mixer controls */
6274             retval = disable_audio_route(adev, &uc_info);
6275             /* 2. Disable the rx device */
6276             retval = disable_snd_device(adev,
6277                     dir ? uc_info.in_snd_device : uc_info.out_snd_device);
6278             list_remove(&uc_info.list);
6279         }
6280     }
6281     return 0;
6282 }
6283 
adev_close(hw_device_t * device)6284 static int adev_close(hw_device_t *device)
6285 {
6286     size_t i;
6287 
6288     pthread_mutex_lock(&adev_init_lock);
6289     if (!device || ((struct audio_device *)device != adev))
6290         goto done;
6291 
6292     if ((--audio_device_ref_count) == 0) {
6293         audio_extn_snd_mon_unregister_listener(adev);
6294         audio_extn_tfa_98xx_deinit();
6295         audio_extn_ma_deinit();
6296         audio_route_free(adev->audio_route);
6297         free(adev->snd_dev_ref_cnt);
6298         platform_deinit(adev->platform);
6299         audio_extn_extspk_deinit(adev->extspk);
6300         audio_extn_sound_trigger_deinit(adev);
6301         audio_extn_snd_mon_deinit();
6302         for (i = 0; i < ARRAY_SIZE(adev->use_case_table); ++i) {
6303             pcm_params_free(adev->use_case_table[i]);
6304         }
6305         if (adev->adm_deinit)
6306             adev->adm_deinit(adev->adm_data);
6307         pthread_mutex_destroy(&adev->lock);
6308         free(device);
6309         adev = NULL;
6310     }
6311 
6312 done:
6313     pthread_mutex_unlock(&adev_init_lock);
6314     return 0;
6315 }
6316 
6317 /* This returns 1 if the input parameter looks at all plausible as a low latency period size,
6318  * or 0 otherwise.  A return value of 1 doesn't mean the value is guaranteed to work,
6319  * just that it _might_ work.
6320  */
period_size_is_plausible_for_low_latency(int period_size)6321 static int period_size_is_plausible_for_low_latency(int period_size)
6322 {
6323     switch (period_size) {
6324     case 48:
6325     case 96:
6326     case 144:
6327     case 160:
6328     case 192:
6329     case 240:
6330     case 320:
6331     case 480:
6332         return 1;
6333     default:
6334         return 0;
6335     }
6336 }
6337 
adev_snd_mon_cb(void * stream __unused,struct str_parms * parms)6338 static void adev_snd_mon_cb(void * stream __unused, struct str_parms * parms)
6339 {
6340     int card;
6341     card_status_t status;
6342 
6343     if (!parms)
6344         return;
6345 
6346     if (parse_snd_card_status(parms, &card, &status) < 0)
6347         return;
6348 
6349     pthread_mutex_lock(&adev->lock);
6350     bool valid_cb = (card == adev->snd_card);
6351     if (valid_cb) {
6352         if (adev->card_status != status) {
6353             adev->card_status = status;
6354             platform_snd_card_update(adev->platform, status);
6355         }
6356     }
6357     pthread_mutex_unlock(&adev->lock);
6358     return;
6359 }
6360 
6361 /* out and adev lock held */
check_a2dp_restore_l(struct audio_device * adev,struct stream_out * out,bool restore)6362 static int check_a2dp_restore_l(struct audio_device *adev, struct stream_out *out, bool restore)
6363 {
6364     struct audio_usecase *uc_info;
6365     float left_p;
6366     float right_p;
6367     audio_devices_t devices;
6368 
6369     uc_info = get_usecase_from_list(adev, out->usecase);
6370     if (uc_info == NULL) {
6371         ALOGE("%s: Could not find the usecase (%d) in the list",
6372               __func__, out->usecase);
6373         return -EINVAL;
6374     }
6375 
6376     ALOGD("%s: enter: usecase(%d: %s)", __func__,
6377           out->usecase, use_case_table[out->usecase]);
6378 
6379     if (restore) {
6380         // restore A2DP device for active usecases and unmute if required
6381         if ((out->devices & AUDIO_DEVICE_OUT_ALL_A2DP) &&
6382             !is_a2dp_device(uc_info->out_snd_device)) {
6383             ALOGD("%s: restoring A2DP and unmuting stream", __func__);
6384             select_devices(adev, uc_info->id);
6385             pthread_mutex_lock(&out->compr_mute_lock);
6386             if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
6387                 (out->a2dp_compress_mute)) {
6388                 out->a2dp_compress_mute = false;
6389                 set_compr_volume(&out->stream, out->volume_l, out->volume_r);
6390             }
6391             pthread_mutex_unlock(&out->compr_mute_lock);
6392         }
6393     } else {
6394         // mute compress stream if suspended
6395         pthread_mutex_lock(&out->compr_mute_lock);
6396         if ((out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
6397             (!out->a2dp_compress_mute)) {
6398             if (!out->standby) {
6399                 ALOGD("%s: selecting speaker and muting stream", __func__);
6400                 devices = out->devices;
6401                 out->devices = AUDIO_DEVICE_OUT_SPEAKER;
6402                 left_p = out->volume_l;
6403                 right_p = out->volume_r;
6404                 if (out->offload_state == OFFLOAD_STATE_PLAYING)
6405                     compress_pause(out->compr);
6406                 set_compr_volume(&out->stream, 0.0f, 0.0f);
6407                 out->a2dp_compress_mute = true;
6408                 select_devices(adev, out->usecase);
6409                 if (out->offload_state == OFFLOAD_STATE_PLAYING)
6410                     compress_resume(out->compr);
6411                 out->devices = devices;
6412                 out->volume_l = left_p;
6413                 out->volume_r = right_p;
6414             }
6415         }
6416         pthread_mutex_unlock(&out->compr_mute_lock);
6417     }
6418     ALOGV("%s: exit", __func__);
6419     return 0;
6420 }
6421 
check_a2dp_restore(struct audio_device * adev,struct stream_out * out,bool restore)6422 int check_a2dp_restore(struct audio_device *adev, struct stream_out *out, bool restore)
6423 {
6424     int ret = 0;
6425 
6426     lock_output_stream(out);
6427     pthread_mutex_lock(&adev->lock);
6428 
6429     ret = check_a2dp_restore_l(adev, out, restore);
6430 
6431     pthread_mutex_unlock(&adev->lock);
6432     pthread_mutex_unlock(&out->lock);
6433     return ret;
6434 }
6435 
adev_open(const hw_module_t * module,const char * name,hw_device_t ** device)6436 static int adev_open(const hw_module_t *module, const char *name,
6437                      hw_device_t **device)
6438 {
6439     int i, ret;
6440 
6441     ALOGD("%s: enter", __func__);
6442     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
6443     pthread_mutex_lock(&adev_init_lock);
6444     if (audio_device_ref_count != 0) {
6445         *device = &adev->device.common;
6446         audio_device_ref_count++;
6447         ALOGV("%s: returning existing instance of adev", __func__);
6448         ALOGV("%s: exit", __func__);
6449         pthread_mutex_unlock(&adev_init_lock);
6450         return 0;
6451     }
6452     adev = calloc(1, sizeof(struct audio_device));
6453 
6454     pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
6455 
6456     adev->device.common.tag = HARDWARE_DEVICE_TAG;
6457     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
6458     adev->device.common.module = (struct hw_module_t *)module;
6459     adev->device.common.close = adev_close;
6460 
6461     adev->device.init_check = adev_init_check;
6462     adev->device.set_voice_volume = adev_set_voice_volume;
6463     adev->device.set_master_volume = adev_set_master_volume;
6464     adev->device.get_master_volume = adev_get_master_volume;
6465     adev->device.set_master_mute = adev_set_master_mute;
6466     adev->device.get_master_mute = adev_get_master_mute;
6467     adev->device.set_mode = adev_set_mode;
6468     adev->device.set_mic_mute = adev_set_mic_mute;
6469     adev->device.get_mic_mute = adev_get_mic_mute;
6470     adev->device.set_parameters = adev_set_parameters;
6471     adev->device.get_parameters = adev_get_parameters;
6472     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
6473     adev->device.open_output_stream = adev_open_output_stream;
6474     adev->device.close_output_stream = adev_close_output_stream;
6475     adev->device.open_input_stream = adev_open_input_stream;
6476 
6477     adev->device.close_input_stream = adev_close_input_stream;
6478     adev->device.dump = adev_dump;
6479     adev->device.get_microphones = adev_get_microphones;
6480 
6481     /* Set the default route before the PCM stream is opened */
6482     pthread_mutex_lock(&adev->lock);
6483     adev->mode = AUDIO_MODE_NORMAL;
6484     adev->primary_output = NULL;
6485     adev->bluetooth_nrec = true;
6486     adev->acdb_settings = TTY_MODE_OFF;
6487     /* adev->cur_hdmi_channels = 0;  by calloc() */
6488     adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
6489     voice_init(adev);
6490     list_init(&adev->usecase_list);
6491     pthread_mutex_unlock(&adev->lock);
6492 
6493     /* Loads platform specific libraries dynamically */
6494     adev->platform = platform_init(adev);
6495     if (!adev->platform) {
6496         free(adev->snd_dev_ref_cnt);
6497         free(adev);
6498         ALOGE("%s: Failed to init platform data, aborting.", __func__);
6499         *device = NULL;
6500         pthread_mutex_unlock(&adev_init_lock);
6501         return -EINVAL;
6502     }
6503     adev->extspk = audio_extn_extspk_init(adev);
6504 
6505     adev->visualizer_lib = dlopen(VISUALIZER_LIBRARY_PATH, RTLD_NOW);
6506     if (adev->visualizer_lib == NULL) {
6507         ALOGW("%s: DLOPEN failed for %s", __func__, VISUALIZER_LIBRARY_PATH);
6508     } else {
6509         ALOGV("%s: DLOPEN successful for %s", __func__, VISUALIZER_LIBRARY_PATH);
6510         adev->visualizer_start_output =
6511                     (int (*)(audio_io_handle_t, int, int, int))dlsym(adev->visualizer_lib,
6512                                                     "visualizer_hal_start_output");
6513         adev->visualizer_stop_output =
6514                     (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
6515                                                     "visualizer_hal_stop_output");
6516     }
6517 
6518     adev->offload_effects_lib = dlopen(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, RTLD_NOW);
6519     if (adev->offload_effects_lib == NULL) {
6520         ALOGW("%s: DLOPEN failed for %s", __func__,
6521               OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
6522     } else {
6523         ALOGV("%s: DLOPEN successful for %s", __func__,
6524               OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
6525         adev->offload_effects_start_output =
6526                     (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
6527                                      "offload_effects_bundle_hal_start_output");
6528         adev->offload_effects_stop_output =
6529                     (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
6530                                      "offload_effects_bundle_hal_stop_output");
6531     }
6532 
6533     adev->adm_lib = dlopen(ADM_LIBRARY_PATH, RTLD_NOW);
6534     if (adev->adm_lib == NULL) {
6535         ALOGW("%s: DLOPEN failed for %s", __func__, ADM_LIBRARY_PATH);
6536     } else {
6537         ALOGV("%s: DLOPEN successful for %s", __func__, ADM_LIBRARY_PATH);
6538         adev->adm_init = (adm_init_t)
6539                                 dlsym(adev->adm_lib, "adm_init");
6540         adev->adm_deinit = (adm_deinit_t)
6541                                 dlsym(adev->adm_lib, "adm_deinit");
6542         adev->adm_register_input_stream = (adm_register_input_stream_t)
6543                                 dlsym(adev->adm_lib, "adm_register_input_stream");
6544         adev->adm_register_output_stream = (adm_register_output_stream_t)
6545                                 dlsym(adev->adm_lib, "adm_register_output_stream");
6546         adev->adm_deregister_stream = (adm_deregister_stream_t)
6547                                 dlsym(adev->adm_lib, "adm_deregister_stream");
6548         adev->adm_request_focus = (adm_request_focus_t)
6549                                 dlsym(adev->adm_lib, "adm_request_focus");
6550         adev->adm_abandon_focus = (adm_abandon_focus_t)
6551                                 dlsym(adev->adm_lib, "adm_abandon_focus");
6552         adev->adm_set_config = (adm_set_config_t)
6553                                     dlsym(adev->adm_lib, "adm_set_config");
6554         adev->adm_request_focus_v2 = (adm_request_focus_v2_t)
6555                                     dlsym(adev->adm_lib, "adm_request_focus_v2");
6556         adev->adm_is_noirq_avail = (adm_is_noirq_avail_t)
6557                                     dlsym(adev->adm_lib, "adm_is_noirq_avail");
6558         adev->adm_on_routing_change = (adm_on_routing_change_t)
6559                                     dlsym(adev->adm_lib, "adm_on_routing_change");
6560     }
6561 
6562     adev->bt_wb_speech_enabled = false;
6563     adev->enable_voicerx = false;
6564 
6565     *device = &adev->device.common;
6566 
6567     if (k_enable_extended_precision)
6568         adev_verify_devices(adev);
6569 
6570     char value[PROPERTY_VALUE_MAX];
6571     int trial;
6572     if ((property_get("vendor.audio_hal.period_size", value, NULL) > 0) ||
6573         (property_get("audio_hal.period_size", value, NULL) > 0)) {
6574         trial = atoi(value);
6575         if (period_size_is_plausible_for_low_latency(trial)) {
6576             pcm_config_low_latency.period_size = trial;
6577             pcm_config_low_latency.start_threshold = trial / 4;
6578             pcm_config_low_latency.avail_min = trial / 4;
6579             configured_low_latency_capture_period_size = trial;
6580         }
6581     }
6582     if ((property_get("vendor.audio_hal.in_period_size", value, NULL) > 0) ||
6583         (property_get("audio_hal.in_period_size", value, NULL) > 0)) {
6584         trial = atoi(value);
6585         if (period_size_is_plausible_for_low_latency(trial)) {
6586             configured_low_latency_capture_period_size = trial;
6587         }
6588     }
6589 
6590     adev->mic_break_enabled = property_get_bool("vendor.audio.mic_break", false);
6591 
6592     adev->camera_orientation = CAMERA_DEFAULT;
6593 
6594     // commented as full set of app type cfg is sent from platform
6595     // audio_extn_utils_send_default_app_type_cfg(adev->platform, adev->mixer);
6596     audio_device_ref_count++;
6597 
6598     if ((property_get("vendor.audio_hal.period_multiplier", value, NULL) > 0) ||
6599         (property_get("audio_hal.period_multiplier", value, NULL) > 0)) {
6600         af_period_multiplier = atoi(value);
6601         if (af_period_multiplier < 0) {
6602             af_period_multiplier = 2;
6603         } else if (af_period_multiplier > 4) {
6604             af_period_multiplier = 4;
6605         }
6606         ALOGV("new period_multiplier = %d", af_period_multiplier);
6607     }
6608 
6609     audio_extn_tfa_98xx_init(adev);
6610     audio_extn_ma_init(adev->platform);
6611     audio_extn_audiozoom_init();
6612 
6613     pthread_mutex_unlock(&adev_init_lock);
6614 
6615     if (adev->adm_init)
6616         adev->adm_data = adev->adm_init();
6617 
6618     audio_extn_perf_lock_init();
6619     audio_extn_snd_mon_init();
6620     pthread_mutex_lock(&adev->lock);
6621     audio_extn_snd_mon_register_listener(NULL, adev_snd_mon_cb);
6622     adev->card_status = CARD_STATUS_ONLINE;
6623     pthread_mutex_unlock(&adev->lock);
6624     audio_extn_sound_trigger_init(adev);/* dependent on snd_mon_init() */
6625 
6626     ALOGD("%s: exit", __func__);
6627     return 0;
6628 }
6629 
6630 static struct hw_module_methods_t hal_module_methods = {
6631     .open = adev_open,
6632 };
6633 
6634 struct audio_module HAL_MODULE_INFO_SYM = {
6635     .common = {
6636         .tag = HARDWARE_MODULE_TAG,
6637         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
6638         .hal_api_version = HARDWARE_HAL_API_VERSION,
6639         .id = AUDIO_HARDWARE_MODULE_ID,
6640         .name = "QCOM Audio HAL",
6641         .author = "Code Aurora Forum",
6642         .methods = &hal_module_methods,
6643     },
6644 };
6645