Home | History | Annotate | Download | only in hal
      1 /*
      2  * Copyright (C) 2013 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "audio_hw_primary"
     18 /*#define LOG_NDEBUG 0*/
     19 /*#define VERY_VERY_VERBOSE_LOGGING*/
     20 #ifdef VERY_VERY_VERBOSE_LOGGING
     21 #define ALOGVV ALOGV
     22 #else
     23 #define ALOGVV(a...) do { } while(0)
     24 #endif
     25 
     26 #include <errno.h>
     27 #include <pthread.h>
     28 #include <stdint.h>
     29 #include <sys/time.h>
     30 #include <stdlib.h>
     31 #include <math.h>
     32 #include <dlfcn.h>
     33 #include <sys/resource.h>
     34 #include <sys/prctl.h>
     35 
     36 #include <cutils/log.h>
     37 #include <cutils/str_parms.h>
     38 #include <cutils/properties.h>
     39 #include <cutils/atomic.h>
     40 #include <cutils/sched_policy.h>
     41 
     42 #include <hardware/audio_effect.h>
     43 #include <system/thread_defs.h>
     44 #include <audio_effects/effect_aec.h>
     45 #include <audio_effects/effect_ns.h>
     46 #include "audio_hw.h"
     47 
     48 #include "sound/compress_params.h"
     49 
     50 #define MIXER_CTL_COMPRESS_PLAYBACK_VOLUME "Compress Playback Volume"
     51 
     52 /* TODO: the following PCM device profiles could be read from a config file */
     53 struct pcm_device_profile pcm_device_playback_hs = {
     54     .config = {
     55         .channels = PLAYBACK_DEFAULT_CHANNEL_COUNT,
     56         .rate = PLAYBACK_DEFAULT_SAMPLING_RATE,
     57         .period_size = PLAYBACK_PERIOD_SIZE,
     58         .period_count = PLAYBACK_PERIOD_COUNT,
     59         .format = PCM_FORMAT_S16_LE,
     60         .start_threshold = PLAYBACK_START_THRESHOLD,
     61         .stop_threshold = PLAYBACK_STOP_THRESHOLD,
     62         .silence_threshold = 0,
     63         .avail_min = PLAYBACK_AVAILABLE_MIN,
     64     },
     65     .card = SOUND_CARD,
     66     .id = 0,
     67     .type = PCM_PLAYBACK,
     68     .devices = AUDIO_DEVICE_OUT_WIRED_HEADSET|AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
     69 };
     70 
     71 struct pcm_device_profile pcm_device_capture = {
     72     .config = {
     73         .channels = CAPTURE_DEFAULT_CHANNEL_COUNT,
     74         .rate = CAPTURE_DEFAULT_SAMPLING_RATE,
     75         .period_size = CAPTURE_PERIOD_SIZE,
     76         .period_count = CAPTURE_PERIOD_COUNT,
     77         .format = PCM_FORMAT_S16_LE,
     78         .start_threshold = CAPTURE_START_THRESHOLD,
     79         .stop_threshold = 0,
     80         .silence_threshold = 0,
     81         .avail_min = 0,
     82     },
     83     .card = SOUND_CARD,
     84     .id = 0,
     85     .type = PCM_CAPTURE,
     86     .devices = AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_WIRED_HEADSET|AUDIO_DEVICE_IN_BACK_MIC,
     87 };
     88 
     89 struct pcm_device_profile pcm_device_capture_loopback_aec = {
     90     .config = {
     91         .channels = CAPTURE_DEFAULT_CHANNEL_COUNT,
     92         .rate = CAPTURE_DEFAULT_SAMPLING_RATE,
     93         .period_size = CAPTURE_PERIOD_SIZE,
     94         .period_count = CAPTURE_PERIOD_COUNT,
     95         .format = PCM_FORMAT_S16_LE,
     96         .start_threshold = CAPTURE_START_THRESHOLD,
     97         .stop_threshold = 0,
     98         .silence_threshold = 0,
     99         .avail_min = 0,
    100     },
    101     .card = SOUND_CARD,
    102     .id = 1,
    103     .type = PCM_CAPTURE,
    104     .devices = SND_DEVICE_IN_LOOPBACK_AEC,
    105 };
    106 
    107 struct pcm_device_profile pcm_device_playback_spk = {
    108     .config = {
    109         .channels = PLAYBACK_DEFAULT_CHANNEL_COUNT,
    110         .rate = PLAYBACK_DEFAULT_SAMPLING_RATE,
    111         .period_size = PLAYBACK_PERIOD_SIZE,
    112         .period_count = PLAYBACK_PERIOD_COUNT,
    113         .format = PCM_FORMAT_S16_LE,
    114         .start_threshold = PLAYBACK_START_THRESHOLD,
    115         .stop_threshold = PLAYBACK_STOP_THRESHOLD,
    116         .silence_threshold = 0,
    117         .avail_min = PLAYBACK_AVAILABLE_MIN,
    118     },
    119     .card = SOUND_CARD,
    120     .id = 1,
    121     .type = PCM_PLAYBACK,
    122     .devices = AUDIO_DEVICE_OUT_SPEAKER,
    123 };
    124 
    125 struct pcm_device_profile pcm_device_playback_sco = {
    126     .config = {
    127         .channels = SCO_DEFAULT_CHANNEL_COUNT,
    128         .rate = SCO_DEFAULT_SAMPLING_RATE,
    129         .period_size = SCO_PERIOD_SIZE,
    130         .period_count = SCO_PERIOD_COUNT,
    131         .format = PCM_FORMAT_S16_LE,
    132         .start_threshold = SCO_START_THRESHOLD,
    133         .stop_threshold = SCO_STOP_THRESHOLD,
    134         .silence_threshold = 0,
    135         .avail_min = SCO_AVAILABLE_MIN,
    136     },
    137     .card = SOUND_CARD,
    138     .id = 2,
    139     .type = PCM_PLAYBACK,
    140     .devices =
    141             AUDIO_DEVICE_OUT_BLUETOOTH_SCO|AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET|
    142             AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT,
    143 };
    144 
    145 struct pcm_device_profile pcm_device_capture_sco = {
    146     .config = {
    147         .channels = SCO_DEFAULT_CHANNEL_COUNT,
    148         .rate = SCO_DEFAULT_SAMPLING_RATE,
    149         .period_size = SCO_PERIOD_SIZE,
    150         .period_count = SCO_PERIOD_COUNT,
    151         .format = PCM_FORMAT_S16_LE,
    152         .start_threshold = CAPTURE_START_THRESHOLD,
    153         .stop_threshold = 0,
    154         .silence_threshold = 0,
    155         .avail_min = 0,
    156     },
    157     .card = SOUND_CARD,
    158     .id = 2,
    159     .type = PCM_CAPTURE,
    160     .devices = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
    161 };
    162 
    163 struct pcm_device_profile pcm_device_hotword_streaming = {
    164     .config = {
    165         .channels = 1,
    166         .rate = 16000,
    167         .period_size = CAPTURE_PERIOD_SIZE,
    168         .period_count = CAPTURE_PERIOD_COUNT,
    169         .format = PCM_FORMAT_S16_LE,
    170         .start_threshold = CAPTURE_START_THRESHOLD,
    171         .stop_threshold = 0,
    172         .silence_threshold = 0,
    173         .avail_min = 0,
    174     },
    175     .card = SOUND_CARD,
    176     .id = 0,
    177     .type = PCM_HOTWORD_STREAMING,
    178     .devices = AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_WIRED_HEADSET|AUDIO_DEVICE_IN_BACK_MIC
    179 };
    180 
    181 struct pcm_device_profile *pcm_devices[] = {
    182     &pcm_device_playback_hs,
    183     &pcm_device_capture,
    184     &pcm_device_playback_spk,
    185     &pcm_device_playback_sco,
    186     &pcm_device_capture_sco,
    187     &pcm_device_capture_loopback_aec,
    188     &pcm_device_hotword_streaming,
    189     NULL,
    190 };
    191 
    192 static const char * const use_case_table[AUDIO_USECASE_MAX] = {
    193     [USECASE_AUDIO_PLAYBACK] = "playback",
    194     [USECASE_AUDIO_PLAYBACK_MULTI_CH] = "playback multi-channel",
    195     [USECASE_AUDIO_PLAYBACK_OFFLOAD] = "compress-offload-playback",
    196     [USECASE_AUDIO_CAPTURE] = "capture",
    197     [USECASE_AUDIO_CAPTURE_HOTWORD] = "capture-hotword",
    198     [USECASE_VOICE_CALL] = "voice-call",
    199 };
    200 
    201 
    202 #define STRING_TO_ENUM(string) { #string, string }
    203 
    204 static unsigned int audio_device_ref_count;
    205 
    206 struct pcm_config pcm_config_deep_buffer = {
    207     .channels = 2,
    208     .rate = DEEP_BUFFER_OUTPUT_SAMPLING_RATE,
    209     .period_size = DEEP_BUFFER_OUTPUT_PERIOD_SIZE,
    210     .period_count = DEEP_BUFFER_OUTPUT_PERIOD_COUNT,
    211     .format = PCM_FORMAT_S16_LE,
    212     .start_threshold = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
    213     .stop_threshold = INT_MAX,
    214     .avail_min = DEEP_BUFFER_OUTPUT_PERIOD_SIZE / 4,
    215 };
    216 
    217 struct string_to_enum {
    218     const char *name;
    219     uint32_t value;
    220 };
    221 
    222 static const struct string_to_enum out_channels_name_to_enum_table[] = {
    223     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
    224     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
    225     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
    226 };
    227 
    228 static void dummybuf_thread_close(struct audio_device *adev);
    229 
    230 static bool is_supported_format(audio_format_t format)
    231 {
    232     if (format == AUDIO_FORMAT_MP3 ||
    233             ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC))
    234         return true;
    235 
    236     return false;
    237 }
    238 
    239 static int get_snd_codec_id(audio_format_t format)
    240 {
    241     int id = 0;
    242 
    243     switch (format & AUDIO_FORMAT_MAIN_MASK) {
    244     case AUDIO_FORMAT_MP3:
    245         id = SND_AUDIOCODEC_MP3;
    246         break;
    247     case AUDIO_FORMAT_AAC:
    248         id = SND_AUDIOCODEC_AAC;
    249         break;
    250     default:
    251         ALOGE("%s: Unsupported audio format", __func__);
    252     }
    253 
    254     return id;
    255 }
    256 
    257 /* Array to store sound devices */
    258 static const char * const device_table[SND_DEVICE_MAX] = {
    259     [SND_DEVICE_NONE] = "none",
    260     /* Playback sound devices */
    261     [SND_DEVICE_OUT_HANDSET] = "handset",
    262     [SND_DEVICE_OUT_SPEAKER] = "speaker",
    263     [SND_DEVICE_OUT_HEADPHONES] = "headphones",
    264     [SND_DEVICE_OUT_SPEAKER_AND_HEADPHONES] = "speaker-and-headphones",
    265     [SND_DEVICE_OUT_VOICE_HANDSET] = "voice-handset",
    266     [SND_DEVICE_OUT_VOICE_SPEAKER] = "voice-speaker",
    267     [SND_DEVICE_OUT_VOICE_HEADPHONES] = "voice-headphones",
    268     [SND_DEVICE_OUT_HDMI] = "hdmi",
    269     [SND_DEVICE_OUT_SPEAKER_AND_HDMI] = "speaker-and-hdmi",
    270     [SND_DEVICE_OUT_BT_SCO] = "bt-sco-headset",
    271     [SND_DEVICE_OUT_VOICE_TTY_FULL_HEADPHONES] = "voice-tty-full-headphones",
    272     [SND_DEVICE_OUT_VOICE_TTY_VCO_HEADPHONES] = "voice-tty-vco-headphones",
    273     [SND_DEVICE_OUT_VOICE_TTY_HCO_HANDSET] = "voice-tty-hco-handset",
    274 
    275     /* Capture sound devices */
    276     [SND_DEVICE_IN_HANDSET_MIC] = "handset-mic",
    277     [SND_DEVICE_IN_SPEAKER_MIC] = "speaker-mic",
    278     [SND_DEVICE_IN_HEADSET_MIC] = "headset-mic",
    279     [SND_DEVICE_IN_HANDSET_MIC_AEC] = "handset-mic",
    280     [SND_DEVICE_IN_SPEAKER_MIC_AEC] = "voice-speaker-mic",
    281     [SND_DEVICE_IN_HEADSET_MIC_AEC] = "headset-mic",
    282     [SND_DEVICE_IN_VOICE_SPEAKER_MIC] = "voice-speaker-mic",
    283     [SND_DEVICE_IN_VOICE_HEADSET_MIC] = "voice-headset-mic",
    284     [SND_DEVICE_IN_HDMI_MIC] = "hdmi-mic",
    285     [SND_DEVICE_IN_BT_SCO_MIC] = "bt-sco-mic",
    286     [SND_DEVICE_IN_CAMCORDER_MIC] = "camcorder-mic",
    287     [SND_DEVICE_IN_VOICE_DMIC_1] = "voice-dmic-1",
    288     [SND_DEVICE_IN_VOICE_SPEAKER_DMIC_1] = "voice-speaker-dmic-1",
    289     [SND_DEVICE_IN_VOICE_TTY_FULL_HEADSET_MIC] = "voice-tty-full-headset-mic",
    290     [SND_DEVICE_IN_VOICE_TTY_VCO_HANDSET_MIC] = "voice-tty-vco-handset-mic",
    291     [SND_DEVICE_IN_VOICE_TTY_HCO_HEADSET_MIC] = "voice-tty-hco-headset-mic",
    292     [SND_DEVICE_IN_VOICE_REC_HEADSET_MIC] = "voice-rec-headset-mic",
    293     [SND_DEVICE_IN_VOICE_REC_MIC] = "voice-rec-mic",
    294     [SND_DEVICE_IN_VOICE_REC_DMIC_1] = "voice-rec-dmic-1",
    295     [SND_DEVICE_IN_VOICE_REC_DMIC_NS_1] = "voice-rec-dmic-ns-1",
    296     [SND_DEVICE_IN_LOOPBACK_AEC] = "loopback-aec",
    297 };
    298 
    299 struct mixer_card *adev_get_mixer_for_card(struct audio_device *adev, int card)
    300 {
    301     struct mixer_card *mixer_card;
    302     struct listnode *node;
    303 
    304     list_for_each(node, &adev->mixer_list) {
    305         mixer_card = node_to_item(node, struct mixer_card, adev_list_node);
    306         if (mixer_card->card == card)
    307             return mixer_card;
    308     }
    309     return NULL;
    310 }
    311 
    312 struct mixer_card *uc_get_mixer_for_card(struct audio_usecase *usecase, int card)
    313 {
    314     struct mixer_card *mixer_card;
    315     struct listnode *node;
    316 
    317     list_for_each(node, &usecase->mixer_list) {
    318         mixer_card = node_to_item(node, struct mixer_card, uc_list_node[usecase->id]);
    319         if (mixer_card->card == card)
    320             return mixer_card;
    321     }
    322     return NULL;
    323 }
    324 
    325 void free_mixer_list(struct audio_device *adev)
    326 {
    327     struct mixer_card *mixer_card;
    328     struct listnode *node;
    329     struct listnode *next;
    330 
    331     list_for_each_safe(node, next, &adev->mixer_list) {
    332         mixer_card = node_to_item(node, struct mixer_card, adev_list_node);
    333         list_remove(node);
    334         audio_route_free(mixer_card->audio_route);
    335         free(mixer_card);
    336     }
    337 }
    338 
    339 int mixer_init(struct audio_device *adev)
    340 {
    341     int i;
    342     int card;
    343     int retry_num;
    344     struct mixer *mixer;
    345     struct audio_route *audio_route;
    346     char mixer_path[PATH_MAX];
    347     struct mixer_card *mixer_card;
    348     struct listnode *node;
    349 
    350     list_init(&adev->mixer_list);
    351 
    352     for (i = 0; pcm_devices[i] != NULL; i++) {
    353         card = pcm_devices[i]->card;
    354         if (adev_get_mixer_for_card(adev, card) == NULL) {
    355             retry_num = 0;
    356             do {
    357                 mixer = mixer_open(card);
    358                 if (mixer == NULL) {
    359                     if (++retry_num > RETRY_NUMBER) {
    360                         ALOGE("%s unable to open the mixer for--card %d, aborting.",
    361                               __func__, card);
    362                         goto error;
    363                     }
    364                     usleep(RETRY_US);
    365                 }
    366             } while (mixer == NULL);
    367 
    368             sprintf(mixer_path, "/system/etc/mixer_paths_%d.xml", card);
    369             audio_route = audio_route_init(card, mixer_path);
    370             if (!audio_route) {
    371                 ALOGE("%s: Failed to init audio route controls for card %d, aborting.",
    372                       __func__, card);
    373                 goto error;
    374             }
    375             mixer_card = calloc(1, sizeof(struct mixer_card));
    376             mixer_card->card = card;
    377             mixer_card->mixer = mixer;
    378             mixer_card->audio_route = audio_route;
    379             list_add_tail(&adev->mixer_list, &mixer_card->adev_list_node);
    380         }
    381     }
    382 
    383     return 0;
    384 
    385 error:
    386     free_mixer_list(adev);
    387     return -ENODEV;
    388 }
    389 
    390 const char *get_snd_device_name(snd_device_t snd_device)
    391 {
    392     const char *name = NULL;
    393 
    394     if (snd_device >= SND_DEVICE_MIN && snd_device < SND_DEVICE_MAX)
    395         name = device_table[snd_device];
    396 
    397     ALOGE_IF(name == NULL, "%s: invalid snd device %d", __func__, snd_device);
    398 
    399    return name;
    400 }
    401 
    402 const char *get_snd_device_display_name(snd_device_t snd_device)
    403 {
    404     const char *name = get_snd_device_name(snd_device);
    405 
    406     if (name == NULL)
    407         name = "SND DEVICE NOT FOUND";
    408 
    409     return name;
    410 }
    411 
    412 struct pcm_device_profile *get_pcm_device(usecase_type_t uc_type, audio_devices_t devices)
    413 {
    414     int i;
    415 
    416     devices &= ~AUDIO_DEVICE_BIT_IN;
    417     for (i = 0; pcm_devices[i] != NULL; i++) {
    418         if ((pcm_devices[i]->type == uc_type) &&
    419                 (devices & pcm_devices[i]->devices))
    420             break;
    421     }
    422     return pcm_devices[i];
    423 }
    424 
    425 static struct audio_usecase *get_usecase_from_id(struct audio_device *adev,
    426                                                    audio_usecase_t uc_id)
    427 {
    428     struct audio_usecase *usecase;
    429     struct listnode *node;
    430 
    431     list_for_each(node, &adev->usecase_list) {
    432         usecase = node_to_item(node, struct audio_usecase, adev_list_node);
    433         if (usecase->id == uc_id)
    434             return usecase;
    435     }
    436     return NULL;
    437 }
    438 
    439 static struct audio_usecase *get_usecase_from_type(struct audio_device *adev,
    440                                                         usecase_type_t type)
    441 {
    442     struct audio_usecase *usecase;
    443     struct listnode *node;
    444 
    445     list_for_each(node, &adev->usecase_list) {
    446         usecase = node_to_item(node, struct audio_usecase, adev_list_node);
    447         if (usecase->type & type)
    448             return usecase;
    449     }
    450     return NULL;
    451 }
    452 
    453 /* always called with adev lock held */
    454 static int set_voice_volume_l(struct audio_device *adev, float volume)
    455 {
    456     int err = 0;
    457     (void)volume;
    458 
    459     if (adev->mode == AUDIO_MODE_IN_CALL) {
    460         /* TODO */
    461     }
    462     return err;
    463 }
    464 
    465 
    466 snd_device_t get_output_snd_device(struct audio_device *adev, audio_devices_t devices)
    467 {
    468 
    469     audio_mode_t mode = adev->mode;
    470     snd_device_t snd_device = SND_DEVICE_NONE;
    471 
    472     ALOGV("%s: enter: output devices(%#x), mode(%d)", __func__, devices, mode);
    473     if (devices == AUDIO_DEVICE_NONE ||
    474         devices & AUDIO_DEVICE_BIT_IN) {
    475         ALOGV("%s: Invalid output devices (%#x)", __func__, devices);
    476         goto exit;
    477     }
    478 
    479     if (mode == AUDIO_MODE_IN_CALL) {
    480         if (devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE ||
    481             devices & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
    482             if (adev->tty_mode == TTY_MODE_FULL)
    483                 snd_device = SND_DEVICE_OUT_VOICE_TTY_FULL_HEADPHONES;
    484             else if (adev->tty_mode == TTY_MODE_VCO)
    485                 snd_device = SND_DEVICE_OUT_VOICE_TTY_VCO_HEADPHONES;
    486             else if (adev->tty_mode == TTY_MODE_HCO)
    487                 snd_device = SND_DEVICE_OUT_VOICE_TTY_HCO_HANDSET;
    488             else
    489                 snd_device = SND_DEVICE_OUT_VOICE_HEADPHONES;
    490         } else if (devices & AUDIO_DEVICE_OUT_ALL_SCO) {
    491             snd_device = SND_DEVICE_OUT_BT_SCO;
    492         } else if (devices & AUDIO_DEVICE_OUT_SPEAKER) {
    493             snd_device = SND_DEVICE_OUT_VOICE_SPEAKER;
    494         } else if (devices & AUDIO_DEVICE_OUT_EARPIECE) {
    495             snd_device = SND_DEVICE_OUT_HANDSET;
    496         }
    497         if (snd_device != SND_DEVICE_NONE) {
    498             goto exit;
    499         }
    500     }
    501 
    502     if (popcount(devices) == 2) {
    503         if (devices == (AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
    504                         AUDIO_DEVICE_OUT_SPEAKER)) {
    505             snd_device = SND_DEVICE_OUT_SPEAKER_AND_HEADPHONES;
    506         } else if (devices == (AUDIO_DEVICE_OUT_WIRED_HEADSET |
    507                                AUDIO_DEVICE_OUT_SPEAKER)) {
    508             snd_device = SND_DEVICE_OUT_SPEAKER_AND_HEADPHONES;
    509         } else {
    510             ALOGE("%s: Invalid combo device(%#x)", __func__, devices);
    511             goto exit;
    512         }
    513         if (snd_device != SND_DEVICE_NONE) {
    514             goto exit;
    515         }
    516     }
    517 
    518     if (popcount(devices) != 1) {
    519         ALOGE("%s: Invalid output devices(%#x)", __func__, devices);
    520         goto exit;
    521     }
    522 
    523     if (devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE ||
    524         devices & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
    525         snd_device = SND_DEVICE_OUT_HEADPHONES;
    526     } else if (devices & AUDIO_DEVICE_OUT_SPEAKER) {
    527         snd_device = SND_DEVICE_OUT_SPEAKER;
    528     } else if (devices & AUDIO_DEVICE_OUT_ALL_SCO) {
    529         snd_device = SND_DEVICE_OUT_BT_SCO;
    530     } else if (devices & AUDIO_DEVICE_OUT_EARPIECE) {
    531         snd_device = SND_DEVICE_OUT_HANDSET;
    532     } else {
    533         ALOGE("%s: Unknown device(s) %#x", __func__, devices);
    534     }
    535 exit:
    536     ALOGV("%s: exit: snd_device(%s)", __func__, device_table[snd_device]);
    537     return snd_device;
    538 }
    539 
    540 snd_device_t get_input_snd_device(struct audio_device *adev, audio_devices_t out_device)
    541 {
    542     audio_source_t  source;
    543     audio_mode_t    mode   = adev->mode;
    544     audio_devices_t in_device;
    545     audio_channel_mask_t channel_mask;
    546     snd_device_t snd_device = SND_DEVICE_NONE;
    547     struct stream_in *active_input = NULL;
    548     struct audio_usecase *usecase;
    549 
    550     usecase = get_usecase_from_type(adev, PCM_CAPTURE|VOICE_CALL);
    551     if (usecase != NULL) {
    552         active_input = (struct stream_in *)usecase->stream;
    553     }
    554     source = (active_input == NULL) ?
    555                                 AUDIO_SOURCE_DEFAULT : active_input->source;
    556 
    557     in_device = ((active_input == NULL) ?
    558                                     AUDIO_DEVICE_NONE : active_input->devices)
    559                                 & ~AUDIO_DEVICE_BIT_IN;
    560     channel_mask = (active_input == NULL) ?
    561                                 AUDIO_CHANNEL_IN_MONO : active_input->main_channels;
    562 
    563     ALOGV("%s: enter: out_device(%#x) in_device(%#x)",
    564           __func__, out_device, in_device);
    565     if (mode == AUDIO_MODE_IN_CALL) {
    566         if (out_device == AUDIO_DEVICE_NONE) {
    567             ALOGE("%s: No output device set for voice call", __func__);
    568             goto exit;
    569         }
    570         if (adev->tty_mode != TTY_MODE_OFF) {
    571             if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADPHONE ||
    572                 out_device & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
    573                 switch (adev->tty_mode) {
    574                 case TTY_MODE_FULL:
    575                     snd_device = SND_DEVICE_IN_VOICE_TTY_FULL_HEADSET_MIC;
    576                     break;
    577                 case TTY_MODE_VCO:
    578                     snd_device = SND_DEVICE_IN_VOICE_TTY_VCO_HANDSET_MIC;
    579                     break;
    580                 case TTY_MODE_HCO:
    581                     snd_device = SND_DEVICE_IN_VOICE_TTY_HCO_HEADSET_MIC;
    582                     break;
    583                 default:
    584                     ALOGE("%s: Invalid TTY mode (%#x)", __func__, adev->tty_mode);
    585                 }
    586                 goto exit;
    587             }
    588         }
    589         if (out_device & AUDIO_DEVICE_OUT_EARPIECE ||
    590                 out_device & AUDIO_DEVICE_OUT_WIRED_HEADPHONE) {
    591             snd_device = SND_DEVICE_IN_HANDSET_MIC;
    592         } else if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
    593             snd_device = SND_DEVICE_IN_VOICE_HEADSET_MIC;
    594         } else if (out_device & AUDIO_DEVICE_OUT_ALL_SCO) {
    595             snd_device = SND_DEVICE_IN_BT_SCO_MIC ;
    596         } else if (out_device & AUDIO_DEVICE_OUT_SPEAKER) {
    597             snd_device = SND_DEVICE_IN_VOICE_SPEAKER_MIC;
    598         }
    599     } else if (source == AUDIO_SOURCE_CAMCORDER) {
    600         if (in_device & AUDIO_DEVICE_IN_BUILTIN_MIC ||
    601             in_device & AUDIO_DEVICE_IN_BACK_MIC) {
    602             snd_device = SND_DEVICE_IN_CAMCORDER_MIC;
    603         }
    604     } else if (source == AUDIO_SOURCE_VOICE_RECOGNITION) {
    605         if (in_device & AUDIO_DEVICE_IN_BUILTIN_MIC) {
    606             if (adev->dualmic_config == DUALMIC_CONFIG_1) {
    607                 if (channel_mask == AUDIO_CHANNEL_IN_FRONT_BACK)
    608                     snd_device = SND_DEVICE_IN_VOICE_REC_DMIC_1;
    609                 else if (adev->ns_in_voice_rec)
    610                     snd_device = SND_DEVICE_IN_VOICE_REC_DMIC_NS_1;
    611             }
    612 
    613             if (snd_device == SND_DEVICE_NONE) {
    614                 snd_device = SND_DEVICE_IN_VOICE_REC_MIC;
    615             }
    616         } else if (in_device & AUDIO_DEVICE_IN_WIRED_HEADSET) {
    617             snd_device = SND_DEVICE_IN_VOICE_REC_HEADSET_MIC;
    618         }
    619     } else if (source == AUDIO_SOURCE_VOICE_COMMUNICATION || source == AUDIO_SOURCE_MIC) {
    620         if (out_device & AUDIO_DEVICE_OUT_SPEAKER)
    621             in_device = AUDIO_DEVICE_IN_BACK_MIC;
    622         if (active_input) {
    623             if (active_input->enable_aec) {
    624                 if (in_device & AUDIO_DEVICE_IN_BACK_MIC) {
    625                     snd_device = SND_DEVICE_IN_SPEAKER_MIC_AEC;
    626                 } else if (in_device & AUDIO_DEVICE_IN_BUILTIN_MIC) {
    627                     if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADPHONE) {
    628                         snd_device = SND_DEVICE_IN_SPEAKER_MIC_AEC;
    629                     } else {
    630                         snd_device = SND_DEVICE_IN_HANDSET_MIC_AEC;
    631                     }
    632                 } else if (in_device & AUDIO_DEVICE_IN_WIRED_HEADSET) {
    633                     snd_device = SND_DEVICE_IN_HEADSET_MIC_AEC;
    634                 }
    635             }
    636             /* TODO: set echo reference */
    637         }
    638     } else if (source == AUDIO_SOURCE_DEFAULT) {
    639         goto exit;
    640     }
    641 
    642 
    643     if (snd_device != SND_DEVICE_NONE) {
    644         goto exit;
    645     }
    646 
    647     if (in_device != AUDIO_DEVICE_NONE &&
    648             !(in_device & AUDIO_DEVICE_IN_VOICE_CALL) &&
    649             !(in_device & AUDIO_DEVICE_IN_COMMUNICATION)) {
    650         if (in_device & AUDIO_DEVICE_IN_BUILTIN_MIC) {
    651             snd_device = SND_DEVICE_IN_HANDSET_MIC;
    652         } else if (in_device & AUDIO_DEVICE_IN_BACK_MIC) {
    653             snd_device = SND_DEVICE_IN_SPEAKER_MIC;
    654         } else if (in_device & AUDIO_DEVICE_IN_WIRED_HEADSET) {
    655             snd_device = SND_DEVICE_IN_HEADSET_MIC;
    656         } else if (in_device & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
    657             snd_device = SND_DEVICE_IN_BT_SCO_MIC ;
    658         } else if (in_device & AUDIO_DEVICE_IN_AUX_DIGITAL) {
    659             snd_device = SND_DEVICE_IN_HDMI_MIC;
    660         } else {
    661             ALOGE("%s: Unknown input device(s) %#x", __func__, in_device);
    662             ALOGW("%s: Using default handset-mic", __func__);
    663             snd_device = SND_DEVICE_IN_HANDSET_MIC;
    664         }
    665     } else {
    666         if (out_device & AUDIO_DEVICE_OUT_EARPIECE) {
    667             snd_device = SND_DEVICE_IN_HANDSET_MIC;
    668         } else if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
    669             snd_device = SND_DEVICE_IN_HEADSET_MIC;
    670         } else if (out_device & AUDIO_DEVICE_OUT_SPEAKER) {
    671             snd_device = SND_DEVICE_IN_SPEAKER_MIC;
    672         } else if (out_device & AUDIO_DEVICE_OUT_WIRED_HEADPHONE) {
    673             snd_device = SND_DEVICE_IN_HANDSET_MIC;
    674         } else if (out_device & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET) {
    675             snd_device = SND_DEVICE_IN_BT_SCO_MIC;
    676         } else {
    677             ALOGE("%s: Unknown output device(s) %#x", __func__, out_device);
    678             ALOGW("%s: Using default handset-mic", __func__);
    679             snd_device = SND_DEVICE_IN_HANDSET_MIC;
    680         }
    681     }
    682 exit:
    683     ALOGV("%s: exit: in_snd_device(%s)", __func__, device_table[snd_device]);
    684     return snd_device;
    685 }
    686 
    687 int set_hdmi_channels(struct audio_device *adev,  int channel_count)
    688 {
    689     struct mixer_ctl *ctl;
    690     const char *mixer_ctl_name = "";
    691     (void)adev;
    692     (void)channel_count;
    693     /* TODO */
    694 
    695     return 0;
    696 }
    697 
    698 int edid_get_max_channels(struct audio_device *adev)
    699 {
    700     int max_channels = 2;
    701     struct mixer_ctl *ctl;
    702     (void)adev;
    703 
    704     /* TODO */
    705     return max_channels;
    706 }
    707 
    708 /* Delay in Us */
    709 int64_t render_latency(audio_usecase_t usecase)
    710 {
    711     (void)usecase;
    712     /* TODO */
    713     return 0;
    714 }
    715 
    716 static int enable_snd_device(struct audio_device *adev,
    717                              struct audio_usecase *uc_info,
    718                              snd_device_t snd_device,
    719                              bool update_mixer)
    720 {
    721     struct mixer_card *mixer_card;
    722     struct listnode *node;
    723     const char *snd_device_name = get_snd_device_name(snd_device);
    724 
    725     if (snd_device_name == NULL)
    726         return -EINVAL;
    727 
    728     adev->snd_dev_ref_cnt[snd_device]++;
    729     if (adev->snd_dev_ref_cnt[snd_device] > 1) {
    730         ALOGV("%s: snd_device(%d: %s) is already active",
    731               __func__, snd_device, snd_device_name);
    732         return 0;
    733     }
    734 
    735     ALOGV("%s: snd_device(%d: %s)", __func__,
    736           snd_device, snd_device_name);
    737 
    738     list_for_each(node, &uc_info->mixer_list) {
    739         mixer_card = node_to_item(node, struct mixer_card, uc_list_node[uc_info->id]);
    740         audio_route_apply_path(mixer_card->audio_route, snd_device_name);
    741         if (update_mixer)
    742             audio_route_update_mixer(mixer_card->audio_route);
    743     }
    744 
    745     return 0;
    746 }
    747 
    748 static int disable_snd_device(struct audio_device *adev,
    749                               struct audio_usecase *uc_info,
    750                               snd_device_t snd_device,
    751                               bool update_mixer)
    752 {
    753     struct mixer_card *mixer_card;
    754     struct listnode *node;
    755     const char *snd_device_name = get_snd_device_name(snd_device);
    756 
    757     if (snd_device_name == NULL)
    758         return -EINVAL;
    759 
    760     if (adev->snd_dev_ref_cnt[snd_device] <= 0) {
    761         ALOGE("%s: device ref cnt is already 0", __func__);
    762         return -EINVAL;
    763     }
    764     adev->snd_dev_ref_cnt[snd_device]--;
    765     if (adev->snd_dev_ref_cnt[snd_device] == 0) {
    766         ALOGV("%s: snd_device(%d: %s)", __func__,
    767               snd_device, snd_device_name);
    768         list_for_each(node, &uc_info->mixer_list) {
    769             mixer_card = node_to_item(node, struct mixer_card, uc_list_node[uc_info->id]);
    770             audio_route_reset_path(mixer_card->audio_route, snd_device_name);
    771             if (update_mixer)
    772                 audio_route_update_mixer(mixer_card->audio_route);
    773         }
    774     }
    775     return 0;
    776 }
    777 
    778 static int select_devices(struct audio_device *adev,
    779                           audio_usecase_t uc_id)
    780 {
    781     snd_device_t out_snd_device = SND_DEVICE_NONE;
    782     snd_device_t in_snd_device = SND_DEVICE_NONE;
    783     struct audio_usecase *usecase = NULL;
    784     struct audio_usecase *vc_usecase = NULL;
    785     struct listnode *node;
    786     struct stream_in *active_input = NULL;
    787     struct stream_out *active_out;
    788     struct mixer_card *mixer_card;
    789 
    790     ALOGV("%s: usecase(%d)", __func__, uc_id);
    791 
    792     if (uc_id == USECASE_AUDIO_CAPTURE_HOTWORD)
    793         return 0;
    794 
    795     usecase = get_usecase_from_type(adev, PCM_CAPTURE|VOICE_CALL);
    796     if (usecase != NULL) {
    797         active_input = (struct stream_in *)usecase->stream;
    798     }
    799 
    800     usecase = get_usecase_from_id(adev, uc_id);
    801     if (usecase == NULL) {
    802         ALOGE("%s: Could not find the usecase(%d)", __func__, uc_id);
    803         return -EINVAL;
    804     }
    805     active_out = (struct stream_out *)usecase->stream;
    806 
    807     if (usecase->type == VOICE_CALL) {
    808         out_snd_device = get_output_snd_device(adev, active_out->devices);
    809         in_snd_device = get_input_snd_device(adev, active_out->devices);
    810         usecase->devices = active_out->devices;
    811     } else {
    812         /*
    813          * If the voice call is active, use the sound devices of voice call usecase
    814          * so that it would not result any device switch. All the usecases will
    815          * be switched to new device when select_devices() is called for voice call
    816          * usecase.
    817          */
    818         if (adev->in_call) {
    819             vc_usecase = get_usecase_from_id(adev, USECASE_VOICE_CALL);
    820             if (usecase == NULL) {
    821                 ALOGE("%s: Could not find the voice call usecase", __func__);
    822             } else {
    823                 in_snd_device = vc_usecase->in_snd_device;
    824                 out_snd_device = vc_usecase->out_snd_device;
    825             }
    826         }
    827         if (usecase->type == PCM_PLAYBACK) {
    828             usecase->devices = active_out->devices;
    829             in_snd_device = SND_DEVICE_NONE;
    830             if (out_snd_device == SND_DEVICE_NONE) {
    831                 out_snd_device = get_output_snd_device(adev, active_out->devices);
    832                 if (active_out == adev->primary_output &&
    833                         active_input &&
    834                         active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
    835                     select_devices(adev, active_input->usecase);
    836                 }
    837             }
    838         } else if (usecase->type == PCM_CAPTURE) {
    839             usecase->devices = ((struct stream_in *)usecase->stream)->devices;
    840             out_snd_device = SND_DEVICE_NONE;
    841             if (in_snd_device == SND_DEVICE_NONE) {
    842                 if (active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
    843                         adev->primary_output && !adev->primary_output->standby) {
    844                     in_snd_device = get_input_snd_device(adev, adev->primary_output->devices);
    845                 } else {
    846                     in_snd_device = get_input_snd_device(adev, AUDIO_DEVICE_NONE);
    847                 }
    848             }
    849         }
    850     }
    851 
    852     if (out_snd_device == usecase->out_snd_device &&
    853         in_snd_device == usecase->in_snd_device) {
    854         return 0;
    855     }
    856 
    857     ALOGV("%s: out_snd_device(%d: %s) in_snd_device(%d: %s)", __func__,
    858           out_snd_device, get_snd_device_display_name(out_snd_device),
    859           in_snd_device,  get_snd_device_display_name(in_snd_device));
    860 
    861 
    862     /* Disable current sound devices */
    863     if (usecase->out_snd_device != SND_DEVICE_NONE) {
    864         pthread_mutex_lock(&adev->tfa9895_lock);
    865         disable_snd_device(adev, usecase, usecase->out_snd_device, false);
    866         pthread_mutex_unlock(&adev->tfa9895_lock);
    867     }
    868 
    869     if (usecase->in_snd_device != SND_DEVICE_NONE) {
    870         disable_snd_device(adev, usecase, usecase->in_snd_device, false);
    871     }
    872 
    873     /* Enable new sound devices */
    874     if (out_snd_device != SND_DEVICE_NONE) {
    875         enable_snd_device(adev, usecase, out_snd_device, false);
    876     }
    877 
    878     if (in_snd_device != SND_DEVICE_NONE) {
    879         enable_snd_device(adev, usecase, in_snd_device, false);
    880     }
    881 
    882     list_for_each(node, &usecase->mixer_list) {
    883          mixer_card = node_to_item(node, struct mixer_card, uc_list_node[usecase->id]);
    884          audio_route_update_mixer(mixer_card->audio_route);
    885     }
    886 
    887     usecase->in_snd_device = in_snd_device;
    888     usecase->out_snd_device = out_snd_device;
    889 
    890     if (out_snd_device != SND_DEVICE_NONE)
    891         if (usecase->devices & (AUDIO_DEVICE_OUT_WIRED_HEADSET | AUDIO_DEVICE_OUT_WIRED_HEADPHONE))
    892             if (adev->htc_acoustic_set_rt5506_amp != NULL)
    893                 adev->htc_acoustic_set_rt5506_amp(adev->mode, usecase->devices);
    894     return 0;
    895 }
    896 
    897 
    898 static ssize_t read_frames(struct stream_in *in, void *buffer, ssize_t frames);
    899 static int do_in_standby_l(struct stream_in *in);
    900 
    901 #ifdef PREPROCESSING_ENABLED
    902 static void get_capture_reference_delay(struct stream_in *in,
    903                               size_t frames,
    904                               struct echo_reference_buffer *buffer)
    905 {
    906     ALOGVV("%s: enter:)", __func__);
    907 
    908     /* read frames available in kernel driver buffer */
    909     unsigned int kernel_frames;
    910     struct timespec tstamp;
    911     long buf_delay;
    912     long kernel_delay;
    913     long delay_ns;
    914     struct pcm_device *ref_device;
    915     long rsmp_delay = 0;
    916 
    917     ref_device = node_to_item(list_tail(&in->pcm_dev_list),
    918                               struct pcm_device, stream_list_node);
    919 
    920     if (pcm_get_htimestamp(ref_device->pcm, &kernel_frames, &tstamp) < 0) {
    921         buffer->time_stamp.tv_sec  = 0;
    922         buffer->time_stamp.tv_nsec = 0;
    923         buffer->delay_ns           = 0;
    924         ALOGW("read get_capture_reference_delay(): pcm_htimestamp error");
    925         return;
    926     }
    927 
    928     /* adjust render time stamp with delay added by current driver buffer.
    929     * Add the duration of current frame as we want the render time of the last
    930     * sample being written. */
    931 
    932     kernel_delay = (long)(((int64_t)kernel_frames * 1000000000) / ref_device->pcm_profile->config.rate);
    933 
    934     buffer->time_stamp = tstamp;
    935     buffer->delay_ns = kernel_delay;
    936 
    937     ALOGVV("get_capture_reference_delay_time_stamp Secs: [%10ld], nSecs: [%9ld], kernel_frames: [%5d],"
    938           " delay_ns: [%d] , frames:[%zd]",
    939            buffer->time_stamp.tv_sec , buffer->time_stamp.tv_nsec, kernel_frames, buffer->delay_ns, frames);
    940 }
    941 
    942 static void get_capture_delay(struct stream_in *in,
    943                               size_t frames,
    944                               struct echo_reference_buffer *buffer)
    945 {
    946     ALOGVV("%s: enter:)", __func__);
    947     /* read frames available in kernel driver buffer */
    948     unsigned int kernel_frames;
    949     struct timespec tstamp;
    950     long buf_delay;
    951     long rsmp_delay;
    952     long kernel_delay;
    953     long delay_ns;
    954     struct pcm_device *pcm_device;
    955 
    956     pcm_device = node_to_item(list_head(&in->pcm_dev_list),
    957                               struct pcm_device, stream_list_node);
    958 
    959     if (pcm_get_htimestamp(pcm_device->pcm, &kernel_frames, &tstamp) < 0) {
    960         buffer->time_stamp.tv_sec  = 0;
    961         buffer->time_stamp.tv_nsec = 0;
    962         buffer->delay_ns           = 0;
    963         ALOGW("read get_capture_delay(): pcm_htimestamp error");
    964         return;
    965     }
    966 
    967     /* read frames available in audio HAL input buffer
    968      * add number of frames being read as we want the capture time of first sample
    969      * in current buffer */
    970     /* frames in in->read_buf are at driver sampling rate while frames in in->proc_buf are
    971      * at requested sampling rate */
    972     buf_delay = (long)(((int64_t)(in->read_buf_frames) * 1000000000) / in->config.rate +
    973                        ((int64_t)(in->proc_buf_frames) * 1000000000) / in->requested_rate );
    974 
    975     /* add delay introduced by resampler */
    976     rsmp_delay = 0;
    977     if (in->resampler) {
    978         rsmp_delay = in->resampler->delay_ns(in->resampler);
    979     }
    980 
    981     kernel_delay = (long)(((int64_t)kernel_frames * 1000000000) / in->config.rate);
    982 
    983     delay_ns = kernel_delay + buf_delay + rsmp_delay;
    984 
    985     buffer->time_stamp = tstamp;
    986     buffer->delay_ns   = delay_ns;
    987     ALOGVV("get_capture_delay_time_stamp Secs: [%10ld], nSecs: [%9ld], kernel_frames:[%5d],"
    988          " delay_ns: [%d], kernel_delay:[%ld], buf_delay:[%ld], rsmp_delay:[%ld],  "
    989          "in->read_buf_frames:[%zd], in->proc_buf_frames:[%zd], frames:[%zd]",
    990          buffer->time_stamp.tv_sec , buffer->time_stamp.tv_nsec, kernel_frames,
    991          buffer->delay_ns, kernel_delay, buf_delay, rsmp_delay,
    992          in->read_buf_frames, in->proc_buf_frames, frames);
    993 }
    994 
    995 static int32_t update_echo_reference(struct stream_in *in, size_t frames)
    996 {
    997     ALOGVV("%s: enter:), in->config.channels(%d)", __func__,in->config.channels);
    998     struct echo_reference_buffer b;
    999     b.delay_ns = 0;
   1000     struct pcm_device *pcm_device;
   1001 
   1002     pcm_device = node_to_item(list_head(&in->pcm_dev_list),
   1003                               struct pcm_device, stream_list_node);
   1004 
   1005     ALOGVV("update_echo_reference, in->config.channels(%d), frames = [%zd], in->ref_buf_frames = [%zd],  "
   1006           "b.frame_count = [%zd]",
   1007           in->config.channels, frames, in->ref_buf_frames, frames - in->ref_buf_frames);
   1008     if (in->ref_buf_frames < frames) {
   1009         if (in->ref_buf_size < frames) {
   1010             in->ref_buf_size = frames;
   1011             in->ref_buf = (int16_t *)realloc(in->ref_buf, pcm_frames_to_bytes(pcm_device->pcm, frames));
   1012             ALOG_ASSERT((in->ref_buf != NULL),
   1013                         "update_echo_reference() failed to reallocate ref_buf");
   1014             ALOGVV("update_echo_reference(): ref_buf %p extended to %d bytes",
   1015                       in->ref_buf, pcm_frames_to_bytes(pcm_device->pcm, frames));
   1016         }
   1017         b.frame_count = frames - in->ref_buf_frames;
   1018         b.raw = (void *)(in->ref_buf + in->ref_buf_frames * in->config.channels);
   1019 
   1020         get_capture_delay(in, frames, &b);
   1021 
   1022         if (in->echo_reference->read(in->echo_reference, &b) == 0)
   1023         {
   1024             in->ref_buf_frames += b.frame_count;
   1025             ALOGVV("update_echo_reference(): in->ref_buf_frames:[%zd], "
   1026                     "in->ref_buf_size:[%zd], frames:[%zd], b.frame_count:[%zd]",
   1027                  in->ref_buf_frames, in->ref_buf_size, frames, b.frame_count);
   1028         }
   1029     } else
   1030         ALOGW("update_echo_reference(): NOT enough frames to read ref buffer");
   1031     return b.delay_ns;
   1032 }
   1033 
   1034 static int set_preprocessor_param(effect_handle_t handle,
   1035                            effect_param_t *param)
   1036 {
   1037     uint32_t size = sizeof(int);
   1038     uint32_t psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
   1039                         param->vsize;
   1040 
   1041     int status = (*handle)->command(handle,
   1042                                    EFFECT_CMD_SET_PARAM,
   1043                                    sizeof (effect_param_t) + psize,
   1044                                    param,
   1045                                    &size,
   1046                                    &param->status);
   1047     if (status == 0)
   1048         status = param->status;
   1049 
   1050     return status;
   1051 }
   1052 
   1053 static int set_preprocessor_echo_delay(effect_handle_t handle,
   1054                                      int32_t delay_us)
   1055 {
   1056     struct {
   1057         effect_param_t  param;
   1058         uint32_t        data_0;
   1059         int32_t         data_1;
   1060     } buf;
   1061     memset(&buf, 0, sizeof(buf));
   1062 
   1063     buf.param.psize = sizeof(uint32_t);
   1064     buf.param.vsize = sizeof(uint32_t);
   1065     buf.data_0 = AEC_PARAM_ECHO_DELAY;
   1066     buf.data_1 = delay_us;
   1067 
   1068     return set_preprocessor_param(handle, &buf.param);
   1069 }
   1070 
   1071 static void push_echo_reference(struct stream_in *in, size_t frames)
   1072 {
   1073     ALOGVV("%s: enter:)", __func__);
   1074     /* read frames from echo reference buffer and update echo delay
   1075      * in->ref_buf_frames is updated with frames available in in->ref_buf */
   1076 
   1077     int32_t delay_us = update_echo_reference(in, frames)/1000;
   1078     int32_t size_in_bytes = 0;
   1079     int i;
   1080     audio_buffer_t buf;
   1081 
   1082     if (in->ref_buf_frames < frames)
   1083         frames = in->ref_buf_frames;
   1084 
   1085     buf.frameCount = frames;
   1086     buf.raw = in->ref_buf;
   1087 
   1088     for (i = 0; i < in->num_preprocessors; i++) {
   1089         if ((*in->preprocessors[i].effect_itfe)->process_reverse == NULL)
   1090             continue;
   1091         ALOGVV("%s: effect_itfe)->process_reverse() BEGIN i=(%d) ", __func__, i);
   1092         (*in->preprocessors[i].effect_itfe)->process_reverse(in->preprocessors[i].effect_itfe,
   1093                                                &buf,
   1094                                                NULL);
   1095         ALOGVV("%s: effect_itfe)->process_reverse() END i=(%d) ", __func__, i);
   1096         set_preprocessor_echo_delay(in->preprocessors[i].effect_itfe, delay_us);
   1097     }
   1098 
   1099     in->ref_buf_frames -= buf.frameCount;
   1100     ALOGVV("%s: in->ref_buf_frames(%zd), in->config.channels(%d) ",
   1101            __func__, in->ref_buf_frames, in->config.channels);
   1102     if (in->ref_buf_frames) {
   1103         memcpy(in->ref_buf,
   1104                in->ref_buf + buf.frameCount * in->config.channels,
   1105                in->ref_buf_frames * in->config.channels * sizeof(int16_t));
   1106     }
   1107 }
   1108 
   1109 static void put_echo_reference(struct audio_device *adev,
   1110                           struct echo_reference_itfe *reference)
   1111 {
   1112     ALOGV("%s: enter:)", __func__);
   1113     int32_t prev_generation = adev->echo_reference_generation;
   1114     struct stream_out *out = adev->primary_output;
   1115 
   1116     if (adev->echo_reference != NULL &&
   1117             reference == adev->echo_reference) {
   1118         /* echo reference is taken from the low latency output stream used
   1119          * for voice use cases */
   1120         adev->echo_reference = NULL;
   1121         android_atomic_inc(&adev->echo_reference_generation);
   1122         if (out != NULL && out->usecase == USECASE_AUDIO_PLAYBACK) {
   1123             // if the primary output is in standby or did not pick the echo reference yet
   1124             // we can safely get rid of it here.
   1125             // otherwise, out_write() or out_standby() will detect the change in echo reference
   1126             // generation and release the echo reference owned by the stream.
   1127             if ((out->echo_reference_generation != prev_generation) || out->standby)
   1128                 release_echo_reference(reference);
   1129         } else {
   1130             release_echo_reference(reference);
   1131         }
   1132         ALOGV("release_echo_reference");
   1133     }
   1134 }
   1135 
   1136 static struct echo_reference_itfe *get_echo_reference(struct audio_device *adev,
   1137                                                       audio_format_t format __unused,
   1138                                                       uint32_t channel_count,
   1139                                                       uint32_t sampling_rate)
   1140 {
   1141     ALOGV("%s: enter:)", __func__);
   1142     put_echo_reference(adev, adev->echo_reference);
   1143     /* echo reference is taken from the low latency output stream used
   1144      * for voice use cases */
   1145     if (adev->primary_output!= NULL && adev->primary_output->usecase == USECASE_AUDIO_PLAYBACK &&
   1146             !adev->primary_output->standby) {
   1147         struct audio_stream *stream =
   1148                 &adev->primary_output->stream.common;
   1149         uint32_t wr_channel_count = audio_channel_count_from_out_mask(stream->get_channels(stream));
   1150         uint32_t wr_sampling_rate = stream->get_sample_rate(stream);
   1151         ALOGV("Calling create_echo_reference");
   1152         int status = create_echo_reference(AUDIO_FORMAT_PCM_16_BIT,
   1153                                            channel_count,
   1154                                            sampling_rate,
   1155                                            AUDIO_FORMAT_PCM_16_BIT,
   1156                                            wr_channel_count,
   1157                                            wr_sampling_rate,
   1158                                            &adev->echo_reference);
   1159         if (status == 0)
   1160             android_atomic_inc(&adev->echo_reference_generation);
   1161     }
   1162     return adev->echo_reference;
   1163 }
   1164 
   1165 #ifdef HW_AEC_LOOPBACK
   1166 static int get_hw_echo_reference(struct stream_in *in)
   1167 {
   1168     struct pcm_device_profile *ref_pcm_profile;
   1169     struct pcm_device *ref_device;
   1170     struct audio_device *adev = in->dev;
   1171 
   1172     in->hw_echo_reference = false;
   1173 
   1174     if (adev->primary_output!= NULL &&
   1175         !adev->primary_output->standby &&
   1176         adev->primary_output->usecase == USECASE_AUDIO_PLAYBACK &&
   1177         adev->primary_output->devices == AUDIO_DEVICE_OUT_SPEAKER) {
   1178         struct audio_stream *stream = &adev->primary_output->stream.common;
   1179 
   1180         ref_pcm_profile = get_pcm_device(PCM_CAPTURE, pcm_device_capture_loopback_aec.devices);
   1181         if (ref_pcm_profile == NULL) {
   1182             ALOGE("%s: Could not find PCM device id for the usecase(%d)",
   1183                 __func__, pcm_device_capture_loopback_aec.devices);
   1184             return -EINVAL;
   1185         }
   1186 
   1187         if (in->input_flags & AUDIO_INPUT_FLAG_FAST) {
   1188             ALOGV("%s: change capture period size to low latency size %d",
   1189                   __func__, CAPTURE_PERIOD_SIZE_LOW_LATENCY);
   1190             ref_pcm_profile->config.period_size = CAPTURE_PERIOD_SIZE_LOW_LATENCY;
   1191         }
   1192 
   1193         ref_device = (struct pcm_device *)calloc(1, sizeof(struct pcm_device));
   1194         ref_device->pcm_profile = ref_pcm_profile;
   1195 
   1196         ALOGV("%s: ref_device rate:%d, ch:%d", __func__, ref_pcm_profile->config.rate, ref_pcm_profile->config.channels);
   1197         ref_device->pcm = pcm_open(ref_device->pcm_profile->card, ref_device->pcm_profile->id, PCM_IN | PCM_MONOTONIC, &ref_device->pcm_profile->config);
   1198 
   1199         if (ref_device->pcm && !pcm_is_ready(ref_device->pcm)) {
   1200            ALOGE("%s: %s", __func__, pcm_get_error(ref_device->pcm));
   1201            pcm_close(ref_device->pcm);
   1202           ref_device->pcm = NULL;
   1203           return -EIO;
   1204         }
   1205         list_add_tail(&in->pcm_dev_list, &ref_device->stream_list_node);
   1206 
   1207         in->hw_echo_reference = true;
   1208 
   1209         ALOGV("%s: hw_echo_reference is true", __func__);
   1210     }
   1211 
   1212     return 0;
   1213 }
   1214 #endif
   1215 
   1216 static int get_playback_delay(struct stream_out *out,
   1217                        size_t frames,
   1218                        struct echo_reference_buffer *buffer)
   1219 {
   1220     unsigned int kernel_frames;
   1221     int status;
   1222     int primary_pcm = 0;
   1223     struct pcm_device *pcm_device;
   1224 
   1225     pcm_device = node_to_item(list_head(&out->pcm_dev_list),
   1226                               struct pcm_device, stream_list_node);
   1227 
   1228     status = pcm_get_htimestamp(pcm_device->pcm, &kernel_frames, &buffer->time_stamp);
   1229     if (status < 0) {
   1230         buffer->time_stamp.tv_sec  = 0;
   1231         buffer->time_stamp.tv_nsec = 0;
   1232         buffer->delay_ns           = 0;
   1233         ALOGV("get_playback_delay(): pcm_get_htimestamp error,"
   1234                 "setting playbackTimestamp to 0");
   1235         return status;
   1236     }
   1237 
   1238     kernel_frames = pcm_get_buffer_size(pcm_device->pcm) - kernel_frames;
   1239 
   1240     /* adjust render time stamp with delay added by current driver buffer.
   1241      * Add the duration of current frame as we want the render time of the last
   1242      * sample being written. */
   1243     buffer->delay_ns = (long)(((int64_t)(kernel_frames + frames)* 1000000000)/
   1244                             out->config.rate);
   1245     ALOGVV("get_playback_delay_time_stamp Secs: [%10ld], nSecs: [%9ld], kernel_frames: [%5u], delay_ns: [%d],",
   1246          buffer->time_stamp.tv_sec, buffer->time_stamp.tv_nsec, kernel_frames, buffer->delay_ns);
   1247 
   1248     return 0;
   1249 }
   1250 
   1251 #define GET_COMMAND_STATUS(status, fct_status, cmd_status) \
   1252             do {                                           \
   1253                 if (fct_status != 0)                       \
   1254                     status = fct_status;                   \
   1255                 else if (cmd_status != 0)                  \
   1256                     status = cmd_status;                   \
   1257             } while(0)
   1258 
   1259 static int in_configure_reverse(struct stream_in *in)
   1260 {
   1261     int32_t cmd_status;
   1262     uint32_t size = sizeof(int);
   1263     effect_config_t config;
   1264     int32_t status = 0;
   1265     int32_t fct_status = 0;
   1266     int i;
   1267     ALOGV("%s: enter: in->num_preprocessors(%d)", __func__, in->num_preprocessors);
   1268     if (in->num_preprocessors > 0) {
   1269         config.inputCfg.channels = in->main_channels;
   1270         config.outputCfg.channels = in->main_channels;
   1271         config.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
   1272         config.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
   1273         config.inputCfg.samplingRate = in->requested_rate;
   1274         config.outputCfg.samplingRate = in->requested_rate;
   1275         config.inputCfg.mask =
   1276                 ( EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT );
   1277         config.outputCfg.mask =
   1278                 ( EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT );
   1279 
   1280         for (i = 0; i < in->num_preprocessors; i++)
   1281         {
   1282             if ((*in->preprocessors[i].effect_itfe)->process_reverse == NULL)
   1283                 continue;
   1284             fct_status = (*(in->preprocessors[i].effect_itfe))->command(
   1285                                                         in->preprocessors[i].effect_itfe,
   1286                                                         EFFECT_CMD_SET_CONFIG_REVERSE,
   1287                                                         sizeof(effect_config_t),
   1288                                                         &config,
   1289                                                         &size,
   1290                                                         &cmd_status);
   1291             ALOGV("%s: calling EFFECT_CMD_SET_CONFIG_REVERSE",__func__);
   1292             GET_COMMAND_STATUS(status, fct_status, cmd_status);
   1293         }
   1294     }
   1295     return status;
   1296 }
   1297 
   1298 #define MAX_NUM_CHANNEL_CONFIGS 10
   1299 
   1300 static void in_read_audio_effect_channel_configs(struct stream_in *in __unused,
   1301                                                  struct effect_info_s *effect_info)
   1302 {
   1303     /* size and format of the cmd are defined in hardware/audio_effect.h */
   1304     effect_handle_t effect = effect_info->effect_itfe;
   1305     uint32_t cmd_size = 2 * sizeof(uint32_t);
   1306     uint32_t cmd[] = { EFFECT_FEATURE_AUX_CHANNELS, MAX_NUM_CHANNEL_CONFIGS };
   1307     /* reply = status + number of configs (n) + n x channel_config_t */
   1308     uint32_t reply_size =
   1309             2 * sizeof(uint32_t) + (MAX_NUM_CHANNEL_CONFIGS * sizeof(channel_config_t));
   1310     int32_t reply[reply_size];
   1311     int32_t cmd_status;
   1312 
   1313     ALOG_ASSERT((effect_info->num_channel_configs == 0),
   1314                 "in_read_audio_effect_channel_configs() num_channel_configs not cleared");
   1315     ALOG_ASSERT((effect_info->channel_configs == NULL),
   1316                 "in_read_audio_effect_channel_configs() channel_configs not cleared");
   1317 
   1318     /* if this command is not supported, then the effect is supposed to return -EINVAL.
   1319      * This error will be interpreted as if the effect supports the main_channels but does not
   1320      * support any aux_channels */
   1321     cmd_status = (*effect)->command(effect,
   1322                                 EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS,
   1323                                 cmd_size,
   1324                                 (void*)&cmd,
   1325                                 &reply_size,
   1326                                 (void*)&reply);
   1327 
   1328     if (cmd_status != 0) {
   1329         ALOGV("in_read_audio_effect_channel_configs(): "
   1330                 "fx->command returned %d", cmd_status);
   1331         return;
   1332     }
   1333 
   1334     if (reply[0] != 0) {
   1335         ALOGW("in_read_audio_effect_channel_configs(): "
   1336                 "command EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS error %d num configs %d",
   1337                 reply[0], (reply[0] == -ENOMEM) ? reply[1] : MAX_NUM_CHANNEL_CONFIGS);
   1338         return;
   1339     }
   1340 
   1341     /* the feature is not supported */
   1342     ALOGV("in_read_audio_effect_channel_configs()(): "
   1343             "Feature supported and adding %d channel configs to the list", reply[1]);
   1344     effect_info->num_channel_configs = reply[1];
   1345     effect_info->channel_configs =
   1346             (channel_config_t *) malloc(sizeof(channel_config_t) * reply[1]); /* n x configs */
   1347     memcpy(effect_info->channel_configs, (reply + 2), sizeof(channel_config_t) * reply[1]);
   1348 }
   1349 
   1350 
   1351 #define NUM_IN_AUX_CNL_CONFIGS 2
   1352 channel_config_t in_aux_cnl_configs[NUM_IN_AUX_CNL_CONFIGS] = {
   1353     { AUDIO_CHANNEL_IN_FRONT , AUDIO_CHANNEL_IN_BACK},
   1354     { AUDIO_CHANNEL_IN_STEREO , AUDIO_CHANNEL_IN_RIGHT}
   1355 };
   1356 static uint32_t in_get_aux_channels(struct stream_in *in)
   1357 {
   1358     int i;
   1359     channel_config_t new_chcfg = {0, 0};
   1360 
   1361     if (in->num_preprocessors == 0)
   1362         return 0;
   1363 
   1364     /* do not enable dual mic configurations when capturing from other microphones than
   1365      * main or sub */
   1366     if (!(in->devices & (AUDIO_DEVICE_IN_BUILTIN_MIC | AUDIO_DEVICE_IN_BACK_MIC)))
   1367         return 0;
   1368 
   1369     /* retain most complex aux channels configuration compatible with requested main channels and
   1370      * supported by audio driver and all pre processors */
   1371     for (i = 0; i < NUM_IN_AUX_CNL_CONFIGS; i++) {
   1372         channel_config_t *cur_chcfg = &in_aux_cnl_configs[i];
   1373         if (cur_chcfg->main_channels == in->main_channels) {
   1374             size_t match_cnt;
   1375             size_t idx_preproc;
   1376             for (idx_preproc = 0, match_cnt = 0;
   1377                  /* no need to continue if at least one preprocessor doesn't match */
   1378                  idx_preproc < (size_t)in->num_preprocessors && match_cnt == idx_preproc;
   1379                  idx_preproc++) {
   1380                 struct effect_info_s *effect_info = &in->preprocessors[idx_preproc];
   1381                 size_t idx_chcfg;
   1382 
   1383                 for (idx_chcfg = 0; idx_chcfg < effect_info->num_channel_configs; idx_chcfg++) {
   1384                     if (memcmp(effect_info->channel_configs + idx_chcfg,
   1385                                cur_chcfg,
   1386                                sizeof(channel_config_t)) == 0) {
   1387                         match_cnt++;
   1388                         break;
   1389                     }
   1390                 }
   1391             }
   1392             /* if all preprocessors match, we have a candidate */
   1393             if (match_cnt == (size_t)in->num_preprocessors) {
   1394                 /* retain most complex aux channels configuration */
   1395                 if (audio_channel_count_from_in_mask(cur_chcfg->aux_channels) > audio_channel_count_from_in_mask(new_chcfg.aux_channels)) {
   1396                     new_chcfg = *cur_chcfg;
   1397                 }
   1398             }
   1399         }
   1400     }
   1401 
   1402     ALOGV("in_get_aux_channels(): return %04x", new_chcfg.aux_channels);
   1403 
   1404     return new_chcfg.aux_channels;
   1405 }
   1406 
   1407 static int in_configure_effect_channels(effect_handle_t effect,
   1408                                         channel_config_t *channel_config)
   1409 {
   1410     int status = 0;
   1411     int fct_status;
   1412     int32_t cmd_status;
   1413     uint32_t reply_size;
   1414     effect_config_t config;
   1415     uint32_t cmd[(sizeof(uint32_t) + sizeof(channel_config_t) - 1) / sizeof(uint32_t) + 1];
   1416 
   1417     ALOGV("in_configure_effect_channels(): configure effect with channels: [%04x][%04x]",
   1418             channel_config->main_channels,
   1419             channel_config->aux_channels);
   1420 
   1421     config.inputCfg.mask = EFFECT_CONFIG_CHANNELS;
   1422     config.outputCfg.mask = EFFECT_CONFIG_CHANNELS;
   1423     reply_size = sizeof(effect_config_t);
   1424     fct_status = (*effect)->command(effect,
   1425                                 EFFECT_CMD_GET_CONFIG,
   1426                                 0,
   1427                                 NULL,
   1428                                 &reply_size,
   1429                                 &config);
   1430     if (fct_status != 0) {
   1431         ALOGE("in_configure_effect_channels(): EFFECT_CMD_GET_CONFIG failed");
   1432         return fct_status;
   1433     }
   1434 
   1435     config.inputCfg.channels = channel_config->main_channels | channel_config->aux_channels;
   1436     config.outputCfg.channels = config.inputCfg.channels;
   1437     reply_size = sizeof(uint32_t);
   1438     fct_status = (*effect)->command(effect,
   1439                                     EFFECT_CMD_SET_CONFIG,
   1440                                     sizeof(effect_config_t),
   1441                                     &config,
   1442                                     &reply_size,
   1443                                     &cmd_status);
   1444     GET_COMMAND_STATUS(status, fct_status, cmd_status);
   1445 
   1446     cmd[0] = EFFECT_FEATURE_AUX_CHANNELS;
   1447     memcpy(cmd + 1, channel_config, sizeof(channel_config_t));
   1448     reply_size = sizeof(uint32_t);
   1449     fct_status = (*effect)->command(effect,
   1450                                 EFFECT_CMD_SET_FEATURE_CONFIG,
   1451                                 sizeof(cmd), //sizeof(uint32_t) + sizeof(channel_config_t),
   1452                                 cmd,
   1453                                 &reply_size,
   1454                                 &cmd_status);
   1455     GET_COMMAND_STATUS(status, fct_status, cmd_status);
   1456 
   1457     /* some implementations need to be re-enabled after a config change */
   1458     reply_size = sizeof(uint32_t);
   1459     fct_status = (*effect)->command(effect,
   1460                                   EFFECT_CMD_ENABLE,
   1461                                   0,
   1462                                   NULL,
   1463                                   &reply_size,
   1464                                   &cmd_status);
   1465     GET_COMMAND_STATUS(status, fct_status, cmd_status);
   1466 
   1467     return status;
   1468 }
   1469 
   1470 static int in_reconfigure_channels(struct stream_in *in,
   1471                                    effect_handle_t effect,
   1472                                    channel_config_t *channel_config,
   1473                                    bool config_changed) {
   1474 
   1475     int status = 0;
   1476 
   1477     ALOGV("in_reconfigure_channels(): config_changed %d effect %p",
   1478           config_changed, effect);
   1479 
   1480     /* if config changed, reconfigure all previously added effects */
   1481     if (config_changed) {
   1482         int i;
   1483         ALOGV("%s: config_changed (%d)", __func__, config_changed);
   1484         for (i = 0; i < in->num_preprocessors; i++)
   1485         {
   1486             int cur_status = in_configure_effect_channels(in->preprocessors[i].effect_itfe,
   1487                                                   channel_config);
   1488             ALOGV("%s: in_configure_effect_channels i=(%d), [main_channel,aux_channel]=[%d|%d], status=%d",
   1489                           __func__, i, channel_config->main_channels, channel_config->aux_channels, cur_status);
   1490             if (cur_status != 0) {
   1491                 ALOGV("in_reconfigure_channels(): error %d configuring effect "
   1492                         "%d with channels: [%04x][%04x]",
   1493                         cur_status,
   1494                         i,
   1495                         channel_config->main_channels,
   1496                         channel_config->aux_channels);
   1497                 status = cur_status;
   1498             }
   1499         }
   1500     } else if (effect != NULL && channel_config->aux_channels) {
   1501         /* if aux channels config did not change but aux channels are present,
   1502          * we still need to configure the effect being added */
   1503         status = in_configure_effect_channels(effect, channel_config);
   1504     }
   1505     return status;
   1506 }
   1507 
   1508 static void in_update_aux_channels(struct stream_in *in,
   1509                                    effect_handle_t effect)
   1510 {
   1511     uint32_t aux_channels;
   1512     channel_config_t channel_config;
   1513     int status;
   1514 
   1515     aux_channels = in_get_aux_channels(in);
   1516 
   1517     channel_config.main_channels = in->main_channels;
   1518     channel_config.aux_channels = aux_channels;
   1519     status = in_reconfigure_channels(in,
   1520                                      effect,
   1521                                      &channel_config,
   1522                                      (aux_channels != in->aux_channels));
   1523 
   1524     if (status != 0) {
   1525         ALOGV("in_update_aux_channels(): in_reconfigure_channels error %d", status);
   1526         /* resetting aux channels configuration */
   1527         aux_channels = 0;
   1528         channel_config.aux_channels = 0;
   1529         in_reconfigure_channels(in, effect, &channel_config, true);
   1530     }
   1531     ALOGV("%s: aux_channels=%d, in->aux_channels_changed=%d", __func__, aux_channels, in->aux_channels_changed);
   1532     if (in->aux_channels != aux_channels) {
   1533         in->aux_channels_changed = true;
   1534         in->aux_channels = aux_channels;
   1535         do_in_standby_l(in);
   1536     }
   1537 }
   1538 #endif
   1539 
   1540 /* This function reads PCM data and:
   1541  * - resample if needed
   1542  * - process if pre-processors are attached
   1543  * - discard unwanted channels
   1544  */
   1545 static ssize_t read_and_process_frames(struct stream_in *in, void* buffer, ssize_t frames)
   1546 {
   1547     ssize_t frames_wr = 0;
   1548     audio_buffer_t in_buf;
   1549     audio_buffer_t out_buf;
   1550     size_t src_channels = in->config.channels;
   1551     size_t dst_channels = audio_channel_count_from_in_mask(in->main_channels);
   1552     int i;
   1553     void *proc_buf_out;
   1554     struct pcm_device *pcm_device;
   1555     bool has_additional_channels = (dst_channels != src_channels) ? true : false;
   1556 #ifdef PREPROCESSING_ENABLED
   1557     bool has_processing = (in->num_preprocessors != 0) ? true : false;
   1558 #endif
   1559 
   1560     /* Additional channels might be added on top of main_channels:
   1561     * - aux_channels (by processing effects)
   1562     * - extra channels due to HW limitations
   1563     * In case of additional channels, we cannot work inplace
   1564     */
   1565     if (has_additional_channels)
   1566         proc_buf_out = in->proc_buf_out;
   1567     else
   1568         proc_buf_out = buffer;
   1569 
   1570     if (list_empty(&in->pcm_dev_list)) {
   1571         ALOGE("%s: pcm device list empty", __func__);
   1572         return -EINVAL;
   1573     }
   1574 
   1575     pcm_device = node_to_item(list_head(&in->pcm_dev_list),
   1576                               struct pcm_device, stream_list_node);
   1577 
   1578 #ifdef PREPROCESSING_ENABLED
   1579     if (has_processing) {
   1580         /* since all the processing below is done in frames and using the config.channels
   1581          * as the number of channels, no changes is required in case aux_channels are present */
   1582         while (frames_wr < frames) {
   1583             /* first reload enough frames at the end of process input buffer */
   1584             if (in->proc_buf_frames < (size_t)frames) {
   1585                 ssize_t frames_rd;
   1586                 if (in->proc_buf_size < (size_t)frames) {
   1587                     size_t size_in_bytes = pcm_frames_to_bytes(pcm_device->pcm, frames);
   1588                     in->proc_buf_size = (size_t)frames;
   1589                     in->proc_buf_in = (int16_t *)realloc(in->proc_buf_in, size_in_bytes);
   1590                     ALOG_ASSERT((in->proc_buf_in != NULL),
   1591                                 "process_frames() failed to reallocate proc_buf_in");
   1592                     if (has_additional_channels) {
   1593                         in->proc_buf_out = (int16_t *)realloc(in->proc_buf_out, size_in_bytes);
   1594                         ALOG_ASSERT((in->proc_buf_out != NULL),
   1595                                     "process_frames() failed to reallocate proc_buf_out");
   1596                         proc_buf_out = in->proc_buf_out;
   1597                     }
   1598                 }
   1599                 frames_rd = read_frames(in,
   1600                                         in->proc_buf_in +
   1601                                             in->proc_buf_frames * in->config.channels,
   1602                                         frames - in->proc_buf_frames);
   1603                   if (frames_rd < 0) {
   1604                     /* Return error code */
   1605                     frames_wr = frames_rd;
   1606                     break;
   1607                 }
   1608                 in->proc_buf_frames += frames_rd;
   1609             }
   1610 
   1611             if (in->echo_reference != NULL) {
   1612                 push_echo_reference(in, in->proc_buf_frames);
   1613             }
   1614 
   1615              /* in_buf.frameCount and out_buf.frameCount indicate respectively
   1616               * the maximum number of frames to be consumed and produced by process() */
   1617             in_buf.frameCount = in->proc_buf_frames;
   1618             in_buf.s16 = in->proc_buf_in;
   1619             out_buf.frameCount = frames - frames_wr;
   1620             out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * in->config.channels;
   1621 
   1622             /* FIXME: this works because of current pre processing library implementation that
   1623              * does the actual process only when the last enabled effect process is called.
   1624              * The generic solution is to have an output buffer for each effect and pass it as
   1625              * input to the next.
   1626              */
   1627             for (i = 0; i < in->num_preprocessors; i++) {
   1628                 (*in->preprocessors[i].effect_itfe)->process(in->preprocessors[i].effect_itfe,
   1629                                                    &in_buf,
   1630                                                    &out_buf);
   1631             }
   1632 
   1633             /* process() has updated the number of frames consumed and produced in
   1634              * in_buf.frameCount and out_buf.frameCount respectively
   1635              * move remaining frames to the beginning of in->proc_buf_in */
   1636             in->proc_buf_frames -= in_buf.frameCount;
   1637 
   1638             if (in->proc_buf_frames) {
   1639                 memcpy(in->proc_buf_in,
   1640                        in->proc_buf_in + in_buf.frameCount * in->config.channels,
   1641                        in->proc_buf_frames * in->config.channels * sizeof(int16_t));
   1642             }
   1643 
   1644             /* if not enough frames were passed to process(), read more and retry. */
   1645             if (out_buf.frameCount == 0) {
   1646                 ALOGW("No frames produced by preproc");
   1647                 continue;
   1648             }
   1649 
   1650             if ((frames_wr + (ssize_t)out_buf.frameCount) <= frames) {
   1651                 frames_wr += out_buf.frameCount;
   1652             } else {
   1653                 /* The effect does not comply to the API. In theory, we should never end up here! */
   1654                 ALOGE("preprocessing produced too many frames: %d + %zd  > %d !",
   1655                       (unsigned int)frames_wr, out_buf.frameCount, (unsigned int)frames);
   1656                 frames_wr = frames;
   1657             }
   1658         }
   1659     }
   1660     else
   1661 #endif //PREPROCESSING_ENABLED
   1662     {
   1663         /* No processing effects attached */
   1664         if (has_additional_channels) {
   1665             /* With additional channels, we cannot use original buffer */
   1666             if (in->proc_buf_size < (size_t)frames) {
   1667                 size_t size_in_bytes = pcm_frames_to_bytes(pcm_device->pcm, frames);
   1668                 in->proc_buf_size = (size_t)frames;
   1669                 in->proc_buf_out = (int16_t *)realloc(in->proc_buf_out, size_in_bytes);
   1670                 ALOG_ASSERT((in->proc_buf_out != NULL),
   1671                             "process_frames() failed to reallocate proc_buf_out");
   1672                 proc_buf_out = in->proc_buf_out;
   1673             }
   1674         }
   1675         frames_wr = read_frames(in, proc_buf_out, frames);
   1676     }
   1677 
   1678     /* Remove all additional channels that have been added on top of main_channels:
   1679      * - aux_channels
   1680      * - extra channels from HW due to HW limitations
   1681      * Assumption is made that the channels are interleaved and that the main
   1682      * channels are first. */
   1683 
   1684     if (has_additional_channels)
   1685     {
   1686         int16_t* src_buffer = (int16_t *)proc_buf_out;
   1687         int16_t* dst_buffer = (int16_t *)buffer;
   1688 
   1689         if (dst_channels == 1) {
   1690             for (i = frames_wr; i > 0; i--)
   1691             {
   1692                 *dst_buffer++ = *src_buffer;
   1693                 src_buffer += src_channels;
   1694             }
   1695         } else {
   1696             for (i = frames_wr; i > 0; i--)
   1697             {
   1698                 memcpy(dst_buffer, src_buffer, dst_channels*sizeof(int16_t));
   1699                 dst_buffer += dst_channels;
   1700                 src_buffer += src_channels;
   1701             }
   1702         }
   1703     }
   1704 
   1705     return frames_wr;
   1706 }
   1707 
   1708 static int get_next_buffer(struct resampler_buffer_provider *buffer_provider,
   1709                                    struct resampler_buffer* buffer)
   1710 {
   1711     struct stream_in *in;
   1712     struct pcm_device *pcm_device;
   1713 
   1714     if (buffer_provider == NULL || buffer == NULL)
   1715         return -EINVAL;
   1716 
   1717     in = (struct stream_in *)((char *)buffer_provider -
   1718                                    offsetof(struct stream_in, buf_provider));
   1719 
   1720     if (list_empty(&in->pcm_dev_list)) {
   1721         buffer->raw = NULL;
   1722         buffer->frame_count = 0;
   1723         in->read_status = -ENODEV;
   1724         return -ENODEV;
   1725     }
   1726 
   1727     pcm_device = node_to_item(list_head(&in->pcm_dev_list),
   1728                               struct pcm_device, stream_list_node);
   1729 
   1730     if (in->read_buf_frames == 0) {
   1731         size_t size_in_bytes = pcm_frames_to_bytes(pcm_device->pcm, in->config.period_size);
   1732         if (in->read_buf_size < in->config.period_size) {
   1733             in->read_buf_size = in->config.period_size;
   1734             in->read_buf = (int16_t *) realloc(in->read_buf, size_in_bytes);
   1735             ALOG_ASSERT((in->read_buf != NULL),
   1736                         "get_next_buffer() failed to reallocate read_buf");
   1737         }
   1738 
   1739         in->read_status = pcm_read(pcm_device->pcm, (void*)in->read_buf, size_in_bytes);
   1740 
   1741         if (in->read_status != 0) {
   1742             ALOGE("get_next_buffer() pcm_read error %d", in->read_status);
   1743             buffer->raw = NULL;
   1744             buffer->frame_count = 0;
   1745             return in->read_status;
   1746         }
   1747         in->read_buf_frames = in->config.period_size;
   1748 
   1749 #ifdef PREPROCESSING_ENABLED
   1750 #ifdef HW_AEC_LOOPBACK
   1751         if (in->hw_echo_reference) {
   1752             struct pcm_device *temp_device = NULL;
   1753             struct pcm_device *ref_device = NULL;
   1754             struct listnode *node = NULL;
   1755             struct echo_reference_buffer b;
   1756             size_t size_hw_ref_bytes;
   1757             size_t size_hw_ref_frames;
   1758             int read_status = 0;
   1759 
   1760             ref_device = node_to_item(list_tail(&in->pcm_dev_list),
   1761                                       struct pcm_device, stream_list_node);
   1762             list_for_each(node, &in->pcm_dev_list) {
   1763                 temp_device = node_to_item(node, struct pcm_device, stream_list_node);
   1764                 if (temp_device->pcm_profile->id == 1) {
   1765                     ref_device = temp_device;
   1766                     break;
   1767                 }
   1768             }
   1769             if (ref_device) {
   1770                 size_hw_ref_bytes = pcm_frames_to_bytes(ref_device->pcm, ref_device->pcm_profile->config.period_size);
   1771                 size_hw_ref_frames = ref_device->pcm_profile->config.period_size;
   1772                 if (in->hw_ref_buf_size < size_hw_ref_frames) {
   1773                     in->hw_ref_buf_size = size_hw_ref_frames;
   1774                     in->hw_ref_buf = (int16_t *) realloc(in->hw_ref_buf, size_hw_ref_bytes);
   1775                     ALOG_ASSERT((in->hw_ref_buf != NULL),
   1776                                 "get_next_buffer() failed to reallocate hw_ref_buf");
   1777                     ALOGV("get_next_buffer(): hw_ref_buf %p extended to %zd bytes",
   1778                           in->hw_ref_buf, size_hw_ref_bytes);
   1779                 }
   1780 
   1781                 read_status = pcm_read(ref_device->pcm, (void*)in->hw_ref_buf, size_hw_ref_bytes);
   1782                 if (read_status != 0) {
   1783                     ALOGE("process_frames() pcm_read error for HW reference %d", read_status);
   1784                     b.raw = NULL;
   1785                     b.frame_count = 0;
   1786                 }
   1787                 else {
   1788                     get_capture_reference_delay(in, size_hw_ref_frames, &b);
   1789                     b.raw = (void *)in->hw_ref_buf;
   1790                     b.frame_count = size_hw_ref_frames;
   1791                     if (b.delay_ns != 0)
   1792                         b.delay_ns = -b.delay_ns; // as this is capture delay, it needs to be subtracted from the microphone delay
   1793                     in->echo_reference->write(in->echo_reference, &b);
   1794                 }
   1795             }
   1796         }
   1797 #endif // HW_AEC_LOOPBACK
   1798 #endif // PREPROCESSING_ENABLED
   1799     }
   1800 
   1801     buffer->frame_count = (buffer->frame_count > in->read_buf_frames) ?
   1802                                 in->read_buf_frames : buffer->frame_count;
   1803     buffer->i16 = in->read_buf + (in->config.period_size - in->read_buf_frames) *
   1804                                                 in->config.channels;
   1805     return in->read_status;
   1806 }
   1807 
   1808 static void release_buffer(struct resampler_buffer_provider *buffer_provider,
   1809                                   struct resampler_buffer* buffer)
   1810 {
   1811     struct stream_in *in;
   1812 
   1813     if (buffer_provider == NULL || buffer == NULL)
   1814         return;
   1815 
   1816     in = (struct stream_in *)((char *)buffer_provider -
   1817                                    offsetof(struct stream_in, buf_provider));
   1818 
   1819     in->read_buf_frames -= buffer->frame_count;
   1820 }
   1821 
   1822 /* read_frames() reads frames from kernel driver, down samples to capture rate
   1823  * if necessary and output the number of frames requested to the buffer specified */
   1824 static ssize_t read_frames(struct stream_in *in, void *buffer, ssize_t frames)
   1825 {
   1826     ssize_t frames_wr = 0;
   1827 
   1828     struct pcm_device *pcm_device;
   1829 
   1830     if (list_empty(&in->pcm_dev_list)) {
   1831         ALOGE("%s: pcm device list empty", __func__);
   1832         return -EINVAL;
   1833     }
   1834 
   1835     pcm_device = node_to_item(list_head(&in->pcm_dev_list),
   1836                               struct pcm_device, stream_list_node);
   1837 
   1838     while (frames_wr < frames) {
   1839         size_t frames_rd = frames - frames_wr;
   1840         ALOGVV("%s: frames_rd: %zd, frames_wr: %zd, in->config.channels: %d",
   1841                __func__,frames_rd,frames_wr,in->config.channels);
   1842         if (in->resampler != NULL) {
   1843             in->resampler->resample_from_provider(in->resampler,
   1844                     (int16_t *)((char *)buffer +
   1845                             pcm_frames_to_bytes(pcm_device->pcm, frames_wr)),
   1846                     &frames_rd);
   1847         } else {
   1848             struct resampler_buffer buf = {
   1849                     { raw : NULL, },
   1850                     frame_count : frames_rd,
   1851             };
   1852             get_next_buffer(&in->buf_provider, &buf);
   1853             if (buf.raw != NULL) {
   1854                 memcpy((char *)buffer +
   1855                             pcm_frames_to_bytes(pcm_device->pcm, frames_wr),
   1856                         buf.raw,
   1857                         pcm_frames_to_bytes(pcm_device->pcm, buf.frame_count));
   1858                 frames_rd = buf.frame_count;
   1859             }
   1860             release_buffer(&in->buf_provider, &buf);
   1861         }
   1862         /* in->read_status is updated by getNextBuffer() also called by
   1863          * in->resampler->resample_from_provider() */
   1864         if (in->read_status != 0)
   1865             return in->read_status;
   1866 
   1867         frames_wr += frames_rd;
   1868     }
   1869     return frames_wr;
   1870 }
   1871 
   1872 static int in_release_pcm_devices(struct stream_in *in)
   1873 {
   1874     struct pcm_device *pcm_device;
   1875     struct listnode *node;
   1876     struct listnode *next;
   1877 
   1878     list_for_each_safe(node, next, &in->pcm_dev_list) {
   1879         pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   1880         list_remove(node);
   1881         free(pcm_device);
   1882     }
   1883 
   1884     return 0;
   1885 }
   1886 
   1887 static int stop_input_stream(struct stream_in *in)
   1888 {
   1889     struct audio_usecase *uc_info;
   1890     struct audio_device *adev = in->dev;
   1891 
   1892     adev->active_input = NULL;
   1893     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   1894           in->usecase, use_case_table[in->usecase]);
   1895     uc_info = get_usecase_from_id(adev, in->usecase);
   1896     if (uc_info == NULL) {
   1897         ALOGE("%s: Could not find the usecase (%d) in the list",
   1898               __func__, in->usecase);
   1899         return -EINVAL;
   1900     }
   1901 
   1902     /* Disable the tx device */
   1903     disable_snd_device(adev, uc_info, uc_info->in_snd_device, true);
   1904 
   1905     list_remove(&uc_info->adev_list_node);
   1906     free(uc_info);
   1907 
   1908     if (list_empty(&in->pcm_dev_list)) {
   1909         ALOGE("%s: pcm device list empty", __func__);
   1910         return -EINVAL;
   1911     }
   1912 
   1913     in_release_pcm_devices(in);
   1914     list_init(&in->pcm_dev_list);
   1915 
   1916 #ifdef HW_AEC_LOOPBACK
   1917     if (in->hw_echo_reference)
   1918     {
   1919         in->hw_echo_reference = false;
   1920     }
   1921 #endif
   1922 
   1923     ALOGV("%s: exit", __func__);
   1924     return 0;
   1925 }
   1926 
   1927 int start_input_stream(struct stream_in *in)
   1928 {
   1929     /* Enable output device and stream routing controls */
   1930     int ret = 0;
   1931     bool recreate_resampler = false;
   1932     struct audio_usecase *uc_info;
   1933     struct audio_device *adev = in->dev;
   1934     struct pcm_device_profile *pcm_profile;
   1935     struct pcm_device *pcm_device;
   1936 
   1937     ALOGV("%s: enter: usecase(%d)", __func__, in->usecase);
   1938     adev->active_input = in;
   1939     pcm_profile = get_pcm_device(in->usecase == USECASE_AUDIO_CAPTURE_HOTWORD
   1940                                  ? PCM_HOTWORD_STREAMING : PCM_CAPTURE, in->devices);
   1941     if (pcm_profile == NULL) {
   1942         ALOGE("%s: Could not find PCM device id for the usecase(%d)",
   1943               __func__, in->usecase);
   1944         ret = -EINVAL;
   1945         goto error_config;
   1946     }
   1947 
   1948     if (in->input_flags & AUDIO_INPUT_FLAG_FAST) {
   1949         ALOGV("%s: change capture period size to low latency size %d",
   1950               __func__, CAPTURE_PERIOD_SIZE_LOW_LATENCY);
   1951         pcm_profile->config.period_size = CAPTURE_PERIOD_SIZE_LOW_LATENCY;
   1952     }
   1953 
   1954     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
   1955     uc_info->id = in->usecase;
   1956     uc_info->type = PCM_CAPTURE;
   1957     uc_info->stream = (struct audio_stream *)in;
   1958     uc_info->devices = in->devices;
   1959     uc_info->in_snd_device = SND_DEVICE_NONE;
   1960     uc_info->out_snd_device = SND_DEVICE_NONE;
   1961 
   1962     pcm_device = (struct pcm_device *)calloc(1, sizeof(struct pcm_device));
   1963     pcm_device->pcm_profile = pcm_profile;
   1964     list_init(&in->pcm_dev_list);
   1965     list_add_tail(&in->pcm_dev_list, &pcm_device->stream_list_node);
   1966 
   1967     list_init(&uc_info->mixer_list);
   1968     list_add_tail(&uc_info->mixer_list,
   1969                   &adev_get_mixer_for_card(adev,
   1970                                        pcm_device->pcm_profile->card)->uc_list_node[uc_info->id]);
   1971 
   1972     list_add_tail(&adev->usecase_list, &uc_info->adev_list_node);
   1973 
   1974     select_devices(adev, in->usecase);
   1975 
   1976     /* Config should be updated as profile can be changed between different calls
   1977      * to this function:
   1978      * - Trigger resampler creation
   1979      * - Config needs to be updated */
   1980     if (in->config.rate != pcm_profile->config.rate) {
   1981         recreate_resampler = true;
   1982     }
   1983     in->config = pcm_profile->config;
   1984 
   1985 #ifdef PREPROCESSING_ENABLED
   1986     if (in->aux_channels_changed) {
   1987         in->config.channels = audio_channel_count_from_in_mask(in->main_channels | in->aux_channels);
   1988         recreate_resampler = true;
   1989     }
   1990 #endif
   1991 
   1992     if (in->requested_rate != in->config.rate) {
   1993         recreate_resampler = true;
   1994     }
   1995 
   1996     if (recreate_resampler) {
   1997         if (in->resampler) {
   1998             release_resampler(in->resampler);
   1999             in->resampler = NULL;
   2000         }
   2001         in->buf_provider.get_next_buffer = get_next_buffer;
   2002         in->buf_provider.release_buffer = release_buffer;
   2003         ret = create_resampler(in->config.rate,
   2004                                in->requested_rate,
   2005                                in->config.channels,
   2006                                RESAMPLER_QUALITY_DEFAULT,
   2007                                &in->buf_provider,
   2008                                &in->resampler);
   2009     }
   2010 
   2011 #ifdef PREPROCESSING_ENABLED
   2012     if (in->enable_aec && in->echo_reference == NULL) {
   2013         in->echo_reference = get_echo_reference(adev,
   2014                                                 AUDIO_FORMAT_PCM_16_BIT,
   2015                                                 audio_channel_count_from_in_mask(in->main_channels),
   2016                                                 in->requested_rate
   2017                                                 );
   2018     }
   2019 
   2020 #ifdef HW_AEC_LOOPBACK
   2021     if (in->enable_aec) {
   2022         ret = get_hw_echo_reference(in);
   2023         if (ret!=0)
   2024             goto error_open;
   2025 
   2026         /* force ref buffer reallocation */
   2027         in->hw_ref_buf_size = 0;
   2028     }
   2029 #endif
   2030 #endif
   2031 
   2032     /* Open the PCM device.
   2033      * The HW is limited to support only the default pcm_profile settings.
   2034      * As such a change in aux_channels will not have an effect.
   2035      */
   2036     ALOGV("%s: Opening PCM device card_id(%d) device_id(%d), channels %d, smp rate %d format %d, \
   2037           period_size %d", __func__, pcm_device->pcm_profile->card, pcm_device->pcm_profile->id,
   2038           pcm_device->pcm_profile->config.channels,pcm_device->pcm_profile->config.rate,
   2039           pcm_device->pcm_profile->config.format, pcm_device->pcm_profile->config.period_size);
   2040 
   2041     if (pcm_profile->type == PCM_HOTWORD_STREAMING) {
   2042         if (!adev->sound_trigger_open_for_streaming) {
   2043             ALOGE("%s: No handle to sound trigger HAL", __func__);
   2044             ret = -EIO;
   2045             goto error_open;
   2046         }
   2047         pcm_device->pcm = NULL;
   2048         pcm_device->sound_trigger_handle = adev->sound_trigger_open_for_streaming();
   2049         if (pcm_device->sound_trigger_handle <= 0) {
   2050             ALOGE("%s: Failed to open DSP for streaming", __func__);
   2051             ret = -EIO;
   2052             goto error_open;
   2053         }
   2054         ALOGV("Opened DSP successfully");
   2055     } else {
   2056         pcm_device->sound_trigger_handle = 0;
   2057         pcm_device->pcm = pcm_open(pcm_device->pcm_profile->card, pcm_device->pcm_profile->id,
   2058                                    PCM_IN | PCM_MONOTONIC, &pcm_device->pcm_profile->config);
   2059 
   2060         if (pcm_device->pcm && !pcm_is_ready(pcm_device->pcm)) {
   2061             ALOGE("%s: %s", __func__, pcm_get_error(pcm_device->pcm));
   2062             pcm_close(pcm_device->pcm);
   2063             pcm_device->pcm = NULL;
   2064             ret = -EIO;
   2065             goto error_open;
   2066         }
   2067     }
   2068 
   2069     /* force read and proc buffer reallocation in case of frame size or
   2070      * channel count change */
   2071     in->proc_buf_frames = 0;
   2072     in->proc_buf_size = 0;
   2073     in->read_buf_size = 0;
   2074     in->read_buf_frames = 0;
   2075 
   2076     /* if no supported sample rate is available, use the resampler */
   2077     if (in->resampler) {
   2078         in->resampler->reset(in->resampler);
   2079     }
   2080 
   2081     ALOGV("%s: exit", __func__);
   2082     return ret;
   2083 
   2084 error_open:
   2085     if (in->resampler) {
   2086         release_resampler(in->resampler);
   2087         in->resampler = NULL;
   2088     }
   2089     stop_input_stream(in);
   2090 
   2091 error_config:
   2092     ALOGD("%s: exit: status(%d)", __func__, ret);
   2093     adev->active_input = NULL;
   2094     return ret;
   2095 }
   2096 
   2097 /* must be called with out->lock locked */
   2098 static int send_offload_cmd_l(struct stream_out* out, int command)
   2099 {
   2100     struct offload_cmd *cmd = (struct offload_cmd *)calloc(1, sizeof(struct offload_cmd));
   2101 
   2102     ALOGVV("%s %d", __func__, command);
   2103 
   2104     cmd->cmd = command;
   2105     list_add_tail(&out->offload_cmd_list, &cmd->node);
   2106     pthread_cond_signal(&out->offload_cond);
   2107     return 0;
   2108 }
   2109 
   2110 /* must be called iwth out->lock locked */
   2111 static void stop_compressed_output_l(struct stream_out *out)
   2112 {
   2113     out->send_new_metadata = 1;
   2114     if (out->compr != NULL) {
   2115         compress_stop(out->compr);
   2116         while (out->offload_thread_blocked) {
   2117             pthread_cond_wait(&out->cond, &out->lock);
   2118         }
   2119     }
   2120 }
   2121 
   2122 static void *offload_thread_loop(void *context)
   2123 {
   2124     struct stream_out *out = (struct stream_out *) context;
   2125     struct listnode *item;
   2126 
   2127     setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
   2128     set_sched_policy(0, SP_FOREGROUND);
   2129     prctl(PR_SET_NAME, (unsigned long)"Offload Callback", 0, 0, 0);
   2130 
   2131     ALOGV("%s", __func__);
   2132     pthread_mutex_lock(&out->lock);
   2133     for (;;) {
   2134         struct offload_cmd *cmd = NULL;
   2135         stream_callback_event_t event;
   2136         bool send_callback = false;
   2137 
   2138         ALOGVV("%s offload_cmd_list %d out->offload_state %d",
   2139               __func__, list_empty(&out->offload_cmd_list),
   2140               out->offload_state);
   2141         if (list_empty(&out->offload_cmd_list)) {
   2142             ALOGV("%s SLEEPING", __func__);
   2143             pthread_cond_wait(&out->offload_cond, &out->lock);
   2144             ALOGV("%s RUNNING", __func__);
   2145             continue;
   2146         }
   2147 
   2148         item = list_head(&out->offload_cmd_list);
   2149         cmd = node_to_item(item, struct offload_cmd, node);
   2150         list_remove(item);
   2151 
   2152         ALOGVV("%s STATE %d CMD %d out->compr %p",
   2153                __func__, out->offload_state, cmd->cmd, out->compr);
   2154 
   2155         if (cmd->cmd == OFFLOAD_CMD_EXIT) {
   2156             free(cmd);
   2157             break;
   2158         }
   2159 
   2160         if (out->compr == NULL) {
   2161             ALOGE("%s: Compress handle is NULL", __func__);
   2162             pthread_cond_signal(&out->cond);
   2163             continue;
   2164         }
   2165         out->offload_thread_blocked = true;
   2166         pthread_mutex_unlock(&out->lock);
   2167         send_callback = false;
   2168         switch(cmd->cmd) {
   2169         case OFFLOAD_CMD_WAIT_FOR_BUFFER:
   2170             compress_wait(out->compr, -1);
   2171             send_callback = true;
   2172             event = STREAM_CBK_EVENT_WRITE_READY;
   2173             break;
   2174         case OFFLOAD_CMD_PARTIAL_DRAIN:
   2175             compress_next_track(out->compr);
   2176             compress_partial_drain(out->compr);
   2177             send_callback = true;
   2178             event = STREAM_CBK_EVENT_DRAIN_READY;
   2179             break;
   2180         case OFFLOAD_CMD_DRAIN:
   2181             compress_drain(out->compr);
   2182             send_callback = true;
   2183             event = STREAM_CBK_EVENT_DRAIN_READY;
   2184             break;
   2185         default:
   2186             ALOGE("%s unknown command received: %d", __func__, cmd->cmd);
   2187             break;
   2188         }
   2189         pthread_mutex_lock(&out->lock);
   2190         out->offload_thread_blocked = false;
   2191         pthread_cond_signal(&out->cond);
   2192         if (send_callback) {
   2193             out->offload_callback(event, NULL, out->offload_cookie);
   2194         }
   2195         free(cmd);
   2196     }
   2197 
   2198     pthread_cond_signal(&out->cond);
   2199     while (!list_empty(&out->offload_cmd_list)) {
   2200         item = list_head(&out->offload_cmd_list);
   2201         list_remove(item);
   2202         free(node_to_item(item, struct offload_cmd, node));
   2203     }
   2204     pthread_mutex_unlock(&out->lock);
   2205 
   2206     return NULL;
   2207 }
   2208 
   2209 static int create_offload_callback_thread(struct stream_out *out)
   2210 {
   2211     pthread_cond_init(&out->offload_cond, (const pthread_condattr_t *) NULL);
   2212     list_init(&out->offload_cmd_list);
   2213     pthread_create(&out->offload_thread, (const pthread_attr_t *) NULL,
   2214                     offload_thread_loop, out);
   2215     return 0;
   2216 }
   2217 
   2218 static int destroy_offload_callback_thread(struct stream_out *out)
   2219 {
   2220     pthread_mutex_lock(&out->lock);
   2221     send_offload_cmd_l(out, OFFLOAD_CMD_EXIT);
   2222 
   2223     pthread_mutex_unlock(&out->lock);
   2224     pthread_join(out->offload_thread, (void **) NULL);
   2225     pthread_cond_destroy(&out->offload_cond);
   2226 
   2227     return 0;
   2228 }
   2229 
   2230 static int uc_release_pcm_devices(struct audio_usecase *usecase)
   2231 {
   2232     struct stream_out *out = (struct stream_out *)usecase->stream;
   2233     struct pcm_device *pcm_device;
   2234     struct listnode *node;
   2235     struct listnode *next;
   2236 
   2237     list_for_each_safe(node, next, &out->pcm_dev_list) {
   2238         pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   2239         list_remove(node);
   2240         free(pcm_device);
   2241     }
   2242     list_init(&usecase->mixer_list);
   2243 
   2244     return 0;
   2245 }
   2246 
   2247 static int uc_select_pcm_devices(struct audio_usecase *usecase)
   2248 
   2249 {
   2250     struct stream_out *out = (struct stream_out *)usecase->stream;
   2251     struct pcm_device *pcm_device;
   2252     struct pcm_device_profile *pcm_profile;
   2253     struct mixer_card *mixer_card;
   2254     audio_devices_t devices = usecase->devices;
   2255 
   2256     list_init(&usecase->mixer_list);
   2257     list_init(&out->pcm_dev_list);
   2258 
   2259     while ((pcm_profile = get_pcm_device(usecase->type, devices)) != NULL) {
   2260         pcm_device = calloc(1, sizeof(struct pcm_device));
   2261         pcm_device->pcm_profile = pcm_profile;
   2262         list_add_tail(&out->pcm_dev_list, &pcm_device->stream_list_node);
   2263         mixer_card = uc_get_mixer_for_card(usecase, pcm_profile->card);
   2264         if (mixer_card == NULL) {
   2265             mixer_card = adev_get_mixer_for_card(out->dev, pcm_profile->card);
   2266             list_add_tail(&usecase->mixer_list, &mixer_card->uc_list_node[usecase->id]);
   2267         }
   2268         devices &= ~pcm_profile->devices;
   2269     }
   2270 
   2271     return 0;
   2272 }
   2273 
   2274 static int out_close_pcm_devices(struct stream_out *out)
   2275 {
   2276     struct pcm_device *pcm_device;
   2277     struct listnode *node;
   2278     struct audio_device *adev = out->dev;
   2279 
   2280     list_for_each(node, &out->pcm_dev_list) {
   2281         pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   2282         if (pcm_device->sound_trigger_handle > 0) {
   2283             adev->sound_trigger_close_for_streaming(pcm_device->sound_trigger_handle);
   2284             pcm_device->sound_trigger_handle = 0;
   2285         }
   2286         if (pcm_device->pcm) {
   2287             pcm_close(pcm_device->pcm);
   2288             pcm_device->pcm = NULL;
   2289         }
   2290         if (pcm_device->resampler) {
   2291             release_resampler(pcm_device->resampler);
   2292             pcm_device->resampler = NULL;
   2293         }
   2294         if (pcm_device->res_buffer) {
   2295             free(pcm_device->res_buffer);
   2296             pcm_device->res_buffer = NULL;
   2297         }
   2298     }
   2299 
   2300     return 0;
   2301 }
   2302 
   2303 static int out_open_pcm_devices(struct stream_out *out)
   2304 {
   2305     struct pcm_device *pcm_device;
   2306     struct listnode *node;
   2307     int ret = 0;
   2308 
   2309     list_for_each(node, &out->pcm_dev_list) {
   2310         pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   2311         ALOGV("%s: Opening PCM device card_id(%d) device_id(%d)",
   2312               __func__, pcm_device->pcm_profile->card, pcm_device->pcm_profile->id);
   2313 
   2314         pcm_device->pcm = pcm_open(pcm_device->pcm_profile->card, pcm_device->pcm_profile->id,
   2315                                PCM_OUT | PCM_MONOTONIC, &pcm_device->pcm_profile->config);
   2316 
   2317         if (pcm_device->pcm && !pcm_is_ready(pcm_device->pcm)) {
   2318             ALOGE("%s: %s", __func__, pcm_get_error(pcm_device->pcm));
   2319             pcm_device->pcm = NULL;
   2320             ret = -EIO;
   2321             goto error_open;
   2322         }
   2323         /*
   2324         * If the stream rate differs from the PCM rate, we need to
   2325         * create a resampler.
   2326         */
   2327         if (out->sample_rate != pcm_device->pcm_profile->config.rate) {
   2328             ALOGV("%s: create_resampler(), pcm_device_card(%d), pcm_device_id(%d), \
   2329                     out_rate(%d), device_rate(%d)",__func__,
   2330                     pcm_device->pcm_profile->card, pcm_device->pcm_profile->id,
   2331                     out->sample_rate, pcm_device->pcm_profile->config.rate);
   2332             ret = create_resampler(out->sample_rate,
   2333                     pcm_device->pcm_profile->config.rate,
   2334                     audio_channel_count_from_out_mask(out->channel_mask),
   2335                     RESAMPLER_QUALITY_DEFAULT,
   2336                     NULL,
   2337                     &pcm_device->resampler);
   2338             pcm_device->res_byte_count = 0;
   2339             pcm_device->res_buffer = NULL;
   2340         }
   2341     }
   2342     return ret;
   2343 
   2344 error_open:
   2345     out_close_pcm_devices(out);
   2346     return ret;
   2347 }
   2348 
   2349 static int disable_output_path_l(struct stream_out *out)
   2350 {
   2351     struct audio_device *adev = out->dev;
   2352     struct audio_usecase *uc_info;
   2353 
   2354     uc_info = get_usecase_from_id(adev, out->usecase);
   2355     if (uc_info == NULL) {
   2356         ALOGE("%s: Could not find the usecase (%d) in the list",
   2357              __func__, out->usecase);
   2358         return -EINVAL;
   2359     }
   2360     disable_snd_device(adev, uc_info, uc_info->out_snd_device, true);
   2361     uc_release_pcm_devices(uc_info);
   2362     list_remove(&uc_info->adev_list_node);
   2363     free(uc_info);
   2364 
   2365     return 0;
   2366 }
   2367 
   2368 static void enable_output_path_l(struct stream_out *out)
   2369 {
   2370     struct audio_device *adev = out->dev;
   2371     struct audio_usecase *uc_info;
   2372 
   2373     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
   2374     uc_info->id = out->usecase;
   2375     uc_info->type = PCM_PLAYBACK;
   2376     uc_info->stream = (struct audio_stream *)out;
   2377     uc_info->devices = out->devices;
   2378     uc_info->in_snd_device = SND_DEVICE_NONE;
   2379     uc_info->out_snd_device = SND_DEVICE_NONE;
   2380     uc_select_pcm_devices(uc_info);
   2381 
   2382     list_add_tail(&adev->usecase_list, &uc_info->adev_list_node);
   2383 
   2384     select_devices(adev, out->usecase);
   2385 }
   2386 
   2387 static int stop_output_stream(struct stream_out *out)
   2388 {
   2389     int ret = 0;
   2390     struct audio_device *adev = out->dev;
   2391     bool do_disable = true;
   2392 
   2393     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   2394           out->usecase, use_case_table[out->usecase]);
   2395 
   2396     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD &&
   2397             adev->offload_fx_stop_output != NULL) {
   2398         adev->offload_fx_stop_output(out->handle);
   2399 
   2400         if (out->offload_state == OFFLOAD_STATE_PAUSED ||
   2401                 out->offload_state == OFFLOAD_STATE_PAUSED_FLUSHED)
   2402             do_disable = false;
   2403         out->offload_state = OFFLOAD_STATE_IDLE;
   2404     }
   2405     if (do_disable)
   2406         ret = disable_output_path_l(out);
   2407 
   2408     ALOGV("%s: exit: status(%d)", __func__, ret);
   2409     return ret;
   2410 }
   2411 
   2412 int start_output_stream(struct stream_out *out)
   2413 {
   2414     int ret = 0;
   2415     struct audio_device *adev = out->dev;
   2416 
   2417     ALOGV("%s: enter: usecase(%d: %s) devices(%#x) channels(%d)",
   2418           __func__, out->usecase, use_case_table[out->usecase], out->devices, out->config.channels);
   2419 
   2420     enable_output_path_l(out);
   2421 
   2422     if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2423         out->compr = NULL;
   2424         ret = out_open_pcm_devices(out);
   2425         if (ret != 0)
   2426             goto error_open;
   2427 #ifdef PREPROCESSING_ENABLED
   2428         out->echo_reference = NULL;
   2429         out->echo_reference_generation = adev->echo_reference_generation;
   2430         if (adev->echo_reference != NULL)
   2431             out->echo_reference = adev->echo_reference;
   2432 #endif
   2433     } else {
   2434         out->compr = compress_open(COMPRESS_CARD, COMPRESS_DEVICE,
   2435                                    COMPRESS_IN, &out->compr_config);
   2436         if (out->compr && !is_compress_ready(out->compr)) {
   2437             ALOGE("%s: %s", __func__, compress_get_error(out->compr));
   2438             compress_close(out->compr);
   2439             out->compr = NULL;
   2440             ret = -EIO;
   2441             goto error_open;
   2442         }
   2443         if (out->offload_callback)
   2444             compress_nonblock(out->compr, out->non_blocking);
   2445 
   2446         if (adev->offload_fx_start_output != NULL)
   2447             adev->offload_fx_start_output(out->handle);
   2448     }
   2449     ALOGV("%s: exit", __func__);
   2450     return 0;
   2451 error_open:
   2452     stop_output_stream(out);
   2453 error_config:
   2454     return ret;
   2455 }
   2456 
   2457 static int stop_voice_call(struct audio_device *adev)
   2458 {
   2459     struct audio_usecase *uc_info;
   2460 
   2461     ALOGV("%s: enter", __func__);
   2462     adev->in_call = false;
   2463 
   2464     /* TODO: implement voice call stop */
   2465 
   2466     uc_info = get_usecase_from_id(adev, USECASE_VOICE_CALL);
   2467     if (uc_info == NULL) {
   2468         ALOGE("%s: Could not find the usecase (%d) in the list",
   2469               __func__, USECASE_VOICE_CALL);
   2470         return -EINVAL;
   2471     }
   2472 
   2473     disable_snd_device(adev, uc_info, uc_info->out_snd_device, false);
   2474     disable_snd_device(adev, uc_info, uc_info->in_snd_device, true);
   2475 
   2476     uc_release_pcm_devices(uc_info);
   2477     list_remove(&uc_info->adev_list_node);
   2478     free(uc_info);
   2479 
   2480     ALOGV("%s: exit", __func__);
   2481     return 0;
   2482 }
   2483 
   2484 /* always called with adev lock held */
   2485 static int start_voice_call(struct audio_device *adev)
   2486 {
   2487     struct audio_usecase *uc_info;
   2488 
   2489     ALOGV("%s: enter", __func__);
   2490 
   2491     uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase));
   2492     uc_info->id = USECASE_VOICE_CALL;
   2493     uc_info->type = VOICE_CALL;
   2494     uc_info->stream = (struct audio_stream *)adev->primary_output;
   2495     uc_info->devices = adev->primary_output->devices;
   2496     uc_info->in_snd_device = SND_DEVICE_NONE;
   2497     uc_info->out_snd_device = SND_DEVICE_NONE;
   2498 
   2499     uc_select_pcm_devices(uc_info);
   2500 
   2501     list_add_tail(&adev->usecase_list, &uc_info->adev_list_node);
   2502 
   2503     select_devices(adev, USECASE_VOICE_CALL);
   2504 
   2505 
   2506     /* TODO: implement voice call start */
   2507 
   2508     /* set cached volume */
   2509     set_voice_volume_l(adev, adev->voice_volume);
   2510 
   2511     adev->in_call = true;
   2512     ALOGV("%s: exit", __func__);
   2513     return 0;
   2514 }
   2515 
   2516 static int check_input_parameters(uint32_t sample_rate,
   2517                                   audio_format_t format,
   2518                                   int channel_count)
   2519 {
   2520     if (format != AUDIO_FORMAT_PCM_16_BIT) return -EINVAL;
   2521 
   2522     if ((channel_count < 1) || (channel_count > 2)) return -EINVAL;
   2523 
   2524     switch (sample_rate) {
   2525     case 8000:
   2526     case 11025:
   2527     case 12000:
   2528     case 16000:
   2529     case 22050:
   2530     case 24000:
   2531     case 32000:
   2532     case 44100:
   2533     case 48000:
   2534         break;
   2535     default:
   2536         return -EINVAL;
   2537     }
   2538 
   2539     return 0;
   2540 }
   2541 
   2542 static size_t get_input_buffer_size(uint32_t sample_rate,
   2543                                     audio_format_t format,
   2544                                     int channel_count,
   2545                                     audio_devices_t devices)
   2546 {
   2547     size_t size = 0;
   2548     struct pcm_device_profile *pcm_profile;
   2549 
   2550     if (check_input_parameters(sample_rate, format, channel_count) != 0)
   2551         return 0;
   2552 
   2553     pcm_profile = get_pcm_device(PCM_CAPTURE, devices);
   2554     if (pcm_profile == NULL)
   2555         return 0;
   2556 
   2557     /*
   2558      * take resampling into account and return the closest majoring
   2559      * multiple of 16 frames, as audioflinger expects audio buffers to
   2560      * be a multiple of 16 frames
   2561      */
   2562     size = (pcm_profile->config.period_size * sample_rate) / pcm_profile->config.rate;
   2563     size = ((size + 15) / 16) * 16;
   2564 
   2565     return (size * channel_count * audio_bytes_per_sample(format));
   2566 
   2567 }
   2568 
   2569 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
   2570 {
   2571     struct stream_out *out = (struct stream_out *)stream;
   2572 
   2573     return out->sample_rate;
   2574 }
   2575 
   2576 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
   2577 {
   2578     (void)stream;
   2579     (void)rate;
   2580     return -ENOSYS;
   2581 }
   2582 
   2583 static size_t out_get_buffer_size(const struct audio_stream *stream)
   2584 {
   2585     struct stream_out *out = (struct stream_out *)stream;
   2586 
   2587     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2588         return out->compr_config.fragment_size;
   2589     }
   2590 
   2591     return out->config.period_size *
   2592                audio_stream_out_frame_size((const struct audio_stream_out *)stream);
   2593 }
   2594 
   2595 static uint32_t out_get_channels(const struct audio_stream *stream)
   2596 {
   2597     struct stream_out *out = (struct stream_out *)stream;
   2598 
   2599     return out->channel_mask;
   2600 }
   2601 
   2602 static audio_format_t out_get_format(const struct audio_stream *stream)
   2603 {
   2604     struct stream_out *out = (struct stream_out *)stream;
   2605 
   2606     return out->format;
   2607 }
   2608 
   2609 static int out_set_format(struct audio_stream *stream, audio_format_t format)
   2610 {
   2611     (void)stream;
   2612     (void)format;
   2613     return -ENOSYS;
   2614 }
   2615 
   2616 static int do_out_standby_l(struct stream_out *out)
   2617 {
   2618     struct audio_device *adev = out->dev;
   2619     int status = 0;
   2620 
   2621     out->standby = true;
   2622     if (out->usecase != USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2623         out_close_pcm_devices(out);
   2624 #ifdef PREPROCESSING_ENABLED
   2625         /* stop writing to echo reference */
   2626         if (out->echo_reference != NULL) {
   2627             out->echo_reference->write(out->echo_reference, NULL);
   2628             if (out->echo_reference_generation != adev->echo_reference_generation) {
   2629                 ALOGV("%s: release_echo_reference %p", __func__, out->echo_reference);
   2630                 release_echo_reference(out->echo_reference);
   2631                 out->echo_reference_generation = adev->echo_reference_generation;
   2632             }
   2633             out->echo_reference = NULL;
   2634         }
   2635 #endif
   2636     } else {
   2637         stop_compressed_output_l(out);
   2638         out->gapless_mdata.encoder_delay = 0;
   2639         out->gapless_mdata.encoder_padding = 0;
   2640         if (out->compr != NULL) {
   2641             compress_close(out->compr);
   2642             out->compr = NULL;
   2643         }
   2644     }
   2645     status = stop_output_stream(out);
   2646 
   2647     return status;
   2648 }
   2649 
   2650 static int out_standby(struct audio_stream *stream)
   2651 {
   2652     struct stream_out *out = (struct stream_out *)stream;
   2653     struct audio_device *adev = out->dev;
   2654 
   2655     ALOGV("%s: enter: usecase(%d: %s)", __func__,
   2656           out->usecase, use_case_table[out->usecase]);
   2657     pthread_mutex_lock(&out->lock);
   2658     if (!out->standby) {
   2659         pthread_mutex_lock(&adev->lock);
   2660         do_out_standby_l(out);
   2661         pthread_mutex_unlock(&adev->lock);
   2662     }
   2663     pthread_mutex_unlock(&out->lock);
   2664     ALOGV("%s: exit", __func__);
   2665     return 0;
   2666 }
   2667 
   2668 static int out_dump(const struct audio_stream *stream, int fd)
   2669 {
   2670     (void)stream;
   2671     (void)fd;
   2672 
   2673     return 0;
   2674 }
   2675 
   2676 static int parse_compress_metadata(struct stream_out *out, struct str_parms *parms)
   2677 {
   2678     int ret = 0;
   2679     char value[32];
   2680     struct compr_gapless_mdata tmp_mdata;
   2681 
   2682     if (!out || !parms) {
   2683         return -EINVAL;
   2684     }
   2685 
   2686     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES, value, sizeof(value));
   2687     if (ret >= 0) {
   2688         tmp_mdata.encoder_delay = atoi(value); /* what is a good limit check? */
   2689     } else {
   2690         return -EINVAL;
   2691     }
   2692 
   2693     ret = str_parms_get_str(parms, AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES, value, sizeof(value));
   2694     if (ret >= 0) {
   2695         tmp_mdata.encoder_padding = atoi(value);
   2696     } else {
   2697         return -EINVAL;
   2698     }
   2699 
   2700     out->gapless_mdata = tmp_mdata;
   2701     out->send_new_metadata = 1;
   2702     ALOGV("%s new encoder delay %u and padding %u", __func__,
   2703           out->gapless_mdata.encoder_delay, out->gapless_mdata.encoder_padding);
   2704 
   2705     return 0;
   2706 }
   2707 
   2708 
   2709 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
   2710 {
   2711     struct stream_out *out = (struct stream_out *)stream;
   2712     struct audio_device *adev = out->dev;
   2713     struct audio_usecase *usecase;
   2714     struct listnode *node;
   2715     struct str_parms *parms;
   2716     char value[32];
   2717     int ret, val = 0;
   2718     struct audio_usecase *uc_info;
   2719     bool do_standby = false;
   2720     struct pcm_device *pcm_device;
   2721     struct pcm_device_profile *pcm_profile;
   2722 #ifdef PREPROCESSING_ENABLED
   2723     struct stream_in *in = NULL;    /* if non-NULL, then force input to standby */
   2724 #endif
   2725 
   2726     ALOGD("%s: enter: usecase(%d: %s) kvpairs: %s out->devices(%d) adev->mode(%d)",
   2727           __func__, out->usecase, use_case_table[out->usecase], kvpairs, out->devices, adev->mode);
   2728     parms = str_parms_create_str(kvpairs);
   2729     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
   2730     if (ret >= 0) {
   2731         val = atoi(value);
   2732         pthread_mutex_lock(&adev->lock_inputs);
   2733         pthread_mutex_lock(&out->lock);
   2734         pthread_mutex_lock(&adev->lock);
   2735 #ifdef PREPROCESSING_ENABLED
   2736         if (((int)out->devices != val) && (val != 0) && (!out->standby) &&
   2737             (out->usecase == USECASE_AUDIO_PLAYBACK)) {
   2738             /* reset active input:
   2739              *  - to attach the echo reference
   2740              *  - because a change in output device may change mic settings */
   2741             if (adev->active_input && (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
   2742                     adev->active_input->source == AUDIO_SOURCE_MIC)) {
   2743                 in = adev->active_input;
   2744             }
   2745         }
   2746 #endif
   2747         if (val != 0) {
   2748             out->devices = val;
   2749 
   2750             if (!out->standby) {
   2751                 uc_info = get_usecase_from_id(adev, out->usecase);
   2752                 if (uc_info == NULL) {
   2753                     ALOGE("%s: Could not find the usecase (%d) in the list",
   2754                           __func__, out->usecase);
   2755                 } else {
   2756                     list_for_each(node, &out->pcm_dev_list) {
   2757                         pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   2758                         if ((pcm_device->pcm_profile->devices & val) == 0)
   2759                             do_standby = true;
   2760                         val &= ~pcm_device->pcm_profile->devices;
   2761                     }
   2762                     if (val != 0)
   2763                         do_standby = true;
   2764                 }
   2765                 if (do_standby)
   2766                     do_out_standby_l(out);
   2767                 else
   2768                     select_devices(adev, out->usecase);
   2769             }
   2770 
   2771             if ((adev->mode == AUDIO_MODE_IN_CALL) && !adev->in_call &&
   2772                     (out == adev->primary_output)) {
   2773                 start_voice_call(adev);
   2774             } else if ((adev->mode == AUDIO_MODE_IN_CALL) && adev->in_call &&
   2775                        (out == adev->primary_output)) {
   2776                 select_devices(adev, USECASE_VOICE_CALL);
   2777             }
   2778         }
   2779 
   2780         if ((adev->mode == AUDIO_MODE_NORMAL) && adev->in_call &&
   2781                 (out == adev->primary_output)) {
   2782             stop_voice_call(adev);
   2783         }
   2784         pthread_mutex_unlock(&adev->lock);
   2785         pthread_mutex_unlock(&out->lock);
   2786 #ifdef PREPROCESSING_ENABLED
   2787         if (in) {
   2788             /* The lock on adev->lock_inputs prevents input stream from being closed */
   2789             pthread_mutex_lock(&in->lock);
   2790             pthread_mutex_lock(&adev->lock);
   2791             LOG_ALWAYS_FATAL_IF(in != adev->active_input);
   2792             do_in_standby_l(in);
   2793             pthread_mutex_unlock(&adev->lock);
   2794             pthread_mutex_unlock(&in->lock);
   2795         }
   2796 #endif
   2797         pthread_mutex_unlock(&adev->lock_inputs);
   2798     }
   2799 
   2800     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2801         parse_compress_metadata(out, parms);
   2802     }
   2803 
   2804     str_parms_destroy(parms);
   2805     ALOGV("%s: exit: code(%d)", __func__, ret);
   2806     return ret;
   2807 }
   2808 
   2809 static char* out_get_parameters(const struct audio_stream *stream, const char *keys)
   2810 {
   2811     struct stream_out *out = (struct stream_out *)stream;
   2812     struct str_parms *query = str_parms_create_str(keys);
   2813     char *str;
   2814     char value[256];
   2815     struct str_parms *reply = str_parms_create();
   2816     size_t i, j;
   2817     int ret;
   2818     bool first = true;
   2819     ALOGV("%s: enter: keys - %s", __func__, keys);
   2820     ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value, sizeof(value));
   2821     if (ret >= 0) {
   2822         value[0] = '\0';
   2823         i = 0;
   2824         while (out->supported_channel_masks[i] != 0) {
   2825             for (j = 0; j < ARRAY_SIZE(out_channels_name_to_enum_table); j++) {
   2826                 if (out_channels_name_to_enum_table[j].value == out->supported_channel_masks[i]) {
   2827                     if (!first) {
   2828                         strcat(value, "|");
   2829                     }
   2830                     strcat(value, out_channels_name_to_enum_table[j].name);
   2831                     first = false;
   2832                     break;
   2833                 }
   2834             }
   2835             i++;
   2836         }
   2837         str_parms_add_str(reply, AUDIO_PARAMETER_STREAM_SUP_CHANNELS, value);
   2838         str = str_parms_to_str(reply);
   2839     } else {
   2840         str = strdup(keys);
   2841     }
   2842     str_parms_destroy(query);
   2843     str_parms_destroy(reply);
   2844     ALOGV("%s: exit: returns - %s", __func__, str);
   2845     return str;
   2846 }
   2847 
   2848 static uint32_t out_get_latency(const struct audio_stream_out *stream)
   2849 {
   2850     struct stream_out *out = (struct stream_out *)stream;
   2851 
   2852     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD)
   2853         return COMPRESS_OFFLOAD_PLAYBACK_LATENCY;
   2854 
   2855     return (out->config.period_count * out->config.period_size * 1000) /
   2856            (out->config.rate);
   2857 }
   2858 
   2859 static int out_set_volume(struct audio_stream_out *stream, float left,
   2860                           float right)
   2861 {
   2862     struct stream_out *out = (struct stream_out *)stream;
   2863     struct audio_device *adev = out->dev;
   2864     int offload_volume[2];//For stereo
   2865 
   2866     if (out->usecase == USECASE_AUDIO_PLAYBACK_MULTI_CH) {
   2867         /* only take left channel into account: the API is for stereo anyway */
   2868         out->muted = (left == 0.0f);
   2869         return 0;
   2870     } else if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2871         struct mixer_ctl *ctl;
   2872         struct mixer *mixer = NULL;
   2873 
   2874         offload_volume[0] = (int)(left * COMPRESS_PLAYBACK_VOLUME_MAX);
   2875         offload_volume[1] = (int)(right * COMPRESS_PLAYBACK_VOLUME_MAX);
   2876 
   2877         mixer = mixer_open(MIXER_CARD);
   2878         if (!mixer) {
   2879             ALOGE("%s unable to open the mixer for card %d, aborting.",
   2880                     __func__, MIXER_CARD);
   2881             return -EINVAL;
   2882         }
   2883         ctl = mixer_get_ctl_by_name(mixer, MIXER_CTL_COMPRESS_PLAYBACK_VOLUME);
   2884         if (!ctl) {
   2885             ALOGE("%s: Could not get ctl for mixer cmd - %s",
   2886                   __func__, MIXER_CTL_COMPRESS_PLAYBACK_VOLUME);
   2887             mixer_close(mixer);
   2888             return -EINVAL;
   2889         }
   2890         ALOGD("out_set_volume set offload volume (%f, %f)", left, right);
   2891         mixer_ctl_set_array(ctl, offload_volume,
   2892                             sizeof(offload_volume)/sizeof(offload_volume[0]));
   2893         mixer_close(mixer);
   2894         return 0;
   2895     }
   2896 
   2897     return -ENOSYS;
   2898 }
   2899 
   2900 static void *tfa9895_config_thread(void *context)
   2901 {
   2902     ALOGD("%s: enter", __func__);
   2903     pthread_detach(pthread_self());
   2904     struct audio_device *adev = (struct audio_device *)context;
   2905     pthread_mutex_lock(&adev->tfa9895_lock);
   2906     adev->tfa9895_init =
   2907         adev->htc_acoustic_set_amp_mode(adev->mode, AUDIO_DEVICE_OUT_SPEAKER, 0, 0, false);
   2908     if (!adev->tfa9895_init) {
   2909         ALOGE("set_amp_mode failed, need to re-config again");
   2910         adev->tfa9895_mode_change |= 0x1;
   2911     }
   2912     ALOGI("@@##tfa9895_config_thread Done!! tfa9895_mode_change=%d", adev->tfa9895_mode_change);
   2913     pthread_mutex_unlock(&adev->tfa9895_lock);
   2914     dummybuf_thread_close(adev);
   2915     return NULL;
   2916 }
   2917 
   2918 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
   2919                          size_t bytes)
   2920 {
   2921     struct stream_out *out = (struct stream_out *)stream;
   2922     struct audio_device *adev = out->dev;
   2923     ssize_t ret = 0;
   2924     struct pcm_device *pcm_device;
   2925     struct listnode *node;
   2926     size_t frame_size = audio_stream_out_frame_size(stream);
   2927     size_t frames_wr = 0, frames_rq = 0;
   2928     unsigned char *data = NULL;
   2929     struct pcm_config config;
   2930 #ifdef PREPROCESSING_ENABLED
   2931     size_t in_frames = bytes / frame_size;
   2932     size_t out_frames = in_frames;
   2933     struct stream_in *in = NULL;
   2934 #endif
   2935 
   2936     pthread_mutex_lock(&out->lock);
   2937     if (out->standby) {
   2938 #ifdef PREPROCESSING_ENABLED
   2939         pthread_mutex_unlock(&out->lock);
   2940         /* Prevent input stream from being closed */
   2941         pthread_mutex_lock(&adev->lock_inputs);
   2942         pthread_mutex_lock(&out->lock);
   2943         if (!out->standby) {
   2944             pthread_mutex_unlock(&adev->lock_inputs);
   2945             goto false_alarm;
   2946         }
   2947 #endif
   2948         pthread_mutex_lock(&adev->lock);
   2949         ret = start_output_stream(out);
   2950         /* ToDo: If use case is compress offload should return 0 */
   2951         if (ret != 0) {
   2952             pthread_mutex_unlock(&adev->lock);
   2953 #ifdef PREPROCESSING_ENABLED
   2954             pthread_mutex_unlock(&adev->lock_inputs);
   2955 #endif
   2956             goto exit;
   2957         }
   2958         out->standby = false;
   2959 
   2960 #ifdef PREPROCESSING_ENABLED
   2961         /* A change in output device may change the microphone selection */
   2962         if (adev->active_input &&
   2963             (adev->active_input->source == AUDIO_SOURCE_VOICE_COMMUNICATION ||
   2964                 adev->active_input->source == AUDIO_SOURCE_MIC)) {
   2965                     in = adev->active_input;
   2966                     ALOGV("%s: enter:) force_input_standby true", __func__);
   2967         }
   2968 #endif
   2969         pthread_mutex_unlock(&adev->lock);
   2970 #ifdef PREPROCESSING_ENABLED
   2971         if (!in) {
   2972             /* Leave mutex locked iff in != NULL */
   2973             pthread_mutex_unlock(&adev->lock_inputs);
   2974         }
   2975 #endif
   2976     }
   2977 false_alarm:
   2978 
   2979     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   2980         ALOGVV("%s: writing buffer (%d bytes) to compress device", __func__, bytes);
   2981 
   2982         if (out->offload_state == OFFLOAD_STATE_PAUSED_FLUSHED) {
   2983             ALOGV("start offload write from pause state");
   2984             pthread_mutex_lock(&adev->lock);
   2985             enable_output_path_l(out);
   2986             pthread_mutex_unlock(&adev->lock);
   2987         }
   2988 
   2989         if (out->send_new_metadata) {
   2990             ALOGVV("send new gapless metadata");
   2991             compress_set_gapless_metadata(out->compr, &out->gapless_mdata);
   2992             out->send_new_metadata = 0;
   2993         }
   2994 
   2995         ret = compress_write(out->compr, buffer, bytes);
   2996         ALOGVV("%s: writing buffer (%d bytes) to compress device returned %d", __func__, bytes, ret);
   2997         if (ret >= 0 && ret < (ssize_t)bytes) {
   2998             send_offload_cmd_l(out, OFFLOAD_CMD_WAIT_FOR_BUFFER);
   2999         }
   3000         if (out->offload_state != OFFLOAD_STATE_PLAYING) {
   3001             compress_start(out->compr);
   3002             out->offload_state = OFFLOAD_STATE_PLAYING;
   3003         }
   3004         pthread_mutex_unlock(&out->lock);
   3005 #ifdef PREPROCESSING_ENABLED
   3006         if (in) {
   3007             /* This mutex was left locked iff in != NULL */
   3008             pthread_mutex_unlock(&adev->lock_inputs);
   3009         }
   3010 #endif
   3011         return ret;
   3012     } else {
   3013 #ifdef PREPROCESSING_ENABLED
   3014         if (android_atomic_acquire_load(&adev->echo_reference_generation)
   3015                 != out->echo_reference_generation) {
   3016             pthread_mutex_lock(&adev->lock);
   3017             if (out->echo_reference != NULL) {
   3018                 ALOGV("%s: release_echo_reference %p", __func__, out->echo_reference);
   3019                 release_echo_reference(out->echo_reference);
   3020             }
   3021             // note that adev->echo_reference_generation here can be different from the one
   3022             // tested above but it doesn't matter as we now have the adev mutex and it is consistent
   3023             // with what has been set by get_echo_reference() or put_echo_reference()
   3024             out->echo_reference_generation = adev->echo_reference_generation;
   3025             out->echo_reference = adev->echo_reference;
   3026             ALOGV("%s: update echo reference generation %d", __func__,
   3027                   out->echo_reference_generation);
   3028             pthread_mutex_unlock(&adev->lock);
   3029         }
   3030 #endif
   3031 
   3032         if (out->muted)
   3033             memset((void *)buffer, 0, bytes);
   3034         list_for_each(node, &out->pcm_dev_list) {
   3035             pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   3036             if (pcm_device->resampler) {
   3037                 if (bytes * pcm_device->pcm_profile->config.rate / out->sample_rate + frame_size
   3038                         > pcm_device->res_byte_count) {
   3039                     pcm_device->res_byte_count =
   3040                         bytes * pcm_device->pcm_profile->config.rate / out->sample_rate + frame_size;
   3041                     pcm_device->res_buffer =
   3042                         realloc(pcm_device->res_buffer, pcm_device->res_byte_count);
   3043                     ALOGV("%s: resampler res_byte_count = %zu", __func__,
   3044                         pcm_device->res_byte_count);
   3045                 }
   3046                 frames_rq = bytes / frame_size;
   3047                 frames_wr = pcm_device->res_byte_count / frame_size;
   3048                 ALOGVV("%s: resampler request frames = %d frame_size = %d",
   3049                     __func__, frames_rq, frame_size);
   3050                 pcm_device->resampler->resample_from_input(pcm_device->resampler,
   3051                     (int16_t *)buffer, &frames_rq, (int16_t *)pcm_device->res_buffer, &frames_wr);
   3052                 ALOGVV("%s: resampler output frames_= %d", __func__, frames_wr);
   3053             }
   3054             if (pcm_device->pcm) {
   3055 #ifdef PREPROCESSING_ENABLED
   3056                 if (out->echo_reference != NULL && pcm_device->pcm_profile->devices != SND_DEVICE_OUT_SPEAKER) {
   3057                     struct echo_reference_buffer b;
   3058                     b.raw = (void *)buffer;
   3059                     b.frame_count = in_frames;
   3060 
   3061                     get_playback_delay(out, out_frames, &b);
   3062                     out->echo_reference->write(out->echo_reference, &b);
   3063                  }
   3064 #endif
   3065                 if (adev->tfa9895_mode_change == 0x1) {
   3066                     if (out->devices & AUDIO_DEVICE_OUT_SPEAKER) {
   3067                         pthread_mutex_lock(&adev->tfa9895_lock);
   3068                         data = (unsigned char *)
   3069                                 calloc(pcm_frames_to_bytes(pcm_device->pcm, out->config.period_size),
   3070                                         sizeof(unsigned char));
   3071                         if (data) {
   3072                             int i;
   3073 
   3074                             // reopen pcm with stop_threshold = INT_MAX/2
   3075                             memcpy(&config, &pcm_device->pcm_profile->config,
   3076                                     sizeof(struct pcm_config));
   3077                             config.stop_threshold = INT_MAX/2;
   3078 
   3079                             if (pcm_device->pcm)
   3080                                 pcm_close(pcm_device->pcm);
   3081 
   3082                             for (i = 0; i < RETRY_NUMBER; i++) {
   3083                                 pcm_device->pcm = pcm_open(pcm_device->pcm_profile->card,
   3084                                         pcm_device->pcm_profile->id,
   3085                                         PCM_OUT | PCM_MONOTONIC, &config);
   3086                                 if (pcm_device->pcm != NULL && pcm_is_ready(pcm_device->pcm))
   3087                                     break;
   3088                                 else
   3089                                     usleep(10000);
   3090                             }
   3091                             if (i >= RETRY_NUMBER)
   3092                                 ALOGE("%s: failed to reopen pcm device", __func__);
   3093 
   3094                             if (pcm_device->pcm) {
   3095                                 for (i = out->config.period_count; i > 0; i--)
   3096                                     pcm_write(pcm_device->pcm, (void *)data,
   3097                                            pcm_frames_to_bytes(pcm_device->pcm,
   3098                                            out->config.period_size));
   3099                                 /* TODO: Hold on 100 ms and wait i2s signal ready
   3100                                      before giving dsp related i2c commands */
   3101                                 usleep(100000);
   3102                                 adev->tfa9895_mode_change &= ~0x1;
   3103                                 ALOGD("@@##checking - 2: tfa9895_config_thread: "
   3104                                     "adev->tfa9895_mode_change=%d", adev->tfa9895_mode_change);
   3105                                 adev->tfa9895_init =
   3106                                         adev->htc_acoustic_set_amp_mode(
   3107                                                 adev->mode, AUDIO_DEVICE_OUT_SPEAKER, 0, 0, false);
   3108                             }
   3109                             free(data);
   3110 
   3111                             // reopen pcm with normal stop_threshold
   3112                             if (pcm_device->pcm)
   3113                                 pcm_close(pcm_device->pcm);
   3114 
   3115                             for (i = 0; i < RETRY_NUMBER; i++) {
   3116                                 pcm_device->pcm = pcm_open(pcm_device->pcm_profile->card,
   3117                                         pcm_device->pcm_profile->id,
   3118                                         PCM_OUT | PCM_MONOTONIC, &pcm_device->pcm_profile->config);
   3119                                 if (pcm_device->pcm != NULL && pcm_is_ready(pcm_device->pcm))
   3120                                     break;
   3121                                 else
   3122                                     usleep(10000);
   3123                             }
   3124                             if (i >= RETRY_NUMBER) {
   3125                                 ALOGE("%s: failed to reopen pcm device, error return", __func__);
   3126                                 pthread_mutex_unlock(&adev->tfa9895_lock);
   3127                                 pthread_mutex_unlock(&out->lock);
   3128                                 return -1;
   3129                             }
   3130                         }
   3131                     }
   3132                     pthread_mutex_unlock(&adev->tfa9895_lock);
   3133                 }
   3134                 ALOGVV("%s: writing buffer (%d bytes) to pcm device", __func__, bytes);
   3135                 if (pcm_device->resampler && pcm_device->res_buffer)
   3136                     pcm_device->status =
   3137                         pcm_write(pcm_device->pcm, (void *)pcm_device->res_buffer,
   3138                             frames_wr * frame_size);
   3139                 else
   3140                     pcm_device->status = pcm_write(pcm_device->pcm, (void *)buffer, bytes);
   3141                 if (pcm_device->status != 0)
   3142                     ret = pcm_device->status;
   3143             }
   3144         }
   3145         if (ret == 0)
   3146             out->written += bytes / (out->config.channels * sizeof(short));
   3147     }
   3148 
   3149 exit:
   3150     pthread_mutex_unlock(&out->lock);
   3151 
   3152     if (ret != 0) {
   3153         list_for_each(node, &out->pcm_dev_list) {
   3154             pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   3155             if (pcm_device->pcm && pcm_device->status != 0)
   3156                 ALOGE("%s: error %zd - %s", __func__, ret, pcm_get_error(pcm_device->pcm));
   3157         }
   3158         out_standby(&out->stream.common);
   3159         usleep(bytes * 1000000 / audio_stream_out_frame_size(stream) /
   3160                out_get_sample_rate(&out->stream.common));
   3161     }
   3162 
   3163 #ifdef PREPROCESSING_ENABLED
   3164     if (in) {
   3165         /* The lock on adev->lock_inputs prevents input stream from being closed */
   3166         pthread_mutex_lock(&in->lock);
   3167         pthread_mutex_lock(&adev->lock);
   3168         LOG_ALWAYS_FATAL_IF(in != adev->active_input);
   3169         do_in_standby_l(in);
   3170         pthread_mutex_unlock(&adev->lock);
   3171         pthread_mutex_unlock(&in->lock);
   3172         /* This mutex was left locked iff in != NULL */
   3173         pthread_mutex_unlock(&adev->lock_inputs);
   3174     }
   3175 #endif
   3176 
   3177     return bytes;
   3178 }
   3179 
   3180 static int out_get_render_position(const struct audio_stream_out *stream,
   3181                                    uint32_t *dsp_frames)
   3182 {
   3183     struct stream_out *out = (struct stream_out *)stream;
   3184     *dsp_frames = 0;
   3185     if ((out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) && (dsp_frames != NULL)) {
   3186         pthread_mutex_lock(&out->lock);
   3187         if (out->compr != NULL) {
   3188             compress_get_tstamp(out->compr, (unsigned long *)dsp_frames,
   3189                     &out->sample_rate);
   3190             ALOGVV("%s rendered frames %d sample_rate %d",
   3191                    __func__, *dsp_frames, out->sample_rate);
   3192         }
   3193         pthread_mutex_unlock(&out->lock);
   3194         return 0;
   3195     } else
   3196         return -EINVAL;
   3197 }
   3198 
   3199 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
   3200 {
   3201     (void)stream;
   3202     (void)effect;
   3203     return 0;
   3204 }
   3205 
   3206 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
   3207 {
   3208     (void)stream;
   3209     (void)effect;
   3210     return 0;
   3211 }
   3212 
   3213 static int out_get_next_write_timestamp(const struct audio_stream_out *stream,
   3214                                         int64_t *timestamp)
   3215 {
   3216     (void)stream;
   3217     (void)timestamp;
   3218     return -EINVAL;
   3219 }
   3220 
   3221 static int out_get_presentation_position(const struct audio_stream_out *stream,
   3222                                    uint64_t *frames, struct timespec *timestamp)
   3223 {
   3224     struct stream_out *out = (struct stream_out *)stream;
   3225     int ret = -1;
   3226     unsigned long dsp_frames;
   3227 
   3228     pthread_mutex_lock(&out->lock);
   3229 
   3230     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3231         if (out->compr != NULL) {
   3232             compress_get_tstamp(out->compr, &dsp_frames,
   3233                     &out->sample_rate);
   3234             ALOGVV("%s rendered frames %ld sample_rate %d",
   3235                    __func__, dsp_frames, out->sample_rate);
   3236             *frames = dsp_frames;
   3237             ret = 0;
   3238             /* this is the best we can do */
   3239             clock_gettime(CLOCK_MONOTONIC, timestamp);
   3240         }
   3241     } else {
   3242         /* FIXME: which device to read from? */
   3243         if (!list_empty(&out->pcm_dev_list)) {
   3244             unsigned int avail;
   3245             struct pcm_device *pcm_device = node_to_item(list_head(&out->pcm_dev_list),
   3246                                                    struct pcm_device, stream_list_node);
   3247 
   3248             if (pcm_get_htimestamp(pcm_device->pcm, &avail, timestamp) == 0) {
   3249                 size_t kernel_buffer_size = out->config.period_size * out->config.period_count;
   3250                 int64_t signed_frames = out->written - kernel_buffer_size + avail;
   3251                 /* This adjustment accounts for buffering after app processor.
   3252                    It is based on estimated DSP latency per use case, rather than exact. */
   3253                 signed_frames -=
   3254                     (render_latency(out->usecase) * out->sample_rate / 1000000LL);
   3255 
   3256                 /* It would be unusual for this value to be negative, but check just in case ... */
   3257                 if (signed_frames >= 0) {
   3258                     *frames = signed_frames;
   3259                     ret = 0;
   3260                 }
   3261             }
   3262         }
   3263     }
   3264 
   3265     pthread_mutex_unlock(&out->lock);
   3266 
   3267     return ret;
   3268 }
   3269 
   3270 static int out_set_callback(struct audio_stream_out *stream,
   3271             stream_callback_t callback, void *cookie)
   3272 {
   3273     struct stream_out *out = (struct stream_out *)stream;
   3274 
   3275     ALOGV("%s", __func__);
   3276     pthread_mutex_lock(&out->lock);
   3277     out->offload_callback = callback;
   3278     out->offload_cookie = cookie;
   3279     pthread_mutex_unlock(&out->lock);
   3280     return 0;
   3281 }
   3282 
   3283 static int out_pause(struct audio_stream_out* stream)
   3284 {
   3285     struct stream_out *out = (struct stream_out *)stream;
   3286     int status = -ENOSYS;
   3287     ALOGV("%s", __func__);
   3288     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3289         pthread_mutex_lock(&out->lock);
   3290         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PLAYING) {
   3291             status = compress_pause(out->compr);
   3292             out->offload_state = OFFLOAD_STATE_PAUSED;
   3293             pthread_mutex_lock(&out->dev->lock);
   3294             status = disable_output_path_l(out);
   3295             pthread_mutex_unlock(&out->dev->lock);
   3296         }
   3297         pthread_mutex_unlock(&out->lock);
   3298     }
   3299     return status;
   3300 }
   3301 
   3302 static int out_resume(struct audio_stream_out* stream)
   3303 {
   3304     struct stream_out *out = (struct stream_out *)stream;
   3305     int status = -ENOSYS;
   3306     ALOGV("%s", __func__);
   3307     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3308         status = 0;
   3309         pthread_mutex_lock(&out->lock);
   3310         if (out->compr != NULL && out->offload_state == OFFLOAD_STATE_PAUSED) {
   3311             pthread_mutex_lock(&out->dev->lock);
   3312             enable_output_path_l(out);
   3313             pthread_mutex_unlock(&out->dev->lock);
   3314             status = compress_resume(out->compr);
   3315             out->offload_state = OFFLOAD_STATE_PLAYING;
   3316         }
   3317         pthread_mutex_unlock(&out->lock);
   3318     }
   3319     return status;
   3320 }
   3321 
   3322 static int out_drain(struct audio_stream_out* stream, audio_drain_type_t type )
   3323 {
   3324     struct stream_out *out = (struct stream_out *)stream;
   3325     int status = -ENOSYS;
   3326     ALOGV("%s", __func__);
   3327     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3328         pthread_mutex_lock(&out->lock);
   3329         if (type == AUDIO_DRAIN_EARLY_NOTIFY)
   3330             status = send_offload_cmd_l(out, OFFLOAD_CMD_PARTIAL_DRAIN);
   3331         else
   3332             status = send_offload_cmd_l(out, OFFLOAD_CMD_DRAIN);
   3333         pthread_mutex_unlock(&out->lock);
   3334     }
   3335     return status;
   3336 }
   3337 
   3338 static int out_flush(struct audio_stream_out* stream)
   3339 {
   3340     struct stream_out *out = (struct stream_out *)stream;
   3341     ALOGV("%s", __func__);
   3342     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3343         pthread_mutex_lock(&out->lock);
   3344         if (out->offload_state == OFFLOAD_STATE_PLAYING) {
   3345             ALOGE("out_flush() called in wrong state %d", out->offload_state);
   3346             pthread_mutex_unlock(&out->lock);
   3347             return -ENOSYS;
   3348         }
   3349         if (out->offload_state == OFFLOAD_STATE_PAUSED) {
   3350             stop_compressed_output_l(out);
   3351             out->offload_state = OFFLOAD_STATE_PAUSED_FLUSHED;
   3352         }
   3353         pthread_mutex_unlock(&out->lock);
   3354         return 0;
   3355     }
   3356     return -ENOSYS;
   3357 }
   3358 
   3359 /** audio_stream_in implementation **/
   3360 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
   3361 {
   3362     struct stream_in *in = (struct stream_in *)stream;
   3363 
   3364     return in->requested_rate;
   3365 }
   3366 
   3367 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
   3368 {
   3369     (void)stream;
   3370     (void)rate;
   3371     return -ENOSYS;
   3372 }
   3373 
   3374 static uint32_t in_get_channels(const struct audio_stream *stream)
   3375 {
   3376     struct stream_in *in = (struct stream_in *)stream;
   3377 
   3378     return in->main_channels;
   3379 }
   3380 
   3381 static audio_format_t in_get_format(const struct audio_stream *stream)
   3382 {
   3383     (void)stream;
   3384     return AUDIO_FORMAT_PCM_16_BIT;
   3385 }
   3386 
   3387 static int in_set_format(struct audio_stream *stream, audio_format_t format)
   3388 {
   3389     (void)stream;
   3390     (void)format;
   3391 
   3392     return -ENOSYS;
   3393 }
   3394 
   3395 static size_t in_get_buffer_size(const struct audio_stream *stream)
   3396 {
   3397     struct stream_in *in = (struct stream_in *)stream;
   3398 
   3399     return get_input_buffer_size(in->requested_rate,
   3400                                  in_get_format(stream),
   3401                                  audio_channel_count_from_in_mask(in->main_channels),
   3402                                  in->devices);
   3403 }
   3404 
   3405 static int in_close_pcm_devices(struct stream_in *in)
   3406 {
   3407     struct pcm_device *pcm_device;
   3408     struct listnode *node;
   3409     struct audio_device *adev = in->dev;
   3410 
   3411     list_for_each(node, &in->pcm_dev_list) {
   3412         pcm_device = node_to_item(node, struct pcm_device, stream_list_node);
   3413         if (pcm_device) {
   3414             if (pcm_device->pcm)
   3415                 pcm_close(pcm_device->pcm);
   3416             pcm_device->pcm = NULL;
   3417             if (pcm_device->sound_trigger_handle > 0)
   3418                 adev->sound_trigger_close_for_streaming(pcm_device->sound_trigger_handle);
   3419             pcm_device->sound_trigger_handle = 0;
   3420         }
   3421     }
   3422     return 0;
   3423 }
   3424 
   3425 
   3426 /* must be called with stream and hw device mutex locked */
   3427 static int do_in_standby_l(struct stream_in *in)
   3428 {
   3429     int status = 0;
   3430 
   3431 #ifdef PREPROCESSING_ENABLED
   3432     struct audio_device *adev = in->dev;
   3433 #endif
   3434     if (!in->standby) {
   3435 
   3436         in_close_pcm_devices(in);
   3437 
   3438 #ifdef PREPROCESSING_ENABLED
   3439         if (in->echo_reference != NULL) {
   3440             /* stop reading from echo reference */
   3441             in->echo_reference->read(in->echo_reference, NULL);
   3442             put_echo_reference(adev, in->echo_reference);
   3443             in->echo_reference = NULL;
   3444         }
   3445 #ifdef HW_AEC_LOOPBACK
   3446         if (in->hw_echo_reference)
   3447         {
   3448             if (in->hw_ref_buf) {
   3449                 free(in->hw_ref_buf);
   3450                 in->hw_ref_buf = NULL;
   3451             }
   3452         }
   3453 #endif  // HW_AEC_LOOPBACK
   3454 #endif  // PREPROCESSING_ENABLED
   3455 
   3456         status = stop_input_stream(in);
   3457 
   3458         if (in->read_buf) {
   3459             free(in->read_buf);
   3460             in->read_buf = NULL;
   3461         }
   3462 
   3463         in->standby = 1;
   3464     }
   3465     return 0;
   3466 }
   3467 
   3468 // called with adev->lock_inputs locked
   3469 static int in_standby_l(struct stream_in *in)
   3470 {
   3471     struct audio_device *adev = in->dev;
   3472     int status = 0;
   3473     pthread_mutex_lock(&in->lock);
   3474     if (!in->standby) {
   3475         pthread_mutex_lock(&adev->lock);
   3476         status = do_in_standby_l(in);
   3477         pthread_mutex_unlock(&adev->lock);
   3478     }
   3479     pthread_mutex_unlock(&in->lock);
   3480     return status;
   3481 }
   3482 
   3483 static int in_standby(struct audio_stream *stream)
   3484 {
   3485     struct stream_in *in = (struct stream_in *)stream;
   3486     struct audio_device *adev = in->dev;
   3487     int status;
   3488     ALOGV("%s: enter", __func__);
   3489     pthread_mutex_lock(&adev->lock_inputs);
   3490     status = in_standby_l(in);
   3491     pthread_mutex_unlock(&adev->lock_inputs);
   3492     ALOGV("%s: exit:  status(%d)", __func__, status);
   3493     return status;
   3494 }
   3495 
   3496 static int in_dump(const struct audio_stream *stream, int fd)
   3497 {
   3498     (void)stream;
   3499     (void)fd;
   3500 
   3501     return 0;
   3502 }
   3503 
   3504 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
   3505 {
   3506     struct stream_in *in = (struct stream_in *)stream;
   3507     struct audio_device *adev = in->dev;
   3508     struct str_parms *parms;
   3509     char *str;
   3510     char value[32];
   3511     int ret, val = 0;
   3512     struct audio_usecase *uc_info;
   3513     bool do_standby = false;
   3514     struct listnode *node;
   3515     struct pcm_device *pcm_device;
   3516     struct pcm_device_profile *pcm_profile;
   3517 
   3518     ALOGV("%s: enter: kvpairs=%s", __func__, kvpairs);
   3519     parms = str_parms_create_str(kvpairs);
   3520 
   3521     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_INPUT_SOURCE, value, sizeof(value));
   3522 
   3523     pthread_mutex_lock(&adev->lock_inputs);
   3524     pthread_mutex_lock(&in->lock);
   3525     pthread_mutex_lock(&adev->lock);
   3526     if (ret >= 0) {
   3527         val = atoi(value);
   3528         /* no audio source uses val == 0 */
   3529         if (((int)in->source != val) && (val != 0)) {
   3530             in->source = val;
   3531         }
   3532     }
   3533 
   3534     ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
   3535     if (ret >= 0) {
   3536         val = atoi(value);
   3537         if (((int)in->devices != val) && (val != 0)) {
   3538             in->devices = val;
   3539             /* If recording is in progress, change the tx device to new device */
   3540             if (!in->standby) {
   3541                 uc_info = get_usecase_from_id(adev, in->usecase);
   3542                 if (uc_info == NULL) {
   3543                     ALOGE("%s: Could not find the usecase (%d) in the list",
   3544                           __func__, in->usecase);
   3545                 } else {
   3546                     if (list_empty(&in->pcm_dev_list))
   3547                         ALOGE("%s: pcm device list empty", __func__);
   3548                     else {
   3549                         pcm_device = node_to_item(list_head(&in->pcm_dev_list),
   3550                                                   struct pcm_device, stream_list_node);
   3551                         if ((pcm_device->pcm_profile->devices & val & ~AUDIO_DEVICE_BIT_IN) == 0) {
   3552                             do_standby = true;
   3553                         }
   3554                     }
   3555                 }
   3556                 if (do_standby) {
   3557                     ret = do_in_standby_l(in);
   3558                 } else
   3559                     ret = select_devices(adev, in->usecase);
   3560             }
   3561         }
   3562     }
   3563     pthread_mutex_unlock(&adev->lock);
   3564     pthread_mutex_unlock(&in->lock);
   3565     pthread_mutex_unlock(&adev->lock_inputs);
   3566     str_parms_destroy(parms);
   3567     ALOGV("%s: exit: status(%d)", __func__, ret);
   3568     return ret;
   3569 }
   3570 
   3571 static char* in_get_parameters(const struct audio_stream *stream,
   3572                                const char *keys)
   3573 {
   3574     (void)stream;
   3575     (void)keys;
   3576 
   3577     return strdup("");
   3578 }
   3579 
   3580 static int in_set_gain(struct audio_stream_in *stream, float gain)
   3581 {
   3582     (void)stream;
   3583     (void)gain;
   3584 
   3585     return 0;
   3586 }
   3587 
   3588 static ssize_t read_bytes_from_dsp(struct stream_in *in, void* buffer,
   3589                                    size_t bytes)
   3590 {
   3591     struct pcm_device *pcm_device;
   3592     struct audio_device *adev = in->dev;
   3593 
   3594     pcm_device = node_to_item(list_head(&in->pcm_dev_list),
   3595                               struct pcm_device, stream_list_node);
   3596 
   3597     if (pcm_device->sound_trigger_handle > 0)
   3598         return adev->sound_trigger_read_samples(pcm_device->sound_trigger_handle, buffer, bytes);
   3599     else
   3600         return 0;
   3601 }
   3602 
   3603 static ssize_t in_read(struct audio_stream_in *stream, void *buffer,
   3604                        size_t bytes)
   3605 {
   3606     struct stream_in *in = (struct stream_in *)stream;
   3607     struct audio_device *adev = in->dev;
   3608     ssize_t frames = -1;
   3609     int ret = -1;
   3610     int read_and_process_successful = false;
   3611 
   3612     size_t frames_rq = bytes / audio_stream_in_frame_size(stream);
   3613 
   3614     /* no need to acquire adev->lock_inputs because API contract prevents a close */
   3615     pthread_mutex_lock(&in->lock);
   3616     if (in->standby) {
   3617         pthread_mutex_unlock(&in->lock);
   3618         pthread_mutex_lock(&adev->lock_inputs);
   3619         pthread_mutex_lock(&in->lock);
   3620         if (!in->standby) {
   3621             pthread_mutex_unlock(&adev->lock_inputs);
   3622             goto false_alarm;
   3623         }
   3624         pthread_mutex_lock(&adev->lock);
   3625         ret = start_input_stream(in);
   3626         pthread_mutex_unlock(&adev->lock);
   3627         pthread_mutex_unlock(&adev->lock_inputs);
   3628         if (ret != 0) {
   3629             goto exit;
   3630         }
   3631         in->standby = 0;
   3632     }
   3633 false_alarm:
   3634 
   3635     if (!list_empty(&in->pcm_dev_list)) {
   3636         if (in->usecase == USECASE_AUDIO_CAPTURE_HOTWORD) {
   3637             bytes = read_bytes_from_dsp(in, buffer, bytes);
   3638             if (bytes > 0)
   3639                 read_and_process_successful = true;
   3640         } else {
   3641             /*
   3642              * Read PCM and:
   3643              * - resample if needed
   3644              * - process if pre-processors are attached
   3645              * - discard unwanted channels
   3646              */
   3647             frames = read_and_process_frames(in, buffer, frames_rq);
   3648             if (frames >= 0)
   3649                 read_and_process_successful = true;
   3650         }
   3651     }
   3652 
   3653     /*
   3654      * Instead of writing zeroes here, we could trust the hardware
   3655      * to always provide zeroes when muted.
   3656      */
   3657     if (read_and_process_successful == true && adev->mic_mute)
   3658         memset(buffer, 0, bytes);
   3659 
   3660 exit:
   3661     pthread_mutex_unlock(&in->lock);
   3662 
   3663     if (read_and_process_successful == false) {
   3664         in_standby(&in->stream.common);
   3665         ALOGV("%s: read failed - sleeping for buffer duration", __func__);
   3666         usleep(bytes * 1000000 / audio_stream_in_frame_size(stream) /
   3667                in->requested_rate);
   3668     }
   3669     return bytes;
   3670 }
   3671 
   3672 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
   3673 {
   3674     (void)stream;
   3675 
   3676     return 0;
   3677 }
   3678 
   3679 static int add_remove_audio_effect(const struct audio_stream *stream,
   3680                                    effect_handle_t effect,
   3681                                    bool enable)
   3682 {
   3683     struct stream_in *in = (struct stream_in *)stream;
   3684     struct audio_device *adev = in->dev;
   3685     int status = 0;
   3686     effect_descriptor_t desc;
   3687 #ifdef PREPROCESSING_ENABLED
   3688     int i;
   3689 #endif
   3690     status = (*effect)->get_descriptor(effect, &desc);
   3691     if (status != 0)
   3692         return status;
   3693 
   3694     ALOGI("add_remove_audio_effect(), effect type: %08x, enable: %d ", desc.type.timeLow, enable);
   3695 
   3696     pthread_mutex_lock(&adev->lock_inputs);
   3697     pthread_mutex_lock(&in->lock);
   3698     pthread_mutex_lock(&in->dev->lock);
   3699 #ifndef PREPROCESSING_ENABLED
   3700     if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
   3701             in->enable_aec != enable &&
   3702             (memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
   3703         in->enable_aec = enable;
   3704         if (!in->standby)
   3705             select_devices(in->dev, in->usecase);
   3706     }
   3707 #else
   3708     if ( (in->num_preprocessors > MAX_PREPROCESSORS) && (enable == true) ) {
   3709         status = -ENOSYS;
   3710         goto exit;
   3711     }
   3712     if ( enable == true ) {
   3713         in->preprocessors[in->num_preprocessors].effect_itfe = effect;
   3714         /* add the supported channel of the effect in the channel_configs */
   3715         in_read_audio_effect_channel_configs(in, &in->preprocessors[in->num_preprocessors]);
   3716         in->num_preprocessors ++;
   3717         /* check compatibility between main channel supported and possible auxiliary channels */
   3718         in_update_aux_channels(in, effect);//wesley crash
   3719         in->aux_channels_changed = true;
   3720     } else {
   3721         /* if ( enable == false ) */
   3722         if (in->num_preprocessors <= 0) {
   3723             status = -ENOSYS;
   3724             goto exit;
   3725         }
   3726         status = -EINVAL;
   3727         for (i=0; i < in->num_preprocessors; i++) {
   3728             if (status == 0) { /* status == 0 means an effect was removed from a previous slot */
   3729                 in->preprocessors[i - 1].effect_itfe = in->preprocessors[i].effect_itfe;
   3730                 in->preprocessors[i - 1].channel_configs = in->preprocessors[i].channel_configs;
   3731                 in->preprocessors[i - 1].num_channel_configs =
   3732                     in->preprocessors[i].num_channel_configs;
   3733                 ALOGV("add_remove_audio_effect moving fx from %d to %d", i, i-1);
   3734                 continue;
   3735             }
   3736             if ( in->preprocessors[i].effect_itfe == effect ) {
   3737                 ALOGV("add_remove_audio_effect found fx at index %d", i);
   3738                 free(in->preprocessors[i].channel_configs);
   3739                 status = 0;
   3740             }
   3741         }
   3742         if (status != 0)
   3743             goto exit;
   3744         in->num_preprocessors--;
   3745         /*  if we remove one effect, at least the last proproc should be reset */
   3746         in->preprocessors[in->num_preprocessors].num_channel_configs = 0;
   3747         in->preprocessors[in->num_preprocessors].effect_itfe = NULL;
   3748         in->preprocessors[in->num_preprocessors].channel_configs = NULL;
   3749         in->aux_channels_changed = false;
   3750         ALOGV("%s: enable(%d), in->aux_channels_changed(%d)", __func__, enable, in->aux_channels_changed);
   3751     }
   3752     ALOGI("%s:  num_preprocessors = %d", __func__, in->num_preprocessors);
   3753 
   3754     if ( memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) {
   3755         in->enable_aec = enable;
   3756         ALOGV("add_remove_audio_effect(), FX_IID_AEC, enable: %d", enable);
   3757         if (!in->standby) {
   3758             select_devices(in->dev, in->usecase);
   3759             do_in_standby_l(in);
   3760         }
   3761         if (in->enable_aec == true) {
   3762             in_configure_reverse(in);
   3763         }
   3764     }
   3765 exit:
   3766 #endif
   3767     ALOGW_IF(status != 0, "add_remove_audio_effect() error %d", status);
   3768     pthread_mutex_unlock(&in->dev->lock);
   3769     pthread_mutex_unlock(&in->lock);
   3770     pthread_mutex_unlock(&adev->lock_inputs);
   3771     return status;
   3772 }
   3773 
   3774 static int in_add_audio_effect(const struct audio_stream *stream,
   3775                                effect_handle_t effect)
   3776 {
   3777     ALOGV("%s: effect %p", __func__, effect);
   3778     return add_remove_audio_effect(stream, effect, true);
   3779 }
   3780 
   3781 static int in_remove_audio_effect(const struct audio_stream *stream,
   3782                                   effect_handle_t effect)
   3783 {
   3784     ALOGV("%s: effect %p", __func__, effect);
   3785     return add_remove_audio_effect(stream, effect, false);
   3786 }
   3787 
   3788 static int adev_open_output_stream(struct audio_hw_device *dev,
   3789                                    audio_io_handle_t handle,
   3790                                    audio_devices_t devices,
   3791                                    audio_output_flags_t flags,
   3792                                    struct audio_config *config,
   3793                                    struct audio_stream_out **stream_out,
   3794                                    const char *address __unused)
   3795 {
   3796     struct audio_device *adev = (struct audio_device *)dev;
   3797     struct stream_out *out;
   3798     int i, ret;
   3799     struct pcm_device_profile *pcm_profile;
   3800 
   3801     ALOGV("%s: enter: sample_rate(%d) channel_mask(%#x) devices(%#x) flags(%#x)",
   3802           __func__, config->sample_rate, config->channel_mask, devices, flags);
   3803     *stream_out = NULL;
   3804     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
   3805 
   3806     if (devices == AUDIO_DEVICE_NONE)
   3807         devices = AUDIO_DEVICE_OUT_SPEAKER;
   3808 
   3809     out->flags = flags;
   3810     out->devices = devices;
   3811     out->dev = adev;
   3812     out->format = config->format;
   3813     out->sample_rate = config->sample_rate;
   3814     out->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
   3815     out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_STEREO;
   3816     out->handle = handle;
   3817 
   3818     pcm_profile = get_pcm_device(PCM_PLAYBACK, devices);
   3819     if (pcm_profile == NULL) {
   3820         ret = -EINVAL;
   3821         goto error_open;
   3822     }
   3823     out->config = pcm_profile->config;
   3824 
   3825     /* Init use case and pcm_config */
   3826     if (out->flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
   3827         if (config->offload_info.version != AUDIO_INFO_INITIALIZER.version ||
   3828             config->offload_info.size != AUDIO_INFO_INITIALIZER.size) {
   3829             ALOGE("%s: Unsupported Offload information", __func__);
   3830             ret = -EINVAL;
   3831             goto error_open;
   3832         }
   3833         if (!is_supported_format(config->offload_info.format)) {
   3834             ALOGE("%s: Unsupported audio format", __func__);
   3835             ret = -EINVAL;
   3836             goto error_open;
   3837         }
   3838 
   3839         out->compr_config.codec = (struct snd_codec *)
   3840                                     calloc(1, sizeof(struct snd_codec));
   3841 
   3842         out->usecase = USECASE_AUDIO_PLAYBACK_OFFLOAD;
   3843         if (config->offload_info.channel_mask)
   3844             out->channel_mask = config->offload_info.channel_mask;
   3845         else if (config->channel_mask)
   3846             out->channel_mask = config->channel_mask;
   3847         out->format = config->offload_info.format;
   3848         out->sample_rate = config->offload_info.sample_rate;
   3849 
   3850         out->stream.set_callback = out_set_callback;
   3851         out->stream.pause = out_pause;
   3852         out->stream.resume = out_resume;
   3853         out->stream.drain = out_drain;
   3854         out->stream.flush = out_flush;
   3855 
   3856         out->compr_config.codec->id =
   3857                 get_snd_codec_id(config->offload_info.format);
   3858         out->compr_config.fragment_size = COMPRESS_OFFLOAD_FRAGMENT_SIZE;
   3859         out->compr_config.fragments = COMPRESS_OFFLOAD_NUM_FRAGMENTS;
   3860         out->compr_config.codec->sample_rate = config->offload_info.sample_rate;
   3861         out->compr_config.codec->bit_rate =
   3862                     config->offload_info.bit_rate;
   3863         out->compr_config.codec->ch_in =
   3864                 audio_channel_count_from_out_mask(config->channel_mask);
   3865         out->compr_config.codec->ch_out = out->compr_config.codec->ch_in;
   3866 
   3867         if (flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING)
   3868             out->non_blocking = 1;
   3869 
   3870         out->send_new_metadata = 1;
   3871         create_offload_callback_thread(out);
   3872         out->offload_state = OFFLOAD_STATE_IDLE;
   3873 
   3874         ALOGV("%s: offloaded output offload_info version %04x bit rate %d",
   3875                 __func__, config->offload_info.version,
   3876                 config->offload_info.bit_rate);
   3877     } else if (out->flags & (AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) {
   3878         out->usecase = USECASE_AUDIO_PLAYBACK_DEEP_BUFFER;
   3879         out->config = pcm_config_deep_buffer;
   3880         out->sample_rate = out->config.rate;
   3881         ALOGD("%s: use AUDIO_PLAYBACK_DEEP_BUFFER",__func__);
   3882     } else {
   3883         out->usecase = USECASE_AUDIO_PLAYBACK;
   3884         out->sample_rate = out->config.rate;
   3885     }
   3886 
   3887     if (flags & AUDIO_OUTPUT_FLAG_PRIMARY) {
   3888         if (adev->primary_output == NULL)
   3889             adev->primary_output = out;
   3890         else {
   3891             ALOGE("%s: Primary output is already opened", __func__);
   3892             ret = -EEXIST;
   3893             goto error_open;
   3894         }
   3895     }
   3896 
   3897     /* Check if this usecase is already existing */
   3898     pthread_mutex_lock(&adev->lock);
   3899     if (get_usecase_from_id(adev, out->usecase) != NULL) {
   3900         ALOGE("%s: Usecase (%d) is already present", __func__, out->usecase);
   3901         pthread_mutex_unlock(&adev->lock);
   3902         ret = -EEXIST;
   3903         goto error_open;
   3904     }
   3905     pthread_mutex_unlock(&adev->lock);
   3906 
   3907     out->stream.common.get_sample_rate = out_get_sample_rate;
   3908     out->stream.common.set_sample_rate = out_set_sample_rate;
   3909     out->stream.common.get_buffer_size = out_get_buffer_size;
   3910     out->stream.common.get_channels = out_get_channels;
   3911     out->stream.common.get_format = out_get_format;
   3912     out->stream.common.set_format = out_set_format;
   3913     out->stream.common.standby = out_standby;
   3914     out->stream.common.dump = out_dump;
   3915     out->stream.common.set_parameters = out_set_parameters;
   3916     out->stream.common.get_parameters = out_get_parameters;
   3917     out->stream.common.add_audio_effect = out_add_audio_effect;
   3918     out->stream.common.remove_audio_effect = out_remove_audio_effect;
   3919     out->stream.get_latency = out_get_latency;
   3920     out->stream.set_volume = out_set_volume;
   3921     out->stream.write = out_write;
   3922     out->stream.get_render_position = out_get_render_position;
   3923     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
   3924     out->stream.get_presentation_position = out_get_presentation_position;
   3925 
   3926     out->standby = 1;
   3927     /* out->muted = false; by calloc() */
   3928     /* out->written = 0; by calloc() */
   3929 
   3930     pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
   3931     pthread_cond_init(&out->cond, (const pthread_condattr_t *) NULL);
   3932 
   3933     config->format = out->stream.common.get_format(&out->stream.common);
   3934     config->channel_mask = out->stream.common.get_channels(&out->stream.common);
   3935     config->sample_rate = out->stream.common.get_sample_rate(&out->stream.common);
   3936 
   3937     *stream_out = &out->stream;
   3938     ALOGV("%s: exit", __func__);
   3939     return 0;
   3940 
   3941 error_open:
   3942     free(out);
   3943     *stream_out = NULL;
   3944     ALOGD("%s: exit: ret %d", __func__, ret);
   3945     return ret;
   3946 }
   3947 
   3948 static void adev_close_output_stream(struct audio_hw_device *dev,
   3949                                      struct audio_stream_out *stream)
   3950 {
   3951     struct stream_out *out = (struct stream_out *)stream;
   3952     struct audio_device *adev = out->dev;
   3953     (void)dev;
   3954 
   3955     ALOGV("%s: enter", __func__);
   3956     out_standby(&stream->common);
   3957     if (out->usecase == USECASE_AUDIO_PLAYBACK_OFFLOAD) {
   3958         destroy_offload_callback_thread(out);
   3959 
   3960         if (out->compr_config.codec != NULL)
   3961             free(out->compr_config.codec);
   3962     }
   3963     pthread_cond_destroy(&out->cond);
   3964     pthread_mutex_destroy(&out->lock);
   3965     free(stream);
   3966     ALOGV("%s: exit", __func__);
   3967 }
   3968 
   3969 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
   3970 {
   3971     struct audio_device *adev = (struct audio_device *)dev;
   3972     struct str_parms *parms;
   3973     char *str;
   3974     char value[32];
   3975     int val;
   3976     int ret;
   3977 
   3978     ALOGV("%s: enter: %s", __func__, kvpairs);
   3979 
   3980     parms = str_parms_create_str(kvpairs);
   3981     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_TTY_MODE, value, sizeof(value));
   3982     if (ret >= 0) {
   3983         int tty_mode;
   3984 
   3985         if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_OFF) == 0)
   3986             tty_mode = TTY_MODE_OFF;
   3987         else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_VCO) == 0)
   3988             tty_mode = TTY_MODE_VCO;
   3989         else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_HCO) == 0)
   3990             tty_mode = TTY_MODE_HCO;
   3991         else if (strcmp(value, AUDIO_PARAMETER_VALUE_TTY_FULL) == 0)
   3992             tty_mode = TTY_MODE_FULL;
   3993         else
   3994             return -EINVAL;
   3995 
   3996         pthread_mutex_lock(&adev->lock);
   3997         if (tty_mode != adev->tty_mode) {
   3998             adev->tty_mode = tty_mode;
   3999             if (adev->in_call)
   4000                 select_devices(adev, USECASE_VOICE_CALL);
   4001         }
   4002         pthread_mutex_unlock(&adev->lock);
   4003     }
   4004 
   4005     ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value));
   4006     if (ret >= 0) {
   4007         /* When set to false, HAL should disable EC and NS
   4008          * But it is currently not supported.
   4009          */
   4010         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   4011             adev->bluetooth_nrec = true;
   4012         else
   4013             adev->bluetooth_nrec = false;
   4014     }
   4015 
   4016     ret = str_parms_get_str(parms, "screen_state", value, sizeof(value));
   4017     if (ret >= 0) {
   4018         if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0)
   4019             adev->screen_off = false;
   4020         else
   4021             adev->screen_off = true;
   4022     }
   4023 
   4024     ret = str_parms_get_int(parms, "rotation", &val);
   4025     if (ret >= 0) {
   4026         bool reverse_speakers = false;
   4027         switch(val) {
   4028         /* FIXME: note that the code below assumes that the speakers are in the correct placement
   4029              relative to the user when the device is rotated 90deg from its default rotation. This
   4030              assumption is device-specific, not platform-specific like this code. */
   4031         case 270:
   4032             reverse_speakers = true;
   4033             break;
   4034         case 0:
   4035         case 90:
   4036         case 180:
   4037             break;
   4038         default:
   4039             ALOGE("%s: unexpected rotation of %d", __func__, val);
   4040         }
   4041         pthread_mutex_lock(&adev->lock);
   4042         if (adev->speaker_lr_swap != reverse_speakers) {
   4043             adev->speaker_lr_swap = reverse_speakers;
   4044             /* only update the selected device if there is active pcm playback */
   4045             struct audio_usecase *usecase;
   4046             struct listnode *node;
   4047             list_for_each(node, &adev->usecase_list) {
   4048                 usecase = node_to_item(node, struct audio_usecase, adev_list_node);
   4049                 if (usecase->type == PCM_PLAYBACK) {
   4050                     select_devices(adev, usecase->id);
   4051                     if (adev->htc_acoustic_spk_reverse)
   4052                         adev->htc_acoustic_spk_reverse(adev->speaker_lr_swap);
   4053                     break;
   4054                 }
   4055             }
   4056         }
   4057         pthread_mutex_unlock(&adev->lock);
   4058     }
   4059 
   4060     str_parms_destroy(parms);
   4061     ALOGV("%s: exit with code(%d)", __func__, ret);
   4062     return ret;
   4063 }
   4064 
   4065 static char* adev_get_parameters(const struct audio_hw_device *dev,
   4066                                  const char *keys)
   4067 {
   4068     (void)dev;
   4069     (void)keys;
   4070 
   4071     return strdup("");
   4072 }
   4073 
   4074 static int adev_init_check(const struct audio_hw_device *dev)
   4075 {
   4076     (void)dev;
   4077 
   4078     return 0;
   4079 }
   4080 
   4081 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
   4082 {
   4083     int ret = 0;
   4084     struct audio_device *adev = (struct audio_device *)dev;
   4085     pthread_mutex_lock(&adev->lock);
   4086     /* cache volume */
   4087     adev->voice_volume = volume;
   4088     ret = set_voice_volume_l(adev, adev->voice_volume);
   4089     pthread_mutex_unlock(&adev->lock);
   4090     return ret;
   4091 }
   4092 
   4093 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
   4094 {
   4095     (void)dev;
   4096     (void)volume;
   4097 
   4098     return -ENOSYS;
   4099 }
   4100 
   4101 static int adev_get_master_volume(struct audio_hw_device *dev,
   4102                                   float *volume)
   4103 {
   4104     (void)dev;
   4105     (void)volume;
   4106 
   4107     return -ENOSYS;
   4108 }
   4109 
   4110 static int adev_set_master_mute(struct audio_hw_device *dev, bool muted)
   4111 {
   4112     (void)dev;
   4113     (void)muted;
   4114 
   4115     return -ENOSYS;
   4116 }
   4117 
   4118 static int adev_get_master_mute(struct audio_hw_device *dev, bool *muted)
   4119 {
   4120     (void)dev;
   4121     (void)muted;
   4122 
   4123     return -ENOSYS;
   4124 }
   4125 
   4126 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
   4127 {
   4128     struct audio_device *adev = (struct audio_device *)dev;
   4129 
   4130     pthread_mutex_lock(&adev->lock);
   4131     if (adev->mode != mode) {
   4132         ALOGI("%s mode = %d", __func__, mode);
   4133         adev->mode = mode;
   4134         pthread_mutex_lock(&adev->tfa9895_lock);
   4135         adev->tfa9895_mode_change |= 0x1;
   4136         pthread_mutex_unlock(&adev->tfa9895_lock);
   4137     }
   4138     pthread_mutex_unlock(&adev->lock);
   4139     return 0;
   4140 }
   4141 
   4142 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
   4143 {
   4144     struct audio_device *adev = (struct audio_device *)dev;
   4145     int err = 0;
   4146 
   4147     pthread_mutex_lock(&adev->lock);
   4148     adev->mic_mute = state;
   4149 
   4150     if (adev->mode == AUDIO_MODE_IN_CALL) {
   4151         /* TODO */
   4152     }
   4153 
   4154     pthread_mutex_unlock(&adev->lock);
   4155     return err;
   4156 }
   4157 
   4158 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
   4159 {
   4160     struct audio_device *adev = (struct audio_device *)dev;
   4161 
   4162     *state = adev->mic_mute;
   4163 
   4164     return 0;
   4165 }
   4166 
   4167 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
   4168                                          const struct audio_config *config)
   4169 {
   4170     (void)dev;
   4171 
   4172     /* NOTE: we default to built in mic which may cause a mismatch between what we
   4173      * report here and the actual buffer size
   4174      */
   4175     return get_input_buffer_size(config->sample_rate,
   4176                                  config->format,
   4177                                  audio_channel_count_from_in_mask(config->channel_mask),
   4178                                  AUDIO_DEVICE_IN_BUILTIN_MIC);
   4179 }
   4180 
   4181 static int adev_open_input_stream(struct audio_hw_device *dev,
   4182                                   audio_io_handle_t handle __unused,
   4183                                   audio_devices_t devices,
   4184                                   struct audio_config *config,
   4185                                   struct audio_stream_in **stream_in,
   4186                                   audio_input_flags_t flags,
   4187                                   const char *address __unused,
   4188                                   audio_source_t source)
   4189 {
   4190     struct audio_device *adev = (struct audio_device *)dev;
   4191     struct stream_in *in;
   4192     struct pcm_device_profile *pcm_profile;
   4193 
   4194     ALOGV("%s: enter", __func__);
   4195 
   4196     *stream_in = NULL;
   4197     if (check_input_parameters(config->sample_rate, config->format,
   4198                                audio_channel_count_from_in_mask(config->channel_mask)) != 0)
   4199         return -EINVAL;
   4200 
   4201     if (source == AUDIO_SOURCE_HOTWORD) {
   4202         pcm_profile = get_pcm_device(PCM_HOTWORD_STREAMING, devices);
   4203     } else {
   4204         pcm_profile = get_pcm_device(PCM_CAPTURE, devices);
   4205     }
   4206     if (pcm_profile == NULL)
   4207         return -EINVAL;
   4208 
   4209     in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
   4210 
   4211     in->stream.common.get_sample_rate = in_get_sample_rate;
   4212     in->stream.common.set_sample_rate = in_set_sample_rate;
   4213     in->stream.common.get_buffer_size = in_get_buffer_size;
   4214     in->stream.common.get_channels = in_get_channels;
   4215     in->stream.common.get_format = in_get_format;
   4216     in->stream.common.set_format = in_set_format;
   4217     in->stream.common.standby = in_standby;
   4218     in->stream.common.dump = in_dump;
   4219     in->stream.common.set_parameters = in_set_parameters;
   4220     in->stream.common.get_parameters = in_get_parameters;
   4221     in->stream.common.add_audio_effect = in_add_audio_effect;
   4222     in->stream.common.remove_audio_effect = in_remove_audio_effect;
   4223     in->stream.set_gain = in_set_gain;
   4224     in->stream.read = in_read;
   4225     in->stream.get_input_frames_lost = in_get_input_frames_lost;
   4226 
   4227     in->devices = devices;
   4228     in->source = source;
   4229     in->dev = adev;
   4230     in->standby = 1;
   4231     in->main_channels = config->channel_mask;
   4232     in->requested_rate = config->sample_rate;
   4233     if (config->sample_rate != CAPTURE_DEFAULT_SAMPLING_RATE)
   4234         flags = flags & ~AUDIO_INPUT_FLAG_FAST;
   4235     in->input_flags = flags;
   4236     /* HW codec is limited to default channels. No need to update with
   4237      * requested channels */
   4238     in->config = pcm_profile->config;
   4239 
   4240     /* Update config params with the requested sample rate and channels */
   4241     if (source == AUDIO_SOURCE_HOTWORD) {
   4242         in->usecase = USECASE_AUDIO_CAPTURE_HOTWORD;
   4243     } else {
   4244         in->usecase = USECASE_AUDIO_CAPTURE;
   4245     }
   4246 
   4247     *stream_in = &in->stream;
   4248     ALOGV("%s: exit", __func__);
   4249     return 0;
   4250 }
   4251 
   4252 static void adev_close_input_stream(struct audio_hw_device *dev,
   4253                                     struct audio_stream_in *stream)
   4254 {
   4255     struct audio_device *adev = (struct audio_device *)dev;
   4256     struct stream_in *in = (struct stream_in*)stream;
   4257     ALOGV("%s", __func__);
   4258 
   4259     /* prevent concurrent out_set_parameters, or out_write from standby */
   4260     pthread_mutex_lock(&adev->lock_inputs);
   4261 
   4262 #ifdef PREPROCESSING_ENABLED
   4263     int i;
   4264 
   4265     for (i=0; i<in->num_preprocessors; i++) {
   4266         free(in->preprocessors[i].channel_configs);
   4267     }
   4268 
   4269     if (in->read_buf) {
   4270         free(in->read_buf);
   4271         in->read_buf = NULL;
   4272     }
   4273 
   4274     if (in->proc_buf_in) {
   4275         free(in->proc_buf_in);
   4276         in->proc_buf_in = NULL;
   4277     }
   4278 
   4279     if (in->proc_buf_out) {
   4280         free(in->proc_buf_out);
   4281         in->proc_buf_out = NULL;
   4282     }
   4283 
   4284     if (in->ref_buf) {
   4285         free(in->ref_buf);
   4286         in->ref_buf = NULL;
   4287     }
   4288 
   4289     if (in->resampler) {
   4290         release_resampler(in->resampler);
   4291         in->resampler = NULL;
   4292     }
   4293 #endif
   4294 
   4295     in_standby_l(in);
   4296     free(stream);
   4297 
   4298     pthread_mutex_unlock(&adev->lock_inputs);
   4299 
   4300     return;
   4301 }
   4302 
   4303 static int adev_dump(const audio_hw_device_t *device, int fd)
   4304 {
   4305     (void)device;
   4306     (void)fd;
   4307 
   4308     return 0;
   4309 }
   4310 
   4311 static int adev_close(hw_device_t *device)
   4312 {
   4313     struct audio_device *adev = (struct audio_device *)device;
   4314     audio_device_ref_count--;
   4315     free(adev->snd_dev_ref_cnt);
   4316     free_mixer_list(adev);
   4317     free(device);
   4318     return 0;
   4319 }
   4320 
   4321 static void *dummybuf_thread(void *context)
   4322 {
   4323     ALOGD("%s: enter", __func__);
   4324     pthread_detach(pthread_self());
   4325     struct audio_device *adev = (struct audio_device *)context;
   4326     struct pcm_config config;
   4327     const char *mixer_ctl_name = "Headphone Jack Switch";
   4328     struct mixer *mixer = NULL;
   4329     struct mixer_ctl *ctl;
   4330     unsigned char *data = NULL;
   4331     struct pcm *pcm = NULL;
   4332     struct pcm_device_profile *profile = NULL;
   4333 
   4334     memset(&config, 0, sizeof(struct pcm_config));
   4335     if (adev->dummybuf_thread_devices == AUDIO_DEVICE_OUT_WIRED_HEADPHONE) {
   4336         profile = &pcm_device_playback_hs;
   4337         mixer = mixer_open(profile->card);
   4338     }
   4339     else
   4340         profile = &pcm_device_playback_spk;
   4341 
   4342     memcpy(&config, &profile->config, sizeof(struct pcm_config));
   4343     /* Use large value for stop_threshold so that automatic
   4344        trigger for stop is avoided, when this thread fails to write data */
   4345     config.stop_threshold = INT_MAX/2;
   4346     pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4347     pcm = pcm_open(profile->card, profile->id,
   4348                    (PCM_OUT | PCM_MONOTONIC), &config);
   4349     if (pcm != NULL && !pcm_is_ready(pcm)) {
   4350         ALOGE("pcm_open: card=%d, id=%d is not ready", profile->card, profile->id);
   4351         pcm_close(pcm);
   4352         pcm = NULL;
   4353     } else {
   4354         ALOGD("pcm_open: card=%d, id=%d", profile->card, profile->id);
   4355     }
   4356 
   4357     if (mixer) {
   4358         ctl = mixer_get_ctl_by_name(mixer, mixer_ctl_name);
   4359         if (ctl != NULL)
   4360             mixer_ctl_set_value(ctl, 0, 1);
   4361         else {
   4362             ALOGE("Invalid mixer control: name(%s): skip dummy thread", mixer_ctl_name);
   4363             adev->dummybuf_thread_active = 1;
   4364             mixer_close(mixer);
   4365             if (pcm) {
   4366                 pcm_close(pcm);
   4367                 pcm = NULL;
   4368             }
   4369             pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4370             return NULL;
   4371         }
   4372     }
   4373     pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4374 
   4375     while (1) {
   4376         pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4377         if (pcm) {
   4378             if (data == NULL)
   4379                 data = (unsigned char *)calloc(DEEP_BUFFER_OUTPUT_PERIOD_SIZE * 8,
   4380                             sizeof(unsigned char));
   4381             if (data) {
   4382                 pcm_write(pcm, (void *)data, DEEP_BUFFER_OUTPUT_PERIOD_SIZE * 8);
   4383                 adev->dummybuf_thread_active = 1;
   4384             } else {
   4385                 ALOGD("%s: cant open a buffer, retry to open it", __func__);
   4386             }
   4387         } else {
   4388             ALOGD("%s: cant open a output deep stream, retry to open it", __func__);
   4389             pcm = pcm_open(profile->card, profile->id,
   4390                    (PCM_OUT | PCM_MONOTONIC), &config);
   4391             if (pcm != NULL && !pcm_is_ready(pcm)) {
   4392                 ALOGE("pcm_open: card=%d, id=%d is not ready", profile->card, profile->id);
   4393                 pcm_close(pcm);
   4394                 pcm = NULL;
   4395             } else {
   4396                 ALOGD("pcm_open: card=%d, id=%d", profile->card, profile->id);
   4397             }
   4398         }
   4399 
   4400         if (adev->dummybuf_thread_cancel || adev->dummybuf_thread_timeout-- <= 0) {
   4401             adev->dummybuf_thread_active = 0;
   4402             adev->dummybuf_thread_cancel = 0;
   4403             if (pcm) {
   4404                 ALOGD("pcm_close ++ card=%d, id=%d", profile->card, profile->id);
   4405                 pcm_close(pcm);
   4406                 if (mixer) {
   4407                     mixer_ctl_set_value(ctl, 0, 0);
   4408                     mixer_close(mixer);
   4409                 }
   4410                 ALOGD("pcm_close -- card=%d, id=%d", profile->card, profile->id);
   4411                 pcm = NULL;
   4412             }
   4413             pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4414 
   4415             break;
   4416         }
   4417 
   4418         pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4419         usleep(3000);
   4420     }
   4421 
   4422     if (data)
   4423         free(data);
   4424 
   4425     return NULL;
   4426 }
   4427 
   4428 static void dummybuf_thread_open(struct audio_device *adev)
   4429 {
   4430     adev->dummybuf_thread_timeout = 6000; /* in 18 sec */
   4431     adev->dummybuf_thread_cancel = 0;
   4432     adev->dummybuf_thread_active = 0;
   4433     pthread_mutex_init(&adev->dummybuf_thread_lock, (const pthread_mutexattr_t *) NULL);
   4434     if (!adev->dummybuf_thread)
   4435         pthread_create(&adev->dummybuf_thread, (const pthread_attr_t *) NULL, dummybuf_thread, adev);
   4436 }
   4437 
   4438 static void dummybuf_thread_close(struct audio_device *adev)
   4439 {
   4440     ALOGD("%s: enter", __func__);
   4441     int retry_cnt = 20;
   4442 
   4443     if (adev->dummybuf_thread == 0)
   4444         return;
   4445 
   4446     pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4447     adev->dummybuf_thread_cancel = 1;
   4448     pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4449 
   4450     while (retry_cnt > 0) {
   4451         pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4452         if (adev->dummybuf_thread_active == 0) {
   4453             pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4454             break;
   4455         }
   4456         pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4457         retry_cnt--;
   4458         usleep(1000);
   4459     }
   4460 
   4461     pthread_join(adev->dummybuf_thread, (void **) NULL);
   4462     pthread_mutex_destroy(&adev->dummybuf_thread_lock);
   4463     adev->dummybuf_thread = 0;
   4464 }
   4465 
   4466 static int adev_open(const hw_module_t *module, const char *name,
   4467                      hw_device_t **device)
   4468 {
   4469     struct audio_device *adev;
   4470     int i, ret, retry_count;
   4471 
   4472     ALOGD("%s: enter", __func__);
   4473     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL;
   4474 
   4475     adev = calloc(1, sizeof(struct audio_device));
   4476 
   4477     adev->device.common.tag = HARDWARE_DEVICE_TAG;
   4478     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
   4479     adev->device.common.module = (struct hw_module_t *)module;
   4480     adev->device.common.close = adev_close;
   4481 
   4482     adev->device.init_check = adev_init_check;
   4483     adev->device.set_voice_volume = adev_set_voice_volume;
   4484     adev->device.set_master_volume = adev_set_master_volume;
   4485     adev->device.get_master_volume = adev_get_master_volume;
   4486     adev->device.set_master_mute = adev_set_master_mute;
   4487     adev->device.get_master_mute = adev_get_master_mute;
   4488     adev->device.set_mode = adev_set_mode;
   4489     adev->device.set_mic_mute = adev_set_mic_mute;
   4490     adev->device.get_mic_mute = adev_get_mic_mute;
   4491     adev->device.set_parameters = adev_set_parameters;
   4492     adev->device.get_parameters = adev_get_parameters;
   4493     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
   4494     adev->device.open_output_stream = adev_open_output_stream;
   4495     adev->device.close_output_stream = adev_close_output_stream;
   4496     adev->device.open_input_stream = adev_open_input_stream;
   4497     adev->device.close_input_stream = adev_close_input_stream;
   4498     adev->device.dump = adev_dump;
   4499 
   4500     /* Set the default route before the PCM stream is opened */
   4501     adev->mode = AUDIO_MODE_NORMAL;
   4502     adev->active_input = NULL;
   4503     adev->primary_output = NULL;
   4504     adev->voice_volume = 1.0f;
   4505     adev->tty_mode = TTY_MODE_OFF;
   4506     adev->bluetooth_nrec = true;
   4507     adev->in_call = false;
   4508     /* adev->cur_hdmi_channels = 0;  by calloc() */
   4509     adev->snd_dev_ref_cnt = calloc(SND_DEVICE_MAX, sizeof(int));
   4510 
   4511     adev->dualmic_config = DUALMIC_CONFIG_NONE;
   4512     adev->ns_in_voice_rec = false;
   4513 
   4514     list_init(&adev->usecase_list);
   4515 
   4516     if (mixer_init(adev) != 0) {
   4517         free(adev->snd_dev_ref_cnt);
   4518         free(adev);
   4519         ALOGE("%s: Failed to init, aborting.", __func__);
   4520         *device = NULL;
   4521         return -EINVAL;
   4522     }
   4523 
   4524     if (access(OFFLOAD_FX_LIBRARY_PATH, R_OK) == 0) {
   4525         adev->offload_fx_lib = dlopen(OFFLOAD_FX_LIBRARY_PATH, RTLD_NOW);
   4526         if (adev->offload_fx_lib == NULL) {
   4527             ALOGE("%s: DLOPEN failed for %s", __func__, OFFLOAD_FX_LIBRARY_PATH);
   4528         } else {
   4529             ALOGV("%s: DLOPEN successful for %s", __func__, OFFLOAD_FX_LIBRARY_PATH);
   4530             adev->offload_fx_start_output =
   4531                         (int (*)(audio_io_handle_t))dlsym(adev->offload_fx_lib,
   4532                                                         "visualizer_hal_start_output");
   4533             adev->offload_fx_stop_output =
   4534                         (int (*)(audio_io_handle_t))dlsym(adev->offload_fx_lib,
   4535                                                         "visualizer_hal_stop_output");
   4536         }
   4537     }
   4538 
   4539     if (access(HTC_ACOUSTIC_LIBRARY_PATH, R_OK) == 0) {
   4540         adev->htc_acoustic_lib = dlopen(HTC_ACOUSTIC_LIBRARY_PATH, RTLD_NOW);
   4541         if (adev->htc_acoustic_lib == NULL) {
   4542             ALOGE("%s: DLOPEN failed for %s", __func__, HTC_ACOUSTIC_LIBRARY_PATH);
   4543         } else {
   4544             ALOGV("%s: DLOPEN successful for %s", __func__, HTC_ACOUSTIC_LIBRARY_PATH);
   4545             adev->htc_acoustic_init_rt5506 =
   4546                         (int (*)())dlsym(adev->htc_acoustic_lib,
   4547                                                         "init_rt5506");
   4548             adev->htc_acoustic_set_rt5506_amp =
   4549                         (int (*)(int, int))dlsym(adev->htc_acoustic_lib,
   4550                                                         "set_rt5506_amp");
   4551             adev->htc_acoustic_set_amp_mode =
   4552                         (int (*)(int , int, int, int, bool))dlsym(adev->htc_acoustic_lib,
   4553                                                         "set_amp_mode");
   4554             adev->htc_acoustic_spk_reverse =
   4555                         (int (*)(bool))dlsym(adev->htc_acoustic_lib,
   4556                                                         "spk_reverse");
   4557             if (adev->htc_acoustic_spk_reverse)
   4558                 adev->htc_acoustic_spk_reverse(adev->speaker_lr_swap);
   4559         }
   4560     }
   4561 
   4562     if (access(SOUND_TRIGGER_HAL_LIBRARY_PATH, R_OK) == 0) {
   4563         adev->sound_trigger_lib = dlopen(SOUND_TRIGGER_HAL_LIBRARY_PATH, RTLD_NOW);
   4564         if (adev->sound_trigger_lib == NULL) {
   4565             ALOGE("%s: DLOPEN failed for %s", __func__, SOUND_TRIGGER_HAL_LIBRARY_PATH);
   4566         } else {
   4567             ALOGV("%s: DLOPEN successful for %s", __func__, SOUND_TRIGGER_HAL_LIBRARY_PATH);
   4568             adev->sound_trigger_open_for_streaming =
   4569                         (int (*)(void))dlsym(adev->sound_trigger_lib,
   4570                                                         "sound_trigger_open_for_streaming");
   4571             adev->sound_trigger_read_samples =
   4572                         (int (*)(audio_io_handle_t, int))dlsym(adev->sound_trigger_lib,
   4573                                                         "sound_trigger_read_samples");
   4574             adev->sound_trigger_close_for_streaming =
   4575                         (int (*)(int))dlsym(adev->sound_trigger_lib,
   4576                                                         "sound_trigger_close_for_streaming");
   4577             if (!adev->sound_trigger_open_for_streaming ||
   4578                 !adev->sound_trigger_read_samples ||
   4579                 !adev->sound_trigger_close_for_streaming) {
   4580 
   4581                 ALOGE("%s: Error grabbing functions in %s", __func__, SOUND_TRIGGER_HAL_LIBRARY_PATH);
   4582                 adev->sound_trigger_open_for_streaming = 0;
   4583                 adev->sound_trigger_read_samples = 0;
   4584                 adev->sound_trigger_close_for_streaming = 0;
   4585             }
   4586         }
   4587     }
   4588 
   4589 
   4590     *device = &adev->device.common;
   4591 
   4592     if (adev->htc_acoustic_init_rt5506 != NULL)
   4593         adev->htc_acoustic_init_rt5506();
   4594 
   4595     if (audio_device_ref_count == 0) {
   4596         /* For HS GPIO initial config */
   4597         adev->dummybuf_thread_devices = AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
   4598         dummybuf_thread_open(adev);
   4599         retry_count = RETRY_NUMBER;
   4600         while (retry_count-- > 0) {
   4601             pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4602             if (adev->dummybuf_thread_active != 0) {
   4603                 pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4604                 break;
   4605             }
   4606             pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4607             usleep(10000);
   4608         }
   4609         dummybuf_thread_close(adev);
   4610 
   4611         /* For NXP DSP config */
   4612         if (adev->htc_acoustic_set_amp_mode) {
   4613             pthread_t th;
   4614             adev->dummybuf_thread_devices = AUDIO_DEVICE_OUT_SPEAKER;
   4615             dummybuf_thread_open(adev);
   4616             pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4617             retry_count = RETRY_NUMBER;
   4618             while (retry_count-- > 0) {
   4619                 if (adev->dummybuf_thread_active) {
   4620                     break;
   4621                 }
   4622                 pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4623                 usleep(10000);
   4624                 pthread_mutex_lock(&adev->dummybuf_thread_lock);
   4625             }
   4626             if (adev->dummybuf_thread_active) {
   4627                 usleep(10000); /* tfa9895 spk amp need more than 1ms i2s signal before giving dsp related i2c commands*/
   4628                 if (pthread_create(&th, NULL, tfa9895_config_thread, (void* )adev) != 0) {
   4629                     ALOGE("@@##THREAD_FADE_IN_UPPER_SPEAKER thread create fail");
   4630                 }
   4631             }
   4632             pthread_mutex_unlock(&adev->dummybuf_thread_lock);
   4633             /* Then, dummybuf_thread_close() is called by tfa9895_config_thread() */
   4634         }
   4635     }
   4636     audio_device_ref_count++;
   4637 
   4638     ALOGV("%s: exit", __func__);
   4639     return 0;
   4640 }
   4641 
   4642 static struct hw_module_methods_t hal_module_methods = {
   4643     .open = adev_open,
   4644 };
   4645 
   4646 struct audio_module HAL_MODULE_INFO_SYM = {
   4647     .common = {
   4648         .tag = HARDWARE_MODULE_TAG,
   4649         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
   4650         .hal_api_version = HARDWARE_HAL_API_VERSION,
   4651         .id = AUDIO_HARDWARE_MODULE_ID,
   4652         .name = "NVIDIA Tegra Audio HAL",
   4653         .author = "The Android Open Source Project",
   4654         .methods = &hal_module_methods,
   4655     },
   4656 };
   4657