• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include <alsa/asoundlib.h>
7 #include <errno.h>
8 #include <limits.h>
9 #include <stdio.h>
10 #include <sys/param.h>
11 #include <sys/select.h>
12 #include <sys/socket.h>
13 #include <sys/time.h>
14 #include <syslog.h>
15 #include <time.h>
16 
17 #include "audio_thread.h"
18 #include "cras_alsa_helpers.h"
19 #include "cras_alsa_io.h"
20 #include "cras_alsa_jack.h"
21 #include "cras_alsa_mixer.h"
22 #include "cras_alsa_ucm.h"
23 #include "cras_audio_area.h"
24 #include "cras_config.h"
25 #include "cras_utf8.h"
26 #include "cras_hotword_handler.h"
27 #include "cras_iodev.h"
28 #include "cras_iodev_list.h"
29 #include "cras_messages.h"
30 #include "cras_ramp.h"
31 #include "cras_rclient.h"
32 #include "cras_shm.h"
33 #include "cras_system_state.h"
34 #include "cras_types.h"
35 #include "cras_util.h"
36 #include "cras_volume_curve.h"
37 #include "sfh.h"
38 #include "softvol_curve.h"
39 #include "utlist.h"
40 
41 #define MAX_ALSA_DEV_NAME_LENGTH 9 /* Alsa names "hw:XX,YY" + 1 for null. */
42 #define HOTWORD_DEV "Wake on Voice"
43 #define DEFAULT "(default)"
44 #define HDMI "HDMI"
45 #define INTERNAL_MICROPHONE "Internal Mic"
46 #define INTERNAL_SPEAKER "Speaker"
47 #define KEYBOARD_MIC "Keyboard Mic"
48 #define HEADPHONE "Headphone"
49 #define MIC "Mic"
50 #define USB "USB"
51 
52 /*
53  * For USB, pad the output buffer.  This avoids a situation where there isn't a
54  * complete URB's worth of audio ready to be transmitted when it is requested.
55  * The URB interval does track directly to the audio clock, making it hard to
56  * predict the exact interval.
57  */
58 #define USB_EXTRA_BUFFER_FRAMES 768
59 
60 /*
61  * When snd_pcm_avail returns a value that is greater than buffer size,
62  * we know there is an underrun. If the number of underrun samples
63  * (avail - buffer_size) is greater than SEVERE_UNDERRUN_MS * rate,
64  * it is a severe underrun. Main thread should disable and then enable
65  * device to recover it from underrun.
66  */
67 #define SEVERE_UNDERRUN_MS 5000
68 
69 /*
70  * This extends cras_ionode to include alsa-specific information.
71  * Members:
72  *    mixer_output - From cras_alsa_mixer.
73  *    volume_curve - Volume curve for this node.
74  *    jack - The jack associated with the node.
75  */
76 struct alsa_output_node {
77 	struct cras_ionode base;
78 	struct mixer_control *mixer_output;
79 	struct cras_volume_curve *volume_curve;
80 	const struct cras_alsa_jack *jack;
81 };
82 
83 struct alsa_input_node {
84 	struct cras_ionode base;
85 	struct mixer_control* mixer_input;
86 	const struct cras_alsa_jack *jack;
87 	int8_t *channel_layout;
88 };
89 
90 /*
91  * Child of cras_iodev, alsa_io handles ALSA interaction for sound devices.
92  * base - The cras_iodev structure "base class".
93  * dev - String that names this device (e.g. "hw:0,0").
94  * dev_name - value from snd_pcm_info_get_name
95  * dev_id - value from snd_pcm_info_get_id
96  * device_index - ALSA index of device, Y in "hw:X:Y".
97  * next_ionode_index - The index we will give to the next ionode. Each ionode
98  *     have a unique index within the iodev.
99  * card_type - the type of the card this iodev belongs.
100  * is_first - true if this is the first iodev on the card.
101  * fully_specified - true if this device and it's nodes were fully specified.
102  *     That is, don't automatically create nodes for it.
103  * enable_htimestamp - True when the device's htimestamp is used.
104  * handle - Handle to the opened ALSA device.
105  * num_underruns - Number of times we have run out of data (playback only).
106  * num_severe_underruns - Number of times we have run out of data badly.
107                           Unlike num_underruns which records for the duration
108                           where device is opened, num_severe_underruns records
109                           since device is created. When severe underrun occurs
110                           a possible action is to close/open device.
111  * alsa_stream - Playback or capture type.
112  * mixer - Alsa mixer used to control volume and mute of the device.
113  * config - Card config for this alsa device.
114  * jack_list - List of alsa jack controls for this device.
115  * ucm - CRAS use case manager, if configuration is found.
116  * mmap_offset - offset returned from mmap_begin.
117  * dsp_name_default - the default dsp name for the device. It can be overridden
118  *     by the jack specific dsp name.
119  * poll_fd - Descriptor used to block until data is ready.
120  * dma_period_set_microsecs - If non-zero, the value to apply to the dma_period.
121  * is_free_running - true if device is playing zeros in the buffer without
122  *                   user filling meaningful data. The device buffer is filled
123  *                   with zeros. In this state, appl_ptr remains the same
124  *                   while hw_ptr keeps running ahead.
125  * filled_zeros_for_draining - The number of zeros filled for draining.
126  * severe_underrun_frames - The threshold for severe underrun.
127  * default_volume_curve - Default volume curve that converts from an index
128  *                        to dBFS.
129  */
130 struct alsa_io {
131 	struct cras_iodev base;
132 	char *dev;
133 	char *dev_name;
134 	char *dev_id;
135 	uint32_t device_index;
136 	uint32_t next_ionode_index;
137 	enum CRAS_ALSA_CARD_TYPE card_type;
138 	int is_first;
139 	int fully_specified;
140 	int enable_htimestamp;
141 	snd_pcm_t *handle;
142 	unsigned int num_underruns;
143 	unsigned int num_severe_underruns;
144 	snd_pcm_stream_t alsa_stream;
145 	struct cras_alsa_mixer *mixer;
146 	const struct cras_card_config *config;
147 	struct cras_alsa_jack_list *jack_list;
148 	struct cras_use_case_mgr *ucm;
149 	snd_pcm_uframes_t mmap_offset;
150 	const char *dsp_name_default;
151 	int poll_fd;
152 	unsigned int dma_period_set_microsecs;
153 	int is_free_running;
154 	unsigned int filled_zeros_for_draining;
155 	snd_pcm_uframes_t severe_underrun_frames;
156 	struct cras_volume_curve *default_volume_curve;
157 	int hwparams_set;
158 };
159 
160 static void init_device_settings(struct alsa_io *aio);
161 
162 static int alsa_iodev_set_active_node(struct cras_iodev *iodev,
163 				      struct cras_ionode *ionode,
164 				      unsigned dev_enabled);
165 
166 /*
167  * Defines the default values of nodes.
168  */
169 static const struct {
170 	const char *name;
171 	enum CRAS_NODE_TYPE type;
172 	enum CRAS_NODE_POSITION position;
173 } node_defaults[] = {
174 	{
175 		.name = DEFAULT,
176 		.type = CRAS_NODE_TYPE_UNKNOWN,
177 		.position = NODE_POSITION_INTERNAL,
178 	},
179 	{
180 		.name = INTERNAL_SPEAKER,
181 		.type = CRAS_NODE_TYPE_INTERNAL_SPEAKER,
182 		.position = NODE_POSITION_INTERNAL,
183 	},
184 	{
185 		.name = INTERNAL_MICROPHONE,
186 		.type = CRAS_NODE_TYPE_MIC,
187 		.position = NODE_POSITION_INTERNAL,
188 	},
189 	{
190 		.name = KEYBOARD_MIC,
191 		.type = CRAS_NODE_TYPE_MIC,
192 		.position = NODE_POSITION_KEYBOARD,
193 	},
194 	{
195 		.name = HDMI,
196 		.type = CRAS_NODE_TYPE_HDMI,
197 		.position = NODE_POSITION_EXTERNAL,
198 	},
199 	{
200 		.name = "IEC958",
201 		.type = CRAS_NODE_TYPE_HDMI,
202 		.position = NODE_POSITION_EXTERNAL,
203 	},
204 	{
205 		.name = "Headphone",
206 		.type = CRAS_NODE_TYPE_HEADPHONE,
207 		.position = NODE_POSITION_EXTERNAL,
208 	},
209 	{
210 		.name = "Front Headphone",
211 		.type = CRAS_NODE_TYPE_HEADPHONE,
212 		.position = NODE_POSITION_EXTERNAL,
213 	},
214 	{
215 		.name = "Front Mic",
216 		.type = CRAS_NODE_TYPE_MIC,
217 		.position = NODE_POSITION_FRONT,
218 	},
219 	{
220 		.name = "Rear Mic",
221 		.type = CRAS_NODE_TYPE_MIC,
222 		.position = NODE_POSITION_REAR,
223 	},
224 	{
225 		.name = "Mic",
226 		.type = CRAS_NODE_TYPE_MIC,
227 		.position = NODE_POSITION_EXTERNAL,
228 	},
229 	{
230 		.name = HOTWORD_DEV,
231 		.type = CRAS_NODE_TYPE_HOTWORD,
232 		.position = NODE_POSITION_INTERNAL,
233 	},
234 	{
235 		.name = "Haptic",
236 		.type = CRAS_NODE_TYPE_HAPTIC,
237 		.position = NODE_POSITION_INTERNAL,
238 	},
239 	{
240 		.name = "Rumbler",
241 		.type = CRAS_NODE_TYPE_HAPTIC,
242 		.position = NODE_POSITION_INTERNAL,
243 	},
244 	{
245 		.name = "Line Out",
246 		.type = CRAS_NODE_TYPE_LINEOUT,
247 		.position = NODE_POSITION_EXTERNAL,
248 	},
249 };
250 
set_hwparams(struct cras_iodev * iodev)251 static int set_hwparams(struct cras_iodev *iodev)
252 {
253 	struct alsa_io *aio = (struct alsa_io *)iodev;
254 	int period_wakeup;
255 	int rc;
256 
257 	/* Only need to set hardware params once. */
258 	if (aio->hwparams_set)
259 		return 0;
260 
261 	/* If it's a wake on voice device, period_wakeups are required. */
262 	period_wakeup = (iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD);
263 
264 	/* Sets frame rate and channel count to alsa device before
265 	 * we test channel mapping. */
266 	rc = cras_alsa_set_hwparams(aio->handle, iodev->format,
267 				    &iodev->buffer_size, period_wakeup,
268 				    aio->dma_period_set_microsecs);
269 	if (rc < 0)
270 		return rc;
271 
272 	aio->hwparams_set = 1;
273 	return 0;
274 }
275 
276 /*
277  * iodev callbacks.
278  */
279 
frames_queued(const struct cras_iodev * iodev,struct timespec * tstamp)280 static int frames_queued(const struct cras_iodev *iodev,
281 			 struct timespec *tstamp)
282 {
283 	struct alsa_io *aio = (struct alsa_io *)iodev;
284 	int rc;
285 	snd_pcm_uframes_t frames;
286 
287 	rc = cras_alsa_get_avail_frames(aio->handle,
288 					aio->base.buffer_size,
289 					aio->severe_underrun_frames,
290 					iodev->info.name,
291 					&frames, tstamp);
292 	if (rc < 0) {
293 		if (rc == -EPIPE)
294 			aio->num_severe_underruns++;
295 		return rc;
296 	}
297 	if (!aio->enable_htimestamp)
298 		clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
299 	if (iodev->direction == CRAS_STREAM_INPUT)
300 		return (int)frames;
301 
302 	/* For output, return number of frames that are used. */
303 	return iodev->buffer_size - frames;
304 }
305 
delay_frames(const struct cras_iodev * iodev)306 static int delay_frames(const struct cras_iodev *iodev)
307 {
308 	struct alsa_io *aio = (struct alsa_io *)iodev;
309 	snd_pcm_sframes_t delay;
310 	int rc;
311 
312 	rc = cras_alsa_get_delay_frames(aio->handle,
313 					iodev->buffer_size,
314 					&delay);
315 	if (rc < 0)
316 		return rc;
317 
318 	return (int)delay;
319 }
320 
close_dev(struct cras_iodev * iodev)321 static int close_dev(struct cras_iodev *iodev)
322 {
323 	struct alsa_io *aio = (struct alsa_io *)iodev;
324 
325 	/* Removes audio thread callback from main thread. */
326 	if (aio->poll_fd >= 0)
327 		audio_thread_rm_callback_sync(
328 				cras_iodev_list_get_audio_thread(),
329 				aio->poll_fd);
330 	if (!aio->handle)
331 		return 0;
332 	cras_alsa_pcm_close(aio->handle);
333 	aio->handle = NULL;
334 	aio->is_free_running = 0;
335 	aio->filled_zeros_for_draining = 0;
336 	aio->hwparams_set = 0;
337 	cras_iodev_free_format(&aio->base);
338 	cras_iodev_free_audio_area(&aio->base);
339 	return 0;
340 }
341 
dummy_hotword_cb(void * arg)342 static int dummy_hotword_cb(void *arg)
343 {
344 	/* Only need this once. */
345 	struct alsa_io *aio = (struct alsa_io *)arg;
346 	audio_thread_rm_callback(aio->poll_fd);
347 	aio->poll_fd = -1;
348 	aio->base.input_streaming = 1;
349 
350 	/* Send hotword triggered signal. */
351 	cras_hotword_send_triggered_msg();
352 
353 	return 0;
354 }
355 
open_dev(struct cras_iodev * iodev)356 static int open_dev(struct cras_iodev *iodev)
357 {
358 	struct alsa_io *aio = (struct alsa_io *)iodev;
359 	snd_pcm_t *handle;
360 	int rc;
361 
362 	rc = cras_alsa_pcm_open(&handle, aio->dev, aio->alsa_stream);
363 	if (rc < 0)
364 		return rc;
365 
366 	aio->handle = handle;
367 
368 	return 0;
369 }
370 
configure_dev(struct cras_iodev * iodev)371 static int configure_dev(struct cras_iodev *iodev)
372 {
373 	struct alsa_io *aio = (struct alsa_io *)iodev;
374 	int rc;
375 
376 	/* This is called after the first stream added so configure for it.
377 	 * format must be set before opening the device.
378 	 */
379 	if (iodev->format == NULL)
380 		return -EINVAL;
381 	aio->num_underruns = 0;
382 	aio->is_free_running = 0;
383 	aio->filled_zeros_for_draining = 0;
384 	aio->severe_underrun_frames =
385 			SEVERE_UNDERRUN_MS * iodev->format->frame_rate / 1000;
386 
387 	cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
388 
389 	syslog(LOG_DEBUG, "Configure alsa device %s rate %zuHz, %zu channels",
390 	       aio->dev, iodev->format->frame_rate,
391 	       iodev->format->num_channels);
392 
393 	rc = set_hwparams(iodev);
394 	if (rc < 0)
395 		return rc;
396 
397 	/* Set channel map to device */
398 	rc = cras_alsa_set_channel_map(aio->handle,
399 				       iodev->format);
400 	if (rc < 0)
401 		return rc;
402 
403 	/* Configure software params. */
404 	rc = cras_alsa_set_swparams(aio->handle, &aio->enable_htimestamp);
405 	if (rc < 0)
406 		return rc;
407 
408 	/* Initialize device settings. */
409 	init_device_settings(aio);
410 
411 	aio->poll_fd = -1;
412 	if (iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD) {
413 		struct pollfd *ufds;
414 		int count, i;
415 
416 		count = snd_pcm_poll_descriptors_count(aio->handle);
417 		if (count <= 0) {
418 			syslog(LOG_ERR, "Invalid poll descriptors count\n");
419 			return count;
420 		}
421 
422 		ufds = (struct pollfd *)malloc(sizeof(struct pollfd) * count);
423 		if (ufds == NULL)
424 			return -ENOMEM;
425 
426 		rc = snd_pcm_poll_descriptors(aio->handle, ufds, count);
427 		if (rc < 0) {
428 			syslog(LOG_ERR,
429 			       "Getting hotword poll descriptors: %s\n",
430 			       snd_strerror(rc));
431 			free(ufds);
432 			return rc;
433 		}
434 
435 		for (i = 0; i < count; i++) {
436 			if (ufds[i].events & POLLIN) {
437 				aio->poll_fd = ufds[i].fd;
438 				break;
439 			}
440 		}
441 		free(ufds);
442 
443 		if (aio->poll_fd >= 0)
444 			audio_thread_add_callback(aio->poll_fd,
445 						  dummy_hotword_cb,
446 						  aio);
447 	}
448 
449 	/* Capture starts right away, playback will wait for samples. */
450 	if (aio->alsa_stream == SND_PCM_STREAM_CAPTURE)
451 		cras_alsa_pcm_start(aio->handle);
452 
453 	return 0;
454 }
455 
456 /*
457  * Check if ALSA device is opened by checking if handle is valid.
458  * Note that to fully open a cras_iodev, ALSA device is opened first, then there
459  * are some device init settings to be done in init_device_settings.
460  * Therefore, when setting volume/mute/gain in init_device_settings,
461  * cras_iodev is not in CRAS_IODEV_STATE_OPEN yet. We need to check if handle
462  * is valid when setting those properties, instead of checking
463  * cras_iodev_is_open.
464  */
has_handle(const struct alsa_io * aio)465 static int has_handle(const struct alsa_io *aio)
466 {
467 	return !!aio->handle;
468 }
469 
start(const struct cras_iodev * iodev)470 static int start(const struct cras_iodev *iodev)
471 {
472 	struct alsa_io *aio = (struct alsa_io *)iodev;
473 	snd_pcm_t *handle = aio->handle;
474 	int rc;
475 
476 	if (snd_pcm_state(handle) == SND_PCM_STATE_RUNNING)
477 		return 0;
478 
479 	if (snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED) {
480 		rc = cras_alsa_attempt_resume(handle);
481 		if (rc < 0) {
482 			syslog(LOG_ERR, "Resume error: %s", snd_strerror(rc));
483 			return rc;
484 		}
485 		cras_iodev_reset_rate_estimator(iodev);
486 	} else {
487 		rc = cras_alsa_pcm_start(handle);
488 		if (rc < 0) {
489 			syslog(LOG_ERR, "Start error: %s", snd_strerror(rc));
490 			return rc;
491 		}
492 	}
493 
494 	return 0;
495 }
496 
get_buffer(struct cras_iodev * iodev,struct cras_audio_area ** area,unsigned * frames)497 static int get_buffer(struct cras_iodev *iodev,
498 		      struct cras_audio_area **area,
499 		      unsigned *frames)
500 {
501 	struct alsa_io *aio = (struct alsa_io *)iodev;
502 	snd_pcm_uframes_t nframes = *frames;
503 	uint8_t *dst = NULL;
504 	size_t format_bytes;
505 	int rc;
506 
507 	aio->mmap_offset = 0;
508 	format_bytes = cras_get_format_bytes(iodev->format);
509 
510 	rc = cras_alsa_mmap_begin(aio->handle,
511 				  format_bytes,
512 				  &dst,
513 				  &aio->mmap_offset,
514 				  &nframes);
515 
516 	iodev->area->frames = nframes;
517 	cras_audio_area_config_buf_pointers(iodev->area, iodev->format, dst);
518 
519 	*area = iodev->area;
520 	*frames = nframes;
521 
522 	return rc;
523 }
524 
put_buffer(struct cras_iodev * iodev,unsigned nwritten)525 static int put_buffer(struct cras_iodev *iodev, unsigned nwritten)
526 {
527 	struct alsa_io *aio = (struct alsa_io *)iodev;
528 
529 	return cras_alsa_mmap_commit(aio->handle,
530 				     aio->mmap_offset,
531 				     nwritten);
532 }
533 
flush_buffer(struct cras_iodev * iodev)534 static int flush_buffer(struct cras_iodev *iodev)
535 {
536 	struct alsa_io *aio = (struct alsa_io *)iodev;
537 	snd_pcm_uframes_t nframes;
538 
539 	if (iodev->direction == CRAS_STREAM_INPUT) {
540 		nframes = snd_pcm_avail(aio->handle);
541 		nframes = snd_pcm_forwardable(aio->handle);
542 		return snd_pcm_forward(aio->handle, nframes);
543 	}
544 	return 0;
545 }
546 
547 /*
548  * Gets the first plugged node in list. This is used as the
549  * default node to set as active.
550  */
first_plugged_node(struct cras_iodev * iodev)551 static struct cras_ionode *first_plugged_node(struct cras_iodev *iodev)
552 {
553 	struct cras_ionode *n;
554 
555 	/* When this is called at iodev creation, none of the nodes
556 	 * are selected. Just pick the first plugged one and let Chrome
557 	 * choose it later. */
558 	DL_FOREACH(iodev->nodes, n) {
559 		if (n->plugged)
560 			return n;
561 	}
562 	return iodev->nodes;
563 }
564 
update_active_node(struct cras_iodev * iodev,unsigned node_idx,unsigned dev_enabled)565 static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
566 			       unsigned dev_enabled)
567 {
568 	struct cras_ionode *n;
569 
570 	/* If a node exists for node_idx, set it as active. */
571 	DL_FOREACH(iodev->nodes, n) {
572 		if (n->idx == node_idx) {
573 			alsa_iodev_set_active_node(iodev, n, dev_enabled);
574 			return;
575 		}
576 	}
577 
578 	alsa_iodev_set_active_node(iodev, first_plugged_node(iodev),
579 				   dev_enabled);
580 }
581 
update_channel_layout(struct cras_iodev * iodev)582 static int update_channel_layout(struct cras_iodev *iodev)
583 {
584 	struct alsa_io *aio = (struct alsa_io *)iodev;
585 	int err = 0;
586 
587 	/* If the capture channel map is specified in UCM, prefer it over
588 	 * what ALSA provides. */
589 	if (aio->ucm && (iodev->direction == CRAS_STREAM_INPUT)) {
590 		struct alsa_input_node *input =
591 			(struct alsa_input_node *)iodev->active_node;
592 
593 		if (input->channel_layout) {
594 			memcpy(iodev->format->channel_layout,
595 			       input->channel_layout,
596 			       CRAS_CH_MAX * sizeof(*input->channel_layout));
597 			return 0;
598 		}
599 	}
600 
601 	err = set_hwparams(iodev);
602 	if (err < 0)
603 		return err;
604 
605 	return cras_alsa_get_channel_map(aio->handle, iodev->format);
606 }
607 
set_hotword_model(struct cras_iodev * iodev,const char * model_name)608 static int set_hotword_model(struct cras_iodev *iodev, const char *model_name)
609 {
610 	struct alsa_io *aio = (struct alsa_io *)iodev;
611 	if (!aio->ucm)
612 		return -EINVAL;
613 
614 	return ucm_set_hotword_model(aio->ucm, model_name);
615 }
616 
get_hotword_models(struct cras_iodev * iodev)617 static char *get_hotword_models(struct cras_iodev *iodev)
618 {
619 	struct alsa_io *aio = (struct alsa_io *)iodev;
620 	if (!aio->ucm)
621 		return NULL;
622 
623 	return ucm_get_hotword_models(aio->ucm);
624 }
625 
626 /*
627  * Alsa helper functions.
628  */
629 
get_active_output(const struct alsa_io * aio)630 static struct alsa_output_node *get_active_output(const struct alsa_io *aio)
631 {
632 	return (struct alsa_output_node *)aio->base.active_node;
633 }
634 
get_active_input(const struct alsa_io * aio)635 static struct alsa_input_node *get_active_input(const struct alsa_io *aio)
636 {
637 	return (struct alsa_input_node *)aio->base.active_node;
638 }
639 
640 /*
641  * Gets the curve for the active output node. If the node doesn't have volume
642  * curve specified, return the default volume curve of the parent iodev.
643  */
get_curve_for_output_node(const struct alsa_io * aio,const struct alsa_output_node * node)644 static const struct cras_volume_curve *get_curve_for_output_node(
645 		const struct alsa_io *aio,
646 		const struct alsa_output_node *node)
647 {
648 	if (node && node->volume_curve)
649 		return node->volume_curve;
650 	return aio->default_volume_curve;
651 }
652 
653 /*
654  * Gets the curve for the active output.
655  */
get_curve_for_active_output(const struct alsa_io * aio)656 static const struct cras_volume_curve *get_curve_for_active_output(
657 		const struct alsa_io *aio)
658 {
659 	struct alsa_output_node *node = get_active_output(aio);
660 	return get_curve_for_output_node(aio, node);
661 }
662 
663 /*
664  * Informs the system of the volume limits for this device.
665  */
set_alsa_volume_limits(struct alsa_io * aio)666 static void set_alsa_volume_limits(struct alsa_io *aio)
667 {
668 	const struct cras_volume_curve *curve;
669 
670 	/* Only set the limits if the dev is active. */
671 	if (!has_handle(aio))
672 		return;
673 
674 	curve = get_curve_for_active_output(aio);
675 	cras_system_set_volume_limits(
676 			curve->get_dBFS(curve, 1), /* min */
677 			curve->get_dBFS(curve, CRAS_MAX_SYSTEM_VOLUME));
678 }
679 
680 /*
681  * Sets the alsa mute control for this iodev.
682  */
set_alsa_mute_control(const struct alsa_io * aio,int muted)683 static void set_alsa_mute_control(const struct alsa_io *aio, int muted)
684 {
685 	struct alsa_output_node *aout;
686 
687 	if (!has_handle(aio))
688 		return;
689 
690 	aout = get_active_output(aio);
691 	cras_alsa_mixer_set_mute(
692 		aio->mixer,
693 		muted,
694 		aout ? aout->mixer_output : NULL);
695 }
696 
697 /*
698  * Sets the volume of the playback device to the specified level. Receives a
699  * volume index from the system settings, ranging from 0 to 100, converts it to
700  * dB using the volume curve, and sends the dB value to alsa.
701  */
set_alsa_volume(struct cras_iodev * iodev)702 static void set_alsa_volume(struct cras_iodev *iodev)
703 {
704 	const struct alsa_io *aio = (const struct alsa_io *)iodev;
705 	const struct cras_volume_curve *curve;
706 	size_t volume;
707 	struct alsa_output_node *aout;
708 
709 	assert(aio);
710 	if (aio->mixer == NULL)
711 		return;
712 
713 	/* Only set the volume if the dev is active. */
714 	if (!has_handle(aio))
715 		return;
716 
717 	volume = cras_system_get_volume();
718 	curve = get_curve_for_active_output(aio);
719 	if (curve == NULL)
720 		return;
721 	aout = get_active_output(aio);
722 	if (aout)
723 		volume = cras_iodev_adjust_node_volume(&aout->base, volume);
724 
725 	/* Samples get scaled for devices using software volume, set alsa
726 	 * volume to 100. */
727 	if (cras_iodev_software_volume_needed(iodev))
728 		volume = 100;
729 
730 	cras_alsa_mixer_set_dBFS(
731 		aio->mixer,
732 		curve->get_dBFS(curve, volume),
733 		aout ? aout->mixer_output : NULL);
734 }
735 
set_alsa_mute(struct cras_iodev * iodev)736 static void set_alsa_mute(struct cras_iodev *iodev)
737 {
738 	/* Mute for zero. */
739 	const struct alsa_io *aio = (const struct alsa_io *)iodev;
740 	set_alsa_mute_control(aio, cras_system_get_mute());
741 }
742 
743 /*
744  * Sets the capture gain to the current system input gain level, given in dBFS.
745  * Set mute based on the system mute state.  This gain can be positive or
746  * negative and might be adjusted often if an app is running an AGC.
747  */
set_alsa_capture_gain(struct cras_iodev * iodev)748 static void set_alsa_capture_gain(struct cras_iodev *iodev)
749 {
750 	const struct alsa_io *aio = (const struct alsa_io *)iodev;
751 	struct alsa_input_node *ain;
752 	long gain;
753 
754 	assert(aio);
755 	if (aio->mixer == NULL)
756 		return;
757 
758 	/* Only set the volume if the dev is active. */
759 	if (!has_handle(aio))
760 		return;
761 	gain = cras_iodev_adjust_active_node_gain(
762 				iodev, cras_system_get_capture_gain());
763 
764 	/* Set hardware gain to 0dB if software gain is needed. */
765 	if (cras_iodev_software_volume_needed(iodev))
766 		gain = 0;
767 
768 	ain = get_active_input(aio);
769 
770 	cras_alsa_mixer_set_capture_dBFS(
771 			aio->mixer,
772 			gain,
773 			ain ? ain->mixer_input : NULL);
774 	cras_alsa_mixer_set_capture_mute(aio->mixer,
775 					 cras_system_get_capture_mute(),
776 					 ain ? ain->mixer_input : NULL);
777 }
778 
779 /*
780  * Swaps the left and right channels of the given node.
781  */
set_alsa_node_swapped(struct cras_iodev * iodev,struct cras_ionode * node,int enable)782 static int set_alsa_node_swapped(struct cras_iodev *iodev,
783 				 struct cras_ionode *node, int enable)
784 {
785 	const struct alsa_io *aio = (const struct alsa_io *)iodev;
786 	assert(aio);
787 	return ucm_enable_swap_mode(aio->ucm, node->name, enable);
788 }
789 
790 /*
791  * Initializes the device settings according to system volume, mute, gain
792  * settings.
793  * Updates system capture gain limits based on current active device/node.
794  */
init_device_settings(struct alsa_io * aio)795 static void init_device_settings(struct alsa_io *aio)
796 {
797 	/* Register for volume/mute callback and set initial volume/mute for
798 	 * the device. */
799 	if (aio->base.direction == CRAS_STREAM_OUTPUT) {
800 		set_alsa_volume_limits(aio);
801 		set_alsa_volume(&aio->base);
802 		set_alsa_mute(&aio->base);
803 	} else {
804 		struct mixer_control *mixer_input = NULL;
805 		struct alsa_input_node *ain = get_active_input(aio);
806 		long min_capture_gain, max_capture_gain;
807 
808 		if (ain)
809 			mixer_input = ain->mixer_input;
810 
811 		if (cras_iodev_software_volume_needed(&aio->base)) {
812 			min_capture_gain = cras_iodev_minimum_software_gain(
813 					&aio->base);
814 			max_capture_gain = cras_iodev_maximum_software_gain(
815 					&aio->base);
816 		} else {
817 			min_capture_gain =
818 				cras_alsa_mixer_get_minimum_capture_gain(
819 						aio->mixer, mixer_input);
820 			max_capture_gain =
821 				cras_alsa_mixer_get_maximum_capture_gain(
822 						aio->mixer, mixer_input);
823 		}
824 		cras_system_set_capture_gain_limits(min_capture_gain,
825 						    max_capture_gain);
826 		set_alsa_capture_gain(&aio->base);
827 	}
828 }
829 
830 /*
831  * Functions run in the main server context.
832  */
833 
834 /*
835  * Frees resources used by the alsa iodev.
836  * Args:
837  *    iodev - the iodev to free the resources from.
838  */
free_alsa_iodev_resources(struct alsa_io * aio)839 static void free_alsa_iodev_resources(struct alsa_io *aio)
840 {
841 	struct cras_ionode *node;
842 	struct alsa_output_node *aout;
843 
844 	free(aio->base.supported_rates);
845 	free(aio->base.supported_channel_counts);
846 	free(aio->base.supported_formats);
847 
848 	DL_FOREACH(aio->base.nodes, node) {
849 		if (aio->base.direction == CRAS_STREAM_OUTPUT) {
850 			aout = (struct alsa_output_node *)node;
851 			cras_volume_curve_destroy(aout->volume_curve);
852 		}
853 		cras_iodev_rm_node(&aio->base, node);
854 		free(node->softvol_scalers);
855 		free(node);
856 	}
857 
858 	free((void *)aio->dsp_name_default);
859 	cras_iodev_free_resources(&aio->base);
860 	free(aio->dev);
861 	if (aio->dev_id)
862 		free(aio->dev_id);
863 	if (aio->dev_name)
864 		free(aio->dev_name);
865 }
866 
867 /*
868  * Returns true if this is the first internal device.
869  */
first_internal_device(struct alsa_io * aio)870 static int first_internal_device(struct alsa_io *aio)
871 {
872 	return aio->is_first && aio->card_type == ALSA_CARD_TYPE_INTERNAL;
873 }
874 
875 /*
876  * Returns true if there is already a node created with the given name.
877  */
has_node(struct alsa_io * aio,const char * name)878 static int has_node(struct alsa_io *aio, const char *name)
879 {
880 	struct cras_ionode *node;
881 
882 	DL_FOREACH(aio->base.nodes, node)
883 		if (!strcmp(node->name, name))
884 			return 1;
885 
886 	return 0;
887 }
888 
889 /*
890  * Returns true if string s ends with the given suffix.
891  */
endswith(const char * s,const char * suffix)892 int endswith(const char *s, const char *suffix)
893 {
894 	size_t n = strlen(s);
895 	size_t m = strlen(suffix);
896 	return n >= m && !strcmp(s + (n - m), suffix);
897 }
898 
899 #ifdef CRAS_DBUS
900 /*
901  * Drop the node name and replace it with node type.
902  */
drop_node_name(struct cras_ionode * node)903 static void drop_node_name(struct cras_ionode *node)
904 {
905 	if (node->type == CRAS_NODE_TYPE_USB)
906 		strcpy(node->name, USB);
907 	else if (node->type == CRAS_NODE_TYPE_HDMI)
908 		strcpy(node->name, HDMI);
909 	else {
910 		/* Only HDMI or USB node might have invalid name to drop */
911 		syslog(LOG_ERR, "Unexpectedly drop node name for "
912 		       "node: %s, type: %d", node->name, node->type);
913 		strcpy(node->name, DEFAULT);
914 	}
915 }
916 #endif
917 
918 /*
919  * Sets the initial plugged state and type of a node based on its
920  * name. Chrome will assign priority to nodes base on node type.
921  */
set_node_initial_state(struct cras_ionode * node,enum CRAS_ALSA_CARD_TYPE card_type)922 static void set_node_initial_state(struct cras_ionode *node,
923 				   enum CRAS_ALSA_CARD_TYPE card_type)
924 {
925 
926 	unsigned i;
927 
928 	node->volume = 100;
929 	node->type = CRAS_NODE_TYPE_UNKNOWN;
930 	/* Go through the known names */
931 	for (i = 0; i < ARRAY_SIZE(node_defaults); i++)
932 		if (!strncmp(node->name, node_defaults[i].name,
933 			     strlen(node_defaults[i].name))) {
934 			node->position = node_defaults[i].position;
935 			node->plugged = (node->position
936 					!= NODE_POSITION_EXTERNAL);
937 			node->type = node_defaults[i].type;
938 			if (node->plugged)
939 				gettimeofday(&node->plugged_time, NULL);
940 			break;
941 		}
942 
943 	/*
944 	 * If we didn't find a matching name above, but the node is a jack node,
945 	 * and there is no "HDMI" in the node name, then this must be a 3.5mm
946 	 * headphone/mic.
947 	 * Set its type and name to headphone/mic. The name is important because
948 	 * it associates the UCM section to the node so the properties like
949 	 * default node gain can be obtained.
950 	 * This matches node names like "DAISY-I2S Mic Jack".
951 	 * If HDMI is in the node name, set its type to HDMI. This matches node names
952 	 * like "Rockchip HDMI Jack".
953 	 */
954 	if (i == ARRAY_SIZE(node_defaults)) {
955 		if (endswith(node->name, "Jack") && !strstr(node->name, HDMI)) {
956 			if (node->dev->direction == CRAS_STREAM_OUTPUT) {
957 				node->type = CRAS_NODE_TYPE_HEADPHONE;
958 				strncpy(node->name, HEADPHONE, sizeof(node->name) - 1);
959 			}
960 			else {
961 				node->type = CRAS_NODE_TYPE_MIC;
962 				strncpy(node->name, MIC, sizeof(node->name) - 1);
963 			}
964 		}
965 		if (strstr(node->name, HDMI) &&
966 		    node->dev->direction == CRAS_STREAM_OUTPUT)
967 			node->type = CRAS_NODE_TYPE_HDMI;
968 	}
969 
970 	/* Regardless of the node name of a USB headset (it can be "Speaker"),
971 	 * set it's type to usb.
972 	 */
973 	if (card_type == ALSA_CARD_TYPE_USB) {
974 		node->type = CRAS_NODE_TYPE_USB;
975 		node->position = NODE_POSITION_EXTERNAL;
976 	}
977 
978 #ifdef CRAS_DBUS
979 	if (!is_utf8_string(node->name))
980 		drop_node_name(node);
981 #endif
982 }
983 
get_ucm_flag_integer(struct alsa_io * aio,const char * flag_name,int * result)984 static int get_ucm_flag_integer(struct alsa_io *aio,
985 				const char *flag_name,
986 				int *result)
987 {
988 	char *value;
989 	int i;
990 
991 	if (!aio->ucm)
992 		return -1;
993 
994 	value = ucm_get_flag(aio->ucm, flag_name);
995 	if (!value)
996 		return -1;
997 
998 	i = atoi(value);
999 	free(value);
1000 	*result = i;
1001 	return 0;
1002 }
1003 
auto_unplug_input_node(struct alsa_io * aio)1004 static int auto_unplug_input_node(struct alsa_io *aio)
1005 {
1006 	int result;
1007 	if (get_ucm_flag_integer(aio, "AutoUnplugInputNode", &result))
1008 		return 0;
1009 	return result;
1010 }
1011 
auto_unplug_output_node(struct alsa_io * aio)1012 static int auto_unplug_output_node(struct alsa_io *aio)
1013 {
1014 	int result;
1015 	if (get_ucm_flag_integer(aio, "AutoUnplugOutputNode", &result))
1016 		return 0;
1017 	return result;
1018 }
1019 
no_create_default_input_node(struct alsa_io * aio)1020 static int no_create_default_input_node(struct alsa_io *aio)
1021 {
1022 	int result;
1023 	if (get_ucm_flag_integer(aio, "NoCreateDefaultInputNode", &result))
1024 		return 0;
1025 	return result;
1026 }
1027 
no_create_default_output_node(struct alsa_io * aio)1028 static int no_create_default_output_node(struct alsa_io *aio)
1029 {
1030 	int result;
1031 	if (get_ucm_flag_integer(aio, "NoCreateDefaultOutputNode", &result))
1032 		return 0;
1033 	return result;
1034 }
1035 
set_output_node_software_volume_needed(struct alsa_output_node * output,struct alsa_io * aio)1036 static void set_output_node_software_volume_needed(
1037 	struct alsa_output_node *output, struct alsa_io *aio)
1038 {
1039 
1040 	struct cras_alsa_mixer *mixer = aio->mixer;
1041 	long range = 0;
1042 
1043 	if (aio->ucm && ucm_get_disable_software_volume(aio->ucm)) {
1044 		output->base.software_volume_needed = 0;
1045 		syslog(LOG_DEBUG, "Disable software volume for %s from ucm.",
1046 		       output->base.name);
1047 		return;
1048 	}
1049 
1050 	/* Use software volume for HDMI output and nodes without volume mixer
1051 	 * control. */
1052 	if ((output->base.type == CRAS_NODE_TYPE_HDMI) ||
1053 	    (!cras_alsa_mixer_has_main_volume(mixer) &&
1054 	     !cras_alsa_mixer_has_volume(output->mixer_output)))
1055 		output->base.software_volume_needed = 1;
1056 
1057 	/* Use software volume if the usb device's volume range is smaller
1058 	 * than 40dB */
1059 	if (output->base.type == CRAS_NODE_TYPE_USB) {
1060 		range += cras_alsa_mixer_get_dB_range(mixer);
1061 		range += cras_alsa_mixer_get_output_dB_range(
1062 				output->mixer_output);
1063 		if (range < 4000)
1064 			output->base.software_volume_needed = 1;
1065 	}
1066 	if (output->base.software_volume_needed)
1067 		syslog(LOG_DEBUG, "Use software volume for node: %s",
1068 		       output->base.name);
1069 }
1070 
set_input_node_software_volume_needed(struct alsa_input_node * input,struct alsa_io * aio)1071 static void set_input_node_software_volume_needed(
1072 	struct alsa_input_node *input, struct alsa_io *aio)
1073 {
1074 	long min_software_gain;
1075 	long max_software_gain;
1076 	int rc;
1077 
1078 	input->base.software_volume_needed = 0;
1079 	input->base.min_software_gain = DEFAULT_MIN_CAPTURE_GAIN;
1080 	input->base.max_software_gain = 0;
1081 
1082 	/* Enable software gain only if max software gain is specified in UCM. */
1083 	if (!aio->ucm)
1084 		return;
1085 
1086 	rc = ucm_get_max_software_gain(aio->ucm, input->base.name,
1087 	                               &max_software_gain);
1088 
1089 	/* If max software gain doesn't exist, skip min software gain setting. */
1090 	if (rc)
1091 		return;
1092 
1093 	input->base.software_volume_needed = 1;
1094 	input->base.max_software_gain = max_software_gain;
1095 	syslog(LOG_INFO,
1096 	       "Use software gain for %s with max %ld because it is specified"
1097 	       " in UCM", input->base.name, max_software_gain);
1098 
1099 	/* Enable min software gain if it is specified in UCM. */
1100 	rc = ucm_get_min_software_gain(aio->ucm, input->base.name,
1101 	                               &min_software_gain);
1102 	if (rc)
1103 		return;
1104 
1105 	if (min_software_gain > max_software_gain) {
1106 		syslog(LOG_ERR,
1107 		       "Ignore MinSoftwareGain %ld because it is larger than "
1108 		       "MaxSoftwareGain %ld", min_software_gain, max_software_gain);
1109 		return;
1110 	}
1111 
1112 	syslog(LOG_INFO,
1113 	       "Use software gain for %s with min %ld because it is specified"
1114 	       " in UCM", input->base.name, min_software_gain);
1115 	input->base.min_software_gain = min_software_gain;
1116 }
1117 
set_input_default_node_gain(struct alsa_input_node * input,struct alsa_io * aio)1118 static void set_input_default_node_gain(struct alsa_input_node *input,
1119 					struct alsa_io *aio)
1120 {
1121 	long default_node_gain;
1122 	int rc;
1123 
1124 	if (!aio->ucm)
1125 		return;
1126 
1127 	rc = ucm_get_default_node_gain(aio->ucm, input->base.name,
1128 					 &default_node_gain);
1129 	if (rc)
1130 		return;
1131 
1132 	input->base.capture_gain = default_node_gain;
1133 }
1134 
check_auto_unplug_output_node(struct alsa_io * aio,struct cras_ionode * node,int plugged)1135 static void check_auto_unplug_output_node(struct alsa_io *aio,
1136 					  struct cras_ionode *node,
1137 					  int plugged)
1138 {
1139 	struct cras_ionode *tmp;
1140 
1141 	if (!auto_unplug_output_node(aio))
1142 		return;
1143 
1144 	/* Auto unplug internal speaker if any output node has been created */
1145 	if (!strcmp(node->name, INTERNAL_SPEAKER) && plugged) {
1146 		DL_FOREACH(aio->base.nodes, tmp)
1147 			if (tmp->plugged && (tmp != node))
1148 				cras_iodev_set_node_attr(node,
1149 							 IONODE_ATTR_PLUGGED,
1150 							 0);
1151 	} else {
1152 		DL_FOREACH(aio->base.nodes, tmp) {
1153 			if (!strcmp(tmp->name, INTERNAL_SPEAKER))
1154 				cras_iodev_set_node_attr(tmp,
1155 							 IONODE_ATTR_PLUGGED,
1156 							 !plugged);
1157 		}
1158 	}
1159 }
1160 
1161 /*
1162  * Callback for listing mixer outputs. The mixer will call this once for each
1163  * output associated with this device. Most commonly this is used to tell the
1164  * device it has Headphones and Speakers.
1165  */
new_output(struct alsa_io * aio,struct mixer_control * cras_output,const char * name)1166 static struct alsa_output_node *new_output(struct alsa_io *aio,
1167 					   struct mixer_control *cras_output,
1168 					   const char *name)
1169 {
1170 	struct alsa_output_node *output;
1171 	syslog(LOG_DEBUG, "New output node for '%s'", name);
1172 	if (aio == NULL) {
1173 		syslog(LOG_ERR, "Invalid aio when listing outputs.");
1174 		return NULL;
1175 	}
1176 	output = (struct alsa_output_node *)calloc(1, sizeof(*output));
1177 	if (output == NULL) {
1178 		syslog(LOG_ERR, "Out of memory when listing outputs.");
1179 		return NULL;
1180 	}
1181 	output->base.dev = &aio->base;
1182 	output->base.idx = aio->next_ionode_index++;
1183 	output->base.stable_id = SuperFastHash(name,
1184 					       strlen(name),
1185 					       aio->base.info.stable_id);
1186 	output->base.stable_id_new = SuperFastHash(name,
1187 						   strlen(name),
1188 						   aio->base.info.stable_id_new
1189 						   );
1190 	output->mixer_output = cras_output;
1191 
1192 	/* Volume curve. */
1193 	output->volume_curve = cras_card_config_get_volume_curve_for_control(
1194 			aio->config,
1195 			name ? name
1196 			     : cras_alsa_mixer_get_control_name(cras_output));
1197 
1198 	strncpy(output->base.name, name, sizeof(output->base.name) - 1);
1199 	set_node_initial_state(&output->base, aio->card_type);
1200 	set_output_node_software_volume_needed(output, aio);
1201 
1202 	cras_iodev_add_node(&aio->base, &output->base);
1203 
1204 	check_auto_unplug_output_node(aio, &output->base, output->base.plugged);
1205 	return output;
1206 }
1207 
new_output_by_mixer_control(struct mixer_control * cras_output,void * callback_arg)1208 static void new_output_by_mixer_control(struct mixer_control *cras_output,
1209 				        void *callback_arg)
1210 {
1211 	struct alsa_io *aio = (struct alsa_io *)callback_arg;
1212 	char node_name[CRAS_IODEV_NAME_BUFFER_SIZE];
1213 	const char *ctl_name;
1214 
1215 	ctl_name = cras_alsa_mixer_get_control_name(cras_output);
1216 	if (!ctl_name)
1217 	        return;
1218 
1219 	if (aio->card_type == ALSA_CARD_TYPE_USB) {
1220 		if (snprintf(node_name, sizeof(node_name), "%s: %s",
1221 			     aio->base.info.name, ctl_name) > 0) {
1222 			new_output(aio, cras_output, node_name);
1223 		}
1224 	} else {
1225 		new_output(aio, cras_output, ctl_name);
1226 	}
1227 }
1228 
check_auto_unplug_input_node(struct alsa_io * aio,struct cras_ionode * node,int plugged)1229 static void check_auto_unplug_input_node(struct alsa_io *aio,
1230 					 struct cras_ionode *node,
1231 					 int plugged)
1232 {
1233 	struct cras_ionode *tmp;
1234 	if (!auto_unplug_input_node(aio))
1235 		return;
1236 
1237 	/* Auto unplug internal mic if any input node has already
1238 	 * been created */
1239 	if (!strcmp(node->name, INTERNAL_MICROPHONE) && plugged) {
1240 		DL_FOREACH(aio->base.nodes, tmp)
1241 			if (tmp->plugged && (tmp != node))
1242 				cras_iodev_set_node_attr(node,
1243 							 IONODE_ATTR_PLUGGED,
1244 							 0);
1245 	} else {
1246 		DL_FOREACH(aio->base.nodes, tmp)
1247 			if (!strcmp(tmp->name, INTERNAL_MICROPHONE))
1248 				cras_iodev_set_node_attr(tmp,
1249 							 IONODE_ATTR_PLUGGED,
1250 							 !plugged);
1251 	}
1252 }
1253 
new_input(struct alsa_io * aio,struct mixer_control * cras_input,const char * name)1254 static struct alsa_input_node *new_input(struct alsa_io *aio,
1255 		struct mixer_control *cras_input, const char *name)
1256 {
1257 	struct cras_iodev *iodev = &aio->base;
1258 	struct alsa_input_node *input;
1259 	char *mic_positions;
1260 	int err;
1261 
1262 	input = (struct alsa_input_node *)calloc(1, sizeof(*input));
1263 	if (input == NULL) {
1264 		syslog(LOG_ERR, "Out of memory when listing inputs.");
1265 		return NULL;
1266 	}
1267 	input->base.dev = &aio->base;
1268 	input->base.idx = aio->next_ionode_index++;
1269 	input->base.stable_id = SuperFastHash(name,
1270 					      strlen(name),
1271 					      aio->base.info.stable_id);
1272 	input->base.stable_id_new = SuperFastHash(name,
1273 						  strlen(name),
1274 						  aio->base.info.stable_id_new);
1275 	input->mixer_input = cras_input;
1276 	strncpy(input->base.name, name, sizeof(input->base.name) - 1);
1277 	set_node_initial_state(&input->base, aio->card_type);
1278 	set_input_node_software_volume_needed(input, aio);
1279 	set_input_default_node_gain(input, aio);
1280 
1281 	if (aio->ucm) {
1282 		/* Check mic positions only for internal mic. */
1283 		if ((input->base.type == CRAS_NODE_TYPE_MIC) &&
1284 		    (input->base.position == NODE_POSITION_INTERNAL)) {
1285 			mic_positions = ucm_get_mic_positions(aio->ucm);
1286 			if (mic_positions) {
1287 				strncpy(input->base.mic_positions,
1288 					mic_positions,
1289 					sizeof(input->base.mic_positions) - 1);
1290 				free(mic_positions);
1291 			}
1292 		}
1293 
1294 		/* Check if channel map is specified in UCM. */
1295 		input->channel_layout = (int8_t *)malloc(
1296 				CRAS_CH_MAX * sizeof(*input->channel_layout));
1297 		err = ucm_get_capture_chmap_for_dev(aio->ucm, name,
1298 						    input->channel_layout);
1299 		if (err) {
1300 			free(input->channel_layout);
1301 			input->channel_layout = 0;
1302 		}
1303 		if (ucm_get_preempt_hotword(aio->ucm, name)) {
1304 			iodev->pre_open_iodev_hook =
1305 				cras_iodev_list_suspend_hotword_streams;
1306 			iodev->post_close_iodev_hook =
1307 				cras_iodev_list_resume_hotword_stream;
1308 		}
1309 	}
1310 
1311 	cras_iodev_add_node(&aio->base, &input->base);
1312 	check_auto_unplug_input_node(aio, &input->base,
1313 				     input->base.plugged);
1314 	return input;
1315 }
1316 
new_input_by_mixer_control(struct mixer_control * cras_input,void * callback_arg)1317 static void new_input_by_mixer_control(struct mixer_control *cras_input,
1318 				       void *callback_arg)
1319 {
1320 	struct alsa_io *aio = (struct alsa_io *)callback_arg;
1321 	char node_name[CRAS_IODEV_NAME_BUFFER_SIZE];
1322 	const char *ctl_name = cras_alsa_mixer_get_control_name(cras_input);
1323 
1324 	if (aio->card_type == ALSA_CARD_TYPE_USB) {
1325 		int ret = snprintf(node_name , sizeof(node_name), "%s: %s",
1326 				   aio->base.info.name, ctl_name);
1327 		// Truncation is OK, but add a check to make the compiler happy.
1328 		if (ret == sizeof(node_name))
1329 			node_name[sizeof(node_name) - 1] = '\0';
1330 		new_input(aio, cras_input, node_name);
1331 	} else {
1332 		new_input(aio, cras_input, ctl_name);
1333 	}
1334 }
1335 
1336 /*
1337  * Finds the output node associated with the jack. Returns NULL if not found.
1338  */
get_output_node_from_jack(struct alsa_io * aio,const struct cras_alsa_jack * jack)1339 static struct alsa_output_node *get_output_node_from_jack(
1340 		struct alsa_io *aio, const struct cras_alsa_jack *jack)
1341 {
1342 	struct mixer_control *mixer_output;
1343 	struct cras_ionode *node = NULL;
1344 	struct alsa_output_node *aout = NULL;
1345 
1346 	/* Search by jack first. */
1347 	DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, aout,
1348 				   jack, jack);
1349 	if (aout)
1350 		return aout;
1351 
1352 	/* Search by mixer control next. */
1353 	mixer_output = cras_alsa_jack_get_mixer_output(jack);
1354 	if (mixer_output == NULL)
1355 		return NULL;
1356 
1357 	DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, aout,
1358 				   mixer_output, mixer_output);
1359 	return aout;
1360 }
1361 
get_input_node_from_jack(struct alsa_io * aio,const struct cras_alsa_jack * jack)1362 static struct alsa_input_node *get_input_node_from_jack(
1363 		struct alsa_io *aio, const struct cras_alsa_jack *jack)
1364 {
1365 	struct mixer_control *mixer_input;
1366 	struct cras_ionode *node = NULL;
1367 	struct alsa_input_node *ain = NULL;
1368 
1369 	mixer_input = cras_alsa_jack_get_mixer_input(jack);
1370 	if (mixer_input == NULL) {
1371 		DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, ain,
1372 					   jack, jack);
1373 		return ain;
1374 	}
1375 
1376 	DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, ain,
1377 				   mixer_input, mixer_input);
1378 	return ain;
1379 }
1380 
get_jack_from_node(struct cras_ionode * node)1381 static const struct cras_alsa_jack *get_jack_from_node(struct cras_ionode *node)
1382 {
1383 	const struct cras_alsa_jack *jack = NULL;
1384 
1385 	if (node == NULL)
1386 		return NULL;
1387 
1388 	if (node->dev->direction == CRAS_STREAM_OUTPUT)
1389 		jack = ((struct alsa_output_node *)node)->jack;
1390 	else if (node->dev->direction == CRAS_STREAM_INPUT)
1391 		jack = ((struct alsa_input_node *)node)->jack;
1392 
1393 	return jack;
1394 }
1395 
1396 /*
1397  * Returns the dsp name specified in the ucm config. If there is a dsp
1398  * name specified for the jack of the active node, use that. Otherwise
1399  * use the default dsp name for the alsa_io device.
1400  */
get_active_dsp_name(struct alsa_io * aio)1401 static const char *get_active_dsp_name(struct alsa_io *aio)
1402 {
1403 	struct cras_ionode *node = aio->base.active_node;
1404 	const struct cras_alsa_jack *jack;
1405 
1406 	if (node == NULL)
1407 		return NULL;
1408 
1409 	if (aio->base.direction == CRAS_STREAM_OUTPUT)
1410 		jack = ((struct alsa_output_node *) node)->jack;
1411 	else
1412 		jack = ((struct alsa_input_node *) node)->jack;
1413 
1414 	return cras_alsa_jack_get_dsp_name(jack) ? : aio->dsp_name_default;
1415 }
1416 
1417 /*
1418  * Creates volume curve for the node associated with given jack.
1419  */
create_volume_curve_for_jack(const struct cras_card_config * config,const struct cras_alsa_jack * jack)1420 static struct cras_volume_curve *create_volume_curve_for_jack(
1421 		const struct cras_card_config *config,
1422 		const struct cras_alsa_jack *jack)
1423 {
1424 	struct cras_volume_curve *curve;
1425 	const char *name;
1426 
1427 	/* Use jack's UCM device name as key to get volume curve. */
1428 	name = cras_alsa_jack_get_ucm_device(jack);
1429 	curve = cras_card_config_get_volume_curve_for_control(config, name);
1430 	if (curve)
1431 		return curve;
1432 
1433 	/* Use alsa jack's name as key to get volume curve. */
1434 	name = cras_alsa_jack_get_name(jack);
1435 	curve = cras_card_config_get_volume_curve_for_control(config, name);
1436 	if (curve)
1437 		return curve;
1438 
1439 	return NULL;
1440 }
1441 
1442 /*
1443  * Callback that is called when an output jack is plugged or unplugged.
1444  */
jack_output_plug_event(const struct cras_alsa_jack * jack,int plugged,void * arg)1445 static void jack_output_plug_event(const struct cras_alsa_jack *jack,
1446 				    int plugged,
1447 				    void *arg)
1448 {
1449 	struct alsa_io *aio;
1450 	struct alsa_output_node *node;
1451 	const char *jack_name;
1452 
1453 	if (arg == NULL)
1454 		return;
1455 
1456 	aio = (struct alsa_io *)arg;
1457 	node = get_output_node_from_jack(aio, jack);
1458 	jack_name = cras_alsa_jack_get_name(jack);
1459 	if (!strcmp(jack_name, "Speaker Phantom Jack"))
1460 		jack_name = INTERNAL_SPEAKER;
1461 
1462 	/* If there isn't a node for this jack, create one. */
1463 	if (node == NULL) {
1464 		if (aio->fully_specified) {
1465 			/* When fully specified, can't have new nodes. */
1466 			syslog(LOG_ERR, "No matching output node for jack %s!",
1467 			       jack_name);
1468 			return;
1469 		}
1470 		node = new_output(aio, NULL, jack_name);
1471 		if (node == NULL)
1472 			return;
1473 
1474 		cras_alsa_jack_update_node_type(jack, &(node->base.type));
1475 	}
1476 
1477 	if (!node->jack) {
1478 		if (aio->fully_specified)
1479 			syslog(LOG_ERR,
1480 			       "Jack '%s' was found to match output node '%s'."
1481 			       " Please fix your UCM configuration to match.",
1482 			       jack_name, node->base.name);
1483 
1484 		/* If we already have the node, associate with the jack. */
1485 		node->jack = jack;
1486 		if (node->volume_curve == NULL)
1487 			node->volume_curve = create_volume_curve_for_jack(
1488 					aio->config, jack);
1489 	}
1490 
1491 	syslog(LOG_DEBUG, "%s plugged: %d, %s", jack_name, plugged,
1492 	       cras_alsa_mixer_get_control_name(node->mixer_output));
1493 
1494 	cras_alsa_jack_update_monitor_name(jack, node->base.name,
1495 					   sizeof(node->base.name));
1496 
1497 #ifdef CRAS_DBUS
1498 	/* The name got from jack might be an invalid UTF8 string. */
1499 	if (!is_utf8_string(node->base.name))
1500 		drop_node_name(&node->base);
1501 #endif
1502 
1503 	cras_iodev_set_node_attr(&node->base, IONODE_ATTR_PLUGGED, plugged);
1504 
1505 	check_auto_unplug_output_node(aio, &node->base, plugged);
1506 }
1507 
1508 /*
1509  * Callback that is called when an input jack is plugged or unplugged.
1510  */
jack_input_plug_event(const struct cras_alsa_jack * jack,int plugged,void * arg)1511 static void jack_input_plug_event(const struct cras_alsa_jack *jack,
1512 				  int plugged,
1513 				  void *arg)
1514 {
1515 	struct alsa_io *aio;
1516 	struct alsa_input_node *node;
1517 	struct mixer_control *cras_input;
1518 	const char *jack_name;
1519 
1520 	if (arg == NULL)
1521 		return;
1522 	aio = (struct alsa_io *)arg;
1523 	node = get_input_node_from_jack(aio, jack);
1524 	jack_name = cras_alsa_jack_get_name(jack);
1525 
1526 	/* If there isn't a node for this jack, create one. */
1527 	if (node == NULL) {
1528 		if (aio->fully_specified) {
1529 			/* When fully specified, can't have new nodes. */
1530 			syslog(LOG_ERR, "No matching input node for jack %s!",
1531 			       jack_name);
1532 			return;
1533 		}
1534 		cras_input = cras_alsa_jack_get_mixer_input(jack);
1535 		node = new_input(aio, cras_input, jack_name);
1536 		if (node == NULL)
1537 			return;
1538 	}
1539 
1540 	syslog(LOG_DEBUG, "%s plugged: %d, %s", jack_name, plugged,
1541 	       cras_alsa_mixer_get_control_name(node->mixer_input));
1542 
1543 	/* If we already have the node, associate with the jack. */
1544 	if (!node->jack) {
1545 		if (aio->fully_specified)
1546 			syslog(LOG_ERR,
1547 			       "Jack '%s' was found to match input node '%s'."
1548 			       " Please fix your UCM configuration to match.",
1549 			       jack_name, node->base.name);
1550 		node->jack = jack;
1551 	}
1552 
1553 	cras_iodev_set_node_attr(&node->base, IONODE_ATTR_PLUGGED, plugged);
1554 
1555 	check_auto_unplug_input_node(aio, &node->base, plugged);
1556 }
1557 
1558 /*
1559  * Sets the name of the given iodev, using the name and index of the card
1560  * combined with the device index and direction.
1561  */
set_iodev_name(struct cras_iodev * dev,const char * card_name,const char * dev_name,size_t card_index,size_t device_index,enum CRAS_ALSA_CARD_TYPE card_type,size_t usb_vid,size_t usb_pid,char * usb_serial_number)1562 static void set_iodev_name(struct cras_iodev *dev,
1563 			   const char *card_name,
1564 			   const char *dev_name,
1565 			   size_t card_index,
1566 			   size_t device_index,
1567 			   enum CRAS_ALSA_CARD_TYPE card_type,
1568 			   size_t usb_vid,
1569 			   size_t usb_pid,
1570 			   char *usb_serial_number)
1571 {
1572 	snprintf(dev->info.name,
1573 		 sizeof(dev->info.name),
1574 		 "%s: %s:%zu,%zu",
1575 		 card_name,
1576 		 dev_name,
1577 		 card_index,
1578 		 device_index);
1579 	dev->info.name[ARRAY_SIZE(dev->info.name) - 1] = '\0';
1580 	syslog(LOG_DEBUG, "Add device name=%s", dev->info.name);
1581 
1582 	dev->info.stable_id = SuperFastHash(card_name,
1583 					    strlen(card_name),
1584 					    strlen(card_name));
1585 	dev->info.stable_id = SuperFastHash(dev_name,
1586 					    strlen(dev_name),
1587 					    dev->info.stable_id);
1588 
1589 	switch (card_type) {
1590 	case ALSA_CARD_TYPE_INTERNAL:
1591 		dev->info.stable_id = SuperFastHash((const char *)&device_index,
1592 						    sizeof(device_index),
1593 						    dev->info.stable_id);
1594 		dev->info.stable_id_new = dev->info.stable_id;
1595 		break;
1596 	case ALSA_CARD_TYPE_USB:
1597 		dev->info.stable_id = SuperFastHash((const char *)&usb_vid,
1598 						    sizeof(usb_vid),
1599 						    dev->info.stable_id);
1600 		dev->info.stable_id = SuperFastHash((const char *)&usb_pid,
1601 						    sizeof(usb_pid),
1602 						    dev->info.stable_id);
1603 		dev->info.stable_id_new =
1604 			SuperFastHash(usb_serial_number,
1605 				      strlen(usb_serial_number),
1606 				      dev->info.stable_id);
1607 		break;
1608 	default:
1609 		dev->info.stable_id_new = dev->info.stable_id;
1610 		break;
1611 	}
1612 	syslog(LOG_DEBUG, "Stable ID=%08x, New Stable ID=%08x",
1613 	       dev->info.stable_id, dev->info.stable_id_new);
1614 }
1615 
get_fixed_rate(struct alsa_io * aio)1616 static int get_fixed_rate(struct alsa_io *aio)
1617 {
1618 	const char *name;
1619 
1620 	if (aio->base.direction == CRAS_STREAM_OUTPUT) {
1621 		struct alsa_output_node *active = get_active_output(aio);
1622 		if (!active)
1623 			return -ENOENT;
1624 		name = active->base.name;
1625 	} else {
1626 		struct alsa_input_node *active = get_active_input(aio);
1627 		if (!active)
1628 			return -ENOENT;
1629 		name = active->base.name;
1630 	}
1631 
1632 	return ucm_get_sample_rate_for_dev(aio->ucm, name, aio->base.direction);
1633 }
1634 
1635 /*
1636  * Updates the supported sample rates and channel counts.
1637  */
update_supported_formats(struct cras_iodev * iodev)1638 static int update_supported_formats(struct cras_iodev *iodev)
1639 {
1640 	struct alsa_io *aio = (struct alsa_io *)iodev;
1641 	int err;
1642 	int fixed_rate;
1643 
1644 	free(iodev->supported_rates);
1645 	iodev->supported_rates = NULL;
1646 	free(iodev->supported_channel_counts);
1647 	iodev->supported_channel_counts = NULL;
1648 	free(iodev->supported_formats);
1649 	iodev->supported_formats = NULL;
1650 
1651 	err = cras_alsa_fill_properties(aio->handle,
1652 					&iodev->supported_rates,
1653 					&iodev->supported_channel_counts,
1654 					&iodev->supported_formats);
1655 	if (err)
1656 		return err;
1657 
1658 	if (aio->ucm) {
1659 		/* Allow UCM to override supplied rates. */
1660 		fixed_rate = get_fixed_rate(aio);
1661 		if (fixed_rate > 0) {
1662 			free(iodev->supported_rates);
1663 			iodev->supported_rates = (size_t*)malloc(
1664 					2 * sizeof(iodev->supported_rates[0]));
1665 			iodev->supported_rates[0] = fixed_rate;
1666 			iodev->supported_rates[1] = 0;
1667 		}
1668 	}
1669 	return 0;
1670 }
1671 
1672 /*
1673  * Builds software volume scalers for output nodes in the device.
1674  */
build_softvol_scalers(struct alsa_io * aio)1675 static void build_softvol_scalers(struct alsa_io *aio)
1676 {
1677 	struct cras_ionode *ionode;
1678 
1679 	DL_FOREACH(aio->base.nodes, ionode) {
1680 		struct alsa_output_node *aout;
1681 		const struct cras_volume_curve *curve;
1682 
1683 		aout = (struct alsa_output_node *)ionode;
1684 		curve = get_curve_for_output_node(aio, aout);
1685 
1686 		ionode->softvol_scalers = softvol_build_from_curve(curve);
1687 	}
1688 }
1689 
enable_active_ucm(struct alsa_io * aio,int plugged)1690 static void enable_active_ucm(struct alsa_io *aio, int plugged)
1691 {
1692 	const struct cras_alsa_jack *jack;
1693 	const char *name;
1694 
1695 	if (aio->base.direction == CRAS_STREAM_OUTPUT) {
1696 		struct alsa_output_node *active = get_active_output(aio);
1697 		if (!active)
1698 			return;
1699 		name = active->base.name;
1700 		jack = active->jack;
1701 	} else {
1702 		struct alsa_input_node *active = get_active_input(aio);
1703 		if (!active)
1704 			return;
1705 		name = active->base.name;
1706 		jack = active->jack;
1707 	}
1708 
1709 	if (jack)
1710 		cras_alsa_jack_enable_ucm(jack, plugged);
1711 	else if (aio->ucm)
1712 		ucm_set_enabled(aio->ucm, name, plugged);
1713 }
1714 
fill_whole_buffer_with_zeros(struct cras_iodev * iodev)1715 static int fill_whole_buffer_with_zeros(struct cras_iodev *iodev)
1716 {
1717 	struct alsa_io *aio = (struct alsa_io *)iodev;
1718 	int rc;
1719 	uint8_t *dst = NULL;
1720 	size_t format_bytes;
1721 
1722 	/* Fill whole buffer with zeros. */
1723 	rc = cras_alsa_mmap_get_whole_buffer(aio->handle, &dst);
1724 
1725 	if (rc < 0) {
1726 		syslog(LOG_ERR, "Failed to get whole buffer: %s",
1727 		       snd_strerror(rc));
1728 		return rc;
1729 	}
1730 
1731 	format_bytes = cras_get_format_bytes(iodev->format);
1732 	memset(dst, 0, iodev->buffer_size * format_bytes);
1733 
1734 	return 0;
1735 }
1736 
adjust_appl_ptr(struct cras_iodev * odev)1737 static int adjust_appl_ptr(struct cras_iodev *odev)
1738 {
1739 	struct alsa_io *aio = (struct alsa_io *)odev;
1740 
1741 	/* Move appl_ptr to min_buffer_level + min_cb_level frames ahead of
1742 	 * hw_ptr when resuming from free run or adjusting appl_ptr from
1743 	 * underrun. */
1744 	return cras_alsa_resume_appl_ptr(
1745 			aio->handle,
1746 			odev->min_buffer_level + odev->min_cb_level);
1747 }
1748 
1749 /* This function is for leaving no-stream state but still not in free run yet.
1750  * The device may have valid samples remaining. We need to adjust appl_ptr to
1751  * the correct position, which is MAX(min_cb_level + min_buffer_level,
1752  * valid_sample) */
adjust_appl_ptr_samples_remaining(struct cras_iodev * odev)1753 static int adjust_appl_ptr_samples_remaining(struct cras_iodev *odev)
1754 {
1755 	struct alsa_io *aio = (struct alsa_io *)odev;
1756 	int rc;
1757 	unsigned int real_hw_level, valid_sample, offset;
1758 	struct timespec hw_tstamp;
1759 
1760 	/* Get the amount of valid samples which haven't been played yet.
1761 	 * The real_hw_level is the real hw_level in device buffer. It doesn't
1762 	 * subtract min_buffer_level. */
1763 	valid_sample = 0;
1764 	rc = odev->frames_queued(odev, &hw_tstamp);
1765 	if(rc < 0)
1766 		return rc;
1767 	real_hw_level = rc;
1768 
1769 	/*
1770 	 * If underrun happened, handle it. Because alsa_output_underrun function
1771 	 * has already called adjust_appl_ptr, we don't need to call it again.
1772 	 */
1773 	if (real_hw_level < odev->min_buffer_level)
1774 		return odev->output_underrun(odev);
1775 
1776 	if (real_hw_level > aio->filled_zeros_for_draining)
1777 		valid_sample = real_hw_level - aio->filled_zeros_for_draining;
1778 
1779 	offset = MAX(odev->min_buffer_level + odev->min_cb_level, valid_sample);
1780 
1781 	/* Fill zeros to make sure there are enough zero samples in device buffer.*/
1782 	if (offset > real_hw_level) {
1783 		rc = cras_iodev_fill_odev_zeros(odev, offset - real_hw_level);
1784 		if (rc)
1785 			return rc;
1786 	}
1787 	return cras_alsa_resume_appl_ptr(aio->handle, offset);
1788 }
1789 
alsa_output_underrun(struct cras_iodev * odev)1790 static int alsa_output_underrun(struct cras_iodev *odev)
1791 {
1792 	struct alsa_io *aio = (struct alsa_io *)odev;
1793 	int rc;
1794 
1795 	/* Update number of underruns we got. */
1796 	aio->num_underruns++;
1797 
1798 	/* Fill whole buffer with zeros. This avoids samples left in buffer causing
1799 	 * noise when device plays them. */
1800 	rc = fill_whole_buffer_with_zeros(odev);
1801 	if (rc)
1802 		return rc;
1803 	/* Adjust appl_ptr to leave underrun. */
1804 	return adjust_appl_ptr(odev);
1805 }
1806 
possibly_enter_free_run(struct cras_iodev * odev)1807 static int possibly_enter_free_run(struct cras_iodev *odev)
1808 {
1809 	struct alsa_io *aio = (struct alsa_io *)odev;
1810 	int rc;
1811 	unsigned int real_hw_level, fr_to_write;
1812 	unsigned int target_hw_level = odev->min_cb_level * 2 + odev->min_buffer_level;
1813 	struct timespec hw_tstamp;
1814 
1815 	if (aio->is_free_running)
1816 		return 0;
1817 
1818 	/* Check if all valid samples are played. If all valid samples are played,
1819 	 * fill whole buffer with zeros. The real_hw_level is the real hw_level in
1820 	 * device buffer. It doesn't subtract min_buffer_level.*/
1821 	rc = odev->frames_queued(odev, &hw_tstamp);
1822 	if(rc < 0)
1823 		return rc;
1824 	real_hw_level = rc;
1825 
1826 	/* If underrun happened, handle it and enter free run state. */
1827 	if (real_hw_level < odev->min_buffer_level) {
1828 		rc = odev->output_underrun(odev);
1829 		if (rc < 0)
1830 			return rc;
1831 		aio->is_free_running = 1;
1832 		return 0;
1833 	}
1834 
1835 	if (real_hw_level <= aio->filled_zeros_for_draining || real_hw_level == 0) {
1836 		rc = fill_whole_buffer_with_zeros(odev);
1837 		if (rc < 0)
1838 			return rc;
1839 		aio->is_free_running = 1;
1840 		return 0;
1841 	}
1842 
1843 	/* Fill some zeros to drain valid samples. */
1844 	fr_to_write = odev->buffer_size - real_hw_level;
1845 	if (real_hw_level < target_hw_level) {
1846 		fr_to_write = MIN(target_hw_level - real_hw_level, fr_to_write);
1847 		rc = cras_iodev_fill_odev_zeros(odev, fr_to_write);
1848 		if (rc)
1849 			return rc;
1850 		aio->filled_zeros_for_draining += fr_to_write;
1851 	}
1852 
1853 	return 0;
1854 }
1855 
leave_free_run(struct cras_iodev * odev)1856 static int leave_free_run(struct cras_iodev *odev)
1857 {
1858 	struct alsa_io *aio = (struct alsa_io *)odev;
1859 	int rc;
1860 
1861 	if (aio->is_free_running)
1862 		rc = adjust_appl_ptr(odev);
1863 	else
1864 		rc = adjust_appl_ptr_samples_remaining(odev);
1865 	if (rc) {
1866 		syslog(LOG_ERR, "device %s failed to leave free run, rc = %d",
1867 		       odev->info.name, rc);
1868 		return rc;
1869 	}
1870 	aio->is_free_running = 0;
1871 	aio->filled_zeros_for_draining = 0;
1872 
1873 	return 0;
1874 }
1875 
1876 /*
1877  * Free run state is the optimization of no_stream playback on alsa_io.
1878  * The whole buffer will be filled with zeros. Device can play these zeros
1879  * indefinitely. When there is new meaningful sample, appl_ptr should be
1880  * resumed to some distance ahead of hw_ptr.
1881  */
no_stream(struct cras_iodev * odev,int enable)1882 static int no_stream(struct cras_iodev *odev, int enable)
1883 {
1884 	if (enable)
1885 		return possibly_enter_free_run(odev);
1886 	else
1887 		return leave_free_run(odev);
1888 }
1889 
output_should_wake(const struct cras_iodev * odev)1890 static int output_should_wake(const struct cras_iodev *odev)
1891 {
1892 	struct alsa_io *aio = (struct alsa_io *)odev;
1893 	if (aio->is_free_running)
1894 		return 0;
1895 	else
1896 		return ((cras_iodev_state(odev) ==
1897 					CRAS_IODEV_STATE_NO_STREAM_RUN) ||
1898 		        (cras_iodev_state(odev) ==
1899 					CRAS_IODEV_STATE_NORMAL_RUN));
1900 }
1901 
get_num_underruns(const struct cras_iodev * iodev)1902 static unsigned int get_num_underruns(const struct cras_iodev *iodev)
1903 {
1904 	const struct alsa_io *aio = (const struct alsa_io *)iodev;
1905 	return aio->num_underruns;
1906 }
1907 
get_num_severe_underruns(const struct cras_iodev * iodev)1908 static unsigned int get_num_severe_underruns(const struct cras_iodev *iodev)
1909 {
1910 	const struct alsa_io *aio = (const struct alsa_io *)iodev;
1911 	return aio->num_severe_underruns;
1912 }
1913 
set_default_hotword_model(struct cras_iodev * iodev)1914 static void set_default_hotword_model(struct cras_iodev *iodev)
1915 {
1916 	const char *default_model = "en_us";
1917 	cras_node_id_t node_id;
1918 
1919 	if (!iodev->active_node ||
1920 	     iodev->active_node->type != CRAS_NODE_TYPE_HOTWORD)
1921 		return;
1922 
1923 	node_id = cras_make_node_id(iodev->info.idx, iodev->active_node->idx);
1924 	/* This is a no-op if the default_model is not supported */
1925 	cras_iodev_list_set_hotword_model(node_id, default_model);
1926 }
1927 
1928 /*
1929  * Exported Interface.
1930  */
1931 
alsa_iodev_create(size_t card_index,const char * card_name,size_t device_index,const char * dev_name,const char * dev_id,enum CRAS_ALSA_CARD_TYPE card_type,int is_first,struct cras_alsa_mixer * mixer,const struct cras_card_config * config,struct cras_use_case_mgr * ucm,snd_hctl_t * hctl,enum CRAS_STREAM_DIRECTION direction,size_t usb_vid,size_t usb_pid,char * usb_serial_number)1932 struct cras_iodev *alsa_iodev_create(size_t card_index,
1933 				     const char *card_name,
1934 				     size_t device_index,
1935 				     const char *dev_name,
1936 				     const char *dev_id,
1937 				     enum CRAS_ALSA_CARD_TYPE card_type,
1938 				     int is_first,
1939 				     struct cras_alsa_mixer *mixer,
1940 				     const struct cras_card_config *config,
1941 				     struct cras_use_case_mgr *ucm,
1942 				     snd_hctl_t *hctl,
1943 				     enum CRAS_STREAM_DIRECTION direction,
1944 				     size_t usb_vid,
1945 				     size_t usb_pid,
1946 				     char *usb_serial_number)
1947 {
1948 	struct alsa_io *aio;
1949 	struct cras_iodev *iodev;
1950 
1951 	if (direction != CRAS_STREAM_INPUT && direction != CRAS_STREAM_OUTPUT)
1952 		return NULL;
1953 
1954 	aio = (struct alsa_io *)calloc(1, sizeof(*aio));
1955 	if (!aio)
1956 		return NULL;
1957 	iodev = &aio->base;
1958 	iodev->direction = direction;
1959 
1960 	aio->device_index = device_index;
1961 	aio->card_type = card_type;
1962 	aio->is_first = is_first;
1963 	aio->handle = NULL;
1964 	aio->num_severe_underruns = 0;
1965 	if (dev_name) {
1966 		aio->dev_name = strdup(dev_name);
1967 		if (!aio->dev_name)
1968 			goto cleanup_iodev;
1969 	}
1970 	if (dev_id) {
1971 		aio->dev_id = strdup(dev_id);
1972 		if (!aio->dev_id)
1973 			goto cleanup_iodev;
1974 	}
1975 	aio->is_free_running = 0;
1976 	aio->filled_zeros_for_draining = 0;
1977 	aio->dev = (char *)malloc(MAX_ALSA_DEV_NAME_LENGTH);
1978 	if (aio->dev == NULL)
1979 		goto cleanup_iodev;
1980 	snprintf(aio->dev,
1981 		 MAX_ALSA_DEV_NAME_LENGTH,
1982 		 "hw:%zu,%zu",
1983 		 card_index,
1984 		 device_index);
1985 
1986 	if (direction == CRAS_STREAM_INPUT) {
1987 		aio->alsa_stream = SND_PCM_STREAM_CAPTURE;
1988 		aio->base.set_capture_gain = set_alsa_capture_gain;
1989 		aio->base.set_capture_mute = set_alsa_capture_gain;
1990 	} else {
1991 		aio->alsa_stream = SND_PCM_STREAM_PLAYBACK;
1992 		aio->base.set_volume = set_alsa_volume;
1993 		aio->base.set_mute = set_alsa_mute;
1994 		aio->base.output_underrun = alsa_output_underrun;
1995 	}
1996 	iodev->open_dev = open_dev;
1997 	iodev->configure_dev = configure_dev;
1998 	iodev->close_dev = close_dev;
1999 	iodev->update_supported_formats = update_supported_formats;
2000 	iodev->frames_queued = frames_queued;
2001 	iodev->delay_frames = delay_frames;
2002 	iodev->get_buffer = get_buffer;
2003 	iodev->put_buffer = put_buffer;
2004 	iodev->flush_buffer = flush_buffer;
2005 	iodev->start = start;
2006 	iodev->update_active_node = update_active_node;
2007 	iodev->update_channel_layout = update_channel_layout;
2008 	iodev->set_hotword_model = set_hotword_model;
2009 	iodev->get_hotword_models = get_hotword_models;
2010 	iodev->no_stream = no_stream;
2011 	iodev->output_should_wake = output_should_wake;
2012 	iodev->get_num_underruns = get_num_underruns;
2013 	iodev->get_num_severe_underruns = get_num_severe_underruns;
2014 	iodev->set_swap_mode_for_node = cras_iodev_dsp_set_swap_mode_for_node;
2015 
2016 	if (card_type == ALSA_CARD_TYPE_USB)
2017 		iodev->min_buffer_level = USB_EXTRA_BUFFER_FRAMES;
2018 
2019 	iodev->ramp = cras_ramp_create();
2020 	if (iodev->ramp == NULL)
2021 		goto cleanup_iodev;
2022 
2023 	aio->mixer = mixer;
2024 	aio->config = config;
2025 	if (direction == CRAS_STREAM_OUTPUT) {
2026 		aio->default_volume_curve =
2027 				cras_card_config_get_volume_curve_for_control(
2028 						config, "Default");
2029 		if (aio->default_volume_curve == NULL)
2030 			aio->default_volume_curve =
2031 					cras_volume_curve_create_default();
2032 	}
2033 	aio->ucm = ucm;
2034 	if (ucm) {
2035 		unsigned int level;
2036 		int rc;
2037 
2038 		aio->dsp_name_default = ucm_get_dsp_name_default(ucm,
2039 								 direction);
2040 		/* Set callback for swap mode if it is supported
2041 		 * in ucm modifier. */
2042 		if (ucm_swap_mode_exists(ucm))
2043 			aio->base.set_swap_mode_for_node =
2044 				set_alsa_node_swapped;
2045 
2046 		rc = ucm_get_min_buffer_level(ucm, &level);
2047 		if (!rc && direction == CRAS_STREAM_OUTPUT)
2048 			iodev->min_buffer_level = level;
2049 
2050 		aio->enable_htimestamp =
2051 			ucm_get_enable_htimestamp_flag(ucm);
2052 	}
2053 
2054 	set_iodev_name(iodev, card_name, dev_name, card_index, device_index,
2055 		       card_type, usb_vid, usb_pid, usb_serial_number);
2056 
2057 	aio->jack_list =
2058 		cras_alsa_jack_list_create(
2059 			card_index,
2060 			card_name,
2061 			device_index,
2062 			is_first,
2063 			mixer,
2064 			ucm,
2065 			hctl,
2066 			direction,
2067 			direction == CRAS_STREAM_OUTPUT ?
2068 				     jack_output_plug_event :
2069 				     jack_input_plug_event,
2070 			aio);
2071 	if (!aio->jack_list)
2072 		goto cleanup_iodev;
2073 
2074 	/* HDMI outputs don't have volume adjustment, do it in software. */
2075 	if (direction == CRAS_STREAM_OUTPUT && strstr(dev_name, HDMI))
2076 		iodev->software_volume_needed = 1;
2077 
2078 	/* Add this now so that cleanup of the iodev (in case of error or card
2079 	 * card removal will function as expected. */
2080 	if (direction == CRAS_STREAM_OUTPUT)
2081 		cras_iodev_list_add_output(&aio->base);
2082 	else
2083 		cras_iodev_list_add_input(&aio->base);
2084 	return &aio->base;
2085 
2086 cleanup_iodev:
2087 	free_alsa_iodev_resources(aio);
2088 	free(aio);
2089 	return NULL;
2090 }
2091 
alsa_iodev_legacy_complete_init(struct cras_iodev * iodev)2092 int alsa_iodev_legacy_complete_init(struct cras_iodev *iodev)
2093 {
2094 	struct alsa_io *aio = (struct alsa_io *)iodev;
2095 	const char *dev_name;
2096 	const char *dev_id;
2097 	enum CRAS_STREAM_DIRECTION direction;
2098 	int err;
2099 	int is_first;
2100 	struct cras_alsa_mixer *mixer;
2101 
2102 	if (!aio)
2103 		return -EINVAL;
2104 	direction = iodev->direction;
2105 	dev_name = aio->dev_name;
2106 	dev_id = aio->dev_id;
2107 	is_first = aio->is_first;
2108 	mixer = aio->mixer;
2109 
2110 	/* Create output nodes for mixer controls, such as Headphone
2111 	 * and Speaker, only for the first device. */
2112 	if (direction == CRAS_STREAM_OUTPUT && is_first)
2113 		cras_alsa_mixer_list_outputs(mixer,
2114 				new_output_by_mixer_control, aio);
2115 	else if (direction == CRAS_STREAM_INPUT && is_first)
2116 		cras_alsa_mixer_list_inputs(mixer,
2117 				new_input_by_mixer_control, aio);
2118 
2119 	err = cras_alsa_jack_list_find_jacks_by_name_matching(aio->jack_list);
2120 	if (err)
2121 		return err;
2122 
2123 	/* Create nodes for jacks that aren't associated with an
2124 	 * already existing node. Get an initial read of the jacks for
2125 	 * this device. */
2126 	cras_alsa_jack_list_report(aio->jack_list);
2127 
2128 	/* Make a default node if there is still no node for this
2129 	 * device, or we still don't have the "Speaker"/"Internal Mic"
2130 	 * node for the first internal device. Note that the default
2131 	 * node creation can be supressed by UCM flags for platforms
2132 	 * which really don't have an internal device. */
2133 	if ((direction == CRAS_STREAM_OUTPUT) &&
2134 			!no_create_default_output_node(aio)) {
2135 		if (first_internal_device(aio) &&
2136 		    !has_node(aio, INTERNAL_SPEAKER) &&
2137 		    !has_node(aio, HDMI)) {
2138 			if (strstr(aio->base.info.name, HDMI))
2139 				new_output(aio, NULL, HDMI);
2140 			else
2141 				new_output(aio, NULL, INTERNAL_SPEAKER);
2142 		} else if (!aio->base.nodes) {
2143 			new_output(aio, NULL, DEFAULT);
2144 		}
2145 	} else if ((direction == CRAS_STREAM_INPUT) &&
2146 			!no_create_default_input_node(aio)) {
2147 		if (first_internal_device(aio) &&
2148 		    !has_node(aio, INTERNAL_MICROPHONE))
2149 			new_input(aio, NULL, INTERNAL_MICROPHONE);
2150 		else if (strstr(dev_name, KEYBOARD_MIC))
2151 			new_input(aio, NULL, KEYBOARD_MIC);
2152 		else if (dev_id && strstr(dev_id, HOTWORD_DEV))
2153 			new_input(aio, NULL, HOTWORD_DEV);
2154 		else if (!aio->base.nodes)
2155 			new_input(aio, NULL, DEFAULT);
2156 	}
2157 
2158 	/* Build software volume scalers. */
2159 	if (direction == CRAS_STREAM_OUTPUT)
2160 		build_softvol_scalers(aio);
2161 
2162 	/* Set the active node as the best node we have now. */
2163 	alsa_iodev_set_active_node(&aio->base,
2164 				   first_plugged_node(&aio->base),
2165 				   0);
2166 
2167 	/* Set plugged for the first USB device per card when it appears if
2168 	 * there is no jack reporting plug status. */
2169 	if (aio->card_type == ALSA_CARD_TYPE_USB && is_first &&
2170 			!get_jack_from_node(iodev->active_node))
2171 		cras_iodev_set_node_attr(iodev->active_node,
2172 					 IONODE_ATTR_PLUGGED, 1);
2173 
2174 	set_default_hotword_model(iodev);
2175 
2176 	return 0;
2177 }
2178 
alsa_iodev_ucm_add_nodes_and_jacks(struct cras_iodev * iodev,struct ucm_section * section)2179 int alsa_iodev_ucm_add_nodes_and_jacks(struct cras_iodev *iodev,
2180 				       struct ucm_section *section)
2181 {
2182 	struct alsa_io *aio = (struct alsa_io *)iodev;
2183 	struct mixer_control *control;
2184 	struct alsa_input_node *input_node = NULL;
2185 	struct cras_alsa_jack *jack;
2186 	struct alsa_output_node *output_node = NULL;
2187 	int rc;
2188 
2189 	if (!aio || !section)
2190 		return -EINVAL;
2191 	if ((uint32_t)section->dev_idx != aio->device_index)
2192 		return -EINVAL;
2193 
2194 	/* This iodev is fully specified. Avoid automatic node creation. */
2195 	aio->fully_specified = 1;
2196 
2197 	/* Check here in case the DmaPeriodMicrosecs flag has only been
2198 	 * specified on one of many device entries with the same PCM. */
2199 	if (!aio->dma_period_set_microsecs)
2200 		aio->dma_period_set_microsecs =
2201 			ucm_get_dma_period_for_dev(aio->ucm, section->name);
2202 
2203 	/* Create a node matching this section. If there is a matching
2204 	 * control use that, otherwise make a node without a control. */
2205 	control = cras_alsa_mixer_get_control_for_section(aio->mixer, section);
2206 	if (iodev->direction == CRAS_STREAM_OUTPUT) {
2207 		output_node = new_output(aio, control, section->name);
2208 		if (!output_node)
2209 			return -ENOMEM;
2210 	} else if (iodev->direction == CRAS_STREAM_INPUT) {
2211 		input_node = new_input(aio, control, section->name);
2212 		if (!input_node)
2213 			return -ENOMEM;
2214 	}
2215 
2216 	/* Find any jack controls for this device. */
2217 	rc = cras_alsa_jack_list_add_jack_for_section(
2218 					aio->jack_list, section, &jack);
2219 	if (rc)
2220 		return rc;
2221 
2222 	/* Associated the jack with the node. */
2223 	if (jack) {
2224 		if (output_node) {
2225 			output_node->jack = jack;
2226 			if (!output_node->volume_curve)
2227 				output_node->volume_curve =
2228 					create_volume_curve_for_jack(
2229 						aio->config, jack);
2230 		} else if (input_node) {
2231 			input_node->jack = jack;
2232 		}
2233 	}
2234 	return 0;
2235 }
2236 
alsa_iodev_ucm_complete_init(struct cras_iodev * iodev)2237 void alsa_iodev_ucm_complete_init(struct cras_iodev *iodev)
2238 {
2239 	struct alsa_io *aio = (struct alsa_io *)iodev;
2240 
2241 	if (!iodev)
2242 		return;
2243 
2244 	/* Get an initial read of the jacks for this device. */
2245 	cras_alsa_jack_list_report(aio->jack_list);
2246 
2247 	/* Build software volume scaler. */
2248 	if (iodev->direction == CRAS_STREAM_OUTPUT)
2249 		build_softvol_scalers(aio);
2250 
2251 	/* Set the active node as the best node we have now. */
2252 	alsa_iodev_set_active_node(&aio->base,
2253 				   first_plugged_node(&aio->base),
2254 				   0);
2255 
2256 	/* Set plugged for the first USB device per card when it appears if
2257 	 * there is no jack reporting plug status. */
2258 	if (aio->card_type == ALSA_CARD_TYPE_USB && aio->is_first &&
2259 			!get_jack_from_node(iodev->active_node))
2260 		cras_iodev_set_node_attr(iodev->active_node,
2261 					 IONODE_ATTR_PLUGGED, 1);
2262 
2263 	set_default_hotword_model(iodev);
2264 }
2265 
alsa_iodev_destroy(struct cras_iodev * iodev)2266 void alsa_iodev_destroy(struct cras_iodev *iodev)
2267 {
2268 	struct alsa_io *aio = (struct alsa_io *)iodev;
2269 	int rc;
2270 
2271 	cras_alsa_jack_list_destroy(aio->jack_list);
2272 	if (iodev->direction == CRAS_STREAM_INPUT)
2273 		rc = cras_iodev_list_rm_input(iodev);
2274 	else
2275 		rc = cras_iodev_list_rm_output(iodev);
2276 
2277 	if (rc == -EBUSY) {
2278 		syslog(LOG_ERR, "Failed to remove iodev %s", iodev->info.name);
2279 		return;
2280 	}
2281 
2282 	/* Free resources when device successfully removed. */
2283 	free_alsa_iodev_resources(aio);
2284 	cras_volume_curve_destroy(aio->default_volume_curve);
2285 	free(iodev);
2286 }
2287 
alsa_iodev_index(struct cras_iodev * iodev)2288 unsigned alsa_iodev_index(struct cras_iodev *iodev)
2289 {
2290 	struct alsa_io *aio = (struct alsa_io *)iodev;
2291 	return aio->device_index;
2292 }
2293 
alsa_iodev_has_hctl_jacks(struct cras_iodev * iodev)2294 int alsa_iodev_has_hctl_jacks(struct cras_iodev *iodev)
2295 {
2296 	struct alsa_io *aio = (struct alsa_io *)iodev;
2297 	return cras_alsa_jack_list_has_hctl_jacks(aio->jack_list);
2298 }
2299 
alsa_iodev_unmute_node(struct alsa_io * aio,struct cras_ionode * ionode)2300 static void alsa_iodev_unmute_node(struct alsa_io *aio,
2301 				   struct cras_ionode *ionode)
2302 {
2303 	struct alsa_output_node *active = (struct alsa_output_node *)ionode;
2304 	struct mixer_control *mixer = active->mixer_output;
2305 	struct alsa_output_node *output;
2306 	struct cras_ionode *node;
2307 
2308 	/* If this node is associated with mixer output, unmute the
2309 	 * active mixer output and mute all others, otherwise just set
2310 	 * the node as active and set the volume curve. */
2311 	if (mixer) {
2312 		set_alsa_mute_control(aio, 1);
2313 		/* Unmute the active mixer output, mute all others. */
2314 		DL_FOREACH(aio->base.nodes, node) {
2315 			output = (struct alsa_output_node *)node;
2316 			if (output->mixer_output)
2317 				cras_alsa_mixer_set_output_active_state(
2318 					output->mixer_output, node == ionode);
2319 		}
2320 	}
2321 }
2322 
alsa_iodev_set_active_node(struct cras_iodev * iodev,struct cras_ionode * ionode,unsigned dev_enabled)2323 static int alsa_iodev_set_active_node(struct cras_iodev *iodev,
2324 				      struct cras_ionode *ionode,
2325 				      unsigned dev_enabled)
2326 {
2327 	struct alsa_io *aio = (struct alsa_io *)iodev;
2328 
2329 	if (iodev->active_node == ionode) {
2330 		enable_active_ucm(aio, dev_enabled);
2331 		init_device_settings(aio);
2332 		return 0;
2333 	}
2334 
2335 	/* Disable jack ucm before switching node. */
2336 	enable_active_ucm(aio, 0);
2337 	if (dev_enabled && (iodev->direction == CRAS_STREAM_OUTPUT))
2338 		alsa_iodev_unmute_node(aio, ionode);
2339 
2340 	cras_iodev_set_active_node(iodev, ionode);
2341 	aio->base.dsp_name = get_active_dsp_name(aio);
2342 	cras_iodev_update_dsp(iodev);
2343 	enable_active_ucm(aio, dev_enabled);
2344 	/* Setting the volume will also unmute if the system isn't muted. */
2345 	init_device_settings(aio);
2346 	return 0;
2347 }
2348