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 <log/log.h>
23 #include <cutils/str_parms.h>
24 #include <sys/ioctl.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <system/audio.h>
29 #include <tinyalsa/asoundlib.h>
30 #include <audio_hw.h>
31 #include <cutils/properties.h>
32 #include <ctype.h>
33 #include <math.h>
34 
35 #ifdef USB_TUNNEL_ENABLED
36 #define USB_BUFF_SIZE           2048
37 #define CHANNEL_NUMBER_STR      "Channels: "
38 #define PLAYBACK_PROFILE_STR    "Playback:"
39 #define CAPTURE_PROFILE_STR     "Capture:"
40 #define DATA_PACKET_INTERVAL_STR "Data packet interval: "
41 #define USB_SIDETONE_GAIN_STR   "usb_sidetone_gain"
42 #define ABS_SUB(A, B) (((A) > (B)) ? ((A) - (B)):((B) - (A)))
43 #define SAMPLE_RATE_8000          8000
44 #define SAMPLE_RATE_11025         11025
45 #define DEFAULT_SERVICE_INTERVAL_US    1000
46 #define USBID_SIZE                16
47 
48 /* TODO: dynamically populate supported sample rates */
49 static uint32_t supported_sample_rates[] =
50     {192000, 176400, 96000, 88200, 64000, 48000, 44100};
51 static uint32_t supported_sample_rates_mask[2];
52 static const uint32_t MAX_SAMPLE_RATE_SIZE =
53         (sizeof(supported_sample_rates)/sizeof(supported_sample_rates[0]));
54 
55 // assert on sizeof bm v/s size of rates if needed
56 
57 typedef enum usb_usecase_type{
58     USB_PLAYBACK = 0,
59     USB_CAPTURE,
60 } usb_usecase_type_t;
61 
62 enum {
63     USB_SIDETONE_ENABLE_INDEX = 0,
64     USB_SIDETONE_VOLUME_INDEX,
65     USB_SIDETONE_MAX_INDEX,
66 };
67 
68 struct usb_device_config {
69     struct listnode list;
70     unsigned int bit_width;
71     unsigned int channel_count;
72     unsigned int rate_size;
73     unsigned int rates[MAX_SAMPLE_RATE_SIZE];
74     unsigned long service_interval_us;
75     usb_usecase_type_t type;
76 };
77 
78 struct usb_card_config {
79     struct listnode list;
80     audio_devices_t usb_device_type;
81     int usb_card;
82     struct listnode usb_device_conf_list;
83     struct mixer *usb_snd_mixer;
84     int usb_sidetone_index[USB_SIDETONE_MAX_INDEX];
85     int usb_sidetone_vol_min;
86     int usb_sidetone_vol_max;
87     char usbid[USBID_SIZE];
88 };
89 
90 struct usb_module {
91     struct listnode usb_card_conf_list;
92     struct audio_device *adev;
93     int sidetone_gain;
94     bool is_capture_supported;
95 };
96 
97 static struct usb_module *usbmod = NULL;
98 static bool usb_audio_debug_enable = false;
99 static int usb_sidetone_gain = 0;
100 
101 static const char * const usb_sidetone_enable_str[] = {
102     "Sidetone Playback Switch",
103     "Mic Playback Switch",
104 };
105 
106 static const char * const usb_sidetone_volume_str[] = {
107     "Sidetone Playback Volume",
108     "Mic Playback Volume",
109 };
110 
usb_mixer_print_enum(struct mixer_ctl * ctl)111 static void usb_mixer_print_enum(struct mixer_ctl *ctl)
112 {
113     unsigned int num_enums;
114     unsigned int i;
115     const char *string;
116 
117     num_enums = mixer_ctl_get_num_enums(ctl);
118 
119     for (i = 0; i < num_enums; i++) {
120         string = mixer_ctl_get_enum_string(ctl, i);
121         ALOGI("\t%s%s", mixer_ctl_get_value(ctl, 0) == (int)i ? ">" : "", string);
122     }
123 }
124 
usb_soundcard_detail_control(struct mixer * mixer,const char * control)125 static void usb_soundcard_detail_control(struct mixer *mixer, const char *control)
126 {
127     struct mixer_ctl *ctl;
128     enum mixer_ctl_type type;
129     unsigned int num_values;
130     unsigned int i;
131     int min, max;
132 
133     if (isdigit(control[0]))
134         ctl = mixer_get_ctl(mixer, atoi(control));
135     else
136         ctl = mixer_get_ctl_by_name(mixer, control);
137 
138     if (!ctl) {
139         fprintf(stderr, "Invalid mixer control\n");
140         return;
141     }
142 
143     type = mixer_ctl_get_type(ctl);
144     num_values = mixer_ctl_get_num_values(ctl);
145 
146     ALOGV("%s:", mixer_ctl_get_name(ctl));
147 
148     for (i = 0; i < num_values; i++) {
149         switch (type) {
150             case MIXER_CTL_TYPE_INT:
151                 ALOGV(" %d", mixer_ctl_get_value(ctl, i));
152                 break;
153             case MIXER_CTL_TYPE_BOOL:
154                 ALOGV(" %s", mixer_ctl_get_value(ctl, i) ? "On" : "Off");
155                 break;
156             case MIXER_CTL_TYPE_ENUM:
157                 usb_mixer_print_enum(ctl);
158                 break;
159             case MIXER_CTL_TYPE_BYTE:
160                 ALOGV(" 0x%02x", mixer_ctl_get_value(ctl, i));
161                 break;
162             default:
163                 ALOGV(" unknown");
164                 break;
165         }
166     }
167 
168     if (type == MIXER_CTL_TYPE_INT) {
169         min = mixer_ctl_get_range_min(ctl);
170         max = mixer_ctl_get_range_max(ctl);
171         ALOGV(" (range %d->%d)", min, max);
172     }
173 }
174 
usb_soundcard_list_controls(struct mixer * mixer)175 static void usb_soundcard_list_controls(struct mixer *mixer)
176 {
177     struct mixer_ctl *ctl;
178     const char *name, *type;
179     unsigned int num_ctls, num_values;
180     unsigned int i;
181 
182     num_ctls = mixer_get_num_ctls(mixer);
183 
184     ALOGV("Number of controls: %d\n", num_ctls);
185 
186     ALOGV("ctl\ttype\tnum\t%-40s value\n", "name");
187     for (i = 0; i < num_ctls; i++) {
188         ctl = mixer_get_ctl(mixer, i);
189         if (ctl != NULL) {
190             name = mixer_ctl_get_name(ctl);
191             type = mixer_ctl_get_type_string(ctl);
192             num_values = mixer_ctl_get_num_values(ctl);
193             ALOGV("%d\t%s\t%d\t%-40s", i, type, num_values, name);
194             if (name != NULL)
195                 usb_soundcard_detail_control(mixer, name);
196         }
197     }
198 }
199 
usb_set_dev_id_mixer_ctl(unsigned int usb_usecase_type,int card,char * dev_mixer_ctl_name)200 static int usb_set_dev_id_mixer_ctl(unsigned int usb_usecase_type, int card,
201                                     char *dev_mixer_ctl_name)
202 {
203     struct mixer_ctl *ctl;
204     unsigned int dev_token;
205     const unsigned int pcm_device_number = 0;
206 
207     /*
208      * usb_dev_token_id is 32 bit number and is defined as below:
209      * usb_sound_card_idx(31:16) | usb PCM device ID(15:8) | usb_usecase_type(7:0)
210      */
211     dev_token = (card << 16 ) |
212                 (pcm_device_number << 8) | (usb_usecase_type & 0xFF);
213 
214     ctl = mixer_get_ctl_by_name(usbmod->adev->mixer, dev_mixer_ctl_name);
215     if (!ctl) {
216        ALOGE("%s: Could not get ctl for mixer cmd - %s",
217              __func__, dev_mixer_ctl_name);
218        return -EINVAL;
219     }
220     mixer_ctl_set_value(ctl, 0, dev_token);
221 
222     return 0;
223 }
224 
usb_get_sample_rates(int type,char * rates_str,struct usb_device_config * config)225 static int usb_get_sample_rates(int type, char *rates_str,
226                                 struct usb_device_config *config)
227 {
228     uint32_t i;
229     char *next_sr_string, *temp_ptr;
230     uint32_t sr, min_sr, max_sr, sr_size = 0;
231 
232     /* Sample rate string can be in any of the folloing two bit_widthes:
233      * Rates: 8000 - 48000 (continuous)
234      * Rates: 8000, 44100, 48000
235      * Support both the bit_widths
236      */
237     ALOGV("%s: rates_str %s", __func__, rates_str);
238     next_sr_string = strtok_r(rates_str, "Rates: ", &temp_ptr);
239     if (next_sr_string == NULL) {
240         ALOGE("%s: could not find min rates string", __func__);
241         return -EINVAL;
242     }
243     if (strstr(rates_str, "continuous") != NULL) {
244         min_sr = (uint32_t)atoi(next_sr_string);
245         next_sr_string = strtok_r(NULL, " ,.-", &temp_ptr);
246         if (next_sr_string == NULL) {
247             ALOGE("%s: could not find max rates string", __func__);
248             return -EINVAL;
249         }
250         max_sr = (uint32_t)atoi(next_sr_string);
251 
252         for (i = 0; i < MAX_SAMPLE_RATE_SIZE; i++) {
253             if (supported_sample_rates[i] >= min_sr &&
254                 supported_sample_rates[i] <= max_sr) {
255                 config->rates[sr_size++] = supported_sample_rates[i];
256                 supported_sample_rates_mask[type] |= (1<<i);
257                 ALOGI_IF(usb_audio_debug_enable,
258                     "%s: continuous sample rate supported_sample_rates[%d] %d",
259                     __func__, i, supported_sample_rates[i]);
260             }
261         }
262     } else {
263         do {
264             sr = (uint32_t)atoi(next_sr_string);
265             for (i = 0; i < MAX_SAMPLE_RATE_SIZE; i++) {
266                 if (supported_sample_rates[i] == sr) {
267                     ALOGI_IF(usb_audio_debug_enable,
268                         "%s: sr %d, supported_sample_rates[%d] %d -> matches!!",
269                         __func__, sr, i, supported_sample_rates[i]);
270                     config->rates[sr_size++] = supported_sample_rates[i];
271                     supported_sample_rates_mask[type] |= (1<<i);
272                 }
273             }
274             next_sr_string = strtok_r(NULL, " ,.-", &temp_ptr);
275         } while (next_sr_string != NULL);
276     }
277     config->rate_size = sr_size;
278     return 0;
279 }
280 
usb_get_service_interval(const char * interval_str_start,struct usb_device_config * usb_device_info)281 static int usb_get_service_interval(const char *interval_str_start,
282                                     struct usb_device_config *usb_device_info)
283 {
284     unsigned long interval = 0;
285     char time_unit[8] = {0};
286     int multiplier = 0;
287     char *eol = strchr(interval_str_start, '\n');
288     if (!eol) {
289         ALOGE("%s: No EOL found", __func__);
290         return -1;
291     }
292     char *tmp = (char *)calloc(1, eol-interval_str_start+1);
293     if (!tmp) {
294         ALOGE("%s: failed to allocate tmp", __func__);
295         return -1;
296     }
297     memcpy(tmp, interval_str_start, eol-interval_str_start);
298     sscanf(tmp, "%lu %2s", &interval, &time_unit[0]);
299     if (!strcmp(time_unit, "us")) {
300         multiplier = 1;
301     } else if (!strcmp(time_unit, "ms")) {
302         multiplier = 1000;
303     } else if (!strcmp(time_unit, "s")) {
304         multiplier = 1000000;
305     } else {
306         ALOGE("%s: unknown time_unit %s, assume default", __func__, time_unit);
307         interval = DEFAULT_SERVICE_INTERVAL_US;
308         multiplier = 1;
309     }
310     interval *= multiplier;
311     ALOGV("%s: set service_interval_us %lu", __func__, interval);
312     usb_device_info->service_interval_us = interval;
313     free(tmp);
314     return 0;
315 }
316 
317 
usb_get_capability(int type,struct usb_card_config * usb_card_info,int card)318 static int usb_get_capability(int type,
319                               struct usb_card_config *usb_card_info,
320                               int card)
321 {
322     int32_t size = 0;
323     int32_t fd=-1;
324     int32_t channels_no;
325     char *str_start = NULL;
326     char *str_end = NULL;
327     char *channel_start = NULL;
328     char *bit_width_start = NULL;
329     char *rates_str_start = NULL;
330     char *target = NULL;
331     char *read_buf = NULL;
332     char *rates_str = NULL;
333     char *interval_str_start = NULL;
334     char path[128];
335     int ret = 0;
336     char *bit_width_str = NULL;
337     struct usb_device_config * usb_device_info;
338     bool check = false;
339     int tries=5;
340 
341     memset(path, 0, sizeof(path));
342     ALOGV("%s: for %s", __func__, (type == USB_PLAYBACK) ?
343           PLAYBACK_PROFILE_STR : CAPTURE_PROFILE_STR);
344 
345     /* TODO: convert the below to using alsa_utils */
346     ret = snprintf(path, sizeof(path), "/proc/asound/card%u/stream0",
347              card);
348     if (ret < 0) {
349         ALOGE("%s: failed on snprintf (%d) to path %s\n",
350           __func__, ret, path);
351         goto done;
352     }
353 
354     // TODO: figure up if this wait is needed any more
355     while (tries--) {
356         if (access(path, F_OK) < 0) {
357             ALOGW("stream %s doesn't exist retrying\n", path);
358             sleep(1);
359             continue;
360         }
361     }
362 
363     fd = open(path, O_RDONLY);
364     if (fd <0) {
365         ALOGE("%s: error failed to open config file %s error: %d\n",
366               __func__, path, errno);
367         ret = -EINVAL;
368         goto done;
369     }
370 
371     read_buf = (char *)calloc(1, USB_BUFF_SIZE + 1);
372 
373     if (!read_buf) {
374         ALOGE("Failed to create read_buf");
375         ret = -ENOMEM;
376         goto done;
377     }
378 
379     if(read(fd, read_buf, USB_BUFF_SIZE) < 0) {
380         ALOGE("file read error\n");
381         goto done;
382     }
383     str_start = strstr(read_buf, ((type == USB_PLAYBACK) ?
384                        PLAYBACK_PROFILE_STR : CAPTURE_PROFILE_STR));
385     if (str_start == NULL) {
386         ALOGE("%s: error %s section not found in usb config file",
387                __func__, ((type == USB_PLAYBACK) ?
388                PLAYBACK_PROFILE_STR : CAPTURE_PROFILE_STR));
389         ret = -EINVAL;
390         goto done;
391     }
392     str_end = strstr(read_buf, ((type == USB_PLAYBACK) ?
393                        CAPTURE_PROFILE_STR : PLAYBACK_PROFILE_STR));
394     if (str_end > str_start)
395         check = true;
396 
397     ALOGV("%s: usb_config = %s, check %d\n", __func__, str_start, check);
398 
399     while (str_start != NULL) {
400         str_start = strstr(str_start, "Altset");
401         if ((str_start == NULL) || (check  && (str_start >= str_end))) {
402             ALOGV("%s: done parsing %s\n", __func__, str_start);
403             break;
404         }
405         ALOGV("%s: remaining string %s\n", __func__, str_start);
406         str_start += sizeof("Altset");
407         usb_device_info = calloc(1, sizeof(struct usb_device_config));
408         if (usb_device_info == NULL) {
409             ALOGE("%s: error unable to allocate memory",
410                   __func__);
411             ret = -ENOMEM;
412             break;
413         }
414         usb_device_info->type = type;
415         /* Bit bit_width parsing */
416         bit_width_start = strstr(str_start, "Format: ");
417         if (bit_width_start == NULL) {
418             ALOGI("%s: Could not find bit_width string", __func__);
419             free(usb_device_info);
420             continue;
421         }
422         target = strchr(bit_width_start, '\n');
423         if (target == NULL) {
424             ALOGI("%s:end of line not found", __func__);
425             free(usb_device_info);
426             continue;
427         }
428         size = target - bit_width_start;
429         if ((bit_width_str = (char *)malloc(size + 1)) == NULL) {
430             ALOGE("%s: unable to allocate memory to hold bit width strings",
431                   __func__);
432             ret = -EINVAL;
433             free(usb_device_info);
434             break;
435         }
436         memcpy(bit_width_str, bit_width_start, size);
437         bit_width_str[size] = '\0';
438         if (strstr(bit_width_str, "S16_LE"))
439             usb_device_info->bit_width = 16;
440         else if (strstr(bit_width_str, "S24_LE"))
441             usb_device_info->bit_width = 24;
442         else if (strstr(bit_width_str, "S24_3LE"))
443             usb_device_info->bit_width = 24;
444         else if (strstr(bit_width_str, "S32_LE"))
445             usb_device_info->bit_width = 32;
446 
447         if (bit_width_str)
448             free(bit_width_str);
449 
450         /* channels parsing */
451         channel_start = strstr(str_start, CHANNEL_NUMBER_STR);
452         if (channel_start == NULL) {
453             ALOGI("%s: could not find Channels string", __func__);
454             free(usb_device_info);
455             continue;
456         }
457         channels_no = atoi(channel_start + strlen(CHANNEL_NUMBER_STR));
458         usb_device_info->channel_count =  channels_no;
459 
460         /* Sample rates parsing */
461         rates_str_start = strstr(str_start, "Rates: ");
462         if (rates_str_start == NULL) {
463             ALOGI("%s: cant find rates string", __func__);
464             free(usb_device_info);
465             continue;
466         }
467         target = strchr(rates_str_start, '\n');
468         if (target == NULL) {
469             ALOGI("%s: end of line not found", __func__);
470             free(usb_device_info);
471             continue;
472         }
473         size = target - rates_str_start;
474         if ((rates_str = (char *)malloc(size + 1)) == NULL) {
475             ALOGE("%s: unable to allocate memory to hold sample rate strings",
476                   __func__);
477             ret = -EINVAL;
478             free(usb_device_info);
479             break;
480         }
481         memcpy(rates_str, rates_str_start, size);
482         rates_str[size] = '\0';
483         ret = usb_get_sample_rates(type, rates_str, usb_device_info);
484         if (rates_str)
485             free(rates_str);
486         if (ret < 0) {
487             ALOGE("%s: error unable to get sample rate values",
488                   __func__);
489             free(usb_device_info);
490             continue;
491         }
492         // Data packet interval is an optional field.
493         // Assume 1ms interval if this cannot be read
494         usb_device_info->service_interval_us = DEFAULT_SERVICE_INTERVAL_US;
495         interval_str_start = strstr(str_start, DATA_PACKET_INTERVAL_STR);
496         if (interval_str_start != NULL) {
497             interval_str_start += strlen(DATA_PACKET_INTERVAL_STR);
498             ret = usb_get_service_interval(interval_str_start, usb_device_info);
499             if (ret < 0) {
500                 ALOGE("%s: error unable to get service interval, assume default",
501                       __func__);
502             }
503         }
504         /* Add to list if every field is valid */
505         list_add_tail(&usb_card_info->usb_device_conf_list,
506                       &usb_device_info->list);
507     }
508 
509 done:
510     if (fd >= 0) close(fd);
511     if (read_buf) free(read_buf);
512     return ret;
513 }
514 
usb_get_usbid(struct usb_card_config * usb_card_info,int card)515 static int usb_get_usbid(struct usb_card_config *usb_card_info,
516                               int card)
517 {
518     int32_t fd=-1;
519     char path[128];
520     int ret = 0;
521 
522     memset(usb_card_info->usbid, 0, sizeof(usb_card_info->usbid));
523 
524     ret = snprintf(path, sizeof(path), "/proc/asound/card%u/usbid",
525              card);
526 
527     if (ret < 0) {
528         ALOGE("%s: failed on snprintf (%d) to path %s\n",
529           __func__, ret, path);
530         goto done;
531     }
532 
533     fd = open(path, O_RDONLY);
534     if (fd < 0) {
535         ALOGE("%s: error failed to open file %s error: %d\n",
536               __func__, path, errno);
537         ret = -EINVAL;
538         goto done;
539     }
540 
541     if (read(fd, usb_card_info->usbid, USBID_SIZE - 1) < 0) {
542         ALOGE("file read error\n");
543         ret = -EINVAL;
544         usb_card_info->usbid[0] = '\0';
545         goto done;
546     }
547 
548     strtok(usb_card_info->usbid, "\n");
549 
550 done:
551     if (fd >= 0)
552         close(fd);
553 
554     return ret;
555 }
556 
usb_get_device_playback_config(struct usb_card_config * usb_card_info,int card)557 static int usb_get_device_playback_config(struct usb_card_config *usb_card_info,
558                                     int card)
559 {
560     int ret;
561 
562     /* get capabilities */
563     if ((ret = usb_get_capability(USB_PLAYBACK, usb_card_info, card))) {
564         ALOGE("%s: could not get Playback capabilities from usb device",
565                __func__);
566         goto exit;
567     }
568     usb_set_dev_id_mixer_ctl(USB_PLAYBACK, card, "USB_AUDIO_RX dev_token");
569 
570 exit:
571 
572     return ret;
573 }
574 
usb_get_device_capture_config(struct usb_card_config * usb_card_info,int card)575 static int usb_get_device_capture_config(struct usb_card_config *usb_card_info,
576                                       int card)
577 {
578     int ret;
579 
580     /* get capabilities */
581     if ((ret = usb_get_capability(USB_CAPTURE, usb_card_info, card))) {
582         ALOGE("%s: could not get Playback capabilities from usb device",
583                __func__);
584         goto exit;
585     }
586     usb_set_dev_id_mixer_ctl(USB_CAPTURE, card, "USB_AUDIO_TX dev_token");
587 
588 exit:
589     return ret;
590 }
591 
usb_get_sidetone_mixer(struct usb_card_config * usb_card_info)592 static void usb_get_sidetone_mixer(struct usb_card_config *usb_card_info)
593 {
594     struct mixer_ctl *ctl;
595     unsigned int index;
596 
597     for (index = 0; index < USB_SIDETONE_MAX_INDEX; index++)
598         usb_card_info->usb_sidetone_index[index] = -1;
599 
600     usb_card_info->usb_snd_mixer = mixer_open(usb_card_info->usb_card);
601     for (index = 0;
602          index < sizeof(usb_sidetone_enable_str)/sizeof(usb_sidetone_enable_str[0]);
603          index++) {
604         ctl = mixer_get_ctl_by_name(usb_card_info->usb_snd_mixer,
605                                     usb_sidetone_enable_str[index]);
606         if (ctl) {
607             usb_card_info->usb_sidetone_index[USB_SIDETONE_ENABLE_INDEX] = index;
608             /* Disable device sidetone by default */
609             mixer_ctl_set_value(ctl, 0, false);
610             ALOGV("%s:: sidetone mixer Control found(%s) ... disabling by default",
611                    __func__, usb_sidetone_enable_str[index]);
612             break;
613         }
614     }
615 #ifdef USB_SIDETONE_VOLUME
616     for (index = 0;
617          index < sizeof(usb_sidetone_volume_str)/sizeof(usb_sidetone_volume_str[0]);
618          index++) {
619         ctl = mixer_get_ctl_by_name(usb_card_info->usb_snd_mixer,
620                                     usb_sidetone_volume_str[index]);
621         if (ctl) {
622             usb_card_info->usb_sidetone_index[USB_SIDETONE_VOLUME_INDEX] = index;
623             usb_card_info->usb_sidetone_vol_min = mixer_ctl_get_range_min(ctl);
624             usb_card_info->usb_sidetone_vol_max = mixer_ctl_get_range_max(ctl);
625             break;
626         }
627     }
628 #endif // USB_SIDETONE_VOLUME
629     if ((usb_card_info->usb_snd_mixer != NULL) && (usb_audio_debug_enable))
630         usb_soundcard_list_controls(usb_card_info->usb_snd_mixer);
631 
632     return;
633 }
634 
usb_output_device(audio_devices_t device)635 static inline bool usb_output_device(audio_devices_t device) {
636     // ignore accessory for now
637     if (device == AUDIO_DEVICE_OUT_USB_ACCESSORY) {
638         return false;
639     }
640     return audio_is_usb_out_device(device);
641 }
642 
usb_input_device(audio_devices_t device)643 static inline bool usb_input_device(audio_devices_t device) {
644     // ignore accessory for now
645     if (device == AUDIO_DEVICE_IN_USB_ACCESSORY) {
646         return false;
647     }
648     return audio_is_usb_in_device(device);
649 }
650 
usb_valid_device(audio_devices_t device)651 static bool usb_valid_device(audio_devices_t device)
652 {
653     return usb_output_device(device) ||
654            usb_input_device(device);
655 }
656 
usb_print_active_device(void)657 static void usb_print_active_device(void){
658     struct listnode *node_i, *node_j;
659     struct usb_device_config *dev_info;
660     struct usb_card_config *card_info;
661     unsigned int i;
662 
663     ALOGI("%s", __func__);
664     list_for_each(node_i, &usbmod->usb_card_conf_list) {
665         card_info = node_to_item(node_i, struct usb_card_config, list);
666         ALOGI("%s: card_dev_type (0x%x), card_no(%d)",
667                __func__,  card_info->usb_device_type, card_info->usb_card);
668         list_for_each(node_j, &card_info->usb_device_conf_list) {
669             dev_info = node_to_item(node_j, struct usb_device_config, list);
670             ALOGI("%s: bit-width(%d) channel(%d)",
671                    __func__, dev_info->bit_width, dev_info->channel_count);
672             for (i =  0; i < dev_info->rate_size; i++)
673                 ALOGI("%s: rate %d", __func__, dev_info->rates[i]);
674         }
675     }
676 }
677 
usb_get_best_bit_width(struct listnode * dev_list,unsigned int stream_bit_width,unsigned int * bit_width)678 static bool usb_get_best_bit_width(
679                             struct listnode *dev_list,
680                             unsigned int stream_bit_width,
681                             unsigned int *bit_width)
682 {
683     struct listnode *node_i;
684     struct usb_device_config *dev_info;
685     unsigned int candidate = 0;
686 
687     list_for_each(node_i, dev_list) {
688         dev_info = node_to_item(node_i, struct usb_device_config, list);
689         ALOGI_IF(usb_audio_debug_enable,
690                  "%s: USB bw(%d), stream bw(%d), candidate(%d)",
691                  __func__, dev_info->bit_width,
692                  stream_bit_width, candidate);
693         if (candidate == 0) {
694             ALOGV("%s: candidate bit-width (%d)",
695                   __func__, dev_info->bit_width);
696             candidate = dev_info->bit_width;
697         } else if (dev_info->bit_width > candidate) {
698             candidate = dev_info->bit_width;
699             ALOGV("%s: Found better candidate bit-width (%d)",
700                   __func__, dev_info->bit_width);
701         }
702     }
703     ALOGV("%s: Use the best candidate bw(%d)",
704           __func__, candidate);
705     *bit_width = candidate;
706 exit:
707     return true;
708 }
709 
usb_get_best_match_for_channels(struct listnode * dev_list,unsigned int bit_width,unsigned int stream_ch,unsigned int * channel_count)710 static bool usb_get_best_match_for_channels(
711                             struct listnode *dev_list,
712                             unsigned int bit_width,
713                             unsigned int stream_ch,
714                             unsigned int *channel_count)
715 {
716     struct listnode *node_i;
717     struct usb_device_config *dev_info;
718     unsigned int candidate = 0;
719 
720     list_for_each(node_i, dev_list) {
721         dev_info = node_to_item(node_i, struct usb_device_config, list);
722         ALOGI_IF(usb_audio_debug_enable,
723                  "%s: USB ch(%d)bw(%d), stream ch(%d)bw(%d), candidate(%d)",
724                  __func__, dev_info->channel_count, dev_info->bit_width,
725                  stream_ch, bit_width, candidate);
726         if (dev_info->bit_width != bit_width)
727             continue;
728         if (dev_info->channel_count== stream_ch) {
729             *channel_count = dev_info->channel_count;
730             ALOGV("%s: Found match channels (%d)",
731                   __func__, dev_info->channel_count);
732             goto exit;
733         } else if (candidate == 0)
734                 candidate = dev_info->channel_count;
735             /*
736             * If stream channel is 4, USB supports both 3 and 5, then
737             *  higher channel 5 is picked up instead of 3
738             */
739         else if (ABS_SUB(stream_ch, dev_info->channel_count) <
740                  ABS_SUB(stream_ch, candidate)) {
741             candidate = dev_info->channel_count;
742         } else if ((ABS_SUB(stream_ch, dev_info->channel_count) ==
743                     ABS_SUB(stream_ch, candidate)) &&
744                    (dev_info->channel_count > candidate)) {
745             candidate = dev_info->channel_count;
746         }
747     }
748     ALOGV("%s: No match found, use the best candidate ch(%d)",
749           __func__, candidate);
750     *channel_count = candidate;
751 exit:
752     return true;
753 
754 }
755 
usb_sample_rate_multiple(unsigned int stream_sample_rate,unsigned int base)756 static bool usb_sample_rate_multiple(
757                                      unsigned int stream_sample_rate,
758                                      unsigned int base)
759 {
760     return (((stream_sample_rate / base) * base) == stream_sample_rate);
761 }
762 
usb_find_sample_rate_candidate(unsigned int base,unsigned stream_rate,unsigned int usb_rate,unsigned int cur_candidate,unsigned int * update_candidate)763 static bool usb_find_sample_rate_candidate(unsigned int base,
764                                            unsigned stream_rate,
765                                            unsigned int usb_rate,
766                                            unsigned int cur_candidate,
767                                            unsigned int *update_candidate)
768 {
769     /* For sample rate, we should consider  fracational sample rate as high priority.
770     * For example, if the stream is 88.2kHz and USB device support both 44.1kH and
771     * 48kHz sample rate, we should pick 44.1kHz instead of 48kHz
772     */
773     if (!usb_sample_rate_multiple(cur_candidate, base) &&
774        usb_sample_rate_multiple(usb_rate, base)) {
775         *update_candidate = usb_rate;
776     } else if (usb_sample_rate_multiple(cur_candidate, base) &&
777                usb_sample_rate_multiple(usb_rate, base)) {
778         if (ABS_SUB(stream_rate, usb_rate) <
779             ABS_SUB(stream_rate, cur_candidate)) {
780             *update_candidate = usb_rate;
781         } else if ((ABS_SUB(stream_rate, usb_rate) ==
782                     ABS_SUB(stream_rate, cur_candidate)) &&
783                    (usb_rate > cur_candidate)) {
784             *update_candidate = usb_rate;
785         }
786     } else if (!usb_sample_rate_multiple(cur_candidate, base) &&
787                !usb_sample_rate_multiple(usb_rate, base)) {
788         if (ABS_SUB(stream_rate, usb_rate) <
789             ABS_SUB(stream_rate, cur_candidate)) {
790             *update_candidate = usb_rate;
791         } else if ((ABS_SUB(stream_rate, usb_rate) ==
792                     ABS_SUB(stream_rate, cur_candidate)) &&
793                    (usb_rate > cur_candidate)) {
794             *update_candidate = usb_rate;
795         }
796     }
797     return true;
798 }
799 
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,unsigned int service_interval,bool do_service_interval_check)800 static bool usb_get_best_match_for_sample_rate (
801                             struct listnode *dev_list,
802                             unsigned int bit_width,
803                             unsigned int channel_count,
804                             unsigned int stream_sample_rate,
805                             unsigned int *sr,
806                             unsigned int service_interval,
807                             bool do_service_interval_check)
808 {
809     struct listnode *node_i;
810     struct usb_device_config *dev_info;
811     unsigned int candidate = 48000;
812     unsigned int base = SAMPLE_RATE_8000;
813     bool multiple_8k = usb_sample_rate_multiple(stream_sample_rate, base);
814     unsigned int i;
815 
816     ALOGV("%s: stm ch(%d)bw(%d)sr(%d), stream sample multiple of 8kHz(%d)",
817         __func__, channel_count, bit_width, stream_sample_rate, multiple_8k);
818 
819     list_for_each(node_i, dev_list) {
820         dev_info = node_to_item(node_i, struct usb_device_config, list);
821         ALOGI_IF(usb_audio_debug_enable,
822                  "%s: USB ch(%d)bw(%d), stm ch(%d)bw(%d)sr(%d), candidate(%d)",
823                  __func__, dev_info->channel_count, dev_info->bit_width,
824                  channel_count, bit_width, stream_sample_rate, candidate);
825         if ((dev_info->bit_width != bit_width) ||
826             (dev_info->channel_count != channel_count) ||
827             (do_service_interval_check && (dev_info->service_interval_us !=
828                                            service_interval)))
829             continue;
830 
831         candidate = 0;
832         for (i = 0; i < dev_info->rate_size; i++) {
833             ALOGI_IF(usb_audio_debug_enable,
834                      "%s: USB ch(%d)bw(%d)sr(%d), stm ch(%d)bw(%d)sr(%d), candidate(%d)",
835                      __func__, dev_info->channel_count,
836                      dev_info->bit_width, dev_info->rates[i],
837                      channel_count, bit_width, stream_sample_rate, candidate);
838             if (stream_sample_rate == dev_info->rates[i]) {
839                 *sr = dev_info->rates[i];
840                 ALOGV("%s: Found match sample rate (%d)",
841                       __func__, dev_info->rates[i]);
842                 goto exit;
843             } else if (candidate == 0) {
844                     candidate = dev_info->rates[i];
845                 /*
846                 * For sample rate, we should consider  fracational sample rate as high priority.
847                 * For example, if the stream is 88.2kHz and USB device support both 44.1kH and
848                 * 48kHz sample rate, we should pick 44.1kHz instead of 48kHz
849                 */
850             } else if (multiple_8k) {
851                 usb_find_sample_rate_candidate(SAMPLE_RATE_8000,
852                                                stream_sample_rate,
853                                                dev_info->rates[i],
854                                                candidate,
855                                                &candidate);
856             } else {
857                 usb_find_sample_rate_candidate(SAMPLE_RATE_11025,
858                                                stream_sample_rate,
859                                                dev_info->rates[i],
860                                                candidate,
861                                                &candidate);
862             }
863         }
864     }
865     ALOGV("%s: No match found, use the best candidate sr(%d)",
866           __func__, candidate);
867     *sr = candidate;
868 exit:
869     return true;
870 }
871 
usb_audio_backend_apply_policy(struct listnode * dev_list,unsigned int * bit_width,unsigned int * sample_rate,unsigned int * channel_count)872 static bool usb_audio_backend_apply_policy(struct listnode *dev_list,
873                                            unsigned int *bit_width,
874                                            unsigned int *sample_rate,
875                                            unsigned int *channel_count)
876 {
877     ALOGV("%s: from stream: bit-width(%d) sample_rate(%d) channels (%d)",
878            __func__, *bit_width, *sample_rate, *channel_count);
879     if (list_empty(dev_list)) {
880         *sample_rate = 48000;
881         *bit_width = 16;
882         *channel_count = 2;
883         ALOGE("%s: list is empty,fall back to default setting", __func__);
884         goto exit;
885     }
886     usb_get_best_bit_width(dev_list, *bit_width, bit_width);
887     usb_get_best_match_for_channels(dev_list,
888                                     *bit_width,
889                                     *channel_count,
890                                     channel_count);
891     usb_get_best_match_for_sample_rate(dev_list,
892                                        *bit_width,
893                                        *channel_count,
894                                        *sample_rate,
895                                        sample_rate,
896                                        0 /*service int*/,
897                                        false /*do service int check*/);
898 exit:
899     ALOGV("%s: Updated sample rate per profile: bit-width(%d) rate(%d) chs(%d)",
900            __func__, *bit_width, *sample_rate, *channel_count);
901     return true;
902 }
903 
usb_get_sidetone_gain(struct usb_card_config * card_info)904 static int usb_get_sidetone_gain(struct usb_card_config *card_info)
905 {
906     int gain = card_info->usb_sidetone_vol_min + usbmod->sidetone_gain;
907     if (gain > card_info->usb_sidetone_vol_max)
908         gain = card_info->usb_sidetone_vol_max;
909     return gain;
910 }
911 
audio_extn_usb_set_sidetone_gain(struct str_parms * parms,char * value,int len)912 void audio_extn_usb_set_sidetone_gain(struct str_parms *parms,
913                                 char *value, int len)
914 {
915     int err;
916 
917     err = str_parms_get_str(parms, USB_SIDETONE_GAIN_STR,
918                             value, len);
919     if (err >= 0) {
920         usb_sidetone_gain = pow(10.0, (float)(atoi(value))/10.0);
921         ALOGV("%s: sidetone gain(%s) decimal %d",
922               __func__, value, usb_sidetone_gain);
923         str_parms_del(parms, USB_SIDETONE_GAIN_STR);
924     }
925     return;
926 }
927 
audio_extn_usb_enable_sidetone(int device,bool enable)928 int audio_extn_usb_enable_sidetone(int device, bool enable)
929 {
930     int ret = -ENODEV;
931     struct listnode *node_i;
932     struct usb_card_config *card_info;
933     int i;
934     ALOGV("%s: card_dev_type (0x%x), sidetone enable(%d)",
935            __func__,  device, enable);
936 
937     list_for_each(node_i, &usbmod->usb_card_conf_list) {
938         card_info = node_to_item(node_i, struct usb_card_config, list);
939         ALOGV("%s: card_dev_type (0x%x), card_no(%d)",
940                __func__,  card_info->usb_device_type, card_info->usb_card);
941         if (usb_output_device(card_info->usb_device_type)) {
942             if ((i = card_info->usb_sidetone_index[USB_SIDETONE_ENABLE_INDEX]) != -1) {
943                 struct mixer_ctl *ctl = mixer_get_ctl_by_name(
944                                 card_info->usb_snd_mixer,
945                                 usb_sidetone_enable_str[i]);
946                 if (ctl)
947                     mixer_ctl_set_value(ctl, 0, enable);
948                 else
949                     break;
950 
951 #ifdef USB_SIDETONE_VOLUME
952                 if ((i = card_info->usb_sidetone_index[USB_SIDETONE_VOLUME_INDEX]) != -1) {
953                     ctl = mixer_get_ctl_by_name(
954                                 card_info->usb_snd_mixer,
955                                 usb_sidetone_volume_str[i]);
956                     if (ctl == NULL)
957                         ALOGV("%s: sidetone gain mixer command is not found",
958                                __func__);
959                     else if (enable)
960                         mixer_ctl_set_value(ctl, 0,
961                                             usb_get_sidetone_gain(card_info));
962                 }
963 #endif // USB_SIDETONE_VOLUME
964                 ret = 0;
965                 break;
966             }
967         }
968     }
969     return ret;
970 }
971 
audio_extn_usb_is_config_supported(unsigned int * bit_width,unsigned int * sample_rate,unsigned int * channel_count,bool is_playback)972 bool audio_extn_usb_is_config_supported(unsigned int *bit_width,
973                                         unsigned int *sample_rate,
974                                         unsigned int *channel_count,
975                                         bool is_playback)
976 {
977     struct listnode *node_i;
978     struct usb_card_config *card_info;
979 
980     ALOGV("%s: from stream: bit-width(%d) sample_rate(%d) ch(%d) is_playback(%d)",
981            __func__, *bit_width, *sample_rate, *channel_count, is_playback);
982     list_for_each(node_i, &usbmod->usb_card_conf_list) {
983         card_info = node_to_item(node_i, struct usb_card_config, list);
984         ALOGI_IF(usb_audio_debug_enable,
985                  "%s: card_dev_type (0x%x), card_no(%d)",
986                  __func__,  card_info->usb_device_type, card_info->usb_card);
987         /* Currently only apply the first playback sound card configuration */
988         if ((is_playback && usb_output_device(card_info->usb_device_type)) ||
989             (!is_playback && usb_input_device(card_info->usb_device_type))) {
990             usb_audio_backend_apply_policy(&card_info->usb_device_conf_list,
991                                            bit_width,
992                                            sample_rate,
993                                            channel_count);
994             break;
995         }
996     }
997     ALOGV("%s: updated: bit-width(%d) sample_rate(%d) channels (%d)",
998            __func__, *bit_width, *sample_rate, *channel_count);
999 
1000     return true;
1001 }
1002 
1003 #define _MAX(x, y) (((x) >= (y)) ? (x) : (y))
1004 #define _MIN(x, y) (((x) <= (y)) ? (x) : (y))
1005 
audio_extn_usb_get_max_channels(bool is_playback)1006 int audio_extn_usb_get_max_channels(bool is_playback)
1007 {
1008     struct listnode *node_i, *node_j;
1009     struct usb_device_config *dev_info;
1010     struct usb_card_config *card_info;
1011     unsigned int max_ch = 1;
1012     list_for_each(node_i, &usbmod->usb_card_conf_list) {
1013             card_info = node_to_item(node_i, struct usb_card_config, list);
1014             if (usb_output_device(card_info->usb_device_type) && !is_playback)
1015                 continue;
1016             else if (usb_input_device(card_info->usb_device_type) && is_playback)
1017                 continue;
1018 
1019             list_for_each(node_j, &card_info->usb_device_conf_list) {
1020                 dev_info = node_to_item(node_j, struct usb_device_config, list);
1021                 max_ch = _MAX(max_ch, dev_info->channel_count);
1022             }
1023     }
1024 
1025     return max_ch;
1026 }
1027 
audio_extn_usb_get_max_bit_width(bool is_playback)1028 int audio_extn_usb_get_max_bit_width(bool is_playback)
1029 {
1030     struct listnode *node_i, *node_j;
1031     struct usb_device_config *dev_info;
1032     struct usb_card_config *card_info;
1033     unsigned int max_bw = 16;
1034     list_for_each(node_i, &usbmod->usb_card_conf_list) {
1035             card_info = node_to_item(node_i, struct usb_card_config, list);
1036             if (usb_output_device(card_info->usb_device_type) && !is_playback)
1037                 continue;
1038             else if (usb_input_device(card_info->usb_device_type) && is_playback)
1039                 continue;
1040 
1041             list_for_each(node_j, &card_info->usb_device_conf_list) {
1042                 dev_info = node_to_item(node_j, struct usb_device_config, list);
1043                 max_bw = _MAX(max_bw, dev_info->bit_width);
1044             }
1045     }
1046 
1047     return max_bw;
1048 }
1049 
audio_extn_usb_sup_sample_rates(bool is_playback,uint32_t * sample_rates,uint32_t sample_rate_size)1050 int audio_extn_usb_sup_sample_rates(bool is_playback,
1051                                     uint32_t *sample_rates,
1052                                     uint32_t sample_rate_size)
1053 {
1054     struct listnode *node_i, *node_j;
1055     struct usb_device_config *dev_info;
1056     struct usb_card_config *card_info;
1057 
1058     int type = is_playback ? USB_PLAYBACK : USB_CAPTURE;
1059 
1060     ALOGV("%s supported_sample_rates_mask 0x%x", __func__, supported_sample_rates_mask[type]);
1061     uint32_t bm = supported_sample_rates_mask[type];
1062     uint32_t tries = _MIN(sample_rate_size, (uint32_t)__builtin_popcount(bm));
1063 
1064     int i = 0;
1065     while (tries--) {
1066         int idx = __builtin_ffs(bm) - 1;
1067         sample_rates[i++] = supported_sample_rates[idx];
1068         bm &= ~(1<<idx);
1069     }
1070 
1071     return i;
1072 }
1073 
audio_extn_usb_is_capture_supported()1074 bool audio_extn_usb_is_capture_supported()
1075 {
1076     if (usbmod == NULL) {
1077         ALOGE("%s: USB device object is NULL", __func__);
1078         return false;
1079     }
1080     ALOGV("%s: capture_supported %d",__func__,usbmod->is_capture_supported);
1081     return usbmod->is_capture_supported;
1082 }
1083 
audio_extn_usb_add_device(audio_devices_t device,int card)1084 void audio_extn_usb_add_device(audio_devices_t device, int card)
1085 {
1086     struct usb_card_config *usb_card_info;
1087     char check_debug_enable[PROPERTY_VALUE_MAX];
1088     struct listnode *node_i;
1089 
1090     property_get("audio.usb.enable.debug", check_debug_enable, NULL);
1091     if (atoi(check_debug_enable)) {
1092         usb_audio_debug_enable = true;
1093     }
1094 
1095     ALOGI_IF(usb_audio_debug_enable,
1096              "%s: parameters device(0x%x), card(%d)",
1097              __func__, device, card);
1098     if (usbmod == NULL) {
1099         ALOGE("%s: USB device object is NULL", __func__);
1100         goto exit;
1101     }
1102 
1103     if (!(usb_valid_device(device)) || (card < 0)) {
1104         ALOGE("%s:device(0x%x), card(%d)",
1105               __func__, device, card);
1106         goto exit;
1107     }
1108 
1109     list_for_each(node_i, &usbmod->usb_card_conf_list) {
1110         usb_card_info = node_to_item(node_i, struct usb_card_config, list);
1111         ALOGI_IF(usb_audio_debug_enable,
1112                  "%s: list has capability for card_dev_type (0x%x), card_no(%d)",
1113                  __func__,  usb_card_info->usb_device_type, usb_card_info->usb_card);
1114         /* If we have cached the capability */
1115         if ((usb_card_info->usb_device_type == device) && (usb_card_info->usb_card == card)) {
1116             ALOGV("%s: capability for device(0x%x), card(%d) is cached, no need to update",
1117                   __func__, device, card);
1118             goto exit;
1119         }
1120     }
1121     usb_card_info = calloc(1, sizeof(struct usb_card_config));
1122     if (usb_card_info == NULL) {
1123         ALOGE("%s: error unable to allocate memory",
1124               __func__);
1125         goto exit;
1126     }
1127     list_init(&usb_card_info->usb_device_conf_list);
1128     if (usb_output_device(device)) {
1129         if (usb_get_usbid(usb_card_info, card) < 0) {
1130             ALOGE("parse card %d usbid fail", card);
1131         }
1132 
1133         if (!usb_get_device_playback_config(usb_card_info, card)){
1134             usb_card_info->usb_card = card;
1135             usb_card_info->usb_device_type = device;
1136             usb_get_sidetone_mixer(usb_card_info);
1137             list_add_tail(&usbmod->usb_card_conf_list, &usb_card_info->list);
1138             goto exit;
1139         }
1140     } else if (usb_input_device(device)) {
1141         if (usb_get_usbid(usb_card_info, card) < 0) {
1142             ALOGE("parse card %d usbid fail", card);
1143         }
1144 
1145         if (!usb_get_device_capture_config(usb_card_info, card)) {
1146             usb_card_info->usb_card = card;
1147             usb_card_info->usb_device_type = device;
1148             usbmod->is_capture_supported = true;
1149             list_add_tail(&usbmod->usb_card_conf_list, &usb_card_info->list);
1150             goto exit;
1151         }
1152     } else {
1153         ALOGW("%s: unknown device 0x%x", __func__, device);
1154     }
1155     /* free memory in error case */
1156     if (usb_card_info != NULL)
1157         free(usb_card_info);
1158 exit:
1159     if (usb_audio_debug_enable)
1160         usb_print_active_device();
1161     return;
1162 }
1163 
audio_extn_usb_remove_device(audio_devices_t device,int card)1164 void audio_extn_usb_remove_device(audio_devices_t device, int card)
1165 {
1166     struct listnode *node_i, *temp_i;
1167     struct listnode *node_j, *temp_j;
1168     struct usb_device_config *dev_info;
1169     struct usb_card_config *card_info;
1170     unsigned int i;
1171 
1172     ALOGV("%s: device(0x%x), card(%d)",
1173            __func__, device, card);
1174 
1175     if (usbmod == NULL) {
1176         ALOGE("%s: USB device object is NULL", __func__);
1177         goto exit;
1178     }
1179 
1180     if (!(usb_valid_device(device)) || (card < 0)) {
1181         ALOGE("%s: Invalid parameters device(0x%x), card(%d)",
1182               __func__, device, card);
1183         goto exit;
1184     }
1185     list_for_each_safe(node_i, temp_i, &usbmod->usb_card_conf_list) {
1186         card_info = node_to_item(node_i, struct usb_card_config, list);
1187         ALOGV("%s: card_dev_type (0x%x), card_no(%d)",
1188                __func__,  card_info->usb_device_type, card_info->usb_card);
1189         if ((device == card_info->usb_device_type) && (card == card_info->usb_card)){
1190             list_for_each_safe(node_j, temp_j, &card_info->usb_device_conf_list) {
1191                 dev_info = node_to_item(node_j, struct usb_device_config, list);
1192                 ALOGV("%s: bit-width(%d) channel(%d)",
1193                        __func__, dev_info->bit_width, dev_info->channel_count);
1194                 for (i =  0; i < dev_info->rate_size; i++)
1195                     ALOGV("%s: rate %d", __func__, dev_info->rates[i]);
1196 
1197                 list_remove(node_j);
1198                 free(node_to_item(node_j, struct usb_device_config, list));
1199             }
1200             list_remove(node_i);
1201             if (card_info->usb_snd_mixer) {
1202                 mixer_close(card_info->usb_snd_mixer);
1203             }
1204             free(node_to_item(node_i, struct usb_card_config, list));
1205         }
1206     }
1207     if (audio_is_usb_in_device(device)) { // XXX not sure if we need to check for card
1208         usbmod->is_capture_supported = false;
1209         supported_sample_rates_mask[USB_CAPTURE] = 0;
1210     } else {
1211         supported_sample_rates_mask[USB_PLAYBACK] = 0;
1212     }
1213 
1214 exit:
1215     if (usb_audio_debug_enable)
1216         usb_print_active_device();
1217 
1218     return;
1219 }
1220 
audio_extn_usb_alive(int card)1221 bool audio_extn_usb_alive(int card) {
1222     char path[PATH_MAX] = {0};
1223     // snprintf should never fail
1224     (void) snprintf(path, sizeof(path), "/proc/asound/card%u/stream0", card);
1225     return access(path, F_OK) == 0;
1226 }
1227 
audio_extn_usb_find_service_interval(bool min,bool playback)1228 unsigned long audio_extn_usb_find_service_interval(bool min,
1229                                                    bool playback) {
1230     struct usb_card_config *card_info;
1231     struct usb_device_config *dev_info;
1232     struct listnode *node_i;
1233     struct listnode *node_j;
1234     unsigned long interval_us = min ? ULONG_MAX : 1; // 0 is invalid
1235     list_for_each(node_i, &usbmod->usb_card_conf_list) {
1236         card_info = node_to_item(node_i, struct usb_card_config, list);
1237         list_for_each(node_j, &card_info->usb_device_conf_list) {
1238             dev_info = node_to_item(node_j, struct usb_device_config, list);
1239             if ((playback && (dev_info->type == USB_PLAYBACK)) ||
1240                 (!playback && (dev_info->type == USB_CAPTURE))) {
1241                 interval_us = min ?
1242                         _MIN(interval_us, dev_info->service_interval_us) :
1243                         _MAX(interval_us, dev_info->service_interval_us);
1244             }
1245         }
1246         break;
1247     }
1248     return interval_us;
1249 }
1250 
audio_extn_usb_altset_for_service_interval(bool playback,unsigned long service_interval,uint32_t * bit_width,uint32_t * sample_rate,uint32_t * channel_count)1251 int audio_extn_usb_altset_for_service_interval(bool playback,
1252                                                unsigned long service_interval,
1253                                                uint32_t *bit_width,
1254                                                uint32_t *sample_rate,
1255                                                uint32_t *channel_count)
1256 {
1257     struct usb_card_config *card_info;
1258     struct usb_device_config *dev_info;
1259     struct listnode *node_i;
1260     struct listnode *node_j;
1261     uint32_t bw = 0;
1262     uint32_t ch = 0;
1263     uint32_t sr = 0;
1264     list_for_each(node_i, &usbmod->usb_card_conf_list) {
1265         /* Currently only apply the first playback sound card configuration */
1266         card_info = node_to_item(node_i, struct usb_card_config, list);
1267         list_for_each(node_j, &card_info->usb_device_conf_list) {
1268             dev_info = node_to_item(node_j, struct usb_device_config, list);
1269             if ((playback && dev_info->type == USB_PLAYBACK) ||
1270                 (!playback && dev_info->type == USB_CAPTURE)) {
1271                 if (dev_info->service_interval_us != service_interval)
1272                     continue;
1273                 if (dev_info->bit_width > bw) {
1274                     bw = dev_info->bit_width;
1275                     ch = dev_info->channel_count;
1276                 } else if (dev_info->bit_width == bw &&
1277                            dev_info->channel_count > ch) {
1278                     ch = dev_info->channel_count;
1279                 }
1280             }
1281         }
1282         break;
1283     }
1284     if (bw == 0 || ch == 0)
1285         return -1;
1286     list_for_each(node_i, &usbmod->usb_card_conf_list) {
1287         /* Currently only apply the first playback sound card configuration */
1288         card_info = node_to_item(node_i, struct usb_card_config, list);
1289         if ((playback && usb_output_device(card_info->usb_device_type)) ||
1290             (!playback && usb_input_device(card_info->usb_device_type))) {
1291             usb_get_best_match_for_sample_rate(&card_info->usb_device_conf_list,
1292                                                bw, ch, sr, &sr,
1293                                                service_interval,
1294                                                true);
1295         }
1296         break;
1297     }
1298     if (sr == 0)
1299         return -1;
1300     *bit_width = bw;
1301     *sample_rate = sr;
1302     *channel_count = ch;
1303     return 0;
1304 }
1305 
audio_extn_usb_usbid()1306 char *audio_extn_usb_usbid()
1307 {
1308     struct usb_card_config *card_info;
1309 
1310     if (usbmod == NULL)
1311         return NULL;
1312 
1313     if (list_empty(&usbmod->usb_card_conf_list))
1314         return NULL;
1315 
1316     card_info = node_to_item(list_head(&usbmod->usb_card_conf_list),\
1317                              struct usb_card_config, list);
1318 
1319     return strdup(card_info->usbid);
1320 }
1321 
audio_extn_usb_init(void * adev)1322 void audio_extn_usb_init(void *adev)
1323 {
1324     if (usbmod == NULL) {
1325         usbmod = calloc(1, sizeof(struct usb_module));
1326         if (usbmod == NULL) {
1327             ALOGE("%s: error unable to allocate memory", __func__);
1328             goto exit;
1329         }
1330     } else {
1331         memset(usbmod, 0, sizeof(*usbmod));
1332     }
1333 
1334     list_init(&usbmod->usb_card_conf_list);
1335     usbmod->adev = (struct audio_device*)adev;
1336     usbmod->sidetone_gain = usb_sidetone_gain;
1337     usbmod->is_capture_supported = false;
1338 exit:
1339     return;
1340 }
1341 
audio_extn_usb_deinit(void)1342 void audio_extn_usb_deinit(void)
1343 {
1344     if (NULL != usbmod){
1345         free(usbmod);
1346         usbmod = NULL;
1347     }
1348 }
1349 #endif /*USB_HEADSET_ENABLED end*/
1350