1 /* Copyright 2017 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 <poll.h>
7 #include <stdbool.h>
8 #include <syslog.h>
9
10 #include "audio_thread_log.h"
11 #include "cras_audio_area.h"
12 #include "cras_audio_thread_monitor.h"
13 #include "cras_device_monitor.h"
14 #include "cras_iodev.h"
15 #include "cras_non_empty_audio_handler.h"
16 #include "cras_rstream.h"
17 #include "cras_server_metrics.h"
18 #include "dev_stream.h"
19 #include "input_data.h"
20 #include "polled_interval_checker.h"
21 #include "rate_estimator.h"
22 #include "utlist.h"
23
24 #include "dev_io.h"
25
26 static const struct timespec playback_wake_fuzz_ts = {
27 0, 500 * 1000 /* 500 usec. */
28 };
29
30 /* The maximum time to wait before checking the device's non-empty status. */
31 static const int NON_EMPTY_UPDATE_INTERVAL_SEC = 5;
32
33 /*
34 * The minimum number of consecutive seconds of empty audio that must be
35 * played before a device is considered to be playing empty audio.
36 */
37 static const int MIN_EMPTY_PERIOD_SEC = 30;
38
39 /*
40 * When the hw_level is less than this time, do not drop frames.
41 * (unit: millisecond).
42 * TODO(yuhsuan): Reduce the threshold when we create the other overrun op for
43 * boards which captures a lot of frames at one time.
44 * e.g. Input devices on grunt reads 1024 frames each time.
45 */
46 static const int DROP_FRAMES_THRESHOLD_MS = 50;
47
48 /* The number of devices playing/capturing non-empty stream(s). */
49 static int non_empty_device_count = 0;
50
51 /* The timestamp of last EIO error time. */
52 static struct timespec last_io_err_time = { 0, 0 };
53
54 /* The gap time to avoid repeated error close request to main thread. */
55 static const int ERROR_CLOSE_GAP_TIME_SECS = 10;
56
57 /* Gets the main device which the stream is attached to. */
get_main_dev(const struct dev_stream * stream)58 static inline struct cras_iodev *get_main_dev(const struct dev_stream *stream)
59 {
60 return (struct cras_iodev *)stream->stream->main_dev.dev_ptr;
61 }
62
63 /* Updates the estimated sample rate of open device to all attached
64 * streams.
65 */
update_estimated_rate(struct open_dev * adev,struct open_dev * odev_list,bool self_rate_need_update)66 static void update_estimated_rate(struct open_dev *adev,
67 struct open_dev *odev_list,
68 bool self_rate_need_update)
69 {
70 struct cras_iodev *main_dev;
71 struct cras_iodev *dev = adev->dev;
72 struct cras_iodev *tracked_dev = NULL;
73 struct dev_stream *dev_stream;
74 double dev_rate_ratio;
75 double main_dev_rate_ratio;
76
77 /*
78 * If there is an output device on the same sound card running with the same
79 * sampling rate, use the rate of that output device for this device.
80 */
81 if (dev->direction == CRAS_STREAM_INPUT &&
82 cras_iodev_is_on_internal_card(dev->active_node)) {
83 struct open_dev *odev;
84 DL_FOREACH (odev_list, odev) {
85 if (!cras_iodev_is_on_internal_card(
86 odev->dev->active_node))
87 continue;
88 if (odev->dev->format->frame_rate !=
89 dev->format->frame_rate)
90 continue;
91 tracked_dev = odev->dev;
92 break;
93 }
94 }
95
96 /*
97 * Self-owned rate esimator does not need to udpate rate. There is no tracked
98 * output device. So there is no need to update.
99 */
100 if (!self_rate_need_update && !tracked_dev)
101 return;
102
103 DL_FOREACH (dev->streams, dev_stream) {
104 main_dev = get_main_dev(dev_stream);
105 if (main_dev == NULL) {
106 syslog(LOG_ERR, "Fail to find main open dev.");
107 continue;
108 }
109
110 if (tracked_dev) {
111 dev_rate_ratio =
112 cras_iodev_get_est_rate_ratio(tracked_dev);
113 main_dev_rate_ratio = dev_rate_ratio;
114 } else {
115 dev_rate_ratio = cras_iodev_get_est_rate_ratio(dev);
116 main_dev_rate_ratio =
117 cras_iodev_get_est_rate_ratio(main_dev);
118 }
119
120 dev_stream_set_dev_rate(dev_stream, dev->format->frame_rate,
121 dev_rate_ratio, main_dev_rate_ratio,
122 adev->coarse_rate_adjust);
123 }
124 }
125
126 /*
127 * Counts the number of devices which are currently playing/capturing non-empty
128 * audio.
129 */
count_non_empty_dev(struct open_dev * adevs)130 static inline int count_non_empty_dev(struct open_dev *adevs)
131 {
132 int count = 0;
133 struct open_dev *adev;
134 DL_FOREACH (adevs, adev) {
135 if (!adev->empty_pi || !pic_interval_elapsed(adev->empty_pi))
136 count++;
137 }
138 return count;
139 }
140
dev_io_check_non_empty_state_transition(struct open_dev * adevs)141 int dev_io_check_non_empty_state_transition(struct open_dev *adevs)
142 {
143 int new_non_empty_dev_count = count_non_empty_dev(adevs);
144
145 // If we have transitioned to or from a state with 0 non-empty devices,
146 // notify the main thread to update system state.
147 if ((non_empty_device_count == 0) != (new_non_empty_dev_count == 0))
148 cras_non_empty_audio_send_msg(new_non_empty_dev_count > 0 ? 1 :
149 0);
150
151 non_empty_device_count = new_non_empty_dev_count;
152 return non_empty_device_count > 0;
153 }
154
155 /* Checks whether it is time to fetch. */
is_time_to_fetch(const struct dev_stream * dev_stream,struct timespec now)156 static bool is_time_to_fetch(const struct dev_stream *dev_stream,
157 struct timespec now)
158 {
159 const struct timespec *next_cb_ts;
160 next_cb_ts = dev_stream_next_cb_ts(dev_stream);
161 if (!next_cb_ts)
162 return 0;
163
164 /*
165 * Check if it's time to get more data from this stream.
166 * Allow for waking up a little early.
167 */
168 add_timespecs(&now, &playback_wake_fuzz_ts);
169 if (timespec_after(&now, next_cb_ts))
170 return 1;
171
172 return 0;
173 }
174
175 /* The log only accepts uint32 arguments, so the float power
176 * must be written as bits and assumed to have a float when
177 * parsing the log.
178 */
get_ewma_power_as_int(struct ewma_power * ewma)179 static uint32_t get_ewma_power_as_int(struct ewma_power *ewma)
180 {
181 uint32_t pow_as_int = 0;
182
183 if (sizeof(uint32_t) == sizeof(float))
184 memcpy(&pow_as_int, &ewma->power, sizeof(uint32_t));
185 return pow_as_int;
186 }
187
188 /* Asks any stream with room for more data. Sets the time stamp for all streams.
189 * Args:
190 * adev - The output device streams are attached to.
191 * Returns:
192 * 0 on success, negative error on failure. If failed, can assume that all
193 * streams have been removed from the device.
194 */
fetch_streams(struct open_dev * adev)195 static int fetch_streams(struct open_dev *adev)
196 {
197 struct dev_stream *dev_stream;
198 struct cras_iodev *odev = adev->dev;
199 int rc;
200 int delay;
201
202 delay = cras_iodev_delay_frames(odev);
203 if (delay < 0)
204 return delay;
205
206 DL_FOREACH (adev->dev->streams, dev_stream) {
207 struct cras_rstream *rstream = dev_stream->stream;
208 struct cras_audio_shm *shm = cras_rstream_shm(rstream);
209 struct timespec now;
210
211 clock_gettime(CLOCK_MONOTONIC_RAW, &now);
212
213 if (dev_stream_is_pending_reply(dev_stream)) {
214 dev_stream_flush_old_audio_messages(dev_stream);
215 cras_rstream_record_fetch_interval(dev_stream->stream,
216 &now);
217 }
218
219 if (!dev_stream_is_running(dev_stream))
220 continue;
221
222 if (!is_time_to_fetch(dev_stream, now))
223 continue;
224
225 if (cras_shm_get_frames(shm) < 0)
226 cras_rstream_set_is_draining(rstream, 1);
227
228 if (cras_rstream_get_is_draining(dev_stream->stream))
229 continue;
230
231 /*
232 * Skip fetching if client still has not replied yet.
233 */
234 if (cras_rstream_is_pending_reply(rstream)) {
235 ATLOG(atlog, AUDIO_THREAD_STREAM_FETCH_PENDING,
236 cras_rstream_id(rstream), 0, 0);
237 continue;
238 }
239
240 /*
241 * Skip fetching if there are enough frames in shared memory.
242 */
243 if (!cras_shm_is_buffer_available(shm)) {
244 ATLOG(atlog, AUDIO_THREAD_STREAM_SKIP_CB,
245 cras_rstream_id(rstream),
246 shm->header->write_offset[0],
247 shm->header->write_offset[1]);
248 dev_stream_update_next_wake_time(dev_stream);
249 cras_server_metrics_missed_cb_event(dev_stream->stream);
250 continue;
251 }
252
253 dev_stream_set_delay(dev_stream, delay);
254
255 ATLOG(atlog, AUDIO_THREAD_FETCH_STREAM, rstream->stream_id,
256 cras_rstream_get_cb_threshold(rstream),
257 get_ewma_power_as_int(&rstream->ewma));
258
259 rc = dev_stream_request_playback_samples(dev_stream, &now);
260 if (rc < 0) {
261 syslog(LOG_ERR, "fetch err: %d for %x", rc,
262 cras_rstream_id(rstream));
263 cras_rstream_set_is_draining(rstream, 1);
264 }
265 }
266
267 return 0;
268 }
269
270 /* Gets the max delay frames of open input devices. */
input_delay_frames(struct open_dev * adevs)271 static int input_delay_frames(struct open_dev *adevs)
272 {
273 struct open_dev *adev;
274 int delay;
275 int max_delay = 0;
276
277 DL_FOREACH (adevs, adev) {
278 if (!cras_iodev_is_open(adev->dev))
279 continue;
280 delay = cras_iodev_delay_frames(adev->dev);
281 if (delay < 0)
282 return delay;
283 if (delay > max_delay)
284 max_delay = delay;
285 }
286 return max_delay;
287 }
288
289 /* Sets the stream delay.
290 * Args:
291 * adev[in] - The device to capture from.
292 */
set_stream_delay(struct open_dev * adev)293 static unsigned int set_stream_delay(struct open_dev *adev)
294 {
295 struct dev_stream *stream;
296 int delay;
297
298 /* TODO(dgreid) - Setting delay from last dev only. */
299 delay = input_delay_frames(adev);
300
301 DL_FOREACH (adev->dev->streams, stream) {
302 if (stream->stream->flags & TRIGGER_ONLY)
303 continue;
304
305 dev_stream_set_delay(stream, delay);
306 }
307
308 return 0;
309 }
310
311 /* Gets the minimum amount of space available for writing across all streams.
312 * Args:
313 * adev[in] - The device to capture from.
314 * write_limit[in] - Initial limit to number of frames to capture.
315 * limit_stream[out] - The pointer to the pointer of stream which
316 * causes capture limit.
317 * Output NULL if there is no stream that causes
318 * capture limit less than the initial limit.
319 */
get_stream_limit(struct open_dev * adev,unsigned int write_limit,struct dev_stream ** limit_stream)320 static unsigned int get_stream_limit(struct open_dev *adev,
321 unsigned int write_limit,
322 struct dev_stream **limit_stream)
323 {
324 struct cras_rstream *rstream;
325 struct cras_audio_shm *shm;
326 struct dev_stream *stream;
327 unsigned int avail;
328
329 *limit_stream = NULL;
330
331 DL_FOREACH (adev->dev->streams, stream) {
332 rstream = stream->stream;
333 if (rstream->flags & TRIGGER_ONLY)
334 continue;
335
336 shm = cras_rstream_shm(rstream);
337 if (cras_shm_check_write_overrun(shm))
338 ATLOG(atlog, AUDIO_THREAD_READ_OVERRUN,
339 adev->dev->info.idx, rstream->stream_id,
340 shm->header->num_overruns);
341 avail = dev_stream_capture_avail(stream);
342 if (avail < write_limit) {
343 write_limit = avail;
344 *limit_stream = stream;
345 }
346 }
347
348 return write_limit;
349 }
350
351 /*
352 * The minimum wake time for a input device, which is 5ms. It's only used by
353 * function get_input_dev_max_wake_ts.
354 */
355 static const struct timespec min_input_dev_wake_ts = {
356 0, 5 * 1000 * 1000 /* 5 ms. */
357 };
358
359 /*
360 * Get input device maximum sleep time, which is the approximate time that the
361 * device will have hw_level = buffer_size / 2 samples. Some devices have
362 * capture period = 2 so the audio_thread should wake up and consume some
363 * samples from hardware at that time. To prevent busy loop occurs, the returned
364 * sleep time should be >= 5ms.
365 *
366 * Returns: 0 on success negative error on device failure.
367 */
get_input_dev_max_wake_ts(struct open_dev * adev,unsigned int curr_level,struct timespec * res_ts)368 static int get_input_dev_max_wake_ts(struct open_dev *adev,
369 unsigned int curr_level,
370 struct timespec *res_ts)
371 {
372 struct timespec dev_wake_ts, now;
373 unsigned int dev_rate, half_buffer_size, target_frames;
374
375 if (!adev || !adev->dev || !adev->dev->format ||
376 !adev->dev->format->frame_rate || !adev->dev->buffer_size)
377 return -EINVAL;
378
379 *res_ts = min_input_dev_wake_ts;
380
381 dev_rate = adev->dev->format->frame_rate;
382 half_buffer_size = adev->dev->buffer_size / 2;
383 if (curr_level < half_buffer_size)
384 target_frames = half_buffer_size - curr_level;
385 else
386 target_frames = 0;
387
388 cras_frames_to_time(target_frames, dev_rate, &dev_wake_ts);
389
390 if (timespec_after(&dev_wake_ts, res_ts)) {
391 *res_ts = dev_wake_ts;
392 }
393
394 clock_gettime(CLOCK_MONOTONIC_RAW, &now);
395 add_timespecs(res_ts, &now);
396 return 0;
397 }
398
399 /* Returns whether a device can drop samples. */
input_devices_can_drop_samples(struct cras_iodev * iodev)400 static bool input_devices_can_drop_samples(struct cras_iodev *iodev)
401 {
402 if (!cras_iodev_is_open(iodev))
403 return false;
404 if (!iodev->streams)
405 return false;
406 if (!iodev->active_node ||
407 iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD ||
408 iodev->active_node->type == CRAS_NODE_TYPE_POST_MIX_PRE_DSP ||
409 iodev->active_node->type == CRAS_NODE_TYPE_POST_DSP)
410 return false;
411 return true;
412 }
413
414 /*
415 * Set wake_ts for this device to be the earliest wake up time for
416 * dev_streams. Default value for adev->wake_ts will be now + 20s even if
417 * any error occurs in this function.
418 * Args:
419 * adev - The input device.
420 * need_to_drop - The pointer to store whether we need to drop samples from
421 * a device in order to keep the lower hw_level.
422 * Returns:
423 * 0 on success. Negative error code on failure.
424 */
set_input_dev_wake_ts(struct open_dev * adev,bool * need_to_drop)425 static int set_input_dev_wake_ts(struct open_dev *adev, bool *need_to_drop)
426 {
427 int rc;
428 struct timespec level_tstamp, wake_time_out, min_ts, now, dev_wake_ts;
429 unsigned int curr_level, cap_limit;
430 struct dev_stream *stream;
431 struct dev_stream *cap_limit_stream;
432
433 /* Limit the sleep time to 20 seconds. */
434 min_ts.tv_sec = 20;
435 min_ts.tv_nsec = 0;
436 clock_gettime(CLOCK_MONOTONIC_RAW, &now);
437 add_timespecs(&min_ts, &now);
438 /* Set default value for device wake_ts. */
439 adev->wake_ts = min_ts;
440
441 rc = cras_iodev_frames_queued(adev->dev, &level_tstamp);
442 if (rc < 0)
443 return rc;
444 curr_level = rc;
445 if (!timespec_is_nonzero(&level_tstamp))
446 clock_gettime(CLOCK_MONOTONIC_RAW, &level_tstamp);
447
448 /*
449 * Drop frames from all devices if any device meets these requirements:
450 * 1. The hw_level is larger than largest_cb_level * 1.5 or larger than
451 * buffer_size * 0.5.
452 * 2. The time of those frames is larger than DROP_FRAMES_THRESHOLD_MS.
453 */
454 if (input_devices_can_drop_samples(adev->dev) &&
455 (rc >= adev->dev->largest_cb_level * 1.5 ||
456 rc >= adev->dev->buffer_size * 0.5) &&
457 cras_frames_to_ms(rc, adev->dev->format->frame_rate) >=
458 DROP_FRAMES_THRESHOLD_MS)
459 *need_to_drop = true;
460
461 cap_limit = get_stream_limit(adev, UINT_MAX, &cap_limit_stream);
462
463 /*
464 * Loop through streams to find the earliest time audio thread
465 * should wake up.
466 */
467 DL_FOREACH (adev->dev->streams, stream) {
468 wake_time_out = min_ts;
469 rc = dev_stream_wake_time(stream, curr_level, &level_tstamp,
470 cap_limit, cap_limit_stream == stream,
471 &wake_time_out);
472
473 /*
474 * rc > 0 means there is no need to set wake up time for this
475 * stream.
476 */
477 if (rc > 0)
478 continue;
479
480 if (rc < 0)
481 return rc;
482
483 if (timespec_after(&min_ts, &wake_time_out)) {
484 min_ts = wake_time_out;
485 }
486 }
487
488 /* If there's no room in streams, don't bother schedule wake for more
489 * input data. */
490 if (adev->dev->active_node &&
491 adev->dev->active_node->type != CRAS_NODE_TYPE_HOTWORD &&
492 cap_limit) {
493 rc = get_input_dev_max_wake_ts(adev, curr_level, &dev_wake_ts);
494 if (rc < 0) {
495 syslog(LOG_ERR,
496 "Failed to call get_input_dev_max_wake_ts."
497 "rc = %d",
498 rc);
499 } else if (timespec_after(&min_ts, &dev_wake_ts)) {
500 min_ts = dev_wake_ts;
501 }
502 }
503
504 adev->wake_ts = min_ts;
505 return rc;
506 }
507
508 /* Read samples from an input device to the specified stream.
509 * Args:
510 * adev - The device to capture samples from.
511 * Returns 0 on success.
512 */
capture_to_streams(struct open_dev * adev,struct open_dev * odev_list)513 static int capture_to_streams(struct open_dev *adev, struct open_dev *odev_list)
514 {
515 struct cras_iodev *idev = adev->dev;
516 snd_pcm_uframes_t remainder, hw_level, cap_limit;
517 struct timespec hw_tstamp;
518 int rc;
519 struct dev_stream *cap_limit_stream;
520 struct dev_stream *stream;
521
522 DL_FOREACH (adev->dev->streams, stream)
523 dev_stream_flush_old_audio_messages(stream);
524
525 rc = cras_iodev_frames_queued(idev, &hw_tstamp);
526 if (rc < 0)
527 return rc;
528 hw_level = rc;
529
530 cras_iodev_update_highest_hw_level(idev, hw_level);
531
532 ATLOG(atlog, AUDIO_THREAD_READ_AUDIO_TSTAMP, idev->info.idx,
533 hw_tstamp.tv_sec, hw_tstamp.tv_nsec);
534 if (timespec_is_nonzero(&hw_tstamp)) {
535 bool self_rate_need_update;
536
537 if (hw_level < idev->min_cb_level / 2)
538 adev->coarse_rate_adjust = 1;
539 else if (hw_level > idev->max_cb_level * 2)
540 adev->coarse_rate_adjust = -1;
541 else
542 adev->coarse_rate_adjust = 0;
543
544 /*
545 * This values means whether the rate estimator in the device
546 * wants to update estimated rate.
547 */
548 self_rate_need_update =
549 !!cras_iodev_update_rate(idev, hw_level, &hw_tstamp);
550
551 /*
552 * Always calls update_estimated_rate so that new output rate
553 * has a chance to propagate to input. In update_estimated_rate,
554 * it will decide whether the new rate is from self rate estimator
555 * or from the tracked output device.
556 */
557 update_estimated_rate(adev, odev_list, self_rate_need_update);
558 }
559
560 cap_limit = get_stream_limit(adev, hw_level, &cap_limit_stream);
561 set_stream_delay(adev);
562
563 remainder = MIN(hw_level, cap_limit);
564
565 ATLOG(atlog, AUDIO_THREAD_READ_AUDIO, idev->info.idx, hw_level,
566 remainder);
567
568 if (cras_iodev_state(idev) != CRAS_IODEV_STATE_NORMAL_RUN)
569 return 0;
570
571 while (remainder > 0) {
572 struct cras_audio_area *area = NULL;
573 unsigned int nread, total_read;
574
575 nread = remainder;
576
577 rc = cras_iodev_get_input_buffer(idev, &nread);
578 if (rc < 0 || nread == 0)
579 return rc;
580
581 DL_FOREACH (adev->dev->streams, stream) {
582 unsigned int this_read;
583 unsigned int area_offset;
584 float software_gain_scaler;
585
586 if ((stream->stream->flags & TRIGGER_ONLY) &&
587 stream->stream->triggered)
588 continue;
589
590 input_data_get_for_stream(idev->input_data,
591 stream->stream,
592 idev->buf_state, &area,
593 &area_offset);
594
595 /*
596 * The UI gain scaler should always take effect.
597 * input_data will decide if stream and iodev internal
598 * software gains should be used or not, based on use
599 * case.
600 */
601 software_gain_scaler =
602 cras_iodev_get_ui_gain_scaler(idev) *
603 input_data_get_software_gain_scaler(
604 idev->input_data,
605 idev->software_gain_scaler,
606 stream->stream);
607
608 this_read =
609 dev_stream_capture(stream, area, area_offset,
610 software_gain_scaler);
611
612 input_data_put_for_stream(idev->input_data,
613 stream->stream,
614 idev->buf_state, this_read);
615 }
616
617 rc = cras_iodev_put_input_buffer(idev);
618 if (rc < 0)
619 return rc;
620
621 total_read = rc;
622 remainder -= nread;
623
624 if (total_read < nread)
625 break;
626 }
627
628 ATLOG(atlog, AUDIO_THREAD_READ_AUDIO_DONE, remainder,
629 get_ewma_power_as_int(&idev->ewma), 0);
630
631 return 0;
632 }
633
634 /* Fill the buffer with samples from the attached streams.
635 * Args:
636 * odevs - The list of open output devices, provided so streams can be
637 * removed from all devices on error.
638 * adev - The device to write to.
639 * dst - The buffer to put the samples in (returned from snd_pcm_mmap_begin)
640 * write_limit - The maximum number of frames to write to dst.
641 *
642 * Returns:
643 * The number of frames rendered on success.
644 * This number of frames is the minimum of the amount of frames each stream
645 * could provide which is the maximum that can currently be rendered.
646 */
write_streams(struct open_dev ** odevs,struct open_dev * adev,uint8_t * dst,size_t write_limit)647 static unsigned int write_streams(struct open_dev **odevs,
648 struct open_dev *adev, uint8_t *dst,
649 size_t write_limit)
650 {
651 struct cras_iodev *odev = adev->dev;
652 struct dev_stream *curr;
653 unsigned int max_offset = 0;
654 unsigned int frame_bytes = cras_get_format_bytes(odev->format);
655 unsigned int num_playing = 0;
656 unsigned int drain_limit = write_limit;
657
658 /* Mix as much as we can, the minimum fill level of any stream. */
659 max_offset = cras_iodev_max_stream_offset(odev);
660
661 /* Mix as much as we can, the minimum fill level of any stream. */
662 DL_FOREACH (adev->dev->streams, curr) {
663 int dev_frames;
664
665 /* Skip stream which hasn't started running yet. */
666 if (!dev_stream_is_running(curr))
667 continue;
668
669 /* If this is a single output dev stream, updates the latest
670 * number of frames for playback. */
671 if (dev_stream_attached_devs(curr) == 1)
672 dev_stream_update_frames(curr);
673
674 dev_frames = dev_stream_playback_frames(curr);
675 if (dev_frames < 0) {
676 dev_io_remove_stream(odevs, curr->stream, NULL);
677 continue;
678 }
679 ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_STREAM,
680 curr->stream->stream_id, dev_frames,
681 dev_stream_is_pending_reply(curr));
682 if (cras_rstream_get_is_draining(curr->stream)) {
683 drain_limit = MIN((size_t)dev_frames, drain_limit);
684 if (!dev_frames)
685 dev_io_remove_stream(odevs, curr->stream, NULL);
686 } else {
687 write_limit = MIN((size_t)dev_frames, write_limit);
688 num_playing++;
689 }
690 }
691
692 if (!num_playing)
693 write_limit = drain_limit;
694
695 if (write_limit > max_offset)
696 memset(dst + max_offset * frame_bytes, 0,
697 (write_limit - max_offset) * frame_bytes);
698
699 ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_MIX, write_limit, max_offset,
700 0);
701
702 DL_FOREACH (adev->dev->streams, curr) {
703 unsigned int offset;
704 int nwritten;
705
706 if (!dev_stream_is_running(curr))
707 continue;
708
709 offset = cras_iodev_stream_offset(odev, curr);
710 if (offset >= write_limit)
711 continue;
712 nwritten = dev_stream_mix(curr, odev->format,
713 dst + frame_bytes * offset,
714 write_limit - offset);
715
716 if (nwritten < 0) {
717 dev_io_remove_stream(odevs, curr->stream, NULL);
718 continue;
719 }
720
721 cras_iodev_stream_written(odev, curr, nwritten);
722 }
723
724 write_limit = cras_iodev_all_streams_written(odev);
725
726 ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_MIXED, write_limit, 0, 0);
727
728 return write_limit;
729 }
730
731 /* Update next wake up time of the device.
732 * Args:
733 * adev[in] - The device to update to.
734 * hw_level[out] - Pointer to number of frames in hardware.
735 */
update_dev_wakeup_time(struct open_dev * adev,unsigned int * hw_level)736 void update_dev_wakeup_time(struct open_dev *adev, unsigned int *hw_level)
737 {
738 struct timespec now;
739 struct timespec sleep_time;
740 double est_rate;
741 unsigned int frames_to_play_in_sleep;
742
743 clock_gettime(CLOCK_MONOTONIC_RAW, &now);
744
745 frames_to_play_in_sleep = cras_iodev_frames_to_play_in_sleep(
746 adev->dev, hw_level, &adev->wake_ts);
747 if (!timespec_is_nonzero(&adev->wake_ts))
748 adev->wake_ts = now;
749
750 if (cras_iodev_state(adev->dev) == CRAS_IODEV_STATE_NORMAL_RUN)
751 cras_iodev_update_highest_hw_level(adev->dev, *hw_level);
752
753 est_rate = adev->dev->format->frame_rate *
754 cras_iodev_get_est_rate_ratio(adev->dev);
755
756 ATLOG(atlog, AUDIO_THREAD_SET_DEV_WAKE, adev->dev->info.idx, *hw_level,
757 frames_to_play_in_sleep);
758
759 cras_frames_to_time_precise(frames_to_play_in_sleep, est_rate,
760 &sleep_time);
761
762 add_timespecs(&adev->wake_ts, &sleep_time);
763
764 ATLOG(atlog, AUDIO_THREAD_DEV_SLEEP_TIME, adev->dev->info.idx,
765 adev->wake_ts.tv_sec, adev->wake_ts.tv_nsec);
766 }
767
768 /* Returns 0 on success negative error on device failure. */
write_output_samples(struct open_dev ** odevs,struct open_dev * adev,struct cras_fmt_conv * output_converter)769 int write_output_samples(struct open_dev **odevs, struct open_dev *adev,
770 struct cras_fmt_conv *output_converter)
771 {
772 struct cras_iodev *odev = adev->dev;
773 unsigned int hw_level;
774 struct timespec hw_tstamp;
775 unsigned int frames, fr_to_req;
776 snd_pcm_sframes_t written;
777 snd_pcm_uframes_t total_written = 0;
778 int rc;
779 int non_empty = 0;
780 int *non_empty_ptr = NULL;
781 uint8_t *dst = NULL;
782 struct cras_audio_area *area = NULL;
783
784 /* Possibly fill zeros for no_stream state and possibly transit state.
785 */
786 rc = cras_iodev_prepare_output_before_write_samples(odev);
787 if (rc < 0) {
788 syslog(LOG_ERR, "Failed to prepare output dev for write");
789 return rc;
790 }
791
792 if (cras_iodev_state(odev) != CRAS_IODEV_STATE_NORMAL_RUN)
793 return 0;
794
795 rc = cras_iodev_frames_queued(odev, &hw_tstamp);
796 if (rc < 0)
797 return rc;
798 hw_level = rc;
799
800 ATLOG(atlog, AUDIO_THREAD_FILL_AUDIO_TSTAMP, adev->dev->info.idx,
801 hw_tstamp.tv_sec, hw_tstamp.tv_nsec);
802 if (timespec_is_nonzero(&hw_tstamp)) {
803 if (hw_level < odev->min_cb_level / 2)
804 adev->coarse_rate_adjust = 1;
805 else if (hw_level > odev->max_cb_level * 2)
806 adev->coarse_rate_adjust = -1;
807 else
808 adev->coarse_rate_adjust = 0;
809
810 if (cras_iodev_update_rate(odev, hw_level, &hw_tstamp))
811 update_estimated_rate(adev, NULL, true);
812 }
813 ATLOG(atlog, AUDIO_THREAD_FILL_AUDIO, adev->dev->info.idx, hw_level,
814 odev->min_cb_level);
815
816 /* Don't request more than hardware can hold. Note that min_buffer_level
817 * has been subtracted from the actual hw_level so we need to take it
818 * into account here. */
819 fr_to_req = cras_iodev_buffer_avail(odev, hw_level);
820
821 /* Have to loop writing to the device, will be at most 2 loops, this
822 * only happens when the circular buffer is at the end and returns us a
823 * partial area to write to from mmap_begin */
824 while (total_written < fr_to_req) {
825 frames = fr_to_req - total_written;
826 rc = cras_iodev_get_output_buffer(odev, &area, &frames);
827 if (rc < 0)
828 return rc;
829
830 /* TODO(dgreid) - This assumes interleaved audio. */
831 dst = area->channels[0].buf;
832 written = write_streams(odevs, adev, dst, frames);
833 if (written < (snd_pcm_sframes_t)frames)
834 /* Got all the samples from client that we can, but it
835 * won't fill the request. */
836 fr_to_req = 0; /* break out after committing samples */
837
838 // This interval is lazily initialized once per device.
839 // Note that newly opened devices are considered non-empty
840 // (until their status is updated through the normal flow).
841 if (!adev->non_empty_check_pi) {
842 adev->non_empty_check_pi = pic_polled_interval_create(
843 NON_EMPTY_UPDATE_INTERVAL_SEC);
844 }
845
846 // If we were empty last iteration, or the sampling interval
847 // has elapsed, check for emptiness.
848 if (adev->empty_pi ||
849 pic_interval_elapsed(adev->non_empty_check_pi)) {
850 non_empty_ptr = &non_empty;
851 pic_interval_reset(adev->non_empty_check_pi);
852 }
853
854 rc = cras_iodev_put_output_buffer(
855 odev, dst, written, non_empty_ptr, output_converter);
856
857 if (rc < 0)
858 return rc;
859 total_written += written;
860
861 if (non_empty && adev->empty_pi) {
862 // We're not empty, but we were previously.
863 // Reset the empty period.
864 pic_polled_interval_destroy(&adev->empty_pi);
865 }
866
867 if (non_empty_ptr && !non_empty && !adev->empty_pi)
868 // We checked for emptiness, we were empty, and we
869 // previously weren't. Start the empty period.
870 adev->empty_pi = pic_polled_interval_create(
871 MIN_EMPTY_PERIOD_SEC);
872 }
873
874 ATLOG(atlog, AUDIO_THREAD_FILL_AUDIO_DONE, hw_level, total_written,
875 get_ewma_power_as_int(&odev->ewma));
876
877 return total_written;
878 }
879
880 /*
881 * Chooses the smallest difference between hw_level and min_cb_level as the
882 * drop time.
883 */
get_input_devices_drop_time(struct open_dev * idev_list,struct timespec * reset_ts)884 static void get_input_devices_drop_time(struct open_dev *idev_list,
885 struct timespec *reset_ts)
886 {
887 struct open_dev *adev;
888 struct cras_iodev *iodev;
889 struct timespec tmp;
890 struct timespec hw_tstamp;
891 double est_rate;
892 unsigned int target_level;
893 bool is_set = false;
894 int rc;
895
896 DL_FOREACH (idev_list, adev) {
897 iodev = adev->dev;
898 if (!input_devices_can_drop_samples(iodev))
899 continue;
900
901 rc = cras_iodev_frames_queued(iodev, &hw_tstamp);
902 if (rc < 0) {
903 syslog(LOG_ERR, "Get frames from device %d, rc = %d",
904 iodev->info.idx, rc);
905 continue;
906 }
907
908 target_level = iodev->min_cb_level;
909 if (rc <= target_level) {
910 reset_ts->tv_sec = 0;
911 reset_ts->tv_nsec = 0;
912 return;
913 }
914 est_rate = iodev->format->frame_rate *
915 cras_iodev_get_est_rate_ratio(iodev);
916 cras_frames_to_time(rc - target_level, est_rate, &tmp);
917
918 if (!is_set || timespec_after(reset_ts, &tmp)) {
919 *reset_ts = tmp;
920 is_set = true;
921 }
922 }
923 }
924
925 /*
926 * Drop samples from all input devices.
927 */
dev_io_drop_samples(struct open_dev * idev_list)928 static void dev_io_drop_samples(struct open_dev *idev_list)
929 {
930 struct open_dev *adev;
931 struct timespec drop_time = {};
932 int rc;
933
934 get_input_devices_drop_time(idev_list, &drop_time);
935 ATLOG(atlog, AUDIO_THREAD_CAPTURE_DROP_TIME, drop_time.tv_sec,
936 drop_time.tv_nsec, 0);
937
938 if (timespec_is_zero(&drop_time))
939 return;
940
941 DL_FOREACH (idev_list, adev) {
942 if (!input_devices_can_drop_samples(adev->dev))
943 continue;
944
945 rc = cras_iodev_drop_frames_by_time(adev->dev, drop_time);
946 if (rc < 0) {
947 syslog(LOG_ERR,
948 "Failed to drop frames from device %d, rc = %d",
949 adev->dev->info.idx, rc);
950 continue;
951 }
952 }
953
954 cras_audio_thread_event_drop_samples();
955
956 return;
957 }
958
959 /*
960 * Public funcitons.
961 */
962
dev_io_send_captured_samples(struct open_dev * idev_list)963 int dev_io_send_captured_samples(struct open_dev *idev_list)
964 {
965 struct open_dev *adev;
966 bool need_to_drop = false;
967 int rc;
968
969 // TODO(dgreid) - once per rstream, not once per dev_stream.
970 DL_FOREACH (idev_list, adev) {
971 struct dev_stream *stream;
972
973 if (!cras_iodev_is_open(adev->dev))
974 continue;
975
976 /* Post samples to rstream if there are enough samples. */
977 DL_FOREACH (adev->dev->streams, stream) {
978 dev_stream_capture_update_rstream(stream);
979 }
980
981 /* Set wake_ts for this device. */
982 rc = set_input_dev_wake_ts(adev, &need_to_drop);
983 if (rc < 0)
984 return rc;
985 }
986
987 if (need_to_drop)
988 dev_io_drop_samples(idev_list);
989
990 return 0;
991 }
992
handle_dev_err(int err_rc,struct open_dev ** odevs,struct open_dev * adev)993 static void handle_dev_err(int err_rc, struct open_dev **odevs,
994 struct open_dev *adev)
995 {
996 struct timespec diff, now;
997 if (err_rc == -EPIPE) {
998 /* Handle severe underrun. */
999 ATLOG(atlog, AUDIO_THREAD_SEVERE_UNDERRUN, adev->dev->info.idx,
1000 0, 0);
1001 cras_iodev_reset_request(adev->dev);
1002 cras_audio_thread_event_severe_underrun();
1003 } else if (err_rc == -EIO) {
1004 syslog(LOG_WARNING, "I/O err, reseting %s dev %s",
1005 adev->dev->direction == CRAS_STREAM_OUTPUT ? "output" :
1006 "input",
1007 adev->dev->info.name);
1008 clock_gettime(CLOCK_REALTIME, &now);
1009 subtract_timespecs(&now, &last_io_err_time, &diff);
1010 if ((last_io_err_time.tv_sec == 0 &&
1011 last_io_err_time.tv_nsec == 0) ||
1012 diff.tv_sec > ERROR_CLOSE_GAP_TIME_SECS)
1013 cras_iodev_reset_request(adev->dev);
1014 else
1015 cras_device_monitor_error_close(adev->dev->info.idx);
1016
1017 last_io_err_time = now;
1018 } else {
1019 syslog(LOG_ERR, "Dev %s err %d", adev->dev->info.name, err_rc);
1020 }
1021 /* Device error, remove it. */
1022 dev_io_rm_open_dev(odevs, adev);
1023 }
1024
dev_io_capture(struct open_dev ** list,struct open_dev ** olist)1025 int dev_io_capture(struct open_dev **list, struct open_dev **olist)
1026 {
1027 struct open_dev *idev_list = *list;
1028 struct open_dev *odev_list = *olist;
1029 struct open_dev *adev;
1030 int rc;
1031
1032 DL_FOREACH (idev_list, adev) {
1033 if (!cras_iodev_is_open(adev->dev))
1034 continue;
1035 rc = capture_to_streams(adev, odev_list);
1036 if (rc < 0)
1037 handle_dev_err(rc, list, adev);
1038 }
1039
1040 return 0;
1041 }
1042
1043 /* If it is the time to fetch, start dev_stream. */
dev_io_check_dev_stream_start(struct open_dev * adev)1044 static void dev_io_check_dev_stream_start(struct open_dev *adev)
1045 {
1046 struct dev_stream *dev_stream;
1047 struct timespec now;
1048 clock_gettime(CLOCK_MONOTONIC_RAW, &now);
1049
1050 DL_FOREACH (adev->dev->streams, dev_stream) {
1051 if (!is_time_to_fetch(dev_stream, now))
1052 continue;
1053 if (!dev_stream_is_running(dev_stream))
1054 cras_iodev_start_stream(adev->dev, dev_stream);
1055 }
1056 }
1057
dev_io_playback_fetch(struct open_dev * odev_list)1058 void dev_io_playback_fetch(struct open_dev *odev_list)
1059 {
1060 struct open_dev *adev;
1061
1062 /* Check whether it is the time to start dev_stream before fetching. */
1063 DL_FOREACH (odev_list, adev) {
1064 if (!cras_iodev_is_open(adev->dev))
1065 continue;
1066 dev_io_check_dev_stream_start(adev);
1067 }
1068
1069 DL_FOREACH (odev_list, adev) {
1070 if (!cras_iodev_is_open(adev->dev))
1071 continue;
1072 fetch_streams(adev);
1073 }
1074 }
1075
dev_io_playback_write(struct open_dev ** odevs,struct cras_fmt_conv * output_converter)1076 int dev_io_playback_write(struct open_dev **odevs,
1077 struct cras_fmt_conv *output_converter)
1078 {
1079 struct open_dev *adev;
1080 struct dev_stream *curr;
1081 int rc;
1082 unsigned int hw_level, total_written;
1083
1084 /* For multiple output case, update the number of queued frames in shm
1085 * of all streams before starting write output samples. */
1086 adev = *odevs;
1087 if (adev && adev->next) {
1088 DL_FOREACH (*odevs, adev) {
1089 DL_FOREACH (adev->dev->streams, curr)
1090 dev_stream_update_frames(curr);
1091 }
1092 }
1093
1094 DL_FOREACH (*odevs, adev) {
1095 if (!cras_iodev_is_open(adev->dev))
1096 continue;
1097
1098 rc = write_output_samples(odevs, adev, output_converter);
1099 if (rc < 0) {
1100 handle_dev_err(rc, odevs, adev);
1101 } else {
1102 total_written = rc;
1103
1104 /*
1105 * Skip the underrun check and device wake up time update if
1106 * device should not wake up.
1107 */
1108 if (!cras_iodev_odev_should_wake(adev->dev))
1109 continue;
1110
1111 /*
1112 * Update device wake up time and get the new hardware
1113 * level.
1114 */
1115 update_dev_wakeup_time(adev, &hw_level);
1116
1117 /*
1118 * If new hardware level is less than or equal to the
1119 * written frames, we can suppose underrun happened. But
1120 * keep in mind there may have a false positive. If
1121 * hardware level changed just after frames being
1122 * written, we may get hw_level <= total_written here
1123 * without underrun happened. However, we can still
1124 * treat it as underrun because it is an abnormal state
1125 * we should handle it.
1126 */
1127 if (hw_level <= total_written) {
1128 rc = cras_iodev_output_underrun(
1129 adev->dev, hw_level, total_written);
1130 if (rc < 0) {
1131 handle_dev_err(rc, odevs, adev);
1132 } else {
1133 update_dev_wakeup_time(adev, &hw_level);
1134 }
1135 }
1136 }
1137 }
1138
1139 /* TODO(dgreid) - once per rstream, not once per dev_stream. */
1140 DL_FOREACH (*odevs, adev) {
1141 struct dev_stream *stream;
1142 if (!cras_iodev_is_open(adev->dev))
1143 continue;
1144 DL_FOREACH (adev->dev->streams, stream) {
1145 dev_stream_playback_update_rstream(stream);
1146 }
1147 }
1148
1149 return 0;
1150 }
1151
update_longest_wake(struct open_dev * dev_list,const struct timespec * ts)1152 static void update_longest_wake(struct open_dev *dev_list,
1153 const struct timespec *ts)
1154 {
1155 struct open_dev *adev;
1156 struct timespec wake_interval;
1157
1158 DL_FOREACH (dev_list, adev) {
1159 if (adev->dev->streams == NULL)
1160 continue;
1161 /*
1162 * Calculate longest wake only when there's stream attached
1163 * and the last wake time has been set.
1164 */
1165 if (adev->last_wake.tv_sec) {
1166 subtract_timespecs(ts, &adev->last_wake,
1167 &wake_interval);
1168 if (timespec_after(&wake_interval, &adev->longest_wake))
1169 adev->longest_wake = wake_interval;
1170 }
1171 adev->last_wake = *ts;
1172 }
1173 }
1174
dev_io_run(struct open_dev ** odevs,struct open_dev ** idevs,struct cras_fmt_conv * output_converter)1175 void dev_io_run(struct open_dev **odevs, struct open_dev **idevs,
1176 struct cras_fmt_conv *output_converter)
1177 {
1178 struct timespec now;
1179
1180 clock_gettime(CLOCK_MONOTONIC_RAW, &now);
1181 pic_update_current_time();
1182 update_longest_wake(*odevs, &now);
1183 update_longest_wake(*idevs, &now);
1184
1185 dev_io_playback_fetch(*odevs);
1186 dev_io_capture(idevs, odevs);
1187 dev_io_send_captured_samples(*idevs);
1188 dev_io_playback_write(odevs, output_converter);
1189 }
1190
input_adev_ignore_wake(const struct open_dev * adev)1191 static int input_adev_ignore_wake(const struct open_dev *adev)
1192 {
1193 if (!cras_iodev_is_open(adev->dev))
1194 return 1;
1195
1196 if (!adev->dev->active_node)
1197 return 1;
1198
1199 if (adev->dev->active_node->type == CRAS_NODE_TYPE_HOTWORD &&
1200 !cras_iodev_input_streaming(adev->dev))
1201 return 1;
1202
1203 return 0;
1204 }
1205
dev_io_next_input_wake(struct open_dev ** idevs,struct timespec * min_ts)1206 int dev_io_next_input_wake(struct open_dev **idevs, struct timespec *min_ts)
1207 {
1208 struct open_dev *adev;
1209 int ret = 0; /* The total number of devices to wait on. */
1210
1211 DL_FOREACH (*idevs, adev) {
1212 if (input_adev_ignore_wake(adev))
1213 continue;
1214 ret++;
1215 ATLOG(atlog, AUDIO_THREAD_DEV_SLEEP_TIME, adev->dev->info.idx,
1216 adev->wake_ts.tv_sec, adev->wake_ts.tv_nsec);
1217 if (timespec_after(min_ts, &adev->wake_ts))
1218 *min_ts = adev->wake_ts;
1219 }
1220
1221 return ret;
1222 }
1223
1224 /* Fills the time that the next stream needs to be serviced. */
get_next_stream_wake_from_list(struct dev_stream * streams,struct timespec * min_ts)1225 static int get_next_stream_wake_from_list(struct dev_stream *streams,
1226 struct timespec *min_ts)
1227 {
1228 struct dev_stream *dev_stream;
1229 int ret = 0; /* The total number of streams to wait on. */
1230
1231 DL_FOREACH (streams, dev_stream) {
1232 const struct timespec *next_cb_ts;
1233
1234 if (cras_rstream_get_is_draining(dev_stream->stream))
1235 continue;
1236
1237 if (cras_rstream_is_pending_reply(dev_stream->stream))
1238 continue;
1239
1240 next_cb_ts = dev_stream_next_cb_ts(dev_stream);
1241 if (!next_cb_ts)
1242 continue;
1243
1244 ATLOG(atlog, AUDIO_THREAD_STREAM_SLEEP_TIME,
1245 dev_stream->stream->stream_id, next_cb_ts->tv_sec,
1246 next_cb_ts->tv_nsec);
1247 if (timespec_after(min_ts, next_cb_ts))
1248 *min_ts = *next_cb_ts;
1249 ret++;
1250 }
1251
1252 return ret;
1253 }
1254
dev_io_next_output_wake(struct open_dev ** odevs,struct timespec * min_ts)1255 int dev_io_next_output_wake(struct open_dev **odevs, struct timespec *min_ts)
1256 {
1257 struct open_dev *adev;
1258 int ret = 0;
1259
1260 DL_FOREACH (*odevs, adev)
1261 ret += get_next_stream_wake_from_list(adev->dev->streams,
1262 min_ts);
1263
1264 DL_FOREACH (*odevs, adev) {
1265 if (!cras_iodev_odev_should_wake(adev->dev))
1266 continue;
1267
1268 ret++;
1269 if (timespec_after(min_ts, &adev->wake_ts))
1270 *min_ts = adev->wake_ts;
1271 }
1272
1273 return ret;
1274 }
1275
dev_io_find_open_dev(struct open_dev * odev_list,unsigned int dev_idx)1276 struct open_dev *dev_io_find_open_dev(struct open_dev *odev_list,
1277 unsigned int dev_idx)
1278 {
1279 struct open_dev *odev;
1280 DL_FOREACH (odev_list, odev)
1281 if (odev->dev->info.idx == dev_idx)
1282 return odev;
1283 return NULL;
1284 }
1285
dev_io_rm_open_dev(struct open_dev ** odev_list,struct open_dev * dev_to_rm)1286 void dev_io_rm_open_dev(struct open_dev **odev_list, struct open_dev *dev_to_rm)
1287 {
1288 struct open_dev *odev;
1289 struct dev_stream *dev_stream;
1290
1291 /* Do nothing if dev_to_rm wasn't already in the active dev list. */
1292 DL_FOREACH (*odev_list, odev) {
1293 if (odev == dev_to_rm)
1294 break;
1295 }
1296 if (!odev)
1297 return;
1298
1299 DL_DELETE(*odev_list, dev_to_rm);
1300
1301 /* Metrics logs the number of underruns of this device. */
1302 cras_server_metrics_num_underruns(
1303 cras_iodev_get_num_underruns(dev_to_rm->dev));
1304
1305 /* Metrics logs the delay of this device. */
1306 cras_server_metrics_highest_device_delay(
1307 dev_to_rm->dev->highest_hw_level,
1308 dev_to_rm->dev->largest_cb_level, dev_to_rm->dev->direction);
1309
1310 /* Metrics logs the highest_hw_level of this device. */
1311 cras_server_metrics_highest_hw_level(dev_to_rm->dev->highest_hw_level,
1312 dev_to_rm->dev->direction);
1313
1314 dev_io_check_non_empty_state_transition(*odev_list);
1315
1316 ATLOG(atlog, AUDIO_THREAD_DEV_REMOVED, dev_to_rm->dev->info.idx, 0, 0);
1317
1318 DL_FOREACH (dev_to_rm->dev->streams, dev_stream) {
1319 cras_iodev_rm_stream(dev_to_rm->dev, dev_stream->stream);
1320 dev_stream_destroy(dev_stream);
1321 }
1322
1323 if (dev_to_rm->empty_pi)
1324 pic_polled_interval_destroy(&dev_to_rm->empty_pi);
1325 if (dev_to_rm->non_empty_check_pi)
1326 pic_polled_interval_destroy(&dev_to_rm->non_empty_check_pi);
1327 free(dev_to_rm);
1328 }
1329
delete_stream_from_dev(struct cras_iodev * dev,struct cras_rstream * stream)1330 static void delete_stream_from_dev(struct cras_iodev *dev,
1331 struct cras_rstream *stream)
1332 {
1333 struct dev_stream *out;
1334
1335 out = cras_iodev_rm_stream(dev, stream);
1336 if (out)
1337 dev_stream_destroy(out);
1338 }
1339
1340 /*
1341 * Finds a matched input stream from open device list.
1342 * The definition of the matched streams: Two streams having
1343 * the same sampling rate and the same cb_threshold.
1344 * This means their sleep time intervals should be very close
1345 * if we neglect device estimated rate.
1346 */
1347 static struct dev_stream *
find_matched_input_stream(const struct cras_rstream * out_stream,struct open_dev * odev_list)1348 find_matched_input_stream(const struct cras_rstream *out_stream,
1349 struct open_dev *odev_list)
1350 {
1351 struct open_dev *odev;
1352 struct dev_stream *dev_stream;
1353 size_t out_rate = out_stream->format.frame_rate;
1354 size_t out_cb_threshold = cras_rstream_get_cb_threshold(out_stream);
1355
1356 DL_FOREACH (odev_list, odev) {
1357 DL_FOREACH (odev->dev->streams, dev_stream) {
1358 if (dev_stream->stream->format.frame_rate != out_rate)
1359 continue;
1360 if (cras_rstream_get_cb_threshold(dev_stream->stream) !=
1361 out_cb_threshold)
1362 continue;
1363 return dev_stream;
1364 }
1365 }
1366 return NULL;
1367 }
1368
1369 static bool
find_matched_input_stream_next_cb_ts(const struct cras_rstream * stream,struct open_dev * odev_list,const struct timespec ** next_cb_ts,const struct timespec ** sleep_interval_ts)1370 find_matched_input_stream_next_cb_ts(const struct cras_rstream *stream,
1371 struct open_dev *odev_list,
1372 const struct timespec **next_cb_ts,
1373 const struct timespec **sleep_interval_ts)
1374 {
1375 struct dev_stream *dev_stream =
1376 find_matched_input_stream(stream, odev_list);
1377 if (dev_stream) {
1378 *next_cb_ts = dev_stream_next_cb_ts(dev_stream);
1379 *sleep_interval_ts = dev_stream_sleep_interval_ts(dev_stream);
1380 return *next_cb_ts != NULL;
1381 }
1382 return false;
1383 }
1384
dev_io_append_stream(struct open_dev ** odevs,struct open_dev ** idevs,struct cras_rstream * stream,struct cras_iodev ** iodevs,unsigned int num_iodevs)1385 int dev_io_append_stream(struct open_dev **odevs, struct open_dev **idevs,
1386 struct cras_rstream *stream,
1387 struct cras_iodev **iodevs, unsigned int num_iodevs)
1388 {
1389 struct open_dev **dev_list;
1390 struct open_dev *open_dev;
1391 struct cras_iodev *dev;
1392 struct dev_stream *out;
1393 struct timespec init_cb_ts;
1394 const struct timespec *init_sleep_interval_ts = NULL;
1395 struct timespec extra_sleep;
1396 const struct timespec *stream_ts;
1397 unsigned int i;
1398 bool cb_ts_set = false;
1399 int level;
1400 int rc = 0;
1401
1402 if (stream->direction == CRAS_STREAM_OUTPUT)
1403 dev_list = odevs;
1404 else
1405 dev_list = idevs;
1406
1407 for (i = 0; i < num_iodevs; i++) {
1408 DL_SEARCH_SCALAR(*dev_list, open_dev, dev, iodevs[i]);
1409 if (!open_dev)
1410 continue;
1411
1412 dev = iodevs[i];
1413 DL_SEARCH_SCALAR(dev->streams, out, stream, stream);
1414 if (out)
1415 continue;
1416
1417 /*
1418 * When dev transitions from no stream to the 1st stream, reset
1419 * last_wake and longest_wake so it can start over the tracking.
1420 */
1421 if (dev->streams == NULL) {
1422 open_dev->last_wake.tv_sec = 0;
1423 open_dev->last_wake.tv_nsec = 0;
1424 open_dev->longest_wake.tv_sec = 0;
1425 open_dev->longest_wake.tv_nsec = 0;
1426 }
1427
1428 /*
1429 * When the first input stream is added, flush the input buffer
1430 * so that we can read from multiple input devices of the same
1431 * buffer level.
1432 */
1433 if ((stream->direction == CRAS_STREAM_INPUT) && !dev->streams) {
1434 int num_flushed = dev->flush_buffer(dev);
1435 if (num_flushed < 0) {
1436 rc = num_flushed;
1437 break;
1438 }
1439 }
1440
1441 /*
1442 * For output, if open device already has stream, get the earliest next
1443 * callback time from these streams to align with. Otherwise, check whether
1444 * there are remaining frames in the device. Set the initial callback time to
1445 * the time when hw_level of device is close to min_cb_level.
1446 * If next callback time is too far from now, it will block writing and
1447 * lower hardware level. Else if we fetch the new stream immediately, it
1448 * may cause device buffer level stack up.
1449 */
1450 if (stream->direction == CRAS_STREAM_OUTPUT) {
1451 /*
1452 * If there is a matched input stream, find its next cb time.
1453 * Use that as the initial cb time for this output stream.
1454 */
1455 const struct timespec *in_stream_ts;
1456 const struct timespec *in_stream_sleep_interval_ts;
1457 bool found_matched_input;
1458 found_matched_input =
1459 find_matched_input_stream_next_cb_ts(
1460 stream, *idevs, &in_stream_ts,
1461 &in_stream_sleep_interval_ts);
1462 if (found_matched_input) {
1463 init_cb_ts = *in_stream_ts;
1464 init_sleep_interval_ts =
1465 in_stream_sleep_interval_ts;
1466 } else {
1467 DL_FOREACH (dev->streams, out) {
1468 stream_ts = dev_stream_next_cb_ts(out);
1469 if (stream_ts &&
1470 (!cb_ts_set ||
1471 timespec_after(&init_cb_ts,
1472 stream_ts))) {
1473 init_cb_ts = *stream_ts;
1474 cb_ts_set = true;
1475 }
1476 }
1477 if (!cb_ts_set) {
1478 level = cras_iodev_get_valid_frames(
1479 dev, &init_cb_ts);
1480 if (level < 0) {
1481 syslog(LOG_ERR,
1482 "Failed to set output init_cb_ts, rc = %d",
1483 level);
1484 rc = -EINVAL;
1485 break;
1486 }
1487 level -= cras_frames_at_rate(
1488 stream->format.frame_rate,
1489 cras_rstream_get_cb_threshold(
1490 stream),
1491 dev->format->frame_rate);
1492 if (level < 0)
1493 level = 0;
1494 cras_frames_to_time(
1495 level, dev->format->frame_rate,
1496 &extra_sleep);
1497 add_timespecs(&init_cb_ts,
1498 &extra_sleep);
1499 }
1500 }
1501 } else {
1502 /*
1503 * For input streams, because audio thread can calculate wake up time
1504 * by hw_level of input device, set the first cb_ts to zero. The stream
1505 * will wake up when it gets enough samples to post. The next_cb_ts will
1506 * be updated after its first post.
1507 *
1508 * TODO(yuhsuan) - Align the new stream fetch time to avoid getting a large
1509 * delay. If a new stream with smaller block size starts when the hardware
1510 * level is high, the hardware level will keep high after removing other
1511 * old streams.
1512 */
1513 init_cb_ts.tv_sec = 0;
1514 init_cb_ts.tv_nsec = 0;
1515 }
1516
1517 out = dev_stream_create(stream, dev->info.idx, dev->format, dev,
1518 &init_cb_ts, init_sleep_interval_ts);
1519 if (!out) {
1520 rc = -EINVAL;
1521 break;
1522 }
1523
1524 cras_iodev_add_stream(dev, out);
1525
1526 /*
1527 * For multiple inputs case, if the new stream is not the first
1528 * one to append, copy the 1st stream's offset to it so that
1529 * future read offsets can be aligned across all input streams
1530 * to avoid the deadlock scenario when multiple streams reading
1531 * from multiple devices.
1532 */
1533 if ((stream->direction == CRAS_STREAM_INPUT) &&
1534 (dev->streams != out)) {
1535 unsigned int offset =
1536 cras_iodev_stream_offset(dev, dev->streams);
1537 if (offset > stream->cb_threshold)
1538 offset = stream->cb_threshold;
1539 cras_iodev_stream_written(dev, out, offset);
1540
1541 offset = cras_rstream_dev_offset(dev->streams->stream,
1542 dev->info.idx);
1543 if (offset > stream->cb_threshold)
1544 offset = stream->cb_threshold;
1545 cras_rstream_dev_offset_update(stream, offset,
1546 dev->info.idx);
1547 }
1548 ATLOG(atlog, AUDIO_THREAD_STREAM_ADDED, stream->stream_id,
1549 dev->info.idx, 0);
1550 }
1551
1552 if (rc) {
1553 DL_FOREACH (*dev_list, open_dev) {
1554 dev = open_dev->dev;
1555 DL_SEARCH_SCALAR(dev->streams, out, stream, stream);
1556 if (!out)
1557 continue;
1558
1559 cras_iodev_rm_stream(dev, stream);
1560 dev_stream_destroy(out);
1561 }
1562 }
1563
1564 return rc;
1565 }
1566
dev_io_remove_stream(struct open_dev ** dev_list,struct cras_rstream * stream,struct cras_iodev * dev)1567 int dev_io_remove_stream(struct open_dev **dev_list,
1568 struct cras_rstream *stream, struct cras_iodev *dev)
1569 {
1570 struct open_dev *open_dev;
1571
1572 ATLOG(atlog, AUDIO_THREAD_STREAM_REMOVED, stream->stream_id, 0, 0);
1573
1574 if (dev == NULL) {
1575 DL_FOREACH (*dev_list, open_dev) {
1576 delete_stream_from_dev(open_dev->dev, stream);
1577 }
1578 } else {
1579 delete_stream_from_dev(dev, stream);
1580 }
1581
1582 return 0;
1583 }
1584