dev_stream.c revision 236cdf04f3b9544b0fa4b8b05e4313987574d483
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 */
20static 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 */
24static const int coarse_rate_adjust_step = 3;
25
26struct dev_stream *dev_stream_create(struct cras_rstream *stream,
27				     unsigned int dev_id,
28				     const struct cras_audio_format *dev_fmt,
29				     void *dev_ptr)
30{
31	struct dev_stream *out;
32	struct cras_audio_format *stream_fmt = &stream->format;
33	int rc = 0;
34	unsigned int max_frames;
35
36	out = calloc(1, sizeof(*out));
37	out->dev_id = dev_id;
38	out->stream = stream;
39
40	if (stream->direction == CRAS_STREAM_OUTPUT) {
41		max_frames = MAX(stream->buffer_frames,
42				 cras_frames_at_rate(stream_fmt->frame_rate,
43						     stream->buffer_frames,
44						     dev_fmt->frame_rate));
45		rc = config_format_converter(&out->conv,
46					     stream->direction,
47					     stream_fmt,
48					     dev_fmt,
49					     max_frames);
50	} else {
51		max_frames = MAX(stream->buffer_frames,
52				 cras_frames_at_rate(dev_fmt->frame_rate,
53						     stream->buffer_frames,
54						     stream_fmt->frame_rate));
55		rc = config_format_converter(&out->conv,
56					     stream->direction,
57					     dev_fmt,
58					     stream_fmt,
59					     max_frames);
60	}
61	if (rc) {
62		free(out);
63		return NULL;
64	}
65
66	if (out->conv) {
67		unsigned int dev_frames;
68		unsigned int buf_bytes;
69		const struct cras_audio_format *ofmt =
70				cras_fmt_conv_out_format(out->conv);
71
72		dev_frames = (stream->direction == CRAS_STREAM_OUTPUT)
73			? cras_fmt_conv_in_frames_to_out(out->conv,
74							 stream->buffer_frames)
75			: cras_fmt_conv_out_frames_to_in(out->conv,
76							 stream->buffer_frames);
77
78		out->conv_buffer_size_frames = 2 * MAX(dev_frames,
79						       stream->buffer_frames);
80
81		/* Create conversion buffer and area using the output format
82		 * of the format converter. Note that this format might not be
83		 * identical to stream_fmt for capture. */
84		buf_bytes = out->conv_buffer_size_frames * cras_get_format_bytes(ofmt);
85		out->conv_buffer = byte_buffer_create(buf_bytes);
86		out->conv_area = cras_audio_area_create(ofmt->num_channels);
87	}
88
89	cras_frames_to_time(cras_rstream_get_cb_threshold(stream),
90			    stream_fmt->frame_rate,
91			    &stream->sleep_interval_ts);
92	clock_gettime(CLOCK_MONOTONIC_RAW, &stream->next_cb_ts);
93
94	if (stream->direction != CRAS_STREAM_OUTPUT) {
95		struct timespec extra_sleep;
96
97		cras_frames_to_time(capture_extra_sleep_frames,
98				    stream->format.frame_rate, &extra_sleep);
99		add_timespecs(&stream->next_cb_ts, &stream->sleep_interval_ts);
100		add_timespecs(&stream->next_cb_ts, &extra_sleep);
101	}
102
103	cras_rstream_dev_attach(stream, dev_id, dev_ptr);
104
105	return out;
106}
107
108void dev_stream_destroy(struct dev_stream *dev_stream)
109{
110	cras_rstream_dev_detach(dev_stream->stream, dev_stream->dev_id);
111	if (dev_stream->conv) {
112		cras_audio_area_destroy(dev_stream->conv_area);
113		cras_fmt_conv_destroy(dev_stream->conv);
114		byte_buffer_destroy(dev_stream->conv_buffer);
115	}
116	free(dev_stream);
117}
118
119void dev_stream_set_dev_rate(struct dev_stream *dev_stream,
120			     unsigned int dev_rate,
121			     double dev_rate_ratio,
122			     double master_rate_ratio,
123			     int coarse_rate_adjust)
124{
125	if (dev_stream->dev_id == dev_stream->stream->master_dev.dev_id) {
126		cras_fmt_conv_set_linear_resample_rates(
127				dev_stream->conv,
128				dev_rate,
129				dev_rate);
130		cras_frames_to_time_precise(
131			cras_rstream_get_cb_threshold(dev_stream->stream),
132			dev_stream->stream->format.frame_rate * dev_rate_ratio,
133			&dev_stream->stream->sleep_interval_ts);
134	} else {
135		double new_rate = dev_rate * dev_rate_ratio /
136				master_rate_ratio +
137				coarse_rate_adjust_step * coarse_rate_adjust;
138		cras_fmt_conv_set_linear_resample_rates(
139				dev_stream->conv,
140				dev_rate,
141				new_rate);
142	}
143
144}
145
146int dev_stream_mix(struct dev_stream *dev_stream,
147		   const struct cras_audio_format *fmt,
148		   uint8_t *dst,
149		   unsigned int num_to_write)
150{
151	struct cras_rstream *rstream = dev_stream->stream;
152	uint8_t *src;
153	uint8_t *target = dst;
154	unsigned int fr_written, fr_read;
155	unsigned int buffer_offset;
156	int fr_in_buf;
157	unsigned int num_samples;
158	size_t frames = 0;
159	unsigned int dev_frames;
160	float mix_vol;
161
162	fr_in_buf = dev_stream_playback_frames(dev_stream);
163	if (fr_in_buf <= 0)
164		return fr_in_buf;
165	if (fr_in_buf < num_to_write)
166		num_to_write = fr_in_buf;
167
168	buffer_offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
169
170	/* Stream volume scaler. */
171	mix_vol = cras_rstream_get_volume_scaler(dev_stream->stream);
172
173	fr_written = 0;
174	fr_read = 0;
175	while (fr_written < num_to_write) {
176		unsigned int read_frames;
177		src = cras_rstream_get_readable_frames(
178				rstream, buffer_offset + fr_read, &frames);
179		if (frames == 0)
180			break;
181		if (cras_fmt_conversion_needed(dev_stream->conv)) {
182			read_frames = frames;
183			dev_frames = cras_fmt_conv_convert_frames(
184					dev_stream->conv,
185					src,
186					dev_stream->conv_buffer->bytes,
187					&read_frames,
188					num_to_write - fr_written);
189			src = dev_stream->conv_buffer->bytes;
190		} else {
191			dev_frames = MIN(frames, num_to_write - fr_written);
192			read_frames = dev_frames;
193		}
194		num_samples = dev_frames * fmt->num_channels;
195		cras_mix_add(fmt->format, target, src, num_samples, 1,
196			     cras_rstream_get_mute(rstream), mix_vol);
197		target += dev_frames * cras_get_format_bytes(fmt);
198		fr_written += dev_frames;
199		fr_read += read_frames;
200	}
201
202	cras_rstream_dev_offset_update(rstream, fr_read, dev_stream->dev_id);
203	ATLOG(atlog, AUDIO_THREAD_DEV_STREAM_MIX,
204				    fr_written, fr_read, 0);
205
206	return fr_written;
207}
208
209/* Copy from the captured buffer to the temporary format converted buffer. */
210static unsigned int capture_with_fmt_conv(struct dev_stream *dev_stream,
211					  const uint8_t *source_samples,
212					  unsigned int num_frames)
213{
214	const struct cras_audio_format *source_format;
215	const struct cras_audio_format *dst_format;
216	uint8_t *buffer;
217	unsigned int total_read = 0;
218	unsigned int write_frames;
219	unsigned int read_frames;
220	unsigned int source_frame_bytes;
221	unsigned int dst_frame_bytes;
222
223	source_format = cras_fmt_conv_in_format(dev_stream->conv);
224	source_frame_bytes = cras_get_format_bytes(source_format);
225	dst_format = cras_fmt_conv_out_format(dev_stream->conv);
226	dst_frame_bytes = cras_get_format_bytes(dst_format);
227
228	dev_stream->conv_area->num_channels = dst_format->num_channels;
229
230	while (total_read < num_frames) {
231		buffer = buf_write_pointer_size(dev_stream->conv_buffer,
232						&write_frames);
233		write_frames /= dst_frame_bytes;
234		if (write_frames == 0)
235			break;
236
237		read_frames = num_frames - total_read;
238		write_frames = cras_fmt_conv_convert_frames(
239				dev_stream->conv,
240				source_samples,
241				buffer,
242				&read_frames,
243				write_frames);
244		total_read += read_frames;
245		source_samples += read_frames * source_frame_bytes;
246		buf_increment_write(dev_stream->conv_buffer,
247				    write_frames * dst_frame_bytes);
248	}
249
250	return total_read;
251}
252
253/* Copy from the converted buffer to the stream shm.  These have the same format
254 * at this point. */
255static unsigned int capture_copy_converted_to_stream(
256		struct dev_stream *dev_stream,
257		struct cras_rstream *rstream,
258		float software_gain_scaler)
259{
260	struct cras_audio_shm *shm;
261	uint8_t *stream_samples;
262	uint8_t *converted_samples;
263	unsigned int num_frames;
264	unsigned int total_written = 0;
265	unsigned int write_frames;
266	unsigned int frame_bytes;
267	unsigned int offset;
268	const struct cras_audio_format *fmt;
269
270	shm = cras_rstream_input_shm(rstream);
271
272	fmt = cras_fmt_conv_out_format(dev_stream->conv);
273	frame_bytes = cras_get_format_bytes(fmt);
274
275	offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
276
277	stream_samples = cras_shm_get_writeable_frames(
278			shm,
279			cras_rstream_get_cb_threshold(rstream),
280			&rstream->audio_area->frames);
281	num_frames = MIN(rstream->audio_area->frames - offset,
282			 buf_queued_bytes(dev_stream->conv_buffer) /
283							frame_bytes);
284
285	ATLOG(atlog, AUDIO_THREAD_CONV_COPY,
286				    shm->area->write_buf_idx,
287				    rstream->audio_area->frames,
288				    offset);
289
290	while (total_written < num_frames) {
291		converted_samples =
292			buf_read_pointer_size(dev_stream->conv_buffer,
293					      &write_frames);
294		write_frames /= frame_bytes;
295		write_frames = MIN(write_frames, num_frames - total_written);
296
297		cras_audio_area_config_buf_pointers(dev_stream->conv_area,
298						    fmt,
299						    converted_samples);
300		cras_audio_area_config_channels(dev_stream->conv_area, fmt);
301		dev_stream->conv_area->frames = write_frames;
302
303		cras_audio_area_config_buf_pointers(rstream->audio_area,
304						    &rstream->format,
305						    stream_samples);
306
307		cras_audio_area_copy(rstream->audio_area, offset,
308				     &rstream->format,
309				     dev_stream->conv_area, 0, 1,
310				     software_gain_scaler);
311
312		buf_increment_read(dev_stream->conv_buffer,
313				   write_frames * frame_bytes);
314		total_written += write_frames;
315		cras_rstream_dev_offset_update(rstream, write_frames,
316					       dev_stream->dev_id);
317		offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
318	}
319
320	ATLOG(atlog, AUDIO_THREAD_CAPTURE_WRITE,
321				    rstream->stream_id,
322				    total_written,
323				    cras_shm_frames_written(shm));
324	return total_written;
325}
326
327unsigned int dev_stream_capture(struct dev_stream *dev_stream,
328			const struct cras_audio_area *area,
329			unsigned int area_offset,
330			float software_gain_scaler)
331{
332	struct cras_rstream *rstream = dev_stream->stream;
333	struct cras_audio_shm *shm;
334	uint8_t *stream_samples;
335	unsigned int nread;
336
337	/* Check if format conversion is needed. */
338	if (cras_fmt_conversion_needed(dev_stream->conv)) {
339		unsigned int format_bytes;
340
341		format_bytes = cras_get_format_bytes(
342				cras_fmt_conv_in_format(dev_stream->conv));
343		nread = capture_with_fmt_conv(
344			dev_stream,
345			area->channels[0].buf + area_offset * format_bytes,
346			area->frames - area_offset);
347		capture_copy_converted_to_stream(dev_stream, rstream,
348						 software_gain_scaler);
349	} else {
350		unsigned int offset =
351			cras_rstream_dev_offset(rstream, dev_stream->dev_id);
352
353		/* Set up the shm area and copy to it. */
354		shm = cras_rstream_input_shm(rstream);
355		stream_samples = cras_shm_get_writeable_frames(
356				shm,
357				cras_rstream_get_cb_threshold(rstream),
358				&rstream->audio_area->frames);
359		cras_audio_area_config_buf_pointers(rstream->audio_area,
360						    &rstream->format,
361						    stream_samples);
362
363		nread = cras_audio_area_copy(rstream->audio_area, offset,
364					     &rstream->format, area,
365					     area_offset, 1,
366					     software_gain_scaler);
367
368		ATLOG(atlog, AUDIO_THREAD_CAPTURE_WRITE,
369					    rstream->stream_id,
370					    nread,
371					    cras_shm_frames_written(shm));
372		cras_rstream_dev_offset_update(rstream, nread,
373					       dev_stream->dev_id);
374	}
375
376	return nread;
377}
378
379int dev_stream_attached_devs(const struct dev_stream *dev_stream)
380{
381	return dev_stream->stream->num_attached_devs;
382}
383
384void dev_stream_update_frames(const struct dev_stream *dev_stream)
385{
386	cras_rstream_update_queued_frames(dev_stream->stream);
387}
388
389int dev_stream_playback_frames(const struct dev_stream *dev_stream)
390{
391	int frames;
392
393	frames = cras_rstream_playable_frames(dev_stream->stream,
394					      dev_stream->dev_id);
395	if (frames < 0)
396		return frames;
397
398	if (!dev_stream->conv)
399		return frames;
400
401	return cras_fmt_conv_in_frames_to_out(dev_stream->conv, frames);
402}
403
404unsigned int dev_stream_cb_threshold(const struct dev_stream *dev_stream)
405{
406	const struct cras_rstream *rstream = dev_stream->stream;
407	unsigned int cb_threshold = cras_rstream_get_cb_threshold(rstream);
408
409	if (rstream->direction == CRAS_STREAM_OUTPUT)
410		return cras_fmt_conv_in_frames_to_out(dev_stream->conv,
411						      cb_threshold);
412	else
413		return cras_fmt_conv_out_frames_to_in(dev_stream->conv,
414						      cb_threshold);
415}
416
417unsigned int dev_stream_capture_avail(const struct dev_stream *dev_stream)
418{
419	struct cras_audio_shm *shm;
420	struct cras_rstream *rstream = dev_stream->stream;
421	unsigned int frames_avail;
422	unsigned int conv_buf_level;
423	unsigned int format_bytes;
424	unsigned int wlimit;
425	unsigned int dev_offset =
426		cras_rstream_dev_offset(rstream, dev_stream->dev_id);
427
428	shm = cras_rstream_input_shm(rstream);
429
430	wlimit = cras_rstream_get_max_write_frames(rstream);
431	wlimit -= dev_offset;
432	cras_shm_get_writeable_frames(shm, wlimit, &frames_avail);
433
434	if (!dev_stream->conv)
435		return frames_avail;
436
437	format_bytes = cras_get_format_bytes(
438			cras_fmt_conv_out_format(dev_stream->conv));
439
440	/* Sample rate conversion may cause some sample left in conv_buffer
441	 * take this buffer into account. */
442	conv_buf_level = buf_queued_bytes(dev_stream->conv_buffer) /
443			format_bytes;
444	if (frames_avail < conv_buf_level)
445		return 0;
446	else
447		frames_avail -= conv_buf_level;
448
449	frames_avail = MIN(frames_avail,
450			   buf_available_bytes(dev_stream->conv_buffer) /
451					format_bytes);
452
453	return cras_fmt_conv_out_frames_to_in(dev_stream->conv, frames_avail);
454}
455
456/* TODO(dgreid) remove this hack to reset the time if needed. */
457static void check_next_wake_time(struct dev_stream *dev_stream)
458{
459	struct cras_rstream *rstream = dev_stream->stream;
460	struct timespec now;
461
462	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
463	if (timespec_after(&now, &rstream->next_cb_ts)) {
464		rstream->next_cb_ts = now;
465		add_timespecs(&rstream->next_cb_ts,
466			      &rstream->sleep_interval_ts);
467	}
468}
469
470int dev_stream_playback_update_rstream(struct dev_stream *dev_stream)
471{
472	cras_rstream_update_output_read_pointer(dev_stream->stream);
473	return 0;
474}
475
476int dev_stream_capture_update_rstream(struct dev_stream *dev_stream)
477{
478	struct cras_rstream *rstream = dev_stream->stream;
479	unsigned int str_cb_threshold = cras_rstream_get_cb_threshold(rstream);
480	unsigned int frames_ready = str_cb_threshold;
481	struct timespec now;
482
483	cras_rstream_update_input_write_pointer(rstream);
484
485	/* If it isn't time for this stream then skip it. */
486	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
487
488	if (!cras_rstream_input_level_met(rstream))
489		return 0;
490
491	/* Enough data for this stream. */
492	if (rstream->flags & BULK_AUDIO_OK)
493		frames_ready = cras_rstream_level(rstream);
494
495	ATLOG(atlog, AUDIO_THREAD_CAPTURE_POST,
496				    rstream->stream_id,
497				    frames_ready,
498				    rstream->shm.area->read_buf_idx);
499
500	return cras_rstream_audio_ready(rstream, frames_ready);
501}
502
503void cras_set_playback_timestamp(size_t frame_rate,
504				 size_t frames,
505				 struct cras_timespec *ts)
506{
507	cras_clock_gettime(CLOCK_MONOTONIC_RAW, ts);
508
509	/* For playback, want now + samples left to be played.
510	 * ts = time next written sample will be played to DAC,
511	 */
512	ts->tv_nsec += frames * 1000000000ULL / frame_rate;
513	while (ts->tv_nsec > 1000000000ULL) {
514		ts->tv_sec++;
515		ts->tv_nsec -= 1000000000ULL;
516	}
517}
518
519void cras_set_capture_timestamp(size_t frame_rate,
520				size_t frames,
521				struct cras_timespec *ts)
522{
523	long tmp;
524
525	cras_clock_gettime(CLOCK_MONOTONIC_RAW, ts);
526
527	/* For capture, now - samples left to be read.
528	 * ts = time next sample to be read was captured at ADC.
529	 */
530	tmp = frames * (1000000000L / frame_rate);
531	while (tmp > 1000000000L) {
532		tmp -= 1000000000L;
533		ts->tv_sec--;
534	}
535	if (ts->tv_nsec >= tmp)
536		ts->tv_nsec -= tmp;
537	else {
538		tmp -= ts->tv_nsec;
539		ts->tv_nsec = 1000000000L - tmp;
540		ts->tv_sec--;
541	}
542}
543
544void dev_stream_set_delay(const struct dev_stream *dev_stream,
545			  unsigned int delay_frames)
546{
547	struct cras_rstream *rstream = dev_stream->stream;
548	struct cras_audio_shm *shm;
549	unsigned int stream_frames;
550
551	if (rstream->direction == CRAS_STREAM_OUTPUT) {
552		shm = cras_rstream_output_shm(rstream);
553		stream_frames = cras_fmt_conv_out_frames_to_in(dev_stream->conv,
554							       delay_frames);
555		cras_set_playback_timestamp(rstream->format.frame_rate,
556					    stream_frames +
557						cras_shm_get_frames(shm),
558					    &shm->area->ts);
559	} else {
560		shm = cras_rstream_input_shm(rstream);
561		stream_frames = cras_fmt_conv_in_frames_to_out(dev_stream->conv,
562							       delay_frames);
563		if (cras_shm_frames_written(shm) == 0)
564			cras_set_capture_timestamp(
565					rstream->format.frame_rate,
566					stream_frames,
567					&shm->area->ts);
568	}
569}
570
571int dev_stream_can_fetch(struct dev_stream *dev_stream)
572{
573	struct cras_rstream *rstream = dev_stream->stream;
574	struct cras_audio_shm *shm;
575
576	shm = cras_rstream_output_shm(rstream);
577
578	/* Don't fetch if the previous request hasn't got response. */
579	return !cras_shm_callback_pending(shm) &&
580	       cras_shm_is_buffer_available(shm);
581}
582
583int dev_stream_request_playback_samples(struct dev_stream *dev_stream,
584					const struct timespec *now)
585{
586	struct cras_rstream *rstream = dev_stream->stream;
587	int rc;
588
589	rc = cras_rstream_request_audio(dev_stream->stream, now);
590	if (rc < 0)
591		return rc;
592
593	add_timespecs(&rstream->next_cb_ts,
594		      &rstream->sleep_interval_ts);
595	check_next_wake_time(dev_stream);
596	cras_shm_set_callback_pending(cras_rstream_output_shm(rstream), 1);
597
598	return 0;
599}
600
601int dev_stream_poll_stream_fd(const struct dev_stream *dev_stream)
602{
603	const struct cras_rstream *stream = dev_stream->stream;
604
605	if (!stream_uses_output(stream) ||
606	    !cras_shm_callback_pending(&stream->shm) ||
607	    cras_rstream_get_is_draining(stream))
608		return -1;
609
610	return stream->fd;
611}
612