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