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