Home | History | Annotate | Download | only in hal
      1 /*
      2  * Copyright (C) 2013-2016 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 ATRACE_TAG ATRACE_TAG_AUDIO
     19 /*#define LOG_NDEBUG 0*/
     20 /*#define VERY_VERY_VERBOSE_LOGGING*/
     21 #ifdef VERY_VERY_VERBOSE_LOGGING
     22 #define ALOGVV ALOGV
     23 #else
     24 #define ALOGVV(a...) do { } while(0)
     25 #endif
     26 
     27 #include <errno.h>
     28 #include <pthread.h>
     29 #include <stdint.h>
     30 #include <sys/time.h>
     31 #include <stdlib.h>
     32 #include <math.h>
     33 #include <dlfcn.h>
     34 #include <sys/resource.h>
     35 #include <sys/prctl.h>
     36 #include <limits.h>
     37 
     38 #include <cutils/log.h>
     39 #include <cutils/trace.h>
     40 #include <cutils/str_parms.h>
     41 #include <cutils/properties.h>
     42 #include <cutils/atomic.h>
     43 #include <cutils/sched_policy.h>
     44 
     45 #include <hardware/audio_effect.h>
     46 #include <hardware/audio_alsaops.h>
     47 #include <system/thread_defs.h>
     48 #include <tinyalsa/asoundlib.h>
     49 #include <audio_effects/effect_aec.h>
     50 #include <audio_effects/effect_ns.h>
     51 #include <audio_utils/clock.h>
     52 #include "audio_hw.h"
     53 #include "audio_extn.h"
     54 #include "platform_api.h"
     55 #include <platform.h>
     56 #include "voice_extn.h"
     57 
     58 #include "sound/compress_params.h"
     59 #include "audio_extn/tfa_98xx.h"
     60 
     61 /* COMPRESS_OFFLOAD_FRAGMENT_SIZE must be more than 8KB and a multiple of 32KB if more than 32KB.
     62  * COMPRESS_OFFLOAD_FRAGMENT_SIZE * COMPRESS_OFFLOAD_NUM_FRAGMENTS must be less than 8MB. */
     63 #define COMPRESS_OFFLOAD_FRAGMENT_SIZE (256 * 1024)
     64 // 2 buffers causes problems with high bitrate files
     65 #define COMPRESS_OFFLOAD_NUM_FRAGMENTS 3
     66 /* ToDo: Check and update a proper value in msec */
     67 #define COMPRESS_OFFLOAD_PLAYBACK_LATENCY 96
     68 /* treat as unsigned Q1.13 */
     69 #define APP_TYPE_GAIN_DEFAULT         0x2000
     70 #define COMPRESS_PLAYBACK_VOLUME_MAX 0x2000
     71 
     72 /* treat as unsigned Q1.13 */
     73 #define VOIP_PLAYBACK_VOLUME_MAX 0x2000
     74 
     75 #define PROXY_OPEN_RETRY_COUNT           100
     76 #define PROXY_OPEN_WAIT_TIME             20
     77 
     78 #define MIN_CHANNEL_COUNT                1
     79 #define DEFAULT_CHANNEL_COUNT            2
     80 
     81 #ifndef MAX_TARGET_SPECIFIC_CHANNEL_CNT
     82 #define MAX_CHANNEL_COUNT 1
     83 #else
     84 #define MAX_CHANNEL_COUNT atoi(XSTR(MAX_TARGET_SPECIFIC_CHANNEL_CNT))
     85 #define XSTR(x) STR(x)
     86 #define STR(x) #x
     87 #endif
     88 #define MAX_HIFI_CHANNEL_COUNT 8
     89 
     90 #define ULL_PERIOD_SIZE (DEFAULT_OUTPUT_SAMPLING_RATE/1000)
     91 
     92 static unsigned int configured_low_latency_capture_period_size =
     93         LOW_LATENCY_CAPTURE_PERIOD_SIZE;
     94 
     95 
     96 #define MMAP_PERIOD_SIZE (DEFAULT_OUTPUT_SAMPLING_RATE/1000)
     97 #define MMAP_PERIOD_COUNT_MIN 32
     98 #define MMAP_PERIOD_COUNT_MAX 512
     99 #define MMAP_PERIOD_COUNT_DEFAULT (MMAP_PERIOD_COUNT_MAX)
    100 
    101 static const int64_t NANOS_PER_SECOND = 1000000000;
    102 
    103 /* This constant enables extended precision handling.
    104  * TODO The flag is off until more testing is done.
    105  */
    106 static const bool k_enable_extended_precision = false;
    107 
    108 struct pcm_config pcm_config_deep_buffer = {
    109     .channels = DEFAULT_CHANNEL_COUNT,
    110     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    111     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
    112     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
    113     .format = PCM_FORMAT_S16_LE,
    114     .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
    115     .stop_threshold = INT_MAX,
    116     .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
    117 };
    118 
    119 struct pcm_config pcm_config_low_latency = {
    120     .channels = DEFAULT_CHANNEL_COUNT,
    121     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    122     .period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
    123     .period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
    124     .format = PCM_FORMAT_S16_LE,
    125     .start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
    126     .stop_threshold = INT_MAX,
    127     .avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
    128 };
    129 
    130 static int af_period_multiplier = 4;
    131 struct pcm_config pcm_config_rt = {
    132     .channels = DEFAULT_CHANNEL_COUNT,
    133     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    134     .period_size = ULL_PERIOD_SIZE, //1 ms
    135     .period_count = 512, //=> buffer size is 512ms
    136     .format = PCM_FORMAT_S16_LE,
    137     .start_threshold = ULL_PERIOD_SIZE*8, //8ms
    138     .stop_threshold = INT_MAX,
    139     .silence_threshold = 0,
    140     .silence_size = 0,
    141     .avail_min = ULL_PERIOD_SIZE, //1 ms
    142 };
    143 
    144 struct pcm_config pcm_config_hdmi_multi = {
    145     .channels = HDMI_MULTI_DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
    146     .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
    147     .period_size = HDMI_MULTI_PERIOD_SIZE,
    148     .period_count = HDMI_MULTI_PERIOD_COUNT,
    149     .format = PCM_FORMAT_S16_LE,
    150     .start_threshold = 0,
    151     .stop_threshold = INT_MAX,
    152     .avail_min = 0,
    153 };
    154 
    155 struct pcm_config pcm_config_mmap_playback = {
    156     .channels = DEFAULT_CHANNEL_COUNT,
    157     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    158     .period_size = MMAP_PERIOD_SIZE,
    159     .period_count = MMAP_PERIOD_COUNT_DEFAULT,
    160     .format = PCM_FORMAT_S16_LE,
    161     .start_threshold = MMAP_PERIOD_SIZE*8,
    162     .stop_threshold = INT32_MAX,
    163     .silence_threshold = 0,
    164     .silence_size = 0,
    165     .avail_min = MMAP_PERIOD_SIZE, //1 ms
    166 };
    167 
    168 struct pcm_config pcm_config_hifi = {
    169     .channels = DEFAULT_CHANNEL_COUNT, /* changed when the stream is opened */
    170     .rate = DEFAULT_OUTPUT_SAMPLING_RATE, /* changed when the stream is opened */
    171     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE, /* change #define */
    172     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
    173     .format = PCM_FORMAT_S24_3LE,
    174     .start_threshold = 0,
    175     .stop_threshold = INT_MAX,
    176     .avail_min = 0,
    177 };
    178 
    179 struct pcm_config pcm_config_audio_capture = {
    180     .channels = DEFAULT_CHANNEL_COUNT,
    181     .period_count = AUDIO_CAPTURE_PERIOD_COUNT,
    182     .format = PCM_FORMAT_S16_LE,
    183     .stop_threshold = INT_MAX,
    184     .avail_min = 0,
    185 };
    186 
    187 struct pcm_config pcm_config_audio_capture_rt = {
    188     .channels = DEFAULT_CHANNEL_COUNT,
    189     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    190     .period_size = ULL_PERIOD_SIZE,
    191     .period_count = 512,
    192     .format = PCM_FORMAT_S16_LE,
    193     .start_threshold = 0,
    194     .stop_threshold = INT_MAX,
    195     .silence_threshold = 0,
    196     .silence_size = 0,
    197     .avail_min = ULL_PERIOD_SIZE, //1 ms
    198 };
    199 
    200 struct pcm_config pcm_config_mmap_capture = {
    201     .channels = DEFAULT_CHANNEL_COUNT,
    202     .rate = DEFAULT_OUTPUT_SAMPLING_RATE,
    203     .period_size = MMAP_PERIOD_SIZE,
    204     .period_count = MMAP_PERIOD_COUNT_DEFAULT,
    205     .format = PCM_FORMAT_S16_LE,
    206     .start_threshold = 0,
    207     .stop_threshold = INT_MAX,
    208     .silence_threshold = 0,
    209     .silence_size = 0,
    210     .avail_min = MMAP_PERIOD_SIZE, //1 ms
    211 };
    212 
    213 struct pcm_config pcm_config_voip = {
    214     .channels = 1,
    215     .period_count = 2,
    216     .format = PCM_FORMAT_S16_LE,
    217     .stop_threshold = INT_MAX,
    218     .avail_min = 0,
    219 };
    220 
    221 #define AFE_PROXY_CHANNEL_COUNT 2
    222 #define AFE_PROXY_SAMPLING_RATE 48000
    223 
    224 #define AFE_PROXY_PLAYBACK_PERIOD_SIZE  768
    225 #define AFE_PROXY_PLAYBACK_PERIOD_COUNT 4
    226 
    227 struct pcm_config pcm_config_afe_proxy_playback = {
    228     .channels = AFE_PROXY_CHANNEL_COUNT,
    229     .rate = AFE_PROXY_SAMPLING_RATE,
    230     .period_size = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    231     .period_count = AFE_PROXY_PLAYBACK_PERIOD_COUNT,
    232     .format = PCM_FORMAT_S16_LE,
    233     .start_threshold = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    234     .stop_threshold = INT_MAX,
    235     .avail_min = AFE_PROXY_PLAYBACK_PERIOD_SIZE,
    236 };
    237 
    238 #define AFE_PROXY_RECORD_PERIOD_SIZE  768
    239 #define AFE_PROXY_RECORD_PERIOD_COUNT 4
    240 
    241 struct pcm_config pcm_config_afe_proxy_record = {
    242     .channels = AFE_PROXY_CHANNEL_COUNT,
    243     .rate = AFE_PROXY_SAMPLING_RATE,
    244     .period_size = AFE_PROXY_RECORD_PERIOD_SIZE,
    245     .period_count = AFE_PROXY_RECORD_PERIOD_COUNT,
    246     .format = PCM_FORMAT_S16_LE,
    247     .start_threshold = AFE_PROXY_RECORD_PERIOD_SIZE,
    248     .stop_threshold = INT_MAX,
    249     .avail_min = AFE_PROXY_RECORD_PERIOD_SIZE,
    250 };
    251 
    252 const char * const use_case_table[AUDIO_USECASE_MAX] = {
    253     [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = "deep-buffer-playback",
    254     [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = "low-latency-playback",
    255     [USECASE_AUDIO_PLAYBACK_HIFI] = "hifi-playback",
    256     [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
    257     [USECASE_AUDIO_PLAYBACK_TTS] = "audio-tts-playback",
    258     [USECASE_AUDIO_PLAYBACK_ULL] = "audio-ull-playback",
    259     [USECASE_AUDIO_PLAYBACK_MMAP] = "mmap-playback",
    260 
    261     [USECASE_AUDIO_RECORD] = "audio-record",
    262     [USECASE_AUDIO_RECORD_LOW_LATENCY] = "low-latency-record",
    263     [USECASE_AUDIO_RECORD_MMAP] = "mmap-record",
    264     [USECASE_AUDIO_RECORD_HIFI] = "hifi-record",
    265 
    266     [USECASE_AUDIO_HFP_SCO] = "hfp-sco",
    267     [USECASE_AUDIO_HFP_SCO_WB] = "hfp-sco-wb",
    268 
    269     [USECASE_VOICE_CALL] = "voice-call",
    270     [USECASE_VOICE2_CALL] = "voice2-call",
    271     [USECASE_VOLTE_CALL] = "volte-call",
    272     [USECASE_QCHAT_CALL] = "qchat-call",
    273     [USECASE_VOWLAN_CALL] = "vowlan-call",
    274     [USECASE_VOICEMMODE1_CALL] = "voicemmode1-call",
    275     [USECASE_VOICEMMODE2_CALL] = "voicemmode2-call",
    276 
    277     [USECASE_AUDIO_SPKR_CALIB_RX] = "spkr-rx-calib",
    278     [USECASE_AUDIO_SPKR_CALIB_TX] = "spkr-vi-record",
    279 
    280     [USECASE_AUDIO_PLAYBACK_AFE_PROXY] = "afe-proxy-playback",
    281     [USECASE_AUDIO_RECORD_AFE_PROXY] = "afe-proxy-record",
    282 
    283     [USECASE_INCALL_REC_UPLINK] = "incall-rec-uplink",
    284     [USECASE_INCALL_REC_DOWNLINK] = "incall-rec-downlink",
    285     [USECASE_INCALL_REC_UPLINK_AND_DOWNLINK] = "incall-rec-uplink-and-downlink",
    286 
    287     [USECASE_AUDIO_PLAYBACK_VOIP] = "audio-playback-voip",
    288     [USECASE_AUDIO_RECORD_VOIP] = "audio-record-voip",
    289 };
    290 
    291 
    292 #define STRING_TO_ENUM(string) { #string, string }
    293 
    294 struct string_to_enum {
    295     const char *name;
    296     uint32_t value;
    297 };
    298 
    299 static const struct string_to_enum channels_name_to_enum_table[] = {
    300     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
    301     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
    302     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
    303     STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
    304     STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
    305     STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
    306     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_1),
    307     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_2),
    308     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_3),
    309     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_4),
    310     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_5),
    311     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_6),
    312     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_7),
    313     STRING_TO_ENUM(AUDIO_CHANNEL_INDEX_MASK_8),
    314 };
    315 
    316 static int set_voice_volume_l(struct audio_device *adev, float volume);
    317 static struct audio_device *adev = NULL;
    318 static pthread_mutex_t adev_init_lock = PTHREAD_MUTEX_INITIALIZER;
    319 static unsigned int audio_device_ref_count;
    320 //cache last MBDRC cal step level
    321 static int last_known_cal_step = -1 ;
    322 
    323 static bool may_use_noirq_mode(struct audio_device *adev, audio_usecase_t uc_id,
    324                                int flags __unused)
    325 {
    326     int dir = 0;
    327     switch (uc_id) {
    328     case USECASE_AUDIO_RECORD_LOW_LATENCY:
    329         dir = 1;
    330     case USECASE_AUDIO_PLAYBACK_ULL:
    331         break;
    332     default:
    333         return false;
    334     }
    335 
    336     int dev_id = platform_get_pcm_device_id(uc_id, dir == 0 ?
    337                                             PCM_PLAYBACK : PCM_CAPTURE);
    338     if (adev->adm_is_noirq_avail)
    339         return adev->adm_is_noirq_avail(adev->adm_data,
    340                                         adev->snd_card, dev_id, dir);
    341     return false;
    342 }
    343 
    344 static void register_out_stream(struct stream_out *out)
    345 {
    346     struct audio_device *adev = out->dev;
    347     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
    348         return;
    349 
    350     if (!adev->adm_register_output_stream)
    351         return;
    352 
    353     adev->adm_register_output_stream(adev->adm_data,
    354                                      out->handle,
    355                                      out->flags);
    356 
    357     if (!adev->adm_set_config)
    358         return;
    359 
    360     if (out->realtime) {
    361         adev->adm_set_config(adev->adm_data,
    362                              out->handle,
    363                              out->pcm, &out->config);
    364     }
    365 }
    366 
    367 static void register_in_stream(struct stream_in *in)
    368 {
    369     struct audio_device *adev = in->dev;
    370     if (!adev->adm_register_input_stream)
    371         return;
    372 
    373     adev->adm_register_input_stream(adev->adm_data,
    374                                     in->capture_handle,
    375                                     in->flags);
    376 
    377     if (!adev->adm_set_config)
    378         return;
    379 
    380     if (in->realtime) {
    381         adev->adm_set_config(adev->adm_data,
    382                              in->capture_handle,
    383                              in->pcm,
    384                              &in->config);
    385     }
    386 }
    387 
    388 static void request_out_focus(struct stream_out *out, long ns)
    389 {
    390     struct audio_device *adev = out->dev;
    391 
    392     if (adev->adm_request_focus_v2) {
    393         adev->adm_request_focus_v2(adev->adm_data, out->handle, ns);
    394     } else if (adev->adm_request_focus) {
    395         adev->adm_request_focus(adev->adm_data, out->handle);
    396     }
    397 }
    398 
    399 static void request_in_focus(struct stream_in *in, long ns)
    400 {
    401     struct audio_device *adev = in->dev;
    402 
    403     if (adev->adm_request_focus_v2) {
    404         adev->adm_request_focus_v2(adev->adm_data, in->capture_handle, ns);
    405     } else if (adev->adm_request_focus) {
    406         adev->adm_request_focus(adev->adm_data, in->capture_handle);
    407     }
    408 }
    409 
    410 static void release_out_focus(struct stream_out *out, long ns __unused)
    411 {
    412     struct audio_device *adev = out->dev;
    413 
    414     if (adev->adm_abandon_focus)
    415         adev->adm_abandon_focus(adev->adm_data, out->handle);
    416 }
    417 
    418 static void release_in_focus(struct stream_in *in, long ns __unused)
    419 {
    420     struct audio_device *adev = in->dev;
    421     if (adev->adm_abandon_focus)
    422         adev->adm_abandon_focus(adev->adm_data, in->capture_handle);
    423 }
    424 
    425 static int parse_snd_card_status(struct str_parms * parms, int * card,
    426                                  card_status_t * status)
    427 {
    428     char value[32]={0};
    429     char state[32]={0};
    430 
    431     int ret = str_parms_get_str(parms, "SND_CARD_STATUS", value, sizeof(value));
    432 
    433     if (ret < 0)
    434         return -1;
    435 
    436     // sscanf should be okay as value is of max length 32.
    437     // same as sizeof state.
    438     if (sscanf(value, "%d,%s", card, state) < 2)
    439         return -1;
    440 
    441     *status = !strcmp(state, "ONLINE") ? CARD_STATUS_ONLINE :
    442                                          CARD_STATUS_OFFLINE;
    443     return 0;
    444 }
    445 
    446 // always call with adev lock held
    447 void send_gain_dep_calibration_l() {
    448     if (last_known_cal_step >= 0)
    449         platform_send_gain_dep_cal(adev->platform, last_known_cal_step);
    450 }
    451 
    452 __attribute__ ((visibility ("default")))
    453 bool audio_hw_send_gain_dep_calibration(int level) {
    454     bool ret_val = false;
    455     ALOGV("%s: enter ... ", __func__);
    456 
    457     pthread_mutex_lock(&adev_init_lock);
    458 
    459     if (adev != NULL && adev->platform != NULL) {
    460         pthread_mutex_lock(&adev->lock);
    461         last_known_cal_step = level;
    462         send_gain_dep_calibration_l();
    463         pthread_mutex_unlock(&adev->lock);
    464     } else {
    465         ALOGE("%s: %s is NULL", __func__, adev == NULL ? "adev" : "adev->platform");
    466     }
    467 
    468     pthread_mutex_unlock(&adev_init_lock);
    469 
    470     ALOGV("%s: exit with ret_val %d ", __func__, ret_val);
    471     return ret_val;
    472 }
    473 
    474 __attribute__ ((visibility ("default")))
    475 int audio_hw_get_gain_level_mapping(struct amp_db_and_gain_table *mapping_tbl,
    476                                     int table_size) {
    477      int ret_val = 0;
    478      ALOGV("%s: enter ... ", __func__);
    479 
    480      pthread_mutex_lock(&adev_init_lock);
    481      if (adev == NULL) {
    482          ALOGW("%s: adev is NULL .... ", __func__);
    483          goto done;
    484      }
    485 
    486      pthread_mutex_lock(&adev->lock);
    487      ret_val = platform_get_gain_level_mapping(mapping_tbl, table_size);
    488      pthread_mutex_unlock(&adev->lock);
    489 done:
    490      pthread_mutex_unlock(&adev_init_lock);
    491      ALOGV("%s: exit ... ", __func__);
    492      return ret_val;
    493 }
    494 
    495 static bool is_supported_format(audio_format_t format)
    496 {
    497     switch (format) {
    498         case AUDIO_FORMAT_MP3:
    499         case AUDIO_FORMAT_AAC_LC:
    500         case AUDIO_FORMAT_AAC_HE_V1:
    501         case AUDIO_FORMAT_AAC_HE_V2:
    502             return true;
    503         default:
    504             break;
    505     }
    506     return false;
    507 }
    508 
    509 static inline bool is_mmap_usecase(audio_usecase_t uc_id)
    510 {
    511     return (uc_id == USECASE_AUDIO_RECORD_AFE_PROXY) ||
    512            (uc_id == USECASE_AUDIO_PLAYBACK_AFE_PROXY);
    513 }
    514 
    515 static int get_snd_codec_id(audio_format_t format)
    516 {
    517     int id = 0;
    518 
    519     switch (format & AUDIO_FORMAT_MAIN_MASK) {
    520     case AUDIO_FORMAT_MP3:
    521         id = SND_AUDIOCODEC_MP3;
    522         break;
    523     case AUDIO_FORMAT_AAC:
    524         id = SND_AUDIOCODEC_AAC;
    525         break;
    526     default:
    527         ALOGE("%s: Unsupported audio format", __func__);
    528     }
    529 
    530     return id;
    531 }
    532 
    533 static int audio_ssr_status(struct audio_device *adev)
    534 {
    535     int ret = 0;
    536     struct mixer_ctl *ctl;
    537     const char *mixer_ctl_name = "Audio SSR Status";
    538 
    539     ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
    540     ret = mixer_ctl_get_value(ctl, 0);
    541     ALOGD("%s: value: %d", __func__, ret);
    542     return ret;
    543 }
    544 
    545 static void stream_app_type_cfg_init(struct stream_app_type_cfg *cfg)
    546 {
    547     cfg->gain[0] = cfg->gain[1] = APP_TYPE_GAIN_DEFAULT;
    548 }
    549 
    550 int enable_audio_route(struct audio_device *adev,
    551                        struct audio_usecase *usecase)
    552 {
    553     snd_device_t snd_device;
    554     char mixer_path[50];
    555 
    556     if (usecase == NULL)
    557         return -EINVAL;
    558 
    559     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
    560 
    561     if (usecase->type == PCM_CAPTURE)
    562         snd_device = usecase->in_snd_device;
    563     else
    564         snd_device = usecase->out_snd_device;
    565 
    566     audio_extn_utils_send_app_type_cfg(adev, usecase);
    567     audio_extn_utils_send_audio_calibration(adev, usecase);
    568     strcpy(mixer_path, use_case_table[usecase->id]);
    569     platform_add_backend_name(adev->platform, mixer_path, snd_device);
    570     ALOGD("%s: usecase(%d) apply and update mixer path: %s", __func__,  usecase->id, mixer_path);
    571     audio_route_apply_and_update_path(adev->audio_route, mixer_path);
    572 
    573     ALOGV("%s: exit", __func__);
    574     return 0;
    575 }
    576 
    577 int disable_audio_route(struct audio_device *adev,
    578                         struct audio_usecase *usecase)
    579 {
    580     snd_device_t snd_device;
    581     char mixer_path[50];
    582 
    583     if (usecase == NULL)
    584         return -EINVAL;
    585 
    586     ALOGV("%s: enter: usecase(%d)", __func__, usecase->id);
    587     if (usecase->type == PCM_CAPTURE)
    588         snd_device = usecase->in_snd_device;
    589     else
    590         snd_device = usecase->out_snd_device;
    591     strcpy(mixer_path, use_case_table[usecase->id]);
    592     platform_add_backend_name(adev->platform, mixer_path, snd_device);
    593     ALOGD("%s: usecase(%d) reset and update mixer path: %s", __func__, usecase->id, mixer_path);
    594     audio_route_reset_and_update_path(adev->audio_route, mixer_path);
    595 
    596     ALOGV("%s: exit", __func__);
    597     return 0;
    598 }
    599 
    600 int enable_snd_device(struct audio_device *adev,
    601                       snd_device_t snd_device)
    602 {
    603     int i, num_devices = 0;
    604     snd_device_t new_snd_devices[2];
    605     int ret_val = -EINVAL;
    606     if (snd_device < SND_DEVICE_MIN ||
    607         snd_device >= SND_DEVICE_MAX) {
    608         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
    609         goto on_error;
    610     }
    611 
    612     platform_send_audio_calibration(adev->platform, snd_device);
    613 
    614     if (adev->snd_dev_ref_cnt[snd_device] >= 1) {
    615         ALOGV("%s: snd_device(%d: %s) is already active",
    616               __func__, snd_device, platform_get_snd_device_name(snd_device));
    617         goto on_success;
    618     }
    619 
    620     /* due to the possibility of calibration overwrite between listen
    621         and audio, notify sound trigger hal before audio calibration is sent */
    622     audio_extn_sound_trigger_update_device_status(snd_device,
    623                                     ST_EVENT_SND_DEVICE_BUSY);
    624 
    625     if (audio_extn_spkr_prot_is_enabled())
    626          audio_extn_spkr_prot_calib_cancel(adev);
    627 
    628     audio_extn_dsm_feedback_enable(adev, snd_device, true);
    629 
    630     if ((snd_device == SND_DEVICE_OUT_SPEAKER ||
    631         snd_device == SND_DEVICE_OUT_VOICE_SPEAKER) &&
    632         audio_extn_spkr_prot_is_enabled()) {
    633         if (audio_extn_spkr_prot_get_acdb_id(snd_device) < 0) {
    634             goto on_error;
    635         }
    636         if (audio_extn_spkr_prot_start_processing(snd_device)) {
    637             ALOGE("%s: spkr_start_processing failed", __func__);
    638             goto on_error;
    639         }
    640     } else if (platform_can_split_snd_device(snd_device,
    641                                              &num_devices,
    642                                              new_snd_devices) == 0) {
    643         for (i = 0; i < num_devices; i++) {
    644             enable_snd_device(adev, new_snd_devices[i]);
    645         }
    646         platform_set_speaker_gain_in_combo(adev, snd_device, true);
    647     } else {
    648         char device_name[DEVICE_NAME_MAX_SIZE] = {0};
    649         if (platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0 ) {
    650             ALOGE(" %s: Invalid sound device returned", __func__);
    651             goto on_error;
    652         }
    653 
    654         ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);
    655         audio_route_apply_and_update_path(adev->audio_route, device_name);
    656     }
    657 on_success:
    658     adev->snd_dev_ref_cnt[snd_device]++;
    659     ret_val = 0;
    660 on_error:
    661     return ret_val;
    662 }
    663 
    664 int disable_snd_device(struct audio_device *adev,
    665                        snd_device_t snd_device)
    666 {
    667     int i, num_devices = 0;
    668     snd_device_t new_snd_devices[2];
    669 
    670     if (snd_device < SND_DEVICE_MIN ||
    671         snd_device >= SND_DEVICE_MAX) {
    672         ALOGE("%s: Invalid sound device %d", __func__, snd_device);
    673         return -EINVAL;
    674     }
    675     if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
    676         ALOGE("%s: device ref cnt is already 0", __func__);
    677         return -EINVAL;
    678     }
    679     audio_extn_tfa_98xx_disable_speaker(snd_device);
    680 
    681     adev->snd_dev_ref_cnt[snd_device]--;
    682     if (adev->snd_dev_ref_cnt[snd_device] == 0) {
    683         audio_extn_dsm_feedback_enable(adev, snd_device, false);
    684         if ((snd_device == SND_DEVICE_OUT_SPEAKER ||
    685             snd_device == SND_DEVICE_OUT_SPEAKER_REVERSE ||
    686             snd_device == SND_DEVICE_OUT_VOICE_SPEAKER) &&
    687             audio_extn_spkr_prot_is_enabled()) {
    688             audio_extn_spkr_prot_stop_processing(snd_device);
    689 
    690             // FIXME b/65363602: bullhead is the only Nexus with audio_extn_spkr_prot_is_enabled()
    691             // and does not use speaker swap. As this code causes a problem with device enable ref
    692             // counting we remove it for now.
    693             // when speaker device is disabled, reset swap.
    694             // will be renabled on usecase start
    695             // platform_set_swap_channels(adev, false);
    696 
    697         } else if (platform_can_split_snd_device(snd_device,
    698                                                  &num_devices,
    699                                                  new_snd_devices) == 0) {
    700             for (i = 0; i < num_devices; i++) {
    701                 disable_snd_device(adev, new_snd_devices[i]);
    702             }
    703             platform_set_speaker_gain_in_combo(adev, snd_device, false);
    704         } else {
    705             char device_name[DEVICE_NAME_MAX_SIZE] = {0};
    706             if (platform_get_snd_device_name_extn(adev->platform, snd_device, device_name) < 0 ) {
    707                 ALOGE(" %s: Invalid sound device returned", __func__);
    708                 return -EINVAL;
    709             }
    710 
    711             ALOGD("%s: snd_device(%d: %s)", __func__, snd_device, device_name);
    712             audio_route_reset_and_update_path(adev->audio_route, device_name);
    713         }
    714         audio_extn_sound_trigger_update_device_status(snd_device,
    715                                         ST_EVENT_SND_DEVICE_FREE);
    716     }
    717 
    718     return 0;
    719 }
    720 
    721 /*
    722   legend:
    723   uc - existing usecase
    724   new_uc - new usecase
    725   d1, d11, d2 - SND_DEVICE enums
    726   a1, a2 - corresponding ANDROID device enums
    727   B, B1, B2 - backend strings
    728 
    729 case 1
    730   uc->dev  d1 (a1)               B1
    731   new_uc->dev d1 (a1), d2 (a2)   B1, B2
    732 
    733   resolution: disable and enable uc->dev on d1
    734 
    735 case 2
    736   uc->dev d1 (a1)        B1
    737   new_uc->dev d11 (a1)   B1
    738 
    739   resolution: need to switch uc since d1 and d11 are related
    740   (e.g. speaker and voice-speaker)
    741   use ANDROID_DEVICE_OUT enums to match devices since SND_DEVICE enums may vary
    742 
    743 case 3
    744   uc->dev d1 (a1)        B1
    745   new_uc->dev d2 (a2)    B2
    746 
    747   resolution: no need to switch uc
    748 
    749 case 4
    750   uc->dev d1 (a1)      B
    751   new_uc->dev d2 (a2)  B
    752 
    753   resolution: disable enable uc-dev on d2 since backends match
    754   we cannot enable two streams on two different devices if they
    755   share the same backend. e.g. if offload is on speaker device using
    756   QUAD_MI2S backend and a low-latency stream is started on voice-handset
    757   using the same backend, offload must also be switched to voice-handset.
    758 
    759 case 5
    760   uc->dev  d1 (a1)                  B
    761   new_uc->dev d1 (a1), d2 (a2)      B
    762 
    763   resolution: disable enable uc-dev on d2 since backends match
    764   we cannot enable two streams on two different devices if they
    765   share the same backend.
    766 
    767 case 6
    768   uc->dev  d1 a1    B1
    769   new_uc->dev d2 a1 B2
    770 
    771   resolution: no need to switch
    772 
    773 case 7
    774 
    775   uc->dev d1 (a1), d2 (a2)       B1, B2
    776   new_uc->dev d1                 B1
    777 
    778   resolution: no need to switch
    779 
    780 */
    781 static snd_device_t derive_playback_snd_device(struct audio_usecase *uc,
    782                                                struct audio_usecase *new_uc,
    783                                                snd_device_t new_snd_device)
    784 {
    785     audio_devices_t a1 = uc->stream.out->devices;
    786     audio_devices_t a2 = new_uc->stream.out->devices;
    787 
    788     snd_device_t d1 = uc->out_snd_device;
    789     snd_device_t d2 = new_snd_device;
    790 
    791     // Treat as a special case when a1 and a2 are not disjoint
    792     if ((a1 != a2) && (a1 & a2)) {
    793         snd_device_t d3[2];
    794         int num_devices = 0;
    795         int ret = platform_can_split_snd_device(popcount(a1) > 1 ? d1 : d2,
    796                                                 &num_devices,
    797                                                 d3);
    798         if (ret < 0) {
    799             if (ret != -ENOSYS) {
    800                 ALOGW("%s failed to split snd_device %d",
    801                       __func__,
    802                       popcount(a1) > 1 ? d1 : d2);
    803             }
    804             goto end;
    805         }
    806 
    807         // NB: case 7 is hypothetical and isn't a practical usecase yet.
    808         // But if it does happen, we need to give priority to d2 if
    809         // the combo devices active on the existing usecase share a backend.
    810         // This is because we cannot have a usecase active on a combo device
    811         // and a new usecase requests one device in this combo pair.
    812         if (platform_check_backends_match(d3[0], d3[1])) {
    813             return d2; // case 5
    814         } else {
    815             return d1; // case 1
    816         }
    817     } else {
    818         if (platform_check_backends_match(d1, d2)) {
    819             return d2; // case 2, 4
    820         } else {
    821             return d1; // case 6, 3
    822         }
    823     }
    824 
    825 end:
    826     return d2; // return whatever was calculated before.
    827 }
    828 
    829 static void check_and_route_playback_usecases(struct audio_device *adev,
    830                                               struct audio_usecase *uc_info,
    831                                               snd_device_t snd_device)
    832 {
    833     struct listnode *node;
    834     struct audio_usecase *usecase;
    835     bool switch_device[AUDIO_USECASE_MAX];
    836     int i, num_uc_to_switch = 0;
    837 
    838     bool force_routing =  platform_check_and_set_playback_backend_cfg(adev,
    839                                                                       uc_info,
    840                                                                       snd_device);
    841 
    842     /*
    843      * This function is to make sure that all the usecases that are active on
    844      * the hardware codec backend are always routed to any one device that is
    845      * handled by the hardware codec.
    846      * For example, if low-latency and deep-buffer usecases are currently active
    847      * on speaker and out_set_parameters(headset) is received on low-latency
    848      * output, then we have to make sure deep-buffer is also switched to headset,
    849      * because of the limitation that both the devices cannot be enabled
    850      * at the same time as they share the same backend.
    851      */
    852     /* Disable all the usecases on the shared backend other than the
    853        specified usecase */
    854     for (i = 0; i < AUDIO_USECASE_MAX; i++)
    855         switch_device[i] = false;
    856 
    857     list_for_each(node, &adev->usecase_list) {
    858         usecase = node_to_item(node, struct audio_usecase, list);
    859         if (usecase->type == PCM_CAPTURE || usecase == uc_info)
    860             continue;
    861 
    862         if (force_routing ||
    863             (usecase->out_snd_device != snd_device &&
    864              (usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND ||
    865               usecase->devices & (AUDIO_DEVICE_OUT_USB_DEVICE|AUDIO_DEVICE_OUT_USB_HEADSET)) &&
    866              platform_check_backends_match(snd_device, usecase->out_snd_device))) {
    867             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
    868                   __func__, use_case_table[usecase->id],
    869                   platform_get_snd_device_name(usecase->out_snd_device));
    870             disable_audio_route(adev, usecase);
    871             switch_device[usecase->id] = true;
    872             num_uc_to_switch++;
    873         }
    874     }
    875 
    876     if (num_uc_to_switch) {
    877         list_for_each(node, &adev->usecase_list) {
    878             usecase = node_to_item(node, struct audio_usecase, list);
    879             if (switch_device[usecase->id]) {
    880                 disable_snd_device(adev, usecase->out_snd_device);
    881             }
    882         }
    883 
    884         snd_device_t d_device;
    885         list_for_each(node, &adev->usecase_list) {
    886             usecase = node_to_item(node, struct audio_usecase, list);
    887             if (switch_device[usecase->id]) {
    888                 d_device = derive_playback_snd_device(usecase, uc_info,
    889                                                       snd_device);
    890                 enable_snd_device(adev, d_device);
    891                 /* Update the out_snd_device before enabling the audio route */
    892                 usecase->out_snd_device = d_device;
    893             }
    894         }
    895 
    896         /* Re-route all the usecases on the shared backend other than the
    897            specified usecase to new snd devices */
    898         list_for_each(node, &adev->usecase_list) {
    899             usecase = node_to_item(node, struct audio_usecase, list);
    900             if (switch_device[usecase->id] ) {
    901                 enable_audio_route(adev, usecase);
    902             }
    903         }
    904     }
    905 }
    906 
    907 static void check_and_route_capture_usecases(struct audio_device *adev,
    908                                              struct audio_usecase *uc_info,
    909                                              snd_device_t snd_device)
    910 {
    911     struct listnode *node;
    912     struct audio_usecase *usecase;
    913     bool switch_device[AUDIO_USECASE_MAX];
    914     int i, num_uc_to_switch = 0;
    915 
    916     platform_check_and_set_capture_backend_cfg(adev, uc_info, snd_device);
    917 
    918     /*
    919      * This function is to make sure that all the active capture usecases
    920      * are always routed to the same input sound device.
    921      * For example, if audio-record and voice-call usecases are currently
    922      * active on speaker(rx) and speaker-mic (tx) and out_set_parameters(earpiece)
    923      * is received for voice call then we have to make sure that audio-record
    924      * usecase is also switched to earpiece i.e. voice-dmic-ef,
    925      * because of the limitation that two devices cannot be enabled
    926      * at the same time if they share the same backend.
    927      */
    928     for (i = 0; i < AUDIO_USECASE_MAX; i++)
    929         switch_device[i] = false;
    930 
    931     list_for_each(node, &adev->usecase_list) {
    932         usecase = node_to_item(node, struct audio_usecase, list);
    933         if (usecase->type != PCM_PLAYBACK &&
    934                 usecase != uc_info &&
    935                 usecase->in_snd_device != snd_device &&
    936                 (usecase->id != USECASE_AUDIO_SPKR_CALIB_TX)) {
    937             ALOGV("%s: Usecase (%s) is active on (%s) - disabling ..",
    938                   __func__, use_case_table[usecase->id],
    939                   platform_get_snd_device_name(usecase->in_snd_device));
    940             disable_audio_route(adev, usecase);
    941             switch_device[usecase->id] = true;
    942             num_uc_to_switch++;
    943         }
    944     }
    945 
    946     if (num_uc_to_switch) {
    947         list_for_each(node, &adev->usecase_list) {
    948             usecase = node_to_item(node, struct audio_usecase, list);
    949             if (switch_device[usecase->id]) {
    950                 disable_snd_device(adev, usecase->in_snd_device);
    951             }
    952         }
    953 
    954         list_for_each(node, &adev->usecase_list) {
    955             usecase = node_to_item(node, struct audio_usecase, list);
    956             if (switch_device[usecase->id]) {
    957                 enable_snd_device(adev, snd_device);
    958             }
    959         }
    960 
    961         /* Re-route all the usecases on the shared backend other than the
    962            specified usecase to new snd devices */
    963         list_for_each(node, &adev->usecase_list) {
    964             usecase = node_to_item(node, struct audio_usecase, list);
    965             /* Update the in_snd_device only before enabling the audio route */
    966             if (switch_device[usecase->id] ) {
    967                 usecase->in_snd_device = snd_device;
    968                 enable_audio_route(adev, usecase);
    969             }
    970         }
    971     }
    972 }
    973 
    974 /* must be called with hw device mutex locked */
    975 static int read_hdmi_channel_masks(struct stream_out *out)
    976 {
    977     int ret = 0;
    978     int channels = platform_edid_get_max_channels(out->dev->platform);
    979 
    980     switch (channels) {
    981         /*
    982          * Do not handle stereo output in Multi-channel cases
    983          * Stereo case is handled in normal playback path
    984          */
    985     case 6:
    986         ALOGV("%s: HDMI supports 5.1", __func__);
    987         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
    988         break;
    989     case 8:
    990         ALOGV("%s: HDMI supports 5.1 and 7.1 channels", __func__);
    991         out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_5POINT1;
    992         out->supported_channel_masks[1] = AUDIO_CHANNEL_OUT_7POINT1;
    993         break;
    994     default:
    995         ALOGE("HDMI does not support multi channel playback");
    996         ret = -ENOSYS;
    997         break;
    998     }
    999     return ret;
   1000 }
   1001 
   1002 static ssize_t read_usb_sup_sample_rates(bool is_playback __unused,
   1003                                          uint32_t *supported_sample_rates __unused,
   1004                                          uint32_t max_rates __unused)
   1005 {
   1006     ssize_t count = audio_extn_usb_sup_sample_rates(is_playback,
   1007                                                     supported_sample_rates,
   1008                                                     max_rates);
   1009 #if !LOG_NDEBUG
   1010     for (ssize_t i=0; i<count; i++) {
   1011         ALOGV("%s %s %d", __func__, is_playback ? "P" : "C",
   1012               supported_sample_rates[i]);
   1013     }
   1014 #endif
   1015     return count;
   1016 }
   1017 
   1018 static int read_usb_sup_channel_masks(bool is_playback,
   1019                                       audio_channel_mask_t *supported_channel_masks,
   1020                                       uint32_t max_masks)
   1021 {
   1022     int channels = audio_extn_usb_get_max_channels(is_playback);
   1023     int channel_count;
   1024     uint32_t num_masks = 0;
   1025     if (channels > MAX_HIFI_CHANNEL_COUNT) {
   1026         channels = MAX_HIFI_CHANNEL_COUNT;
   1027     }
   1028     if (is_playback) {
   1029         // For playback we never report mono because the framework always outputs stereo
   1030         channel_count = DEFAULT_CHANNEL_COUNT;
   1031         // audio_channel_out_mask_from_count() does return positional masks for channel counts
   1032         // above 2 but we want indexed masks here. So we
   1033         for ( ; channel_count <= channels && num_masks < max_masks; channel_count++) {
   1034             supported_channel_masks[num_masks++] = audio_channel_out_mask_from_count(channel_count);
   1035         }
   1036         for ( ; channel_count <= channels && num_masks < max_masks; channel_count++) {
   1037             supported_channel_masks[num_masks++] =
   1038                     audio_channel_mask_for_index_assignment_from_count(channel_count);
   1039         }
   1040     } else {
   1041         // For capture we report all supported channel masks from 1 channel up.
   1042         channel_count = MIN_CHANNEL_COUNT;
   1043         // audio_channel_in_mask_from_count() does the right conversion to either positional or
   1044         // indexed mask
   1045         for ( ; channel_count <= channels && num_masks < max_masks; channel_count++) {
   1046             supported_channel_masks[num_masks++] =
   1047                     audio_channel_in_mask_from_count(channel_count);
   1048         }
   1049     }
   1050     ALOGV("%s: %s supported ch %d supported_channel_masks[0] %08x num_masks %d", __func__,
   1051           is_playback ? "P" : "C", channels, supported_channel_masks[0], num_masks);
   1052     return num_masks;
   1053 }
   1054 
   1055 static int read_usb_sup_formats(bool is_playback __unused,
   1056                                 audio_format_t *supported_formats,
   1057                                 uint32_t max_formats __unused)
   1058 {
   1059     int bitwidth = audio_extn_usb_get_max_bit_width(is_playback);
   1060     switch (bitwidth) {
   1061         case 24:
   1062             // XXX : usb.c returns 24 for s24 and s24_le?
   1063             supported_formats[0] = AUDIO_FORMAT_PCM_24_BIT_PACKED;
   1064             break;
   1065         case 32:
   1066             supported_formats[0] = AUDIO_FORMAT_PCM_32_BIT;
   1067             break;
   1068         case 16:
   1069         default :
   1070             supported_formats[0] = AUDIO_FORMAT_PCM_16_BIT;
   1071             break;
   1072     }
   1073     ALOGV("%s: %s supported format %d", __func__,
   1074           is_playback ? "P" : "C", bitwidth);
   1075     return 1;
   1076 }
   1077 
   1078 static int read_usb_sup_params_and_compare(bool is_playback,
   1079                                            audio_format_t *format,
   1080                                            audio_format_t *supported_formats,
   1081                                            uint32_t max_formats,
   1082                                            audio_channel_mask_t *mask,
   1083                                            audio_channel_mask_t *supported_channel_masks,
   1084                                            uint32_t max_masks,
   1085                                            uint32_t *rate,
   1086                                            uint32_t *supported_sample_rates,
   1087                                            uint32_t max_rates) {
   1088     int ret = 0;
   1089     int num_formats;
   1090     int num_masks;
   1091     int num_rates;
   1092     int i;
   1093 
   1094     num_formats = read_usb_sup_formats(is_playback, supported_formats,
   1095                                        max_formats);
   1096     num_masks = read_usb_sup_channel_masks(is_playback, supported_channel_masks,
   1097                                            max_masks);
   1098 
   1099     num_rates = read_usb_sup_sample_rates(is_playback,
   1100                                           supported_sample_rates, max_rates);
   1101 
   1102 #define LUT(table, len, what, dflt)                  \
   1103     for (i=0; i<len && (table[i] != what); i++);    \
   1104     if (i==len) { ret |= (what == dflt ? 0 : -1); what=table[0]; }
   1105 
   1106     LUT(supported_formats, num_formats, *format, AUDIO_FORMAT_DEFAULT);
   1107     LUT(supported_channel_masks, num_masks, *mask, AUDIO_CHANNEL_NONE);
   1108     LUT(supported_sample_rates, num_rates, *rate, 0);
   1109 
   1110 #undef LUT
   1111     return ret < 0 ? -EINVAL : 0; // HACK TBD
   1112 }
   1113 
   1114 static bool is_usb_ready(struct audio_device *adev, bool is_playback)
   1115 {
   1116     // Check if usb is ready.
   1117     // The usb device may have been removed quickly after insertion and hence
   1118     // no longer available.  This will show up as empty channel masks, or rates.
   1119 
   1120     pthread_mutex_lock(&adev->lock);
   1121     uint32_t supported_sample_rate;
   1122 
   1123     // we consider usb ready if we can fetch at least one sample rate.
   1124     const bool ready = read_usb_sup_sample_rates(
   1125             is_playback, &supported_sample_rate, 1 /* max_rates */) > 0;
   1126     pthread_mutex_unlock(&adev->lock);
   1127     return ready;
   1128 }
   1129 
   1130 static audio_usecase_t get_voice_usecase_id_from_list(struct audio_device *adev)
   1131 {
   1132     struct audio_usecase *usecase;
   1133     struct listnode *node;
   1134 
   1135     list_for_each(node, &adev->usecase_list) {
   1136         usecase = node_to_item(node, struct audio_usecase, list);
   1137         if (usecase->type == VOICE_CALL) {
   1138             ALOGV("%s: usecase id %d", __func__, usecase->id);
   1139             return usecase->id;
   1140         }
   1141     }
   1142     return USECASE_INVALID;
   1143 }
   1144 
   1145 struct audio_usecase *get_usecase_from_list(struct audio_device *adev,
   1146                                             audio_usecase_t uc_id)
   1147 {
   1148     struct audio_usecase *usecase;
   1149     struct listnode *node;
   1150 
   1151     list_for_each(node, &adev->usecase_list) {
   1152         usecase = node_to_item(node, struct audio_usecase, list);
   1153         if (usecase->id == uc_id)
   1154             return usecase;
   1155     }
   1156     return NULL;
   1157 }
   1158 
   1159 int select_devices(struct audio_device *adev,
   1160                    audio_usecase_t uc_id)
   1161 {
   1162     snd_device_t out_snd_device = SND_DEVICE_NONE;
   1163     snd_device_t in_snd_device = SND_DEVICE_NONE;
   1164     struct audio_usecase *usecase = NULL;
   1165     struct audio_usecase *vc_usecase = NULL;
   1166     struct audio_usecase *hfp_usecase = NULL;
   1167     audio_usecase_t hfp_ucid;
   1168     struct listnode *node;
   1169     int status = 0;
   1170     struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
   1171                                              USECASE_AUDIO_PLAYBACK_VOIP);
   1172 
   1173     usecase = get_usecase_from_list(adev, uc_id);
   1174     if (usecase == NULL) {
   1175         ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
   1176         return -EINVAL;
   1177     }
   1178 
   1179     if ((usecase->type == VOICE_CALL) ||
   1180         (usecase->type == PCM_HFP_CALL)) {
   1181         out_snd_device = platform_get_output_snd_device(adev->platform,
   1182                                                         usecase->stream.out->devices);
   1183         in_snd_device = platform_get_input_snd_device(adev->platform, usecase->stream.out->devices);
   1184         usecase->devices = usecase->stream.out->devices;
   1185     } else {
   1186         /*
   1187          * If the voice call is active, use the sound devices of voice call usecase
   1188          * so that it would not result any device switch. All the usecases will
   1189          * be switched to new device when select_devices() is called for voice call
   1190          * usecase. This is to avoid switching devices for voice call when
   1191          * check_and_route_playback_usecases() is called below.
   1192          */
   1193         if (voice_is_in_call(adev)) {
   1194             vc_usecase = get_usecase_from_list(adev,
   1195                                                get_voice_usecase_id_from_list(adev));
   1196             if ((vc_usecase != NULL) &&
   1197                 ((vc_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
   1198                 (usecase->devices == AUDIO_DEVICE_IN_VOICE_CALL))) {
   1199                 in_snd_device = vc_usecase->in_snd_device;
   1200                 out_snd_device = vc_usecase->out_snd_device;
   1201             }
   1202         } else if (audio_extn_hfp_is_active(adev)) {
   1203             hfp_ucid = audio_extn_hfp_get_usecase();
   1204             hfp_usecase = get_usecase_from_list(adev, hfp_ucid);
   1205             if (hfp_usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) {
   1206                    in_snd_device = hfp_usecase->in_snd_device;
   1207                    out_snd_device = hfp_usecase->out_snd_device;
   1208             }
   1209         }
   1210         if (usecase->type == PCM_PLAYBACK) {
   1211             usecase->devices = usecase->stream.out->devices;
   1212             in_snd_device = SND_DEVICE_NONE;
   1213             if (out_snd_device == SND_DEVICE_NONE) {
   1214                 struct stream_out *voip_out = adev->primary_output;
   1215 
   1216                 out_snd_device = platform_get_output_snd_device(adev->platform,
   1217                                             usecase->stream.out->devices);
   1218 
   1219                 if (voip_usecase)
   1220                     voip_out = voip_usecase->stream.out;
   1221 
   1222                 if (usecase->stream.out == voip_out &&
   1223                         adev->active_input &&
   1224                         (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
   1225                             adev->mode == AUDIO_MODE_IN_COMMUNICATION)) {
   1226                     select_devices(adev, adev->active_input->usecase);
   1227                 }
   1228             }
   1229         } else if (usecase->type == PCM_CAPTURE) {
   1230             usecase->devices = usecase->stream.in->device;
   1231             out_snd_device = SND_DEVICE_NONE;
   1232             if (in_snd_device == SND_DEVICE_NONE) {
   1233                 audio_devices_t out_device = AUDIO_DEVICE_NONE;
   1234                 if (adev->active_input &&
   1235                         (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
   1236                             adev->mode == AUDIO_MODE_IN_COMMUNICATION)) {
   1237 
   1238                     struct audio_usecase *voip_usecase = get_usecase_from_list(adev,
   1239                                                              USECASE_AUDIO_PLAYBACK_VOIP);
   1240 
   1241                     platform_set_echo_reference(adev, false, AUDIO_DEVICE_NONE);
   1242                     if (usecase->id == USECASE_AUDIO_RECORD_AFE_PROXY) {
   1243                         out_device = AUDIO_DEVICE_OUT_TELEPHONY_TX;
   1244                     } else if (voip_usecase) {
   1245                         out_device = voip_usecase->stream.out->devices;
   1246                     } else if (adev->primary_output) {
   1247                         out_device = adev->primary_output->devices;
   1248                     }
   1249                 }
   1250                 in_snd_device = platform_get_input_snd_device(adev->platform, out_device);
   1251             }
   1252         }
   1253     }
   1254 
   1255     if (out_snd_device == usecase->out_snd_device &&
   1256         in_snd_device == usecase->in_snd_device) {
   1257         return 0;
   1258     }
   1259 
   1260     if (out_snd_device != SND_DEVICE_NONE &&
   1261             out_snd_device != adev->last_logged_snd_device[uc_id][0]) {
   1262         ALOGD("%s: changing use case %s output device from(%d: %s, acdb %d) to (%d: %s, acdb %d)",
   1263               __func__,
   1264               use_case_table[uc_id],
   1265               adev->last_logged_snd_device[uc_id][0],
   1266               platform_get_snd_device_name(adev->last_logged_snd_device[uc_id][0]),
   1267               adev->last_logged_snd_device[uc_id][0] != SND_DEVICE_NONE ?
   1268                       platform_get_snd_device_acdb_id(adev->last_logged_snd_device[uc_id][0]) :
   1269                       -1,
   1270               out_snd_device,
   1271               platform_get_snd_device_name(out_snd_device),
   1272               platform_get_snd_device_acdb_id(out_snd_device));
   1273         adev->last_logged_snd_device[uc_id][0] = out_snd_device;
   1274     }
   1275     if (in_snd_device != SND_DEVICE_NONE &&
   1276             in_snd_device != adev->last_logged_snd_device[uc_id][1]) {
   1277         ALOGD("%s: changing use case %s input device from(%d: %s, acdb %d) to (%d: %s, acdb %d)",
   1278               __func__,
   1279               use_case_table[uc_id],
   1280               adev->last_logged_snd_device[uc_id][1],
   1281               platform_get_snd_device_name(adev->last_logged_snd_device[uc_id][1]),
   1282               adev->last_logged_snd_device[uc_id][1] != SND_DEVICE_NONE ?
   1283                       platform_get_snd_device_acdb_id(adev->last_logged_snd_device[uc_id][1]) :
   1284                       -1,
   1285               in_snd_device,
   1286               platform_get_snd_device_name(in_snd_device),
   1287               platform_get_snd_device_acdb_id(in_snd_device));
   1288         adev->last_logged_snd_device[uc_id][1] = in_snd_device;
   1289     }
   1290 
   1291     /*
   1292      * Limitation: While in call, to do a device switch we need to disable
   1293      * and enable both RX and TX devices though one of them is same as current
   1294      * device.
   1295      */
   1296     if ((usecase->type == VOICE_CALL) &&
   1297         (usecase->in_snd_device != SND_DEVICE_NONE) &&
   1298         (usecase->out_snd_device != SND_DEVICE_NONE)) {
   1299         status = platform_switch_voice_call_device_pre(adev->platform);
   1300         /* Disable sidetone only if voice call already exists */
   1301         if (voice_is_call_state_active(adev))
   1302             voice_set_sidetone(adev, usecase->out_snd_device, false);
   1303     }
   1304 
   1305     /* Disable current sound devices */
   1306     if (usecase->out_snd_device != SND_DEVICE_NONE) {
   1307         disable_audio_route(adev, usecase);
   1308         disable_snd_device(adev, usecase->out_snd_device);
   1309     }
   1310 
   1311     if (usecase->in_snd_device != SND_DEVICE_NONE) {
   1312         disable_audio_route(adev, usecase);
   1313         disable_snd_device(adev, usecase->in_snd_device);
   1314     }
   1315 
   1316     /* Applicable only on the targets that has external modem.
   1317      * New device information should be sent to modem before enabling
   1318      * the devices to reduce in-call device switch time.
   1319      */
   1320     if ((usecase->type == VOICE_CALL) &&
   1321         (usecase->in_snd_device != SND_DEVICE_NONE) &&
   1322         (usecase->out_snd_device != SND_DEVICE_NONE)) {
   1323         status = platform_switch_voice_call_enable_device_config(adev->platform,
   1324                                                                  out_snd_device,
   1325                                                                  in_snd_device);
   1326     }
   1327 
   1328     /* Enable new sound devices */
   1329     if (out_snd_device != SND_DEVICE_NONE) {
   1330         if ((usecase->devices & AUDIO_DEVICE_OUT_ALL_CODEC_BACKEND) ||
   1331             (usecase->devices & (AUDIO_DEVICE_OUT_USB_DEVICE|AUDIO_DEVICE_OUT_USB_HEADSET)))
   1332             check_and_route_playback_usecases(adev, usecase, out_snd_device);
   1333         enable_snd_device(adev, out_snd_device);
   1334     }
   1335 
   1336     if (in_snd_device != SND_DEVICE_NONE) {
   1337         check_and_route_capture_usecases(adev, usecase, in_snd_device);
   1338         enable_snd_device(adev, in_snd_device);
   1339     }
   1340 
   1341     if (usecase->type == VOICE_CALL)
   1342         status = platform_switch_voice_call_device_post(adev->platform,
   1343                                                         out_snd_device,
   1344                                                         in_snd_device);
   1345 
   1346     usecase->in_snd_device = in_snd_device;
   1347     usecase->out_snd_device = out_snd_device;
   1348 
   1349     audio_extn_tfa_98xx_set_mode();
   1350 
   1351     enable_audio_route(adev, usecase);
   1352 
   1353     /* Applicable only on the targets that has external modem.
   1354      * Enable device command should be sent to modem only after
   1355      * enabling voice call mixer controls
   1356      */
   1357     if (usecase->type == VOICE_CALL) {
   1358         status = platform_switch_voice_call_usecase_route_post(adev->platform,
   1359                                                                out_snd_device,
   1360                                                                in_snd_device);
   1361          /* Enable sidetone only if voice call already exists */
   1362         if (voice_is_call_state_active(adev))
   1363             voice_set_sidetone(adev, out_snd_device, true);
   1364     }
   1365 
   1366     if (usecase == voip_usecase) {
   1367         struct stream_out *voip_out = voip_usecase->stream.out;
   1368         audio_extn_utils_send_app_type_gain(adev,
   1369                                             voip_out->app_type_cfg.app_type,
   1370                                             &voip_out->app_type_cfg.gain[0]);
   1371     }
   1372     return status;
   1373 }
   1374 
   1375 static int stop_input_stream(struct stream_in *in)
   1376 {
   1377     int i, ret = 0;
   1378     struct audio_usecase *uc_info;
   1379     struct audio_device *adev = in->dev;
   1380 
   1381     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   1382           in->usecase, use_case_table[in->usecase]);
   1383 
   1384     if (adev->active_input) {
   1385         if (adev->active_input->usecase == in->usecase) {
   1386             adev->active_input = NULL;
   1387         } else {
   1388             ALOGW("%s adev->active_input->usecase %s, v/s in->usecase %s",
   1389                 __func__,
   1390                 use_case_table[adev->active_input->usecase],
   1391                 use_case_table[in->usecase]);
   1392         }
   1393     }
   1394 
   1395     uc_info = get_usecase_from_list(adev, in->usecase);
   1396     if (uc_info == NULL) {
   1397         ALOGE("%s: Could not find the usecase (%d) in the list",
   1398               __func__, in->usecase);
   1399         return -EINVAL;
   1400     }
   1401 
   1402     /* Close in-call recording streams */
   1403     voice_check_and_stop_incall_rec_usecase(adev, in);
   1404 
   1405     /* 1. Disable stream specific mixer controls */
   1406     disable_audio_route(adev, uc_info);
   1407 
   1408     /* 2. Disable the tx device */
   1409     disable_snd_device(adev, uc_info->in_snd_device);
   1410 
   1411     list_remove(&uc_info->list);
   1412     free(uc_info);
   1413 
   1414     ALOGV("%s: exit: status(%d)", __func__, ret);
   1415     return ret;
   1416 }
   1417 
   1418 int start_input_stream(struct stream_in *in)
   1419 {
   1420     /* 1. Enable output device and stream routing controls */
   1421     int ret = 0;
   1422     struct audio_usecase *uc_info;
   1423     struct audio_device *adev = in->dev;
   1424 
   1425     ALOGV("%s: enter: usecase(%d)", __func__, in->usecase);
   1426 
   1427     if (audio_extn_tfa_98xx_is_supported() && !audio_ssr_status(adev))
   1428         return -EIO;
   1429 
   1430     if (in->card_status == CARD_STATUS_OFFLINE ||
   1431         adev->card_status == CARD_STATUS_OFFLINE) {
   1432         ALOGW("in->card_status or adev->card_status offline, try again");
   1433         ret = -EAGAIN;
   1434         goto error_config;
   1435     }
   1436 
   1437     /* Check if source matches incall recording usecase criteria */
   1438     ret = voice_check_and_set_incall_rec_usecase(adev, in);
   1439     if (ret)
   1440         goto error_config;
   1441     else
   1442         ALOGV("%s: usecase(%d)", __func__, in->usecase);
   1443 
   1444     in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
   1445     if (in->pcm_device_id < 0) {
   1446         ALOGE("%s: Could not find PCM device id for the usecase(%d)",
   1447               __func__, in->usecase);
   1448         ret = -EINVAL;
   1449         goto error_config;
   1450     }
   1451 
   1452     adev->active_input = in;
   1453     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
   1454     uc_info->id = in->usecase;
   1455     uc_info->type = PCM_CAPTURE;
   1456     uc_info->stream.in = in;
   1457     uc_info->devices = in->device;
   1458     uc_info->in_snd_device = SND_DEVICE_NONE;
   1459     uc_info->out_snd_device = SND_DEVICE_NONE;
   1460 
   1461     list_add_tail(&adev->usecase_list, &uc_info->list);
   1462 
   1463     audio_extn_perf_lock_acquire();
   1464 
   1465     select_devices(adev, in->usecase);
   1466 
   1467     if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
   1468         if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
   1469             ALOGE("%s: pcm stream not ready", __func__);
   1470             goto error_open;
   1471         }
   1472         ret = pcm_start(in->pcm);
   1473         if (ret < 0) {
   1474             ALOGE("%s: MMAP pcm_start failed ret %d", __func__, ret);
   1475             goto error_open;
   1476         }
   1477     } else {
   1478         unsigned int flags = PCM_IN | PCM_MONOTONIC;
   1479         unsigned int pcm_open_retry_count = 0;
   1480 
   1481         if (in->usecase == USECASE_AUDIO_RECORD_AFE_PROXY) {
   1482             flags |= PCM_MMAP | PCM_NOIRQ;
   1483             pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
   1484         } else if (in->realtime) {
   1485             flags |= PCM_MMAP | PCM_NOIRQ;
   1486         }
   1487 
   1488         ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
   1489               __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
   1490 
   1491         while (1) {
   1492             in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
   1493                                flags, &in->config);
   1494             if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
   1495                 ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
   1496                 if (in->pcm != NULL) {
   1497                     pcm_close(in->pcm);
   1498                     in->pcm = NULL;
   1499                 }
   1500                 if (pcm_open_retry_count-- == 0) {
   1501                     ret = -EIO;
   1502                     goto error_open;
   1503                 }
   1504                 usleep(PROXY_OPEN_WAIT_TIME * 1000);
   1505                 continue;
   1506             }
   1507             break;
   1508         }
   1509 
   1510         ALOGV("%s: pcm_prepare", __func__);
   1511         ret = pcm_prepare(in->pcm);
   1512         if (ret < 0) {
   1513             ALOGE("%s: pcm_prepare returned %d", __func__, ret);
   1514             pcm_close(in->pcm);
   1515             in->pcm = NULL;
   1516             goto error_open;
   1517         }
   1518         if (in->realtime) {
   1519             ret = pcm_start(in->pcm);
   1520             if (ret < 0) {
   1521                 ALOGE("%s: RT pcm_start failed ret %d", __func__, ret);
   1522                 pcm_close(in->pcm);
   1523                 in->pcm = NULL;
   1524                 goto error_open;
   1525             }
   1526         }
   1527     }
   1528     register_in_stream(in);
   1529     audio_extn_perf_lock_release();
   1530     ALOGV("%s: exit", __func__);
   1531 
   1532     return 0;
   1533 
   1534 error_open:
   1535     stop_input_stream(in);
   1536     audio_extn_perf_lock_release();
   1537 
   1538 error_config:
   1539     adev->active_input = NULL;
   1540     ALOGW("%s: exit: status(%d)", __func__, ret);
   1541     return ret;
   1542 }
   1543 
   1544 void lock_input_stream(struct stream_in *in)
   1545 {
   1546     pthread_mutex_lock(&in->pre_lock);
   1547     pthread_mutex_lock(&in->lock);
   1548     pthread_mutex_unlock(&in->pre_lock);
   1549 }
   1550 
   1551 void lock_output_stream(struct stream_out *out)
   1552 {
   1553     pthread_mutex_lock(&out->pre_lock);
   1554     pthread_mutex_lock(&out->lock);
   1555     pthread_mutex_unlock(&out->pre_lock);
   1556 }
   1557 
   1558 /* must be called with out->lock locked */
   1559 static int send_offload_cmd_l(struct stream_out* out, int command)
   1560 {
   1561     struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));
   1562 
   1563     ALOGVV("%s %d", __func__, command);
   1564 
   1565     cmd->cmd = command;
   1566     list_add_tail(&out->offload_cmd_list, &cmd->node);
   1567     pthread_cond_signal(&out->offload_cond);
   1568     return 0;
   1569 }
   1570 
   1571 /* must be called iwth out->lock locked */
   1572 static void stop_compressed_output_l(struct stream_out *out)
   1573 {
   1574     out->offload_state = OFFLOAD_STATE_IDLE;
   1575     out->playback_started = 0;
   1576     out->send_new_metadata = 1;
   1577     if (out->compr != NULL) {
   1578         compress_stop(out->compr);
   1579         while (out->offload_thread_blocked) {
   1580             pthread_cond_wait(&out->cond, &out->lock);
   1581         }
   1582     }
   1583 }
   1584 
   1585 static void *offload_thread_loop(void *context)
   1586 {
   1587     struct stream_out *out = (struct stream_out *) context;
   1588     struct listnode *item;
   1589 
   1590     out->offload_state = OFFLOAD_STATE_IDLE;
   1591     out->playback_started = 0;
   1592 
   1593     setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
   1594     set_sched_policy(0, SP_FOREGROUND);
   1595     prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);
   1596 
   1597     ALOGV("%s", __func__);
   1598     lock_output_stream(out);
   1599     for (;;) {
   1600         struct offload_cmd *cmd = NULL;
   1601         stream_callback_event_t event;
   1602         bool send_callback = false;
   1603 
   1604         ALOGVV("%s offload_cmd_list %d out->offload_state %d",
   1605               __func__, list_empty(&out->offload_cmd_list),
   1606               out->offload_state);
   1607         if (list_empty(&out->offload_cmd_list)) {
   1608             ALOGV("%s SLEEPING", __func__);
   1609             pthread_cond_wait(&out->offload_cond, &out->lock);
   1610             ALOGV("%s RUNNING", __func__);
   1611             continue;
   1612         }
   1613 
   1614         item = list_head(&out->offload_cmd_list);
   1615         cmd = node_to_item(item, struct offload_cmd, node);
   1616         list_remove(item);
   1617 
   1618         ALOGVV("%s STATE %d CMD %d out->compr %p",
   1619                __func__, out->offload_state, cmd->cmd, out->compr);
   1620 
   1621         if (cmd->cmd == OFFLOAD_CMD_EXIT) {
   1622             free(cmd);
   1623             break;
   1624         }
   1625 
   1626         if (out->compr == NULL) {
   1627             ALOGE("%s: Compress handle is NULL", __func__);
   1628             free(cmd);
   1629             pthread_cond_signal(&out->cond);
   1630             continue;
   1631         }
   1632         out->offload_thread_blocked = true;
   1633         pthread_mutex_unlock(&out->lock);
   1634         send_callback = false;
   1635         switch(cmd->cmd) {
   1636         case OFFLOAD_CMD_WAIT_FOR_BUFFER:
   1637             compress_wait(out->compr, -1);
   1638             send_callback = true;
   1639             event = STREAM_CBK_EVENT_WRITE_READY;
   1640             break;
   1641         case OFFLOAD_CMD_PARTIAL_DRAIN:
   1642             compress_next_track(out->compr);
   1643             compress_partial_drain(out->compr);
   1644             send_callback = true;
   1645             event = STREAM_CBK_EVENT_DRAIN_READY;
   1646             /* Resend the metadata for next iteration */
   1647             out->send_new_metadata = 1;
   1648             break;
   1649         case OFFLOAD_CMD_DRAIN:
   1650             compress_drain(out->compr);
   1651             send_callback = true;
   1652             event = STREAM_CBK_EVENT_DRAIN_READY;
   1653             break;
   1654         case OFFLOAD_CMD_ERROR:
   1655             send_callback = true;
   1656             event = STREAM_CBK_EVENT_ERROR;
   1657             break;
   1658         default:
   1659             ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
   1660             break;
   1661         }
   1662         lock_output_stream(out);
   1663         out->offload_thread_blocked = false;
   1664         pthread_cond_signal(&out->cond);
   1665         if (send_callback) {
   1666             ALOGVV("%s: sending offload_callback event %d", __func__, event);
   1667             out->offload_callback(event, NULL, out->offload_cookie);
   1668         }
   1669         free(cmd);
   1670     }
   1671 
   1672     pthread_cond_signal(&out->cond);
   1673     while (!list_empty(&out->offload_cmd_list)) {
   1674         item = list_head(&out->offload_cmd_list);
   1675         list_remove(item);
   1676         free(node_to_item(item, struct offload_cmd, node));
   1677     }
   1678     pthread_mutex_unlock(&out->lock);
   1679 
   1680     return NULL;
   1681 }
   1682 
   1683 static int create_offload_callback_thread(struct stream_out *out)
   1684 {
   1685     pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
   1686     list_init(&out->offload_cmd_list);
   1687     pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
   1688                     offload_thread_loop, out);
   1689     return 0;
   1690 }
   1691 
   1692 static int destroy_offload_callback_thread(struct stream_out *out)
   1693 {
   1694     lock_output_stream(out);
   1695     stop_compressed_output_l(out);
   1696     send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);
   1697 
   1698     pthread_mutex_unlock(&out->lock);
   1699     pthread_join(out->offload_thread, (void **) NULL);
   1700     pthread_cond_destroy(&out->offload_cond);
   1701 
   1702     return 0;
   1703 }
   1704 
   1705 static bool allow_hdmi_channel_config(struct audio_device *adev)
   1706 {
   1707     struct listnode *node;
   1708     struct audio_usecase *usecase;
   1709     bool ret = true;
   1710 
   1711     list_for_each(node, &adev->usecase_list) {
   1712         usecase = node_to_item(node, struct audio_usecase, list);
   1713         if (usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
   1714             /*
   1715              * If voice call is already existing, do not proceed further to avoid
   1716              * disabling/enabling both RX and TX devices, CSD calls, etc.
   1717              * Once the voice call done, the HDMI channels can be configured to
   1718              * max channels of remaining use cases.
   1719              */
   1720             if (usecase->id == USECASE_VOICE_CALL) {
   1721                 ALOGV("%s: voice call is active, no change in HDMI channels",
   1722                       __func__);
   1723                 ret = false;
   1724                 break;
   1725             } else if (usecase->id == USECASE_AUDIO_PLAYBACK_HIFI) {
   1726                 ALOGV("%s: hifi playback is active, "
   1727                       "no change in HDMI channels", __func__);
   1728                 ret = false;
   1729                 break;
   1730             }
   1731         }
   1732     }
   1733     return ret;
   1734 }
   1735 
   1736 static int check_and_set_hdmi_channels(struct audio_device *adev,
   1737                                        unsigned int channels)
   1738 {
   1739     struct listnode *node;
   1740     struct audio_usecase *usecase;
   1741 
   1742     /* Check if change in HDMI channel config is allowed */
   1743     if (!allow_hdmi_channel_config(adev))
   1744         return 0;
   1745 
   1746     if (channels == adev->cur_hdmi_channels) {
   1747         ALOGV("%s: Requested channels are same as current", __func__);
   1748         return 0;
   1749     }
   1750 
   1751     platform_set_hdmi_channels(adev->platform, channels);
   1752     adev->cur_hdmi_channels = channels;
   1753 
   1754     /*
   1755      * Deroute all the playback streams routed to HDMI so that
   1756      * the back end is deactivated. Note that backend will not
   1757      * be deactivated if any one stream is connected to it.
   1758      */
   1759     list_for_each(node, &adev->usecase_list) {
   1760         usecase = node_to_item(node, struct audio_usecase, list);
   1761         if (usecase->type == PCM_PLAYBACK &&
   1762                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
   1763             disable_audio_route(adev, usecase);
   1764         }
   1765     }
   1766 
   1767     /*
   1768      * Enable all the streams disabled above. Now the HDMI backend
   1769      * will be activated with new channel configuration
   1770      */
   1771     list_for_each(node, &adev->usecase_list) {
   1772         usecase = node_to_item(node, struct audio_usecase, list);
   1773         if (usecase->type == PCM_PLAYBACK &&
   1774                 usecase->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL) {
   1775             enable_audio_route(adev, usecase);
   1776         }
   1777     }
   1778 
   1779     return 0;
   1780 }
   1781 
   1782 static int stop_output_stream(struct stream_out *out)
   1783 {
   1784     int i, ret = 0;
   1785     struct audio_usecase *uc_info;
   1786     struct audio_device *adev = out->dev;
   1787 
   1788     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   1789           out->usecase, use_case_table[out->usecase]);
   1790     uc_info = get_usecase_from_list(adev, out->usecase);
   1791     if (uc_info == NULL) {
   1792         ALOGE("%s: Could not find the usecase (%d) in the list",
   1793               __func__, out->usecase);
   1794         return -EINVAL;
   1795     }
   1796 
   1797     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1798         if (adev->visualizer_stop_output != NULL)
   1799             adev->visualizer_stop_output(out->handle, out->pcm_device_id);
   1800         if (adev->offload_effects_stop_output != NULL)
   1801             adev->offload_effects_stop_output(out->handle, out->pcm_device_id);
   1802     }
   1803 
   1804     /* 1. Get and set stream specific mixer controls */
   1805     disable_audio_route(adev, uc_info);
   1806 
   1807     /* 2. Disable the rx device */
   1808     disable_snd_device(adev, uc_info->out_snd_device);
   1809 
   1810     list_remove(&uc_info->list);
   1811     free(uc_info);
   1812 
   1813     audio_extn_extspk_update(adev->extspk);
   1814 
   1815     /* Must be called after removing the usecase from list */
   1816     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
   1817         check_and_set_hdmi_channels(adev, DEFAULT_HDMI_OUT_CHANNELS);
   1818     else if (out->devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
   1819         struct listnode *node;
   1820         struct audio_usecase *usecase;
   1821         list_for_each(node, &adev->usecase_list) {
   1822             usecase = node_to_item(node, struct audio_usecase, list);
   1823             if (usecase->devices & AUDIO_DEVICE_OUT_SPEAKER)
   1824                 select_devices(adev, usecase->id);
   1825         }
   1826     }
   1827 
   1828     ALOGV("%s: exit: status(%d)", __func__, ret);
   1829     return ret;
   1830 }
   1831 
   1832 int start_output_stream(struct stream_out *out)
   1833 {
   1834     int ret = 0;
   1835     struct audio_usecase *uc_info;
   1836     struct audio_device *adev = out->dev;
   1837 
   1838     ALOGV("%s: enter: usecase(%d: %s) devices(%#x)",
   1839           __func__, out->usecase, use_case_table[out->usecase], out->devices);
   1840 
   1841     if (out->card_status == CARD_STATUS_OFFLINE ||
   1842         adev->card_status == CARD_STATUS_OFFLINE) {
   1843         ALOGW("out->card_status or adev->card_status offline, try again");
   1844         ret = -EAGAIN;
   1845         goto error_config;
   1846     }
   1847 
   1848     out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
   1849     if (out->pcm_device_id < 0) {
   1850         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
   1851               __func__, out->pcm_device_id, out->usecase);
   1852         ret = -EINVAL;
   1853         goto error_config;
   1854     }
   1855 
   1856     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
   1857     uc_info->id = out->usecase;
   1858     uc_info->type = PCM_PLAYBACK;
   1859     uc_info->stream.out = out;
   1860     uc_info->devices = out->devices;
   1861     uc_info->in_snd_device = SND_DEVICE_NONE;
   1862     uc_info->out_snd_device = SND_DEVICE_NONE;
   1863 
   1864     /* This must be called before adding this usecase to the list */
   1865     if (out->devices & AUDIO_DEVICE_OUT_AUX_DIGITAL)
   1866         check_and_set_hdmi_channels(adev, out->config.channels);
   1867 
   1868     list_add_tail(&adev->usecase_list, &uc_info->list);
   1869 
   1870     audio_extn_perf_lock_acquire();
   1871 
   1872     select_devices(adev, out->usecase);
   1873 
   1874     audio_extn_extspk_update(adev->extspk);
   1875 
   1876     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d) format(%#x)",
   1877           __func__, adev->snd_card, out->pcm_device_id, out->config.format);
   1878     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   1879         out->pcm = NULL;
   1880         out->compr = compress_open(adev->snd_card, out->pcm_device_id,
   1881                                    COMPRESS_IN, &out->compr_config);
   1882         if (out->compr && !is_compress_ready(out->compr)) {
   1883             ALOGE("%s: %s", __func__, compress_get_error(out->compr));
   1884             compress_close(out->compr);
   1885             out->compr = NULL;
   1886             ret = -EIO;
   1887             goto error_open;
   1888         }
   1889         if (out->offload_callback)
   1890             compress_nonblock(out->compr, out->non_blocking);
   1891 
   1892         if (adev->visualizer_start_output != NULL)
   1893             adev->visualizer_start_output(out->handle, out->pcm_device_id);
   1894         if (adev->offload_effects_start_output != NULL)
   1895             adev->offload_effects_start_output(out->handle, out->pcm_device_id);
   1896     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
   1897         if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
   1898             ALOGE("%s: pcm stream not ready", __func__);
   1899             goto error_open;
   1900         }
   1901         ret = pcm_start(out->pcm);
   1902         if (ret < 0) {
   1903             ALOGE("%s: MMAP pcm_start failed ret %d", __func__, ret);
   1904             goto error_open;
   1905         }
   1906     } else {
   1907         unsigned int flags = PCM_OUT | PCM_MONOTONIC;
   1908         unsigned int pcm_open_retry_count = 0;
   1909 
   1910         if (out->usecase == USECASE_AUDIO_PLAYBACK_AFE_PROXY) {
   1911             flags |= PCM_MMAP | PCM_NOIRQ;
   1912             pcm_open_retry_count = PROXY_OPEN_RETRY_COUNT;
   1913         } else if (out->realtime) {
   1914             flags |= PCM_MMAP | PCM_NOIRQ;
   1915         }
   1916 
   1917         while (1) {
   1918             out->pcm = pcm_open(adev->snd_card, out->pcm_device_id,
   1919                                flags, &out->config);
   1920             if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
   1921                 ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
   1922                 if (out->pcm != NULL) {
   1923                     pcm_close(out->pcm);
   1924                     out->pcm = NULL;
   1925                 }
   1926                 if (pcm_open_retry_count-- == 0) {
   1927                     ret = -EIO;
   1928                     goto error_open;
   1929                 }
   1930                 usleep(PROXY_OPEN_WAIT_TIME * 1000);
   1931                 continue;
   1932             }
   1933             break;
   1934         }
   1935         ALOGV("%s: pcm_prepare", __func__);
   1936         if (pcm_is_ready(out->pcm)) {
   1937             ret = pcm_prepare(out->pcm);
   1938             if (ret < 0) {
   1939                 ALOGE("%s: pcm_prepare returned %d", __func__, ret);
   1940                 pcm_close(out->pcm);
   1941                 out->pcm = NULL;
   1942                 goto error_open;
   1943             }
   1944         }
   1945         if (out->realtime) {
   1946             ret = pcm_start(out->pcm);
   1947             if (ret < 0) {
   1948                 ALOGE("%s: RT pcm_start failed ret %d", __func__, ret);
   1949                 pcm_close(out->pcm);
   1950                 out->pcm = NULL;
   1951                 goto error_open;
   1952             }
   1953         }
   1954     }
   1955     register_out_stream(out);
   1956     audio_extn_perf_lock_release();
   1957     audio_extn_tfa_98xx_enable_speaker();
   1958 
   1959     // consider a scenario where on pause lower layers are tear down.
   1960     // so on resume, swap mixer control need to be sent only when
   1961     // backend is active, hence rather than sending from enable device
   1962     // sending it from start of streamtream
   1963 
   1964     platform_set_swap_channels(adev, true);
   1965 
   1966     ALOGV("%s: exit", __func__);
   1967     return 0;
   1968 error_open:
   1969     audio_extn_perf_lock_release();
   1970     stop_output_stream(out);
   1971 error_config:
   1972     return ret;
   1973 }
   1974 
   1975 static int check_input_parameters(uint32_t sample_rate,
   1976                                   audio_format_t format,
   1977                                   int channel_count, bool is_usb_hifi)
   1978 {
   1979     if ((format != AUDIO_FORMAT_PCM_16_BIT) &&
   1980         (format != AUDIO_FORMAT_PCM_8_24_BIT) &&
   1981         (format != AUDIO_FORMAT_PCM_24_BIT_PACKED) &&
   1982         !(is_usb_hifi && (format == AUDIO_FORMAT_PCM_32_BIT))) {
   1983         ALOGE("%s: unsupported AUDIO FORMAT (%d) ", __func__, format);
   1984         return -EINVAL;
   1985     }
   1986 
   1987     int max_channel_count = is_usb_hifi ? MAX_HIFI_CHANNEL_COUNT : MAX_CHANNEL_COUNT;
   1988     if ((channel_count < MIN_CHANNEL_COUNT) || (channel_count > max_channel_count)) {
   1989         ALOGE("%s: unsupported channel count (%d) passed  Min / Max (%d / %d)", __func__,
   1990                channel_count, MIN_CHANNEL_COUNT, max_channel_count);
   1991         return -EINVAL;
   1992     }
   1993 
   1994     switch (sample_rate) {
   1995     case 8000:
   1996     case 11025:
   1997     case 12000:
   1998     case 16000:
   1999     case 22050:
   2000     case 24000:
   2001     case 32000:
   2002     case 44100:
   2003     case 48000:
   2004     case 96000:
   2005         break;
   2006     default:
   2007         ALOGE("%s: unsupported (%d) samplerate passed ", __func__, sample_rate);
   2008         return -EINVAL;
   2009     }
   2010 
   2011     return 0;
   2012 }
   2013 
   2014 static size_t get_stream_buffer_size(size_t duration_ms,
   2015                                      uint32_t sample_rate,
   2016                                      audio_format_t format,
   2017                                      int channel_count,
   2018                                      bool is_low_latency)
   2019 {
   2020     size_t size = 0;
   2021 
   2022     size = (sample_rate * duration_ms) / 1000;
   2023     if (is_low_latency)
   2024         size = configured_low_latency_capture_period_size;
   2025 
   2026     size *= channel_count * audio_bytes_per_sample(format);
   2027 
   2028     /* make sure the size is multiple of 32 bytes
   2029      * At 48 kHz mono 16-bit PCM:
   2030      *  5.000 ms = 240 frames = 15*16*1*2 = 480, a whole multiple of 32 (15)
   2031      *  3.333 ms = 160 frames = 10*16*1*2 = 320, a whole multiple of 32 (10)
   2032      */
   2033     size += 0x1f;
   2034     size &= ~0x1f;
   2035 
   2036     return size;
   2037 }
   2038 
   2039 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
   2040 {
   2041     struct stream_out *out = (struct stream_out *)stream;
   2042 
   2043     return out->sample_rate;
   2044 }
   2045 
   2046 static int out_set_sample_rate(struct audio_stream *stream __unused, uint32_t rate __unused)
   2047 {
   2048     return -ENOSYS;
   2049 }
   2050 
   2051 static size_t out_get_buffer_size(const struct audio_stream *stream)
   2052 {
   2053     struct stream_out *out = (struct stream_out *)stream;
   2054 
   2055     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2056         return out->compr_config.fragment_size;
   2057     }
   2058     return out->config.period_size * out->af_period_multiplier *
   2059                 audio_stream_out_frame_size((const struct audio_stream_out *)stream);
   2060 }
   2061 
   2062 static uint32_t out_get_channels(const struct audio_stream *stream)
   2063 {
   2064     struct stream_out *out = (struct stream_out *)stream;
   2065 
   2066     return out->channel_mask;
   2067 }
   2068 
   2069 static audio_format_t out_get_format(const struct audio_stream *stream)
   2070 {
   2071     struct stream_out *out = (struct stream_out *)stream;
   2072 
   2073     return out->format;
   2074 }
   2075 
   2076 static int out_set_format(struct audio_stream *stream __unused, audio_format_t format __unused)
   2077 {
   2078     return -ENOSYS;
   2079 }
   2080 
   2081 /* must be called with out->lock locked */
   2082 static int out_standby_l(struct audio_stream *stream)
   2083 {
   2084     struct stream_out *out = (struct stream_out *)stream;
   2085     struct audio_device *adev = out->dev;
   2086     bool do_stop = true;
   2087 
   2088     if (!out->standby) {
   2089         if (adev->adm_deregister_stream)
   2090             adev->adm_deregister_stream(adev->adm_data, out->handle);
   2091         pthread_mutex_lock(&adev->lock);
   2092         out->standby = true;
   2093         if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2094             if (out->pcm) {
   2095                 pcm_close(out->pcm);
   2096                 out->pcm = NULL;
   2097             }
   2098             if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
   2099                 do_stop = out->playback_started;
   2100                 out->playback_started = false;
   2101             }
   2102         } else {
   2103             stop_compressed_output_l(out);
   2104             out->gapless_mdata.encoder_delay = 0;
   2105             out->gapless_mdata.encoder_padding = 0;
   2106             if (out->compr != NULL) {
   2107                 compress_close(out->compr);
   2108                 out->compr = NULL;
   2109             }
   2110         }
   2111         if (do_stop) {
   2112             stop_output_stream(out);
   2113         }
   2114         pthread_mutex_unlock(&adev->lock);
   2115     }
   2116     return 0;
   2117 }
   2118 
   2119 static int out_standby(struct audio_stream *stream)
   2120 {
   2121     struct stream_out *out = (struct stream_out *)stream;
   2122 
   2123     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   2124           out->usecase, use_case_table[out->usecase]);
   2125 
   2126     lock_output_stream(out);
   2127     out_standby_l(stream);
   2128     pthread_mutex_unlock(&out->lock);
   2129     ALOGV("%s: exit", __func__);
   2130     return 0;
   2131 }
   2132 
   2133 static int out_on_error(struct audio_stream *stream)
   2134 {
   2135     struct stream_out *out = (struct stream_out *)stream;
   2136     struct audio_device *adev = out->dev;
   2137     bool do_standby = false;
   2138 
   2139     lock_output_stream(out);
   2140     if (!out->standby) {
   2141         if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2142             stop_compressed_output_l(out);
   2143             send_offload_cmd_l(out, OFFLOAD_CMD_ERROR);
   2144         } else
   2145             do_standby = true;
   2146     }
   2147     pthread_mutex_unlock(&out->lock);
   2148 
   2149     if (do_standby)
   2150         return out_standby(&out->stream.common);
   2151 
   2152     return 0;
   2153 }
   2154 
   2155 static int out_dump(const struct audio_stream *stream, int fd)
   2156 {
   2157     struct stream_out *out = (struct stream_out *)stream;
   2158 
   2159     // We try to get the lock for consistency,
   2160     // but it isn't necessary for these variables.
   2161     // If we're not in standby, we may be blocked on a write.
   2162     const bool locked = (pthread_mutex_trylock(&out->lock) == 0);
   2163     dprintf(fd, "      Standby: %s\n", out->standby ? "yes" : "no");
   2164     dprintf(fd, "      Frames written: %lld\n", (long long)out->written);
   2165 
   2166     if (locked) {
   2167         pthread_mutex_unlock(&out->lock);
   2168     }
   2169 
   2170     // dump error info
   2171     (void)error_log_dump(
   2172             out->error_log, fd, "      " /* prefix */, 0 /* lines */, 0 /* limit_ns */);
   2173 
   2174     return 0;
   2175 }
   2176 
   2177 static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
   2178 {
   2179     int ret = 0;
   2180     char value[32];
   2181     struct compr_gapless_mdata tmp_mdata;
   2182 
   2183     if (!out || !parms) {
   2184         return -EINVAL;
   2185     }
   2186 
   2187     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
   2188     if (ret >= 0) {
   2189         tmp_mdata.encoder_delay = atoi(value); //whats a good limit check?
   2190     } else {
   2191         return -EINVAL;
   2192     }
   2193 
   2194     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
   2195     if (ret >= 0) {
   2196         tmp_mdata.encoder_padding = atoi(value);
   2197     } else {
   2198         return -EINVAL;
   2199     }
   2200 
   2201     out->gapless_mdata = tmp_mdata;
   2202     out->send_new_metadata = 1;
   2203     ALOGV("%s new encoder delay %u and padding %u", __func__,
   2204           out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);
   2205 
   2206     return 0;
   2207 }
   2208 
   2209 static bool output_drives_call(struct audio_device *adev, struct stream_out *out)
   2210 {
   2211     return out == adev->primary_output || out == adev->voice_tx_output;
   2212 }
   2213 
   2214 static int get_alive_usb_card(struct str_parms* parms) {
   2215     int card;
   2216     if ((str_parms_get_int(parms, "card", &card) >= 0) &&
   2217         !audio_extn_usb_alive(card)) {
   2218         return card;
   2219     }
   2220     return -ENODEV;
   2221 }
   2222 
   2223 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
   2224 {
   2225     struct stream_out *out = (struct stream_out *)stream;
   2226     struct audio_device *adev = out->dev;
   2227     struct audio_usecase *usecase;
   2228     struct listnode *node;
   2229     struct str_parms *parms;
   2230     char value[32];
   2231     int ret, val = 0;
   2232     bool select_new_device = false;
   2233     int status = 0;
   2234 
   2235     ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s",
   2236           __func__, out->usecase, use_case_table[out->usecase], kvpairs);
   2237     parms = str_parms_create_str(kvpairs);
   2238     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
   2239     if (ret >= 0) {
   2240         val = atoi(value);
   2241 
   2242         lock_output_stream(out);
   2243 
   2244         // The usb driver needs to be closed after usb device disconnection
   2245         // otherwise audio is no longer played on the new usb devices.
   2246         // By forcing the stream in standby, the usb stack refcount drops to 0
   2247         // and the driver is closed.
   2248         if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD && val == AUDIO_DEVICE_NONE &&
   2249                 audio_is_usb_out_device(out->devices)) {
   2250             ALOGD("%s() putting the usb device in standby after disconnection", __func__);
   2251             out_standby_l(&out->stream.common);
   2252         }
   2253 
   2254         pthread_mutex_lock(&adev->lock);
   2255 
   2256         /*
   2257          * When HDMI cable is unplugged the music playback is paused and
   2258          * the policy manager sends routing=0. But the audioflinger
   2259          * continues to write data until standby time (3sec).
   2260          * As the HDMI core is turned off, the write gets blocked.
   2261          * Avoid this by routing audio to speaker until standby.
   2262          */
   2263         if (out->devices == AUDIO_DEVICE_OUT_AUX_DIGITAL &&
   2264                 val == AUDIO_DEVICE_NONE) {
   2265             val = AUDIO_DEVICE_OUT_SPEAKER;
   2266         }
   2267 
   2268         audio_devices_t new_dev = val;
   2269 
   2270         // Workaround: If routing to an non existing usb device, fail gracefully
   2271         // The routing request will otherwise block during 10 second
   2272         int card;
   2273         if (audio_is_usb_out_device(new_dev) &&
   2274             (card = get_alive_usb_card(parms)) >= 0) {
   2275 
   2276             ALOGW("out_set_parameters() ignoring rerouting to non existing USB card %d", card);
   2277             pthread_mutex_unlock(&adev->lock);
   2278             pthread_mutex_unlock(&out->lock);
   2279             status = -ENOSYS;
   2280             goto routing_fail;
   2281         }
   2282 
   2283         /*
   2284          * select_devices() call below switches all the usecases on the same
   2285          * backend to the new device. Refer to check_and_route_playback_usecases() in
   2286          * the select_devices(). But how do we undo this?
   2287          *
   2288          * For example, music playback is active on headset (deep-buffer usecase)
   2289          * and if we go to ringtones and select a ringtone, low-latency usecase
   2290          * will be started on headset+speaker. As we can't enable headset+speaker
   2291          * and headset devices at the same time, select_devices() switches the music
   2292          * playback to headset+speaker while starting low-lateny usecase for ringtone.
   2293          * So when the ringtone playback is completed, how do we undo the same?
   2294          *
   2295          * We are relying on the out_set_parameters() call on deep-buffer output,
   2296          * once the ringtone playback is ended.
   2297          * NOTE: We should not check if the current devices are same as new devices.
   2298          *       Because select_devices() must be called to switch back the music
   2299          *       playback to headset.
   2300          */
   2301         if (new_dev != AUDIO_DEVICE_NONE) {
   2302             bool same_dev = out->devices == new_dev;
   2303             out->devices = new_dev;
   2304 
   2305             if (output_drives_call(adev, out)) {
   2306                 if (!voice_is_in_call(adev)) {
   2307                     if (adev->mode == AUDIO_MODE_IN_CALL) {
   2308                         adev->current_call_output = out;
   2309                         ret = voice_start_call(adev);
   2310                     }
   2311                 } else {
   2312                     adev->current_call_output = out;
   2313                     voice_update_devices_for_all_voice_usecases(adev);
   2314                 }
   2315             }
   2316 
   2317             if (!out->standby) {
   2318                 if (!same_dev) {
   2319                     ALOGV("update routing change");
   2320                     // inform adm before actual routing to prevent glitches.
   2321                     if (adev->adm_on_routing_change) {
   2322                         adev->adm_on_routing_change(adev->adm_data,
   2323                                                     out->handle);
   2324                     }
   2325                 }
   2326                 select_devices(adev, out->usecase);
   2327                 audio_extn_tfa_98xx_update();
   2328 
   2329                 // on device switch force swap, lower functions will make sure
   2330                 // to check if swap is allowed or not.
   2331 
   2332                 if (!same_dev)
   2333                     platform_set_swap_channels(adev, true);
   2334             }
   2335 
   2336         }
   2337 
   2338         pthread_mutex_unlock(&adev->lock);
   2339         pthread_mutex_unlock(&out->lock);
   2340 
   2341         /*handles device and call state changes*/
   2342         audio_extn_extspk_update(adev->extspk);
   2343     }
   2344     routing_fail:
   2345 
   2346     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2347         parse_compress_metadata(out, parms);
   2348     }
   2349 
   2350     str_parms_destroy(parms);
   2351     ALOGV("%s: exit: code(%d)", __func__, status);
   2352     return status;
   2353 }
   2354 
   2355 static bool stream_get_parameter_channels(struct str_parms *query,
   2356                                           struct str_parms *reply,
   2357                                           audio_channel_mask_t *supported_channel_masks) {
   2358     int ret = -1;
   2359     char value[256];
   2360     bool first = true;
   2361     size_t i, j;
   2362 
   2363     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
   2364         ret = 0;
   2365         value[0] = '\0';
   2366         i = 0;
   2367         while (supported_channel_masks[i] != 0) {
   2368             for (j = 0; j < ARRAY_SIZE(channels_name_to_enum_table); j++) {
   2369                 if (channels_name_to_enum_table[j].value == supported_channel_masks[i]) {
   2370                     if (!first) {
   2371                         strcat(value, "|");
   2372                     }
   2373                     strcat(value, channels_name_to_enum_table[j].name);
   2374                     first = false;
   2375                     break;
   2376                 }
   2377             }
   2378             i++;
   2379         }
   2380         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
   2381     }
   2382     return ret >= 0;
   2383 }
   2384 
   2385 static bool stream_get_parameter_formats(struct str_parms *query,
   2386                                          struct str_parms *reply,
   2387                                          audio_format_t *supported_formats) {
   2388     int ret = -1;
   2389     char value[256];
   2390     int i;
   2391 
   2392     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
   2393         ret = 0;
   2394         value[0] = '\0';
   2395         switch (supported_formats[0]) {
   2396             case AUDIO_FORMAT_PCM_16_BIT:
   2397                 strcat(value, "AUDIO_FORMAT_PCM_16_BIT");
   2398                 break;
   2399             case AUDIO_FORMAT_PCM_24_BIT_PACKED:
   2400                 strcat(value, "AUDIO_FORMAT_PCM_24_BIT_PACKED");
   2401                 break;
   2402             case AUDIO_FORMAT_PCM_32_BIT:
   2403                 strcat(value, "AUDIO_FORMAT_PCM_32_BIT");
   2404                 break;
   2405             default:
   2406                 ALOGE("%s: unsupported format %#x", __func__,
   2407                       supported_formats[0]);
   2408                 break;
   2409         }
   2410         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_FORMATS, value);
   2411     }
   2412     return ret >= 0;
   2413 }
   2414 
   2415 static bool stream_get_parameter_rates(struct str_parms *query,
   2416                                        struct str_parms *reply,
   2417                                        uint32_t *supported_sample_rates) {
   2418 
   2419     int i;
   2420     char value[256];
   2421     int ret = -1;
   2422     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
   2423         ret = 0;
   2424         value[0] = '\0';
   2425         i=0;
   2426         int cursor = 0;
   2427         while (supported_sample_rates[i]) {
   2428             int avail = sizeof(value) - cursor;
   2429             ret = snprintf(value + cursor, avail, "%s%d",
   2430                            cursor > 0 ? "|" : "",
   2431                            supported_sample_rates[i]);
   2432             if (ret < 0 || ret >= avail) {
   2433                 // if cursor is at the last element of the array
   2434                 //    overwrite with \0 is duplicate work as
   2435                 //    snprintf already put a \0 in place.
   2436                 // else
   2437                 //    we had space to write the '|' at value[cursor]
   2438                 //    (which will be overwritten) or no space to fill
   2439                 //    the first element (=> cursor == 0)
   2440                 value[cursor] = '\0';
   2441                 break;
   2442             }
   2443             cursor += ret;
   2444             ++i;
   2445         }
   2446         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES,
   2447                           value);
   2448     }
   2449     return ret >= 0;
   2450 }
   2451 
   2452 static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
   2453 {
   2454     struct stream_out *out = (struct stream_out *)stream;
   2455     struct str_parms *query = str_parms_create_str(keys);
   2456     char *str;
   2457     struct str_parms *reply = str_parms_create();
   2458     bool replied = false;
   2459     ALOGV("%s: enter: keys - %s", __func__, keys);
   2460 
   2461     replied |= stream_get_parameter_channels(query, reply,
   2462                                              &out->supported_channel_masks[0]);
   2463     replied |= stream_get_parameter_formats(query, reply,
   2464                                             &out->supported_formats[0]);
   2465     replied |= stream_get_parameter_rates(query, reply,
   2466                                           &out->supported_sample_rates[0]);
   2467     if (replied) {
   2468         str = str_parms_to_str(reply);
   2469     } else {
   2470         str = strdup("");
   2471     }
   2472     str_parms_destroy(query);
   2473     str_parms_destroy(reply);
   2474     ALOGV("%s: exit: returns - %s", __func__, str);
   2475     return str;
   2476 }
   2477 
   2478 static uint32_t out_get_latency(const struct audio_stream_out *stream)
   2479 {
   2480     uint32_t hw_delay, period_ms;
   2481     struct stream_out *out = (struct stream_out *)stream;
   2482 
   2483     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
   2484         return COMPRESS_OFFLOAD_PLAYBACK_LATENCY;
   2485     else if ((out->realtime) ||
   2486             (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP)) {
   2487         // since the buffer won't be filled up faster than realtime,
   2488         // return a smaller number
   2489         period_ms = (out->af_period_multiplier * out->config.period_size *
   2490                      1000) / (out->config.rate);
   2491         hw_delay = platform_render_latency(out->usecase)/1000;
   2492         return period_ms + hw_delay;
   2493     }
   2494 
   2495     return (out->config.period_count * out->config.period_size * 1000) /
   2496            (out->config.rate);
   2497 }
   2498 
   2499 static int out_set_volume(struct audio_stream_out *stream, float left,
   2500                           float right)
   2501 {
   2502     struct stream_out *out = (struct stream_out *)stream;
   2503     int volume[2];
   2504 
   2505     if (out->usecase == USECASE_AUDIO_PLAYBACK_HIFI) {
   2506         /* only take left channel into account: the API is for stereo anyway */
   2507         out->muted = (left == 0.0f);
   2508         return 0;
   2509     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2510         const char *mixer_ctl_name = "Compress Playback Volume";
   2511         struct audio_device *adev = out->dev;
   2512         struct mixer_ctl *ctl;
   2513         ctl = mixer_get_ctl_by_name(adev->mixer, mixer_ctl_name);
   2514         if (!ctl) {
   2515             /* try with the control based on device id */
   2516             int pcm_device_id = platform_get_pcm_device_id(out->usecase,
   2517                                                        PCM_PLAYBACK);
   2518             char ctl_name[128] = {0};
   2519             snprintf(ctl_name, sizeof(ctl_name),
   2520                      "Compress Playback %d Volume", pcm_device_id);
   2521             ctl = mixer_get_ctl_by_name(adev->mixer, ctl_name);
   2522             if (!ctl) {
   2523                 ALOGE("%s: Could not get volume ctl mixer cmd", __func__);
   2524                 return -EINVAL;
   2525             }
   2526         }
   2527         volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
   2528         volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
   2529         mixer_ctl_set_array(ctl, volume, sizeof(volume)/sizeof(volume[0]));
   2530         return 0;
   2531     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP) {
   2532         out->app_type_cfg.gain[0] = (int)(left * VOIP_PLAYBACK_VOLUME_MAX);
   2533         out->app_type_cfg.gain[1] = (int)(right * VOIP_PLAYBACK_VOLUME_MAX);
   2534         if (!out->standby) {
   2535             // if in standby, cached volume will be sent after stream is opened
   2536             audio_extn_utils_send_app_type_gain(out->dev,
   2537                                                 out->app_type_cfg.app_type,
   2538                                                 &out->app_type_cfg.gain[0]);
   2539         }
   2540         return 0;
   2541     }
   2542 
   2543     return -ENOSYS;
   2544 }
   2545 
   2546 // note: this call is safe only if the stream_cb is
   2547 // removed first in close_output_stream (as is done now).
   2548 static void out_snd_mon_cb(void * stream, struct str_parms * parms)
   2549 {
   2550     if (!stream || !parms)
   2551         return;
   2552 
   2553     struct stream_out *out = (struct stream_out *)stream;
   2554     struct audio_device *adev = out->dev;
   2555 
   2556     card_status_t status;
   2557     int card;
   2558     if (parse_snd_card_status(parms, &card, &status) < 0)
   2559         return;
   2560 
   2561     pthread_mutex_lock(&adev->lock);
   2562     bool valid_cb = (card == adev->snd_card);
   2563     pthread_mutex_unlock(&adev->lock);
   2564 
   2565     if (!valid_cb)
   2566         return;
   2567 
   2568     lock_output_stream(out);
   2569     if (out->card_status != status)
   2570         out->card_status = status;
   2571     pthread_mutex_unlock(&out->lock);
   2572 
   2573     ALOGW("out_snd_mon_cb for card %d usecase %s, status %s", card,
   2574           use_case_table[out->usecase],
   2575           status == CARD_STATUS_OFFLINE ? "offline" : "online");
   2576 
   2577     if (status == CARD_STATUS_OFFLINE)
   2578         out_on_error(stream);
   2579 
   2580     return;
   2581 }
   2582 
   2583 #ifdef NO_AUDIO_OUT
   2584 static ssize_t out_write_for_no_output(struct audio_stream_out *stream,
   2585                                        const void *buffer __unused, size_t bytes)
   2586 {
   2587     struct stream_out *out = (struct stream_out *)stream;
   2588 
   2589     /* No Output device supported other than BT for playback.
   2590      * Sleep for the amount of buffer duration
   2591      */
   2592     lock_output_stream(out);
   2593     usleep(bytes * 1000000 / audio_stream_out_frame_size(
   2594             (const struct audio_stream_out *)&out->stream) /
   2595             out_get_sample_rate(&out->stream.common));
   2596     pthread_mutex_unlock(&out->lock);
   2597     return bytes;
   2598 }
   2599 #endif
   2600 
   2601 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
   2602                          size_t bytes)
   2603 {
   2604     struct stream_out *out = (struct stream_out *)stream;
   2605     struct audio_device *adev = out->dev;
   2606     ssize_t ret = 0;
   2607     int error_code = ERROR_CODE_STANDBY;
   2608 
   2609     lock_output_stream(out);
   2610     // this is always nonzero
   2611     const size_t frame_size = audio_stream_out_frame_size(stream);
   2612     const size_t frames = bytes / frame_size;
   2613 
   2614     if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP) {
   2615         error_code = ERROR_CODE_WRITE;
   2616         goto exit;
   2617     }
   2618     if (out->standby) {
   2619         out->standby = false;
   2620         pthread_mutex_lock(&adev->lock);
   2621         ret = start_output_stream(out);
   2622 
   2623         /* ToDo: If use case is compress offload should return 0 */
   2624         if (ret != 0) {
   2625             out->standby = true;
   2626             pthread_mutex_unlock(&adev->lock);
   2627             goto exit;
   2628         }
   2629 
   2630         // after standby always force set last known cal step
   2631         // dont change level anywhere except at the audio_hw_send_gain_dep_calibration
   2632         ALOGD("%s: retry previous failed cal level set", __func__);
   2633         send_gain_dep_calibration_l();
   2634         pthread_mutex_unlock(&adev->lock);
   2635     }
   2636 
   2637     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2638         ALOGVV("%s: writing buffer (%zu bytes) to compress device", __func__, bytes);
   2639         if (out->send_new_metadata) {
   2640             ALOGVV("send new gapless metadata");
   2641             compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
   2642             out->send_new_metadata = 0;
   2643         }
   2644         unsigned int avail;
   2645         struct timespec tstamp;
   2646         ret = compress_get_hpointer(out->compr, &avail, &tstamp);
   2647         /* Do not limit write size if the available frames count is unknown */
   2648         if (ret != 0) {
   2649             avail = bytes;
   2650         }
   2651         if (avail == 0) {
   2652             ret = 0;
   2653         } else {
   2654             if (avail > bytes) {
   2655                 avail = bytes;
   2656             }
   2657             ret = compress_write(out->compr, buffer, avail);
   2658             ALOGVV("%s: writing buffer (%d bytes) to compress device returned %zd",
   2659                    __func__, avail, ret);
   2660         }
   2661 
   2662         if (ret >= 0 && ret < (ssize_t)bytes) {
   2663             send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
   2664         }
   2665         if (ret > 0 && !out->playback_started) {
   2666             compress_start(out->compr);
   2667             out->playback_started = 1;
   2668             out->offload_state = OFFLOAD_STATE_PLAYING;
   2669         }
   2670         if (ret < 0) {
   2671             error_log_log(out->error_log, ERROR_CODE_WRITE, audio_utils_get_real_time_ns());
   2672         } else {
   2673             out->written += ret; // accumulate bytes written for offload.
   2674         }
   2675         pthread_mutex_unlock(&out->lock);
   2676         // TODO: consider logging offload pcm
   2677         return ret;
   2678     } else {
   2679         error_code = ERROR_CODE_WRITE;
   2680         if (out->pcm) {
   2681             size_t bytes_to_write = bytes;
   2682 
   2683             if (out->muted)
   2684                 memset((void *)buffer, 0, bytes);
   2685             // FIXME: this can be removed once audio flinger mixer supports mono output
   2686             if (out->usecase == USECASE_AUDIO_PLAYBACK_VOIP) {
   2687                 size_t channel_count = audio_channel_count_from_out_mask(out->channel_mask);
   2688                 int16_t *src = (int16_t *)buffer;
   2689                 int16_t *dst = (int16_t *)buffer;
   2690 
   2691                 LOG_ALWAYS_FATAL_IF(out->config.channels != 1 || channel_count != 2 ||
   2692                                     out->format != AUDIO_FORMAT_PCM_16_BIT,
   2693                                     "out_write called for VOIP use case with wrong properties");
   2694 
   2695                 for (size_t i = 0; i < frames ; i++, dst++, src += 2) {
   2696                     *dst = (int16_t)(((int32_t)src[0] + (int32_t)src[1]) >> 1);
   2697                 }
   2698                 bytes_to_write /= 2;
   2699             }
   2700             ALOGVV("%s: writing buffer (%zu bytes) to pcm device", __func__, bytes_to_write);
   2701 
   2702             long ns = (frames * NANOS_PER_SECOND) / out->config.rate;
   2703             request_out_focus(out, ns);
   2704 
   2705             bool use_mmap = is_mmap_usecase(out->usecase) || out->realtime;
   2706             if (use_mmap)
   2707                 ret = pcm_mmap_write(out->pcm, (void *)buffer, bytes_to_write);
   2708             else
   2709                 ret = pcm_write(out->pcm, (void *)buffer, bytes_to_write);
   2710 
   2711             release_out_focus(out, ns);
   2712         } else {
   2713             LOG_ALWAYS_FATAL("out->pcm is NULL after starting output stream");
   2714         }
   2715     }
   2716 
   2717 exit:
   2718     // For PCM we always consume the buffer and return #bytes regardless of ret.
   2719     if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2720         out->written += frames;
   2721     }
   2722     long long sleeptime_us = 0;
   2723 
   2724     if (ret != 0) {
   2725         error_log_log(out->error_log, error_code, audio_utils_get_real_time_ns());
   2726         if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2727             ALOGE_IF(out->pcm != NULL,
   2728                     "%s: error %zd - %s", __func__, ret, pcm_get_error(out->pcm));
   2729             sleeptime_us = frames * 1000000LL / out_get_sample_rate(&out->stream.common);
   2730             // usleep not guaranteed for values over 1 second but we don't limit here.
   2731         }
   2732     }
   2733 
   2734     pthread_mutex_unlock(&out->lock);
   2735 
   2736     if (ret != 0) {
   2737         out_on_error(&out->stream.common);
   2738         if (sleeptime_us != 0)
   2739             usleep(sleeptime_us);
   2740     }
   2741     return bytes;
   2742 }
   2743 
   2744 static int out_get_render_position(const struct audio_stream_out *stream,
   2745                                    uint32_t *dsp_frames)
   2746 {
   2747     struct stream_out *out = (struct stream_out *)stream;
   2748     *dsp_frames = 0;
   2749     if ((out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) && (dsp_frames != NULL)) {
   2750         lock_output_stream(out);
   2751         if (out->compr != NULL) {
   2752             unsigned long frames = 0;
   2753             // TODO: check return value
   2754             compress_get_tstamp(out->compr, &frames, &out->sample_rate);
   2755             *dsp_frames = (uint32_t)frames;
   2756             ALOGVV("%s rendered frames %d sample_rate %d",
   2757                    __func__, *dsp_frames, out->sample_rate);
   2758         }
   2759         pthread_mutex_unlock(&out->lock);
   2760         return 0;
   2761     } else
   2762         return -ENODATA;
   2763 }
   2764 
   2765 static int out_add_audio_effect(const struct audio_stream *stream __unused,
   2766                                 effect_handle_t effect __unused)
   2767 {
   2768     return 0;
   2769 }
   2770 
   2771 static int out_remove_audio_effect(const struct audio_stream *stream __unused,
   2772                                    effect_handle_t effect __unused)
   2773 {
   2774     return 0;
   2775 }
   2776 
   2777 static int out_get_next_write_timestamp(const struct audio_stream_out *stream __unused,
   2778                                         int64_t *timestamp __unused)
   2779 {
   2780     return -ENOSYS;
   2781 }
   2782 
   2783 static int out_get_presentation_position(const struct audio_stream_out *stream,
   2784                                    uint64_t *frames, struct timespec *timestamp)
   2785 {
   2786     struct stream_out *out = (struct stream_out *)stream;
   2787     int ret = -ENODATA;
   2788     unsigned long dsp_frames;
   2789 
   2790     lock_output_stream(out);
   2791 
   2792     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2793         if (out->compr != NULL) {
   2794             // TODO: check return value
   2795             compress_get_tstamp(out->compr, &dsp_frames,
   2796                     &out->sample_rate);
   2797             ALOGVV("%s rendered frames %ld sample_rate %d",
   2798                    __func__, dsp_frames, out->sample_rate);
   2799             *frames = dsp_frames;
   2800             ret = 0;
   2801             /* this is the best we can do */
   2802             clock_gettime(CLOCK_MONOTONIC, timestamp);
   2803         }
   2804     } else {
   2805         if (out->pcm) {
   2806             unsigned int avail;
   2807             if (pcm_get_htimestamp(out->pcm, &avail, timestamp) == 0) {
   2808                 size_t kernel_buffer_size = out->config.period_size * out->config.period_count;
   2809                 int64_t signed_frames = out->written - kernel_buffer_size + avail;
   2810                 // This adjustment accounts for buffering after app processor.
   2811                 // It is based on estimated DSP latency per use case, rather than exact.
   2812                 signed_frames -=
   2813                     (platform_render_latency(out->usecase) * out->sample_rate / 1000000LL);
   2814 
   2815                 // It would be unusual for this value to be negative, but check just in case ...
   2816                 if (signed_frames >= 0) {
   2817                     *frames = signed_frames;
   2818                     ret = 0;
   2819                 }
   2820             }
   2821         }
   2822     }
   2823 
   2824     pthread_mutex_unlock(&out->lock);
   2825 
   2826     return ret;
   2827 }
   2828 
   2829 static int out_set_callback(struct audio_stream_out *stream,
   2830             stream_callback_t callback, void *cookie)
   2831 {
   2832     struct stream_out *out = (struct stream_out *)stream;
   2833 
   2834     ALOGV("%s", __func__);
   2835     lock_output_stream(out);
   2836     out->offload_callback = callback;
   2837     out->offload_cookie = cookie;
   2838     pthread_mutex_unlock(&out->lock);
   2839     return 0;
   2840 }
   2841 
   2842 static int out_pause(struct audio_stream_out* stream)
   2843 {
   2844     struct stream_out *out = (struct stream_out *)stream;
   2845     int status = -ENOSYS;
   2846     ALOGV("%s", __func__);
   2847     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2848         lock_output_stream(out);
   2849         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
   2850             status = compress_pause(out->compr);
   2851             out->offload_state = OFFLOAD_STATE_PAUSED;
   2852         }
   2853         pthread_mutex_unlock(&out->lock);
   2854     }
   2855     return status;
   2856 }
   2857 
   2858 static int out_resume(struct audio_stream_out* stream)
   2859 {
   2860     struct stream_out *out = (struct stream_out *)stream;
   2861     int status = -ENOSYS;
   2862     ALOGV("%s", __func__);
   2863     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2864         status = 0;
   2865         lock_output_stream(out);
   2866         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
   2867             status = compress_resume(out->compr);
   2868             out->offload_state = OFFLOAD_STATE_PLAYING;
   2869         }
   2870         pthread_mutex_unlock(&out->lock);
   2871     }
   2872     return status;
   2873 }
   2874 
   2875 static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
   2876 {
   2877     struct stream_out *out = (struct stream_out *)stream;
   2878     int status = -ENOSYS;
   2879     ALOGV("%s", __func__);
   2880     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2881         lock_output_stream(out);
   2882         if (type == AUDIO_DRAIN_EARLY_NOTIFY)
   2883             status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
   2884         else
   2885             status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
   2886         pthread_mutex_unlock(&out->lock);
   2887     }
   2888     return status;
   2889 }
   2890 
   2891 static int out_flush(struct audio_stream_out* stream)
   2892 {
   2893     struct stream_out *out = (struct stream_out *)stream;
   2894     ALOGV("%s", __func__);
   2895     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2896         lock_output_stream(out);
   2897         stop_compressed_output_l(out);
   2898         pthread_mutex_unlock(&out->lock);
   2899         return 0;
   2900     }
   2901     return -ENOSYS;
   2902 }
   2903 
   2904 static int out_stop(const struct audio_stream_out* stream)
   2905 {
   2906     struct stream_out *out = (struct stream_out *)stream;
   2907     struct audio_device *adev = out->dev;
   2908     int ret = -ENOSYS;
   2909 
   2910     ALOGV("%s", __func__);
   2911     pthread_mutex_lock(&adev->lock);
   2912     if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP && !out->standby &&
   2913             out->playback_started && out->pcm != NULL) {
   2914         pcm_stop(out->pcm);
   2915         ret = stop_output_stream(out);
   2916         out->playback_started = false;
   2917     }
   2918     pthread_mutex_unlock(&adev->lock);
   2919     return ret;
   2920 }
   2921 
   2922 static int out_start(const struct audio_stream_out* stream)
   2923 {
   2924     struct stream_out *out = (struct stream_out *)stream;
   2925     struct audio_device *adev = out->dev;
   2926     int ret = -ENOSYS;
   2927 
   2928     ALOGV("%s", __func__);
   2929     pthread_mutex_lock(&adev->lock);
   2930     if (out->usecase == USECASE_AUDIO_PLAYBACK_MMAP && !out->standby &&
   2931             !out->playback_started && out->pcm != NULL) {
   2932         ret = start_output_stream(out);
   2933         if (ret == 0) {
   2934             out->playback_started = true;
   2935         }
   2936     }
   2937     pthread_mutex_unlock(&adev->lock);
   2938     return ret;
   2939 }
   2940 
   2941 /*
   2942  * Modify config->period_count based on min_size_frames
   2943  */
   2944 static void adjust_mmap_period_count(struct pcm_config *config, int32_t min_size_frames)
   2945 {
   2946     int periodCountRequested = (min_size_frames + config->period_size - 1)
   2947                                / config->period_size;
   2948     int periodCount = MMAP_PERIOD_COUNT_MIN;
   2949 
   2950     ALOGV("%s original config.period_size = %d config.period_count = %d",
   2951           __func__, config->period_size, config->period_count);
   2952 
   2953     while (periodCount < periodCountRequested && (periodCount * 2) < MMAP_PERIOD_COUNT_MAX) {
   2954         periodCount *= 2;
   2955     }
   2956     config->period_count = periodCount;
   2957 
   2958     ALOGV("%s requested config.period_count = %d", __func__, config->period_count);
   2959 }
   2960 
   2961 static int out_create_mmap_buffer(const struct audio_stream_out *stream,
   2962                                   int32_t min_size_frames,
   2963                                   struct audio_mmap_buffer_info *info)
   2964 {
   2965     struct stream_out *out = (struct stream_out *)stream;
   2966     struct audio_device *adev = out->dev;
   2967     int ret = 0;
   2968     unsigned int offset1;
   2969     unsigned int frames1;
   2970     const char *step = "";
   2971     uint32_t mmap_size;
   2972     uint32_t buffer_size;
   2973 
   2974     ALOGV("%s", __func__);
   2975     pthread_mutex_lock(&adev->lock);
   2976 
   2977     if (info == NULL || min_size_frames == 0) {
   2978         ALOGE("%s: info = %p, min_size_frames = %d", __func__, info, min_size_frames);
   2979         ret = -EINVAL;
   2980         goto exit;
   2981     }
   2982     if (out->usecase != USECASE_AUDIO_PLAYBACK_MMAP || !out->standby) {
   2983         ALOGE("%s: usecase = %d, standby = %d", __func__, out->usecase, out->standby);
   2984         ret = -ENOSYS;
   2985         goto exit;
   2986     }
   2987     out->pcm_device_id = platform_get_pcm_device_id(out->usecase, PCM_PLAYBACK);
   2988     if (out->pcm_device_id < 0) {
   2989         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
   2990               __func__, out->pcm_device_id, out->usecase);
   2991         ret = -EINVAL;
   2992         goto exit;
   2993     }
   2994 
   2995     adjust_mmap_period_count(&out->config, min_size_frames);
   2996 
   2997     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
   2998           __func__, adev->snd_card, out->pcm_device_id, out->config.channels);
   2999     out->pcm = pcm_open(adev->snd_card, out->pcm_device_id,
   3000                         (PCM_OUT | PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC), &out->config);
   3001     if (out->pcm == NULL || !pcm_is_ready(out->pcm)) {
   3002         step = "open";
   3003         ret = -ENODEV;
   3004         goto exit;
   3005     }
   3006     ret = pcm_mmap_begin(out->pcm, &info->shared_memory_address, &offset1, &frames1);
   3007     if (ret < 0)  {
   3008         step = "begin";
   3009         goto exit;
   3010     }
   3011     info->buffer_size_frames = pcm_get_buffer_size(out->pcm);
   3012     buffer_size = pcm_frames_to_bytes(out->pcm, info->buffer_size_frames);
   3013     info->burst_size_frames = out->config.period_size;
   3014     ret = platform_get_mmap_data_fd(adev->platform,
   3015                                     out->pcm_device_id, 0 /*playback*/,
   3016                                     &info->shared_memory_fd,
   3017                                     &mmap_size);
   3018     if (ret < 0) {
   3019         // Fall back to non exclusive mode
   3020         info->shared_memory_fd = pcm_get_poll_fd(out->pcm);
   3021     } else {
   3022         if (mmap_size < buffer_size) {
   3023             step = "mmap";
   3024             goto exit;
   3025         }
   3026         // FIXME: indicate exclusive mode support by returning a negative buffer size
   3027         info->buffer_size_frames *= -1;
   3028     }
   3029     memset(info->shared_memory_address, 0, buffer_size);
   3030 
   3031     ret = pcm_mmap_commit(out->pcm, 0, MMAP_PERIOD_SIZE);
   3032     if (ret < 0) {
   3033         step = "commit";
   3034         goto exit;
   3035     }
   3036 
   3037     out->standby = false;
   3038     ret = 0;
   3039 
   3040     ALOGV("%s: got mmap buffer address %p info->buffer_size_frames %d",
   3041           __func__, info->shared_memory_address, info->buffer_size_frames);
   3042 
   3043 exit:
   3044     if (ret != 0) {
   3045         if (out->pcm == NULL) {
   3046             ALOGE("%s: %s - %d", __func__, step, ret);
   3047         } else {
   3048             ALOGE("%s: %s %s", __func__, step, pcm_get_error(out->pcm));
   3049             pcm_close(out->pcm);
   3050             out->pcm = NULL;
   3051         }
   3052     }
   3053     pthread_mutex_unlock(&adev->lock);
   3054     return ret;
   3055 }
   3056 
   3057 static int out_get_mmap_position(const struct audio_stream_out *stream,
   3058                                   struct audio_mmap_position *position)
   3059 {
   3060     struct stream_out *out = (struct stream_out *)stream;
   3061     ALOGVV("%s", __func__);
   3062     if (position == NULL) {
   3063         return -EINVAL;
   3064     }
   3065     if (out->usecase != USECASE_AUDIO_PLAYBACK_MMAP) {
   3066         return -ENOSYS;
   3067     }
   3068     if (out->pcm == NULL) {
   3069         return -ENOSYS;
   3070     }
   3071 
   3072     struct timespec ts = { 0, 0 };
   3073     int ret = pcm_mmap_get_hw_ptr(out->pcm, (unsigned int *)&position->position_frames, &ts);
   3074     if (ret < 0) {
   3075         ALOGE("%s: %s", __func__, pcm_get_error(out->pcm));
   3076         return ret;
   3077     }
   3078     position->time_nanoseconds = audio_utils_ns_from_timespec(&ts);
   3079     return 0;
   3080 }
   3081 
   3082 
   3083 /** audio_stream_in implementation **/
   3084 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
   3085 {
   3086     struct stream_in *in = (struct stream_in *)stream;
   3087 
   3088     return in->config.rate;
   3089 }
   3090 
   3091 static int in_set_sample_rate(struct audio_stream *stream __unused, uint32_t rate __unused)
   3092 {
   3093     return -ENOSYS;
   3094 }
   3095 
   3096 static size_t in_get_buffer_size(const struct audio_stream *stream)
   3097 {
   3098     struct stream_in *in = (struct stream_in *)stream;
   3099     return in->config.period_size * in->af_period_multiplier *
   3100         audio_stream_in_frame_size((const struct audio_stream_in *)stream);
   3101 }
   3102 
   3103 static uint32_t in_get_channels(const struct audio_stream *stream)
   3104 {
   3105     struct stream_in *in = (struct stream_in *)stream;
   3106 
   3107     return in->channel_mask;
   3108 }
   3109 
   3110 static audio_format_t in_get_format(const struct audio_stream *stream)
   3111 {
   3112     struct stream_in *in = (struct stream_in *)stream;
   3113     return in->format;
   3114 }
   3115 
   3116 static int in_set_format(struct audio_stream *stream __unused, audio_format_t format __unused)
   3117 {
   3118     return -ENOSYS;
   3119 }
   3120 
   3121 static int in_standby(struct audio_stream *stream)
   3122 {
   3123     struct stream_in *in = (struct stream_in *)stream;
   3124     struct audio_device *adev = in->dev;
   3125     int status = 0;
   3126     bool do_stop = true;
   3127 
   3128     ALOGV("%s: enter", __func__);
   3129 
   3130     lock_input_stream(in);
   3131 
   3132     if (!in->standby && in->is_st_session) {
   3133         ALOGV("%s: sound trigger pcm stop lab", __func__);
   3134         audio_extn_sound_trigger_stop_lab(in);
   3135         in->standby = true;
   3136     }
   3137 
   3138     if (!in->standby) {
   3139         if (adev->adm_deregister_stream)
   3140             adev->adm_deregister_stream(adev->adm_data, in->capture_handle);
   3141 
   3142         pthread_mutex_lock(&adev->lock);
   3143         in->standby = true;
   3144         if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
   3145             do_stop = in->capture_started;
   3146             in->capture_started = false;
   3147         }
   3148         if (in->pcm) {
   3149             pcm_close(in->pcm);
   3150             in->pcm = NULL;
   3151         }
   3152         adev->enable_voicerx = false;
   3153         platform_set_echo_reference(adev, false, AUDIO_DEVICE_NONE );
   3154         if (do_stop) {
   3155             status = stop_input_stream(in);
   3156         }
   3157         pthread_mutex_unlock(&adev->lock);
   3158     }
   3159     pthread_mutex_unlock(&in->lock);
   3160     ALOGV("%s: exit:  status(%d)", __func__, status);
   3161     return status;
   3162 }
   3163 
   3164 static int in_dump(const struct audio_stream *stream, int fd)
   3165 {
   3166     struct stream_in *in = (struct stream_in *)stream;
   3167 
   3168     // We try to get the lock for consistency,
   3169     // but it isn't necessary for these variables.
   3170     // If we're not in standby, we may be blocked on a read.
   3171     const bool locked = (pthread_mutex_trylock(&in->lock) == 0);
   3172     dprintf(fd, "      Standby: %s\n", in->standby ? "yes" : "no");
   3173     dprintf(fd, "      Frames read: %lld\n", (long long)in->frames_read);
   3174     dprintf(fd, "      Frames muted: %lld\n", (long long)in->frames_muted);
   3175 
   3176     if (locked) {
   3177         pthread_mutex_unlock(&in->lock);
   3178     }
   3179 
   3180     // dump error info
   3181     (void)error_log_dump(
   3182             in->error_log, fd, "      " /* prefix */, 0 /* lines */, 0 /* limit_ns */);
   3183     return 0;
   3184 }
   3185 
   3186 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
   3187 {
   3188     struct stream_in *in = (struct stream_in *)stream;
   3189     struct audio_device *adev = in->dev;
   3190     struct str_parms *parms;
   3191     char *str;
   3192     char value[32];
   3193     int ret, val = 0;
   3194     int status = 0;
   3195 
   3196     ALOGV("%s: enter: kvpairs=%s", __func__, kvpairs);
   3197     parms = str_parms_create_str(kvpairs);
   3198 
   3199     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
   3200 
   3201     lock_input_stream(in);
   3202 
   3203     pthread_mutex_lock(&adev->lock);
   3204     if (ret >= 0) {
   3205         val = atoi(value);
   3206         /* no audio source uses val == 0 */
   3207         if ((in->source != val) && (val != 0)) {
   3208             in->source = val;
   3209         }
   3210     }
   3211 
   3212     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
   3213 
   3214     if (ret >= 0) {
   3215         val = atoi(value);
   3216         if (((int)in->device != val) && (val != 0) && audio_is_input_device(val) ) {
   3217 
   3218             // Workaround: If routing to an non existing usb device, fail gracefully
   3219             // The routing request will otherwise block during 10 second
   3220             int card;
   3221             if (audio_is_usb_in_device(val) &&
   3222                 (card = get_alive_usb_card(parms)) >= 0) {
   3223 
   3224                 ALOGW("in_set_parameters() ignoring rerouting to non existing USB card %d", card);
   3225                 status = -ENOSYS;
   3226             } else {
   3227 
   3228                 in->device = val;
   3229                 /* If recording is in progress, change the tx device to new device */
   3230                 if (!in->standby) {
   3231                     ALOGV("update input routing change");
   3232                     // inform adm before actual routing to prevent glitches.
   3233                     if (adev->adm_on_routing_change) {
   3234                         adev->adm_on_routing_change(adev->adm_data,
   3235                                                     in->capture_handle);
   3236                     }
   3237                     select_devices(adev, in->usecase);
   3238                 }
   3239             }
   3240         }
   3241     }
   3242 
   3243     pthread_mutex_unlock(&adev->lock);
   3244     pthread_mutex_unlock(&in->lock);
   3245 
   3246     str_parms_destroy(parms);
   3247     ALOGV("%s: exit: status(%d)", __func__, status);
   3248     return status;
   3249 }
   3250 
   3251 static char* in_get_parameters(const struct audio_stream *stream,
   3252                                const char *keys)
   3253 {
   3254     struct stream_in *in = (struct stream_in *)stream;
   3255     struct str_parms *query = str_parms_create_str(keys);
   3256     char *str;
   3257     struct str_parms *reply = str_parms_create();
   3258     bool replied = false;
   3259 
   3260     ALOGV("%s: enter: keys - %s", __func__, keys);
   3261     replied |= stream_get_parameter_channels(query, reply,
   3262                                              &in->supported_channel_masks[0]);
   3263     replied |= stream_get_parameter_formats(query, reply,
   3264                                             &in->supported_formats[0]);
   3265     replied |= stream_get_parameter_rates(query, reply,
   3266                                           &in->supported_sample_rates[0]);
   3267     if (replied) {
   3268         str = str_parms_to_str(reply);
   3269     } else {
   3270         str = strdup("");
   3271     }
   3272     str_parms_destroy(query);
   3273     str_parms_destroy(reply);
   3274     ALOGV("%s: exit: returns - %s", __func__, str);
   3275     return str;
   3276 }
   3277 
   3278 static int in_set_gain(struct audio_stream_in *stream __unused, float gain __unused)
   3279 {
   3280     return -ENOSYS;
   3281 }
   3282 
   3283 static void in_snd_mon_cb(void * stream, struct str_parms * parms)
   3284 {
   3285     if (!stream || !parms)
   3286         return;
   3287 
   3288     struct stream_in *in = (struct stream_in *)stream;
   3289     struct audio_device *adev = in->dev;
   3290 
   3291     card_status_t status;
   3292     int card;
   3293     if (parse_snd_card_status(parms, &card, &status) < 0)
   3294         return;
   3295 
   3296     pthread_mutex_lock(&adev->lock);
   3297     bool valid_cb = (card == adev->snd_card);
   3298     pthread_mutex_unlock(&adev->lock);
   3299 
   3300     if (!valid_cb)
   3301         return;
   3302 
   3303     lock_input_stream(in);
   3304     if (in->card_status != status)
   3305         in->card_status = status;
   3306     pthread_mutex_unlock(&in->lock);
   3307 
   3308     ALOGW("in_snd_mon_cb for card %d usecase %s, status %s", card,
   3309           use_case_table[in->usecase],
   3310           status == CARD_STATUS_OFFLINE ? "offline" : "online");
   3311 
   3312     // a better solution would be to report error back to AF and let
   3313     // it put the stream to standby
   3314     if (status == CARD_STATUS_OFFLINE)
   3315         in_standby(&in->stream.common);
   3316 
   3317     return;
   3318 }
   3319 
   3320 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
   3321                        size_t bytes)
   3322 {
   3323     struct stream_in *in = (struct stream_in *)stream;
   3324     struct audio_device *adev = in->dev;
   3325     int i, ret = -1;
   3326     int *int_buf_stream = NULL;
   3327     int error_code = ERROR_CODE_STANDBY; // initial errors are considered coming out of standby.
   3328 
   3329     lock_input_stream(in);
   3330     const size_t frame_size = audio_stream_in_frame_size(stream);
   3331     const size_t frames = bytes / frame_size;
   3332 
   3333     if (in->is_st_session) {
   3334         ALOGVV(" %s: reading on st session bytes=%zu", __func__, bytes);
   3335         /* Read from sound trigger HAL */
   3336         audio_extn_sound_trigger_read(in, buffer, bytes);
   3337         pthread_mutex_unlock(&in->lock);
   3338         return bytes;
   3339     }
   3340 
   3341     if (in->usecase == USECASE_AUDIO_RECORD_MMAP) {
   3342         ret = -ENOSYS;
   3343         goto exit;
   3344     }
   3345 
   3346     if (in->standby) {
   3347         pthread_mutex_lock(&adev->lock);
   3348         ret = start_input_stream(in);
   3349         pthread_mutex_unlock(&adev->lock);
   3350         if (ret != 0) {
   3351             goto exit;
   3352         }
   3353         in->standby = 0;
   3354     }
   3355 
   3356     // errors that occur here are read errors.
   3357     error_code = ERROR_CODE_READ;
   3358 
   3359     //what's the duration requested by the client?
   3360     long ns = pcm_bytes_to_frames(in->pcm, bytes)*1000000000LL/
   3361                                                 in->config.rate;
   3362     request_in_focus(in, ns);
   3363 
   3364     bool use_mmap = is_mmap_usecase(in->usecase) || in->realtime;
   3365     if (in->pcm) {
   3366         if (use_mmap) {
   3367             ret = pcm_mmap_read(in->pcm, buffer, bytes);
   3368         } else {
   3369             ret = pcm_read(in->pcm, buffer, bytes);
   3370         }
   3371         if (ret < 0) {
   3372             ALOGE("Failed to read w/err %s", strerror(errno));
   3373             ret = -errno;
   3374         }
   3375         if (!ret && bytes > 0 && (in->format == AUDIO_FORMAT_PCM_8_24_BIT)) {
   3376             if (bytes % 4 == 0) {
   3377                 /* data from DSP comes in 24_8 format, convert it to 8_24 */
   3378                 int_buf_stream = buffer;
   3379                 for (size_t itt=0; itt < bytes/4 ; itt++) {
   3380                     int_buf_stream[itt] >>= 8;
   3381                 }
   3382             } else {
   3383                 ALOGE("%s: !!! something wrong !!! ... data not 32 bit aligned ", __func__);
   3384                 ret = -EINVAL;
   3385                 goto exit;
   3386             }
   3387         }
   3388     }
   3389 
   3390     release_in_focus(in, ns);
   3391 
   3392     /*
   3393      * Instead of writing zeroes here, we could trust the hardware
   3394      * to always provide zeroes when muted.
   3395      * No need to acquire adev->lock to read mic_muted here as we don't change its state.
   3396      */
   3397     if (ret == 0 && adev->mic_muted && in->usecase != USECASE_AUDIO_RECORD_AFE_PROXY) {
   3398         memset(buffer, 0, bytes);
   3399         in->frames_muted += frames;
   3400     }
   3401 
   3402 exit:
   3403     pthread_mutex_unlock(&in->lock);
   3404 
   3405     if (ret != 0) {
   3406         error_log_log(in->error_log, error_code, audio_utils_get_real_time_ns());
   3407         in_standby(&in->stream.common);
   3408         ALOGV("%s: read failed - sleeping for buffer duration", __func__);
   3409         usleep(frames * 1000000LL / in_get_sample_rate(&in->stream.common));
   3410         memset(buffer, 0, bytes); // clear return data
   3411         in->frames_muted += frames;
   3412     }
   3413     if (bytes > 0) {
   3414         in->frames_read += frames;
   3415     }
   3416     return bytes;
   3417 }
   3418 
   3419 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream __unused)
   3420 {
   3421     return 0;
   3422 }
   3423 
   3424 static int in_get_capture_position(const struct audio_stream_in *stream,
   3425                                    int64_t *frames, int64_t *time)
   3426 {
   3427     if (stream == NULL || frames == NULL || time == NULL) {
   3428         return -EINVAL;
   3429     }
   3430     struct stream_in *in = (struct stream_in *)stream;
   3431     int ret = -ENOSYS;
   3432 
   3433     lock_input_stream(in);
   3434     if (in->pcm) {
   3435         struct timespec timestamp;
   3436         unsigned int avail;
   3437         if (pcm_get_htimestamp(in->pcm, &avail, &timestamp) == 0) {
   3438             *frames = in->frames_read + avail;
   3439             *time = timestamp.tv_sec * 1000000000LL + timestamp.tv_nsec;
   3440             ret = 0;
   3441         }
   3442     }
   3443     pthread_mutex_unlock(&in->lock);
   3444     return ret;
   3445 }
   3446 
   3447 static int add_remove_audio_effect(const struct audio_stream *stream,
   3448                                    effect_handle_t effect,
   3449                                    bool enable)
   3450 {
   3451     struct stream_in *in = (struct stream_in *)stream;
   3452     struct audio_device *adev = in->dev;
   3453     int status = 0;
   3454     effect_descriptor_t desc;
   3455 
   3456     status = (*effect)->get_descriptor(effect, &desc);
   3457     if (status != 0)
   3458         return status;
   3459 
   3460     lock_input_stream(in);
   3461     pthread_mutex_lock(&in->dev->lock);
   3462     if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
   3463             in->source == AUDIO_SOURCE_VOICE_RECOGNITION ||
   3464             adev->mode == AUDIO_MODE_IN_COMMUNICATION) &&
   3465             in->enable_aec != enable &&
   3466             (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
   3467         in->enable_aec = enable;
   3468         if (!enable)
   3469             platform_set_echo_reference(in->dev, enable, AUDIO_DEVICE_NONE);
   3470         if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
   3471             adev->mode == AUDIO_MODE_IN_COMMUNICATION) {
   3472             adev->enable_voicerx = enable;
   3473             struct audio_usecase *usecase;
   3474             struct listnode *node;
   3475             list_for_each(node, &adev->usecase_list) {
   3476                 usecase = node_to_item(node, struct audio_usecase, list);
   3477                 if (usecase->type == PCM_PLAYBACK)
   3478                     select_devices(adev, usecase->id);
   3479             }
   3480         }
   3481         if (!in->standby)
   3482             select_devices(in->dev, in->usecase);
   3483     }
   3484     if (in->enable_ns != enable &&
   3485             (memcmp(&desc.type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
   3486         in->enable_ns = enable;
   3487         if (!in->standby)
   3488             select_devices(in->dev, in->usecase);
   3489     }
   3490     pthread_mutex_unlock(&in->dev->lock);
   3491     pthread_mutex_unlock(&in->lock);
   3492 
   3493     return 0;
   3494 }
   3495 
   3496 static int in_add_audio_effect(const struct audio_stream *stream,
   3497                                effect_handle_t effect)
   3498 {
   3499     ALOGV("%s: effect %p", __func__, effect);
   3500     return add_remove_audio_effect(stream, effect, true);
   3501 }
   3502 
   3503 static int in_remove_audio_effect(const struct audio_stream *stream,
   3504                                   effect_handle_t effect)
   3505 {
   3506     ALOGV("%s: effect %p", __func__, effect);
   3507     return add_remove_audio_effect(stream, effect, false);
   3508 }
   3509 
   3510 static int in_stop(const struct audio_stream_in* stream)
   3511 {
   3512     struct stream_in *in = (struct stream_in *)stream;
   3513     struct audio_device *adev = in->dev;
   3514 
   3515     int ret = -ENOSYS;
   3516     ALOGV("%s", __func__);
   3517     pthread_mutex_lock(&adev->lock);
   3518     if (in->usecase == USECASE_AUDIO_RECORD_MMAP && !in->standby &&
   3519             in->capture_started && in->pcm != NULL) {
   3520         pcm_stop(in->pcm);
   3521         ret = stop_input_stream(in);
   3522         in->capture_started = false;
   3523     }
   3524     pthread_mutex_unlock(&adev->lock);
   3525     return ret;
   3526 }
   3527 
   3528 static int in_start(const struct audio_stream_in* stream)
   3529 {
   3530     struct stream_in *in = (struct stream_in *)stream;
   3531     struct audio_device *adev = in->dev;
   3532     int ret = -ENOSYS;
   3533 
   3534     ALOGV("%s in %p", __func__, in);
   3535     pthread_mutex_lock(&adev->lock);
   3536     if (in->usecase == USECASE_AUDIO_RECORD_MMAP && !in->standby &&
   3537             !in->capture_started && in->pcm != NULL) {
   3538         if (!in->capture_started) {
   3539             ret = start_input_stream(in);
   3540             if (ret == 0) {
   3541                 in->capture_started = true;
   3542             }
   3543         }
   3544     }
   3545     pthread_mutex_unlock(&adev->lock);
   3546     return ret;
   3547 }
   3548 
   3549 static int in_create_mmap_buffer(const struct audio_stream_in *stream,
   3550                                   int32_t min_size_frames,
   3551                                   struct audio_mmap_buffer_info *info)
   3552 {
   3553     struct stream_in *in = (struct stream_in *)stream;
   3554     struct audio_device *adev = in->dev;
   3555     int ret = 0;
   3556     unsigned int offset1;
   3557     unsigned int frames1;
   3558     const char *step = "";
   3559     uint32_t mmap_size;
   3560     uint32_t buffer_size;
   3561 
   3562     pthread_mutex_lock(&adev->lock);
   3563     ALOGV("%s in %p", __func__, in);
   3564 
   3565     if (info == NULL || min_size_frames == 0) {
   3566         ALOGE("%s invalid argument info %p min_size_frames %d", __func__, info, min_size_frames);
   3567         ret = -EINVAL;
   3568         goto exit;
   3569     }
   3570     if (in->usecase != USECASE_AUDIO_RECORD_MMAP || !in->standby) {
   3571         ALOGE("%s: usecase = %d, standby = %d", __func__, in->usecase, in->standby);
   3572         ALOGV("%s in %p", __func__, in);
   3573         ret = -ENOSYS;
   3574         goto exit;
   3575     }
   3576     in->pcm_device_id = platform_get_pcm_device_id(in->usecase, PCM_CAPTURE);
   3577     if (in->pcm_device_id < 0) {
   3578         ALOGE("%s: Invalid PCM device id(%d) for the usecase(%d)",
   3579               __func__, in->pcm_device_id, in->usecase);
   3580         ret = -EINVAL;
   3581         goto exit;
   3582     }
   3583 
   3584     adjust_mmap_period_count(&in->config, min_size_frames);
   3585 
   3586     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d",
   3587           __func__, adev->snd_card, in->pcm_device_id, in->config.channels);
   3588     in->pcm = pcm_open(adev->snd_card, in->pcm_device_id,
   3589                         (PCM_IN | PCM_MMAP | PCM_NOIRQ | PCM_MONOTONIC), &in->config);
   3590     if (in->pcm == NULL || !pcm_is_ready(in->pcm)) {
   3591         step = "open";
   3592         ret = -ENODEV;
   3593         goto exit;
   3594     }
   3595 
   3596     ret = pcm_mmap_begin(in->pcm, &info->shared_memory_address, &offset1, &frames1);
   3597     if (ret < 0)  {
   3598         step = "begin";
   3599         goto exit;
   3600     }
   3601     info->buffer_size_frames = pcm_get_buffer_size(in->pcm);
   3602     buffer_size = pcm_frames_to_bytes(in->pcm, info->buffer_size_frames);
   3603     info->burst_size_frames = in->config.period_size;
   3604     ret = platform_get_mmap_data_fd(adev->platform,
   3605                                     in->pcm_device_id, 1 /*capture*/,
   3606                                     &info->shared_memory_fd,
   3607                                     &mmap_size);
   3608     if (ret < 0) {
   3609         // Fall back to non exclusive mode
   3610         info->shared_memory_fd = pcm_get_poll_fd(in->pcm);
   3611     } else {
   3612         if (mmap_size < buffer_size) {
   3613             step = "mmap";
   3614             goto exit;
   3615         }
   3616         // FIXME: indicate exclusive mode support by returning a negative buffer size
   3617         info->buffer_size_frames *= -1;
   3618     }
   3619 
   3620     memset(info->shared_memory_address, 0, buffer_size);
   3621 
   3622     ret = pcm_mmap_commit(in->pcm, 0, MMAP_PERIOD_SIZE);
   3623     if (ret < 0) {
   3624         step = "commit";
   3625         goto exit;
   3626     }
   3627 
   3628     in->standby = false;
   3629     ret = 0;
   3630 
   3631     ALOGV("%s: got mmap buffer address %p info->buffer_size_frames %d",
   3632           __func__, info->shared_memory_address, info->buffer_size_frames);
   3633 
   3634 exit:
   3635     if (ret != 0) {
   3636         if (in->pcm == NULL) {
   3637             ALOGE("%s: %s - %d", __func__, step, ret);
   3638         } else {
   3639             ALOGE("%s: %s %s", __func__, step, pcm_get_error(in->pcm));
   3640             pcm_close(in->pcm);
   3641             in->pcm = NULL;
   3642         }
   3643     }
   3644     pthread_mutex_unlock(&adev->lock);
   3645     return ret;
   3646 }
   3647 
   3648 static int in_get_mmap_position(const struct audio_stream_in *stream,
   3649                                   struct audio_mmap_position *position)
   3650 {
   3651     struct stream_in *in = (struct stream_in *)stream;
   3652     ALOGVV("%s", __func__);
   3653     if (position == NULL) {
   3654         return -EINVAL;
   3655     }
   3656     if (in->usecase != USECASE_AUDIO_RECORD_MMAP) {
   3657         return -ENOSYS;
   3658     }
   3659     if (in->pcm == NULL) {
   3660         return -ENOSYS;
   3661     }
   3662     struct timespec ts = { 0, 0 };
   3663     int ret = pcm_mmap_get_hw_ptr(in->pcm, (unsigned int *)&position->position_frames, &ts);
   3664     if (ret < 0) {
   3665         ALOGE("%s: %s", __func__, pcm_get_error(in->pcm));
   3666         return ret;
   3667     }
   3668     position->time_nanoseconds = audio_utils_ns_from_timespec(&ts);
   3669     return 0;
   3670 }
   3671 
   3672 
   3673 static int adev_open_output_stream(struct audio_hw_device *dev,
   3674                                    audio_io_handle_t handle,
   3675                                    audio_devices_t devices,
   3676                                    audio_output_flags_t flags,
   3677                                    struct audio_config *config,
   3678                                    struct audio_stream_out **stream_out,
   3679                                    const char *address __unused)
   3680 {
   3681     struct audio_device *adev = (struct audio_device *)dev;
   3682     struct stream_out *out;
   3683     int i, ret;
   3684     bool is_hdmi = devices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
   3685     bool is_usb_dev = audio_is_usb_out_device(devices) &&
   3686                       (devices != AUDIO_DEVICE_OUT_USB_ACCESSORY);
   3687     bool direct_dev = is_hdmi || is_usb_dev;
   3688 
   3689     if (is_usb_dev && !is_usb_ready(adev, true /* is_playback */)) {
   3690         return -ENOSYS;
   3691     }
   3692 
   3693     ALOGV("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)",
   3694           __func__, config->sample_rate, config->channel_mask, devices, flags);
   3695     *stream_out = NULL;
   3696     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
   3697 
   3698     if (devices == AUDIO_DEVICE_NONE)
   3699         devices = AUDIO_DEVICE_OUT_SPEAKER;
   3700 
   3701     out->flags = flags;
   3702     out->devices = devices;
   3703     out->dev = adev;
   3704     out->format = config->format;
   3705     out->sample_rate = config->sample_rate;
   3706     out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
   3707     out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
   3708     out->handle = handle;
   3709 
   3710     /* Init use case and pcm_config */
   3711     if (audio_is_linear_pcm(out->format) &&
   3712         (out->flags == AUDIO_OUTPUT_FLAG_NONE ||
   3713          out->flags == AUDIO_OUTPUT_FLAG_DIRECT) && direct_dev) {
   3714         pthread_mutex_lock(&adev->lock);
   3715         if (is_hdmi) {
   3716             ret = read_hdmi_channel_masks(out);
   3717             if (config->sample_rate == 0)
   3718                 config->sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE;
   3719             if (config->channel_mask == 0)
   3720                 config->channel_mask = AUDIO_CHANNEL_OUT_5POINT1;
   3721             if (config->format == AUDIO_FORMAT_DEFAULT)
   3722                 config->format = AUDIO_FORMAT_PCM_16_BIT;
   3723         } else if (is_usb_dev) {
   3724             ret = read_usb_sup_params_and_compare(true /*is_playback*/,
   3725                                                   &config->format,
   3726                                                   &out->supported_formats[0],
   3727                                                   MAX_SUPPORTED_FORMATS,
   3728                                                   &config->channel_mask,
   3729                                                   &out->supported_channel_masks[0],
   3730                                                   MAX_SUPPORTED_CHANNEL_MASKS,
   3731                                                   &config->sample_rate,
   3732                                                   &out->supported_sample_rates[0],
   3733                                                   MAX_SUPPORTED_SAMPLE_RATES);
   3734             ALOGV("plugged dev USB ret %d", ret);
   3735         } else {
   3736             ret = -1;
   3737         }
   3738         pthread_mutex_unlock(&adev->lock);
   3739         if (ret != 0)
   3740             goto error_open;
   3741 
   3742         out->channel_mask = config->channel_mask;
   3743         out->sample_rate = config->sample_rate;
   3744         out->format = config->format;
   3745         out->usecase = USECASE_AUDIO_PLAYBACK_HIFI;
   3746         // does this change?
   3747         out->config = is_hdmi ? pcm_config_hdmi_multi : pcm_config_hifi;
   3748         out->config.rate = config->sample_rate;
   3749         out->config.channels = audio_channel_count_from_out_mask(out->channel_mask);
   3750         out->config.period_size = HDMI_MULTI_PERIOD_BYTES / (out->config.channels *
   3751                                                          audio_bytes_per_sample(config->format));
   3752         out->config.format = pcm_format_from_audio_format(out->format);
   3753     } else if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
   3754         pthread_mutex_lock(&adev->lock);
   3755         bool offline = (adev->card_status == CARD_STATUS_OFFLINE);
   3756         pthread_mutex_unlock(&adev->lock);
   3757 
   3758         // reject offload during card offline to allow
   3759         // fallback to s/w paths
   3760         if (offline) {
   3761             ret = -ENODEV;
   3762             goto error_open;
   3763         }
   3764 
   3765         if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
   3766             config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
   3767             ALOGE("%s: Unsupported Offload information", __func__);
   3768             ret = -EINVAL;
   3769             goto error_open;
   3770         }
   3771         if (!is_supported_format(config->offload_info.format)) {
   3772             ALOGE("%s: Unsupported audio format", __func__);
   3773             ret = -EINVAL;
   3774             goto error_open;
   3775         }
   3776 
   3777         out->compr_config.codec = (struct snd_codec *)
   3778                                     calloc(1, sizeof(struct snd_codec));
   3779 
   3780         out->usecase = USECASE_AUDIO_PLAYBACK_OFFLOAD;
   3781         if (config->offload_info.channel_mask)
   3782             out->channel_mask = config->offload_info.channel_mask;
   3783         else if (config->channel_mask)
   3784             out->channel_mask = config->channel_mask;
   3785         out->format = config->offload_info.format;
   3786         out->sample_rate = config->offload_info.sample_rate;
   3787 
   3788         out->stream.set_callback = out_set_callback;
   3789         out->stream.pause = out_pause;
   3790         out->stream.resume = out_resume;
   3791         out->stream.drain = out_drain;
   3792         out->stream.flush = out_flush;
   3793 
   3794         out->compr_config.codec->id =
   3795                 get_snd_codec_id(config->offload_info.format);
   3796         out->compr_config.fragment_size = COMPRESS_OFFLOAD_FRAGMENT_SIZE;
   3797         out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
   3798         out->compr_config.codec->sample_rate = config->offload_info.sample_rate;
   3799         out->compr_config.codec->bit_rate =
   3800                     config->offload_info.bit_rate;
   3801         out->compr_config.codec->ch_in =
   3802                 audio_channel_count_from_out_mask(config->channel_mask);
   3803         out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
   3804 
   3805         if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
   3806             out->non_blocking = 1;
   3807 
   3808         out->send_new_metadata = 1;
   3809         create_offload_callback_thread(out);
   3810         ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
   3811                 __func__, config->offload_info.version,
   3812                 config->offload_info.bit_rate);
   3813     } else  if (out->devices == AUDIO_DEVICE_OUT_TELEPHONY_TX) {
   3814         switch (config->sample_rate) {
   3815             case 8000:
   3816             case 16000:
   3817             case 48000:
   3818                 out->sample_rate = config->sample_rate;
   3819                 break;
   3820             default:
   3821                 out->sample_rate = AFE_PROXY_SAMPLING_RATE;
   3822         }
   3823         out->format = AUDIO_FORMAT_PCM_16_BIT;
   3824         out->usecase = USECASE_AUDIO_PLAYBACK_AFE_PROXY;
   3825         out->config = pcm_config_afe_proxy_playback;
   3826         adev->voice_tx_output = out;
   3827     } else if (out->flags == AUDIO_OUTPUT_FLAG_VOIP_RX) {
   3828         //FIXME: add support for MONO stream configuration when audioflinger mixer supports it
   3829         uint32_t buffer_size, frame_size;
   3830         out->usecase = USECASE_AUDIO_PLAYBACK_VOIP;
   3831         out->config = pcm_config_voip;
   3832         out->config.format = pcm_format_from_audio_format(config->format);
   3833         out->config.rate = config->sample_rate;
   3834         buffer_size = get_stream_buffer_size(VOIP_PLAYBACK_PERIOD_DURATION_MSEC,
   3835                                              config->sample_rate,
   3836                                              config->format,
   3837                                              out->config.channels,
   3838                                              false /*is_low_latency*/);
   3839         frame_size = audio_bytes_per_sample(config->format) * out->config.channels;
   3840         out->config.period_size = buffer_size / frame_size;
   3841         out->config.period_count = VOIP_PLAYBACK_PERIOD_COUNT;
   3842         out->af_period_multiplier = 1;
   3843     } else {
   3844         if (out->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
   3845             out->usecase = USECASE_AUDIO_PLAYBACK_DEEP_BUFFER;
   3846             out->config = pcm_config_deep_buffer;
   3847         } else if (out->flags & AUDIO_OUTPUT_FLAG_TTS) {
   3848             out->usecase = USECASE_AUDIO_PLAYBACK_TTS;
   3849             out->config = pcm_config_deep_buffer;
   3850         } else if (out->flags & AUDIO_OUTPUT_FLAG_RAW) {
   3851             out->usecase = USECASE_AUDIO_PLAYBACK_ULL;
   3852             out->realtime = may_use_noirq_mode(adev, USECASE_AUDIO_PLAYBACK_ULL, out->flags);
   3853             out->config = out->realtime ? pcm_config_rt : pcm_config_low_latency;
   3854         } else if (out->flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
   3855             out->usecase = USECASE_AUDIO_PLAYBACK_MMAP;
   3856             out->config = pcm_config_mmap_playback;
   3857             out->stream.start = out_start;
   3858             out->stream.stop = out_stop;
   3859             out->stream.create_mmap_buffer = out_create_mmap_buffer;
   3860             out->stream.get_mmap_position = out_get_mmap_position;
   3861         } else {
   3862             out->usecase = USECASE_AUDIO_PLAYBACK_LOW_LATENCY;
   3863             out->config = pcm_config_low_latency;
   3864         }
   3865         if (config->format != audio_format_from_pcm_format(out->config.format)) {
   3866             out->config.format = pcm_format_from_audio_format(config->format);
   3867         }
   3868         out->sample_rate = out->config.rate;
   3869     }
   3870 
   3871     if ((config->sample_rate != 0 && config->sample_rate != out->sample_rate) ||
   3872         (config->format != AUDIO_FORMAT_DEFAULT && config->format != out->format) ||
   3873         (config->channel_mask != 0 && config->channel_mask != out->channel_mask)) {
   3874         ALOGI("%s: Unsupported output config. sample_rate:%u format:%#x channel_mask:%#x",
   3875               __func__, config->sample_rate, config->format, config->channel_mask);
   3876         config->sample_rate = out->sample_rate;
   3877         config->format = out->format;
   3878         config->channel_mask = out->channel_mask;
   3879         ret = -EINVAL;
   3880         goto error_open;
   3881     }
   3882 
   3883     ALOGV("%s: Usecase(%s) config->format %#x  out->config.format %#x\n",
   3884             __func__, use_case_table[out->usecase], config->format, out->config.format);
   3885 
   3886     if (flags & AUDIO_OUTPUT_FLAG_PRIMARY) {
   3887         if (adev->primary_output == NULL)
   3888             adev->primary_output = out;
   3889         else {
   3890             ALOGE("%s: Primary output is already opened", __func__);
   3891             ret = -EEXIST;
   3892             goto error_open;
   3893         }
   3894     }
   3895 
   3896     /* Check if this usecase is already existing */
   3897     pthread_mutex_lock(&adev->lock);
   3898     if (get_usecase_from_list(adev, out->usecase) != NULL) {
   3899         ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
   3900         pthread_mutex_unlock(&adev->lock);
   3901         ret = -EEXIST;
   3902         goto error_open;
   3903     }
   3904     pthread_mutex_unlock(&adev->lock);
   3905 
   3906     out->stream.common.get_sample_rate = out_get_sample_rate;
   3907     out->stream.common.set_sample_rate = out_set_sample_rate;
   3908     out->stream.common.get_buffer_size = out_get_buffer_size;
   3909     out->stream.common.get_channels = out_get_channels;
   3910     out->stream.common.get_format = out_get_format;
   3911     out->stream.common.set_format = out_set_format;
   3912     out->stream.common.standby = out_standby;
   3913     out->stream.common.dump = out_dump;
   3914     out->stream.common.set_parameters = out_set_parameters;
   3915     out->stream.common.get_parameters = out_get_parameters;
   3916     out->stream.common.add_audio_effect = out_add_audio_effect;
   3917     out->stream.common.remove_audio_effect = out_remove_audio_effect;
   3918     out->stream.get_latency = out_get_latency;
   3919     out->stream.set_volume = out_set_volume;
   3920 #ifdef NO_AUDIO_OUT
   3921     out->stream.write = out_write_for_no_output;
   3922 #else
   3923     out->stream.write = out_write;
   3924 #endif
   3925     out->stream.get_render_position = out_get_render_position;
   3926     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
   3927     out->stream.get_presentation_position = out_get_presentation_position;
   3928 
   3929     if (out->realtime)
   3930         out->af_period_multiplier = af_period_multiplier;
   3931     else
   3932         out->af_period_multiplier = 1;
   3933 
   3934     out->standby = 1;
   3935     /* out->muted = false; by calloc() */
   3936     /* out->written = 0; by calloc() */
   3937 
   3938     pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
   3939     pthread_mutex_init(&out->pre_lock, (const pthread_mutexattr_t *) NULL);
   3940     pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);
   3941 
   3942     config->format = out->stream.common.get_format(&out->stream.common);
   3943     config->channel_mask = out->stream.common.get_channels(&out->stream.common);
   3944     config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
   3945 
   3946     out->error_log = error_log_create(
   3947             ERROR_LOG_ENTRIES,
   3948             1000000000 /* aggregate consecutive identical errors within one second in ns */);
   3949 
   3950     /*
   3951        By locking output stream before registering, we allow the callback
   3952        to update stream's state only after stream's initial state is set to
   3953        adev state.
   3954     */
   3955     lock_output_stream(out);
   3956     audio_extn_snd_mon_register_listener(out, out_snd_mon_cb);
   3957     pthread_mutex_lock(&adev->lock);
   3958     out->card_status = adev->card_status;
   3959     pthread_mutex_unlock(&adev->lock);
   3960     pthread_mutex_unlock(&out->lock);
   3961 
   3962     stream_app_type_cfg_init(&out->app_type_cfg);
   3963 
   3964     *stream_out = &out->stream;
   3965 
   3966     ALOGV("%s: exit", __func__);
   3967     return 0;
   3968 
   3969 error_open:
   3970     free(out);
   3971     *stream_out = NULL;
   3972     ALOGW("%s: exit: ret %d", __func__, ret);
   3973     return ret;
   3974 }
   3975 
   3976 static void adev_close_output_stream(struct audio_hw_device *dev __unused,
   3977                                      struct audio_stream_out *stream)
   3978 {
   3979     struct stream_out *out = (struct stream_out *)stream;
   3980     struct audio_device *adev = out->dev;
   3981 
   3982     ALOGV("%s: enter", __func__);
   3983 
   3984     // must deregister from sndmonitor first to prevent races
   3985     // between the callback and close_stream
   3986     audio_extn_snd_mon_unregister_listener(out);
   3987     out_standby(&stream->common);
   3988     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3989         destroy_offload_callback_thread(out);
   3990 
   3991         if (out->compr_config.codec != NULL)
   3992             free(out->compr_config.codec);
   3993     }
   3994 
   3995     if (adev->voice_tx_output == out)
   3996         adev->voice_tx_output = NULL;
   3997 
   3998     error_log_destroy(out->error_log);
   3999     out->error_log = NULL;
   4000 
   4001     pthread_cond_destroy(&out->cond);
   4002     pthread_mutex_destroy(&out->lock);
   4003     free(stream);
   4004     ALOGV("%s: exit", __func__);
   4005 }
   4006 
   4007 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
   4008 {
   4009     struct audio_device *adev = (struct audio_device *)dev;
   4010     struct str_parms *parms;
   4011     char *str;
   4012     char value[32];
   4013     int val;
   4014     int ret;
   4015     int status = 0;
   4016 
   4017     ALOGV("%s: enter: %s", __func__, kvpairs);
   4018 
   4019     pthread_mutex_lock(&adev->lock);
   4020 
   4021     parms = str_parms_create_str(kvpairs);
   4022     status = voice_set_parameters(adev, parms);
   4023     if (status != 0) {
   4024         goto done;
   4025     }
   4026 
   4027     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
   4028     if (ret >= 0) {
   4029         /* When set to false, HAL should disable EC and NS */
   4030         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   4031             adev->bluetooth_nrec = true;
   4032         else
   4033             adev->bluetooth_nrec = false;
   4034     }
   4035 
   4036     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
   4037     if (ret >= 0) {
   4038         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   4039             adev->screen_off = false;
   4040         else
   4041             adev->screen_off = true;
   4042     }
   4043 
   4044     ret = str_parms_get_int(parms, "rotation", &val);
   4045     if (ret >= 0) {
   4046         bool reverse_speakers = false;
   4047         switch(val) {
   4048         // FIXME: note that the code below assumes that the speakers are in the correct placement
   4049         //   relative to the user when the device is rotated 90deg from its default rotation. This
   4050         //   assumption is device-specific, not platform-specific like this code.
   4051         case 270:
   4052             reverse_speakers = true;
   4053             break;
   4054         case 0:
   4055         case 90:
   4056         case 180:
   4057             break;
   4058         default:
   4059             ALOGE("%s: unexpected rotation of %d", __func__, val);
   4060             status = -EINVAL;
   4061         }
   4062         if (status == 0) {
   4063             // check and set swap
   4064             //   - check if orientation changed and speaker active
   4065             //   - set rotation and cache the rotation value
   4066             platform_check_and_set_swap_lr_channels(adev, reverse_speakers);
   4067         }
   4068     }
   4069 
   4070     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value));
   4071     if (ret >= 0) {
   4072         adev->bt_wb_speech_enabled = !strcmp(value, AUDIO_PARAMETER_VALUE_ON);
   4073     }
   4074 
   4075     ret = str_parms_get_str(parms, AUDIO_PARAMETER_DEVICE_CONNECT, value, sizeof(value));
   4076     if (ret >= 0) {
   4077         audio_devices_t device = (audio_devices_t)strtoul(value, NULL, 10);
   4078         if (audio_is_usb_out_device(device)) {
   4079             ret = str_parms_get_str(parms, "card", value, sizeof(value));
   4080             if (ret >= 0) {
   4081                 const int card = atoi(value);
   4082                 audio_extn_usb_add_device(device, card);
   4083             }
   4084         } else if (audio_is_usb_in_device(device)) {
   4085             ret = str_parms_get_str(parms, "card", value, sizeof(value));
   4086             if (ret >= 0) {
   4087                 const int card = atoi(value);
   4088                 audio_extn_usb_add_device(device, card);
   4089             }
   4090         }
   4091     }
   4092 
   4093     ret = str_parms_get_str(parms, AUDIO_PARAMETER_DEVICE_DISCONNECT, value, sizeof(value));
   4094     if (ret >= 0) {
   4095         audio_devices_t device = (audio_devices_t)strtoul(value, NULL, 10);
   4096         if (audio_is_usb_out_device(device)) {
   4097             ret = str_parms_get_str(parms, "card", value, sizeof(value));
   4098             if (ret >= 0) {
   4099                 const int card = atoi(value);
   4100 
   4101                 audio_extn_usb_remove_device(device, card);
   4102             }
   4103         } else if (audio_is_usb_in_device(device)) {
   4104             ret = str_parms_get_str(parms, "card", value, sizeof(value));
   4105             if (ret >= 0) {
   4106                 const int card = atoi(value);
   4107                 audio_extn_usb_remove_device(device, card);
   4108             }
   4109         }
   4110     }
   4111 
   4112     audio_extn_hfp_set_parameters(adev, parms);
   4113 done:
   4114     str_parms_destroy(parms);
   4115     pthread_mutex_unlock(&adev->lock);
   4116     ALOGV("%s: exit with code(%d)", __func__, status);
   4117     return status;
   4118 }
   4119 
   4120 static char* adev_get_parameters(const struct audio_hw_device *dev,
   4121                                  const char *keys)
   4122 {
   4123     struct audio_device *adev = (struct audio_device *)dev;
   4124     struct str_parms *reply = str_parms_create();
   4125     struct str_parms *query = str_parms_create_str(keys);
   4126     char *str;
   4127 
   4128     pthread_mutex_lock(&adev->lock);
   4129 
   4130     voice_get_parameters(adev, query, reply);
   4131     str = str_parms_to_str(reply);
   4132     str_parms_destroy(query);
   4133     str_parms_destroy(reply);
   4134 
   4135     pthread_mutex_unlock(&adev->lock);
   4136     ALOGV("%s: exit: returns - %s", __func__, str);
   4137     return str;
   4138 }
   4139 
   4140 static int adev_init_check(const struct audio_hw_device *dev __unused)
   4141 {
   4142     return 0;
   4143 }
   4144 
   4145 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
   4146 {
   4147     int ret;
   4148     struct audio_device *adev = (struct audio_device *)dev;
   4149 
   4150     audio_extn_extspk_set_voice_vol(adev->extspk, volume);
   4151 
   4152     pthread_mutex_lock(&adev->lock);
   4153     ret = voice_set_volume(adev, volume);
   4154     pthread_mutex_unlock(&adev->lock);
   4155 
   4156     return ret;
   4157 }
   4158 
   4159 static int adev_set_master_volume(struct audio_hw_device *dev __unused, float volume __unused)
   4160 {
   4161     return -ENOSYS;
   4162 }
   4163 
   4164 static int adev_get_master_volume(struct audio_hw_device *dev __unused,
   4165                                   float *volume __unused)
   4166 {
   4167     return -ENOSYS;
   4168 }
   4169 
   4170 static int adev_set_master_mute(struct audio_hw_device *dev __unused, bool muted __unused)
   4171 {
   4172     return -ENOSYS;
   4173 }
   4174 
   4175 static int adev_get_master_mute(struct audio_hw_device *dev __unused, bool *muted __unused)
   4176 {
   4177     return -ENOSYS;
   4178 }
   4179 
   4180 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
   4181 {
   4182     struct audio_device *adev = (struct audio_device *)dev;
   4183 
   4184     pthread_mutex_lock(&adev->lock);
   4185     if (adev->mode != mode) {
   4186         ALOGD("%s: mode %d", __func__, (int)mode);
   4187         adev->mode = mode;
   4188         if ((mode == AUDIO_MODE_NORMAL || mode == AUDIO_MODE_IN_COMMUNICATION) &&
   4189                 voice_is_in_call(adev)) {
   4190             voice_stop_call(adev);
   4191             adev->current_call_output = NULL;
   4192         }
   4193     }
   4194     pthread_mutex_unlock(&adev->lock);
   4195 
   4196     audio_extn_extspk_set_mode(adev->extspk, mode);
   4197 
   4198     return 0;
   4199 }
   4200 
   4201 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
   4202 {
   4203     int ret;
   4204     struct audio_device *adev = (struct audio_device *)dev;
   4205 
   4206     ALOGD("%s: state %d", __func__, (int)state);
   4207     pthread_mutex_lock(&adev->lock);
   4208     if (audio_extn_tfa_98xx_is_supported() && adev->enable_hfp) {
   4209         ret = audio_extn_hfp_set_mic_mute(adev, state);
   4210     } else {
   4211         ret = voice_set_mic_mute(adev, state);
   4212     }
   4213     adev->mic_muted = state;
   4214     pthread_mutex_unlock(&adev->lock);
   4215 
   4216     return ret;
   4217 }
   4218 
   4219 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
   4220 {
   4221     *state = voice_get_mic_mute((struct audio_device *)dev);
   4222     return 0;
   4223 }
   4224 
   4225 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev __unused,
   4226                                          const struct audio_config *config)
   4227 {
   4228     int channel_count = audio_channel_count_from_in_mask(config->channel_mask);
   4229 
   4230     /* Don't know if USB HIFI in this context so use true to be conservative */
   4231     if (check_input_parameters(config->sample_rate, config->format, channel_count,
   4232                                true /*is_usb_hifi */) != 0)
   4233         return 0;
   4234 
   4235     return get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
   4236                                  config->sample_rate, config->format,
   4237                                  channel_count,
   4238                                  false /* is_low_latency: since we don't know, be conservative */);
   4239 }
   4240 
   4241 static bool adev_input_allow_hifi_record(struct audio_device *adev,
   4242                                          audio_devices_t devices,
   4243                                          audio_input_flags_t flags,
   4244                                          audio_source_t source) {
   4245     const bool allowed = true;
   4246 
   4247     if (!audio_is_usb_in_device(devices))
   4248         return !allowed;
   4249 
   4250     switch (flags) {
   4251         case AUDIO_INPUT_FLAG_NONE:
   4252         case AUDIO_INPUT_FLAG_FAST: // just fast, not fast|raw || fast|mmap
   4253             break;
   4254         default:
   4255             return !allowed;
   4256     }
   4257 
   4258     switch (source) {
   4259         case AUDIO_SOURCE_DEFAULT:
   4260         case AUDIO_SOURCE_MIC:
   4261         case AUDIO_SOURCE_UNPROCESSED:
   4262             break;
   4263         default:
   4264             return !allowed;
   4265     }
   4266 
   4267     switch (adev->mode) {
   4268         case 0:
   4269             break;
   4270         default:
   4271             return !allowed;
   4272     }
   4273 
   4274     return allowed;
   4275 }
   4276 
   4277 static int adev_open_input_stream(struct audio_hw_device *dev,
   4278                                   audio_io_handle_t handle,
   4279                                   audio_devices_t devices,
   4280                                   struct audio_config *config,
   4281                                   struct audio_stream_in **stream_in,
   4282                                   audio_input_flags_t flags,
   4283                                   const char *address __unused,
   4284                                   audio_source_t source )
   4285 {
   4286     struct audio_device *adev = (struct audio_device *)dev;
   4287     struct stream_in *in;
   4288     int ret = 0, buffer_size, frame_size;
   4289     int channel_count;
   4290     bool is_low_latency = false;
   4291     bool is_usb_dev = audio_is_usb_in_device(devices);
   4292     bool may_use_hifi_record = adev_input_allow_hifi_record(adev,
   4293                                                             devices,
   4294                                                             flags,
   4295                                                             source);
   4296     ALOGV("%s: enter", __func__);
   4297     *stream_in = NULL;
   4298 
   4299     if (is_usb_dev && !is_usb_ready(adev, false /* is_playback */)) {
   4300         return -ENOSYS;
   4301     }
   4302 
   4303     if (!(is_usb_dev && may_use_hifi_record)) {
   4304         if (config->sample_rate == 0)
   4305             config->sample_rate = DEFAULT_INPUT_SAMPLING_RATE;
   4306         if (config->channel_mask == AUDIO_CHANNEL_NONE)
   4307             config->channel_mask = AUDIO_CHANNEL_IN_MONO;
   4308         if (config->format == AUDIO_FORMAT_DEFAULT)
   4309             config->format = AUDIO_FORMAT_PCM_16_BIT;
   4310 
   4311         channel_count = audio_channel_count_from_in_mask(config->channel_mask);
   4312 
   4313         if (check_input_parameters(config->sample_rate, config->format, channel_count, false) != 0)
   4314             return -EINVAL;
   4315     }
   4316 
   4317     if (audio_extn_tfa_98xx_is_supported() &&
   4318         (audio_extn_hfp_is_active(adev) || voice_is_in_call(adev)))
   4319         return -EINVAL;
   4320 
   4321     in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
   4322 
   4323     pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
   4324     pthread_mutex_init(&in->pre_lock, (const pthread_mutexattr_t *) NULL);
   4325 
   4326     in->stream.common.get_sample_rate = in_get_sample_rate;
   4327     in->stream.common.set_sample_rate = in_set_sample_rate;
   4328     in->stream.common.get_buffer_size = in_get_buffer_size;
   4329     in->stream.common.get_channels = in_get_channels;
   4330     in->stream.common.get_format = in_get_format;
   4331     in->stream.common.set_format = in_set_format;
   4332     in->stream.common.standby = in_standby;
   4333     in->stream.common.dump = in_dump;
   4334     in->stream.common.set_parameters = in_set_parameters;
   4335     in->stream.common.get_parameters = in_get_parameters;
   4336     in->stream.common.add_audio_effect = in_add_audio_effect;
   4337     in->stream.common.remove_audio_effect = in_remove_audio_effect;
   4338     in->stream.set_gain = in_set_gain;
   4339     in->stream.read = in_read;
   4340     in->stream.get_input_frames_lost = in_get_input_frames_lost;
   4341     in->stream.get_capture_position = in_get_capture_position;
   4342 
   4343     in->device = devices;
   4344     in->source = source;
   4345     in->dev = adev;
   4346     in->standby = 1;
   4347     in->capture_handle = handle;
   4348     in->flags = flags;
   4349 
   4350     if (is_usb_dev && may_use_hifi_record) {
   4351         /* HiFi record selects an appropriate format, channel, rate combo
   4352            depending on sink capabilities*/
   4353         ret = read_usb_sup_params_and_compare(false /*is_playback*/,
   4354                                               &config->format,
   4355                                               &in->supported_formats[0],
   4356                                               MAX_SUPPORTED_FORMATS,
   4357                                               &config->channel_mask,
   4358                                               &in->supported_channel_masks[0],
   4359                                               MAX_SUPPORTED_CHANNEL_MASKS,
   4360                                               &config->sample_rate,
   4361                                               &in->supported_sample_rates[0],
   4362                                               MAX_SUPPORTED_SAMPLE_RATES);
   4363         if (ret != 0) {
   4364             ret = -EINVAL;
   4365             goto err_open;
   4366         }
   4367         channel_count = audio_channel_count_from_in_mask(config->channel_mask);
   4368     } else if (config->format == AUDIO_FORMAT_DEFAULT) {
   4369         config->format = AUDIO_FORMAT_PCM_16_BIT;
   4370     } else if (config->format == AUDIO_FORMAT_PCM_FLOAT ||
   4371                config->format == AUDIO_FORMAT_PCM_24_BIT_PACKED ||
   4372                config->format == AUDIO_FORMAT_PCM_8_24_BIT) {
   4373         bool ret_error = false;
   4374         /* 24 bit is restricted to UNPROCESSED source only,also format supported
   4375            from HAL is 8_24
   4376            *> In case of UNPROCESSED source, for 24 bit, if format requested is other than
   4377               8_24 return error indicating supported format is 8_24
   4378            *> In case of any other source requesting 24 bit or float return error
   4379               indicating format supported is 16 bit only.
   4380 
   4381            on error flinger will retry with supported format passed
   4382          */
   4383         if (source != AUDIO_SOURCE_UNPROCESSED) {
   4384             config->format = AUDIO_FORMAT_PCM_16_BIT;
   4385             ret_error = true;
   4386         } else if (config->format != AUDIO_FORMAT_PCM_8_24_BIT) {
   4387             config->format = AUDIO_FORMAT_PCM_8_24_BIT;
   4388             ret_error = true;
   4389         }
   4390 
   4391         if (ret_error) {
   4392             ret = -EINVAL;
   4393             goto err_open;
   4394         }
   4395     }
   4396 
   4397     in->format = config->format;
   4398     in->channel_mask = config->channel_mask;
   4399 
   4400     /* Update config params with the requested sample rate and channels */
   4401     if (in->device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
   4402         if (config->sample_rate == 0)
   4403             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
   4404         if (config->sample_rate != 48000 && config->sample_rate != 16000 &&
   4405                 config->sample_rate != 8000) {
   4406             config->sample_rate = AFE_PROXY_SAMPLING_RATE;
   4407             ret = -EINVAL;
   4408             goto err_open;
   4409         }
   4410 
   4411         if (config->format != AUDIO_FORMAT_PCM_16_BIT) {
   4412             config->format = AUDIO_FORMAT_PCM_16_BIT;
   4413             ret = -EINVAL;
   4414             goto err_open;
   4415         }
   4416 
   4417         in->usecase = USECASE_AUDIO_RECORD_AFE_PROXY;
   4418         in->config = pcm_config_afe_proxy_record;
   4419         in->af_period_multiplier = 1;
   4420     } else if (is_usb_dev && may_use_hifi_record) {
   4421         in->usecase = USECASE_AUDIO_RECORD_HIFI;
   4422         in->config = pcm_config_audio_capture;
   4423         frame_size = audio_stream_in_frame_size(&in->stream);
   4424         buffer_size = get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
   4425                                              config->sample_rate,
   4426                                              config->format,
   4427                                              channel_count,
   4428                                              false /*is_low_latency*/);
   4429         in->config.period_size = buffer_size / frame_size;
   4430         in->config.rate = config->sample_rate;
   4431         in->af_period_multiplier = 1;
   4432         in->config.format = pcm_format_from_audio_format(config->format);
   4433     } else {
   4434         in->usecase = USECASE_AUDIO_RECORD;
   4435         if (config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE &&
   4436                 (in->flags & AUDIO_INPUT_FLAG_FAST) != 0) {
   4437             is_low_latency = true;
   4438 #if LOW_LATENCY_CAPTURE_USE_CASE
   4439             in->usecase = USECASE_AUDIO_RECORD_LOW_LATENCY;
   4440 #endif
   4441             in->realtime = may_use_noirq_mode(adev, in->usecase, in->flags);
   4442             if (!in->realtime) {
   4443                 in->config = pcm_config_audio_capture;
   4444                 frame_size = audio_stream_in_frame_size(&in->stream);
   4445                 buffer_size = get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
   4446                                                      config->sample_rate,
   4447                                                      config->format,
   4448                                                      channel_count,
   4449                                                      is_low_latency);
   4450                 in->config.period_size = buffer_size / frame_size;
   4451                 in->config.rate = config->sample_rate;
   4452                 in->af_period_multiplier = 1;
   4453             } else {
   4454                 // period size is left untouched for rt mode playback
   4455                 in->config = pcm_config_audio_capture_rt;
   4456                 in->af_period_multiplier = af_period_multiplier;
   4457             }
   4458         } else if ((config->sample_rate == LOW_LATENCY_CAPTURE_SAMPLE_RATE) &&
   4459                 ((in->flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0)) {
   4460             // FIXME: Add support for multichannel capture over USB using MMAP
   4461             in->usecase = USECASE_AUDIO_RECORD_MMAP;
   4462             in->config = pcm_config_mmap_capture;
   4463             in->stream.start = in_start;
   4464             in->stream.stop = in_stop;
   4465             in->stream.create_mmap_buffer = in_create_mmap_buffer;
   4466             in->stream.get_mmap_position = in_get_mmap_position;
   4467             in->af_period_multiplier = 1;
   4468             ALOGV("%s: USECASE_AUDIO_RECORD_MMAP", __func__);
   4469         } else if (in->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
   4470                    in->flags & AUDIO_INPUT_FLAG_VOIP_TX &&
   4471                    (config->sample_rate == 8000 ||
   4472                     config->sample_rate == 16000 ||
   4473                     config->sample_rate == 32000 ||
   4474                     config->sample_rate == 48000) &&
   4475                    channel_count == 1) {
   4476             in->usecase = USECASE_AUDIO_RECORD_VOIP;
   4477             in->config = pcm_config_audio_capture;
   4478             frame_size = audio_stream_in_frame_size(&in->stream);
   4479             buffer_size = get_stream_buffer_size(VOIP_CAPTURE_PERIOD_DURATION_MSEC,
   4480                                                  config->sample_rate,
   4481                                                  config->format,
   4482                                                  channel_count, false /*is_low_latency*/);
   4483             in->config.period_size = buffer_size / frame_size;
   4484             in->config.period_count = VOIP_CAPTURE_PERIOD_COUNT;
   4485             in->config.rate = config->sample_rate;
   4486             in->af_period_multiplier = 1;
   4487         } else {
   4488             in->config = pcm_config_audio_capture;
   4489             frame_size = audio_stream_in_frame_size(&in->stream);
   4490             buffer_size = get_stream_buffer_size(AUDIO_CAPTURE_PERIOD_DURATION_MSEC,
   4491                                                  config->sample_rate,
   4492                                                  config->format,
   4493                                                  channel_count,
   4494                                                  is_low_latency);
   4495             in->config.period_size = buffer_size / frame_size;
   4496             in->config.rate = config->sample_rate;
   4497             in->af_period_multiplier = 1;
   4498         }
   4499         if (config->format == AUDIO_FORMAT_PCM_8_24_BIT)
   4500             in->config.format = PCM_FORMAT_S24_LE;
   4501     }
   4502 
   4503     in->config.channels = channel_count;
   4504     in->sample_rate  = in->config.rate;
   4505 
   4506     in->error_log = error_log_create(
   4507             ERROR_LOG_ENTRIES,
   4508             NANOS_PER_SECOND /* aggregate consecutive identical errors within one second */);
   4509 
   4510     /* This stream could be for sound trigger lab,
   4511        get sound trigger pcm if present */
   4512     audio_extn_sound_trigger_check_and_get_session(in);
   4513 
   4514     lock_input_stream(in);
   4515     audio_extn_snd_mon_register_listener(in, in_snd_mon_cb);
   4516     pthread_mutex_lock(&adev->lock);
   4517     in->card_status = adev->card_status;
   4518     pthread_mutex_unlock(&adev->lock);
   4519     pthread_mutex_unlock(&in->lock);
   4520 
   4521     stream_app_type_cfg_init(&in->app_type_cfg);
   4522 
   4523     *stream_in = &in->stream;
   4524     ALOGV("%s: exit", __func__);
   4525     return 0;
   4526 
   4527 err_open:
   4528     free(in);
   4529     *stream_in = NULL;
   4530     return ret;
   4531 }
   4532 
   4533 static void adev_close_input_stream(struct audio_hw_device *dev __unused,
   4534                                     struct audio_stream_in *stream)
   4535 {
   4536     struct stream_in *in = (struct stream_in *)stream;
   4537     ALOGV("%s", __func__);
   4538 
   4539     // must deregister from sndmonitor first to prevent races
   4540     // between the callback and close_stream
   4541     audio_extn_snd_mon_unregister_listener(stream);
   4542     in_standby(&stream->common);
   4543 
   4544     error_log_destroy(in->error_log);
   4545     in->error_log = NULL;
   4546 
   4547     free(stream);
   4548 
   4549     return;
   4550 }
   4551 
   4552 static int adev_dump(const audio_hw_device_t *device __unused, int fd __unused)
   4553 {
   4554     return 0;
   4555 }
   4556 
   4557 /* verifies input and output devices and their capabilities.
   4558  *
   4559  * This verification is required when enabling extended bit-depth or
   4560  * sampling rates, as not all qcom products support it.
   4561  *
   4562  * Suitable for calling only on initialization such as adev_open().
   4563  * It fills the audio_device use_case_table[] array.
   4564  *
   4565  * Has a side-effect that it needs to configure audio routing / devices
   4566  * in order to power up the devices and read the device parameters.
   4567  * It does not acquire any hw device lock. Should restore the devices
   4568  * back to "normal state" upon completion.
   4569  */
   4570 static int adev_verify_devices(struct audio_device *adev)
   4571 {
   4572     /* enumeration is a bit difficult because one really wants to pull
   4573      * the use_case, device id, etc from the hidden pcm_device_table[].
   4574      * In this case there are the following use cases and device ids.
   4575      *
   4576      * [USECASE_AUDIO_PLAYBACK_DEEP_BUFFER] = {0, 0},
   4577      * [USECASE_AUDIO_PLAYBACK_LOW_LATENCY] = {15, 15},
   4578      * [USECASE_AUDIO_PLAYBACK_HIFI] = {1, 1},
   4579      * [USECASE_AUDIO_PLAYBACK_OFFLOAD] = {9, 9},
   4580      * [USECASE_AUDIO_RECORD] = {0, 0},
   4581      * [USECASE_AUDIO_RECORD_LOW_LATENCY] = {15, 15},
   4582      * [USECASE_VOICE_CALL] = {2, 2},
   4583      *
   4584      * USECASE_AUDIO_PLAYBACK_OFFLOAD, USECASE_AUDIO_PLAYBACK_HIFI omitted.
   4585      * USECASE_VOICE_CALL omitted, but possible for either input or output.
   4586      */
   4587 
   4588     /* should be the usecases enabled in adev_open_input_stream() */
   4589     static const int test_in_usecases[] = {
   4590              USECASE_AUDIO_RECORD,
   4591              USECASE_AUDIO_RECORD_LOW_LATENCY, /* does not appear to be used */
   4592     };
   4593     /* should be the usecases enabled in adev_open_output_stream()*/
   4594     static const int test_out_usecases[] = {
   4595             USECASE_AUDIO_PLAYBACK_DEEP_BUFFER,
   4596             USECASE_AUDIO_PLAYBACK_LOW_LATENCY,
   4597     };
   4598     static const usecase_type_t usecase_type_by_dir[] = {
   4599             PCM_PLAYBACK,
   4600             PCM_CAPTURE,
   4601     };
   4602     static const unsigned flags_by_dir[] = {
   4603             PCM_OUT,
   4604             PCM_IN,
   4605     };
   4606 
   4607     size_t i;
   4608     unsigned dir;
   4609     const unsigned card_id = adev->snd_card;
   4610     char info[512]; /* for possible debug info */
   4611 
   4612     for (dir = 0; dir < 2; ++dir) {
   4613         const usecase_type_t usecase_type = usecase_type_by_dir[dir];
   4614         const unsigned flags_dir = flags_by_dir[dir];
   4615         const size_t testsize =
   4616                 dir ? ARRAY_SIZE(test_in_usecases) : ARRAY_SIZE(test_out_usecases);
   4617         const int *testcases =
   4618                 dir ? test_in_usecases : test_out_usecases;
   4619         const audio_devices_t audio_device =
   4620                 dir ? AUDIO_DEVICE_IN_BUILTIN_MIC : AUDIO_DEVICE_OUT_SPEAKER;
   4621 
   4622         for (i = 0; i < testsize; ++i) {
   4623             const audio_usecase_t audio_usecase = testcases[i];
   4624             int device_id;
   4625             snd_device_t snd_device;
   4626             struct pcm_params **pparams;
   4627             struct stream_out out;
   4628             struct stream_in in;
   4629             struct audio_usecase uc_info;
   4630             int retval;
   4631 
   4632             pparams = &adev->use_case_table[audio_usecase];
   4633             pcm_params_free(*pparams); /* can accept null input */
   4634             *pparams = NULL;
   4635 
   4636             /* find the device ID for the use case (signed, for error) */
   4637             device_id = platform_get_pcm_device_id(audio_usecase, usecase_type);
   4638             if (device_id < 0)
   4639                 continue;
   4640 
   4641             /* prepare structures for device probing */
   4642             memset(&uc_info, 0, sizeof(uc_info));
   4643             uc_info.id = audio_usecase;
   4644             uc_info.type = usecase_type;
   4645             if (dir) {
   4646                 adev->active_input = &in;
   4647                 memset(&in, 0, sizeof(in));
   4648                 in.device = audio_device;
   4649                 in.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
   4650                 uc_info.stream.in = &in;
   4651             }  else {
   4652                 adev->active_input = NULL;
   4653             }
   4654             memset(&out, 0, sizeof(out));
   4655             out.devices = audio_device; /* only field needed in select_devices */
   4656             uc_info.stream.out = &out;
   4657             uc_info.devices = audio_device;
   4658             uc_info.in_snd_device = SND_DEVICE_NONE;
   4659             uc_info.out_snd_device = SND_DEVICE_NONE;
   4660             list_add_tail(&adev->usecase_list, &uc_info.list);
   4661 
   4662             /* select device - similar to start_(in/out)put_stream() */
   4663             retval = select_devices(adev, audio_usecase);
   4664             if (retval >= 0) {
   4665                 *pparams = pcm_params_get(card_id, device_id, flags_dir);
   4666 #if LOG_NDEBUG == 0
   4667                 if (*pparams) {
   4668                     ALOGV("%s: (%s) card %d  device %d", __func__,
   4669                             dir ? "input" : "output", card_id, device_id);
   4670                     pcm_params_to_string(*pparams, info, ARRAY_SIZE(info));
   4671                 } else {
   4672                     ALOGV("%s: cannot locate card %d  device %d", __func__, card_id, device_id);
   4673                 }
   4674 #endif
   4675             }
   4676 
   4677             /* deselect device - similar to stop_(in/out)put_stream() */
   4678             /* 1. Get and set stream specific mixer controls */
   4679             retval = disable_audio_route(adev, &uc_info);
   4680             /* 2. Disable the rx device */
   4681             retval = disable_snd_device(adev,
   4682                     dir ? uc_info.in_snd_device : uc_info.out_snd_device);
   4683             list_remove(&uc_info.list);
   4684         }
   4685     }
   4686     adev->active_input = NULL; /* restore adev state */
   4687     return 0;
   4688 }
   4689 
   4690 static int adev_close(hw_device_t *device)
   4691 {
   4692     size_t i;
   4693     struct audio_device *adev = (struct audio_device *)device;
   4694 
   4695     if (!adev)
   4696         return 0;
   4697 
   4698     pthread_mutex_lock(&adev_init_lock);
   4699 
   4700     if ((--audio_device_ref_count) == 0) {
   4701         audio_extn_snd_mon_unregister_listener(adev);
   4702         audio_extn_tfa_98xx_deinit();
   4703         audio_route_free(adev->audio_route);
   4704         free(adev->snd_dev_ref_cnt);
   4705         platform_deinit(adev->platform);
   4706         audio_extn_extspk_deinit(adev->extspk);
   4707         audio_extn_sound_trigger_deinit(adev);
   4708         audio_extn_snd_mon_deinit();
   4709         for (i = 0; i < ARRAY_SIZE(adev->use_case_table); ++i) {
   4710             pcm_params_free(adev->use_case_table[i]);
   4711         }
   4712         if (adev->adm_deinit)
   4713             adev->adm_deinit(adev->adm_data);
   4714         free(device);
   4715     }
   4716 
   4717     pthread_mutex_unlock(&adev_init_lock);
   4718 
   4719     return 0;
   4720 }
   4721 
   4722 /* This returns 1 if the input parameter looks at all plausible as a low latency period size,
   4723  * or 0 otherwise.  A return value of 1 doesn't mean the value is guaranteed to work,
   4724  * just that it _might_ work.
   4725  */
   4726 static int period_size_is_plausible_for_low_latency(int period_size)
   4727 {
   4728     switch (period_size) {
   4729     case 48:
   4730     case 96:
   4731     case 144:
   4732     case 160:
   4733     case 192:
   4734     case 240:
   4735     case 320:
   4736     case 480:
   4737         return 1;
   4738     default:
   4739         return 0;
   4740     }
   4741 }
   4742 
   4743 static void adev_snd_mon_cb(void * stream __unused, struct str_parms * parms)
   4744 {
   4745     int card;
   4746     card_status_t status;
   4747 
   4748     if (!parms)
   4749         return;
   4750 
   4751     if (parse_snd_card_status(parms, &card, &status) < 0)
   4752         return;
   4753 
   4754     pthread_mutex_lock(&adev->lock);
   4755     bool valid_cb = (card == adev->snd_card);
   4756     if (valid_cb) {
   4757         if (adev->card_status != status) {
   4758             adev->card_status = status;
   4759             platform_snd_card_update(adev->platform, status);
   4760         }
   4761     }
   4762     pthread_mutex_unlock(&adev->lock);
   4763     return;
   4764 }
   4765 
   4766 static int adev_open(const hw_module_t *module, const char *name,
   4767                      hw_device_t **device)
   4768 {
   4769     int i, ret;
   4770 
   4771     ALOGD("%s: enter", __func__);
   4772     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
   4773     pthread_mutex_lock(&adev_init_lock);
   4774     if (audio_device_ref_count != 0) {
   4775         *device = &adev->device.common;
   4776         audio_device_ref_count++;
   4777         ALOGV("%s: returning existing instance of adev", __func__);
   4778         ALOGV("%s: exit", __func__);
   4779         pthread_mutex_unlock(&adev_init_lock);
   4780         return 0;
   4781     }
   4782     adev = calloc(1, sizeof(struct audio_device));
   4783 
   4784     pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
   4785 
   4786     adev->device.common.tag = HARDWARE_DEVICE_TAG;
   4787     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
   4788     adev->device.common.module = (struct hw_module_t *)module;
   4789     adev->device.common.close = adev_close;
   4790 
   4791     adev->device.init_check = adev_init_check;
   4792     adev->device.set_voice_volume = adev_set_voice_volume;
   4793     adev->device.set_master_volume = adev_set_master_volume;
   4794     adev->device.get_master_volume = adev_get_master_volume;
   4795     adev->device.set_master_mute = adev_set_master_mute;
   4796     adev->device.get_master_mute = adev_get_master_mute;
   4797     adev->device.set_mode = adev_set_mode;
   4798     adev->device.set_mic_mute = adev_set_mic_mute;
   4799     adev->device.get_mic_mute = adev_get_mic_mute;
   4800     adev->device.set_parameters = adev_set_parameters;
   4801     adev->device.get_parameters = adev_get_parameters;
   4802     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
   4803     adev->device.open_output_stream = adev_open_output_stream;
   4804     adev->device.close_output_stream = adev_close_output_stream;
   4805     adev->device.open_input_stream = adev_open_input_stream;
   4806 
   4807     adev->device.close_input_stream = adev_close_input_stream;
   4808     adev->device.dump = adev_dump;
   4809 
   4810     /* Set the default route before the PCM stream is opened */
   4811     pthread_mutex_lock(&adev->lock);
   4812     adev->mode = AUDIO_MODE_NORMAL;
   4813     adev->active_input = NULL;
   4814     adev->primary_output = NULL;
   4815     adev->bluetooth_nrec = true;
   4816     adev->acdb_settings = TTY_MODE_OFF;
   4817     /* adev->cur_hdmi_channels = 0;  by calloc() */
   4818     adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
   4819     voice_init(adev);
   4820     list_init(&adev->usecase_list);
   4821     pthread_mutex_unlock(&adev->lock);
   4822 
   4823     /* Loads platform specific libraries dynamically */
   4824     adev->platform = platform_init(adev);
   4825     if (!adev->platform) {
   4826         free(adev->snd_dev_ref_cnt);
   4827         free(adev);
   4828         ALOGE("%s: Failed to init platform data, aborting.", __func__);
   4829         *device = NULL;
   4830         pthread_mutex_unlock(&adev_init_lock);
   4831         return -EINVAL;
   4832     }
   4833     adev->extspk = audio_extn_extspk_init(adev);
   4834 
   4835     adev->visualizer_lib = dlopen(VISUALIZER_LIBRARY_PATH, RTLD_NOW);
   4836     if (adev->visualizer_lib == NULL) {
   4837         ALOGW("%s: DLOPEN failed for %s", __func__, VISUALIZER_LIBRARY_PATH);
   4838     } else {
   4839         ALOGV("%s: DLOPEN successful for %s", __func__, VISUALIZER_LIBRARY_PATH);
   4840         adev->visualizer_start_output =
   4841                     (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
   4842                                                     "visualizer_hal_start_output");
   4843         adev->visualizer_stop_output =
   4844                     (int (*)(audio_io_handle_t, int))dlsym(adev->visualizer_lib,
   4845                                                     "visualizer_hal_stop_output");
   4846     }
   4847 
   4848     adev->offload_effects_lib = dlopen(OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH, RTLD_NOW);
   4849     if (adev->offload_effects_lib == NULL) {
   4850         ALOGW("%s: DLOPEN failed for %s", __func__,
   4851               OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
   4852     } else {
   4853         ALOGV("%s: DLOPEN successful for %s", __func__,
   4854               OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH);
   4855         adev->offload_effects_start_output =
   4856                     (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
   4857                                      "offload_effects_bundle_hal_start_output");
   4858         adev->offload_effects_stop_output =
   4859                     (int (*)(audio_io_handle_t, int))dlsym(adev->offload_effects_lib,
   4860                                      "offload_effects_bundle_hal_stop_output");
   4861     }
   4862 
   4863     adev->adm_lib = dlopen(ADM_LIBRARY_PATH, RTLD_NOW);
   4864     if (adev->adm_lib == NULL) {
   4865         ALOGW("%s: DLOPEN failed for %s", __func__, ADM_LIBRARY_PATH);
   4866     } else {
   4867         ALOGV("%s: DLOPEN successful for %s", __func__, ADM_LIBRARY_PATH);
   4868         adev->adm_init = (adm_init_t)
   4869                                 dlsym(adev->adm_lib, "adm_init");
   4870         adev->adm_deinit = (adm_deinit_t)
   4871                                 dlsym(adev->adm_lib, "adm_deinit");
   4872         adev->adm_register_input_stream = (adm_register_input_stream_t)
   4873                                 dlsym(adev->adm_lib, "adm_register_input_stream");
   4874         adev->adm_register_output_stream = (adm_register_output_stream_t)
   4875                                 dlsym(adev->adm_lib, "adm_register_output_stream");
   4876         adev->adm_deregister_stream = (adm_deregister_stream_t)
   4877                                 dlsym(adev->adm_lib, "adm_deregister_stream");
   4878         adev->adm_request_focus = (adm_request_focus_t)
   4879                                 dlsym(adev->adm_lib, "adm_request_focus");
   4880         adev->adm_abandon_focus = (adm_abandon_focus_t)
   4881                                 dlsym(adev->adm_lib, "adm_abandon_focus");
   4882         adev->adm_set_config = (adm_set_config_t)
   4883                                     dlsym(adev->adm_lib, "adm_set_config");
   4884         adev->adm_request_focus_v2 = (adm_request_focus_v2_t)
   4885                                     dlsym(adev->adm_lib, "adm_request_focus_v2");
   4886         adev->adm_is_noirq_avail = (adm_is_noirq_avail_t)
   4887                                     dlsym(adev->adm_lib, "adm_is_noirq_avail");
   4888         adev->adm_on_routing_change = (adm_on_routing_change_t)
   4889                                     dlsym(adev->adm_lib, "adm_on_routing_change");
   4890     }
   4891 
   4892     adev->bt_wb_speech_enabled = false;
   4893     adev->enable_voicerx = false;
   4894 
   4895     *device = &adev->device.common;
   4896 
   4897     if (k_enable_extended_precision)
   4898         adev_verify_devices(adev);
   4899 
   4900     char value[PROPERTY_VALUE_MAX];
   4901     int trial;
   4902     if (property_get("audio_hal.period_size", value, NULL) > 0) {
   4903         trial = atoi(value);
   4904         if (period_size_is_plausible_for_low_latency(trial)) {
   4905             pcm_config_low_latency.period_size = trial;
   4906             pcm_config_low_latency.start_threshold = trial / 4;
   4907             pcm_config_low_latency.avail_min = trial / 4;
   4908             configured_low_latency_capture_period_size = trial;
   4909         }
   4910     }
   4911     if (property_get("audio_hal.in_period_size", value, NULL) > 0) {
   4912         trial = atoi(value);
   4913         if (period_size_is_plausible_for_low_latency(trial)) {
   4914             configured_low_latency_capture_period_size = trial;
   4915         }
   4916     }
   4917 
   4918     // commented as full set of app type cfg is sent from platform
   4919     // audio_extn_utils_send_default_app_type_cfg(adev->platform, adev->mixer);
   4920     audio_device_ref_count++;
   4921 
   4922     if (property_get("audio_hal.period_multiplier", value, NULL) > 0) {
   4923         af_period_multiplier = atoi(value);
   4924         if (af_period_multiplier < 0) {
   4925             af_period_multiplier = 2;
   4926         } else if (af_period_multiplier > 4) {
   4927             af_period_multiplier = 4;
   4928         }
   4929         ALOGV("new period_multiplier = %d", af_period_multiplier);
   4930     }
   4931 
   4932     audio_extn_tfa_98xx_init(adev);
   4933 
   4934     pthread_mutex_unlock(&adev_init_lock);
   4935 
   4936     if (adev->adm_init)
   4937         adev->adm_data = adev->adm_init();
   4938 
   4939     audio_extn_perf_lock_init();
   4940     audio_extn_snd_mon_init();
   4941     pthread_mutex_lock(&adev->lock);
   4942     audio_extn_snd_mon_register_listener(NULL, adev_snd_mon_cb);
   4943     adev->card_status = CARD_STATUS_ONLINE;
   4944     pthread_mutex_unlock(&adev->lock);
   4945     audio_extn_sound_trigger_init(adev);/* dependent on snd_mon_init() */
   4946 
   4947     ALOGD("%s: exit", __func__);
   4948     return 0;
   4949 }
   4950 
   4951 static struct hw_module_methods_t hal_module_methods = {
   4952     .open = adev_open,
   4953 };
   4954 
   4955 struct audio_module HAL_MODULE_INFO_SYM = {
   4956     .common = {
   4957         .tag = HARDWARE_MODULE_TAG,
   4958         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
   4959         .hal_api_version = HARDWARE_HAL_API_VERSION,
   4960         .id = AUDIO_HARDWARE_MODULE_ID,
   4961         .name = "QCOM Audio HAL",
   4962         .author = "Code Aurora Forum",
   4963         .methods = &hal_module_methods,
   4964     },
   4965 };
   4966