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