1 /*
2  * Copyright (c) 2013-2015, The Linux Foundation. All rights reserved.
3  * Not a Contribution.
4  *
5  * Copyright (C) 2013 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 
20 #define LOG_TAG "audio_hw_primary"
21 /*#define LOG_NDEBUG 0*/
22 /*#define VERY_VERY_VERBOSE_LOGGING*/
23 #ifdef VERY_VERY_VERBOSE_LOGGING
24 #define ALOGVV ALOGV
25 #else
26 #define ALOGVV(a...) do { } while(0)
27 #endif
28 
29 #include <errno.h>
30 #include <pthread.h>
31 #include <stdint.h>
32 #include <sys/time.h>
33 #include <stdlib.h>
34 #include <math.h>
35 #include <dlfcn.h>
36 #include <sys/resource.h>
37 #include <sys/prctl.h>
38 
39 #include <cutils/log.h>
40 #include <cutils/str_parms.h>
41 #include <cutils/properties.h>
42 #include <cutils/atomic.h>
43 #include <cutils/sched_policy.h>
44 
45 #include <hardware/audio_effect.h>
46 #include <system/thread_defs.h>
47 #include <audio_effects/effect_aec.h>
48 #include <audio_effects/effect_ns.h>
49 #include "audio_hw.h"
50 #include "platform_api.h"
51 #include <platform.h>
52 #include "audio_extn.h"
53 #include "voice_extn.h"
54 
55 #include "sound/compress_params.h"
56 #include "sound/asound.h"
57 
58 #define COMPRESS_OFFLOAD_NUM_FRAGMENTS 4
59 /* ToDo: Check and update a proper value in msec */
60 #define COMPRESS_OFFLOAD_PLAYBACK_LATENCY 96
61 #define COMPRESS_PLAYBACK_VOLUME_MAX 0x2000
62 
63 #define PROXY_OPEN_RETRY_COUNT           100
64 #define PROXY_OPEN_WAIT_TIME             20
65 
66 #define USECASE_AUDIO_PLAYBACK_PRIMARY USECASE_AUDIO_PLAYBACK_DEEP_BUFFER
67 
68 static unsigned int configured_low_latency_capture_period_size =
69         LOW_LATENCY_CAPTURE_PERIOD_SIZE;
70 
71 struct pcm_config pcm_config_deep_buffer = {
72     .channels = 2,
73     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
74     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
75     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
76     .format = PCM_FORMAT_S16_LE,
77     .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
78     .stop_threshold = INT_MAX,
79     .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
80 };
81 
82 struct pcm_config pcm_config_low_latency = {
83     .channels = 2,
84     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
85     .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
86     .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
87     .format = PCM_FORMAT_S16_LE,
88     .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
89     .stop_threshold = INT_MAX,
90     .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
91 };
92 
93 struct pcm_config pcm_config_hdmi_multi = {
94     .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
95     .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
96     .period_size = HDMI_MULTI_PERIOD_SIZE,
97     .period_count = HDMI_MULTI_PERIOD_COUNT,
98     .format = PCM_FORMAT_S16_LE,
99     .start_threshold = 0,
100     .stop_threshold = INT_MAX,
101     .avail_min = 0,
102 };
103 
104 struct pcm_config pcm_config_audio_capture = {
105     .channels = 2,
106     .period_count = AUDIO_CAPTURE_PERIOD_COUNT,
107     .format = PCM_FORMAT_S16_LE,
108 };
109 
110 #define AFE_PROXY_CHANNEL_COUNT 2
111 #define AFE_PROXY_SAMPLING_RATE 48000
112 
113 #define AFE_PROXY_PLAYBACK_PERIOD_SIZE  768
114 #define AFE_PROXY_PLAYBACK_PERIOD_COUNT 4
115 
116 struct pcm_config pcm_config_afe_proxy_playback = {
117     .channels = AFE_PROXY_CHANNEL_COUNT,
118     .rate = AFE_PROXY_SAMPLING_RATE,
119     .period_size = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
120     .period_count = AFE_PROXY_PLAYBACK_PERIOD_COUNT,
121     .format = PCM_FORMAT_S16_LE,
122     .start_threshold = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
123     .stop_threshold = INT_MAX,
124     .avail_min = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
125 };
126 
127 #define AFE_PROXY_RECORD_PERIOD_SIZE  768
128 #define AFE_PROXY_RECORD_PERIOD_COUNT 4
129 
130 struct pcm_config pcm_config_afe_proxy_record = {
131     .channels = AFE_PROXY_CHANNEL_COUNT,
132     .rate = AFE_PROXY_SAMPLING_RATE,
133     .period_size = AFE_PROXY_RECORD_PERIOD_SIZE,
134     .period_count = AFE_PROXY_RECORD_PERIOD_COUNT,
135     .format = PCM_FORMAT_S16_LE,
136     .start_threshold = AFE_PROXY_RECORD_PERIOD_SIZE,
137     .stop_threshold = INT_MAX,
138     .avail_min = AFE_PROXY_RECORD_PERIOD_SIZE,
139 };
140 
141 const char * const use_case_table[AUDIO_USECASE_MAX] = {
142     [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = "deep-buffer-playback",
143     [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = "low-latency-playback",
144     [USECASE_AUDIO_PLAYBACK_MULTI_CH] = "multi-channel-playback",
145     [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
146 #ifdef MULTIPLE_OFFLOAD_ENABLED
147     [USECASE_AUDIO_PLAYBACK_OFFLOAD2] = "compress-offload-playback2",
148     [USECASE_AUDIO_PLAYBACK_OFFLOAD3] = "compress-offload-playback3",
149     [USECASE_AUDIO_PLAYBACK_OFFLOAD4] = "compress-offload-playback4",
150     [USECASE_AUDIO_PLAYBACK_OFFLOAD5] = "compress-offload-playback5",
151     [USECASE_AUDIO_PLAYBACK_OFFLOAD6] = "compress-offload-playback6",
152     [USECASE_AUDIO_PLAYBACK_OFFLOAD7] = "compress-offload-playback7",
153     [USECASE_AUDIO_PLAYBACK_OFFLOAD8] = "compress-offload-playback8",
154     [USECASE_AUDIO_PLAYBACK_OFFLOAD9] = "compress-offload-playback9",
155 #endif
156     [USECASE_AUDIO_RECORD] = "audio-record",
157     [USECASE_AUDIO_RECORD_COMPRESS] = "audio-record-compress",
158     [USECASE_AUDIO_RECORD_LOW_LATENCY] = "low-latency-record",
159     [USECASE_AUDIO_RECORD_FM_VIRTUAL] = "fm-virtual-record",
160     [USECASE_AUDIO_PLAYBACK_FM] = "play-fm",
161     [USECASE_AUDIO_HFP_SCO] = "hfp-sco",
162     [USECASE_AUDIO_HFP_SCO_WB] = "hfp-sco-wb",
163     [USECASE_VOICE_CALL] = "voice-call",
164 
165     [USECASE_VOICE2_CALL] = "voice2-call",
166     [USECASE_VOLTE_CALL] = "volte-call",
167     [USECASE_QCHAT_CALL] = "qchat-call",
168     [USECASE_VOWLAN_CALL] = "vowlan-call",
169     [USECASE_COMPRESS_VOIP_CALL] = "compress-voip-call",
170     [USECASE_INCALL_REC_UPLINK] = "incall-rec-uplink",
171     [USECASE_INCALL_REC_DOWNLINK] = "incall-rec-downlink",
172     [USECASE_INCALL_REC_UPLINK_AND_DOWNLINK] = "incall-rec-uplink-and-downlink",
173     [USECASE_INCALL_REC_UPLINK_COMPRESS] = "incall-rec-uplink-compress",
174     [USECASE_INCALL_REC_DOWNLINK_COMPRESS] = "incall-rec-downlink-compress",
175     [USECASE_INCALL_REC_UPLINK_AND_DOWNLINK_COMPRESS] = "incall-rec-uplink-and-downlink-compress",
176 
177     [USECASE_INCALL_MUSIC_UPLINK] = "incall_music_uplink",
178     [USECASE_INCALL_MUSIC_UPLINK2] = "incall_music_uplink2",
179     [USECASE_AUDIO_SPKR_CALIB_RX] = "spkr-rx-calib",
180     [USECASE_AUDIO_SPKR_CALIB_TX] = "spkr-vi-record",
181 
182     [USECASE_AUDIO_PLAYBACK_AFE_PROXY] = "afe-proxy-playback",
183     [USECASE_AUDIO_RECORD_AFE_PROXY] = "afe-proxy-record",
184 };
185 
186 static const audio_usecase_t offload_usecases[] = {
187     USECASE_AUDIO_PLAYBACK_OFFLOAD,
188 #ifdef MULTIPLE_OFFLOAD_ENABLED
189     USECASE_AUDIO_PLAYBACK_OFFLOAD2,
190     USECASE_AUDIO_PLAYBACK_OFFLOAD3,
191     USECASE_AUDIO_PLAYBACK_OFFLOAD4,
192     USECASE_AUDIO_PLAYBACK_OFFLOAD5,
193     USECASE_AUDIO_PLAYBACK_OFFLOAD6,
194     USECASE_AUDIO_PLAYBACK_OFFLOAD7,
195     USECASE_AUDIO_PLAYBACK_OFFLOAD8,
196     USECASE_AUDIO_PLAYBACK_OFFLOAD9,
197 #endif
198 };
199 
200 #define STRING_TO_ENUM(string) { #string, string }
201 
202 struct string_to_enum {
203     const char *name;
204     uint32_t value;
205 };
206 
207 static const struct string_to_enum out_channels_name_to_enum_table[] = {
208     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
209     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
210     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
211 };
212 
213 static const struct string_to_enum out_formats_name_to_enum_table[] = {
214     STRING_TO_ENUM(AUDIO_FORMAT_AC3),
215     STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
216     STRING_TO_ENUM(AUDIO_FORMAT_E_AC3_JOC),
217 };
218 
219 static struct audio_device *adev = NULL;
220 static pthread_mutex_t adev_init_lock;
221 static unsigned int audio_device_ref_count;
222 
223 static int set_voice_volume_l(struct audio_device *adev, float volume);
224 
check_and_set_gapless_mode(struct audio_device * adev)225 static int check_and_set_gapless_mode(struct audio_device *adev) {
226 
227 
228     char value[PROPERTY_VALUE_MAX] = {0};
229     bool gapless_enabled = false;
230     const char *mixer_ctl_name = "Compress Gapless Playback";
231     struct mixer_ctl *ctl;
232 
233     ALOGV("%s:", __func__);
234     property_get("audio.offload.gapless.enabled", value, NULL);
235     gapless_enabled = atoi(value) || !strncmp("true", value, 4);
236 
237     ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
238     if (!ctl) {
239         ALOGE("%s: Could not get ctl for mixer cmd - %s",
240                                __func__, mixer_ctl_name);
241         return -EINVAL;
242     }
243 
244     if (mixer_ctl_set_value(ctl, 0, gapless_enabled) < 0) {
245         ALOGE("%s: Could not set gapless mode %d",
246                        __func__, gapless_enabled);
247          return -EINVAL;
248     }
249     return 0;
250 }
251 
is_supported_format(audio_format_t format)252 static bool is_supported_format(audio_format_t format)
253 {
254     if (format == AUDIO_FORMAT_MP3 ||
255         format == AUDIO_FORMAT_AAC_LC ||
256         format == AUDIO_FORMAT_AAC_HE_V1 ||
257         format == AUDIO_FORMAT_AAC_HE_V2 ||
258         format == AUDIO_FORMAT_PCM_16_BIT_OFFLOAD ||
259         format == AUDIO_FORMAT_PCM_24_BIT_OFFLOAD ||
260         format == AUDIO_FORMAT_FLAC ||
261         format == AUDIO_FORMAT_ALAC ||
262         format == AUDIO_FORMAT_APE ||
263         format == AUDIO_FORMAT_VORBIS ||
264         format == AUDIO_FORMAT_WMA ||
265         format == AUDIO_FORMAT_WMA_PRO)
266            return true;
267 
268     return false;
269 }
270 
get_snd_codec_id(audio_format_t format)271 static int get_snd_codec_id(audio_format_t format)
272 {
273     int id = 0;
274 
275     switch (format & AUDIO_FORMAT_MAIN_MASK) {
276     case AUDIO_FORMAT_MP3:
277         id = SND_AUDIOCODEC_MP3;
278         break;
279     case AUDIO_FORMAT_AAC:
280         id = SND_AUDIOCODEC_AAC;
281         break;
282     case AUDIO_FORMAT_PCM_OFFLOAD:
283         id = SND_AUDIOCODEC_PCM;
284         break;
285     case AUDIO_FORMAT_FLAC:
286         id = SND_AUDIOCODEC_FLAC;
287         break;
288     case AUDIO_FORMAT_ALAC:
289         id = SND_AUDIOCODEC_ALAC;
290         break;
291     case AUDIO_FORMAT_APE:
292         id = SND_AUDIOCODEC_APE;
293         break;
294     case AUDIO_FORMAT_VORBIS:
295         id = SND_AUDIOCODEC_VORBIS;
296         break;
297     case AUDIO_FORMAT_WMA:
298         id = SND_AUDIOCODEC_WMA;
299         break;
300     case AUDIO_FORMAT_WMA_PRO:
301         id = SND_AUDIOCODEC_WMA_PRO;
302         break;
303     default:
304         ALOGE("%s: Unsupported audio format :%x", __func__, format);
305     }
306 
307     return id;
308 }
309 
get_snd_card_state(struct audio_device * adev)310 int get_snd_card_state(struct audio_device *adev)
311 {
312     int snd_scard_state;
313 
314     if (!adev)
315         return SND_CARD_STATE_OFFLINE;
316 
317     pthread_mutex_lock(&adev->snd_card_status.lock);
318     snd_scard_state = adev->snd_card_status.state;
319     pthread_mutex_unlock(&adev->snd_card_status.lock);
320 
321     return snd_scard_state;
322 }
323 
set_snd_card_state(struct audio_device * adev,int snd_scard_state)324 static int set_snd_card_state(struct audio_device *adev, int snd_scard_state)
325 {
326     if (!adev)
327         return -ENOSYS;
328 
329     pthread_mutex_lock(&adev->snd_card_status.lock);
330     adev->snd_card_status.state = snd_scard_state;
331     pthread_mutex_unlock(&adev->snd_card_status.lock);
332 
333     return 0;
334 }
335 
enable_audio_route_for_voice_usecases(struct audio_device * adev,struct audio_usecase * uc_info)336 static int enable_audio_route_for_voice_usecases(struct audio_device *adev,
337                                                  struct audio_usecase *uc_info)
338 {
339     struct listnode *node;
340     struct audio_usecase *usecase;
341 
342     if (uc_info == NULL)
343         return -EINVAL;
344 
345     /* Re-route all voice usecases on the shared backend other than the
346        specified usecase to new snd devices */
347     list_for_each(node, &adev->usecase_list) {
348         usecase = node_to_item(node, struct audio_usecase, list);
349         if ((usecase->type == VOICE_CALL || usecase->type == VOIP_CALL) &&
350              (usecase != uc_info))
351             enable_audio_route(adev, usecase);
352     }
353     return 0;
354 }
355 
pcm_ioctl(struct pcm * pcm,int request,...)356 int pcm_ioctl(struct pcm *pcm, int request, ...)
357 {
358     va_list ap;
359     void * arg;
360     int pcm_fd = *(int*)pcm;
361 
362     va_start(ap, request);
363     arg = va_arg(ap, void *);
364     va_end(ap);
365 
366     return ioctl(pcm_fd, request, arg);
367 }
368 
enable_audio_route(struct audio_device * adev,struct audio_usecase * usecase)369 int enable_audio_route(struct audio_device *adev,
370                        struct audio_usecase *usecase)
371 {
372     snd_device_t snd_device;
373     char mixer_path[MIXER_PATH_MAX_LENGTH];
374 
375     if (usecase == NULL)
376         return -EINVAL;
377 
378     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
379 
380     if (usecase->type == PCM_CAPTURE)
381         snd_device = usecase->in_snd_device;
382     else
383         snd_device = usecase->out_snd_device;
384 
385 #ifdef DS1_DOLBY_DAP_ENABLED
386     audio_extn_dolby_set_dmid(adev);
387     audio_extn_dolby_set_endpoint(adev);
388 #endif
389     audio_extn_dolby_ds2_set_endpoint(adev);
390     audio_extn_sound_trigger_update_stream_status(usecase, ST_EVENT_STREAM_BUSY);
391     audio_extn_listen_update_stream_status(usecase, LISTEN_EVENT_STREAM_BUSY);
392     audio_extn_utils_send_audio_calibration(adev, usecase);
393     audio_extn_utils_send_app_type_cfg(usecase);
394     strcpy(mixer_path, use_case_table[usecase->id]);
395     platform_add_backend_name(mixer_path, snd_device);
396     ALOGD("%s: apply mixer and update path: %s", __func__, mixer_path);
397     audio_route_apply_and_update_path(adev->audio_route, mixer_path);
398     ALOGV("%s: exit", __func__);
399     return 0;
400 }
401 
disable_audio_route(struct audio_device * adev,struct audio_usecase * usecase)402 int disable_audio_route(struct audio_device *adev,
403                         struct audio_usecase *usecase)
404 {
405     snd_device_t snd_device;
406     char mixer_path[MIXER_PATH_MAX_LENGTH];
407 
408     if (usecase == NULL || usecase->id == USECASE_INVALID)
409         return -EINVAL;
410 
411     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
412     if (usecase->type == PCM_CAPTURE)
413         snd_device = usecase->in_snd_device;
414     else
415         snd_device = usecase->out_snd_device;
416     strcpy(mixer_path, use_case_table[usecase->id]);
417     platform_add_backend_name(mixer_path, snd_device);
418     ALOGD("%s: reset and update mixer path: %s", __func__, mixer_path);
419     audio_route_reset_and_update_path(adev->audio_route, mixer_path);
420     audio_extn_sound_trigger_update_stream_status(usecase, ST_EVENT_STREAM_FREE);
421     audio_extn_listen_update_stream_status(usecase, LISTEN_EVENT_STREAM_FREE);
422     ALOGV("%s: exit", __func__);
423     return 0;
424 }
425 
enable_snd_device(struct audio_device * adev,snd_device_t snd_device)426 int enable_snd_device(struct audio_device *adev,
427                       snd_device_t snd_device)
428 {
429     char device_name[DEVICE_NAME_MAX_SIZE] = {0};
430 
431     if (snd_device < SND_DEVICE_MIN ||
432         snd_device >= SND_DEVICE_MAX) {
433         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
434         return -EINVAL;
435     }
436 
437     adev->snd_dev_ref_cnt[snd_device]++;
438 
439     if(platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0 ) {
440         ALOGE("%s: Invalid sound device returned", __func__);
441         return -EINVAL;
442     }
443     if (adev->snd_dev_ref_cnt[snd_device] > 1) {
444         ALOGV("%s: snd_device(%d: %s) is already active",
445               __func__, snd_device, device_name);
446         return 0;
447     }
448 
449     if (audio_extn_spkr_prot_is_enabled())
450          audio_extn_spkr_prot_calib_cancel(adev);
451     /* start usb playback thread */
452     if(SND_DEVICE_OUT_USB_HEADSET == snd_device ||
453        SND_DEVICE_OUT_SPEAKER_AND_USB_HEADSET == snd_device)
454         audio_extn_usb_start_playback(adev);
455 
456     /* start usb capture thread */
457     if(SND_DEVICE_IN_USB_HEADSET_MIC == snd_device)
458        audio_extn_usb_start_capture(adev);
459 
460     if (SND_DEVICE_OUT_BT_A2DP == snd_device ||
461        (SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP) == snd_device)
462         audio_extn_a2dp_start_playback();
463 
464     if ((snd_device == SND_DEVICE_OUT_SPEAKER ||
465         snd_device == SND_DEVICE_OUT_VOICE_SPEAKER) &&
466         audio_extn_spkr_prot_is_enabled()) {
467        if (audio_extn_spkr_prot_get_acdb_id(snd_device) < 0) {
468            adev->snd_dev_ref_cnt[snd_device]--;
469            return -EINVAL;
470        }
471         if (audio_extn_spkr_prot_start_processing(snd_device)) {
472             ALOGE("%s: spkr_start_processing failed", __func__);
473             return -EINVAL;
474         }
475     } else {
476         ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);
477         /* due to the possibility of calibration overwrite between listen
478             and audio, notify listen hal before audio calibration is sent */
479         audio_extn_sound_trigger_update_device_status(snd_device,
480                                         ST_EVENT_SND_DEVICE_BUSY);
481         audio_extn_listen_update_device_status(snd_device,
482                                         LISTEN_EVENT_SND_DEVICE_BUSY);
483         if (platform_get_snd_device_acdb_id(snd_device) < 0) {
484             adev->snd_dev_ref_cnt[snd_device]--;
485             audio_extn_sound_trigger_update_device_status(snd_device,
486                                             ST_EVENT_SND_DEVICE_FREE);
487             audio_extn_listen_update_device_status(snd_device,
488                                         LISTEN_EVENT_SND_DEVICE_FREE);
489             return -EINVAL;
490         }
491         audio_extn_dev_arbi_acquire(snd_device);
492         audio_route_apply_and_update_path(adev->audio_route, device_name);
493     }
494     return 0;
495 }
496 
disable_snd_device(struct audio_device * adev,snd_device_t snd_device)497 int disable_snd_device(struct audio_device *adev,
498                        snd_device_t snd_device)
499 {
500     char device_name[DEVICE_NAME_MAX_SIZE] = {0};
501 
502     if (snd_device < SND_DEVICE_MIN ||
503         snd_device >= SND_DEVICE_MAX) {
504         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
505         return -EINVAL;
506     }
507     if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
508         ALOGE("%s: device ref cnt is already 0", __func__);
509         return -EINVAL;
510     }
511 
512     adev->snd_dev_ref_cnt[snd_device]--;
513 
514     if(platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0) {
515         ALOGE("%s: Invalid sound device returned", __func__);
516         return -EINVAL;
517     }
518 
519     if (adev->snd_dev_ref_cnt[snd_device] == 0) {
520         ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);
521         /* exit usb play back thread */
522         if(SND_DEVICE_OUT_USB_HEADSET == snd_device ||
523            SND_DEVICE_OUT_SPEAKER_AND_USB_HEADSET == snd_device)
524             audio_extn_usb_stop_playback();
525 
526         /* exit usb capture thread */
527         if(SND_DEVICE_IN_USB_HEADSET_MIC == snd_device)
528             audio_extn_usb_stop_capture();
529 
530         if (SND_DEVICE_OUT_BT_A2DP == snd_device ||
531            (SND_DEVICE_OUT_SPEAKER_AND_BT_A2DP) == snd_device)
532             audio_extn_a2dp_stop_playback();
533 
534         if ((snd_device == SND_DEVICE_OUT_SPEAKER ||
535             snd_device == SND_DEVICE_OUT_VOICE_SPEAKER) &&
536             audio_extn_spkr_prot_is_enabled()) {
537             audio_extn_spkr_prot_stop_processing(snd_device);
538         } else {
539             audio_route_reset_and_update_path(adev->audio_route, device_name);
540             audio_extn_dev_arbi_release(snd_device);
541         }
542 
543         audio_extn_sound_trigger_update_device_status(snd_device,
544                                         ST_EVENT_SND_DEVICE_FREE);
545         audio_extn_listen_update_device_status(snd_device,
546                                         LISTEN_EVENT_SND_DEVICE_FREE);
547     }
548 
549     return 0;
550 }
551 
check_usecases_codec_backend(struct audio_device * adev,struct audio_usecase * uc_info,snd_device_t snd_device)552 static void check_usecases_codec_backend(struct audio_device *adev,
553                                           struct audio_usecase *uc_info,
554                                           snd_device_t snd_device)
555 {
556     struct listnode *node;
557     struct audio_usecase *usecase;
558     bool switch_device[AUDIO_USECASE_MAX];
559     int i, num_uc_to_switch = 0;
560 
561     /*
562      * This function is to make sure that all the usecases that are active on
563      * the hardware codec backend are always routed to any one device that is
564      * handled by the hardware codec.
565      * For example, if low-latency and deep-buffer usecases are currently active
566      * on speaker and out_set_parameters(headset) is received on low-latency
567      * output, then we have to make sure deep-buffer is also switched to headset,
568      * because of the limitation that both the devices cannot be enabled
569      * at the same time as they share the same backend.
570      */
571     /*
572      * This call is to check if we need to force routing for a particular stream
573      * If there is a backend configuration change for the device when a
574      * new stream starts, then ADM needs to be closed and re-opened with the new
575      * configuraion. This call check if we need to re-route all the streams
576      * associated with the backend. Touch tone + 24 bit playback.
577      */
578     bool force_routing = platform_check_and_set_codec_backend_cfg(adev, uc_info);
579 
580     /* Disable all the usecases on the shared backend other than the
581        specified usecase */
582     for (i = 0; i < AUDIO_USECASE_MAX; i++)
583         switch_device[i] = false;
584 
585     list_for_each(node, &adev->usecase_list) {
586         usecase = node_to_item(node, struct audio_usecase, list);
587         if (usecase->type != PCM_CAPTURE &&
588                 usecase != uc_info &&
589                 (usecase->out_snd_device != snd_device || force_routing)  &&
590                 usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
591             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
592                   __func__, use_case_table[usecase->id],
593                   platform_get_snd_device_name(usecase->out_snd_device));
594             disable_audio_route(adev, usecase);
595             switch_device[usecase->id] = true;
596             num_uc_to_switch++;
597         }
598     }
599 
600     if (num_uc_to_switch) {
601         /* All streams have been de-routed. Disable the device */
602 
603         /* Make sure the previous devices to be disabled first and then enable the
604            selected devices */
605         list_for_each(node, &adev->usecase_list) {
606             usecase = node_to_item(node, struct audio_usecase, list);
607             if (switch_device[usecase->id]) {
608                 disable_snd_device(adev, usecase->out_snd_device);
609             }
610         }
611 
612         list_for_each(node, &adev->usecase_list) {
613             usecase = node_to_item(node, struct audio_usecase, list);
614             if (switch_device[usecase->id]) {
615                 enable_snd_device(adev, snd_device);
616             }
617         }
618 
619         /* Re-route all the usecases on the shared backend other than the
620            specified usecase to new snd devices */
621         list_for_each(node, &adev->usecase_list) {
622             usecase = node_to_item(node, struct audio_usecase, list);
623             /* Update the out_snd_device only before enabling the audio route */
624             if (switch_device[usecase->id] ) {
625                 usecase->out_snd_device = snd_device;
626                 if (usecase->type != VOICE_CALL && usecase->type != VOIP_CALL)
627                     enable_audio_route(adev, usecase);
628             }
629         }
630     }
631 }
632 
check_and_route_capture_usecases(struct audio_device * adev,struct audio_usecase * uc_info,snd_device_t snd_device)633 static void check_and_route_capture_usecases(struct audio_device *adev,
634                                              struct audio_usecase *uc_info,
635                                              snd_device_t snd_device)
636 {
637     struct listnode *node;
638     struct audio_usecase *usecase;
639     bool switch_device[AUDIO_USECASE_MAX];
640     int i, num_uc_to_switch = 0;
641 
642     /*
643      * This function is to make sure that all the active capture usecases
644      * are always routed to the same input sound device.
645      * For example, if audio-record and voice-call usecases are currently
646      * active on speaker(rx) and speaker-mic (tx) and out_set_parameters(earpiece)
647      * is received for voice call then we have to make sure that audio-record
648      * usecase is also switched to earpiece i.e. voice-dmic-ef,
649      * because of the limitation that two devices cannot be enabled
650      * at the same time if they share the same backend.
651      */
652     for (i = 0; i < AUDIO_USECASE_MAX; i++)
653         switch_device[i] = false;
654 
655     list_for_each(node, &adev->usecase_list) {
656         usecase = node_to_item(node, struct audio_usecase, list);
657         if (usecase->type != PCM_PLAYBACK &&
658                 usecase != uc_info &&
659                 usecase->in_snd_device != snd_device) {
660             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
661                   __func__, use_case_table[usecase->id],
662                   platform_get_snd_device_name(usecase->in_snd_device));
663             disable_audio_route(adev, usecase);
664             switch_device[usecase->id] = true;
665             num_uc_to_switch++;
666         }
667     }
668 
669     if (num_uc_to_switch) {
670         /* All streams have been de-routed. Disable the device */
671 
672         /* Make sure the previous devices to be disabled first and then enable the
673            selected devices */
674         list_for_each(node, &adev->usecase_list) {
675             usecase = node_to_item(node, struct audio_usecase, list);
676             if (switch_device[usecase->id]) {
677                 disable_snd_device(adev, usecase->in_snd_device);
678             }
679         }
680 
681         list_for_each(node, &adev->usecase_list) {
682             usecase = node_to_item(node, struct audio_usecase, list);
683             if (switch_device[usecase->id]) {
684                 enable_snd_device(adev, snd_device);
685             }
686         }
687 
688         /* Re-route all the usecases on the shared backend other than the
689            specified usecase to new snd devices */
690         list_for_each(node, &adev->usecase_list) {
691             usecase = node_to_item(node, struct audio_usecase, list);
692             /* Update the in_snd_device only before enabling the audio route */
693             if (switch_device[usecase->id] ) {
694                 usecase->in_snd_device = snd_device;
695                 if (usecase->type != VOICE_CALL && usecase->type != VOIP_CALL)
696                     enable_audio_route(adev, usecase);
697             }
698         }
699     }
700 }
701 
702 /* must be called with hw device mutex locked */
read_hdmi_channel_masks(struct stream_out * out)703 static int read_hdmi_channel_masks(struct stream_out *out)
704 {
705     int ret = 0;
706     int channels = platform_edid_get_max_channels(out->dev->platform);
707 
708     switch (channels) {
709         /*
710          * Do not handle stereo output in Multi-channel cases
711          * Stereo case is handled in normal playback path
712          */
713     case 6:
714         ALOGV("%s: HDMI supports 5.1", __func__);
715         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
716         break;
717     case 8:
718         ALOGV("%s: HDMI supports 5.1 and 7.1 channels", __func__);
719         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
720         out->supported_channel_masks[1] = AUDIO_CHANNEL_OUT_7POINT1;
721         break;
722     default:
723         ALOGE("HDMI does not support multi channel playback");
724         ret = -ENOSYS;
725         break;
726     }
727     return ret;
728 }
729 
get_usecase_id_from_usecase_type(struct audio_device * adev,usecase_type_t type)730 audio_usecase_t get_usecase_id_from_usecase_type(struct audio_device *adev,
731                                                  usecase_type_t type)
732 {
733     struct audio_usecase *usecase;
734     struct listnode *node;
735 
736     list_for_each(node, &adev->usecase_list) {
737         usecase = node_to_item(node, struct audio_usecase, list);
738         if (usecase->type == type) {
739             ALOGV("%s: usecase id %d", __func__, usecase->id);
740             return usecase->id;
741         }
742     }
743     return USECASE_INVALID;
744 }
745 
get_usecase_from_list(struct audio_device * adev,audio_usecase_t uc_id)746 struct audio_usecase *get_usecase_from_list(struct audio_device *adev,
747                                             audio_usecase_t uc_id)
748 {
749     struct audio_usecase *usecase;
750     struct listnode *node;
751 
752     list_for_each(node, &adev->usecase_list) {
753         usecase = node_to_item(node, struct audio_usecase, list);
754         if (usecase->id == uc_id)
755             return usecase;
756     }
757     return NULL;
758 }
759 
select_devices(struct audio_device * adev,audio_usecase_t uc_id)760 int select_devices(struct audio_device *adev, audio_usecase_t uc_id)
761 {
762     snd_device_t out_snd_device = SND_DEVICE_NONE;
763     snd_device_t in_snd_device = SND_DEVICE_NONE;
764     struct audio_usecase *usecase = NULL;
765     struct audio_usecase *vc_usecase = NULL;
766     struct audio_usecase *voip_usecase = NULL;
767     struct audio_usecase *hfp_usecase = NULL;
768     audio_usecase_t hfp_ucid;
769     struct listnode *node;
770     int status = 0;
771 
772     usecase = get_usecase_from_list(adev, uc_id);
773     if (usecase == NULL) {
774         ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
775         return -EINVAL;
776     }
777 
778     if ((usecase->type == VOICE_CALL) ||
779         (usecase->type == VOIP_CALL)  ||
780         (usecase->type == PCM_HFP_CALL)) {
781         out_snd_device = platform_get_output_snd_device(adev->platform,
782                                                         usecase->stream.out->devices);
783         in_snd_device = platform_get_input_snd_device(adev->platform, usecase->stream.out->devices);
784         usecase->devices = usecase->stream.out->devices;
785     } else {
786         /*
787          * If the voice call is active, use the sound devices of voice call usecase
788          * so that it would not result any device switch. All the usecases will
789          * be switched to new device when select_devices() is called for voice call
790          * usecase. This is to avoid switching devices for voice call when
791          * check_usecases_codec_backend() is called below.
792          */
793         if (voice_is_in_call(adev) && adev->mode == AUDIO_MODE_IN_CALL) {
794             vc_usecase = get_usecase_from_list(adev,
795                                                get_usecase_id_from_usecase_type(adev, VOICE_CALL));
796             if ((vc_usecase) && ((vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
797                 (usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL))) {
798                 in_snd_device = vc_usecase->in_snd_device;
799                 out_snd_device = vc_usecase->out_snd_device;
800             }
801         } else if (voice_extn_compress_voip_is_active(adev)) {
802             voip_usecase = get_usecase_from_list(adev, USECASE_COMPRESS_VOIP_CALL);
803             if ((voip_usecase) && ((voip_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) &&
804                 (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) &&
805                  (voip_usecase->stream.out != adev->primary_output))) {
806                     in_snd_device = voip_usecase->in_snd_device;
807                     out_snd_device = voip_usecase->out_snd_device;
808             }
809         } else if (audio_extn_hfp_is_active(adev)) {
810             hfp_ucid = audio_extn_hfp_get_usecase();
811             hfp_usecase = get_usecase_from_list(adev, hfp_ucid);
812             if ((hfp_usecase) && (hfp_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND)) {
813                    in_snd_device = hfp_usecase->in_snd_device;
814                    out_snd_device = hfp_usecase->out_snd_device;
815             }
816         }
817         if (usecase->type == PCM_PLAYBACK) {
818             usecase->devices = usecase->stream.out->devices;
819             in_snd_device = SND_DEVICE_NONE;
820             if (out_snd_device == SND_DEVICE_NONE) {
821                 out_snd_device = platform_get_output_snd_device(adev->platform,
822                                             usecase->stream.out->devices);
823                 if (usecase->stream.out == adev->primary_output &&
824                         adev->active_input &&
825                         out_snd_device != usecase->out_snd_device) {
826                     select_devices(adev, adev->active_input->usecase);
827                 }
828             }
829         } else if (usecase->type == PCM_CAPTURE) {
830             usecase->devices = usecase->stream.in->device;
831             out_snd_device = SND_DEVICE_NONE;
832             if (in_snd_device == SND_DEVICE_NONE) {
833                 audio_devices_t out_device = AUDIO_DEVICE_NONE;
834                 if ((adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
835                     (adev->mode == AUDIO_MODE_IN_COMMUNICATION &&
836                      adev->active_input->source == AUDIO_SOURCE_MIC)) &&
837                      adev->primary_output && !adev->primary_output->standby) {
838                     out_device = adev->primary_output->devices;
839                     platform_set_echo_reference(adev->platform, false);
840                 } else if (usecase->id == USECASE_AUDIO_RECORD_AFE_PROXY) {
841                     out_device = AUDIO_DEVICE_OUT_TELEPHONY_TX;
842                 }
843                 in_snd_device = platform_get_input_snd_device(adev->platform, out_device);
844             }
845         }
846     }
847 
848     if (out_snd_device == usecase->out_snd_device &&
849         in_snd_device == usecase->in_snd_device) {
850         return 0;
851     }
852 
853     ALOGD("%s: out_snd_device(%d: %s) in_snd_device(%d: %s)", __func__,
854           out_snd_device, platform_get_snd_device_name(out_snd_device),
855           in_snd_device,  platform_get_snd_device_name(in_snd_device));
856 
857     /*
858      * Limitation: While in call, to do a device switch we need to disable
859      * and enable both RX and TX devices though one of them is same as current
860      * device.
861      */
862     if ((usecase->type == VOICE_CALL) &&
863         (usecase->in_snd_device != SND_DEVICE_NONE) &&
864         (usecase->out_snd_device != SND_DEVICE_NONE)) {
865         status = platform_switch_voice_call_device_pre(adev->platform);
866     }
867 
868     /* Disable current sound devices */
869     if (usecase->out_snd_device != SND_DEVICE_NONE) {
870         disable_audio_route(adev, usecase);
871         disable_snd_device(adev, usecase->out_snd_device);
872     }
873 
874     if (usecase->in_snd_device != SND_DEVICE_NONE) {
875         disable_audio_route(adev, usecase);
876         disable_snd_device(adev, usecase->in_snd_device);
877     }
878 
879     /* Applicable only on the targets that has external modem.
880      * New device information should be sent to modem before enabling
881      * the devices to reduce in-call device switch time.
882      */
883     if ((usecase->type == VOICE_CALL) &&
884         (usecase->in_snd_device != SND_DEVICE_NONE) &&
885         (usecase->out_snd_device != SND_DEVICE_NONE)) {
886         status = platform_switch_voice_call_enable_device_config(adev->platform,
887                                                                  out_snd_device,
888                                                                  in_snd_device);
889     }
890 
891     /* Enable new sound devices */
892     if (out_snd_device != SND_DEVICE_NONE) {
893         if (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND)
894             check_usecases_codec_backend(adev, usecase, out_snd_device);
895         enable_snd_device(adev, out_snd_device);
896     }
897 
898     if (in_snd_device != SND_DEVICE_NONE) {
899         check_and_route_capture_usecases(adev, usecase, in_snd_device);
900         enable_snd_device(adev, in_snd_device);
901     }
902 
903     if (usecase->type == VOICE_CALL || usecase->type == VOIP_CALL) {
904         status = platform_switch_voice_call_device_post(adev->platform,
905                                                         out_snd_device,
906                                                         in_snd_device);
907         enable_audio_route_for_voice_usecases(adev, usecase);
908     }
909 
910     usecase->in_snd_device = in_snd_device;
911     usecase->out_snd_device = out_snd_device;
912 
913     if (usecase->type == PCM_PLAYBACK) {
914         audio_extn_utils_update_stream_app_type_cfg(adev->platform,
915                                                 &adev->streams_output_cfg_list,
916                                                 usecase->stream.out->devices,
917                                                 usecase->stream.out->flags,
918                                                 usecase->stream.out->format,
919                                                 usecase->stream.out->sample_rate,
920                                                 usecase->stream.out->bit_width,
921                                                 &usecase->stream.out->app_type_cfg);
922         ALOGI("%s Selected apptype: %d", __func__, usecase->stream.out->app_type_cfg.app_type);
923     }
924 
925     enable_audio_route(adev, usecase);
926 
927     /* Applicable only on the targets that has external modem.
928      * Enable device command should be sent to modem only after
929      * enabling voice call mixer controls
930      */
931     if (usecase->type == VOICE_CALL)
932         status = platform_switch_voice_call_usecase_route_post(adev->platform,
933                                                                out_snd_device,
934                                                                in_snd_device);
935     ALOGD("%s: done",__func__);
936 
937     return status;
938 }
939 
stop_input_stream(struct stream_in * in)940 static int stop_input_stream(struct stream_in *in)
941 {
942     int i, ret = 0;
943     struct audio_usecase *uc_info;
944     struct audio_device *adev = in->dev;
945 
946     adev->active_input = NULL;
947 
948     ALOGV("%s: enter: usecase(%d: %s)", __func__,
949           in->usecase, use_case_table[in->usecase]);
950     uc_info = get_usecase_from_list(adev, in->usecase);
951     if (uc_info == NULL) {
952         ALOGE("%s: Could not find the usecase (%d) in the list",
953               __func__, in->usecase);
954         return -EINVAL;
955     }
956 
957     /* Close in-call recording streams */
958     voice_check_and_stop_incall_rec_usecase(adev, in);
959 
960     /* 1. Disable stream specific mixer controls */
961     disable_audio_route(adev, uc_info);
962 
963     /* 2. Disable the tx device */
964     disable_snd_device(adev, uc_info->in_snd_device);
965 
966     list_remove(&uc_info->list);
967     free(uc_info);
968 
969     ALOGV("%s: exit: status(%d)", __func__, ret);
970     return ret;
971 }
972 
start_input_stream(struct stream_in * in)973 int start_input_stream(struct stream_in *in)
974 {
975     /* 1. Enable output device and stream routing controls */
976     int ret = 0;
977     struct audio_usecase *uc_info;
978     struct audio_device *adev = in->dev;
979     int snd_card_status = get_snd_card_state(adev);
980 
981     int usecase = platform_update_usecase_from_source(in->source,in->usecase);
982     if (get_usecase_from_list(adev, usecase) == NULL)
983         in->usecase = usecase;
984 
985     ALOGD("%s: enter: stream(%p)usecase(%d: %s)",
986           __func__, &in->stream, in->usecase, use_case_table[in->usecase]);
987 
988 
989     if (SND_CARD_STATE_OFFLINE == snd_card_status) {
990         ALOGE("%s: sound card is not active/SSR returning error", __func__);
991         ret = -EIO;
992         goto error_config;
993     }
994 
995     /* Check if source matches incall recording usecase criteria */
996     ret = voice_check_and_set_incall_rec_usecase(adev, in);
997     if (ret)
998         goto error_config;
999     else
1000         ALOGV("%s: usecase(%d)", __func__, in->usecase);
1001 
1002     if (get_usecase_from_list(adev, in->usecase) != NULL) {
1003         ALOGE("%s: use case assigned already in use, stream(%p)usecase(%d: %s)",
1004             __func__, &in->stream, in->usecase, use_case_table[in->usecase]);
1005         goto error_config;
1006     }
1007 
1008     in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
1009     if (in->pcm_device_id < 0) {
1010         ALOGE("%s: Could not find PCM device id for the usecase(%d)",
1011               __func__, in->usecase);
1012         ret = -EINVAL;
1013         goto error_config;
1014     }
1015 
1016     adev->active_input = in;
1017     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
1018 
1019     if (!uc_info) {
1020         ret = -ENOMEM;
1021         goto error_config;
1022     }
1023 
1024     uc_info->id = in->usecase;
1025     uc_info->type = PCM_CAPTURE;
1026     uc_info->stream.in = in;
1027     uc_info->devices = in->device;
1028     uc_info->in_snd_device = SND_DEVICE_NONE;
1029     uc_info->out_snd_device = SND_DEVICE_NONE;
1030 
1031     list_add_tail(&adev->usecase_list, &uc_info->list);
1032     audio_extn_perf_lock_acquire();
1033     select_devices(adev, in->usecase);
1034 
1035     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
1036           __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
1037 
1038     unsigned int flags = PCM_IN;
1039     unsigned int pcm_open_retry_count = 0;
1040 
1041     if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY) {
1042         flags |= PCM_MMAP | PCM_NOIRQ;
1043         pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
1044     }
1045 
1046     while (1) {
1047         in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
1048                            flags, &in->config);
1049         if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
1050             ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
1051             if (in->pcm != NULL) {
1052                 pcm_close(in->pcm);
1053                 in->pcm = NULL;
1054             }
1055             if (pcm_open_retry_count-- == 0) {
1056                 ret = -EIO;
1057                 goto error_open;
1058             }
1059             usleep(PROXY_OPEN_WAIT_TIME * 1000);
1060             continue;
1061         }
1062         break;
1063     }
1064 
1065     ALOGV("%s: pcm_prepare", __func__);
1066     ret = pcm_prepare(in->pcm);
1067     if (ret < 0) {
1068         ALOGE("%s: pcm_prepare returned %d", __func__, ret);
1069         pcm_close(in->pcm);
1070         in->pcm = NULL;
1071         goto error_open;
1072     }
1073 
1074     audio_extn_perf_lock_release();
1075 
1076     ALOGD("%s: exit", __func__);
1077 
1078     return ret;
1079 
1080 error_open:
1081     stop_input_stream(in);
1082     audio_extn_perf_lock_release();
1083 
1084 error_config:
1085     adev->active_input = NULL;
1086     ALOGD("%s: exit: status(%d)", __func__, ret);
1087 
1088     return ret;
1089 }
1090 
1091 /* must be called with out->lock locked */
send_offload_cmd_l(struct stream_out * out,int command)1092 static int send_offload_cmd_l(struct stream_out* out, int command)
1093 {
1094     struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));
1095 
1096     if (!cmd) {
1097         ALOGE("failed to allocate mem for command 0x%x", command);
1098         return -ENOMEM;
1099     }
1100 
1101     ALOGVV("%s %d", __func__, command);
1102 
1103     cmd->cmd = command;
1104     list_add_tail(&out->offload_cmd_list, &cmd->node);
1105     pthread_cond_signal(&out->offload_cond);
1106     return 0;
1107 }
1108 
1109 /* must be called iwth out->lock locked */
stop_compressed_output_l(struct stream_out * out)1110 static void stop_compressed_output_l(struct stream_out *out)
1111 {
1112     out->offload_state = OFFLOAD_STATE_IDLE;
1113     out->playback_started = 0;
1114     out->send_new_metadata = 1;
1115     if (out->compr != NULL) {
1116         compress_stop(out->compr);
1117         while (out->offload_thread_blocked) {
1118             pthread_cond_wait(&out->cond, &out->lock);
1119         }
1120     }
1121 }
1122 
is_offload_usecase(audio_usecase_t uc_id)1123 bool is_offload_usecase(audio_usecase_t uc_id)
1124 {
1125     unsigned int i;
1126     for (i = 0; i < sizeof(offload_usecases)/sizeof(offload_usecases[0]); i++) {
1127         if (uc_id == offload_usecases[i])
1128             return true;
1129     }
1130     return false;
1131 }
1132 
get_offload_usecase(struct audio_device * adev)1133 static audio_usecase_t get_offload_usecase(struct audio_device *adev)
1134 {
1135     audio_usecase_t ret = USECASE_AUDIO_PLAYBACK_OFFLOAD;
1136     unsigned int i, num_usecase = sizeof(offload_usecases)/sizeof(offload_usecases[0]);
1137     char value[PROPERTY_VALUE_MAX] = {0};
1138 
1139     property_get("audio.offload.multiple.enabled", value, NULL);
1140     if (!(atoi(value) || !strncmp("true", value, 4)))
1141         num_usecase = 1; /* If prop is not set, limit the num of offload usecases to 1 */
1142 
1143     ALOGV("%s: num_usecase: %d", __func__, num_usecase);
1144     for (i = 0; i < num_usecase; i++) {
1145         if (!(adev->offload_usecases_state & (0x1<<i))) {
1146             adev->offload_usecases_state |= 0x1 << i;
1147             ret = offload_usecases[i];
1148             break;
1149         }
1150     }
1151     ALOGV("%s: offload usecase is %d", __func__, ret);
1152     return ret;
1153 }
1154 
free_offload_usecase(struct audio_device * adev,audio_usecase_t uc_id)1155 static void free_offload_usecase(struct audio_device *adev,
1156                                  audio_usecase_t uc_id)
1157 {
1158     unsigned int i;
1159     for (i = 0; i < sizeof(offload_usecases)/sizeof(offload_usecases[0]); i++) {
1160         if (offload_usecases[i] == uc_id) {
1161             adev->offload_usecases_state &= ~(0x1<<i);
1162             break;
1163         }
1164     }
1165     ALOGV("%s: free offload usecase %d", __func__, uc_id);
1166 }
1167 
offload_thread_loop(void * context)1168 static void *offload_thread_loop(void *context)
1169 {
1170     struct stream_out *out = (struct stream_out *) context;
1171     struct listnode *item;
1172     int ret = 0;
1173 
1174     setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
1175     set_sched_policy(0, SP_FOREGROUND);
1176     prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);
1177 
1178     ALOGV("%s", __func__);
1179     pthread_mutex_lock(&out->lock);
1180     for (;;) {
1181         struct offload_cmd *cmd = NULL;
1182         stream_callback_event_t event;
1183         bool send_callback = false;
1184 
1185         ALOGVV("%s offload_cmd_list %d out->offload_state %d",
1186               __func__, list_empty(&out->offload_cmd_list),
1187               out->offload_state);
1188         if (list_empty(&out->offload_cmd_list)) {
1189             ALOGV("%s SLEEPING", __func__);
1190             pthread_cond_wait(&out->offload_cond, &out->lock);
1191             ALOGV("%s RUNNING", __func__);
1192             continue;
1193         }
1194 
1195         item = list_head(&out->offload_cmd_list);
1196         cmd = node_to_item(item, struct offload_cmd, node);
1197         list_remove(item);
1198 
1199         ALOGVV("%s STATE %d CMD %d out->compr %p",
1200                __func__, out->offload_state, cmd->cmd, out->compr);
1201 
1202         if (cmd->cmd == OFFLOAD_CMD_EXIT) {
1203             free(cmd);
1204             break;
1205         }
1206 
1207         if (out->compr == NULL) {
1208             ALOGE("%s: Compress handle is NULL", __func__);
1209             pthread_cond_signal(&out->cond);
1210             continue;
1211         }
1212         out->offload_thread_blocked = true;
1213         pthread_mutex_unlock(&out->lock);
1214         send_callback = false;
1215         switch(cmd->cmd) {
1216         case OFFLOAD_CMD_WAIT_FOR_BUFFER:
1217             ALOGD("copl(%p):calling compress_wait", out);
1218             compress_wait(out->compr, -1);
1219             ALOGD("copl(%p):out of compress_wait", out);
1220             send_callback = true;
1221             event = STREAM_CBK_EVENT_WRITE_READY;
1222             break;
1223         case OFFLOAD_CMD_PARTIAL_DRAIN:
1224             ret = compress_next_track(out->compr);
1225             if(ret == 0) {
1226                 ALOGD("copl(%p):calling compress_partial_drain", out);
1227                 ret = compress_partial_drain(out->compr);
1228                 ALOGD("copl(%p):out of compress_partial_drain", out);
1229                 if (ret < 0)
1230                     ret = -errno;
1231             }
1232             else if (ret == -ETIMEDOUT)
1233                 compress_drain(out->compr);
1234             else
1235                 ALOGE("%s: Next track returned error %d",__func__, ret);
1236 
1237             if (ret != -ENETRESET) {
1238                 send_callback = true;
1239                 event = STREAM_CBK_EVENT_DRAIN_READY;
1240                 ALOGV("copl(%p):send drain callback, ret %d", out, ret);
1241             } else
1242                 ALOGE("%s: Block drain ready event during SSR", __func__);
1243             break;
1244         case OFFLOAD_CMD_DRAIN:
1245             ALOGD("copl(%p):calling compress_drain", out);
1246             compress_drain(out->compr);
1247             ALOGD("copl(%p):calling compress_drain", out);
1248             send_callback = true;
1249             event = STREAM_CBK_EVENT_DRAIN_READY;
1250             break;
1251         default:
1252             ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
1253             break;
1254         }
1255         pthread_mutex_lock(&out->lock);
1256         out->offload_thread_blocked = false;
1257         pthread_cond_signal(&out->cond);
1258         if (send_callback) {
1259             out->offload_callback(event, NULL, out->offload_cookie);
1260         }
1261         free(cmd);
1262     }
1263 
1264     pthread_cond_signal(&out->cond);
1265     while (!list_empty(&out->offload_cmd_list)) {
1266         item = list_head(&out->offload_cmd_list);
1267         list_remove(item);
1268         free(node_to_item(item, struct offload_cmd, node));
1269     }
1270     pthread_mutex_unlock(&out->lock);
1271 
1272     return NULL;
1273 }
1274 
create_offload_callback_thread(struct stream_out * out)1275 static int create_offload_callback_thread(struct stream_out *out)
1276 {
1277     pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
1278     list_init(&out->offload_cmd_list);
1279     pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
1280                     offload_thread_loop, out);
1281     return 0;
1282 }
1283 
destroy_offload_callback_thread(struct stream_out * out)1284 static int destroy_offload_callback_thread(struct stream_out *out)
1285 {
1286     pthread_mutex_lock(&out->lock);
1287     stop_compressed_output_l(out);
1288     send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);
1289 
1290     pthread_mutex_unlock(&out->lock);
1291     pthread_join(out->offload_thread, (void **) NULL);
1292     pthread_cond_destroy(&out->offload_cond);
1293 
1294     return 0;
1295 }
1296 
allow_hdmi_channel_config(struct audio_device * adev)1297 static bool allow_hdmi_channel_config(struct audio_device *adev)
1298 {
1299     struct listnode *node;
1300     struct audio_usecase *usecase;
1301     bool ret = true;
1302 
1303     list_for_each(node, &adev->usecase_list) {
1304         usecase = node_to_item(node, struct audio_usecase, list);
1305         if (usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
1306             /*
1307              * If voice call is already existing, do not proceed further to avoid
1308              * disabling/enabling both RX and TX devices, CSD calls, etc.
1309              * Once the voice call done, the HDMI channels can be configured to
1310              * max channels of remaining use cases.
1311              */
1312             if (usecase->id == USECASE_VOICE_CALL) {
1313                 ALOGD("%s: voice call is active, no change in HDMI channels",
1314                       __func__);
1315                 ret = false;
1316                 break;
1317             } else if (usecase->id == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
1318                 ALOGD("%s: multi channel playback is active, "
1319                       "no change in HDMI channels", __func__);
1320                 ret = false;
1321                 break;
1322             } else if (is_offload_usecase(usecase->id) &&
1323                        audio_channel_count_from_out_mask(usecase->stream.out->channel_mask) > 2) {
1324                 ALOGD("%s: multi-channel(%x) compress offload playback is active, "
1325                       "no change in HDMI channels", __func__, usecase->stream.out->channel_mask);
1326                 ret = false;
1327                 break;
1328             }
1329         }
1330     }
1331     return ret;
1332 }
1333 
check_and_set_hdmi_channels(struct audio_device * adev,unsigned int channels)1334 static int check_and_set_hdmi_channels(struct audio_device *adev,
1335                                        unsigned int channels)
1336 {
1337     struct listnode *node;
1338     struct audio_usecase *usecase;
1339 
1340     /* Check if change in HDMI channel config is allowed */
1341     if (!allow_hdmi_channel_config(adev))
1342         return 0;
1343 
1344     if (channels == adev->cur_hdmi_channels) {
1345         ALOGD("%s: Requested channels are same as current channels(%d)", __func__, channels);
1346         return 0;
1347     }
1348 
1349     platform_set_hdmi_channels(adev->platform, channels);
1350     adev->cur_hdmi_channels = channels;
1351 
1352     /*
1353      * Deroute all the playback streams routed to HDMI so that
1354      * the back end is deactivated. Note that backend will not
1355      * be deactivated if any one stream is connected to it.
1356      */
1357     list_for_each(node, &adev->usecase_list) {
1358         usecase = node_to_item(node, struct audio_usecase, list);
1359         if (usecase->type == PCM_PLAYBACK &&
1360                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
1361             disable_audio_route(adev, usecase);
1362         }
1363     }
1364 
1365     /*
1366      * Enable all the streams disabled above. Now the HDMI backend
1367      * will be activated with new channel configuration
1368      */
1369     list_for_each(node, &adev->usecase_list) {
1370         usecase = node_to_item(node, struct audio_usecase, list);
1371         if (usecase->type == PCM_PLAYBACK &&
1372                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
1373             enable_audio_route(adev, usecase);
1374         }
1375     }
1376 
1377     return 0;
1378 }
1379 
stop_output_stream(struct stream_out * out)1380 static int stop_output_stream(struct stream_out *out)
1381 {
1382     int i, ret = 0;
1383     struct audio_usecase *uc_info;
1384     struct audio_device *adev = out->dev;
1385 
1386     ALOGV("%s: enter: usecase(%d: %s)", __func__,
1387           out->usecase, use_case_table[out->usecase]);
1388     uc_info = get_usecase_from_list(adev, out->usecase);
1389     if (uc_info == NULL) {
1390         ALOGE("%s: Could not find the usecase (%d) in the list",
1391               __func__, out->usecase);
1392         return -EINVAL;
1393     }
1394 
1395     if (is_offload_usecase(out->usecase)) {
1396         if (adev->visualizer_stop_output != NULL)
1397             adev->visualizer_stop_output(out->handle, out->pcm_device_id);
1398         if (adev->offload_effects_stop_output != NULL)
1399             adev->offload_effects_stop_output(out->handle, out->pcm_device_id);
1400     }
1401 
1402     /* 1. Get and set stream specific mixer controls */
1403     disable_audio_route(adev, uc_info);
1404 
1405     /* 2. Disable the rx device */
1406     disable_snd_device(adev, uc_info->out_snd_device);
1407 
1408     list_remove(&uc_info->list);
1409     free(uc_info);
1410 
1411     /* Must be called after removing the usecase from list */
1412     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
1413         check_and_set_hdmi_channels(adev, DEFAULT_HDMI_OUT_CHANNELS);
1414 
1415     ALOGV("%s: exit: status(%d)", __func__, ret);
1416     return ret;
1417 }
1418 
start_output_stream(struct stream_out * out)1419 int start_output_stream(struct stream_out *out)
1420 {
1421     int ret = 0;
1422     int sink_channels = 0;
1423     char prop_value[PROPERTY_VALUE_MAX] = {0};
1424     struct audio_usecase *uc_info;
1425     struct audio_device *adev = out->dev;
1426     int snd_card_status = get_snd_card_state(adev);
1427 
1428     if ((out->usecase < 0) || (out->usecase >= AUDIO_USECASE_MAX)) {
1429         ret = -EINVAL;
1430         goto error_config;
1431     }
1432 
1433     ALOGD("%s: enter: stream(%p)usecase(%d: %s) devices(%#x)",
1434           __func__, &out->stream, out->usecase, use_case_table[out->usecase],
1435           out->devices);
1436 
1437     if (SND_CARD_STATE_OFFLINE == snd_card_status) {
1438         ALOGE("%s: sound card is not active/SSR returning error", __func__);
1439         ret = -EIO;
1440         goto error_config;
1441     }
1442 
1443     out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
1444     if (out->pcm_device_id < 0) {
1445         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
1446               __func__, out->pcm_device_id, out->usecase);
1447         ret = -EINVAL;
1448         goto error_config;
1449     }
1450 
1451     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
1452 
1453     if (!uc_info) {
1454         ret = -ENOMEM;
1455         goto error_config;
1456     }
1457 
1458     uc_info->id = out->usecase;
1459     uc_info->type = PCM_PLAYBACK;
1460     uc_info->stream.out = out;
1461     uc_info->devices = out->devices;
1462     uc_info->in_snd_device = SND_DEVICE_NONE;
1463     uc_info->out_snd_device = SND_DEVICE_NONE;
1464 
1465     /* This must be called before adding this usecase to the list */
1466     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
1467         property_get("audio.use.hdmi.sink.cap", prop_value, NULL);
1468         if (!strncmp("true", prop_value, 4)) {
1469             sink_channels = platform_edid_get_max_channels(out->dev->platform);
1470             ALOGD("%s: set HDMI channel count[%d] based on sink capability", __func__, sink_channels);
1471             check_and_set_hdmi_channels(adev, sink_channels);
1472         } else {
1473             if (is_offload_usecase(out->usecase))
1474                 check_and_set_hdmi_channels(adev, out->compr_config.codec->ch_in);
1475             else
1476                 check_and_set_hdmi_channels(adev, out->config.channels);
1477         }
1478     }
1479 
1480     list_add_tail(&adev->usecase_list, &uc_info->list);
1481 
1482     select_devices(adev, out->usecase);
1483 
1484     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d) format(%#x)",
1485           __func__, adev->snd_card, out->pcm_device_id, out->config.format);
1486     if (!is_offload_usecase(out->usecase)) {
1487         unsigned int flags = PCM_OUT;
1488         unsigned int pcm_open_retry_count = 0;
1489         if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY) {
1490             flags |= PCM_MMAP | PCM_NOIRQ;
1491             pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
1492         } else
1493             flags |= PCM_MONOTONIC;
1494 
1495         while (1) {
1496             out->pcm = pcm_open(adev->snd_card, out->pcm_device_id,
1497                                flags, &out->config);
1498             if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
1499                 ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
1500                 if (out->pcm != NULL) {
1501                     pcm_close(out->pcm);
1502                     out->pcm = NULL;
1503                 }
1504                 if (pcm_open_retry_count-- == 0) {
1505                     ret = -EIO;
1506                     goto error_open;
1507                 }
1508                 usleep(PROXY_OPEN_WAIT_TIME * 1000);
1509                 continue;
1510             }
1511             break;
1512         }
1513 
1514         ALOGV("%s: pcm_prepare", __func__);
1515         if (pcm_is_ready(out->pcm)) {
1516             ret = pcm_prepare(out->pcm);
1517             if (ret < 0) {
1518                 ALOGE("%s: pcm_prepare returned %d", __func__, ret);
1519                 pcm_close(out->pcm);
1520                 out->pcm = NULL;
1521                 goto error_open;
1522             }
1523         }
1524     } else {
1525         out->pcm = NULL;
1526         out->compr = compress_open(adev->snd_card,
1527                                    out->pcm_device_id,
1528                                    COMPRESS_IN, &out->compr_config);
1529         if (out->compr && !is_compress_ready(out->compr)) {
1530             ALOGE("%s: %s", __func__, compress_get_error(out->compr));
1531             compress_close(out->compr);
1532             out->compr = NULL;
1533             ret = -EIO;
1534             goto error_open;
1535         }
1536         if (out->offload_callback)
1537             compress_nonblock(out->compr, out->non_blocking);
1538 
1539 #ifdef DS1_DOLBY_DDP_ENABLED
1540         if (audio_extn_is_dolby_format(out->format))
1541             audio_extn_dolby_send_ddp_endp_params(adev);
1542 #endif
1543 
1544         if (adev->visualizer_start_output != NULL)
1545             adev->visualizer_start_output(out->handle, out->pcm_device_id);
1546         if (adev->offload_effects_start_output != NULL)
1547             adev->offload_effects_start_output(out->handle, out->pcm_device_id);
1548     }
1549 
1550     ALOGD("%s: exit", __func__);
1551 
1552     return 0;
1553 error_open:
1554     stop_output_stream(out);
1555 error_config:
1556     return ret;
1557 }
1558 
check_input_parameters(uint32_t sample_rate,audio_format_t format,int channel_count)1559 static int check_input_parameters(uint32_t sample_rate,
1560                                   audio_format_t format,
1561                                   int channel_count)
1562 {
1563     int ret = 0;
1564 
1565     if ((format != AUDIO_FORMAT_PCM_16_BIT) &&
1566         !voice_extn_compress_voip_is_format_supported(format) &&
1567             !audio_extn_compr_cap_format_supported(format))  ret = -EINVAL;
1568 
1569     switch (channel_count) {
1570     case 1:
1571     case 2:
1572     case 6:
1573         break;
1574     default:
1575         ret = -EINVAL;
1576     }
1577 
1578     switch (sample_rate) {
1579     case 8000:
1580     case 11025:
1581     case 12000:
1582     case 16000:
1583     case 22050:
1584     case 24000:
1585     case 32000:
1586     case 44100:
1587     case 48000:
1588         break;
1589     default:
1590         ret = -EINVAL;
1591     }
1592 
1593     return ret;
1594 }
1595 
get_input_buffer_size(uint32_t sample_rate,audio_format_t format,int channel_count,bool is_low_latency)1596 static size_t get_input_buffer_size(uint32_t sample_rate,
1597                                     audio_format_t format,
1598                                     int channel_count,
1599                                     bool is_low_latency)
1600 {
1601     size_t size = 0;
1602 
1603     if (check_input_parameters(sample_rate, format, channel_count) != 0)
1604         return 0;
1605 
1606     size = (sample_rate * AUDIO_CAPTURE_PERIOD_DURATION_MSEC) / 1000;
1607     if (is_low_latency)
1608         size = configured_low_latency_capture_period_size;
1609     /* ToDo: should use frame_size computed based on the format and
1610        channel_count here. */
1611     size *= sizeof(short) * channel_count;
1612 
1613     /* make sure the size is multiple of 32 bytes
1614      * At 48 kHz mono 16-bit PCM:
1615      *  5.000 ms = 240 frames = 15*16*1*2 = 480, a whole multiple of 32 (15)
1616      *  3.333 ms = 160 frames = 10*16*1*2 = 320, a whole multiple of 32 (10)
1617      */
1618     size += 0x1f;
1619     size &= ~0x1f;
1620 
1621     return size;
1622 }
1623 
out_get_sample_rate(const struct audio_stream * stream)1624 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1625 {
1626     struct stream_out *out = (struct stream_out *)stream;
1627 
1628     return out->sample_rate;
1629 }
1630 
out_set_sample_rate(struct audio_stream * stream __unused,uint32_t rate __unused)1631 static int out_set_sample_rate(struct audio_stream *stream __unused,
1632                                uint32_t rate __unused)
1633 {
1634     return -ENOSYS;
1635 }
1636 
out_get_buffer_size(const struct audio_stream * stream)1637 static size_t out_get_buffer_size(const struct audio_stream *stream)
1638 {
1639     struct stream_out *out = (struct stream_out *)stream;
1640 
1641     if (is_offload_usecase(out->usecase))
1642         return out->compr_config.fragment_size;
1643     else if(out->usecase == USECASE_COMPRESS_VOIP_CALL)
1644         return voice_extn_compress_voip_out_get_buffer_size(out);
1645 
1646     return out->config.period_size *
1647                 audio_stream_out_frame_size((const struct audio_stream_out *)stream);
1648 }
1649 
out_get_channels(const struct audio_stream * stream)1650 static uint32_t out_get_channels(const struct audio_stream *stream)
1651 {
1652     struct stream_out *out = (struct stream_out *)stream;
1653 
1654     return out->channel_mask;
1655 }
1656 
out_get_format(const struct audio_stream * stream)1657 static audio_format_t out_get_format(const struct audio_stream *stream)
1658 {
1659     struct stream_out *out = (struct stream_out *)stream;
1660 
1661     return out->format;
1662 }
1663 
out_set_format(struct audio_stream * stream __unused,audio_format_t format __unused)1664 static int out_set_format(struct audio_stream *stream __unused,
1665                           audio_format_t format __unused)
1666 {
1667     return -ENOSYS;
1668 }
1669 
out_standby(struct audio_stream * stream)1670 static int out_standby(struct audio_stream *stream)
1671 {
1672     struct stream_out *out = (struct stream_out *)stream;
1673     struct audio_device *adev = out->dev;
1674 
1675     ALOGD("%s: enter: stream (%p) usecase(%d: %s)", __func__,
1676           stream, out->usecase, use_case_table[out->usecase]);
1677     if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
1678         /* Ignore standby in case of voip call because the voip output
1679          * stream is closed in adev_close_output_stream()
1680          */
1681         ALOGD("%s: Ignore Standby in VOIP call", __func__);
1682         return 0;
1683     }
1684 
1685     pthread_mutex_lock(&out->lock);
1686     if (!out->standby) {
1687         pthread_mutex_lock(&adev->lock);
1688         out->standby = true;
1689         if (!is_offload_usecase(out->usecase)) {
1690             if (out->pcm) {
1691                 pcm_close(out->pcm);
1692                 out->pcm = NULL;
1693             }
1694         } else {
1695             ALOGD("copl(%p):standby", out);
1696             stop_compressed_output_l(out);
1697             out->gapless_mdata.encoder_delay = 0;
1698             out->gapless_mdata.encoder_padding = 0;
1699             if (out->compr != NULL) {
1700                 compress_close(out->compr);
1701                 out->compr = NULL;
1702             }
1703         }
1704         stop_output_stream(out);
1705         pthread_mutex_unlock(&adev->lock);
1706     }
1707     pthread_mutex_unlock(&out->lock);
1708     ALOGV("%s: exit", __func__);
1709     return 0;
1710 }
1711 
out_dump(const struct audio_stream * stream __unused,int fd __unused)1712 static int out_dump(const struct audio_stream *stream __unused,
1713                     int fd __unused)
1714 {
1715     return 0;
1716 }
1717 
parse_compress_metadata(struct stream_out * out,struct str_parms * parms)1718 static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
1719 {
1720     int ret = 0;
1721     char value[32];
1722     bool is_meta_data_params = false;
1723 
1724     if (!out || !parms) {
1725         ALOGE("%s: return invalid ",__func__);
1726         return -EINVAL;
1727     }
1728 
1729     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_FORMAT, value, sizeof(value));
1730     if (ret >= 0) {
1731         if (atoi(value) == SND_AUDIOSTREAMFORMAT_MP4ADTS) {
1732             out->compr_config.codec->format = SND_AUDIOSTREAMFORMAT_MP4ADTS;
1733             ALOGV("ADTS format is set in offload mode");
1734         }
1735         out->send_new_metadata = 1;
1736     }
1737 
1738     ret = audio_extn_parse_compress_metadata(out, parms);
1739 
1740     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_SAMPLE_RATE, value, sizeof(value));
1741     if(ret >= 0)
1742         is_meta_data_params = true;
1743     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_NUM_CHANNEL, value, sizeof(value));
1744     if(ret >= 0)
1745         is_meta_data_params = true;
1746     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_AVG_BIT_RATE, value, sizeof(value));
1747     if(ret >= 0)
1748         is_meta_data_params = true;
1749     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
1750     if (ret >= 0) {
1751         is_meta_data_params = true;
1752         out->gapless_mdata.encoder_delay = atoi(value); //whats a good limit check?
1753     }
1754     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
1755     if (ret >= 0) {
1756         is_meta_data_params = true;
1757         out->gapless_mdata.encoder_padding = atoi(value);
1758     }
1759 
1760     if(!is_meta_data_params) {
1761         ALOGV("%s: Not gapless meta data params", __func__);
1762         return 0;
1763     }
1764     out->send_new_metadata = 1;
1765     ALOGV("%s new encoder delay %u and padding %u", __func__,
1766           out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);
1767 
1768     return 0;
1769 }
1770 
output_drives_call(struct audio_device * adev,struct stream_out * out)1771 static bool output_drives_call(struct audio_device *adev, struct stream_out *out)
1772 {
1773     return out == adev->primary_output || out == adev->voice_tx_output;
1774 }
1775 
out_set_parameters(struct audio_stream * stream,const char * kvpairs)1776 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1777 {
1778     struct stream_out *out = (struct stream_out *)stream;
1779     struct audio_device *adev = out->dev;
1780     struct audio_usecase *usecase;
1781     struct listnode *node;
1782     struct str_parms *parms;
1783     char value[32];
1784     int ret = 0, val = 0, err;
1785     bool select_new_device = false;
1786 
1787     ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s",
1788           __func__, out->usecase, use_case_table[out->usecase], kvpairs);
1789     parms = str_parms_create_str(kvpairs);
1790     if (!parms)
1791         goto error;
1792     err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
1793     if (err >= 0) {
1794         val = atoi(value);
1795         pthread_mutex_lock(&out->lock);
1796         pthread_mutex_lock(&adev->lock);
1797 
1798         /*
1799          * When HDMI cable is unplugged/usb hs is disconnected the
1800          * music playback is paused and the policy manager sends routing=0
1801          * But the audioflingercontinues to write data until standby time
1802          * (3sec). As the HDMI core is turned off, the write gets blocked.
1803          * Avoid this by routing audio to speaker until standby.
1804          */
1805         if ((out->devices == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
1806                 out->devices == AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET) &&
1807                 val == AUDIO_DEVICE_NONE) {
1808             val = AUDIO_DEVICE_OUT_SPEAKER;
1809         }
1810 
1811         /*
1812          * select_devices() call below switches all the usecases on the same
1813          * backend to the new device. Refer to check_usecases_codec_backend() in
1814          * the select_devices(). But how do we undo this?
1815          *
1816          * For example, music playback is active on headset (deep-buffer usecase)
1817          * and if we go to ringtones and select a ringtone, low-latency usecase
1818          * will be started on headset+speaker. As we can't enable headset+speaker
1819          * and headset devices at the same time, select_devices() switches the music
1820          * playback to headset+speaker while starting low-lateny usecase for ringtone.
1821          * So when the ringtone playback is completed, how do we undo the same?
1822          *
1823          * We are relying on the out_set_parameters() call on deep-buffer output,
1824          * once the ringtone playback is ended.
1825          * NOTE: We should not check if the current devices are same as new devices.
1826          *       Because select_devices() must be called to switch back the music
1827          *       playback to headset.
1828          */
1829         if (val != 0) {
1830             out->devices = val;
1831 
1832             if (!out->standby)
1833                 select_devices(adev, out->usecase);
1834 
1835             if ((adev->mode == AUDIO_MODE_IN_CALL) &&
1836                     output_drives_call(adev, out)) {
1837                 adev->current_call_output = out;
1838                 if (!voice_is_in_call(adev))
1839                     ret = voice_start_call(adev);
1840                 else
1841                     voice_update_devices_for_all_voice_usecases(adev);
1842             }
1843         }
1844 
1845         pthread_mutex_unlock(&adev->lock);
1846         pthread_mutex_unlock(&out->lock);
1847     }
1848 
1849     if (out == adev->primary_output) {
1850         pthread_mutex_lock(&adev->lock);
1851         audio_extn_set_parameters(adev, parms);
1852         pthread_mutex_unlock(&adev->lock);
1853     }
1854     if (is_offload_usecase(out->usecase)) {
1855         pthread_mutex_lock(&out->lock);
1856         parse_compress_metadata(out, parms);
1857         pthread_mutex_unlock(&out->lock);
1858     }
1859 
1860     str_parms_destroy(parms);
1861 error:
1862     ALOGV("%s: exit: code(%d)", __func__, ret);
1863     return ret;
1864 }
1865 
out_get_parameters(const struct audio_stream * stream,const char * keys)1866 static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
1867 {
1868     struct stream_out *out = (struct stream_out *)stream;
1869     struct str_parms *query = str_parms_create_str(keys);
1870     char *str;
1871     char value[256];
1872     struct str_parms *reply = str_parms_create();
1873     size_t i, j;
1874     int ret;
1875     bool first = true;
1876 
1877     if (!query || !reply) {
1878         ALOGE("out_get_parameters: failed to allocate mem for query or reply");
1879         return NULL;
1880     }
1881 
1882     ALOGV("%s: enter: keys - %s", __func__, keys);
1883     ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value, sizeof(value));
1884     if (ret >= 0) {
1885         value[0] = '\0';
1886         i = 0;
1887         while (out->supported_channel_masks[i] != 0) {
1888             for (j = 0; j < ARRAY_SIZE(out_channels_name_to_enum_table); j++) {
1889                 if (out_channels_name_to_enum_table[j].value == out->supported_channel_masks[i]) {
1890                     if (!first) {
1891                         strcat(value, "|");
1892                     }
1893                     strcat(value, out_channels_name_to_enum_table[j].name);
1894                     first = false;
1895                     break;
1896                 }
1897             }
1898             i++;
1899         }
1900         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
1901         str = str_parms_to_str(reply);
1902     } else {
1903         voice_extn_out_get_parameters(out, query, reply);
1904         str = str_parms_to_str(reply);
1905         if (!strncmp(str, "", sizeof(""))) {
1906             free(str);
1907             str = strdup(keys);
1908         }
1909     }
1910     str_parms_destroy(query);
1911     str_parms_destroy(reply);
1912     ALOGV("%s: exit: returns - %s", __func__, str);
1913     return str;
1914 }
1915 
out_get_latency(const struct audio_stream_out * stream)1916 static uint32_t out_get_latency(const struct audio_stream_out *stream)
1917 {
1918     struct stream_out *out = (struct stream_out *)stream;
1919 
1920     if (is_offload_usecase(out->usecase))
1921         return COMPRESS_OFFLOAD_PLAYBACK_LATENCY;
1922 
1923     return (out->config.period_count * out->config.period_size * 1000) /
1924            (out->config.rate);
1925 }
1926 
out_set_volume(struct audio_stream_out * stream,float left,float right)1927 static int out_set_volume(struct audio_stream_out *stream, float left,
1928                           float right)
1929 {
1930     struct stream_out *out = (struct stream_out *)stream;
1931     int volume[2];
1932 
1933     if (out->usecase == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
1934         /* only take left channel into account: the API is for stereo anyway */
1935         out->muted = (left == 0.0f);
1936         return 0;
1937     } else if (is_offload_usecase(out->usecase)) {
1938         char mixer_ctl_name[128];
1939         struct audio_device *adev = out->dev;
1940         struct mixer_ctl *ctl;
1941         int pcm_device_id = platform_get_pcm_device_id(out->usecase,
1942                                                        PCM_PLAYBACK);
1943 
1944         snprintf(mixer_ctl_name, sizeof(mixer_ctl_name),
1945                  "Compress Playback %d Volume", pcm_device_id);
1946         ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
1947         if (!ctl) {
1948             ALOGE("%s: Could not get ctl for mixer cmd - %s",
1949                   __func__, mixer_ctl_name);
1950             return -EINVAL;
1951         }
1952         volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
1953         volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
1954         mixer_ctl_set_array(ctl, volume, sizeof(volume)/sizeof(volume[0]));
1955         return 0;
1956     }
1957 
1958     return -ENOSYS;
1959 }
1960 
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)1961 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
1962                          size_t bytes)
1963 {
1964     struct stream_out *out = (struct stream_out *)stream;
1965     struct audio_device *adev = out->dev;
1966     int snd_scard_state = get_snd_card_state(adev);
1967     ssize_t ret = 0;
1968 
1969     pthread_mutex_lock(&out->lock);
1970 
1971     if (SND_CARD_STATE_OFFLINE == snd_scard_state) {
1972         // increase written size during SSR to avoid mismatch
1973         // with the written frames count in AF
1974         if (!is_offload_usecase(out->usecase))
1975             out->written += bytes / (out->config.channels * sizeof(short));
1976 
1977         if (out->pcm) {
1978             ALOGD(" %s: sound card is not active/SSR state", __func__);
1979             ret= -EIO;
1980             goto exit;
1981         } else if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1982             //during SSR for compress usecase we should return error to flinger
1983             ALOGD(" copl %s: sound card is not active/SSR state", __func__);
1984             pthread_mutex_unlock(&out->lock);
1985             return -ENETRESET;
1986         }
1987     }
1988 
1989     if (out->standby) {
1990         out->standby = false;
1991         pthread_mutex_lock(&adev->lock);
1992         if (out->usecase == USECASE_COMPRESS_VOIP_CALL)
1993             ret = voice_extn_compress_voip_start_output_stream(out);
1994         else
1995             ret = start_output_stream(out);
1996         pthread_mutex_unlock(&adev->lock);
1997         /* ToDo: If use case is compress offload should return 0 */
1998         if (ret != 0) {
1999             out->standby = true;
2000             goto exit;
2001         }
2002     }
2003 
2004     if (is_offload_usecase(out->usecase)) {
2005         ALOGD("copl(%p): writing buffer (%zu bytes) to compress device", out, bytes);
2006         if (out->send_new_metadata) {
2007             ALOGD("copl(%p):send new gapless metadata", out);
2008             compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
2009             out->send_new_metadata = 0;
2010         }
2011 
2012         ret = compress_write(out->compr, buffer, bytes);
2013         if (ret < 0)
2014             ret = -errno;
2015         ALOGVV("%s: writing buffer (%d bytes) to compress device returned %d", __func__, bytes, ret);
2016         if (ret >= 0 && ret < (ssize_t)bytes) {
2017             ALOGD("No space available in compress driver, post msg to cb thread");
2018             send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
2019         } else if (-ENETRESET == ret) {
2020             ALOGE("copl %s: received sound card offline state on compress write", __func__);
2021             set_snd_card_state(adev,SND_CARD_STATE_OFFLINE);
2022             pthread_mutex_unlock(&out->lock);
2023             out_standby(&out->stream.common);
2024             return ret;
2025         }
2026         if (!out->playback_started && ret >= 0) {
2027             compress_start(out->compr);
2028             out->playback_started = 1;
2029             out->offload_state = OFFLOAD_STATE_PLAYING;
2030         }
2031         pthread_mutex_unlock(&out->lock);
2032         return ret;
2033     } else {
2034         if (out->pcm) {
2035             if (out->muted)
2036                 memset((void *)buffer, 0, bytes);
2037             ALOGVV("%s: writing buffer (%d bytes) to pcm device", __func__, bytes);
2038             if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY)
2039                 ret = pcm_mmap_write(out->pcm, (void *)buffer, bytes);
2040             else
2041                 ret = pcm_write(out->pcm, (void *)buffer, bytes);
2042             if (ret < 0)
2043                 ret = -errno;
2044             else if (ret == 0)
2045                 out->written += bytes / (out->config.channels * sizeof(short));
2046         }
2047     }
2048 
2049 exit:
2050     /* ToDo: There may be a corner case when SSR happens back to back during
2051        start/stop. Need to post different error to handle that. */
2052     if (-ENETRESET == ret) {
2053         set_snd_card_state(adev,SND_CARD_STATE_OFFLINE);
2054     }
2055 
2056     pthread_mutex_unlock(&out->lock);
2057 
2058     if (ret != 0) {
2059         if (out->pcm)
2060             ALOGE("%s: error %ld - %s", __func__, ret, pcm_get_error(out->pcm));
2061         if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
2062             pthread_mutex_lock(&adev->lock);
2063             voice_extn_compress_voip_close_output_stream(&out->stream.common);
2064             pthread_mutex_unlock(&adev->lock);
2065             out->standby = true;
2066         }
2067         out_standby(&out->stream.common);
2068         usleep(bytes * 1000000 / audio_stream_out_frame_size(stream) /
2069                         out_get_sample_rate(&out->stream.common));
2070 
2071     }
2072     return bytes;
2073 }
2074 
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)2075 static int out_get_render_position(const struct audio_stream_out *stream,
2076                                    uint32_t *dsp_frames)
2077 {
2078     struct stream_out *out = (struct stream_out *)stream;
2079     struct audio_device *adev = out->dev;
2080 
2081     if (dsp_frames == NULL)
2082         return -EINVAL;
2083 
2084     *dsp_frames = 0;
2085     if (is_offload_usecase(out->usecase)) {
2086         ssize_t ret = 0;
2087         pthread_mutex_lock(&out->lock);
2088         if (out->compr != NULL) {
2089             ret = compress_get_tstamp(out->compr, (unsigned long *)dsp_frames,
2090                     &out->sample_rate);
2091             if (ret < 0)
2092                 ret = -errno;
2093             ALOGVV("%s rendered frames %d sample_rate %d",
2094                    __func__, *dsp_frames, out->sample_rate);
2095         }
2096         pthread_mutex_unlock(&out->lock);
2097         if (-ENETRESET == ret) {
2098             ALOGE(" ERROR: sound card not active Unable to get time stamp from compress driver");
2099             set_snd_card_state(adev,SND_CARD_STATE_OFFLINE);
2100             return -EINVAL;
2101         } else if(ret < 0) {
2102             ALOGE(" ERROR: Unable to get time stamp from compress driver");
2103             return -EINVAL;
2104         } else if (get_snd_card_state(adev) == SND_CARD_STATE_OFFLINE){
2105             /*
2106              * Handle corner case where compress session is closed during SSR
2107              * and timestamp is queried
2108              */
2109             ALOGE(" ERROR: sound card not active, return error");
2110             return -EINVAL;
2111         } else {
2112             return 0;
2113         }
2114     } else if (audio_is_linear_pcm(out->format)) {
2115         *dsp_frames = out->written;
2116         return 0;
2117     } else
2118         return -EINVAL;
2119 }
2120 
out_add_audio_effect(const struct audio_stream * stream __unused,effect_handle_t effect __unused)2121 static int out_add_audio_effect(const struct audio_stream *stream __unused,
2122                                 effect_handle_t effect __unused)
2123 {
2124     return 0;
2125 }
2126 
out_remove_audio_effect(const struct audio_stream * stream __unused,effect_handle_t effect __unused)2127 static int out_remove_audio_effect(const struct audio_stream *stream __unused,
2128                                    effect_handle_t effect __unused)
2129 {
2130     return 0;
2131 }
2132 
out_get_next_write_timestamp(const struct audio_stream_out * stream __unused,int64_t * timestamp __unused)2133 static int out_get_next_write_timestamp(const struct audio_stream_out *stream __unused,
2134                                         int64_t *timestamp __unused)
2135 {
2136     return -EINVAL;
2137 }
2138 
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)2139 static int out_get_presentation_position(const struct audio_stream_out *stream,
2140                                    uint64_t *frames, struct timespec *timestamp)
2141 {
2142     struct stream_out *out = (struct stream_out *)stream;
2143     int ret = -1;
2144     unsigned long dsp_frames;
2145 
2146     pthread_mutex_lock(&out->lock);
2147 
2148     if (is_offload_usecase(out->usecase)) {
2149         if (out->compr != NULL) {
2150             ret = compress_get_tstamp(out->compr, &dsp_frames,
2151                     &out->sample_rate);
2152             ALOGVV("%s rendered frames %ld sample_rate %d",
2153                    __func__, dsp_frames, out->sample_rate);
2154             *frames = dsp_frames;
2155             if (ret < 0)
2156                 ret = -errno;
2157             if (-ENETRESET == ret) {
2158                 ALOGE(" ERROR: sound card not active Unable to get time stamp from compress driver");
2159                 set_snd_card_state(adev,SND_CARD_STATE_OFFLINE);
2160                 ret = -EINVAL;
2161             } else
2162                 ret = 0;
2163 
2164             /* this is the best we can do */
2165             clock_gettime(CLOCK_MONOTONIC, timestamp);
2166         }
2167     } else {
2168         if (out->pcm) {
2169             unsigned int avail;
2170             if (pcm_get_htimestamp(out->pcm, &avail, timestamp) == 0) {
2171                 size_t kernel_buffer_size = out->config.period_size * out->config.period_count;
2172                 int64_t signed_frames = out->written - kernel_buffer_size + avail;
2173                 // This adjustment accounts for buffering after app processor.
2174                 // It is based on estimated DSP latency per use case, rather than exact.
2175                 signed_frames -=
2176                     (platform_render_latency(out->usecase) * out->sample_rate / 1000000LL);
2177 
2178                 // It would be unusual for this value to be negative, but check just in case ...
2179                 if (signed_frames >= 0) {
2180                     *frames = signed_frames;
2181                     ret = 0;
2182                 }
2183             }
2184         }
2185     }
2186 
2187     pthread_mutex_unlock(&out->lock);
2188 
2189     return ret;
2190 }
2191 
out_set_callback(struct audio_stream_out * stream,stream_callback_t callback,void * cookie)2192 static int out_set_callback(struct audio_stream_out *stream,
2193             stream_callback_t callback, void *cookie)
2194 {
2195     struct stream_out *out = (struct stream_out *)stream;
2196 
2197     ALOGV("%s", __func__);
2198     pthread_mutex_lock(&out->lock);
2199     out->offload_callback = callback;
2200     out->offload_cookie = cookie;
2201     pthread_mutex_unlock(&out->lock);
2202     return 0;
2203 }
2204 
out_pause(struct audio_stream_out * stream)2205 static int out_pause(struct audio_stream_out* stream)
2206 {
2207     struct stream_out *out = (struct stream_out *)stream;
2208     int status = -ENOSYS;
2209     ALOGV("%s", __func__);
2210     if (is_offload_usecase(out->usecase)) {
2211         ALOGD("copl(%p):pause compress driver", out);
2212         pthread_mutex_lock(&out->lock);
2213         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
2214             struct audio_device *adev = out->dev;
2215             int snd_scard_state = get_snd_card_state(adev);
2216 
2217             if (SND_CARD_STATE_ONLINE == snd_scard_state)
2218                 status = compress_pause(out->compr);
2219 
2220             out->offload_state = OFFLOAD_STATE_PAUSED;
2221         }
2222         pthread_mutex_unlock(&out->lock);
2223     }
2224     return status;
2225 }
2226 
out_resume(struct audio_stream_out * stream)2227 static int out_resume(struct audio_stream_out* stream)
2228 {
2229     struct stream_out *out = (struct stream_out *)stream;
2230     int status = -ENOSYS;
2231     ALOGV("%s", __func__);
2232     if (is_offload_usecase(out->usecase)) {
2233         ALOGD("copl(%p):resume compress driver", out);
2234         status = 0;
2235         pthread_mutex_lock(&out->lock);
2236         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
2237             struct audio_device *adev = out->dev;
2238             int snd_scard_state = get_snd_card_state(adev);
2239 
2240             if (SND_CARD_STATE_ONLINE == snd_scard_state)
2241                 status = compress_resume(out->compr);
2242 
2243             out->offload_state = OFFLOAD_STATE_PLAYING;
2244         }
2245         pthread_mutex_unlock(&out->lock);
2246     }
2247     return status;
2248 }
2249 
out_drain(struct audio_stream_out * stream,audio_drain_type_t type)2250 static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
2251 {
2252     struct stream_out *out = (struct stream_out *)stream;
2253     int status = -ENOSYS;
2254     ALOGV("%s", __func__);
2255     if (is_offload_usecase(out->usecase)) {
2256         pthread_mutex_lock(&out->lock);
2257         if (type == AUDIO_DRAIN_EARLY_NOTIFY)
2258             status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
2259         else
2260             status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
2261         pthread_mutex_unlock(&out->lock);
2262     }
2263     return status;
2264 }
2265 
out_flush(struct audio_stream_out * stream)2266 static int out_flush(struct audio_stream_out* stream)
2267 {
2268     struct stream_out *out = (struct stream_out *)stream;
2269     ALOGV("%s", __func__);
2270     if (is_offload_usecase(out->usecase)) {
2271         ALOGD("copl(%p):calling compress flush", out);
2272         pthread_mutex_lock(&out->lock);
2273         stop_compressed_output_l(out);
2274         pthread_mutex_unlock(&out->lock);
2275         ALOGD("copl(%p):out of compress flush", out);
2276         return 0;
2277     }
2278     return -ENOSYS;
2279 }
2280 
2281 /** audio_stream_in implementation **/
in_get_sample_rate(const struct audio_stream * stream)2282 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
2283 {
2284     struct stream_in *in = (struct stream_in *)stream;
2285 
2286     return in->config.rate;
2287 }
2288 
in_set_sample_rate(struct audio_stream * stream __unused,uint32_t rate __unused)2289 static int in_set_sample_rate(struct audio_stream *stream __unused,
2290                               uint32_t rate __unused)
2291 {
2292     return -ENOSYS;
2293 }
2294 
in_get_buffer_size(const struct audio_stream * stream)2295 static size_t in_get_buffer_size(const struct audio_stream *stream)
2296 {
2297     struct stream_in *in = (struct stream_in *)stream;
2298 
2299     if(in->usecase == USECASE_COMPRESS_VOIP_CALL)
2300         return voice_extn_compress_voip_in_get_buffer_size(in);
2301     else if(audio_extn_compr_cap_usecase_supported(in->usecase))
2302         return audio_extn_compr_cap_get_buffer_size(in->config.format);
2303 
2304     return in->config.period_size *
2305                 audio_stream_in_frame_size((const struct audio_stream_in *)stream);
2306 }
2307 
in_get_channels(const struct audio_stream * stream)2308 static uint32_t in_get_channels(const struct audio_stream *stream)
2309 {
2310     struct stream_in *in = (struct stream_in *)stream;
2311 
2312     return in->channel_mask;
2313 }
2314 
in_get_format(const struct audio_stream * stream)2315 static audio_format_t in_get_format(const struct audio_stream *stream)
2316 {
2317     struct stream_in *in = (struct stream_in *)stream;
2318 
2319     return in->format;
2320 }
2321 
in_set_format(struct audio_stream * stream __unused,audio_format_t format __unused)2322 static int in_set_format(struct audio_stream *stream __unused,
2323                          audio_format_t format __unused)
2324 {
2325     return -ENOSYS;
2326 }
2327 
in_standby(struct audio_stream * stream)2328 static int in_standby(struct audio_stream *stream)
2329 {
2330     struct stream_in *in = (struct stream_in *)stream;
2331     struct audio_device *adev = in->dev;
2332     int status = 0;
2333     ALOGD("%s: enter: stream (%p) usecase(%d: %s)", __func__,
2334           stream, in->usecase, use_case_table[in->usecase]);
2335 
2336     if (in->usecase == USECASE_COMPRESS_VOIP_CALL) {
2337         /* Ignore standby in case of voip call because the voip input
2338          * stream is closed in adev_close_input_stream()
2339          */
2340         ALOGV("%s: Ignore Standby in VOIP call", __func__);
2341         return status;
2342     }
2343 
2344     pthread_mutex_lock(&in->lock);
2345     if (!in->standby && in->is_st_session) {
2346         ALOGD("%s: sound trigger pcm stop lab", __func__);
2347         audio_extn_sound_trigger_stop_lab(in);
2348         in->standby = 1;
2349     }
2350 
2351     if (!in->standby) {
2352         pthread_mutex_lock(&adev->lock);
2353         in->standby = true;
2354         if (in->pcm) {
2355             pcm_close(in->pcm);
2356             in->pcm = NULL;
2357         }
2358         status = stop_input_stream(in);
2359         pthread_mutex_unlock(&adev->lock);
2360     }
2361     pthread_mutex_unlock(&in->lock);
2362     ALOGV("%s: exit:  status(%d)", __func__, status);
2363     return status;
2364 }
2365 
in_dump(const struct audio_stream * stream __unused,int fd __unused)2366 static int in_dump(const struct audio_stream *stream __unused,
2367                    int fd __unused)
2368 {
2369     return 0;
2370 }
2371 
in_set_parameters(struct audio_stream * stream,const char * kvpairs)2372 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
2373 {
2374     struct stream_in *in = (struct stream_in *)stream;
2375     struct audio_device *adev = in->dev;
2376     struct str_parms *parms;
2377     char *str;
2378     char value[32];
2379     int ret = 0, val = 0, err;
2380 
2381     ALOGD("%s: enter: kvpairs=%s", __func__, kvpairs);
2382     parms = str_parms_create_str(kvpairs);
2383 
2384     if (!parms)
2385         goto error;
2386     pthread_mutex_lock(&in->lock);
2387     pthread_mutex_lock(&adev->lock);
2388 
2389     err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
2390     if (err >= 0) {
2391         val = atoi(value);
2392         /* no audio source uses val == 0 */
2393         if ((in->source != val) && (val != 0)) {
2394             in->source = val;
2395             if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
2396                 (in->dev->mode == AUDIO_MODE_IN_COMMUNICATION) &&
2397                 (voice_extn_compress_voip_is_format_supported(in->format)) &&
2398                 (in->config.rate == 8000 || in->config.rate == 16000) &&
2399                 (audio_channel_count_from_in_mask(in->channel_mask) == 1)) {
2400                 err = voice_extn_compress_voip_open_input_stream(in);
2401                 if (err != 0) {
2402                     ALOGE("%s: Compress voip input cannot be opened, error:%d",
2403                           __func__, err);
2404                 }
2405             }
2406         }
2407     }
2408 
2409     err = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
2410     if (err >= 0) {
2411         val = atoi(value);
2412         if (((int)in->device != val) && (val != 0)) {
2413             in->device = val;
2414             /* If recording is in progress, change the tx device to new device */
2415             if (!in->standby && !in->is_st_session)
2416                 ret = select_devices(adev, in->usecase);
2417         }
2418     }
2419 
2420 done:
2421     pthread_mutex_unlock(&adev->lock);
2422     pthread_mutex_unlock(&in->lock);
2423 
2424     str_parms_destroy(parms);
2425 error:
2426     ALOGV("%s: exit: status(%d)", __func__, ret);
2427     return ret;
2428 }
2429 
in_get_parameters(const struct audio_stream * stream,const char * keys)2430 static char* in_get_parameters(const struct audio_stream *stream,
2431                                const char *keys)
2432 {
2433     struct stream_in *in = (struct stream_in *)stream;
2434     struct str_parms *query = str_parms_create_str(keys);
2435     char *str;
2436     char value[256];
2437     struct str_parms *reply = str_parms_create();
2438 
2439     if (!query || !reply) {
2440         ALOGE("in_get_parameters: failed to create query or reply");
2441         return NULL;
2442     }
2443 
2444     ALOGV("%s: enter: keys - %s", __func__, keys);
2445 
2446     voice_extn_in_get_parameters(in, query, reply);
2447 
2448     str = str_parms_to_str(reply);
2449     str_parms_destroy(query);
2450     str_parms_destroy(reply);
2451 
2452     ALOGV("%s: exit: returns - %s", __func__, str);
2453     return str;
2454 }
2455 
in_set_gain(struct audio_stream_in * stream __unused,float gain __unused)2456 static int in_set_gain(struct audio_stream_in *stream __unused,
2457                        float gain __unused)
2458 {
2459     return 0;
2460 }
2461 
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)2462 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
2463                        size_t bytes)
2464 {
2465     struct stream_in *in = (struct stream_in *)stream;
2466     struct audio_device *adev = in->dev;
2467     int i, ret = -1;
2468     int snd_scard_state = get_snd_card_state(adev);
2469 
2470     pthread_mutex_lock(&in->lock);
2471 
2472     if (in->pcm) {
2473         if(SND_CARD_STATE_OFFLINE == snd_scard_state) {
2474             ALOGD(" %s: sound card is not active/SSR state", __func__);
2475             ret= -EIO;;
2476             goto exit;
2477         }
2478     }
2479 
2480     if (in->standby) {
2481         if (!in->is_st_session) {
2482             pthread_mutex_lock(&adev->lock);
2483             if (in->usecase == USECASE_COMPRESS_VOIP_CALL)
2484                 ret = voice_extn_compress_voip_start_input_stream(in);
2485             else
2486                 ret = start_input_stream(in);
2487             pthread_mutex_unlock(&adev->lock);
2488             if (ret != 0) {
2489                 goto exit;
2490             }
2491         }
2492         in->standby = 0;
2493     }
2494 
2495     if (in->pcm) {
2496         if (audio_extn_ssr_get_enabled() &&
2497                 audio_channel_count_from_in_mask(in->channel_mask) == 6)
2498             ret = audio_extn_ssr_read(stream, buffer, bytes);
2499         else if (audio_extn_compr_cap_usecase_supported(in->usecase))
2500             ret = audio_extn_compr_cap_read(in, buffer, bytes);
2501         else if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY)
2502             ret = pcm_mmap_read(in->pcm, buffer, bytes);
2503         else
2504             ret = pcm_read(in->pcm, buffer, bytes);
2505         if (ret < 0)
2506             ret = -errno;
2507     }
2508 
2509     /*
2510      * Instead of writing zeroes here, we could trust the hardware
2511      * to always provide zeroes when muted.
2512      */
2513     if (ret == 0 && voice_get_mic_mute(adev) && !voice_is_in_call_rec_stream(in))
2514         memset(buffer, 0, bytes);
2515 
2516 exit:
2517     /* ToDo: There may be a corner case when SSR happens back to back during
2518        start/stop. Need to post different error to handle that. */
2519     if (-ENETRESET == ret) {
2520         set_snd_card_state(adev,SND_CARD_STATE_OFFLINE);
2521     }
2522     pthread_mutex_unlock(&in->lock);
2523 
2524     if (ret != 0) {
2525         if (in->usecase == USECASE_COMPRESS_VOIP_CALL) {
2526             pthread_mutex_lock(&adev->lock);
2527             voice_extn_compress_voip_close_input_stream(&in->stream.common);
2528             pthread_mutex_unlock(&adev->lock);
2529             in->standby = true;
2530         }
2531         memset(buffer, 0, bytes);
2532         in_standby(&in->stream.common);
2533         ALOGV("%s: read failed status %d- sleeping for buffer duration", __func__, ret);
2534         usleep(bytes * 1000000 / audio_stream_in_frame_size(stream) /
2535                                    in_get_sample_rate(&in->stream.common));
2536     }
2537     return bytes;
2538 }
2539 
in_get_input_frames_lost(struct audio_stream_in * stream __unused)2540 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream __unused)
2541 {
2542     return 0;
2543 }
2544 
add_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect,bool enable)2545 static int add_remove_audio_effect(const struct audio_stream *stream,
2546                                    effect_handle_t effect,
2547                                    bool enable)
2548 {
2549     struct stream_in *in = (struct stream_in *)stream;
2550     int status = 0;
2551     effect_descriptor_t desc;
2552 
2553     status = (*effect)->get_descriptor(effect, &desc);
2554     if (status != 0)
2555         return status;
2556 
2557     pthread_mutex_lock(&in->lock);
2558     pthread_mutex_lock(&in->dev->lock);
2559     if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
2560             in->enable_aec != enable &&
2561             (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
2562         in->enable_aec = enable;
2563         if (!in->standby)
2564             select_devices(in->dev, in->usecase);
2565     }
2566     if (in->enable_ns != enable &&
2567             (memcmp(&desc.type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
2568         in->enable_ns = enable;
2569         if (!in->standby)
2570             select_devices(in->dev, in->usecase);
2571     }
2572     pthread_mutex_unlock(&in->dev->lock);
2573     pthread_mutex_unlock(&in->lock);
2574 
2575     return 0;
2576 }
2577 
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)2578 static int in_add_audio_effect(const struct audio_stream *stream,
2579                                effect_handle_t effect)
2580 {
2581     ALOGV("%s: effect %p", __func__, effect);
2582     return add_remove_audio_effect(stream, effect, true);
2583 }
2584 
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)2585 static int in_remove_audio_effect(const struct audio_stream *stream,
2586                                   effect_handle_t effect)
2587 {
2588     ALOGV("%s: effect %p", __func__, effect);
2589     return add_remove_audio_effect(stream, effect, false);
2590 }
2591 
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)2592 static int adev_open_output_stream(struct audio_hw_device *dev,
2593                                    audio_io_handle_t handle,
2594                                    audio_devices_t devices,
2595                                    audio_output_flags_t flags,
2596                                    struct audio_config *config,
2597                                    struct audio_stream_out **stream_out,
2598                                    const char *address __unused)
2599 {
2600     struct audio_device *adev = (struct audio_device *)dev;
2601     struct stream_out *out;
2602     int i, ret = 0;
2603     audio_format_t format;
2604 
2605     *stream_out = NULL;
2606 
2607     if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
2608              (SND_CARD_STATE_OFFLINE == get_snd_card_state(adev))) {
2609         ALOGE(" sound card is not active rejecting compress output open request");
2610         return -EINVAL;
2611     }
2612 
2613     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
2614 
2615     ALOGD("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)\
2616         stream_handle(%p)",__func__, config->sample_rate, config->channel_mask,
2617         devices, flags, &out->stream);
2618 
2619 
2620     if (!out) {
2621         return -ENOMEM;
2622     }
2623 
2624     if (devices == AUDIO_DEVICE_NONE)
2625         devices = AUDIO_DEVICE_OUT_SPEAKER;
2626 
2627     out->flags = flags;
2628     out->devices = devices;
2629     out->dev = adev;
2630     format = out->format = config->format;
2631     out->sample_rate = config->sample_rate;
2632     out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2633     out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
2634     out->handle = handle;
2635     out->bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH;
2636 
2637     /* Init use case and pcm_config */
2638     if ((out->flags == AUDIO_OUTPUT_FLAG_DIRECT) &&
2639         (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2640         out->devices & AUDIO_DEVICE_OUT_PROXY)) {
2641 
2642         pthread_mutex_lock(&adev->lock);
2643         if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
2644             ret = read_hdmi_channel_masks(out);
2645 
2646         if (out->devices & AUDIO_DEVICE_OUT_PROXY)
2647             ret = audio_extn_read_afe_proxy_channel_masks(out);
2648         pthread_mutex_unlock(&adev->lock);
2649         if (ret != 0)
2650             goto error_open;
2651 
2652         if (config->sample_rate == 0)
2653             config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
2654         if (config->channel_mask == 0)
2655             config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
2656 
2657         out->channel_mask = config->channel_mask;
2658         out->sample_rate = config->sample_rate;
2659         out->usecase = USECASE_AUDIO_PLAYBACK_MULTI_CH;
2660         out->config = pcm_config_hdmi_multi;
2661         out->config.rate = config->sample_rate;
2662         out->config.channels = audio_channel_count_from_out_mask(out->channel_mask);
2663         out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels * 2);
2664     } else if ((out->dev->mode == AUDIO_MODE_IN_COMMUNICATION) &&
2665                (out->flags == (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_VOIP_RX)) &&
2666                (voice_extn_compress_voip_is_config_supported(config))) {
2667         ret = voice_extn_compress_voip_open_output_stream(out);
2668         if (ret != 0) {
2669             ALOGE("%s: Compress voip output cannot be opened, error:%d",
2670                   __func__, ret);
2671             goto error_open;
2672         }
2673     } else if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2674         if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
2675             config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
2676             ALOGE("%s: Unsupported Offload information", __func__);
2677             ret = -EINVAL;
2678             goto error_open;
2679         }
2680         if (!is_supported_format(config->offload_info.format) &&
2681                 !audio_extn_is_dolby_format(config->offload_info.format)) {
2682             ALOGE("%s: Unsupported audio format", __func__);
2683             ret = -EINVAL;
2684             goto error_open;
2685         }
2686 
2687         out->compr_config.codec = (struct snd_codec *)
2688                                     calloc(1, sizeof(struct snd_codec));
2689 
2690         if (!out->compr_config.codec) {
2691             ret = -ENOMEM;
2692             goto error_open;
2693         }
2694 
2695         out->usecase = get_offload_usecase(adev);
2696         if (config->offload_info.channel_mask)
2697             out->channel_mask = config->offload_info.channel_mask;
2698         else if (config->channel_mask) {
2699             out->channel_mask = config->channel_mask;
2700             config->offload_info.channel_mask = config->channel_mask;
2701         }
2702         format = out->format = config->offload_info.format;
2703         out->sample_rate = config->offload_info.sample_rate;
2704 
2705         out->stream.set_callback = out_set_callback;
2706         out->stream.pause = out_pause;
2707         out->stream.resume = out_resume;
2708         out->stream.drain = out_drain;
2709         out->stream.flush = out_flush;
2710         out->bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH;
2711 
2712         if (audio_extn_is_dolby_format(config->offload_info.format))
2713             out->compr_config.codec->id =
2714                 audio_extn_dolby_get_snd_codec_id(adev, out,
2715                                                   config->offload_info.format);
2716         else
2717             out->compr_config.codec->id =
2718                 get_snd_codec_id(config->offload_info.format);
2719         if (audio_is_offload_pcm(config->offload_info.format)) {
2720             out->compr_config.fragment_size =
2721                        platform_get_pcm_offload_buffer_size(&config->offload_info);
2722         } else {
2723             out->compr_config.fragment_size =
2724                        platform_get_compress_offload_buffer_size(&config->offload_info);
2725         }
2726         out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
2727         out->compr_config.codec->sample_rate =
2728                     config->offload_info.sample_rate;
2729         out->compr_config.codec->bit_rate =
2730                     config->offload_info.bit_rate;
2731         out->compr_config.codec->ch_in =
2732                 audio_channel_count_from_out_mask(config->channel_mask);
2733         out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
2734         out->bit_width = PCM_OUTPUT_BIT_WIDTH;
2735 
2736         if (config->offload_info.format == AUDIO_FORMAT_AAC)
2737             out->compr_config.codec->format = SND_AUDIOSTREAMFORMAT_RAW;
2738         if (config->offload_info.format == AUDIO_FORMAT_PCM_16_BIT_OFFLOAD)
2739             out->compr_config.codec->format = SNDRV_PCM_FORMAT_S16_LE;
2740         if(config->offload_info.format == AUDIO_FORMAT_PCM_24_BIT_OFFLOAD)
2741             out->compr_config.codec->format = SNDRV_PCM_FORMAT_S24_LE;
2742 
2743         if (out->bit_width == 24) {
2744             out->compr_config.codec->format = SNDRV_PCM_FORMAT_S24_LE;
2745         }
2746 
2747         if (config->offload_info.format == AUDIO_FORMAT_FLAC)
2748             out->compr_config.codec->options.flac_dec.sample_size = PCM_OUTPUT_BIT_WIDTH;
2749 
2750         if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
2751             out->non_blocking = 1;
2752 
2753         out->send_new_metadata = 1;
2754         out->offload_state = OFFLOAD_STATE_IDLE;
2755         out->playback_started = 0;
2756 
2757         create_offload_callback_thread(out);
2758         ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
2759                 __func__, config->offload_info.version,
2760                 config->offload_info.bit_rate);
2761         //Decide if we need to use gapless mode by default
2762         check_and_set_gapless_mode(adev);
2763 
2764     } else if (out->flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) {
2765         ret = voice_check_and_set_incall_music_usecase(adev, out);
2766         if (ret != 0) {
2767             ALOGE("%s: Incall music delivery usecase cannot be set error:%d",
2768                   __func__, ret);
2769             goto error_open;
2770         }
2771     } else  if (out->devices == AUDIO_DEVICE_OUT_TELEPHONY_TX) {
2772         if (config->sample_rate == 0)
2773             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
2774         if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
2775                 config->sample_rate != 8000) {
2776             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
2777             ret = -EINVAL;
2778             goto error_open;
2779         }
2780         out->sample_rate = config->sample_rate;
2781         out->config.rate = config->sample_rate;
2782         if (config->format == AUDIO_FORMAT_DEFAULT)
2783             config->format = AUDIO_FORMAT_PCM_16_BIT;
2784         if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
2785             config->format = AUDIO_FORMAT_PCM_16_BIT;
2786             ret = -EINVAL;
2787             goto error_open;
2788         }
2789         out->format = config->format;
2790         out->usecase = USECASE_AUDIO_PLAYBACK_AFE_PROXY;
2791         out->config = pcm_config_afe_proxy_playback;
2792         adev->voice_tx_output = out;
2793     } else if (out->flags & AUDIO_OUTPUT_FLAG_FAST) {
2794         format = AUDIO_FORMAT_PCM_16_BIT;
2795         out->usecase = USECASE_AUDIO_PLAYBACK_LOW_LATENCY;
2796         out->config = pcm_config_low_latency;
2797         out->sample_rate = out->config.rate;
2798     } else {
2799         /* primary path is the default path selected if no other outputs are available/suitable */
2800         format = AUDIO_FORMAT_PCM_16_BIT;
2801         out->usecase = USECASE_AUDIO_PLAYBACK_PRIMARY;
2802         out->config = pcm_config_deep_buffer;
2803         out->sample_rate = out->config.rate;
2804     }
2805 
2806     ALOGV("%s devices %d,flags %x, format %x, out->sample_rate %d, out->bit_width %d",
2807            __func__, devices, flags, format, out->sample_rate, out->bit_width);
2808     audio_extn_utils_update_stream_app_type_cfg(adev->platform,
2809                                                 &adev->streams_output_cfg_list,
2810                                                 devices, flags, format, out->sample_rate,
2811                                                 out->bit_width, &out->app_type_cfg);
2812     if ((out->usecase == USECASE_AUDIO_PLAYBACK_PRIMARY) ||
2813         (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
2814         /* Ensure the default output is not selected twice */
2815         if(adev->primary_output == NULL)
2816             adev->primary_output = out;
2817         else {
2818             ALOGE("%s: Primary output is already opened", __func__);
2819             ret = -EEXIST;
2820             goto error_open;
2821         }
2822     }
2823 
2824     /* Check if this usecase is already existing */
2825     pthread_mutex_lock(&adev->lock);
2826     if ((get_usecase_from_list(adev, out->usecase) != NULL) &&
2827         (out->usecase != USECASE_COMPRESS_VOIP_CALL)) {
2828         ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
2829         pthread_mutex_unlock(&adev->lock);
2830         ret = -EEXIST;
2831         goto error_open;
2832     }
2833     pthread_mutex_unlock(&adev->lock);
2834 
2835     out->stream.common.get_sample_rate = out_get_sample_rate;
2836     out->stream.common.set_sample_rate = out_set_sample_rate;
2837     out->stream.common.get_buffer_size = out_get_buffer_size;
2838     out->stream.common.get_channels = out_get_channels;
2839     out->stream.common.get_format = out_get_format;
2840     out->stream.common.set_format = out_set_format;
2841     out->stream.common.standby = out_standby;
2842     out->stream.common.dump = out_dump;
2843     out->stream.common.set_parameters = out_set_parameters;
2844     out->stream.common.get_parameters = out_get_parameters;
2845     out->stream.common.add_audio_effect = out_add_audio_effect;
2846     out->stream.common.remove_audio_effect = out_remove_audio_effect;
2847     out->stream.get_latency = out_get_latency;
2848     out->stream.set_volume = out_set_volume;
2849     out->stream.write = out_write;
2850     out->stream.get_render_position = out_get_render_position;
2851     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
2852     out->stream.get_presentation_position = out_get_presentation_position;
2853 
2854     out->standby = 1;
2855     /* out->muted = false; by calloc() */
2856     /* out->written = 0; by calloc() */
2857 
2858     pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
2859     pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);
2860 
2861     config->format = out->stream.common.get_format(&out->stream.common);
2862     config->channel_mask = out->stream.common.get_channels(&out->stream.common);
2863     config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
2864 
2865     *stream_out = &out->stream;
2866     ALOGD("%s: Stream (%p) picks up usecase (%s)", __func__, &out->stream,
2867         use_case_table[out->usecase]);
2868     ALOGV("%s: exit", __func__);
2869     return 0;
2870 
2871 error_open:
2872     free(out);
2873     *stream_out = NULL;
2874     ALOGD("%s: exit: ret %d", __func__, ret);
2875     return ret;
2876 }
2877 
adev_close_output_stream(struct audio_hw_device * dev __unused,struct audio_stream_out * stream)2878 static void adev_close_output_stream(struct audio_hw_device *dev __unused,
2879                                      struct audio_stream_out *stream)
2880 {
2881     struct stream_out *out = (struct stream_out *)stream;
2882     struct audio_device *adev = out->dev;
2883     int ret = 0;
2884 
2885     ALOGD("%s: enter:stream_handle(%p)",__func__, out);
2886 
2887     if (out->usecase == USECASE_COMPRESS_VOIP_CALL) {
2888         pthread_mutex_lock(&adev->lock);
2889         ret = voice_extn_compress_voip_close_output_stream(&stream->common);
2890         pthread_mutex_unlock(&adev->lock);
2891         if(ret != 0)
2892             ALOGE("%s: Compress voip output cannot be closed, error:%d",
2893                   __func__, ret);
2894     } else
2895         out_standby(&stream->common);
2896 
2897     if (is_offload_usecase(out->usecase)) {
2898         destroy_offload_callback_thread(out);
2899         free_offload_usecase(adev, out->usecase);
2900         if (out->compr_config.codec != NULL)
2901             free(out->compr_config.codec);
2902     }
2903 
2904     if (adev->voice_tx_output == out)
2905         adev->voice_tx_output = NULL;
2906 
2907     pthread_cond_destroy(&out->cond);
2908     pthread_mutex_destroy(&out->lock);
2909     free(stream);
2910     ALOGV("%s: exit", __func__);
2911 }
2912 
adev_set_parameters(struct audio_hw_device * dev,const char * kvpairs)2913 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
2914 {
2915     struct audio_device *adev = (struct audio_device *)dev;
2916     struct str_parms *parms;
2917     char *str;
2918     char value[32];
2919     int val;
2920     int ret;
2921     int status = 0;
2922 
2923     ALOGD("%s: enter: %s", __func__, kvpairs);
2924     parms = str_parms_create_str(kvpairs);
2925 
2926     if (!parms)
2927         goto error;
2928     ret = str_parms_get_str(parms, "SND_CARD_STATUS", value, sizeof(value));
2929     if (ret >= 0) {
2930         char *snd_card_status = value+2;
2931         if (strstr(snd_card_status, "OFFLINE")) {
2932             struct listnode *node;
2933             struct audio_usecase *usecase;
2934 
2935             ALOGD("Received sound card OFFLINE status");
2936             set_snd_card_state(adev,SND_CARD_STATE_OFFLINE);
2937 
2938             pthread_mutex_lock(&adev->lock);
2939             //close compress session on OFFLINE status
2940             usecase = get_usecase_from_list(adev,USECASE_AUDIO_PLAYBACK_OFFLOAD);
2941             if (usecase && usecase->stream.out) {
2942                 ALOGD(" %s closing compress session on OFFLINE state", __func__);
2943 
2944                 struct stream_out *out = usecase->stream.out;
2945 
2946                 pthread_mutex_unlock(&adev->lock);
2947                 out_standby(&out->stream.common);
2948             } else
2949                 pthread_mutex_unlock(&adev->lock);
2950         } else if (strstr(snd_card_status, "ONLINE")) {
2951             ALOGD("Received sound card ONLINE status");
2952             set_snd_card_state(adev,SND_CARD_STATE_ONLINE);
2953             if (!platform_is_acdb_initialized(adev->platform)) {
2954                 ret = platform_acdb_init(adev->platform);
2955                 if(ret)
2956                    ALOGE("acdb initialization is failed");
2957 
2958             }
2959         }
2960     }
2961 
2962     pthread_mutex_lock(&adev->lock);
2963     status = voice_set_parameters(adev, parms);
2964     if (status != 0)
2965         goto done;
2966 
2967     status = platform_set_parameters(adev->platform, parms);
2968     if (status != 0)
2969         goto done;
2970 
2971     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
2972     if (ret >= 0) {
2973         /* When set to false, HAL should disable EC and NS */
2974         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
2975             adev->bluetooth_nrec = true;
2976         else
2977             adev->bluetooth_nrec = false;
2978     }
2979 
2980     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
2981     if (ret >= 0) {
2982         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
2983             adev->screen_off = false;
2984         else
2985             adev->screen_off = true;
2986     }
2987 
2988     ret = str_parms_get_int(parms, "rotation", &val);
2989     if (ret >= 0) {
2990         bool reverse_speakers = false;
2991         switch(val) {
2992         // FIXME: note that the code below assumes that the speakers are in the correct placement
2993         //   relative to the user when the device is rotated 90deg from its default rotation. This
2994         //   assumption is device-specific, not platform-specific like this code.
2995         case 270:
2996             reverse_speakers = true;
2997             break;
2998         case 0:
2999         case 90:
3000         case 180:
3001             break;
3002         default:
3003             ALOGE("%s: unexpected rotation of %d", __func__, val);
3004             status = -EINVAL;
3005         }
3006         if (status == 0) {
3007             if (adev->speaker_lr_swap != reverse_speakers) {
3008                 adev->speaker_lr_swap = reverse_speakers;
3009                 // only update the selected device if there is active pcm playback
3010                 struct audio_usecase *usecase;
3011                 struct listnode *node;
3012                 list_for_each(node, &adev->usecase_list) {
3013                     usecase = node_to_item(node, struct audio_usecase, list);
3014                     if (usecase->type == PCM_PLAYBACK) {
3015                         select_devices(adev, usecase->id);
3016                         break;
3017                     }
3018                 }
3019             }
3020         }
3021     }
3022 
3023     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value));
3024     if (ret >= 0) {
3025         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
3026             adev->bt_wb_speech_enabled = true;
3027         else
3028             adev->bt_wb_speech_enabled = false;
3029     }
3030 
3031     audio_extn_set_parameters(adev, parms);
3032 
3033 done:
3034     str_parms_destroy(parms);
3035     pthread_mutex_unlock(&adev->lock);
3036 error:
3037     ALOGV("%s: exit with code(%d)", __func__, status);
3038     return status;
3039 }
3040 
adev_get_parameters(const struct audio_hw_device * dev,const char * keys)3041 static char* adev_get_parameters(const struct audio_hw_device *dev,
3042                                  const char *keys)
3043 {
3044     struct audio_device *adev = (struct audio_device *)dev;
3045     struct str_parms *reply = str_parms_create();
3046     struct str_parms *query = str_parms_create_str(keys);
3047     char *str;
3048     char value[256] = {0};
3049     int ret = 0;
3050 
3051     if (!query || !reply) {
3052         ALOGE("adev_get_parameters: failed to create query or reply");
3053         return NULL;
3054     }
3055 
3056     ret = str_parms_get_str(query, "SND_CARD_STATUS", value,
3057                             sizeof(value));
3058     if (ret >=0) {
3059         int val = 1;
3060         pthread_mutex_lock(&adev->snd_card_status.lock);
3061         if (SND_CARD_STATE_OFFLINE == adev->snd_card_status.state)
3062             val = 0;
3063         pthread_mutex_unlock(&adev->snd_card_status.lock);
3064         str_parms_add_int(reply, "SND_CARD_STATUS", val);
3065         goto exit;
3066     }
3067 
3068     pthread_mutex_lock(&adev->lock);
3069     audio_extn_get_parameters(adev, query, reply);
3070     voice_get_parameters(adev, query, reply);
3071     platform_get_parameters(adev->platform, query, reply);
3072     pthread_mutex_unlock(&adev->lock);
3073 
3074 exit:
3075     str = str_parms_to_str(reply);
3076     str_parms_destroy(query);
3077     str_parms_destroy(reply);
3078 
3079     ALOGV("%s: exit: returns - %s", __func__, str);
3080     return str;
3081 }
3082 
adev_init_check(const struct audio_hw_device * dev __unused)3083 static int adev_init_check(const struct audio_hw_device *dev __unused)
3084 {
3085     return 0;
3086 }
3087 
adev_set_voice_volume(struct audio_hw_device * dev,float volume)3088 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
3089 {
3090     int ret;
3091     struct audio_device *adev = (struct audio_device *)dev;
3092     pthread_mutex_lock(&adev->lock);
3093     /* cache volume */
3094     ret = voice_set_volume(adev, volume);
3095     pthread_mutex_unlock(&adev->lock);
3096     return ret;
3097 }
3098 
adev_set_master_volume(struct audio_hw_device * dev __unused,float volume __unused)3099 static int adev_set_master_volume(struct audio_hw_device *dev __unused,
3100                                   float volume __unused)
3101 {
3102     return -ENOSYS;
3103 }
3104 
adev_get_master_volume(struct audio_hw_device * dev __unused,float * volume __unused)3105 static int adev_get_master_volume(struct audio_hw_device *dev __unused,
3106                                   float *volume __unused)
3107 {
3108     return -ENOSYS;
3109 }
3110 
adev_set_master_mute(struct audio_hw_device * dev __unused,bool muted __unused)3111 static int adev_set_master_mute(struct audio_hw_device *dev __unused,
3112                                 bool muted __unused)
3113 {
3114     return -ENOSYS;
3115 }
3116 
adev_get_master_mute(struct audio_hw_device * dev __unused,bool * muted __unused)3117 static int adev_get_master_mute(struct audio_hw_device *dev __unused,
3118                                 bool *muted __unused)
3119 {
3120     return -ENOSYS;
3121 }
3122 
adev_set_mode(struct audio_hw_device * dev,audio_mode_t mode)3123 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
3124 {
3125     struct audio_device *adev = (struct audio_device *)dev;
3126 
3127     pthread_mutex_lock(&adev->lock);
3128     if (adev->mode != mode) {
3129         ALOGD("%s: mode %d\n", __func__, mode);
3130         adev->mode = mode;
3131         if ((mode == AUDIO_MODE_NORMAL || mode == AUDIO_MODE_IN_COMMUNICATION) &&
3132                 voice_is_in_call(adev)) {
3133             voice_stop_call(adev);
3134             adev->current_call_output = NULL;
3135         }
3136     }
3137     pthread_mutex_unlock(&adev->lock);
3138     return 0;
3139 }
3140 
adev_set_mic_mute(struct audio_hw_device * dev,bool state)3141 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
3142 {
3143     int ret;
3144 
3145     pthread_mutex_lock(&adev->lock);
3146     ALOGD("%s state %d\n", __func__, state);
3147     ret = voice_set_mic_mute((struct audio_device *)dev, state);
3148     pthread_mutex_unlock(&adev->lock);
3149 
3150     return ret;
3151 }
3152 
adev_get_mic_mute(const struct audio_hw_device * dev,bool * state)3153 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
3154 {
3155     *state = voice_get_mic_mute((struct audio_device *)dev);
3156     return 0;
3157 }
3158 
adev_get_input_buffer_size(const struct audio_hw_device * dev __unused,const struct audio_config * config)3159 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev __unused,
3160                                          const struct audio_config *config)
3161 {
3162     int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
3163 
3164     return get_input_buffer_size(config->sample_rate, config->format, channel_count,
3165             false /* is_low_latency: since we don't know, be conservative */);
3166 }
3167 
adev_open_input_stream(struct audio_hw_device * dev,audio_io_handle_t handle __unused,audio_devices_t devices,struct audio_config * config,struct audio_stream_in ** stream_in,audio_input_flags_t flags __unused,const char * address __unused,audio_source_t source __unused)3168 static int adev_open_input_stream(struct audio_hw_device *dev,
3169                                   audio_io_handle_t handle __unused,
3170                                   audio_devices_t devices,
3171                                   struct audio_config *config,
3172                                   struct audio_stream_in **stream_in,
3173                                   audio_input_flags_t flags __unused,
3174                                   const char *address __unused,
3175                                   audio_source_t source __unused)
3176 {
3177     struct audio_device *adev = (struct audio_device *)dev;
3178     struct stream_in *in;
3179     int ret = 0, buffer_size, frame_size;
3180     int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
3181     bool is_low_latency = false;
3182 
3183     *stream_in = NULL;
3184     if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0)
3185         return -EINVAL;
3186 
3187     in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
3188 
3189     if (!in) {
3190         ALOGE("failed to allocate input stream");
3191         return -ENOMEM;
3192     }
3193 
3194     ALOGD("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x)\
3195         stream_handle(%p) io_handle(%d)",__func__, config->sample_rate, config->channel_mask,
3196         devices, &in->stream, handle);
3197 
3198     pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
3199 
3200     in->stream.common.get_sample_rate = in_get_sample_rate;
3201     in->stream.common.set_sample_rate = in_set_sample_rate;
3202     in->stream.common.get_buffer_size = in_get_buffer_size;
3203     in->stream.common.get_channels = in_get_channels;
3204     in->stream.common.get_format = in_get_format;
3205     in->stream.common.set_format = in_set_format;
3206     in->stream.common.standby = in_standby;
3207     in->stream.common.dump = in_dump;
3208     in->stream.common.set_parameters = in_set_parameters;
3209     in->stream.common.get_parameters = in_get_parameters;
3210     in->stream.common.add_audio_effect = in_add_audio_effect;
3211     in->stream.common.remove_audio_effect = in_remove_audio_effect;
3212     in->stream.set_gain = in_set_gain;
3213     in->stream.read = in_read;
3214     in->stream.get_input_frames_lost = in_get_input_frames_lost;
3215 
3216     in->device = devices;
3217     in->source = AUDIO_SOURCE_DEFAULT;
3218     in->dev = adev;
3219     in->standby = 1;
3220     in->channel_mask = config->channel_mask;
3221     in->capture_handle = handle;
3222 
3223     /* Update config params with the requested sample rate and channels */
3224     in->usecase = USECASE_AUDIO_RECORD;
3225     if (config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE &&
3226             (flags & AUDIO_INPUT_FLAG_FAST) != 0) {
3227         is_low_latency = true;
3228 #if LOW_LATENCY_CAPTURE_USE_CASE
3229         in->usecase = USECASE_AUDIO_RECORD_LOW_LATENCY;
3230 #endif
3231     }
3232     in->config = pcm_config_audio_capture;
3233     in->config.rate = config->sample_rate;
3234     in->format = config->format;
3235 
3236     if (in->device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
3237         if (config->sample_rate == 0)
3238             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
3239         if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
3240                 config->sample_rate != 8000) {
3241             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
3242             ret = -EINVAL;
3243             goto err_open;
3244         }
3245         if (config->format == AUDIO_FORMAT_DEFAULT)
3246             config->format = AUDIO_FORMAT_PCM_16_BIT;
3247         if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
3248             config->format = AUDIO_FORMAT_PCM_16_BIT;
3249             ret = -EINVAL;
3250             goto err_open;
3251         }
3252 
3253         in->usecase = USECASE_AUDIO_RECORD_AFE_PROXY;
3254         in->config = pcm_config_afe_proxy_record;
3255         in->config.channels = channel_count;
3256         in->config.rate = config->sample_rate;
3257     } else if (channel_count == 6) {
3258         if(audio_extn_ssr_get_enabled()) {
3259             if(audio_extn_ssr_init(in)) {
3260                 ALOGE("%s: audio_extn_ssr_init failed", __func__);
3261                 ret = -EINVAL;
3262                 goto err_open;
3263             }
3264         } else {
3265             ALOGW("%s: surround sound recording is not supported", __func__);
3266         }
3267     } else if (audio_extn_compr_cap_enabled() &&
3268             audio_extn_compr_cap_format_supported(config->format) &&
3269             (in->dev->mode != AUDIO_MODE_IN_COMMUNICATION)) {
3270         audio_extn_compr_cap_init(in);
3271     } else {
3272         in->config.channels = channel_count;
3273         frame_size = audio_stream_in_frame_size(&in->stream);
3274         buffer_size = get_input_buffer_size(config->sample_rate,
3275                                             config->format,
3276                                             channel_count,
3277                                             is_low_latency);
3278         in->config.period_size = buffer_size / frame_size;
3279     }
3280 
3281     /* This stream could be for sound trigger lab,
3282        get sound trigger pcm if present */
3283     audio_extn_sound_trigger_check_and_get_session(in);
3284     audio_extn_perf_lock_init();
3285 
3286     *stream_in = &in->stream;
3287     ALOGV("%s: exit", __func__);
3288     return ret;
3289 
3290 err_open:
3291     free(in);
3292     *stream_in = NULL;
3293     return ret;
3294 }
3295 
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream)3296 static void adev_close_input_stream(struct audio_hw_device *dev,
3297                                     struct audio_stream_in *stream)
3298 {
3299     int ret;
3300     struct stream_in *in = (struct stream_in *)stream;
3301     struct audio_device *adev = (struct audio_device *)dev;
3302 
3303     ALOGD("%s: enter:stream_handle(%p)",__func__, in);
3304 
3305     /* Disable echo reference while closing input stream */
3306     platform_set_echo_reference(adev->platform, false);
3307 
3308     if (in->usecase == USECASE_COMPRESS_VOIP_CALL) {
3309         pthread_mutex_lock(&adev->lock);
3310         ret = voice_extn_compress_voip_close_input_stream(&stream->common);
3311         pthread_mutex_unlock(&adev->lock);
3312         if (ret != 0)
3313             ALOGE("%s: Compress voip input cannot be closed, error:%d",
3314                   __func__, ret);
3315     } else
3316         in_standby(&stream->common);
3317 
3318     if (audio_extn_ssr_get_enabled() &&
3319             (audio_channel_count_from_in_mask(in->channel_mask) == 6)) {
3320         audio_extn_ssr_deinit();
3321     }
3322 
3323     if(audio_extn_compr_cap_enabled() &&
3324             audio_extn_compr_cap_format_supported(in->config.format))
3325         audio_extn_compr_cap_deinit();
3326 
3327     free(stream);
3328     return;
3329 }
3330 
adev_dump(const audio_hw_device_t * device __unused,int fd __unused)3331 static int adev_dump(const audio_hw_device_t *device __unused,
3332                      int fd __unused)
3333 {
3334     return 0;
3335 }
3336 
adev_close(hw_device_t * device)3337 static int adev_close(hw_device_t *device)
3338 {
3339     struct audio_device *adev = (struct audio_device *)device;
3340 
3341     if (!adev)
3342         return 0;
3343 
3344     pthread_mutex_lock(&adev_init_lock);
3345 
3346     if ((--audio_device_ref_count) == 0) {
3347         audio_extn_sound_trigger_deinit(adev);
3348         audio_extn_listen_deinit(adev);
3349         audio_extn_utils_release_streams_output_cfg_list(&adev->streams_output_cfg_list);
3350         audio_route_free(adev->audio_route);
3351         free(adev->snd_dev_ref_cnt);
3352         platform_deinit(adev->platform);
3353         free(device);
3354         adev = NULL;
3355     }
3356     pthread_mutex_unlock(&adev_init_lock);
3357     return 0;
3358 }
3359 
3360 /* This returns 1 if the input parameter looks at all plausible as a low latency period size,
3361  * or 0 otherwise.  A return value of 1 doesn't mean the value is guaranteed to work,
3362  * just that it _might_ work.
3363  */
period_size_is_plausible_for_low_latency(int period_size)3364 static int period_size_is_plausible_for_low_latency(int period_size)
3365 {
3366     switch (period_size) {
3367     case 160:
3368     case 240:
3369     case 320:
3370     case 480:
3371         return 1;
3372     default:
3373         return 0;
3374     }
3375 }
3376 
adev_open(const hw_module_t * module,const char * name,hw_device_t ** device)3377 static int adev_open(const hw_module_t *module, const char *name,
3378                      hw_device_t **device)
3379 {
3380     int i, ret;
3381 
3382     ALOGD("%s: enter", __func__);
3383     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
3384 
3385     pthread_mutex_lock(&adev_init_lock);
3386     if (audio_device_ref_count != 0){
3387             *device = &adev->device.common;
3388             audio_device_ref_count++;
3389             ALOGD("%s: returning existing instance of adev", __func__);
3390             ALOGD("%s: exit", __func__);
3391             pthread_mutex_unlock(&adev_init_lock);
3392             return 0;
3393     }
3394 
3395     adev = calloc(1, sizeof(struct audio_device));
3396 
3397     if (!adev) {
3398         pthread_mutex_unlock(&adev_init_lock);
3399         return -ENOMEM;
3400     }
3401 
3402     pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
3403 
3404     adev->device.common.tag = HARDWARE_DEVICE_TAG;
3405     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
3406     adev->device.common.module = (struct hw_module_t *)module;
3407     adev->device.common.close = adev_close;
3408 
3409     adev->device.init_check = adev_init_check;
3410     adev->device.set_voice_volume = adev_set_voice_volume;
3411     adev->device.set_master_volume = adev_set_master_volume;
3412     adev->device.get_master_volume = adev_get_master_volume;
3413     adev->device.set_master_mute = adev_set_master_mute;
3414     adev->device.get_master_mute = adev_get_master_mute;
3415     adev->device.set_mode = adev_set_mode;
3416     adev->device.set_mic_mute = adev_set_mic_mute;
3417     adev->device.get_mic_mute = adev_get_mic_mute;
3418     adev->device.set_parameters = adev_set_parameters;
3419     adev->device.get_parameters = adev_get_parameters;
3420     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
3421     adev->device.open_output_stream = adev_open_output_stream;
3422     adev->device.close_output_stream = adev_close_output_stream;
3423     adev->device.open_input_stream = adev_open_input_stream;
3424     adev->device.close_input_stream = adev_close_input_stream;
3425     adev->device.dump = adev_dump;
3426 
3427     /* Set the default route before the PCM stream is opened */
3428     adev->mode = AUDIO_MODE_NORMAL;
3429     adev->active_input = NULL;
3430     adev->primary_output = NULL;
3431     adev->out_device = AUDIO_DEVICE_NONE;
3432     adev->bluetooth_nrec = true;
3433     adev->acdb_settings = TTY_MODE_OFF;
3434     /* adev->cur_hdmi_channels = 0;  by calloc() */
3435     adev->cur_codec_backend_samplerate = CODEC_BACKEND_DEFAULT_SAMPLE_RATE;
3436     adev->cur_codec_backend_bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH;
3437     adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
3438     voice_init(adev);
3439     list_init(&adev->usecase_list);
3440     adev->cur_wfd_channels = 2;
3441     adev->offload_usecases_state = 0;
3442 
3443     pthread_mutex_init(&adev->snd_card_status.lock, (const pthread_mutexattr_t *) NULL);
3444     adev->snd_card_status.state = SND_CARD_STATE_OFFLINE;
3445     /* Loads platform specific libraries dynamically */
3446     adev->platform = platform_init(adev);
3447     if (!adev->platform) {
3448         free(adev->snd_dev_ref_cnt);
3449         free(adev);
3450         ALOGE("%s: Failed to init platform data, aborting.", __func__);
3451         *device = NULL;
3452         pthread_mutex_unlock(&adev_init_lock);
3453         return -EINVAL;
3454     }
3455 
3456     adev->snd_card_status.state = SND_CARD_STATE_ONLINE;
3457 
3458     if (access(VISUALIZER_LIBRARY_PATH, R_OK) == 0) {
3459         adev->visualizer_lib = dlopen(VISUALIZER_LIBRARY_PATH, RTLD_NOW);
3460         if (adev->visualizer_lib == NULL) {
3461             ALOGE("%s: DLOPEN failed for %s", __func__, VISUALIZER_LIBRARY_PATH);
3462         } else {
3463             ALOGV("%s: DLOPEN successful for %s", __func__, VISUALIZER_LIBRARY_PATH);
3464             adev->visualizer_start_output =
3465                         (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
3466                                                         "visualizer_hal_start_output");
3467             adev->visualizer_stop_output =
3468                         (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
3469                                                         "visualizer_hal_stop_output");
3470         }
3471     }
3472     audio_extn_listen_init(adev, adev->snd_card);
3473     audio_extn_sound_trigger_init(adev);
3474 
3475     if (access(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, R_OK) == 0) {
3476         adev->offload_effects_lib = dlopen(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, RTLD_NOW);
3477         if (adev->offload_effects_lib == NULL) {
3478             ALOGE("%s: DLOPEN failed for %s", __func__,
3479                   OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
3480         } else {
3481             ALOGV("%s: DLOPEN successful for %s", __func__,
3482                   OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
3483             adev->offload_effects_start_output =
3484                         (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
3485                                          "offload_effects_bundle_hal_start_output");
3486             adev->offload_effects_stop_output =
3487                         (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
3488                                          "offload_effects_bundle_hal_stop_output");
3489         }
3490     }
3491 
3492     adev->bt_wb_speech_enabled = false;
3493 
3494     audio_extn_ds2_enable(adev);
3495     *device = &adev->device.common;
3496 
3497     audio_extn_utils_update_streams_output_cfg_list(adev->platform, adev->mixer,
3498                                                     &adev->streams_output_cfg_list);
3499 
3500     audio_device_ref_count++;
3501 
3502     char value[PROPERTY_VALUE_MAX];
3503     int trial;
3504     if (property_get("audio_hal.period_size", value, NULL) > 0) {
3505         trial = atoi(value);
3506         if (period_size_is_plausible_for_low_latency(trial)) {
3507             pcm_config_low_latency.period_size = trial;
3508             pcm_config_low_latency.start_threshold = trial / 4;
3509             pcm_config_low_latency.avail_min = trial / 4;
3510             configured_low_latency_capture_period_size = trial;
3511         }
3512     }
3513     if (property_get("audio_hal.in_period_size", value, NULL) > 0) {
3514         trial = atoi(value);
3515         if (period_size_is_plausible_for_low_latency(trial)) {
3516             configured_low_latency_capture_period_size = trial;
3517         }
3518     }
3519 
3520     pthread_mutex_unlock(&adev_init_lock);
3521 
3522     ALOGV("%s: exit", __func__);
3523     return 0;
3524 }
3525 
3526 static struct hw_module_methods_t hal_module_methods = {
3527     .open = adev_open,
3528 };
3529 
3530 struct audio_module HAL_MODULE_INFO_SYM = {
3531     .common = {
3532         .tag = HARDWARE_MODULE_TAG,
3533         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
3534         .hal_api_version = HARDWARE_HAL_API_VERSION,
3535         .id = AUDIO_HARDWARE_MODULE_ID,
3536         .name = "QCOM Audio HAL",
3537         .author = "The Linux Foundation",
3538         .methods = &hal_module_methods,
3539     },
3540 };
3541