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_cond_signal(&out->write_wake);
372 pthread_mutex_unlock(&out->lock);
373
374 if (is_zone_selected_to_play(&out->dev->device, zone_id)) {
375 int write_error = ext_pcm_write(ext_pcm, out->bus_address,
376 buffer, ext_pcm_frames_to_bytes(ext_pcm, frames));
377 if (write_error) {
378 ALOGE("pcm_write failed %s address %s",
379 ext_pcm_get_error(ext_pcm), out->bus_address);
380 restart = true;
381 } else {
382 ALOGV("pcm_write succeed address %s", out->bus_address);
383 }
384 }
385 }
386 if (buffer) {
387 free(buffer);
388 }
389
390 return NULL;
391 }
392
393 // Call with out->lock held
get_current_output_position(struct generic_stream_out * out,uint64_t * position,struct timespec * timestamp)394 static void get_current_output_position(struct generic_stream_out *out,
395 uint64_t *position, struct timespec * timestamp) {
396 struct timespec curtime = { .tv_sec = 0, .tv_nsec = 0 };
397 clock_gettime(CLOCK_MONOTONIC, &curtime);
398 const int64_t now_us = (curtime.tv_sec * 1000000000LL + curtime.tv_nsec) / 1000;
399 if (timestamp) {
400 *timestamp = curtime;
401 }
402 int64_t position_since_underrun;
403 if (out->standby) {
404 position_since_underrun = 0;
405 } else {
406 const int64_t first_us = (out->underrun_time.tv_sec * 1000000000LL +
407 out->underrun_time.tv_nsec) / 1000;
408 position_since_underrun = (now_us - first_us) *
409 out_get_sample_rate(&out->stream.common) /
410 1000000;
411 if (position_since_underrun < 0) {
412 position_since_underrun = 0;
413 }
414 }
415 *position = out->underrun_position + position_since_underrun;
416
417 // The device will reuse the same output stream leading to periods of
418 // underrun.
419 if (*position > out->frames_written) {
420 ALOGW("Not supplying enough data to HAL, expected position %" PRIu64 " , only wrote "
421 "%" PRIu64,
422 *position, out->frames_written);
423
424 *position = out->frames_written;
425 out->underrun_position = *position;
426 out->underrun_time = curtime;
427 out->frames_total_buffered = 0;
428 }
429 }
430
431 // 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)432 static void out_apply_gain(struct generic_stream_out *out, const void *buffer, size_t bytes) {
433 int16_t *int16_buffer = (int16_t *)buffer;
434 size_t int16_size = bytes / sizeof(int16_t);
435 for (int i = 0; i < int16_size; i++) {
436 if ((i % 2) && !(out->enabled_channels & RIGHT_CHANNEL)) {
437 int16_buffer[i] = 0;
438 } else if (!(i % 2) && !(out->enabled_channels & LEFT_CHANNEL)) {
439 int16_buffer[i] = 0;
440 } else {
441 float multiplied = int16_buffer[i] * out->amplitude_ratio;
442 if (multiplied > INT16_MAX) int16_buffer[i] = INT16_MAX;
443 else if (multiplied < INT16_MIN) int16_buffer[i] = INT16_MIN;
444 else int16_buffer[i] = (int16_t)multiplied;
445 }
446 }
447 }
448
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)449 static ssize_t out_write(struct audio_stream_out *stream, const void *buffer, size_t bytes) {
450 struct generic_stream_out *out = (struct generic_stream_out *)stream;
451 ALOGV("%s: to device %s", __func__, out->bus_address);
452 const size_t frame_size = audio_stream_out_frame_size(stream);
453 const size_t frames = bytes / frame_size;
454
455 pthread_mutex_lock(&out->lock);
456
457 if (out->worker_standby) {
458 out->worker_standby = false;
459 }
460
461 uint64_t current_position;
462 struct timespec current_time;
463
464 get_current_output_position(out, ¤t_position, ¤t_time);
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
474 const int available_frames_in_buffer = audio_vbuffer_dead(&out->buffer);
475 const int frames_sleep =
476 available_frames_in_buffer > frames ? 0 : frames - available_frames_in_buffer;
477 const uint64_t sleep_time_us =
478 frames_sleep * 1000000LL / out_get_sample_rate(&stream->common);
479
480 if (sleep_time_us > 0) {
481 pthread_mutex_unlock(&out->lock);
482 usleep(sleep_time_us);
483 pthread_mutex_lock(&out->lock);
484 }
485
486 if (out->dev->main_mute) {
487 ALOGV("%s: ignored due to main mute", __func__);
488 } else {
489 out_apply_gain(out, buffer, bytes);
490 frames_written = 0;
491
492 bool write_incomplete = true;
493 do {
494 frames_written += audio_vbuffer_write(
495 &out->buffer,
496 (const char *)buffer + frames_written * frame_size,
497 frames - frames_written);
498 pthread_cond_signal(&out->worker_wake);
499 write_incomplete = frames_written < frames;
500 if (write_incomplete) {
501 // Wait for write worker to consume the buffer
502 pthread_cond_wait(&out->write_wake, &out->lock);
503 }
504 } while (write_incomplete);
505 }
506
507 /* Implementation just consumes bytes if we start getting backed up */
508 out->frames_written += frames;
509 out->frames_rendered += frames;
510 out->frames_total_buffered += frames;
511
512 pthread_mutex_unlock(&out->lock);
513
514 if (frames_written < frames) {
515 ALOGW("%s Hardware backing HAL too slow, could only write %zu of %zu frames",
516 __func__, frames_written, frames);
517 }
518
519 /* Always consume all bytes */
520 return bytes;
521 }
522
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)523 static int out_get_presentation_position(const struct audio_stream_out *stream,
524 uint64_t *frames, struct timespec *timestamp) {
525 if (stream == NULL || frames == NULL || timestamp == NULL) {
526 return -EINVAL;
527 }
528 struct generic_stream_out *out = (struct generic_stream_out *)stream;
529
530 pthread_mutex_lock(&out->lock);
531 get_current_output_position(out, frames, timestamp);
532 pthread_mutex_unlock(&out->lock);
533
534 return 0;
535 }
536
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)537 static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames) {
538 if (stream == NULL || dsp_frames == NULL) {
539 return -EINVAL;
540 }
541 struct generic_stream_out *out = (struct generic_stream_out *)stream;
542 pthread_mutex_lock(&out->lock);
543 *dsp_frames = out->frames_rendered;
544 pthread_mutex_unlock(&out->lock);
545 return 0;
546 }
547
548 // Must be called with out->lock held
do_out_standby(struct generic_stream_out * out)549 static void do_out_standby(struct generic_stream_out *out) {
550 int frames_sleep = 0;
551 uint64_t sleep_time_us = 0;
552 if (out->standby) {
553 return;
554 }
555 while (true) {
556 get_current_output_position(out, &out->underrun_position, NULL);
557 frames_sleep = out->frames_written - out->underrun_position;
558
559 if (frames_sleep == 0) {
560 break;
561 }
562
563 sleep_time_us = frames_sleep * 1000000LL /
564 out_get_sample_rate(&out->stream.common);
565
566 pthread_mutex_unlock(&out->lock);
567 usleep(sleep_time_us);
568 pthread_mutex_lock(&out->lock);
569 }
570 out->worker_standby = true;
571 out->standby = true;
572 }
573
out_standby(struct audio_stream * stream)574 static int out_standby(struct audio_stream *stream) {
575 struct generic_stream_out *out = (struct generic_stream_out *)stream;
576 pthread_mutex_lock(&out->lock);
577 do_out_standby(out);
578 pthread_mutex_unlock(&out->lock);
579 return 0;
580 }
581
out_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)582 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect) {
583 // out_add_audio_effect is a no op
584 return 0;
585 }
586
out_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)587 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect) {
588 // out_remove_audio_effect is a no op
589 return 0;
590 }
591
out_get_next_write_timestamp(const struct audio_stream_out * stream,int64_t * timestamp)592 static int out_get_next_write_timestamp(const struct audio_stream_out *stream,
593 int64_t *timestamp) {
594 return -ENOSYS;
595 }
596
in_get_sample_rate(const struct audio_stream * stream)597 static uint32_t in_get_sample_rate(const struct audio_stream *stream) {
598 struct generic_stream_in *in = (struct generic_stream_in *)stream;
599 return in->req_config.sample_rate;
600 }
601
in_set_sample_rate(struct audio_stream * stream,uint32_t rate)602 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate) {
603 return -ENOSYS;
604 }
605
refine_output_parameters(uint32_t * sample_rate,audio_format_t * format,audio_channel_mask_t * channel_mask)606 static int refine_output_parameters(uint32_t *sample_rate, audio_format_t *format,
607 audio_channel_mask_t *channel_mask) {
608 static const uint32_t sample_rates [] = {
609 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000
610 };
611 static const int sample_rates_count = sizeof(sample_rates)/sizeof(uint32_t);
612 bool inval = false;
613 if (*format != AUDIO_FORMAT_PCM_16_BIT) {
614 *format = AUDIO_FORMAT_PCM_16_BIT;
615 inval = true;
616 }
617
618 int channel_count = popcount(*channel_mask);
619 if (channel_count != 1 && channel_count != 2) {
620 *channel_mask = AUDIO_CHANNEL_IN_STEREO;
621 inval = true;
622 }
623
624 int i;
625 for (i = 0; i < sample_rates_count; i++) {
626 if (*sample_rate < sample_rates[i]) {
627 *sample_rate = sample_rates[i];
628 inval=true;
629 break;
630 }
631 else if (*sample_rate == sample_rates[i]) {
632 break;
633 }
634 else if (i == sample_rates_count-1) {
635 // Cap it to the highest rate we support
636 *sample_rate = sample_rates[i];
637 inval=true;
638 }
639 }
640
641 if (inval) {
642 return -EINVAL;
643 }
644 return 0;
645 }
646
refine_input_parameters(uint32_t * sample_rate,audio_format_t * format,audio_channel_mask_t * channel_mask)647 static int refine_input_parameters(uint32_t *sample_rate, audio_format_t *format,
648 audio_channel_mask_t *channel_mask) {
649 static const uint32_t sample_rates [] = {
650 8000, 11025, 16000, 22050, 44100, 48000
651 };
652 static const int sample_rates_count = sizeof(sample_rates)/sizeof(uint32_t);
653 bool inval = false;
654 // Only PCM_16_bit is supported. If this is changed, stereo to mono drop
655 // must be fixed in in_read
656 if (*format != AUDIO_FORMAT_PCM_16_BIT) {
657 *format = AUDIO_FORMAT_PCM_16_BIT;
658 inval = true;
659 }
660
661 int channel_count = popcount(*channel_mask);
662 if (channel_count != 1 && channel_count != 2) {
663 *channel_mask = AUDIO_CHANNEL_IN_STEREO;
664 inval = true;
665 }
666
667 int i;
668 for (i = 0; i < sample_rates_count; i++) {
669 if (*sample_rate < sample_rates[i]) {
670 *sample_rate = sample_rates[i];
671 inval=true;
672 break;
673 }
674 else if (*sample_rate == sample_rates[i]) {
675 break;
676 }
677 else if (i == sample_rates_count-1) {
678 // Cap it to the highest rate we support
679 *sample_rate = sample_rates[i];
680 inval=true;
681 }
682 }
683
684 if (inval) {
685 return -EINVAL;
686 }
687 return 0;
688 }
689
get_input_buffer_size(uint32_t sample_rate,audio_format_t format,audio_channel_mask_t channel_mask)690 static size_t get_input_buffer_size(uint32_t sample_rate, audio_format_t format,
691 audio_channel_mask_t channel_mask) {
692 size_t size;
693 int channel_count = popcount(channel_mask);
694 if (refine_input_parameters(&sample_rate, &format, &channel_mask) != 0)
695 return 0;
696
697 size = sample_rate * get_in_period_ms() / 1000;
698 // Audioflinger expects audio buffers to be multiple of 16 frames
699 size = ((size + 15) / 16) * 16;
700 size *= sizeof(short) * channel_count;
701
702 return size;
703 }
704
in_get_buffer_size(const struct audio_stream * stream)705 static size_t in_get_buffer_size(const struct audio_stream *stream) {
706 struct generic_stream_in *in = (struct generic_stream_in *)stream;
707 int size = get_input_buffer_size(in->req_config.sample_rate,
708 in->req_config.format,
709 in->req_config.channel_mask);
710
711 return size;
712 }
713
in_get_channels(const struct audio_stream * stream)714 static audio_channel_mask_t in_get_channels(const struct audio_stream *stream) {
715 struct generic_stream_in *in = (struct generic_stream_in *)stream;
716 return in->req_config.channel_mask;
717 }
718
in_get_format(const struct audio_stream * stream)719 static audio_format_t in_get_format(const struct audio_stream *stream) {
720 struct generic_stream_in *in = (struct generic_stream_in *)stream;
721 return in->req_config.format;
722 }
723
in_set_format(struct audio_stream * stream,audio_format_t format)724 static int in_set_format(struct audio_stream *stream, audio_format_t format) {
725 return -ENOSYS;
726 }
727
in_dump(const struct audio_stream * stream,int fd)728 static int in_dump(const struct audio_stream *stream, int fd) {
729 struct generic_stream_in *in = (struct generic_stream_in *)stream;
730
731 pthread_mutex_lock(&in->lock);
732 dprintf(fd, "\tin_dump:\n"
733 "\t\tsample rate: %u\n"
734 "\t\tbuffer size: %zu\n"
735 "\t\tchannel mask: %08x\n"
736 "\t\tformat: %d\n"
737 "\t\tdevice: %08x\n"
738 "\t\taudio dev: %p\n\n",
739 in_get_sample_rate(stream),
740 in_get_buffer_size(stream),
741 in_get_channels(stream),
742 in_get_format(stream),
743 in->device,
744 in->dev);
745 pthread_mutex_unlock(&in->lock);
746 return 0;
747 }
748
in_set_parameters(struct audio_stream * stream,const char * kvpairs)749 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs) {
750 struct generic_stream_in *in = (struct generic_stream_in *)stream;
751 struct str_parms *parms;
752 int ret = 0;
753
754 pthread_mutex_lock(&in->lock);
755 if (!in->standby) {
756 ret = -ENOSYS;
757 } else {
758 parms = str_parms_create_str(kvpairs);
759 int val = 0;
760 ret = get_int_value(parms, AUDIO_PARAMETER_STREAM_ROUTING, &val);
761 if (ret >= 0) {
762 in->device = (int)val;
763 ret = 0;
764 }
765
766 str_parms_destroy(parms);
767 }
768 pthread_mutex_unlock(&in->lock);
769 return ret;
770 }
771
in_get_parameters(const struct audio_stream * stream,const char * keys)772 static char *in_get_parameters(const struct audio_stream *stream, const char *keys) {
773 struct generic_stream_in *in = (struct generic_stream_in *)stream;
774 struct str_parms *query = str_parms_create_str(keys);
775 char *str;
776 char value[256];
777 struct str_parms *reply = str_parms_create();
778 int ret;
779
780 ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value));
781 if (ret >= 0) {
782 str_parms_add_int(reply, AUDIO_PARAMETER_STREAM_ROUTING, in->device);
783 str = strdup(str_parms_to_str(reply));
784 } else {
785 str = strdup(keys);
786 }
787
788 str_parms_destroy(query);
789 str_parms_destroy(reply);
790 return str;
791 }
792
in_set_gain(struct audio_stream_in * stream,float gain)793 static int in_set_gain(struct audio_stream_in *stream, float gain) {
794 // TODO(hwwang): support adjusting input gain
795 return 0;
796 }
797
798 // Call with in->lock held
get_current_input_position(struct generic_stream_in * in,int64_t * position,struct timespec * timestamp)799 static void get_current_input_position(struct generic_stream_in *in,
800 int64_t * position, struct timespec * timestamp) {
801 struct timespec t = { .tv_sec = 0, .tv_nsec = 0 };
802 clock_gettime(CLOCK_MONOTONIC, &t);
803 const int64_t now_us = (t.tv_sec * 1000000000LL + t.tv_nsec) / 1000;
804 if (timestamp) {
805 *timestamp = t;
806 }
807 int64_t position_since_standby;
808 if (in->standby) {
809 position_since_standby = 0;
810 } else {
811 const int64_t first_us = (in->standby_exit_time.tv_sec * 1000000000LL +
812 in->standby_exit_time.tv_nsec) / 1000;
813 position_since_standby = (now_us - first_us) *
814 in_get_sample_rate(&in->stream.common) /
815 1000000;
816 if (position_since_standby < 0) {
817 position_since_standby = 0;
818 }
819 }
820 *position = in->standby_position + position_since_standby;
821 }
822
823 // Must be called with in->lock held
do_in_standby(struct generic_stream_in * in)824 static void do_in_standby(struct generic_stream_in *in) {
825 if (in->standby) {
826 return;
827 }
828 in->worker_standby = true;
829 get_current_input_position(in, &in->standby_position, NULL);
830 in->standby = true;
831 }
832
in_standby(struct audio_stream * stream)833 static int in_standby(struct audio_stream *stream) {
834 struct generic_stream_in *in = (struct generic_stream_in *)stream;
835 pthread_mutex_lock(&in->lock);
836 do_in_standby(in);
837 pthread_mutex_unlock(&in->lock);
838 return 0;
839 }
840
841 // Generates pure tone for FM_TUNER and bus_device
pseudo_pcm_read(void * data,unsigned int count,struct oscillator * oscillator)842 static int pseudo_pcm_read(void *data, unsigned int count, struct oscillator *oscillator) {
843 unsigned int length = count / sizeof(int16_t);
844 int16_t *sdata = (int16_t *)data;
845 for (int index = 0; index < length; index++) {
846 sdata[index] = (int16_t)(sin(oscillator->phase) * 4096);
847 oscillator->phase += oscillator->phase_increment;
848 oscillator->phase = oscillator->phase > TWO_PI ?
849 oscillator->phase - TWO_PI : oscillator->phase;
850 }
851
852 return count;
853 }
854
in_read_worker(void * args)855 static void *in_read_worker(void *args) {
856 struct generic_stream_in *in = (struct generic_stream_in *)args;
857 struct pcm *pcm = NULL;
858 uint8_t *buffer = NULL;
859 size_t buffer_frames;
860 int buffer_size;
861
862 bool restart = false;
863 bool shutdown = false;
864 while (true) {
865 pthread_mutex_lock(&in->lock);
866 while (in->worker_standby || restart) {
867 restart = false;
868 if (pcm) {
869 pcm_close(pcm); // Frees pcm
870 pcm = NULL;
871 free(buffer);
872 buffer=NULL;
873 }
874 if (in->worker_exit) {
875 break;
876 }
877 pthread_cond_wait(&in->worker_wake, &in->lock);
878 }
879
880 if (in->worker_exit) {
881 if (!in->worker_standby) {
882 ALOGE("In worker not in standby before exiting");
883 }
884 shutdown = true;
885 }
886 if (shutdown) {
887 pthread_mutex_unlock(&in->lock);
888 break;
889 }
890 if (!pcm) {
891 pcm = pcm_open(PCM_CARD, PCM_DEVICE,
892 PCM_IN | PCM_MONOTONIC, &in->pcm_config);
893 if (!pcm_is_ready(pcm)) {
894 ALOGE("pcm_open(in) failed: %s: channels %d format %d rate %d",
895 pcm_get_error(pcm),
896 in->pcm_config.channels,
897 in->pcm_config.format,
898 in->pcm_config.rate);
899 pthread_mutex_unlock(&in->lock);
900 break;
901 }
902 buffer_frames = in->pcm_config.period_size;
903 buffer_size = pcm_frames_to_bytes(pcm, buffer_frames);
904 buffer = malloc(buffer_size);
905 if (!buffer) {
906 ALOGE("could not allocate worker read buffer");
907 pthread_mutex_unlock(&in->lock);
908 break;
909 }
910 }
911 pthread_mutex_unlock(&in->lock);
912 int ret = pcm_read(pcm, buffer, pcm_frames_to_bytes(pcm, buffer_frames));
913 if (ret != 0) {
914 ALOGW("pcm_read failed %s", pcm_get_error(pcm));
915 restart = true;
916 }
917
918 pthread_mutex_lock(&in->lock);
919 size_t frames_written = audio_vbuffer_write(&in->buffer, buffer, buffer_frames);
920 pthread_mutex_unlock(&in->lock);
921
922 if (frames_written != buffer_frames) {
923 ALOGW("in_read_worker only could write %zu / %zu frames",
924 frames_written, buffer_frames);
925 }
926 }
927 if (buffer) {
928 free(buffer);
929 }
930 return NULL;
931 }
932
address_has_tone_keyword(const char * address)933 static bool address_has_tone_keyword(const char * address) {
934 return strstr(address, TONE_ADDRESS_KEYWORD) != NULL;
935 }
936
is_tone_generator_device(struct generic_stream_in * in)937 static bool is_tone_generator_device(struct generic_stream_in *in) {
938 return in->device == AUDIO_DEVICE_IN_FM_TUNER || ((in->device == AUDIO_DEVICE_IN_BUS) &&
939 address_has_tone_keyword(in->bus_address));
940 }
941
read_frames_from_stream(void * dst,struct generic_stream_in * in,size_t frames_cnt)942 static size_t read_frames_from_stream(void* dst, struct generic_stream_in* in, size_t frames_cnt) {
943 size_t frames_read = 0;
944 void *cur_dst = NULL;
945 audio_vbuffer_t *src = &in->buffer;
946 size_t frame_size = in->buffer.frame_size;
947 for (int attempt = 0; attempt < MAX_READ_ATTEMPTS; attempt++) {
948 cur_dst = &((uint8_t *)dst)[frames_read * frame_size];
949 frames_read += audio_vbuffer_read(src, cur_dst, frames_cnt - frames_read);
950 if (frames_read == frames_cnt)
951 break;
952 // The next notification from the device informs about new available frames.
953 // Wait for a time of the order of one notification interval.
954 pthread_mutex_unlock(&in->lock);
955 usleep(NOTIFICATION_AVR_INTERVAL_US / 2);
956 pthread_mutex_lock(&in->lock);
957 }
958 return frames_read;
959 }
960
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)961 static ssize_t in_read(struct audio_stream_in *stream, void *buffer, size_t bytes) {
962 struct generic_stream_in *in = (struct generic_stream_in *)stream;
963 struct generic_audio_device *adev = in->dev;
964 const size_t frames = bytes / audio_stream_in_frame_size(stream);
965 bool mic_mute = false;
966 size_t read_bytes = 0;
967
968 adev_get_mic_mute(&adev->device, &mic_mute);
969 pthread_mutex_lock(&in->lock);
970
971 if (in->worker_standby) {
972 in->worker_standby = false;
973 }
974
975 // Tone generators fill the buffer via pseudo_pcm_read directly
976 if (!is_tone_generator_device(in)) {
977 pthread_cond_signal(&in->worker_wake);
978 }
979
980 int64_t current_position;
981 struct timespec current_time;
982
983 get_current_input_position(in, ¤t_position, ¤t_time);
984 if (in->standby) {
985 in->standby = false;
986 in->standby_exit_time = current_time;
987 in->standby_frames_read = 0;
988 }
989
990 const int64_t frames_available =
991 current_position - in->standby_position - in->standby_frames_read;
992 assert(frames_available >= 0);
993
994 const size_t frames_wait =
995 ((uint64_t)frames_available > frames) ? 0 : frames - frames_available;
996
997 int64_t sleep_time_us = frames_wait * 1000000LL / in_get_sample_rate(&stream->common);
998
999 pthread_mutex_unlock(&in->lock);
1000
1001 if (sleep_time_us > 0) {
1002 usleep(sleep_time_us);
1003 }
1004
1005 pthread_mutex_lock(&in->lock);
1006 size_t read_frames = 0;
1007 if (in->standby) {
1008 ALOGW("Input put to sleep while read in progress");
1009 goto exit;
1010 }
1011 in->standby_frames_read += frames;
1012
1013 if (is_tone_generator_device(in)) {
1014 int read_bytes = pseudo_pcm_read(buffer, bytes, &in->oscillator);
1015 read_frames = read_bytes / audio_stream_in_frame_size(stream);
1016 } else if (popcount(in->req_config.channel_mask) == 1 &&
1017 in->pcm_config.channels == 2) {
1018 // Need to resample to mono
1019 if (in->stereo_to_mono_buf_size < bytes*2) {
1020 in->stereo_to_mono_buf = realloc(in->stereo_to_mono_buf, bytes*2);
1021 if (!in->stereo_to_mono_buf) {
1022 ALOGE("Failed to allocate stereo_to_mono_buff");
1023 goto exit;
1024 }
1025 }
1026
1027 read_frames = read_frames_from_stream(in->stereo_to_mono_buf, in, frames);
1028 if (read_frames != frames) {
1029 ALOGE("Failed to read all the frames! Is the device dead?");
1030 goto exit;
1031 }
1032
1033
1034 // Currently only pcm 16 is supported.
1035 uint16_t *src = (uint16_t *)in->stereo_to_mono_buf;
1036 uint16_t *dst = (uint16_t *)buffer;
1037 size_t i;
1038 // Resample stereo 16 to mono 16 by dropping one channel.
1039 // The stereo stream is interleaved L-R-L-R
1040 for (i = 0; i < frames; i++) {
1041 *dst = *src;
1042 src += 2;
1043 dst += 1;
1044 }
1045 } else {
1046 read_frames = read_frames_from_stream(buffer, in, frames);
1047 if (read_frames != frames) {
1048 ALOGE("Failed to read all the frames! Is the device dead?");
1049 goto exit;
1050 }
1051 }
1052
1053 exit:
1054 read_bytes = read_frames*audio_stream_in_frame_size(stream);
1055
1056 if (mic_mute) {
1057 read_bytes = 0;
1058 }
1059
1060 if (read_bytes < bytes) {
1061 memset (&((uint8_t *)buffer)[read_bytes], 0, bytes-read_bytes);
1062 }
1063
1064 pthread_mutex_unlock(&in->lock);
1065
1066 return bytes;
1067 }
1068
in_get_input_frames_lost(struct audio_stream_in * stream)1069 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream) {
1070 return 0;
1071 }
1072
in_get_capture_position(const struct audio_stream_in * stream,int64_t * frames,int64_t * time)1073 static int in_get_capture_position(const struct audio_stream_in *stream,
1074 int64_t *frames, int64_t *time) {
1075 struct generic_stream_in *in = (struct generic_stream_in *)stream;
1076 pthread_mutex_lock(&in->lock);
1077 struct timespec current_time;
1078 get_current_input_position(in, frames, ¤t_time);
1079 *time = (current_time.tv_sec * 1000000000LL + current_time.tv_nsec);
1080 pthread_mutex_unlock(&in->lock);
1081 return 0;
1082 }
1083
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1084 static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect) {
1085 // in_add_audio_effect is a no op
1086 return 0;
1087 }
1088
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1089 static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect) {
1090 // in_add_audio_effect is a no op
1091 return 0;
1092 }
1093
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)1094 static int adev_open_output_stream(struct audio_hw_device *dev,
1095 audio_io_handle_t handle, audio_devices_t devices, audio_output_flags_t flags,
1096 struct audio_config *config, struct audio_stream_out **stream_out, const char *address) {
1097 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1098 struct generic_stream_out *out;
1099 int ret = 0;
1100
1101 if (refine_output_parameters(&config->sample_rate, &config->format, &config->channel_mask)) {
1102 ALOGE("Error opening output stream format %d, channel_mask %04x, sample_rate %u",
1103 config->format, config->channel_mask, config->sample_rate);
1104 ret = -EINVAL;
1105 goto error;
1106 }
1107
1108 out = (struct generic_stream_out *)calloc(1, sizeof(struct generic_stream_out));
1109
1110 if (!out)
1111 return -ENOMEM;
1112
1113 out->stream.common.get_sample_rate = out_get_sample_rate;
1114 out->stream.common.set_sample_rate = out_set_sample_rate;
1115 out->stream.common.get_buffer_size = out_get_buffer_size;
1116 out->stream.common.get_channels = out_get_channels;
1117 out->stream.common.get_format = out_get_format;
1118 out->stream.common.set_format = out_set_format;
1119 out->stream.common.standby = out_standby;
1120 out->stream.common.dump = out_dump;
1121 out->stream.common.set_parameters = out_set_parameters;
1122 out->stream.common.get_parameters = out_get_parameters;
1123 out->stream.common.add_audio_effect = out_add_audio_effect;
1124 out->stream.common.remove_audio_effect = out_remove_audio_effect;
1125 out->stream.get_latency = out_get_latency;
1126 out->stream.set_volume = out_set_volume;
1127 out->stream.write = out_write;
1128 out->stream.get_render_position = out_get_render_position;
1129 out->stream.get_presentation_position = out_get_presentation_position;
1130 out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
1131
1132 pthread_mutex_init(&out->lock, (const pthread_mutexattr_t *) NULL);
1133 out->dev = adev;
1134 out->device = devices;
1135 memcpy(&out->req_config, config, sizeof(struct audio_config));
1136 memcpy(&out->pcm_config, &pcm_config_out, sizeof(struct pcm_config));
1137 out->pcm_config.rate = config->sample_rate;
1138 out->pcm_config.period_size = out->pcm_config.rate * get_out_period_ms() / 1000;
1139
1140 out->standby = true;
1141 out->underrun_position = 0;
1142 out->underrun_time.tv_sec = 0;
1143 out->underrun_time.tv_nsec = 0;
1144 out->last_write_time_us = 0;
1145 out->frames_total_buffered = 0;
1146 out->frames_written = 0;
1147 out->frames_rendered = 0;
1148
1149 ret = audio_vbuffer_init(&out->buffer,
1150 out->pcm_config.period_size * out->pcm_config.period_count,
1151 out->pcm_config.channels *
1152 pcm_format_to_bits(out->pcm_config.format) >> 3);
1153 if (ret == 0) {
1154 pthread_cond_init(&out->worker_wake, NULL);
1155 out->worker_standby = true;
1156 out->worker_exit = false;
1157 pthread_create(&out->worker_thread, NULL, out_write_worker, out);
1158 }
1159
1160 out->enabled_channels = BOTH_CHANNELS;
1161 if (address) {
1162 out->bus_address = strdup(address);
1163 hashmapPut(adev->out_bus_stream_map, (void*)out->bus_address, out);
1164 /* TODO: read struct audio_gain from audio_policy_configuration */
1165 out->gain_stage = (struct audio_gain) {
1166 .min_value = -3200,
1167 .max_value = 600,
1168 .step_value = 100,
1169 };
1170 out->amplitude_ratio = 1.0;
1171 if (property_get_bool(PROP_KEY_SIMULATE_MULTI_ZONE_AUDIO, false)) {
1172 out->enabled_channels = strstr(out->bus_address, AUDIO_ZONE_KEYWORD)
1173 ? RIGHT_CHANNEL: LEFT_CHANNEL;
1174 ALOGD("%s Routing %s to %s channel", __func__,
1175 out->bus_address, out->enabled_channels == RIGHT_CHANNEL ? "Right" : "Left");
1176 }
1177 }
1178 *stream_out = &out->stream;
1179 ALOGD("%s bus: %s", __func__, out->bus_address);
1180
1181 error:
1182 return ret;
1183 }
1184
adev_close_output_stream(struct audio_hw_device * dev,struct audio_stream_out * stream)1185 static void adev_close_output_stream(struct audio_hw_device *dev,
1186 struct audio_stream_out *stream) {
1187 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1188 struct generic_stream_out *out = (struct generic_stream_out *)stream;
1189 ALOGD("%s bus:%s", __func__, out->bus_address);
1190 pthread_mutex_lock(&out->lock);
1191 do_out_standby(out);
1192
1193 out->worker_exit = true;
1194 pthread_cond_signal(&out->worker_wake);
1195 pthread_mutex_unlock(&out->lock);
1196
1197 pthread_join(out->worker_thread, NULL);
1198 pthread_mutex_destroy(&out->lock);
1199 audio_vbuffer_destroy(&out->buffer);
1200
1201 if (out->bus_address) {
1202 hashmapRemove(adev->out_bus_stream_map, (void*)out->bus_address);
1203 free((void*)out->bus_address);
1204 }
1205 free(stream);
1206 }
1207
adev_set_parameters(struct audio_hw_device * dev,const char * kvpairs)1208 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs) {
1209 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1210 pthread_mutex_lock(&adev->lock);
1211 struct str_parms *parms = str_parms_create_str(kvpairs);
1212 int value = 0;
1213 int results = get_int_value(parms, AAE_PARAMETER_KEY_FOR_SELECTED_ZONE, &value);
1214 if (results >= 0) {
1215 adev->last_zone_selected_to_play = value;
1216 results = 0;
1217 ALOGD("%s Changed play zone id to %d", __func__, adev->last_zone_selected_to_play);
1218 }
1219 str_parms_destroy(parms);
1220 pthread_mutex_unlock(&adev->lock);
1221 return results;
1222 }
1223
adev_get_parameters(const struct audio_hw_device * dev,const char * keys)1224 static char *adev_get_parameters(const struct audio_hw_device * dev, const char *keys) {
1225 return NULL;
1226 }
1227
adev_init_check(const struct audio_hw_device * dev)1228 static int adev_init_check(const struct audio_hw_device *dev) {
1229 return 0;
1230 }
1231
adev_set_voice_volume(struct audio_hw_device * dev,float volume)1232 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume) {
1233 // adev_set_voice_volume is a no op (simulates phones)
1234 return 0;
1235 }
1236
adev_set_main_volume(struct audio_hw_device * dev,float volume)1237 static int adev_set_main_volume(struct audio_hw_device *dev, float volume) {
1238 return -ENOSYS;
1239 }
1240
adev_get_main_volume(struct audio_hw_device * dev,float * volume)1241 static int adev_get_main_volume(struct audio_hw_device *dev, float *volume) {
1242 return -ENOSYS;
1243 }
1244
adev_set_main_mute(struct audio_hw_device * dev,bool muted)1245 static int adev_set_main_mute(struct audio_hw_device *dev, bool muted) {
1246 ALOGD("%s: %s", __func__, _bool_str(muted));
1247 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1248 pthread_mutex_lock(&adev->lock);
1249 adev->main_mute = muted;
1250 pthread_mutex_unlock(&adev->lock);
1251 return 0;
1252 }
1253
adev_get_main_mute(struct audio_hw_device * dev,bool * muted)1254 static int adev_get_main_mute(struct audio_hw_device *dev, bool *muted) {
1255 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1256 pthread_mutex_lock(&adev->lock);
1257 *muted = adev->main_mute;
1258 pthread_mutex_unlock(&adev->lock);
1259 ALOGD("%s: %s", __func__, _bool_str(*muted));
1260 return 0;
1261 }
1262
adev_set_mode(struct audio_hw_device * dev,audio_mode_t mode)1263 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode) {
1264 // adev_set_mode is a no op (simulates phones)
1265 return 0;
1266 }
1267
adev_set_mic_mute(struct audio_hw_device * dev,bool state)1268 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state) {
1269 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1270 pthread_mutex_lock(&adev->lock);
1271 adev->mic_mute = state;
1272 pthread_mutex_unlock(&adev->lock);
1273 return 0;
1274 }
1275
adev_get_mic_mute(const struct audio_hw_device * dev,bool * state)1276 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state) {
1277 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1278 pthread_mutex_lock(&adev->lock);
1279 *state = adev->mic_mute;
1280 pthread_mutex_unlock(&adev->lock);
1281 return 0;
1282 }
1283
adev_get_input_buffer_size(const struct audio_hw_device * dev,const struct audio_config * config)1284 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
1285 const struct audio_config *config) {
1286 return get_input_buffer_size(config->sample_rate, config->format, config->channel_mask);
1287 }
1288
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream)1289 static void adev_close_input_stream(struct audio_hw_device *dev,
1290 struct audio_stream_in *stream) {
1291 struct generic_stream_in *in = (struct generic_stream_in *)stream;
1292 pthread_mutex_lock(&in->lock);
1293 do_in_standby(in);
1294
1295 in->worker_exit = true;
1296 pthread_cond_signal(&in->worker_wake);
1297 pthread_mutex_unlock(&in->lock);
1298 pthread_join(in->worker_thread, NULL);
1299
1300 if (in->stereo_to_mono_buf != NULL) {
1301 free(in->stereo_to_mono_buf);
1302 in->stereo_to_mono_buf_size = 0;
1303 }
1304
1305 if (in->bus_address) {
1306 free((void*)in->bus_address);
1307 }
1308
1309 pthread_mutex_destroy(&in->lock);
1310 audio_vbuffer_destroy(&in->buffer);
1311 free(stream);
1312 }
1313
increase_next_tone_frequency(struct generic_audio_device * adev)1314 static void increase_next_tone_frequency(struct generic_audio_device *adev) {
1315 adev->next_tone_frequency_to_assign += TONE_FREQUENCY_INCREASE;
1316 if (adev->next_tone_frequency_to_assign > MAX_TONE_FREQUENCY) {
1317 adev->next_tone_frequency_to_assign = DEFAULT_FREQUENCY;
1318 }
1319 }
1320
create_or_fetch_tone_frequency(struct generic_audio_device * adev,const char * address,int update_frequency)1321 static int create_or_fetch_tone_frequency(struct generic_audio_device *adev,
1322 const char *address, int update_frequency) {
1323 int *frequency = hashmapGet(adev->in_bus_tone_frequency_map, (void*)address);
1324 if (frequency == NULL) {
1325 frequency = calloc(1, sizeof(int));
1326 *frequency = update_frequency;
1327 hashmapPut(adev->in_bus_tone_frequency_map, strdup(address), frequency);
1328 ALOGD("%s assigned frequency %d to %s", __func__, *frequency, address);
1329 }
1330 return *frequency;
1331 }
1332
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)1333 static int adev_open_input_stream(struct audio_hw_device *dev,
1334 audio_io_handle_t handle, audio_devices_t devices, struct audio_config *config,
1335 struct audio_stream_in **stream_in, audio_input_flags_t flags __unused, const char *address,
1336 audio_source_t source) {
1337 ALOGV("%s: audio_source_t: %d", __func__, source);
1338 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1339 struct generic_stream_in *in;
1340 int ret = 0;
1341 if (refine_input_parameters(&config->sample_rate, &config->format, &config->channel_mask)) {
1342 ALOGE("Error opening input stream format %d, channel_mask %04x, sample_rate %u",
1343 config->format, config->channel_mask, config->sample_rate);
1344 ret = -EINVAL;
1345 goto error;
1346 }
1347
1348 in = (struct generic_stream_in *)calloc(1, sizeof(struct generic_stream_in));
1349 if (!in) {
1350 ret = -ENOMEM;
1351 goto error;
1352 }
1353
1354 in->stream.common.get_sample_rate = in_get_sample_rate;
1355 in->stream.common.set_sample_rate = in_set_sample_rate; // no op
1356 in->stream.common.get_buffer_size = in_get_buffer_size;
1357 in->stream.common.get_channels = in_get_channels;
1358 in->stream.common.get_format = in_get_format;
1359 in->stream.common.set_format = in_set_format; // no op
1360 in->stream.common.standby = in_standby;
1361 in->stream.common.dump = in_dump;
1362 in->stream.common.set_parameters = in_set_parameters;
1363 in->stream.common.get_parameters = in_get_parameters;
1364 in->stream.common.add_audio_effect = in_add_audio_effect; // no op
1365 in->stream.common.remove_audio_effect = in_remove_audio_effect; // no op
1366 in->stream.set_gain = in_set_gain; // no op
1367 in->stream.read = in_read;
1368 in->stream.get_input_frames_lost = in_get_input_frames_lost; // no op
1369 in->stream.get_capture_position = in_get_capture_position;
1370
1371 pthread_mutex_init(&in->lock, (const pthread_mutexattr_t *) NULL);
1372 in->dev = adev;
1373 in->device = devices;
1374 memcpy(&in->req_config, config, sizeof(struct audio_config));
1375 memcpy(&in->pcm_config, &pcm_config_in, sizeof(struct pcm_config));
1376 in->pcm_config.rate = config->sample_rate;
1377 in->pcm_config.period_size = in->pcm_config.rate * get_in_period_ms() / 1000;
1378
1379 in->stereo_to_mono_buf = NULL;
1380 in->stereo_to_mono_buf_size = 0;
1381
1382 in->standby = true;
1383 in->standby_position = 0;
1384 in->standby_exit_time.tv_sec = 0;
1385 in->standby_exit_time.tv_nsec = 0;
1386 in->standby_frames_read = 0;
1387
1388 ret = audio_vbuffer_init(&in->buffer,
1389 in->pcm_config.period_size*in->pcm_config.period_count,
1390 in->pcm_config.channels *
1391 pcm_format_to_bits(in->pcm_config.format) >> 3);
1392 if (ret == 0) {
1393 pthread_cond_init(&in->worker_wake, NULL);
1394 in->worker_standby = true;
1395 in->worker_exit = false;
1396 pthread_create(&in->worker_thread, NULL, in_read_worker, in);
1397 }
1398
1399 if (address) {
1400 in->bus_address = strdup(address);
1401 if (is_tone_generator_device(in)) {
1402 int update_frequency = adev->next_tone_frequency_to_assign;
1403 int frequency = create_or_fetch_tone_frequency(adev, address, update_frequency);
1404 if (update_frequency == frequency) {
1405 increase_next_tone_frequency(adev);
1406 }
1407 in->oscillator.phase = 0.0f;
1408 in->oscillator.phase_increment = (TWO_PI*(frequency))
1409 / ((float) in_get_sample_rate(&in->stream.common));
1410 }
1411 }
1412
1413 *stream_in = &in->stream;
1414
1415 error:
1416 return ret;
1417 }
1418
adev_dump(const audio_hw_device_t * dev,int fd)1419 static int adev_dump(const audio_hw_device_t *dev, int fd) {
1420 return 0;
1421 }
1422
adev_set_audio_port_config(struct audio_hw_device * dev,const struct audio_port_config * config)1423 static int adev_set_audio_port_config(struct audio_hw_device *dev,
1424 const struct audio_port_config *config) {
1425 int ret = 0;
1426 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1427 const char *bus_address = config->ext.device.address;
1428 struct generic_stream_out *out = hashmapGet(adev->out_bus_stream_map, (void*)bus_address);
1429 if (out) {
1430 pthread_mutex_lock(&out->lock);
1431 int gainIndex = (config->gain.values[0] - out->gain_stage.min_value) /
1432 out->gain_stage.step_value;
1433 int totalSteps = (out->gain_stage.max_value - out->gain_stage.min_value) /
1434 out->gain_stage.step_value;
1435 int minDb = out->gain_stage.min_value / 100;
1436 int maxDb = out->gain_stage.max_value / 100;
1437 // curve: 10^((minDb + (maxDb - minDb) * gainIndex / totalSteps) / 20)
1438 out->amplitude_ratio = pow(10,
1439 (minDb + (maxDb - minDb) * (gainIndex / (float)totalSteps)) / 20);
1440 pthread_mutex_unlock(&out->lock);
1441 ALOGD("%s: set audio gain: %f on %s",
1442 __func__, out->amplitude_ratio, bus_address);
1443 } else {
1444 ALOGE("%s: can not find output stream by bus_address:%s", __func__, bus_address);
1445 ret = -EINVAL;
1446 }
1447 return ret;
1448 }
1449
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)1450 static int adev_create_audio_patch(struct audio_hw_device *dev,
1451 unsigned int num_sources,
1452 const struct audio_port_config *sources,
1453 unsigned int num_sinks,
1454 const struct audio_port_config *sinks,
1455 audio_patch_handle_t *handle) {
1456 struct generic_audio_device *audio_dev = (struct generic_audio_device *)dev;
1457 for (int i = 0; i < num_sources; i++) {
1458 ALOGD("%s: source[%d] type=%d address=%s", __func__, i, sources[i].type,
1459 sources[i].type == AUDIO_PORT_TYPE_DEVICE
1460 ? sources[i].ext.device.address
1461 : "");
1462 }
1463 for (int i = 0; i < num_sinks; i++) {
1464 ALOGD("%s: sink[%d] type=%d address=%s", __func__, i, sinks[i].type,
1465 sinks[i].type == AUDIO_PORT_TYPE_DEVICE ? sinks[i].ext.device.address
1466 : "N/A");
1467 }
1468 if (num_sources == 1 && num_sinks == 1 &&
1469 sources[0].type == AUDIO_PORT_TYPE_DEVICE &&
1470 sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1471 pthread_mutex_lock(&audio_dev->lock);
1472 audio_dev->last_patch_id += 1;
1473 pthread_mutex_unlock(&audio_dev->lock);
1474 *handle = audio_dev->last_patch_id;
1475 ALOGD("%s: handle: %d", __func__, *handle);
1476 }
1477 return 0;
1478 }
1479
adev_release_audio_patch(struct audio_hw_device * dev,audio_patch_handle_t handle)1480 static int adev_release_audio_patch(struct audio_hw_device *dev,
1481 audio_patch_handle_t handle) {
1482 ALOGD("%s: handle: %d", __func__, handle);
1483 return 0;
1484 }
1485
adev_close(hw_device_t * dev)1486 static int adev_close(hw_device_t *dev) {
1487 struct generic_audio_device *adev = (struct generic_audio_device *)dev;
1488 int ret = 0;
1489 if (!adev)
1490 return 0;
1491
1492 pthread_mutex_lock(&adev_init_lock);
1493
1494 if (audio_device_ref_count == 0) {
1495 ALOGE("adev_close called when ref_count 0");
1496 ret = -EINVAL;
1497 goto error;
1498 }
1499
1500 if ((--audio_device_ref_count) == 0) {
1501 if (adev->mixer) {
1502 mixer_close(adev->mixer);
1503 }
1504 if (adev->out_bus_stream_map) {
1505 hashmapFree(adev->out_bus_stream_map);
1506 }
1507 if (adev->in_bus_tone_frequency_map) {
1508 hashmapFree(adev->in_bus_tone_frequency_map);
1509 }
1510 free(adev);
1511 }
1512
1513 error:
1514 pthread_mutex_unlock(&adev_init_lock);
1515 return ret;
1516 }
1517
1518 /* copied from libcutils/str_parms.c */
str_eq(void * key_a,void * key_b)1519 static bool str_eq(void *key_a, void *key_b) {
1520 return !strcmp((const char *)key_a, (const char *)key_b);
1521 }
1522
1523 /**
1524 * use djb hash unless we find it inadequate.
1525 * copied from libcutils/str_parms.c
1526 */
1527 #ifdef __clang__
1528 __attribute__((no_sanitize("integer")))
1529 #endif
str_hash_fn(void * str)1530 static int str_hash_fn(void *str) {
1531 uint32_t hash = 5381;
1532 char *p;
1533 for (p = str; p && *p; p++) {
1534 hash = ((hash << 5) + hash) + *p;
1535 }
1536 return (int)hash;
1537 }
1538
adev_open(const hw_module_t * module,const char * name,hw_device_t ** device)1539 static int adev_open(const hw_module_t *module,
1540 const char *name, hw_device_t **device) {
1541 static struct generic_audio_device *adev;
1542
1543 if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
1544 return -EINVAL;
1545
1546 pthread_mutex_lock(&adev_init_lock);
1547 if (audio_device_ref_count != 0) {
1548 *device = &adev->device.common;
1549 audio_device_ref_count++;
1550 ALOGV("%s: returning existing instance of adev", __func__);
1551 ALOGV("%s: exit", __func__);
1552 goto unlock;
1553 }
1554
1555 pcm_config_in.period_count = get_in_period_count();
1556 pcm_config_out.period_count = get_out_period_count();
1557
1558 adev = calloc(1, sizeof(struct generic_audio_device));
1559
1560 pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
1561
1562 adev->device.common.tag = HARDWARE_DEVICE_TAG;
1563 adev->device.common.version = AUDIO_DEVICE_API_VERSION_3_0;
1564 adev->device.common.module = (struct hw_module_t *) module;
1565 adev->device.common.close = adev_close;
1566
1567 adev->device.init_check = adev_init_check; // no op
1568 adev->device.set_voice_volume = adev_set_voice_volume; // no op
1569 adev->device.set_master_volume = adev_set_main_volume; // no op
1570 adev->device.get_master_volume = adev_get_main_volume; // no op
1571 adev->device.set_master_mute = adev_set_main_mute;
1572 adev->device.get_master_mute = adev_get_main_mute;
1573 adev->device.set_mode = adev_set_mode; // no op
1574 adev->device.set_mic_mute = adev_set_mic_mute;
1575 adev->device.get_mic_mute = adev_get_mic_mute;
1576 adev->device.set_parameters = adev_set_parameters; // no op
1577 adev->device.get_parameters = adev_get_parameters; // no op
1578 adev->device.get_input_buffer_size = adev_get_input_buffer_size;
1579 adev->device.open_output_stream = adev_open_output_stream;
1580 adev->device.close_output_stream = adev_close_output_stream;
1581 adev->device.open_input_stream = adev_open_input_stream;
1582 adev->device.close_input_stream = adev_close_input_stream;
1583 adev->device.dump = adev_dump;
1584
1585 // New in AUDIO_DEVICE_API_VERSION_3_0
1586 adev->device.set_audio_port_config = adev_set_audio_port_config;
1587 adev->device.create_audio_patch = adev_create_audio_patch;
1588 adev->device.release_audio_patch = adev_release_audio_patch;
1589
1590 *device = &adev->device.common;
1591
1592 adev->mixer = mixer_open(PCM_CARD);
1593
1594 ALOGD("%s Mixer name %s", __func__, mixer_get_name(adev->mixer));
1595 struct mixer_ctl *ctl;
1596
1597 // Set default mixer ctls
1598 // Enable channels and set volume
1599 for (int i = 0; i < (int)mixer_get_num_ctls(adev->mixer); i++) {
1600 ctl = mixer_get_ctl(adev->mixer, i);
1601 ALOGD("mixer %d name %s", i, mixer_ctl_get_name(ctl));
1602 if (!strcmp(mixer_ctl_get_name(ctl), "Master Playback Volume") ||
1603 !strcmp(mixer_ctl_get_name(ctl), "Capture Volume")) {
1604 for (int z = 0; z < (int)mixer_ctl_get_num_values(ctl); z++) {
1605 ALOGD("set ctl %d to %d", z, 100);
1606 mixer_ctl_set_percent(ctl, z, 100);
1607 }
1608 continue;
1609 }
1610 if (!strcmp(mixer_ctl_get_name(ctl), "Master Playback Switch") ||
1611 !strcmp(mixer_ctl_get_name(ctl), "Capture Switch")) {
1612 for (int z = 0; z < (int)mixer_ctl_get_num_values(ctl); z++) {
1613 ALOGD("set ctl %d to %d", z, 1);
1614 mixer_ctl_set_value(ctl, z, 1);
1615 }
1616 continue;
1617 }
1618 }
1619
1620 // Initialize the bus address to output stream map
1621 adev->out_bus_stream_map = hashmapCreate(5, str_hash_fn, str_eq);
1622
1623 // Initialize the bus address to input stream map
1624 adev->in_bus_tone_frequency_map = hashmapCreate(5, str_hash_fn, str_eq);
1625
1626 adev->next_tone_frequency_to_assign = DEFAULT_FREQUENCY;
1627
1628 adev->last_zone_selected_to_play = DEFAULT_ZONE_TO_LEFT_SPEAKER;
1629
1630 audio_device_ref_count++;
1631
1632 unlock:
1633 pthread_mutex_unlock(&adev_init_lock);
1634 return 0;
1635 }
1636
1637 static struct hw_module_methods_t hal_module_methods = {
1638 .open = adev_open,
1639 };
1640
1641 struct audio_module HAL_MODULE_INFO_SYM = {
1642 .common = {
1643 .tag = HARDWARE_MODULE_TAG,
1644 .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
1645 .hal_api_version = HARDWARE_HAL_API_VERSION,
1646 .id = AUDIO_HARDWARE_MODULE_ID,
1647 .name = "Generic car audio HW HAL",
1648 .author = "The Android Open Source Project",
1649 .methods = &hal_module_methods,
1650 },
1651 };
1652