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