Home | History | Annotate | Download | only in audio
      1 /*
      2  * Copyright (C) 2012 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_generic"
     18 
     19 #include <assert.h>
     20 #include <errno.h>
     21 #include <inttypes.h>
     22 #include <pthread.h>
     23 #include <stdint.h>
     24 #include <stdlib.h>
     25 #include <sys/time.h>
     26 #include <dlfcn.h>
     27 #include <fcntl.h>
     28 #include <unistd.h>
     29 
     30 #include <log/log.h>
     31 #include <cutils/str_parms.h>
     32 
     33 #include <hardware/hardware.h>
     34 #include <system/audio.h>
     35 #include <hardware/audio.h>
     36 #include <tinyalsa/asoundlib.h>
     37 
     38 #define PCM_CARD 0
     39 #define PCM_DEVICE 0
     40 
     41 
     42 #define OUT_PERIOD_MS 15
     43 #define OUT_PERIOD_COUNT 4
     44 
     45 #define IN_PERIOD_MS 15
     46 #define IN_PERIOD_COUNT 4
     47 
     48 struct generic_audio_device {
     49     struct audio_hw_device device; // Constant after init
     50     pthread_mutex_t lock;
     51     bool mic_mute;                 // Proteced by this->lock
     52     struct mixer* mixer;           // Proteced by this->lock
     53 };
     54 
     55 /* If not NULL, this is a pointer to the fallback module.
     56  * This really is the original goldfish audio device /dev/eac which we will use
     57  * if no alsa devices are detected.
     58  */
     59 static struct audio_module*  sFallback;
     60 static pthread_once_t sFallbackOnce = PTHREAD_ONCE_INIT;
     61 static void fallback_init(void);
     62 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state);
     63 
     64 typedef struct audio_vbuffer {
     65     pthread_mutex_t lock;
     66     uint8_t *  data;
     67     size_t     frame_size;
     68     size_t     frame_count;
     69     size_t     head;
     70     size_t     tail;
     71     size_t     live;
     72 } audio_vbuffer_t;
     73 
     74 static int audio_vbuffer_init (audio_vbuffer_t * audio_vbuffer, size_t frame_count,
     75                               size_t frame_size) {
     76     if (!audio_vbuffer) {
     77         return -EINVAL;
     78     }
     79     audio_vbuffer->frame_size = frame_size;
     80     audio_vbuffer->frame_count = frame_count;
     81     size_t bytes = frame_count * frame_size;
     82     audio_vbuffer->data = calloc(bytes, 1);
     83     if (!audio_vbuffer->data) {
     84         return -ENOMEM;
     85     }
     86     audio_vbuffer->head = 0;
     87     audio_vbuffer->tail = 0;
     88     audio_vbuffer->live = 0;
     89     pthread_mutex_init (&audio_vbuffer->lock, (const pthread_mutexattr_t *) NULL);
     90     return 0;
     91 }
     92 
     93 static int audio_vbuffer_destroy (audio_vbuffer_t * audio_vbuffer) {
     94     if (!audio_vbuffer) {
     95         return -EINVAL;
     96     }
     97     free(audio_vbuffer->data);
     98     pthread_mutex_destroy(&audio_vbuffer->lock);
     99     return 0;
    100 }
    101 
    102 static int audio_vbuffer_live (audio_vbuffer_t * audio_vbuffer) {
    103     if (!audio_vbuffer) {
    104         return -EINVAL;
    105     }
    106     pthread_mutex_lock (&audio_vbuffer->lock);
    107     int live = audio_vbuffer->live;
    108     pthread_mutex_unlock (&audio_vbuffer->lock);
    109     return live;
    110 }
    111 
    112 static int audio_vbuffer_dead (audio_vbuffer_t * audio_vbuffer) {
    113     if (!audio_vbuffer) {
    114         return -EINVAL;
    115     }
    116     pthread_mutex_lock (&audio_vbuffer->lock);
    117     int dead = audio_vbuffer->frame_count - audio_vbuffer->live;
    118     pthread_mutex_unlock (&audio_vbuffer->lock);
    119     return dead;
    120 }
    121 
    122 #define MIN(a,b) (((a)<(b))?(a):(b))
    123 static size_t audio_vbuffer_write (audio_vbuffer_t * audio_vbuffer, const void * buffer, size_t frame_count) {
    124     size_t frames_written = 0;
    125     pthread_mutex_lock (&audio_vbuffer->lock);
    126 
    127     while (frame_count != 0) {
    128         int frames = 0;
    129         if (audio_vbuffer->live == 0 || audio_vbuffer->head > audio_vbuffer->tail) {
    130             frames = MIN(frame_count, audio_vbuffer->frame_count - audio_vbuffer->head);
    131         } else if (audio_vbuffer->head < audio_vbuffer->tail) {
    132             frames = MIN(frame_count, audio_vbuffer->tail - (audio_vbuffer->head));
    133         } else {
    134             // Full
    135             break;
    136         }
    137         memcpy(&audio_vbuffer->data[audio_vbuffer->head*audio_vbuffer->frame_size],
    138                &((uint8_t*)buffer)[frames_written*audio_vbuffer->frame_size],
    139                frames*audio_vbuffer->frame_size);
    140         audio_vbuffer->live += frames;
    141         frames_written += frames;
    142         frame_count -= frames;
    143         audio_vbuffer->head = (audio_vbuffer->head + frames) % audio_vbuffer->frame_count;
    144     }
    145 
    146     pthread_mutex_unlock (&audio_vbuffer->lock);
    147     return frames_written;
    148 }
    149 
    150 static size_t audio_vbuffer_read (audio_vbuffer_t * audio_vbuffer, void * buffer, size_t frame_count) {
    151     size_t frames_read = 0;
    152     pthread_mutex_lock (&audio_vbuffer->lock);
    153 
    154     while (frame_count != 0) {
    155         int frames = 0;
    156         if (audio_vbuffer->live == audio_vbuffer->frame_count ||
    157             audio_vbuffer->tail > audio_vbuffer->head) {
    158             frames = MIN(frame_count, audio_vbuffer->frame_count - audio_vbuffer->tail);
    159         } else if (audio_vbuffer->tail < audio_vbuffer->head) {
    160             frames = MIN(frame_count, audio_vbuffer->head - audio_vbuffer->tail);
    161         } else {
    162             break;
    163         }
    164         memcpy(&((uint8_t*)buffer)[frames_read*audio_vbuffer->frame_size],
    165                &audio_vbuffer->data[audio_vbuffer->tail*audio_vbuffer->frame_size],
    166                frames*audio_vbuffer->frame_size);
    167         audio_vbuffer->live -= frames;
    168         frames_read += frames;
    169         frame_count -= frames;
    170         audio_vbuffer->tail = (audio_vbuffer->tail + frames) % audio_vbuffer->frame_count;
    171     }
    172 
    173     pthread_mutex_unlock (&audio_vbuffer->lock);
    174     return frames_read;
    175 }
    176 
    177 struct generic_stream_out {
    178     struct audio_stream_out stream;   // Constant after init
    179     pthread_mutex_t lock;
    180     struct generic_audio_device *dev; // Constant after init
    181     audio_devices_t device;           // Protected by this->lock
    182     struct audio_config req_config;   // Constant after init
    183     struct pcm_config pcm_config;     // Constant after init
    184     audio_vbuffer_t buffer;           // Constant after init
    185 
    186     // Time & Position Keeping
    187     bool standby;                      // Protected by this->lock
    188     uint64_t underrun_position;        // Protected by this->lock
    189     struct timespec underrun_time;     // Protected by this->lock
    190     uint64_t last_write_time_us;       // Protected by this->lock
    191     uint64_t frames_total_buffered;    // Protected by this->lock
    192     uint64_t frames_written;           // Protected by this->lock
    193     uint64_t frames_rendered;          // Protected by this->lock
    194 
    195     // Worker
    196     pthread_t worker_thread;          // Constant after init
    197     pthread_cond_t worker_wake;       // Protected by this->lock
    198     bool worker_standby;              // Protected by this->lock
    199     bool worker_exit;                 // Protected by this->lock
    200 };
    201 
    202 struct generic_stream_in {
    203     struct audio_stream_in stream;    // Constant after init
    204     pthread_mutex_t lock;
    205     struct generic_audio_device *dev; // Constant after init
    206     audio_devices_t device;           // Protected by this->lock
    207     struct audio_config req_config;   // Constant after init
    208     struct pcm *pcm;                  // Protected by this->lock
    209     struct pcm_config pcm_config;     // Constant after init
    210     int16_t *stereo_to_mono_buf;      // Protected by this->lock
    211     size_t stereo_to_mono_buf_size;   // Protected by this->lock
    212     audio_vbuffer_t buffer;           // Protected by this->lock
    213 
    214     // Time & Position Keeping
    215     bool standby;                     // Protected by this->lock
    216     int64_t standby_position;         // Protected by this->lock
    217     struct timespec standby_exit_time;// Protected by this->lock
    218     int64_t standby_frames_read;      // Protected by this->lock
    219 
    220     // Worker
    221     pthread_t worker_thread;          // Constant after init
    222     pthread_cond_t worker_wake;       // Protected by this->lock
    223     bool worker_standby;              // Protected by this->lock
    224     bool worker_exit;                 // Protected by this->lock
    225 };
    226 
    227 static struct pcm_config pcm_config_out = {
    228     .channels = 2,
    229     .rate = 0,
    230     .period_size = 0,
    231     .period_count = OUT_PERIOD_COUNT,
    232     .format = PCM_FORMAT_S16_LE,
    233     .start_threshold = 0,
    234 };
    235 
    236 static struct pcm_config pcm_config_in = {
    237     .channels = 2,
    238     .rate = 0,
    239     .period_size = 0,
    240     .period_count = IN_PERIOD_COUNT,
    241     .format = PCM_FORMAT_S16_LE,
    242     .start_threshold = 0,
    243     .stop_threshold = INT_MAX,
    244 };
    245 
    246 static pthread_mutex_t adev_init_lock = PTHREAD_MUTEX_INITIALIZER;
    247 static unsigned int audio_device_ref_count = 0;
    248 
    249 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
    250 {
    251     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    252     return out->req_config.sample_rate;
    253 }
    254 
    255 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
    256 {
    257     return -ENOSYS;
    258 }
    259 
    260 static size_t out_get_buffer_size(const struct audio_stream *stream)
    261 {
    262     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    263     int size = out->pcm_config.period_size *
    264                 audio_stream_out_frame_size(&out->stream);
    265 
    266     return size;
    267 }
    268 
    269 static audio_channel_mask_t out_get_channels(const struct audio_stream *stream)
    270 {
    271     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    272     return out->req_config.channel_mask;
    273 }
    274 
    275 static audio_format_t out_get_format(const struct audio_stream *stream)
    276 {
    277     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    278     return out->req_config.format;
    279 }
    280 
    281 static int out_set_format(struct audio_stream *stream, audio_format_t format)
    282 {
    283     return -ENOSYS;
    284 }
    285 
    286 static int out_dump(const struct audio_stream *stream, int fd)
    287 {
    288     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    289     pthread_mutex_lock(&out->lock);
    290     dprintf(fd, "\tout_dump:\n"
    291                 "\t\tsample rate: %u\n"
    292                 "\t\tbuffer size: %zu\n"
    293                 "\t\tchannel mask: %08x\n"
    294                 "\t\tformat: %d\n"
    295                 "\t\tdevice: %08x\n"
    296                 "\t\taudio dev: %p\n\n",
    297                 out_get_sample_rate(stream),
    298                 out_get_buffer_size(stream),
    299                 out_get_channels(stream),
    300                 out_get_format(stream),
    301                 out->device,
    302                 out->dev);
    303     pthread_mutex_unlock(&out->lock);
    304     return 0;
    305 }
    306 
    307 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
    308 {
    309     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    310     struct str_parms *parms;
    311     char value[32];
    312     int ret;
    313     long val;
    314     char *end;
    315 
    316     pthread_mutex_lock(&out->lock);
    317     if (!out->standby) {
    318         //Do not support changing params while stream running
    319         ret = -ENOSYS;
    320     } else {
    321         parms = str_parms_create_str(kvpairs);
    322         ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING,
    323                                 value, sizeof(value));
    324         if (ret >= 0) {
    325             errno = 0;
    326             val = strtol(value, &end, 10);
    327             if (errno == 0 && (end != NULL) && (*end == '\0') && ((int)val == val)) {
    328                 out->device = (int)val;
    329                 ret = 0;
    330             } else {
    331                 ret = -EINVAL;
    332             }
    333         }
    334         str_parms_destroy(parms);
    335     }
    336     pthread_mutex_unlock(&out->lock);
    337     return ret;
    338 }
    339 
    340 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
    341 {
    342     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    343     struct str_parms *query = str_parms_create_str(keys);
    344     char *str;
    345     char value[256];
    346     struct str_parms *reply = str_parms_create();
    347     int ret;
    348 
    349     ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
    350     if (ret >= 0) {
    351         pthread_mutex_lock(&out->lock);
    352         str_parms_add_int(reply, AUDIO_PARAMETER_STREAM_ROUTING, out->device);
    353         pthread_mutex_unlock(&out->lock);
    354         str = strdup(str_parms_to_str(reply));
    355     } else {
    356         str = strdup(keys);
    357     }
    358 
    359     str_parms_destroy(query);
    360     str_parms_destroy(reply);
    361     return str;
    362 }
    363 
    364 static uint32_t out_get_latency(const struct audio_stream_out *stream)
    365 {
    366     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    367     return (out->pcm_config.period_size * 1000) / out->pcm_config.rate;
    368 }
    369 
    370 static int out_set_volume(struct audio_stream_out *stream, float left,
    371                           float right)
    372 {
    373     return -ENOSYS;
    374 }
    375 
    376 static void *out_write_worker(void * args)
    377 {
    378     struct generic_stream_out *out = (struct generic_stream_out *)args;
    379     struct pcm *pcm = NULL;
    380     uint8_t *buffer = NULL;
    381     int buffer_frames;
    382     int buffer_size;
    383     bool restart = false;
    384     bool shutdown = false;
    385     while (true) {
    386         pthread_mutex_lock(&out->lock);
    387         while (out->worker_standby || restart) {
    388             restart = false;
    389             if (pcm) {
    390                 pcm_close(pcm); // Frees pcm
    391                 pcm = NULL;
    392                 free(buffer);
    393                 buffer=NULL;
    394             }
    395             if (out->worker_exit) {
    396                 break;
    397             }
    398             pthread_cond_wait(&out->worker_wake, &out->lock);
    399         }
    400 
    401         if (out->worker_exit) {
    402             if (!out->worker_standby) {
    403                 ALOGE("Out worker not in standby before exiting");
    404             }
    405             shutdown = true;
    406         }
    407 
    408         while (!shutdown && audio_vbuffer_live(&out->buffer) == 0) {
    409             pthread_cond_wait(&out->worker_wake, &out->lock);
    410         }
    411 
    412         if (shutdown) {
    413             pthread_mutex_unlock(&out->lock);
    414             break;
    415         }
    416 
    417         if (!pcm) {
    418             pcm = pcm_open(PCM_CARD, PCM_DEVICE,
    419                           PCM_OUT | PCM_MONOTONIC, &out->pcm_config);
    420             if (!pcm_is_ready(pcm)) {
    421                 ALOGE("pcm_open(out) failed: %s: channels %d format %d rate %d",
    422                   pcm_get_error(pcm),
    423                   out->pcm_config.channels,
    424                   out->pcm_config.format,
    425                   out->pcm_config.rate
    426                    );
    427                 pthread_mutex_unlock(&out->lock);
    428                 break;
    429             }
    430             buffer_frames = out->pcm_config.period_size;
    431             buffer_size = pcm_frames_to_bytes(pcm, buffer_frames);
    432             buffer = malloc(buffer_size);
    433             if (!buffer) {
    434                 ALOGE("could not allocate write buffer");
    435                 pthread_mutex_unlock(&out->lock);
    436                 break;
    437             }
    438         }
    439         int frames = audio_vbuffer_read(&out->buffer, buffer, buffer_frames);
    440         pthread_mutex_unlock(&out->lock);
    441         int ret = pcm_write(pcm, buffer, pcm_frames_to_bytes(pcm, frames));
    442         if (ret != 0) {
    443             ALOGE("pcm_write failed %s", pcm_get_error(pcm));
    444             restart = true;
    445         }
    446     }
    447     if (buffer) {
    448         free(buffer);
    449     }
    450 
    451     return NULL;
    452 }
    453 
    454 // Call with in->lock held
    455 static void get_current_output_position(struct generic_stream_out *out,
    456                                        uint64_t * position,
    457                                        struct timespec * timestamp) {
    458     struct timespec curtime = { .tv_sec = 0, .tv_nsec = 0 };
    459     clock_gettime(CLOCK_MONOTONIC, &curtime);
    460     const int64_t now_us = (curtime.tv_sec * 1000000000LL + curtime.tv_nsec) / 1000;
    461     if (timestamp) {
    462         *timestamp = curtime;
    463     }
    464     int64_t position_since_underrun;
    465     if (out->standby) {
    466         position_since_underrun = 0;
    467     } else {
    468         const int64_t first_us = (out->underrun_time.tv_sec * 1000000000LL +
    469                                   out->underrun_time.tv_nsec) / 1000;
    470         position_since_underrun = (now_us - first_us) *
    471                 out_get_sample_rate(&out->stream.common) /
    472                 1000000;
    473         if (position_since_underrun < 0) {
    474             position_since_underrun = 0;
    475         }
    476     }
    477     *position = out->underrun_position + position_since_underrun;
    478 
    479     // The device will reuse the same output stream leading to periods of
    480     // underrun.
    481     if (*position > out->frames_written) {
    482         ALOGW("Not supplying enough data to HAL, expected position %" PRIu64 " , only wrote "
    483               "%" PRIu64,
    484               *position, out->frames_written);
    485 
    486         *position = out->frames_written;
    487         out->underrun_position = *position;
    488         out->underrun_time = curtime;
    489         out->frames_total_buffered = 0;
    490     }
    491 }
    492 
    493 
    494 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer,
    495                          size_t bytes)
    496 {
    497     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    498     const size_t frames =  bytes / audio_stream_out_frame_size(stream);
    499 
    500     pthread_mutex_lock(&out->lock);
    501 
    502     if (out->worker_standby) {
    503         out->worker_standby = false;
    504     }
    505 
    506     uint64_t current_position;
    507     struct timespec current_time;
    508 
    509     get_current_output_position(out, &current_position, &current_time);
    510     const uint64_t now_us = (current_time.tv_sec * 1000000000LL +
    511                              current_time.tv_nsec) / 1000;
    512     if (out->standby) {
    513         out->standby = false;
    514         out->underrun_time = current_time;
    515         out->frames_rendered = 0;
    516         out->frames_total_buffered = 0;
    517     }
    518 
    519     size_t frames_written = audio_vbuffer_write(&out->buffer, buffer, frames);
    520     pthread_cond_signal(&out->worker_wake);
    521 
    522     /* Implementation just consumes bytes if we start getting backed up */
    523     out->frames_written += frames;
    524     out->frames_rendered += frames;
    525     out->frames_total_buffered += frames;
    526 
    527     // We simulate the audio device blocking when it's write buffers become
    528     // full.
    529 
    530     // At the beginning or after an underrun, try to fill up the vbuffer.
    531     // This will be throttled by the PlaybackThread
    532     int frames_sleep = out->frames_total_buffered < out->buffer.frame_count ? 0 : frames;
    533 
    534     uint64_t sleep_time_us = frames_sleep * 1000000LL /
    535                             out_get_sample_rate(&stream->common);
    536 
    537     // If the write calls are delayed, subtract time off of the sleep to
    538     // compensate
    539     uint64_t time_since_last_write_us = now_us - out->last_write_time_us;
    540     if (time_since_last_write_us < sleep_time_us) {
    541         sleep_time_us -= time_since_last_write_us;
    542     } else {
    543         sleep_time_us = 0;
    544     }
    545     out->last_write_time_us = now_us + sleep_time_us;
    546 
    547     pthread_mutex_unlock(&out->lock);
    548 
    549     if (sleep_time_us > 0) {
    550         usleep(sleep_time_us);
    551     }
    552 
    553     if (frames_written < frames) {
    554         ALOGW("Hardware backing HAL too slow, could only write %zu of %zu frames", frames_written, frames);
    555     }
    556 
    557     /* Always consume all bytes */
    558     return bytes;
    559 }
    560 
    561 static int out_get_presentation_position(const struct audio_stream_out *stream,
    562                                    uint64_t *frames, struct timespec *timestamp)
    563 
    564 {
    565     int ret = -EINVAL;
    566     if (stream == NULL || frames == NULL || timestamp == NULL) {
    567         return -EINVAL;
    568     }
    569     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    570 
    571     pthread_mutex_lock(&out->lock);
    572     get_current_output_position(out, frames, timestamp);
    573     pthread_mutex_unlock(&out->lock);
    574 
    575     return 0;
    576 }
    577 
    578 static int out_get_render_position(const struct audio_stream_out *stream,
    579                                    uint32_t *dsp_frames)
    580 {
    581     if (stream == NULL || dsp_frames == NULL) {
    582         return -EINVAL;
    583     }
    584     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    585     pthread_mutex_lock(&out->lock);
    586     *dsp_frames = out->frames_rendered;
    587     pthread_mutex_unlock(&out->lock);
    588     return 0;
    589 }
    590 
    591 // Must be called with out->lock held
    592 static void do_out_standby(struct generic_stream_out *out)
    593 {
    594     int frames_sleep = 0;
    595     uint64_t sleep_time_us = 0;
    596     if (out->standby) {
    597         return;
    598     }
    599     while (true) {
    600         get_current_output_position(out, &out->underrun_position, NULL);
    601         frames_sleep = out->frames_written - out->underrun_position;
    602 
    603         if (frames_sleep == 0) {
    604             break;
    605         }
    606 
    607         sleep_time_us = frames_sleep * 1000000LL /
    608                         out_get_sample_rate(&out->stream.common);
    609 
    610         pthread_mutex_unlock(&out->lock);
    611         usleep(sleep_time_us);
    612         pthread_mutex_lock(&out->lock);
    613     }
    614     out->worker_standby = true;
    615     out->standby = true;
    616 }
    617 
    618 static int out_standby(struct audio_stream *stream)
    619 {
    620     struct generic_stream_out *out = (struct generic_stream_out *)stream;
    621     pthread_mutex_lock(&out->lock);
    622     do_out_standby(out);
    623     pthread_mutex_unlock(&out->lock);
    624     return 0;
    625 }
    626 
    627 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
    628 {
    629     // out_add_audio_effect is a no op
    630     return 0;
    631 }
    632 
    633 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
    634 {
    635     // out_remove_audio_effect is a no op
    636     return 0;
    637 }
    638 
    639 static int out_get_next_write_timestamp(const struct audio_stream_out *stream,
    640                                         int64_t *timestamp)
    641 {
    642     return -ENOSYS;
    643 }
    644 
    645 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
    646 {
    647     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    648     return in->req_config.sample_rate;
    649 }
    650 
    651 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
    652 {
    653     return -ENOSYS;
    654 }
    655 
    656 static int refine_output_parameters(uint32_t *sample_rate, audio_format_t *format, audio_channel_mask_t *channel_mask)
    657 {
    658     static const uint32_t sample_rates [] = {8000,11025,16000,22050,24000,32000,
    659                                             44100,48000};
    660     static const int sample_rates_count = sizeof(sample_rates)/sizeof(uint32_t);
    661     bool inval = false;
    662     if (*format != AUDIO_FORMAT_PCM_16_BIT) {
    663         *format = AUDIO_FORMAT_PCM_16_BIT;
    664         inval = true;
    665     }
    666 
    667     int channel_count = popcount(*channel_mask);
    668     if (channel_count != 1 && channel_count != 2) {
    669         *channel_mask = AUDIO_CHANNEL_IN_STEREO;
    670         inval = true;
    671     }
    672 
    673     int i;
    674     for (i = 0; i < sample_rates_count; i++) {
    675         if (*sample_rate < sample_rates[i]) {
    676             *sample_rate = sample_rates[i];
    677             inval=true;
    678             break;
    679         }
    680         else if (*sample_rate == sample_rates[i]) {
    681             break;
    682         }
    683         else if (i == sample_rates_count-1) {
    684             // Cap it to the highest rate we support
    685             *sample_rate = sample_rates[i];
    686             inval=true;
    687         }
    688     }
    689 
    690     if (inval) {
    691         return -EINVAL;
    692     }
    693     return 0;
    694 }
    695 
    696 static int check_output_parameters(uint32_t sample_rate, audio_format_t format,
    697                                   audio_channel_mask_t channel_mask)
    698 {
    699     return refine_output_parameters(&sample_rate, &format, &channel_mask);
    700 }
    701 
    702 
    703 static int refine_input_parameters(uint32_t *sample_rate, audio_format_t *format, audio_channel_mask_t *channel_mask)
    704 {
    705     static const uint32_t sample_rates [] = {8000, 11025, 16000, 22050, 44100, 48000};
    706     static const int sample_rates_count = sizeof(sample_rates)/sizeof(uint32_t);
    707     bool inval = false;
    708     // Only PCM_16_bit is supported. If this is changed, stereo to mono drop
    709     // must be fixed in in_read
    710     if (*format != AUDIO_FORMAT_PCM_16_BIT) {
    711         *format = AUDIO_FORMAT_PCM_16_BIT;
    712         inval = true;
    713     }
    714 
    715     int channel_count = popcount(*channel_mask);
    716     if (channel_count != 1 && channel_count != 2) {
    717         *channel_mask = AUDIO_CHANNEL_IN_STEREO;
    718         inval = true;
    719     }
    720 
    721     int i;
    722     for (i = 0; i < sample_rates_count; i++) {
    723         if (*sample_rate < sample_rates[i]) {
    724             *sample_rate = sample_rates[i];
    725             inval=true;
    726             break;
    727         }
    728         else if (*sample_rate == sample_rates[i]) {
    729             break;
    730         }
    731         else if (i == sample_rates_count-1) {
    732             // Cap it to the highest rate we support
    733             *sample_rate = sample_rates[i];
    734             inval=true;
    735         }
    736     }
    737 
    738     if (inval) {
    739         return -EINVAL;
    740     }
    741     return 0;
    742 }
    743 
    744 static int check_input_parameters(uint32_t sample_rate, audio_format_t format,
    745                                   audio_channel_mask_t channel_mask)
    746 {
    747     return refine_input_parameters(&sample_rate, &format, &channel_mask);
    748 }
    749 
    750 static size_t get_input_buffer_size(uint32_t sample_rate, audio_format_t format,
    751                                     audio_channel_mask_t channel_mask)
    752 {
    753     size_t size;
    754     size_t device_rate;
    755     int channel_count = popcount(channel_mask);
    756     if (check_input_parameters(sample_rate, format, channel_mask) != 0)
    757         return 0;
    758 
    759     size = sample_rate*IN_PERIOD_MS/1000;
    760     // Audioflinger expects audio buffers to be multiple of 16 frames
    761     size = ((size + 15) / 16) * 16;
    762     size *= sizeof(short) * channel_count;
    763 
    764     return size;
    765 }
    766 
    767 
    768 static size_t in_get_buffer_size(const struct audio_stream *stream)
    769 {
    770     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    771     int size = get_input_buffer_size(in->req_config.sample_rate,
    772                                  in->req_config.format,
    773                                  in->req_config.channel_mask);
    774 
    775     return size;
    776 }
    777 
    778 static audio_channel_mask_t in_get_channels(const struct audio_stream *stream)
    779 {
    780     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    781     return in->req_config.channel_mask;
    782 }
    783 
    784 static audio_format_t in_get_format(const struct audio_stream *stream)
    785 {
    786     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    787     return in->req_config.format;
    788 }
    789 
    790 static int in_set_format(struct audio_stream *stream, audio_format_t format)
    791 {
    792     return -ENOSYS;
    793 }
    794 
    795 static int in_dump(const struct audio_stream *stream, int fd)
    796 {
    797     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    798 
    799     pthread_mutex_lock(&in->lock);
    800     dprintf(fd, "\tin_dump:\n"
    801                 "\t\tsample rate: %u\n"
    802                 "\t\tbuffer size: %zu\n"
    803                 "\t\tchannel mask: %08x\n"
    804                 "\t\tformat: %d\n"
    805                 "\t\tdevice: %08x\n"
    806                 "\t\taudio dev: %p\n\n",
    807                 in_get_sample_rate(stream),
    808                 in_get_buffer_size(stream),
    809                 in_get_channels(stream),
    810                 in_get_format(stream),
    811                 in->device,
    812                 in->dev);
    813     pthread_mutex_unlock(&in->lock);
    814     return 0;
    815 }
    816 
    817 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
    818 {
    819     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    820     struct str_parms *parms;
    821     char value[32];
    822     int ret;
    823     long val;
    824     char *end;
    825 
    826     pthread_mutex_lock(&in->lock);
    827     if (!in->standby) {
    828         ret = -ENOSYS;
    829     } else {
    830         parms = str_parms_create_str(kvpairs);
    831 
    832         ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING,
    833                                 value, sizeof(value));
    834         if (ret >= 0) {
    835             errno = 0;
    836             val = strtol(value, &end, 10);
    837             if ((errno == 0) && (end != NULL) && (*end == '\0') && ((int)val == val)) {
    838                 in->device = (int)val;
    839                 ret = 0;
    840             } else {
    841                 ret = -EINVAL;
    842             }
    843         }
    844 
    845         str_parms_destroy(parms);
    846     }
    847     pthread_mutex_unlock(&in->lock);
    848     return ret;
    849 }
    850 
    851 static char * in_get_parameters(const struct audio_stream *stream,
    852                                 const char *keys)
    853 {
    854     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    855     struct str_parms *query = str_parms_create_str(keys);
    856     char *str;
    857     char value[256];
    858     struct str_parms *reply = str_parms_create();
    859     int ret;
    860 
    861     ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
    862     if (ret >= 0) {
    863         str_parms_add_int(reply, AUDIO_PARAMETER_STREAM_ROUTING, in->device);
    864         str = strdup(str_parms_to_str(reply));
    865     } else {
    866         str = strdup(keys);
    867     }
    868 
    869     str_parms_destroy(query);
    870     str_parms_destroy(reply);
    871     return str;
    872 }
    873 
    874 static int in_set_gain(struct audio_stream_in *stream, float gain)
    875 {
    876     // in_set_gain is a no op
    877     return 0;
    878 }
    879 
    880 // Call with in->lock held
    881 static void get_current_input_position(struct generic_stream_in *in,
    882                                        int64_t * position,
    883                                        struct timespec * timestamp) {
    884     struct timespec t = { .tv_sec = 0, .tv_nsec = 0 };
    885     clock_gettime(CLOCK_MONOTONIC, &t);
    886     const int64_t now_us = (t.tv_sec * 1000000000LL + t.tv_nsec) / 1000;
    887     if (timestamp) {
    888         *timestamp = t;
    889     }
    890     int64_t position_since_standby;
    891     if (in->standby) {
    892         position_since_standby = 0;
    893     } else {
    894         const int64_t first_us = (in->standby_exit_time.tv_sec * 1000000000LL +
    895                                   in->standby_exit_time.tv_nsec) / 1000;
    896         position_since_standby = (now_us - first_us) *
    897                 in_get_sample_rate(&in->stream.common) /
    898                 1000000;
    899         if (position_since_standby < 0) {
    900             position_since_standby = 0;
    901         }
    902     }
    903     *position = in->standby_position + position_since_standby;
    904 }
    905 
    906 // Must be called with in->lock held
    907 static void do_in_standby(struct generic_stream_in *in)
    908 {
    909     if (in->standby) {
    910         return;
    911     }
    912     in->worker_standby = true;
    913     get_current_input_position(in, &in->standby_position, NULL);
    914     in->standby = true;
    915 }
    916 
    917 static int in_standby(struct audio_stream *stream)
    918 {
    919     struct generic_stream_in *in = (struct generic_stream_in *)stream;
    920     pthread_mutex_lock(&in->lock);
    921     do_in_standby(in);
    922     pthread_mutex_unlock(&in->lock);
    923     return 0;
    924 }
    925 
    926 static void *in_read_worker(void * args)
    927 {
    928     struct generic_stream_in *in = (struct generic_stream_in *)args;
    929     struct pcm *pcm = NULL;
    930     uint8_t *buffer = NULL;
    931     size_t buffer_frames;
    932     int buffer_size;
    933 
    934     bool restart = false;
    935     bool shutdown = false;
    936     while (true) {
    937         pthread_mutex_lock(&in->lock);
    938         while (in->worker_standby || restart) {
    939             restart = false;
    940             if (pcm) {
    941                 pcm_close(pcm); // Frees pcm
    942                 pcm = NULL;
    943                 free(buffer);
    944                 buffer=NULL;
    945             }
    946             if (in->worker_exit) {
    947                 break;
    948             }
    949             pthread_cond_wait(&in->worker_wake, &in->lock);
    950         }
    951 
    952         if (in->worker_exit) {
    953             if (!in->worker_standby) {
    954                 ALOGE("In worker not in standby before exiting");
    955             }
    956             shutdown = true;
    957         }
    958         if (shutdown) {
    959             pthread_mutex_unlock(&in->lock);
    960             break;
    961         }
    962         if (!pcm) {
    963             pcm = pcm_open(PCM_CARD, PCM_DEVICE,
    964                           PCM_IN | PCM_MONOTONIC, &in->pcm_config);
    965             if (!pcm_is_ready(pcm)) {
    966                 ALOGE("pcm_open(in) failed: %s: channels %d format %d rate %d",
    967                   pcm_get_error(pcm),
    968                   in->pcm_config.channels,
    969                   in->pcm_config.format,
    970                   in->pcm_config.rate
    971                    );
    972                 pthread_mutex_unlock(&in->lock);
    973                 break;
    974             }
    975             buffer_frames = in->pcm_config.period_size;
    976             buffer_size = pcm_frames_to_bytes(pcm, buffer_frames);
    977             buffer = malloc(buffer_size);
    978             if (!buffer) {
    979                 ALOGE("could not allocate worker read buffer");
    980                 pthread_mutex_unlock(&in->lock);
    981                 break;
    982             }
    983         }
    984         pthread_mutex_unlock(&in->lock);
    985         int ret = pcm_read(pcm, buffer, pcm_frames_to_bytes(pcm, buffer_frames));
    986         if (ret != 0) {
    987             ALOGW("pcm_read failed %s", pcm_get_error(pcm));
    988             restart = true;
    989         }
    990 
    991         pthread_mutex_lock(&in->lock);
    992         size_t frames_written = audio_vbuffer_write(&in->buffer, buffer, buffer_frames);
    993         pthread_mutex_unlock(&in->lock);
    994 
    995         if (frames_written != buffer_frames) {
    996             ALOGW("in_read_worker only could write %zu / %zu frames", frames_written, buffer_frames);
    997         }
    998     }
    999     if (buffer) {
   1000         free(buffer);
   1001     }
   1002     return NULL;
   1003 }
   1004 
   1005 static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
   1006                        size_t bytes)
   1007 {
   1008     struct generic_stream_in *in = (struct generic_stream_in *)stream;
   1009     struct generic_audio_device *adev = in->dev;
   1010     const size_t frames =  bytes / audio_stream_in_frame_size(stream);
   1011     int ret = 0;
   1012     bool mic_mute = false;
   1013     size_t read_bytes = 0;
   1014 
   1015     adev_get_mic_mute(&adev->device, &mic_mute);
   1016     pthread_mutex_lock(&in->lock);
   1017 
   1018     if (in->worker_standby) {
   1019         in->worker_standby = false;
   1020     }
   1021     pthread_cond_signal(&in->worker_wake);
   1022 
   1023     int64_t current_position;
   1024     struct timespec current_time;
   1025 
   1026     get_current_input_position(in, &current_position, &current_time);
   1027     if (in->standby) {
   1028         in->standby = false;
   1029         in->standby_exit_time = current_time;
   1030         in->standby_frames_read = 0;
   1031     }
   1032 
   1033     const int64_t frames_available = current_position - in->standby_position - in->standby_frames_read;
   1034     assert(frames_available >= 0);
   1035 
   1036     const size_t frames_wait = ((uint64_t)frames_available > frames) ? 0 : frames - frames_available;
   1037 
   1038     int64_t sleep_time_us  = frames_wait * 1000000LL /
   1039                              in_get_sample_rate(&stream->common);
   1040 
   1041     pthread_mutex_unlock(&in->lock);
   1042 
   1043     if (sleep_time_us > 0) {
   1044         usleep(sleep_time_us);
   1045     }
   1046 
   1047     pthread_mutex_lock(&in->lock);
   1048     int read_frames = 0;
   1049     if (in->standby) {
   1050         ALOGW("Input put to sleep while read in progress");
   1051         goto exit;
   1052     }
   1053     in->standby_frames_read += frames;
   1054 
   1055     if (popcount(in->req_config.channel_mask) == 1 &&
   1056         in->pcm_config.channels == 2) {
   1057         // Need to resample to mono
   1058         if (in->stereo_to_mono_buf_size < bytes*2) {
   1059             in->stereo_to_mono_buf = realloc(in->stereo_to_mono_buf,
   1060                                              bytes*2);
   1061             if (!in->stereo_to_mono_buf) {
   1062                 ALOGE("Failed to allocate stereo_to_mono_buff");
   1063                 goto exit;
   1064             }
   1065         }
   1066 
   1067         read_frames = audio_vbuffer_read(&in->buffer, in->stereo_to_mono_buf, frames);
   1068 
   1069         // Currently only pcm 16 is supported.
   1070         uint16_t *src = (uint16_t *)in->stereo_to_mono_buf;
   1071         uint16_t *dst = (uint16_t *)buffer;
   1072         size_t i;
   1073         // Resample stereo 16 to mono 16 by dropping one channel.
   1074         // The stereo stream is interleaved L-R-L-R
   1075         for (i = 0; i < frames; i++) {
   1076             *dst = *src;
   1077             src += 2;
   1078             dst += 1;
   1079         }
   1080     } else {
   1081         read_frames = audio_vbuffer_read(&in->buffer, buffer, frames);
   1082     }
   1083 
   1084 exit:
   1085     read_bytes = read_frames*audio_stream_in_frame_size(stream);
   1086 
   1087     if (mic_mute) {
   1088         read_bytes = 0;
   1089     }
   1090 
   1091     if (read_bytes < bytes) {
   1092         memset (&((uint8_t *)buffer)[read_bytes], 0, bytes-read_bytes);
   1093     }
   1094 
   1095     pthread_mutex_unlock(&in->lock);
   1096 
   1097     return bytes;
   1098 }
   1099 
   1100 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
   1101 {
   1102     return 0;
   1103 }
   1104 
   1105 static int in_get_capture_position(const struct audio_stream_in *stream,
   1106                                 int64_t *frames, int64_t *time)
   1107 {
   1108     struct generic_stream_in *in = (struct generic_stream_in *)stream;
   1109     pthread_mutex_lock(&in->lock);
   1110     struct timespec current_time;
   1111     get_current_input_position(in, frames, &current_time);
   1112     *time = (current_time.tv_sec * 1000000000LL + current_time.tv_nsec);
   1113     pthread_mutex_unlock(&in->lock);
   1114     return 0;
   1115 }
   1116 
   1117 static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
   1118 {
   1119     // in_add_audio_effect is a no op
   1120     return 0;
   1121 }
   1122 
   1123 static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
   1124 {
   1125     // in_add_audio_effect is a no op
   1126     return 0;
   1127 }
   1128 
   1129 static int adev_open_output_stream(struct audio_hw_device *dev,
   1130                                    audio_io_handle_t handle,
   1131                                    audio_devices_t devices,
   1132                                    audio_output_flags_t flags,
   1133                                    struct audio_config *config,
   1134                                    struct audio_stream_out **stream_out,
   1135                                    const char *address __unused)
   1136 {
   1137     struct generic_audio_device *adev = (struct generic_audio_device *)dev;
   1138     struct generic_stream_out *out;
   1139     int ret = 0;
   1140 
   1141     if (refine_output_parameters(&config->sample_rate, &config->format, &config->channel_mask)) {
   1142         ALOGE("Error opening output stream format %d, channel_mask %04x, sample_rate %u",
   1143               config->format, config->channel_mask, config->sample_rate);
   1144         ret = -EINVAL;
   1145         goto error;
   1146     }
   1147 
   1148     out = (struct generic_stream_out *)calloc(1, sizeof(struct generic_stream_out));
   1149 
   1150     if (!out)
   1151         return -ENOMEM;
   1152 
   1153     out->stream.common.get_sample_rate = out_get_sample_rate;
   1154     out->stream.common.set_sample_rate = out_set_sample_rate;
   1155     out->stream.common.get_buffer_size = out_get_buffer_size;
   1156     out->stream.common.get_channels = out_get_channels;
   1157     out->stream.common.get_format = out_get_format;
   1158     out->stream.common.set_format = out_set_format;
   1159     out->stream.common.standby = out_standby;
   1160     out->stream.common.dump = out_dump;
   1161     out->stream.common.set_parameters = out_set_parameters;
   1162     out->stream.common.get_parameters = out_get_parameters;
   1163     out->stream.common.add_audio_effect = out_add_audio_effect;
   1164     out->stream.common.remove_audio_effect = out_remove_audio_effect;
   1165     out->stream.get_latency = out_get_latency;
   1166     out->stream.set_volume = out_set_volume;
   1167     out->stream.write = out_write;
   1168     out->stream.get_render_position = out_get_render_position;
   1169     out->stream.get_presentation_position = out_get_presentation_position;
   1170     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
   1171 
   1172     pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
   1173     out->dev = adev;
   1174     out->device = devices;
   1175     memcpy(&out->req_config, config, sizeof(struct audio_config));
   1176     memcpy(&out->pcm_config, &pcm_config_out, sizeof(struct pcm_config));
   1177     out->pcm_config.rate = config->sample_rate;
   1178     out->pcm_config.period_size = out->pcm_config.rate*OUT_PERIOD_MS/1000;
   1179 
   1180     out->standby = true;
   1181     out->underrun_position = 0;
   1182     out->underrun_time.tv_sec = 0;
   1183     out->underrun_time.tv_nsec = 0;
   1184     out->last_write_time_us = 0;
   1185     out->frames_total_buffered = 0;
   1186     out->frames_written = 0;
   1187     out->frames_rendered = 0;
   1188 
   1189     ret = audio_vbuffer_init(&out->buffer,
   1190                       out->pcm_config.period_size*out->pcm_config.period_count,
   1191                       out->pcm_config.channels *
   1192                       pcm_format_to_bits(out->pcm_config.format) >> 3);
   1193     if (ret == 0) {
   1194         pthread_cond_init(&out->worker_wake, NULL);
   1195         out->worker_standby = true;
   1196         out->worker_exit = false;
   1197         pthread_create(&out->worker_thread, NULL, out_write_worker, out);
   1198 
   1199     }
   1200     *stream_out = &out->stream;
   1201 
   1202 
   1203 error:
   1204 
   1205     return ret;
   1206 }
   1207 
   1208 static void adev_close_output_stream(struct audio_hw_device *dev,
   1209                                      struct audio_stream_out *stream)
   1210 {
   1211     struct generic_stream_out *out = (struct generic_stream_out *)stream;
   1212     pthread_mutex_lock(&out->lock);
   1213     do_out_standby(out);
   1214 
   1215     out->worker_exit = true;
   1216     pthread_cond_signal(&out->worker_wake);
   1217     pthread_mutex_unlock(&out->lock);
   1218 
   1219     pthread_join(out->worker_thread, NULL);
   1220     pthread_mutex_destroy(&out->lock);
   1221     audio_vbuffer_destroy(&out->buffer);
   1222     free(stream);
   1223 }
   1224 
   1225 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
   1226 {
   1227     return 0;
   1228 }
   1229 
   1230 static char * adev_get_parameters(const struct audio_hw_device *dev,
   1231                                   const char *keys)
   1232 {
   1233     return strdup("");
   1234 }
   1235 
   1236 static int adev_init_check(const struct audio_hw_device *dev)
   1237 {
   1238     return 0;
   1239 }
   1240 
   1241 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
   1242 {
   1243     // adev_set_voice_volume is a no op (simulates phones)
   1244     return 0;
   1245 }
   1246 
   1247 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
   1248 {
   1249     return -ENOSYS;
   1250 }
   1251 
   1252 static int adev_get_master_volume(struct audio_hw_device *dev, float *volume)
   1253 {
   1254     return -ENOSYS;
   1255 }
   1256 
   1257 static int adev_set_master_mute(struct audio_hw_device *dev, bool muted)
   1258 {
   1259     return -ENOSYS;
   1260 }
   1261 
   1262 static int adev_get_master_mute(struct audio_hw_device *dev, bool *muted)
   1263 {
   1264     return -ENOSYS;
   1265 }
   1266 
   1267 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
   1268 {
   1269     // adev_set_mode is a no op (simulates phones)
   1270     return 0;
   1271 }
   1272 
   1273 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
   1274 {
   1275     struct generic_audio_device *adev = (struct generic_audio_device *)dev;
   1276     pthread_mutex_lock(&adev->lock);
   1277     adev->mic_mute = state;
   1278     pthread_mutex_unlock(&adev->lock);
   1279     return 0;
   1280 }
   1281 
   1282 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
   1283 {
   1284     struct generic_audio_device *adev = (struct generic_audio_device *)dev;
   1285     pthread_mutex_lock(&adev->lock);
   1286     *state = adev->mic_mute;
   1287     pthread_mutex_unlock(&adev->lock);
   1288     return 0;
   1289 }
   1290 
   1291 
   1292 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
   1293                                          const struct audio_config *config)
   1294 {
   1295     return get_input_buffer_size(config->sample_rate, config->format, config->channel_mask);
   1296 }
   1297 
   1298 
   1299 static void adev_close_input_stream(struct audio_hw_device *dev,
   1300                                    struct audio_stream_in *stream)
   1301 {
   1302     struct generic_stream_in *in = (struct generic_stream_in *)stream;
   1303     pthread_mutex_lock(&in->lock);
   1304     do_in_standby(in);
   1305 
   1306     in->worker_exit = true;
   1307     pthread_cond_signal(&in->worker_wake);
   1308     pthread_mutex_unlock(&in->lock);
   1309     pthread_join(in->worker_thread, NULL);
   1310 
   1311     if (in->stereo_to_mono_buf != NULL) {
   1312         free(in->stereo_to_mono_buf);
   1313         in->stereo_to_mono_buf_size = 0;
   1314     }
   1315 
   1316     pthread_mutex_destroy(&in->lock);
   1317     audio_vbuffer_destroy(&in->buffer);
   1318     free(stream);
   1319 }
   1320 
   1321 
   1322 static int adev_open_input_stream(struct audio_hw_device *dev,
   1323                                   audio_io_handle_t handle,
   1324                                   audio_devices_t devices,
   1325                                   struct audio_config *config,
   1326                                   struct audio_stream_in **stream_in,
   1327                                   audio_input_flags_t flags __unused,
   1328                                   const char *address __unused,
   1329                                   audio_source_t source __unused)
   1330 {
   1331     struct generic_audio_device *adev = (struct generic_audio_device *)dev;
   1332     struct generic_stream_in *in;
   1333     int ret = 0;
   1334     if (refine_input_parameters(&config->sample_rate, &config->format, &config->channel_mask)) {
   1335         ALOGE("Error opening input stream format %d, channel_mask %04x, sample_rate %u",
   1336               config->format, config->channel_mask, config->sample_rate);
   1337         ret = -EINVAL;
   1338         goto error;
   1339     }
   1340 
   1341     in = (struct generic_stream_in *)calloc(1, sizeof(struct generic_stream_in));
   1342     if (!in) {
   1343         ret = -ENOMEM;
   1344         goto error;
   1345     }
   1346 
   1347     in->stream.common.get_sample_rate = in_get_sample_rate;
   1348     in->stream.common.set_sample_rate = in_set_sample_rate;         // no op
   1349     in->stream.common.get_buffer_size = in_get_buffer_size;
   1350     in->stream.common.get_channels = in_get_channels;
   1351     in->stream.common.get_format = in_get_format;
   1352     in->stream.common.set_format = in_set_format;                   // no op
   1353     in->stream.common.standby = in_standby;
   1354     in->stream.common.dump = in_dump;
   1355     in->stream.common.set_parameters = in_set_parameters;
   1356     in->stream.common.get_parameters = in_get_parameters;
   1357     in->stream.common.add_audio_effect = in_add_audio_effect;       // no op
   1358     in->stream.common.remove_audio_effect = in_remove_audio_effect; // no op
   1359     in->stream.set_gain = in_set_gain;                              // no op
   1360     in->stream.read = in_read;
   1361     in->stream.get_input_frames_lost = in_get_input_frames_lost;    // no op
   1362     in->stream.get_capture_position = in_get_capture_position;
   1363 
   1364     pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
   1365     in->dev = adev;
   1366     in->device = devices;
   1367     memcpy(&in->req_config, config, sizeof(struct audio_config));
   1368     memcpy(&in->pcm_config, &pcm_config_in, sizeof(struct pcm_config));
   1369     in->pcm_config.rate = config->sample_rate;
   1370     in->pcm_config.period_size = in->pcm_config.rate*IN_PERIOD_MS/1000;
   1371 
   1372     in->stereo_to_mono_buf = NULL;
   1373     in->stereo_to_mono_buf_size = 0;
   1374 
   1375     in->standby = true;
   1376     in->standby_position = 0;
   1377     in->standby_exit_time.tv_sec = 0;
   1378     in->standby_exit_time.tv_nsec = 0;
   1379     in->standby_frames_read = 0;
   1380 
   1381     ret = audio_vbuffer_init(&in->buffer,
   1382                       in->pcm_config.period_size*in->pcm_config.period_count,
   1383                       in->pcm_config.channels *
   1384                       pcm_format_to_bits(in->pcm_config.format) >> 3);
   1385     if (ret == 0) {
   1386         pthread_cond_init(&in->worker_wake, NULL);
   1387         in->worker_standby = true;
   1388         in->worker_exit = false;
   1389         pthread_create(&in->worker_thread, NULL, in_read_worker, in);
   1390     }
   1391 
   1392     *stream_in = &in->stream;
   1393 
   1394 error:
   1395     return ret;
   1396 }
   1397 
   1398 
   1399 static int adev_dump(const audio_hw_device_t *dev, int fd)
   1400 {
   1401     return 0;
   1402 }
   1403 
   1404 static int adev_close(hw_device_t *dev)
   1405 {
   1406     struct generic_audio_device *adev = (struct generic_audio_device *)dev;
   1407     int ret = 0;
   1408     if (!adev)
   1409         return 0;
   1410 
   1411     pthread_mutex_lock(&adev_init_lock);
   1412 
   1413     if (audio_device_ref_count == 0) {
   1414         ALOGE("adev_close called when ref_count 0");
   1415         ret = -EINVAL;
   1416         goto error;
   1417     }
   1418 
   1419     if ((--audio_device_ref_count) == 0) {
   1420         if (adev->mixer) {
   1421             mixer_close(adev->mixer);
   1422         }
   1423         free(adev);
   1424     }
   1425 
   1426 error:
   1427     pthread_mutex_unlock(&adev_init_lock);
   1428     return ret;
   1429 }
   1430 
   1431 static int adev_open(const hw_module_t* module, const char* name,
   1432                      hw_device_t** device)
   1433 {
   1434     static struct generic_audio_device *adev;
   1435 
   1436     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
   1437         return -EINVAL;
   1438 
   1439     pthread_once(&sFallbackOnce, fallback_init);
   1440     if (sFallback != NULL) {
   1441         return sFallback->common.methods->open(&sFallback->common, name, device);
   1442     }
   1443 
   1444     pthread_mutex_lock(&adev_init_lock);
   1445     if (audio_device_ref_count != 0) {
   1446         *device = &adev->device.common;
   1447         audio_device_ref_count++;
   1448         ALOGV("%s: returning existing instance of adev", __func__);
   1449         ALOGV("%s: exit", __func__);
   1450         goto unlock;
   1451     }
   1452     adev = calloc(1, sizeof(struct generic_audio_device));
   1453 
   1454     pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
   1455 
   1456     adev->device.common.tag = HARDWARE_DEVICE_TAG;
   1457     adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
   1458     adev->device.common.module = (struct hw_module_t *) module;
   1459     adev->device.common.close = adev_close;
   1460 
   1461     adev->device.init_check = adev_init_check;               // no op
   1462     adev->device.set_voice_volume = adev_set_voice_volume;   // no op
   1463     adev->device.set_master_volume = adev_set_master_volume; // no op
   1464     adev->device.get_master_volume = adev_get_master_volume; // no op
   1465     adev->device.set_master_mute = adev_set_master_mute;     // no op
   1466     adev->device.get_master_mute = adev_get_master_mute;     // no op
   1467     adev->device.set_mode = adev_set_mode;                   // no op
   1468     adev->device.set_mic_mute = adev_set_mic_mute;
   1469     adev->device.get_mic_mute = adev_get_mic_mute;
   1470     adev->device.set_parameters = adev_set_parameters;       // no op
   1471     adev->device.get_parameters = adev_get_parameters;       // no op
   1472     adev->device.get_input_buffer_size = adev_get_input_buffer_size;
   1473     adev->device.open_output_stream = adev_open_output_stream;
   1474     adev->device.close_output_stream = adev_close_output_stream;
   1475     adev->device.open_input_stream = adev_open_input_stream;
   1476     adev->device.close_input_stream = adev_close_input_stream;
   1477     adev->device.dump = adev_dump;
   1478 
   1479     *device = &adev->device.common;
   1480 
   1481     adev->mixer = mixer_open(PCM_CARD);
   1482     struct mixer_ctl *ctl;
   1483 
   1484     // Set default mixer ctls
   1485     // Enable channels and set volume
   1486     for (int i = 0; i < (int)mixer_get_num_ctls(adev->mixer); i++) {
   1487         ctl = mixer_get_ctl(adev->mixer, i);
   1488         ALOGD("mixer %d name %s", i, mixer_ctl_get_name(ctl));
   1489         if (!strcmp(mixer_ctl_get_name(ctl), "Master Playback Volume") ||
   1490             !strcmp(mixer_ctl_get_name(ctl), "Capture Volume")) {
   1491             for (int z = 0; z < (int)mixer_ctl_get_num_values(ctl); z++) {
   1492                 ALOGD("set ctl %d to %d", z, 100);
   1493                 mixer_ctl_set_percent(ctl, z, 100);
   1494             }
   1495             continue;
   1496         }
   1497         if (!strcmp(mixer_ctl_get_name(ctl), "Master Playback Switch") ||
   1498             !strcmp(mixer_ctl_get_name(ctl), "Capture Switch")) {
   1499             for (int z = 0; z < (int)mixer_ctl_get_num_values(ctl); z++) {
   1500                 ALOGD("set ctl %d to %d", z, 1);
   1501                 mixer_ctl_set_value(ctl, z, 1);
   1502             }
   1503             continue;
   1504         }
   1505     }
   1506 
   1507     audio_device_ref_count++;
   1508 
   1509 unlock:
   1510     pthread_mutex_unlock(&adev_init_lock);
   1511     return 0;
   1512 }
   1513 
   1514 static struct hw_module_methods_t hal_module_methods = {
   1515     .open = adev_open,
   1516 };
   1517 
   1518 struct audio_module HAL_MODULE_INFO_SYM = {
   1519     .common = {
   1520         .tag = HARDWARE_MODULE_TAG,
   1521         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
   1522         .hal_api_version = HARDWARE_HAL_API_VERSION,
   1523         .id = AUDIO_HARDWARE_MODULE_ID,
   1524         .name = "Generic audio HW HAL",
   1525         .author = "The Android Open Source Project",
   1526         .methods = &hal_module_methods,
   1527     },
   1528 };
   1529 
   1530 /* This function detects whether or not we should be using an alsa audio device
   1531  * or fall back to the legacy goldfish_audio driver.
   1532  */
   1533 static void
   1534 fallback_init(void)
   1535 {
   1536     void* module;
   1537 
   1538     FILE *fptr = fopen ("/proc/asound/pcm", "r");
   1539     if (fptr != NULL) {
   1540       // asound/pcm is empty if there are no devices
   1541       int c = fgetc(fptr);
   1542       fclose(fptr);
   1543       if (c != EOF) {
   1544           ALOGD("Emulator host-side ALSA audio emulation detected.");
   1545           return;
   1546       }
   1547     }
   1548 
   1549     ALOGD("Emulator without host-side ALSA audio emulation detected.");
   1550 #if __LP64__
   1551     module = dlopen("/system/lib64/hw/audio.primary.goldfish_legacy.so",
   1552                     RTLD_LAZY|RTLD_LOCAL);
   1553 #else
   1554     module = dlopen("/system/lib/hw/audio.primary.goldfish_legacy.so",
   1555                     RTLD_LAZY|RTLD_LOCAL);
   1556 #endif
   1557     if (module != NULL) {
   1558         sFallback = (struct audio_module *)(dlsym(module, HAL_MODULE_INFO_SYM_AS_STR));
   1559         if (sFallback == NULL) {
   1560             dlclose(module);
   1561         }
   1562     }
   1563     if (sFallback == NULL) {
   1564         ALOGE("Could not find legacy fallback module!?");
   1565     }
   1566 }
   1567