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