Home | History | Annotate | Download | only in hal
      1 /*
      2  * Copyright (C) 2013-2014 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_primary"
     18 /*#define LOG_NDEBUG 0*/
     19 /*#define VERY_VERY_VERBOSE_LOGGING*/
     20 #ifdef VERY_VERY_VERBOSE_LOGGING
     21 #define ALOGVV ALOGV
     22 #else
     23 #define ALOGVV(a...) do { } while(0)
     24 #endif
     25 
     26 #include <errno.h>
     27 #include <pthread.h>
     28 #include <stdint.h>
     29 #include <sys/time.h>
     30 #include <stdlib.h>
     31 #include <math.h>
     32 #include <dlfcn.h>
     33 #include <sys/resource.h>
     34 #include <sys/prctl.h>
     35 
     36 #include <cutils/log.h>
     37 #include <cutils/str_parms.h>
     38 #include <cutils/properties.h>
     39 #include <cutils/atomic.h>
     40 #include <cutils/sched_policy.h>
     41 
     42 #include <hardware/audio_effect.h>
     43 #include <hardware/audio_alsaops.h>
     44 #include <system/thread_defs.h>
     45 #include <audio_effects/effect_aec.h>
     46 #include <audio_effects/effect_ns.h>
     47 #include "audio_hw.h"
     48 #include "audio_extn.h"
     49 #include "platform_api.h"
     50 #include <platform.h>
     51 #include "voice_extn.h"
     52 
     53 #include "sound/compress_params.h"
     54 
     55 #define COMPRESS_OFFLOAD_FRAGMENT_SIZE (32 * 1024)
     56 #define COMPRESS_OFFLOAD_NUM_FRAGMENTS 4
     57 /* ToDo: Check and update a proper value in msec */
     58 #define COMPRESS_OFFLOAD_PLAYBACK_LATENCY 96
     59 #define COMPRESS_PLAYBACK_VOLUME_MAX 0x2000
     60 
     61 #define PROXY_OPEN_RETRY_COUNT           100
     62 #define PROXY_OPEN_WAIT_TIME             20
     63 
     64 static unsigned int configured_low_latency_capture_period_size =
     65         LOW_LATENCY_CAPTURE_PERIOD_SIZE;
     66 
     67 /* This constant enables extended precision handling.
     68  * TODO The flag is off until more testing is done.
     69  */
     70 static const bool k_enable_extended_precision = false;
     71 
     72 struct pcm_config pcm_config_deep_buffer = {
     73     .channels = 2,
     74     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
     75     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
     76     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
     77     .format = PCM_FORMAT_S16_LE,
     78     .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
     79     .stop_threshold = INT_MAX,
     80     .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
     81 };
     82 
     83 struct pcm_config pcm_config_low_latency = {
     84     .channels = 2,
     85     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
     86     .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
     87     .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
     88     .format = PCM_FORMAT_S16_LE,
     89     .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
     90     .stop_threshold = INT_MAX,
     91     .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
     92 };
     93 
     94 struct pcm_config pcm_config_hdmi_multi = {
     95     .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
     96     .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
     97     .period_size = HDMI_MULTI_PERIOD_SIZE,
     98     .period_count = HDMI_MULTI_PERIOD_COUNT,
     99     .format = PCM_FORMAT_S16_LE,
    100     .start_threshold = 0,
    101     .stop_threshold = INT_MAX,
    102     .avail_min = 0,
    103 };
    104 
    105 struct pcm_config pcm_config_audio_capture = {
    106     .channels = 2,
    107     .period_count = AUDIO_CAPTURE_PERIOD_COUNT,
    108     .format = PCM_FORMAT_S16_LE,
    109 };
    110 
    111 #define AFE_PROXY_CHANNEL_COUNT 2
    112 #define AFE_PROXY_SAMPLING_RATE 48000
    113 
    114 #define AFE_PROXY_PLAYBACK_PERIOD_SIZE  768
    115 #define AFE_PROXY_PLAYBACK_PERIOD_COUNT 4
    116 
    117 struct pcm_config pcm_config_afe_proxy_playback = {
    118     .channels = AFE_PROXY_CHANNEL_COUNT,
    119     .rate = AFE_PROXY_SAMPLING_RATE,
    120     .period_size = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    121     .period_count = AFE_PROXY_PLAYBACK_PERIOD_COUNT,
    122     .format = PCM_FORMAT_S16_LE,
    123     .start_threshold = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    124     .stop_threshold = INT_MAX,
    125     .avail_min = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    126 };
    127 
    128 #define AFE_PROXY_RECORD_PERIOD_SIZE  768
    129 #define AFE_PROXY_RECORD_PERIOD_COUNT 4
    130 
    131 struct pcm_config pcm_config_afe_proxy_record = {
    132     .channels = AFE_PROXY_CHANNEL_COUNT,
    133     .rate = AFE_PROXY_SAMPLING_RATE,
    134     .period_size = AFE_PROXY_RECORD_PERIOD_SIZE,
    135     .period_count = AFE_PROXY_RECORD_PERIOD_COUNT,
    136     .format = PCM_FORMAT_S16_LE,
    137     .start_threshold = AFE_PROXY_RECORD_PERIOD_SIZE,
    138     .stop_threshold = INT_MAX,
    139     .avail_min = AFE_PROXY_RECORD_PERIOD_SIZE,
    140 };
    141 
    142 const char * const use_case_table[AUDIO_USECASE_MAX] = {
    143     [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = "deep-buffer-playback",
    144     [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = "low-latency-playback",
    145     [USECASE_AUDIO_PLAYBACK_MULTI_CH] = "multi-channel-playback",
    146     [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
    147 
    148     [USECASE_AUDIO_RECORD] = "audio-record",
    149     [USECASE_AUDIO_RECORD_LOW_LATENCY] = "low-latency-record",
    150 
    151     [USECASE_AUDIO_HFP_SCO] = "hfp-sco",
    152     [USECASE_AUDIO_HFP_SCO_WB] = "hfp-sco-wb",
    153 
    154     [USECASE_VOICE_CALL] = "voice-call",
    155     [USECASE_VOICE2_CALL] = "voice2-call",
    156     [USECASE_VOLTE_CALL] = "volte-call",
    157     [USECASE_QCHAT_CALL] = "qchat-call",
    158     [USECASE_VOWLAN_CALL] = "vowlan-call",
    159 
    160     [USECASE_AUDIO_PLAYBACK_AFE_PROXY] = "afe-proxy-playback",
    161     [USECASE_AUDIO_RECORD_AFE_PROXY] = "afe-proxy-record",
    162 };
    163 
    164 
    165 #define STRING_TO_ENUM(string) { #string, string }
    166 
    167 struct string_to_enum {
    168     const char *name;
    169     uint32_t value;
    170 };
    171 
    172 static const struct string_to_enum out_channels_name_to_enum_table[] = {
    173     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
    174     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
    175     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
    176 };
    177 
    178 static int set_voice_volume_l(struct audio_device *adev, float volume);
    179 
    180 static bool is_supported_format(audio_format_t format)
    181 {
    182     switch (format) {
    183         case AUDIO_FORMAT_MP3:
    184         case AUDIO_FORMAT_AAC_LC:
    185         case AUDIO_FORMAT_AAC_HE_V1:
    186         case AUDIO_FORMAT_AAC_HE_V2:
    187             return true;
    188         default:
    189             break;
    190     }
    191     return false;
    192 }
    193 
    194 static int get_snd_codec_id(audio_format_t format)
    195 {
    196     int id = 0;
    197 
    198     switch (format & AUDIO_FORMAT_MAIN_MASK) {
    199     case AUDIO_FORMAT_MP3:
    200         id = SND_AUDIOCODEC_MP3;
    201         break;
    202     case AUDIO_FORMAT_AAC:
    203         id = SND_AUDIOCODEC_AAC;
    204         break;
    205     default:
    206         ALOGE("%s: Unsupported audio format", __func__);
    207     }
    208 
    209     return id;
    210 }
    211 
    212 int enable_audio_route(struct audio_device *adev,
    213                        struct audio_usecase *usecase)
    214 {
    215     snd_device_t snd_device;
    216     char mixer_path[50];
    217 
    218     if (usecase == NULL)
    219         return -EINVAL;
    220 
    221     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
    222 
    223     if (usecase->type == PCM_CAPTURE)
    224         snd_device = usecase->in_snd_device;
    225     else
    226         snd_device = usecase->out_snd_device;
    227 
    228     strcpy(mixer_path, use_case_table[usecase->id]);
    229     platform_add_backend_name(adev->platform, mixer_path, snd_device);
    230     ALOGD("%s: apply and update mixer path: %s", __func__, mixer_path);
    231     audio_route_apply_and_update_path(adev->audio_route, mixer_path);
    232 
    233     ALOGV("%s: exit", __func__);
    234     return 0;
    235 }
    236 
    237 int disable_audio_route(struct audio_device *adev,
    238                         struct audio_usecase *usecase)
    239 {
    240     snd_device_t snd_device;
    241     char mixer_path[50];
    242 
    243     if (usecase == NULL)
    244         return -EINVAL;
    245 
    246     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
    247     if (usecase->type == PCM_CAPTURE)
    248         snd_device = usecase->in_snd_device;
    249     else
    250         snd_device = usecase->out_snd_device;
    251     strcpy(mixer_path, use_case_table[usecase->id]);
    252     platform_add_backend_name(adev->platform, mixer_path, snd_device);
    253     ALOGD("%s: reset and update mixer path: %s", __func__, mixer_path);
    254     audio_route_reset_and_update_path(adev->audio_route, mixer_path);
    255 
    256     ALOGV("%s: exit", __func__);
    257     return 0;
    258 }
    259 
    260 int enable_snd_device(struct audio_device *adev,
    261                       snd_device_t snd_device)
    262 {
    263     if (snd_device < SND_DEVICE_MIN ||
    264         snd_device >= SND_DEVICE_MAX) {
    265         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
    266         return -EINVAL;
    267     }
    268 
    269     adev->snd_dev_ref_cnt[snd_device]++;
    270     if (adev->snd_dev_ref_cnt[snd_device] > 1) {
    271         ALOGV("%s: snd_device(%d: %s) is already active",
    272               __func__, snd_device, platform_get_snd_device_name(snd_device));
    273         return 0;
    274     }
    275 
    276     if (platform_send_audio_calibration(adev->platform, snd_device) < 0) {
    277         adev->snd_dev_ref_cnt[snd_device]--;
    278         return -EINVAL;
    279     }
    280 
    281     const char * dev_path = platform_get_snd_device_name(snd_device);
    282     ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, dev_path);
    283     audio_route_apply_and_update_path(adev->audio_route, dev_path);
    284 
    285     return 0;
    286 }
    287 
    288 int disable_snd_device(struct audio_device *adev,
    289                        snd_device_t snd_device)
    290 {
    291     if (snd_device < SND_DEVICE_MIN ||
    292         snd_device >= SND_DEVICE_MAX) {
    293         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
    294         return -EINVAL;
    295     }
    296     if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
    297         ALOGE("%s: device ref cnt is already 0", __func__);
    298         return -EINVAL;
    299     }
    300     adev->snd_dev_ref_cnt[snd_device]--;
    301     if (adev->snd_dev_ref_cnt[snd_device] == 0) {
    302         const char * dev_path = platform_get_snd_device_name(snd_device);
    303         ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, dev_path);
    304         audio_route_reset_and_update_path(adev->audio_route, dev_path);
    305     }
    306     return 0;
    307 }
    308 
    309 static void check_usecases_codec_backend(struct audio_device *adev,
    310                                           struct audio_usecase *uc_info,
    311                                           snd_device_t snd_device)
    312 {
    313     struct listnode *node;
    314     struct audio_usecase *usecase;
    315     bool switch_device[AUDIO_USECASE_MAX];
    316     int i, num_uc_to_switch = 0;
    317 
    318     /*
    319      * This function is to make sure that all the usecases that are active on
    320      * the hardware codec backend are always routed to any one device that is
    321      * handled by the hardware codec.
    322      * For example, if low-latency and deep-buffer usecases are currently active
    323      * on speaker and out_set_parameters(headset) is received on low-latency
    324      * output, then we have to make sure deep-buffer is also switched to headset,
    325      * because of the limitation that both the devices cannot be enabled
    326      * at the same time as they share the same backend.
    327      */
    328     /* Disable all the usecases on the shared backend other than the
    329        specified usecase */
    330     for (i = 0; i < AUDIO_USECASE_MAX; i++)
    331         switch_device[i] = false;
    332 
    333     list_for_each(node, &adev->usecase_list) {
    334         usecase = node_to_item(node, struct audio_usecase, list);
    335         if (usecase->type != PCM_CAPTURE &&
    336                 usecase != uc_info &&
    337                 usecase->out_snd_device != snd_device &&
    338                 usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
    339             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
    340                   __func__, use_case_table[usecase->id],
    341                   platform_get_snd_device_name(usecase->out_snd_device));
    342             disable_audio_route(adev, usecase);
    343             switch_device[usecase->id] = true;
    344             num_uc_to_switch++;
    345         }
    346     }
    347 
    348     if (num_uc_to_switch) {
    349         list_for_each(node, &adev->usecase_list) {
    350             usecase = node_to_item(node, struct audio_usecase, list);
    351             if (switch_device[usecase->id]) {
    352                 disable_snd_device(adev, usecase->out_snd_device);
    353             }
    354         }
    355 
    356         list_for_each(node, &adev->usecase_list) {
    357             usecase = node_to_item(node, struct audio_usecase, list);
    358             if (switch_device[usecase->id]) {
    359                 enable_snd_device(adev, snd_device);
    360             }
    361         }
    362 
    363         /* Re-route all the usecases on the shared backend other than the
    364            specified usecase to new snd devices */
    365         list_for_each(node, &adev->usecase_list) {
    366             usecase = node_to_item(node, struct audio_usecase, list);
    367             /* Update the out_snd_device only before enabling the audio route */
    368             if (switch_device[usecase->id] ) {
    369                 usecase->out_snd_device = snd_device;
    370                 enable_audio_route(adev, usecase);
    371             }
    372         }
    373     }
    374 }
    375 
    376 static void check_and_route_capture_usecases(struct audio_device *adev,
    377                                              struct audio_usecase *uc_info,
    378                                              snd_device_t snd_device)
    379 {
    380     struct listnode *node;
    381     struct audio_usecase *usecase;
    382     bool switch_device[AUDIO_USECASE_MAX];
    383     int i, num_uc_to_switch = 0;
    384 
    385     /*
    386      * This function is to make sure that all the active capture usecases
    387      * are always routed to the same input sound device.
    388      * For example, if audio-record and voice-call usecases are currently
    389      * active on speaker(rx) and speaker-mic (tx) and out_set_parameters(earpiece)
    390      * is received for voice call then we have to make sure that audio-record
    391      * usecase is also switched to earpiece i.e. voice-dmic-ef,
    392      * because of the limitation that two devices cannot be enabled
    393      * at the same time if they share the same backend.
    394      */
    395     for (i = 0; i < AUDIO_USECASE_MAX; i++)
    396         switch_device[i] = false;
    397 
    398     list_for_each(node, &adev->usecase_list) {
    399         usecase = node_to_item(node, struct audio_usecase, list);
    400         if (usecase->type != PCM_PLAYBACK &&
    401                 usecase != uc_info &&
    402                 usecase->in_snd_device != snd_device) {
    403             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
    404                   __func__, use_case_table[usecase->id],
    405                   platform_get_snd_device_name(usecase->in_snd_device));
    406             disable_audio_route(adev, usecase);
    407             switch_device[usecase->id] = true;
    408             num_uc_to_switch++;
    409         }
    410     }
    411 
    412     if (num_uc_to_switch) {
    413         list_for_each(node, &adev->usecase_list) {
    414             usecase = node_to_item(node, struct audio_usecase, list);
    415             if (switch_device[usecase->id]) {
    416                 disable_snd_device(adev, usecase->in_snd_device);
    417             }
    418         }
    419 
    420         list_for_each(node, &adev->usecase_list) {
    421             usecase = node_to_item(node, struct audio_usecase, list);
    422             if (switch_device[usecase->id]) {
    423                 enable_snd_device(adev, snd_device);
    424             }
    425         }
    426 
    427         /* Re-route all the usecases on the shared backend other than the
    428            specified usecase to new snd devices */
    429         list_for_each(node, &adev->usecase_list) {
    430             usecase = node_to_item(node, struct audio_usecase, list);
    431             /* Update the in_snd_device only before enabling the audio route */
    432             if (switch_device[usecase->id] ) {
    433                 usecase->in_snd_device = snd_device;
    434                 enable_audio_route(adev, usecase);
    435             }
    436         }
    437     }
    438 }
    439 
    440 /* must be called with hw device mutex locked */
    441 static int read_hdmi_channel_masks(struct stream_out *out)
    442 {
    443     int ret = 0;
    444     int channels = platform_edid_get_max_channels(out->dev->platform);
    445 
    446     switch (channels) {
    447         /*
    448          * Do not handle stereo output in Multi-channel cases
    449          * Stereo case is handled in normal playback path
    450          */
    451     case 6:
    452         ALOGV("%s: HDMI supports 5.1", __func__);
    453         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
    454         break;
    455     case 8:
    456         ALOGV("%s: HDMI supports 5.1 and 7.1 channels", __func__);
    457         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
    458         out->supported_channel_masks[1] = AUDIO_CHANNEL_OUT_7POINT1;
    459         break;
    460     default:
    461         ALOGE("HDMI does not support multi channel playback");
    462         ret = -ENOSYS;
    463         break;
    464     }
    465     return ret;
    466 }
    467 
    468 static audio_usecase_t get_voice_usecase_id_from_list(struct audio_device *adev)
    469 {
    470     struct audio_usecase *usecase;
    471     struct listnode *node;
    472 
    473     list_for_each(node, &adev->usecase_list) {
    474         usecase = node_to_item(node, struct audio_usecase, list);
    475         if (usecase->type == VOICE_CALL) {
    476             ALOGV("%s: usecase id %d", __func__, usecase->id);
    477             return usecase->id;
    478         }
    479     }
    480     return USECASE_INVALID;
    481 }
    482 
    483 struct audio_usecase *get_usecase_from_list(struct audio_device *adev,
    484                                             audio_usecase_t uc_id)
    485 {
    486     struct audio_usecase *usecase;
    487     struct listnode *node;
    488 
    489     list_for_each(node, &adev->usecase_list) {
    490         usecase = node_to_item(node, struct audio_usecase, list);
    491         if (usecase->id == uc_id)
    492             return usecase;
    493     }
    494     return NULL;
    495 }
    496 
    497 int select_devices(struct audio_device *adev,
    498                    audio_usecase_t uc_id)
    499 {
    500     snd_device_t out_snd_device = SND_DEVICE_NONE;
    501     snd_device_t in_snd_device = SND_DEVICE_NONE;
    502     struct audio_usecase *usecase = NULL;
    503     struct audio_usecase *vc_usecase = NULL;
    504     struct audio_usecase *hfp_usecase = NULL;
    505     audio_usecase_t hfp_ucid;
    506     struct listnode *node;
    507     int status = 0;
    508 
    509     usecase = get_usecase_from_list(adev, uc_id);
    510     if (usecase == NULL) {
    511         ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
    512         return -EINVAL;
    513     }
    514 
    515     if ((usecase->type == VOICE_CALL) ||
    516         (usecase->type == PCM_HFP_CALL)) {
    517         out_snd_device = platform_get_output_snd_device(adev->platform,
    518                                                         usecase->stream.out->devices);
    519         in_snd_device = platform_get_input_snd_device(adev->platform, usecase->stream.out->devices);
    520         usecase->devices = usecase->stream.out->devices;
    521     } else {
    522         /*
    523          * If the voice call is active, use the sound devices of voice call usecase
    524          * so that it would not result any device switch. All the usecases will
    525          * be switched to new device when select_devices() is called for voice call
    526          * usecase. This is to avoid switching devices for voice call when
    527          * check_usecases_codec_backend() is called below.
    528          */
    529         if (voice_is_in_call(adev)) {
    530             vc_usecase = get_usecase_from_list(adev,
    531                                                get_voice_usecase_id_from_list(adev));
    532             if ((vc_usecase != NULL) &&
    533                 ((vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
    534                 (usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL))) {
    535                 in_snd_device = vc_usecase->in_snd_device;
    536                 out_snd_device = vc_usecase->out_snd_device;
    537             }
    538         } else if (audio_extn_hfp_is_active(adev)) {
    539             hfp_ucid = audio_extn_hfp_get_usecase();
    540             hfp_usecase = get_usecase_from_list(adev, hfp_ucid);
    541             if (hfp_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
    542                    in_snd_device = hfp_usecase->in_snd_device;
    543                    out_snd_device = hfp_usecase->out_snd_device;
    544             }
    545         }
    546         if (usecase->type == PCM_PLAYBACK) {
    547             usecase->devices = usecase->stream.out->devices;
    548             in_snd_device = SND_DEVICE_NONE;
    549             if (out_snd_device == SND_DEVICE_NONE) {
    550                 out_snd_device = platform_get_output_snd_device(adev->platform,
    551                                             usecase->stream.out->devices);
    552                 if (usecase->stream.out == adev->primary_output &&
    553                         adev->active_input &&
    554                         adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
    555                         out_snd_device != usecase->out_snd_device) {
    556                     select_devices(adev, adev->active_input->usecase);
    557                 }
    558             }
    559         } else if (usecase->type == PCM_CAPTURE) {
    560             usecase->devices = usecase->stream.in->device;
    561             out_snd_device = SND_DEVICE_NONE;
    562             if (in_snd_device == SND_DEVICE_NONE) {
    563                 audio_devices_t out_device = AUDIO_DEVICE_NONE;
    564                 if (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
    565                         adev->primary_output && !adev->primary_output->standby) {
    566                     out_device = adev->primary_output->devices;
    567                     platform_set_echo_reference(adev, false, AUDIO_DEVICE_NONE);
    568                 } else if (usecase->id == USECASE_AUDIO_RECORD_AFE_PROXY) {
    569                     out_device = AUDIO_DEVICE_OUT_TELEPHONY_TX;
    570                 }
    571                 in_snd_device = platform_get_input_snd_device(adev->platform, out_device);
    572             }
    573         }
    574     }
    575 
    576     if (out_snd_device == usecase->out_snd_device &&
    577         in_snd_device == usecase->in_snd_device) {
    578         return 0;
    579     }
    580 
    581     ALOGD("%s: out_snd_device(%d: %s) in_snd_device(%d: %s)", __func__,
    582           out_snd_device, platform_get_snd_device_name(out_snd_device),
    583           in_snd_device,  platform_get_snd_device_name(in_snd_device));
    584 
    585     /*
    586      * Limitation: While in call, to do a device switch we need to disable
    587      * and enable both RX and TX devices though one of them is same as current
    588      * device.
    589      */
    590     if ((usecase->type == VOICE_CALL) &&
    591         (usecase->in_snd_device != SND_DEVICE_NONE) &&
    592         (usecase->out_snd_device != SND_DEVICE_NONE)) {
    593         status = platform_switch_voice_call_device_pre(adev->platform);
    594     }
    595 
    596     /* Disable current sound devices */
    597     if (usecase->out_snd_device != SND_DEVICE_NONE) {
    598         disable_audio_route(adev, usecase);
    599         disable_snd_device(adev, usecase->out_snd_device);
    600     }
    601 
    602     if (usecase->in_snd_device != SND_DEVICE_NONE) {
    603         disable_audio_route(adev, usecase);
    604         disable_snd_device(adev, usecase->in_snd_device);
    605     }
    606 
    607     /* Applicable only on the targets that has external modem.
    608      * New device information should be sent to modem before enabling
    609      * the devices to reduce in-call device switch time.
    610      */
    611     if ((usecase->type == VOICE_CALL) &&
    612         (usecase->in_snd_device != SND_DEVICE_NONE) &&
    613         (usecase->out_snd_device != SND_DEVICE_NONE)) {
    614         status = platform_switch_voice_call_enable_device_config(adev->platform,
    615                                                                  out_snd_device,
    616                                                                  in_snd_device);
    617     }
    618 
    619     /* Enable new sound devices */
    620     if (out_snd_device != SND_DEVICE_NONE) {
    621         if (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND)
    622             check_usecases_codec_backend(adev, usecase, out_snd_device);
    623         enable_snd_device(adev, out_snd_device);
    624     }
    625 
    626     if (in_snd_device != SND_DEVICE_NONE) {
    627         check_and_route_capture_usecases(adev, usecase, in_snd_device);
    628         enable_snd_device(adev, in_snd_device);
    629     }
    630 
    631     if (usecase->type == VOICE_CALL)
    632         status = platform_switch_voice_call_device_post(adev->platform,
    633                                                         out_snd_device,
    634                                                         in_snd_device);
    635 
    636     usecase->in_snd_device = in_snd_device;
    637     usecase->out_snd_device = out_snd_device;
    638 
    639     enable_audio_route(adev, usecase);
    640 
    641     /* Applicable only on the targets that has external modem.
    642      * Enable device command should be sent to modem only after
    643      * enabling voice call mixer controls
    644      */
    645     if (usecase->type == VOICE_CALL)
    646         status = platform_switch_voice_call_usecase_route_post(adev->platform,
    647                                                                out_snd_device,
    648                                                                in_snd_device);
    649 
    650     return status;
    651 }
    652 
    653 static int stop_input_stream(struct stream_in *in)
    654 {
    655     int i, ret = 0;
    656     struct audio_usecase *uc_info;
    657     struct audio_device *adev = in->dev;
    658 
    659     adev->active_input = NULL;
    660 
    661     ALOGV("%s: enter: usecase(%d: %s)", __func__,
    662           in->usecase, use_case_table[in->usecase]);
    663     uc_info = get_usecase_from_list(adev, in->usecase);
    664     if (uc_info == NULL) {
    665         ALOGE("%s: Could not find the usecase (%d) in the list",
    666               __func__, in->usecase);
    667         return -EINVAL;
    668     }
    669 
    670     /* 1. Disable stream specific mixer controls */
    671     disable_audio_route(adev, uc_info);
    672 
    673     /* 2. Disable the tx device */
    674     disable_snd_device(adev, uc_info->in_snd_device);
    675 
    676     list_remove(&uc_info->list);
    677     free(uc_info);
    678 
    679     ALOGV("%s: exit: status(%d)", __func__, ret);
    680     return ret;
    681 }
    682 
    683 int start_input_stream(struct stream_in *in)
    684 {
    685     /* 1. Enable output device and stream routing controls */
    686     int ret = 0;
    687     struct audio_usecase *uc_info;
    688     struct audio_device *adev = in->dev;
    689 
    690     ALOGV("%s: enter: usecase(%d)", __func__, in->usecase);
    691     in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
    692     if (in->pcm_device_id < 0) {
    693         ALOGE("%s: Could not find PCM device id for the usecase(%d)",
    694               __func__, in->usecase);
    695         ret = -EINVAL;
    696         goto error_config;
    697     }
    698 
    699     adev->active_input = in;
    700     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
    701     uc_info->id = in->usecase;
    702     uc_info->type = PCM_CAPTURE;
    703     uc_info->stream.in = in;
    704     uc_info->devices = in->device;
    705     uc_info->in_snd_device = SND_DEVICE_NONE;
    706     uc_info->out_snd_device = SND_DEVICE_NONE;
    707 
    708     list_add_tail(&adev->usecase_list, &uc_info->list);
    709     select_devices(adev, in->usecase);
    710 
    711     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
    712           __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
    713 
    714     unsigned int flags = PCM_IN;
    715     unsigned int pcm_open_retry_count = 0;
    716 
    717     if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY) {
    718         flags |= PCM_MMAP | PCM_NOIRQ;
    719         pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
    720     }
    721 
    722     while (1) {
    723         in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
    724                            flags, &in->config);
    725         if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
    726             ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
    727             if (in->pcm != NULL) {
    728                 pcm_close(in->pcm);
    729                 in->pcm = NULL;
    730             }
    731             if (pcm_open_retry_count-- == 0) {
    732                 ret = -EIO;
    733                 goto error_open;
    734             }
    735             usleep(PROXY_OPEN_WAIT_TIME * 1000);
    736             continue;
    737         }
    738         break;
    739     }
    740 
    741     ALOGV("%s: exit", __func__);
    742     return ret;
    743 
    744 error_open:
    745     stop_input_stream(in);
    746 
    747 error_config:
    748     adev->active_input = NULL;
    749     ALOGD("%s: exit: status(%d)", __func__, ret);
    750 
    751     return ret;
    752 }
    753 
    754 /* must be called with out->lock locked */
    755 static int send_offload_cmd_l(struct stream_out* out, int command)
    756 {
    757     struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));
    758 
    759     ALOGVV("%s %d", __func__, command);
    760 
    761     cmd->cmd = command;
    762     list_add_tail(&out->offload_cmd_list, &cmd->node);
    763     pthread_cond_signal(&out->offload_cond);
    764     return 0;
    765 }
    766 
    767 /* must be called iwth out->lock locked */
    768 static void stop_compressed_output_l(struct stream_out *out)
    769 {
    770     out->offload_state = OFFLOAD_STATE_IDLE;
    771     out->playback_started = 0;
    772     out->send_new_metadata = 1;
    773     if (out->compr != NULL) {
    774         compress_stop(out->compr);
    775         while (out->offload_thread_blocked) {
    776             pthread_cond_wait(&out->cond, &out->lock);
    777         }
    778     }
    779 }
    780 
    781 static void *offload_thread_loop(void *context)
    782 {
    783     struct stream_out *out = (struct stream_out *) context;
    784     struct listnode *item;
    785 
    786     out->offload_state = OFFLOAD_STATE_IDLE;
    787     out->playback_started = 0;
    788 
    789     setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
    790     set_sched_policy(0, SP_FOREGROUND);
    791     prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);
    792 
    793     ALOGV("%s", __func__);
    794     pthread_mutex_lock(&out->lock);
    795     for (;;) {
    796         struct offload_cmd *cmd = NULL;
    797         stream_callback_event_t event;
    798         bool send_callback = false;
    799 
    800         ALOGVV("%s offload_cmd_list %d out->offload_state %d",
    801               __func__, list_empty(&out->offload_cmd_list),
    802               out->offload_state);
    803         if (list_empty(&out->offload_cmd_list)) {
    804             ALOGV("%s SLEEPING", __func__);
    805             pthread_cond_wait(&out->offload_cond, &out->lock);
    806             ALOGV("%s RUNNING", __func__);
    807             continue;
    808         }
    809 
    810         item = list_head(&out->offload_cmd_list);
    811         cmd = node_to_item(item, struct offload_cmd, node);
    812         list_remove(item);
    813 
    814         ALOGVV("%s STATE %d CMD %d out->compr %p",
    815                __func__, out->offload_state, cmd->cmd, out->compr);
    816 
    817         if (cmd->cmd == OFFLOAD_CMD_EXIT) {
    818             free(cmd);
    819             break;
    820         }
    821 
    822         if (out->compr == NULL) {
    823             ALOGE("%s: Compress handle is NULL", __func__);
    824             pthread_cond_signal(&out->cond);
    825             continue;
    826         }
    827         out->offload_thread_blocked = true;
    828         pthread_mutex_unlock(&out->lock);
    829         send_callback = false;
    830         switch(cmd->cmd) {
    831         case OFFLOAD_CMD_WAIT_FOR_BUFFER:
    832             compress_wait(out->compr, -1);
    833             send_callback = true;
    834             event = STREAM_CBK_EVENT_WRITE_READY;
    835             break;
    836         case OFFLOAD_CMD_PARTIAL_DRAIN:
    837             compress_next_track(out->compr);
    838             compress_partial_drain(out->compr);
    839             send_callback = true;
    840             event = STREAM_CBK_EVENT_DRAIN_READY;
    841             /* Resend the metadata for next iteration */
    842             out->send_new_metadata = 1;
    843             break;
    844         case OFFLOAD_CMD_DRAIN:
    845             compress_drain(out->compr);
    846             send_callback = true;
    847             event = STREAM_CBK_EVENT_DRAIN_READY;
    848             break;
    849         default:
    850             ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
    851             break;
    852         }
    853         pthread_mutex_lock(&out->lock);
    854         out->offload_thread_blocked = false;
    855         pthread_cond_signal(&out->cond);
    856         if (send_callback) {
    857             ALOGVV("%s: sending offload_callback event %d", __func__, event);
    858             out->offload_callback(event, NULL, out->offload_cookie);
    859         }
    860         free(cmd);
    861     }
    862 
    863     pthread_cond_signal(&out->cond);
    864     while (!list_empty(&out->offload_cmd_list)) {
    865         item = list_head(&out->offload_cmd_list);
    866         list_remove(item);
    867         free(node_to_item(item, struct offload_cmd, node));
    868     }
    869     pthread_mutex_unlock(&out->lock);
    870 
    871     return NULL;
    872 }
    873 
    874 static int create_offload_callback_thread(struct stream_out *out)
    875 {
    876     pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
    877     list_init(&out->offload_cmd_list);
    878     pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
    879                     offload_thread_loop, out);
    880     return 0;
    881 }
    882 
    883 static int destroy_offload_callback_thread(struct stream_out *out)
    884 {
    885     pthread_mutex_lock(&out->lock);
    886     stop_compressed_output_l(out);
    887     send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);
    888 
    889     pthread_mutex_unlock(&out->lock);
    890     pthread_join(out->offload_thread, (void **) NULL);
    891     pthread_cond_destroy(&out->offload_cond);
    892 
    893     return 0;
    894 }
    895 
    896 static bool allow_hdmi_channel_config(struct audio_device *adev)
    897 {
    898     struct listnode *node;
    899     struct audio_usecase *usecase;
    900     bool ret = true;
    901 
    902     list_for_each(node, &adev->usecase_list) {
    903         usecase = node_to_item(node, struct audio_usecase, list);
    904         if (usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
    905             /*
    906              * If voice call is already existing, do not proceed further to avoid
    907              * disabling/enabling both RX and TX devices, CSD calls, etc.
    908              * Once the voice call done, the HDMI channels can be configured to
    909              * max channels of remaining use cases.
    910              */
    911             if (usecase->id == USECASE_VOICE_CALL) {
    912                 ALOGD("%s: voice call is active, no change in HDMI channels",
    913                       __func__);
    914                 ret = false;
    915                 break;
    916             } else if (usecase->id == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
    917                 ALOGD("%s: multi channel playback is active, "
    918                       "no change in HDMI channels", __func__);
    919                 ret = false;
    920                 break;
    921             }
    922         }
    923     }
    924     return ret;
    925 }
    926 
    927 static int check_and_set_hdmi_channels(struct audio_device *adev,
    928                                        unsigned int channels)
    929 {
    930     struct listnode *node;
    931     struct audio_usecase *usecase;
    932 
    933     /* Check if change in HDMI channel config is allowed */
    934     if (!allow_hdmi_channel_config(adev))
    935         return 0;
    936 
    937     if (channels == adev->cur_hdmi_channels) {
    938         ALOGD("%s: Requested channels are same as current", __func__);
    939         return 0;
    940     }
    941 
    942     platform_set_hdmi_channels(adev->platform, channels);
    943     adev->cur_hdmi_channels = channels;
    944 
    945     /*
    946      * Deroute all the playback streams routed to HDMI so that
    947      * the back end is deactivated. Note that backend will not
    948      * be deactivated if any one stream is connected to it.
    949      */
    950     list_for_each(node, &adev->usecase_list) {
    951         usecase = node_to_item(node, struct audio_usecase, list);
    952         if (usecase->type == PCM_PLAYBACK &&
    953                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
    954             disable_audio_route(adev, usecase);
    955         }
    956     }
    957 
    958     /*
    959      * Enable all the streams disabled above. Now the HDMI backend
    960      * will be activated with new channel configuration
    961      */
    962     list_for_each(node, &adev->usecase_list) {
    963         usecase = node_to_item(node, struct audio_usecase, list);
    964         if (usecase->type == PCM_PLAYBACK &&
    965                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
    966             enable_audio_route(adev, usecase);
    967         }
    968     }
    969 
    970     return 0;
    971 }
    972 
    973 static int stop_output_stream(struct stream_out *out)
    974 {
    975     int i, ret = 0;
    976     struct audio_usecase *uc_info;
    977     struct audio_device *adev = out->dev;
    978 
    979     ALOGV("%s: enter: usecase(%d: %s)", __func__,
    980           out->usecase, use_case_table[out->usecase]);
    981     uc_info = get_usecase_from_list(adev, out->usecase);
    982     if (uc_info == NULL) {
    983         ALOGE("%s: Could not find the usecase (%d) in the list",
    984               __func__, out->usecase);
    985         return -EINVAL;
    986     }
    987 
    988     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
    989         if (adev->visualizer_stop_output != NULL)
    990             adev->visualizer_stop_output(out->handle, out->pcm_device_id);
    991         if (adev->offload_effects_stop_output != NULL)
    992             adev->offload_effects_stop_output(out->handle, out->pcm_device_id);
    993     }
    994 
    995     /* 1. Get and set stream specific mixer controls */
    996     disable_audio_route(adev, uc_info);
    997 
    998     /* 2. Disable the rx device */
    999     disable_snd_device(adev, uc_info->out_snd_device);
   1000 
   1001     list_remove(&uc_info->list);
   1002     free(uc_info);
   1003 
   1004     audio_extn_extspk_update(adev->extspk);
   1005 
   1006     /* Must be called after removing the usecase from list */
   1007     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
   1008         check_and_set_hdmi_channels(adev, DEFAULT_HDMI_OUT_CHANNELS);
   1009 
   1010     ALOGV("%s: exit: status(%d)", __func__, ret);
   1011     return ret;
   1012 }
   1013 
   1014 int start_output_stream(struct stream_out *out)
   1015 {
   1016     int ret = 0;
   1017     struct audio_usecase *uc_info;
   1018     struct audio_device *adev = out->dev;
   1019 
   1020     ALOGV("%s: enter: usecase(%d: %s) devices(%#x)",
   1021           __func__, out->usecase, use_case_table[out->usecase], out->devices);
   1022     out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
   1023     if (out->pcm_device_id < 0) {
   1024         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
   1025               __func__, out->pcm_device_id, out->usecase);
   1026         ret = -EINVAL;
   1027         goto error_config;
   1028     }
   1029 
   1030     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
   1031     uc_info->id = out->usecase;
   1032     uc_info->type = PCM_PLAYBACK;
   1033     uc_info->stream.out = out;
   1034     uc_info->devices = out->devices;
   1035     uc_info->in_snd_device = SND_DEVICE_NONE;
   1036     uc_info->out_snd_device = SND_DEVICE_NONE;
   1037 
   1038     /* This must be called before adding this usecase to the list */
   1039     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
   1040         check_and_set_hdmi_channels(adev, out->config.channels);
   1041 
   1042     list_add_tail(&adev->usecase_list, &uc_info->list);
   1043 
   1044     select_devices(adev, out->usecase);
   1045 
   1046     audio_extn_extspk_update(adev->extspk);
   1047 
   1048     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d) format(%#x)",
   1049           __func__, adev->snd_card, out->pcm_device_id, out->config.format);
   1050     if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1051         unsigned int flags = PCM_OUT;
   1052         unsigned int pcm_open_retry_count = 0;
   1053         if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY) {
   1054             flags |= PCM_MMAP | PCM_NOIRQ;
   1055             pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
   1056         } else
   1057             flags |= PCM_MONOTONIC;
   1058 
   1059         while (1) {
   1060             out->pcm = pcm_open(adev->snd_card, out->pcm_device_id,
   1061                                flags, &out->config);
   1062             if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
   1063                 ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
   1064                 if (out->pcm != NULL) {
   1065                     pcm_close(out->pcm);
   1066                     out->pcm = NULL;
   1067                 }
   1068                 if (pcm_open_retry_count-- == 0) {
   1069                     ret = -EIO;
   1070                     goto error_open;
   1071                 }
   1072                 usleep(PROXY_OPEN_WAIT_TIME * 1000);
   1073                 continue;
   1074             }
   1075             break;
   1076         }
   1077     } else {
   1078         out->pcm = NULL;
   1079         out->compr = compress_open(adev->snd_card, out->pcm_device_id,
   1080                                    COMPRESS_IN, &out->compr_config);
   1081         if (out->compr && !is_compress_ready(out->compr)) {
   1082             ALOGE("%s: %s", __func__, compress_get_error(out->compr));
   1083             compress_close(out->compr);
   1084             out->compr = NULL;
   1085             ret = -EIO;
   1086             goto error_open;
   1087         }
   1088         if (out->offload_callback)
   1089             compress_nonblock(out->compr, out->non_blocking);
   1090 
   1091         if (adev->visualizer_start_output != NULL)
   1092             adev->visualizer_start_output(out->handle, out->pcm_device_id);
   1093         if (adev->offload_effects_start_output != NULL)
   1094             adev->offload_effects_start_output(out->handle, out->pcm_device_id);
   1095     }
   1096     ALOGV("%s: exit", __func__);
   1097     return 0;
   1098 error_open:
   1099     stop_output_stream(out);
   1100 error_config:
   1101     return ret;
   1102 }
   1103 
   1104 static int check_input_parameters(uint32_t sample_rate,
   1105                                   audio_format_t format,
   1106                                   int channel_count)
   1107 {
   1108     if (format != AUDIO_FORMAT_PCM_16_BIT) return -EINVAL;
   1109 
   1110     if ((channel_count < 1) || (channel_count > 2)) return -EINVAL;
   1111 
   1112     switch (sample_rate) {
   1113     case 8000:
   1114     case 11025:
   1115     case 12000:
   1116     case 16000:
   1117     case 22050:
   1118     case 24000:
   1119     case 32000:
   1120     case 44100:
   1121     case 48000:
   1122         break;
   1123     default:
   1124         return -EINVAL;
   1125     }
   1126 
   1127     return 0;
   1128 }
   1129 
   1130 static size_t get_input_buffer_size(uint32_t sample_rate,
   1131                                     audio_format_t format,
   1132                                     int channel_count,
   1133                                     bool is_low_latency)
   1134 {
   1135     size_t size = 0;
   1136 
   1137     if (check_input_parameters(sample_rate, format, channel_count) != 0)
   1138         return 0;
   1139 
   1140     size = (sample_rate * AUDIO_CAPTURE_PERIOD_DURATION_MSEC) / 1000;
   1141     if (is_low_latency)
   1142         size = configured_low_latency_capture_period_size;
   1143     /* ToDo: should use frame_size computed based on the format and
   1144        channel_count here. */
   1145     size *= sizeof(short) * channel_count;
   1146 
   1147     /* make sure the size is multiple of 32 bytes
   1148      * At 48 kHz mono 16-bit PCM:
   1149      *  5.000 ms = 240 frames = 15*16*1*2 = 480, a whole multiple of 32 (15)
   1150      *  3.333 ms = 160 frames = 10*16*1*2 = 320, a whole multiple of 32 (10)
   1151      */
   1152     size += 0x1f;
   1153     size &= ~0x1f;
   1154 
   1155     return size;
   1156 }
   1157 
   1158 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
   1159 {
   1160     struct stream_out *out = (struct stream_out *)stream;
   1161 
   1162     return out->sample_rate;
   1163 }
   1164 
   1165 static int out_set_sample_rate(struct audio_stream *stream __unused, uint32_t rate __unused)
   1166 {
   1167     return -ENOSYS;
   1168 }
   1169 
   1170 static size_t out_get_buffer_size(const struct audio_stream *stream)
   1171 {
   1172     struct stream_out *out = (struct stream_out *)stream;
   1173 
   1174     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1175         return out->compr_config.fragment_size;
   1176     }
   1177     return out->config.period_size *
   1178                 audio_stream_out_frame_size((const struct audio_stream_out *)stream);
   1179 }
   1180 
   1181 static uint32_t out_get_channels(const struct audio_stream *stream)
   1182 {
   1183     struct stream_out *out = (struct stream_out *)stream;
   1184 
   1185     return out->channel_mask;
   1186 }
   1187 
   1188 static audio_format_t out_get_format(const struct audio_stream *stream)
   1189 {
   1190     struct stream_out *out = (struct stream_out *)stream;
   1191 
   1192     return out->format;
   1193 }
   1194 
   1195 static int out_set_format(struct audio_stream *stream __unused, audio_format_t format __unused)
   1196 {
   1197     return -ENOSYS;
   1198 }
   1199 
   1200 static int out_standby(struct audio_stream *stream)
   1201 {
   1202     struct stream_out *out = (struct stream_out *)stream;
   1203     struct audio_device *adev = out->dev;
   1204 
   1205     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   1206           out->usecase, use_case_table[out->usecase]);
   1207 
   1208     pthread_mutex_lock(&out->lock);
   1209     if (!out->standby) {
   1210         pthread_mutex_lock(&adev->lock);
   1211         out->standby = true;
   1212         if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1213             if (out->pcm) {
   1214                 pcm_close(out->pcm);
   1215                 out->pcm = NULL;
   1216             }
   1217         } else {
   1218             stop_compressed_output_l(out);
   1219             out->gapless_mdata.encoder_delay = 0;
   1220             out->gapless_mdata.encoder_padding = 0;
   1221             if (out->compr != NULL) {
   1222                 compress_close(out->compr);
   1223                 out->compr = NULL;
   1224             }
   1225         }
   1226         stop_output_stream(out);
   1227         pthread_mutex_unlock(&adev->lock);
   1228     }
   1229     pthread_mutex_unlock(&out->lock);
   1230     ALOGV("%s: exit", __func__);
   1231     return 0;
   1232 }
   1233 
   1234 static int out_dump(const struct audio_stream *stream __unused, int fd __unused)
   1235 {
   1236     return 0;
   1237 }
   1238 
   1239 static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
   1240 {
   1241     int ret = 0;
   1242     char value[32];
   1243     struct compr_gapless_mdata tmp_mdata;
   1244 
   1245     if (!out || !parms) {
   1246         return -EINVAL;
   1247     }
   1248 
   1249     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
   1250     if (ret >= 0) {
   1251         tmp_mdata.encoder_delay = atoi(value); //whats a good limit check?
   1252     } else {
   1253         return -EINVAL;
   1254     }
   1255 
   1256     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
   1257     if (ret >= 0) {
   1258         tmp_mdata.encoder_padding = atoi(value);
   1259     } else {
   1260         return -EINVAL;
   1261     }
   1262 
   1263     out->gapless_mdata = tmp_mdata;
   1264     out->send_new_metadata = 1;
   1265     ALOGV("%s new encoder delay %u and padding %u", __func__,
   1266           out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);
   1267 
   1268     return 0;
   1269 }
   1270 
   1271 static bool output_drives_call(struct audio_device *adev, struct stream_out *out)
   1272 {
   1273     return out == adev->primary_output || out == adev->voice_tx_output;
   1274 }
   1275 
   1276 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
   1277 {
   1278     struct stream_out *out = (struct stream_out *)stream;
   1279     struct audio_device *adev = out->dev;
   1280     struct audio_usecase *usecase;
   1281     struct listnode *node;
   1282     struct str_parms *parms;
   1283     char value[32];
   1284     int ret, val = 0;
   1285     bool select_new_device = false;
   1286     int status = 0;
   1287 
   1288     ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s",
   1289           __func__, out->usecase, use_case_table[out->usecase], kvpairs);
   1290     parms = str_parms_create_str(kvpairs);
   1291     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
   1292     if (ret >= 0) {
   1293         val = atoi(value);
   1294         pthread_mutex_lock(&out->lock);
   1295         pthread_mutex_lock(&adev->lock);
   1296 
   1297         /*
   1298          * When HDMI cable is unplugged the music playback is paused and
   1299          * the policy manager sends routing=0. But the audioflinger
   1300          * continues to write data until standby time (3sec).
   1301          * As the HDMI core is turned off, the write gets blocked.
   1302          * Avoid this by routing audio to speaker until standby.
   1303          */
   1304         if (out->devices == AUDIO_DEVICE_OUT_AUX_DIGITAL &&
   1305                 val == AUDIO_DEVICE_NONE) {
   1306             val = AUDIO_DEVICE_OUT_SPEAKER;
   1307         }
   1308 
   1309         /*
   1310          * select_devices() call below switches all the usecases on the same
   1311          * backend to the new device. Refer to check_usecases_codec_backend() in
   1312          * the select_devices(). But how do we undo this?
   1313          *
   1314          * For example, music playback is active on headset (deep-buffer usecase)
   1315          * and if we go to ringtones and select a ringtone, low-latency usecase
   1316          * will be started on headset+speaker. As we can't enable headset+speaker
   1317          * and headset devices at the same time, select_devices() switches the music
   1318          * playback to headset+speaker while starting low-lateny usecase for ringtone.
   1319          * So when the ringtone playback is completed, how do we undo the same?
   1320          *
   1321          * We are relying on the out_set_parameters() call on deep-buffer output,
   1322          * once the ringtone playback is ended.
   1323          * NOTE: We should not check if the current devices are same as new devices.
   1324          *       Because select_devices() must be called to switch back the music
   1325          *       playback to headset.
   1326          */
   1327         if (val != 0) {
   1328             out->devices = val;
   1329 
   1330             if (!out->standby)
   1331                 select_devices(adev, out->usecase);
   1332 
   1333             if (output_drives_call(adev, out)) {
   1334                 if (!voice_is_in_call(adev)) {
   1335                     if (adev->mode == AUDIO_MODE_IN_CALL) {
   1336                         adev->current_call_output = out;
   1337                         ret = voice_start_call(adev);
   1338                     }
   1339                 } else {
   1340                     adev->current_call_output = out;
   1341                     voice_update_devices_for_all_voice_usecases(adev);
   1342                 }
   1343             }
   1344         }
   1345 
   1346         pthread_mutex_unlock(&adev->lock);
   1347         pthread_mutex_unlock(&out->lock);
   1348 
   1349         /*handles device and call state changes*/
   1350         audio_extn_extspk_update(adev->extspk);
   1351     }
   1352 
   1353     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1354         parse_compress_metadata(out, parms);
   1355     }
   1356 
   1357     str_parms_destroy(parms);
   1358     ALOGV("%s: exit: code(%d)", __func__, status);
   1359     return status;
   1360 }
   1361 
   1362 static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
   1363 {
   1364     struct stream_out *out = (struct stream_out *)stream;
   1365     struct str_parms *query = str_parms_create_str(keys);
   1366     char *str;
   1367     char value[256];
   1368     struct str_parms *reply = str_parms_create();
   1369     size_t i, j;
   1370     int ret;
   1371     bool first = true;
   1372     ALOGV("%s: enter: keys - %s", __func__, keys);
   1373     ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value, sizeof(value));
   1374     if (ret >= 0) {
   1375         value[0] = '\0';
   1376         i = 0;
   1377         while (out->supported_channel_masks[i] != 0) {
   1378             for (j = 0; j < ARRAY_SIZE(out_channels_name_to_enum_table); j++) {
   1379                 if (out_channels_name_to_enum_table[j].value == out->supported_channel_masks[i]) {
   1380                     if (!first) {
   1381                         strcat(value, "|");
   1382                     }
   1383                     strcat(value, out_channels_name_to_enum_table[j].name);
   1384                     first = false;
   1385                     break;
   1386                 }
   1387             }
   1388             i++;
   1389         }
   1390         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
   1391         str = str_parms_to_str(reply);
   1392     } else {
   1393         str = strdup(keys);
   1394     }
   1395     str_parms_destroy(query);
   1396     str_parms_destroy(reply);
   1397     ALOGV("%s: exit: returns - %s", __func__, str);
   1398     return str;
   1399 }
   1400 
   1401 static uint32_t out_get_latency(const struct audio_stream_out *stream)
   1402 {
   1403     struct stream_out *out = (struct stream_out *)stream;
   1404 
   1405     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
   1406         return COMPRESS_OFFLOAD_PLAYBACK_LATENCY;
   1407 
   1408     return (out->config.period_count * out->config.period_size * 1000) /
   1409            (out->config.rate);
   1410 }
   1411 
   1412 static int out_set_volume(struct audio_stream_out *stream, float left,
   1413                           float right)
   1414 {
   1415     struct stream_out *out = (struct stream_out *)stream;
   1416     int volume[2];
   1417 
   1418     if (out->usecase == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
   1419         /* only take left channel into account: the API is for stereo anyway */
   1420         out->muted = (left == 0.0f);
   1421         return 0;
   1422     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1423         const char *mixer_ctl_name = "Compress Playback Volume";
   1424         struct audio_device *adev = out->dev;
   1425         struct mixer_ctl *ctl;
   1426         ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
   1427         if (!ctl) {
   1428             /* try with the control based on device id */
   1429             int pcm_device_id = platform_get_pcm_device_id(out->usecase,
   1430                                                        PCM_PLAYBACK);
   1431             char ctl_name[128] = {0};
   1432             snprintf(ctl_name, sizeof(ctl_name),
   1433                      "Compress Playback %d Volume", pcm_device_id);
   1434             ctl = mixer_get_ctl_by_name(adev->mixer, ctl_name);
   1435             if (!ctl) {
   1436                 ALOGE("%s: Could not get volume ctl mixer cmd", __func__);
   1437                 return -EINVAL;
   1438             }
   1439         }
   1440         volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
   1441         volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
   1442         mixer_ctl_set_array(ctl, volume, sizeof(volume)/sizeof(volume[0]));
   1443         return 0;
   1444     }
   1445 
   1446     return -ENOSYS;
   1447 }
   1448 
   1449 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
   1450                          size_t bytes)
   1451 {
   1452     struct stream_out *out = (struct stream_out *)stream;
   1453     struct audio_device *adev = out->dev;
   1454     ssize_t ret = 0;
   1455 
   1456     pthread_mutex_lock(&out->lock);
   1457     if (out->standby) {
   1458         out->standby = false;
   1459         pthread_mutex_lock(&adev->lock);
   1460         ret = start_output_stream(out);
   1461         pthread_mutex_unlock(&adev->lock);
   1462         /* ToDo: If use case is compress offload should return 0 */
   1463         if (ret != 0) {
   1464             out->standby = true;
   1465             goto exit;
   1466         }
   1467     }
   1468 
   1469     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1470         ALOGVV("%s: writing buffer (%d bytes) to compress device", __func__, bytes);
   1471         if (out->send_new_metadata) {
   1472             ALOGVV("send new gapless metadata");
   1473             compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
   1474             out->send_new_metadata = 0;
   1475         }
   1476 
   1477         ret = compress_write(out->compr, buffer, bytes);
   1478         ALOGVV("%s: writing buffer (%d bytes) to compress device returned %d", __func__, bytes, ret);
   1479         if (ret >= 0 && ret < (ssize_t)bytes) {
   1480             send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
   1481         }
   1482         if (!out->playback_started) {
   1483             compress_start(out->compr);
   1484             out->playback_started = 1;
   1485             out->offload_state = OFFLOAD_STATE_PLAYING;
   1486         }
   1487         pthread_mutex_unlock(&out->lock);
   1488         return ret;
   1489     } else {
   1490         if (out->pcm) {
   1491             if (out->muted)
   1492                 memset((void *)buffer, 0, bytes);
   1493             ALOGVV("%s: writing buffer (%d bytes) to pcm device", __func__, bytes);
   1494             if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY) {
   1495                 ret = pcm_mmap_write(out->pcm, (void *)buffer, bytes);
   1496             }
   1497             else
   1498                 ret = pcm_write(out->pcm, (void *)buffer, bytes);
   1499             if (ret == 0)
   1500                 out->written += bytes / (out->config.channels * sizeof(short));
   1501         }
   1502     }
   1503 
   1504 exit:
   1505     pthread_mutex_unlock(&out->lock);
   1506 
   1507     if (ret != 0) {
   1508         if (out->pcm)
   1509             ALOGE("%s: error %d - %s", __func__, ret, pcm_get_error(out->pcm));
   1510         out_standby(&out->stream.common);
   1511         usleep(bytes * 1000000 / audio_stream_out_frame_size(stream) /
   1512                out_get_sample_rate(&out->stream.common));
   1513     }
   1514     return bytes;
   1515 }
   1516 
   1517 static int out_get_render_position(const struct audio_stream_out *stream,
   1518                                    uint32_t *dsp_frames)
   1519 {
   1520     struct stream_out *out = (struct stream_out *)stream;
   1521     *dsp_frames = 0;
   1522     if ((out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) && (dsp_frames != NULL)) {
   1523         pthread_mutex_lock(&out->lock);
   1524         if (out->compr != NULL) {
   1525             compress_get_tstamp(out->compr, (unsigned long *)dsp_frames,
   1526                     &out->sample_rate);
   1527             ALOGVV("%s rendered frames %d sample_rate %d",
   1528                    __func__, *dsp_frames, out->sample_rate);
   1529         }
   1530         pthread_mutex_unlock(&out->lock);
   1531         return 0;
   1532     } else
   1533         return -EINVAL;
   1534 }
   1535 
   1536 static int out_add_audio_effect(const struct audio_stream *stream __unused,
   1537                                 effect_handle_t effect __unused)
   1538 {
   1539     return 0;
   1540 }
   1541 
   1542 static int out_remove_audio_effect(const struct audio_stream *stream __unused,
   1543                                    effect_handle_t effect __unused)
   1544 {
   1545     return 0;
   1546 }
   1547 
   1548 static int out_get_next_write_timestamp(const struct audio_stream_out *stream __unused,
   1549                                         int64_t *timestamp __unused)
   1550 {
   1551     return -EINVAL;
   1552 }
   1553 
   1554 static int out_get_presentation_position(const struct audio_stream_out *stream,
   1555                                    uint64_t *frames, struct timespec *timestamp)
   1556 {
   1557     struct stream_out *out = (struct stream_out *)stream;
   1558     int ret = -1;
   1559     unsigned long dsp_frames;
   1560 
   1561     pthread_mutex_lock(&out->lock);
   1562 
   1563     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1564         if (out->compr != NULL) {
   1565             compress_get_tstamp(out->compr, &dsp_frames,
   1566                     &out->sample_rate);
   1567             ALOGVV("%s rendered frames %ld sample_rate %d",
   1568                    __func__, dsp_frames, out->sample_rate);
   1569             *frames = dsp_frames;
   1570             ret = 0;
   1571             /* this is the best we can do */
   1572             clock_gettime(CLOCK_MONOTONIC, timestamp);
   1573         }
   1574     } else {
   1575         if (out->pcm) {
   1576             size_t avail;
   1577             if (pcm_get_htimestamp(out->pcm, &avail, timestamp) == 0) {
   1578                 size_t kernel_buffer_size = out->config.period_size * out->config.period_count;
   1579                 int64_t signed_frames = out->written - kernel_buffer_size + avail;
   1580                 // This adjustment accounts for buffering after app processor.
   1581                 // It is based on estimated DSP latency per use case, rather than exact.
   1582                 signed_frames -=
   1583                     (platform_render_latency(out->usecase) * out->sample_rate / 1000000LL);
   1584 
   1585                 // It would be unusual for this value to be negative, but check just in case ...
   1586                 if (signed_frames >= 0) {
   1587                     *frames = signed_frames;
   1588                     ret = 0;
   1589                 }
   1590             }
   1591         }
   1592     }
   1593 
   1594     pthread_mutex_unlock(&out->lock);
   1595 
   1596     return ret;
   1597 }
   1598 
   1599 static int out_set_callback(struct audio_stream_out *stream,
   1600             stream_callback_t callback, void *cookie)
   1601 {
   1602     struct stream_out *out = (struct stream_out *)stream;
   1603 
   1604     ALOGV("%s", __func__);
   1605     pthread_mutex_lock(&out->lock);
   1606     out->offload_callback = callback;
   1607     out->offload_cookie = cookie;
   1608     pthread_mutex_unlock(&out->lock);
   1609     return 0;
   1610 }
   1611 
   1612 static int out_pause(struct audio_stream_out* stream)
   1613 {
   1614     struct stream_out *out = (struct stream_out *)stream;
   1615     int status = -ENOSYS;
   1616     ALOGV("%s", __func__);
   1617     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1618         pthread_mutex_lock(&out->lock);
   1619         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
   1620             status = compress_pause(out->compr);
   1621             out->offload_state = OFFLOAD_STATE_PAUSED;
   1622         }
   1623         pthread_mutex_unlock(&out->lock);
   1624     }
   1625     return status;
   1626 }
   1627 
   1628 static int out_resume(struct audio_stream_out* stream)
   1629 {
   1630     struct stream_out *out = (struct stream_out *)stream;
   1631     int status = -ENOSYS;
   1632     ALOGV("%s", __func__);
   1633     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1634         status = 0;
   1635         pthread_mutex_lock(&out->lock);
   1636         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
   1637             status = compress_resume(out->compr);
   1638             out->offload_state = OFFLOAD_STATE_PLAYING;
   1639         }
   1640         pthread_mutex_unlock(&out->lock);
   1641     }
   1642     return status;
   1643 }
   1644 
   1645 static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
   1646 {
   1647     struct stream_out *out = (struct stream_out *)stream;
   1648     int status = -ENOSYS;
   1649     ALOGV("%s", __func__);
   1650     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1651         pthread_mutex_lock(&out->lock);
   1652         if (type == AUDIO_DRAIN_EARLY_NOTIFY)
   1653             status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
   1654         else
   1655             status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
   1656         pthread_mutex_unlock(&out->lock);
   1657     }
   1658     return status;
   1659 }
   1660 
   1661 static int out_flush(struct audio_stream_out* stream)
   1662 {
   1663     struct stream_out *out = (struct stream_out *)stream;
   1664     ALOGV("%s", __func__);
   1665     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1666         pthread_mutex_lock(&out->lock);
   1667         stop_compressed_output_l(out);
   1668         pthread_mutex_unlock(&out->lock);
   1669         return 0;
   1670     }
   1671     return -ENOSYS;
   1672 }
   1673 
   1674 /** audio_stream_in implementation **/
   1675 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
   1676 {
   1677     struct stream_in *in = (struct stream_in *)stream;
   1678 
   1679     return in->config.rate;
   1680 }
   1681 
   1682 static int in_set_sample_rate(struct audio_stream *stream __unused, uint32_t rate __unused)
   1683 {
   1684     return -ENOSYS;
   1685 }
   1686 
   1687 static size_t in_get_buffer_size(const struct audio_stream *stream)
   1688 {
   1689     struct stream_in *in = (struct stream_in *)stream;
   1690 
   1691     return in->config.period_size *
   1692                 audio_stream_in_frame_size((const struct audio_stream_in *)stream);
   1693 }
   1694 
   1695 static uint32_t in_get_channels(const struct audio_stream *stream)
   1696 {
   1697     struct stream_in *in = (struct stream_in *)stream;
   1698 
   1699     return in->channel_mask;
   1700 }
   1701 
   1702 static audio_format_t in_get_format(const struct audio_stream *stream __unused)
   1703 {
   1704     return AUDIO_FORMAT_PCM_16_BIT;
   1705 }
   1706 
   1707 static int in_set_format(struct audio_stream *stream __unused, audio_format_t format __unused)
   1708 {
   1709     return -ENOSYS;
   1710 }
   1711 
   1712 static int in_standby(struct audio_stream *stream)
   1713 {
   1714     struct stream_in *in = (struct stream_in *)stream;
   1715     struct audio_device *adev = in->dev;
   1716     int status = 0;
   1717     ALOGV("%s: enter", __func__);
   1718     pthread_mutex_lock(&in->lock);
   1719     if (!in->standby) {
   1720         pthread_mutex_lock(&adev->lock);
   1721         in->standby = true;
   1722         if (in->pcm) {
   1723             pcm_close(in->pcm);
   1724             in->pcm = NULL;
   1725         }
   1726         adev->enable_voicerx = false;
   1727         platform_set_echo_reference(adev, false, AUDIO_DEVICE_NONE );
   1728         status = stop_input_stream(in);
   1729         pthread_mutex_unlock(&adev->lock);
   1730     }
   1731     pthread_mutex_unlock(&in->lock);
   1732     ALOGV("%s: exit:  status(%d)", __func__, status);
   1733     return status;
   1734 }
   1735 
   1736 static int in_dump(const struct audio_stream *stream __unused, int fd __unused)
   1737 {
   1738     return 0;
   1739 }
   1740 
   1741 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
   1742 {
   1743     struct stream_in *in = (struct stream_in *)stream;
   1744     struct audio_device *adev = in->dev;
   1745     struct str_parms *parms;
   1746     char *str;
   1747     char value[32];
   1748     int ret, val = 0;
   1749     int status = 0;
   1750 
   1751     ALOGV("%s: enter: kvpairs=%s", __func__, kvpairs);
   1752     parms = str_parms_create_str(kvpairs);
   1753 
   1754     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
   1755 
   1756     pthread_mutex_lock(&in->lock);
   1757     pthread_mutex_lock(&adev->lock);
   1758     if (ret >= 0) {
   1759         val = atoi(value);
   1760         /* no audio source uses val == 0 */
   1761         if ((in->source != val) && (val != 0)) {
   1762             in->source = val;
   1763         }
   1764     }
   1765 
   1766     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
   1767 
   1768     if (ret >= 0) {
   1769         val = atoi(value);
   1770         if (((int)in->device != val) && (val != 0)) {
   1771             in->device = val;
   1772             /* If recording is in progress, change the tx device to new device */
   1773             if (!in->standby)
   1774                 status = select_devices(adev, in->usecase);
   1775         }
   1776     }
   1777 
   1778     pthread_mutex_unlock(&adev->lock);
   1779     pthread_mutex_unlock(&in->lock);
   1780 
   1781     str_parms_destroy(parms);
   1782     ALOGV("%s: exit: status(%d)", __func__, status);
   1783     return status;
   1784 }
   1785 
   1786 static char* in_get_parameters(const struct audio_stream *stream __unused,
   1787                                const char *keys __unused)
   1788 {
   1789     return strdup("");
   1790 }
   1791 
   1792 static int in_set_gain(struct audio_stream_in *stream __unused, float gain __unused)
   1793 {
   1794     return 0;
   1795 }
   1796 
   1797 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
   1798                        size_t bytes)
   1799 {
   1800     struct stream_in *in = (struct stream_in *)stream;
   1801     struct audio_device *adev = in->dev;
   1802     int i, ret = -1;
   1803 
   1804     pthread_mutex_lock(&in->lock);
   1805     if (in->standby) {
   1806         pthread_mutex_lock(&adev->lock);
   1807         ret = start_input_stream(in);
   1808         pthread_mutex_unlock(&adev->lock);
   1809         if (ret != 0) {
   1810             goto exit;
   1811         }
   1812         in->standby = 0;
   1813     }
   1814 
   1815     if (in->pcm) {
   1816         if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY) {
   1817             ret = pcm_mmap_read(in->pcm, buffer, bytes);
   1818         } else
   1819             ret = pcm_read(in->pcm, buffer, bytes);
   1820     }
   1821 
   1822     /*
   1823      * Instead of writing zeroes here, we could trust the hardware
   1824      * to always provide zeroes when muted.
   1825      * No need to acquire adev->lock to read mic_muted here as we don't change its state.
   1826      */
   1827     if (ret == 0 && adev->mic_muted && in->usecase != USECASE_AUDIO_RECORD_AFE_PROXY)
   1828         memset(buffer, 0, bytes);
   1829 
   1830 exit:
   1831     pthread_mutex_unlock(&in->lock);
   1832 
   1833     if (ret != 0) {
   1834         in_standby(&in->stream.common);
   1835         ALOGV("%s: read failed - sleeping for buffer duration", __func__);
   1836         usleep(bytes * 1000000 / audio_stream_in_frame_size(stream) /
   1837                in_get_sample_rate(&in->stream.common));
   1838     }
   1839     return bytes;
   1840 }
   1841 
   1842 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream __unused)
   1843 {
   1844     return 0;
   1845 }
   1846 
   1847 static int add_remove_audio_effect(const struct audio_stream *stream,
   1848                                    effect_handle_t effect,
   1849                                    bool enable)
   1850 {
   1851     struct stream_in *in = (struct stream_in *)stream;
   1852     struct audio_device *adev = in->dev;
   1853     int status = 0;
   1854     effect_descriptor_t desc;
   1855 
   1856     status = (*effect)->get_descriptor(effect, &desc);
   1857     if (status != 0)
   1858         return status;
   1859 
   1860     pthread_mutex_lock(&in->lock);
   1861     pthread_mutex_lock(&in->dev->lock);
   1862     if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
   1863             in->enable_aec != enable &&
   1864             (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
   1865         in->enable_aec = enable;
   1866         if (!enable)
   1867             platform_set_echo_reference(in->dev, enable, AUDIO_DEVICE_NONE);
   1868         adev->enable_voicerx = enable;
   1869         struct audio_usecase *usecase;
   1870         struct listnode *node;
   1871         list_for_each(node, &adev->usecase_list) {
   1872             usecase = node_to_item(node, struct audio_usecase, list);
   1873             if (usecase->type == PCM_PLAYBACK) {
   1874                 select_devices(adev, usecase->id);
   1875             break;
   1876             }
   1877         }
   1878         if (!in->standby)
   1879             select_devices(in->dev, in->usecase);
   1880     }
   1881     if (in->enable_ns != enable &&
   1882             (memcmp(&desc.type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
   1883         in->enable_ns = enable;
   1884         if (!in->standby)
   1885             select_devices(in->dev, in->usecase);
   1886     }
   1887     pthread_mutex_unlock(&in->dev->lock);
   1888     pthread_mutex_unlock(&in->lock);
   1889 
   1890     return 0;
   1891 }
   1892 
   1893 static int in_add_audio_effect(const struct audio_stream *stream,
   1894                                effect_handle_t effect)
   1895 {
   1896     ALOGV("%s: effect %p", __func__, effect);
   1897     return add_remove_audio_effect(stream, effect, true);
   1898 }
   1899 
   1900 static int in_remove_audio_effect(const struct audio_stream *stream,
   1901                                   effect_handle_t effect)
   1902 {
   1903     ALOGV("%s: effect %p", __func__, effect);
   1904     return add_remove_audio_effect(stream, effect, false);
   1905 }
   1906 
   1907 static int adev_open_output_stream(struct audio_hw_device *dev,
   1908                                    audio_io_handle_t handle,
   1909                                    audio_devices_t devices,
   1910                                    audio_output_flags_t flags,
   1911                                    struct audio_config *config,
   1912                                    struct audio_stream_out **stream_out,
   1913                                    const char *address __unused)
   1914 {
   1915     struct audio_device *adev = (struct audio_device *)dev;
   1916     struct stream_out *out;
   1917     int i, ret;
   1918 
   1919     ALOGV("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)",
   1920           __func__, config->sample_rate, config->channel_mask, devices, flags);
   1921     *stream_out = NULL;
   1922     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
   1923 
   1924     if (devices == AUDIO_DEVICE_NONE)
   1925         devices = AUDIO_DEVICE_OUT_SPEAKER;
   1926 
   1927     out->flags = flags;
   1928     out->devices = devices;
   1929     out->dev = adev;
   1930     out->format = config->format;
   1931     out->sample_rate = config->sample_rate;
   1932     out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
   1933     out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
   1934     out->handle = handle;
   1935 
   1936     /* Init use case and pcm_config */
   1937     if (out->flags & AUDIO_OUTPUT_FLAG_DIRECT &&
   1938             !(out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
   1939         out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
   1940         pthread_mutex_lock(&adev->lock);
   1941         ret = read_hdmi_channel_masks(out);
   1942         pthread_mutex_unlock(&adev->lock);
   1943         if (ret != 0)
   1944             goto error_open;
   1945 
   1946         if (config->sample_rate == 0)
   1947             config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
   1948         if (config->channel_mask == 0)
   1949             config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
   1950 
   1951         out->channel_mask = config->channel_mask;
   1952         out->sample_rate = config->sample_rate;
   1953         out->usecase = USECASE_AUDIO_PLAYBACK_MULTI_CH;
   1954         out->config = pcm_config_hdmi_multi;
   1955         out->config.rate = config->sample_rate;
   1956         out->config.channels = audio_channel_count_from_out_mask(out->channel_mask);
   1957         out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels * 2);
   1958     } else if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
   1959         if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
   1960             config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
   1961             ALOGE("%s: Unsupported Offload information", __func__);
   1962             ret = -EINVAL;
   1963             goto error_open;
   1964         }
   1965         if (!is_supported_format(config->offload_info.format)) {
   1966             ALOGE("%s: Unsupported audio format", __func__);
   1967             ret = -EINVAL;
   1968             goto error_open;
   1969         }
   1970 
   1971         out->compr_config.codec = (struct snd_codec *)
   1972                                     calloc(1, sizeof(struct snd_codec));
   1973 
   1974         out->usecase = USECASE_AUDIO_PLAYBACK_OFFLOAD;
   1975         if (config->offload_info.channel_mask)
   1976             out->channel_mask = config->offload_info.channel_mask;
   1977         else if (config->channel_mask)
   1978             out->channel_mask = config->channel_mask;
   1979         out->format = config->offload_info.format;
   1980         out->sample_rate = config->offload_info.sample_rate;
   1981 
   1982         out->stream.set_callback = out_set_callback;
   1983         out->stream.pause = out_pause;
   1984         out->stream.resume = out_resume;
   1985         out->stream.drain = out_drain;
   1986         out->stream.flush = out_flush;
   1987 
   1988         out->compr_config.codec->id =
   1989                 get_snd_codec_id(config->offload_info.format);
   1990         out->compr_config.fragment_size = COMPRESS_OFFLOAD_FRAGMENT_SIZE;
   1991         out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
   1992         out->compr_config.codec->sample_rate = config->offload_info.sample_rate;
   1993         out->compr_config.codec->bit_rate =
   1994                     config->offload_info.bit_rate;
   1995         out->compr_config.codec->ch_in =
   1996                 audio_channel_count_from_out_mask(config->channel_mask);
   1997         out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
   1998 
   1999         if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
   2000             out->non_blocking = 1;
   2001 
   2002         out->send_new_metadata = 1;
   2003         create_offload_callback_thread(out);
   2004         ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
   2005                 __func__, config->offload_info.version,
   2006                 config->offload_info.bit_rate);
   2007     } else  if (out->devices == AUDIO_DEVICE_OUT_TELEPHONY_TX) {
   2008         if (config->sample_rate == 0)
   2009             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
   2010         if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
   2011                 config->sample_rate != 8000) {
   2012             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
   2013             ret = -EINVAL;
   2014             goto error_open;
   2015         }
   2016         out->sample_rate = config->sample_rate;
   2017         out->config.rate = config->sample_rate;
   2018         if (config->format == AUDIO_FORMAT_DEFAULT)
   2019             config->format = AUDIO_FORMAT_PCM_16_BIT;
   2020         if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
   2021             config->format = AUDIO_FORMAT_PCM_16_BIT;
   2022             ret = -EINVAL;
   2023             goto error_open;
   2024         }
   2025         out->format = config->format;
   2026         out->usecase = USECASE_AUDIO_PLAYBACK_AFE_PROXY;
   2027         out->config = pcm_config_afe_proxy_playback;
   2028         adev->voice_tx_output = out;
   2029     } else {
   2030         if (out->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
   2031             out->usecase = USECASE_AUDIO_PLAYBACK_DEEP_BUFFER;
   2032             out->config = pcm_config_deep_buffer;
   2033         } else {
   2034             out->usecase = USECASE_AUDIO_PLAYBACK_LOW_LATENCY;
   2035             out->config = pcm_config_low_latency;
   2036         }
   2037         if (config->format != audio_format_from_pcm_format(out->config.format)) {
   2038             if (k_enable_extended_precision
   2039                     && pcm_params_format_test(adev->use_case_table[out->usecase],
   2040                             pcm_format_from_audio_format(config->format))) {
   2041                 out->config.format = pcm_format_from_audio_format(config->format);
   2042                 /* out->format already set to config->format */
   2043             } else {
   2044                 /* deny the externally proposed config format
   2045                  * and use the one specified in audio_hw layer configuration.
   2046                  * Note: out->format is returned by out->stream.common.get_format()
   2047                  * and is used to set config->format in the code several lines below.
   2048                  */
   2049                 out->format = audio_format_from_pcm_format(out->config.format);
   2050             }
   2051         }
   2052         out->sample_rate = out->config.rate;
   2053     }
   2054     ALOGV("%s: Usecase(%s) config->format %#x  out->config.format %#x\n",
   2055             __func__, use_case_table[out->usecase], config->format, out->config.format);
   2056 
   2057     if (flags & AUDIO_OUTPUT_FLAG_PRIMARY) {
   2058         if (adev->primary_output == NULL)
   2059             adev->primary_output = out;
   2060         else {
   2061             ALOGE("%s: Primary output is already opened", __func__);
   2062             ret = -EEXIST;
   2063             goto error_open;
   2064         }
   2065     }
   2066 
   2067     /* Check if this usecase is already existing */
   2068     pthread_mutex_lock(&adev->lock);
   2069     if (get_usecase_from_list(adev, out->usecase) != NULL) {
   2070         ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
   2071         pthread_mutex_unlock(&adev->lock);
   2072         ret = -EEXIST;
   2073         goto error_open;
   2074     }
   2075     pthread_mutex_unlock(&adev->lock);
   2076 
   2077     out->stream.common.get_sample_rate = out_get_sample_rate;
   2078     out->stream.common.set_sample_rate = out_set_sample_rate;
   2079     out->stream.common.get_buffer_size = out_get_buffer_size;
   2080     out->stream.common.get_channels = out_get_channels;
   2081     out->stream.common.get_format = out_get_format;
   2082     out->stream.common.set_format = out_set_format;
   2083     out->stream.common.standby = out_standby;
   2084     out->stream.common.dump = out_dump;
   2085     out->stream.common.set_parameters = out_set_parameters;
   2086     out->stream.common.get_parameters = out_get_parameters;
   2087     out->stream.common.add_audio_effect = out_add_audio_effect;
   2088     out->stream.common.remove_audio_effect = out_remove_audio_effect;
   2089     out->stream.get_latency = out_get_latency;
   2090     out->stream.set_volume = out_set_volume;
   2091     out->stream.write = out_write;
   2092     out->stream.get_render_position = out_get_render_position;
   2093     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
   2094     out->stream.get_presentation_position = out_get_presentation_position;
   2095 
   2096     out->standby = 1;
   2097     /* out->muted = false; by calloc() */
   2098     /* out->written = 0; by calloc() */
   2099 
   2100     pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
   2101     pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);
   2102 
   2103     config->format = out->stream.common.get_format(&out->stream.common);
   2104     config->channel_mask = out->stream.common.get_channels(&out->stream.common);
   2105     config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
   2106 
   2107     *stream_out = &out->stream;
   2108     ALOGV("%s: exit", __func__);
   2109     return 0;
   2110 
   2111 error_open:
   2112     free(out);
   2113     *stream_out = NULL;
   2114     ALOGD("%s: exit: ret %d", __func__, ret);
   2115     return ret;
   2116 }
   2117 
   2118 static void adev_close_output_stream(struct audio_hw_device *dev __unused,
   2119                                      struct audio_stream_out *stream)
   2120 {
   2121     struct stream_out *out = (struct stream_out *)stream;
   2122     struct audio_device *adev = out->dev;
   2123 
   2124     ALOGV("%s: enter", __func__);
   2125     out_standby(&stream->common);
   2126     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2127         destroy_offload_callback_thread(out);
   2128 
   2129         if (out->compr_config.codec != NULL)
   2130             free(out->compr_config.codec);
   2131     }
   2132 
   2133     if (adev->voice_tx_output == out)
   2134         adev->voice_tx_output = NULL;
   2135 
   2136     pthread_cond_destroy(&out->cond);
   2137     pthread_mutex_destroy(&out->lock);
   2138     free(stream);
   2139     ALOGV("%s: exit", __func__);
   2140 }
   2141 
   2142 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
   2143 {
   2144     struct audio_device *adev = (struct audio_device *)dev;
   2145     struct str_parms *parms;
   2146     char *str;
   2147     char value[32];
   2148     int val;
   2149     int ret;
   2150     int status = 0;
   2151 
   2152     ALOGD("%s: enter: %s", __func__, kvpairs);
   2153 
   2154     pthread_mutex_lock(&adev->lock);
   2155 
   2156     parms = str_parms_create_str(kvpairs);
   2157     status = voice_set_parameters(adev, parms);
   2158     if (status != 0) {
   2159         goto done;
   2160     }
   2161 
   2162     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
   2163     if (ret >= 0) {
   2164         /* When set to false, HAL should disable EC and NS
   2165          * But it is currently not supported.
   2166          */
   2167         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   2168             adev->bluetooth_nrec = true;
   2169         else
   2170             adev->bluetooth_nrec = false;
   2171     }
   2172 
   2173     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
   2174     if (ret >= 0) {
   2175         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   2176             adev->screen_off = false;
   2177         else
   2178             adev->screen_off = true;
   2179     }
   2180 
   2181     ret = str_parms_get_int(parms, "rotation", &val);
   2182     if (ret >= 0) {
   2183         bool reverse_speakers = false;
   2184         switch(val) {
   2185         // FIXME: note that the code below assumes that the speakers are in the correct placement
   2186         //   relative to the user when the device is rotated 90deg from its default rotation. This
   2187         //   assumption is device-specific, not platform-specific like this code.
   2188         case 270:
   2189             reverse_speakers = true;
   2190             break;
   2191         case 0:
   2192         case 90:
   2193         case 180:
   2194             break;
   2195         default:
   2196             ALOGE("%s: unexpected rotation of %d", __func__, val);
   2197             status = -EINVAL;
   2198         }
   2199         if (status == 0) {
   2200             if (adev->speaker_lr_swap != reverse_speakers) {
   2201                 adev->speaker_lr_swap = reverse_speakers;
   2202                 // only update the selected device if there is active pcm playback
   2203                 struct audio_usecase *usecase;
   2204                 struct listnode *node;
   2205                 list_for_each(node, &adev->usecase_list) {
   2206                     usecase = node_to_item(node, struct audio_usecase, list);
   2207                     if (usecase->type == PCM_PLAYBACK) {
   2208                         select_devices(adev, usecase->id);
   2209                         break;
   2210                     }
   2211                 }
   2212             }
   2213         }
   2214     }
   2215 
   2216     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value));
   2217     if (ret >= 0) {
   2218         adev->bt_wb_speech_enabled = !strcmp(value, AUDIO_PARAMETER_VALUE_ON);
   2219     }
   2220 
   2221     audio_extn_hfp_set_parameters(adev, parms);
   2222 done:
   2223     str_parms_destroy(parms);
   2224     pthread_mutex_unlock(&adev->lock);
   2225     ALOGV("%s: exit with code(%d)", __func__, status);
   2226     return status;
   2227 }
   2228 
   2229 static char* adev_get_parameters(const struct audio_hw_device *dev,
   2230                                  const char *keys)
   2231 {
   2232     struct audio_device *adev = (struct audio_device *)dev;
   2233     struct str_parms *reply = str_parms_create();
   2234     struct str_parms *query = str_parms_create_str(keys);
   2235     char *str;
   2236 
   2237     pthread_mutex_lock(&adev->lock);
   2238 
   2239     voice_get_parameters(adev, query, reply);
   2240     str = str_parms_to_str(reply);
   2241     str_parms_destroy(query);
   2242     str_parms_destroy(reply);
   2243 
   2244     pthread_mutex_unlock(&adev->lock);
   2245     ALOGV("%s: exit: returns - %s", __func__, str);
   2246     return str;
   2247 }
   2248 
   2249 static int adev_init_check(const struct audio_hw_device *dev __unused)
   2250 {
   2251     return 0;
   2252 }
   2253 
   2254 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
   2255 {
   2256     int ret;
   2257     struct audio_device *adev = (struct audio_device *)dev;
   2258 
   2259     audio_extn_extspk_set_voice_vol(adev->extspk, volume);
   2260 
   2261     pthread_mutex_lock(&adev->lock);
   2262     ret = voice_set_volume(adev, volume);
   2263     pthread_mutex_unlock(&adev->lock);
   2264 
   2265     return ret;
   2266 }
   2267 
   2268 static int adev_set_master_volume(struct audio_hw_device *dev __unused, float volume __unused)
   2269 {
   2270     return -ENOSYS;
   2271 }
   2272 
   2273 static int adev_get_master_volume(struct audio_hw_device *dev __unused,
   2274                                   float *volume __unused)
   2275 {
   2276     return -ENOSYS;
   2277 }
   2278 
   2279 static int adev_set_master_mute(struct audio_hw_device *dev __unused, bool muted __unused)
   2280 {
   2281     return -ENOSYS;
   2282 }
   2283 
   2284 static int adev_get_master_mute(struct audio_hw_device *dev __unused, bool *muted __unused)
   2285 {
   2286     return -ENOSYS;
   2287 }
   2288 
   2289 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
   2290 {
   2291     struct audio_device *adev = (struct audio_device *)dev;
   2292 
   2293     pthread_mutex_lock(&adev->lock);
   2294     if (adev->mode != mode) {
   2295         ALOGD("%s: mode %d\n", __func__, mode);
   2296         adev->mode = mode;
   2297         if ((mode == AUDIO_MODE_NORMAL || mode == AUDIO_MODE_IN_COMMUNICATION) &&
   2298                 voice_is_in_call(adev)) {
   2299             voice_stop_call(adev);
   2300             adev->current_call_output = NULL;
   2301         }
   2302     }
   2303     pthread_mutex_unlock(&adev->lock);
   2304 
   2305     audio_extn_extspk_set_mode(adev->extspk, mode);
   2306 
   2307     return 0;
   2308 }
   2309 
   2310 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
   2311 {
   2312     int ret;
   2313     struct audio_device *adev = (struct audio_device *)dev;
   2314 
   2315     ALOGD("%s: state %d\n", __func__, state);
   2316     pthread_mutex_lock(&adev->lock);
   2317     ret = voice_set_mic_mute(adev, state);
   2318     adev->mic_muted = state;
   2319     pthread_mutex_unlock(&adev->lock);
   2320 
   2321     return ret;
   2322 }
   2323 
   2324 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
   2325 {
   2326     *state = voice_get_mic_mute((struct audio_device *)dev);
   2327     return 0;
   2328 }
   2329 
   2330 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev __unused,
   2331                                          const struct audio_config *config)
   2332 {
   2333     int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
   2334 
   2335     return get_input_buffer_size(config->sample_rate, config->format, channel_count,
   2336             false /* is_low_latency: since we don't know, be conservative */);
   2337 }
   2338 
   2339 static int adev_open_input_stream(struct audio_hw_device *dev,
   2340                                   audio_io_handle_t handle __unused,
   2341                                   audio_devices_t devices,
   2342                                   struct audio_config *config,
   2343                                   struct audio_stream_in **stream_in,
   2344                                   audio_input_flags_t flags,
   2345                                   const char *address __unused,
   2346                                   audio_source_t source )
   2347 {
   2348     struct audio_device *adev = (struct audio_device *)dev;
   2349     struct stream_in *in;
   2350     int ret = 0, buffer_size, frame_size;
   2351     int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
   2352     bool is_low_latency = false;
   2353 
   2354     ALOGV("%s: enter", __func__);
   2355     *stream_in = NULL;
   2356     if (check_input_parameters(config->sample_rate, config->format, channel_count) != 0)
   2357         return -EINVAL;
   2358 
   2359     in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
   2360 
   2361     pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
   2362 
   2363     in->stream.common.get_sample_rate = in_get_sample_rate;
   2364     in->stream.common.set_sample_rate = in_set_sample_rate;
   2365     in->stream.common.get_buffer_size = in_get_buffer_size;
   2366     in->stream.common.get_channels = in_get_channels;
   2367     in->stream.common.get_format = in_get_format;
   2368     in->stream.common.set_format = in_set_format;
   2369     in->stream.common.standby = in_standby;
   2370     in->stream.common.dump = in_dump;
   2371     in->stream.common.set_parameters = in_set_parameters;
   2372     in->stream.common.get_parameters = in_get_parameters;
   2373     in->stream.common.add_audio_effect = in_add_audio_effect;
   2374     in->stream.common.remove_audio_effect = in_remove_audio_effect;
   2375     in->stream.set_gain = in_set_gain;
   2376     in->stream.read = in_read;
   2377     in->stream.get_input_frames_lost = in_get_input_frames_lost;
   2378 
   2379     in->device = devices;
   2380     in->source = source;
   2381     in->dev = adev;
   2382     in->standby = 1;
   2383     in->channel_mask = config->channel_mask;
   2384 
   2385     /* Update config params with the requested sample rate and channels */
   2386     if (in->device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
   2387         if (config->sample_rate == 0)
   2388             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
   2389         if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
   2390                 config->sample_rate != 8000) {
   2391             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
   2392             ret = -EINVAL;
   2393             goto err_open;
   2394         }
   2395         if (config->format == AUDIO_FORMAT_DEFAULT)
   2396             config->format = AUDIO_FORMAT_PCM_16_BIT;
   2397         if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
   2398             config->format = AUDIO_FORMAT_PCM_16_BIT;
   2399             ret = -EINVAL;
   2400             goto err_open;
   2401         }
   2402 
   2403         in->usecase = USECASE_AUDIO_RECORD_AFE_PROXY;
   2404         in->config = pcm_config_afe_proxy_record;
   2405     } else {
   2406         in->usecase = USECASE_AUDIO_RECORD;
   2407         if (config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE &&
   2408                 (flags & AUDIO_INPUT_FLAG_FAST) != 0) {
   2409             is_low_latency = true;
   2410 #if LOW_LATENCY_CAPTURE_USE_CASE
   2411             in->usecase = USECASE_AUDIO_RECORD_LOW_LATENCY;
   2412 #endif
   2413         }
   2414         in->config = pcm_config_audio_capture;
   2415 
   2416         frame_size = audio_stream_in_frame_size(&in->stream);
   2417         buffer_size = get_input_buffer_size(config->sample_rate,
   2418                                             config->format,
   2419                                             channel_count,
   2420                                             is_low_latency);
   2421         in->config.period_size = buffer_size / frame_size;
   2422     }
   2423     in->config.channels = channel_count;
   2424     in->config.rate = config->sample_rate;
   2425 
   2426 
   2427     *stream_in = &in->stream;
   2428     ALOGV("%s: exit", __func__);
   2429     return 0;
   2430 
   2431 err_open:
   2432     free(in);
   2433     *stream_in = NULL;
   2434     return ret;
   2435 }
   2436 
   2437 static void adev_close_input_stream(struct audio_hw_device *dev __unused,
   2438                                     struct audio_stream_in *stream)
   2439 {
   2440     ALOGV("%s", __func__);
   2441 
   2442     in_standby(&stream->common);
   2443     free(stream);
   2444 
   2445     return;
   2446 }
   2447 
   2448 static int adev_dump(const audio_hw_device_t *device __unused, int fd __unused)
   2449 {
   2450     return 0;
   2451 }
   2452 
   2453 /* verifies input and output devices and their capabilities.
   2454  *
   2455  * This verification is required when enabling extended bit-depth or
   2456  * sampling rates, as not all qcom products support it.
   2457  *
   2458  * Suitable for calling only on initialization such as adev_open().
   2459  * It fills the audio_device use_case_table[] array.
   2460  *
   2461  * Has a side-effect that it needs to configure audio routing / devices
   2462  * in order to power up the devices and read the device parameters.
   2463  * It does not acquire any hw device lock. Should restore the devices
   2464  * back to "normal state" upon completion.
   2465  */
   2466 static int adev_verify_devices(struct audio_device *adev)
   2467 {
   2468     /* enumeration is a bit difficult because one really wants to pull
   2469      * the use_case, device id, etc from the hidden pcm_device_table[].
   2470      * In this case there are the following use cases and device ids.
   2471      *
   2472      * [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = {0, 0},
   2473      * [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = {15, 15},
   2474      * [USECASE_AUDIO_PLAYBACK_MULTI_CH] = {1, 1},
   2475      * [USECASE_AUDIO_PLAYBACK_OFFLOAD] = {9, 9},
   2476      * [USECASE_AUDIO_RECORD] = {0, 0},
   2477      * [USECASE_AUDIO_RECORD_LOW_LATENCY] = {15, 15},
   2478      * [USECASE_VOICE_CALL] = {2, 2},
   2479      *
   2480      * USECASE_AUDIO_PLAYBACK_OFFLOAD, USECASE_AUDIO_PLAYBACK_MULTI_CH omitted.
   2481      * USECASE_VOICE_CALL omitted, but possible for either input or output.
   2482      */
   2483 
   2484     /* should be the usecases enabled in adev_open_input_stream() */
   2485     static const int test_in_usecases[] = {
   2486              USECASE_AUDIO_RECORD,
   2487              USECASE_AUDIO_RECORD_LOW_LATENCY, /* does not appear to be used */
   2488     };
   2489     /* should be the usecases enabled in adev_open_output_stream()*/
   2490     static const int test_out_usecases[] = {
   2491             USECASE_AUDIO_PLAYBACK_DEEP_BUFFER,
   2492             USECASE_AUDIO_PLAYBACK_LOW_LATENCY,
   2493     };
   2494     static const usecase_type_t usecase_type_by_dir[] = {
   2495             PCM_PLAYBACK,
   2496             PCM_CAPTURE,
   2497     };
   2498     static const unsigned flags_by_dir[] = {
   2499             PCM_OUT,
   2500             PCM_IN,
   2501     };
   2502 
   2503     size_t i;
   2504     unsigned dir;
   2505     const unsigned card_id = adev->snd_card;
   2506     char info[512]; /* for possible debug info */
   2507 
   2508     for (dir = 0; dir < 2; ++dir) {
   2509         const usecase_type_t usecase_type = usecase_type_by_dir[dir];
   2510         const unsigned flags_dir = flags_by_dir[dir];
   2511         const size_t testsize =
   2512                 dir ? ARRAY_SIZE(test_in_usecases) : ARRAY_SIZE(test_out_usecases);
   2513         const int *testcases =
   2514                 dir ? test_in_usecases : test_out_usecases;
   2515         const audio_devices_t audio_device =
   2516                 dir ? AUDIO_DEVICE_IN_BUILTIN_MIC : AUDIO_DEVICE_OUT_SPEAKER;
   2517 
   2518         for (i = 0; i < testsize; ++i) {
   2519             const audio_usecase_t audio_usecase = testcases[i];
   2520             int device_id;
   2521             snd_device_t snd_device;
   2522             struct pcm_params **pparams;
   2523             struct stream_out out;
   2524             struct stream_in in;
   2525             struct audio_usecase uc_info;
   2526             int retval;
   2527 
   2528             pparams = &adev->use_case_table[audio_usecase];
   2529             pcm_params_free(*pparams); /* can accept null input */
   2530             *pparams = NULL;
   2531 
   2532             /* find the device ID for the use case (signed, for error) */
   2533             device_id = platform_get_pcm_device_id(audio_usecase, usecase_type);
   2534             if (device_id < 0)
   2535                 continue;
   2536 
   2537             /* prepare structures for device probing */
   2538             memset(&uc_info, 0, sizeof(uc_info));
   2539             uc_info.id = audio_usecase;
   2540             uc_info.type = usecase_type;
   2541             if (dir) {
   2542                 adev->active_input = &in;
   2543                 memset(&in, 0, sizeof(in));
   2544                 in.device = audio_device;
   2545                 in.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
   2546                 uc_info.stream.in = &in;
   2547             }  else {
   2548                 adev->active_input = NULL;
   2549             }
   2550             memset(&out, 0, sizeof(out));
   2551             out.devices = audio_device; /* only field needed in select_devices */
   2552             uc_info.stream.out = &out;
   2553             uc_info.devices = audio_device;
   2554             uc_info.in_snd_device = SND_DEVICE_NONE;
   2555             uc_info.out_snd_device = SND_DEVICE_NONE;
   2556             list_add_tail(&adev->usecase_list, &uc_info.list);
   2557 
   2558             /* select device - similar to start_(in/out)put_stream() */
   2559             retval = select_devices(adev, audio_usecase);
   2560             if (retval >= 0) {
   2561                 *pparams = pcm_params_get(card_id, device_id, flags_dir);
   2562 #if LOG_NDEBUG == 0
   2563                 if (*pparams) {
   2564                     ALOGV("%s: (%s) card %d  device %d", __func__,
   2565                             dir ? "input" : "output", card_id, device_id);
   2566                     pcm_params_to_string(*pparams, info, ARRAY_SIZE(info));
   2567                     ALOGV(info); /* print parameters */
   2568                 } else {
   2569                     ALOGV("%s: cannot locate card %d  device %d", __func__, card_id, device_id);
   2570                 }
   2571 #endif
   2572             }
   2573 
   2574             /* deselect device - similar to stop_(in/out)put_stream() */
   2575             /* 1. Get and set stream specific mixer controls */
   2576             retval = disable_audio_route(adev, &uc_info);
   2577             /* 2. Disable the rx device */
   2578             retval = disable_snd_device(adev,
   2579                     dir ? uc_info.in_snd_device : uc_info.out_snd_device);
   2580             list_remove(&uc_info.list);
   2581         }
   2582     }
   2583     adev->active_input = NULL; /* restore adev state */
   2584     return 0;
   2585 }
   2586 
   2587 static int adev_close(hw_device_t *device)
   2588 {
   2589     size_t i;
   2590     struct audio_device *adev = (struct audio_device *)device;
   2591     audio_route_free(adev->audio_route);
   2592     free(adev->snd_dev_ref_cnt);
   2593     platform_deinit(adev->platform);
   2594     audio_extn_extspk_deinit(adev->extspk);
   2595     for (i = 0; i < ARRAY_SIZE(adev->use_case_table); ++i) {
   2596         pcm_params_free(adev->use_case_table[i]);
   2597     }
   2598     free(device);
   2599     return 0;
   2600 }
   2601 
   2602 /* This returns 1 if the input parameter looks at all plausible as a low latency period size,
   2603  * or 0 otherwise.  A return value of 1 doesn't mean the value is guaranteed to work,
   2604  * just that it _might_ work.
   2605  */
   2606 static int period_size_is_plausible_for_low_latency(int period_size)
   2607 {
   2608     switch (period_size) {
   2609     case 160:
   2610     case 240:
   2611     case 320:
   2612     case 480:
   2613         return 1;
   2614     default:
   2615         return 0;
   2616     }
   2617 }
   2618 
   2619 static int adev_open(const hw_module_t *module, const char *name,
   2620                      hw_device_t **device)
   2621 {
   2622     struct audio_device *adev;
   2623     int i, ret;
   2624 
   2625     ALOGD("%s: enter", __func__);
   2626     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
   2627 
   2628     adev = calloc(1, sizeof(struct audio_device));
   2629 
   2630     pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
   2631 
   2632     adev->device.common.tag = HARDWARE_DEVICE_TAG;
   2633     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
   2634     adev->device.common.module = (struct hw_module_t *)module;
   2635     adev->device.common.close = adev_close;
   2636 
   2637     adev->device.init_check = adev_init_check;
   2638     adev->device.set_voice_volume = adev_set_voice_volume;
   2639     adev->device.set_master_volume = adev_set_master_volume;
   2640     adev->device.get_master_volume = adev_get_master_volume;
   2641     adev->device.set_master_mute = adev_set_master_mute;
   2642     adev->device.get_master_mute = adev_get_master_mute;
   2643     adev->device.set_mode = adev_set_mode;
   2644     adev->device.set_mic_mute = adev_set_mic_mute;
   2645     adev->device.get_mic_mute = adev_get_mic_mute;
   2646     adev->device.set_parameters = adev_set_parameters;
   2647     adev->device.get_parameters = adev_get_parameters;
   2648     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
   2649     adev->device.open_output_stream = adev_open_output_stream;
   2650     adev->device.close_output_stream = adev_close_output_stream;
   2651     adev->device.open_input_stream = adev_open_input_stream;
   2652     adev->device.close_input_stream = adev_close_input_stream;
   2653     adev->device.dump = adev_dump;
   2654 
   2655     /* Set the default route before the PCM stream is opened */
   2656     pthread_mutex_lock(&adev->lock);
   2657     adev->mode = AUDIO_MODE_NORMAL;
   2658     adev->active_input = NULL;
   2659     adev->primary_output = NULL;
   2660     adev->bluetooth_nrec = true;
   2661     adev->acdb_settings = TTY_MODE_OFF;
   2662     /* adev->cur_hdmi_channels = 0;  by calloc() */
   2663     adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
   2664     voice_init(adev);
   2665     list_init(&adev->usecase_list);
   2666     pthread_mutex_unlock(&adev->lock);
   2667 
   2668     /* Loads platform specific libraries dynamically */
   2669     adev->platform = platform_init(adev);
   2670     if (!adev->platform) {
   2671         free(adev->snd_dev_ref_cnt);
   2672         free(adev);
   2673         ALOGE("%s: Failed to init platform data, aborting.", __func__);
   2674         *device = NULL;
   2675         return -EINVAL;
   2676     }
   2677 
   2678     adev->extspk = audio_extn_extspk_init(adev);
   2679 
   2680     if (access(VISUALIZER_LIBRARY_PATH, R_OK) == 0) {
   2681         adev->visualizer_lib = dlopen(VISUALIZER_LIBRARY_PATH, RTLD_NOW);
   2682         if (adev->visualizer_lib == NULL) {
   2683             ALOGE("%s: DLOPEN failed for %s", __func__, VISUALIZER_LIBRARY_PATH);
   2684         } else {
   2685             ALOGV("%s: DLOPEN successful for %s", __func__, VISUALIZER_LIBRARY_PATH);
   2686             adev->visualizer_start_output =
   2687                         (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
   2688                                                         "visualizer_hal_start_output");
   2689             adev->visualizer_stop_output =
   2690                         (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
   2691                                                         "visualizer_hal_stop_output");
   2692         }
   2693     }
   2694 
   2695     if (access(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, R_OK) == 0) {
   2696         adev->offload_effects_lib = dlopen(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, RTLD_NOW);
   2697         if (adev->offload_effects_lib == NULL) {
   2698             ALOGE("%s: DLOPEN failed for %s", __func__,
   2699                   OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
   2700         } else {
   2701             ALOGV("%s: DLOPEN successful for %s", __func__,
   2702                   OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
   2703             adev->offload_effects_start_output =
   2704                         (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
   2705                                          "offload_effects_bundle_hal_start_output");
   2706             adev->offload_effects_stop_output =
   2707                         (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
   2708                                          "offload_effects_bundle_hal_stop_output");
   2709         }
   2710     }
   2711 
   2712     adev->bt_wb_speech_enabled = false;
   2713     adev->enable_voicerx = false;
   2714 
   2715     *device = &adev->device.common;
   2716     if (k_enable_extended_precision)
   2717         adev_verify_devices(adev);
   2718 
   2719     char value[PROPERTY_VALUE_MAX];
   2720     int trial;
   2721     if (property_get("audio_hal.period_size", value, NULL) > 0) {
   2722         trial = atoi(value);
   2723         if (period_size_is_plausible_for_low_latency(trial)) {
   2724             pcm_config_low_latency.period_size = trial;
   2725             pcm_config_low_latency.start_threshold = trial / 4;
   2726             pcm_config_low_latency.avail_min = trial / 4;
   2727             configured_low_latency_capture_period_size = trial;
   2728         }
   2729     }
   2730     if (property_get("audio_hal.in_period_size", value, NULL) > 0) {
   2731         trial = atoi(value);
   2732         if (period_size_is_plausible_for_low_latency(trial)) {
   2733             configured_low_latency_capture_period_size = trial;
   2734         }
   2735     }
   2736 
   2737     ALOGV("%s: exit", __func__);
   2738     return 0;
   2739 }
   2740 
   2741 static struct hw_module_methods_t hal_module_methods = {
   2742     .open = adev_open,
   2743 };
   2744 
   2745 struct audio_module HAL_MODULE_INFO_SYM = {
   2746     .common = {
   2747         .tag = HARDWARE_MODULE_TAG,
   2748         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
   2749         .hal_api_version = HARDWARE_HAL_API_VERSION,
   2750         .id = AUDIO_HARDWARE_MODULE_ID,
   2751         .name = "QCOM Audio HAL",
   2752         .author = "Code Aurora Forum",
   2753         .methods = &hal_module_methods,
   2754     },
   2755 };
   2756