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 <pthread.h>
7 #include <stdbool.h>
8 #include <stdlib.h>
9 #include <sys/param.h>
10 #include <sys/time.h>
11 #include <syslog.h>
12 #include <time.h>
13 
14 #include "audio_thread.h"
15 #include "audio_thread_log.h"
16 #include "buffer_share.h"
17 #include "cras_audio_area.h"
18 #include "cras_audio_thread_monitor.h"
19 #include "cras_device_monitor.h"
20 #include "cras_dsp.h"
21 #include "cras_dsp_pipeline.h"
22 #include "cras_fmt_conv.h"
23 #include "cras_iodev.h"
24 #include "cras_main_thread_log.h"
25 #include "cras_iodev_list.h"
26 #include "cras_mix.h"
27 #include "cras_ramp.h"
28 #include "cras_rstream.h"
29 #include "cras_server_metrics.h"
30 #include "cras_system_state.h"
31 #include "cras_util.h"
32 #include "dev_stream.h"
33 #include "input_data.h"
34 #include "utlist.h"
35 #include "rate_estimator.h"
36 #include "softvol_curve.h"
37 
38 static const float RAMP_UNMUTE_DURATION_SECS = 0.5;
39 static const float RAMP_NEW_STREAM_DURATION_SECS = 0.01;
40 static const float RAMP_MUTE_DURATION_SECS = 0.1;
41 static const float RAMP_RESUME_MUTE_DURATION_SECS = 1;
42 static const float RAMP_SWITCH_MUTE_DURATION_SECS = 0.5;
43 static const float RAMP_VOLUME_CHANGE_DURATION_SECS = 0.1;
44 
45 /*
46  * It is the lastest time for the device to wake up when it is in the normal
47  * run state. It represents how many remaining frames in the device buffer.
48  */
49 static const struct timespec dev_normal_run_wake_up_time = {
50 	0, 1 * 1000 * 1000 /* 1 msec. */
51 };
52 
53 /*
54  * It is the lastest time for the device to wake up when it is in the no stream
55  * state. It represents how many remaining frames in the device buffer.
56  */
57 static const struct timespec dev_no_stream_wake_up_time = {
58 	0, 5 * 1000 * 1000 /* 5 msec. */
59 };
60 
61 /*
62  * Check issu b/72496547 and commit message for the history of
63  * rate estimator tuning.
64  */
65 static const struct timespec rate_estimation_window_sz = {
66 	5, 0 /* 5 sec. */
67 };
68 static const double rate_estimation_smooth_factor = 0.3f;
69 
70 static void cras_iodev_alloc_dsp(struct cras_iodev *iodev);
71 
default_no_stream_playback(struct cras_iodev * odev)72 static int default_no_stream_playback(struct cras_iodev *odev)
73 {
74 	int rc;
75 	unsigned int hw_level, fr_to_write;
76 	unsigned int target_hw_level = odev->min_cb_level * 2;
77 	struct timespec hw_tstamp;
78 
79 	/* The default action for no stream playback is to fill zeros. */
80 	rc = cras_iodev_frames_queued(odev, &hw_tstamp);
81 	if (rc < 0)
82 		return rc;
83 	hw_level = rc;
84 
85 	/* If underrun happened, handle underrun and get hw_level again. */
86 	if (hw_level == 0) {
87 		rc = cras_iodev_output_underrun(odev, hw_level, 0);
88 		if (rc < 0)
89 			return rc;
90 
91 		rc = cras_iodev_frames_queued(odev, &hw_tstamp);
92 		if (rc < 0)
93 			return rc;
94 		hw_level = rc;
95 	}
96 
97 	ATLOG(atlog, AUDIO_THREAD_ODEV_DEFAULT_NO_STREAMS, odev->info.idx,
98 	      hw_level, target_hw_level);
99 
100 	fr_to_write = cras_iodev_buffer_avail(odev, hw_level);
101 	if (hw_level <= target_hw_level) {
102 		fr_to_write = MIN(target_hw_level - hw_level, fr_to_write);
103 		return cras_iodev_fill_odev_zeros(odev, fr_to_write);
104 	}
105 	return 0;
106 }
107 
cras_iodev_start(struct cras_iodev * iodev)108 static int cras_iodev_start(struct cras_iodev *iodev)
109 {
110 	int rc;
111 	if (!cras_iodev_is_open(iodev))
112 		return -EPERM;
113 	if (!iodev->start) {
114 		syslog(LOG_ERR,
115 		       "start called on device %s not supporting start ops",
116 		       iodev->info.name);
117 		return -EINVAL;
118 	}
119 	rc = iodev->start(iodev);
120 	if (rc)
121 		return rc;
122 	iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
123 	return 0;
124 }
125 
126 /* Gets the number of frames ready for this device to play.
127  * It is the minimum number of available samples in dev_streams.
128  */
dev_playback_frames(struct cras_iodev * odev)129 static unsigned int dev_playback_frames(struct cras_iodev *odev)
130 {
131 	struct dev_stream *curr;
132 	int frames = 0;
133 
134 	DL_FOREACH (odev->streams, curr) {
135 		int dev_frames;
136 
137 		/* Skip stream which hasn't started running yet. */
138 		if (!dev_stream_is_running(curr))
139 			continue;
140 
141 		/* If this is a single output dev stream, updates the latest
142 		 * number of frames for playback. */
143 		if (dev_stream_attached_devs(curr) == 1)
144 			dev_stream_update_frames(curr);
145 
146 		dev_frames = dev_stream_playback_frames(curr);
147 		/* Do not handle stream error or end of draining in this
148 		 * function because they should be handled in write_streams. */
149 		if (dev_frames < 0)
150 			continue;
151 		if (!dev_frames) {
152 			if (cras_rstream_get_is_draining(curr->stream))
153 				continue;
154 			else
155 				return 0;
156 		}
157 		if (frames == 0)
158 			frames = dev_frames;
159 		else
160 			frames = MIN(dev_frames, frames);
161 	}
162 	return frames;
163 }
164 
165 /* Let device enter/leave no stream playback.
166  * Args:
167  *    iodev[in] - The output device.
168  *    enable[in] - 1 to enter no stream playback, 0 to leave.
169  * Returns:
170  *    0 on success. Negative error code on failure.
171  */
cras_iodev_no_stream_playback_transition(struct cras_iodev * odev,int enable)172 static int cras_iodev_no_stream_playback_transition(struct cras_iodev *odev,
173 						    int enable)
174 {
175 	int rc;
176 
177 	if (odev->direction != CRAS_STREAM_OUTPUT)
178 		return -EINVAL;
179 
180 	/* This function is for transition between normal run and
181 	 * no stream run state.
182 	 */
183 	if ((odev->state != CRAS_IODEV_STATE_NORMAL_RUN) &&
184 	    (odev->state != CRAS_IODEV_STATE_NO_STREAM_RUN))
185 		return -EINVAL;
186 
187 	if (enable) {
188 		ATLOG(atlog, AUDIO_THREAD_ODEV_NO_STREAMS, odev->info.idx, 0,
189 		      0);
190 	} else {
191 		ATLOG(atlog, AUDIO_THREAD_ODEV_LEAVE_NO_STREAMS, odev->info.idx,
192 		      0, 0);
193 	}
194 
195 	rc = odev->no_stream(odev, enable);
196 	if (rc < 0)
197 		return rc;
198 	if (enable)
199 		odev->state = CRAS_IODEV_STATE_NO_STREAM_RUN;
200 	else
201 		odev->state = CRAS_IODEV_STATE_NORMAL_RUN;
202 	return 0;
203 }
204 
205 /* Determines if the output device should mute. It considers system mute,
206  * system volume, and active node volume on the device. */
output_should_mute(struct cras_iodev * odev)207 static int output_should_mute(struct cras_iodev *odev)
208 {
209 	/* System mute has highest priority. */
210 	if (cras_system_get_mute())
211 		return 1;
212 
213 	/* consider system volume and active node volume. */
214 	return cras_iodev_is_zero_volume(odev);
215 }
216 
cras_iodev_is_zero_volume(const struct cras_iodev * odev)217 int cras_iodev_is_zero_volume(const struct cras_iodev *odev)
218 {
219 	size_t system_volume;
220 	unsigned int adjusted_node_volume;
221 
222 	system_volume = cras_system_get_volume();
223 	if (odev->active_node) {
224 		adjusted_node_volume = cras_iodev_adjust_node_volume(
225 			odev->active_node, system_volume);
226 		return (adjusted_node_volume == 0);
227 	}
228 	return (system_volume == 0);
229 }
230 
231 /* Output device state transition diagram:
232  *
233  *                           ----------------
234  *  -------------<-----------| S0  Closed   |------<-------.
235  *  |                        ----------------              |
236  *  |                           |   iodev_list enables     |
237  *  |                           |   device and adds to     |
238  *  |                           V   audio thread           | iodev_list removes
239  *  |                        ----------------              | device from
240  *  |                        | S1  Open     |              | audio_thread and
241  *  |                        ----------------              | closes device
242  *  | Device with empty start       |                      |
243  *  | ops transits into             | Sample is ready      |
244  *  | no stream state right         V                      |
245  *  | after open.            ----------------              |
246  *  |                        | S2  Normal   |              |
247  *  |                        ----------------              |
248  *  |                           |        ^                 |
249  *  |       There is no stream  |        | Sample is ready |
250  *  |                           V        |                 |
251  *  |                        ----------------              |
252  *  ------------->-----------| S3 No Stream |------->------
253  *                           ----------------
254  *
255  *  Device in open_devs can be in one of S1, S2, S3.
256  *
257  * cras_iodev_output_event_sample_ready change device state from S1 or S3 into
258  * S2.
259  */
cras_iodev_output_event_sample_ready(struct cras_iodev * odev)260 static int cras_iodev_output_event_sample_ready(struct cras_iodev *odev)
261 {
262 	if (odev->state == CRAS_IODEV_STATE_OPEN ||
263 	    odev->state == CRAS_IODEV_STATE_NO_STREAM_RUN) {
264 		/* Starts ramping up if device should not be muted.
265 		 * Both mute and volume are taken into consideration.
266 		 */
267 		if (odev->ramp && !output_should_mute(odev)) {
268 			cras_iodev_start_ramp(odev, odev->initial_ramp_request);
269 		}
270 	}
271 
272 	if (odev->state == CRAS_IODEV_STATE_OPEN) {
273 		/* S1 => S2:
274 		 * If device is not started yet, and there is sample ready from
275 		 * stream, fill 1 min_cb_level of zeros first and fill sample
276 		 * from stream later.
277 		 * Starts the device here to finish state transition. */
278 		cras_iodev_fill_odev_zeros(odev, odev->min_cb_level);
279 		ATLOG(atlog, AUDIO_THREAD_ODEV_START, odev->info.idx,
280 		      odev->min_cb_level, 0);
281 		return cras_iodev_start(odev);
282 	} else if (odev->state == CRAS_IODEV_STATE_NO_STREAM_RUN) {
283 		/* S3 => S2:
284 		 * Device in no stream state get sample ready. Leave no stream
285 		 * state and transit to normal run state.*/
286 		return cras_iodev_no_stream_playback_transition(odev, 0);
287 	} else {
288 		syslog(LOG_ERR,
289 		       "Device %s in state %d received sample ready event",
290 		       odev->info.name, odev->state);
291 		return -EINVAL;
292 	}
293 	return 0;
294 }
295 
296 /*
297  * Exported Interface.
298  */
299 
300 /* Finds the supported sample rate that best suits the requested rate, "rrate".
301  * Exact matches have highest priority, then integer multiples, then the default
302  * rate for the device. */
get_best_rate(struct cras_iodev * iodev,size_t rrate)303 static size_t get_best_rate(struct cras_iodev *iodev, size_t rrate)
304 {
305 	size_t i;
306 	size_t best;
307 
308 	if (iodev->supported_rates[0] == 0) /* No rates supported */
309 		return 0;
310 
311 	for (i = 0, best = 0; iodev->supported_rates[i] != 0; i++) {
312 		if (rrate == iodev->supported_rates[i] && rrate >= 44100)
313 			return rrate;
314 		if (best == 0 && (rrate % iodev->supported_rates[i] == 0 ||
315 				  iodev->supported_rates[i] % rrate == 0))
316 			best = iodev->supported_rates[i];
317 	}
318 
319 	if (best)
320 		return best;
321 	return iodev->supported_rates[0];
322 }
323 
324 /* Finds the best match for the channel count.  The following match rules
325  * will apply in order and return the value once matched:
326  * 1. Match the exact given channel count.
327  * 2. Match the preferred channel count.
328  * 3. The first channel count in the list.
329  */
get_best_channel_count(struct cras_iodev * iodev,size_t count)330 static size_t get_best_channel_count(struct cras_iodev *iodev, size_t count)
331 {
332 	static const size_t preferred_channel_count = 2;
333 	size_t i;
334 
335 	assert(iodev->supported_channel_counts[0] != 0);
336 
337 	for (i = 0; iodev->supported_channel_counts[i] != 0; i++) {
338 		if (iodev->supported_channel_counts[i] == count)
339 			return count;
340 	}
341 
342 	/* If provided count is not supported, search for preferred
343 	 * channel count to which we're good at converting.
344 	 */
345 	for (i = 0; iodev->supported_channel_counts[i] != 0; i++) {
346 		if (iodev->supported_channel_counts[i] ==
347 		    preferred_channel_count)
348 			return preferred_channel_count;
349 	}
350 
351 	return iodev->supported_channel_counts[0];
352 }
353 
354 /* finds the best match for the current format. If no exact match is
355  * found, use the first. */
get_best_pcm_format(struct cras_iodev * iodev,snd_pcm_format_t fmt)356 static snd_pcm_format_t get_best_pcm_format(struct cras_iodev *iodev,
357 					    snd_pcm_format_t fmt)
358 {
359 	size_t i;
360 
361 	for (i = 0; iodev->supported_formats[i] != 0; i++) {
362 		if (fmt == iodev->supported_formats[i])
363 			return fmt;
364 	}
365 
366 	return iodev->supported_formats[0];
367 }
368 
369 /* Applies the DSP to the samples for the iodev if applicable. */
apply_dsp(struct cras_iodev * iodev,uint8_t * buf,size_t frames)370 static int apply_dsp(struct cras_iodev *iodev, uint8_t *buf, size_t frames)
371 {
372 	struct cras_dsp_context *ctx;
373 	struct pipeline *pipeline;
374 	int rc;
375 
376 	ctx = iodev->dsp_context;
377 	if (!ctx)
378 		return 0;
379 
380 	pipeline = cras_dsp_get_pipeline(ctx);
381 	if (!pipeline)
382 		return 0;
383 
384 	rc = cras_dsp_pipeline_apply(pipeline, buf, iodev->format->format,
385 				     frames);
386 
387 	cras_dsp_put_pipeline(ctx);
388 	return rc;
389 }
390 
cras_iodev_free_dsp(struct cras_iodev * iodev)391 static void cras_iodev_free_dsp(struct cras_iodev *iodev)
392 {
393 	if (iodev->dsp_context) {
394 		cras_dsp_context_free(iodev->dsp_context);
395 		iodev->dsp_context = NULL;
396 	}
397 }
398 
399 /* Modifies the number of channels in device format to the one that will be
400  * presented to the device after any channel changes from the DSP. */
adjust_dev_channel_for_dsp(const struct cras_iodev * iodev)401 static inline void adjust_dev_channel_for_dsp(const struct cras_iodev *iodev)
402 {
403 	struct cras_dsp_context *ctx = iodev->dsp_context;
404 
405 	if (!ctx || !cras_dsp_get_pipeline(ctx))
406 		return;
407 
408 	if (iodev->direction == CRAS_STREAM_OUTPUT)
409 		iodev->format->num_channels = cras_dsp_num_output_channels(ctx);
410 	else
411 		iodev->format->num_channels = cras_dsp_num_input_channels(ctx);
412 
413 	cras_dsp_put_pipeline(ctx);
414 }
415 
416 /* Updates channel layout based on the number of channels set by a
417  * client stream. Set a default value to format if the update call
418  * fails.
419  */
update_channel_layout(struct cras_iodev * iodev)420 static void update_channel_layout(struct cras_iodev *iodev)
421 {
422 	int rc;
423 
424 	if (iodev->update_channel_layout == NULL)
425 		return;
426 
427 	rc = iodev->update_channel_layout(iodev);
428 	if (rc < 0)
429 		cras_audio_format_set_default_channel_layout(iodev->format);
430 }
431 
432 /*
433  * For the specified format, removes any channels from the channel layout that
434  * are higher than the supported number of channels. Should be used when the
435  * number of channels of the format been reduced.
436  */
trim_channel_layout(struct cras_audio_format * fmt)437 static void trim_channel_layout(struct cras_audio_format *fmt)
438 {
439 	int i;
440 	for (i = 0; i < CRAS_CH_MAX; i++)
441 		if (fmt->channel_layout[i] >= fmt->num_channels)
442 			fmt->channel_layout[i] = -1;
443 }
444 
cras_iodev_set_format(struct cras_iodev * iodev,const struct cras_audio_format * fmt)445 int cras_iodev_set_format(struct cras_iodev *iodev,
446 			  const struct cras_audio_format *fmt)
447 {
448 	size_t actual_rate, actual_num_channels;
449 	snd_pcm_format_t actual_format;
450 	int rc;
451 
452 	/* Update supported formats on iodev before negotiating the final value
453 	 * with what stream requested.
454 	 */
455 	if (iodev->update_supported_formats) {
456 		rc = iodev->update_supported_formats(iodev);
457 		if (rc) {
458 			syslog(LOG_ERR, "Failed to update formats");
459 			return rc;
460 		}
461 	}
462 
463 	/* If this device isn't already using a format, try to match the one
464 	 * requested in "fmt". */
465 	if (iodev->format == NULL) {
466 		iodev->format = malloc(sizeof(struct cras_audio_format));
467 		if (!iodev->format)
468 			return -ENOMEM;
469 		*iodev->format = *fmt;
470 
471 		/* Finds the actual rate of device before allocating DSP
472 		 * because DSP needs to use the rate of device, not rate of
473 		 * stream. */
474 		actual_rate = get_best_rate(iodev, fmt->frame_rate);
475 		iodev->format->frame_rate = actual_rate;
476 
477 		cras_iodev_alloc_dsp(iodev);
478 		cras_iodev_update_dsp(iodev);
479 		if (iodev->dsp_context)
480 			adjust_dev_channel_for_dsp(iodev);
481 
482 		actual_num_channels = get_best_channel_count(
483 			iodev, iodev->format->num_channels);
484 		actual_format = get_best_pcm_format(iodev, fmt->format);
485 		if (actual_rate == 0 || actual_num_channels == 0 ||
486 		    actual_format == 0) {
487 			/* No compatible frame rate found. */
488 			rc = -EINVAL;
489 			goto error;
490 		}
491 		iodev->format->format = actual_format;
492 		if (iodev->format->num_channels != actual_num_channels) {
493 			/* If the DSP for this device doesn't match, drop it. */
494 			iodev->format->num_channels = actual_num_channels;
495 			trim_channel_layout(iodev->format);
496 			cras_iodev_free_dsp(iodev);
497 		}
498 
499 		update_channel_layout(iodev);
500 
501 		if (!iodev->rate_est)
502 			iodev->rate_est = rate_estimator_create(
503 				actual_rate, &rate_estimation_window_sz,
504 				rate_estimation_smooth_factor);
505 		else
506 			rate_estimator_reset_rate(iodev->rate_est, actual_rate);
507 	}
508 
509 	return 0;
510 
511 error:
512 	free(iodev->format);
513 	iodev->format = NULL;
514 	return rc;
515 }
516 
517 /*
518  * Configures the external dsp module and adds it to the existing dsp pipeline.
519  */
add_ext_dsp_module_to_pipeline(struct cras_iodev * iodev)520 static void add_ext_dsp_module_to_pipeline(struct cras_iodev *iodev)
521 {
522 	struct pipeline *pipeline;
523 
524 	pipeline = iodev->dsp_context ?
525 			   cras_dsp_get_pipeline(iodev->dsp_context) :
526 			   NULL;
527 
528 	if (!pipeline) {
529 		cras_iodev_alloc_dsp(iodev);
530 		cras_dsp_load_mock_pipeline(iodev->dsp_context,
531 					    iodev->format->num_channels);
532 		pipeline = cras_dsp_get_pipeline(iodev->dsp_context);
533 	}
534 	/* dsp_context mutex locked. Now it's safe to modify dsp
535 	 * pipeline resources. */
536 
537 	if (iodev->ext_dsp_module)
538 		iodev->ext_dsp_module->configure(iodev->ext_dsp_module,
539 						 iodev->buffer_size,
540 						 iodev->format->num_channels,
541 						 iodev->format->frame_rate);
542 
543 	cras_dsp_pipeline_set_sink_ext_module(pipeline, iodev->ext_dsp_module);
544 
545 	/* Unlock dsp_context mutex. */
546 	cras_dsp_put_pipeline(iodev->dsp_context);
547 }
548 
549 /*
550  * Releases the ext_dsp_module if it ever added to iodev's dsp pipeline.
551  */
release_ext_dsp_module_from_pipeline(struct cras_iodev * iodev)552 static void release_ext_dsp_module_from_pipeline(struct cras_iodev *iodev)
553 {
554 	struct pipeline *pipeline;
555 
556 	if (iodev->dsp_context == NULL)
557 		return;
558 
559 	pipeline = cras_dsp_get_pipeline(iodev->dsp_context);
560 	if (pipeline == NULL)
561 		return;
562 	/* dsp_context mutex locked. */
563 
564 	cras_dsp_pipeline_set_sink_ext_module(pipeline, NULL);
565 
566 	/* Unlock dsp_context mutex. */
567 	cras_dsp_put_pipeline(iodev->dsp_context);
568 }
569 
cras_iodev_set_ext_dsp_module(struct cras_iodev * iodev,struct ext_dsp_module * ext)570 void cras_iodev_set_ext_dsp_module(struct cras_iodev *iodev,
571 				   struct ext_dsp_module *ext)
572 {
573 	iodev->ext_dsp_module = ext;
574 
575 	if (!cras_iodev_is_open(iodev))
576 		return;
577 
578 	if (iodev->ext_dsp_module)
579 		add_ext_dsp_module_to_pipeline(iodev);
580 	else
581 		release_ext_dsp_module_from_pipeline(iodev);
582 }
583 
cras_iodev_update_dsp(struct cras_iodev * iodev)584 void cras_iodev_update_dsp(struct cras_iodev *iodev)
585 {
586 	char swap_lr_disabled = 1;
587 
588 	if (!iodev->dsp_context)
589 		return;
590 
591 	cras_dsp_set_variable_string(iodev->dsp_context, "dsp_name",
592 				     iodev->dsp_name ?: "");
593 
594 	if (iodev->active_node && iodev->active_node->left_right_swapped)
595 		swap_lr_disabled = 0;
596 
597 	cras_dsp_set_variable_boolean(iodev->dsp_context, "swap_lr_disabled",
598 				      swap_lr_disabled);
599 
600 	cras_dsp_load_pipeline(iodev->dsp_context);
601 }
602 
cras_iodev_dsp_set_swap_mode_for_node(struct cras_iodev * iodev,struct cras_ionode * node,int enable)603 int cras_iodev_dsp_set_swap_mode_for_node(struct cras_iodev *iodev,
604 					  struct cras_ionode *node, int enable)
605 {
606 	if (node->left_right_swapped == enable)
607 		return 0;
608 
609 	/* Sets left_right_swapped property on the node. It will be used
610 	 * when cras_iodev_update_dsp is called. */
611 	node->left_right_swapped = enable;
612 
613 	/* Possibly updates dsp if the node is active on the device and there
614 	 * is dsp context. If dsp context is not created yet,
615 	 * cras_iodev_update_dsp returns right away. */
616 	if (iodev->active_node == node)
617 		cras_iodev_update_dsp(iodev);
618 	return 0;
619 }
620 
cras_iodev_free_format(struct cras_iodev * iodev)621 void cras_iodev_free_format(struct cras_iodev *iodev)
622 {
623 	free(iodev->format);
624 	iodev->format = NULL;
625 }
626 
cras_iodev_init_audio_area(struct cras_iodev * iodev,int num_channels)627 void cras_iodev_init_audio_area(struct cras_iodev *iodev, int num_channels)
628 {
629 	if (iodev->area)
630 		cras_iodev_free_audio_area(iodev);
631 
632 	iodev->area = cras_audio_area_create(num_channels);
633 	cras_audio_area_config_channels(iodev->area, iodev->format);
634 }
635 
cras_iodev_free_audio_area(struct cras_iodev * iodev)636 void cras_iodev_free_audio_area(struct cras_iodev *iodev)
637 {
638 	if (!iodev->area)
639 		return;
640 
641 	cras_audio_area_destroy(iodev->area);
642 	iodev->area = NULL;
643 }
644 
cras_iodev_free_resources(struct cras_iodev * iodev)645 void cras_iodev_free_resources(struct cras_iodev *iodev)
646 {
647 	cras_iodev_free_dsp(iodev);
648 	rate_estimator_destroy(iodev->rate_est);
649 	if (iodev->ramp)
650 		cras_ramp_destroy(iodev->ramp);
651 }
652 
cras_iodev_alloc_dsp(struct cras_iodev * iodev)653 static void cras_iodev_alloc_dsp(struct cras_iodev *iodev)
654 {
655 	const char *purpose;
656 
657 	if (iodev->direction == CRAS_STREAM_OUTPUT)
658 		purpose = "playback";
659 	else
660 		purpose = "capture";
661 
662 	cras_iodev_free_dsp(iodev);
663 	iodev->dsp_context =
664 		cras_dsp_context_new(iodev->format->frame_rate, purpose);
665 }
666 
cras_iodev_fill_time_from_frames(size_t frames,size_t frame_rate,struct timespec * ts)667 void cras_iodev_fill_time_from_frames(size_t frames, size_t frame_rate,
668 				      struct timespec *ts)
669 {
670 	uint64_t to_play_usec;
671 
672 	ts->tv_sec = 0;
673 	/* adjust sleep time to target our callback threshold */
674 	to_play_usec = (uint64_t)frames * 1000000L / (uint64_t)frame_rate;
675 
676 	while (to_play_usec > 1000000) {
677 		ts->tv_sec++;
678 		to_play_usec -= 1000000;
679 	}
680 	ts->tv_nsec = to_play_usec * 1000;
681 }
682 
683 /* This is called when a node is plugged/unplugged */
cras_iodev_set_node_plugged(struct cras_ionode * node,int plugged)684 void cras_iodev_set_node_plugged(struct cras_ionode *node, int plugged)
685 {
686 	if (node->plugged == plugged)
687 		return;
688 	node->plugged = plugged;
689 	MAINLOG(main_log, MAIN_THREAD_NODE_PLUGGED, node->dev->info.idx,
690 		plugged, 0);
691 	if (plugged) {
692 		gettimeofday(&node->plugged_time, NULL);
693 	} else if (node == node->dev->active_node) {
694 		/*
695 		 * Remove normal and pinned streams, when node unplugged.
696 		 * TODO(hychao): clean this up, per crbug.com/1006646
697 		 */
698 		cras_iodev_list_disable_dev(node->dev, true);
699 	}
700 	cras_iodev_list_notify_nodes_changed();
701 }
702 
cras_iodev_add_node(struct cras_iodev * iodev,struct cras_ionode * node)703 void cras_iodev_add_node(struct cras_iodev *iodev, struct cras_ionode *node)
704 {
705 	DL_APPEND(iodev->nodes, node);
706 	cras_iodev_list_notify_nodes_changed();
707 }
708 
cras_iodev_rm_node(struct cras_iodev * iodev,struct cras_ionode * node)709 void cras_iodev_rm_node(struct cras_iodev *iodev, struct cras_ionode *node)
710 {
711 	DL_DELETE(iodev->nodes, node);
712 	cras_iodev_list_notify_nodes_changed();
713 }
714 
cras_iodev_set_active_node(struct cras_iodev * iodev,struct cras_ionode * node)715 void cras_iodev_set_active_node(struct cras_iodev *iodev,
716 				struct cras_ionode *node)
717 {
718 	iodev->active_node = node;
719 	cras_iodev_list_notify_active_node_changed(iodev->direction);
720 }
721 
cras_iodev_is_aec_use_case(const struct cras_ionode * node)722 bool cras_iodev_is_aec_use_case(const struct cras_ionode *node)
723 {
724 	if ((node->type == CRAS_NODE_TYPE_INTERNAL_SPEAKER) ||
725 	    (node->type == CRAS_NODE_TYPE_ECHO_REFERENCE))
726 		return true;
727 
728 	if (node->type == CRAS_NODE_TYPE_MIC)
729 		return (node->position == NODE_POSITION_INTERNAL) ||
730 		       (node->position == NODE_POSITION_FRONT);
731 
732 	return false;
733 }
734 
cras_iodev_is_on_internal_card(const struct cras_ionode * node)735 bool cras_iodev_is_on_internal_card(const struct cras_ionode *node)
736 {
737 	if (node->type == CRAS_NODE_TYPE_INTERNAL_SPEAKER)
738 		return true;
739 	if (node->type == CRAS_NODE_TYPE_HEADPHONE)
740 		return true;
741 	if (node->type == CRAS_NODE_TYPE_MIC)
742 		return true;
743 	return false;
744 }
745 
cras_iodev_get_software_volume_scaler(struct cras_iodev * iodev)746 float cras_iodev_get_software_volume_scaler(struct cras_iodev *iodev)
747 {
748 	unsigned int volume;
749 
750 	volume = cras_iodev_adjust_active_node_volume(iodev,
751 						      cras_system_get_volume());
752 
753 	if (iodev->active_node && iodev->active_node->softvol_scalers)
754 		return iodev->active_node->softvol_scalers[volume];
755 	return softvol_get_scaler(volume);
756 }
757 
cras_iodev_get_software_gain_scaler(const struct cras_iodev * iodev)758 float cras_iodev_get_software_gain_scaler(const struct cras_iodev *iodev)
759 {
760 	if (cras_iodev_software_volume_needed(iodev))
761 		return convert_softvol_scaler_from_dB(
762 			iodev->active_node->capture_gain);
763 	return 1.0f;
764 }
765 
cras_iodev_get_valid_frames(struct cras_iodev * odev,struct timespec * hw_tstamp)766 int cras_iodev_get_valid_frames(struct cras_iodev *odev,
767 				struct timespec *hw_tstamp)
768 {
769 	int rc;
770 
771 	if (odev->direction != CRAS_STREAM_OUTPUT)
772 		return -EINVAL;
773 
774 	if (odev->get_valid_frames) {
775 		rc = odev->get_valid_frames(odev, hw_tstamp);
776 		if (rc < 0)
777 			return rc;
778 
779 		if (rc < odev->min_buffer_level)
780 			return 0;
781 
782 		return rc - odev->min_buffer_level;
783 	} else {
784 		return cras_iodev_frames_queued(odev, hw_tstamp);
785 	}
786 }
787 
cras_iodev_add_stream(struct cras_iodev * iodev,struct dev_stream * stream)788 int cras_iodev_add_stream(struct cras_iodev *iodev, struct dev_stream *stream)
789 {
790 	/*
791 	 * For input stream, start stream right after adding stream.
792 	 * For output stream, start stream after its first fetch such that it does not
793 	 * block other existing streams.
794 	 */
795 	DL_APPEND(iodev->streams, stream);
796 	if (!iodev->buf_state)
797 		iodev->buf_state = buffer_share_create(iodev->buffer_size);
798 	if (stream->stream->direction == CRAS_STREAM_INPUT)
799 		cras_iodev_start_stream(iodev, stream);
800 	return 0;
801 }
802 
cras_iodev_start_stream(struct cras_iodev * iodev,struct dev_stream * stream)803 void cras_iodev_start_stream(struct cras_iodev *iodev,
804 			     struct dev_stream *stream)
805 {
806 	unsigned int cb_threshold = dev_stream_cb_threshold(stream);
807 
808 	if (dev_stream_is_running(stream))
809 		return;
810 	/*
811 	 * TRIGGER_ONLY streams do not want to receive data, so do not add them
812 	 * to buffer_share, otherwise they'll affect other streams to receive.
813 	 */
814 	if (!(stream->stream->flags & TRIGGER_ONLY))
815 		buffer_share_add_id(iodev->buf_state, stream->stream->stream_id,
816 				    NULL);
817 	iodev->min_cb_level = MIN(iodev->min_cb_level, cb_threshold);
818 	iodev->max_cb_level = MAX(iodev->max_cb_level, cb_threshold);
819 	iodev->largest_cb_level = MAX(iodev->largest_cb_level, cb_threshold);
820 	dev_stream_set_running(stream);
821 }
822 
cras_iodev_rm_stream(struct cras_iodev * iodev,const struct cras_rstream * rstream)823 struct dev_stream *cras_iodev_rm_stream(struct cras_iodev *iodev,
824 					const struct cras_rstream *rstream)
825 {
826 	struct dev_stream *out;
827 	struct dev_stream *ret = NULL;
828 	unsigned int cb_threshold;
829 	struct timespec earliest_next_cb_ts;
830 	int set_earliest = 0;
831 
832 	iodev->min_cb_level = iodev->buffer_size / 2;
833 	iodev->max_cb_level = 0;
834 	DL_FOREACH (iodev->streams, out) {
835 		if (out->stream == rstream) {
836 			buffer_share_rm_id(iodev->buf_state,
837 					   rstream->stream_id);
838 			ret = out;
839 			DL_DELETE(iodev->streams, out);
840 			continue;
841 		}
842 		if (!dev_stream_is_running(out))
843 			continue;
844 		cb_threshold = dev_stream_cb_threshold(out);
845 		iodev->min_cb_level = MIN(iodev->min_cb_level, cb_threshold);
846 		iodev->max_cb_level = MAX(iodev->max_cb_level, cb_threshold);
847 		if (!set_earliest) {
848 			set_earliest = 1;
849 			earliest_next_cb_ts = out->stream->next_cb_ts;
850 		}
851 		if (timespec_after(&earliest_next_cb_ts,
852 				   &out->stream->next_cb_ts))
853 			earliest_next_cb_ts = out->stream->next_cb_ts;
854 	}
855 
856 	if (!iodev->streams) {
857 		buffer_share_destroy(iodev->buf_state);
858 		iodev->buf_state = NULL;
859 		iodev->min_cb_level = iodev->buffer_size / 2;
860 		/* Let output device transit into no stream state if it's
861 		 * in normal run state now. Leave input device in normal
862 		 * run state. */
863 		if ((iodev->direction == CRAS_STREAM_OUTPUT) &&
864 		    (iodev->state == CRAS_IODEV_STATE_NORMAL_RUN))
865 			cras_iodev_no_stream_playback_transition(iodev, 1);
866 	}
867 
868 	if (!set_earliest)
869 		return ret;
870 
871 	DL_FOREACH (iodev->streams, out) {
872 		if (!dev_stream_is_running(out))
873 			out->stream->next_cb_ts = earliest_next_cb_ts;
874 	}
875 
876 	return ret;
877 }
878 
cras_iodev_stream_offset(struct cras_iodev * iodev,struct dev_stream * stream)879 unsigned int cras_iodev_stream_offset(struct cras_iodev *iodev,
880 				      struct dev_stream *stream)
881 {
882 	return buffer_share_id_offset(iodev->buf_state,
883 				      stream->stream->stream_id);
884 }
885 
cras_iodev_stream_written(struct cras_iodev * iodev,struct dev_stream * stream,unsigned int nwritten)886 void cras_iodev_stream_written(struct cras_iodev *iodev,
887 			       struct dev_stream *stream, unsigned int nwritten)
888 {
889 	buffer_share_offset_update(iodev->buf_state, stream->stream->stream_id,
890 				   nwritten);
891 }
892 
cras_iodev_all_streams_written(struct cras_iodev * iodev)893 unsigned int cras_iodev_all_streams_written(struct cras_iodev *iodev)
894 {
895 	if (!iodev->buf_state)
896 		return 0;
897 	return buffer_share_get_new_write_point(iodev->buf_state);
898 }
899 
cras_iodev_max_stream_offset(const struct cras_iodev * iodev)900 unsigned int cras_iodev_max_stream_offset(const struct cras_iodev *iodev)
901 {
902 	unsigned int max = 0;
903 	struct dev_stream *curr;
904 
905 	DL_FOREACH (iodev->streams, curr) {
906 		/* Skip stream which hasn't started running yet. */
907 		if (!dev_stream_is_running(curr))
908 			continue;
909 
910 		max = MAX(max, buffer_share_id_offset(iodev->buf_state,
911 						      curr->stream->stream_id));
912 	}
913 
914 	return max;
915 }
916 
cras_iodev_open(struct cras_iodev * iodev,unsigned int cb_level,const struct cras_audio_format * fmt)917 int cras_iodev_open(struct cras_iodev *iodev, unsigned int cb_level,
918 		    const struct cras_audio_format *fmt)
919 {
920 	struct cras_loopback *loopback;
921 	int rc;
922 
923 	if (iodev->pre_open_iodev_hook)
924 		iodev->pre_open_iodev_hook();
925 
926 	DL_FOREACH (iodev->loopbacks, loopback) {
927 		if (loopback->hook_control)
928 			loopback->hook_control(true, loopback->cb_data);
929 	}
930 
931 	if (iodev->open_dev) {
932 		rc = iodev->open_dev(iodev);
933 		if (rc)
934 			return rc;
935 	}
936 
937 	if (iodev->format == NULL) {
938 		rc = cras_iodev_set_format(iodev, fmt);
939 		if (rc) {
940 			iodev->close_dev(iodev);
941 			return rc;
942 		}
943 	}
944 
945 	rc = iodev->configure_dev(iodev);
946 	if (rc < 0) {
947 		iodev->close_dev(iodev);
948 		return rc;
949 	}
950 
951 	/*
952 	 * Convert cb_level from input format to device format
953 	 */
954 	cb_level = cras_frames_at_rate(fmt->frame_rate, cb_level,
955 				       iodev->format->frame_rate);
956 	/* Make sure the min_cb_level doesn't get too large. */
957 	iodev->min_cb_level = MIN(iodev->buffer_size / 2, cb_level);
958 	iodev->max_cb_level = 0;
959 	iodev->largest_cb_level = 0;
960 	iodev->num_underruns = 0;
961 
962 	iodev->reset_request_pending = 0;
963 	iodev->state = CRAS_IODEV_STATE_OPEN;
964 	iodev->highest_hw_level = 0;
965 	iodev->input_dsp_offset = 0;
966 
967 	ewma_power_init(&iodev->ewma, iodev->format->frame_rate);
968 
969 	if (iodev->direction == CRAS_STREAM_OUTPUT) {
970 		/* If device supports start ops, device can be in open state.
971 		 * Otherwise, device starts running right after opening. */
972 		if (iodev->start) {
973 			iodev->state = CRAS_IODEV_STATE_OPEN;
974 		} else {
975 			iodev->state = CRAS_IODEV_STATE_NO_STREAM_RUN;
976 			cras_iodev_fill_odev_zeros(iodev, iodev->min_cb_level);
977 		}
978 	} else {
979 		iodev->input_data = input_data_create(iodev);
980 		/* If this is the echo reference dev, its ext_dsp_module will
981 		 * be set to APM reverse module. Do not override it to its
982 		 * input data. */
983 		if (iodev->ext_dsp_module == NULL)
984 			iodev->ext_dsp_module = &iodev->input_data->ext;
985 
986 		/* Input device starts running right after opening.
987 		 * No stream state is only for output device. Input device
988 		 * should be in normal run state. */
989 		iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
990 		/* Initialize the input_streaming flag to zero.*/
991 		iodev->input_streaming = 0;
992 
993 		/*
994 		 * The device specific gain scaler to be used in audio thread.
995 		 * It's expected to stick to 1.0f if device has hardware gain
996 		 * control. For alsa device, this gain value will be configured
997 		 * based on UCM labels IntrinsicSensitivity.
998 		 */
999 		iodev->software_gain_scaler =
1000 			cras_iodev_get_software_gain_scaler(iodev);
1001 	}
1002 
1003 	add_ext_dsp_module_to_pipeline(iodev);
1004 	clock_gettime(CLOCK_MONOTONIC_RAW, &iodev->open_ts);
1005 
1006 	return 0;
1007 }
1008 
cras_iodev_state(const struct cras_iodev * iodev)1009 enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev *iodev)
1010 {
1011 	return iodev->state;
1012 }
1013 
cras_iodev_close(struct cras_iodev * iodev)1014 int cras_iodev_close(struct cras_iodev *iodev)
1015 {
1016 	struct cras_loopback *loopback;
1017 	int rc;
1018 
1019 	if (!cras_iodev_is_open(iodev))
1020 		return 0;
1021 
1022 	if (iodev->active_node) {
1023 		cras_server_metrics_device_runtime(iodev);
1024 		cras_server_metrics_device_gain(iodev);
1025 		cras_server_metrics_device_volume(iodev);
1026 	}
1027 
1028 	if (iodev->input_data) {
1029 		if (iodev->ext_dsp_module == &iodev->input_data->ext)
1030 			iodev->ext_dsp_module = NULL;
1031 		input_data_destroy(&iodev->input_data);
1032 	}
1033 
1034 	rc = iodev->close_dev(iodev);
1035 	if (rc)
1036 		syslog(LOG_ERR, "Error closing dev %s, rc %d", iodev->info.name,
1037 		       rc);
1038 	iodev->state = CRAS_IODEV_STATE_CLOSE;
1039 	if (iodev->ramp)
1040 		cras_ramp_reset(iodev->ramp);
1041 
1042 	if (iodev->post_close_iodev_hook)
1043 		iodev->post_close_iodev_hook();
1044 
1045 	DL_FOREACH (iodev->loopbacks, loopback) {
1046 		if (loopback->hook_control)
1047 			loopback->hook_control(false, loopback->cb_data);
1048 	}
1049 
1050 	return 0;
1051 }
1052 
cras_iodev_put_input_buffer(struct cras_iodev * iodev)1053 int cras_iodev_put_input_buffer(struct cras_iodev *iodev)
1054 {
1055 	unsigned int min_frames;
1056 	unsigned int dsp_frames;
1057 	struct input_data *data = iodev->input_data;
1058 	int rc;
1059 
1060 	if (iodev->streams)
1061 		min_frames = buffer_share_get_new_write_point(iodev->buf_state);
1062 	else
1063 		min_frames = data->area->frames;
1064 
1065 	// Update the max number of frames has applied input dsp.
1066 	dsp_frames = MAX(iodev->input_frames_read, iodev->input_dsp_offset);
1067 	iodev->input_dsp_offset = dsp_frames - min_frames;
1068 
1069 	input_data_set_all_streams_read(data, min_frames);
1070 	rate_estimator_add_frames(iodev->rate_est, -min_frames);
1071 	rc = iodev->put_buffer(iodev, min_frames);
1072 	if (rc < 0)
1073 		return rc;
1074 	return min_frames;
1075 }
1076 
cras_iodev_put_output_buffer(struct cras_iodev * iodev,uint8_t * frames,unsigned int nframes,int * is_non_empty,struct cras_fmt_conv * remix_converter)1077 int cras_iodev_put_output_buffer(struct cras_iodev *iodev, uint8_t *frames,
1078 				 unsigned int nframes, int *is_non_empty,
1079 				 struct cras_fmt_conv *remix_converter)
1080 {
1081 	const struct cras_audio_format *fmt = iodev->format;
1082 	struct cras_ramp_action ramp_action = {
1083 		.type = CRAS_RAMP_ACTION_NONE,
1084 		.scaler = 0.0f,
1085 		.increment = 0.0f,
1086 		.target = 1.0f,
1087 	};
1088 	float software_volume_scaler = 1.0;
1089 	int software_volume_needed = cras_iodev_software_volume_needed(iodev);
1090 	int rc;
1091 	struct cras_loopback *loopback;
1092 
1093 	/* Calculate whether the final output was non-empty, if requested. */
1094 	if (is_non_empty) {
1095 		const size_t bytes = nframes * cras_get_format_bytes(fmt);
1096 
1097 		/*
1098 		 * Speed up checking frames are all zeros using memcmp.
1099 		 * frames contains all zeros if both conditions are met:
1100 		 *  - frames[0] is 0.
1101 		 *  - frames[i] == frames[i+1] for i in [0, 1, ..., bytes - 2].
1102 		 */
1103 		*is_non_empty = bytes ? (*frames || memcmp(frames, frames + 1,
1104 							   bytes - 1)) :
1105 					0;
1106 	}
1107 
1108 	DL_FOREACH (iodev->loopbacks, loopback) {
1109 		if (loopback->type == LOOPBACK_POST_MIX_PRE_DSP)
1110 			loopback->hook_data(frames, nframes, iodev->format,
1111 					    loopback->cb_data);
1112 	}
1113 
1114 	ewma_power_calculate(&iodev->ewma, (int16_t *)frames,
1115 			     iodev->format->num_channels, nframes);
1116 
1117 	rc = apply_dsp(iodev, frames, nframes);
1118 	if (rc)
1119 		return rc;
1120 
1121 	DL_FOREACH (iodev->loopbacks, loopback) {
1122 		if (loopback->type == LOOPBACK_POST_DSP)
1123 			loopback->hook_data(frames, nframes, iodev->format,
1124 					    loopback->cb_data);
1125 	}
1126 
1127 	if (iodev->ramp) {
1128 		ramp_action = cras_ramp_get_current_action(iodev->ramp);
1129 	}
1130 
1131 	/* Mute samples if adjusted volume is 0 or system is muted, plus
1132 	 * that this device is not ramping. */
1133 	if (output_should_mute(iodev) &&
1134 	    ramp_action.type != CRAS_RAMP_ACTION_PARTIAL) {
1135 		const unsigned int frame_bytes = cras_get_format_bytes(fmt);
1136 		cras_mix_mute_buffer(frames, frame_bytes, nframes);
1137 	}
1138 
1139 	/* Compute scaler for software volume if needed. */
1140 	if (software_volume_needed) {
1141 		software_volume_scaler =
1142 			cras_iodev_get_software_volume_scaler(iodev);
1143 	}
1144 
1145 	if (ramp_action.type == CRAS_RAMP_ACTION_PARTIAL) {
1146 		/* Scale with increment for ramp and possibly
1147 		 * software volume using cras_scale_buffer_increment.*/
1148 		float starting_scaler = ramp_action.scaler;
1149 		float increment = ramp_action.increment;
1150 		float target = ramp_action.target;
1151 
1152 		if (software_volume_needed) {
1153 			starting_scaler *= software_volume_scaler;
1154 			increment *= software_volume_scaler;
1155 			target *= software_volume_scaler;
1156 		}
1157 
1158 		cras_scale_buffer_increment(fmt->format, frames, nframes,
1159 					    starting_scaler, increment, target,
1160 					    fmt->num_channels);
1161 		cras_ramp_update_ramped_frames(iodev->ramp, nframes);
1162 	} else if (!output_should_mute(iodev) && software_volume_needed) {
1163 		/* Just scale for software volume using
1164 		 * cras_scale_buffer. */
1165 		unsigned int nsamples = nframes * fmt->num_channels;
1166 		cras_scale_buffer(fmt->format, frames, nsamples,
1167 				  software_volume_scaler);
1168 	}
1169 
1170 	if (remix_converter)
1171 		cras_channel_remix_convert(remix_converter, iodev->format,
1172 					   frames, nframes);
1173 	if (iodev->rate_est)
1174 		rate_estimator_add_frames(iodev->rate_est, nframes);
1175 
1176 	return iodev->put_buffer(iodev, nframes);
1177 }
1178 
cras_iodev_get_input_buffer(struct cras_iodev * iodev,unsigned int * frames)1179 int cras_iodev_get_input_buffer(struct cras_iodev *iodev, unsigned int *frames)
1180 {
1181 	const unsigned int frame_bytes = cras_get_format_bytes(iodev->format);
1182 	struct input_data *data = iodev->input_data;
1183 	int rc;
1184 	uint8_t *hw_buffer;
1185 	unsigned frame_requested = *frames;
1186 
1187 	rc = iodev->get_buffer(iodev, &data->area, frames);
1188 	if (rc < 0 || *frames == 0)
1189 		return rc;
1190 
1191 	if (*frames > frame_requested) {
1192 		syslog(LOG_ERR,
1193 		       "frames returned from get_buffer is greater than "
1194 		       "requested: %u > %u",
1195 		       *frames, frame_requested);
1196 		return -EINVAL;
1197 	}
1198 
1199 	iodev->input_frames_read = *frames;
1200 
1201 	/* TODO(hychao) - This assumes interleaved audio. */
1202 	hw_buffer = data->area->channels[0].buf;
1203 
1204 	/*
1205 	 * input_dsp_offset records the position where input dsp has applied to
1206 	 * last time. It's possible the requested |frames| count is smaller
1207 	 * than the tracked offset. That could happen when client stream uses
1208 	 * small buffer size and runs APM processing (which requires 10 ms
1209 	 * equivalent of data to process).
1210 	 * Only apply input dsp to the part of read buffer beyond where we've
1211 	 * already applied dsp.
1212 	 */
1213 	if (*frames > iodev->input_dsp_offset) {
1214 		rc = apply_dsp(iodev,
1215 			       hw_buffer +
1216 				       iodev->input_dsp_offset * frame_bytes,
1217 			       *frames - iodev->input_dsp_offset);
1218 		if (rc)
1219 			return rc;
1220 		ewma_power_calculate_area(
1221 			&iodev->ewma,
1222 			(int16_t *)(hw_buffer +
1223 				    iodev->input_dsp_offset * frame_bytes),
1224 			data->area, *frames - iodev->input_dsp_offset);
1225 	}
1226 
1227 	if (cras_system_get_capture_mute())
1228 		cras_mix_mute_buffer(hw_buffer, frame_bytes, *frames);
1229 
1230 	return rc;
1231 }
1232 
cras_iodev_get_output_buffer(struct cras_iodev * iodev,struct cras_audio_area ** area,unsigned * frames)1233 int cras_iodev_get_output_buffer(struct cras_iodev *iodev,
1234 				 struct cras_audio_area **area,
1235 				 unsigned *frames)
1236 {
1237 	int rc;
1238 	unsigned frame_requested = *frames;
1239 
1240 	rc = iodev->get_buffer(iodev, area, frames);
1241 	if (*frames > frame_requested) {
1242 		syslog(LOG_ERR,
1243 		       "frames returned from get_buffer is greater than "
1244 		       "requested: %u > %u",
1245 		       *frames, frame_requested);
1246 		return -EINVAL;
1247 	}
1248 	return rc;
1249 }
1250 
cras_iodev_update_rate(struct cras_iodev * iodev,unsigned int level,struct timespec * level_tstamp)1251 int cras_iodev_update_rate(struct cras_iodev *iodev, unsigned int level,
1252 			   struct timespec *level_tstamp)
1253 {
1254 	/* If output underruns, reset to avoid incorrect estimated rate. */
1255 	if ((iodev->direction == CRAS_STREAM_OUTPUT) && !level)
1256 		rate_estimator_reset_rate(iodev->rate_est,
1257 					  iodev->format->frame_rate);
1258 
1259 	return rate_estimator_check(iodev->rate_est, level, level_tstamp);
1260 }
1261 
cras_iodev_reset_rate_estimator(const struct cras_iodev * iodev)1262 int cras_iodev_reset_rate_estimator(const struct cras_iodev *iodev)
1263 {
1264 	rate_estimator_reset_rate(iodev->rate_est, iodev->format->frame_rate);
1265 	return 0;
1266 }
1267 
cras_iodev_get_est_rate_ratio(const struct cras_iodev * iodev)1268 double cras_iodev_get_est_rate_ratio(const struct cras_iodev *iodev)
1269 {
1270 	return rate_estimator_get_rate(iodev->rate_est) /
1271 	       iodev->format->frame_rate;
1272 }
1273 
cras_iodev_get_dsp_delay(const struct cras_iodev * iodev)1274 int cras_iodev_get_dsp_delay(const struct cras_iodev *iodev)
1275 {
1276 	struct cras_dsp_context *ctx;
1277 	struct pipeline *pipeline;
1278 	int delay;
1279 
1280 	ctx = iodev->dsp_context;
1281 	if (!ctx)
1282 		return 0;
1283 
1284 	pipeline = cras_dsp_get_pipeline(ctx);
1285 	if (!pipeline)
1286 		return 0;
1287 
1288 	delay = cras_dsp_pipeline_get_delay(pipeline);
1289 
1290 	cras_dsp_put_pipeline(ctx);
1291 	return delay;
1292 }
1293 
cras_iodev_frames_queued(struct cras_iodev * iodev,struct timespec * hw_tstamp)1294 int cras_iodev_frames_queued(struct cras_iodev *iodev,
1295 			     struct timespec *hw_tstamp)
1296 {
1297 	int rc;
1298 
1299 	rc = iodev->frames_queued(iodev, hw_tstamp);
1300 	if (rc < 0)
1301 		return rc;
1302 
1303 	if (iodev->direction == CRAS_STREAM_INPUT) {
1304 		if (rc > 0)
1305 			iodev->input_streaming = 1;
1306 		return rc;
1307 	}
1308 
1309 	if (rc < iodev->min_buffer_level)
1310 		return 0;
1311 
1312 	return rc - iodev->min_buffer_level;
1313 }
1314 
cras_iodev_buffer_avail(struct cras_iodev * iodev,unsigned hw_level)1315 int cras_iodev_buffer_avail(struct cras_iodev *iodev, unsigned hw_level)
1316 {
1317 	if (iodev->direction == CRAS_STREAM_INPUT)
1318 		return hw_level;
1319 
1320 	if (hw_level + iodev->min_buffer_level > iodev->buffer_size)
1321 		return 0;
1322 
1323 	return iodev->buffer_size - iodev->min_buffer_level - hw_level;
1324 }
1325 
cras_iodev_fill_odev_zeros(struct cras_iodev * odev,unsigned int frames)1326 int cras_iodev_fill_odev_zeros(struct cras_iodev *odev, unsigned int frames)
1327 {
1328 	struct cras_audio_area *area = NULL;
1329 	unsigned int frame_bytes, frames_written;
1330 	int rc;
1331 	uint8_t *buf;
1332 
1333 	if (odev->direction != CRAS_STREAM_OUTPUT)
1334 		return -EINVAL;
1335 
1336 	ATLOG(atlog, AUDIO_THREAD_FILL_ODEV_ZEROS, odev->info.idx, frames, 0);
1337 
1338 	frame_bytes = cras_get_format_bytes(odev->format);
1339 	while (frames > 0) {
1340 		frames_written = frames;
1341 		rc = cras_iodev_get_output_buffer(odev, &area, &frames_written);
1342 		if (rc < 0) {
1343 			syslog(LOG_ERR, "fill zeros fail: %d", rc);
1344 			return rc;
1345 		}
1346 
1347 		/* This assumes consecutive channel areas. */
1348 		buf = area->channels[0].buf;
1349 		memset(buf, 0, (size_t)frames_written * (size_t)frame_bytes);
1350 		cras_iodev_put_output_buffer(odev, buf, frames_written, NULL,
1351 					     NULL);
1352 		frames -= frames_written;
1353 	}
1354 
1355 	return 0;
1356 }
1357 
cras_iodev_output_underrun(struct cras_iodev * odev,unsigned int hw_level,unsigned int frames_written)1358 int cras_iodev_output_underrun(struct cras_iodev *odev, unsigned int hw_level,
1359 			       unsigned int frames_written)
1360 {
1361 	ATLOG(atlog, AUDIO_THREAD_UNDERRUN, odev->info.idx, hw_level,
1362 	      frames_written);
1363 	odev->num_underruns++;
1364 	cras_audio_thread_event_underrun();
1365 	if (odev->output_underrun)
1366 		return odev->output_underrun(odev);
1367 	else
1368 		return cras_iodev_fill_odev_zeros(odev, odev->min_cb_level);
1369 }
1370 
cras_iodev_odev_should_wake(const struct cras_iodev * odev)1371 int cras_iodev_odev_should_wake(const struct cras_iodev *odev)
1372 {
1373 	if (odev->direction != CRAS_STREAM_OUTPUT)
1374 		return 0;
1375 
1376 	if (odev->is_free_running && odev->is_free_running(odev))
1377 		return 0;
1378 
1379 	/* Do not wake up for device not started yet. */
1380 	return (odev->state == CRAS_IODEV_STATE_NORMAL_RUN ||
1381 		odev->state == CRAS_IODEV_STATE_NO_STREAM_RUN);
1382 }
1383 
1384 unsigned int
cras_iodev_default_frames_to_play_in_sleep(struct cras_iodev * odev,unsigned int * hw_level,struct timespec * hw_tstamp)1385 cras_iodev_default_frames_to_play_in_sleep(struct cras_iodev *odev,
1386 					   unsigned int *hw_level,
1387 					   struct timespec *hw_tstamp)
1388 {
1389 	int rc = cras_iodev_frames_queued(odev, hw_tstamp);
1390 	unsigned int level = (rc < 0) ? 0 : rc;
1391 	unsigned int wakeup_frames;
1392 	*hw_level = level;
1393 
1394 	if (odev->streams) {
1395 		/*
1396 		 * We have two cases in this scope. The first one is if there are frames
1397 		 * waiting to be played, audio thread will wake up when hw_level drops
1398 		 * to min_cb_level. This situation only happens when hardware buffer is
1399 		 * smaller than the client stream buffer. The second one is waking up
1400 		 * when hw_level drops to dev_normal_run_wake_up_time. It is a default
1401 		 * behavior. This wake up time is the bottom line to avoid underrun.
1402 		 * Normally, the audio thread does not wake up at that time because the
1403 		 * streams should wake it up before then.
1404 		 */
1405 		if (*hw_level > odev->min_cb_level && dev_playback_frames(odev))
1406 			return *hw_level - odev->min_cb_level;
1407 
1408 		wakeup_frames = cras_time_to_frames(
1409 			&dev_normal_run_wake_up_time, odev->format->frame_rate);
1410 		if (level > wakeup_frames)
1411 			return level - wakeup_frames;
1412 		else
1413 			return level;
1414 	}
1415 
1416 	/*
1417 	 * When this device has no stream, schedule audio thread to wake up when
1418 	 * hw_level drops to dev_no_stream_wake_up_time so audio thread can
1419 	 * fill zeros to it. We also need to consider min_cb_level in order to avoid
1420 	 * busyloop when device buffer size is smaller than wake up time.
1421 	 */
1422 	wakeup_frames = cras_time_to_frames(&dev_no_stream_wake_up_time,
1423 					    odev->format->frame_rate);
1424 	if (level > MIN(odev->min_cb_level, wakeup_frames))
1425 		return level - MIN(odev->min_cb_level, wakeup_frames);
1426 	else
1427 		return 0;
1428 }
1429 
cras_iodev_frames_to_play_in_sleep(struct cras_iodev * odev,unsigned int * hw_level,struct timespec * hw_tstamp)1430 unsigned int cras_iodev_frames_to_play_in_sleep(struct cras_iodev *odev,
1431 						unsigned int *hw_level,
1432 						struct timespec *hw_tstamp)
1433 {
1434 	/* Use odev's own implementation, if not supported then fall back
1435 	 * to default behavior below. */
1436 	if (odev->frames_to_play_in_sleep)
1437 		return odev->frames_to_play_in_sleep(odev, hw_level, hw_tstamp);
1438 	else
1439 		return cras_iodev_default_frames_to_play_in_sleep(
1440 			odev, hw_level, hw_tstamp);
1441 }
1442 
cras_iodev_default_no_stream_playback(struct cras_iodev * odev,int enable)1443 int cras_iodev_default_no_stream_playback(struct cras_iodev *odev, int enable)
1444 {
1445 	if (enable)
1446 		return default_no_stream_playback(odev);
1447 	return 0;
1448 }
1449 
cras_iodev_prepare_output_before_write_samples(struct cras_iodev * odev)1450 int cras_iodev_prepare_output_before_write_samples(struct cras_iodev *odev)
1451 {
1452 	int may_enter_normal_run;
1453 	enum CRAS_IODEV_STATE state;
1454 
1455 	if (odev->direction != CRAS_STREAM_OUTPUT)
1456 		return -EINVAL;
1457 
1458 	state = cras_iodev_state(odev);
1459 
1460 	may_enter_normal_run = (state == CRAS_IODEV_STATE_OPEN ||
1461 				state == CRAS_IODEV_STATE_NO_STREAM_RUN);
1462 
1463 	if (may_enter_normal_run && dev_playback_frames(odev))
1464 		return cras_iodev_output_event_sample_ready(odev);
1465 
1466 	/* no_stream ops is called every cycle in no_stream state. */
1467 	if (state == CRAS_IODEV_STATE_NO_STREAM_RUN)
1468 		return odev->no_stream(odev, 1);
1469 
1470 	return 0;
1471 }
1472 
cras_iodev_get_num_underruns(const struct cras_iodev * iodev)1473 unsigned int cras_iodev_get_num_underruns(const struct cras_iodev *iodev)
1474 {
1475 	return iodev->num_underruns;
1476 }
1477 
cras_iodev_get_num_severe_underruns(const struct cras_iodev * iodev)1478 unsigned int cras_iodev_get_num_severe_underruns(const struct cras_iodev *iodev)
1479 {
1480 	if (iodev->get_num_severe_underruns)
1481 		return iodev->get_num_severe_underruns(iodev);
1482 	return 0;
1483 }
1484 
cras_iodev_reset_request(struct cras_iodev * iodev)1485 int cras_iodev_reset_request(struct cras_iodev *iodev)
1486 {
1487 	/* Ignore requests if there is a pending request.
1488 	 * This function sends the request from audio thread to main
1489 	 * thread when audio thread finds a device is in a bad state
1490 	 * e.g. severe underrun. Before main thread receives the
1491 	 * request and resets device, audio thread might try to send
1492 	 * multiple requests because it finds device is still in bad
1493 	 * state. We should ignore requests in this cause. Otherwise,
1494 	 * main thread will reset device multiple times.
1495 	 * The flag is cleared in cras_iodev_open.
1496 	 * */
1497 	if (iodev->reset_request_pending)
1498 		return 0;
1499 	iodev->reset_request_pending = 1;
1500 	return cras_device_monitor_reset_device(iodev->info.idx);
1501 }
1502 
ramp_down_mute_callback(void * data)1503 static void ramp_down_mute_callback(void *data)
1504 {
1505 	struct cras_iodev *odev = (struct cras_iodev *)data;
1506 	cras_device_monitor_set_device_mute_state(odev->info.idx);
1507 }
1508 
1509 /* Used in audio thread. Check the docstrings of CRAS_IODEV_RAMP_REQUEST. */
cras_iodev_start_ramp(struct cras_iodev * odev,enum CRAS_IODEV_RAMP_REQUEST request)1510 int cras_iodev_start_ramp(struct cras_iodev *odev,
1511 			  enum CRAS_IODEV_RAMP_REQUEST request)
1512 {
1513 	cras_ramp_cb cb = NULL;
1514 	void *cb_data = NULL;
1515 	int rc;
1516 	float from, to, duration_secs;
1517 
1518 	/* Ignores request if device is closed. */
1519 	if (!cras_iodev_is_open(odev))
1520 		return 0;
1521 
1522 	switch (request) {
1523 	case CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE:
1524 		from = 0.0;
1525 		to = 1.0;
1526 		duration_secs = RAMP_UNMUTE_DURATION_SECS;
1527 		break;
1528 	case CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK:
1529 		from = 0.0;
1530 		to = 1.0;
1531 		duration_secs = RAMP_NEW_STREAM_DURATION_SECS;
1532 		break;
1533 	/* Unmute -> mute. Callback to set mute state should be called after
1534 	 * ramping is done. */
1535 	case CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE:
1536 		from = 1.0;
1537 		to = 0.0;
1538 		duration_secs = RAMP_MUTE_DURATION_SECS;
1539 		cb = ramp_down_mute_callback;
1540 		cb_data = (void *)odev;
1541 		break;
1542 	case CRAS_IODEV_RAMP_REQUEST_RESUME_MUTE:
1543 		from = 0;
1544 		to = 0;
1545 		duration_secs = RAMP_RESUME_MUTE_DURATION_SECS;
1546 		odev->initial_ramp_request =
1547 			CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
1548 		break;
1549 	case CRAS_IODEV_RAMP_REQUEST_SWITCH_MUTE:
1550 		from = 0;
1551 		to = 0;
1552 		duration_secs = RAMP_SWITCH_MUTE_DURATION_SECS;
1553 		odev->initial_ramp_request =
1554 			CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
1555 		break;
1556 	default:
1557 		return -EINVAL;
1558 	}
1559 
1560 	/* Starts ramping. */
1561 	rc = cras_mute_ramp_start(odev->ramp, from, to,
1562 				  duration_secs * odev->format->frame_rate, cb,
1563 				  cb_data);
1564 
1565 	if (rc)
1566 		return rc;
1567 
1568 	/* Mute -> unmute case, unmute state should be set after ramping is
1569 	 * started so device can start playing with samples close to 0. */
1570 	if (request == CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE)
1571 		cras_device_monitor_set_device_mute_state(odev->info.idx);
1572 
1573 	return 0;
1574 }
1575 
cras_iodev_start_volume_ramp(struct cras_iodev * odev,unsigned int old_volume,unsigned int new_volume)1576 int cras_iodev_start_volume_ramp(struct cras_iodev *odev,
1577 				 unsigned int old_volume,
1578 				 unsigned int new_volume)
1579 {
1580 	float old_scaler, new_scaler;
1581 	float from, to;
1582 
1583 	if (old_volume == new_volume)
1584 		return 0;
1585 	if (!cras_iodev_is_open(odev))
1586 		return 0;
1587 	if (!odev->format)
1588 		return -EINVAL;
1589 	if (odev->active_node && odev->active_node->softvol_scalers) {
1590 		old_scaler = odev->active_node->softvol_scalers[old_volume];
1591 		new_scaler = odev->active_node->softvol_scalers[new_volume];
1592 	} else {
1593 		old_scaler = softvol_get_scaler(old_volume);
1594 		new_scaler = softvol_get_scaler(new_volume);
1595 	}
1596 	if (new_scaler == 0.0) {
1597 		return -EINVAL;
1598 	}
1599 	/* We will soon set odev's volume to new_volume from old_volume.
1600 	 * Because we're using softvol, we were previously scaling our volume by
1601 	 * old_scaler. If we want to avoid a jump in volume, we need to start
1602 	 * our ramp so that (from * new_scaler) = old_scaler. */
1603 	from = old_scaler / new_scaler;
1604 	to = 1.0;
1605 
1606 	return cras_volume_ramp_start(odev->ramp, from, to,
1607 				      RAMP_VOLUME_CHANGE_DURATION_SECS *
1608 					      odev->format->frame_rate,
1609 				      NULL, NULL);
1610 }
1611 
cras_iodev_set_mute(struct cras_iodev * iodev)1612 int cras_iodev_set_mute(struct cras_iodev *iodev)
1613 {
1614 	if (!cras_iodev_is_open(iodev))
1615 		return 0;
1616 
1617 	if (iodev->set_mute)
1618 		iodev->set_mute(iodev);
1619 	return 0;
1620 }
1621 
cras_iodev_update_highest_hw_level(struct cras_iodev * iodev,unsigned int hw_level)1622 void cras_iodev_update_highest_hw_level(struct cras_iodev *iodev,
1623 					unsigned int hw_level)
1624 {
1625 	/*
1626 	 * If the hw_level is unreasonably high and reach to the device's
1627 	 * buffer size, regard it as a device overrun.
1628 	 * In the normal status, the hw_level for should be between 1 to 2
1629 	 * largest_cb_level for an output device and 0 to 1 largest_cb_level
1630 	 * for an input device. Therefore, larger than 3 can be considered
1631 	 * unreasonable.
1632 	 */
1633 	if (hw_level == iodev->buffer_size &&
1634 	    iodev->largest_cb_level * 3 < iodev->buffer_size) {
1635 		ATLOG(atlog, AUDIO_THREAD_DEV_OVERRUN, iodev->info.idx,
1636 		      hw_level, 0);
1637 		/* Only log the event when the first time it happens. */
1638 		if (iodev->highest_hw_level != hw_level)
1639 			cras_audio_thread_event_dev_overrun();
1640 	}
1641 	iodev->highest_hw_level = MAX(iodev->highest_hw_level, hw_level);
1642 }
1643 
1644 /*
1645  * Makes an input device drop the given number of frames.
1646  * Args:
1647  *    iodev - The device.
1648  *    frames - How many frames will be dropped in a device.
1649  * Returns:
1650  *    The number of frames have been dropped. Negative error code on failure.
1651  */
cras_iodev_drop_frames(struct cras_iodev * iodev,unsigned int frames)1652 static int cras_iodev_drop_frames(struct cras_iodev *iodev, unsigned int frames)
1653 {
1654 	struct timespec hw_tstamp;
1655 	int i, rc;
1656 	unsigned int target_frames, dropped_frames = 0;
1657 
1658 	if (iodev->direction != CRAS_STREAM_INPUT)
1659 		return -EINVAL;
1660 
1661 	rc = cras_iodev_frames_queued(iodev, &hw_tstamp);
1662 	if (rc < 0)
1663 		return rc;
1664 
1665 	target_frames = MIN(frames, rc);
1666 
1667 	/*
1668 	 * Loop reading the buffer, at most twice. This is to cover when
1669 	 * circular buffer is at the end and returns partial of the target
1670 	 * frames.
1671 	 */
1672 	for (i = 0; (dropped_frames < target_frames) && (i < 2); i++) {
1673 		frames = target_frames - dropped_frames;
1674 		rc = iodev->get_buffer(iodev, &iodev->input_data->area,
1675 				       &frames);
1676 		if (rc < 0)
1677 			return rc;
1678 
1679 		rc = iodev->put_buffer(iodev, frames);
1680 		if (rc < 0)
1681 			return rc;
1682 		dropped_frames += frames;
1683 		/*
1684 		 * Tell rate estimator that some frames have been dropped to
1685 		 * avoid calculating the wrong rate.
1686 		 */
1687 		rate_estimator_add_frames(iodev->rate_est, -frames);
1688 	}
1689 
1690 	ATLOG(atlog, AUDIO_THREAD_DEV_DROP_FRAMES, iodev->info.idx,
1691 	      dropped_frames, 0);
1692 
1693 	return frames;
1694 }
1695 
cras_iodev_drop_frames_by_time(struct cras_iodev * iodev,struct timespec ts)1696 int cras_iodev_drop_frames_by_time(struct cras_iodev *iodev, struct timespec ts)
1697 {
1698 	int frames_to_set;
1699 	double est_rate;
1700 	int rc;
1701 
1702 	est_rate = iodev->format->frame_rate *
1703 		   cras_iodev_get_est_rate_ratio(iodev);
1704 	frames_to_set = cras_time_to_frames(&ts, est_rate);
1705 
1706 	rc = cras_iodev_drop_frames(iodev, frames_to_set);
1707 
1708 	return rc;
1709 }
1710 
cras_iodev_support_noise_cancellation(const struct cras_iodev * iodev)1711 bool cras_iodev_support_noise_cancellation(const struct cras_iodev *iodev)
1712 {
1713 	if (iodev->direction != CRAS_STREAM_INPUT)
1714 		return false;
1715 
1716 	if (iodev->support_noise_cancellation)
1717 		return !!iodev->support_noise_cancellation(iodev);
1718 	return false;
1719 }
1720