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