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