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