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