1 /*
2  * Copyright (C) 2017 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 "audio_hw_usb"
18 
19 #include <errno.h>
20 #include <pthread.h>
21 #include <stdlib.h>
22 #include <cutils/log.h>
23 #include <cutils/str_parms.h>
24 #include <sys/ioctl.h>
25 #include <fcntl.h>
26 #include <sys/stat.h>
27 #include <system/audio.h>
28 #include <tinyalsa/asoundlib.h>
29 #include <audio_hw.h>
30 #include <cutils/properties.h>
31 #include <ctype.h>
32 #include <math.h>
33 
34 #ifdef USB_TUNNEL_ENABLED
35 #define USB_BUFF_SIZE           2048
36 #define CHANNEL_NUMBER_STR      "Channels: "
37 #define PLAYBACK_PROFILE_STR    "Playback:"
38 #define CAPTURE_PROFILE_STR     "Capture:"
39 #define USB_SIDETONE_GAIN_STR   "usb_sidetone_gain"
40 #define ABS_SUB(A, B) (((A) > (B)) ? ((A) - (B)):((B) - (A)))
41 #define SAMPLE_RATE_8000          8000
42 #define SAMPLE_RATE_11025         11025
43 /* TODO: dynamically populate supported sample rates */
44 static uint32_t supported_sample_rates[] =
45     {44100, 48000, 64000, 88200, 96000, 176400, 192000, 384000};
46 
47 #define  MAX_SAMPLE_RATE_SIZE  sizeof(supported_sample_rates)/sizeof(supported_sample_rates[0])
48 
49 enum usb_usecase_type{
50     USB_PLAYBACK = 0,
51     USB_CAPTURE,
52 };
53 
54 enum {
55     USB_SIDETONE_ENABLE_INDEX = 0,
56     USB_SIDETONE_VOLUME_INDEX,
57     USB_SIDETONE_MAX_INDEX,
58 };
59 
60 struct usb_device_config {
61     struct listnode list;
62     unsigned int bit_width;
63     unsigned int channel_count;
64     unsigned int rate_size;
65     unsigned int rates[MAX_SAMPLE_RATE_SIZE];
66 };
67 
68 struct usb_card_config {
69     struct listnode list;
70     audio_devices_t usb_device_type;
71     int usb_card;
72     struct listnode usb_device_conf_list;
73     struct mixer *usb_snd_mixer;
74     int usb_sidetone_index[USB_SIDETONE_MAX_INDEX];
75     int usb_sidetone_vol_min;
76     int usb_sidetone_vol_max;
77 };
78 
79 struct usb_module {
80     struct listnode usb_card_conf_list;
81     struct audio_device *adev;
82     int sidetone_gain;
83     bool is_capture_supported;
84 };
85 
86 static struct usb_module *usbmod = NULL;
87 static bool usb_audio_debug_enable = false;
88 static int usb_sidetone_gain = 0;
89 
90 static const char * const usb_sidetone_enable_str[] = {
91     "Sidetone Playback Switch",
92     "Mic Playback Switch",
93 };
94 
95 static const char * const usb_sidetone_volume_str[] = {
96     "Sidetone Playback Volume",
97     "Mic Playback Volume",
98 };
99 
usb_mixer_print_enum(struct mixer_ctl * ctl)100 static void usb_mixer_print_enum(struct mixer_ctl *ctl)
101 {
102     unsigned int num_enums;
103     unsigned int i;
104     const char *string;
105 
106     num_enums = mixer_ctl_get_num_enums(ctl);
107 
108     for (i = 0; i < num_enums; i++) {
109         string = mixer_ctl_get_enum_string(ctl, i);
110         ALOGI("\t%s%s", mixer_ctl_get_value(ctl, 0) == (int)i ? ">" : "", string);
111     }
112 }
113 
usb_soundcard_detail_control(struct mixer * mixer,const char * control)114 static void usb_soundcard_detail_control(struct mixer *mixer, const char *control)
115 {
116     struct mixer_ctl *ctl;
117     enum mixer_ctl_type type;
118     unsigned int num_values;
119     unsigned int i;
120     int min, max;
121 
122     if (isdigit(control[0]))
123         ctl = mixer_get_ctl(mixer, atoi(control));
124     else
125         ctl = mixer_get_ctl_by_name(mixer, control);
126 
127     if (!ctl) {
128         fprintf(stderr, "Invalid mixer control\n");
129         return;
130     }
131 
132     type = mixer_ctl_get_type(ctl);
133     num_values = mixer_ctl_get_num_values(ctl);
134 
135     ALOGV("%s:", mixer_ctl_get_name(ctl));
136 
137     for (i = 0; i < num_values; i++) {
138         switch (type) {
139             case MIXER_CTL_TYPE_INT:
140                 ALOGV(" %d", mixer_ctl_get_value(ctl, i));
141                 break;
142             case MIXER_CTL_TYPE_BOOL:
143                 ALOGV(" %s", mixer_ctl_get_value(ctl, i) ? "On" : "Off");
144                 break;
145             case MIXER_CTL_TYPE_ENUM:
146                 usb_mixer_print_enum(ctl);
147                 break;
148             case MIXER_CTL_TYPE_BYTE:
149                 ALOGV(" 0x%02x", mixer_ctl_get_value(ctl, i));
150                 break;
151             default:
152                 ALOGV(" unknown");
153                 break;
154         }
155     }
156 
157     if (type == MIXER_CTL_TYPE_INT) {
158         min = mixer_ctl_get_range_min(ctl);
159         max = mixer_ctl_get_range_max(ctl);
160         ALOGV(" (range %d->%d)", min, max);
161     }
162 }
163 
usb_soundcard_list_controls(struct mixer * mixer)164 static void usb_soundcard_list_controls(struct mixer *mixer)
165 {
166     struct mixer_ctl *ctl;
167     const char *name, *type;
168     unsigned int num_ctls, num_values;
169     unsigned int i;
170 
171     num_ctls = mixer_get_num_ctls(mixer);
172 
173     ALOGV("Number of controls: %d\n", num_ctls);
174 
175     ALOGV("ctl\ttype\tnum\t%-40s value\n", "name");
176     for (i = 0; i < num_ctls; i++) {
177         ctl = mixer_get_ctl(mixer, i);
178         if (ctl != NULL) {
179             name = mixer_ctl_get_name(ctl);
180             type = mixer_ctl_get_type_string(ctl);
181             num_values = mixer_ctl_get_num_values(ctl);
182             ALOGV("%d\t%s\t%d\t%-40s", i, type, num_values, name);
183             if (name != NULL)
184                 usb_soundcard_detail_control(mixer, name);
185         }
186     }
187 }
188 
usb_set_dev_id_mixer_ctl(unsigned int usb_usecase_type,int card,char * dev_mixer_ctl_name)189 static int usb_set_dev_id_mixer_ctl(unsigned int usb_usecase_type, int card,
190                                     char *dev_mixer_ctl_name)
191 {
192     struct mixer_ctl *ctl;
193     unsigned int dev_token;
194     const unsigned int pcm_device_number = 0;
195 
196     /*
197      * usb_dev_token_id is 32 bit number and is defined as below:
198      * usb_sound_card_idx(31:16) | usb PCM device ID(15:8) | usb_usecase_type(7:0)
199      */
200     dev_token = (card << 16 ) |
201                 (pcm_device_number << 8) | (usb_usecase_type & 0xFF);
202 
203     ctl = mixer_get_ctl_by_name(usbmod->adev->mixer, dev_mixer_ctl_name);
204     if (!ctl) {
205        ALOGE("%s: Could not get ctl for mixer cmd - %s",
206              __func__, dev_mixer_ctl_name);
207        return -EINVAL;
208     }
209     mixer_ctl_set_value(ctl, 0, dev_token);
210 
211     return 0;
212 }
213 
usb_get_sample_rates(char * rates_str,struct usb_device_config * config)214 static int usb_get_sample_rates(char *rates_str,
215                                 struct usb_device_config *config)
216 {
217     uint32_t i;
218     char *next_sr_string, *temp_ptr;
219     uint32_t sr, min_sr, max_sr, sr_size = 0;
220 
221     /* Sample rate string can be in any of the folloing two bit_widthes:
222      * Rates: 8000 - 48000 (continuous)
223      * Rates: 8000, 44100, 48000
224      * Support both the bit_widths
225      */
226     ALOGV("%s: rates_str %s", __func__, rates_str);
227     next_sr_string = strtok_r(rates_str, "Rates: ", &temp_ptr);
228     if (next_sr_string == NULL) {
229         ALOGE("%s: could not find min rates string", __func__);
230         return -EINVAL;
231     }
232     if (strstr(rates_str, "continuous") != NULL) {
233         min_sr = (uint32_t)atoi(next_sr_string);
234         next_sr_string = strtok_r(NULL, " ,.-", &temp_ptr);
235         if (next_sr_string == NULL) {
236             ALOGE("%s: could not find max rates string", __func__);
237             return -EINVAL;
238         }
239         max_sr = (uint32_t)atoi(next_sr_string);
240 
241         for (i = 0; i < MAX_SAMPLE_RATE_SIZE; i++) {
242             if (supported_sample_rates[i] >= min_sr &&
243                 supported_sample_rates[i] <= max_sr) {
244                 config->rates[sr_size++] = supported_sample_rates[i];
245                 ALOGI_IF(usb_audio_debug_enable,
246                     "%s: continuous sample rate supported_sample_rates[%d] %d",
247                     __func__, i, supported_sample_rates[i]);
248             }
249         }
250     } else {
251         do {
252             sr = (uint32_t)atoi(next_sr_string);
253             for (i = 0; i < MAX_SAMPLE_RATE_SIZE; i++) {
254                 if (supported_sample_rates[i] == sr) {
255                     ALOGI_IF(usb_audio_debug_enable,
256                         "%s: sr %d, supported_sample_rates[%d] %d -> matches!!",
257                         __func__, sr, i, supported_sample_rates[i]);
258                     config->rates[sr_size++] = supported_sample_rates[i];
259                 }
260             }
261             next_sr_string = strtok_r(NULL, " ,.-", &temp_ptr);
262         } while (next_sr_string != NULL);
263     }
264     config->rate_size = sr_size;
265     return 0;
266 }
267 
usb_get_capability(int type,struct usb_card_config * usb_card_info,int card)268 static int usb_get_capability(int type,
269                               struct usb_card_config *usb_card_info,
270                               int card)
271 {
272     int32_t size = 0;
273     int32_t fd=-1;
274     int32_t channels_no;
275     char *str_start = NULL;
276     char *str_end = NULL;
277     char *channel_start = NULL;
278     char *bit_width_start = NULL;
279     char *rates_str_start = NULL;
280     char *target = NULL;
281     char *read_buf = NULL;
282     char *rates_str = NULL;
283     char path[128];
284     int ret = 0;
285     char *bit_width_str = NULL;
286     struct usb_device_config * usb_device_info;
287     bool check = false;
288 
289     memset(path, 0, sizeof(path));
290     ALOGV("%s: for %s", __func__, (type == USB_PLAYBACK) ?
291           PLAYBACK_PROFILE_STR : CAPTURE_PROFILE_STR);
292 
293     /* TODO: convert the below to using alsa_utils */
294     ret = snprintf(path, sizeof(path), "/proc/asound/card%u/stream0",
295              card);
296     if(ret < 0) {
297         ALOGE("%s: failed on snprintf (%d) to path %s\n",
298           __func__, ret, path);
299         goto done;
300     }
301 
302     fd = open(path, O_RDONLY);
303     if (fd <0) {
304         ALOGE("%s: error failed to open config file %s error: %d\n",
305               __func__, path, errno);
306         ret = -EINVAL;
307         goto done;
308     }
309 
310     read_buf = (char *)calloc(1, USB_BUFF_SIZE + 1);
311 
312     if (!read_buf) {
313         ALOGE("Failed to create read_buf");
314         ret = -ENOMEM;
315         goto done;
316     }
317 
318     if(read(fd, read_buf, USB_BUFF_SIZE) < 0) {
319         ALOGE("file read error\n");
320         goto done;
321     }
322     str_start = strstr(read_buf, ((type == USB_PLAYBACK) ?
323                        PLAYBACK_PROFILE_STR : CAPTURE_PROFILE_STR));
324     if (str_start == NULL) {
325         ALOGE("%s: error %s section not found in usb config file",
326                __func__, ((type == USB_PLAYBACK) ?
327                PLAYBACK_PROFILE_STR : CAPTURE_PROFILE_STR));
328         ret = -EINVAL;
329         goto done;
330     }
331     str_end = strstr(read_buf, ((type == USB_PLAYBACK) ?
332                        CAPTURE_PROFILE_STR : PLAYBACK_PROFILE_STR));
333     if (str_end > str_start)
334         check = true;
335 
336     ALOGV("%s: usb_config = %s, check %d\n", __func__, str_start, check);
337 
338     while (str_start != NULL) {
339         str_start = strstr(str_start, "Altset");
340         if ((str_start == NULL) || (check  && (str_start >= str_end))) {
341             ALOGV("%s: done parsing %s\n", __func__, str_start);
342             break;
343         }
344         ALOGV("%s: remaining string %s\n", __func__, str_start);
345         str_start += sizeof("Altset");
346         usb_device_info = calloc(1, sizeof(struct usb_device_config));
347         if (usb_device_info == NULL) {
348             ALOGE("%s: error unable to allocate memory",
349                   __func__);
350             ret = -ENOMEM;
351             break;
352         }
353         /* Bit bit_width parsing */
354         bit_width_start = strstr(str_start, "Format: ");
355         if (bit_width_start == NULL) {
356             ALOGI("%s: Could not find bit_width string", __func__);
357             free(usb_device_info);
358             continue;
359         }
360         target = strchr(bit_width_start, '\n');
361         if (target == NULL) {
362             ALOGI("%s:end of line not found", __func__);
363             free(usb_device_info);
364             continue;
365         }
366         size = target - bit_width_start;
367         if ((bit_width_str = (char *)malloc(size + 1)) == NULL) {
368             ALOGE("%s: unable to allocate memory to hold bit width strings",
369                   __func__);
370             ret = -EINVAL;
371             free(usb_device_info);
372             break;
373         }
374         memcpy(bit_width_str, bit_width_start, size);
375         bit_width_str[size] = '\0';
376         if (strstr(bit_width_str, "S16_LE"))
377             usb_device_info->bit_width = 16;
378         else if (strstr(bit_width_str, "S24_LE"))
379             usb_device_info->bit_width = 24;
380         else if (strstr(bit_width_str, "S24_3LE"))
381             usb_device_info->bit_width = 24;
382         else if (strstr(bit_width_str, "S32_LE"))
383             usb_device_info->bit_width = 32;
384 
385         if (bit_width_str)
386             free(bit_width_str);
387 
388         /* channels parsing */
389         channel_start = strstr(str_start, CHANNEL_NUMBER_STR);
390         if (channel_start == NULL) {
391             ALOGI("%s: could not find Channels string", __func__);
392             free(usb_device_info);
393             continue;
394         }
395         channels_no = atoi(channel_start + strlen(CHANNEL_NUMBER_STR));
396         usb_device_info->channel_count =  channels_no;
397 
398         /* Sample rates parsing */
399         rates_str_start = strstr(str_start, "Rates: ");
400         if (rates_str_start == NULL) {
401             ALOGI("%s: cant find rates string", __func__);
402             free(usb_device_info);
403             continue;
404         }
405         target = strchr(rates_str_start, '\n');
406         if (target == NULL) {
407             ALOGI("%s: end of line not found", __func__);
408             free(usb_device_info);
409             continue;
410         }
411         size = target - rates_str_start;
412         if ((rates_str = (char *)malloc(size + 1)) == NULL) {
413             ALOGE("%s: unable to allocate memory to hold sample rate strings",
414                   __func__);
415             ret = -EINVAL;
416             free(usb_device_info);
417             break;
418         }
419         memcpy(rates_str, rates_str_start, size);
420         rates_str[size] = '\0';
421         ret = usb_get_sample_rates(rates_str, usb_device_info);
422         if (rates_str)
423             free(rates_str);
424         if (ret < 0) {
425             ALOGE("%s: error unable to get sample rate values",
426                   __func__);
427             free(usb_device_info);
428             continue;
429         }
430         /* Add to list if every field is valid */
431         list_add_tail(&usb_card_info->usb_device_conf_list,
432                       &usb_device_info->list);
433     }
434 
435 done:
436     if (fd >= 0) close(fd);
437     if (read_buf) free(read_buf);
438     return ret;
439 }
440 
usb_get_device_playback_config(struct usb_card_config * usb_card_info,int card)441 static int usb_get_device_playback_config(struct usb_card_config *usb_card_info,
442                                     int card)
443 {
444     int ret;
445 
446     /* get capabilities */
447     if ((ret = usb_get_capability(USB_PLAYBACK, usb_card_info, card))) {
448         ALOGE("%s: could not get Playback capabilities from usb device",
449                __func__);
450         goto exit;
451     }
452     usb_set_dev_id_mixer_ctl(USB_PLAYBACK, card, "USB_AUDIO_RX dev_token");
453 
454 exit:
455 
456     return ret;
457 }
458 
usb_get_device_capture_config(struct usb_card_config * usb_card_info,int card)459 static int usb_get_device_capture_config(struct usb_card_config *usb_card_info,
460                                       int card)
461 {
462     int ret;
463 
464     /* get capabilities */
465     if ((ret = usb_get_capability(USB_CAPTURE, usb_card_info, card))) {
466         ALOGE("%s: could not get Playback capabilities from usb device",
467                __func__);
468         goto exit;
469     }
470     usb_set_dev_id_mixer_ctl(USB_CAPTURE, card, "USB_AUDIO_TX dev_token");
471 
472 exit:
473     return ret;
474 }
475 
usb_get_sidetone_mixer(struct usb_card_config * usb_card_info)476 static void usb_get_sidetone_mixer(struct usb_card_config *usb_card_info)
477 {
478     struct mixer_ctl *ctl;
479     unsigned int index;
480 
481     for (index = 0; index < USB_SIDETONE_MAX_INDEX; index++)
482         usb_card_info->usb_sidetone_index[index] = -1;
483 
484     usb_card_info->usb_snd_mixer = mixer_open(usb_card_info->usb_card);
485     for (index = 0;
486          index < sizeof(usb_sidetone_enable_str)/sizeof(usb_sidetone_enable_str[0]);
487          index++) {
488         ctl = mixer_get_ctl_by_name(usb_card_info->usb_snd_mixer,
489                                     usb_sidetone_enable_str[index]);
490         if (ctl) {
491             usb_card_info->usb_sidetone_index[USB_SIDETONE_ENABLE_INDEX] = index;
492             /* Disable device sidetone by default */
493             mixer_ctl_set_value(ctl, 0, false);
494             break;
495         }
496     }
497     for (index = 0;
498          index < sizeof(usb_sidetone_volume_str)/sizeof(usb_sidetone_volume_str[0]);
499          index++) {
500         ctl = mixer_get_ctl_by_name(usb_card_info->usb_snd_mixer,
501                                     usb_sidetone_volume_str[index]);
502         if (ctl) {
503             usb_card_info->usb_sidetone_index[USB_SIDETONE_VOLUME_INDEX] = index;
504             usb_card_info->usb_sidetone_vol_min = mixer_ctl_get_range_min(ctl);
505             usb_card_info->usb_sidetone_vol_max = mixer_ctl_get_range_max(ctl);
506             break;
507         }
508     }
509 
510     if ((usb_card_info->usb_snd_mixer != NULL) && (usb_audio_debug_enable))
511         usb_soundcard_list_controls(usb_card_info->usb_snd_mixer);
512 
513     return;
514 }
515 
usb_valid_device(audio_devices_t device)516 static bool usb_valid_device(audio_devices_t device)
517 {
518     if ((popcount(device) == 1) && (device & AUDIO_DEVICE_OUT_USB_DEVICE))
519         return true;
520 
521     if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
522         device &= ~AUDIO_DEVICE_BIT_IN;
523         if (popcount(device) == 1 && (device & AUDIO_DEVICE_IN_USB_DEVICE) != 0)
524             return true;
525     }
526 
527     return false;
528 }
529 
usb_print_active_device(void)530 static void usb_print_active_device(void){
531     struct listnode *node_i, *node_j;
532     struct usb_device_config *dev_info;
533     struct usb_card_config *card_info;
534     unsigned int i;
535 
536     ALOGI("%s", __func__);
537     list_for_each(node_i, &usbmod->usb_card_conf_list) {
538         card_info = node_to_item(node_i, struct usb_card_config, list);
539         ALOGI("%s: card_dev_type (0x%x), card_no(%d)",
540                __func__,  card_info->usb_device_type, card_info->usb_card);
541         list_for_each(node_j, &card_info->usb_device_conf_list) {
542             dev_info = node_to_item(node_j, struct usb_device_config, list);
543             ALOGI("%s: bit-width(%d) channel(%d)",
544                    __func__, dev_info->bit_width, dev_info->channel_count);
545             for (i =  0; i < dev_info->rate_size; i++)
546                 ALOGI("%s: rate %d", __func__, dev_info->rates[i]);
547         }
548     }
549 }
550 
usb_get_best_match_for_bit_width(struct listnode * dev_list,unsigned int stream_bit_width,unsigned int * bit_width)551 static bool usb_get_best_match_for_bit_width(
552                             struct listnode *dev_list,
553                             unsigned int stream_bit_width,
554                             unsigned int *bit_width)
555 {
556     struct listnode *node_i;
557     struct usb_device_config *dev_info;
558     unsigned int candidate = 0;
559 
560     list_for_each(node_i, dev_list) {
561         dev_info = node_to_item(node_i, struct usb_device_config, list);
562         ALOGI_IF(usb_audio_debug_enable,
563                  "%s: USB bw(%d), stream bw(%d), candidate(%d)",
564                  __func__, dev_info->bit_width,
565                  stream_bit_width, candidate);
566         if (dev_info->bit_width == stream_bit_width) {
567             *bit_width = dev_info->bit_width;
568             ALOGV("%s: Found match bit-width (%d)",
569                   __func__, dev_info->bit_width);
570             goto exit;
571         } else if (candidate == 0) {
572                 candidate = dev_info->bit_width;
573         }
574         /*
575         * If stream bit is 24, USB supports both 16 bit and 32 bit, then
576         *  higher bit width 32 is picked up instead of 16-bit
577         */
578         else if (ABS_SUB(stream_bit_width, dev_info->bit_width) <
579                  ABS_SUB(stream_bit_width, candidate)) {
580             candidate = dev_info->bit_width;
581         }
582         else if ((ABS_SUB(stream_bit_width, dev_info->bit_width) ==
583                   ABS_SUB(stream_bit_width, candidate)) &&
584                  (dev_info->bit_width > candidate)) {
585             candidate = dev_info->bit_width;
586         }
587     }
588     ALOGV("%s: No match found, use the best candidate bw(%d)",
589           __func__, candidate);
590     *bit_width = candidate;
591 exit:
592     return true;
593 }
594 
usb_get_best_match_for_channels(struct listnode * dev_list,unsigned int bit_width,unsigned int stream_ch,unsigned int * channel_count)595 static bool usb_get_best_match_for_channels(
596                             struct listnode *dev_list,
597                             unsigned int bit_width,
598                             unsigned int stream_ch,
599                             unsigned int *channel_count)
600 {
601     struct listnode *node_i;
602     struct usb_device_config *dev_info;
603     unsigned int candidate = 0;
604 
605     list_for_each(node_i, dev_list) {
606         dev_info = node_to_item(node_i, struct usb_device_config, list);
607         ALOGI_IF(usb_audio_debug_enable,
608                  "%s: USB ch(%d)bw(%d), stream ch(%d)bw(%d), candidate(%d)",
609                  __func__, dev_info->channel_count, dev_info->bit_width,
610                  stream_ch, bit_width, candidate);
611         if (dev_info->bit_width != bit_width)
612             continue;
613         if (dev_info->channel_count== stream_ch) {
614             *channel_count = dev_info->channel_count;
615             ALOGV("%s: Found match channels (%d)",
616                   __func__, dev_info->channel_count);
617             goto exit;
618         } else if (candidate == 0)
619                 candidate = dev_info->channel_count;
620             /*
621             * If stream channel is 4, USB supports both 3 and 5, then
622             *  higher channel 5 is picked up instead of 3
623             */
624         else if (ABS_SUB(stream_ch, dev_info->channel_count) <
625                  ABS_SUB(stream_ch, candidate)) {
626             candidate = dev_info->channel_count;
627         } else if ((ABS_SUB(stream_ch, dev_info->channel_count) ==
628                     ABS_SUB(stream_ch, candidate)) &&
629                    (dev_info->channel_count > candidate)) {
630             candidate = dev_info->channel_count;
631         }
632     }
633     ALOGV("%s: No match found, use the best candidate ch(%d)",
634           __func__, candidate);
635     *channel_count = candidate;
636 exit:
637     return true;
638 
639 }
640 
usb_sample_rate_multiple(unsigned int stream_sample_rate,unsigned int base)641 static bool usb_sample_rate_multiple(
642                                      unsigned int stream_sample_rate,
643                                      unsigned int base)
644 {
645     return (((stream_sample_rate / base) * base) == stream_sample_rate);
646 }
647 
usb_find_sample_rate_candidate(unsigned int base,unsigned stream_rate,unsigned int usb_rate,unsigned int cur_candidate,unsigned int * update_candidate)648 static bool usb_find_sample_rate_candidate(unsigned int base,
649                                            unsigned stream_rate,
650                                            unsigned int usb_rate,
651                                            unsigned int cur_candidate,
652                                            unsigned int *update_candidate)
653 {
654     /* For sample rate, we should consider  fracational sample rate as high priority.
655     * For example, if the stream is 88.2kHz and USB device support both 44.1kH and
656     * 48kHz sample rate, we should pick 44.1kHz instead of 48kHz
657     */
658     if (!usb_sample_rate_multiple(cur_candidate, base) &&
659        usb_sample_rate_multiple(usb_rate, base)) {
660         *update_candidate = usb_rate;
661     } else if (usb_sample_rate_multiple(cur_candidate, base) &&
662                usb_sample_rate_multiple(usb_rate, base)) {
663         if (ABS_SUB(stream_rate, usb_rate) <
664             ABS_SUB(stream_rate, cur_candidate)) {
665             *update_candidate = usb_rate;
666         } else if ((ABS_SUB(stream_rate, usb_rate) ==
667                     ABS_SUB(stream_rate, cur_candidate)) &&
668                    (usb_rate > cur_candidate)) {
669             *update_candidate = usb_rate;
670         }
671     } else if (!usb_sample_rate_multiple(cur_candidate, base) &&
672                !usb_sample_rate_multiple(usb_rate, base)) {
673         if (ABS_SUB(stream_rate, usb_rate) <
674             ABS_SUB(stream_rate, cur_candidate)) {
675             *update_candidate = usb_rate;
676         } else if ((ABS_SUB(stream_rate, usb_rate) ==
677                     ABS_SUB(stream_rate, cur_candidate)) &&
678                    (usb_rate > cur_candidate)) {
679             *update_candidate = usb_rate;
680         }
681     }
682     return true;
683 }
684 
usb_get_best_match_for_sample_rate(struct listnode * dev_list,unsigned int bit_width,unsigned int channel_count,unsigned int stream_sample_rate,unsigned int * sr)685 static bool usb_get_best_match_for_sample_rate(
686                             struct listnode *dev_list,
687                             unsigned int bit_width,
688                             unsigned int channel_count,
689                             unsigned int stream_sample_rate,
690                             unsigned int *sr)
691 {
692     struct listnode *node_i;
693     struct usb_device_config *dev_info;
694     unsigned int candidate = 48000;
695     unsigned int base = SAMPLE_RATE_8000;
696     bool multiple_8k = usb_sample_rate_multiple(stream_sample_rate, base);
697     unsigned int i;
698 
699     ALOGV("%s: stm ch(%d)bw(%d)sr(%d), stream sample multiple of 8kHz(%d)",
700         __func__, channel_count, bit_width, stream_sample_rate, multiple_8k);
701 
702     list_for_each(node_i, dev_list) {
703         dev_info = node_to_item(node_i, struct usb_device_config, list);
704         ALOGI_IF(usb_audio_debug_enable,
705                  "%s: USB ch(%d)bw(%d), stm ch(%d)bw(%d)sr(%d), candidate(%d)",
706                  __func__, dev_info->channel_count, dev_info->bit_width,
707                  channel_count, bit_width, stream_sample_rate, candidate);
708         if ((dev_info->bit_width != bit_width) || dev_info->channel_count != channel_count)
709             continue;
710 
711         candidate = 0;
712         for (i = 0; i < dev_info->rate_size; i++) {
713             ALOGI_IF(usb_audio_debug_enable,
714                      "%s: USB ch(%d)bw(%d)sr(%d), stm ch(%d)bw(%d)sr(%d), candidate(%d)",
715                      __func__, dev_info->channel_count,
716                      dev_info->bit_width, dev_info->rates[i],
717                      channel_count, bit_width, stream_sample_rate, candidate);
718             if (stream_sample_rate == dev_info->rates[i]) {
719                 *sr = dev_info->rates[i];
720                 ALOGV("%s: Found match sample rate (%d)",
721                       __func__, dev_info->rates[i]);
722                 goto exit;
723             } else if (candidate == 0) {
724                     candidate = dev_info->rates[i];
725                 /*
726                 * For sample rate, we should consider  fracational sample rate as high priority.
727                 * For example, if the stream is 88.2kHz and USB device support both 44.1kH and
728                 * 48kHz sample rate, we should pick 44.1kHz instead of 48kHz
729                 */
730             } else if (multiple_8k) {
731                 usb_find_sample_rate_candidate(SAMPLE_RATE_8000,
732                                                stream_sample_rate,
733                                                dev_info->rates[i],
734                                                candidate,
735                                                &candidate);
736             } else {
737                 usb_find_sample_rate_candidate(SAMPLE_RATE_11025,
738                                                stream_sample_rate,
739                                                dev_info->rates[i],
740                                                candidate,
741                                                &candidate);
742             }
743         }
744     }
745     ALOGV("%s: No match found, use the best candidate sr(%d)",
746           __func__, candidate);
747     *sr = candidate;
748 exit:
749     return true;
750 }
751 
usb_audio_backend_apply_policy(struct listnode * dev_list,unsigned int * bit_width,unsigned int * sample_rate,unsigned int * channel_count)752 static bool usb_audio_backend_apply_policy(struct listnode *dev_list,
753                                            unsigned int *bit_width,
754                                            unsigned int *sample_rate,
755                                            unsigned int *channel_count)
756 {
757     ALOGV("%s: from stream: bit-width(%d) sample_rate(%d) channels (%d)",
758            __func__, *bit_width, *sample_rate, *channel_count);
759     if (list_empty(dev_list)) {
760         *sample_rate = 48000;
761         *bit_width = 16;
762         *channel_count = 2;
763         ALOGE("%s: list is empty,fall back to default setting", __func__);
764         goto exit;
765     }
766     usb_get_best_match_for_bit_width(dev_list, *bit_width, bit_width);
767     usb_get_best_match_for_channels(dev_list,
768                                     *bit_width,
769                                     *channel_count,
770                                     channel_count);
771     usb_get_best_match_for_sample_rate(dev_list,
772                                        *bit_width,
773                                        *channel_count,
774                                        *sample_rate,
775                                        sample_rate);
776 exit:
777     ALOGV("%s: Updated sample rate per profile: bit-width(%d) rate(%d) chs(%d)",
778            __func__, *bit_width, *sample_rate, *channel_count);
779     return true;
780 }
781 
usb_get_sidetone_gain(struct usb_card_config * card_info)782 static int usb_get_sidetone_gain(struct usb_card_config *card_info)
783 {
784     int gain = card_info->usb_sidetone_vol_min + usbmod->sidetone_gain;
785     if (gain > card_info->usb_sidetone_vol_max)
786         gain = card_info->usb_sidetone_vol_max;
787     return gain;
788 }
789 
audio_extn_usb_set_sidetone_gain(struct str_parms * parms,char * value,int len)790 void audio_extn_usb_set_sidetone_gain(struct str_parms *parms,
791                                 char *value, int len)
792 {
793     int err;
794 
795     err = str_parms_get_str(parms, USB_SIDETONE_GAIN_STR,
796                             value, len);
797     if (err >= 0) {
798         usb_sidetone_gain = pow(10.0, (float)(atoi(value))/10.0);
799         ALOGV("%s: sidetone gain(%s) decimal %d",
800               __func__, value, usb_sidetone_gain);
801         str_parms_del(parms, USB_SIDETONE_GAIN_STR);
802     }
803     return;
804 }
805 
audio_extn_usb_enable_sidetone(int device,bool enable)806 int audio_extn_usb_enable_sidetone(int device, bool enable)
807 {
808     int ret = -ENODEV;
809     struct listnode *node_i;
810     struct usb_card_config *card_info;
811     int i;
812     ALOGV("%s: card_dev_type (0x%x), sidetone enable(%d)",
813            __func__,  device, enable);
814 
815     list_for_each(node_i, &usbmod->usb_card_conf_list) {
816         card_info = node_to_item(node_i, struct usb_card_config, list);
817         ALOGV("%s: card_dev_type (0x%x), card_no(%d)",
818                __func__,  card_info->usb_device_type, card_info->usb_card);
819         if (card_info->usb_device_type == AUDIO_DEVICE_OUT_USB_DEVICE) {
820             if ((i = card_info->usb_sidetone_index[USB_SIDETONE_ENABLE_INDEX]) != -1) {
821                 struct mixer_ctl *ctl = mixer_get_ctl_by_name(
822                                 card_info->usb_snd_mixer,
823                                 usb_sidetone_enable_str[i]);
824                 if (ctl)
825                     mixer_ctl_set_value(ctl, 0, enable);
826                 else
827                     break;
828 
829                 if ((i = card_info->usb_sidetone_index[USB_SIDETONE_VOLUME_INDEX]) != -1) {
830                     ctl = mixer_get_ctl_by_name(
831                                 card_info->usb_snd_mixer,
832                                 usb_sidetone_volume_str[i]);
833                     if (ctl == NULL)
834                         ALOGV("%s: sidetone gain mixer command is not found",
835                                __func__);
836                     else if (enable)
837                         mixer_ctl_set_value(ctl, 0,
838                                             usb_get_sidetone_gain(card_info));
839                 }
840                 ret = 0;
841                 break;
842             }
843         }
844     }
845     return ret;
846 }
847 
audio_extn_usb_is_config_supported(unsigned int * bit_width,unsigned int * sample_rate,unsigned int * channel_count,bool is_playback)848 bool audio_extn_usb_is_config_supported(unsigned int *bit_width,
849                                         unsigned int *sample_rate,
850                                         unsigned int *channel_count,
851                                         bool is_playback)
852 {
853     struct listnode *node_i;
854     struct usb_card_config *card_info;
855 
856     ALOGV("%s: from stream: bit-width(%d) sample_rate(%d) ch(%d) is_playback(%d)",
857            __func__, *bit_width, *sample_rate, *channel_count, is_playback);
858     list_for_each(node_i, &usbmod->usb_card_conf_list) {
859         card_info = node_to_item(node_i, struct usb_card_config, list);
860         ALOGI_IF(usb_audio_debug_enable,
861                  "%s: card_dev_type (0x%x), card_no(%d)",
862                  __func__,  card_info->usb_device_type, card_info->usb_card);
863         /* Currently only apply the first playback sound card configuration */
864         if ((is_playback && card_info->usb_device_type == AUDIO_DEVICE_OUT_USB_DEVICE) ||
865             ((!is_playback) && card_info->usb_device_type == AUDIO_DEVICE_IN_USB_DEVICE)){
866             usb_audio_backend_apply_policy(&card_info->usb_device_conf_list,
867                                            bit_width,
868                                            sample_rate,
869                                            channel_count);
870             break;
871         }
872     }
873     ALOGV("%s: updated: bit-width(%d) sample_rate(%d) channels (%d)",
874            __func__, *bit_width, *sample_rate, *channel_count);
875 
876     return true;
877 }
878 
audio_extn_usb_is_capture_supported()879 bool audio_extn_usb_is_capture_supported()
880 {
881     if (usbmod == NULL) {
882         ALOGE("%s: USB device object is NULL", __func__);
883         return false;
884     }
885     ALOGV("%s: capture_supported %d",__func__,usbmod->is_capture_supported);
886     return usbmod->is_capture_supported;
887 }
888 
audio_extn_usb_add_device(audio_devices_t device,int card)889 void audio_extn_usb_add_device(audio_devices_t device, int card)
890 {
891     struct usb_card_config *usb_card_info;
892     char check_debug_enable[PROPERTY_VALUE_MAX];
893     struct listnode *node_i;
894 
895     property_get("audio.usb.enable.debug", check_debug_enable, NULL);
896     if (atoi(check_debug_enable)) {
897         usb_audio_debug_enable = true;
898     }
899 
900     ALOGI_IF(usb_audio_debug_enable,
901              "%s: parameters device(0x%x), card(%d)",
902              __func__, device, card);
903     if (usbmod == NULL) {
904         ALOGE("%s: USB device object is NULL", __func__);
905         goto exit;
906     }
907 
908     if (!(usb_valid_device(device)) || (card < 0)) {
909         ALOGE("%s:device(0x%x), card(%d)",
910               __func__, device, card);
911         goto exit;
912     }
913 
914     list_for_each(node_i, &usbmod->usb_card_conf_list) {
915         usb_card_info = node_to_item(node_i, struct usb_card_config, list);
916         ALOGI_IF(usb_audio_debug_enable,
917                  "%s: list has capability for card_dev_type (0x%x), card_no(%d)",
918                  __func__,  usb_card_info->usb_device_type, usb_card_info->usb_card);
919         /* If we have cached the capability */
920         if ((usb_card_info->usb_device_type == device) && (usb_card_info->usb_card == card)) {
921             ALOGV("%s: capability for device(0x%x), card(%d) is cached, no need to update",
922                   __func__, device, card);
923             goto exit;
924         }
925     }
926     usb_card_info = calloc(1, sizeof(struct usb_card_config));
927     if (usb_card_info == NULL) {
928         ALOGE("%s: error unable to allocate memory",
929               __func__);
930         goto exit;
931     }
932     list_init(&usb_card_info->usb_device_conf_list);
933     if (device & AUDIO_DEVICE_OUT_USB_DEVICE) {
934         if (!usb_get_device_playback_config(usb_card_info, card)){
935             usb_card_info->usb_card = card;
936             usb_card_info->usb_device_type = AUDIO_DEVICE_OUT_USB_DEVICE;
937             usb_get_sidetone_mixer(usb_card_info);
938             list_add_tail(&usbmod->usb_card_conf_list, &usb_card_info->list);
939             goto exit;
940         }
941     } else if (device & AUDIO_DEVICE_IN_USB_DEVICE) {
942         if (!usb_get_device_capture_config(usb_card_info, card)) {
943             usb_card_info->usb_card = card;
944             usb_card_info->usb_device_type = AUDIO_DEVICE_IN_USB_DEVICE;
945             usbmod->is_capture_supported = true;
946             list_add_tail(&usbmod->usb_card_conf_list, &usb_card_info->list);
947             goto exit;
948         }
949     }
950     /* free memory in error case */
951     if (usb_card_info != NULL)
952         free(usb_card_info);
953 exit:
954     if (usb_audio_debug_enable)
955         usb_print_active_device();
956     return;
957 }
958 
audio_extn_usb_remove_device(audio_devices_t device,int card)959 void audio_extn_usb_remove_device(audio_devices_t device, int card)
960 {
961     struct listnode *node_i, *temp_i;
962     struct listnode *node_j, *temp_j;
963     struct usb_device_config *dev_info;
964     struct usb_card_config *card_info;
965     unsigned int i;
966 
967     ALOGV("%s: device(0x%x), card(%d)",
968            __func__, device, card);
969 
970     if (usbmod == NULL) {
971         ALOGE("%s: USB device object is NULL", __func__);
972         goto exit;
973     }
974 
975     if (!(usb_valid_device(device)) || (card < 0)) {
976         ALOGE("%s: Invalid parameters device(0x%x), card(%d)",
977               __func__, device, card);
978         goto exit;
979     }
980     list_for_each_safe(node_i, temp_i, &usbmod->usb_card_conf_list) {
981         card_info = node_to_item(node_i, struct usb_card_config, list);
982         ALOGV("%s: card_dev_type (0x%x), card_no(%d)",
983                __func__,  card_info->usb_device_type, card_info->usb_card);
984         if ((device == card_info->usb_device_type) && (card == card_info->usb_card)){
985             list_for_each_safe(node_j, temp_j, &card_info->usb_device_conf_list) {
986                 dev_info = node_to_item(node_j, struct usb_device_config, list);
987                 ALOGV("%s: bit-width(%d) channel(%d)",
988                        __func__, dev_info->bit_width, dev_info->channel_count);
989                 for (i =  0; i < dev_info->rate_size; i++)
990                     ALOGV("%s: rate %d", __func__, dev_info->rates[i]);
991 
992                 list_remove(node_j);
993                 free(node_to_item(node_j, struct usb_device_config, list));
994             }
995             list_remove(node_i);
996             free(node_to_item(node_i, struct usb_card_config, list));
997         }
998     }
999     usbmod->is_capture_supported = false;
1000 exit:
1001     if (usb_audio_debug_enable)
1002         usb_print_active_device();
1003 
1004     return;
1005 }
1006 
audio_extn_usb_init(void * adev)1007 void audio_extn_usb_init(void *adev)
1008 {
1009     if (usbmod == NULL) {
1010         usbmod = calloc(1, sizeof(struct usb_module));
1011         if (usbmod == NULL) {
1012             ALOGE("%s: error unable to allocate memory", __func__);
1013             goto exit;
1014         }
1015     } else {
1016         memset(usbmod, 0, sizeof(*usbmod));
1017     }
1018 
1019     list_init(&usbmod->usb_card_conf_list);
1020     usbmod->adev = (struct audio_device*)adev;
1021     usbmod->sidetone_gain = usb_sidetone_gain;
1022     usbmod->is_capture_supported = false;
1023 exit:
1024     return;
1025 }
1026 
audio_extn_usb_deinit(void)1027 void audio_extn_usb_deinit(void)
1028 {
1029     if (NULL != usbmod){
1030         free(usbmod);
1031         usbmod = NULL;
1032     }
1033 }
1034 #endif /*USB_HEADSET_ENABLED end*/
1035