audio_hw.c revision 83281a951af159ca00517f6132fab39727b293f5
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "audio_hw_primary"
18/*#define LOG_NDEBUG 0*/
19/*#define VERY_VERY_VERBOSE_LOGGING*/
20#ifdef VERY_VERY_VERBOSE_LOGGING
21#define ALOGVV ALOGV
22#else
23#define ALOGVV(a...) do { } while(0)
24#endif
25
26#include <errno.h>
27#include <pthread.h>
28#include <stdint.h>
29#include <sys/time.h>
30#include <stdlib.h>
31#include <math.h>
32#include <dlfcn.h>
33#include <sys/resource.h>
34#include <sys/prctl.h>
35
36#include <cutils/log.h>
37#include <cutils/str_parms.h>
38#include <cutils/properties.h>
39#include <cutils/atomic.h>
40#include <cutils/sched_policy.h>
41
42#include <hardware/audio_effect.h>
43#include <hardware/audio_alsaops.h>
44#include <system/thread_defs.h>
45#include <audio_effects/effect_aec.h>
46#include <audio_effects/effect_ns.h>
47#include "audio_hw.h"
48#include "platform_api.h"
49#include <platform.h>
50
51#include "sound/compress_params.h"
52
53#define COMPRESS_OFFLOAD_FRAGMENT_SIZE (32 * 1024)
54#define COMPRESS_OFFLOAD_NUM_FRAGMENTS 4
55/* ToDo: Check and update a proper value in msec */
56#define COMPRESS_OFFLOAD_PLAYBACK_LATENCY 96
57#define COMPRESS_PLAYBACK_VOLUME_MAX 0x2000
58
59/* This constant enables extended precision handling.
60 * TODO The flag is off until more testing is done.
61 */
62static const bool k_enable_extended_precision = false;
63
64struct pcm_config pcm_config_deep_buffer = {
65    .channels = 2,
66    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
67    .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
68    .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
69    .format = PCM_FORMAT_S16_LE,
70    .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
71    .stop_threshold = INT_MAX,
72    .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
73};
74
75struct pcm_config pcm_config_low_latency = {
76    .channels = 2,
77    .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
78    .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
79    .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
80    .format = PCM_FORMAT_S16_LE,
81    .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
82    .stop_threshold = INT_MAX,
83    .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
84};
85
86struct pcm_config pcm_config_hdmi_multi = {
87    .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
88    .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
89    .period_size = HDMI_MULTI_PERIOD_SIZE,
90    .period_count = HDMI_MULTI_PERIOD_COUNT,
91    .format = PCM_FORMAT_S16_LE,
92    .start_threshold = 0,
93    .stop_threshold = INT_MAX,
94    .avail_min = 0,
95};
96
97struct pcm_config pcm_config_audio_capture = {
98    .channels = 2,
99    .period_count = AUDIO_CAPTURE_PERIOD_COUNT,
100    .format = PCM_FORMAT_S16_LE,
101};
102
103struct pcm_config pcm_config_voice_call = {
104    .channels = 1,
105    .rate = 8000,
106    .period_size = 160,
107    .period_count = 2,
108    .format = PCM_FORMAT_S16_LE,
109};
110
111static const char * const use_case_table[AUDIO_USECASE_MAX] = {
112    [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = "deep-buffer-playback",
113    [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = "low-latency-playback",
114    [USECASE_AUDIO_PLAYBACK_MULTI_CH] = "multi-channel-playback",
115    [USECASE_AUDIO_RECORD] = "audio-record",
116    [USECASE_AUDIO_RECORD_LOW_LATENCY] = "low-latency-record",
117    [USECASE_VOICE_CALL] = "voice-call",
118    [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
119};
120
121
122#define STRING_TO_ENUM(string) { #string, string }
123
124struct string_to_enum {
125    const char *name;
126    uint32_t value;
127};
128
129static const struct string_to_enum out_channels_name_to_enum_table[] = {
130    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
131    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
132    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
133};
134
135static int set_voice_volume_l(struct audio_device *adev, float volume);
136
137static bool is_supported_format(audio_format_t format)
138{
139    if (format == AUDIO_FORMAT_MP3 ||
140            format == AUDIO_FORMAT_AAC)
141        return true;
142
143    return false;
144}
145
146static int get_snd_codec_id(audio_format_t format)
147{
148    int id = 0;
149
150    switch (format) {
151    case AUDIO_FORMAT_MP3:
152        id = SND_AUDIOCODEC_MP3;
153        break;
154    case AUDIO_FORMAT_AAC:
155        id = SND_AUDIOCODEC_AAC;
156        break;
157    default:
158        ALOGE("%s: Unsupported audio format", __func__);
159    }
160
161    return id;
162}
163
164static int enable_audio_route(struct audio_device *adev,
165                              struct audio_usecase *usecase)
166{
167    snd_device_t snd_device;
168    char mixer_path[50];
169
170    if (usecase == NULL)
171        return -EINVAL;
172
173    ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
174
175    if (usecase->type == PCM_CAPTURE)
176        snd_device = usecase->in_snd_device;
177    else
178        snd_device = usecase->out_snd_device;
179
180    strcpy(mixer_path, use_case_table[usecase->id]);
181    platform_add_backend_name(mixer_path, snd_device);
182    ALOGV("%s: apply and update mixer path: %s", __func__, mixer_path);
183    audio_route_apply_and_update_path(adev->audio_route, mixer_path);
184
185    ALOGV("%s: exit", __func__);
186    return 0;
187}
188
189static int disable_audio_route(struct audio_device *adev,
190                               struct audio_usecase *usecase)
191{
192    snd_device_t snd_device;
193    char mixer_path[50];
194
195    if (usecase == NULL)
196        return -EINVAL;
197
198    ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
199    if (usecase->type == PCM_CAPTURE)
200        snd_device = usecase->in_snd_device;
201    else
202        snd_device = usecase->out_snd_device;
203    strcpy(mixer_path, use_case_table[usecase->id]);
204    platform_add_backend_name(mixer_path, snd_device);
205    ALOGV("%s: reset and update mixer path: %s", __func__, mixer_path);
206    audio_route_reset_and_update_path(adev->audio_route, mixer_path);
207
208    ALOGV("%s: exit", __func__);
209    return 0;
210}
211
212static int enable_snd_device(struct audio_device *adev,
213                             snd_device_t snd_device)
214{
215    if (snd_device < SND_DEVICE_MIN ||
216        snd_device >= SND_DEVICE_MAX) {
217        ALOGE("%s: Invalid sound device %d", __func__, snd_device);
218        return -EINVAL;
219    }
220
221    adev->snd_dev_ref_cnt[snd_device]++;
222    if (adev->snd_dev_ref_cnt[snd_device] > 1) {
223        ALOGV("%s: snd_device(%d: %s) is already active",
224              __func__, snd_device, platform_get_snd_device_name(snd_device));
225        return 0;
226    }
227
228    if (platform_send_audio_calibration(adev->platform, snd_device) < 0) {
229        adev->snd_dev_ref_cnt[snd_device]--;
230        return -EINVAL;
231    }
232
233    const char * dev_path = platform_get_snd_device_name(snd_device);
234    ALOGV("%s: snd_device(%d: %s)", __func__, snd_device, dev_path);
235    audio_route_apply_and_update_path(adev->audio_route, dev_path);
236
237    return 0;
238}
239
240static int disable_snd_device(struct audio_device *adev,
241                              snd_device_t snd_device)
242{
243    if (snd_device < SND_DEVICE_MIN ||
244        snd_device >= SND_DEVICE_MAX) {
245        ALOGE("%s: Invalid sound device %d", __func__, snd_device);
246        return -EINVAL;
247    }
248    if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
249        ALOGE("%s: device ref cnt is already 0", __func__);
250        return -EINVAL;
251    }
252    adev->snd_dev_ref_cnt[snd_device]--;
253    if (adev->snd_dev_ref_cnt[snd_device] == 0) {
254        const char * dev_path = platform_get_snd_device_name(snd_device);
255        ALOGV("%s: snd_device(%d: %s)", __func__,
256              snd_device, dev_path);
257        audio_route_reset_and_update_path(adev->audio_route, dev_path);
258    }
259    return 0;
260}
261
262static void check_usecases_codec_backend(struct audio_device *adev,
263                                          struct audio_usecase *uc_info,
264                                          snd_device_t snd_device)
265{
266    struct listnode *node;
267    struct audio_usecase *usecase;
268    bool switch_device[AUDIO_USECASE_MAX];
269    int i, num_uc_to_switch = 0;
270
271    /*
272     * This function is to make sure that all the usecases that are active on
273     * the hardware codec backend are always routed to any one device that is
274     * handled by the hardware codec.
275     * For example, if low-latency and deep-buffer usecases are currently active
276     * on speaker and out_set_parameters(headset) is received on low-latency
277     * output, then we have to make sure deep-buffer is also switched to headset,
278     * because of the limitation that both the devices cannot be enabled
279     * at the same time as they share the same backend.
280     */
281    /* Disable all the usecases on the shared backend other than the
282       specified usecase */
283    for (i = 0; i < AUDIO_USECASE_MAX; i++)
284        switch_device[i] = false;
285
286    list_for_each(node, &adev->usecase_list) {
287        usecase = node_to_item(node, struct audio_usecase, list);
288        if (usecase->type != PCM_CAPTURE &&
289                usecase != uc_info &&
290                usecase->out_snd_device != snd_device &&
291                usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
292            ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
293                  __func__, use_case_table[usecase->id],
294                  platform_get_snd_device_name(usecase->out_snd_device));
295            disable_audio_route(adev, usecase);
296            switch_device[usecase->id] = true;
297            num_uc_to_switch++;
298        }
299    }
300
301    if (num_uc_to_switch) {
302        list_for_each(node, &adev->usecase_list) {
303            usecase = node_to_item(node, struct audio_usecase, list);
304            if (switch_device[usecase->id]) {
305                disable_snd_device(adev, usecase->out_snd_device);
306            }
307        }
308
309        list_for_each(node, &adev->usecase_list) {
310            usecase = node_to_item(node, struct audio_usecase, list);
311            if (switch_device[usecase->id]) {
312                enable_snd_device(adev, snd_device);
313            }
314        }
315
316        /* Re-route all the usecases on the shared backend other than the
317           specified usecase to new snd devices */
318        list_for_each(node, &adev->usecase_list) {
319            usecase = node_to_item(node, struct audio_usecase, list);
320            /* Update the out_snd_device only before enabling the audio route */
321            if (switch_device[usecase->id] ) {
322                usecase->out_snd_device = snd_device;
323                enable_audio_route(adev, usecase);
324            }
325        }
326    }
327}
328
329static void check_and_route_capture_usecases(struct audio_device *adev,
330                                             struct audio_usecase *uc_info,
331                                             snd_device_t snd_device)
332{
333    struct listnode *node;
334    struct audio_usecase *usecase;
335    bool switch_device[AUDIO_USECASE_MAX];
336    int i, num_uc_to_switch = 0;
337
338    /*
339     * This function is to make sure that all the active capture usecases
340     * are always routed to the same input sound device.
341     * For example, if audio-record and voice-call usecases are currently
342     * active on speaker(rx) and speaker-mic (tx) and out_set_parameters(earpiece)
343     * is received for voice call then we have to make sure that audio-record
344     * usecase is also switched to earpiece i.e. voice-dmic-ef,
345     * because of the limitation that two devices cannot be enabled
346     * at the same time if they share the same backend.
347     */
348    for (i = 0; i < AUDIO_USECASE_MAX; i++)
349        switch_device[i] = false;
350
351    list_for_each(node, &adev->usecase_list) {
352        usecase = node_to_item(node, struct audio_usecase, list);
353        if (usecase->type != PCM_PLAYBACK &&
354                usecase != uc_info &&
355                usecase->in_snd_device != snd_device) {
356            ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
357                  __func__, use_case_table[usecase->id],
358                  platform_get_snd_device_name(usecase->in_snd_device));
359            disable_audio_route(adev, usecase);
360            switch_device[usecase->id] = true;
361            num_uc_to_switch++;
362        }
363    }
364
365    if (num_uc_to_switch) {
366        list_for_each(node, &adev->usecase_list) {
367            usecase = node_to_item(node, struct audio_usecase, list);
368            if (switch_device[usecase->id]) {
369                disable_snd_device(adev, usecase->in_snd_device);
370                enable_snd_device(adev, snd_device);
371            }
372        }
373
374        /* Re-route all the usecases on the shared backend other than the
375           specified usecase to new snd devices */
376        list_for_each(node, &adev->usecase_list) {
377            usecase = node_to_item(node, struct audio_usecase, list);
378            /* Update the in_snd_device only before enabling the audio route */
379            if (switch_device[usecase->id] ) {
380                usecase->in_snd_device = snd_device;
381                enable_audio_route(adev, usecase);
382            }
383        }
384    }
385}
386
387
388/* must be called with hw device mutex locked */
389static int read_hdmi_channel_masks(struct stream_out *out)
390{
391    int ret = 0;
392    int channels = platform_edid_get_max_channels(out->dev->platform);
393
394    switch (channels) {
395        /*
396         * Do not handle stereo output in Multi-channel cases
397         * Stereo case is handled in normal playback path
398         */
399    case 6:
400        ALOGV("%s: HDMI supports 5.1", __func__);
401        out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
402        break;
403    case 8:
404        ALOGV("%s: HDMI supports 5.1 and 7.1 channels", __func__);
405        out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
406        out->supported_channel_masks[1] = AUDIO_CHANNEL_OUT_7POINT1;
407        break;
408    default:
409        ALOGE("HDMI does not support multi channel playback");
410        ret = -ENOSYS;
411        break;
412    }
413    return ret;
414}
415
416static struct audio_usecase *get_usecase_from_list(struct audio_device *adev,
417                                                   audio_usecase_t uc_id)
418{
419    struct audio_usecase *usecase;
420    struct listnode *node;
421
422    list_for_each(node, &adev->usecase_list) {
423        usecase = node_to_item(node, struct audio_usecase, list);
424        if (usecase->id == uc_id)
425            return usecase;
426    }
427    return NULL;
428}
429
430static int select_devices(struct audio_device *adev,
431                          audio_usecase_t uc_id)
432{
433    snd_device_t out_snd_device = SND_DEVICE_NONE;
434    snd_device_t in_snd_device = SND_DEVICE_NONE;
435    struct audio_usecase *usecase = NULL;
436    struct audio_usecase *vc_usecase = NULL;
437    struct listnode *node;
438    int status = 0;
439
440    usecase = get_usecase_from_list(adev, uc_id);
441    if (usecase == NULL) {
442        ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
443        return -EINVAL;
444    }
445
446    if (usecase->type == VOICE_CALL) {
447        out_snd_device = platform_get_output_snd_device(adev->platform,
448                                                        usecase->stream.out->devices);
449        in_snd_device = platform_get_input_snd_device(adev->platform, usecase->stream.out->devices);
450        usecase->devices = usecase->stream.out->devices;
451    } else {
452        /*
453         * If the voice call is active, use the sound devices of voice call usecase
454         * so that it would not result any device switch. All the usecases will
455         * be switched to new device when select_devices() is called for voice call
456         * usecase. This is to avoid switching devices for voice call when
457         * check_usecases_codec_backend() is called below.
458         */
459        if (adev->in_call) {
460            vc_usecase = get_usecase_from_list(adev, USECASE_VOICE_CALL);
461            if (vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
462                in_snd_device = vc_usecase->in_snd_device;
463                out_snd_device = vc_usecase->out_snd_device;
464            }
465        }
466        if (usecase->type == PCM_PLAYBACK) {
467            usecase->devices = usecase->stream.out->devices;
468            in_snd_device = SND_DEVICE_NONE;
469            if (out_snd_device == SND_DEVICE_NONE) {
470                out_snd_device = platform_get_output_snd_device(adev->platform,
471                                            usecase->stream.out->devices);
472                if (usecase->stream.out == adev->primary_output &&
473                        adev->active_input &&
474                        adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
475                    select_devices(adev, adev->active_input->usecase);
476                }
477            }
478        } else if (usecase->type == PCM_CAPTURE) {
479            usecase->devices = usecase->stream.in->device;
480            out_snd_device = SND_DEVICE_NONE;
481            if (in_snd_device == SND_DEVICE_NONE) {
482                if (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
483                        adev->primary_output && !adev->primary_output->standby) {
484                    in_snd_device = platform_get_input_snd_device(adev->platform,
485                                        adev->primary_output->devices);
486                } else {
487                    in_snd_device = platform_get_input_snd_device(adev->platform,
488                                                                  AUDIO_DEVICE_NONE);
489                }
490            }
491        }
492    }
493
494    if (out_snd_device == usecase->out_snd_device &&
495        in_snd_device == usecase->in_snd_device) {
496        return 0;
497    }
498
499    ALOGD("%s: out_snd_device(%d: %s) in_snd_device(%d: %s)", __func__,
500          out_snd_device, platform_get_snd_device_name(out_snd_device),
501          in_snd_device,  platform_get_snd_device_name(in_snd_device));
502
503    /*
504     * Limitation: While in call, to do a device switch we need to disable
505     * and enable both RX and TX devices though one of them is same as current
506     * device.
507     */
508    if (usecase->type == VOICE_CALL) {
509        status = platform_switch_voice_call_device_pre(adev->platform);
510    }
511
512    /* Disable current sound devices */
513    if (usecase->out_snd_device != SND_DEVICE_NONE) {
514        disable_audio_route(adev, usecase);
515        disable_snd_device(adev, usecase->out_snd_device);
516    }
517
518    if (usecase->in_snd_device != SND_DEVICE_NONE) {
519        disable_audio_route(adev, usecase);
520        disable_snd_device(adev, usecase->in_snd_device);
521    }
522
523    /* Applicable only on the targets that has external modem.
524     * New device information should be sent to modem before enabling
525     * the devices to reduce in-call device switch time.
526     */
527    if (usecase->type == VOICE_CALL)
528        status = platform_switch_voice_call_enable_device_config(adev->platform,
529                                                                 out_snd_device,
530                                                                 in_snd_device);
531
532    /* Enable new sound devices */
533    if (out_snd_device != SND_DEVICE_NONE) {
534        if (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND)
535            check_usecases_codec_backend(adev, usecase, out_snd_device);
536        enable_snd_device(adev, out_snd_device);
537    }
538
539    if (in_snd_device != SND_DEVICE_NONE) {
540        check_and_route_capture_usecases(adev, usecase, in_snd_device);
541        enable_snd_device(adev, in_snd_device);
542    }
543
544    if (usecase->type == VOICE_CALL)
545        status = platform_switch_voice_call_device_post(adev->platform,
546                                                        out_snd_device,
547                                                        in_snd_device);
548
549    usecase->in_snd_device = in_snd_device;
550    usecase->out_snd_device = out_snd_device;
551
552    enable_audio_route(adev, usecase);
553
554    /* Applicable only on the targets that has external modem.
555     * Enable device command should be sent to modem only after
556     * enabling voice call mixer controls
557     */
558    if (usecase->type == VOICE_CALL)
559        status = platform_switch_voice_call_usecase_route_post(adev->platform,
560                                                               out_snd_device,
561                                                               in_snd_device);
562
563    return status;
564}
565
566static int stop_input_stream(struct stream_in *in)
567{
568    int i, ret = 0;
569    struct audio_usecase *uc_info;
570    struct audio_device *adev = in->dev;
571
572    adev->active_input = NULL;
573
574    ALOGV("%s: enter: usecase(%d: %s)", __func__,
575          in->usecase, use_case_table[in->usecase]);
576    uc_info = get_usecase_from_list(adev, in->usecase);
577    if (uc_info == NULL) {
578        ALOGE("%s: Could not find the usecase (%d) in the list",
579              __func__, in->usecase);
580        return -EINVAL;
581    }
582
583    /* 1. Disable stream specific mixer controls */
584    disable_audio_route(adev, uc_info);
585
586    /* 2. Disable the tx device */
587    disable_snd_device(adev, uc_info->in_snd_device);
588
589    list_remove(&uc_info->list);
590    free(uc_info);
591
592    ALOGV("%s: exit: status(%d)", __func__, ret);
593    return ret;
594}
595
596int start_input_stream(struct stream_in *in)
597{
598    /* 1. Enable output device and stream routing controls */
599    int ret = 0;
600    struct audio_usecase *uc_info;
601    struct audio_device *adev = in->dev;
602
603    ALOGV("%s: enter: usecase(%d)", __func__, in->usecase);
604    in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
605    if (in->pcm_device_id < 0) {
606        ALOGE("%s: Could not find PCM device id for the usecase(%d)",
607              __func__, in->usecase);
608        ret = -EINVAL;
609        goto error_config;
610    }
611
612    adev->active_input = in;
613    uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
614    uc_info->id = in->usecase;
615    uc_info->type = PCM_CAPTURE;
616    uc_info->stream.in = in;
617    uc_info->devices = in->device;
618    uc_info->in_snd_device = SND_DEVICE_NONE;
619    uc_info->out_snd_device = SND_DEVICE_NONE;
620
621    list_add_tail(&adev->usecase_list, &uc_info->list);
622    select_devices(adev, in->usecase);
623
624    ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
625          __func__, SOUND_CARD, in->pcm_device_id, in->config.channels);
626    in->pcm = pcm_open(SOUND_CARD, in->pcm_device_id,
627                           PCM_IN, &in->config);
628    if (in->pcm && !pcm_is_ready(in->pcm)) {
629        ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
630        pcm_close(in->pcm);
631        in->pcm = NULL;
632        ret = -EIO;
633        goto error_open;
634    }
635    ALOGV("%s: exit", __func__);
636    return ret;
637
638error_open:
639    stop_input_stream(in);
640
641error_config:
642    adev->active_input = NULL;
643    ALOGD("%s: exit: status(%d)", __func__, ret);
644
645    return ret;
646}
647
648/* must be called with out->lock locked */
649static int send_offload_cmd_l(struct stream_out* out, int command)
650{
651    struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));
652
653    ALOGVV("%s %d", __func__, command);
654
655    cmd->cmd = command;
656    list_add_tail(&out->offload_cmd_list, &cmd->node);
657    pthread_cond_signal(&out->offload_cond);
658    return 0;
659}
660
661/* must be called iwth out->lock locked */
662static void stop_compressed_output_l(struct stream_out *out)
663{
664    out->offload_state = OFFLOAD_STATE_IDLE;
665    out->playback_started = 0;
666    out->send_new_metadata = 1;
667    if (out->compr != NULL) {
668        compress_stop(out->compr);
669        while (out->offload_thread_blocked) {
670            pthread_cond_wait(&out->cond, &out->lock);
671        }
672    }
673}
674
675static void *offload_thread_loop(void *context)
676{
677    struct stream_out *out = (struct stream_out *) context;
678    struct listnode *item;
679
680    out->offload_state = OFFLOAD_STATE_IDLE;
681    out->playback_started = 0;
682
683    setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
684    set_sched_policy(0, SP_FOREGROUND);
685    prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);
686
687    ALOGV("%s", __func__);
688    pthread_mutex_lock(&out->lock);
689    for (;;) {
690        struct offload_cmd *cmd = NULL;
691        stream_callback_event_t event;
692        bool send_callback = false;
693
694        ALOGVV("%s offload_cmd_list %d out->offload_state %d",
695              __func__, list_empty(&out->offload_cmd_list),
696              out->offload_state);
697        if (list_empty(&out->offload_cmd_list)) {
698            ALOGV("%s SLEEPING", __func__);
699            pthread_cond_wait(&out->offload_cond, &out->lock);
700            ALOGV("%s RUNNING", __func__);
701            continue;
702        }
703
704        item = list_head(&out->offload_cmd_list);
705        cmd = node_to_item(item, struct offload_cmd, node);
706        list_remove(item);
707
708        ALOGVV("%s STATE %d CMD %d out->compr %p",
709               __func__, out->offload_state, cmd->cmd, out->compr);
710
711        if (cmd->cmd == OFFLOAD_CMD_EXIT) {
712            free(cmd);
713            break;
714        }
715
716        if (out->compr == NULL) {
717            ALOGE("%s: Compress handle is NULL", __func__);
718            pthread_cond_signal(&out->cond);
719            continue;
720        }
721        out->offload_thread_blocked = true;
722        pthread_mutex_unlock(&out->lock);
723        send_callback = false;
724        switch(cmd->cmd) {
725        case OFFLOAD_CMD_WAIT_FOR_BUFFER:
726            compress_wait(out->compr, -1);
727            send_callback = true;
728            event = STREAM_CBK_EVENT_WRITE_READY;
729            break;
730        case OFFLOAD_CMD_PARTIAL_DRAIN:
731            compress_next_track(out->compr);
732            compress_partial_drain(out->compr);
733            send_callback = true;
734            event = STREAM_CBK_EVENT_DRAIN_READY;
735            break;
736        case OFFLOAD_CMD_DRAIN:
737            compress_drain(out->compr);
738            send_callback = true;
739            event = STREAM_CBK_EVENT_DRAIN_READY;
740            break;
741        default:
742            ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
743            break;
744        }
745        pthread_mutex_lock(&out->lock);
746        out->offload_thread_blocked = false;
747        pthread_cond_signal(&out->cond);
748        if (send_callback) {
749            out->offload_callback(event, NULL, out->offload_cookie);
750        }
751        free(cmd);
752    }
753
754    pthread_cond_signal(&out->cond);
755    while (!list_empty(&out->offload_cmd_list)) {
756        item = list_head(&out->offload_cmd_list);
757        list_remove(item);
758        free(node_to_item(item, struct offload_cmd, node));
759    }
760    pthread_mutex_unlock(&out->lock);
761
762    return NULL;
763}
764
765static int create_offload_callback_thread(struct stream_out *out)
766{
767    pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
768    list_init(&out->offload_cmd_list);
769    pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
770                    offload_thread_loop, out);
771    return 0;
772}
773
774static int destroy_offload_callback_thread(struct stream_out *out)
775{
776    pthread_mutex_lock(&out->lock);
777    stop_compressed_output_l(out);
778    send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);
779
780    pthread_mutex_unlock(&out->lock);
781    pthread_join(out->offload_thread, (void **) NULL);
782    pthread_cond_destroy(&out->offload_cond);
783
784    return 0;
785}
786
787static bool allow_hdmi_channel_config(struct audio_device *adev)
788{
789    struct listnode *node;
790    struct audio_usecase *usecase;
791    bool ret = true;
792
793    list_for_each(node, &adev->usecase_list) {
794        usecase = node_to_item(node, struct audio_usecase, list);
795        if (usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
796            /*
797             * If voice call is already existing, do not proceed further to avoid
798             * disabling/enabling both RX and TX devices, CSD calls, etc.
799             * Once the voice call done, the HDMI channels can be configured to
800             * max channels of remaining use cases.
801             */
802            if (usecase->id == USECASE_VOICE_CALL) {
803                ALOGD("%s: voice call is active, no change in HDMI channels",
804                      __func__);
805                ret = false;
806                break;
807            } else if (usecase->id == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
808                ALOGD("%s: multi channel playback is active, "
809                      "no change in HDMI channels", __func__);
810                ret = false;
811                break;
812            }
813        }
814    }
815    return ret;
816}
817
818static int check_and_set_hdmi_channels(struct audio_device *adev,
819                                       unsigned int channels)
820{
821    struct listnode *node;
822    struct audio_usecase *usecase;
823
824    /* Check if change in HDMI channel config is allowed */
825    if (!allow_hdmi_channel_config(adev))
826        return 0;
827
828    if (channels == adev->cur_hdmi_channels) {
829        ALOGD("%s: Requested channels are same as current", __func__);
830        return 0;
831    }
832
833    platform_set_hdmi_channels(adev->platform, channels);
834    adev->cur_hdmi_channels = channels;
835
836    /*
837     * Deroute all the playback streams routed to HDMI so that
838     * the back end is deactivated. Note that backend will not
839     * be deactivated if any one stream is connected to it.
840     */
841    list_for_each(node, &adev->usecase_list) {
842        usecase = node_to_item(node, struct audio_usecase, list);
843        if (usecase->type == PCM_PLAYBACK &&
844                usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
845            disable_audio_route(adev, usecase);
846        }
847    }
848
849    /*
850     * Enable all the streams disabled above. Now the HDMI backend
851     * will be activated with new channel configuration
852     */
853    list_for_each(node, &adev->usecase_list) {
854        usecase = node_to_item(node, struct audio_usecase, list);
855        if (usecase->type == PCM_PLAYBACK &&
856                usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
857            enable_audio_route(adev, usecase);
858        }
859    }
860
861    return 0;
862}
863
864static int stop_output_stream(struct stream_out *out)
865{
866    int i, ret = 0;
867    struct audio_usecase *uc_info;
868    struct audio_device *adev = out->dev;
869
870    ALOGV("%s: enter: usecase(%d: %s)", __func__,
871          out->usecase, use_case_table[out->usecase]);
872    uc_info = get_usecase_from_list(adev, out->usecase);
873    if (uc_info == NULL) {
874        ALOGE("%s: Could not find the usecase (%d) in the list",
875              __func__, out->usecase);
876        return -EINVAL;
877    }
878
879    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD &&
880            adev->visualizer_stop_output != NULL)
881        adev->visualizer_stop_output(out->handle);
882
883    /* 1. Get and set stream specific mixer controls */
884    disable_audio_route(adev, uc_info);
885
886    /* 2. Disable the rx device */
887    disable_snd_device(adev, uc_info->out_snd_device);
888
889    list_remove(&uc_info->list);
890    free(uc_info);
891
892    /* Must be called after removing the usecase from list */
893    if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
894        check_and_set_hdmi_channels(adev, DEFAULT_HDMI_OUT_CHANNELS);
895
896    ALOGV("%s: exit: status(%d)", __func__, ret);
897    return ret;
898}
899
900int start_output_stream(struct stream_out *out)
901{
902    int ret = 0;
903    struct audio_usecase *uc_info;
904    struct audio_device *adev = out->dev;
905
906    ALOGV("%s: enter: usecase(%d: %s) devices(%#x)",
907          __func__, out->usecase, use_case_table[out->usecase], out->devices);
908    out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
909    if (out->pcm_device_id < 0) {
910        ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
911              __func__, out->pcm_device_id, out->usecase);
912        ret = -EINVAL;
913        goto error_config;
914    }
915
916    uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
917    uc_info->id = out->usecase;
918    uc_info->type = PCM_PLAYBACK;
919    uc_info->stream.out = out;
920    uc_info->devices = out->devices;
921    uc_info->in_snd_device = SND_DEVICE_NONE;
922    uc_info->out_snd_device = SND_DEVICE_NONE;
923
924    /* This must be called before adding this usecase to the list */
925    if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
926        check_and_set_hdmi_channels(adev, out->config.channels);
927
928    list_add_tail(&adev->usecase_list, &uc_info->list);
929
930    select_devices(adev, out->usecase);
931
932    ALOGV("%s: Opening PCM device card_id(%d) device_id(%d) format(%#x)",
933          __func__, SOUND_CARD, out->pcm_device_id, out->config.format);
934    if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
935        out->pcm = pcm_open(SOUND_CARD, out->pcm_device_id,
936                               PCM_OUT | PCM_MONOTONIC, &out->config);
937        if (out->pcm && !pcm_is_ready(out->pcm)) {
938            ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
939            pcm_close(out->pcm);
940            out->pcm = NULL;
941            ret = -EIO;
942            goto error_open;
943        }
944    } else {
945        out->pcm = NULL;
946        out->compr = compress_open(SOUND_CARD, out->pcm_device_id,
947                                   COMPRESS_IN, &out->compr_config);
948        if (out->compr && !is_compress_ready(out->compr)) {
949            ALOGE("%s: %s", __func__, compress_get_error(out->compr));
950            compress_close(out->compr);
951            out->compr = NULL;
952            ret = -EIO;
953            goto error_open;
954        }
955        if (out->offload_callback)
956            compress_nonblock(out->compr, out->non_blocking);
957
958        if (adev->visualizer_start_output != NULL)
959            adev->visualizer_start_output(out->handle);
960    }
961    ALOGV("%s: exit", __func__);
962    return 0;
963error_open:
964    stop_output_stream(out);
965error_config:
966    return ret;
967}
968
969static int stop_voice_call(struct audio_device *adev)
970{
971    int i, ret = 0;
972    struct audio_usecase *uc_info;
973
974    ALOGV("%s: enter", __func__);
975    adev->in_call = false;
976
977    ret = platform_stop_voice_call(adev->platform);
978
979    /* 1. Close the PCM devices */
980    if (adev->voice_call_rx) {
981        pcm_close(adev->voice_call_rx);
982        adev->voice_call_rx = NULL;
983    }
984    if (adev->voice_call_tx) {
985        pcm_close(adev->voice_call_tx);
986        adev->voice_call_tx = NULL;
987    }
988
989    uc_info = get_usecase_from_list(adev, USECASE_VOICE_CALL);
990    if (uc_info == NULL) {
991        ALOGE("%s: Could not find the usecase (%d) in the list",
992              __func__, USECASE_VOICE_CALL);
993        return -EINVAL;
994    }
995
996    /* 2. Get and set stream specific mixer controls */
997    disable_audio_route(adev, uc_info);
998
999    /* 3. Disable the rx and tx devices */
1000    disable_snd_device(adev, uc_info->out_snd_device);
1001    disable_snd_device(adev, uc_info->in_snd_device);
1002
1003    list_remove(&uc_info->list);
1004    free(uc_info);
1005
1006    ALOGV("%s: exit: status(%d)", __func__, ret);
1007    return ret;
1008}
1009
1010static int start_voice_call(struct audio_device *adev)
1011{
1012    int i, ret = 0;
1013    struct audio_usecase *uc_info;
1014    int pcm_dev_rx_id, pcm_dev_tx_id;
1015
1016    ALOGV("%s: enter", __func__);
1017
1018    uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
1019    uc_info->id = USECASE_VOICE_CALL;
1020    uc_info->type = VOICE_CALL;
1021    uc_info->stream.out = adev->primary_output;
1022    uc_info->devices = adev->primary_output->devices;
1023    uc_info->in_snd_device = SND_DEVICE_NONE;
1024    uc_info->out_snd_device = SND_DEVICE_NONE;
1025
1026    list_add_tail(&adev->usecase_list, &uc_info->list);
1027
1028    select_devices(adev, USECASE_VOICE_CALL);
1029
1030    pcm_dev_rx_id = platform_get_pcm_device_id(uc_info->id, PCM_PLAYBACK);
1031    pcm_dev_tx_id = platform_get_pcm_device_id(uc_info->id, PCM_CAPTURE);
1032
1033    if (pcm_dev_rx_id < 0 || pcm_dev_tx_id < 0) {
1034        ALOGE("%s: Invalid PCM devices (rx: %d tx: %d) for the usecase(%d)",
1035              __func__, pcm_dev_rx_id, pcm_dev_tx_id, uc_info->id);
1036        ret = -EIO;
1037        goto error_start_voice;
1038    }
1039
1040    ALOGV("%s: Opening PCM playback device card_id(%d) device_id(%d)",
1041          __func__, SOUND_CARD, pcm_dev_rx_id);
1042    adev->voice_call_rx = pcm_open(SOUND_CARD,
1043                                  pcm_dev_rx_id,
1044                                  PCM_OUT | PCM_MONOTONIC, &pcm_config_voice_call);
1045    if (adev->voice_call_rx && !pcm_is_ready(adev->voice_call_rx)) {
1046        ALOGE("%s: %s", __func__, pcm_get_error(adev->voice_call_rx));
1047        ret = -EIO;
1048        goto error_start_voice;
1049    }
1050
1051    ALOGV("%s: Opening PCM capture device card_id(%d) device_id(%d)",
1052          __func__, SOUND_CARD, pcm_dev_tx_id);
1053    adev->voice_call_tx = pcm_open(SOUND_CARD,
1054                                   pcm_dev_tx_id,
1055                                   PCM_IN, &pcm_config_voice_call);
1056    if (adev->voice_call_tx && !pcm_is_ready(adev->voice_call_tx)) {
1057        ALOGE("%s: %s", __func__, pcm_get_error(adev->voice_call_tx));
1058        ret = -EIO;
1059        goto error_start_voice;
1060    }
1061
1062    /* set cached volume */
1063    set_voice_volume_l(adev, adev->voice_volume);
1064
1065    pcm_start(adev->voice_call_rx);
1066    pcm_start(adev->voice_call_tx);
1067
1068    ret = platform_start_voice_call(adev->platform);
1069    if (ret < 0) {
1070        ALOGE("%s: platform_start_voice_call error %d\n", __func__, ret);
1071        goto error_start_voice;
1072    }
1073    adev->in_call = true;
1074    return 0;
1075
1076error_start_voice:
1077    stop_voice_call(adev);
1078
1079    ALOGD("%s: exit: status(%d)", __func__, ret);
1080    return ret;
1081}
1082
1083static int check_input_parameters(uint32_t sample_rate,
1084                                  audio_format_t format,
1085                                  int channel_count)
1086{
1087    if (format != AUDIO_FORMAT_PCM_16_BIT) return -EINVAL;
1088
1089    if ((channel_count < 1) || (channel_count > 2)) return -EINVAL;
1090
1091    switch (sample_rate) {
1092    case 8000:
1093    case 11025:
1094    case 12000:
1095    case 16000:
1096    case 22050:
1097    case 24000:
1098    case 32000:
1099    case 44100:
1100    case 48000:
1101        break;
1102    default:
1103        return -EINVAL;
1104    }
1105
1106    return 0;
1107}
1108
1109static size_t get_input_buffer_size(uint32_t sample_rate,
1110                                    audio_format_t format,
1111                                    int channel_count)
1112{
1113    size_t size = 0;
1114
1115    if (check_input_parameters(sample_rate, format, channel_count) != 0)
1116        return 0;
1117
1118    size = (sample_rate * AUDIO_CAPTURE_PERIOD_DURATION_MSEC) / 1000;
1119    /* ToDo: should use frame_size computed based on the format and
1120       channel_count here. */
1121    size *= sizeof(short) * channel_count;
1122
1123    /* make sure the size is multiple of 64 */
1124    size += 0x3f;
1125    size &= ~0x3f;
1126
1127    return size;
1128}
1129
1130static uint32_t out_get_sample_rate(const struct audio_stream *stream)
1131{
1132    struct stream_out *out = (struct stream_out *)stream;
1133
1134    return out->sample_rate;
1135}
1136
1137static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1138{
1139    return -ENOSYS;
1140}
1141
1142static size_t out_get_buffer_size(const struct audio_stream *stream)
1143{
1144    struct stream_out *out = (struct stream_out *)stream;
1145
1146    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1147        return out->compr_config.fragment_size;
1148    }
1149
1150    return out->config.period_size * audio_stream_frame_size(stream);
1151}
1152
1153static uint32_t out_get_channels(const struct audio_stream *stream)
1154{
1155    struct stream_out *out = (struct stream_out *)stream;
1156
1157    return out->channel_mask;
1158}
1159
1160static audio_format_t out_get_format(const struct audio_stream *stream)
1161{
1162    struct stream_out *out = (struct stream_out *)stream;
1163
1164    return out->format;
1165}
1166
1167static int out_set_format(struct audio_stream *stream, audio_format_t format)
1168{
1169    return -ENOSYS;
1170}
1171
1172static int out_standby(struct audio_stream *stream)
1173{
1174    struct stream_out *out = (struct stream_out *)stream;
1175    struct audio_device *adev = out->dev;
1176
1177    ALOGV("%s: enter: usecase(%d: %s)", __func__,
1178          out->usecase, use_case_table[out->usecase]);
1179
1180    pthread_mutex_lock(&out->lock);
1181    if (!out->standby) {
1182        pthread_mutex_lock(&adev->lock);
1183        out->standby = true;
1184        if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1185            if (out->pcm) {
1186                pcm_close(out->pcm);
1187                out->pcm = NULL;
1188            }
1189        } else {
1190            stop_compressed_output_l(out);
1191            out->gapless_mdata.encoder_delay = 0;
1192            out->gapless_mdata.encoder_padding = 0;
1193            if (out->compr != NULL) {
1194                compress_close(out->compr);
1195                out->compr = NULL;
1196            }
1197        }
1198        stop_output_stream(out);
1199        pthread_mutex_unlock(&adev->lock);
1200    }
1201    pthread_mutex_unlock(&out->lock);
1202    ALOGV("%s: exit", __func__);
1203    return 0;
1204}
1205
1206static int out_dump(const struct audio_stream *stream, int fd)
1207{
1208    return 0;
1209}
1210
1211static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
1212{
1213    int ret = 0;
1214    char value[32];
1215    struct compr_gapless_mdata tmp_mdata;
1216
1217    if (!out || !parms) {
1218        return -EINVAL;
1219    }
1220
1221    ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
1222    if (ret >= 0) {
1223        tmp_mdata.encoder_delay = atoi(value); //whats a good limit check?
1224    } else {
1225        return -EINVAL;
1226    }
1227
1228    ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
1229    if (ret >= 0) {
1230        tmp_mdata.encoder_padding = atoi(value);
1231    } else {
1232        return -EINVAL;
1233    }
1234
1235    out->gapless_mdata = tmp_mdata;
1236    out->send_new_metadata = 1;
1237    ALOGV("%s new encoder delay %u and padding %u", __func__,
1238          out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);
1239
1240    return 0;
1241}
1242
1243
1244static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
1245{
1246    struct stream_out *out = (struct stream_out *)stream;
1247    struct audio_device *adev = out->dev;
1248    struct audio_usecase *usecase;
1249    struct listnode *node;
1250    struct str_parms *parms;
1251    char value[32];
1252    int ret, val = 0;
1253    bool select_new_device = false;
1254    int status = 0;
1255
1256    ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s",
1257          __func__, out->usecase, use_case_table[out->usecase], kvpairs);
1258    parms = str_parms_create_str(kvpairs);
1259    ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
1260    if (ret >= 0) {
1261        val = atoi(value);
1262        pthread_mutex_lock(&out->lock);
1263        pthread_mutex_lock(&adev->lock);
1264
1265        /*
1266         * When HDMI cable is unplugged the music playback is paused and
1267         * the policy manager sends routing=0. But the audioflinger
1268         * continues to write data until standby time (3sec).
1269         * As the HDMI core is turned off, the write gets blocked.
1270         * Avoid this by routing audio to speaker until standby.
1271         */
1272        if (out->devices == AUDIO_DEVICE_OUT_AUX_DIGITAL &&
1273                val == AUDIO_DEVICE_NONE) {
1274            val = AUDIO_DEVICE_OUT_SPEAKER;
1275        }
1276
1277        /*
1278         * select_devices() call below switches all the usecases on the same
1279         * backend to the new device. Refer to check_usecases_codec_backend() in
1280         * the select_devices(). But how do we undo this?
1281         *
1282         * For example, music playback is active on headset (deep-buffer usecase)
1283         * and if we go to ringtones and select a ringtone, low-latency usecase
1284         * will be started on headset+speaker. As we can't enable headset+speaker
1285         * and headset devices at the same time, select_devices() switches the music
1286         * playback to headset+speaker while starting low-lateny usecase for ringtone.
1287         * So when the ringtone playback is completed, how do we undo the same?
1288         *
1289         * We are relying on the out_set_parameters() call on deep-buffer output,
1290         * once the ringtone playback is ended.
1291         * NOTE: We should not check if the current devices are same as new devices.
1292         *       Because select_devices() must be called to switch back the music
1293         *       playback to headset.
1294         */
1295        if (val != 0) {
1296            out->devices = val;
1297
1298            if (!out->standby)
1299                select_devices(adev, out->usecase);
1300
1301            if ((adev->mode == AUDIO_MODE_IN_CALL) && !adev->in_call &&
1302                    (out == adev->primary_output)) {
1303                start_voice_call(adev);
1304            } else if ((adev->mode == AUDIO_MODE_IN_CALL) && adev->in_call &&
1305                       (out == adev->primary_output)) {
1306                select_devices(adev, USECASE_VOICE_CALL);
1307            }
1308        }
1309
1310        if ((adev->mode == AUDIO_MODE_NORMAL) && adev->in_call &&
1311                (out == adev->primary_output)) {
1312            stop_voice_call(adev);
1313        }
1314
1315        pthread_mutex_unlock(&adev->lock);
1316        pthread_mutex_unlock(&out->lock);
1317    }
1318
1319    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1320        parse_compress_metadata(out, parms);
1321    }
1322
1323    str_parms_destroy(parms);
1324    ALOGV("%s: exit: code(%d)", __func__, status);
1325    return status;
1326}
1327
1328static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
1329{
1330    struct stream_out *out = (struct stream_out *)stream;
1331    struct str_parms *query = str_parms_create_str(keys);
1332    char *str;
1333    char value[256];
1334    struct str_parms *reply = str_parms_create();
1335    size_t i, j;
1336    int ret;
1337    bool first = true;
1338    ALOGV("%s: enter: keys - %s", __func__, keys);
1339    ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value, sizeof(value));
1340    if (ret >= 0) {
1341        value[0] = '\0';
1342        i = 0;
1343        while (out->supported_channel_masks[i] != 0) {
1344            for (j = 0; j < ARRAY_SIZE(out_channels_name_to_enum_table); j++) {
1345                if (out_channels_name_to_enum_table[j].value == out->supported_channel_masks[i]) {
1346                    if (!first) {
1347                        strcat(value, "|");
1348                    }
1349                    strcat(value, out_channels_name_to_enum_table[j].name);
1350                    first = false;
1351                    break;
1352                }
1353            }
1354            i++;
1355        }
1356        str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
1357        str = str_parms_to_str(reply);
1358    } else {
1359        str = strdup(keys);
1360    }
1361    str_parms_destroy(query);
1362    str_parms_destroy(reply);
1363    ALOGV("%s: exit: returns - %s", __func__, str);
1364    return str;
1365}
1366
1367static uint32_t out_get_latency(const struct audio_stream_out *stream)
1368{
1369    struct stream_out *out = (struct stream_out *)stream;
1370
1371    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
1372        return COMPRESS_OFFLOAD_PLAYBACK_LATENCY;
1373
1374    return (out->config.period_count * out->config.period_size * 1000) /
1375           (out->config.rate);
1376}
1377
1378static int out_set_volume(struct audio_stream_out *stream, float left,
1379                          float right)
1380{
1381    struct stream_out *out = (struct stream_out *)stream;
1382    int volume[2];
1383
1384    if (out->usecase == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
1385        /* only take left channel into account: the API is for stereo anyway */
1386        out->muted = (left == 0.0f);
1387        return 0;
1388    } else if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1389        const char *mixer_ctl_name = "Compress Playback Volume";
1390        struct audio_device *adev = out->dev;
1391        struct mixer_ctl *ctl;
1392
1393        ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
1394        if (!ctl) {
1395            ALOGE("%s: Could not get ctl for mixer cmd - %s",
1396                  __func__, mixer_ctl_name);
1397            return -EINVAL;
1398        }
1399        volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
1400        volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
1401        mixer_ctl_set_array(ctl, volume, sizeof(volume)/sizeof(volume[0]));
1402        return 0;
1403    }
1404
1405    return -ENOSYS;
1406}
1407
1408static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
1409                         size_t bytes)
1410{
1411    struct stream_out *out = (struct stream_out *)stream;
1412    struct audio_device *adev = out->dev;
1413    ssize_t ret = 0;
1414
1415    pthread_mutex_lock(&out->lock);
1416    if (out->standby) {
1417        out->standby = false;
1418        pthread_mutex_lock(&adev->lock);
1419        ret = start_output_stream(out);
1420        pthread_mutex_unlock(&adev->lock);
1421        /* ToDo: If use case is compress offload should return 0 */
1422        if (ret != 0) {
1423            out->standby = true;
1424            goto exit;
1425        }
1426    }
1427
1428    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1429        ALOGVV("%s: writing buffer (%d bytes) to compress device", __func__, bytes);
1430        if (out->send_new_metadata) {
1431            ALOGVV("send new gapless metadata");
1432            compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
1433            out->send_new_metadata = 0;
1434        }
1435
1436        ret = compress_write(out->compr, buffer, bytes);
1437        ALOGVV("%s: writing buffer (%d bytes) to compress device returned %d", __func__, bytes, ret);
1438        if (ret >= 0 && ret < (ssize_t)bytes) {
1439            send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
1440        }
1441        if (!out->playback_started) {
1442            compress_start(out->compr);
1443            out->playback_started = 1;
1444            out->offload_state = OFFLOAD_STATE_PLAYING;
1445        }
1446        pthread_mutex_unlock(&out->lock);
1447        return ret;
1448    } else {
1449        if (out->pcm) {
1450            if (out->muted)
1451                memset((void *)buffer, 0, bytes);
1452            ALOGVV("%s: writing buffer (%d bytes) to pcm device", __func__, bytes);
1453            ret = pcm_write(out->pcm, (void *)buffer, bytes);
1454            if (ret == 0)
1455                out->written += bytes / (out->config.channels * sizeof(short));
1456        }
1457    }
1458
1459exit:
1460    pthread_mutex_unlock(&out->lock);
1461
1462    if (ret != 0) {
1463        if (out->pcm)
1464            ALOGE("%s: error %d - %s", __func__, ret, pcm_get_error(out->pcm));
1465        out_standby(&out->stream.common);
1466        usleep(bytes * 1000000 / audio_stream_frame_size(&out->stream.common) /
1467               out_get_sample_rate(&out->stream.common));
1468    }
1469    return bytes;
1470}
1471
1472static int out_get_render_position(const struct audio_stream_out *stream,
1473                                   uint32_t *dsp_frames)
1474{
1475    struct stream_out *out = (struct stream_out *)stream;
1476    *dsp_frames = 0;
1477    if ((out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) && (dsp_frames != NULL)) {
1478        pthread_mutex_lock(&out->lock);
1479        if (out->compr != NULL) {
1480            compress_get_tstamp(out->compr, (unsigned long *)dsp_frames,
1481                    &out->sample_rate);
1482            ALOGVV("%s rendered frames %d sample_rate %d",
1483                   __func__, *dsp_frames, out->sample_rate);
1484        }
1485        pthread_mutex_unlock(&out->lock);
1486        return 0;
1487    } else
1488        return -EINVAL;
1489}
1490
1491static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1492{
1493    return 0;
1494}
1495
1496static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1497{
1498    return 0;
1499}
1500
1501static int out_get_next_write_timestamp(const struct audio_stream_out *stream,
1502                                        int64_t *timestamp)
1503{
1504    return -EINVAL;
1505}
1506
1507static int out_get_presentation_position(const struct audio_stream_out *stream,
1508                                   uint64_t *frames, struct timespec *timestamp)
1509{
1510    struct stream_out *out = (struct stream_out *)stream;
1511    int ret = -1;
1512    unsigned long dsp_frames;
1513
1514    pthread_mutex_lock(&out->lock);
1515
1516    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1517        if (out->compr != NULL) {
1518            compress_get_tstamp(out->compr, &dsp_frames,
1519                    &out->sample_rate);
1520            ALOGVV("%s rendered frames %ld sample_rate %d",
1521                   __func__, dsp_frames, out->sample_rate);
1522            *frames = dsp_frames;
1523            ret = 0;
1524            /* this is the best we can do */
1525            clock_gettime(CLOCK_MONOTONIC, timestamp);
1526        }
1527    } else {
1528        if (out->pcm) {
1529            size_t avail;
1530            if (pcm_get_htimestamp(out->pcm, &avail, timestamp) == 0) {
1531                size_t kernel_buffer_size = out->config.period_size * out->config.period_count;
1532                int64_t signed_frames = out->written - kernel_buffer_size + avail;
1533                // This adjustment accounts for buffering after app processor.
1534                // It is based on estimated DSP latency per use case, rather than exact.
1535                signed_frames -=
1536                    (platform_render_latency(out->usecase) * out->sample_rate / 1000000LL);
1537
1538                // It would be unusual for this value to be negative, but check just in case ...
1539                if (signed_frames >= 0) {
1540                    *frames = signed_frames;
1541                    ret = 0;
1542                }
1543            }
1544        }
1545    }
1546
1547    pthread_mutex_unlock(&out->lock);
1548
1549    return ret;
1550}
1551
1552static int out_set_callback(struct audio_stream_out *stream,
1553            stream_callback_t callback, void *cookie)
1554{
1555    struct stream_out *out = (struct stream_out *)stream;
1556
1557    ALOGV("%s", __func__);
1558    pthread_mutex_lock(&out->lock);
1559    out->offload_callback = callback;
1560    out->offload_cookie = cookie;
1561    pthread_mutex_unlock(&out->lock);
1562    return 0;
1563}
1564
1565static int out_pause(struct audio_stream_out* stream)
1566{
1567    struct stream_out *out = (struct stream_out *)stream;
1568    int status = -ENOSYS;
1569    ALOGV("%s", __func__);
1570    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1571        pthread_mutex_lock(&out->lock);
1572        if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
1573            status = compress_pause(out->compr);
1574            out->offload_state = OFFLOAD_STATE_PAUSED;
1575        }
1576        pthread_mutex_unlock(&out->lock);
1577    }
1578    return status;
1579}
1580
1581static int out_resume(struct audio_stream_out* stream)
1582{
1583    struct stream_out *out = (struct stream_out *)stream;
1584    int status = -ENOSYS;
1585    ALOGV("%s", __func__);
1586    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1587        status = 0;
1588        pthread_mutex_lock(&out->lock);
1589        if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
1590            status = compress_resume(out->compr);
1591            out->offload_state = OFFLOAD_STATE_PLAYING;
1592        }
1593        pthread_mutex_unlock(&out->lock);
1594    }
1595    return status;
1596}
1597
1598static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
1599{
1600    struct stream_out *out = (struct stream_out *)stream;
1601    int status = -ENOSYS;
1602    ALOGV("%s", __func__);
1603    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1604        pthread_mutex_lock(&out->lock);
1605        if (type == AUDIO_DRAIN_EARLY_NOTIFY)
1606            status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
1607        else
1608            status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
1609        pthread_mutex_unlock(&out->lock);
1610    }
1611    return status;
1612}
1613
1614static int out_flush(struct audio_stream_out* stream)
1615{
1616    struct stream_out *out = (struct stream_out *)stream;
1617    ALOGV("%s", __func__);
1618    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
1619        pthread_mutex_lock(&out->lock);
1620        stop_compressed_output_l(out);
1621        pthread_mutex_unlock(&out->lock);
1622        return 0;
1623    }
1624    return -ENOSYS;
1625}
1626
1627/** audio_stream_in implementation **/
1628static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1629{
1630    struct stream_in *in = (struct stream_in *)stream;
1631
1632    return in->config.rate;
1633}
1634
1635static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1636{
1637    return -ENOSYS;
1638}
1639
1640static size_t in_get_buffer_size(const struct audio_stream *stream)
1641{
1642    struct stream_in *in = (struct stream_in *)stream;
1643
1644    return in->config.period_size * audio_stream_frame_size(stream);
1645}
1646
1647static uint32_t in_get_channels(const struct audio_stream *stream)
1648{
1649    struct stream_in *in = (struct stream_in *)stream;
1650
1651    return in->channel_mask;
1652}
1653
1654static audio_format_t in_get_format(const struct audio_stream *stream)
1655{
1656    return AUDIO_FORMAT_PCM_16_BIT;
1657}
1658
1659static int in_set_format(struct audio_stream *stream, audio_format_t format)
1660{
1661    return -ENOSYS;
1662}
1663
1664static int in_standby(struct audio_stream *stream)
1665{
1666    struct stream_in *in = (struct stream_in *)stream;
1667    struct audio_device *adev = in->dev;
1668    int status = 0;
1669    ALOGV("%s: enter", __func__);
1670    pthread_mutex_lock(&in->lock);
1671    if (!in->standby) {
1672        pthread_mutex_lock(&adev->lock);
1673        in->standby = true;
1674        if (in->pcm) {
1675            pcm_close(in->pcm);
1676            in->pcm = NULL;
1677        }
1678        status = stop_input_stream(in);
1679        pthread_mutex_unlock(&adev->lock);
1680    }
1681    pthread_mutex_unlock(&in->lock);
1682    ALOGV("%s: exit:  status(%d)", __func__, status);
1683    return status;
1684}
1685
1686static int in_dump(const struct audio_stream *stream, int fd)
1687{
1688    return 0;
1689}
1690
1691static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1692{
1693    struct stream_in *in = (struct stream_in *)stream;
1694    struct audio_device *adev = in->dev;
1695    struct str_parms *parms;
1696    char *str;
1697    char value[32];
1698    int ret, val = 0;
1699    int status = 0;
1700
1701    ALOGV("%s: enter: kvpairs=%s", __func__, kvpairs);
1702    parms = str_parms_create_str(kvpairs);
1703
1704    ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
1705
1706    pthread_mutex_lock(&in->lock);
1707    pthread_mutex_lock(&adev->lock);
1708    if (ret >= 0) {
1709        val = atoi(value);
1710        /* no audio source uses val == 0 */
1711        if ((in->source != val) && (val != 0)) {
1712            in->source = val;
1713        }
1714    }
1715
1716    ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
1717
1718    if (ret >= 0) {
1719        val = atoi(value);
1720        if ((in->device != val) && (val != 0)) {
1721            in->device = val;
1722            /* If recording is in progress, change the tx device to new device */
1723            if (!in->standby)
1724                status = select_devices(adev, in->usecase);
1725        }
1726    }
1727
1728    pthread_mutex_unlock(&adev->lock);
1729    pthread_mutex_unlock(&in->lock);
1730
1731    str_parms_destroy(parms);
1732    ALOGV("%s: exit: status(%d)", __func__, status);
1733    return status;
1734}
1735
1736static char* in_get_parameters(const struct audio_stream *stream,
1737                               const char *keys)
1738{
1739    return strdup("");
1740}
1741
1742static int in_set_gain(struct audio_stream_in *stream, float gain)
1743{
1744    return 0;
1745}
1746
1747static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
1748                       size_t bytes)
1749{
1750    struct stream_in *in = (struct stream_in *)stream;
1751    struct audio_device *adev = in->dev;
1752    int i, ret = -1;
1753
1754    pthread_mutex_lock(&in->lock);
1755    if (in->standby) {
1756        pthread_mutex_lock(&adev->lock);
1757        ret = start_input_stream(in);
1758        pthread_mutex_unlock(&adev->lock);
1759        if (ret != 0) {
1760            goto exit;
1761        }
1762        in->standby = 0;
1763    }
1764
1765    if (in->pcm) {
1766        ret = pcm_read(in->pcm, buffer, bytes);
1767    }
1768
1769    /*
1770     * Instead of writing zeroes here, we could trust the hardware
1771     * to always provide zeroes when muted.
1772     */
1773    if (ret == 0 && adev->mic_mute)
1774        memset(buffer, 0, bytes);
1775
1776exit:
1777    pthread_mutex_unlock(&in->lock);
1778
1779    if (ret != 0) {
1780        in_standby(&in->stream.common);
1781        ALOGV("%s: read failed - sleeping for buffer duration", __func__);
1782        usleep(bytes * 1000000 / audio_stream_frame_size(&in->stream.common) /
1783               in_get_sample_rate(&in->stream.common));
1784    }
1785    return bytes;
1786}
1787
1788static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1789{
1790    return 0;
1791}
1792
1793static int add_remove_audio_effect(const struct audio_stream *stream,
1794                                   effect_handle_t effect,
1795                                   bool enable)
1796{
1797    struct stream_in *in = (struct stream_in *)stream;
1798    int status = 0;
1799    effect_descriptor_t desc;
1800
1801    status = (*effect)->get_descriptor(effect, &desc);
1802    if (status != 0)
1803        return status;
1804
1805    pthread_mutex_lock(&in->lock);
1806    pthread_mutex_lock(&in->dev->lock);
1807    if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
1808            in->enable_aec != enable &&
1809            (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
1810        in->enable_aec = enable;
1811        if (!in->standby)
1812            select_devices(in->dev, in->usecase);
1813    }
1814    pthread_mutex_unlock(&in->dev->lock);
1815    pthread_mutex_unlock(&in->lock);
1816
1817    return 0;
1818}
1819
1820static int in_add_audio_effect(const struct audio_stream *stream,
1821                               effect_handle_t effect)
1822{
1823    ALOGV("%s: effect %p", __func__, effect);
1824    return add_remove_audio_effect(stream, effect, true);
1825}
1826
1827static int in_remove_audio_effect(const struct audio_stream *stream,
1828                                  effect_handle_t effect)
1829{
1830    ALOGV("%s: effect %p", __func__, effect);
1831    return add_remove_audio_effect(stream, effect, false);
1832}
1833
1834static int adev_open_output_stream(struct audio_hw_device *dev,
1835                                   audio_io_handle_t handle,
1836                                   audio_devices_t devices,
1837                                   audio_output_flags_t flags,
1838                                   struct audio_config *config,
1839                                   struct audio_stream_out **stream_out)
1840{
1841    struct audio_device *adev = (struct audio_device *)dev;
1842    struct stream_out *out;
1843    int i, ret;
1844
1845    ALOGV("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)",
1846          __func__, config->sample_rate, config->channel_mask, devices, flags);
1847    *stream_out = NULL;
1848    out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
1849
1850    if (devices == AUDIO_DEVICE_NONE)
1851        devices = AUDIO_DEVICE_OUT_SPEAKER;
1852
1853    out->flags = flags;
1854    out->devices = devices;
1855    out->dev = adev;
1856    out->format = config->format;
1857    out->sample_rate = config->sample_rate;
1858    out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1859    out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
1860    out->handle = handle;
1861
1862    /* Init use case and pcm_config */
1863    if (out->flags & AUDIO_OUTPUT_FLAG_DIRECT &&
1864            !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
1865        out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
1866        pthread_mutex_lock(&adev->lock);
1867        ret = read_hdmi_channel_masks(out);
1868        pthread_mutex_unlock(&adev->lock);
1869        if (ret != 0)
1870            goto error_open;
1871
1872        if (config->sample_rate == 0)
1873            config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
1874        if (config->channel_mask == 0)
1875            config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
1876
1877        out->channel_mask = config->channel_mask;
1878        out->sample_rate = config->sample_rate;
1879        out->usecase = USECASE_AUDIO_PLAYBACK_MULTI_CH;
1880        out->config = pcm_config_hdmi_multi;
1881        out->config.rate = config->sample_rate;
1882        out->config.channels = popcount(out->channel_mask);
1883        out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels * 2);
1884    } else if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1885        if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
1886            config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
1887            ALOGE("%s: Unsupported Offload information", __func__);
1888            ret = -EINVAL;
1889            goto error_open;
1890        }
1891        if (!is_supported_format(config->offload_info.format)) {
1892            ALOGE("%s: Unsupported audio format", __func__);
1893            ret = -EINVAL;
1894            goto error_open;
1895        }
1896
1897        out->compr_config.codec = (struct snd_codec *)
1898                                    calloc(1, sizeof(struct snd_codec));
1899
1900        out->usecase = USECASE_AUDIO_PLAYBACK_OFFLOAD;
1901        if (config->offload_info.channel_mask)
1902            out->channel_mask = config->offload_info.channel_mask;
1903        else if (config->channel_mask)
1904            out->channel_mask = config->channel_mask;
1905        out->format = config->offload_info.format;
1906        out->sample_rate = config->offload_info.sample_rate;
1907
1908        out->stream.set_callback = out_set_callback;
1909        out->stream.pause = out_pause;
1910        out->stream.resume = out_resume;
1911        out->stream.drain = out_drain;
1912        out->stream.flush = out_flush;
1913
1914        out->compr_config.codec->id =
1915                get_snd_codec_id(config->offload_info.format);
1916        out->compr_config.fragment_size = COMPRESS_OFFLOAD_FRAGMENT_SIZE;
1917        out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
1918        out->compr_config.codec->sample_rate =
1919                    compress_get_alsa_rate(config->offload_info.sample_rate);
1920        out->compr_config.codec->bit_rate =
1921                    config->offload_info.bit_rate;
1922        out->compr_config.codec->ch_in =
1923                    popcount(config->channel_mask);
1924        out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
1925
1926        if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
1927            out->non_blocking = 1;
1928
1929        out->send_new_metadata = 1;
1930        create_offload_callback_thread(out);
1931        ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
1932                __func__, config->offload_info.version,
1933                config->offload_info.bit_rate);
1934    } else {
1935        if (out->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1936            out->usecase = USECASE_AUDIO_PLAYBACK_DEEP_BUFFER;
1937            out->config = pcm_config_deep_buffer;
1938        } else {
1939            out->usecase = USECASE_AUDIO_PLAYBACK_LOW_LATENCY;
1940            out->config = pcm_config_low_latency;
1941        }
1942        if (config->format != audio_format_from_pcm_format(out->config.format)) {
1943            if (k_enable_extended_precision
1944                    && pcm_params_format_test(adev->use_case_table[out->usecase],
1945                            pcm_format_from_audio_format(config->format))) {
1946                out->config.format = pcm_format_from_audio_format(config->format);
1947                /* out->format already set to config->format */
1948            } else {
1949                /* deny the externally proposed config format
1950                 * and use the one specified in audio_hw layer configuration.
1951                 * Note: out->format is returned by out->stream.common.get_format()
1952                 * and is used to set config->format in the code several lines below.
1953                 */
1954                out->format = audio_format_from_pcm_format(out->config.format);
1955            }
1956        }
1957        out->sample_rate = out->config.rate;
1958    }
1959    ALOGV("%s: Usecase(%s) config->format %#x  out->config.format %#x\n",
1960            __func__, use_case_table[out->usecase], config->format, out->config.format);
1961
1962    if (flags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1963        if(adev->primary_output == NULL)
1964            adev->primary_output = out;
1965        else {
1966            ALOGE("%s: Primary output is already opened", __func__);
1967            ret = -EEXIST;
1968            goto error_open;
1969        }
1970    }
1971
1972    /* Check if this usecase is already existing */
1973    pthread_mutex_lock(&adev->lock);
1974    if (get_usecase_from_list(adev, out->usecase) != NULL) {
1975        ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
1976        pthread_mutex_unlock(&adev->lock);
1977        ret = -EEXIST;
1978        goto error_open;
1979    }
1980    pthread_mutex_unlock(&adev->lock);
1981
1982    out->stream.common.get_sample_rate = out_get_sample_rate;
1983    out->stream.common.set_sample_rate = out_set_sample_rate;
1984    out->stream.common.get_buffer_size = out_get_buffer_size;
1985    out->stream.common.get_channels = out_get_channels;
1986    out->stream.common.get_format = out_get_format;
1987    out->stream.common.set_format = out_set_format;
1988    out->stream.common.standby = out_standby;
1989    out->stream.common.dump = out_dump;
1990    out->stream.common.set_parameters = out_set_parameters;
1991    out->stream.common.get_parameters = out_get_parameters;
1992    out->stream.common.add_audio_effect = out_add_audio_effect;
1993    out->stream.common.remove_audio_effect = out_remove_audio_effect;
1994    out->stream.get_latency = out_get_latency;
1995    out->stream.set_volume = out_set_volume;
1996    out->stream.write = out_write;
1997    out->stream.get_render_position = out_get_render_position;
1998    out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
1999    out->stream.get_presentation_position = out_get_presentation_position;
2000
2001    out->standby = 1;
2002    /* out->muted = false; by calloc() */
2003    /* out->written = 0; by calloc() */
2004
2005    pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
2006    pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);
2007
2008    config->format = out->stream.common.get_format(&out->stream.common);
2009    config->channel_mask = out->stream.common.get_channels(&out->stream.common);
2010    config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
2011
2012    *stream_out = &out->stream;
2013    ALOGV("%s: exit", __func__);
2014    return 0;
2015
2016error_open:
2017    free(out);
2018    *stream_out = NULL;
2019    ALOGD("%s: exit: ret %d", __func__, ret);
2020    return ret;
2021}
2022
2023static void adev_close_output_stream(struct audio_hw_device *dev,
2024                                     struct audio_stream_out *stream)
2025{
2026    struct stream_out *out = (struct stream_out *)stream;
2027    struct audio_device *adev = out->dev;
2028
2029    ALOGV("%s: enter", __func__);
2030    out_standby(&stream->common);
2031    if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
2032        destroy_offload_callback_thread(out);
2033
2034        if (out->compr_config.codec != NULL)
2035            free(out->compr_config.codec);
2036    }
2037    pthread_cond_destroy(&out->cond);
2038    pthread_mutex_destroy(&out->lock);
2039    free(stream);
2040    ALOGV("%s: exit", __func__);
2041}
2042
2043static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
2044{
2045    struct audio_device *adev = (struct audio_device *)dev;
2046    struct str_parms *parms;
2047    char *str;
2048    char value[32];
2049    int val;
2050    int ret;
2051    int status = 0;
2052
2053    ALOGV("%s: enter: %s", __func__, kvpairs);
2054
2055    parms = str_parms_create_str(kvpairs);
2056    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_TTY_MODE, value, sizeof(value));
2057    if (ret >= 0) {
2058        int tty_mode;
2059
2060        if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_OFF) == 0)
2061            tty_mode = TTY_MODE_OFF;
2062        else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_VCO) == 0)
2063            tty_mode = TTY_MODE_VCO;
2064        else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_HCO) == 0)
2065            tty_mode = TTY_MODE_HCO;
2066        else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_FULL) == 0)
2067            tty_mode = TTY_MODE_FULL;
2068        else
2069            return -EINVAL;
2070
2071        pthread_mutex_lock(&adev->lock);
2072        if (tty_mode != adev->tty_mode) {
2073            adev->tty_mode = tty_mode;
2074            adev->acdb_settings = (adev->acdb_settings & TTY_MODE_CLEAR) | tty_mode;
2075            if (adev->in_call)
2076                select_devices(adev, USECASE_VOICE_CALL);
2077        }
2078        pthread_mutex_unlock(&adev->lock);
2079    }
2080
2081    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
2082    if (ret >= 0) {
2083        /* When set to false, HAL should disable EC and NS
2084         * But it is currently not supported.
2085         */
2086        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
2087            adev->bluetooth_nrec = true;
2088        else
2089            adev->bluetooth_nrec = false;
2090    }
2091
2092    ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
2093    if (ret >= 0) {
2094        if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
2095            adev->screen_off = false;
2096        else
2097            adev->screen_off = true;
2098    }
2099
2100    ret = str_parms_get_int(parms, "rotation", &val);
2101    if (ret >= 0) {
2102        bool reverse_speakers = false;
2103        switch(val) {
2104        // FIXME: note that the code below assumes that the speakers are in the correct placement
2105        //   relative to the user when the device is rotated 90deg from its default rotation. This
2106        //   assumption is device-specific, not platform-specific like this code.
2107        case 270:
2108            reverse_speakers = true;
2109            break;
2110        case 0:
2111        case 90:
2112        case 180:
2113            break;
2114        default:
2115            ALOGE("%s: unexpected rotation of %d", __func__, val);
2116            status = -EINVAL;
2117        }
2118        if (status == 0) {
2119            pthread_mutex_lock(&adev->lock);
2120            if (adev->speaker_lr_swap != reverse_speakers) {
2121                adev->speaker_lr_swap = reverse_speakers;
2122                // only update the selected device if there is active pcm playback
2123                struct audio_usecase *usecase;
2124                struct listnode *node;
2125                list_for_each(node, &adev->usecase_list) {
2126                    usecase = node_to_item(node, struct audio_usecase, list);
2127                    if (usecase->type == PCM_PLAYBACK) {
2128                        select_devices(adev, usecase->id);
2129                        break;
2130                    }
2131                }
2132            }
2133            pthread_mutex_unlock(&adev->lock);
2134        }
2135    }
2136
2137    ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value));
2138    if (ret >= 0) {
2139        pthread_mutex_lock(&adev->lock);
2140        adev->bt_wb_speech_enabled = !strcmp(value, AUDIO_PARAMETER_VALUE_ON);
2141        pthread_mutex_unlock(&adev->lock);
2142    }
2143
2144    str_parms_destroy(parms);
2145    ALOGV("%s: exit with code(%d)", __func__, status);
2146    return status;
2147}
2148
2149static char* adev_get_parameters(const struct audio_hw_device *dev,
2150                                 const char *keys)
2151{
2152    return strdup("");
2153}
2154
2155static int adev_init_check(const struct audio_hw_device *dev)
2156{
2157    return 0;
2158}
2159
2160/* always called with adev lock held */
2161static int set_voice_volume_l(struct audio_device *adev, float volume)
2162{
2163    int vol, err = 0;
2164
2165    if (adev->mode == AUDIO_MODE_IN_CALL) {
2166        if (volume < 0.0) {
2167            volume = 0.0;
2168        } else if (volume > 1.0) {
2169            volume = 1.0;
2170        }
2171
2172        vol = lrint(volume * 100.0);
2173
2174        // Voice volume levels from android are mapped to driver volume levels as follows.
2175        // 0 -> 5, 20 -> 4, 40 ->3, 60 -> 2, 80 -> 1, 100 -> 0
2176        // So adjust the volume to get the correct volume index in driver
2177        vol = 100 - vol;
2178
2179        err = platform_set_voice_volume(adev->platform, vol);
2180    }
2181    return err;
2182}
2183
2184static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
2185{
2186    int ret;
2187    struct audio_device *adev = (struct audio_device *)dev;
2188    pthread_mutex_lock(&adev->lock);
2189    /* cache volume */
2190    adev->voice_volume = volume;
2191    ret = set_voice_volume_l(adev, adev->voice_volume);
2192    pthread_mutex_unlock(&adev->lock);
2193    return ret;
2194}
2195
2196static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
2197{
2198    return -ENOSYS;
2199}
2200
2201static int adev_get_master_volume(struct audio_hw_device *dev,
2202                                  float *volume)
2203{
2204    return -ENOSYS;
2205}
2206
2207static int adev_set_master_mute(struct audio_hw_device *dev, bool muted)
2208{
2209    return -ENOSYS;
2210}
2211
2212static int adev_get_master_mute(struct audio_hw_device *dev, bool *muted)
2213{
2214    return -ENOSYS;
2215}
2216
2217static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
2218{
2219    struct audio_device *adev = (struct audio_device *)dev;
2220
2221    pthread_mutex_lock(&adev->lock);
2222    if (adev->mode != mode) {
2223        adev->mode = mode;
2224    }
2225    pthread_mutex_unlock(&adev->lock);
2226    return 0;
2227}
2228
2229static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
2230{
2231    struct audio_device *adev = (struct audio_device *)dev;
2232    int err = 0;
2233
2234    pthread_mutex_lock(&adev->lock);
2235    adev->mic_mute = state;
2236
2237    err = platform_set_mic_mute(adev->platform, state);
2238    pthread_mutex_unlock(&adev->lock);
2239    return err;
2240}
2241
2242static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
2243{
2244    struct audio_device *adev = (struct audio_device *)dev;
2245
2246    *state = adev->mic_mute;
2247
2248    return 0;
2249}
2250
2251static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
2252                                         const struct audio_config *config)
2253{
2254    int channel_count = popcount(config->channel_mask);
2255
2256    return get_input_buffer_size(config->sample_rate, config->format, channel_count);
2257}
2258
2259static int adev_open_input_stream(struct audio_hw_device *dev,
2260                                  audio_io_handle_t handle,
2261                                  audio_devices_t devices,
2262                                  struct audio_config *config,
2263                                  struct audio_stream_in **stream_in)
2264{
2265    struct audio_device *adev = (struct audio_device *)dev;
2266    struct stream_in *in;
2267    int ret, buffer_size, frame_size;
2268    int channel_count = popcount(config->channel_mask);
2269
2270    ALOGV("%s: enter", __func__);
2271    *stream_in = NULL;
2272    if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0)
2273        return -EINVAL;
2274
2275    in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
2276
2277    in->stream.common.get_sample_rate = in_get_sample_rate;
2278    in->stream.common.set_sample_rate = in_set_sample_rate;
2279    in->stream.common.get_buffer_size = in_get_buffer_size;
2280    in->stream.common.get_channels = in_get_channels;
2281    in->stream.common.get_format = in_get_format;
2282    in->stream.common.set_format = in_set_format;
2283    in->stream.common.standby = in_standby;
2284    in->stream.common.dump = in_dump;
2285    in->stream.common.set_parameters = in_set_parameters;
2286    in->stream.common.get_parameters = in_get_parameters;
2287    in->stream.common.add_audio_effect = in_add_audio_effect;
2288    in->stream.common.remove_audio_effect = in_remove_audio_effect;
2289    in->stream.set_gain = in_set_gain;
2290    in->stream.read = in_read;
2291    in->stream.get_input_frames_lost = in_get_input_frames_lost;
2292
2293    in->device = devices;
2294    in->source = AUDIO_SOURCE_DEFAULT;
2295    in->dev = adev;
2296    in->standby = 1;
2297    in->channel_mask = config->channel_mask;
2298
2299    /* Update config params with the requested sample rate and channels */
2300    in->usecase = USECASE_AUDIO_RECORD;
2301    in->config = pcm_config_audio_capture;
2302    in->config.channels = channel_count;
2303    in->config.rate = config->sample_rate;
2304
2305    frame_size = audio_stream_frame_size((struct audio_stream *)in);
2306    buffer_size = get_input_buffer_size(config->sample_rate,
2307                                        config->format,
2308                                        channel_count);
2309    in->config.period_size = buffer_size / frame_size;
2310
2311    *stream_in = &in->stream;
2312    ALOGV("%s: exit", __func__);
2313    return 0;
2314
2315err_open:
2316    free(in);
2317    *stream_in = NULL;
2318    return ret;
2319}
2320
2321static void adev_close_input_stream(struct audio_hw_device *dev,
2322                                    struct audio_stream_in *stream)
2323{
2324    ALOGV("%s", __func__);
2325
2326    in_standby(&stream->common);
2327    free(stream);
2328
2329    return;
2330}
2331
2332static int adev_dump(const audio_hw_device_t *device, int fd)
2333{
2334    return 0;
2335}
2336
2337/* verifies input and output devices and their capabilities.
2338 *
2339 * This verification is required when enabling extended bit-depth or
2340 * sampling rates, as not all qcom products support it.
2341 *
2342 * Suitable for calling only on initialization such as adev_open().
2343 * It fills the audio_device use_case_table[] array.
2344 *
2345 * Has a side-effect that it needs to configure audio routing / devices
2346 * in order to power up the devices and read the device parameters.
2347 * It does not acquire any hw device lock. Should restore the devices
2348 * back to "normal state" upon completion.
2349 */
2350static int adev_verify_devices(struct audio_device *adev)
2351{
2352    /* enumeration is a bit difficult because one really wants to pull
2353     * the use_case, device id, etc from the hidden pcm_device_table[].
2354     * In this case there are the following use cases and device ids.
2355     *
2356     * [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = {0, 0},
2357     * [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = {15, 15},
2358     * [USECASE_AUDIO_PLAYBACK_MULTI_CH] = {1, 1},
2359     * [USECASE_AUDIO_PLAYBACK_OFFLOAD] = {9, 9},
2360     * [USECASE_AUDIO_RECORD] = {0, 0},
2361     * [USECASE_AUDIO_RECORD_LOW_LATENCY] = {15, 15},
2362     * [USECASE_VOICE_CALL] = {2, 2},
2363     *
2364     * USECASE_AUDIO_PLAYBACK_OFFLOAD, USECASE_AUDIO_PLAYBACK_MULTI_CH omitted.
2365     * USECASE_VOICE_CALL omitted, but possible for either input or output.
2366     */
2367
2368    /* should be the usecases enabled in adev_open_input_stream() */
2369    static const int test_in_usecases[] = {
2370             USECASE_AUDIO_RECORD,
2371             USECASE_AUDIO_RECORD_LOW_LATENCY, /* does not appear to be used */
2372    };
2373    /* should be the usecases enabled in adev_open_output_stream()*/
2374    static const int test_out_usecases[] = {
2375            USECASE_AUDIO_PLAYBACK_DEEP_BUFFER,
2376            USECASE_AUDIO_PLAYBACK_LOW_LATENCY,
2377    };
2378    static const usecase_type_t usecase_type_by_dir[] = {
2379            PCM_PLAYBACK,
2380            PCM_CAPTURE,
2381    };
2382    static const unsigned flags_by_dir[] = {
2383            PCM_OUT,
2384            PCM_IN,
2385    };
2386
2387    size_t i;
2388    unsigned dir;
2389    const unsigned card_id = SOUND_CARD;
2390    char info[512]; /* for possible debug info */
2391
2392    for (dir = 0; dir < 2; ++dir) {
2393        const usecase_type_t usecase_type = usecase_type_by_dir[dir];
2394        const unsigned flags_dir = flags_by_dir[dir];
2395        const size_t testsize =
2396                dir ? ARRAY_SIZE(test_in_usecases) : ARRAY_SIZE(test_out_usecases);
2397        const int *testcases =
2398                dir ? test_in_usecases : test_out_usecases;
2399        const audio_devices_t audio_device =
2400                dir ? AUDIO_DEVICE_IN_BUILTIN_MIC : AUDIO_DEVICE_OUT_SPEAKER;
2401
2402        for (i = 0; i < testsize; ++i) {
2403            const audio_usecase_t audio_usecase = testcases[i];
2404            int device_id;
2405            snd_device_t snd_device;
2406            struct pcm_params **pparams;
2407            struct stream_out out;
2408            struct stream_in in;
2409            struct audio_usecase uc_info;
2410            int retval;
2411
2412            pparams = &adev->use_case_table[audio_usecase];
2413            pcm_params_free(*pparams); /* can accept null input */
2414            *pparams = NULL;
2415
2416            /* find the device ID for the use case (signed, for error) */
2417            device_id = platform_get_pcm_device_id(audio_usecase, usecase_type);
2418            if (device_id < 0)
2419                continue;
2420
2421            /* prepare structures for device probing */
2422            memset(&uc_info, 0, sizeof(uc_info));
2423            uc_info.id = audio_usecase;
2424            uc_info.type = usecase_type;
2425            if (dir) {
2426                adev->active_input = &in;
2427                memset(&in, 0, sizeof(in));
2428                in.device = audio_device;
2429                in.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
2430                uc_info.stream.in = &in;
2431            }  else {
2432                adev->active_input = NULL;
2433            }
2434            memset(&out, 0, sizeof(out));
2435            out.devices = audio_device; /* only field needed in select_devices */
2436            uc_info.stream.out = &out;
2437            uc_info.devices = audio_device;
2438            uc_info.in_snd_device = SND_DEVICE_NONE;
2439            uc_info.out_snd_device = SND_DEVICE_NONE;
2440            list_add_tail(&adev->usecase_list, &uc_info.list);
2441
2442            /* select device - similar to start_(in/out)put_stream() */
2443            retval = select_devices(adev, audio_usecase);
2444            if (retval >= 0) {
2445                *pparams = pcm_params_get(card_id, device_id, flags_dir);
2446#if LOG_NDEBUG == 0
2447                if (*pparams) {
2448                    ALOGV("%s: (%s) card %d  device %d", __func__,
2449                            dir ? "input" : "output", card_id, device_id);
2450                    pcm_params_to_string(*pparams, info, ARRAY_SIZE(info));
2451                    ALOGV(info); /* print parameters */
2452                } else {
2453                    ALOGV("%s: cannot locate card %d  device %d", __func__, card_id, device_id);
2454                }
2455#endif
2456            }
2457
2458            /* deselect device - similar to stop_(in/out)put_stream() */
2459            /* 1. Get and set stream specific mixer controls */
2460            retval = disable_audio_route(adev, &uc_info);
2461            /* 2. Disable the rx device */
2462            retval = disable_snd_device(adev,
2463                    dir ? uc_info.in_snd_device : uc_info.out_snd_device);
2464            list_remove(&uc_info.list);
2465        }
2466    }
2467    adev->active_input = NULL; /* restore adev state */
2468    return 0;
2469}
2470
2471static int adev_close(hw_device_t *device)
2472{
2473    size_t i;
2474    struct audio_device *adev = (struct audio_device *)device;
2475    audio_route_free(adev->audio_route);
2476    free(adev->snd_dev_ref_cnt);
2477    platform_deinit(adev->platform);
2478    for (i = 0; i < ARRAY_SIZE(adev->use_case_table); ++i) {
2479        pcm_params_free(adev->use_case_table[i]);
2480    }
2481    free(device);
2482    return 0;
2483}
2484
2485static int adev_open(const hw_module_t *module, const char *name,
2486                     hw_device_t **device)
2487{
2488    struct audio_device *adev;
2489    int i, ret;
2490
2491    ALOGD("%s: enter", __func__);
2492    if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
2493
2494    adev = calloc(1, sizeof(struct audio_device));
2495
2496    adev->device.common.tag = HARDWARE_DEVICE_TAG;
2497    adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
2498    adev->device.common.module = (struct hw_module_t *)module;
2499    adev->device.common.close = adev_close;
2500
2501    adev->device.init_check = adev_init_check;
2502    adev->device.set_voice_volume = adev_set_voice_volume;
2503    adev->device.set_master_volume = adev_set_master_volume;
2504    adev->device.get_master_volume = adev_get_master_volume;
2505    adev->device.set_master_mute = adev_set_master_mute;
2506    adev->device.get_master_mute = adev_get_master_mute;
2507    adev->device.set_mode = adev_set_mode;
2508    adev->device.set_mic_mute = adev_set_mic_mute;
2509    adev->device.get_mic_mute = adev_get_mic_mute;
2510    adev->device.set_parameters = adev_set_parameters;
2511    adev->device.get_parameters = adev_get_parameters;
2512    adev->device.get_input_buffer_size = adev_get_input_buffer_size;
2513    adev->device.open_output_stream = adev_open_output_stream;
2514    adev->device.close_output_stream = adev_close_output_stream;
2515    adev->device.open_input_stream = adev_open_input_stream;
2516    adev->device.close_input_stream = adev_close_input_stream;
2517    adev->device.dump = adev_dump;
2518
2519    /* Set the default route before the PCM stream is opened */
2520    pthread_mutex_lock(&adev->lock);
2521    adev->mode = AUDIO_MODE_NORMAL;
2522    adev->active_input = NULL;
2523    adev->primary_output = NULL;
2524    adev->voice_call_rx = NULL;
2525    adev->voice_call_tx = NULL;
2526    adev->voice_volume = 1.0f;
2527    adev->tty_mode = TTY_MODE_OFF;
2528    adev->bluetooth_nrec = true;
2529    adev->in_call = false;
2530    adev->acdb_settings = TTY_MODE_OFF;
2531    /* adev->cur_hdmi_channels = 0;  by calloc() */
2532    adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
2533    list_init(&adev->usecase_list);
2534    pthread_mutex_unlock(&adev->lock);
2535
2536    /* Loads platform specific libraries dynamically */
2537    adev->platform = platform_init(adev);
2538    if (!adev->platform) {
2539        free(adev->snd_dev_ref_cnt);
2540        free(adev);
2541        ALOGE("%s: Failed to init platform data, aborting.", __func__);
2542        *device = NULL;
2543        return -EINVAL;
2544    }
2545
2546    if (access(VISUALIZER_LIBRARY_PATH, R_OK) == 0) {
2547        adev->visualizer_lib = dlopen(VISUALIZER_LIBRARY_PATH, RTLD_NOW);
2548        if (adev->visualizer_lib == NULL) {
2549            ALOGE("%s: DLOPEN failed for %s", __func__, VISUALIZER_LIBRARY_PATH);
2550        } else {
2551            ALOGV("%s: DLOPEN successful for %s", __func__, VISUALIZER_LIBRARY_PATH);
2552            adev->visualizer_start_output =
2553                        (int (*)(audio_io_handle_t))dlsym(adev->visualizer_lib,
2554                                                        "visualizer_hal_start_output");
2555            adev->visualizer_stop_output =
2556                        (int (*)(audio_io_handle_t))dlsym(adev->visualizer_lib,
2557                                                        "visualizer_hal_stop_output");
2558        }
2559    }
2560
2561    adev->bt_wb_speech_enabled = false;
2562
2563    *device = &adev->device.common;
2564    if (k_enable_extended_precision)
2565        adev_verify_devices(adev);
2566
2567    ALOGV("%s: exit", __func__);
2568    return 0;
2569}
2570
2571static struct hw_module_methods_t hal_module_methods = {
2572    .open = adev_open,
2573};
2574
2575struct audio_module HAL_MODULE_INFO_SYM = {
2576    .common = {
2577        .tag = HARDWARE_MODULE_TAG,
2578        .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
2579        .hal_api_version = HARDWARE_HAL_API_VERSION,
2580        .id = AUDIO_HARDWARE_MODULE_ID,
2581        .name = "QCOM Audio HAL",
2582        .author = "Code Aurora Forum",
2583        .methods = &hal_module_methods,
2584    },
2585};
2586