1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "modules.usbaudio.audio_hal"
18 /* #define LOG_NDEBUG 0 */
19 
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <math.h>
23 #include <pthread.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29 
30 #include <log/log.h>
31 #include <cutils/list.h>
32 #include <cutils/str_parms.h>
33 #include <cutils/properties.h>
34 
35 #include <hardware/audio.h>
36 #include <hardware/audio_alsaops.h>
37 #include <hardware/hardware.h>
38 
39 #include <system/audio.h>
40 
41 #include <tinyalsa/asoundlib.h>
42 
43 #include <audio_utils/channels.h>
44 
45 #include "alsa_device_profile.h"
46 #include "alsa_device_proxy.h"
47 #include "alsa_logging.h"
48 
49 /* Lock play & record samples rates at or above this threshold */
50 #define RATELOCK_THRESHOLD 96000
51 
52 #define max(a, b) ((a) > (b) ? (a) : (b))
53 #define min(a, b) ((a) < (b) ? (a) : (b))
54 
55 struct audio_device {
56     struct audio_hw_device hw_device;
57 
58     pthread_mutex_t lock; /* see note below on mutex acquisition order */
59 
60     /* output */
61     struct listnode output_stream_list;
62 
63     /* input */
64     struct listnode input_stream_list;
65 
66     /* lock input & output sample rates */
67     /*FIXME - How do we address multiple output streams? */
68     uint32_t device_sample_rate;    // this should be a rate that is common to both input & output
69 
70     bool mic_muted;
71 
72     int32_t inputs_open; /* number of input streams currently open. */
73 
74     audio_patch_handle_t next_patch_handle; // Increase 1 when create audio patch
75 };
76 
77 struct stream_lock {
78     pthread_mutex_t lock;               /* see note below on mutex acquisition order */
79     pthread_mutex_t pre_lock;           /* acquire before lock to avoid DOS by playback thread */
80 };
81 
82 struct alsa_device_info {
83     alsa_device_profile profile;        /* The profile of the ALSA device */
84     alsa_device_proxy proxy;            /* The state */
85     struct listnode list_node;
86 };
87 
88 struct stream_out {
89     struct audio_stream_out stream;
90 
91     struct stream_lock lock;
92 
93     bool standby;
94 
95     struct audio_device *adev;           /* hardware information - only using this for the lock */
96 
97     struct listnode alsa_devices;       /* The ALSA devices connected to the stream. */
98 
99     unsigned hal_channel_count;         /* channel count exposed to AudioFlinger.
100                                          * This may differ from the device channel count when
101                                          * the device is not compatible with AudioFlinger
102                                          * capabilities, e.g. exposes too many channels or
103                                          * too few channels. */
104     audio_channel_mask_t hal_channel_mask;  /* USB devices deal in channel counts, not masks
105                                              * so the proxy doesn't have a channel_mask, but
106                                              * audio HALs need to talk about channel masks
107                                              * so expose the one calculated by
108                                              * adev_open_output_stream */
109 
110     struct listnode list_node;
111 
112     void * conversion_buffer;           /* any conversions are put into here
113                                          * they could come from here too if
114                                          * there was a previous conversion */
115     size_t conversion_buffer_size;      /* in bytes */
116 
117     struct pcm_config config;
118 
119     audio_io_handle_t handle; // Unique constant for a stream
120 
121     audio_patch_handle_t patch_handle; // Patch handle for this stream
122 
123     bool is_bit_perfect; // True if the stream is open with bit-perfect output flag
124 
125     // Mixer information used for volume handling
126     struct mixer* mixer;
127     struct mixer_ctl* volume_ctl;
128     int volume_ctl_num_values;
129     int max_volume_level;
130     int min_volume_level;
131 };
132 
133 struct stream_in {
134     struct audio_stream_in stream;
135 
136     struct stream_lock  lock;
137 
138     bool standby;
139 
140     struct audio_device *adev;           /* hardware information - only using this for the lock */
141 
142     struct listnode alsa_devices;       /* The ALSA devices connected to the stream. */
143 
144     unsigned hal_channel_count;         /* channel count exposed to AudioFlinger.
145                                          * This may differ from the device channel count when
146                                          * the device is not compatible with AudioFlinger
147                                          * capabilities, e.g. exposes too many channels or
148                                          * too few channels. */
149     audio_channel_mask_t hal_channel_mask;  /* USB devices deal in channel counts, not masks
150                                              * so the proxy doesn't have a channel_mask, but
151                                              * audio HALs need to talk about channel masks
152                                              * so expose the one calculated by
153                                              * adev_open_input_stream */
154 
155     struct listnode list_node;
156 
157     /* We may need to read more data from the device in order to data reduce to 16bit, 4chan */
158     void * conversion_buffer;           /* any conversions are put into here
159                                          * they could come from here too if
160                                          * there was a previous conversion */
161     size_t conversion_buffer_size;      /* in bytes */
162 
163     struct pcm_config config;
164 
165     audio_io_handle_t handle; // Unique identifier for a stream
166 
167     audio_patch_handle_t patch_handle; // Patch handle for this stream
168 };
169 
170 // Map channel count to output channel mask
171 static const audio_channel_mask_t OUT_CHANNEL_MASKS_MAP[FCC_24 + 1] = {
172     [0] = AUDIO_CHANNEL_NONE,  // == 0 (so this line is optional and could be omitted)
173                                // != AUDIO_CHANNEL_INVALID == 0xC0000000u
174 
175     [1] = AUDIO_CHANNEL_OUT_MONO,
176     [2] = AUDIO_CHANNEL_OUT_STEREO,
177     [3] = AUDIO_CHANNEL_OUT_2POINT1,
178     [4] = AUDIO_CHANNEL_OUT_QUAD,
179     [5] = AUDIO_CHANNEL_OUT_PENTA,
180     [6] = AUDIO_CHANNEL_OUT_5POINT1,
181     [7] = AUDIO_CHANNEL_OUT_6POINT1,
182     [8] = AUDIO_CHANNEL_OUT_7POINT1,
183 
184     [9 ... 11] = AUDIO_CHANNEL_NONE,  // == 0 (so this line is optional and could be omitted).
185 
186     [12] = AUDIO_CHANNEL_OUT_7POINT1POINT4,
187 
188     [13 ... 23] = AUDIO_CHANNEL_NONE,  //  == 0 (so this line is optional and could be omitted).
189 
190     [24] = AUDIO_CHANNEL_OUT_22POINT2,
191 };
192 static const int OUT_CHANNEL_MASKS_SIZE = AUDIO_ARRAY_SIZE(OUT_CHANNEL_MASKS_MAP);
193 
194 // Map channel count to input channel mask
195 static const audio_channel_mask_t IN_CHANNEL_MASKS_MAP[] = {
196     AUDIO_CHANNEL_NONE,       /* 0 */
197     AUDIO_CHANNEL_IN_MONO,    /* 1 */
198     AUDIO_CHANNEL_IN_STEREO,  /* 2 */
199     /* channel counts greater than this are not considered */
200 };
201 static const int IN_CHANNEL_MASKS_SIZE = AUDIO_ARRAY_SIZE(IN_CHANNEL_MASKS_MAP);
202 
203 // Map channel count to index mask
204 static const audio_channel_mask_t CHANNEL_INDEX_MASKS_MAP[FCC_24 + 1] = {
205     [0] = AUDIO_CHANNEL_NONE,  // == 0 (so this line is optional and could be omitted).
206 
207     [1] = AUDIO_CHANNEL_INDEX_MASK_1,
208     [2] = AUDIO_CHANNEL_INDEX_MASK_2,
209     [3] = AUDIO_CHANNEL_INDEX_MASK_3,
210     [4] = AUDIO_CHANNEL_INDEX_MASK_4,
211     [5] = AUDIO_CHANNEL_INDEX_MASK_5,
212     [6] = AUDIO_CHANNEL_INDEX_MASK_6,
213     [7] = AUDIO_CHANNEL_INDEX_MASK_7,
214     [8] = AUDIO_CHANNEL_INDEX_MASK_8,
215 
216     [9] = AUDIO_CHANNEL_INDEX_MASK_9,
217     [10] = AUDIO_CHANNEL_INDEX_MASK_10,
218     [11] = AUDIO_CHANNEL_INDEX_MASK_11,
219     [12] = AUDIO_CHANNEL_INDEX_MASK_12,
220     [13] = AUDIO_CHANNEL_INDEX_MASK_13,
221     [14] = AUDIO_CHANNEL_INDEX_MASK_14,
222     [15] = AUDIO_CHANNEL_INDEX_MASK_15,
223     [16] = AUDIO_CHANNEL_INDEX_MASK_16,
224 
225     [17] = AUDIO_CHANNEL_INDEX_MASK_17,
226     [18] = AUDIO_CHANNEL_INDEX_MASK_18,
227     [19] = AUDIO_CHANNEL_INDEX_MASK_19,
228     [20] = AUDIO_CHANNEL_INDEX_MASK_20,
229     [21] = AUDIO_CHANNEL_INDEX_MASK_21,
230     [22] = AUDIO_CHANNEL_INDEX_MASK_22,
231     [23] = AUDIO_CHANNEL_INDEX_MASK_23,
232     [24] = AUDIO_CHANNEL_INDEX_MASK_24,
233 };
234 static const int CHANNEL_INDEX_MASKS_SIZE = AUDIO_ARRAY_SIZE(CHANNEL_INDEX_MASKS_MAP);
235 
236 static const char* ALL_VOLUME_CONTROL_NAMES[] = {
237     "PCM Playback Volume",
238     "Headset Playback Volume",
239     "Headphone Playback Volume",
240     "Master Playback Volume",
241 };
242 static const int VOLUME_CONTROL_NAMES_NUM = AUDIO_ARRAY_SIZE(ALL_VOLUME_CONTROL_NAMES);
243 
244 /*
245  * Locking Helpers
246  */
247 /*
248  * NOTE: when multiple mutexes have to be acquired, always take the
249  * stream_in or stream_out mutex first, followed by the audio_device mutex.
250  * stream pre_lock is always acquired before stream lock to prevent starvation of control thread by
251  * higher priority playback or capture thread.
252  */
253 
stream_lock_init(struct stream_lock * lock)254 static void stream_lock_init(struct stream_lock *lock) {
255     pthread_mutex_init(&lock->lock, (const pthread_mutexattr_t *) NULL);
256     pthread_mutex_init(&lock->pre_lock, (const pthread_mutexattr_t *) NULL);
257 }
258 
stream_lock(struct stream_lock * lock)259 static void stream_lock(struct stream_lock *lock) {
260     if (lock == NULL) {
261         return;
262     }
263     pthread_mutex_lock(&lock->pre_lock);
264     pthread_mutex_lock(&lock->lock);
265     pthread_mutex_unlock(&lock->pre_lock);
266 }
267 
stream_unlock(struct stream_lock * lock)268 static void stream_unlock(struct stream_lock *lock) {
269     pthread_mutex_unlock(&lock->lock);
270 }
271 
device_lock(struct audio_device * adev)272 static void device_lock(struct audio_device *adev) {
273     pthread_mutex_lock(&adev->lock);
274 }
275 
device_try_lock(struct audio_device * adev)276 static int device_try_lock(struct audio_device *adev) {
277     return pthread_mutex_trylock(&adev->lock);
278 }
279 
device_unlock(struct audio_device * adev)280 static void device_unlock(struct audio_device *adev) {
281     pthread_mutex_unlock(&adev->lock);
282 }
283 
284 /*
285  * streams list management
286  */
adev_add_stream_to_list(struct audio_device * adev,struct listnode * list,struct listnode * stream_node)287 static void adev_add_stream_to_list(
288     struct audio_device* adev, struct listnode* list, struct listnode* stream_node) {
289     device_lock(adev);
290 
291     list_add_tail(list, stream_node);
292 
293     device_unlock(adev);
294 }
295 
adev_get_stream_out_by_io_handle_l(struct audio_device * adev,audio_io_handle_t handle)296 static struct stream_out* adev_get_stream_out_by_io_handle_l(
297         struct audio_device* adev, audio_io_handle_t handle) {
298     struct listnode *node;
299     list_for_each (node, &adev->output_stream_list) {
300         struct stream_out *out = node_to_item(node, struct stream_out, list_node);
301         if (out->handle == handle) {
302             return out;
303         }
304     }
305     return NULL;
306 }
307 
adev_get_stream_in_by_io_handle_l(struct audio_device * adev,audio_io_handle_t handle)308 static struct stream_in* adev_get_stream_in_by_io_handle_l(
309         struct audio_device* adev, audio_io_handle_t handle) {
310     struct listnode *node;
311     list_for_each (node, &adev->input_stream_list) {
312         struct stream_in *in = node_to_item(node, struct stream_in, list_node);
313         if (in->handle == handle) {
314             return in;
315         }
316     }
317     return NULL;
318 }
319 
adev_get_stream_out_by_patch_handle_l(struct audio_device * adev,audio_patch_handle_t patch_handle)320 static struct stream_out* adev_get_stream_out_by_patch_handle_l(
321         struct audio_device* adev, audio_patch_handle_t patch_handle) {
322     struct listnode *node;
323     list_for_each (node, &adev->output_stream_list) {
324         struct stream_out *out = node_to_item(node, struct stream_out, list_node);
325         if (out->patch_handle == patch_handle) {
326             return out;
327         }
328     }
329     return NULL;
330 }
331 
adev_get_stream_in_by_patch_handle_l(struct audio_device * adev,audio_patch_handle_t patch_handle)332 static struct stream_in* adev_get_stream_in_by_patch_handle_l(
333         struct audio_device* adev, audio_patch_handle_t patch_handle) {
334     struct listnode *node;
335     list_for_each (node, &adev->input_stream_list) {
336         struct stream_in *in = node_to_item(node, struct stream_in, list_node);
337         if (in->patch_handle == patch_handle) {
338             return in;
339         }
340     }
341     return NULL;
342 }
343 
344 /*
345  * Extract the card and device numbers from the supplied key/value pairs.
346  *   kvpairs    A null-terminated string containing the key/value pairs or card and device.
347  *              i.e. "card=1;device=42"
348  *   card   A pointer to a variable to receive the parsed-out card number.
349  *   device A pointer to a variable to receive the parsed-out device number.
350  * NOTE: The variables pointed to by card and device return -1 (undefined) if the
351  *  associated key/value pair is not found in the provided string.
352  *  Return true if the kvpairs string contain a card/device spec, false otherwise.
353  */
parse_card_device_params(const char * kvpairs,int * card,int * device)354 static bool parse_card_device_params(const char *kvpairs, int *card, int *device)
355 {
356     struct str_parms * parms = str_parms_create_str(kvpairs);
357     char value[32];
358     int param_val;
359 
360     // initialize to "undefined" state.
361     *card = -1;
362     *device = -1;
363 
364     param_val = str_parms_get_str(parms, "card", value, sizeof(value));
365     if (param_val >= 0) {
366         *card = atoi(value);
367     }
368 
369     param_val = str_parms_get_str(parms, "device", value, sizeof(value));
370     if (param_val >= 0) {
371         *device = atoi(value);
372     }
373 
374     str_parms_destroy(parms);
375 
376     return *card >= 0 && *device >= 0;
377 }
378 
device_get_parameters(const alsa_device_profile * profile,const char * keys)379 static char *device_get_parameters(const alsa_device_profile *profile, const char * keys)
380 {
381     if (profile->card < 0 || profile->device < 0) {
382         return strdup("");
383     }
384 
385     struct str_parms *query = str_parms_create_str(keys);
386     struct str_parms *result = str_parms_create();
387 
388     /* These keys are from hardware/libhardware/include/audio.h */
389     /* supported sample rates */
390     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES)) {
391         char* rates_list = profile_get_sample_rate_strs(profile);
392         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES,
393                           rates_list);
394         free(rates_list);
395     }
396 
397     /* supported channel counts */
398     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_CHANNELS)) {
399         char* channels_list = profile_get_channel_count_strs(profile);
400         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_CHANNELS,
401                           channels_list);
402         free(channels_list);
403     }
404 
405     /* supported sample formats */
406     if (str_parms_has_key(query, AUDIO_PARAMETER_STREAM_SUP_FORMATS)) {
407         char * format_params = profile_get_format_strs(profile);
408         str_parms_add_str(result, AUDIO_PARAMETER_STREAM_SUP_FORMATS,
409                           format_params);
410         free(format_params);
411     }
412     str_parms_destroy(query);
413 
414     char* result_str = str_parms_to_str(result);
415     str_parms_destroy(result);
416 
417     ALOGV("device_get_parameters = %s", result_str);
418 
419     return result_str;
420 }
421 
audio_format_from(enum pcm_format format)422 static audio_format_t audio_format_from(enum pcm_format format)
423 {
424     switch (format) {
425     case PCM_FORMAT_S16_LE:
426         return AUDIO_FORMAT_PCM_16_BIT;
427     case PCM_FORMAT_S32_LE:
428         return AUDIO_FORMAT_PCM_32_BIT;
429     case PCM_FORMAT_S8:
430         return AUDIO_FORMAT_PCM_8_BIT;
431     case PCM_FORMAT_S24_LE:
432         return AUDIO_FORMAT_PCM_8_24_BIT;
433     case PCM_FORMAT_S24_3LE:
434         return AUDIO_FORMAT_PCM_24_BIT_PACKED;
435     default:
436         return AUDIO_FORMAT_INVALID;
437     }
438 }
439 
populate_channel_mask_from_profile(const alsa_device_profile * profile,bool is_output,audio_channel_mask_t channel_masks[])440 static unsigned int populate_channel_mask_from_profile(const alsa_device_profile* profile,
441                                                        bool is_output,
442                                                        audio_channel_mask_t channel_masks[])
443 {
444     unsigned int num_channel_masks = 0;
445     const audio_channel_mask_t* channel_masks_map =
446             is_output ? OUT_CHANNEL_MASKS_MAP : IN_CHANNEL_MASKS_MAP;
447     int channel_masks_size = is_output ? OUT_CHANNEL_MASKS_SIZE : IN_CHANNEL_MASKS_SIZE;
448     if (channel_masks_size > FCC_LIMIT + 1) {
449         channel_masks_size = FCC_LIMIT + 1;
450     }
451     unsigned int channel_count = 0;
452     for (size_t i = 0; i < min(channel_masks_size, AUDIO_PORT_MAX_CHANNEL_MASKS) &&
453             (channel_count = profile->channel_counts[i]) != 0 &&
454             num_channel_masks < AUDIO_PORT_MAX_CHANNEL_MASKS; ++i) {
455         if (channel_count < channel_masks_size &&
456             channel_masks_map[channel_count] != AUDIO_CHANNEL_NONE) {
457             channel_masks[num_channel_masks++] = channel_masks_map[channel_count];
458             if (num_channel_masks >= AUDIO_PORT_MAX_CHANNEL_MASKS) {
459                 break;
460             }
461         }
462         if (channel_count < CHANNEL_INDEX_MASKS_SIZE &&
463             CHANNEL_INDEX_MASKS_MAP[channel_count] != AUDIO_CHANNEL_NONE) {
464             channel_masks[num_channel_masks++] = CHANNEL_INDEX_MASKS_MAP[channel_count];
465         }
466     }
467     return num_channel_masks;
468 }
469 
populate_sample_rates_from_profile(const alsa_device_profile * profile,unsigned int sample_rates[])470 static unsigned int populate_sample_rates_from_profile(const alsa_device_profile* profile,
471                                                        unsigned int sample_rates[])
472 {
473     unsigned int num_sample_rates = 0;
474     for (;num_sample_rates < min(MAX_PROFILE_SAMPLE_RATES, AUDIO_PORT_MAX_SAMPLING_RATES) &&
475             profile->sample_rates[num_sample_rates] != 0; num_sample_rates++) {
476         sample_rates[num_sample_rates] = profile->sample_rates[num_sample_rates];
477     }
478     return num_sample_rates;
479 }
480 
are_all_devices_found(unsigned int num_devices_to_find,const int cards_to_find[],const int devices_to_find[],unsigned int num_devices,const int cards[],const int devices[])481 static bool are_all_devices_found(unsigned int num_devices_to_find,
482                                   const int cards_to_find[],
483                                   const int devices_to_find[],
484                                   unsigned int num_devices,
485                                   const int cards[],
486                                   const int devices[]) {
487     for (unsigned int i = 0; i < num_devices_to_find; ++i) {
488         unsigned int j = 0;
489         for (; j < num_devices; ++j) {
490             if (cards_to_find[i] == cards[j] && devices_to_find[i] == devices[j]) {
491                 break;
492             }
493         }
494         if (j >= num_devices) {
495             return false;
496         }
497     }
498     return true;
499 }
500 
are_devices_the_same(unsigned int left_num_devices,const int left_cards[],const int left_devices[],unsigned int right_num_devices,const int right_cards[],const int right_devices[])501 static bool are_devices_the_same(unsigned int left_num_devices,
502                                  const int left_cards[],
503                                  const int left_devices[],
504                                  unsigned int right_num_devices,
505                                  const int right_cards[],
506                                  const int right_devices[]) {
507     if (left_num_devices != right_num_devices) {
508         return false;
509     }
510     return are_all_devices_found(left_num_devices, left_cards, left_devices,
511                                  right_num_devices, right_cards, right_devices) &&
512            are_all_devices_found(right_num_devices, right_cards, right_devices,
513                                  left_num_devices, left_cards, left_devices);
514 }
515 
out_stream_find_mixer_volume_control(struct stream_out * out,int card)516 static void out_stream_find_mixer_volume_control(struct stream_out* out, int card) {
517     out->mixer = mixer_open(card);
518     if (out->mixer == NULL) {
519         ALOGI("%s, no mixer found for card=%d", __func__, card);
520         return;
521     }
522     unsigned int num_ctls = mixer_get_num_ctls(out->mixer);
523     for (int i = 0; i < VOLUME_CONTROL_NAMES_NUM; ++i) {
524         for (unsigned int j = 0; j < num_ctls; ++j) {
525             struct mixer_ctl *ctl = mixer_get_ctl(out->mixer, j);
526             enum mixer_ctl_type ctl_type = mixer_ctl_get_type(ctl);
527             if (strcasestr(mixer_ctl_get_name(ctl), ALL_VOLUME_CONTROL_NAMES[i]) == NULL ||
528                 ctl_type != MIXER_CTL_TYPE_INT) {
529                 continue;
530             }
531             ALOGD("%s, mixer volume control(%s) found", __func__, ALL_VOLUME_CONTROL_NAMES[i]);
532             out->volume_ctl_num_values = mixer_ctl_get_num_values(ctl);
533             if (out->volume_ctl_num_values <= 0) {
534                 ALOGE("%s the num(%d) of volume ctl values is wrong",
535                         __func__, out->volume_ctl_num_values);
536                 out->volume_ctl_num_values = 0;
537                 continue;
538             }
539             out->max_volume_level = mixer_ctl_get_range_max(ctl);
540             out->min_volume_level = mixer_ctl_get_range_min(ctl);
541             if (out->max_volume_level < out->min_volume_level) {
542                 ALOGE("%s the max volume level(%d) is less than min volume level(%d)",
543                         __func__, out->max_volume_level, out->min_volume_level);
544                 out->max_volume_level = 0;
545                 out->min_volume_level = 0;
546                 continue;
547             }
548             out->volume_ctl = ctl;
549             return;
550         }
551     }
552     ALOGI("%s, no volume control found", __func__);
553 }
554 
555 /*
556  * HAl Functions
557  */
558 /**
559  * NOTE: when multiple mutexes have to be acquired, always respect the
560  * following order: hw device > out stream
561  */
562 
stream_get_first_alsa_device(const struct listnode * alsa_devices)563 static struct alsa_device_info* stream_get_first_alsa_device(const struct listnode *alsa_devices) {
564     if (list_empty(alsa_devices)) {
565         return NULL;
566     }
567     return node_to_item(list_head(alsa_devices), struct alsa_device_info, list_node);
568 }
569 
570 /**
571  * Must be called with holding the stream's lock.
572  */
stream_standby_l(struct listnode * alsa_devices,bool * standby)573 static void stream_standby_l(struct listnode *alsa_devices, bool *standby)
574 {
575     if (!*standby) {
576         struct listnode *node;
577         list_for_each (node, alsa_devices) {
578             struct alsa_device_info *device_info =
579                     node_to_item(node, struct alsa_device_info, list_node);
580             proxy_close(&device_info->proxy);
581         }
582         *standby = true;
583     }
584 }
585 
stream_clear_devices(struct listnode * alsa_devices)586 static void stream_clear_devices(struct listnode *alsa_devices)
587 {
588     struct listnode *node, *temp;
589     struct alsa_device_info *device_info = NULL;
590     list_for_each_safe (node, temp, alsa_devices) {
591         device_info = node_to_item(node, struct alsa_device_info, list_node);
592         if (device_info != NULL) {
593             list_remove(&device_info->list_node);
594             free(device_info);
595         }
596     }
597 }
598 
stream_set_new_devices(struct pcm_config * config,struct listnode * alsa_devices,unsigned int num_devices,const int cards[],const int devices[],int direction,bool is_bit_perfect)599 static int stream_set_new_devices(struct pcm_config *config,
600                                   struct listnode *alsa_devices,
601                                   unsigned int num_devices,
602                                   const int cards[],
603                                   const int devices[],
604                                   int direction,
605                                   bool is_bit_perfect)
606 {
607     int status = 0;
608     stream_clear_devices(alsa_devices);
609 
610     for (unsigned int i = 0; i < num_devices; ++i) {
611         struct alsa_device_info *device_info =
612                 (struct alsa_device_info *) calloc(1, sizeof(struct alsa_device_info));
613         profile_init(&device_info->profile, direction);
614         device_info->profile.card = cards[i];
615         device_info->profile.device = devices[i];
616         status = profile_read_device_info(&device_info->profile) ? 0 : -EINVAL;
617         if (status != 0) {
618             ALOGE("%s failed to read device info card=%d;device=%d",
619                     __func__, cards[i], devices[i]);
620             goto exit;
621         }
622         status = proxy_prepare(&device_info->proxy, &device_info->profile, config, is_bit_perfect);
623         if (status != 0) {
624             ALOGE("%s failed to prepare device card=%d;device=%d",
625                     __func__, cards[i], devices[i]);
626             goto exit;
627         }
628         list_add_tail(alsa_devices, &device_info->list_node);
629     }
630 
631 exit:
632     if (status != 0) {
633         stream_clear_devices(alsa_devices);
634     }
635     return status;
636 }
637 
stream_dump_alsa_devices(const struct listnode * alsa_devices,int fd)638 static void stream_dump_alsa_devices(const struct listnode *alsa_devices, int fd) {
639     struct listnode *node;
640     size_t i = 0;
641     list_for_each(node, alsa_devices) {
642         struct alsa_device_info *device_info =
643                 node_to_item(node, struct alsa_device_info, list_node);
644         const char* direction = device_info->profile.direction == PCM_OUT ? "Output" : "Input";
645         dprintf(fd, "%s Profile %zu:\n", direction, i);
646         profile_dump(&device_info->profile, fd);
647 
648         dprintf(fd, "%s Proxy %zu:\n", direction, i);
649         proxy_dump(&device_info->proxy, fd);
650     }
651 }
652 
653 /*
654  * OUT functions
655  */
out_get_sample_rate(const struct audio_stream * stream)656 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
657 {
658     struct alsa_device_info *device_info = stream_get_first_alsa_device(
659             &((struct stream_out*)stream)->alsa_devices);
660     if (device_info == NULL) {
661         ALOGW("%s device info is null", __func__);
662         return 0;
663     }
664     uint32_t rate = proxy_get_sample_rate(&device_info->proxy);
665     ALOGV("out_get_sample_rate() = %d", rate);
666     return rate;
667 }
668 
out_set_sample_rate(struct audio_stream * stream,uint32_t rate)669 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
670 {
671     return 0;
672 }
673 
out_get_buffer_size(const struct audio_stream * stream)674 static size_t out_get_buffer_size(const struct audio_stream *stream)
675 {
676     const struct stream_out* out = (const struct stream_out*)stream;
677     const struct alsa_device_info* device_info = stream_get_first_alsa_device(&out->alsa_devices);
678     if (device_info == NULL) {
679         ALOGW("%s device info is null", __func__);
680         return 0;
681     }
682     return proxy_get_period_size(&device_info->proxy) * audio_stream_out_frame_size(&(out->stream));
683 }
684 
out_get_channels(const struct audio_stream * stream)685 static uint32_t out_get_channels(const struct audio_stream *stream)
686 {
687     const struct stream_out *out = (const struct stream_out*)stream;
688     return out->hal_channel_mask;
689 }
690 
out_get_format(const struct audio_stream * stream)691 static audio_format_t out_get_format(const struct audio_stream *stream)
692 {
693     /* Note: The HAL doesn't do any FORMAT conversion at this time. It
694      * Relies on the framework to provide data in the specified format.
695      * This could change in the future.
696      */
697     struct alsa_device_info *device_info = stream_get_first_alsa_device(
698             &((struct stream_out*)stream)->alsa_devices);
699     if (device_info == NULL) {
700         ALOGW("%s device info is null", __func__);
701         return AUDIO_FORMAT_DEFAULT;
702     }
703     audio_format_t format = audio_format_from_pcm_format(proxy_get_format(&device_info->proxy));
704     return format;
705 }
706 
out_set_format(struct audio_stream * stream,audio_format_t format)707 static int out_set_format(struct audio_stream *stream, audio_format_t format)
708 {
709     return 0;
710 }
711 
out_standby(struct audio_stream * stream)712 static int out_standby(struct audio_stream *stream)
713 {
714     struct stream_out *out = (struct stream_out *)stream;
715 
716     stream_lock(&out->lock);
717     device_lock(out->adev);
718     stream_standby_l(&out->alsa_devices, &out->standby);
719     device_unlock(out->adev);
720     stream_unlock(&out->lock);
721     return 0;
722 }
723 
out_dump(const struct audio_stream * stream,int fd)724 static int out_dump(const struct audio_stream *stream, int fd) {
725     const struct stream_out* out_stream = (const struct stream_out*) stream;
726 
727     if (out_stream != NULL) {
728         stream_dump_alsa_devices(&out_stream->alsa_devices, fd);
729     }
730 
731     return 0;
732 }
733 
out_set_parameters(struct audio_stream * stream __unused,const char * kvpairs)734 static int out_set_parameters(struct audio_stream *stream __unused, const char *kvpairs)
735 {
736     ALOGV("out_set_parameters() keys:%s", kvpairs);
737 
738     // The set parameters here only matters when the routing devices are changed.
739     // When the device version is not less than 3.0, the framework will use create
740     // audio patch API instead of set parameters to chanage audio routing.
741     return 0;
742 }
743 
out_get_parameters(const struct audio_stream * stream,const char * keys)744 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
745 {
746     struct stream_out *out = (struct stream_out *)stream;
747     stream_lock(&out->lock);
748     struct alsa_device_info *device_info = stream_get_first_alsa_device(&out->alsa_devices);
749     char *params_str = NULL;
750     if (device_info != NULL) {
751         params_str =  device_get_parameters(&device_info->profile, keys);
752     }
753     stream_unlock(&out->lock);
754     return params_str;
755 }
756 
out_get_latency(const struct audio_stream_out * stream)757 static uint32_t out_get_latency(const struct audio_stream_out *stream)
758 {
759     struct alsa_device_info *device_info = stream_get_first_alsa_device(
760             &((struct stream_out*)stream)->alsa_devices);
761     if (device_info == NULL) {
762         ALOGW("%s device info is null", __func__);
763         return 0;
764     }
765     return proxy_get_latency(&device_info->proxy);
766 }
767 
out_set_volume(struct audio_stream_out * stream,float left,float right)768 static int out_set_volume(struct audio_stream_out *stream, float left, float right)
769 {
770     struct stream_out *out = (struct stream_out *)stream;
771     int result = -ENOSYS;
772     stream_lock(&out->lock);
773     if (out->volume_ctl != NULL) {
774         int left_volume =
775             out->min_volume_level + ceil((out->max_volume_level - out->min_volume_level) * left);
776         int right_volume =
777             out->min_volume_level + ceil((out->max_volume_level - out->min_volume_level) * right);
778         int volumes[out->volume_ctl_num_values];
779         if (out->volume_ctl_num_values == 1) {
780             volumes[0] = left_volume;
781         } else {
782             volumes[0] = left_volume;
783             volumes[1] = right_volume;
784             for (int i = 2; i < out->volume_ctl_num_values; ++i) {
785                 volumes[i] = left_volume;
786             }
787         }
788         result = mixer_ctl_set_array(out->volume_ctl, volumes, out->volume_ctl_num_values);
789         if (result != 0) {
790             ALOGE("%s error=%d left=%f right=%f", __func__, result, left, right);
791         }
792     }
793     stream_unlock(&out->lock);
794     return result;
795 }
796 
797 /* must be called with hw device and output stream mutexes locked */
start_output_stream(struct stream_out * out)798 static int start_output_stream(struct stream_out *out)
799 {
800     int status = 0;
801     struct listnode *node;
802     list_for_each(node, &out->alsa_devices) {
803         struct alsa_device_info *device_info =
804                 node_to_item(node, struct alsa_device_info, list_node);
805         ALOGV("start_output_stream(card:%d device:%d)",
806                 device_info->profile.card, device_info->profile.device);
807         status = proxy_open(&device_info->proxy);
808         if (status != 0) {
809             ALOGE("%s failed to open device(card: %d device: %d)",
810                     __func__, device_info->profile.card, device_info->profile.device);
811             goto exit;
812         } else {
813             out->standby = false;
814         }
815     }
816 
817 exit:
818     if (status != 0) {
819         list_for_each(node, &out->alsa_devices) {
820             struct alsa_device_info *device_info =
821                     node_to_item(node, struct alsa_device_info, list_node);
822             proxy_close(&device_info->proxy);
823         }
824 
825     }
826     return status;
827 }
828 
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)829 static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes)
830 {
831     int ret;
832     struct stream_out *out = (struct stream_out *)stream;
833 
834     stream_lock(&out->lock);
835     if (out->standby) {
836         ret = start_output_stream(out);
837         if (ret != 0) {
838             goto err;
839         }
840     }
841 
842     struct listnode* node;
843     list_for_each(node, &out->alsa_devices) {
844         struct alsa_device_info* device_info =
845                 node_to_item(node, struct alsa_device_info, list_node);
846         alsa_device_proxy* proxy = &device_info->proxy;
847         const void * write_buff = buffer;
848         int num_write_buff_bytes = bytes;
849         const int num_device_channels = proxy_get_channel_count(proxy); /* what we told alsa */
850         const int num_req_channels = out->hal_channel_count; /* what we told AudioFlinger */
851         if (num_device_channels != num_req_channels) {
852             /* allocate buffer */
853             const size_t required_conversion_buffer_size =
854                      bytes * num_device_channels / num_req_channels;
855             if (required_conversion_buffer_size > out->conversion_buffer_size) {
856                 out->conversion_buffer_size = required_conversion_buffer_size;
857                 out->conversion_buffer = realloc(out->conversion_buffer,
858                                                  out->conversion_buffer_size);
859             }
860             /* convert data */
861             const audio_format_t audio_format = out_get_format(&(out->stream.common));
862             const unsigned sample_size_in_bytes = audio_bytes_per_sample(audio_format);
863             num_write_buff_bytes =
864                     adjust_channels(write_buff, num_req_channels,
865                                     out->conversion_buffer, num_device_channels,
866                                     sample_size_in_bytes, num_write_buff_bytes);
867             write_buff = out->conversion_buffer;
868         }
869 
870         if (write_buff != NULL && num_write_buff_bytes != 0) {
871             proxy_write(proxy, write_buff, num_write_buff_bytes);
872         }
873     }
874 
875     stream_unlock(&out->lock);
876 
877     return bytes;
878 
879 err:
880     stream_unlock(&out->lock);
881     if (ret != 0) {
882         usleep(bytes * 1000000 / audio_stream_out_frame_size(stream) /
883                out_get_sample_rate(&stream->common));
884     }
885 
886     return bytes;
887 }
888 
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)889 static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames)
890 {
891     return -EINVAL;
892 }
893 
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)894 static int out_get_presentation_position(const struct audio_stream_out *stream,
895                                          uint64_t *frames, struct timespec *timestamp)
896 {
897     struct stream_out *out = (struct stream_out *)stream; // discard const qualifier
898     stream_lock(&out->lock);
899 
900     const struct alsa_device_info* device_info = stream_get_first_alsa_device(&out->alsa_devices);
901     const int ret = device_info == NULL ? -ENODEV :
902             proxy_get_presentation_position(&device_info->proxy, frames, timestamp);
903     stream_unlock(&out->lock);
904     return ret;
905 }
906 
out_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)907 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
908 {
909     return 0;
910 }
911 
out_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)912 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
913 {
914     return 0;
915 }
916 
out_get_next_write_timestamp(const struct audio_stream_out * stream,int64_t * timestamp)917 static int out_get_next_write_timestamp(const struct audio_stream_out *stream, int64_t *timestamp)
918 {
919     return -EINVAL;
920 }
921 
adev_open_output_stream(struct audio_hw_device * hw_dev,audio_io_handle_t handle,audio_devices_t devicesSpec __unused,audio_output_flags_t flags,struct audio_config * config,struct audio_stream_out ** stream_out,const char * address)922 static int adev_open_output_stream(struct audio_hw_device *hw_dev,
923                                    audio_io_handle_t handle,
924                                    audio_devices_t devicesSpec __unused,
925                                    audio_output_flags_t flags,
926                                    struct audio_config *config,
927                                    struct audio_stream_out **stream_out,
928                                    const char *address /*__unused*/)
929 {
930     ALOGV("adev_open_output_stream() handle:0x%X, devicesSpec:0x%X, flags:0x%X, addr:%s",
931           handle, devicesSpec, flags, address);
932 
933     const bool is_bit_perfect = ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE);
934     if (is_bit_perfect && (config->format == AUDIO_FORMAT_DEFAULT ||
935             config->sample_rate == 0 ||
936             config->channel_mask == AUDIO_CHANNEL_NONE)) {
937         ALOGE("%s request bit perfect playback, config(format=%#x, sample_rate=%u, "
938               "channel_mask=%#x) must be specified", __func__, config->format,
939               config->sample_rate, config->channel_mask);
940         return -EINVAL;
941     }
942 
943     struct stream_out *out;
944 
945     out = (struct stream_out *)calloc(1, sizeof(struct stream_out));
946     if (out == NULL) {
947         return -ENOMEM;
948     }
949 
950     /* setup function pointers */
951     out->stream.common.get_sample_rate = out_get_sample_rate;
952     out->stream.common.set_sample_rate = out_set_sample_rate;
953     out->stream.common.get_buffer_size = out_get_buffer_size;
954     out->stream.common.get_channels = out_get_channels;
955     out->stream.common.get_format = out_get_format;
956     out->stream.common.set_format = out_set_format;
957     out->stream.common.standby = out_standby;
958     out->stream.common.dump = out_dump;
959     out->stream.common.set_parameters = out_set_parameters;
960     out->stream.common.get_parameters = out_get_parameters;
961     out->stream.common.add_audio_effect = out_add_audio_effect;
962     out->stream.common.remove_audio_effect = out_remove_audio_effect;
963     out->stream.get_latency = out_get_latency;
964     out->stream.set_volume = out_set_volume;
965     out->stream.write = out_write;
966     out->stream.get_render_position = out_get_render_position;
967     out->stream.get_presentation_position = out_get_presentation_position;
968     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
969 
970     out->handle = handle;
971 
972     stream_lock_init(&out->lock);
973 
974     out->adev = (struct audio_device *)hw_dev;
975 
976     list_init(&out->alsa_devices);
977     struct alsa_device_info *device_info =
978             (struct alsa_device_info *)calloc(1, sizeof(struct alsa_device_info));
979     profile_init(&device_info->profile, PCM_OUT);
980 
981     // build this to hand to the alsa_device_proxy
982     struct pcm_config proxy_config = {};
983 
984     /* Pull out the card/device pair */
985     parse_card_device_params(address, &device_info->profile.card, &device_info->profile.device);
986 
987     profile_read_device_info(&device_info->profile);
988 
989     int ret = 0;
990 
991     /* Rate */
992     if (config->sample_rate == 0) {
993         proxy_config.rate = profile_get_default_sample_rate(&device_info->profile);
994     } else if (profile_is_sample_rate_valid(&device_info->profile, config->sample_rate)) {
995         proxy_config.rate = config->sample_rate;
996     } else {
997         ret = -EINVAL;
998         if (is_bit_perfect) {
999             ALOGE("%s requesting bit-perfect but the sample rate(%u) is not valid",
1000                     __func__, config->sample_rate);
1001             return ret;
1002         }
1003         proxy_config.rate = config->sample_rate =
1004                 profile_get_default_sample_rate(&device_info->profile);
1005     }
1006 
1007     /* TODO: This is a problem if the input does not support this rate */
1008     device_lock(out->adev);
1009     out->adev->device_sample_rate = config->sample_rate;
1010     device_unlock(out->adev);
1011 
1012     /* Format */
1013     if (config->format == AUDIO_FORMAT_DEFAULT) {
1014         proxy_config.format = profile_get_default_format(&device_info->profile);
1015         config->format = audio_format_from_pcm_format(proxy_config.format);
1016     } else {
1017         enum pcm_format fmt = pcm_format_from_audio_format(config->format);
1018         if (profile_is_format_valid(&device_info->profile, fmt)) {
1019             proxy_config.format = fmt;
1020         } else {
1021             ret = -EINVAL;
1022             if (is_bit_perfect) {
1023                 ALOGE("%s request bit-perfect but the format(%#x) is not valid",
1024                         __func__, config->format);
1025                 return ret;
1026             }
1027             proxy_config.format = profile_get_default_format(&device_info->profile);
1028             config->format = audio_format_from_pcm_format(proxy_config.format);
1029         }
1030     }
1031 
1032     /* Channels */
1033     bool calc_mask = false;
1034     if (config->channel_mask == AUDIO_CHANNEL_NONE) {
1035         /* query case */
1036         out->hal_channel_count = profile_get_default_channel_count(&device_info->profile);
1037         calc_mask = true;
1038     } else {
1039         /* explicit case */
1040         out->hal_channel_count = audio_channel_count_from_out_mask(config->channel_mask);
1041     }
1042 
1043     /* The Framework is currently limited to no more than this number of channels */
1044     if (out->hal_channel_count > FCC_LIMIT) {
1045         out->hal_channel_count = FCC_LIMIT;
1046         calc_mask = true;
1047     }
1048 
1049     if (calc_mask) {
1050         /* need to calculate the mask from channel count either because this is the query case
1051          * or the specified mask isn't valid for this device, or is more than the FW can handle */
1052         config->channel_mask = out->hal_channel_count <= FCC_2
1053                 /* position mask for mono and stereo*/
1054                 ? audio_channel_out_mask_from_count(out->hal_channel_count)
1055                 /* otherwise indexed */
1056                 : audio_channel_mask_for_index_assignment_from_count(out->hal_channel_count);
1057     }
1058 
1059     out->hal_channel_mask = config->channel_mask;
1060 
1061     // Validate the "logical" channel count against support in the "actual" profile.
1062     // if they differ, choose the "actual" number of channels *closest* to the "logical".
1063     // and store THAT in proxy_config.channels
1064     proxy_config.channels =
1065             profile_get_closest_channel_count(&device_info->profile, out->hal_channel_count);
1066     if (is_bit_perfect && proxy_config.channels != out->hal_channel_count) {
1067         ALOGE("%s request bit-perfect, but channel mask(%#x) cannot find exact match",
1068                 __func__, config->channel_mask);
1069         return -EINVAL;
1070     }
1071 
1072     ret = proxy_prepare(&device_info->proxy, &device_info->profile, &proxy_config, is_bit_perfect);
1073     if (is_bit_perfect && ret != 0) {
1074         ALOGE("%s failed to prepare proxy for bit-perfect playback, err=%d", __func__, ret);
1075         return ret;
1076     }
1077     out->config = proxy_config;
1078 
1079     list_add_tail(&out->alsa_devices, &device_info->list_node);
1080 
1081     if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
1082         out_stream_find_mixer_volume_control(out, device_info->profile.card);
1083     }
1084 
1085     /* TODO The retry mechanism isn't implemented in AudioPolicyManager/AudioFlinger
1086      * So clear any errors that may have occurred above.
1087      */
1088     ret = 0;
1089 
1090     out->conversion_buffer = NULL;
1091     out->conversion_buffer_size = 0;
1092 
1093     out->standby = true;
1094 
1095     /* Save the stream for adev_dump() */
1096     adev_add_stream_to_list(out->adev, &out->adev->output_stream_list, &out->list_node);
1097 
1098     *stream_out = &out->stream;
1099 
1100     return ret;
1101 }
1102 
adev_close_output_stream(struct audio_hw_device * hw_dev,struct audio_stream_out * stream)1103 static void adev_close_output_stream(struct audio_hw_device *hw_dev,
1104                                      struct audio_stream_out *stream)
1105 {
1106     struct stream_out *out = (struct stream_out *)stream;
1107 
1108     stream_lock(&out->lock);
1109     /* Close the pcm device */
1110     stream_standby_l(&out->alsa_devices, &out->standby);
1111     stream_clear_devices(&out->alsa_devices);
1112 
1113     free(out->conversion_buffer);
1114 
1115     out->conversion_buffer = NULL;
1116     out->conversion_buffer_size = 0;
1117 
1118     if (out->volume_ctl != NULL) {
1119         for (int i = 0; i < out->volume_ctl_num_values; ++i) {
1120             mixer_ctl_set_value(out->volume_ctl, i, out->max_volume_level);
1121         }
1122         out->volume_ctl = NULL;
1123     }
1124     if (out->mixer != NULL) {
1125         mixer_close(out->mixer);
1126         out->mixer = NULL;
1127     }
1128 
1129     device_lock(out->adev);
1130     list_remove(&out->list_node);
1131     out->adev->device_sample_rate = 0;
1132     device_unlock(out->adev);
1133     stream_unlock(&out->lock);
1134 
1135     free(stream);
1136 }
1137 
adev_get_input_buffer_size(const struct audio_hw_device * hw_dev,const struct audio_config * config)1138 static size_t adev_get_input_buffer_size(const struct audio_hw_device *hw_dev,
1139                                          const struct audio_config *config)
1140 {
1141     /* TODO This needs to be calculated based on format/channels/rate */
1142     return 320;
1143 }
1144 
1145 /*
1146  * IN functions
1147  */
in_get_sample_rate(const struct audio_stream * stream)1148 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
1149 {
1150     struct alsa_device_info *device_info = stream_get_first_alsa_device(
1151             &((const struct stream_in *)stream)->alsa_devices);
1152     if (device_info == NULL) {
1153         ALOGW("%s device info is null", __func__);
1154         return 0;
1155     }
1156     uint32_t rate = proxy_get_sample_rate(&device_info->proxy);
1157     ALOGV("in_get_sample_rate() = %d", rate);
1158     return rate;
1159 }
1160 
in_set_sample_rate(struct audio_stream * stream,uint32_t rate)1161 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1162 {
1163     ALOGV("in_set_sample_rate(%d) - NOPE", rate);
1164     return -ENOSYS;
1165 }
1166 
in_get_buffer_size(const struct audio_stream * stream)1167 static size_t in_get_buffer_size(const struct audio_stream *stream)
1168 {
1169     const struct stream_in * in = ((const struct stream_in*)stream);
1170     struct alsa_device_info *device_info = stream_get_first_alsa_device(&in->alsa_devices);
1171     if (device_info == NULL) {
1172         ALOGW("%s device info is null", __func__);
1173         return 0;
1174     }
1175     return proxy_get_period_size(&device_info->proxy) * audio_stream_in_frame_size(&(in->stream));
1176 }
1177 
in_get_channels(const struct audio_stream * stream)1178 static uint32_t in_get_channels(const struct audio_stream *stream)
1179 {
1180     const struct stream_in *in = (const struct stream_in*)stream;
1181     return in->hal_channel_mask;
1182 }
1183 
in_get_format(const struct audio_stream * stream)1184 static audio_format_t in_get_format(const struct audio_stream *stream)
1185 {
1186     struct alsa_device_info *device_info = stream_get_first_alsa_device(
1187             &((const struct stream_in *)stream)->alsa_devices);
1188     if (device_info == NULL) {
1189         ALOGW("%s device info is null", __func__);
1190         return AUDIO_FORMAT_DEFAULT;
1191     }
1192      alsa_device_proxy *proxy = &device_info->proxy;
1193      audio_format_t format = audio_format_from_pcm_format(proxy_get_format(proxy));
1194      return format;
1195 }
1196 
in_set_format(struct audio_stream * stream,audio_format_t format)1197 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1198 {
1199     ALOGV("in_set_format(%d) - NOPE", format);
1200 
1201     return -ENOSYS;
1202 }
1203 
in_standby(struct audio_stream * stream)1204 static int in_standby(struct audio_stream *stream)
1205 {
1206     struct stream_in *in = (struct stream_in *)stream;
1207 
1208     stream_lock(&in->lock);
1209     device_lock(in->adev);
1210     stream_standby_l(&in->alsa_devices, &in->standby);
1211     device_unlock(in->adev);
1212     stream_unlock(&in->lock);
1213     return 0;
1214 }
1215 
in_dump(const struct audio_stream * stream,int fd)1216 static int in_dump(const struct audio_stream *stream, int fd)
1217 {
1218   const struct stream_in* in_stream = (const struct stream_in*)stream;
1219   if (in_stream != NULL) {
1220       stream_dump_alsa_devices(&in_stream->alsa_devices, fd);
1221   }
1222 
1223   return 0;
1224 }
1225 
in_set_parameters(struct audio_stream * stream,const char * kvpairs)1226 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1227 {
1228     ALOGV("in_set_parameters() keys:%s", kvpairs);
1229 
1230     // The set parameters here only matters when the routing devices are changed.
1231     // When the device version higher than 3.0, the framework will use create_audio_patch
1232     // API instead of set_parameters to change audio routing.
1233     return 0;
1234 }
1235 
in_get_parameters(const struct audio_stream * stream,const char * keys)1236 static char * in_get_parameters(const struct audio_stream *stream, const char *keys)
1237 {
1238     struct stream_in *in = (struct stream_in *)stream;
1239 
1240     stream_lock(&in->lock);
1241     struct alsa_device_info *device_info = stream_get_first_alsa_device(&in->alsa_devices);
1242     char *params_str = NULL;
1243     if (device_info != NULL) {
1244         params_str =  device_get_parameters(&device_info->profile, keys);
1245     }
1246     stream_unlock(&in->lock);
1247 
1248     return params_str;
1249 }
1250 
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1251 static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1252 {
1253     return 0;
1254 }
1255 
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1256 static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1257 {
1258     return 0;
1259 }
1260 
in_set_gain(struct audio_stream_in * stream,float gain)1261 static int in_set_gain(struct audio_stream_in *stream, float gain)
1262 {
1263     return 0;
1264 }
1265 
1266 /* must be called with hw device and input stream mutexes locked */
start_input_stream(struct stream_in * in)1267 static int start_input_stream(struct stream_in *in)
1268 {
1269     // Only care about the first device as only one input device is allowed.
1270     struct alsa_device_info *device_info = stream_get_first_alsa_device(&in->alsa_devices);
1271     if (device_info == NULL) {
1272         return -ENODEV;
1273     }
1274 
1275     ALOGV("start_input_stream(card:%d device:%d)",
1276             device_info->profile.card, device_info->profile.device);
1277     int ret = proxy_open(&device_info->proxy);
1278     if (ret == 0) {
1279         in->standby = false;
1280     }
1281     return ret;
1282 }
1283 
1284 /* TODO mutex stuff here (see out_write) */
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)1285 static ssize_t in_read(struct audio_stream_in *stream, void* buffer, size_t bytes)
1286 {
1287     size_t num_read_buff_bytes = 0;
1288     void * read_buff = buffer;
1289     void * out_buff = buffer;
1290     int ret = 0;
1291 
1292     struct stream_in * in = (struct stream_in *)stream;
1293 
1294     stream_lock(&in->lock);
1295     if (in->standby) {
1296         ret = start_input_stream(in);
1297         if (ret != 0) {
1298             goto err;
1299         }
1300     }
1301 
1302     // Only care about the first device as only one input device is allowed.
1303     struct alsa_device_info *device_info = stream_get_first_alsa_device(&in->alsa_devices);
1304     if (device_info == NULL) {
1305         return 0;
1306     }
1307 
1308     /*
1309      * OK, we need to figure out how much data to read to be able to output the requested
1310      * number of bytes in the HAL format (16-bit, stereo).
1311      */
1312     num_read_buff_bytes = bytes;
1313     int num_device_channels = proxy_get_channel_count(&device_info->proxy); /* what we told Alsa */
1314     int num_req_channels = in->hal_channel_count; /* what we told AudioFlinger */
1315 
1316     if (num_device_channels != num_req_channels) {
1317         num_read_buff_bytes = (num_device_channels * num_read_buff_bytes) / num_req_channels;
1318     }
1319 
1320     /* Setup/Realloc the conversion buffer (if necessary). */
1321     if (num_read_buff_bytes != bytes) {
1322         if (num_read_buff_bytes > in->conversion_buffer_size) {
1323             /*TODO Remove this when AudioPolicyManger/AudioFlinger support arbitrary formats
1324               (and do these conversions themselves) */
1325             in->conversion_buffer_size = num_read_buff_bytes;
1326             in->conversion_buffer = realloc(in->conversion_buffer, in->conversion_buffer_size);
1327         }
1328         read_buff = in->conversion_buffer;
1329     }
1330 
1331     ret = proxy_read(&device_info->proxy, read_buff, num_read_buff_bytes);
1332     if (ret == 0) {
1333         if (num_device_channels != num_req_channels) {
1334             // ALOGV("chans dev:%d req:%d", num_device_channels, num_req_channels);
1335 
1336             out_buff = buffer;
1337             /* Num Channels conversion */
1338             if (num_device_channels != num_req_channels) {
1339                 audio_format_t audio_format = in_get_format(&(in->stream.common));
1340                 unsigned sample_size_in_bytes = audio_bytes_per_sample(audio_format);
1341 
1342                 num_read_buff_bytes =
1343                     adjust_channels(read_buff, num_device_channels,
1344                                     out_buff, num_req_channels,
1345                                     sample_size_in_bytes, num_read_buff_bytes);
1346             }
1347         }
1348 
1349         /* no need to acquire in->adev->lock to read mic_muted here as we don't change its state */
1350         if (num_read_buff_bytes > 0 && in->adev->mic_muted)
1351             memset(buffer, 0, num_read_buff_bytes);
1352     } else {
1353         num_read_buff_bytes = 0; // reset the value after USB headset is unplugged
1354     }
1355 
1356 err:
1357     stream_unlock(&in->lock);
1358     return num_read_buff_bytes;
1359 }
1360 
in_get_input_frames_lost(struct audio_stream_in * stream)1361 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1362 {
1363     return 0;
1364 }
1365 
in_get_capture_position(const struct audio_stream_in * stream,int64_t * frames,int64_t * time)1366 static int in_get_capture_position(const struct audio_stream_in *stream,
1367                                    int64_t *frames, int64_t *time)
1368 {
1369     struct stream_in *in = (struct stream_in *)stream; // discard const qualifier
1370     stream_lock(&in->lock);
1371 
1372     struct alsa_device_info *device_info = stream_get_first_alsa_device(&in->alsa_devices);
1373 
1374     const int ret = device_info == NULL ? -ENODEV
1375             : proxy_get_capture_position(&device_info->proxy, frames, time);
1376 
1377     stream_unlock(&in->lock);
1378     return ret;
1379 }
1380 
in_get_active_microphones(const struct audio_stream_in * stream,struct audio_microphone_characteristic_t * mic_array,size_t * mic_count)1381 static int in_get_active_microphones(const struct audio_stream_in *stream,
1382                                      struct audio_microphone_characteristic_t *mic_array,
1383                                      size_t *mic_count) {
1384     (void)stream;
1385     (void)mic_array;
1386     (void)mic_count;
1387 
1388     return -ENOSYS;
1389 }
1390 
in_set_microphone_direction(const struct audio_stream_in * stream,audio_microphone_direction_t dir)1391 static int in_set_microphone_direction(const struct audio_stream_in *stream,
1392                                            audio_microphone_direction_t dir) {
1393     (void)stream;
1394     (void)dir;
1395     ALOGV("---- in_set_microphone_direction()");
1396     return -ENOSYS;
1397 }
1398 
in_set_microphone_field_dimension(const struct audio_stream_in * stream,float zoom)1399 static int in_set_microphone_field_dimension(const struct audio_stream_in *stream, float zoom) {
1400     (void)zoom;
1401     ALOGV("---- in_set_microphone_field_dimension()");
1402     return -ENOSYS;
1403 }
1404 
adev_open_input_stream(struct audio_hw_device * hw_dev,audio_io_handle_t handle,audio_devices_t devicesSpec __unused,struct audio_config * config,struct audio_stream_in ** stream_in,audio_input_flags_t flags __unused,const char * address,audio_source_t source __unused)1405 static int adev_open_input_stream(struct audio_hw_device *hw_dev,
1406                                   audio_io_handle_t handle,
1407                                   audio_devices_t devicesSpec __unused,
1408                                   struct audio_config *config,
1409                                   struct audio_stream_in **stream_in,
1410                                   audio_input_flags_t flags __unused,
1411                                   const char *address,
1412                                   audio_source_t source __unused)
1413 {
1414     ALOGV("adev_open_input_stream() rate:%" PRIu32 ", chanMask:0x%" PRIX32 ", fmt:%" PRIu8,
1415           config->sample_rate, config->channel_mask, config->format);
1416 
1417     /* Pull out the card/device pair */
1418     int32_t card, device;
1419     if (!parse_card_device_params(address, &card, &device)) {
1420         ALOGW("%s fail - invalid address %s", __func__, address);
1421         *stream_in = NULL;
1422         return -EINVAL;
1423     }
1424 
1425     struct stream_in * const in = (struct stream_in *)calloc(1, sizeof(struct stream_in));
1426     if (in == NULL) {
1427         *stream_in = NULL;
1428         return -ENOMEM;
1429     }
1430 
1431     /* setup function pointers */
1432     in->stream.common.get_sample_rate = in_get_sample_rate;
1433     in->stream.common.set_sample_rate = in_set_sample_rate;
1434     in->stream.common.get_buffer_size = in_get_buffer_size;
1435     in->stream.common.get_channels = in_get_channels;
1436     in->stream.common.get_format = in_get_format;
1437     in->stream.common.set_format = in_set_format;
1438     in->stream.common.standby = in_standby;
1439     in->stream.common.dump = in_dump;
1440     in->stream.common.set_parameters = in_set_parameters;
1441     in->stream.common.get_parameters = in_get_parameters;
1442     in->stream.common.add_audio_effect = in_add_audio_effect;
1443     in->stream.common.remove_audio_effect = in_remove_audio_effect;
1444 
1445     in->stream.set_gain = in_set_gain;
1446     in->stream.read = in_read;
1447     in->stream.get_input_frames_lost = in_get_input_frames_lost;
1448     in->stream.get_capture_position = in_get_capture_position;
1449 
1450     in->stream.get_active_microphones = in_get_active_microphones;
1451     in->stream.set_microphone_direction = in_set_microphone_direction;
1452     in->stream.set_microphone_field_dimension = in_set_microphone_field_dimension;
1453 
1454     in->handle = handle;
1455 
1456     stream_lock_init(&in->lock);
1457 
1458     in->adev = (struct audio_device *)hw_dev;
1459 
1460     list_init(&in->alsa_devices);
1461     struct alsa_device_info *device_info =
1462             (struct alsa_device_info *)calloc(1, sizeof(struct alsa_device_info));
1463     profile_init(&device_info->profile, PCM_IN);
1464 
1465     memset(&in->config, 0, sizeof(in->config));
1466 
1467     int ret = 0;
1468     device_lock(in->adev);
1469     int num_open_inputs = in->adev->inputs_open;
1470     device_unlock(in->adev);
1471 
1472     /* Check if an input stream is already open */
1473     if (num_open_inputs > 0) {
1474         if (!profile_is_cached_for(&device_info->profile, card, device)) {
1475             ALOGW("%s fail - address card:%d device:%d doesn't match existing profile",
1476                     __func__, card, device);
1477             ret = -EINVAL;
1478         }
1479     } else {
1480         /* Read input profile only if necessary */
1481         device_info->profile.card = card;
1482         device_info->profile.device = device;
1483         if (!profile_read_device_info(&device_info->profile)) {
1484             ALOGW("%s fail - cannot read profile", __func__);
1485             ret = -EINVAL;
1486         }
1487     }
1488     if (ret != 0) {
1489         free(in);
1490         *stream_in = NULL;
1491         return ret;
1492     }
1493 
1494     /* Rate */
1495     int request_config_rate = config->sample_rate;
1496     if (config->sample_rate == 0) {
1497         config->sample_rate = profile_get_default_sample_rate(&device_info->profile);
1498     }
1499 
1500     if (in->adev->device_sample_rate != 0 &&   /* we are playing, so lock the rate if possible */
1501         in->adev->device_sample_rate >= RATELOCK_THRESHOLD) {/* but only for high sample rates */
1502         if (config->sample_rate != in->adev->device_sample_rate) {
1503             unsigned highest_rate = profile_get_highest_sample_rate(&device_info->profile);
1504             if (highest_rate == 0) {
1505                 ret = -EINVAL; /* error with device */
1506             } else {
1507                 in->config.rate = config->sample_rate =
1508                         min(highest_rate, in->adev->device_sample_rate);
1509                 if (request_config_rate != 0 && in->config.rate != config->sample_rate) {
1510                     /* Changing the requested rate */
1511                     ret = -EINVAL;
1512                 } else {
1513                     /* Everything AOK! */
1514                     ret = 0;
1515                 }
1516             }
1517         } else if (profile_is_sample_rate_valid(&device_info->profile, config->sample_rate)) {
1518             in->config.rate = config->sample_rate;
1519         }
1520     } else if (profile_is_sample_rate_valid(&device_info->profile, config->sample_rate)) {
1521         in->config.rate = config->sample_rate;
1522     } else {
1523         in->config.rate = config->sample_rate =
1524                 profile_get_default_sample_rate(&device_info->profile);
1525         ret = -EINVAL;
1526     }
1527 
1528     /* Format */
1529     if (config->format == AUDIO_FORMAT_DEFAULT) {
1530         in->config.format = profile_get_default_format(&device_info->profile);
1531         config->format = audio_format_from_pcm_format(in->config.format);
1532     } else {
1533         enum pcm_format fmt = pcm_format_from_audio_format(config->format);
1534         if (profile_is_format_valid(&device_info->profile, fmt)) {
1535             in->config.format = fmt;
1536         } else {
1537             in->config.format = profile_get_default_format(&device_info->profile);
1538             config->format = audio_format_from_pcm_format(in->config.format);
1539             ret = -EINVAL;
1540         }
1541     }
1542 
1543     /* Channels */
1544     bool calc_mask = false;
1545     if (config->channel_mask == AUDIO_CHANNEL_NONE) {
1546         /* query case */
1547         in->hal_channel_count = profile_get_default_channel_count(&device_info->profile);
1548         calc_mask = true;
1549     } else {
1550         /* explicit case */
1551         in->hal_channel_count = audio_channel_count_from_in_mask(config->channel_mask);
1552     }
1553 
1554     /* The Framework is currently limited to no more than this number of channels */
1555     if (in->hal_channel_count > FCC_LIMIT) {
1556         in->hal_channel_count = FCC_LIMIT;
1557         calc_mask = true;
1558     }
1559 
1560     if (calc_mask) {
1561         /* need to calculate the mask from channel count either because this is the query case
1562          * or the specified mask isn't valid for this device, or is more than the FW can handle */
1563         in->hal_channel_mask = in->hal_channel_count <= FCC_2
1564             /* position mask for mono & stereo */
1565             ? audio_channel_in_mask_from_count(in->hal_channel_count)
1566             /* otherwise indexed */
1567             : audio_channel_mask_for_index_assignment_from_count(in->hal_channel_count);
1568 
1569         // if we change the mask...
1570         if (in->hal_channel_mask != config->channel_mask &&
1571             config->channel_mask != AUDIO_CHANNEL_NONE) {
1572             config->channel_mask = in->hal_channel_mask;
1573             ret = -EINVAL;
1574         }
1575     } else {
1576         in->hal_channel_mask = config->channel_mask;
1577     }
1578 
1579     if (ret == 0) {
1580         // Validate the "logical" channel count against support in the "actual" profile.
1581         // if they differ, choose the "actual" number of channels *closest* to the "logical".
1582         // and store THAT in proxy_config.channels
1583         in->config.channels =
1584                 profile_get_closest_channel_count(&device_info->profile, in->hal_channel_count);
1585         ret = proxy_prepare(&device_info->proxy, &device_info->profile, &in->config,
1586                             false /*require_exact_match*/);
1587         if (ret == 0) {
1588             in->standby = true;
1589 
1590             in->conversion_buffer = NULL;
1591             in->conversion_buffer_size = 0;
1592 
1593             *stream_in = &in->stream;
1594 
1595             /* Save this for adev_dump() */
1596             adev_add_stream_to_list(in->adev, &in->adev->input_stream_list, &in->list_node);
1597         } else {
1598             ALOGW("proxy_prepare error %d", ret);
1599             unsigned channel_count = proxy_get_channel_count(&device_info->proxy);
1600             config->channel_mask = channel_count <= FCC_2
1601                 ? audio_channel_in_mask_from_count(channel_count)
1602                 : audio_channel_mask_for_index_assignment_from_count(channel_count);
1603             config->format = audio_format_from_pcm_format(proxy_get_format(&device_info->proxy));
1604             config->sample_rate = proxy_get_sample_rate(&device_info->proxy);
1605         }
1606     }
1607 
1608     if (ret != 0) {
1609         // Deallocate this stream on error, because AudioFlinger won't call
1610         // adev_close_input_stream() in this case.
1611         *stream_in = NULL;
1612         free(in);
1613         return ret;
1614     }
1615 
1616     list_add_tail(&in->alsa_devices, &device_info->list_node);
1617 
1618     device_lock(in->adev);
1619     ++in->adev->inputs_open;
1620     device_unlock(in->adev);
1621 
1622     return ret;
1623 }
1624 
adev_close_input_stream(struct audio_hw_device * hw_dev,struct audio_stream_in * stream)1625 static void adev_close_input_stream(struct audio_hw_device *hw_dev,
1626                                     struct audio_stream_in *stream)
1627 {
1628     struct stream_in *in = (struct stream_in *)stream;
1629 
1630     stream_lock(&in->lock);
1631     device_lock(in->adev);
1632     list_remove(&in->list_node);
1633     --in->adev->inputs_open;
1634     struct alsa_device_info *device_info = stream_get_first_alsa_device(&in->alsa_devices);
1635     if (device_info != NULL) {
1636         ALOGV("adev_close_input_stream(c:%d d:%d)",
1637                 device_info->profile.card, device_info->profile.device);
1638     }
1639     LOG_ALWAYS_FATAL_IF(in->adev->inputs_open < 0,
1640             "invalid inputs_open: %d", in->adev->inputs_open);
1641 
1642     stream_standby_l(&in->alsa_devices, &in->standby);
1643 
1644     device_unlock(in->adev);
1645 
1646     stream_clear_devices(&in->alsa_devices);
1647     stream_unlock(&in->lock);
1648 
1649     free(in->conversion_buffer);
1650 
1651     free(stream);
1652 }
1653 
1654 /*
1655  * ADEV Functions
1656  */
adev_set_parameters(struct audio_hw_device * hw_dev,const char * kvpairs)1657 static int adev_set_parameters(struct audio_hw_device *hw_dev, const char *kvpairs)
1658 {
1659     return 0;
1660 }
1661 
adev_get_parameters(const struct audio_hw_device * hw_dev,const char * keys)1662 static char * adev_get_parameters(const struct audio_hw_device *hw_dev, const char *keys)
1663 {
1664     return strdup("");
1665 }
1666 
adev_init_check(const struct audio_hw_device * hw_dev)1667 static int adev_init_check(const struct audio_hw_device *hw_dev)
1668 {
1669     return 0;
1670 }
1671 
adev_set_voice_volume(struct audio_hw_device * hw_dev,float volume)1672 static int adev_set_voice_volume(struct audio_hw_device *hw_dev, float volume)
1673 {
1674     return -ENOSYS;
1675 }
1676 
adev_set_master_volume(struct audio_hw_device * hw_dev,float volume)1677 static int adev_set_master_volume(struct audio_hw_device *hw_dev, float volume)
1678 {
1679     return -ENOSYS;
1680 }
1681 
adev_set_mode(struct audio_hw_device * hw_dev,audio_mode_t mode)1682 static int adev_set_mode(struct audio_hw_device *hw_dev, audio_mode_t mode)
1683 {
1684     return 0;
1685 }
1686 
adev_set_mic_mute(struct audio_hw_device * hw_dev,bool state)1687 static int adev_set_mic_mute(struct audio_hw_device *hw_dev, bool state)
1688 {
1689     struct audio_device * adev = (struct audio_device *)hw_dev;
1690     device_lock(adev);
1691     adev->mic_muted = state;
1692     device_unlock(adev);
1693     return -ENOSYS;
1694 }
1695 
adev_get_mic_mute(const struct audio_hw_device * hw_dev,bool * state)1696 static int adev_get_mic_mute(const struct audio_hw_device *hw_dev, bool *state)
1697 {
1698     return -ENOSYS;
1699 }
1700 
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)1701 static int adev_create_audio_patch(struct audio_hw_device *dev,
1702                                    unsigned int num_sources,
1703                                    const struct audio_port_config *sources,
1704                                    unsigned int num_sinks,
1705                                    const struct audio_port_config *sinks,
1706                                    audio_patch_handle_t *handle) {
1707     if (num_sources != 1 || num_sinks == 0 || num_sinks > AUDIO_PATCH_PORTS_MAX) {
1708         // Only accept mix->device and device->mix cases. In that case, the number of sources
1709         // must be 1. The number of sinks must be in the range of (0, AUDIO_PATCH_PORTS_MAX].
1710         return -EINVAL;
1711     }
1712 
1713     if (sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1714         // If source is a device, the number of sinks should be 1.
1715         if (num_sinks != 1 || sinks[0].type != AUDIO_PORT_TYPE_MIX) {
1716             return -EINVAL;
1717         }
1718     } else if (sources[0].type == AUDIO_PORT_TYPE_MIX) {
1719         // If source is a mix, all sinks should be device.
1720         for (unsigned int i = 0; i < num_sinks; i++) {
1721             if (sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
1722                 ALOGE("%s() invalid sink type %#x for mix source", __func__, sinks[i].type);
1723                 return -EINVAL;
1724             }
1725         }
1726     } else {
1727         // All other cases are invalid.
1728         return -EINVAL;
1729     }
1730 
1731     struct audio_device* adev = (struct audio_device*) dev;
1732     bool generatedPatchHandle = false;
1733     device_lock(adev);
1734     if (*handle == AUDIO_PATCH_HANDLE_NONE) {
1735         *handle = ++adev->next_patch_handle;
1736         generatedPatchHandle = true;
1737     }
1738 
1739     int cards[AUDIO_PATCH_PORTS_MAX];
1740     int devices[AUDIO_PATCH_PORTS_MAX];
1741     const struct audio_port_config *port_configs =
1742             sources[0].type == AUDIO_PORT_TYPE_DEVICE ? sources : sinks;
1743     int num_configs = 0;
1744     audio_io_handle_t io_handle = 0;
1745     bool wasStandby = true;
1746     int direction = PCM_OUT;
1747     audio_patch_handle_t *patch_handle = NULL;
1748     struct listnode *alsa_devices = NULL;
1749     struct stream_lock *lock = NULL;
1750     struct pcm_config *config = NULL;
1751     struct stream_in *in = NULL;
1752     struct stream_out *out = NULL;
1753     bool is_bit_perfect = false;
1754 
1755     unsigned int num_saved_devices = 0;
1756     int saved_cards[AUDIO_PATCH_PORTS_MAX];
1757     int saved_devices[AUDIO_PATCH_PORTS_MAX];
1758 
1759     struct listnode *node;
1760 
1761     // Only handle patches for mix->devices and device->mix case.
1762     if (sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1763         in = adev_get_stream_in_by_io_handle_l(adev, sinks[0].ext.mix.handle);
1764         if (in == NULL) {
1765             ALOGE("%s()can not find stream with handle(%d)", __func__, sinks[0].ext.mix.handle);
1766             device_unlock(adev);
1767             return -EINVAL;
1768         }
1769 
1770         direction = PCM_IN;
1771         wasStandby = in->standby;
1772         io_handle = in->handle;
1773         num_configs = num_sources;
1774         patch_handle = &in->patch_handle;
1775         alsa_devices = &in->alsa_devices;
1776         lock = &in->lock;
1777         config = &in->config;
1778     } else {
1779         out = adev_get_stream_out_by_io_handle_l(adev, sources[0].ext.mix.handle);
1780         if (out == NULL) {
1781             ALOGE("%s()can not find stream with handle(%d)", __func__, sources[0].ext.mix.handle);
1782             device_unlock(adev);
1783             return -EINVAL;
1784         }
1785 
1786         direction = PCM_OUT;
1787         wasStandby = out->standby;
1788         io_handle = out->handle;
1789         num_configs = num_sinks;
1790         patch_handle = &out->patch_handle;
1791         alsa_devices = &out->alsa_devices;
1792         lock = &out->lock;
1793         config = &out->config;
1794         is_bit_perfect = out->is_bit_perfect;
1795     }
1796 
1797     // Check if the patch handle match the recorded one if a valid patch handle is passed.
1798     if (!generatedPatchHandle && *patch_handle != *handle) {
1799         ALOGE("%s() the patch handle(%d) does not match recorded one(%d) for stream "
1800               "with handle(%d) when creating audio patch",
1801               __func__, *handle, *patch_handle, io_handle);
1802         device_unlock(adev);
1803         return -EINVAL;
1804     }
1805     device_unlock(adev);
1806 
1807     for (unsigned int i = 0; i < num_configs; ++i) {
1808         if (!parse_card_device_params(port_configs[i].ext.device.address, &cards[i], &devices[i])) {
1809             ALOGE("%s, failed to parse card and device %s",
1810                     __func__, port_configs[i].ext.device.address);
1811             return -EINVAL;
1812         }
1813     }
1814 
1815     stream_lock(lock);
1816     list_for_each (node, alsa_devices) {
1817         struct alsa_device_info *device_info =
1818                 node_to_item(node, struct alsa_device_info, list_node);
1819         saved_cards[num_saved_devices] = device_info->profile.card;
1820         saved_devices[num_saved_devices++] = device_info->profile.device;
1821     }
1822 
1823     if (are_devices_the_same(
1824                 num_configs, cards, devices, num_saved_devices, saved_cards, saved_devices)) {
1825         // The new devices are the same as original ones. No need to update.
1826         stream_unlock(lock);
1827         return 0;
1828     }
1829 
1830     device_lock(adev);
1831     stream_standby_l(alsa_devices, out == NULL ? &in->standby : &out->standby);
1832     device_unlock(adev);
1833 
1834     // Timestamps:
1835     // Audio timestamps assume continuous PCM frame counts which are maintained
1836     // with the device proxy.transferred variable.  Technically it would be better
1837     // associated with in or out stream, not the device; here we save and restore
1838     // using the first alsa device as a simplification.
1839     uint64_t saved_transferred_frames = 0;
1840     struct alsa_device_info *device_info = stream_get_first_alsa_device(alsa_devices);
1841     if (device_info != NULL) saved_transferred_frames = device_info->proxy.transferred;
1842 
1843     int ret = stream_set_new_devices(
1844             config, alsa_devices, num_configs, cards, devices, direction, is_bit_perfect);
1845 
1846     if (ret != 0) {
1847         *handle = generatedPatchHandle ? AUDIO_PATCH_HANDLE_NONE : *handle;
1848         stream_set_new_devices(
1849                 config, alsa_devices, num_saved_devices, saved_cards, saved_devices, direction,
1850                 is_bit_perfect);
1851     } else {
1852         *patch_handle = *handle;
1853     }
1854 
1855     // Timestamps: Restore transferred frames.
1856     if (saved_transferred_frames != 0) {
1857         device_info = stream_get_first_alsa_device(alsa_devices);
1858         if (device_info != NULL) device_info->proxy.transferred = saved_transferred_frames;
1859     }
1860 
1861     if (!wasStandby) {
1862         device_lock(adev);
1863         if (in != NULL) {
1864             ret = start_input_stream(in);
1865         }
1866         if (out != NULL) {
1867             ret = start_output_stream(out);
1868         }
1869         device_unlock(adev);
1870     }
1871     stream_unlock(lock);
1872     return ret;
1873 }
1874 
adev_release_audio_patch(struct audio_hw_device * dev,audio_patch_handle_t patch_handle)1875 static int adev_release_audio_patch(struct audio_hw_device *dev,
1876                                     audio_patch_handle_t patch_handle)
1877 {
1878     struct audio_device* adev = (struct audio_device*) dev;
1879 
1880     device_lock(adev);
1881     struct stream_out *out = adev_get_stream_out_by_patch_handle_l(adev, patch_handle);
1882     device_unlock(adev);
1883     if (out != NULL) {
1884         stream_lock(&out->lock);
1885         device_lock(adev);
1886         stream_standby_l(&out->alsa_devices, &out->standby);
1887         device_unlock(adev);
1888         out->patch_handle = AUDIO_PATCH_HANDLE_NONE;
1889         stream_unlock(&out->lock);
1890         return 0;
1891     }
1892 
1893     device_lock(adev);
1894     struct stream_in *in = adev_get_stream_in_by_patch_handle_l(adev, patch_handle);
1895     device_unlock(adev);
1896     if (in != NULL) {
1897         stream_lock(&in->lock);
1898         device_lock(adev);
1899         stream_standby_l(&in->alsa_devices, &in->standby);
1900         device_unlock(adev);
1901         in->patch_handle = AUDIO_PATCH_HANDLE_NONE;
1902         stream_unlock(&in->lock);
1903         return 0;
1904     }
1905 
1906     ALOGE("%s cannot find stream with patch handle as %d", __func__, patch_handle);
1907     return -EINVAL;
1908 }
1909 
adev_get_audio_port(struct audio_hw_device * dev,struct audio_port * port)1910 static int adev_get_audio_port(struct audio_hw_device *dev, struct audio_port *port)
1911 {
1912     if (port->type != AUDIO_PORT_TYPE_DEVICE) {
1913         return -EINVAL;
1914     }
1915 
1916     alsa_device_profile profile;
1917     const bool is_output = audio_is_output_device(port->ext.device.type);
1918     profile_init(&profile, is_output ? PCM_OUT : PCM_IN);
1919     if (!parse_card_device_params(port->ext.device.address, &profile.card, &profile.device)) {
1920         return -EINVAL;
1921     }
1922 
1923     if (!profile_read_device_info(&profile)) {
1924         return -ENOENT;
1925     }
1926 
1927     port->num_formats = 0;;
1928     for (size_t i = 0; i < min(MAX_PROFILE_FORMATS, AUDIO_PORT_MAX_FORMATS) &&
1929             profile.formats[i] != 0; ++i) {
1930         audio_format_t format = audio_format_from(profile.formats[i]);
1931         if (format != AUDIO_FORMAT_INVALID) {
1932             port->formats[port->num_formats++] = format;
1933         }
1934     }
1935 
1936     port->num_sample_rates = populate_sample_rates_from_profile(&profile, port->sample_rates);
1937     port->num_channel_masks = populate_channel_mask_from_profile(
1938             &profile, is_output, port->channel_masks);
1939 
1940     return 0;
1941 }
1942 
adev_get_audio_port_v7(struct audio_hw_device * dev,struct audio_port_v7 * port)1943 static int adev_get_audio_port_v7(struct audio_hw_device *dev, struct audio_port_v7 *port)
1944 {
1945     if (port->type != AUDIO_PORT_TYPE_DEVICE) {
1946         return -EINVAL;
1947     }
1948 
1949     alsa_device_profile profile;
1950     const bool is_output = audio_is_output_device(port->ext.device.type);
1951     profile_init(&profile, is_output ? PCM_OUT : PCM_IN);
1952     if (!parse_card_device_params(port->ext.device.address, &profile.card, &profile.device)) {
1953         return -EINVAL;
1954     }
1955 
1956     if (!profile_read_device_info(&profile)) {
1957         return -ENOENT;
1958     }
1959 
1960     audio_channel_mask_t channel_masks[AUDIO_PORT_MAX_CHANNEL_MASKS];
1961     unsigned int num_channel_masks = populate_channel_mask_from_profile(
1962             &profile, is_output, channel_masks);
1963     unsigned int sample_rates[AUDIO_PORT_MAX_SAMPLING_RATES];
1964     const unsigned int num_sample_rates =
1965             populate_sample_rates_from_profile(&profile, sample_rates);
1966     port->num_audio_profiles = 0;;
1967     for (size_t i = 0; i < min(MAX_PROFILE_FORMATS, AUDIO_PORT_MAX_AUDIO_PROFILES) &&
1968             profile.formats[i] != 0; ++i) {
1969         audio_format_t format = audio_format_from(profile.formats[i]);
1970         if (format == AUDIO_FORMAT_INVALID) {
1971             continue;
1972         }
1973         const unsigned int j = port->num_audio_profiles++;
1974         port->audio_profiles[j].format = format;
1975         port->audio_profiles[j].num_sample_rates = num_sample_rates;
1976         memcpy(port->audio_profiles[j].sample_rates,
1977                sample_rates,
1978                num_sample_rates * sizeof(unsigned int));
1979         port->audio_profiles[j].num_channel_masks = num_channel_masks;
1980         memcpy(port->audio_profiles[j].channel_masks,
1981                channel_masks,
1982                num_channel_masks* sizeof(audio_channel_mask_t));
1983     }
1984 
1985     return 0;
1986 }
1987 
adev_dump(const struct audio_hw_device * device,int fd)1988 static int adev_dump(const struct audio_hw_device *device, int fd)
1989 {
1990     dprintf(fd, "\nUSB audio module:\n");
1991 
1992     struct audio_device* adev = (struct audio_device*)device;
1993     const int kNumRetries = 3;
1994     const int kSleepTimeMS = 500;
1995 
1996     // use device_try_lock() in case we dumpsys during a deadlock
1997     int retry = kNumRetries;
1998     while (retry > 0 && device_try_lock(adev) != 0) {
1999       sleep(kSleepTimeMS);
2000       retry--;
2001     }
2002 
2003     if (retry > 0) {
2004         if (list_empty(&adev->output_stream_list)) {
2005             dprintf(fd, "  No output streams.\n");
2006         } else {
2007             struct listnode* node;
2008             list_for_each(node, &adev->output_stream_list) {
2009                 struct audio_stream* stream =
2010                         (struct audio_stream *)node_to_item(node, struct stream_out, list_node);
2011                 out_dump(stream, fd);
2012             }
2013         }
2014 
2015         if (list_empty(&adev->input_stream_list)) {
2016             dprintf(fd, "\n  No input streams.\n");
2017         } else {
2018             struct listnode* node;
2019             list_for_each(node, &adev->input_stream_list) {
2020                 struct audio_stream* stream =
2021                         (struct audio_stream *)node_to_item(node, struct stream_in, list_node);
2022                 in_dump(stream, fd);
2023             }
2024         }
2025 
2026         device_unlock(adev);
2027     } else {
2028         // Couldn't lock
2029         dprintf(fd, "  Could not obtain device lock.\n");
2030     }
2031 
2032     return 0;
2033 }
2034 
adev_close(hw_device_t * device)2035 static int adev_close(hw_device_t *device)
2036 {
2037     free(device);
2038 
2039     return 0;
2040 }
2041 
adev_open(const hw_module_t * module,const char * name,hw_device_t ** device)2042 static int adev_open(const hw_module_t* module, const char* name, hw_device_t** device)
2043 {
2044     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
2045         return -EINVAL;
2046 
2047     struct audio_device *adev = calloc(1, sizeof(struct audio_device));
2048     if (!adev)
2049         return -ENOMEM;
2050 
2051     pthread_mutex_init(&adev->lock, (const pthread_mutexattr_t *) NULL);
2052 
2053     list_init(&adev->output_stream_list);
2054     list_init(&adev->input_stream_list);
2055 
2056     adev->hw_device.common.tag = HARDWARE_DEVICE_TAG;
2057     adev->hw_device.common.version = AUDIO_DEVICE_API_VERSION_3_2;
2058     adev->hw_device.common.module = (struct hw_module_t *)module;
2059     adev->hw_device.common.close = adev_close;
2060 
2061     adev->hw_device.init_check = adev_init_check;
2062     adev->hw_device.set_voice_volume = adev_set_voice_volume;
2063     adev->hw_device.set_master_volume = adev_set_master_volume;
2064     adev->hw_device.set_mode = adev_set_mode;
2065     adev->hw_device.set_mic_mute = adev_set_mic_mute;
2066     adev->hw_device.get_mic_mute = adev_get_mic_mute;
2067     adev->hw_device.set_parameters = adev_set_parameters;
2068     adev->hw_device.get_parameters = adev_get_parameters;
2069     adev->hw_device.get_input_buffer_size = adev_get_input_buffer_size;
2070     adev->hw_device.open_output_stream = adev_open_output_stream;
2071     adev->hw_device.close_output_stream = adev_close_output_stream;
2072     adev->hw_device.open_input_stream = adev_open_input_stream;
2073     adev->hw_device.close_input_stream = adev_close_input_stream;
2074     adev->hw_device.create_audio_patch = adev_create_audio_patch;
2075     adev->hw_device.release_audio_patch = adev_release_audio_patch;
2076     adev->hw_device.get_audio_port = adev_get_audio_port;
2077     adev->hw_device.get_audio_port_v7 = adev_get_audio_port_v7;
2078     adev->hw_device.dump = adev_dump;
2079 
2080     *device = &adev->hw_device.common;
2081 
2082     return 0;
2083 }
2084 
2085 static struct hw_module_methods_t hal_module_methods = {
2086     .open = adev_open,
2087 };
2088 
2089 struct audio_module HAL_MODULE_INFO_SYM = {
2090     .common = {
2091         .tag = HARDWARE_MODULE_TAG,
2092         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
2093         .hal_api_version = HARDWARE_HAL_API_VERSION,
2094         .id = AUDIO_HARDWARE_MODULE_ID,
2095         .name = "USB audio HW HAL",
2096         .author = "The Android Open Source Project",
2097         .methods = &hal_module_methods,
2098     },
2099 };
2100