1/*
2 * Copyright (C) 2012 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 "modules.audio.audio_hal"
18/*#define LOG_NDEBUG 0*/
19
20#include <errno.h>
21#include <inttypes.h>
22#include <pthread.h>
23#include <stdint.h>
24#include <stdlib.h>
25#include <sys/time.h>
26
27#include <log/log.h>
28#include <cutils/str_parms.h>
29#include <cutils/properties.h>
30
31#include <hardware/audio.h>
32#include <hardware/audio_alsaops.h>
33#include <hardware/hardware.h>
34
35#include <system/audio.h>
36
37#include <tinyalsa/asoundlib.h>
38
39#include <audio_utils/channels.h>
40
41#include <dirent.h>
42#include <sys/ioctl.h>
43#include <fcntl.h>
44#include <sound/asound.h>
45
46
47#define PCM_DEV_STR "pcm"
48#if TARGET_AUDIO_PRIMARY
49#define AUDIO_STR "ALC662 rev1 Analog"
50#else
51#define AUDIO_STR "USB Audio"
52#endif
53#define MAX_PATH_LEN 30
54
55#define NBR_RETRIES 5
56#define RETRY_WAIT_USEC 20000
57
58/* FOR TESTING:
59 * Set k_force_channels to force the number of channels to present to AudioFlinger.
60 *   0 disables (this is default: present the device channels to AudioFlinger).
61 *   2 forces to legacy stereo mode.
62 *
63 * Others values can be tried (up to 8).
64 * TODO: AudioFlinger cannot support more than 8 active output channels
65 * at this time, so limiting logic needs to be put here or communicated from above.
66 */
67static const unsigned k_force_channels = 0;
68
69#include "alsa_device_profile.h"
70#include "alsa_device_proxy.h"
71#include "alsa_logging.h"
72
73#define DEFAULT_INPUT_BUFFER_SIZE_MS 20
74
75struct audio_device {
76    struct audio_hw_device hw_device;
77
78    pthread_mutex_t lock; /* see note below on mutex acquisition order */
79
80    /* output */
81    alsa_device_profile out_profile;
82
83    /* input */
84    alsa_device_profile in_profile;
85
86    bool mic_muted;
87
88    bool standby;
89#if TARGET_AUDIO_PRIMARY
90    unsigned int master_volume;
91#endif
92};
93
94struct stream_out {
95    struct audio_stream_out stream;
96
97    pthread_mutex_t lock;               /* see note below on mutex acquisition order */
98    pthread_mutex_t pre_lock;           /* acquire before lock to avoid DOS by playback thread */
99    bool standby;
100
101    struct audio_device *dev;           /* hardware information - only using this for the lock */
102
103    alsa_device_profile * profile;      /* Points to the alsa_device_profile in the audio_device */
104    alsa_device_proxy proxy;            /* state of the stream */
105
106    unsigned hal_channel_count;         /* channel count exposed to AudioFlinger.
107                                         * This may differ from the device channel count when
108                                         * the device is not compatible with AudioFlinger
109                                         * capabilities, e.g. exposes too many channels or
110                                         * too few channels. */
111    audio_channel_mask_t hal_channel_mask;   /* channel mask exposed to AudioFlinger. */
112
113    void * conversion_buffer;           /* any conversions are put into here
114                                         * they could come from here too if
115                                         * there was a previous conversion */
116    size_t conversion_buffer_size;      /* in bytes */
117};
118
119struct stream_in {
120    struct audio_stream_in stream;
121
122    pthread_mutex_t lock;               /* see note below on mutex acquisition order */
123    pthread_mutex_t pre_lock;           /* acquire before lock to avoid DOS by capture thread */
124    bool standby;
125
126    struct audio_device *dev;           /* hardware information - only using this for the lock */
127
128    alsa_device_profile * profile;      /* Points to the alsa_device_profile in the audio_device */
129    alsa_device_proxy proxy;            /* state of the stream */
130
131    unsigned hal_channel_count;         /* channel count exposed to AudioFlinger.
132                                         * This may differ from the device channel count when
133                                         * the device is not compatible with AudioFlinger
134                                         * capabilities, e.g. exposes too many channels or
135                                         * too few channels. */
136    audio_channel_mask_t hal_channel_mask;   /* channel mask exposed to AudioFlinger. */
137
138    /* We may need to read more data from the device in order to data reduce to 16bit, 4chan */
139    void * conversion_buffer;           /* any conversions are put into here
140                                         * they could come from here too if
141                                         * there was a previous conversion */
142    size_t conversion_buffer_size;      /* in bytes */
143};
144
145/*
146 * NOTE: when multiple mutexes have to be acquired, always take the
147 * stream_in or stream_out mutex first, followed by the audio_device mutex.
148 * stream pre_lock is always acquired before stream lock to prevent starvation of control thread by
149 * higher priority playback or capture thread.
150 */
151
152
153static int in_stream_card_number = -1, out_stream_card_number = -1;
154
155
156/*
157 * Examines a pcm-device file to see if its a USB Audio device and
158 * returns its card-number. If no match, returns -1.
159 */
160static int first_valid_sound_card(char *pcm_name, bool is_out_stream)
161{
162    int fd;
163    char pcm_dev_path[MAX_PATH_LEN];
164    struct snd_pcm_info info;
165    char type;
166    int pcm_name_length;
167
168    ALOGV("%s enter",__func__);
169
170    pcm_name_length = strlen(pcm_name);
171    if (pcm_name_length < 2) {
172        return -1;
173    }
174    type = is_out_stream ? 'p' : 'c';
175    /* If pcm out then filename must end with 0p/0c */
176    if ((pcm_name[pcm_name_length -2] != '0') && (pcm_name[pcm_name_length - 1] != type)) {
177        ALOGV("%s exit",__func__);
178        return -1;
179    }
180
181    snprintf(pcm_dev_path, sizeof(pcm_dev_path), "/dev/snd/%s", pcm_name);
182    fd = open(pcm_dev_path, O_RDONLY);
183
184    if (fd != -1) {
185        if (!(ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info))) {
186            if (strstr(info.id, AUDIO_STR)) {
187                close(fd);
188                ALOGV("%s exit",__func__);
189                return info.card;
190            }
191        } else {
192            ALOGE("ioctl failed for file: %s", pcm_dev_path);
193        }
194
195        close(fd);
196    }
197
198    ALOGV("%s exit",__func__);
199    return -1;
200}
201
202/*
203 * Returns the number of the first valid USB Audio card
204 * If none is found, returns -1.
205 */
206static int get_first_sound_card(bool is_out_stream)
207{
208    DIR *dir;
209    struct dirent *de = NULL;
210    int card_nr;
211
212    ALOGV("%s enter",__func__);
213
214    dir = opendir("/dev/snd");
215    if (dir == NULL) {
216        ALOGE("Could not open directory /dev/snd");
217        ALOGV("%s exit",__func__);
218        return -1;
219    }
220
221    while ((de = readdir(dir))) {
222        if (strncmp(de->d_name, PCM_DEV_STR, sizeof(PCM_DEV_STR) - 1) == 0) {
223            if ((card_nr = first_valid_sound_card(de->d_name, is_out_stream)) != -1) {
224                closedir(dir);
225                ALOGV("%s exit",__func__);
226                return card_nr;
227            }
228        }
229    }
230
231    closedir(dir);
232    ALOGW("No usb-card found in /dev/snd");
233    ALOGV("%s exit",__func__);
234    return -1;
235}
236
237static bool parse_card_device_params(bool is_out_stream, int *card, int *device)
238{
239    int try_time;
240    int found_card = -1;
241
242    if (is_out_stream) {
243        if (out_stream_card_number != -1) {
244            *card = out_stream_card_number;
245            *device = 0;
246            return true;
247        }
248    } else {
249        if (in_stream_card_number != -1) {
250            *card = in_stream_card_number;
251            *device = 0;
252            return true;
253        }
254    }
255
256    for (try_time = 0; try_time < NBR_RETRIES; try_time++) {
257        found_card = get_first_sound_card(is_out_stream);
258        if (found_card == -1)
259            usleep(RETRY_WAIT_USEC);
260        else
261            break;
262    }
263
264    if (found_card == -1) {
265        *card = -1;
266        *device = -1;
267        return false;
268    }
269
270    if (is_out_stream) {
271        out_stream_card_number = found_card;
272    } else {
273        in_stream_card_number = found_card;
274    }
275
276    *card = found_card;
277    *device = 0;
278
279    return true;
280}
281
282static char * device_get_parameters(alsa_device_profile * profile, const char * keys)
283{
284    if (profile->card < 0 || profile->device < 0) {
285        return strdup("");
286    }
287
288    struct str_parms *query = str_parms_create_str(keys);
289    struct str_parms *result = str_parms_create();
290
291    /* These keys are from hardware/libhardware/include/audio.h */
292    /* supported sample rates */
293    if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
294        char* rates_list = profile_get_sample_rate_strs(profile);
295        str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES,
296                          rates_list);
297        free(rates_list);
298    }
299
300    /* supported channel counts */
301    if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
302        char* channels_list = profile_get_channel_count_strs(profile);
303        str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_CHANNELS,
304                          channels_list);
305        free(channels_list);
306    }
307
308    /* supported sample formats */
309    if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
310        char * format_params = profile_get_format_strs(profile);
311        str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_FORMATS,
312                          format_params);
313        free(format_params);
314    }
315    str_parms_destroy(query);
316
317    char* result_str = str_parms_to_str(result);
318    str_parms_destroy(result);
319
320    ALOGV("device_get_parameters = %s", result_str);
321
322    return result_str;
323}
324
325void lock_input_stream(struct stream_in *in)
326{
327    pthread_mutex_lock(&in->pre_lock);
328    pthread_mutex_lock(&in->lock);
329    pthread_mutex_unlock(&in->pre_lock);
330}
331
332void lock_output_stream(struct stream_out *out)
333{
334    pthread_mutex_lock(&out->pre_lock);
335    pthread_mutex_lock(&out->lock);
336    pthread_mutex_unlock(&out->pre_lock);
337}
338
339/*
340 * HAl Functions
341 */
342/**
343 * NOTE: when multiple mutexes have to be acquired, always respect the
344 * following order: hw device > out stream
345 */
346
347/*
348 * OUT functions
349 */
350static uint32_t out_get_sample_rate(const struct audio_stream *stream)
351{
352    uint32_t rate = proxy_get_sample_rate(&((struct stream_out*)stream)->proxy);
353    ALOGV("out_get_sample_rate() = %d", rate);
354    return rate;
355}
356
357static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
358{
359    return 0;
360}
361
362static size_t out_get_buffer_size(const struct audio_stream *stream)
363{
364    const struct stream_out* out = (const struct stream_out*)stream;
365    size_t buffer_size =
366        proxy_get_period_size(&out->proxy) * audio_stream_out_frame_size(&(out->stream));
367    return buffer_size;
368}
369
370static uint32_t out_get_channels(const struct audio_stream *stream)
371{
372    const struct stream_out *out = (const struct stream_out*)stream;
373    return out->hal_channel_mask;
374}
375
376static audio_format_t out_get_format(const struct audio_stream *stream)
377{
378    /* Note: The HAL doesn't do any FORMAT conversion at this time. It
379     * Relies on the framework to provide data in the specified format.
380     * This could change in the future.
381     */
382    alsa_device_proxy * proxy = &((struct stream_out*)stream)->proxy;
383    audio_format_t format = audio_format_from_pcm_format(proxy_get_format(proxy));
384    return format;
385}
386
387static int out_set_format(struct audio_stream *stream, audio_format_t format)
388{
389    return 0;
390}
391
392static int out_standby(struct audio_stream *stream)
393{
394    struct stream_out *out = (struct stream_out *)stream;
395    lock_output_stream(out);
396    if (!out->standby) {
397        pthread_mutex_lock(&out->dev->lock);
398        proxy_close(&out->proxy);
399        pthread_mutex_unlock(&out->dev->lock);
400        out->standby = true;
401    }
402    pthread_mutex_unlock(&out->lock);
403
404    return 0;
405}
406
407static int out_dump(const struct audio_stream *stream, int fd)
408{
409    return 0;
410}
411
412static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
413{
414    ALOGV("out_set_parameters() keys:%s", kvpairs);
415
416    struct stream_out *out = (struct stream_out *)stream;
417
418    int routing = 0;
419    int ret_value = 0;
420    int card = -1;
421    int device = -1;
422
423    if (!parse_card_device_params(true, &card, &device)) {
424        // nothing to do
425        return ret_value;
426    }
427
428    lock_output_stream(out);
429    /* Lock the device because that is where the profile lives */
430    pthread_mutex_lock(&out->dev->lock);
431
432    if (!profile_is_cached_for(out->profile, card, device)) {
433        /* cannot read pcm device info if playback is active */
434        if (!out->standby)
435            ret_value = -ENOSYS;
436        else {
437            int saved_card = out->profile->card;
438            int saved_device = out->profile->device;
439            out->profile->card = card;
440            out->profile->device = device;
441            ret_value = profile_read_device_info(out->profile) ? 0 : -EINVAL;
442            if (ret_value != 0) {
443                out->profile->card = saved_card;
444                out->profile->device = saved_device;
445            }
446        }
447    }
448
449    pthread_mutex_unlock(&out->dev->lock);
450    pthread_mutex_unlock(&out->lock);
451
452    return ret_value;
453}
454
455static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
456{
457    struct stream_out *out = (struct stream_out *)stream;
458    lock_output_stream(out);
459    pthread_mutex_lock(&out->dev->lock);
460
461    char * params_str =  device_get_parameters(out->profile, keys);
462
463    pthread_mutex_unlock(&out->lock);
464    pthread_mutex_unlock(&out->dev->lock);
465
466    return params_str;
467}
468
469static uint32_t out_get_latency(const struct audio_stream_out *stream)
470{
471    alsa_device_proxy * proxy = &((struct stream_out*)stream)->proxy;
472    return proxy_get_latency(proxy);
473}
474
475static int out_set_volume(struct audio_stream_out *stream, float left, float right)
476{
477    return -ENOSYS;
478}
479
480/* must be called with hw device and output stream mutexes locked */
481static int start_output_stream(struct stream_out *out)
482{
483    ALOGV("start_output_stream(card:%d device:%d)", out->profile->card, out->profile->device);
484
485    return proxy_open(&out->proxy);
486}
487
488static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes)
489{
490    int ret;
491    struct stream_out *out = (struct stream_out *)stream;
492
493    lock_output_stream(out);
494    if (out->standby) {
495        pthread_mutex_lock(&out->dev->lock);
496        ret = start_output_stream(out);
497        pthread_mutex_unlock(&out->dev->lock);
498        if (ret != 0) {
499            goto err;
500        }
501        out->standby = false;
502    }
503
504    alsa_device_proxy* proxy = &out->proxy;
505    const void * write_buff = buffer;
506    int num_write_buff_bytes = bytes;
507    const int num_device_channels = proxy_get_channel_count(proxy); /* what we told alsa */
508    const int num_req_channels = out->hal_channel_count; /* what we told AudioFlinger */
509    if (num_device_channels != num_req_channels) {
510        /* allocate buffer */
511        const size_t required_conversion_buffer_size =
512                 bytes * num_device_channels / num_req_channels;
513        if (required_conversion_buffer_size > out->conversion_buffer_size) {
514            out->conversion_buffer_size = required_conversion_buffer_size;
515            out->conversion_buffer = realloc(out->conversion_buffer,
516                                             out->conversion_buffer_size);
517        }
518        /* convert data */
519        const audio_format_t audio_format = out_get_format(&(out->stream.common));
520        const unsigned sample_size_in_bytes = audio_bytes_per_sample(audio_format);
521        num_write_buff_bytes =
522                adjust_channels(write_buff, num_req_channels,
523                                out->conversion_buffer, num_device_channels,
524                                sample_size_in_bytes, num_write_buff_bytes);
525        write_buff = out->conversion_buffer;
526    }
527
528    if (write_buff != NULL && num_write_buff_bytes != 0) {
529        proxy_write(&out->proxy, write_buff, num_write_buff_bytes);
530    }
531
532    pthread_mutex_unlock(&out->lock);
533
534    return bytes;
535
536err:
537    pthread_mutex_unlock(&out->lock);
538    if (ret != 0) {
539        usleep(bytes * 1000000 / audio_stream_out_frame_size(stream) /
540               out_get_sample_rate(&stream->common));
541    }
542
543    return bytes;
544}
545
546static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames)
547{
548    return -EINVAL;
549}
550
551static int out_get_presentation_position(const struct audio_stream_out *stream,
552                                         uint64_t *frames, struct timespec *timestamp)
553{
554    struct stream_out *out = (struct stream_out *)stream; // discard const qualifier
555    lock_output_stream(out);
556
557    const alsa_device_proxy *proxy = &out->proxy;
558    const int ret = proxy_get_presentation_position(proxy, frames, timestamp);
559
560    pthread_mutex_unlock(&out->lock);
561    ALOGV("out_get_presentation_position() status:%d  frames:%llu",
562            ret, (unsigned long long)*frames);
563    return ret;
564}
565
566static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
567{
568    return 0;
569}
570
571static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
572{
573    return 0;
574}
575
576static int out_get_next_write_timestamp(const struct audio_stream_out *stream, int64_t *timestamp)
577{
578    return -EINVAL;
579}
580
581static int adev_open_output_stream(struct audio_hw_device *dev,
582                                   audio_io_handle_t handle,
583                                   audio_devices_t devices,
584                                   audio_output_flags_t flags,
585                                   struct audio_config *config,
586                                   struct audio_stream_out **stream_out,
587                                   const char *address /*__unused*/)
588{
589    ALOGV("adev_open_output_stream() handle:0x%X, device:0x%X, flags:0x%X, addr:%s",
590          handle, devices, flags, address);
591
592    struct audio_device *adev = (struct audio_device *)dev;
593
594    struct stream_out *out;
595    out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
596    if (!out)
597        return -ENOMEM;
598
599    /* setup function pointers */
600    out->stream.common.get_sample_rate = out_get_sample_rate;
601    out->stream.common.set_sample_rate = out_set_sample_rate;
602    out->stream.common.get_buffer_size = out_get_buffer_size;
603    out->stream.common.get_channels = out_get_channels;
604    out->stream.common.get_format = out_get_format;
605    out->stream.common.set_format = out_set_format;
606    out->stream.common.standby = out_standby;
607    out->stream.common.dump = out_dump;
608    out->stream.common.set_parameters = out_set_parameters;
609    out->stream.common.get_parameters = out_get_parameters;
610    out->stream.common.add_audio_effect = out_add_audio_effect;
611    out->stream.common.remove_audio_effect = out_remove_audio_effect;
612    out->stream.get_latency = out_get_latency;
613    out->stream.set_volume = out_set_volume;
614    out->stream.write = out_write;
615    out->stream.get_render_position = out_get_render_position;
616    out->stream.get_presentation_position = out_get_presentation_position;
617    out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
618
619    pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
620    pthread_mutex_init(&out->pre_lock, (const pthread_mutexattr_t *) NULL);
621
622    out->dev = adev;
623    pthread_mutex_lock(&adev->lock);
624    out->profile = &adev->out_profile;
625
626    // build this to hand to the alsa_device_proxy
627    struct pcm_config proxy_config;
628    memset(&proxy_config, 0, sizeof(proxy_config));
629
630    /* Pull out the card/device pair */
631    parse_card_device_params(true, &(out->profile->card), &(out->profile->device));
632
633    profile_read_device_info(out->profile);
634
635    pthread_mutex_unlock(&adev->lock);
636
637    int ret = 0;
638
639    /* Rate */
640    if (config->sample_rate == 0) {
641        proxy_config.rate = config->sample_rate = profile_get_default_sample_rate(out->profile);
642    } else if (profile_is_sample_rate_valid(out->profile, config->sample_rate)) {
643        proxy_config.rate = config->sample_rate;
644    } else {
645        ALOGE("%s: The requested sample rate (%d) is not valid", __func__, config->sample_rate);
646        proxy_config.rate = config->sample_rate = profile_get_default_sample_rate(out->profile);
647        ret = -EINVAL;
648    }
649
650    /* Format */
651    if (config->format == AUDIO_FORMAT_DEFAULT) {
652        proxy_config.format = profile_get_default_format(out->profile);
653        config->format = audio_format_from_pcm_format(proxy_config.format);
654    } else {
655        enum pcm_format fmt = pcm_format_from_audio_format(config->format);
656        if (profile_is_format_valid(out->profile, fmt)) {
657            proxy_config.format = fmt;
658        } else {
659            ALOGE("%s: The requested format (0x%x) is not valid", __func__, config->format);
660            proxy_config.format = profile_get_default_format(out->profile);
661            config->format = audio_format_from_pcm_format(proxy_config.format);
662            ret = -EINVAL;
663        }
664    }
665
666    /* Channels */
667    unsigned proposed_channel_count = 0;
668    if (k_force_channels) {
669        proposed_channel_count = k_force_channels;
670    } else if (config->channel_mask == AUDIO_CHANNEL_NONE) {
671        proposed_channel_count =  profile_get_default_channel_count(out->profile);
672    }
673    if (proposed_channel_count != 0) {
674        if (proposed_channel_count <= FCC_2) {
675            // use channel position mask for mono and stereo
676            config->channel_mask = audio_channel_out_mask_from_count(proposed_channel_count);
677        } else {
678            // use channel index mask for multichannel
679            config->channel_mask =
680                    audio_channel_mask_for_index_assignment_from_count(proposed_channel_count);
681        }
682        out->hal_channel_count = proposed_channel_count;
683    } else {
684        out->hal_channel_count = audio_channel_count_from_out_mask(config->channel_mask);
685    }
686    /* we can expose any channel mask, and emulate internally based on channel count. */
687    out->hal_channel_mask = config->channel_mask;
688
689    /* no validity checks are needed as proxy_prepare() forces channel_count to be valid.
690     * and we emulate any channel count discrepancies in out_write(). */
691    proxy_config.channels = proposed_channel_count;
692
693    proxy_prepare(&out->proxy, out->profile, &proxy_config);
694
695    /* TODO The retry mechanism isn't implemented in AudioPolicyManager/AudioFlinger. */
696    ret = 0;
697
698    out->conversion_buffer = NULL;
699    out->conversion_buffer_size = 0;
700
701    out->standby = true;
702
703    *stream_out = &out->stream;
704
705    return ret;
706
707err_open:
708    free(out);
709    *stream_out = NULL;
710    return -ENOSYS;
711}
712
713static void adev_close_output_stream(struct audio_hw_device *dev,
714                                     struct audio_stream_out *stream)
715{
716    struct stream_out *out = (struct stream_out *)stream;
717    ALOGV("adev_close_output_stream(c:%d d:%d)", out->profile->card, out->profile->device);
718    /* Close the pcm device */
719    out_standby(&stream->common);
720
721    free(out->conversion_buffer);
722
723    out->conversion_buffer = NULL;
724    out->conversion_buffer_size = 0;
725
726    free(stream);
727}
728
729static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
730                                         const struct audio_config *config)
731{
732    /* TODO This needs to be calculated based on format/channels/rate */
733    return 320;
734}
735
736/*
737 * IN functions
738 */
739static uint32_t in_get_sample_rate(const struct audio_stream *stream)
740{
741    uint32_t rate = proxy_get_sample_rate(&((const struct stream_in *)stream)->proxy);
742    ALOGV("in_get_sample_rate() = %d", rate);
743    return rate;
744}
745
746static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
747{
748    ALOGV("in_set_sample_rate(%d) - NOPE", rate);
749    return -ENOSYS;
750}
751
752static size_t in_get_buffer_size(const struct audio_stream *stream)
753{
754    const struct stream_in * in = ((const struct stream_in*)stream);
755    return proxy_get_period_size(&in->proxy) * audio_stream_in_frame_size(&(in->stream));
756}
757
758static uint32_t in_get_channels(const struct audio_stream *stream)
759{
760    const struct stream_in *in = (const struct stream_in*)stream;
761    return in->hal_channel_mask;
762}
763
764static audio_format_t in_get_format(const struct audio_stream *stream)
765{
766     alsa_device_proxy *proxy = &((struct stream_in*)stream)->proxy;
767     audio_format_t format = audio_format_from_pcm_format(proxy_get_format(proxy));
768     return format;
769}
770
771static int in_set_format(struct audio_stream *stream, audio_format_t format)
772{
773    ALOGV("in_set_format(%d) - NOPE", format);
774
775    return -ENOSYS;
776}
777
778static int in_standby(struct audio_stream *stream)
779{
780    struct stream_in *in = (struct stream_in *)stream;
781
782    lock_input_stream(in);
783    if (!in->standby) {
784        pthread_mutex_lock(&in->dev->lock);
785        proxy_close(&in->proxy);
786        pthread_mutex_unlock(&in->dev->lock);
787        in->standby = true;
788    }
789
790    pthread_mutex_unlock(&in->lock);
791
792    return 0;
793}
794
795static int in_dump(const struct audio_stream *stream, int fd)
796{
797    return 0;
798}
799
800static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
801{
802    ALOGV("in_set_parameters() keys:%s", kvpairs);
803
804    struct stream_in *in = (struct stream_in *)stream;
805
806    char value[32];
807    int param_val;
808    int routing = 0;
809    int ret_value = 0;
810    int card = -1;
811    int device = -1;
812
813    if (!parse_card_device_params(false, &card, &device)) {
814        // nothing to do
815        return ret_value;
816    }
817
818    lock_input_stream(in);
819    pthread_mutex_lock(&in->dev->lock);
820
821    if (card >= 0 && device >= 0 && !profile_is_cached_for(in->profile, card, device)) {
822        /* cannot read pcm device info if playback is active */
823        if (!in->standby)
824            ret_value = -ENOSYS;
825        else {
826            int saved_card = in->profile->card;
827            int saved_device = in->profile->device;
828            in->profile->card = card;
829            in->profile->device = device;
830            ret_value = profile_read_device_info(in->profile) ? 0 : -EINVAL;
831            if (ret_value != 0) {
832                in->profile->card = saved_card;
833                in->profile->device = saved_device;
834            }
835        }
836    }
837
838    pthread_mutex_unlock(&in->dev->lock);
839    pthread_mutex_unlock(&in->lock);
840
841    return ret_value;
842}
843
844static char * in_get_parameters(const struct audio_stream *stream, const char *keys)
845{
846    struct stream_in *in = (struct stream_in *)stream;
847
848    lock_input_stream(in);
849    pthread_mutex_lock(&in->dev->lock);
850
851    char * params_str =  device_get_parameters(in->profile, keys);
852
853    pthread_mutex_unlock(&in->dev->lock);
854    pthread_mutex_unlock(&in->lock);
855
856    return params_str;
857}
858
859static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
860{
861    return 0;
862}
863
864static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
865{
866    return 0;
867}
868
869static int in_set_gain(struct audio_stream_in *stream, float gain)
870{
871    return 0;
872}
873
874/* must be called with hw device and output stream mutexes locked */
875static int start_input_stream(struct stream_in *in)
876{
877    ALOGV("ustart_input_stream(card:%d device:%d)", in->profile->card, in->profile->device);
878
879    return proxy_open(&in->proxy);
880}
881
882/* TODO mutex stuff here (see out_write) */
883static ssize_t in_read(struct audio_stream_in *stream, void* buffer, size_t bytes)
884{
885    size_t num_read_buff_bytes = 0;
886    void * read_buff = buffer;
887    void * out_buff = buffer;
888    int ret = 0;
889
890    struct stream_in * in = (struct stream_in *)stream;
891
892    lock_input_stream(in);
893    if (in->standby) {
894        pthread_mutex_lock(&in->dev->lock);
895        ret = start_input_stream(in);
896        pthread_mutex_unlock(&in->dev->lock);
897        if (ret != 0) {
898            goto err;
899        }
900        in->standby = false;
901    }
902
903    alsa_device_profile * profile = in->profile;
904
905    /*
906     * OK, we need to figure out how much data to read to be able to output the requested
907     * number of bytes in the HAL format (16-bit, stereo).
908     */
909    num_read_buff_bytes = bytes;
910    int num_device_channels = proxy_get_channel_count(&in->proxy); /* what we told Alsa */
911    int num_req_channels = in->hal_channel_count; /* what we told AudioFlinger */
912
913    if (num_device_channels != num_req_channels) {
914        num_read_buff_bytes = (num_device_channels * num_read_buff_bytes) / num_req_channels;
915    }
916
917    /* Setup/Realloc the conversion buffer (if necessary). */
918    if (num_read_buff_bytes != bytes) {
919        if (num_read_buff_bytes > in->conversion_buffer_size) {
920            /*TODO Remove this when AudioPolicyManger/AudioFlinger support arbitrary formats
921              (and do these conversions themselves) */
922            in->conversion_buffer_size = num_read_buff_bytes;
923            in->conversion_buffer = realloc(in->conversion_buffer, in->conversion_buffer_size);
924        }
925        read_buff = in->conversion_buffer;
926    }
927
928    ret = proxy_read(&in->proxy, read_buff, num_read_buff_bytes);
929    if (ret == 0) {
930        if (num_device_channels != num_req_channels) {
931            // ALOGV("chans dev:%d req:%d", num_device_channels, num_req_channels);
932
933            out_buff = buffer;
934            /* Num Channels conversion */
935            if (num_device_channels != num_req_channels) {
936                audio_format_t audio_format = in_get_format(&(in->stream.common));
937                unsigned sample_size_in_bytes = audio_bytes_per_sample(audio_format);
938
939                num_read_buff_bytes =
940                    adjust_channels(read_buff, num_device_channels,
941                                    out_buff, num_req_channels,
942                                    sample_size_in_bytes, num_read_buff_bytes);
943            }
944        }
945
946        /* no need to acquire in->dev->lock to read mic_muted here as we don't change its state */
947        if (num_read_buff_bytes > 0 && in->dev->mic_muted)
948            memset(buffer, 0, num_read_buff_bytes);
949    } else {
950        num_read_buff_bytes = 0; // reset the value after USB headset is unplugged
951    }
952
953err:
954    pthread_mutex_unlock(&in->lock);
955
956    return num_read_buff_bytes;
957}
958
959static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
960{
961    return 0;
962}
963
964static int adev_open_input_stream(struct audio_hw_device *dev,
965                                  audio_io_handle_t handle,
966                                  audio_devices_t devices,
967                                  struct audio_config *config,
968                                  struct audio_stream_in **stream_in,
969                                  audio_input_flags_t flags __unused,
970                                  const char *address /*__unused*/,
971                                  audio_source_t source __unused)
972{
973    ALOGV("in adev_open_input_stream() rate:%" PRIu32 ", chanMask:0x%" PRIX32 ", fmt:%" PRIu8,
974          config->sample_rate, config->channel_mask, config->format);
975
976    struct stream_in *in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
977    int ret = 0;
978
979    if (in == NULL)
980        return -ENOMEM;
981
982    /* setup function pointers */
983    in->stream.common.get_sample_rate = in_get_sample_rate;
984    in->stream.common.set_sample_rate = in_set_sample_rate;
985    in->stream.common.get_buffer_size = in_get_buffer_size;
986    in->stream.common.get_channels = in_get_channels;
987    in->stream.common.get_format = in_get_format;
988    in->stream.common.set_format = in_set_format;
989    in->stream.common.standby = in_standby;
990    in->stream.common.dump = in_dump;
991    in->stream.common.set_parameters = in_set_parameters;
992    in->stream.common.get_parameters = in_get_parameters;
993    in->stream.common.add_audio_effect = in_add_audio_effect;
994    in->stream.common.remove_audio_effect = in_remove_audio_effect;
995
996    in->stream.set_gain = in_set_gain;
997    in->stream.read = in_read;
998    in->stream.get_input_frames_lost = in_get_input_frames_lost;
999
1000    pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
1001    pthread_mutex_init(&in->pre_lock, (const pthread_mutexattr_t *) NULL);
1002
1003    in->dev = (struct audio_device *)dev;
1004    pthread_mutex_lock(&in->dev->lock);
1005
1006    in->profile = &in->dev->in_profile;
1007
1008    struct pcm_config proxy_config;
1009    memset(&proxy_config, 0, sizeof(proxy_config));
1010
1011    /* Pull out the card/device pair */
1012    parse_card_device_params(false, &(in->profile->card), &(in->profile->device));
1013
1014    profile_read_device_info(in->profile);
1015    pthread_mutex_unlock(&in->dev->lock);
1016
1017    /* Rate */
1018    if (config->sample_rate == 0) {
1019        proxy_config.rate = config->sample_rate = profile_get_default_sample_rate(in->profile);
1020    } else if (profile_is_sample_rate_valid(in->profile, config->sample_rate)) {
1021        proxy_config.rate = config->sample_rate;
1022    } else {
1023        ALOGE("%s: The requested sample rate (%d) is not valid", __func__, config->sample_rate);
1024        proxy_config.rate = config->sample_rate = profile_get_default_sample_rate(in->profile);
1025        ret = -EINVAL;
1026    }
1027
1028    /* Format */
1029    if (config->format == AUDIO_FORMAT_DEFAULT) {
1030        proxy_config.format = profile_get_default_format(in->profile);
1031        config->format = audio_format_from_pcm_format(proxy_config.format);
1032    } else {
1033        enum pcm_format fmt = pcm_format_from_audio_format(config->format);
1034        if (profile_is_format_valid(in->profile, fmt)) {
1035            proxy_config.format = fmt;
1036        } else {
1037            ALOGE("%s: The requested format (0x%x) is not valid", __func__, config->format);
1038            proxy_config.format = profile_get_default_format(in->profile);
1039            config->format = audio_format_from_pcm_format(proxy_config.format);
1040            ret = -EINVAL;
1041        }
1042    }
1043
1044    /* Channels */
1045    unsigned proposed_channel_count = 0;
1046    if (k_force_channels) {
1047        proposed_channel_count = k_force_channels;
1048    } else if (config->channel_mask == AUDIO_CHANNEL_NONE) {
1049        proposed_channel_count = profile_get_default_channel_count(in->profile);
1050    }
1051    if (proposed_channel_count != 0) {
1052        config->channel_mask = audio_channel_in_mask_from_count(proposed_channel_count);
1053        if (config->channel_mask == AUDIO_CHANNEL_INVALID)
1054            config->channel_mask =
1055                    audio_channel_mask_for_index_assignment_from_count(proposed_channel_count);
1056        in->hal_channel_count = proposed_channel_count;
1057    } else {
1058        in->hal_channel_count = audio_channel_count_from_in_mask(config->channel_mask);
1059    }
1060    /* we can expose any channel mask, and emulate internally based on channel count. */
1061    in->hal_channel_mask = config->channel_mask;
1062
1063    proxy_config.channels = profile_get_default_channel_count(in->profile);
1064    proxy_prepare(&in->proxy, in->profile, &proxy_config);
1065
1066    in->standby = true;
1067
1068    in->conversion_buffer = NULL;
1069    in->conversion_buffer_size = 0;
1070
1071    *stream_in = &in->stream;
1072
1073    return ret;
1074}
1075
1076static void adev_close_input_stream(struct audio_hw_device *dev, struct audio_stream_in *stream)
1077{
1078    struct stream_in *in = (struct stream_in *)stream;
1079
1080    /* Close the pcm device */
1081    in_standby(&stream->common);
1082
1083    free(in->conversion_buffer);
1084
1085    free(stream);
1086}
1087
1088/*
1089 * ADEV Functions
1090 */
1091static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
1092{
1093    return 0;
1094}
1095
1096static char * adev_get_parameters(const struct audio_hw_device *dev, const char *keys)
1097{
1098    return strdup("");
1099}
1100
1101static int adev_init_check(const struct audio_hw_device *dev)
1102{
1103    return 0;
1104}
1105
1106static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
1107{
1108    return -ENOSYS;
1109}
1110
1111static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
1112{
1113#if TARGET_AUDIO_PRIMARY
1114    struct mixer *mixer;
1115    struct mixer_ctl *ctl;
1116    struct audio_device * adev = (struct audio_device *)dev;
1117
1118    if ((0 > volume) || (1 < volume) || (NULL == adev))
1119      return -EINVAL;
1120
1121    pthread_mutex_lock(&adev->lock);
1122    adev->master_volume = (int)(volume*100);
1123
1124    if (!(mixer = mixer_open(1))) {
1125      pthread_mutex_unlock(&adev->lock);
1126      return -ENOSYS;
1127    }
1128
1129    ctl = mixer_get_ctl(mixer,29);
1130    mixer_ctl_set_value(ctl,0,adev->master_volume);
1131    mixer_close(mixer);
1132    pthread_mutex_unlock(&adev->lock);
1133    return 0;
1134#else
1135    return -ENOSYS;
1136#endif
1137}
1138
1139static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
1140{
1141    return 0;
1142}
1143
1144static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
1145{
1146    struct audio_device * adev = (struct audio_device *)dev;
1147    pthread_mutex_lock(&adev->lock);
1148    adev->mic_muted = state;
1149    pthread_mutex_unlock(&adev->lock);
1150    return -ENOSYS;
1151}
1152
1153static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1154{
1155    return -ENOSYS;
1156}
1157
1158static int adev_dump(const audio_hw_device_t *device, int fd)
1159{
1160    return 0;
1161}
1162
1163static int adev_close(hw_device_t *device)
1164{
1165    struct audio_device *adev = (struct audio_device *)device;
1166    free(device);
1167
1168    return 0;
1169}
1170
1171static int adev_open(const hw_module_t* module, const char* name, hw_device_t** device)
1172{
1173#if TARGET_AUDIO_PRIMARY
1174    struct mixer *mixer;
1175    struct mixer_ctl *ctl;
1176#endif
1177    if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
1178        return -EINVAL;
1179
1180    struct audio_device *adev = calloc(1, sizeof(struct audio_device));
1181    if (!adev)
1182        return -ENOMEM;
1183
1184    profile_init(&adev->out_profile, PCM_OUT);
1185    profile_init(&adev->in_profile, PCM_IN);
1186
1187    adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
1188    adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
1189    adev->hw_device.common.module = (struct hw_module_t *)module;
1190    adev->hw_device.common.close = adev_close;
1191
1192    adev->hw_device.init_check = adev_init_check;
1193    adev->hw_device.set_voice_volume = adev_set_voice_volume;
1194    adev->hw_device.set_master_volume = adev_set_master_volume;
1195    adev->hw_device.set_mode = adev_set_mode;
1196    adev->hw_device.set_mic_mute = adev_set_mic_mute;
1197    adev->hw_device.get_mic_mute = adev_get_mic_mute;
1198    adev->hw_device.set_parameters = adev_set_parameters;
1199    adev->hw_device.get_parameters = adev_get_parameters;
1200    adev->hw_device.get_input_buffer_size = adev_get_input_buffer_size;
1201    adev->hw_device.open_output_stream = adev_open_output_stream;
1202    adev->hw_device.close_output_stream = adev_close_output_stream;
1203    adev->hw_device.open_input_stream = adev_open_input_stream;
1204    adev->hw_device.close_input_stream = adev_close_input_stream;
1205    adev->hw_device.dump = adev_dump;
1206
1207    *device = &adev->hw_device.common;
1208#if TARGET_AUDIO_PRIMARY
1209    mixer = mixer_open(1);
1210
1211    if (mixer) {
1212        /* turning on master volume */
1213        ctl = mixer_get_ctl(mixer,30);
1214        mixer_ctl_set_value(ctl,0,1);
1215
1216        /* setting master volume to value 50 */
1217        ctl = mixer_get_ctl(mixer,29);
1218        adev->master_volume = 50;
1219        mixer_ctl_set_value(ctl,0,adev->master_volume);
1220        mixer_close(mixer);
1221    }
1222#endif
1223    return 0;
1224}
1225
1226static struct hw_module_methods_t hal_module_methods = {
1227    .open = adev_open,
1228};
1229
1230struct audio_module HAL_MODULE_INFO_SYM = {
1231    .common = {
1232        .tag = HARDWARE_MODULE_TAG,
1233        .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
1234        .hal_api_version = HARDWARE_HAL_API_VERSION,
1235        .id = AUDIO_HARDWARE_MODULE_ID,
1236        .name = "audio HW HAL",
1237        .author = "The Android Open Source Project",
1238        .methods = &hal_module_methods,
1239    },
1240};
1241