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