OSDN Git Service

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