Home | History | Annotate | Download | only in server
      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 <syslog.h>
      7 
      8 #include "audio_thread.h"
      9 #include "cras_empty_iodev.h"
     10 #include "cras_iodev.h"
     11 #include "cras_iodev_info.h"
     12 #include "cras_iodev_list.h"
     13 #include "cras_loopback_iodev.h"
     14 #include "cras_observer.h"
     15 #include "cras_rstream.h"
     16 #include "cras_server.h"
     17 #include "cras_tm.h"
     18 #include "cras_types.h"
     19 #include "cras_system_state.h"
     20 #include "server_stream.h"
     21 #include "stream_list.h"
     22 #include "test_iodev.h"
     23 #include "utlist.h"
     24 
     25 const struct timespec idle_timeout_interval = {
     26 	.tv_sec = 10,
     27 	.tv_nsec = 0
     28 };
     29 
     30 /* Linked list of available devices. */
     31 struct iodev_list {
     32 	struct cras_iodev *iodevs;
     33 	size_t size;
     34 };
     35 
     36 /* List of enabled input/output devices.
     37  *    dev - The device.
     38  *    init_timer - Timer for a delayed call to init this iodev.
     39  */
     40 struct enabled_dev {
     41 	struct cras_iodev *dev;
     42 	struct enabled_dev *prev, *next;
     43 };
     44 
     45 struct dev_init_retry {
     46 	int dev_idx;
     47 	struct cras_timer *init_timer;
     48 	struct dev_init_retry *next, *prev;
     49 };
     50 
     51 struct device_enabled_cb {
     52 	device_enabled_callback_t enabled_cb;
     53 	device_disabled_callback_t disabled_cb;
     54 	void *cb_data;
     55 	struct device_enabled_cb *next, *prev;
     56 };
     57 
     58 /* Lists for devs[CRAS_STREAM_INPUT] and devs[CRAS_STREAM_OUTPUT]. */
     59 static struct iodev_list devs[CRAS_NUM_DIRECTIONS];
     60 /* The observer client iodev_list used to listen on various events. */
     61 static struct cras_observer_client *list_observer;
     62 /* Keep a list of enabled inputs and outputs. */
     63 static struct enabled_dev *enabled_devs[CRAS_NUM_DIRECTIONS];
     64 /* Keep an empty device per direction. */
     65 static struct cras_iodev *fallback_devs[CRAS_NUM_DIRECTIONS];
     66 /* Special empty device for hotword streams. */
     67 static struct cras_iodev *empty_hotword_dev;
     68 /* Loopback devices. */
     69 static struct cras_iodev *loopdev_post_mix;
     70 static struct cras_iodev *loopdev_post_dsp;
     71 /* List of pending device init retries. */
     72 static struct dev_init_retry *init_retries;
     73 
     74 /* Keep a constantly increasing index for iodevs. Index 0 is reserved
     75  * to mean "no device". */
     76 static uint32_t next_iodev_idx = MAX_SPECIAL_DEVICE_IDX;
     77 
     78 /* Call when a device is enabled or disabled. */
     79 struct device_enabled_cb *device_enable_cbs;
     80 
     81 /* Thread that handles audio input and output. */
     82 static struct audio_thread *audio_thread;
     83 /* List of all streams. */
     84 static struct stream_list *stream_list;
     85 /* Idle device timer. */
     86 static struct cras_timer *idle_timer;
     87 /* Flag to indicate that the stream list is disconnected from audio thread. */
     88 static int stream_list_suspended = 0;
     89 /* If init device failed, retry after 1 second. */
     90 static const unsigned int INIT_DEV_DELAY_MS = 1000;
     91 /* Flag to indicate that hotword streams are suspended. */
     92 static int hotword_suspended = 0;
     93 
     94 static void idle_dev_check(struct cras_timer *timer, void *data);
     95 
     96 static struct cras_iodev *find_dev(size_t dev_index)
     97 {
     98 	struct cras_iodev *dev;
     99 
    100 	DL_FOREACH(devs[CRAS_STREAM_OUTPUT].iodevs, dev)
    101 		if (dev->info.idx == dev_index)
    102 			return dev;
    103 
    104 	DL_FOREACH(devs[CRAS_STREAM_INPUT].iodevs, dev)
    105 		if (dev->info.idx == dev_index)
    106 			return dev;
    107 
    108 	return NULL;
    109 }
    110 
    111 static struct cras_ionode *find_node(cras_node_id_t id)
    112 {
    113 	struct cras_iodev *dev;
    114 	struct cras_ionode *node;
    115 	uint32_t dev_index, node_index;
    116 
    117 	dev_index = dev_index_of(id);
    118 	node_index = node_index_of(id);
    119 
    120 	dev = find_dev(dev_index);
    121 	if (!dev)
    122 		return NULL;
    123 
    124 	DL_FOREACH(dev->nodes, node)
    125 		if (node->idx == node_index)
    126 			return node;
    127 
    128 	return NULL;
    129 }
    130 
    131 /* Adds a device to the list.  Used from add_input and add_output. */
    132 static int add_dev_to_list(struct cras_iodev *dev)
    133 {
    134 	struct cras_iodev *tmp;
    135 	uint32_t new_idx;
    136 	struct iodev_list *list = &devs[dev->direction];
    137 
    138 	DL_FOREACH(list->iodevs, tmp)
    139 		if (tmp == dev)
    140 			return -EEXIST;
    141 
    142 	dev->format = NULL;
    143 	dev->ext_format = NULL;
    144 	dev->prev = dev->next = NULL;
    145 
    146 	/* Move to the next index and make sure it isn't taken. */
    147 	new_idx = next_iodev_idx;
    148 	while (1) {
    149 		if (new_idx < MAX_SPECIAL_DEVICE_IDX)
    150 			new_idx = MAX_SPECIAL_DEVICE_IDX;
    151 		DL_SEARCH_SCALAR(list->iodevs, tmp, info.idx, new_idx);
    152 		if (tmp == NULL)
    153 			break;
    154 		new_idx++;
    155 	}
    156 	dev->info.idx = new_idx;
    157 	next_iodev_idx = new_idx + 1;
    158 	list->size++;
    159 
    160 	syslog(LOG_INFO, "Adding %s dev at index %u.",
    161 	       dev->direction == CRAS_STREAM_OUTPUT ? "output" : "input",
    162 	       dev->info.idx);
    163 	DL_PREPEND(list->iodevs, dev);
    164 
    165 	cras_iodev_list_update_device_list();
    166 	return 0;
    167 }
    168 
    169 /* Removes a device to the list.  Used from rm_input and rm_output. */
    170 static int rm_dev_from_list(struct cras_iodev *dev)
    171 {
    172 	struct cras_iodev *tmp;
    173 
    174 	DL_FOREACH(devs[dev->direction].iodevs, tmp)
    175 		if (tmp == dev) {
    176 			if (cras_iodev_is_open(dev))
    177 				return -EBUSY;
    178 			DL_DELETE(devs[dev->direction].iodevs, dev);
    179 			devs[dev->direction].size--;
    180 			return 0;
    181 		}
    182 
    183 	/* Device not found. */
    184 	return -EINVAL;
    185 }
    186 
    187 /* Fills a dev_info array from the iodev_list. */
    188 static void fill_dev_list(struct iodev_list *list,
    189 			  struct cras_iodev_info *dev_info,
    190 			  size_t out_size)
    191 {
    192 	int i = 0;
    193 	struct cras_iodev *tmp;
    194 	DL_FOREACH(list->iodevs, tmp) {
    195 		memcpy(&dev_info[i], &tmp->info, sizeof(dev_info[0]));
    196 		i++;
    197 		if (i == out_size)
    198 			return;
    199 	}
    200 }
    201 
    202 static const char *node_type_to_str(struct cras_ionode *node)
    203 {
    204 	switch (node->type) {
    205 	case CRAS_NODE_TYPE_INTERNAL_SPEAKER:
    206 		return "INTERNAL_SPEAKER";
    207 	case CRAS_NODE_TYPE_HEADPHONE:
    208 		return "HEADPHONE";
    209 	case CRAS_NODE_TYPE_HDMI:
    210 		return "HDMI";
    211 	case CRAS_NODE_TYPE_HAPTIC:
    212 		return "HAPTIC";
    213 	case CRAS_NODE_TYPE_MIC:
    214 		switch (node->position) {
    215 		case NODE_POSITION_INTERNAL:
    216 			return "INTERNAL_MIC";
    217 		case NODE_POSITION_FRONT:
    218 			return "FRONT_MIC";
    219 		case NODE_POSITION_REAR:
    220 			return "REAR_MIC";
    221 		case NODE_POSITION_KEYBOARD:
    222 			return "KEYBOARD_MIC";
    223 		case NODE_POSITION_EXTERNAL:
    224 		default:
    225 			return "MIC";
    226 		}
    227 	case CRAS_NODE_TYPE_HOTWORD:
    228 		return "HOTWORD";
    229 	case CRAS_NODE_TYPE_LINEOUT:
    230 		return "LINEOUT";
    231 	case CRAS_NODE_TYPE_POST_MIX_PRE_DSP:
    232 		return "POST_MIX_LOOPBACK";
    233 	case CRAS_NODE_TYPE_POST_DSP:
    234 		return "POST_DSP_LOOPBACK";
    235 	case CRAS_NODE_TYPE_USB:
    236 		return "USB";
    237 	case CRAS_NODE_TYPE_BLUETOOTH:
    238 		return "BLUETOOTH";
    239 	case CRAS_NODE_TYPE_UNKNOWN:
    240 	default:
    241 		return "UNKNOWN";
    242 	}
    243 }
    244 
    245 /* Fills an ionode_info array from the iodev_list. */
    246 static int fill_node_list(struct iodev_list *list,
    247 			  struct cras_ionode_info *node_info,
    248 			  size_t out_size)
    249 {
    250 	int i = 0;
    251 	struct cras_iodev *dev;
    252 	struct cras_ionode *node;
    253 	DL_FOREACH(list->iodevs, dev) {
    254 		DL_FOREACH(dev->nodes, node) {
    255 			node_info->iodev_idx = dev->info.idx;
    256 			node_info->ionode_idx = node->idx;
    257 			node_info->plugged = node->plugged;
    258 			node_info->plugged_time.tv_sec =
    259 				node->plugged_time.tv_sec;
    260 			node_info->plugged_time.tv_usec =
    261 				node->plugged_time.tv_usec;
    262 			node_info->active = dev->is_enabled &&
    263 					    (dev->active_node == node);
    264 			node_info->volume = node->volume;
    265 			node_info->capture_gain = node->capture_gain;
    266 			node_info->left_right_swapped = node->left_right_swapped;
    267 			node_info->stable_id = node->stable_id;
    268 			node_info->stable_id_new = node->stable_id_new;
    269 			strcpy(node_info->mic_positions, node->mic_positions);
    270 			strcpy(node_info->name, node->name);
    271 			strcpy(node_info->active_hotword_model,
    272 				node->active_hotword_model);
    273 			snprintf(node_info->type, sizeof(node_info->type), "%s",
    274 				node_type_to_str(node));
    275 			node_info->type_enum = node->type;
    276 			node_info++;
    277 			i++;
    278 			if (i == out_size)
    279 				return i;
    280 		}
    281 	}
    282 	return i;
    283 }
    284 
    285 /* Copies the info for each device in the list to "list_out". */
    286 static int get_dev_list(struct iodev_list *list,
    287 			struct cras_iodev_info **list_out)
    288 {
    289 	struct cras_iodev_info *dev_info;
    290 
    291 	if (!list_out)
    292 		return list->size;
    293 
    294 	*list_out = NULL;
    295 	if (list->size == 0)
    296 		return 0;
    297 
    298 	dev_info = malloc(sizeof(*list_out[0]) * list->size);
    299 	if (dev_info == NULL)
    300 		return -ENOMEM;
    301 
    302 	fill_dev_list(list, dev_info, list->size);
    303 
    304 	*list_out = dev_info;
    305 	return list->size;
    306 }
    307 
    308 /* Called when the system volume changes.  Pass the current volume setting to
    309  * the default output if it is active. */
    310 static void sys_vol_change(void *context, int32_t volume)
    311 {
    312 	struct cras_iodev *dev;
    313 
    314 	DL_FOREACH(devs[CRAS_STREAM_OUTPUT].iodevs, dev) {
    315 		if (dev->set_volume && cras_iodev_is_open(dev))
    316 			dev->set_volume(dev);
    317 	}
    318 }
    319 
    320 /*
    321  * Checks if a device should start ramping for mute/unmute change.
    322  * Device must meet all the conditions:
    323  *
    324  * - Device is enabled in iodev_list.
    325  * - Device has ramp support.
    326  * - Device is in normal run state, that is, it must be running with valid
    327  *   streams.
    328  * - Device volume, which considers both system volume and adjusted active
    329  *   node volume, is not zero. If device volume is zero, all the samples are
    330  *   suppressed to zero and there is no need to ramp.
    331  */
    332 static int device_should_start_ramp_for_mute(const struct cras_iodev *dev)
    333 {
    334 	return (cras_iodev_list_dev_is_enabled(dev) && dev->ramp &&
    335 		cras_iodev_state(dev) == CRAS_IODEV_STATE_NORMAL_RUN &&
    336 		!cras_iodev_is_zero_volume(dev));
    337 }
    338 
    339 /* Called when the system mute state changes.  Pass the current mute setting
    340  * to the default output if it is active. */
    341 static void sys_mute_change(void *context, int muted, int user_muted,
    342 			    int mute_locked)
    343 {
    344 	struct cras_iodev *dev;
    345 	int should_mute = muted || user_muted;
    346 
    347 	DL_FOREACH(devs[CRAS_STREAM_OUTPUT].iodevs, dev) {
    348 		if (device_should_start_ramp_for_mute(dev)) {
    349 			/*
    350 			 * Start ramping in audio thread and set mute/unmute
    351 			 * state on device. This should only be done when
    352 			 * device is running with valid streams.
    353 			 *
    354 			 * 1. Mute -> Unmute: Set device unmute state after
    355 			 *                    ramping is started.
    356 			 * 2. Unmute -> Mute: Set device mute state after
    357 			 *                    ramping is done.
    358 			 *
    359 			 * The above transition will be handled by
    360 			 * cras_iodev_ramp_start.
    361 			 */
    362 			audio_thread_dev_start_ramp(
    363 					audio_thread,
    364 					dev,
    365 					(should_mute ?
    366 					 CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE :
    367 					 CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE));
    368 
    369 		} else {
    370 			/* For device without ramp, just set its mute state. */
    371 			cras_iodev_set_mute(dev);
    372 		}
    373 	}
    374 }
    375 
    376 static void remove_all_streams_from_dev(struct cras_iodev *dev)
    377 {
    378 	struct cras_rstream *rstream;
    379 
    380 	audio_thread_rm_open_dev(audio_thread, dev);
    381 
    382 	DL_FOREACH(stream_list_get(stream_list), rstream) {
    383 		if (rstream->apm_list == NULL)
    384 			continue;
    385 		cras_apm_list_remove(rstream->apm_list, dev);
    386 	}
    387 }
    388 
    389 /*
    390  * If output dev has an echo reference dev associated, add a server
    391  * stream to read audio data from it so APM can analyze.
    392  */
    393 static void possibly_enable_echo_reference(struct cras_iodev *dev)
    394 {
    395 	if (dev->direction != CRAS_STREAM_OUTPUT)
    396 		return;
    397 
    398 	if (dev->echo_reference_dev == NULL)
    399 		return;
    400 
    401 	server_stream_create(stream_list, dev->echo_reference_dev->info.idx);
    402 }
    403 
    404 /*
    405  * If output dev has an echo reference dev associated, check if there
    406  * is server stream opened for it and remove it.
    407  */
    408 static void possibly_disable_echo_reference(struct cras_iodev *dev)
    409 {
    410 	if (dev->echo_reference_dev == NULL)
    411 		return;
    412 
    413 	server_stream_destroy(stream_list, dev->echo_reference_dev->info.idx);
    414 }
    415 
    416 /*
    417  * Close dev if it's opened, without the extra call to idle_dev_check.
    418  * This is useful for closing a dev inside idle_dev_check function to
    419  * avoid infinite recursive call.
    420  *
    421  * Returns:
    422  *    -EINVAL if device was not opened, otherwise return 0.
    423  */
    424 static int close_dev_without_idle_check(struct cras_iodev *dev)
    425 {
    426 	if (!cras_iodev_is_open(dev))
    427 	       return -EINVAL;
    428 	if (cras_iodev_has_pinned_stream(dev))
    429 		syslog(LOG_ERR, "Closing device with pinned streams.");
    430 
    431 	remove_all_streams_from_dev(dev);
    432 	dev->idle_timeout.tv_sec = 0;
    433 	cras_iodev_close(dev);
    434 	possibly_disable_echo_reference(dev);
    435 	return 0;
    436 }
    437 
    438 static void close_dev(struct cras_iodev *dev)
    439 {
    440 	if (close_dev_without_idle_check(dev))
    441 		return;
    442 
    443 	if (idle_timer)
    444 		cras_tm_cancel_timer(cras_system_state_get_tm(), idle_timer);
    445 	idle_dev_check(NULL, NULL);
    446 }
    447 
    448 static void idle_dev_check(struct cras_timer *timer, void *data)
    449 {
    450 	struct enabled_dev *edev;
    451 	struct timespec now;
    452 	struct timespec min_idle_expiration;
    453 	unsigned int num_idle_devs = 0;
    454 	unsigned int min_idle_timeout_ms;
    455 
    456 	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
    457 	min_idle_expiration.tv_sec = 0;
    458 	min_idle_expiration.tv_nsec = 0;
    459 
    460 	DL_FOREACH(enabled_devs[CRAS_STREAM_OUTPUT], edev) {
    461 		if (edev->dev->idle_timeout.tv_sec == 0)
    462 			continue;
    463 		if (timespec_after(&now, &edev->dev->idle_timeout)) {
    464 			close_dev_without_idle_check(edev->dev);
    465 			continue;
    466 		}
    467 		num_idle_devs++;
    468 		if (min_idle_expiration.tv_sec == 0 ||
    469 		    timespec_after(&min_idle_expiration,
    470 				   &edev->dev->idle_timeout))
    471 			min_idle_expiration = edev->dev->idle_timeout;
    472 	}
    473 
    474 	idle_timer = NULL;
    475 	if (!num_idle_devs)
    476 		return;
    477 	if (timespec_after(&now, &min_idle_expiration)) {
    478 		min_idle_timeout_ms = 0;
    479 	} else {
    480 		struct timespec timeout;
    481 		subtract_timespecs(&min_idle_expiration, &now, &timeout);
    482 		min_idle_timeout_ms = timespec_to_ms(&timeout);
    483 	}
    484 	/* Wake up when it is time to close the next idle device.  Sleep for a
    485 	 * minimum of 10 milliseconds. */
    486 	idle_timer = cras_tm_create_timer(cras_system_state_get_tm(),
    487 					  MAX(min_idle_timeout_ms, 10),
    488 					  idle_dev_check, NULL);
    489 }
    490 
    491 /*
    492  * Cancel pending init tries. Called at device initialization or when device
    493  * is disabled.
    494  */
    495 static void cancel_pending_init_retries(unsigned int dev_idx)
    496 {
    497 	struct dev_init_retry *retry;
    498 
    499 	DL_FOREACH(init_retries, retry) {
    500 		if (retry->dev_idx != dev_idx)
    501 			continue;
    502 		cras_tm_cancel_timer(cras_system_state_get_tm(),
    503 				     retry->init_timer);
    504 		DL_DELETE(init_retries, retry);
    505 		free(retry);
    506 	}
    507 }
    508 
    509 /* Open the device potentially filling the output with a pre buffer. */
    510 static int init_device(struct cras_iodev *dev,
    511 		       struct cras_rstream *rstream)
    512 {
    513 	int rc;
    514 
    515 	dev->idle_timeout.tv_sec = 0;
    516 
    517 	if (cras_iodev_is_open(dev))
    518 		return 0;
    519 	cancel_pending_init_retries(dev->info.idx);
    520 
    521 	rc = cras_iodev_open(dev, rstream->cb_threshold, &rstream->format);
    522 	if (rc)
    523 		return rc;
    524 
    525 	rc = audio_thread_add_open_dev(audio_thread, dev);
    526 	if (rc)
    527 		cras_iodev_close(dev);
    528 
    529 	possibly_enable_echo_reference(dev);
    530 
    531 	return rc;
    532 }
    533 
    534 static void suspend_devs()
    535 {
    536 	struct enabled_dev *edev;
    537 	struct cras_rstream *rstream;
    538 
    539 	DL_FOREACH(stream_list_get(stream_list), rstream) {
    540 		if (rstream->is_pinned) {
    541 			struct cras_iodev *dev;
    542 
    543 			if ((rstream->flags & HOTWORD_STREAM) == HOTWORD_STREAM)
    544 				continue;
    545 
    546 			dev = find_dev(rstream->pinned_dev_idx);
    547 			if (dev) {
    548 				audio_thread_disconnect_stream(audio_thread,
    549 							       rstream, dev);
    550 				if (!cras_iodev_list_dev_is_enabled(dev))
    551 					close_dev(dev);
    552 			}
    553 		} else {
    554 			audio_thread_disconnect_stream(audio_thread, rstream,
    555 						       NULL);
    556 		}
    557 	}
    558 	stream_list_suspended = 1;
    559 
    560 	DL_FOREACH(enabled_devs[CRAS_STREAM_OUTPUT], edev) {
    561 		close_dev(edev->dev);
    562 	}
    563 	DL_FOREACH(enabled_devs[CRAS_STREAM_INPUT], edev) {
    564 		close_dev(edev->dev);
    565 	}
    566 }
    567 
    568 static int stream_added_cb(struct cras_rstream *rstream);
    569 
    570 static void resume_devs()
    571 {
    572 	struct cras_rstream *rstream;
    573 
    574 	stream_list_suspended = 0;
    575 	DL_FOREACH(stream_list_get(stream_list), rstream) {
    576 		if ((rstream->flags & HOTWORD_STREAM) == HOTWORD_STREAM)
    577 			continue;
    578 		stream_added_cb(rstream);
    579 	}
    580 }
    581 
    582 /* Called when the system audio is suspended or resumed. */
    583 void sys_suspend_change(void *arg, int suspended)
    584 {
    585 	if (suspended)
    586 		suspend_devs();
    587 	else
    588 		resume_devs();
    589 }
    590 
    591 /* Called when the system capture gain changes.  Pass the current capture_gain
    592  * setting to the default input if it is active. */
    593 void sys_cap_gain_change(void *context, int32_t gain)
    594 {
    595 	struct cras_iodev *dev;
    596 
    597 	DL_FOREACH(devs[CRAS_STREAM_INPUT].iodevs, dev) {
    598 		if (dev->set_capture_gain && cras_iodev_is_open(dev))
    599 			dev->set_capture_gain(dev);
    600 	}
    601 }
    602 
    603 /* Called when the system capture mute state changes.  Pass the current capture
    604  * mute setting to the default input if it is active. */
    605 static void sys_cap_mute_change(void *context, int muted, int mute_locked)
    606 {
    607 	struct cras_iodev *dev;
    608 
    609 	DL_FOREACH(devs[CRAS_STREAM_INPUT].iodevs, dev) {
    610 		if (dev->set_capture_mute && cras_iodev_is_open(dev))
    611 			dev->set_capture_mute(dev);
    612 	}
    613 }
    614 
    615 static int disable_device(struct enabled_dev *edev, bool force);
    616 static int enable_device(struct cras_iodev *dev);
    617 
    618 static void possibly_disable_fallback(enum CRAS_STREAM_DIRECTION dir)
    619 {
    620 	struct enabled_dev *edev;
    621 
    622 	DL_FOREACH(enabled_devs[dir], edev) {
    623 		if (edev->dev == fallback_devs[dir])
    624 			disable_device(edev, false);
    625 	}
    626 }
    627 
    628 static void possibly_enable_fallback(enum CRAS_STREAM_DIRECTION dir)
    629 {
    630 	if (fallback_devs[dir] == NULL)
    631 		return;
    632 	if (!cras_iodev_list_dev_is_enabled(fallback_devs[dir]))
    633 		enable_device(fallback_devs[dir]);
    634 }
    635 
    636 /*
    637  * Adds stream to one or more open iodevs. If the stream has processing effect
    638  * turned on, create new APM instance and add to the list. This makes sure the
    639  * time consuming APM creation happens in main thread.
    640  */
    641 static int add_stream_to_open_devs(struct cras_rstream *stream,
    642 				    struct cras_iodev **iodevs,
    643 				    unsigned int num_iodevs)
    644 {
    645 	int i;
    646 	if (stream->apm_list) {
    647 		for (i = 0; i < num_iodevs; i++)
    648 			cras_apm_list_add(stream->apm_list,
    649 					  iodevs[i],
    650 					  iodevs[i]->ext_format);
    651 	}
    652 	return audio_thread_add_stream(audio_thread,
    653 				       stream, iodevs, num_iodevs);
    654 }
    655 
    656 static int init_and_attach_streams(struct cras_iodev *dev)
    657 {
    658 	int rc;
    659 	enum CRAS_STREAM_DIRECTION dir = dev->direction;
    660 	struct cras_rstream *stream;
    661 	int dev_enabled = cras_iodev_list_dev_is_enabled(dev);
    662 
    663 	/* If called after suspend, for example bluetooth
    664 	 * profile switching, don't add back the stream list. */
    665 	if (stream_list_suspended)
    666 		return 0;
    667 
    668 	/* If there are active streams to attach to this device,
    669 	 * open it. */
    670 	DL_FOREACH(stream_list_get(stream_list), stream) {
    671 		if (stream->direction != dir)
    672 			continue;
    673 		/*
    674 		 * Don't attach this stream if (1) this stream pins to a
    675 		 * different device, or (2) this is a normal stream, but
    676 		 * device is not enabled.
    677 		 */
    678 		if(stream->is_pinned) {
    679 		   if (stream->pinned_dev_idx != dev->info.idx)
    680 			continue;
    681 		} else if (!dev_enabled) {
    682 			continue;
    683 		}
    684 
    685 		rc = init_device(dev, stream);
    686 		if (rc) {
    687 			syslog(LOG_ERR, "Enable %s failed, rc = %d",
    688 			       dev->info.name, rc);
    689 			return rc;
    690 		}
    691 		add_stream_to_open_devs(stream, &dev, 1);
    692 	}
    693 	return 0;
    694 }
    695 
    696 static void init_device_cb(struct cras_timer *timer, void *arg)
    697 {
    698 	int rc;
    699 	struct dev_init_retry *retry = (struct dev_init_retry *)arg;
    700 	struct cras_iodev *dev = find_dev(retry->dev_idx);
    701 
    702 	/*
    703 	 * First of all, remove retry record to avoid confusion to the
    704 	 * actual device init work.
    705 	 */
    706 	DL_DELETE(init_retries, retry);
    707 	free(retry);
    708 
    709 	if (cras_iodev_is_open(dev))
    710 		return;
    711 
    712 	rc = init_and_attach_streams(dev);
    713 	if (rc < 0)
    714 		syslog(LOG_ERR, "Init device retry failed");
    715 	else
    716 		possibly_disable_fallback(dev->direction);
    717 }
    718 
    719 static int schedule_init_device_retry(struct cras_iodev *dev)
    720 {
    721 	struct dev_init_retry *retry;
    722 	struct cras_tm *tm = cras_system_state_get_tm();
    723 
    724 	retry = (struct dev_init_retry *)calloc(1, sizeof(*retry));
    725 	if (!retry)
    726 		return -ENOMEM;
    727 
    728 	retry->dev_idx = dev->info.idx;
    729 	retry->init_timer = cras_tm_create_timer(
    730 			tm, INIT_DEV_DELAY_MS, init_device_cb, retry);
    731 	DL_APPEND(init_retries, retry);
    732 	return 0;
    733 }
    734 
    735 static int init_pinned_device(struct cras_iodev *dev,
    736 			      struct cras_rstream *rstream)
    737 {
    738 	int rc;
    739 
    740 	if (audio_thread_is_dev_open(audio_thread, dev))
    741 		return 0;
    742 
    743 	/* Make sure the active node is configured properly, it could be
    744 	 * disabled when last normal stream removed. */
    745 	dev->update_active_node(dev, dev->active_node->idx, 1);
    746 
    747 	/* Negative EAGAIN code indicates dev will be opened later. */
    748 	rc = init_device(dev, rstream);
    749 	if (rc && (rc != -EAGAIN))
    750 		return rc;
    751 	return 0;
    752 }
    753 
    754 static int close_pinned_device(struct cras_iodev *dev)
    755 {
    756 	close_dev(dev);
    757 	dev->update_active_node(dev, dev->active_node->idx, 0);
    758 	return 0;
    759 }
    760 
    761 static struct cras_iodev *find_pinned_device(struct cras_rstream *rstream)
    762 {
    763 	struct cras_iodev *dev;
    764 	if (!rstream->is_pinned)
    765 		return NULL;
    766 
    767 	dev = find_dev(rstream->pinned_dev_idx);
    768 
    769 	if ((rstream->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
    770 		return dev;
    771 
    772 	/* Double check node type for hotword stream */
    773 	if (dev && dev->active_node->type != CRAS_NODE_TYPE_HOTWORD) {
    774 		syslog(LOG_ERR, "Hotword stream pinned to invalid dev %u",
    775 		       dev->info.idx);
    776 		return NULL;
    777 	}
    778 
    779 	return hotword_suspended ? empty_hotword_dev : dev;
    780 }
    781 
    782 static int pinned_stream_added(struct cras_rstream *rstream)
    783 {
    784 	struct cras_iodev *dev;
    785 	int rc;
    786 
    787 	/* Check that the target device is valid for pinned streams. */
    788 	dev = find_pinned_device(rstream);
    789 	if (!dev)
    790 		return -EINVAL;
    791 
    792 	rc = init_pinned_device(dev, rstream);
    793 	if (rc) {
    794 		syslog(LOG_INFO, "init_pinned_device failed, rc %d", rc);
    795 		return schedule_init_device_retry(dev);
    796 	}
    797 
    798 	return add_stream_to_open_devs(rstream, &dev, 1);
    799 }
    800 
    801 static int stream_added_cb(struct cras_rstream *rstream)
    802 {
    803 	struct enabled_dev *edev;
    804 	struct cras_iodev *iodevs[10];
    805 	unsigned int num_iodevs;
    806 	int rc;
    807 
    808 	if (stream_list_suspended)
    809 		return 0;
    810 
    811 	if (rstream->is_pinned)
    812 		return pinned_stream_added(rstream);
    813 
    814 	/* Add the new stream to all enabled iodevs at once to avoid offset
    815 	 * in shm level between different ouput iodevs. */
    816 	num_iodevs = 0;
    817 	DL_FOREACH(enabled_devs[rstream->direction], edev) {
    818 		if (num_iodevs >= ARRAY_SIZE(iodevs)) {
    819 			syslog(LOG_ERR, "too many enabled devices");
    820 			break;
    821 		}
    822 
    823 		rc = init_device(edev->dev, rstream);
    824 		if (rc) {
    825 			/* Error log but don't return error here, because
    826 			 * stopping audio could block video playback.
    827 			 */
    828 			syslog(LOG_ERR, "Init %s failed, rc = %d",
    829 			       edev->dev->info.name, rc);
    830 			schedule_init_device_retry(edev->dev);
    831 			continue;
    832 		}
    833 
    834 		iodevs[num_iodevs++] = edev->dev;
    835 	}
    836 	if (num_iodevs) {
    837 		rc = add_stream_to_open_devs(rstream, iodevs, num_iodevs);
    838 		if (rc) {
    839 			syslog(LOG_ERR, "adding stream to thread fail");
    840 			return rc;
    841 		}
    842 	} else {
    843 		/* Enable fallback device if no other iodevs can be initialized
    844 		 * successfully.
    845 		 * For error codes like EAGAIN and ENOENT, a new iodev will be
    846 		 * enabled soon so streams are going to route there. As for the
    847 		 * rest of the error cases, silence will be played or recorded
    848 		 * so client won't be blocked.
    849 		 * The enabled fallback device will be disabled when
    850 		 * cras_iodev_list_select_node() is called to re-select the
    851 		 * active node.
    852 		 */
    853 		possibly_enable_fallback(rstream->direction);
    854 	}
    855 	return 0;
    856 }
    857 
    858 static int possibly_close_enabled_devs(enum CRAS_STREAM_DIRECTION dir)
    859 {
    860 	struct enabled_dev *edev;
    861 	const struct cras_rstream *s;
    862 
    863 	/* Check if there are still default streams attached. */
    864 	DL_FOREACH(stream_list_get(stream_list), s) {
    865 		if (s->direction == dir && !s->is_pinned)
    866 			return 0;
    867 	}
    868 
    869 	/* No more default streams, close any device that doesn't have a stream
    870 	 * pinned to it. */
    871 	DL_FOREACH(enabled_devs[dir], edev) {
    872 		if (cras_iodev_has_pinned_stream(edev->dev))
    873 			continue;
    874 		if (dir == CRAS_STREAM_INPUT) {
    875 			close_dev(edev->dev);
    876 			continue;
    877 		}
    878 		/* Allow output devs to drain before closing. */
    879 		clock_gettime(CLOCK_MONOTONIC_RAW, &edev->dev->idle_timeout);
    880 		add_timespecs(&edev->dev->idle_timeout, &idle_timeout_interval);
    881 		idle_dev_check(NULL, NULL);
    882 	}
    883 
    884 	return 0;
    885 }
    886 
    887 static void pinned_stream_removed(struct cras_rstream *rstream)
    888 {
    889 	struct cras_iodev *dev;
    890 
    891 	dev = find_pinned_device(rstream);
    892 	if (!dev)
    893 		return;
    894 	if (!cras_iodev_list_dev_is_enabled(dev) &&
    895 	    !cras_iodev_has_pinned_stream(dev))
    896 		close_pinned_device(dev);
    897 }
    898 
    899 /* Returns the number of milliseconds left to drain this stream.  This is passed
    900  * directly from the audio thread. */
    901 static int stream_removed_cb(struct cras_rstream *rstream)
    902 {
    903 	enum CRAS_STREAM_DIRECTION direction = rstream->direction;
    904 	int rc;
    905 
    906 	rc = audio_thread_drain_stream(audio_thread, rstream);
    907 	if (rc)
    908 		return rc;
    909 
    910 	if (rstream->is_pinned)
    911 		pinned_stream_removed(rstream);
    912 
    913 	possibly_close_enabled_devs(direction);
    914 
    915 	return 0;
    916 }
    917 
    918 static int enable_device(struct cras_iodev *dev)
    919 {
    920 	int rc;
    921 	struct enabled_dev *edev;
    922 	enum CRAS_STREAM_DIRECTION dir = dev->direction;
    923 	struct device_enabled_cb *callback;
    924 
    925 	DL_FOREACH(enabled_devs[dir], edev) {
    926 		if (edev->dev == dev)
    927 			return -EEXIST;
    928 	}
    929 
    930 	edev = calloc(1, sizeof(*edev));
    931 	edev->dev = dev;
    932 	DL_APPEND(enabled_devs[dir], edev);
    933 	dev->is_enabled = 1;
    934 
    935 	rc = init_and_attach_streams(dev);
    936 	if (rc < 0) {
    937 		syslog(LOG_INFO, "Enable device fail, rc %d", rc);
    938 		schedule_init_device_retry(dev);
    939 		return rc;
    940 	}
    941 
    942 	DL_FOREACH(device_enable_cbs, callback)
    943 		callback->enabled_cb(dev, callback->cb_data);
    944 
    945 	return 0;
    946 }
    947 
    948 /* Set `force to true to flush any pinned streams before closing the device. */
    949 static int disable_device(struct enabled_dev *edev, bool force)
    950 {
    951 	struct cras_iodev *dev = edev->dev;
    952 	enum CRAS_STREAM_DIRECTION dir = dev->direction;
    953 	struct cras_rstream *stream;
    954 	struct device_enabled_cb *callback;
    955 
    956 	/*
    957 	 * Remove from enabled dev list. However this dev could have a stream
    958 	 * pinned to it, only cancel pending init timers when force flag is set.
    959 	 */
    960 	DL_DELETE(enabled_devs[dir], edev);
    961 	free(edev);
    962 	dev->is_enabled = 0;
    963 	if (force)
    964 		cancel_pending_init_retries(dev->info.idx);
    965 
    966 	/*
    967 	 * Pull all default streams off this device.
    968 	 * Pull all pinned streams off as well if force is true.
    969 	 */
    970 	DL_FOREACH(stream_list_get(stream_list), stream) {
    971 		if (stream->direction != dev->direction)
    972 			continue;
    973 		if (stream->is_pinned && !force)
    974 			continue;
    975 		audio_thread_disconnect_stream(audio_thread, stream, dev);
    976 	}
    977 	if (cras_iodev_has_pinned_stream(dev))
    978 		return 0;
    979 	DL_FOREACH(device_enable_cbs, callback)
    980 		callback->disabled_cb(dev, callback->cb_data);
    981 	close_dev(dev);
    982 	dev->update_active_node(dev, dev->active_node->idx, 0);
    983 
    984 	return 0;
    985 }
    986 
    987 /*
    988  * Assume the device is not in enabled_devs list.
    989  * Assume there is no default stream on the device.
    990  * An example is that this device is unplugged while it is playing
    991  * a pinned stream. The device and stream may have been removed in
    992  * audio thread due to I/O error handling.
    993  */
    994 static int force_close_pinned_only_device(struct cras_iodev *dev)
    995 {
    996 	struct cras_rstream *rstream;
    997 
    998 	/* Pull pinned streams off this device. */
    999 	DL_FOREACH(stream_list_get(stream_list), rstream) {
   1000 		if (rstream->direction != dev->direction)
   1001 			continue;
   1002 		if (!rstream->is_pinned)
   1003 			continue;
   1004 		if (dev->info.idx != rstream->pinned_dev_idx)
   1005 			continue;
   1006 		audio_thread_disconnect_stream(audio_thread, rstream, dev);
   1007 	}
   1008 	if (cras_iodev_has_pinned_stream(dev))
   1009 		return -EEXIST;
   1010 	close_dev(dev);
   1011 	dev->update_active_node(dev, dev->active_node->idx, 0);
   1012 	return 0;
   1013 }
   1014 
   1015 /*
   1016  * Exported Interface.
   1017  */
   1018 
   1019 void cras_iodev_list_init()
   1020 {
   1021 	struct cras_observer_ops observer_ops;
   1022 
   1023 	memset(&observer_ops, 0, sizeof(observer_ops));
   1024 	observer_ops.output_volume_changed = sys_vol_change;
   1025 	observer_ops.output_mute_changed = sys_mute_change;
   1026 	observer_ops.capture_gain_changed = sys_cap_gain_change;
   1027 	observer_ops.capture_mute_changed = sys_cap_mute_change;
   1028 	observer_ops.suspend_changed = sys_suspend_change;
   1029 	list_observer = cras_observer_add(&observer_ops, NULL);
   1030 	idle_timer = NULL;
   1031 
   1032 	/* Create the audio stream list for the system. */
   1033 	stream_list = stream_list_create(stream_added_cb, stream_removed_cb,
   1034 					 cras_rstream_create,
   1035 					 cras_rstream_destroy,
   1036 					 cras_system_state_get_tm());
   1037 
   1038 	/* Add an empty device so there is always something to play to or
   1039 	 * capture from. */
   1040 	fallback_devs[CRAS_STREAM_OUTPUT] = empty_iodev_create(
   1041 			CRAS_STREAM_OUTPUT,
   1042 			CRAS_NODE_TYPE_UNKNOWN);
   1043 	fallback_devs[CRAS_STREAM_INPUT] = empty_iodev_create(
   1044 			CRAS_STREAM_INPUT,
   1045 			CRAS_NODE_TYPE_UNKNOWN);
   1046 	enable_device(fallback_devs[CRAS_STREAM_OUTPUT]);
   1047 	enable_device(fallback_devs[CRAS_STREAM_INPUT]);
   1048 
   1049 	empty_hotword_dev = empty_iodev_create(
   1050 			CRAS_STREAM_INPUT,
   1051 			CRAS_NODE_TYPE_HOTWORD);
   1052 
   1053 	/* Create loopback devices. */
   1054 	loopdev_post_mix = loopback_iodev_create(LOOPBACK_POST_MIX_PRE_DSP);
   1055 	loopdev_post_dsp = loopback_iodev_create(LOOPBACK_POST_DSP);
   1056 
   1057 	audio_thread = audio_thread_create();
   1058 	if (!audio_thread) {
   1059 		syslog(LOG_ERR, "Fatal: audio thread init");
   1060 		exit(-ENOMEM);
   1061 	}
   1062 	audio_thread_start(audio_thread);
   1063 
   1064 	cras_iodev_list_update_device_list();
   1065 }
   1066 
   1067 void cras_iodev_list_deinit()
   1068 {
   1069 	audio_thread_destroy(audio_thread);
   1070 	loopback_iodev_destroy(loopdev_post_dsp);
   1071 	loopback_iodev_destroy(loopdev_post_mix);
   1072 	empty_iodev_destroy(empty_hotword_dev);
   1073 	empty_iodev_destroy(fallback_devs[CRAS_STREAM_INPUT]);
   1074 	empty_iodev_destroy(fallback_devs[CRAS_STREAM_OUTPUT]);
   1075 	stream_list_destroy(stream_list);
   1076 	if (list_observer) {
   1077 		cras_observer_remove(list_observer);
   1078 		list_observer = NULL;
   1079 	}
   1080 }
   1081 
   1082 int cras_iodev_list_dev_is_enabled(const struct cras_iodev *dev)
   1083 {
   1084 	struct enabled_dev *edev;
   1085 
   1086 	DL_FOREACH(enabled_devs[dev->direction], edev) {
   1087 		if (edev->dev == dev)
   1088 			return 1;
   1089 	}
   1090 
   1091 	return 0;
   1092 }
   1093 
   1094 void cras_iodev_list_enable_dev(struct cras_iodev *dev)
   1095 {
   1096 	possibly_disable_fallback(dev->direction);
   1097 	/* Enable ucm setting of active node. */
   1098 	dev->update_active_node(dev, dev->active_node->idx, 1);
   1099 	enable_device(dev);
   1100 	cras_iodev_list_notify_active_node_changed(dev->direction);
   1101 }
   1102 
   1103 void cras_iodev_list_add_active_node(enum CRAS_STREAM_DIRECTION dir,
   1104 				     cras_node_id_t node_id)
   1105 {
   1106 	struct cras_iodev *new_dev;
   1107 	new_dev = find_dev(dev_index_of(node_id));
   1108 	if (!new_dev || new_dev->direction != dir)
   1109 		return;
   1110 
   1111 	/* If the new dev is already enabled but its active node needs to be
   1112 	 * changed. Disable new dev first, update active node, and then
   1113 	 * re-enable it again.
   1114 	 */
   1115 	if (cras_iodev_list_dev_is_enabled(new_dev)) {
   1116 		if (node_index_of(node_id) == new_dev->active_node->idx)
   1117 			return;
   1118 		else
   1119 			cras_iodev_list_disable_dev(new_dev, true);
   1120 	}
   1121 
   1122 	new_dev->update_active_node(new_dev, node_index_of(node_id), 1);
   1123 	cras_iodev_list_enable_dev(new_dev);
   1124 }
   1125 
   1126 /*
   1127  * Disables device which may or may not be in enabled_devs list.
   1128  */
   1129 void cras_iodev_list_disable_dev(struct cras_iodev *dev, bool force_close)
   1130 {
   1131 	struct enabled_dev *edev, *edev_to_disable = NULL;
   1132 
   1133 	int is_the_only_enabled_device = 1;
   1134 
   1135 	DL_FOREACH(enabled_devs[dev->direction], edev) {
   1136 		if (edev->dev == dev)
   1137 			edev_to_disable = edev;
   1138 		else
   1139 			is_the_only_enabled_device = 0;
   1140 	}
   1141 
   1142 	/*
   1143 	 * Disables the device for these two cases:
   1144 	 * 1. Disable a device in the enabled_devs list.
   1145 	 * 2. Force close a device that is not in the enabled_devs list,
   1146 	 *    but it is running a pinned stream.
   1147 	 */
   1148 	if (!edev_to_disable) {
   1149 		if (force_close)
   1150 			force_close_pinned_only_device(dev);
   1151 		return;
   1152 	}
   1153 
   1154 	/* If the device to be closed is the only enabled device, we should
   1155 	 * enable the fallback device first then disable the target
   1156 	 * device. */
   1157 	if (is_the_only_enabled_device && fallback_devs[dev->direction])
   1158 		enable_device(fallback_devs[dev->direction]);
   1159 
   1160 	disable_device(edev_to_disable, force_close);
   1161 
   1162 	cras_iodev_list_notify_active_node_changed(dev->direction);
   1163 	return;
   1164 }
   1165 
   1166 void cras_iodev_list_rm_active_node(enum CRAS_STREAM_DIRECTION dir,
   1167 				    cras_node_id_t node_id)
   1168 {
   1169 	struct cras_iodev *dev;
   1170 
   1171 	dev = find_dev(dev_index_of(node_id));
   1172 	if (!dev)
   1173 		return;
   1174 
   1175 	cras_iodev_list_disable_dev(dev, false);
   1176 }
   1177 
   1178 int cras_iodev_list_add_output(struct cras_iodev *output)
   1179 {
   1180 	int rc;
   1181 
   1182 	if (output->direction != CRAS_STREAM_OUTPUT)
   1183 		return -EINVAL;
   1184 
   1185 	rc = add_dev_to_list(output);
   1186 	if (rc)
   1187 		return rc;
   1188 
   1189 	return 0;
   1190 }
   1191 
   1192 int cras_iodev_list_add_input(struct cras_iodev *input)
   1193 {
   1194 	int rc;
   1195 
   1196 	if (input->direction != CRAS_STREAM_INPUT)
   1197 		return -EINVAL;
   1198 
   1199 	rc = add_dev_to_list(input);
   1200 	if (rc)
   1201 		return rc;
   1202 
   1203 	return 0;
   1204 }
   1205 
   1206 int cras_iodev_list_rm_output(struct cras_iodev *dev)
   1207 {
   1208 	int res;
   1209 
   1210 	/* Retire the current active output device before removing it from
   1211 	 * list, otherwise it could be busy and remain in the list.
   1212 	 */
   1213 	cras_iodev_list_disable_dev(dev, true);
   1214 	res = rm_dev_from_list(dev);
   1215 	if (res == 0)
   1216 		cras_iodev_list_update_device_list();
   1217 	return res;
   1218 }
   1219 
   1220 int cras_iodev_list_rm_input(struct cras_iodev *dev)
   1221 {
   1222 	int res;
   1223 
   1224 	/* Retire the current active input device before removing it from
   1225 	 * list, otherwise it could be busy and remain in the list.
   1226 	 */
   1227 	cras_iodev_list_disable_dev(dev, true);
   1228 	res = rm_dev_from_list(dev);
   1229 	if (res == 0)
   1230 		cras_iodev_list_update_device_list();
   1231 	return res;
   1232 }
   1233 
   1234 int cras_iodev_list_get_outputs(struct cras_iodev_info **list_out)
   1235 {
   1236 	return get_dev_list(&devs[CRAS_STREAM_OUTPUT], list_out);
   1237 }
   1238 
   1239 int cras_iodev_list_get_inputs(struct cras_iodev_info **list_out)
   1240 {
   1241 	return get_dev_list(&devs[CRAS_STREAM_INPUT], list_out);
   1242 }
   1243 
   1244 struct cras_iodev *cras_iodev_list_get_first_enabled_iodev(
   1245 	enum CRAS_STREAM_DIRECTION direction)
   1246 {
   1247 	struct enabled_dev *edev = enabled_devs[direction];
   1248 
   1249 	return edev ? edev->dev : NULL;
   1250 }
   1251 
   1252 cras_node_id_t cras_iodev_list_get_active_node_id(
   1253 	enum CRAS_STREAM_DIRECTION direction)
   1254 {
   1255 	struct enabled_dev *edev = enabled_devs[direction];
   1256 
   1257 	if (!edev || !edev->dev || !edev->dev->active_node)
   1258 		return 0;
   1259 
   1260 	return cras_make_node_id(edev->dev->info.idx,
   1261 				 edev->dev->active_node->idx);
   1262 }
   1263 
   1264 void cras_iodev_list_update_device_list()
   1265 {
   1266 	struct cras_server_state *state;
   1267 
   1268 	state = cras_system_state_update_begin();
   1269 	if (!state)
   1270 		return;
   1271 
   1272 	state->num_output_devs = devs[CRAS_STREAM_OUTPUT].size;
   1273 	state->num_input_devs = devs[CRAS_STREAM_INPUT].size;
   1274 	fill_dev_list(&devs[CRAS_STREAM_OUTPUT], &state->output_devs[0],
   1275 		      CRAS_MAX_IODEVS);
   1276 	fill_dev_list(&devs[CRAS_STREAM_INPUT], &state->input_devs[0],
   1277 		      CRAS_MAX_IODEVS);
   1278 
   1279 	state->num_output_nodes = fill_node_list(&devs[CRAS_STREAM_OUTPUT],
   1280 						 &state->output_nodes[0],
   1281 						 CRAS_MAX_IONODES);
   1282 	state->num_input_nodes = fill_node_list(&devs[CRAS_STREAM_INPUT],
   1283 						&state->input_nodes[0],
   1284 						CRAS_MAX_IONODES);
   1285 
   1286 	cras_system_state_update_complete();
   1287 }
   1288 
   1289 /* Look up the first hotword stream and the device it pins to. */
   1290 int find_hotword_stream_dev(struct cras_iodev **dev,
   1291 			    struct cras_rstream **stream)
   1292 {
   1293 	DL_FOREACH(stream_list_get(stream_list), *stream) {
   1294 		if (((*stream)->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
   1295 			continue;
   1296 
   1297 		*dev = find_dev((*stream)->pinned_dev_idx);
   1298 		if (*dev == NULL)
   1299 			return -ENOENT;
   1300 		break;
   1301 	}
   1302 	return 0;
   1303 }
   1304 
   1305 /* Suspend/resume hotword streams functions are used to provide seamless
   1306  * experience to cras clients when there's hardware limitation about concurrent
   1307  * DSP and normal recording. The empty hotword iodev is used to hold all
   1308  * hotword streams during suspend, so client side will not know about the
   1309  * transition, and can still remove or add streams. At resume, the real hotword
   1310  * device will be initialized and opened again to re-arm the DSP.
   1311  */
   1312 int cras_iodev_list_suspend_hotword_streams()
   1313 {
   1314 	struct cras_iodev *hotword_dev;
   1315 	struct cras_rstream *stream = NULL;
   1316 	int rc;
   1317 
   1318 	rc = find_hotword_stream_dev(&hotword_dev, &stream);
   1319 	if (rc)
   1320 		return rc;
   1321 
   1322 	if (stream == NULL) {
   1323 		hotword_suspended = 1;
   1324 		return 0;
   1325 	}
   1326 	/* Move all existing hotword streams to the empty hotword iodev. */
   1327 	init_pinned_device(empty_hotword_dev, stream);
   1328 	DL_FOREACH(stream_list_get(stream_list), stream) {
   1329 		if ((stream->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
   1330 			continue;
   1331 		if (stream->pinned_dev_idx != hotword_dev->info.idx) {
   1332 			syslog(LOG_ERR,
   1333 			       "Failed to suspend hotword stream on dev %u",
   1334 				stream->pinned_dev_idx);
   1335 			continue;
   1336 		}
   1337 
   1338 		audio_thread_disconnect_stream(audio_thread, stream, hotword_dev);
   1339 		audio_thread_add_stream(audio_thread, stream, &empty_hotword_dev, 1);
   1340 	}
   1341 	close_pinned_device(hotword_dev);
   1342 	hotword_suspended = 1;
   1343 	return 0;
   1344 }
   1345 
   1346 int cras_iodev_list_resume_hotword_stream()
   1347 {
   1348 	struct cras_iodev *hotword_dev;
   1349 	struct cras_rstream *stream = NULL;
   1350 	int rc;
   1351 
   1352 	rc = find_hotword_stream_dev(&hotword_dev, &stream);
   1353 	if (rc)
   1354 		return rc;
   1355 
   1356 	if (stream == NULL) {
   1357 		hotword_suspended = 0;
   1358 		return 0;
   1359 	}
   1360 	/* Move all existing hotword streams to the real hotword iodev. */
   1361 	init_pinned_device(hotword_dev, stream);
   1362 	DL_FOREACH(stream_list_get(stream_list), stream) {
   1363 		if ((stream->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
   1364 			continue;
   1365 		if (stream->pinned_dev_idx != hotword_dev->info.idx) {
   1366 			syslog(LOG_ERR,
   1367 			       "Fail to resume hotword stream on dev %u",
   1368 			       stream->pinned_dev_idx);
   1369 			continue;
   1370 		}
   1371 
   1372 		audio_thread_disconnect_stream(audio_thread, stream, empty_hotword_dev);
   1373 		audio_thread_add_stream(audio_thread, stream, &hotword_dev, 1);
   1374 	}
   1375 	close_pinned_device(empty_hotword_dev);
   1376 	hotword_suspended = 0;
   1377 	return 0;
   1378 }
   1379 
   1380 char *cras_iodev_list_get_hotword_models(cras_node_id_t node_id)
   1381 {
   1382 	struct cras_iodev *dev = NULL;
   1383 
   1384 	dev = find_dev(dev_index_of(node_id));
   1385 	if (!dev || !dev->get_hotword_models ||
   1386 	    (dev->active_node->type != CRAS_NODE_TYPE_HOTWORD))
   1387 		return NULL;
   1388 
   1389 	return dev->get_hotword_models(dev);
   1390 }
   1391 
   1392 int cras_iodev_list_set_hotword_model(cras_node_id_t node_id,
   1393 				      const char *model_name)
   1394 {
   1395 	int ret;
   1396 	struct cras_iodev *dev =
   1397 			 find_dev(dev_index_of(node_id));
   1398 	if (!dev || !dev->get_hotword_models ||
   1399 	    (dev->active_node->type != CRAS_NODE_TYPE_HOTWORD))
   1400 		return -EINVAL;
   1401 
   1402 	ret = dev->set_hotword_model(dev, model_name);
   1403 	if (!ret)
   1404 		strncpy(dev->active_node->active_hotword_model, model_name,
   1405 			sizeof(dev->active_node->active_hotword_model) - 1);
   1406 	return ret;
   1407 }
   1408 
   1409 void cras_iodev_list_notify_nodes_changed()
   1410 {
   1411 	cras_observer_notify_nodes();
   1412 }
   1413 
   1414 void cras_iodev_list_notify_active_node_changed(
   1415 		enum CRAS_STREAM_DIRECTION direction)
   1416 {
   1417 	cras_observer_notify_active_node(direction,
   1418 			cras_iodev_list_get_active_node_id(direction));
   1419 }
   1420 
   1421 void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
   1422 				 cras_node_id_t node_id)
   1423 {
   1424 	struct cras_iodev *new_dev = NULL;
   1425 	struct enabled_dev *edev;
   1426         int new_node_already_enabled = 0;
   1427 	int rc;
   1428 
   1429 	/* find the devices for the id. */
   1430 	new_dev = find_dev(dev_index_of(node_id));
   1431 
   1432 	/* Do nothing if the direction is mismatched. The new_dev == NULL case
   1433 	   could happen if node_id is 0 (no selection), or the client tries
   1434 	   to select a non-existing node (maybe it's unplugged just before
   1435 	   the client selects it). We will just behave like there is no selected
   1436 	   node. */
   1437 	if (new_dev && new_dev->direction != direction)
   1438 		return;
   1439 
   1440 	/* Determine whether the new device and node are already enabled - if
   1441 	 * they are, the selection algorithm should avoid disabling the new
   1442 	 * device. */
   1443 	DL_FOREACH(enabled_devs[direction], edev) {
   1444 		if (edev->dev == new_dev &&
   1445 		    edev->dev->active_node->idx == node_index_of(node_id)) {
   1446 			new_node_already_enabled = 1;
   1447 			break;
   1448 		}
   1449 	}
   1450 
   1451 	/* Enable fallback device during the transition so client will not be
   1452 	 * blocked in this duration, which is as long as 300 ms on some boards
   1453 	 * before new device is opened.
   1454 	 * Note that the fallback node is not needed if the new node is already
   1455 	 * enabled - the new node will remain enabled. */
   1456 	if (!new_node_already_enabled)
   1457 		possibly_enable_fallback(direction);
   1458 
   1459 	/* Disable all devices except for fallback device, and the new device,
   1460 	 * provided it is already enabled. */
   1461 	DL_FOREACH(enabled_devs[direction], edev) {
   1462 		if (edev->dev != fallback_devs[direction] &&
   1463 		    !(new_node_already_enabled && edev->dev == new_dev)) {
   1464 			disable_device(edev, false);
   1465 		}
   1466 	}
   1467 
   1468 	if (new_dev && !new_node_already_enabled) {
   1469 		new_dev->update_active_node(new_dev, node_index_of(node_id), 1);
   1470 		rc = enable_device(new_dev);
   1471 		if (rc == 0) {
   1472 			/* Disable fallback device after new device is enabled.
   1473 			 * Leave the fallback device enabled if new_dev failed
   1474 			 * to open, or the new_dev == NULL case. */
   1475 			possibly_disable_fallback(direction);
   1476 		}
   1477 	}
   1478 
   1479 	cras_iodev_list_notify_active_node_changed(direction);
   1480 }
   1481 
   1482 int cras_iodev_list_set_node_attr(cras_node_id_t node_id,
   1483 				  enum ionode_attr attr, int value)
   1484 {
   1485 	struct cras_ionode *node;
   1486 	int rc;
   1487 
   1488 	node = find_node(node_id);
   1489 	if (!node)
   1490 		return -EINVAL;
   1491 
   1492 	rc = cras_iodev_set_node_attr(node, attr, value);
   1493 	return rc;
   1494 }
   1495 
   1496 void cras_iodev_list_notify_node_volume(struct cras_ionode *node)
   1497 {
   1498 	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
   1499 	cras_iodev_list_update_device_list();
   1500 	cras_observer_notify_output_node_volume(id, node->volume);
   1501 }
   1502 
   1503 void cras_iodev_list_notify_node_left_right_swapped(struct cras_ionode *node)
   1504 {
   1505 	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
   1506 	cras_iodev_list_update_device_list();
   1507 	cras_observer_notify_node_left_right_swapped(id,
   1508 						     node->left_right_swapped);
   1509 }
   1510 
   1511 void cras_iodev_list_notify_node_capture_gain(struct cras_ionode *node)
   1512 {
   1513 	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
   1514 	cras_iodev_list_update_device_list();
   1515 	cras_observer_notify_input_node_gain(id, node->capture_gain);
   1516 }
   1517 
   1518 void cras_iodev_list_add_test_dev(enum TEST_IODEV_TYPE type)
   1519 {
   1520 	if (type != TEST_IODEV_HOTWORD)
   1521 		return;
   1522 	test_iodev_create(CRAS_STREAM_INPUT, type);
   1523 }
   1524 
   1525 void cras_iodev_list_test_dev_command(unsigned int iodev_idx,
   1526 				      enum CRAS_TEST_IODEV_CMD command,
   1527 				      unsigned int data_len,
   1528 				      const uint8_t *data)
   1529 {
   1530 	struct cras_iodev *dev = find_dev(iodev_idx);
   1531 
   1532 	if (!dev)
   1533 		return;
   1534 
   1535 	test_iodev_command(dev, command, data_len, data);
   1536 }
   1537 
   1538 struct audio_thread *cras_iodev_list_get_audio_thread()
   1539 {
   1540 	return audio_thread;
   1541 }
   1542 
   1543 struct stream_list *cras_iodev_list_get_stream_list()
   1544 {
   1545 	return stream_list;
   1546 }
   1547 
   1548 int cras_iodev_list_set_device_enabled_callback(
   1549 		device_enabled_callback_t enabled_cb,
   1550 		device_disabled_callback_t disabled_cb,
   1551 		void *cb_data)
   1552 {
   1553 	struct device_enabled_cb *callback;
   1554 
   1555 	DL_FOREACH(device_enable_cbs, callback) {
   1556 		if (callback->cb_data != cb_data)
   1557 			continue;
   1558 
   1559 		DL_DELETE(device_enable_cbs, callback);
   1560 		free(callback);
   1561 	}
   1562 
   1563 	if (enabled_cb && disabled_cb) {
   1564 		callback = (struct device_enabled_cb *)
   1565 				calloc(1, sizeof(*callback));
   1566 		callback->enabled_cb = enabled_cb;
   1567 		callback->disabled_cb = disabled_cb;
   1568 		callback->cb_data = cb_data;
   1569 		DL_APPEND(device_enable_cbs, callback);
   1570 	}
   1571 
   1572 	return 0;
   1573 }
   1574 
   1575 void cras_iodev_list_reset()
   1576 {
   1577 	struct enabled_dev *edev;
   1578 
   1579 	DL_FOREACH(enabled_devs[CRAS_STREAM_OUTPUT], edev) {
   1580 		DL_DELETE(enabled_devs[CRAS_STREAM_OUTPUT], edev);
   1581 		free(edev);
   1582 	}
   1583 	enabled_devs[CRAS_STREAM_OUTPUT] = NULL;
   1584 	DL_FOREACH(enabled_devs[CRAS_STREAM_INPUT], edev) {
   1585 		DL_DELETE(enabled_devs[CRAS_STREAM_INPUT], edev);
   1586 		free(edev);
   1587 	}
   1588 	enabled_devs[CRAS_STREAM_INPUT] = NULL;
   1589 	devs[CRAS_STREAM_OUTPUT].iodevs = NULL;
   1590 	devs[CRAS_STREAM_INPUT].iodevs = NULL;
   1591 	devs[CRAS_STREAM_OUTPUT].size = 0;
   1592 	devs[CRAS_STREAM_INPUT].size = 0;
   1593 }
   1594