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