• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include <syslog.h>
7 
8 #include "audio_thread_log.h"
9 #include "byte_buffer.h"
10 #include "cras_fmt_conv.h"
11 #include "dev_stream.h"
12 #include "cras_audio_area.h"
13 #include "cras_mix.h"
14 #include "cras_shm.h"
15 
16 /*
17  * Sleep this much time past the buffer size to be sure at least
18  * the buffer size is captured when the audio thread wakes up.
19  */
20 static const unsigned int capture_extra_sleep_frames = 20;
21 /* Adjust device's sample rate by this step faster or slower. Used
22  * to make sure multiple active device has stable buffer level.
23  */
24 static const int coarse_rate_adjust_step = 3;
25 
26 /*
27  * Allow capture callback to fire this much earlier than the scheduled
28  * next_cb_ts to avoid an extra wake of audio thread.
29  */
30 static const struct timespec capture_callback_fuzz_ts = {
31 	.tv_sec = 0,
32 	.tv_nsec = 1000000, /* 1 ms. */
33 };
34 
35 /*
36  * Returns the size in frames that a format converter must allocate for its
37  * temporary buffers to be able to convert the specified number of stream
38  * frames to or from the corresponding number of device frames, at the
39  * specified device rate.
40  */
max_frames_for_conversion(unsigned int stream_frames,unsigned int stream_rate,unsigned int device_rate)41 unsigned int max_frames_for_conversion(unsigned int stream_frames,
42 				       unsigned int stream_rate,
43 				       unsigned int device_rate) {
44 	/*
45 	 * There are multiple temp buffers in the format converter,
46 	 * which are all the same size. Some of these contain audio
47 	 * in the source sample rate, and others in the converted
48 	 * sample rate. We need to make sure the converter is large
49 	 * enough to hold either.
50 	 */
51 	return MAX(
52 	    // Number of stream frames does not require conversion.
53 	    stream_frames,
54 	    // Calculate corresponding number of frames at device rate.
55 	    cras_frames_at_rate(stream_rate,
56 				stream_frames,
57 				device_rate))
58 			/*
59 			 * Add 1 because the linear resampler's frame rate
60 			 * conversion does this, and is used to calculate
61 			 * how many frames to read from the device.
62 			 * See linear_resampler_{in,out}_frames_to_{out,in}(..)
63 			 */
64 			+ 1;
65 }
66 
dev_stream_create(struct cras_rstream * stream,unsigned int dev_id,const struct cras_audio_format * dev_fmt,void * dev_ptr,struct timespec * cb_ts)67 struct dev_stream *dev_stream_create(struct cras_rstream *stream,
68 				     unsigned int dev_id,
69 				     const struct cras_audio_format *dev_fmt,
70 				     void *dev_ptr,
71 				     struct timespec *cb_ts)
72 {
73 	struct dev_stream *out;
74 	struct cras_audio_format *stream_fmt = &stream->format;
75 	int rc = 0;
76 	unsigned int max_frames, dev_frames, buf_bytes;
77 	const struct cras_audio_format *ofmt;
78 
79 	out = calloc(1, sizeof(*out));
80 	out->dev_id = dev_id;
81 	out->stream = stream;
82 	out->dev_rate = dev_fmt->frame_rate;
83 
84 	max_frames = max_frames_for_conversion(stream->buffer_frames,
85 					       stream_fmt->frame_rate,
86 					       dev_fmt->frame_rate);
87 
88 	if (stream->direction == CRAS_STREAM_OUTPUT) {
89 		rc = config_format_converter(&out->conv,
90 					     stream->direction,
91 					     stream_fmt,
92 					     dev_fmt,
93 					     max_frames);
94 	} else {
95 		/*
96 		 * For input, take into account the stream specific processing
97 		 * like AEC. Use the post processing format to configure format
98 		 * converter.
99 		 */
100 		ofmt = cras_rstream_post_processing_format(
101 				stream, dev_ptr) ? : dev_fmt,
102 		rc = config_format_converter(&out->conv,
103 					     stream->direction,
104 					     ofmt,
105 					     stream_fmt,
106 					     max_frames);
107 	}
108 	if (rc) {
109 		free(out);
110 		return NULL;
111 	}
112 
113 	ofmt = cras_fmt_conv_out_format(out->conv);
114 
115 	dev_frames = (stream->direction == CRAS_STREAM_OUTPUT)
116 		? cras_fmt_conv_in_frames_to_out(out->conv,
117 						 stream->buffer_frames)
118 		: cras_fmt_conv_out_frames_to_in(out->conv,
119 						 stream->buffer_frames);
120 
121 	out->conv_buffer_size_frames = 2 * MAX(dev_frames,
122 					       stream->buffer_frames);
123 
124 	/* Create conversion buffer and area using the output format
125 	 * of the format converter. Note that this format might not be
126 	 * identical to stream_fmt for capture. */
127 	buf_bytes = out->conv_buffer_size_frames * cras_get_format_bytes(ofmt);
128 	out->conv_buffer = byte_buffer_create(buf_bytes);
129 	out->conv_area = cras_audio_area_create(ofmt->num_channels);
130 
131 	cras_frames_to_time(cras_rstream_get_cb_threshold(stream),
132 			    stream_fmt->frame_rate,
133 			    &stream->sleep_interval_ts);
134 	stream->next_cb_ts = *cb_ts;
135 
136 	if (stream->direction != CRAS_STREAM_OUTPUT) {
137 		struct timespec extra_sleep;
138 
139 		cras_frames_to_time(capture_extra_sleep_frames,
140 				    stream->format.frame_rate, &extra_sleep);
141 		add_timespecs(&stream->next_cb_ts, &stream->sleep_interval_ts);
142 		add_timespecs(&stream->next_cb_ts, &extra_sleep);
143 	}
144 
145 	cras_rstream_dev_attach(stream, dev_id, dev_ptr);
146 
147 	return out;
148 }
149 
dev_stream_destroy(struct dev_stream * dev_stream)150 void dev_stream_destroy(struct dev_stream *dev_stream)
151 {
152 	cras_rstream_dev_detach(dev_stream->stream, dev_stream->dev_id);
153 	if (dev_stream->conv) {
154 		cras_audio_area_destroy(dev_stream->conv_area);
155 		cras_fmt_conv_destroy(&dev_stream->conv);
156 		byte_buffer_destroy(&dev_stream->conv_buffer);
157 	}
158 	free(dev_stream);
159 }
160 
dev_stream_set_dev_rate(struct dev_stream * dev_stream,unsigned int dev_rate,double dev_rate_ratio,double master_rate_ratio,int coarse_rate_adjust)161 void dev_stream_set_dev_rate(struct dev_stream *dev_stream,
162 			     unsigned int dev_rate,
163 			     double dev_rate_ratio,
164 			     double master_rate_ratio,
165 			     int coarse_rate_adjust)
166 {
167 	if (dev_stream->dev_id == dev_stream->stream->master_dev.dev_id) {
168 		cras_fmt_conv_set_linear_resample_rates(
169 				dev_stream->conv,
170 				dev_rate,
171 				dev_rate);
172 		cras_frames_to_time_precise(
173 			cras_rstream_get_cb_threshold(dev_stream->stream),
174 			dev_stream->stream->format.frame_rate * dev_rate_ratio,
175 			&dev_stream->stream->sleep_interval_ts);
176 	} else {
177 		double new_rate = dev_rate * dev_rate_ratio /
178 				master_rate_ratio +
179 				coarse_rate_adjust_step * coarse_rate_adjust;
180 		cras_fmt_conv_set_linear_resample_rates(
181 				dev_stream->conv,
182 				dev_rate,
183 				new_rate);
184 	}
185 
186 }
187 
dev_stream_mix(struct dev_stream * dev_stream,const struct cras_audio_format * fmt,uint8_t * dst,unsigned int num_to_write)188 int dev_stream_mix(struct dev_stream *dev_stream,
189 		   const struct cras_audio_format *fmt,
190 		   uint8_t *dst,
191 		   unsigned int num_to_write)
192 {
193 	struct cras_rstream *rstream = dev_stream->stream;
194 	uint8_t *src;
195 	uint8_t *target = dst;
196 	unsigned int fr_written, fr_read;
197 	unsigned int buffer_offset;
198 	int fr_in_buf;
199 	unsigned int num_samples;
200 	size_t frames = 0;
201 	unsigned int dev_frames;
202 	float mix_vol;
203 
204 	fr_in_buf = dev_stream_playback_frames(dev_stream);
205 	if (fr_in_buf <= 0)
206 		return fr_in_buf;
207 	if (fr_in_buf < num_to_write)
208 		num_to_write = fr_in_buf;
209 
210 	buffer_offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
211 
212 	/* Stream volume scaler. */
213 	mix_vol = cras_rstream_get_volume_scaler(dev_stream->stream);
214 
215 	fr_written = 0;
216 	fr_read = 0;
217 	while (fr_written < num_to_write) {
218 		unsigned int read_frames;
219 		src = cras_rstream_get_readable_frames(
220 				rstream, buffer_offset + fr_read, &frames);
221 		if (frames == 0)
222 			break;
223 		if (cras_fmt_conversion_needed(dev_stream->conv)) {
224 			read_frames = frames;
225 			dev_frames = cras_fmt_conv_convert_frames(
226 					dev_stream->conv,
227 					src,
228 					dev_stream->conv_buffer->bytes,
229 					&read_frames,
230 					num_to_write - fr_written);
231 			src = dev_stream->conv_buffer->bytes;
232 		} else {
233 			dev_frames = MIN(frames, num_to_write - fr_written);
234 			read_frames = dev_frames;
235 		}
236 		num_samples = dev_frames * fmt->num_channels;
237 		cras_mix_add(fmt->format, target, src, num_samples, 1,
238 			     cras_rstream_get_mute(rstream), mix_vol);
239 		target += dev_frames * cras_get_format_bytes(fmt);
240 		fr_written += dev_frames;
241 		fr_read += read_frames;
242 	}
243 
244 	cras_rstream_dev_offset_update(rstream, fr_read, dev_stream->dev_id);
245 	ATLOG(atlog, AUDIO_THREAD_DEV_STREAM_MIX,
246 				    fr_written, fr_read, 0);
247 
248 	return fr_written;
249 }
250 
251 /* Copy from the captured buffer to the temporary format converted buffer. */
capture_with_fmt_conv(struct dev_stream * dev_stream,const uint8_t * source_samples,unsigned int num_frames)252 static unsigned int capture_with_fmt_conv(struct dev_stream *dev_stream,
253 					  const uint8_t *source_samples,
254 					  unsigned int num_frames)
255 {
256 	const struct cras_audio_format *source_format;
257 	const struct cras_audio_format *dst_format;
258 	uint8_t *buffer;
259 	unsigned int total_read = 0;
260 	unsigned int write_frames;
261 	unsigned int read_frames;
262 	unsigned int source_frame_bytes;
263 	unsigned int dst_frame_bytes;
264 
265 	source_format = cras_fmt_conv_in_format(dev_stream->conv);
266 	source_frame_bytes = cras_get_format_bytes(source_format);
267 	dst_format = cras_fmt_conv_out_format(dev_stream->conv);
268 	dst_frame_bytes = cras_get_format_bytes(dst_format);
269 
270 	dev_stream->conv_area->num_channels = dst_format->num_channels;
271 
272 	while (total_read < num_frames) {
273 		buffer = buf_write_pointer_size(dev_stream->conv_buffer,
274 						&write_frames);
275 		write_frames /= dst_frame_bytes;
276 		if (write_frames == 0)
277 			break;
278 
279 		read_frames = num_frames - total_read;
280 		write_frames = cras_fmt_conv_convert_frames(
281 				dev_stream->conv,
282 				source_samples,
283 				buffer,
284 				&read_frames,
285 				write_frames);
286 		total_read += read_frames;
287 		source_samples += read_frames * source_frame_bytes;
288 		buf_increment_write(dev_stream->conv_buffer,
289 				    write_frames * dst_frame_bytes);
290 	}
291 
292 	return total_read;
293 }
294 
295 /* Copy from the converted buffer to the stream shm.  These have the same format
296  * at this point. */
capture_copy_converted_to_stream(struct dev_stream * dev_stream,struct cras_rstream * rstream,float software_gain_scaler)297 static unsigned int capture_copy_converted_to_stream(
298 		struct dev_stream *dev_stream,
299 		struct cras_rstream *rstream,
300 		float software_gain_scaler)
301 {
302 	struct cras_audio_shm *shm;
303 	uint8_t *stream_samples;
304 	uint8_t *converted_samples;
305 	unsigned int num_frames;
306 	unsigned int total_written = 0;
307 	unsigned int write_frames;
308 	unsigned int frame_bytes;
309 	unsigned int offset;
310 	const struct cras_audio_format *fmt;
311 
312 	shm = cras_rstream_input_shm(rstream);
313 
314 	fmt = cras_fmt_conv_out_format(dev_stream->conv);
315 	frame_bytes = cras_get_format_bytes(fmt);
316 
317 	offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
318 
319 	stream_samples = cras_shm_get_writeable_frames(
320 			shm,
321 			cras_rstream_get_cb_threshold(rstream),
322 			&rstream->audio_area->frames);
323 	num_frames = MIN(rstream->audio_area->frames - offset,
324 			 buf_queued(dev_stream->conv_buffer) /
325 							frame_bytes);
326 
327 	ATLOG(atlog, AUDIO_THREAD_CONV_COPY,
328 				    shm->area->write_buf_idx,
329 				    rstream->audio_area->frames,
330 				    offset);
331 
332 	while (total_written < num_frames) {
333 		converted_samples =
334 			buf_read_pointer_size(dev_stream->conv_buffer,
335 					      &write_frames);
336 		write_frames /= frame_bytes;
337 		write_frames = MIN(write_frames, num_frames - total_written);
338 
339 		cras_audio_area_config_buf_pointers(dev_stream->conv_area,
340 						    fmt,
341 						    converted_samples);
342 		cras_audio_area_config_channels(dev_stream->conv_area, fmt);
343 		dev_stream->conv_area->frames = write_frames;
344 
345 		cras_audio_area_config_buf_pointers(rstream->audio_area,
346 						    &rstream->format,
347 						    stream_samples);
348 
349 		cras_audio_area_copy(rstream->audio_area, offset,
350 				     &rstream->format,
351 				     dev_stream->conv_area, 0,
352 				     software_gain_scaler);
353 
354 		buf_increment_read(dev_stream->conv_buffer,
355 				   write_frames * frame_bytes);
356 		total_written += write_frames;
357 		cras_rstream_dev_offset_update(rstream, write_frames,
358 					       dev_stream->dev_id);
359 		offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
360 	}
361 
362 	ATLOG(atlog, AUDIO_THREAD_CAPTURE_WRITE,
363 				    rstream->stream_id,
364 				    total_written,
365 				    cras_shm_frames_written(shm));
366 	return total_written;
367 }
368 
dev_stream_capture(struct dev_stream * dev_stream,const struct cras_audio_area * area,unsigned int area_offset,float software_gain_scaler)369 unsigned int dev_stream_capture(struct dev_stream *dev_stream,
370 			const struct cras_audio_area *area,
371 			unsigned int area_offset,
372 			float software_gain_scaler)
373 {
374 	struct cras_rstream *rstream = dev_stream->stream;
375 	struct cras_audio_shm *shm;
376 	uint8_t *stream_samples;
377 	unsigned int nread;
378 
379 	/* Check if format conversion is needed. */
380 	if (cras_fmt_conversion_needed(dev_stream->conv)) {
381 		unsigned int format_bytes, fr_to_capture;
382 
383 		fr_to_capture = dev_stream_capture_avail(dev_stream);
384 		fr_to_capture = MIN(fr_to_capture, area->frames - area_offset);
385 
386 		format_bytes = cras_get_format_bytes(
387 				cras_fmt_conv_in_format(dev_stream->conv));
388 		nread = capture_with_fmt_conv(
389 			dev_stream,
390 			area->channels[0].buf + area_offset * format_bytes,
391 			fr_to_capture);
392 
393 		capture_copy_converted_to_stream(dev_stream, rstream,
394 						 software_gain_scaler);
395 	} else {
396 		unsigned int offset =
397 			cras_rstream_dev_offset(rstream, dev_stream->dev_id);
398 
399 		/* Set up the shm area and copy to it. */
400 		shm = cras_rstream_input_shm(rstream);
401 		stream_samples = cras_shm_get_writeable_frames(
402 				shm,
403 				cras_rstream_get_cb_threshold(rstream),
404 				&rstream->audio_area->frames);
405 		cras_audio_area_config_buf_pointers(rstream->audio_area,
406 						    &rstream->format,
407 						    stream_samples);
408 
409 		nread = cras_audio_area_copy(rstream->audio_area, offset,
410 					     &rstream->format, area,
411 					     area_offset,
412 					     software_gain_scaler);
413 
414 		ATLOG(atlog, AUDIO_THREAD_CAPTURE_WRITE,
415 					    rstream->stream_id,
416 					    nread,
417 					    cras_shm_frames_written(shm));
418 		cras_rstream_dev_offset_update(rstream, nread,
419 					       dev_stream->dev_id);
420 	}
421 
422 	return nread;
423 }
424 
dev_stream_attached_devs(const struct dev_stream * dev_stream)425 int dev_stream_attached_devs(const struct dev_stream *dev_stream)
426 {
427 	return dev_stream->stream->num_attached_devs;
428 }
429 
dev_stream_update_frames(const struct dev_stream * dev_stream)430 void dev_stream_update_frames(const struct dev_stream *dev_stream)
431 {
432 	cras_rstream_update_queued_frames(dev_stream->stream);
433 }
434 
dev_stream_playback_frames(const struct dev_stream * dev_stream)435 int dev_stream_playback_frames(const struct dev_stream *dev_stream)
436 {
437 	int frames;
438 
439 	frames = cras_rstream_playable_frames(dev_stream->stream,
440 					      dev_stream->dev_id);
441 	if (frames < 0)
442 		return frames;
443 
444 	if (!dev_stream->conv)
445 		return frames;
446 
447 	return cras_fmt_conv_in_frames_to_out(dev_stream->conv, frames);
448 }
449 
dev_stream_cb_threshold(const struct dev_stream * dev_stream)450 unsigned int dev_stream_cb_threshold(const struct dev_stream *dev_stream)
451 {
452 	const struct cras_rstream *rstream = dev_stream->stream;
453 	unsigned int cb_threshold = cras_rstream_get_cb_threshold(rstream);
454 
455 	if (rstream->direction == CRAS_STREAM_OUTPUT)
456 		return cras_fmt_conv_in_frames_to_out(dev_stream->conv,
457 						      cb_threshold);
458 	else
459 		return cras_fmt_conv_out_frames_to_in(dev_stream->conv,
460 						      cb_threshold);
461 }
462 
dev_stream_capture_avail(const struct dev_stream * dev_stream)463 unsigned int dev_stream_capture_avail(const struct dev_stream *dev_stream)
464 {
465 	struct cras_audio_shm *shm;
466 	struct cras_rstream *rstream = dev_stream->stream;
467 	unsigned int frames_avail;
468 	unsigned int conv_buf_level;
469 	unsigned int format_bytes;
470 	unsigned int wlimit;
471 	unsigned int dev_offset =
472 		cras_rstream_dev_offset(rstream, dev_stream->dev_id);
473 
474 	shm = cras_rstream_input_shm(rstream);
475 
476 	wlimit = cras_rstream_get_max_write_frames(rstream);
477 	wlimit -= dev_offset;
478 	cras_shm_get_writeable_frames(shm, wlimit, &frames_avail);
479 
480 	if (!dev_stream->conv)
481 		return frames_avail;
482 
483 	format_bytes = cras_get_format_bytes(
484 			cras_fmt_conv_out_format(dev_stream->conv));
485 
486 	/* Sample rate conversion may cause some sample left in conv_buffer
487 	 * take this buffer into account. */
488 	conv_buf_level = buf_queued(dev_stream->conv_buffer) /
489 			format_bytes;
490 	if (frames_avail <= conv_buf_level)
491 		return 0;
492 	else
493 		frames_avail -= conv_buf_level;
494 
495 	frames_avail = MIN(frames_avail,
496 			   buf_available(dev_stream->conv_buffer) /
497 					format_bytes);
498 
499 	return cras_fmt_conv_out_frames_to_in(dev_stream->conv, frames_avail);
500 }
501 
502 /* TODO(dgreid) remove this hack to reset the time if needed. */
check_next_wake_time(struct dev_stream * dev_stream)503 static void check_next_wake_time(struct dev_stream *dev_stream)
504 {
505 	struct cras_rstream *rstream = dev_stream->stream;
506 	struct timespec now;
507 
508 	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
509 	if (timespec_after(&now, &rstream->next_cb_ts)) {
510 		rstream->next_cb_ts = now;
511 		add_timespecs(&rstream->next_cb_ts,
512 			      &rstream->sleep_interval_ts);
513 	}
514 }
515 
dev_stream_playback_update_rstream(struct dev_stream * dev_stream)516 int dev_stream_playback_update_rstream(struct dev_stream *dev_stream)
517 {
518 	cras_rstream_update_output_read_pointer(dev_stream->stream);
519 	return 0;
520 }
521 
late_enough_for_capture_callback(struct dev_stream * dev_stream)522 static int late_enough_for_capture_callback(struct dev_stream *dev_stream)
523 {
524 	struct timespec now;
525 	struct cras_rstream *rstream = dev_stream->stream;
526 	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
527 	add_timespecs(&now, &capture_callback_fuzz_ts);
528 	return timespec_after(&now, &rstream->next_cb_ts);
529 }
530 
dev_stream_capture_update_rstream(struct dev_stream * dev_stream)531 int dev_stream_capture_update_rstream(struct dev_stream *dev_stream)
532 {
533 	struct cras_rstream *rstream = dev_stream->stream;
534 	unsigned int frames_ready = cras_rstream_get_cb_threshold(rstream);
535 	int rc;
536 
537 	if ((rstream->flags & TRIGGER_ONLY) && rstream->triggered)
538 		return 0;
539 
540 	cras_rstream_update_input_write_pointer(rstream);
541 
542 	/*
543 	 * For stream without BULK_AUDIO_OK flag, if it isn't time for
544 	 * this stream then skip it.
545 	 */
546 	if (!(rstream->flags & BULK_AUDIO_OK) &&
547 	    !late_enough_for_capture_callback(dev_stream))
548 		return 0;
549 
550 	/* If there is not enough data for one callback, skip it. */
551 	if (!cras_rstream_input_level_met(rstream))
552 		return 0;
553 
554 	/* Enough data for this stream. */
555 	if (rstream->flags & BULK_AUDIO_OK)
556 		frames_ready = cras_rstream_level(rstream);
557 
558 	ATLOG(atlog, AUDIO_THREAD_CAPTURE_POST,
559 				    rstream->stream_id,
560 				    frames_ready,
561 				    rstream->shm.area->read_buf_idx);
562 
563 	rc = cras_rstream_audio_ready(rstream, frames_ready);
564 
565 	if (rc < 0)
566 		return rc;
567 
568 	if (rstream->flags & TRIGGER_ONLY)
569 		rstream->triggered = 1;
570 
571 	/* Update next callback time according to perfect schedule. */
572 	add_timespecs(&rstream->next_cb_ts,
573 		      &rstream->sleep_interval_ts);
574 	/* Reset schedule if the schedule is missed. */
575 	check_next_wake_time(dev_stream);
576 
577 	return 0;
578 }
579 
cras_set_playback_timestamp(size_t frame_rate,size_t frames,struct cras_timespec * ts)580 void cras_set_playback_timestamp(size_t frame_rate,
581 				 size_t frames,
582 				 struct cras_timespec *ts)
583 {
584 	cras_clock_gettime(CLOCK_MONOTONIC_RAW, ts);
585 
586 	/* For playback, want now + samples left to be played.
587 	 * ts = time next written sample will be played to DAC,
588 	 */
589 	ts->tv_nsec += frames * 1000000000ULL / frame_rate;
590 	while (ts->tv_nsec > 1000000000ULL) {
591 		ts->tv_sec++;
592 		ts->tv_nsec -= 1000000000ULL;
593 	}
594 }
595 
cras_set_capture_timestamp(size_t frame_rate,size_t frames,struct cras_timespec * ts)596 void cras_set_capture_timestamp(size_t frame_rate,
597 				size_t frames,
598 				struct cras_timespec *ts)
599 {
600 	long tmp;
601 
602 	cras_clock_gettime(CLOCK_MONOTONIC_RAW, ts);
603 
604 	/* For capture, now - samples left to be read.
605 	 * ts = time next sample to be read was captured at ADC.
606 	 */
607 	tmp = frames * (1000000000L / frame_rate);
608 	while (tmp > 1000000000L) {
609 		tmp -= 1000000000L;
610 		ts->tv_sec--;
611 	}
612 	if (ts->tv_nsec >= tmp)
613 		ts->tv_nsec -= tmp;
614 	else {
615 		tmp -= ts->tv_nsec;
616 		ts->tv_nsec = 1000000000L - tmp;
617 		ts->tv_sec--;
618 	}
619 }
620 
dev_stream_set_delay(const struct dev_stream * dev_stream,unsigned int delay_frames)621 void dev_stream_set_delay(const struct dev_stream *dev_stream,
622 			  unsigned int delay_frames)
623 {
624 	struct cras_rstream *rstream = dev_stream->stream;
625 	struct cras_audio_shm *shm;
626 	unsigned int stream_frames;
627 
628 	if (rstream->direction == CRAS_STREAM_OUTPUT) {
629 		shm = cras_rstream_output_shm(rstream);
630 		stream_frames = cras_fmt_conv_out_frames_to_in(dev_stream->conv,
631 							       delay_frames);
632 		cras_set_playback_timestamp(rstream->format.frame_rate,
633 					    stream_frames +
634 						cras_shm_get_frames(shm),
635 					    &shm->area->ts);
636 	} else {
637 		shm = cras_rstream_input_shm(rstream);
638 		stream_frames = cras_fmt_conv_in_frames_to_out(dev_stream->conv,
639 							       delay_frames);
640 		if (cras_shm_frames_written(shm) == 0)
641 			cras_set_capture_timestamp(
642 					rstream->format.frame_rate,
643 					stream_frames,
644 					&shm->area->ts);
645 	}
646 }
647 
dev_stream_can_fetch(struct dev_stream * dev_stream)648 int dev_stream_can_fetch(struct dev_stream *dev_stream)
649 {
650 	struct cras_rstream *rstream = dev_stream->stream;
651 	struct cras_audio_shm *shm;
652 
653 	shm = cras_rstream_output_shm(rstream);
654 
655 	/* Don't fetch if the previous request hasn't got response. */
656 	return !cras_rstream_is_pending_reply(rstream) &&
657 	       cras_shm_is_buffer_available(shm);
658 }
659 
dev_stream_request_playback_samples(struct dev_stream * dev_stream,const struct timespec * now)660 int dev_stream_request_playback_samples(struct dev_stream *dev_stream,
661 					const struct timespec *now)
662 {
663 	struct cras_rstream *rstream = dev_stream->stream;
664 	int rc;
665 
666 	rc = cras_rstream_request_audio(dev_stream->stream, now);
667 	if (rc < 0)
668 		return rc;
669 
670 	add_timespecs(&rstream->next_cb_ts,
671 		      &rstream->sleep_interval_ts);
672 	check_next_wake_time(dev_stream);
673 
674 	return 0;
675 }
676 
dev_stream_poll_stream_fd(const struct dev_stream * dev_stream)677 int dev_stream_poll_stream_fd(const struct dev_stream *dev_stream)
678 {
679 	const struct cras_rstream *stream = dev_stream->stream;
680 
681 	/* For streams which rely on dev level timing, we should
682 	 * let client response wake audio thread up. */
683 	if (stream_uses_input(stream) && (stream->flags & USE_DEV_TIMING) &&
684 	    cras_rstream_is_pending_reply(stream))
685 		return stream->fd;
686 
687 	if (!stream_uses_output(stream) ||
688 	    !cras_rstream_is_pending_reply(stream) ||
689 	    cras_rstream_get_is_draining(stream))
690 		return -1;
691 
692 	return stream->fd;
693 }
694 
695 /*
696  * Gets proper wake up time for an input stream. It considers both
697  * time for samples to reach one callback level, and the time for next callback.
698  * Returns:
699  *   0 on success; negavite error code on failure. A positive value if
700  *   there is no need to set wake up time for this stream.
701  */
get_input_wake_time(struct dev_stream * dev_stream,unsigned int curr_level,struct timespec * level_tstamp,unsigned int cap_limit,int is_cap_limit_stream,struct timespec * wake_time_out)702 static int get_input_wake_time(struct dev_stream *dev_stream,
703 			       unsigned int curr_level,
704 			       struct timespec *level_tstamp,
705 			       unsigned int cap_limit,
706 			       int is_cap_limit_stream,
707 			       struct timespec *wake_time_out)
708 {
709 	struct cras_rstream *rstream = dev_stream->stream;
710 	struct timespec time_for_sample;
711 	int needed_frames_from_device;
712 
713 	needed_frames_from_device = dev_stream_capture_avail(dev_stream);
714 
715 	/*
716 	 * If this stream is not cap_limit stream, and it needs more
717 	 * frames than the capture limit from audio thread, don't bother
718 	 * re-calculating the wake time for it because
719 	 * |needed_frames_from_device| cannot be all copied to shm until
720 	 * the cap_limit stream get its samples in shm read by client
721 	 * and relieve the cap_limit.
722 	 *
723 	 * Note that we need to know whether this stream is cap_limit
724 	 * stream here because the client of cap_limit stream may read
725 	 * the data from shm during this time window, and cause
726 	 * needed_frames_from_device to be greater than cap_limit which
727 	 * was calculated before.
728 	 */
729 	if (!is_cap_limit_stream && needed_frames_from_device > cap_limit)
730 		return 1;
731 
732 	/*
733 	 * For capture stream using device timing, the flow would be:
734 	 * 1. Device has less than one cb_threshold of data.
735 	 * 2. Device has a large chunk of data that client needs to consume
736 	 *    in multiple cycles.
737 	 * 3. Audio thread sends one block to client and goes to sleep.
738 	 * 4. Client sends reply to wake up audio thread.
739 	 * 5. Repeat 3 and 4 until there is less than one cb_threshold of data.
740 	 * 6. Goes to 1.
741 	 *
742 	 * In 1, we schedule the next wake up time based on the needed frames.
743 	 * This is needed to poll the samples from device.
744 	 *
745 	 * In 3, we do not schedule a wake up time for this stream.
746 	 * We let reply from client wakes up audio thread to send next
747 	 * cb_threshold of data.
748 	 *
749 	 * TODO(cychiang) Do we want to actually block sending data to client
750 	 * until client replies ? Or control the scheduling of wake up time
751 	 * is enough ?
752 	 *
753 	 */
754 	if ((rstream->flags & USE_DEV_TIMING) &&
755 	     cras_rstream_is_pending_reply(rstream))
756 		return 1;
757 
758 	*wake_time_out = rstream->next_cb_ts;
759 
760 	/*
761 	 * If current frames in the device can provide needed amount for stream,
762 	 * there is no need to wait.
763 	 */
764 	if (curr_level >= needed_frames_from_device)
765 		needed_frames_from_device = 0;
766 	else
767 		needed_frames_from_device -= curr_level;
768 
769 	cras_frames_to_time(needed_frames_from_device,
770 			    dev_stream->dev_rate,
771 			    &time_for_sample);
772 
773 	add_timespecs(&time_for_sample, level_tstamp);
774 
775 	/* Select the time that is later so both sample and time conditions
776 	 * are met. */
777 	if (timespec_after(&time_for_sample, &rstream->next_cb_ts))
778 		*wake_time_out =  time_for_sample;
779 	/* Using device timing means the stream neglects next callback time. */
780 	if (rstream->flags & USE_DEV_TIMING)
781 		*wake_time_out =  time_for_sample;
782 
783 	return 0;
784 }
785 
dev_stream_wake_time(struct dev_stream * dev_stream,unsigned int curr_level,struct timespec * level_tstamp,unsigned int cap_limit,int is_cap_limit_stream,struct timespec * wake_time_out)786 int dev_stream_wake_time(struct dev_stream *dev_stream,
787 			 unsigned int curr_level,
788 			 struct timespec *level_tstamp,
789 			 unsigned int cap_limit,
790 			 int is_cap_limit_stream,
791 			 struct timespec *wake_time_out)
792 {
793 	if (dev_stream->stream->direction == CRAS_STREAM_OUTPUT) {
794 		/*
795                  * TODO(cychiang) Implement the method for output stream.
796 		 * The logic should be similar to what
797 		 * get_next_stream_wake_from_list in audio_thread.c is doing.
798 		 */
799 		return -EINVAL;
800 	}
801 
802 	return get_input_wake_time(dev_stream, curr_level, level_tstamp,
803 				   cap_limit, is_cap_limit_stream,
804 				   wake_time_out);
805 }
806 
dev_stream_is_pending_reply(const struct dev_stream * dev_stream)807 int dev_stream_is_pending_reply(const struct dev_stream *dev_stream)
808 {
809 	return cras_rstream_is_pending_reply(dev_stream->stream);
810 }
811 
dev_stream_flush_old_audio_messages(struct dev_stream * dev_stream)812 int dev_stream_flush_old_audio_messages(struct dev_stream *dev_stream)
813 {
814 	return cras_rstream_flush_old_audio_messages(dev_stream->stream);
815 }
816