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