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 "stream_list.h"
     21 #include "test_iodev.h"
     22 #include "utlist.h"
     23 
     24 const struct timespec idle_timeout_interval = {
     25 	.tv_sec = 10,
     26 	.tv_nsec = 0
     27 };
     28 
     29 /* Linked list of available devices. */
     30 struct iodev_list {
     31 	struct cras_iodev *iodevs;
     32 	size_t size;
     33 };
     34 
     35 /* List of enabled input/output devices.
     36  *    dev - The device.
     37  *    init_timer - Timer for a delayed call to init this iodev.
     38  */
     39 struct enabled_dev {
     40 	struct cras_iodev *dev;
     41 	struct cras_timer *init_timer;
     42 	struct enabled_dev *prev, *next;
     43 };
     44 
     45 /* Lists for devs[CRAS_STREAM_INPUT] and devs[CRAS_STREAM_OUTPUT]. */
     46 static struct iodev_list devs[CRAS_NUM_DIRECTIONS];
     47 /* The observer client iodev_list used to listen on various events. */
     48 static struct cras_observer_client *list_observer;
     49 /* Keep a list of enabled inputs and outputs. */
     50 static struct enabled_dev *enabled_devs[CRAS_NUM_DIRECTIONS];
     51 /* Keep an empty device per direction. */
     52 static struct cras_iodev *fallback_devs[CRAS_NUM_DIRECTIONS];
     53 /* Keep a constantly increasing index for iodevs. Index 0 is reserved
     54  * to mean "no device". */
     55 static uint32_t next_iodev_idx = MAX_SPECIAL_DEVICE_IDX;
     56 
     57 /* Call when a device is enabled or disabled. */
     58 static device_enabled_callback_t device_enabled_callback;
     59 static void *device_enabled_cb_data;
     60 /* Thread that handles audio input and output. */
     61 static struct audio_thread *audio_thread;
     62 /* List of all streams. */
     63 static struct stream_list *stream_list;
     64 /* Idle device timer. */
     65 static struct cras_timer *idle_timer;
     66 /* Flag to indicate that the stream list is disconnected from audio thread. */
     67 static int stream_list_suspended = 0;
     68 /* If init device failed, retry after 1 second. */
     69 static const unsigned int INIT_DEV_DELAY_MS = 1000;
     70 
     71 static void idle_dev_check(struct cras_timer *timer, void *data);
     72 
     73 static struct cras_iodev *find_dev(size_t dev_index)
     74 {
     75 	struct cras_iodev *dev;
     76 
     77 	DL_FOREACH(devs[CRAS_STREAM_OUTPUT].iodevs, dev)
     78 		if (dev->info.idx == dev_index)
     79 			return dev;
     80 
     81 	DL_FOREACH(devs[CRAS_STREAM_INPUT].iodevs, dev)
     82 		if (dev->info.idx == dev_index)
     83 			return dev;
     84 
     85 	return NULL;
     86 }
     87 
     88 static struct cras_ionode *find_node(cras_node_id_t id)
     89 {
     90 	struct cras_iodev *dev;
     91 	struct cras_ionode *node;
     92 	uint32_t dev_index, node_index;
     93 
     94 	dev_index = dev_index_of(id);
     95 	node_index = node_index_of(id);
     96 
     97 	dev = find_dev(dev_index);
     98 	if (!dev)
     99 		return NULL;
    100 
    101 	DL_FOREACH(dev->nodes, node)
    102 		if (node->idx == node_index)
    103 			return node;
    104 
    105 	return NULL;
    106 }
    107 
    108 /* Adds a device to the list.  Used from add_input and add_output. */
    109 static int add_dev_to_list(struct cras_iodev *dev)
    110 {
    111 	struct cras_iodev *tmp;
    112 	uint32_t new_idx;
    113 	struct iodev_list *list = &devs[dev->direction];
    114 
    115 	DL_FOREACH(list->iodevs, tmp)
    116 		if (tmp == dev)
    117 			return -EEXIST;
    118 
    119 	dev->format = NULL;
    120 	dev->ext_format = NULL;
    121 	dev->prev = dev->next = NULL;
    122 
    123 	/* Move to the next index and make sure it isn't taken. */
    124 	new_idx = next_iodev_idx;
    125 	while (1) {
    126 		if (new_idx < MAX_SPECIAL_DEVICE_IDX)
    127 			new_idx = MAX_SPECIAL_DEVICE_IDX;
    128 		DL_SEARCH_SCALAR(list->iodevs, tmp, info.idx, new_idx);
    129 		if (tmp == NULL)
    130 			break;
    131 		new_idx++;
    132 	}
    133 	dev->info.idx = new_idx;
    134 	next_iodev_idx = new_idx + 1;
    135 	list->size++;
    136 
    137 	syslog(LOG_INFO, "Adding %s dev at index %u.",
    138 	       dev->direction == CRAS_STREAM_OUTPUT ? "output" : "input",
    139 	       dev->info.idx);
    140 	DL_PREPEND(list->iodevs, dev);
    141 
    142 	cras_iodev_list_update_device_list();
    143 	return 0;
    144 }
    145 
    146 /* Removes a device to the list.  Used from rm_input and rm_output. */
    147 static int rm_dev_from_list(struct cras_iodev *dev)
    148 {
    149 	struct cras_iodev *tmp;
    150 
    151 	DL_FOREACH(devs[dev->direction].iodevs, tmp)
    152 		if (tmp == dev) {
    153 			if (cras_iodev_is_open(dev))
    154 				return -EBUSY;
    155 			DL_DELETE(devs[dev->direction].iodevs, dev);
    156 			devs[dev->direction].size--;
    157 			return 0;
    158 		}
    159 
    160 	/* Device not found. */
    161 	return -EINVAL;
    162 }
    163 
    164 /* Fills a dev_info array from the iodev_list. */
    165 static void fill_dev_list(struct iodev_list *list,
    166 			  struct cras_iodev_info *dev_info,
    167 			  size_t out_size)
    168 {
    169 	int i = 0;
    170 	struct cras_iodev *tmp;
    171 	DL_FOREACH(list->iodevs, tmp) {
    172 		memcpy(&dev_info[i], &tmp->info, sizeof(dev_info[0]));
    173 		i++;
    174 		if (i == out_size)
    175 			return;
    176 	}
    177 }
    178 
    179 static const char *node_type_to_str(struct cras_ionode *node)
    180 {
    181 	switch (node->type) {
    182 	case CRAS_NODE_TYPE_INTERNAL_SPEAKER:
    183 		return "INTERNAL_SPEAKER";
    184 	case CRAS_NODE_TYPE_HEADPHONE:
    185 		return "HEADPHONE";
    186 	case CRAS_NODE_TYPE_HDMI:
    187 		return "HDMI";
    188 	case CRAS_NODE_TYPE_HAPTIC:
    189 		return "HAPTIC";
    190 	case CRAS_NODE_TYPE_MIC:
    191 		switch (node->position) {
    192 		case NODE_POSITION_INTERNAL:
    193 			return "INTERNAL_MIC";
    194 		case NODE_POSITION_FRONT:
    195 			return "FRONT_MIC";
    196 		case NODE_POSITION_REAR:
    197 			return "REAR_MIC";
    198 		case NODE_POSITION_KEYBOARD:
    199 			return "KEYBOARD_MIC";
    200 		case NODE_POSITION_EXTERNAL:
    201 		default:
    202 			return "MIC";
    203 		}
    204 	case CRAS_NODE_TYPE_HOTWORD:
    205 		return "HOTWORD";
    206 	case CRAS_NODE_TYPE_LINEOUT:
    207 		return "LINEOUT";
    208 	case CRAS_NODE_TYPE_POST_MIX_PRE_DSP:
    209 		return "POST_MIX_LOOPBACK";
    210 	case CRAS_NODE_TYPE_POST_DSP:
    211 		return "POST_DSP_LOOPBACK";
    212 	case CRAS_NODE_TYPE_USB:
    213 		return "USB";
    214 	case CRAS_NODE_TYPE_BLUETOOTH:
    215 		return "BLUETOOTH";
    216 	case CRAS_NODE_TYPE_UNKNOWN:
    217 	default:
    218 		return "UNKNOWN";
    219 	}
    220 }
    221 
    222 /* Fills an ionode_info array from the iodev_list. */
    223 static int fill_node_list(struct iodev_list *list,
    224 			  struct cras_ionode_info *node_info,
    225 			  size_t out_size)
    226 {
    227 	int i = 0;
    228 	struct cras_iodev *dev;
    229 	struct cras_ionode *node;
    230 	DL_FOREACH(list->iodevs, dev) {
    231 		DL_FOREACH(dev->nodes, node) {
    232 			node_info->iodev_idx = dev->info.idx;
    233 			node_info->ionode_idx = node->idx;
    234 			node_info->plugged = node->plugged;
    235 			node_info->plugged_time.tv_sec =
    236 				node->plugged_time.tv_sec;
    237 			node_info->plugged_time.tv_usec =
    238 				node->plugged_time.tv_usec;
    239 			node_info->active = dev->is_enabled &&
    240 					    (dev->active_node == node);
    241 			node_info->volume = node->volume;
    242 			node_info->capture_gain = node->capture_gain;
    243 			node_info->left_right_swapped = node->left_right_swapped;
    244 			node_info->stable_id = node->stable_id;
    245 			node_info->stable_id_new = node->stable_id_new;
    246 			strcpy(node_info->mic_positions, node->mic_positions);
    247 			strcpy(node_info->name, node->name);
    248 			strcpy(node_info->active_hotword_model,
    249 				node->active_hotword_model);
    250 			snprintf(node_info->type, sizeof(node_info->type), "%s",
    251 				node_type_to_str(node));
    252 			node_info->type_enum = node->type;
    253 			node_info++;
    254 			i++;
    255 			if (i == out_size)
    256 				return i;
    257 		}
    258 	}
    259 	return i;
    260 }
    261 
    262 /* Copies the info for each device in the list to "list_out". */
    263 static int get_dev_list(struct iodev_list *list,
    264 			struct cras_iodev_info **list_out)
    265 {
    266 	struct cras_iodev_info *dev_info;
    267 
    268 	if (!list_out)
    269 		return list->size;
    270 
    271 	*list_out = NULL;
    272 	if (list->size == 0)
    273 		return 0;
    274 
    275 	dev_info = malloc(sizeof(*list_out[0]) * list->size);
    276 	if (dev_info == NULL)
    277 		return -ENOMEM;
    278 
    279 	fill_dev_list(list, dev_info, list->size);
    280 
    281 	*list_out = dev_info;
    282 	return list->size;
    283 }
    284 
    285 /* Called when the system volume changes.  Pass the current volume setting to
    286  * the default output if it is active. */
    287 static void sys_vol_change(void *context, int32_t volume)
    288 {
    289 	struct cras_iodev *dev;
    290 
    291 	DL_FOREACH(devs[CRAS_STREAM_OUTPUT].iodevs, dev) {
    292 		if (dev->set_volume && cras_iodev_is_open(dev))
    293 			dev->set_volume(dev);
    294 	}
    295 }
    296 
    297 /*
    298  * Checks if a device should start ramping for mute/unmute change.
    299  * Device must meet all the conditions:
    300  *
    301  * - Device is enabled in iodev_list.
    302  * - Device has ramp support.
    303  * - Device is in normal run state, that is, it must be running with valid
    304  *   streams.
    305  * - Device volume, which considers both system volume and adjusted active
    306  *   node volume, is not zero. If device volume is zero, all the samples are
    307  *   suppressed to zero and there is no need to ramp.
    308  */
    309 static int device_should_start_ramp_for_mute(const struct cras_iodev *dev)
    310 {
    311 	return (cras_iodev_list_dev_is_enabled(dev) && dev->ramp &&
    312 		cras_iodev_state(dev) == CRAS_IODEV_STATE_NORMAL_RUN &&
    313 		!cras_iodev_is_zero_volume(dev));
    314 }
    315 
    316 /* Called when the system mute state changes.  Pass the current mute setting
    317  * to the default output if it is active. */
    318 static void sys_mute_change(void *context, int muted, int user_muted,
    319 			    int mute_locked)
    320 {
    321 	struct cras_iodev *dev;
    322 	int should_mute = muted || user_muted;
    323 
    324 	DL_FOREACH(devs[CRAS_STREAM_OUTPUT].iodevs, dev) {
    325 		if (device_should_start_ramp_for_mute(dev)) {
    326 			/*
    327 			 * Start ramping in audio thread and set mute/unmute
    328 			 * state on device. This should only be done when
    329 			 * device is running with valid streams.
    330 			 *
    331 			 * 1. Mute -> Unmute: Set device unmute state after
    332 			 *                    ramping is started.
    333 			 * 2. Unmute -> Mute: Set device mute state after
    334 			 *                    ramping is done.
    335 			 *
    336 			 * The above transition will be handled by
    337 			 * cras_iodev_ramp_start.
    338 			 */
    339 			audio_thread_dev_start_ramp(
    340 					audio_thread,
    341 					dev,
    342 					(should_mute ?
    343 					 CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE :
    344 					 CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE));
    345 
    346 		} else {
    347 			/* For device without ramp, just set its mute state. */
    348 			cras_iodev_set_mute(dev);
    349 		}
    350 	}
    351 }
    352 
    353 static int dev_has_pinned_stream(unsigned int dev_idx)
    354 {
    355 	const struct cras_rstream *rstream;
    356 
    357 	DL_FOREACH(stream_list_get(stream_list), rstream) {
    358 		if (rstream->is_pinned && (rstream->pinned_dev_idx == dev_idx))
    359 			return 1;
    360 	}
    361 	return 0;
    362 }
    363 
    364 static void close_dev(struct cras_iodev *dev)
    365 {
    366 	if (!cras_iodev_is_open(dev) ||
    367 	    dev_has_pinned_stream(dev->info.idx))
    368 		return;
    369 	audio_thread_rm_open_dev(audio_thread, dev);
    370 	dev->idle_timeout.tv_sec = 0;
    371 	cras_iodev_close(dev);
    372 	if (idle_timer)
    373 		cras_tm_cancel_timer(cras_system_state_get_tm(), idle_timer);
    374 	idle_dev_check(NULL, NULL);
    375 }
    376 
    377 static void idle_dev_check(struct cras_timer *timer, void *data)
    378 {
    379 	struct enabled_dev *edev;
    380 	struct timespec now;
    381 	struct timespec min_idle_expiration;
    382 	unsigned int num_idle_devs = 0;
    383 	unsigned int min_idle_timeout_ms;
    384 
    385 	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
    386 	min_idle_expiration.tv_sec = 0;
    387 	min_idle_expiration.tv_nsec = 0;
    388 
    389 	DL_FOREACH(enabled_devs[CRAS_STREAM_OUTPUT], edev) {
    390 		if (edev->dev->idle_timeout.tv_sec == 0)
    391 			continue;
    392 		if (timespec_after(&now, &edev->dev->idle_timeout)) {
    393 			audio_thread_rm_open_dev(audio_thread, edev->dev);
    394 			edev->dev->idle_timeout.tv_sec = 0;
    395 			cras_iodev_close(edev->dev);
    396 			continue;
    397 		}
    398 		num_idle_devs++;
    399 		if (min_idle_expiration.tv_sec == 0 ||
    400 		    timespec_after(&min_idle_expiration,
    401 				   &edev->dev->idle_timeout))
    402 			min_idle_expiration = edev->dev->idle_timeout;
    403 	}
    404 
    405 	idle_timer = NULL;
    406 	if (!num_idle_devs)
    407 		return;
    408 	if (timespec_after(&now, &min_idle_expiration)) {
    409 		min_idle_timeout_ms = 0;
    410 	} else {
    411 		struct timespec timeout;
    412 		subtract_timespecs(&min_idle_expiration, &now, &timeout);
    413 		min_idle_timeout_ms = timespec_to_ms(&timeout);
    414 	}
    415 	/* Wake up when it is time to close the next idle device.  Sleep for a
    416 	 * minimum of 10 milliseconds. */
    417 	idle_timer = cras_tm_create_timer(cras_system_state_get_tm(),
    418 					  MAX(min_idle_timeout_ms, 10),
    419 					  idle_dev_check, NULL);
    420 }
    421 
    422 /* Open the device potentially filling the output with a pre buffer. */
    423 static int init_device(struct cras_iodev *dev,
    424 		       struct cras_rstream *rstream)
    425 {
    426 	int rc;
    427 
    428 	dev->idle_timeout.tv_sec = 0;
    429 
    430 	if (cras_iodev_is_open(dev))
    431 		return 0;
    432 
    433 	if (dev->ext_format == NULL) {
    434 		rc = cras_iodev_set_format(dev, &rstream->format);
    435 		if (rc)
    436 			return rc;
    437 	}
    438 
    439 	rc = cras_iodev_open(dev, rstream->cb_threshold);
    440 	if (rc)
    441 		return rc;
    442 
    443 	rc = audio_thread_add_open_dev(audio_thread, dev);
    444 	if (rc)
    445 		cras_iodev_close(dev);
    446 	return rc;
    447 }
    448 
    449 static void suspend_devs()
    450 {
    451 	struct enabled_dev *edev;
    452 	struct cras_rstream *rstream;
    453 
    454 	DL_FOREACH(stream_list_get(stream_list), rstream) {
    455 		if (rstream->is_pinned) {
    456 			struct cras_iodev *dev;
    457 
    458 			dev = find_dev(rstream->pinned_dev_idx);
    459 			if (dev) {
    460 				audio_thread_disconnect_stream(audio_thread,
    461 							       rstream, dev);
    462 				if (!cras_iodev_list_dev_is_enabled(dev))
    463 					close_dev(dev);
    464 			}
    465 		} else {
    466 			audio_thread_disconnect_stream(audio_thread, rstream,
    467 						       NULL);
    468 		}
    469 	}
    470 	stream_list_suspended = 1;
    471 
    472 	DL_FOREACH(enabled_devs[CRAS_STREAM_OUTPUT], edev) {
    473 		close_dev(edev->dev);
    474 	}
    475 	DL_FOREACH(enabled_devs[CRAS_STREAM_INPUT], edev) {
    476 		close_dev(edev->dev);
    477 	}
    478 }
    479 
    480 static int stream_added_cb(struct cras_rstream *rstream);
    481 
    482 static void resume_devs()
    483 {
    484 	struct cras_rstream *rstream;
    485 
    486 	stream_list_suspended = 0;
    487 	DL_FOREACH(stream_list_get(stream_list), rstream)
    488 		stream_added_cb(rstream);
    489 }
    490 
    491 /* Called when the system audio is suspended or resumed. */
    492 void sys_suspend_change(void *arg, int suspended)
    493 {
    494 	if (suspended)
    495 		suspend_devs();
    496 	else
    497 		resume_devs();
    498 }
    499 
    500 /* Called when the system capture gain changes.  Pass the current capture_gain
    501  * setting to the default input if it is active. */
    502 void sys_cap_gain_change(void *context, int32_t gain)
    503 {
    504 	struct cras_iodev *dev;
    505 
    506 	DL_FOREACH(devs[CRAS_STREAM_INPUT].iodevs, dev) {
    507 		if (dev->set_capture_gain && cras_iodev_is_open(dev))
    508 			dev->set_capture_gain(dev);
    509 	}
    510 }
    511 
    512 /* Called when the system capture mute state changes.  Pass the current capture
    513  * mute setting to the default input if it is active. */
    514 static void sys_cap_mute_change(void *context, int muted, int mute_locked)
    515 {
    516 	struct cras_iodev *dev;
    517 
    518 	DL_FOREACH(devs[CRAS_STREAM_INPUT].iodevs, dev) {
    519 		if (dev->set_capture_mute && cras_iodev_is_open(dev))
    520 			dev->set_capture_mute(dev);
    521 	}
    522 }
    523 
    524 static int disable_device(struct enabled_dev *edev);
    525 static int enable_device(struct cras_iodev *dev);
    526 
    527 static void possibly_disable_fallback(enum CRAS_STREAM_DIRECTION dir)
    528 {
    529 	struct enabled_dev *edev;
    530 
    531 	DL_FOREACH(enabled_devs[dir], edev) {
    532 		if (edev->dev == fallback_devs[dir])
    533 			disable_device(edev);
    534 	}
    535 }
    536 
    537 static void possibly_enable_fallback(enum CRAS_STREAM_DIRECTION dir)
    538 {
    539 	if (!cras_iodev_list_dev_is_enabled(fallback_devs[dir]))
    540 		enable_device(fallback_devs[dir]);
    541 }
    542 
    543 static int init_and_attach_streams(struct cras_iodev *dev)
    544 {
    545 	int rc;
    546 	enum CRAS_STREAM_DIRECTION dir = dev->direction;
    547 	struct cras_rstream *stream;
    548 
    549 	/* If called after suspend, for example bluetooth
    550 	 * profile switching, don't add back the stream list. */
    551 	if (!stream_list_suspended) {
    552 		/* If there are active streams to attach to this device,
    553 		 * open it. */
    554 		DL_FOREACH(stream_list_get(stream_list), stream) {
    555 			if (stream->direction != dir || stream->is_pinned)
    556 				continue;
    557 			rc = init_device(dev, stream);
    558 			if (rc) {
    559 				syslog(LOG_ERR, "Enable %s failed, rc = %d",
    560 				       dev->info.name, rc);
    561 				return rc;
    562 			}
    563 			audio_thread_add_stream(audio_thread,
    564 						stream, &dev, 1);
    565 		}
    566 	}
    567 	return 0;
    568 }
    569 
    570 static void init_device_cb(struct cras_timer *timer, void *arg)
    571 {
    572 	int rc;
    573 	struct enabled_dev *edev = (struct enabled_dev *)arg;
    574 	struct cras_iodev *dev = edev->dev;
    575 
    576 	edev->init_timer = NULL;
    577 	if (cras_iodev_is_open(dev))
    578 		return;
    579 
    580 	rc = init_and_attach_streams(dev);
    581 	if (rc < 0)
    582 		syslog(LOG_ERR, "Init device retry failed");
    583 	else
    584 		possibly_disable_fallback(dev->direction);
    585 }
    586 
    587 static void schedule_init_device_retry(struct enabled_dev *edev)
    588 {
    589 	struct cras_tm *tm = cras_system_state_get_tm();
    590 
    591 	if (edev->init_timer == NULL)
    592 		edev->init_timer = cras_tm_create_timer(
    593 				tm, INIT_DEV_DELAY_MS, init_device_cb, edev);
    594 }
    595 
    596 static int pinned_stream_added(struct cras_rstream *rstream)
    597 {
    598 	struct cras_iodev *dev;
    599 	int rc;
    600 
    601 	/* Check that the target device is valid for pinned streams. */
    602 	dev = find_dev(rstream->pinned_dev_idx);
    603 	if (!dev)
    604 		return -EINVAL;
    605 
    606 	/* Make sure the active node is configured properly, it could be
    607 	 * disabled when last normal stream removed. */
    608 	dev->update_active_node(dev, dev->active_node->idx, 1);
    609 
    610 	/* Negative EAGAIN code indicates dev will be opened later. */
    611 	rc = init_device(dev, rstream);
    612 	if (rc && (rc != -EAGAIN))
    613 		return rc;
    614 
    615 	return audio_thread_add_stream(audio_thread, rstream, &dev, 1);
    616 }
    617 
    618 static int stream_added_cb(struct cras_rstream *rstream)
    619 {
    620 	struct enabled_dev *edev;
    621 	struct cras_iodev *iodevs[10];
    622 	unsigned int num_iodevs;
    623 	int rc;
    624 
    625 	if (stream_list_suspended)
    626 		return 0;
    627 
    628 	if (rstream->is_pinned)
    629 		return pinned_stream_added(rstream);
    630 
    631 	/* Add the new stream to all enabled iodevs at once to avoid offset
    632 	 * in shm level between different ouput iodevs. */
    633 	num_iodevs = 0;
    634 	DL_FOREACH(enabled_devs[rstream->direction], edev) {
    635 		if (num_iodevs >= ARRAY_SIZE(iodevs)) {
    636 			syslog(LOG_ERR, "too many enabled devices");
    637 			break;
    638 		}
    639 
    640 		rc = init_device(edev->dev, rstream);
    641 		if (rc) {
    642 			/* Error log but don't return error here, because
    643 			 * stopping audio could block video playback.
    644 			 */
    645 			syslog(LOG_ERR, "Init %s failed, rc = %d",
    646 			       edev->dev->info.name, rc);
    647 			schedule_init_device_retry(edev);
    648 			continue;
    649 		}
    650 
    651 		iodevs[num_iodevs++] = edev->dev;
    652 	}
    653 	if (num_iodevs) {
    654 		rc = audio_thread_add_stream(audio_thread, rstream,
    655 					     iodevs, num_iodevs);
    656 		if (rc) {
    657 			syslog(LOG_ERR, "adding stream to thread fail");
    658 			return rc;
    659 		}
    660 	} else {
    661 		/* Enable fallback device if no other iodevs can be initialized
    662 		 * successfully.
    663 		 * For error codes like EAGAIN and ENOENT, a new iodev will be
    664 		 * enabled soon so streams are going to route there. As for the
    665 		 * rest of the error cases, silence will be played or recorded
    666 		 * so client won't be blocked.
    667 		 * The enabled fallback device will be disabled when
    668 		 * cras_iodev_list_select_node() is called to re-select the
    669 		 * active node.
    670 		 */
    671 		possibly_enable_fallback(rstream->direction);
    672 	}
    673 	return 0;
    674 }
    675 
    676 static int possibly_close_enabled_devs(enum CRAS_STREAM_DIRECTION dir)
    677 {
    678 	struct enabled_dev *edev;
    679 	const struct cras_rstream *s;
    680 
    681 	/* Check if there are still default streams attached. */
    682 	DL_FOREACH(stream_list_get(stream_list), s) {
    683 		if (s->direction == dir && !s->is_pinned)
    684 			return 0;
    685 	}
    686 
    687 	/* No more default streams, close any device that doesn't have a stream
    688 	 * pinned to it. */
    689 	DL_FOREACH(enabled_devs[dir], edev) {
    690 		if (dev_has_pinned_stream(edev->dev->info.idx))
    691 			continue;
    692 		if (dir == CRAS_STREAM_INPUT) {
    693 			close_dev(edev->dev);
    694 			continue;
    695 		}
    696 		/* Allow output devs to drain before closing. */
    697 		clock_gettime(CLOCK_MONOTONIC_RAW, &edev->dev->idle_timeout);
    698 		add_timespecs(&edev->dev->idle_timeout, &idle_timeout_interval);
    699 		idle_dev_check(NULL, NULL);
    700 	}
    701 
    702 	return 0;
    703 }
    704 
    705 static void pinned_stream_removed(struct cras_rstream *rstream)
    706 {
    707 	struct cras_iodev *dev;
    708 
    709 	dev = find_dev(rstream->pinned_dev_idx);
    710 	if (!cras_iodev_list_dev_is_enabled(dev)) {
    711 		close_dev(dev);
    712 		dev->update_active_node(dev, dev->active_node->idx, 0);
    713 	}
    714 }
    715 
    716 /* Returns the number of milliseconds left to drain this stream.  This is passed
    717  * directly from the audio thread. */
    718 static int stream_removed_cb(struct cras_rstream *rstream)
    719 {
    720 	enum CRAS_STREAM_DIRECTION direction = rstream->direction;
    721 	int rc;
    722 
    723 	rc = audio_thread_drain_stream(audio_thread, rstream);
    724 	if (rc)
    725 		return rc;
    726 
    727 	if (rstream->is_pinned)
    728 		pinned_stream_removed(rstream);
    729 
    730 	possibly_close_enabled_devs(direction);
    731 
    732 	return 0;
    733 }
    734 
    735 static int enable_device(struct cras_iodev *dev)
    736 {
    737 	int rc;
    738 	struct enabled_dev *edev;
    739 	enum CRAS_STREAM_DIRECTION dir = dev->direction;
    740 
    741 	DL_FOREACH(enabled_devs[dir], edev) {
    742 		if (edev->dev == dev)
    743 			return -EEXIST;
    744 	}
    745 
    746 	edev = calloc(1, sizeof(*edev));
    747 	edev->dev = dev;
    748 	edev->init_timer = NULL;
    749 	DL_APPEND(enabled_devs[dir], edev);
    750 	dev->is_enabled = 1;
    751 
    752 	rc = init_and_attach_streams(dev);
    753 	if (rc < 0) {
    754 		schedule_init_device_retry(edev);
    755 		return rc;
    756 	}
    757 
    758 	if (device_enabled_callback)
    759 		device_enabled_callback(dev, 1, device_enabled_cb_data);
    760 
    761 	return 0;
    762 }
    763 
    764 static int disable_device(struct enabled_dev *edev)
    765 {
    766 	struct cras_iodev *dev = edev->dev;
    767 	enum CRAS_STREAM_DIRECTION dir = dev->direction;
    768 	struct cras_rstream *stream;
    769 
    770 	DL_DELETE(enabled_devs[dir], edev);
    771 	if (edev->init_timer) {
    772 		cras_tm_cancel_timer(cras_system_state_get_tm(),
    773 				     edev->init_timer);
    774 		edev->init_timer = NULL;
    775 	}
    776 	free(edev);
    777 	dev->is_enabled = 0;
    778 
    779 	/* Pull all default streams off this device. */
    780 	DL_FOREACH(stream_list_get(stream_list), stream) {
    781 		if (stream->direction != dev->direction || stream->is_pinned)
    782 			continue;
    783 		audio_thread_disconnect_stream(audio_thread, stream, dev);
    784 	}
    785 	if (device_enabled_callback)
    786 		device_enabled_callback(dev, 0, device_enabled_cb_data);
    787 	close_dev(dev);
    788 	dev->update_active_node(dev, dev->active_node->idx, 0);
    789 
    790 	return 0;
    791 }
    792 
    793 /*
    794  * Exported Interface.
    795  */
    796 
    797 void cras_iodev_list_init()
    798 {
    799 	struct cras_observer_ops observer_ops;
    800 
    801 	memset(&observer_ops, 0, sizeof(observer_ops));
    802 	observer_ops.output_volume_changed = sys_vol_change;
    803 	observer_ops.output_mute_changed = sys_mute_change;
    804 	observer_ops.capture_gain_changed = sys_cap_gain_change;
    805 	observer_ops.capture_mute_changed = sys_cap_mute_change;
    806 	observer_ops.suspend_changed = sys_suspend_change;
    807 	list_observer = cras_observer_add(&observer_ops, NULL);
    808 	idle_timer = NULL;
    809 
    810 	/* Create the audio stream list for the system. */
    811 	stream_list = stream_list_create(stream_added_cb, stream_removed_cb,
    812 					 cras_rstream_create,
    813 					 cras_rstream_destroy,
    814 					 cras_system_state_get_tm());
    815 
    816 	/* Add an empty device so there is always something to play to or
    817 	 * capture from. */
    818 	fallback_devs[CRAS_STREAM_OUTPUT] =
    819 			empty_iodev_create(CRAS_STREAM_OUTPUT);
    820 	fallback_devs[CRAS_STREAM_INPUT] =
    821 			empty_iodev_create(CRAS_STREAM_INPUT);
    822 	enable_device(fallback_devs[CRAS_STREAM_OUTPUT]);
    823 	enable_device(fallback_devs[CRAS_STREAM_INPUT]);
    824 
    825 	/* Create loopback devices. */
    826 	loopback_iodev_create(LOOPBACK_POST_MIX_PRE_DSP);
    827 	loopback_iodev_create(LOOPBACK_POST_DSP);
    828 
    829 	audio_thread = audio_thread_create();
    830 	if (!audio_thread) {
    831 		syslog(LOG_ERR, "Fatal: audio thread init");
    832 		exit(-ENOMEM);
    833 	}
    834 	audio_thread_start(audio_thread);
    835 
    836 	cras_iodev_list_update_device_list();
    837 }
    838 
    839 void cras_iodev_list_deinit()
    840 {
    841 	if (list_observer) {
    842 		cras_observer_remove(list_observer);
    843 		list_observer = NULL;
    844 	}
    845 	audio_thread_destroy(audio_thread);
    846 	stream_list_destroy(stream_list);
    847 }
    848 
    849 int cras_iodev_list_dev_is_enabled(const struct cras_iodev *dev)
    850 {
    851 	struct enabled_dev *edev;
    852 
    853 	DL_FOREACH(enabled_devs[dev->direction], edev) {
    854 		if (edev->dev == dev)
    855 			return 1;
    856 	}
    857 
    858 	return 0;
    859 }
    860 
    861 void cras_iodev_list_enable_dev(struct cras_iodev *dev)
    862 {
    863 	possibly_disable_fallback(dev->direction);
    864 	enable_device(dev);
    865 	cras_iodev_list_notify_active_node_changed(dev->direction);
    866 }
    867 
    868 void cras_iodev_list_add_active_node(enum CRAS_STREAM_DIRECTION dir,
    869 				     cras_node_id_t node_id)
    870 {
    871 	struct cras_iodev *new_dev;
    872 	new_dev = find_dev(dev_index_of(node_id));
    873 	if (!new_dev || new_dev->direction != dir)
    874 		return;
    875 
    876 	new_dev->update_active_node(new_dev, node_index_of(node_id), 1);
    877 	cras_iodev_list_enable_dev(new_dev);
    878 }
    879 
    880 void cras_iodev_list_disable_dev(struct cras_iodev *dev)
    881 {
    882 	struct enabled_dev *edev, *edev_to_disable = NULL;
    883 
    884 	int is_the_only_enabled_device = 1;
    885 
    886 	DL_FOREACH(enabled_devs[dev->direction], edev) {
    887 		if (edev->dev == dev)
    888 			edev_to_disable = edev;
    889 		else
    890 			is_the_only_enabled_device = 0;
    891 	}
    892 
    893 	if (!edev_to_disable)
    894 		return;
    895 
    896 	/* If the device to be closed is the only enabled device, we should
    897 	 * enable the fallback device first then disable the target
    898 	 * device. */
    899 	if (is_the_only_enabled_device)
    900 		enable_device(fallback_devs[dev->direction]);
    901 
    902 	disable_device(edev_to_disable);
    903 
    904 	cras_iodev_list_notify_active_node_changed(dev->direction);
    905 	return;
    906 }
    907 
    908 void cras_iodev_list_rm_active_node(enum CRAS_STREAM_DIRECTION dir,
    909 				    cras_node_id_t node_id)
    910 {
    911 	struct cras_iodev *dev;
    912 
    913 	dev = find_dev(dev_index_of(node_id));
    914 	if (!dev)
    915 		return;
    916 
    917 	cras_iodev_list_disable_dev(dev);
    918 }
    919 
    920 int cras_iodev_list_add_output(struct cras_iodev *output)
    921 {
    922 	int rc;
    923 
    924 	if (output->direction != CRAS_STREAM_OUTPUT)
    925 		return -EINVAL;
    926 
    927 	rc = add_dev_to_list(output);
    928 	if (rc)
    929 		return rc;
    930 
    931 	return 0;
    932 }
    933 
    934 int cras_iodev_list_add_input(struct cras_iodev *input)
    935 {
    936 	int rc;
    937 
    938 	if (input->direction != CRAS_STREAM_INPUT)
    939 		return -EINVAL;
    940 
    941 	rc = add_dev_to_list(input);
    942 	if (rc)
    943 		return rc;
    944 
    945 	return 0;
    946 }
    947 
    948 int cras_iodev_list_rm_output(struct cras_iodev *dev)
    949 {
    950 	int res;
    951 
    952 	/* Retire the current active output device before removing it from
    953 	 * list, otherwise it could be busy and remain in the list.
    954 	 */
    955 	cras_iodev_list_disable_dev(dev);
    956 	res = rm_dev_from_list(dev);
    957 	if (res == 0)
    958 		cras_iodev_list_update_device_list();
    959 	return res;
    960 }
    961 
    962 int cras_iodev_list_rm_input(struct cras_iodev *dev)
    963 {
    964 	int res;
    965 
    966 	/* Retire the current active input device before removing it from
    967 	 * list, otherwise it could be busy and remain in the list.
    968 	 */
    969 	cras_iodev_list_disable_dev(dev);
    970 	res = rm_dev_from_list(dev);
    971 	if (res == 0)
    972 		cras_iodev_list_update_device_list();
    973 	return res;
    974 }
    975 
    976 int cras_iodev_list_get_outputs(struct cras_iodev_info **list_out)
    977 {
    978 	return get_dev_list(&devs[CRAS_STREAM_OUTPUT], list_out);
    979 }
    980 
    981 int cras_iodev_list_get_inputs(struct cras_iodev_info **list_out)
    982 {
    983 	return get_dev_list(&devs[CRAS_STREAM_INPUT], list_out);
    984 }
    985 
    986 struct cras_iodev *cras_iodev_list_get_first_enabled_iodev(
    987 	enum CRAS_STREAM_DIRECTION direction)
    988 {
    989 	struct enabled_dev *edev = enabled_devs[direction];
    990 
    991 	return edev ? edev->dev : NULL;
    992 }
    993 
    994 cras_node_id_t cras_iodev_list_get_active_node_id(
    995 	enum CRAS_STREAM_DIRECTION direction)
    996 {
    997 	struct enabled_dev *edev = enabled_devs[direction];
    998 
    999 	if (!edev || !edev->dev || !edev->dev->active_node)
   1000 		return 0;
   1001 
   1002 	return cras_make_node_id(edev->dev->info.idx,
   1003 				 edev->dev->active_node->idx);
   1004 }
   1005 
   1006 void cras_iodev_list_update_device_list()
   1007 {
   1008 	struct cras_server_state *state;
   1009 
   1010 	state = cras_system_state_update_begin();
   1011 	if (!state)
   1012 		return;
   1013 
   1014 	state->num_output_devs = devs[CRAS_STREAM_OUTPUT].size;
   1015 	state->num_input_devs = devs[CRAS_STREAM_INPUT].size;
   1016 	fill_dev_list(&devs[CRAS_STREAM_OUTPUT], &state->output_devs[0],
   1017 		      CRAS_MAX_IODEVS);
   1018 	fill_dev_list(&devs[CRAS_STREAM_INPUT], &state->input_devs[0],
   1019 		      CRAS_MAX_IODEVS);
   1020 
   1021 	state->num_output_nodes = fill_node_list(&devs[CRAS_STREAM_OUTPUT],
   1022 						 &state->output_nodes[0],
   1023 						 CRAS_MAX_IONODES);
   1024 	state->num_input_nodes = fill_node_list(&devs[CRAS_STREAM_INPUT],
   1025 						&state->input_nodes[0],
   1026 						CRAS_MAX_IONODES);
   1027 
   1028 	cras_system_state_update_complete();
   1029 }
   1030 
   1031 char *cras_iodev_list_get_hotword_models(cras_node_id_t node_id)
   1032 {
   1033 	struct cras_iodev *dev = NULL;
   1034 
   1035 	dev = find_dev(dev_index_of(node_id));
   1036 	if (!dev || !dev->get_hotword_models ||
   1037 	    (dev->active_node->type != CRAS_NODE_TYPE_HOTWORD))
   1038 		return NULL;
   1039 
   1040 	return dev->get_hotword_models(dev);
   1041 }
   1042 
   1043 int cras_iodev_list_set_hotword_model(cras_node_id_t node_id,
   1044 				      const char *model_name)
   1045 {
   1046 	int ret;
   1047 	struct cras_iodev *dev =
   1048 			 find_dev(dev_index_of(node_id));
   1049 	if (!dev || !dev->get_hotword_models ||
   1050 	    (dev->active_node->type != CRAS_NODE_TYPE_HOTWORD))
   1051 		return -EINVAL;
   1052 
   1053 	ret = dev->set_hotword_model(dev, model_name);
   1054 	if (!ret)
   1055 		strncpy(dev->active_node->active_hotword_model, model_name,
   1056 			sizeof(dev->active_node->active_hotword_model) - 1);
   1057 	return ret;
   1058 }
   1059 
   1060 void cras_iodev_list_notify_nodes_changed()
   1061 {
   1062 	cras_observer_notify_nodes();
   1063 }
   1064 
   1065 void cras_iodev_list_notify_active_node_changed(
   1066 		enum CRAS_STREAM_DIRECTION direction)
   1067 {
   1068 	cras_observer_notify_active_node(direction,
   1069 			cras_iodev_list_get_active_node_id(direction));
   1070 }
   1071 
   1072 void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
   1073 				 cras_node_id_t node_id)
   1074 {
   1075 	struct cras_iodev *new_dev = NULL;
   1076 	struct enabled_dev *edev;
   1077         int new_node_already_enabled = 0;
   1078 	int rc;
   1079 
   1080 	/* find the devices for the id. */
   1081 	new_dev = find_dev(dev_index_of(node_id));
   1082 
   1083 	/* Do nothing if the direction is mismatched. The new_dev == NULL case
   1084 	   could happen if node_id is 0 (no selection), or the client tries
   1085 	   to select a non-existing node (maybe it's unplugged just before
   1086 	   the client selects it). We will just behave like there is no selected
   1087 	   node. */
   1088 	if (new_dev && new_dev->direction != direction)
   1089 		return;
   1090 
   1091 	/* Determine whether the new device and node are already enabled - if
   1092 	 * they are, the selection algorithm should avoid disabling the new
   1093 	 * device. */
   1094 	DL_FOREACH(enabled_devs[direction], edev) {
   1095 		if (edev->dev == new_dev &&
   1096 		    edev->dev->active_node->idx == node_index_of(node_id)) {
   1097 			new_node_already_enabled = 1;
   1098 			break;
   1099 		}
   1100 	}
   1101 
   1102 	/* Enable fallback device during the transition so client will not be
   1103 	 * blocked in this duration, which is as long as 300 ms on some boards
   1104 	 * before new device is opened.
   1105 	 * Note that the fallback node is not needed if the new node is already
   1106 	 * enabled - the new node will remain enabled. */
   1107 	if (!new_node_already_enabled)
   1108 		possibly_enable_fallback(direction);
   1109 
   1110 	/* Disable all devices except for fallback device, and the new device,
   1111 	 * provided it is already enabled. */
   1112 	DL_FOREACH(enabled_devs[direction], edev) {
   1113 		if (edev->dev != fallback_devs[direction] &&
   1114 		    !(new_node_already_enabled && edev->dev == new_dev)) {
   1115 			disable_device(edev);
   1116 		}
   1117 	}
   1118 
   1119 	if (new_dev && !new_node_already_enabled) {
   1120 		new_dev->update_active_node(new_dev, node_index_of(node_id), 1);
   1121 		rc = enable_device(new_dev);
   1122 		if (rc == 0) {
   1123 			/* Disable fallback device after new device is enabled.
   1124 			 * Leave the fallback device enabled if new_dev failed
   1125 			 * to open, or the new_dev == NULL case. */
   1126 			possibly_disable_fallback(direction);
   1127 		}
   1128 	}
   1129 
   1130 	cras_iodev_list_notify_active_node_changed(direction);
   1131 }
   1132 
   1133 int cras_iodev_list_set_node_attr(cras_node_id_t node_id,
   1134 				  enum ionode_attr attr, int value)
   1135 {
   1136 	struct cras_ionode *node;
   1137 	int rc;
   1138 
   1139 	node = find_node(node_id);
   1140 	if (!node)
   1141 		return -EINVAL;
   1142 
   1143 	rc = cras_iodev_set_node_attr(node, attr, value);
   1144 	return rc;
   1145 }
   1146 
   1147 void cras_iodev_list_notify_node_volume(struct cras_ionode *node)
   1148 {
   1149 	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
   1150 	cras_iodev_list_update_device_list();
   1151 	cras_observer_notify_output_node_volume(id, node->volume);
   1152 }
   1153 
   1154 void cras_iodev_list_notify_node_left_right_swapped(struct cras_ionode *node)
   1155 {
   1156 	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
   1157 	cras_iodev_list_update_device_list();
   1158 	cras_observer_notify_node_left_right_swapped(id,
   1159 						     node->left_right_swapped);
   1160 }
   1161 
   1162 void cras_iodev_list_notify_node_capture_gain(struct cras_ionode *node)
   1163 {
   1164 	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
   1165 	cras_iodev_list_update_device_list();
   1166 	cras_observer_notify_input_node_gain(id, node->capture_gain);
   1167 }
   1168 
   1169 void cras_iodev_list_add_test_dev(enum TEST_IODEV_TYPE type)
   1170 {
   1171 	if (type != TEST_IODEV_HOTWORD)
   1172 		return;
   1173 	test_iodev_create(CRAS_STREAM_INPUT, type);
   1174 }
   1175 
   1176 void cras_iodev_list_test_dev_command(unsigned int iodev_idx,
   1177 				      enum CRAS_TEST_IODEV_CMD command,
   1178 				      unsigned int data_len,
   1179 				      const uint8_t *data)
   1180 {
   1181 	struct cras_iodev *dev = find_dev(iodev_idx);
   1182 
   1183 	if (!dev)
   1184 		return;
   1185 
   1186 	test_iodev_command(dev, command, data_len, data);
   1187 }
   1188 
   1189 struct audio_thread *cras_iodev_list_get_audio_thread()
   1190 {
   1191 	return audio_thread;
   1192 }
   1193 
   1194 struct stream_list *cras_iodev_list_get_stream_list()
   1195 {
   1196 	return stream_list;
   1197 }
   1198 
   1199 int cras_iodev_list_set_device_enabled_callback(
   1200 		device_enabled_callback_t device_enabled_cb, void *cb_data)
   1201 {
   1202 	if (!device_enabled_cb) {
   1203 		device_enabled_callback = NULL;
   1204 		device_enabled_cb_data = NULL;
   1205 		return 0;
   1206 	}
   1207 
   1208 	/* TODO(chinyue): Allow multiple callbacks to be registered. */
   1209 	if (device_enabled_callback) {
   1210 		syslog(LOG_ERR, "Device enabled callback already registered.");
   1211 		return -EEXIST;
   1212 	}
   1213 
   1214 	device_enabled_callback = device_enabled_cb;
   1215 	device_enabled_cb_data = cb_data;
   1216 	return 0;
   1217 }
   1218 
   1219 void cras_iodev_list_reset()
   1220 {
   1221 	struct enabled_dev *edev;
   1222 
   1223 	DL_FOREACH(enabled_devs[CRAS_STREAM_OUTPUT], edev) {
   1224 		DL_DELETE(enabled_devs[CRAS_STREAM_OUTPUT], edev);
   1225 		free(edev);
   1226 	}
   1227 	enabled_devs[CRAS_STREAM_OUTPUT] = NULL;
   1228 	DL_FOREACH(enabled_devs[CRAS_STREAM_INPUT], edev) {
   1229 		DL_DELETE(enabled_devs[CRAS_STREAM_INPUT], edev);
   1230 		free(edev);
   1231 	}
   1232 	enabled_devs[CRAS_STREAM_INPUT] = NULL;
   1233 	devs[CRAS_STREAM_OUTPUT].iodevs = NULL;
   1234 	devs[CRAS_STREAM_INPUT].iodevs = NULL;
   1235 	devs[CRAS_STREAM_OUTPUT].size = 0;
   1236 	devs[CRAS_STREAM_INPUT].size = 0;
   1237 }
   1238