OSDN Git Service

Multi-format USB audio input
[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 /* This is the default configuration to hand to The Framework on the initial
40  * adev_open_output_stream(). Actual device attributes will be used on the subsequent
41  * adev_open_output_stream() after the card and device number have been set in out_set_parameters()
42  */
43 #define OUT_PERIOD_SIZE 1024
44 #define OUT_PERIOD_COUNT 4
45 #define OUT_SAMPLING_RATE 44100
46
47 struct pcm_config default_alsa_out_config = {
48     .channels = 2,
49     .rate = OUT_SAMPLING_RATE,
50     .period_size = OUT_PERIOD_SIZE,
51     .period_count = OUT_PERIOD_COUNT,
52     .format = PCM_FORMAT_S16_LE,
53 };
54
55 /*
56  * Input defaults.  See comment above.
57  */
58 #define IN_PERIOD_SIZE 1024
59 #define IN_PERIOD_COUNT 4
60 #define IN_SAMPLING_RATE 44100
61
62 struct pcm_config default_alsa_in_config = {
63     .channels = 2,
64     .rate = IN_SAMPLING_RATE,
65     .period_size = IN_PERIOD_SIZE,
66     .period_count = IN_PERIOD_COUNT,
67     .format = PCM_FORMAT_S16_LE,
68     .start_threshold = 1,
69     .stop_threshold = (IN_PERIOD_SIZE * IN_PERIOD_COUNT),
70 };
71
72 struct audio_device {
73     struct audio_hw_device hw_device;
74
75     pthread_mutex_t lock; /* see note below on mutex acquisition order */
76
77     /* output */
78     int out_card;
79     int out_device;
80
81     /* input */
82     int in_card;
83     int in_device;
84
85     bool standby;
86 };
87
88 struct stream_out {
89     struct audio_stream_out stream;
90
91     pthread_mutex_t lock;               /* see note below on mutex acquisition order */
92     struct pcm *pcm;                    /* state of the stream */
93     bool standby;
94
95     struct audio_device *dev;           /* hardware information */
96
97     void * conversion_buffer;           /* any conversions are put into here
98                                          * they could come from here too if
99                                          * there was a previous conversion */
100     size_t conversion_buffer_size;      /* in bytes */
101 };
102
103 /*
104  * Output Configuration Cache
105  * FIXME(pmclean) This is not reentrant. Should probably be moved into the stream structure.
106  */
107 static struct pcm_config cached_output_hardware_config;
108 static bool output_hardware_config_is_cached = false;
109
110 struct stream_in {
111     struct audio_stream_in stream;
112
113     pthread_mutex_t lock; /* see note below on mutex acquisition order */
114     struct pcm *pcm;
115     bool standby;
116
117     struct audio_device *dev;
118
119     struct audio_config hal_pcm_config;
120
121     /* this is the format the framework thinks it's using. We may need to convert from the actual
122      * (24-bit, 32-bit?) format to this theoretical (framework, probably 16-bit)
123      * format in in_read() */
124     enum pcm_format input_framework_format;
125
126 //    struct resampler_itfe *resampler;
127 //    struct resampler_buffer_provider buf_provider;
128
129     int read_status;
130
131     // We may need to read more data from the device in order to data reduce to 16bit, 4chan */
132     void * conversion_buffer;           /* any conversions are put into here
133                                          * they could come from here too if
134                                          * there was a previous conversion */
135     size_t conversion_buffer_size;      /* in bytes */
136 };
137
138 /*
139  * Input Configuration Cache
140  * FIXME(pmclean) This is not reentrant. Should probably be moved into the stream structure
141  * but that will involve changes in The Framework.
142  */
143 static struct pcm_config cached_input_hardware_config;
144 static bool input_hardware_config_is_cached = false;
145
146 /*
147  * Utility
148  */
149 /*
150  * Data Conversions
151  */
152 /*
153  * Convert a buffer of packed (3-byte) PCM24LE samples to PCM16LE samples.
154  *   in_buff points to the buffer of PCM24LE 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 PCM24_3LE (24-bit, packed).
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_24_3_to_16(const unsigned char * in_buff, size_t num_in_samples,
166                                  short * out_buff)
167 {
168     /*
169      * Move from front to back so that the conversion can be done in-place
170      * i.e. in_buff == out_buff
171      */
172     /* we need 2 bytes in the output for every 3 bytes in the input */
173     unsigned char* dst_ptr = (unsigned char*)out_buff;
174     const unsigned char* src_ptr = in_buff;
175     size_t src_smpl_index;
176     for (src_smpl_index = 0; src_smpl_index < num_in_samples; src_smpl_index++) {
177         src_ptr++;               /* lowest-(skip)-byte */
178         *dst_ptr++ = *src_ptr++; /* low-byte */
179         *dst_ptr++ = *src_ptr++; /* high-byte */
180     }
181
182     /* return number of *bytes* generated: */
183     return num_in_samples * 2;
184 }
185
186 /*
187  * Convert a buffer of packed (3-byte) PCM32 samples to PCM16LE samples.
188  *   in_buff points to the buffer of PCM32 samples
189  *   num_in_samples size of input buffer in SAMPLES
190  *   out_buff points to the buffer to receive converted PCM16LE LE samples.
191  * returns
192  *   the number of BYTES of output data.
193  * We are doing this since we *always* present to The Framework as A PCM16LE device, but need to
194  * support PCM_FORMAT_S32_LE (32-bit).
195  * NOTE:
196  *   This conversion is safe to do in-place (in_buff == out_buff).
197  * TODO Move this to a utilities module.
198  */
199 static size_t convert_32_to_16(const int32_t * in_buff, size_t num_in_samples, short * out_buff)
200 {
201     /*
202      * Move from front to back so that the conversion can be done in-place
203      * i.e. in_buff == out_buff
204      */
205
206     short * dst_ptr = out_buff;
207     const int32_t* src_ptr = in_buff;
208     size_t src_smpl_index;
209     for (src_smpl_index = 0; src_smpl_index < num_in_samples; src_smpl_index++) {
210         *dst_ptr++ = *src_ptr++ >> 16;
211     }
212
213     /* return number of *bytes* generated: */
214     return num_in_samples * 2;
215 }
216
217 /*
218  * Convert a buffer of N-channel, interleaved PCM16 samples to M-channel PCM16 channels
219  * (where N < M).
220  *   in_buff points to the buffer of PCM16 samples
221  *   in_buff_channels Specifies the number of channels in the input buffer.
222  *   out_buff points to the buffer to receive converted PCM16 samples.
223  *   out_buff_channels Specifies the number of channels in the output buffer.
224  *   num_in_samples size of input buffer in SAMPLES
225  * returns
226  *   the number of BYTES of output data.
227  * NOTE
228  *   channels > N are filled with silence.
229  *   This conversion is safe to do in-place (in_buff == out_buff)
230  * We are doing this since we *always* present to The Framework as STEREO device, but need to
231  * support 4-channel devices.
232  * TODO Move this to a utilities module.
233  */
234 static size_t expand_channels_16(const short* in_buff, int in_buff_chans,
235                                  short* out_buff, int out_buff_chans,
236                                  size_t num_in_samples)
237 {
238     /*
239      * Move from back to front so that the conversion can be done in-place
240      * i.e. in_buff == out_buff
241      * NOTE: num_in_samples * out_buff_channels must be an even multiple of in_buff_chans
242      */
243     int num_out_samples = (num_in_samples * out_buff_chans)/in_buff_chans;
244
245     short* dst_ptr = out_buff + num_out_samples - 1;
246     size_t src_index;
247     const short* src_ptr = in_buff + num_in_samples - 1;
248     int num_zero_chans = out_buff_chans - in_buff_chans;
249     for (src_index = 0; src_index < num_in_samples; src_index += in_buff_chans) {
250         int dst_offset;
251         for (dst_offset = 0; dst_offset < num_zero_chans; dst_offset++) {
252             *dst_ptr-- = 0;
253         }
254         for (; dst_offset < out_buff_chans; dst_offset++) {
255             *dst_ptr-- = *src_ptr--;
256         }
257     }
258
259     /* return number of *bytes* generated */
260     return num_out_samples * sizeof(short);
261 }
262
263 /*
264  * Convert a buffer of N-channel, interleaved PCM16 samples to M-channel PCM16 channels
265  * (where N > M).
266  *   in_buff points to the buffer of PCM16 samples
267  *   in_buff_channels Specifies the number of channels in the input buffer.
268  *   out_buff points to the buffer to receive converted PCM16 samples.
269  *   out_buff_channels Specifies the number of channels in the output buffer.
270  *   num_in_samples size of input buffer in SAMPLES
271  * returns
272  *   the number of BYTES of output data.
273  * NOTE
274  *   channels > N are thrown away.
275  *   This conversion is safe to do in-place (in_buff == out_buff)
276  * We are doing this since we *always* present to The Framework as STEREO device, but need to
277  * support 4-channel devices.
278  * TODO Move this to a utilities module.
279  */
280 static size_t contract_channels_16(short* in_buff, int in_buff_chans,
281                                    short* out_buff, int out_buff_chans,
282                                    size_t num_in_samples)
283 {
284     /*
285      * Move from front to back so that the conversion can be done in-place
286      * i.e. in_buff == out_buff
287      * NOTE: num_in_samples * out_buff_channels must be an even multiple of in_buff_chans
288      */
289     int num_out_samples = (num_in_samples * out_buff_chans)/in_buff_chans;
290
291     int num_skip_samples = in_buff_chans - out_buff_chans;
292
293     short* dst_ptr = out_buff;
294     short* src_ptr = in_buff;
295     size_t src_index;
296     for (src_index = 0; src_index < num_in_samples; src_index += in_buff_chans) {
297         int dst_offset;
298         for (dst_offset = 0; dst_offset < out_buff_chans; dst_offset++) {
299             *dst_ptr++ = *src_ptr++;
300         }
301         src_ptr += num_skip_samples;
302     }
303
304     /* return number of *bytes* generated */
305     return num_out_samples * sizeof(short);
306 }
307
308 /*
309  * ALSA Utilities
310  */
311 /*TODO This table and the function that uses it should be moved to a utilities module (probably) */
312 /*
313  * Maps bit-positions in a pcm_mask to the corresponding AUDIO_ format string.
314  */
315 static const char * const format_string_map[] = {
316     "AUDIO_FORMAT_PCM_8_BIT",           /* 00 - SNDRV_PCM_FORMAT_S8 */
317     "AUDIO_FORMAT_PCM_8_BIT",           /* 01 - SNDRV_PCM_FORMAT_U8 */
318     "AUDIO_FORMAT_PCM_16_BIT",          /* 02 - SNDRV_PCM_FORMAT_S16_LE */
319     NULL,                               /* 03 - SNDRV_PCM_FORMAT_S16_BE */
320     NULL,                               /* 04 - SNDRV_PCM_FORMAT_U16_LE */
321     NULL,                               /* 05 - SNDRV_PCM_FORMAT_U16_BE */
322     "AUDIO_FORMAT_PCM_24_BIT_PACKED",   /* 06 - SNDRV_PCM_FORMAT_S24_LE */
323     NULL,                               /* 07 - SNDRV_PCM_FORMAT_S24_BE */
324     NULL,                               /* 08 - SNDRV_PCM_FORMAT_U24_LE */
325     NULL,                               /* 09 - SNDRV_PCM_FORMAT_U24_BE */
326     "AUDIO_FORMAT_PCM_32_BIT",          /* 10 - SNDRV_PCM_FORMAT_S32_LE */
327     NULL,                               /* 11 - SNDRV_PCM_FORMAT_S32_BE */
328     NULL,                               /* 12 - SNDRV_PCM_FORMAT_U32_LE */
329     NULL,                               /* 13 - SNDRV_PCM_FORMAT_U32_BE */
330     "AUDIO_FORMAT_PCM_FLOAT",           /* 14 - SNDRV_PCM_FORMAT_FLOAT_LE */
331     NULL,                               /* 15 - SNDRV_PCM_FORMAT_FLOAT_BE */
332     NULL,                               /* 16 - SNDRV_PCM_FORMAT_FLOAT64_LE */
333     NULL,                               /* 17 - SNDRV_PCM_FORMAT_FLOAT64_BE */
334     NULL,                               /* 18 - SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE */
335     NULL,                               /* 19 - SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE */
336     NULL,                               /* 20 - SNDRV_PCM_FORMAT_MU_LAW */
337     NULL,                               /* 21 - SNDRV_PCM_FORMAT_A_LAW */
338     NULL,                               /* 22 - SNDRV_PCM_FORMAT_IMA_ADPCM */
339     NULL,                               /* 23 - SNDRV_PCM_FORMAT_MPEG */
340     NULL,                               /* 24 - SNDRV_PCM_FORMAT_GSM */
341     NULL, NULL, NULL, NULL, NULL, NULL, /* 25 -> 30 (not assigned) */
342     NULL,                               /* 31 - SNDRV_PCM_FORMAT_SPECIAL */
343     "AUDIO_FORMAT_PCM_24_BIT_PACKED",   /* 32 - SNDRV_PCM_FORMAT_S24_3LE */ /* ??? */
344     NULL,                               /* 33 - SNDRV_PCM_FORMAT_S24_3BE */
345     NULL,                               /* 34 - SNDRV_PCM_FORMAT_U24_3LE */
346     NULL,                               /* 35 - SNDRV_PCM_FORMAT_U24_3BE */
347     NULL,                               /* 36 - SNDRV_PCM_FORMAT_S20_3LE */
348     NULL,                               /* 37 - SNDRV_PCM_FORMAT_S20_3BE */
349     NULL,                               /* 38 - SNDRV_PCM_FORMAT_U20_3LE */
350     NULL,                               /* 39 - SNDRV_PCM_FORMAT_U20_3BE */
351     NULL,                               /* 40 - SNDRV_PCM_FORMAT_S18_3LE */
352     NULL,                               /* 41 - SNDRV_PCM_FORMAT_S18_3BE */
353     NULL,                               /* 42 - SNDRV_PCM_FORMAT_U18_3LE */
354     NULL,                               /* 43 - SNDRV_PCM_FORMAT_U18_3BE */
355     NULL,                               /* 44 - SNDRV_PCM_FORMAT_G723_24 */
356     NULL,                               /* 45 - SNDRV_PCM_FORMAT_G723_24_1B */
357     NULL,                               /* 46 - SNDRV_PCM_FORMAT_G723_40 */
358     NULL,                               /* 47 - SNDRV_PCM_FORMAT_G723_40_1B */
359     NULL,                               /* 48 - SNDRV_PCM_FORMAT_DSD_U8 */
360     NULL                                /* 49 - SNDRV_PCM_FORMAT_DSD_U16_LE */
361 };
362
363 /*
364  * Generate string containing a bar ("|") delimited list of AUDIO_ formats specified in
365  * the mask parameter.
366  *
367  */
368 static char* get_format_str_for_mask(struct pcm_mask* mask)
369 {
370     char buffer[256];
371     int buffer_size = sizeof(buffer) / sizeof(buffer[0]);
372     buffer[0] = '\0';
373
374     int num_slots = sizeof(mask->bits) / sizeof(mask->bits[0]);
375     int bits_per_slot = sizeof(mask->bits[0]) * 8;
376
377     const char* format_str = NULL;
378     int table_size = sizeof(format_string_map)/sizeof(format_string_map[0]);
379
380     int slot_index, bit_index, table_index;
381     table_index = 0;
382     int num_written = 0;
383     for (slot_index = 0; slot_index < num_slots; slot_index++) {
384         unsigned bit_mask = 1;
385         for (bit_index = 0; bit_index < bits_per_slot; bit_index++) {
386             if ((mask->bits[slot_index] & bit_mask) != 0) {
387                 format_str = table_index < table_size
388                                 ? format_string_map[table_index]
389                                 : NULL;
390                 if (format_str != NULL) {
391                     if (num_written != 0) {
392                         num_written += snprintf(buffer + num_written,
393                                                 buffer_size - num_written, "|");
394                     }
395                     num_written += snprintf(buffer + num_written, buffer_size - num_written,
396                                             "%s", format_str);
397                 }
398             }
399             bit_mask <<= 1;
400             table_index++;
401         }
402     }
403
404     return strdup(buffer);
405 }
406
407 /*
408  * Maps from bit position in pcm_mask to AUDIO_ format constants.
409  */
410 static audio_format_t const format_value_map[] = {
411     AUDIO_FORMAT_PCM_8_BIT,           /* 00 - SNDRV_PCM_FORMAT_S8 */
412     AUDIO_FORMAT_PCM_8_BIT,           /* 01 - SNDRV_PCM_FORMAT_U8 */
413     AUDIO_FORMAT_PCM_16_BIT,          /* 02 - SNDRV_PCM_FORMAT_S16_LE */
414     AUDIO_FORMAT_INVALID,             /* 03 - SNDRV_PCM_FORMAT_S16_BE */
415     AUDIO_FORMAT_INVALID,             /* 04 - SNDRV_PCM_FORMAT_U16_LE */
416     AUDIO_FORMAT_INVALID,             /* 05 - SNDRV_PCM_FORMAT_U16_BE */
417     AUDIO_FORMAT_INVALID,             /* 06 - SNDRV_PCM_FORMAT_S24_LE */
418     AUDIO_FORMAT_INVALID,             /* 07 - SNDRV_PCM_FORMAT_S24_BE */
419     AUDIO_FORMAT_INVALID,             /* 08 - SNDRV_PCM_FORMAT_U24_LE */
420     AUDIO_FORMAT_INVALID,             /* 09 - SNDRV_PCM_FORMAT_U24_BE */
421     AUDIO_FORMAT_PCM_32_BIT,          /* 10 - SNDRV_PCM_FORMAT_S32_LE */
422     AUDIO_FORMAT_INVALID,             /* 11 - SNDRV_PCM_FORMAT_S32_BE */
423     AUDIO_FORMAT_INVALID,             /* 12 - SNDRV_PCM_FORMAT_U32_LE */
424     AUDIO_FORMAT_INVALID,             /* 13 - SNDRV_PCM_FORMAT_U32_BE */
425     AUDIO_FORMAT_PCM_FLOAT,           /* 14 - SNDRV_PCM_FORMAT_FLOAT_LE */
426     AUDIO_FORMAT_INVALID,             /* 15 - SNDRV_PCM_FORMAT_FLOAT_BE */
427     AUDIO_FORMAT_INVALID,             /* 16 - SNDRV_PCM_FORMAT_FLOAT64_LE */
428     AUDIO_FORMAT_INVALID,             /* 17 - SNDRV_PCM_FORMAT_FLOAT64_BE */
429     AUDIO_FORMAT_INVALID,             /* 18 - SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE */
430     AUDIO_FORMAT_INVALID,             /* 19 - SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE */
431     AUDIO_FORMAT_INVALID,             /* 20 - SNDRV_PCM_FORMAT_MU_LAW */
432     AUDIO_FORMAT_INVALID,             /* 21 - SNDRV_PCM_FORMAT_A_LAW */
433     AUDIO_FORMAT_INVALID,             /* 22 - SNDRV_PCM_FORMAT_IMA_ADPCM */
434     AUDIO_FORMAT_INVALID,             /* 23 - SNDRV_PCM_FORMAT_MPEG */
435     AUDIO_FORMAT_INVALID,             /* 24 - SNDRV_PCM_FORMAT_GSM */
436     AUDIO_FORMAT_INVALID,             /* 25 -> 30 (not assigned) */
437     AUDIO_FORMAT_INVALID,
438     AUDIO_FORMAT_INVALID,
439     AUDIO_FORMAT_INVALID,
440     AUDIO_FORMAT_INVALID,
441     AUDIO_FORMAT_INVALID,
442     AUDIO_FORMAT_INVALID,             /* 31 - SNDRV_PCM_FORMAT_SPECIAL */
443     AUDIO_FORMAT_PCM_24_BIT_PACKED,   /* 32 - SNDRV_PCM_FORMAT_S24_3LE */
444     AUDIO_FORMAT_INVALID,             /* 33 - SNDRV_PCM_FORMAT_S24_3BE */
445     AUDIO_FORMAT_INVALID,             /* 34 - SNDRV_PCM_FORMAT_U24_3LE */
446     AUDIO_FORMAT_INVALID,             /* 35 - SNDRV_PCM_FORMAT_U24_3BE */
447     AUDIO_FORMAT_INVALID,             /* 36 - SNDRV_PCM_FORMAT_S20_3LE */
448     AUDIO_FORMAT_INVALID,             /* 37 - SNDRV_PCM_FORMAT_S20_3BE */
449     AUDIO_FORMAT_INVALID,             /* 38 - SNDRV_PCM_FORMAT_U20_3LE */
450     AUDIO_FORMAT_INVALID,             /* 39 - SNDRV_PCM_FORMAT_U20_3BE */
451     AUDIO_FORMAT_INVALID,             /* 40 - SNDRV_PCM_FORMAT_S18_3LE */
452     AUDIO_FORMAT_INVALID,             /* 41 - SNDRV_PCM_FORMAT_S18_3BE */
453     AUDIO_FORMAT_INVALID,             /* 42 - SNDRV_PCM_FORMAT_U18_3LE */
454     AUDIO_FORMAT_INVALID,             /* 43 - SNDRV_PCM_FORMAT_U18_3BE */
455     AUDIO_FORMAT_INVALID,             /* 44 - SNDRV_PCM_FORMAT_G723_24 */
456     AUDIO_FORMAT_INVALID,             /* 45 - SNDRV_PCM_FORMAT_G723_24_1B */
457     AUDIO_FORMAT_INVALID,             /* 46 - SNDRV_PCM_FORMAT_G723_40 */
458     AUDIO_FORMAT_INVALID,             /* 47 - SNDRV_PCM_FORMAT_G723_40_1B */
459     AUDIO_FORMAT_INVALID,             /* 48 - SNDRV_PCM_FORMAT_DSD_U8 */
460     AUDIO_FORMAT_INVALID              /* 49 - SNDRV_PCM_FORMAT_DSD_U16_LE */
461 };
462
463 /*
464  * Returns true if mask indicates support for PCM_16.
465  */
466 static bool mask_has_pcm_16(struct pcm_mask* mask) {
467     return (mask->bits[0] & 0x0004) != 0;
468 }
469
470 static int get_format_for_mask(struct pcm_mask* mask)
471 {
472     int num_slots = sizeof(mask->bits)/ sizeof(mask->bits[0]);
473     int bits_per_slot = sizeof(mask->bits[0]) * 8;
474
475     int table_size = sizeof(format_value_map) / sizeof(format_value_map[0]);
476
477     int slot_index, bit_index, table_index;
478     table_index = 0;
479     int num_written = 0;
480     for (slot_index = 0; slot_index < num_slots; slot_index++) {
481         unsigned bit_mask = 1;
482         for (bit_index = 0; bit_index < bits_per_slot; bit_index++) {
483             if ((mask->bits[slot_index] & bit_mask) != 0) {
484                 /* just return the first one */
485                 return table_index < table_size
486                            ? format_value_map[table_index]
487                            : AUDIO_FORMAT_INVALID;
488             }
489             bit_mask <<= 1;
490             table_index++;
491         }
492     }
493
494     return AUDIO_FORMAT_INVALID;
495 }
496
497 /*
498  * Maps from bit position in pcm_mask to AUDIO_ format constants.
499  */
500 static int const pcm_format_value_map[] = {
501     PCM_FORMAT_S8,          /* 00 - SNDRV_PCM_FORMAT_S8 */
502     0,                      /* 01 - SNDRV_PCM_FORMAT_U8 */
503     PCM_FORMAT_S16_LE,      /* 02 - SNDRV_PCM_FORMAT_S16_LE */
504     0,                      /* 03 - SNDRV_PCM_FORMAT_S16_BE */
505     0,                      /* 04 - SNDRV_PCM_FORMAT_U16_LE */
506     0,                      /* 05 - SNDRV_PCM_FORMAT_U16_BE */
507     PCM_FORMAT_S24_3LE,     /* 06 - SNDRV_PCM_FORMAT_S24_LE */
508     0,                      /* 07 - SNDRV_PCM_FORMAT_S24_BE */
509     0,                      /* 08 - SNDRV_PCM_FORMAT_U24_LE */
510     0,                      /* 09 - SNDRV_PCM_FORMAT_U24_BE */
511     PCM_FORMAT_S32_LE,      /* 10 - SNDRV_PCM_FORMAT_S32_LE */
512     0,                      /* 11 - SNDRV_PCM_FORMAT_S32_BE */
513     0,                      /* 12 - SNDRV_PCM_FORMAT_U32_LE */
514     0,                      /* 13 - SNDRV_PCM_FORMAT_U32_BE */
515     0,                      /* 14 - SNDRV_PCM_FORMAT_FLOAT_LE */
516     0,                      /* 15 - SNDRV_PCM_FORMAT_FLOAT_BE */
517     0,                      /* 16 - SNDRV_PCM_FORMAT_FLOAT64_LE */
518     0,                      /* 17 - SNDRV_PCM_FORMAT_FLOAT64_BE */
519     0,                      /* 18 - SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE */
520     0,                      /* 19 - SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE */
521     0,                      /* 20 - SNDRV_PCM_FORMAT_MU_LAW */
522     0,                      /* 21 - SNDRV_PCM_FORMAT_A_LAW */
523     0,                      /* 22 - SNDRV_PCM_FORMAT_IMA_ADPCM */
524     0,                      /* 23 - SNDRV_PCM_FORMAT_MPEG */
525     0,                      /* 24 - SNDRV_PCM_FORMAT_GSM */
526     0,                      /* 25 -> 30 (not assigned) */
527     0,
528     0,
529     0,
530     0,
531     0,
532     0,                      /* 31 - SNDRV_PCM_FORMAT_SPECIAL */
533     PCM_FORMAT_S24_3LE,     /* 32 - SNDRV_PCM_FORMAT_S24_3LE */ /* ??? */
534     0,                      /* 33 - SNDRV_PCM_FORMAT_S24_3BE */
535     0,                      /* 34 - SNDRV_PCM_FORMAT_U24_3LE */
536     0,                      /* 35 - SNDRV_PCM_FORMAT_U24_3BE */
537     0,                      /* 36 - SNDRV_PCM_FORMAT_S20_3LE */
538     0,                      /* 37 - SNDRV_PCM_FORMAT_S20_3BE */
539     0,                      /* 38 - SNDRV_PCM_FORMAT_U20_3LE */
540     0,                      /* 39 - SNDRV_PCM_FORMAT_U20_3BE */
541     0,                      /* 40 - SNDRV_PCM_FORMAT_S18_3LE */
542     0,                      /* 41 - SNDRV_PCM_FORMAT_S18_3BE */
543     0,                      /* 42 - SNDRV_PCM_FORMAT_U18_3LE */
544     0,                      /* 43 - SNDRV_PCM_FORMAT_U18_3BE */
545     0,                      /* 44 - SNDRV_PCM_FORMAT_G723_24 */
546     0,                      /* 45 - SNDRV_PCM_FORMAT_G723_24_1B */
547     0,                      /* 46 - SNDRV_PCM_FORMAT_G723_40 */
548     0,                      /* 47 - SNDRV_PCM_FORMAT_G723_40_1B */
549     0,                      /* 48 - SNDRV_PCM_FORMAT_DSD_U8 */
550     0                       /* 49 - SNDRV_PCM_FORMAT_DSD_U16_LE */
551 };
552
553 static int get_pcm_format_for_mask(struct pcm_mask* mask) {
554     int num_slots = sizeof(mask->bits)/ sizeof(mask->bits[0]);
555     int bits_per_slot = sizeof(mask->bits[0]) * 8;
556
557     int table_size = sizeof(pcm_format_value_map) / sizeof(pcm_format_value_map[0]);
558
559     int slot_index, bit_index, table_index;
560     table_index = 0;
561     int num_written = 0;
562     for (slot_index = 0; slot_index < num_slots; slot_index++) {
563         unsigned bit_mask = 1;
564         for (bit_index = 0; bit_index < bits_per_slot; bit_index++) {
565             if ((mask->bits[slot_index] & bit_mask) != 0) {
566                 /* just return the first one */
567                 return table_index < table_size
568                            ? pcm_format_value_map[table_index]
569                            : AUDIO_FORMAT_INVALID;
570             }
571             bit_mask <<= 1;
572             table_index++;
573         }
574     }
575
576     return 0; // is this right?
577 }
578
579 static void log_pcm_mask(const char* mask_name, struct pcm_mask* mask) {
580     char buff[512];
581     char bit_buff[32];
582     int buffSize = sizeof(buff)/sizeof(buff[0]);
583
584     buff[0] = '\0';
585
586     int num_slots = sizeof(mask->bits) / sizeof(mask->bits[0]);
587     int bits_per_slot = sizeof(mask->bits[0]) * 8;
588
589     int slot_index, bit_index;
590     strcat(buff, "[");
591     for (slot_index = 0; slot_index < num_slots; slot_index++) {
592         unsigned bit_mask = 1;
593         for (bit_index = 0; bit_index < bits_per_slot; bit_index++) {
594             strcat(buff, (mask->bits[slot_index] & bit_mask) != 0 ? "1" : "0");
595             bit_mask <<= 1;
596         }
597         if (slot_index < num_slots - 1) {
598             strcat(buff, ",");
599         }
600     }
601     strcat(buff, "]");
602
603     ALOGV("usb:audio_hw - %s mask:%s", mask_name, buff);
604 }
605
606 static void log_pcm_params(struct pcm_params * alsa_hw_params) {
607     ALOGV("usb:audio_hw - PCM_PARAM_SAMPLE_BITS min:%u, max:%u",
608           pcm_params_get_min(alsa_hw_params, PCM_PARAM_SAMPLE_BITS),
609           pcm_params_get_max(alsa_hw_params, PCM_PARAM_SAMPLE_BITS));
610     ALOGV("usb:audio_hw - PCM_PARAM_FRAME_BITS min:%u, max:%u",
611           pcm_params_get_min(alsa_hw_params, PCM_PARAM_FRAME_BITS),
612           pcm_params_get_max(alsa_hw_params, PCM_PARAM_FRAME_BITS));
613     log_pcm_mask("PCM_PARAM_FORMAT", pcm_params_get_mask(alsa_hw_params, PCM_PARAM_FORMAT));
614     log_pcm_mask("PCM_PARAM_SUBFORMAT", pcm_params_get_mask(alsa_hw_params, PCM_PARAM_SUBFORMAT));
615     ALOGV("usb:audio_hw - PCM_PARAM_CHANNELS min:%u, max:%u",
616           pcm_params_get_min(alsa_hw_params, PCM_PARAM_CHANNELS),
617           pcm_params_get_max(alsa_hw_params, PCM_PARAM_CHANNELS));
618     ALOGV("usb:audio_hw - PCM_PARAM_RATE min:%u, max:%u",
619           pcm_params_get_min(alsa_hw_params, PCM_PARAM_RATE),
620           pcm_params_get_max(alsa_hw_params, PCM_PARAM_RATE));
621     ALOGV("usb:audio_hw - PCM_PARAM_PERIOD_TIME min:%u, max:%u",
622           pcm_params_get_min(alsa_hw_params, PCM_PARAM_PERIOD_TIME),
623           pcm_params_get_max(alsa_hw_params, PCM_PARAM_PERIOD_TIME));
624     ALOGV("usb:audio_hw - PCM_PARAM_PERIOD_SIZE min:%u, max:%u",
625           pcm_params_get_min(alsa_hw_params, PCM_PARAM_PERIOD_SIZE),
626           pcm_params_get_max(alsa_hw_params, PCM_PARAM_PERIOD_SIZE));
627     ALOGV("usb:audio_hw - PCM_PARAM_PERIOD_BYTES min:%u, max:%u",
628           pcm_params_get_min(alsa_hw_params, PCM_PARAM_PERIOD_BYTES),
629           pcm_params_get_max(alsa_hw_params, PCM_PARAM_PERIOD_BYTES));
630     ALOGV("usb:audio_hw - PCM_PARAM_PERIODS min:%u, max:%u",
631           pcm_params_get_min(alsa_hw_params, PCM_PARAM_PERIODS),
632           pcm_params_get_max(alsa_hw_params, PCM_PARAM_PERIODS));
633     ALOGV("usb:audio_hw - PCM_PARAM_BUFFER_TIME min:%u, max:%u",
634           pcm_params_get_min(alsa_hw_params, PCM_PARAM_BUFFER_TIME),
635           pcm_params_get_max(alsa_hw_params, PCM_PARAM_BUFFER_TIME));
636     ALOGV("usb:audio_hw - PCM_PARAM_BUFFER_SIZE min:%u, max:%u",
637           pcm_params_get_min(alsa_hw_params, PCM_PARAM_BUFFER_SIZE),
638           pcm_params_get_max(alsa_hw_params, PCM_PARAM_BUFFER_SIZE));
639     ALOGV("usb:audio_hw - PCM_PARAM_BUFFER_BYTES min:%u, max:%u",
640           pcm_params_get_min(alsa_hw_params, PCM_PARAM_BUFFER_BYTES),
641           pcm_params_get_max(alsa_hw_params, PCM_PARAM_BUFFER_BYTES));
642     ALOGV("usb:audio_hw - PCM_PARAM_TICK_TIME min:%u, max:%u",
643           pcm_params_get_min(alsa_hw_params, PCM_PARAM_TICK_TIME),
644           pcm_params_get_max(alsa_hw_params, PCM_PARAM_TICK_TIME));
645 }
646
647 /*
648  * Returns the supplied value rounded up to the next even multiple of 16
649  */
650 static unsigned int round_to_16_mult(unsigned int size) {
651     return (size + 15) & 0xFFFFFFF0;
652 }
653
654 /*TODO - Evaluate if this value should/can be retrieved from a device-specific property */
655 #define MIN_BUFF_TIME   5   /* milliseconds */
656
657 /*
658  * Returns the system defined minimum period size based on the supplied sample rate
659  */
660 static unsigned int calc_min_period_size(unsigned int sample_rate) {
661     unsigned int period_size = (sample_rate * MIN_BUFF_TIME) / 1000;
662     return round_to_16_mult(period_size);
663 }
664
665 /*
666  * Reads and decodes configuration info from the specified ALSA card/device
667  */
668 static int read_alsa_device_config(int card, int device, int io_type, struct pcm_config * config)
669 {
670     ALOGV("usb:audio_hw - read_alsa_device_config(c:%d d:%d t:0x%X)",card, device, io_type);
671
672     if (card < 0 || device < 0) {
673         return -EINVAL;
674     }
675
676     struct pcm_params * alsa_hw_params = pcm_params_get(card, device, io_type);
677     if (alsa_hw_params == NULL) {
678         return -EINVAL;
679     }
680
681     /*
682      * This Logging will be useful when testing new USB devices.
683      */
684     /* log_pcm_params(alsa_hw_params); */
685
686     config->channels = pcm_params_get_min(alsa_hw_params, PCM_PARAM_CHANNELS);
687     config->rate = pcm_params_get_min(alsa_hw_params, PCM_PARAM_RATE);
688     config->period_size = pcm_params_get_min(alsa_hw_params, PCM_PARAM_BUFFER_SIZE);
689     /* round this up to a multiple of 16 */
690     config->period_size = round_to_16_mult(config->period_size);
691     /* make sure it is above a minimum value to minimize jitter */
692     unsigned int min_period_size = calc_min_period_size(config->rate);
693     if (config->period_size < min_period_size) {
694         config->period_size = min_period_size;
695     }
696     config->period_count = pcm_params_get_min(alsa_hw_params, PCM_PARAM_PERIODS);
697
698     config->format = get_pcm_format_for_mask(pcm_params_get_mask(alsa_hw_params, PCM_PARAM_FORMAT));
699     return 0;
700 }
701
702 /*
703  * HAl Functions
704  */
705 /**
706  * NOTE: when multiple mutexes have to be acquired, always respect the
707  * following order: hw device > out stream
708  */
709
710 /* Helper functions */
711 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
712 {
713     return cached_output_hardware_config.rate;
714 }
715
716 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
717 {
718     return 0;
719 }
720
721 static size_t out_get_buffer_size(const struct audio_stream *stream)
722 {
723     return cached_output_hardware_config.period_size * audio_stream_frame_size(stream);
724 }
725
726 static uint32_t out_get_channels(const struct audio_stream *stream)
727 {
728     // Always Stero for now. We will do *some* conversions in this HAL.
729     /* TODO When AudioPolicyManager & AudioFlinger supports arbitrary channels
730        rewrite this to return the ACTUAL channel format */
731     return AUDIO_CHANNEL_OUT_STEREO;
732 }
733
734 static audio_format_t out_get_format(const struct audio_stream *stream)
735 {
736     return audio_format_from_pcm_format(cached_output_hardware_config.format);
737 }
738
739 static int out_set_format(struct audio_stream *stream, audio_format_t format)
740 {
741     cached_output_hardware_config.format = pcm_format_from_audio_format(format);
742     return 0;
743 }
744
745 static int out_standby(struct audio_stream *stream)
746 {
747     struct stream_out *out = (struct stream_out *)stream;
748
749     pthread_mutex_lock(&out->dev->lock);
750     pthread_mutex_lock(&out->lock);
751
752     if (!out->standby) {
753         pcm_close(out->pcm);
754         out->pcm = NULL;
755         out->standby = true;
756     }
757
758     pthread_mutex_unlock(&out->lock);
759     pthread_mutex_unlock(&out->dev->lock);
760
761     return 0;
762 }
763
764 static int out_dump(const struct audio_stream *stream, int fd)
765 {
766     return 0;
767 }
768
769 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
770 {
771     ALOGV("usb:audio_hw::out out_set_parameters() keys:%s", kvpairs);
772
773     struct stream_out *out = (struct stream_out *)stream;
774     struct audio_device *adev = out->dev;
775     struct str_parms *parms;
776     char value[32];
777     int param_val;
778     int routing = 0;
779     int ret_value = 0;
780
781     parms = str_parms_create_str(kvpairs);
782     pthread_mutex_lock(&adev->lock);
783
784     bool recache_device_params = false;
785     param_val = str_parms_get_str(parms, "card", value, sizeof(value));
786     if (param_val >= 0) {
787         adev->out_card = atoi(value);
788         recache_device_params = true;
789     }
790
791     param_val = str_parms_get_str(parms, "device", value, sizeof(value));
792     if (param_val >= 0) {
793         adev->out_device = atoi(value);
794         recache_device_params = true;
795     }
796
797     if (recache_device_params && adev->out_card >= 0 && adev->out_device >= 0) {
798         ret_value = read_alsa_device_config(adev->out_card, adev->out_device, PCM_OUT,
799                                             &cached_output_hardware_config);
800         output_hardware_config_is_cached = (ret_value == 0);
801     }
802
803     pthread_mutex_unlock(&adev->lock);
804     str_parms_destroy(parms);
805
806     return ret_value;
807 }
808
809 /*TODO it seems like both out_get_parameters() and in_get_parameters()
810   could be written in terms of a get_device_parameters(io_type) */
811
812 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
813 {
814     ALOGV("usb:audio_hw::out out_get_parameters() keys:%s", keys);
815
816     struct stream_out *out = (struct stream_out *) stream;
817     struct audio_device *adev = out->dev;
818
819     if (adev->out_card < 0 || adev->out_device < 0)
820         return strdup("");
821
822     unsigned min, max;
823
824     struct str_parms *query = str_parms_create_str(keys);
825     struct str_parms *result = str_parms_create();
826
827     int num_written = 0;
828     char buffer[256];
829     int buffer_size = sizeof(buffer) / sizeof(buffer[0]);
830     char* result_str = NULL;
831
832     struct pcm_params * alsa_hw_params = pcm_params_get(adev->out_card, adev->out_device, PCM_OUT);
833
834     // These keys are from hardware/libhardware/include/audio.h
835     // supported sample rates
836     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
837         // pcm_hw_params doesn't have a list of supported samples rates, just a min and a max, so
838         // if they are different, return a list containing those two values, otherwise just the one.
839         min = pcm_params_get_min(alsa_hw_params, PCM_PARAM_RATE);
840         max = pcm_params_get_max(alsa_hw_params, PCM_PARAM_RATE);
841         num_written = snprintf(buffer, buffer_size, "%u", min);
842         if (min != max) {
843             snprintf(buffer + num_written, buffer_size - num_written, "|%u", max);
844         }
845         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES,
846                           buffer);
847     }  // AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES
848
849     // supported channel counts
850     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
851         // Similarly for output channels count
852         /* TODO - This is wrong, we need format strings, not numbers (another CL) */
853         min = pcm_params_get_min(alsa_hw_params, PCM_PARAM_CHANNELS);
854         max = pcm_params_get_max(alsa_hw_params, PCM_PARAM_CHANNELS);
855         num_written = snprintf(buffer, buffer_size, "%u", min);
856         if (min != max) {
857             snprintf(buffer + num_written, buffer_size - num_written, "|%u", max);
858         }
859         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, buffer);
860     }  // AUDIO_PARAMETER_STREAM_SUP_CHANNELS
861
862     // supported sample formats
863     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
864         char * format_params =
865             get_format_str_for_mask(pcm_params_get_mask(alsa_hw_params, PCM_PARAM_FORMAT));
866         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_FORMATS, format_params);
867         free(format_params);
868     }  // AUDIO_PARAMETER_STREAM_SUP_FORMATS
869
870     result_str = str_parms_to_str(result);
871
872     // done with these...
873     str_parms_destroy(query);
874     str_parms_destroy(result);
875
876     ALOGV("usb:audio_hw::out out_get_parameters() = %s", result_str);
877
878     return result_str;
879 }
880
881 static uint32_t out_get_latency(const struct audio_stream_out *stream)
882 {
883     struct stream_out *out = (struct stream_out *) stream;
884
885     /*TODO Do we need a term here for the USB latency (as reported in the USB descriptors)? */
886     uint32_t latency = (cached_output_hardware_config.period_size
887                     * cached_output_hardware_config.period_count * 1000)
888                     / out_get_sample_rate(&stream->common);
889     return latency;
890 }
891
892 static int out_set_volume(struct audio_stream_out *stream, float left, float right)
893 {
894     return -ENOSYS;
895 }
896
897 /* must be called with hw device and output stream mutexes locked */
898 static int start_output_stream(struct stream_out *out)
899 {
900     struct audio_device *adev = out->dev;
901     int return_val = 0;
902
903     ALOGV("usb:audio_hw::out start_output_stream(card:%d device:%d)",
904           adev->out_card, adev->out_device);
905
906     out->pcm = pcm_open(adev->out_card, adev->out_device, PCM_OUT, &cached_output_hardware_config);
907
908     if (out->pcm == NULL) {
909         return -ENOMEM;
910     }
911
912     if (out->pcm && !pcm_is_ready(out->pcm)) {
913         ALOGE("audio_hw audio_hw pcm_open() failed: %s", pcm_get_error(out->pcm));
914         pcm_close(out->pcm);
915         return -ENOMEM;
916     }
917
918     return 0;
919 }
920
921 static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes)
922 {
923     int ret;
924     struct stream_out *out = (struct stream_out *)stream;
925
926     pthread_mutex_lock(&out->dev->lock);
927     pthread_mutex_lock(&out->lock);
928     if (out->standby) {
929         ret = start_output_stream(out);
930         if (ret != 0) {
931             goto err;
932         }
933         out->standby = false;
934     }
935
936     // Setup conversion buffer
937     // compute maximum potential buffer size.
938     // * 2 for stereo -> quad conversion
939     // * 3/2 for 16bit -> 24 bit conversion
940     size_t required_conversion_buffer_size = (bytes * 3 * 2) / 2;
941     if (required_conversion_buffer_size > out->conversion_buffer_size) {
942         /* TODO Remove this when AudioPolicyManger/AudioFlinger support arbitrary formats
943            (and do these conversions themselves) */
944         out->conversion_buffer_size = required_conversion_buffer_size;
945         out->conversion_buffer = realloc(out->conversion_buffer, out->conversion_buffer_size);
946     }
947
948     const void * write_buff = buffer;
949     int num_write_buff_bytes = bytes;
950
951     /*
952      * Num Channels conversion
953      */
954     int num_device_channels = cached_output_hardware_config.channels;
955     int num_req_channels = 2; /* always, for now */
956     if (num_device_channels != num_req_channels) {
957         num_write_buff_bytes =
958                 expand_channels_16(write_buff, num_req_channels,
959                                    out->conversion_buffer, num_device_channels,
960                                    num_write_buff_bytes / sizeof(short));
961         write_buff = out->conversion_buffer;
962     }
963
964     if (write_buff != NULL && num_write_buff_bytes != 0) {
965         pcm_write(out->pcm, write_buff, num_write_buff_bytes);
966     }
967
968     pthread_mutex_unlock(&out->lock);
969     pthread_mutex_unlock(&out->dev->lock);
970
971     return bytes;
972
973 err:
974     pthread_mutex_unlock(&out->lock);
975     pthread_mutex_unlock(&out->dev->lock);
976     if (ret != 0) {
977         usleep(bytes * 1000000 / audio_stream_frame_size(&stream->common) /
978                out_get_sample_rate(&stream->common));
979     }
980
981     return bytes;
982 }
983
984 static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames)
985 {
986     return -EINVAL;
987 }
988
989 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
990 {
991     return 0;
992 }
993
994 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
995 {
996     return 0;
997 }
998
999 static int out_get_next_write_timestamp(const struct audio_stream_out *stream, int64_t *timestamp)
1000 {
1001     return -EINVAL;
1002 }
1003
1004 static int adev_open_output_stream(struct audio_hw_device *dev,
1005                                    audio_io_handle_t handle,
1006                                    audio_devices_t devices,
1007                                    audio_output_flags_t flags,
1008                                    struct audio_config *config,
1009                                    struct audio_stream_out **stream_out)
1010 {
1011     ALOGV("usb:audio_hw::out adev_open_output_stream() handle:0x%X, device:0x%X, flags:0x%X",
1012           handle, devices, flags);
1013
1014     struct audio_device *adev = (struct audio_device *)dev;
1015
1016     struct stream_out *out;
1017
1018     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
1019     if (!out)
1020         return -ENOMEM;
1021
1022     // setup function pointers
1023     out->stream.common.get_sample_rate = out_get_sample_rate;
1024     out->stream.common.set_sample_rate = out_set_sample_rate;
1025     out->stream.common.get_buffer_size = out_get_buffer_size;
1026     out->stream.common.get_channels = out_get_channels;
1027     out->stream.common.get_format = out_get_format;
1028     out->stream.common.set_format = out_set_format;
1029     out->stream.common.standby = out_standby;
1030     out->stream.common.dump = out_dump;
1031     out->stream.common.set_parameters = out_set_parameters;
1032     out->stream.common.get_parameters = out_get_parameters;
1033     out->stream.common.add_audio_effect = out_add_audio_effect;
1034     out->stream.common.remove_audio_effect = out_remove_audio_effect;
1035     out->stream.get_latency = out_get_latency;
1036     out->stream.set_volume = out_set_volume;
1037     out->stream.write = out_write;
1038     out->stream.get_render_position = out_get_render_position;
1039     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
1040
1041     out->dev = adev;
1042
1043     if (output_hardware_config_is_cached) {
1044         config->sample_rate = cached_output_hardware_config.rate;
1045
1046         config->format = audio_format_from_pcm_format(cached_output_hardware_config.format);
1047
1048         config->channel_mask =
1049                 audio_channel_out_mask_from_count(cached_output_hardware_config.channels);
1050         if (config->channel_mask != AUDIO_CHANNEL_OUT_STEREO) {
1051             // Always report STEREO for now.  AudioPolicyManagerBase/AudioFlinger dont' understand
1052             // formats with more channels, so we won't get chosen (say with a 4-channel DAC).
1053             /*TODO remove this when the above restriction is removed. */
1054             config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1055         }
1056     } else {
1057         cached_output_hardware_config = default_alsa_out_config;
1058
1059         config->format = out_get_format(&out->stream.common);
1060         config->channel_mask = out_get_channels(&out->stream.common);
1061         config->sample_rate = out_get_sample_rate(&out->stream.common);
1062     }
1063
1064     out->conversion_buffer = NULL;
1065     out->conversion_buffer_size = 0;
1066
1067     out->standby = true;
1068
1069     *stream_out = &out->stream;
1070     return 0;
1071
1072 err_open:
1073     free(out);
1074     *stream_out = NULL;
1075     return -ENOSYS;
1076 }
1077
1078 static void adev_close_output_stream(struct audio_hw_device *dev,
1079                                      struct audio_stream_out *stream)
1080 {
1081     ALOGV("usb:audio_hw::out adev_close_output_stream()");
1082     struct stream_out *out = (struct stream_out *)stream;
1083
1084     // Close the pcm device
1085     out_standby(&stream->common);
1086
1087     free(out->conversion_buffer);
1088     out->conversion_buffer = NULL;
1089     out->conversion_buffer_size = 0;
1090
1091     free(stream);
1092 }
1093
1094 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
1095 {
1096     return 0;
1097 }
1098
1099 static char * adev_get_parameters(const struct audio_hw_device *dev, const char *keys)
1100 {
1101     return strdup("");
1102 }
1103
1104 static int adev_init_check(const struct audio_hw_device *dev)
1105 {
1106     return 0;
1107 }
1108
1109 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
1110 {
1111     return -ENOSYS;
1112 }
1113
1114 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
1115 {
1116     return -ENOSYS;
1117 }
1118
1119 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
1120 {
1121     return 0;
1122 }
1123
1124 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
1125 {
1126     return -ENOSYS;
1127 }
1128
1129 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1130 {
1131     return -ENOSYS;
1132 }
1133
1134 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
1135                                          const struct audio_config *config)
1136 {
1137     return 0;
1138 }
1139
1140 /* Helper functions */
1141 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1142 {
1143     return cached_input_hardware_config.rate;
1144 }
1145
1146 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1147 {
1148     return -ENOSYS;
1149 }
1150
1151 static size_t in_get_buffer_size(const struct audio_stream *stream)
1152 {
1153     ALOGV("usb: in_get_buffer_size() = %zu",
1154           cached_input_hardware_config.period_size * audio_stream_frame_size(stream));
1155     return cached_input_hardware_config.period_size * audio_stream_frame_size(stream);
1156 }
1157
1158 static uint32_t in_get_channels(const struct audio_stream *stream)
1159 {
1160     // just report stereo for now
1161     return AUDIO_CHANNEL_IN_STEREO;
1162 }
1163
1164 static audio_format_t in_get_format(const struct audio_stream *stream)
1165 {
1166     const struct stream_in * in_stream = (const struct stream_in *)stream;
1167
1168     ALOGV("in_get_format() = %d -> %d", in_stream->input_framework_format,
1169           audio_format_from_pcm_format(in_stream->input_framework_format));
1170     /* return audio_format_from_pcm_format(cached_input_hardware_config.format); */
1171     return audio_format_from_pcm_format(in_stream->input_framework_format);
1172 }
1173
1174 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1175 {
1176     return -ENOSYS;
1177 }
1178
1179 static int in_standby(struct audio_stream *stream)
1180 {
1181     struct stream_in *in = (struct stream_in *) stream;
1182
1183     pthread_mutex_lock(&in->dev->lock);
1184     pthread_mutex_lock(&in->lock);
1185
1186     if (!in->standby) {
1187         pcm_close(in->pcm);
1188         in->pcm = NULL;
1189         in->standby = true;
1190     }
1191
1192     pthread_mutex_unlock(&in->lock);
1193     pthread_mutex_unlock(&in->dev->lock);
1194
1195     return 0;
1196 }
1197
1198 static int in_dump(const struct audio_stream *stream, int fd)
1199 {
1200     return 0;
1201 }
1202
1203 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1204 {
1205     ALOGV("usb: audio_hw::in in_set_parameters() keys:%s", kvpairs);
1206
1207     struct stream_in *in = (struct stream_in *)stream;
1208     struct audio_device *adev = in->dev;
1209     struct str_parms *parms;
1210     char value[32];
1211     int param_val;
1212     int routing = 0;
1213     int ret_value = 0;
1214
1215     parms = str_parms_create_str(kvpairs);
1216     pthread_mutex_lock(&adev->lock);
1217
1218     bool recache_device_params = false;
1219
1220     // Card/Device
1221     param_val = str_parms_get_str(parms, "card", value, sizeof(value));
1222     if (param_val >= 0) {
1223         adev->in_card = atoi(value);
1224         recache_device_params = true;
1225     }
1226
1227     param_val = str_parms_get_str(parms, "device", value, sizeof(value));
1228     if (param_val >= 0) {
1229         adev->in_device = atoi(value);
1230         recache_device_params = true;
1231     }
1232
1233     if (recache_device_params && adev->in_card >= 0 && adev->in_device >= 0) {
1234         ret_value = read_alsa_device_config(adev->in_card, adev->in_device,
1235                                             PCM_IN, &(cached_input_hardware_config));
1236         input_hardware_config_is_cached = (ret_value == 0);
1237     }
1238
1239     pthread_mutex_unlock(&adev->lock);
1240     str_parms_destroy(parms);
1241
1242     return ret_value;
1243 }
1244
1245 /*TODO it seems like both out_get_parameters() and in_get_parameters()
1246    could be written in terms of a get_device_parameters(io_type) */
1247
1248 static char * in_get_parameters(const struct audio_stream *stream, const char *keys) {
1249     ALOGV("usb:audio_hw::in in_get_parameters() keys:%s", keys);
1250
1251     struct stream_in *in = (struct stream_in *)stream;
1252     struct audio_device *adev = in->dev;
1253
1254     if (adev->in_card < 0 || adev->in_device < 0)
1255         return strdup("");
1256
1257     struct pcm_params * alsa_hw_params = pcm_params_get(adev->in_card, adev->in_device, PCM_IN);
1258     if (alsa_hw_params == NULL)
1259         return strdup("");
1260
1261     struct str_parms *query = str_parms_create_str(keys);
1262     struct str_parms *result = str_parms_create();
1263
1264     int num_written = 0;
1265     char buffer[256];
1266     int buffer_size = sizeof(buffer) / sizeof(buffer[0]);
1267     char* result_str = NULL;
1268
1269     unsigned min, max;
1270
1271     // These keys are from hardware/libhardware/include/audio.h
1272     // supported sample rates
1273     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
1274         // pcm_hw_params doesn't have a list of supported samples rates, just a min and a max, so
1275         // if they are different, return a list containing those two values, otherwise just the one.
1276         min = pcm_params_get_min(alsa_hw_params, PCM_PARAM_RATE);
1277         max = pcm_params_get_max(alsa_hw_params, PCM_PARAM_RATE);
1278         num_written = snprintf(buffer, buffer_size, "%u", min);
1279         if (min != max) {
1280             snprintf(buffer + num_written, buffer_size - num_written, "|%u", max);
1281         }
1282         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SAMPLING_RATE, buffer);
1283     }  // AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES
1284
1285     // supported channel counts
1286     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
1287         // Similarly for output channels count
1288         // TODO This is wrong, we need format strings, not numbers (another CL)
1289         min = pcm_params_get_min(alsa_hw_params, PCM_PARAM_CHANNELS);
1290         max = pcm_params_get_max(alsa_hw_params, PCM_PARAM_CHANNELS);
1291         num_written = snprintf(buffer, buffer_size, "%u", min);
1292         if (min != max) {
1293             snprintf(buffer + num_written, buffer_size - num_written, "|%u", max);
1294         }
1295         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_CHANNELS, buffer);
1296     }  // AUDIO_PARAMETER_STREAM_SUP_CHANNELS
1297
1298     // supported sample formats
1299     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
1300         struct pcm_mask * format_mask = pcm_params_get_mask(alsa_hw_params, PCM_PARAM_FORMAT);
1301         char * format_params = get_format_str_for_mask(format_mask);
1302         if (!mask_has_pcm_16(format_mask)) {
1303             /* For now, always support PCM_16 and convert locally if necessary */
1304             char buff[256];
1305             snprintf(buff, sizeof(buff), "AUDIO_FORMAT_PCM_16_BIT|%s", format_params);
1306             free(format_params);
1307             str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_FORMATS, buff);
1308         } else {
1309             str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_FORMATS, format_params);
1310         }
1311     }  // AUDIO_PARAMETER_STREAM_SUP_FORMATS
1312
1313     result_str = str_parms_to_str(result);
1314
1315     // done with these...
1316     str_parms_destroy(query);
1317     str_parms_destroy(result);
1318
1319     ALOGV("usb:audio_hw::in in_get_parameters() = %s", result_str);
1320
1321     return result_str;
1322 }
1323
1324 static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1325 {
1326     return 0;
1327 }
1328
1329 static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1330 {
1331     return 0;
1332 }
1333
1334 static int in_set_gain(struct audio_stream_in *stream, float gain)
1335 {
1336     return 0;
1337 }
1338
1339 /* must be called with hw device and output stream mutexes locked */
1340 static int start_input_stream(struct stream_in *in) {
1341     struct audio_device *adev = in->dev;
1342     int return_val = 0;
1343
1344     ALOGV("usb:audio_hw::start_input_stream(card:%d device:%d)",
1345           adev->in_card, adev->in_device);
1346
1347     in->pcm = pcm_open(adev->in_card, adev->in_device, PCM_IN, &cached_input_hardware_config);
1348     if (in->pcm == NULL) {
1349         ALOGE("usb:audio_hw pcm_open() in->pcm == NULL");
1350         return -ENOMEM;
1351     }
1352
1353     if (in->pcm && !pcm_is_ready(in->pcm)) {
1354         ALOGE("usb:audio_hw audio_hw pcm_open() failed: %s", pcm_get_error(in->pcm));
1355         pcm_close(in->pcm);
1356         return -ENOMEM;
1357     }
1358
1359     return 0;
1360 }
1361
1362 /* TODO mutex stuff here (see out_write) */
1363 static ssize_t in_read(struct audio_stream_in *stream, void* buffer, size_t bytes)
1364 {
1365     size_t num_read_buff_bytes = 0;
1366     void * read_buff = buffer;
1367     void * out_buff = buffer;
1368
1369     struct stream_in * in = (struct stream_in *) stream;
1370
1371     pthread_mutex_lock(&in->dev->lock);
1372     pthread_mutex_lock(&in->lock);
1373
1374     if (in->standby) {
1375         if (start_input_stream(in) != 0) {
1376             goto err;
1377         }
1378         in->standby = false;
1379     }
1380
1381     // OK, we need to figure out how much data to read to be able to output the requested
1382     // number of bytes in the HAL format (16-bit, stereo).
1383     num_read_buff_bytes = bytes;
1384     int num_device_channels = cached_input_hardware_config.channels;
1385     int num_req_channels = 2; /* always, for now */
1386
1387     if (num_device_channels != num_req_channels) {
1388         num_read_buff_bytes = (num_device_channels * num_read_buff_bytes) / num_req_channels;
1389     }
1390
1391     /* Assume (for now) that in->input_framework_format == PCM_FORMAT_S16_LE */
1392     if (cached_input_hardware_config.format == PCM_FORMAT_S24_3LE) {
1393         /* 24-bit USB device */
1394         num_read_buff_bytes = (3 * num_read_buff_bytes) / 2;
1395     } else if (cached_input_hardware_config.format == PCM_FORMAT_S32_LE) {
1396         /* 32-bit USB device */
1397         num_read_buff_bytes = num_read_buff_bytes * 2;
1398     }
1399
1400     // Setup/Realloc the conversion buffer (if necessary).
1401     if (num_read_buff_bytes != bytes) {
1402         if (num_read_buff_bytes > in->conversion_buffer_size) {
1403             /*TODO Remove this when AudioPolicyManger/AudioFlinger support arbitrary formats
1404               (and do these conversions themselves) */
1405             in->conversion_buffer_size = num_read_buff_bytes;
1406             in->conversion_buffer = realloc(in->conversion_buffer, in->conversion_buffer_size);
1407         }
1408         read_buff = in->conversion_buffer;
1409     }
1410
1411     if (pcm_read(in->pcm, read_buff, num_read_buff_bytes) == 0) {
1412         /*
1413          * Do any conversions necessary to send the data in the format specified to/by the HAL
1414          * (but different from the ALSA format), such as 24bit ->16bit, or 4chan -> 2chan.
1415          */
1416         if (cached_input_hardware_config.format != PCM_FORMAT_S16_LE) {
1417             // we need to convert
1418             if (num_device_channels != num_req_channels) {
1419                 out_buff = read_buff;
1420             }
1421
1422             if (cached_input_hardware_config.format == PCM_FORMAT_S24_3LE) {
1423                 num_read_buff_bytes =
1424                     convert_24_3_to_16(read_buff, num_read_buff_bytes / 3, out_buff);
1425             } else if (cached_input_hardware_config.format == PCM_FORMAT_S32_LE) {
1426                 num_read_buff_bytes =
1427                     convert_32_to_16(read_buff, num_read_buff_bytes / 4, out_buff);
1428             }
1429             else {
1430                 goto err;
1431             }
1432         }
1433
1434         if (num_device_channels != num_req_channels) {
1435             out_buff = buffer;
1436             /* Num Channels conversion */
1437             if (num_device_channels < num_req_channels) {
1438                 num_read_buff_bytes =
1439                     expand_channels_16(read_buff, num_device_channels,
1440                                        out_buff, num_req_channels,
1441                                        num_read_buff_bytes / sizeof(short));
1442             } else {
1443                 num_read_buff_bytes =
1444                     contract_channels_16(read_buff, num_device_channels,
1445                                          out_buff, num_req_channels,
1446                                          num_read_buff_bytes / sizeof(short));
1447             }
1448         }
1449     }
1450
1451 err:
1452     pthread_mutex_unlock(&in->lock);
1453     pthread_mutex_unlock(&in->dev->lock);
1454
1455     return num_read_buff_bytes;
1456 }
1457
1458 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1459 {
1460     return 0;
1461 }
1462
1463 static int adev_open_input_stream(struct audio_hw_device *dev,
1464                                   audio_io_handle_t handle,
1465                                   audio_devices_t devices,
1466                                   struct audio_config *config,
1467                                   struct audio_stream_in **stream_in)
1468 {
1469     ALOGV("usb: in adev_open_input_stream() rate:%" PRIu32 ", chanMask:0x%" PRIX32 ", fmt:%" PRIu8,
1470           config->sample_rate, config->channel_mask, config->format);
1471
1472     struct stream_in *in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
1473     int ret = 0;
1474
1475     if (in == NULL)
1476         return -ENOMEM;
1477
1478     // setup function pointers
1479     in->stream.common.get_sample_rate = in_get_sample_rate;
1480     in->stream.common.set_sample_rate = in_set_sample_rate;
1481     in->stream.common.get_buffer_size = in_get_buffer_size;
1482     in->stream.common.get_channels = in_get_channels;
1483     in->stream.common.get_format = in_get_format;
1484     in->stream.common.set_format = in_set_format;
1485     in->stream.common.standby = in_standby;
1486     in->stream.common.dump = in_dump;
1487     in->stream.common.set_parameters = in_set_parameters;
1488     in->stream.common.get_parameters = in_get_parameters;
1489     in->stream.common.add_audio_effect = in_add_audio_effect;
1490     in->stream.common.remove_audio_effect = in_remove_audio_effect;
1491
1492     in->stream.set_gain = in_set_gain;
1493     in->stream.read = in_read;
1494     in->stream.get_input_frames_lost = in_get_input_frames_lost;
1495
1496     in->input_framework_format = PCM_FORMAT_S16_LE;
1497
1498     in->dev = (struct audio_device *)dev;
1499
1500     if (!input_hardware_config_is_cached) {
1501         // just return defaults until we can actually query the device.
1502         cached_input_hardware_config = default_alsa_in_config;
1503     }
1504
1505     /* Rate */
1506     /* TODO Check that the requested rate is valid for the connected device */
1507     if (config->sample_rate == 0) {
1508         config->sample_rate = cached_input_hardware_config.rate;
1509     } else {
1510         cached_input_hardware_config.rate = config->sample_rate;
1511     }
1512
1513     /* Format */
1514     /* until the framework supports format conversion, just take what it asks for
1515      * i.e. AUDIO_FORMAT_PCM_16_BIT */
1516     /* config->format = audio_format_from_pcm_format(cached_input_hardware_config.format); */
1517     if (config->format == AUDIO_FORMAT_DEFAULT) {
1518         /* just return AUDIO_FORMAT_PCM_16_BIT until the framework supports other input
1519          * formats */
1520         config->format = AUDIO_FORMAT_PCM_16_BIT;
1521     } else if (config->format == AUDIO_FORMAT_PCM_16_BIT) {
1522         /* Always accept AUDIO_FORMAT_PCM_16_BIT until the framework supports other input
1523          * formats */
1524     } else {
1525         /* When the framework support other formats, validate here */
1526         config->format = AUDIO_FORMAT_PCM_16_BIT;
1527         ret = -EINVAL;
1528     }
1529
1530     /* don't change the cached_input_hardware_config, we will open it as what it is and
1531      * convert as necessary */
1532     if (config->channel_mask == AUDIO_CHANNEL_NONE) {
1533         /* just return AUDIO_CHANNEL_IN_STEREO until the framework supports other input
1534          * formats */
1535         config->channel_mask = AUDIO_CHANNEL_IN_STEREO;
1536     } else if (config->channel_mask != AUDIO_CHANNEL_IN_STEREO) {
1537         /* allow only stereo capture for now */
1538         config->channel_mask = AUDIO_CHANNEL_IN_STEREO;
1539         ret = -EINVAL;
1540     }
1541
1542     in->standby = true;
1543
1544     in->conversion_buffer = NULL;
1545     in->conversion_buffer_size = 0;
1546
1547     *stream_in = &in->stream;
1548
1549     return ret;
1550 }
1551
1552 static void adev_close_input_stream(struct audio_hw_device *dev, struct audio_stream_in *stream)
1553 {
1554     struct stream_in *in = (struct stream_in *)stream;
1555
1556     // Close the pcm device
1557     in_standby(&stream->common);
1558
1559     free(in->conversion_buffer);
1560
1561     free(stream);
1562 }
1563
1564 static int adev_dump(const audio_hw_device_t *device, int fd)
1565 {
1566     return 0;
1567 }
1568
1569 static int adev_close(hw_device_t *device)
1570 {
1571     struct audio_device *adev = (struct audio_device *)device;
1572     free(device);
1573
1574     output_hardware_config_is_cached = false;
1575     input_hardware_config_is_cached = false;
1576
1577     return 0;
1578 }
1579
1580 static int adev_open(const hw_module_t* module, const char* name, hw_device_t** device)
1581 {
1582     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
1583         return -EINVAL;
1584
1585     struct audio_device *adev = calloc(1, sizeof(struct audio_device));
1586     if (!adev)
1587         return -ENOMEM;
1588
1589     adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
1590     adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
1591     adev->hw_device.common.module = (struct hw_module_t *) module;
1592     adev->hw_device.common.close = adev_close;
1593
1594     adev->hw_device.init_check = adev_init_check;
1595     adev->hw_device.set_voice_volume = adev_set_voice_volume;
1596     adev->hw_device.set_master_volume = adev_set_master_volume;
1597     adev->hw_device.set_mode = adev_set_mode;
1598     adev->hw_device.set_mic_mute = adev_set_mic_mute;
1599     adev->hw_device.get_mic_mute = adev_get_mic_mute;
1600     adev->hw_device.set_parameters = adev_set_parameters;
1601     adev->hw_device.get_parameters = adev_get_parameters;
1602     adev->hw_device.get_input_buffer_size = adev_get_input_buffer_size;
1603     adev->hw_device.open_output_stream = adev_open_output_stream;
1604     adev->hw_device.close_output_stream = adev_close_output_stream;
1605     adev->hw_device.open_input_stream = adev_open_input_stream;
1606     adev->hw_device.close_input_stream = adev_close_input_stream;
1607     adev->hw_device.dump = adev_dump;
1608
1609     *device = &adev->hw_device.common;
1610
1611     return 0;
1612 }
1613
1614 static struct hw_module_methods_t hal_module_methods = {
1615     .open = adev_open,
1616 };
1617
1618 struct audio_module HAL_MODULE_INFO_SYM = {
1619     .common = {
1620         .tag = HARDWARE_MODULE_TAG,
1621         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
1622         .hal_api_version = HARDWARE_HAL_API_VERSION,
1623         .id = AUDIO_HARDWARE_MODULE_ID,
1624         .name = "USB audio HW HAL",
1625         .author = "The Android Open Source Project",
1626         .methods = &hal_module_methods,
1627     },
1628 };