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