• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2013 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 <stdint.h>
7 #include <sys/ioctl.h>
8 #include <sys/param.h>
9 #include <linux/sockios.h>
10 #include <sys/socket.h>
11 #include <sys/time.h>
12 #include <syslog.h>
13 #include <time.h>
14 
15 #include "audio_thread.h"
16 #include "audio_thread_log.h"
17 #include "byte_buffer.h"
18 #include "cras_iodev_list.h"
19 #include "cras_a2dp_endpoint.h"
20 #include "cras_a2dp_info.h"
21 #include "cras_a2dp_iodev.h"
22 #include "cras_audio_area.h"
23 #include "cras_audio_thread_monitor.h"
24 #include "cras_bt_device.h"
25 #include "cras_iodev.h"
26 #include "cras_util.h"
27 #include "rtp.h"
28 #include "utlist.h"
29 
30 #define PCM_BUF_MAX_SIZE_FRAMES (4096 * 4)
31 #define PCM_BUF_MAX_SIZE_BYTES (PCM_BUF_MAX_SIZE_FRAMES * 4)
32 
33 /* Threshold for reasonable a2dp throttle log in audio dump. */
34 static const struct timespec throttle_log_threshold = {
35 	0, 20000000 /* 20ms */
36 };
37 
38 /* Threshold for severe a2dp throttle event. */
39 static const struct timespec throttle_event_threshold = {
40 	2, 0 /* 2s */
41 };
42 
43 /* Child of cras_iodev to handle bluetooth A2DP streaming.
44  * Members:
45  *    base - The cras_iodev structure "base class"
46  *    a2dp - The codec and encoded state of a2dp_io.
47  *    transport - The transport object for bluez media API.
48  *    sock_depth_frames - Socket depth in frames of the a2dp socket.
49  *    pcm_buf - Buffer to hold pcm samples before encode.
50  *    destroyed - Flag to note if this a2dp_io is about to destroy.
51  *    next_flush_time - The time when it is okay for next flush call.
52  *    flush_period - The time period between two a2dp packet writes.
53  *    write_block - How many frames of audio samples are transferred in one
54  *        a2dp packet write.
55  */
56 struct a2dp_io {
57 	struct cras_iodev base;
58 	struct a2dp_info a2dp;
59 	struct cras_bt_transport *transport;
60 	unsigned sock_depth_frames;
61 	struct byte_buffer *pcm_buf;
62 	int destroyed;
63 	struct timespec next_flush_time;
64 	struct timespec flush_period;
65 	unsigned int write_block;
66 };
67 
68 static int encode_and_flush(const struct cras_iodev *iodev);
69 
update_supported_formats(struct cras_iodev * iodev)70 static int update_supported_formats(struct cras_iodev *iodev)
71 {
72 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
73 	size_t rate = 0;
74 	size_t channel;
75 	a2dp_sbc_t a2dp;
76 
77 	cras_bt_transport_configuration(a2dpio->transport, &a2dp, sizeof(a2dp));
78 
79 	channel = (a2dp.channel_mode == SBC_CHANNEL_MODE_MONO) ? 1 : 2;
80 
81 	if (a2dp.frequency & SBC_SAMPLING_FREQ_48000)
82 		rate = 48000;
83 	else if (a2dp.frequency & SBC_SAMPLING_FREQ_44100)
84 		rate = 44100;
85 	else if (a2dp.frequency & SBC_SAMPLING_FREQ_32000)
86 		rate = 32000;
87 	else if (a2dp.frequency & SBC_SAMPLING_FREQ_16000)
88 		rate = 16000;
89 
90 	free(iodev->supported_rates);
91 	iodev->supported_rates = (size_t *)malloc(2 * sizeof(rate));
92 	iodev->supported_rates[0] = rate;
93 	iodev->supported_rates[1] = 0;
94 
95 	free(iodev->supported_channel_counts);
96 	iodev->supported_channel_counts = (size_t *)malloc(2 * sizeof(channel));
97 	iodev->supported_channel_counts[0] = channel;
98 	iodev->supported_channel_counts[1] = 0;
99 
100 	free(iodev->supported_formats);
101 	iodev->supported_formats =
102 		(snd_pcm_format_t *)malloc(2 * sizeof(snd_pcm_format_t));
103 	iodev->supported_formats[0] = SND_PCM_FORMAT_S16_LE;
104 	iodev->supported_formats[1] = (snd_pcm_format_t)0;
105 
106 	return 0;
107 }
108 
bt_local_queued_frames(const struct cras_iodev * iodev)109 static unsigned int bt_local_queued_frames(const struct cras_iodev *iodev)
110 {
111 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
112 	return a2dp_queued_frames(&a2dpio->a2dp) +
113 	       buf_queued(a2dpio->pcm_buf) /
114 		       cras_get_format_bytes(iodev->format);
115 }
116 
frames_queued(const struct cras_iodev * iodev,struct timespec * tstamp)117 static int frames_queued(const struct cras_iodev *iodev,
118 			 struct timespec *tstamp)
119 {
120 	int local_queued_frames = bt_local_queued_frames(iodev);
121 	clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
122 	return MIN(iodev->buffer_size, local_queued_frames);
123 }
124 
125 /*
126  * Utility function to fill zero frames until buffer level reaches
127  * target_level. This is useful to allocate just enough data to write
128  * to controller, while not introducing extra latency.
129  */
fill_zeros_to_target_level(struct cras_iodev * iodev,unsigned int target_level)130 static int fill_zeros_to_target_level(struct cras_iodev *iodev,
131 				      unsigned int target_level)
132 {
133 	unsigned int local_queued_frames = bt_local_queued_frames(iodev);
134 
135 	if (local_queued_frames < target_level)
136 		return cras_iodev_fill_odev_zeros(
137 			iodev, target_level - local_queued_frames);
138 	return 0;
139 }
140 
141 /*
142  * dev_io_playback_write() has the logic to detect underrun scenario
143  * and calls into this underrun ops, by comparing buffer level with
144  * number of frames just written. Note that it's not correct 100% of
145  * the time in a2dp case, because we lose track of samples once they're
146  * flushed to socket.
147  */
output_underrun(struct cras_iodev * iodev)148 static int output_underrun(struct cras_iodev *iodev)
149 {
150 	unsigned int local_queued_frames = bt_local_queued_frames(iodev);
151 
152 	/*
153 	 * Examples to help understand the check:
154 	 *
155 	 * [False-positive underrun]
156 	 * Assume min_buffer_level = 1000, written 900, and flushes
157 	 * 800 of data. Audio thread sees 1000 + 900 - 800 = 1100 of
158 	 * data left. This is merely 100(< 900) above min_buffer_level
159 	 * so audio_thread thinks it underruns, but actually not.
160 	 *
161 	 * [True underrun]
162 	 * min_buffer_level = 1000, written 200, and flushes 800 of
163 	 * data. Now that buffer runs lower than min_buffer_level so
164 	 * it's indeed an underrun.
165 	 */
166 	if (local_queued_frames > iodev->min_buffer_level)
167 		return 0;
168 
169 	return cras_iodev_fill_odev_zeros(iodev, iodev->min_cb_level);
170 }
171 
172 /*
173  * This will be called multiple times when a2dpio is in no_stream state
174  * frames_to_play_in_sleep ops determins how regular this will be called.
175  */
enter_no_stream(struct a2dp_io * a2dpio)176 static int enter_no_stream(struct a2dp_io *a2dpio)
177 {
178 	struct cras_iodev *odev = &a2dpio->base;
179 	int rc;
180 	/*
181          * Setting target level to 3 times of min_buffer_level.
182          * We want hw_level to stay bewteen 1-2 times of min_buffer_level on
183 	 * top of the underrun threshold(i.e one min_cb_level).
184          */
185 	rc = fill_zeros_to_target_level(odev, 3 * odev->min_buffer_level);
186 	if (rc)
187 		syslog(LOG_ERR, "Error in A2DP enter_no_stream");
188 	return encode_and_flush(odev);
189 }
190 
191 /*
192  * This is called when stream data is available to write. Prepare audio
193  * data to one min_buffer_level. Don't flush it now because stream data is
194  * coming right up which will trigger next flush at appropriate time.
195  */
leave_no_stream(struct a2dp_io * a2dpio)196 static int leave_no_stream(struct a2dp_io *a2dpio)
197 {
198 	struct cras_iodev *odev = &a2dpio->base;
199 
200 	/*
201 	 * Since stream data is ready, just make sure hw_level doesn't underrun
202 	 * after one flush. Hence setting the target level to 2 times of
203 	 * min_buffer_level.
204          */
205 	return fill_zeros_to_target_level(odev, 2 * odev->min_buffer_level);
206 }
207 
208 /*
209  * Makes sure there's enough data(zero frames) to flush when no stream presents.
210  * Note that the underrun condition is when real buffer level goes below
211  * min_buffer_level, so we want to keep data at a reasonable higher level on top
212  * of that.
213  */
no_stream(struct cras_iodev * odev,int enable)214 static int no_stream(struct cras_iodev *odev, int enable)
215 {
216 	struct a2dp_io *a2dpio = (struct a2dp_io *)odev;
217 
218 	if (enable)
219 		return enter_no_stream(a2dpio);
220 	else
221 		return leave_no_stream(a2dpio);
222 }
223 
224 /* Encode as much PCM data as we can until the buffer level of a2dp_info
225  * reaches MTU.
226  * Returns:
227  *    0 for success, otherwise negative error code.
228  */
encode_a2dp_packet(struct a2dp_io * a2dpio)229 static int encode_a2dp_packet(struct a2dp_io *a2dpio)
230 {
231 	int processed;
232 	size_t format_bytes = cras_get_format_bytes(a2dpio->base.format);
233 
234 	while (buf_queued(a2dpio->pcm_buf)) {
235 		processed = a2dp_encode(
236 			&a2dpio->a2dp, buf_read_pointer(a2dpio->pcm_buf),
237 			buf_readable(a2dpio->pcm_buf), format_bytes,
238 			cras_bt_transport_write_mtu(a2dpio->transport));
239 		if (processed == -ENOSPC || processed == 0)
240 			break;
241 		if (processed < 0)
242 			return processed;
243 
244 		buf_increment_read(a2dpio->pcm_buf, processed);
245 	}
246 	return 0;
247 }
248 
249 /*
250  * To be called when a2dp socket becomes writable.
251  */
a2dp_socket_write_cb(void * arg,int revent)252 static int a2dp_socket_write_cb(void *arg, int revent)
253 {
254 	struct cras_iodev *iodev = (struct cras_iodev *)arg;
255 	return encode_and_flush(iodev);
256 }
257 
configure_dev(struct cras_iodev * iodev)258 static int configure_dev(struct cras_iodev *iodev)
259 {
260 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
261 	int sock_depth;
262 	int err;
263 	socklen_t optlen;
264 	int a2dp_payload_length;
265 
266 	err = cras_bt_transport_acquire(a2dpio->transport);
267 	if (err < 0) {
268 		syslog(LOG_ERR, "transport_acquire failed");
269 		return err;
270 	}
271 
272 	/* Apply the node's volume after transport is acquired. Doing this
273 	 * is necessary because the volume can not sync to hardware until
274 	 * it is opened. */
275 	iodev->set_volume(iodev);
276 
277 	/* Assert format is set before opening device. */
278 	if (iodev->format == NULL)
279 		return -EINVAL;
280 	iodev->format->format = SND_PCM_FORMAT_S16_LE;
281 	cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
282 
283 	a2dpio->pcm_buf = byte_buffer_create(PCM_BUF_MAX_SIZE_BYTES);
284 	if (!a2dpio->pcm_buf)
285 		return -ENOMEM;
286 
287 	/* Set up the socket to hold two MTUs full of data before returning
288 	 * EAGAIN.  This will allow the write to be throttled when a reasonable
289 	 * amount of data is queued. */
290 	sock_depth = 2 * cras_bt_transport_write_mtu(a2dpio->transport);
291 	setsockopt(cras_bt_transport_fd(a2dpio->transport), SOL_SOCKET,
292 		   SO_SNDBUF, &sock_depth, sizeof(sock_depth));
293 	optlen = sizeof(sock_depth);
294 	getsockopt(cras_bt_transport_fd(a2dpio->transport), SOL_SOCKET,
295 		   SO_SNDBUF, &sock_depth, &optlen);
296 	a2dpio->sock_depth_frames = a2dp_block_size(&a2dpio->a2dp, sock_depth) /
297 				    cras_get_format_bytes(iodev->format);
298 	/*
299 	 * Per avdtp_write, subtract the room for packet header first.
300 	 * Calculate how many frames are encapsulated in one a2dp packet, and
301 	 * the corresponding time period between two packets.
302 	 */
303 	a2dp_payload_length = cras_bt_transport_write_mtu(a2dpio->transport) -
304 			      sizeof(struct rtp_header) -
305 			      sizeof(struct rtp_payload);
306 	a2dpio->write_block =
307 		a2dp_block_size(&a2dpio->a2dp, a2dp_payload_length) /
308 		cras_get_format_bytes(iodev->format);
309 	cras_frames_to_time(a2dpio->write_block, iodev->format->frame_rate,
310 			    &a2dpio->flush_period);
311 
312 	/* PCM buffer size plus one encoded a2dp packet. */
313 	iodev->buffer_size = PCM_BUF_MAX_SIZE_FRAMES + a2dpio->write_block;
314 
315 	/*
316 	 * Buffer level less than one write_block can't be send over a2dp
317 	 * packet. Configure min_buffer_level to this value so when stream
318 	 * underruns, audio thread can take action to fill some zeros.
319 	 */
320 	iodev->min_buffer_level = a2dpio->write_block;
321 
322 	audio_thread_add_events_callback(
323 		cras_bt_transport_fd(a2dpio->transport), a2dp_socket_write_cb,
324 		iodev, POLLOUT | POLLERR | POLLHUP);
325 	audio_thread_config_events_callback(
326 		cras_bt_transport_fd(a2dpio->transport), TRIGGER_NONE);
327 	return 0;
328 }
329 
start(const struct cras_iodev * iodev)330 static int start(const struct cras_iodev *iodev)
331 {
332 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
333 
334 	/*
335 	 * This is called when iodev in open state, at the moment when
336 	 * output sample is ready. Initialize the next_flush_time for
337 	 * following flush calls.
338 	 */
339 	clock_gettime(CLOCK_MONOTONIC_RAW, &a2dpio->next_flush_time);
340 
341 	return 0;
342 }
343 
close_dev(struct cras_iodev * iodev)344 static int close_dev(struct cras_iodev *iodev)
345 {
346 	int err;
347 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
348 	struct cras_bt_device *device;
349 
350 	if (!a2dpio->transport)
351 		return 0;
352 
353 	/* Remove audio thread callback and sync before releasing
354 	 * the transport. */
355 	audio_thread_rm_callback_sync(cras_iodev_list_get_audio_thread(),
356 				      cras_bt_transport_fd(a2dpio->transport));
357 
358 	err = cras_bt_transport_release(a2dpio->transport, !a2dpio->destroyed);
359 	if (err < 0)
360 		syslog(LOG_ERR, "transport_release failed");
361 
362 	device = cras_bt_transport_device(a2dpio->transport);
363 	if (device)
364 		cras_bt_device_cancel_suspend(device);
365 	a2dp_reset(&a2dpio->a2dp);
366 	byte_buffer_destroy(&a2dpio->pcm_buf);
367 	cras_iodev_free_format(iodev);
368 	cras_iodev_free_audio_area(iodev);
369 	return 0;
370 }
371 
frames_to_play_in_sleep(struct cras_iodev * iodev,unsigned int * hw_level,struct timespec * hw_tstamp)372 static unsigned int frames_to_play_in_sleep(struct cras_iodev *iodev,
373 					    unsigned int *hw_level,
374 					    struct timespec *hw_tstamp)
375 {
376 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
377 	int frames_until;
378 
379 	*hw_level = frames_queued(iodev, hw_tstamp);
380 	if (*hw_level < a2dpio->write_block)
381 		*hw_level = 0;
382 	else
383 		*hw_level -= a2dpio->write_block;
384 
385 	frames_until = cras_frames_until_time(&a2dpio->next_flush_time,
386 					      iodev->format->frame_rate);
387 	if (frames_until > 0)
388 		return frames_until;
389 
390 	/* If time has passed next_flush_time, for example when socket write
391 	 * throttles, sleep a moderate of time so that audio thread doesn't
392 	 * busy wake up. */
393 	return a2dpio->write_block;
394 }
395 
396 /* Encodes PCM data to a2dp frames and try to flush it to the socket.
397  * Returns:
398  *    0 when the flush succeeded, -1 when error occurred.
399  */
encode_and_flush(const struct cras_iodev * iodev)400 static int encode_and_flush(const struct cras_iodev *iodev)
401 {
402 	int err;
403 	size_t format_bytes;
404 	int written = 0;
405 	unsigned int queued_frames;
406 	struct a2dp_io *a2dpio;
407 	struct cras_bt_device *device;
408 	struct timespec now, ts;
409 	static const struct timespec flush_wake_fuzz_ts = {
410 		0, 1000000 /* 1ms */
411 	};
412 
413 	a2dpio = (struct a2dp_io *)iodev;
414 	format_bytes = cras_get_format_bytes(iodev->format);
415 	device = cras_bt_transport_device(a2dpio->transport);
416 
417 	/* If bt device has been destroyed, this a2dp iodev will soon be
418 	 * destroyed as well. */
419 	if (device == NULL)
420 		return -EINVAL;
421 
422 	ATLOG(atlog, AUDIO_THREAD_A2DP_FLUSH, iodev->state,
423 	      a2dpio->next_flush_time.tv_sec, a2dpio->next_flush_time.tv_nsec);
424 
425 	/* Only allow data to be flushed after start() ops is called. */
426 	if ((iodev->state != CRAS_IODEV_STATE_NORMAL_RUN) &&
427 	    (iodev->state != CRAS_IODEV_STATE_NO_STREAM_RUN))
428 		return 0;
429 
430 	err = encode_a2dp_packet(a2dpio);
431 	if (err < 0)
432 		return err;
433 
434 do_flush:
435 	/* If flush gets called before targeted next flush time, do nothing. */
436 	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
437 	add_timespecs(&now, &flush_wake_fuzz_ts);
438 	if (!timespec_after(&now, &a2dpio->next_flush_time)) {
439 		if (iodev->buffer_size == bt_local_queued_frames(iodev)) {
440 			/*
441 			 * If buffer is full, audio thread will no longer call
442 			 * into get/put buffer in subsequent wake-ups. In that
443 			 * case set the registered callback to be triggered at
444 			 * next audio thread wake up.
445 			 */
446 			audio_thread_config_events_callback(
447 				cras_bt_transport_fd(a2dpio->transport),
448 				TRIGGER_WAKEUP);
449 			cras_audio_thread_event_a2dp_overrun();
450 			syslog(LOG_WARNING, "Buffer overrun in A2DP iodev");
451 		}
452 		return 0;
453 	}
454 
455 	/* If the A2DP write schedule miss exceeds a small threshold, log it for
456 	 * debug purpose. */
457 	subtract_timespecs(&now, &a2dpio->next_flush_time, &ts);
458 	if (timespec_after(&ts, &throttle_log_threshold))
459 		ATLOG(atlog, AUDIO_THREAD_A2DP_THROTTLE_TIME, ts.tv_sec,
460 		      ts.tv_nsec, bt_local_queued_frames(iodev));
461 
462 	/* Log an event if the A2DP write schedule miss exceeds a large threshold
463 	 * that we consider it as something severe. */
464 	if (timespec_after(&ts, &throttle_event_threshold))
465 		cras_audio_thread_event_a2dp_throttle();
466 
467 	written = a2dp_write(&a2dpio->a2dp,
468 			     cras_bt_transport_fd(a2dpio->transport),
469 			     cras_bt_transport_write_mtu(a2dpio->transport));
470 	ATLOG(atlog, AUDIO_THREAD_A2DP_WRITE, written,
471 	      a2dp_queued_frames(&a2dpio->a2dp), 0);
472 	if (written == -EAGAIN) {
473 		/* If EAGAIN error lasts longer than 5 seconds, suspend the
474 		 * a2dp connection. */
475 		cras_bt_device_schedule_suspend(device, 5000,
476 						A2DP_LONG_TX_FAILURE);
477 		audio_thread_config_events_callback(
478 			cras_bt_transport_fd(a2dpio->transport), TRIGGER_POLL);
479 		return 0;
480 	} else if (written < 0) {
481 		/* Suspend a2dp immediately when receives error other than
482 		 * EAGAIN. */
483 		cras_bt_device_cancel_suspend(device);
484 		cras_bt_device_schedule_suspend(device, 0, A2DP_TX_FATAL_ERROR);
485 		/* Stop polling the socket in audio thread. Main thread will
486 		 * close this iodev soon. */
487 		audio_thread_config_events_callback(
488 			cras_bt_transport_fd(a2dpio->transport), TRIGGER_NONE);
489 		return written;
490 	}
491 
492 	/* Update the next flush time if one block successfully been written. */
493 	if (written)
494 		add_timespecs(&a2dpio->next_flush_time, &a2dpio->flush_period);
495 
496 	/* a2dp_write no longer return -EAGAIN when reaches here, disable
497 	 * the polling write callback. */
498 	audio_thread_config_events_callback(
499 		cras_bt_transport_fd(a2dpio->transport), TRIGGER_NONE);
500 
501 	/* Data succcessfully written to a2dp socket, cancel any scheduled
502 	 * suspend timer. */
503 	cras_bt_device_cancel_suspend(device);
504 
505 	/* If it looks okay to write more and we do have queued data, try
506 	 * encode more. But avoid the case when PCM buffer level is too close
507 	 * to min_buffer_level so that another A2DP write could causes underrun.
508 	 */
509 	queued_frames = buf_queued(a2dpio->pcm_buf) / format_bytes;
510 	if (written &&
511 	    (iodev->min_buffer_level + a2dpio->write_block < queued_frames)) {
512 		err = encode_a2dp_packet(a2dpio);
513 		if (err < 0)
514 			return err;
515 		goto do_flush;
516 	}
517 
518 	return 0;
519 }
520 
delay_frames(const struct cras_iodev * iodev)521 static int delay_frames(const struct cras_iodev *iodev)
522 {
523 	const struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
524 	struct timespec tstamp;
525 
526 	/* The number of frames in the pcm buffer plus two mtu packets */
527 	return frames_queued(iodev, &tstamp) + a2dpio->sock_depth_frames;
528 }
529 
get_buffer(struct cras_iodev * iodev,struct cras_audio_area ** area,unsigned * frames)530 static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
531 		      unsigned *frames)
532 {
533 	size_t format_bytes;
534 	struct a2dp_io *a2dpio;
535 
536 	a2dpio = (struct a2dp_io *)iodev;
537 
538 	format_bytes = cras_get_format_bytes(iodev->format);
539 
540 	if (iodev->direction != CRAS_STREAM_OUTPUT)
541 		return 0;
542 
543 	*frames = MIN(*frames, buf_writable(a2dpio->pcm_buf) / format_bytes);
544 	iodev->area->frames = *frames;
545 	cras_audio_area_config_buf_pointers(iodev->area, iodev->format,
546 					    buf_write_pointer(a2dpio->pcm_buf));
547 	*area = iodev->area;
548 	return 0;
549 }
550 
put_buffer(struct cras_iodev * iodev,unsigned nwritten)551 static int put_buffer(struct cras_iodev *iodev, unsigned nwritten)
552 {
553 	size_t written_bytes;
554 	size_t format_bytes;
555 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
556 
557 	format_bytes = cras_get_format_bytes(iodev->format);
558 	written_bytes = nwritten * format_bytes;
559 
560 	if (written_bytes > buf_writable(a2dpio->pcm_buf))
561 		return -EINVAL;
562 
563 	buf_increment_write(a2dpio->pcm_buf, written_bytes);
564 
565 	return encode_and_flush(iodev);
566 }
567 
flush_buffer(struct cras_iodev * iodev)568 static int flush_buffer(struct cras_iodev *iodev)
569 {
570 	return 0;
571 }
572 
set_volume(struct cras_iodev * iodev)573 static void set_volume(struct cras_iodev *iodev)
574 {
575 	size_t volume;
576 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
577 	struct cras_bt_device *device =
578 		cras_bt_transport_device(a2dpio->transport);
579 
580 	if (!cras_bt_device_get_use_hardware_volume(device))
581 		return;
582 
583 	volume = iodev->active_node->volume * 127 / 100;
584 
585 	if (a2dpio->transport)
586 		cras_bt_transport_set_volume(a2dpio->transport, volume);
587 }
588 
update_active_node(struct cras_iodev * iodev,unsigned node_idx,unsigned dev_enabled)589 static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
590 			       unsigned dev_enabled)
591 {
592 }
593 
free_resources(struct a2dp_io * a2dpio)594 void free_resources(struct a2dp_io *a2dpio)
595 {
596 	struct cras_ionode *node;
597 
598 	node = a2dpio->base.active_node;
599 	if (node) {
600 		cras_iodev_rm_node(&a2dpio->base, node);
601 		free(node);
602 	}
603 	free(a2dpio->base.supported_channel_counts);
604 	free(a2dpio->base.supported_rates);
605 	free(a2dpio->base.supported_formats);
606 	destroy_a2dp(&a2dpio->a2dp);
607 }
608 
a2dp_iodev_create(struct cras_bt_transport * transport)609 struct cras_iodev *a2dp_iodev_create(struct cras_bt_transport *transport)
610 {
611 	int err;
612 	struct a2dp_io *a2dpio;
613 	struct cras_iodev *iodev;
614 	struct cras_ionode *node;
615 	a2dp_sbc_t a2dp;
616 	struct cras_bt_device *device;
617 	const char *name;
618 
619 	a2dpio = (struct a2dp_io *)calloc(1, sizeof(*a2dpio));
620 	if (!a2dpio)
621 		goto error;
622 
623 	a2dpio->transport = transport;
624 	cras_bt_transport_configuration(a2dpio->transport, &a2dp, sizeof(a2dp));
625 	err = init_a2dp(&a2dpio->a2dp, &a2dp);
626 	if (err) {
627 		syslog(LOG_ERR, "Fail to init a2dp");
628 		goto error;
629 	}
630 
631 	iodev = &a2dpio->base;
632 
633 	/* A2DP only does output now */
634 	iodev->direction = CRAS_STREAM_OUTPUT;
635 
636 	/* Set iodev's name by bluetooth device's readable name, if
637 	 * the readable name is not available, use address instead.
638 	 */
639 	device = cras_bt_transport_device(transport);
640 	name = cras_bt_device_name(device);
641 	if (!name)
642 		name = cras_bt_transport_object_path(a2dpio->transport);
643 
644 	snprintf(iodev->info.name, sizeof(iodev->info.name), "%s", name);
645 	iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = '\0';
646 	iodev->info.stable_id = cras_bt_device_get_stable_id(device);
647 
648 	iodev->configure_dev = configure_dev;
649 	iodev->frames_queued = frames_queued;
650 	iodev->delay_frames = delay_frames;
651 	iodev->get_buffer = get_buffer;
652 	iodev->put_buffer = put_buffer;
653 	iodev->flush_buffer = flush_buffer;
654 	iodev->no_stream = no_stream;
655 	iodev->output_underrun = output_underrun;
656 	iodev->close_dev = close_dev;
657 	iodev->update_supported_formats = update_supported_formats;
658 	iodev->update_active_node = update_active_node;
659 	iodev->set_volume = set_volume;
660 	iodev->start = start;
661 	iodev->frames_to_play_in_sleep = frames_to_play_in_sleep;
662 
663 	/* Create an empty ionode */
664 	node = (struct cras_ionode *)calloc(1, sizeof(*node));
665 	node->dev = iodev;
666 	strcpy(node->name, iodev->info.name);
667 	node->plugged = 1;
668 	node->type = CRAS_NODE_TYPE_BLUETOOTH;
669 	node->volume = 100;
670 	gettimeofday(&node->plugged_time, NULL);
671 
672 	/* Prepare active node before append, so bt_io can extract correct
673 	 * info from A2DP iodev and node. */
674 	cras_iodev_add_node(iodev, node);
675 	cras_iodev_set_active_node(iodev, node);
676 	cras_bt_device_append_iodev(
677 		device, iodev, cras_bt_transport_profile(a2dpio->transport));
678 
679 	/* Record max supported channels into cras_iodev_info. */
680 	iodev->info.max_supported_channels =
681 		(a2dp.channel_mode == SBC_CHANNEL_MODE_MONO) ? 1 : 2;
682 
683 	ewma_power_disable(&iodev->ewma);
684 
685 	return iodev;
686 error:
687 	if (a2dpio) {
688 		free_resources(a2dpio);
689 		free(a2dpio);
690 	}
691 	return NULL;
692 }
693 
a2dp_iodev_destroy(struct cras_iodev * iodev)694 void a2dp_iodev_destroy(struct cras_iodev *iodev)
695 {
696 	struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
697 	struct cras_bt_device *device;
698 
699 	a2dpio->destroyed = 1;
700 	device = cras_bt_transport_device(a2dpio->transport);
701 
702 	/* A2DP does output only */
703 	cras_bt_device_rm_iodev(device, iodev);
704 
705 	/* Free resources when device successfully removed. */
706 	free_resources(a2dpio);
707 	cras_iodev_free_resources(iodev);
708 	free(a2dpio);
709 }
710