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