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 <stdlib.h>
8 #include <string.h>
9 #include <sys/socket.h>
10 #include <syslog.h>
11 
12 #include "audio_thread.h"
13 #include "bluetooth.h"
14 #include "byte_buffer.h"
15 #include "cras_hfp_info.h"
16 #include "cras_hfp_slc.h"
17 #include "cras_iodev_list.h"
18 #include "cras_plc.h"
19 #include "cras_sbc_codec.h"
20 #include "cras_server_metrics.h"
21 #include "utlist.h"
22 #include "packet_status_logger.h"
23 
24 /* The max buffer size. Note that the actual used size must set to multiple
25  * of SCO packet size, and the packet size does not necessarily be equal to
26  * MTU. We should keep this as common multiple of possible packet sizes, for
27  * example: 48, 60, 64, 128.
28  */
29 #define MAX_HFP_BUF_SIZE_BYTES 28800
30 
31 /* rate(8kHz) * sample_size(2 bytes) * channels(1) */
32 #define HFP_BYTE_RATE 16000
33 
34 /* Per Bluetooth Core v5.0 and HFP 1.7 specification. */
35 #define MSBC_H2_HEADER_LEN 2
36 #define MSBC_FRAME_LEN 57
37 #define MSBC_FRAME_SIZE 59
38 #define MSBC_CODE_SIZE 240
39 #define MSBC_SYNC_WORD 0xAD
40 
41 /* For one mSBC 1 compressed wideband audio channel the HCI packets will
42  * be 3 octets of HCI header + 60 octets of data. */
43 #define MSBC_PKT_SIZE 60
44 
45 #define H2_HEADER_0 0x01
46 
47 /* Supported HCI SCO packet sizes. The wideband speech mSBC frame parsing
48  * code ties to limited packet size values. Specifically list them out
49  * to check against when setting packet size.
50  *
51  * Temp buffer size should be set to least common multiple of HCI SCO packet
52  * size and MSBC_PKT_SIZE for optimizing buffer copy.
53  * To add a new supported packet size value, add corresponding entry to the
54  * lists, test the read/write msbc code, and fix the code if needed.
55  */
56 static const size_t wbs_supported_packet_size[] = { 60, 24, 0 };
57 static const size_t wbs_hci_sco_buffer_size[] = { 60, 120, 0 };
58 
59 /* Second octet of H2 header is composed by 4 bits fixed 0x8 and 4 bits
60  * sequence number 0000, 0011, 1100, 1111. */
61 static const uint8_t h2_header_frames_count[] = { 0x08, 0x38, 0xc8, 0xf8 };
62 
63 /* Structure to hold variables for a HFP connection. Since HFP supports
64  * bi-direction audio, two iodevs should share one hfp_info if they
65  * represent two directions of the same HFP headset
66  * Members:
67  *     fd - The file descriptor for SCO socket.
68  *     started - If the hfp_info has started to read/write SCO data.
69  *     mtu - The max transmit unit reported from BT adapter.
70  *     packet_size - The size of SCO packet to read/write preferred by
71  *         adapter, could be different than mtu.
72  *     capture_buf - The buffer to hold samples read from SCO socket.
73  *     playback_buf - The buffer to hold samples about to write to SCO socket.
74  *     msbc_read - mSBC codec to decode input audio in wideband speech mode.
75  *     msbc_write - mSBC codec to encode output audio in wideband speech mode.
76  *     msbc_plc - PLC component to handle the packet loss of input audio in
77  *         wideband speech mode.
78  *     msbc_num_out_frames - Number of total written mSBC frames.
79  *     msbc_num_in_frames - Number of total read mSBC frames.
80  *     msbc_num_lost_frames - Number of total lost mSBC frames.
81  *     read_cb - Callback to call when SCO socket can read. It returns the
82  *         number of PCM bytes read.
83  *     write_cb - Callback to call when SCO socket can write.
84  *     write_buf - Temp buffer for writeing HCI SCO packet in wideband.
85  *     read_buf - Temp buffer for reading HCI SCO packet in wideband.
86  *     input_format_bytes - The audio format bytes for input device. 0 means
87  *         there is no input device for the hfp_info.
88  *     output_format_bytes - The audio format bytes for output device. 0 means
89  *         there is no output device for the hfp_info.
90  *     write_wp - Write pointer of write_buf.
91  *     write_rp - Read pointer of write_buf.
92  *     read_wp - Write pointer of read_buf.
93  *     read_rp - Read pointer of read_buf.
94  *     read_align_cb - Callback used to align mSBC frame reading with read buf.
95  *     msbc_read_current_corrupted - Flag to mark if the current mSBC frame
96  *         read is corrupted.
97  *     wbs_logger - The logger for packet status in WBS.
98  */
99 struct hfp_info {
100 	int fd;
101 	int started;
102 	unsigned int mtu;
103 	unsigned int packet_size;
104 	struct byte_buffer *capture_buf;
105 	struct byte_buffer *playback_buf;
106 	struct cras_audio_codec *msbc_read;
107 	struct cras_audio_codec *msbc_write;
108 	struct cras_msbc_plc *msbc_plc;
109 	unsigned int msbc_num_out_frames;
110 	unsigned int msbc_num_in_frames;
111 	unsigned int msbc_num_lost_frames;
112 	int (*read_cb)(struct hfp_info *info);
113 	int (*write_cb)(struct hfp_info *info);
114 	uint8_t *write_buf;
115 	uint8_t *read_buf;
116 	size_t input_format_bytes;
117 	size_t output_format_bytes;
118 	size_t write_wp;
119 	size_t write_rp;
120 	size_t read_wp;
121 	size_t read_rp;
122 	int (*read_align_cb)(uint8_t *buf);
123 	bool msbc_read_current_corrupted;
124 	struct packet_status_logger *wbs_logger;
125 };
126 
hfp_info_add_iodev(struct hfp_info * info,enum CRAS_STREAM_DIRECTION direction,struct cras_audio_format * format)127 int hfp_info_add_iodev(struct hfp_info *info,
128 		       enum CRAS_STREAM_DIRECTION direction,
129 		       struct cras_audio_format *format)
130 {
131 	if (direction == CRAS_STREAM_OUTPUT) {
132 		if (info->output_format_bytes)
133 			goto invalid;
134 		info->output_format_bytes = cras_get_format_bytes(format);
135 
136 		buf_reset(info->playback_buf);
137 	} else if (direction == CRAS_STREAM_INPUT) {
138 		if (info->input_format_bytes)
139 			goto invalid;
140 		info->input_format_bytes = cras_get_format_bytes(format);
141 
142 		buf_reset(info->capture_buf);
143 	}
144 
145 	return 0;
146 
147 invalid:
148 	return -EINVAL;
149 }
150 
hfp_info_rm_iodev(struct hfp_info * info,enum CRAS_STREAM_DIRECTION direction)151 int hfp_info_rm_iodev(struct hfp_info *info,
152 		      enum CRAS_STREAM_DIRECTION direction)
153 {
154 	if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes) {
155 		memset(info->playback_buf->bytes, 0,
156 		       info->playback_buf->used_size);
157 		info->output_format_bytes = 0;
158 	} else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes) {
159 		info->input_format_bytes = 0;
160 	} else {
161 		return -EINVAL;
162 	}
163 
164 	return 0;
165 }
166 
hfp_info_has_iodev(struct hfp_info * info)167 int hfp_info_has_iodev(struct hfp_info *info)
168 {
169 	return info->output_format_bytes || info->input_format_bytes;
170 }
171 
hfp_buf_acquire(struct hfp_info * info,enum CRAS_STREAM_DIRECTION direction,uint8_t ** buf,unsigned * count)172 void hfp_buf_acquire(struct hfp_info *info,
173 		     enum CRAS_STREAM_DIRECTION direction, uint8_t **buf,
174 		     unsigned *count)
175 {
176 	size_t format_bytes;
177 	unsigned int buf_avail;
178 
179 	if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes) {
180 		*buf = buf_write_pointer_size(info->playback_buf, &buf_avail);
181 		format_bytes = info->output_format_bytes;
182 	} else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes) {
183 		*buf = buf_read_pointer_size(info->capture_buf, &buf_avail);
184 		format_bytes = info->input_format_bytes;
185 	} else {
186 		*count = 0;
187 		return;
188 	}
189 
190 	if (*count * format_bytes > buf_avail)
191 		*count = buf_avail / format_bytes;
192 }
193 
hfp_buf_size(struct hfp_info * info,enum CRAS_STREAM_DIRECTION direction)194 int hfp_buf_size(struct hfp_info *info, enum CRAS_STREAM_DIRECTION direction)
195 {
196 	if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes)
197 		return info->playback_buf->used_size /
198 		       info->output_format_bytes;
199 	else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes)
200 		return info->capture_buf->used_size / info->input_format_bytes;
201 	return 0;
202 }
203 
hfp_buf_release(struct hfp_info * info,enum CRAS_STREAM_DIRECTION direction,unsigned written_frames)204 void hfp_buf_release(struct hfp_info *info,
205 		     enum CRAS_STREAM_DIRECTION direction,
206 		     unsigned written_frames)
207 {
208 	if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes)
209 		buf_increment_write(info->playback_buf,
210 				    written_frames * info->output_format_bytes);
211 	else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes)
212 		buf_increment_read(info->capture_buf,
213 				   written_frames * info->input_format_bytes);
214 	else
215 		written_frames = 0;
216 }
217 
hfp_buf_queued(struct hfp_info * info,enum CRAS_STREAM_DIRECTION direction)218 int hfp_buf_queued(struct hfp_info *info, enum CRAS_STREAM_DIRECTION direction)
219 {
220 	if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes)
221 		return buf_queued(info->playback_buf) /
222 		       info->output_format_bytes;
223 	else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes)
224 		return buf_queued(info->capture_buf) / info->input_format_bytes;
225 	else
226 		return 0;
227 }
228 
hfp_fill_output_with_zeros(struct hfp_info * info,unsigned int nframes)229 int hfp_fill_output_with_zeros(struct hfp_info *info, unsigned int nframes)
230 {
231 	unsigned int buf_avail;
232 	unsigned int nbytes;
233 	uint8_t *buf;
234 	int i;
235 	int ret = 0;
236 
237 	if (info->output_format_bytes) {
238 		nbytes = nframes * info->output_format_bytes;
239 		/* Loop twice to make sure ring buffer is filled. */
240 		for (i = 0; i < 2; i++) {
241 			buf = buf_write_pointer_size(info->playback_buf,
242 						     &buf_avail);
243 			if (buf_avail == 0)
244 				break;
245 			buf_avail = MIN(nbytes, buf_avail);
246 			memset(buf, 0, buf_avail);
247 			buf_increment_write(info->playback_buf, buf_avail);
248 			nbytes -= buf_avail;
249 			ret += buf_avail / info->output_format_bytes;
250 		}
251 	}
252 	return ret;
253 }
254 
hfp_force_output_level(struct hfp_info * info,unsigned int level)255 void hfp_force_output_level(struct hfp_info *info, unsigned int level)
256 {
257 	if (info->output_format_bytes) {
258 		level *= info->output_format_bytes;
259 		level = MIN(level, MAX_HFP_BUF_SIZE_BYTES);
260 		buf_adjust_readable(info->playback_buf, level);
261 	}
262 }
263 
hfp_write_msbc(struct hfp_info * info)264 int hfp_write_msbc(struct hfp_info *info)
265 {
266 	size_t encoded;
267 	int err;
268 	int pcm_encoded;
269 	unsigned int pcm_avail, to_write;
270 	uint8_t *samples;
271 	uint8_t *wp;
272 
273 	if (info->write_rp + info->packet_size <= info->write_wp)
274 		goto msbc_send_again;
275 
276 	/* Make sure there are MSBC_CODE_SIZE bytes to encode. */
277 	samples = buf_read_pointer_size(info->playback_buf, &pcm_avail);
278 	if (pcm_avail < MSBC_CODE_SIZE) {
279 		to_write = MSBC_CODE_SIZE - pcm_avail;
280 		/*
281 		 * Size of playback_buf is multiple of MSBC_CODE_SIZE so we
282 		 * are safe to prepare the buffer by appending some zero bytes.
283 		 */
284 		wp = buf_write_pointer_size(info->playback_buf, &pcm_avail);
285 		memset(wp, 0, to_write);
286 		buf_increment_write(info->playback_buf, to_write);
287 
288 		samples = buf_read_pointer_size(info->playback_buf, &pcm_avail);
289 		if (pcm_avail < MSBC_CODE_SIZE)
290 			return -EINVAL;
291 	}
292 
293 	/* Encode the next MSBC_CODE_SIZE of bytes. */
294 	wp = info->write_buf + info->write_wp;
295 	wp[0] = H2_HEADER_0;
296 	wp[1] = h2_header_frames_count[info->msbc_num_out_frames % 4];
297 	pcm_encoded = info->msbc_write->encode(
298 		info->msbc_write, samples, pcm_avail, wp + MSBC_H2_HEADER_LEN,
299 		MSBC_PKT_SIZE - MSBC_H2_HEADER_LEN, &encoded);
300 	if (pcm_encoded < 0) {
301 		syslog(LOG_ERR, "msbc encoding err: %s", strerror(pcm_encoded));
302 		return pcm_encoded;
303 	}
304 	buf_increment_read(info->playback_buf, pcm_encoded);
305 	pcm_avail -= pcm_encoded;
306 	info->write_wp += MSBC_PKT_SIZE;
307 	info->msbc_num_out_frames++;
308 
309 	if (info->write_rp + info->packet_size > info->write_wp)
310 		return 0;
311 
312 msbc_send_again:
313 	err = send(info->fd, info->write_buf + info->write_rp,
314 		   info->packet_size, 0);
315 	if (err < 0) {
316 		if (errno == EINTR)
317 			goto msbc_send_again;
318 		return err;
319 	}
320 	if (err != (int)info->packet_size) {
321 		syslog(LOG_ERR, "Partially write %d bytes for mSBC", err);
322 		return -1;
323 	}
324 	info->write_rp += info->packet_size;
325 	if (info->write_rp == info->write_wp) {
326 		info->write_rp = 0;
327 		info->write_wp = 0;
328 	}
329 
330 	return err;
331 }
332 
hfp_write(struct hfp_info * info)333 int hfp_write(struct hfp_info *info)
334 {
335 	int err = 0;
336 	unsigned to_send;
337 	uint8_t *samples;
338 
339 	/* Write something */
340 	samples = buf_read_pointer_size(info->playback_buf, &to_send);
341 	if (to_send < info->packet_size)
342 		return 0;
343 	to_send = info->packet_size;
344 
345 send_sample:
346 	err = send(info->fd, samples, to_send, 0);
347 	if (err < 0) {
348 		if (errno == EINTR)
349 			goto send_sample;
350 
351 		return err;
352 	}
353 
354 	if (err != (int)info->packet_size) {
355 		syslog(LOG_ERR,
356 		       "Partially write %d bytes for SCO packet size %u", err,
357 		       info->packet_size);
358 		return -1;
359 	}
360 
361 	buf_increment_read(info->playback_buf, to_send);
362 
363 	return err;
364 }
365 
h2_header_get_seq(const uint8_t * p)366 static int h2_header_get_seq(const uint8_t *p)
367 {
368 	int i;
369 	for (i = 0; i < 4; i++) {
370 		if (*p == h2_header_frames_count[i])
371 			return i;
372 	}
373 	return -1;
374 }
375 
376 /*
377  * Extract mSBC frame from SCO socket input bytes, given that the mSBC frame
378  * could be lost or corrupted.
379  * Args:
380  *    input - Pointer to input bytes read from SCO socket.
381  *    len - Length of input bytes.
382  *    seq_out - To be filled by the sequence number of mSBC packet.
383  * Returns:
384  *    The starting position of mSBC frame if found.
385  */
extract_msbc_frame(const uint8_t * input,int len,unsigned int * seq_out)386 static const uint8_t *extract_msbc_frame(const uint8_t *input, int len,
387 					 unsigned int *seq_out)
388 {
389 	int rp = 0;
390 	int seq = -1;
391 	while (len - rp >= MSBC_FRAME_SIZE) {
392 		if ((input[rp] != H2_HEADER_0) ||
393 		    (input[rp + 2] != MSBC_SYNC_WORD)) {
394 			rp++;
395 			continue;
396 		}
397 		seq = h2_header_get_seq(input + rp + 1);
398 		if (seq < 0) {
399 			rp++;
400 			continue;
401 		}
402 		// `seq` is guaranteed to be positive now.
403 		*seq_out = (unsigned int)seq;
404 		return input + rp;
405 	}
406 	return NULL;
407 }
408 
409 /* Log value 0 when packet is received. */
log_wbs_packet_received(struct hfp_info * info)410 static void log_wbs_packet_received(struct hfp_info *info)
411 {
412 	if (info->wbs_logger)
413 		packet_status_logger_update(info->wbs_logger, 0);
414 }
415 
416 /* Log value 1 when packet is lost. */
log_wbs_packet_lost(struct hfp_info * info)417 static void log_wbs_packet_lost(struct hfp_info *info)
418 {
419 	if (info->wbs_logger)
420 		packet_status_logger_update(info->wbs_logger, 1);
421 }
422 
423 /*
424  * Handle the case when mSBC frame is considered lost.
425  * Args:
426  *    info - The hfp_info instance holding mSBC codec and PLC objects.
427  */
handle_packet_loss(struct hfp_info * info)428 static int handle_packet_loss(struct hfp_info *info)
429 {
430 	int decoded;
431 	unsigned int pcm_avail;
432 	uint8_t *in_bytes;
433 
434 	/* It's possible client doesn't consume data causing overrun. In that
435 	 * case we treat it as one mSBC frame read but dropped. */
436 	info->msbc_num_in_frames++;
437 	info->msbc_num_lost_frames++;
438 
439 	log_wbs_packet_lost(info);
440 
441 	in_bytes = buf_write_pointer_size(info->capture_buf, &pcm_avail);
442 	if (pcm_avail < MSBC_CODE_SIZE)
443 		return 0;
444 
445 	decoded = cras_msbc_plc_handle_bad_frames(info->msbc_plc,
446 						  info->msbc_read, in_bytes);
447 	if (decoded < 0)
448 		return decoded;
449 
450 	buf_increment_write(info->capture_buf, decoded);
451 
452 	return decoded;
453 }
454 
455 /* Checks if mSBC frame header aligns with the beginning of buffer. */
msbc_frame_align(uint8_t * buf)456 static int msbc_frame_align(uint8_t *buf)
457 {
458 	if ((buf[0] != H2_HEADER_0) || (buf[2] != MSBC_SYNC_WORD)) {
459 		syslog(LOG_DEBUG, "Waiting for valid mSBC frame head");
460 		return 0;
461 	}
462 	return 1;
463 }
464 
hfp_read_msbc(struct hfp_info * info)465 int hfp_read_msbc(struct hfp_info *info)
466 {
467 	int err = 0;
468 	unsigned int pcm_avail = 0;
469 	int decoded;
470 	size_t pcm_decoded = 0;
471 	size_t pcm_read = 0;
472 	uint8_t *capture_buf;
473 	const uint8_t *frame_head = NULL;
474 	unsigned int seq;
475 
476 	struct msghdr msg = { 0 };
477 	struct iovec iov;
478 	struct cmsghdr *cmsg;
479 	const unsigned int control_size = CMSG_SPACE(sizeof(int));
480 	char control[control_size];
481 	uint8_t pkt_status;
482 
483 	memset(control, 0, sizeof(control));
484 recv_msbc_bytes:
485 	msg.msg_iov = &iov;
486 	msg.msg_iovlen = 1;
487 	iov.iov_base = info->read_buf + info->read_wp;
488 	iov.iov_len = info->packet_size;
489 	msg.msg_control = control;
490 	msg.msg_controllen = control_size;
491 
492 	err = recvmsg(info->fd, &msg, 0);
493 	if (err < 0) {
494 		syslog(LOG_ERR, "HCI SCO packet read err %s", strerror(errno));
495 		if (errno == EINTR)
496 			goto recv_msbc_bytes;
497 		return err;
498 	}
499 	/*
500 	 * Treat return code 0 (socket shutdown) as error here. BT stack
501 	 * shall send signal to main thread for device disconnection.
502 	 */
503 	if (err != (int)info->packet_size) {
504 		syslog(LOG_ERR, "Partially read %d bytes for mSBC packet", err);
505 		return -1;
506 	}
507 
508 	/* Offset in input data breaks mSBC frame parsing. Discard this packet
509 	 * until read alignment succeed. */
510 	if (info->read_align_cb) {
511 		if (!info->read_align_cb(info->read_buf))
512 			return 0;
513 		else
514 			info->read_align_cb = NULL;
515 	}
516 	info->read_wp += err;
517 
518 	pkt_status = 0;
519 	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
520 	     cmsg = CMSG_NXTHDR(&msg, cmsg)) {
521 		if (cmsg->cmsg_level == SOL_BLUETOOTH &&
522 		    cmsg->cmsg_type == BT_SCM_PKT_STATUS) {
523 			size_t len = cmsg->cmsg_len - sizeof(*cmsg);
524 			memcpy(&pkt_status, CMSG_DATA(cmsg), len);
525 		}
526 	}
527 
528 	/*
529 	 * HCI SCO packet status flag:
530 	 * 0x00 - correctly received data.
531 	 * 0x01 - possibly invalid data.
532 	 * 0x10 - No data received.
533 	 * 0x11 - Data partially lost.
534 	 *
535 	 * If the latest SCO packet read doesn't cross the boundary of a mSBC
536 	 * frame, the packet status flag can be used to derive if the current
537 	 * mSBC frame is corrupted.
538 	 */
539 	if (info->read_rp + MSBC_PKT_SIZE >= info->read_wp)
540 		info->msbc_read_current_corrupted |= (pkt_status > 0);
541 
542 	/* Read buffer not enough to parse another mSBC frame. */
543 	if (info->read_rp + MSBC_PKT_SIZE > info->read_wp)
544 		return 0;
545 
546 	if (info->msbc_read_current_corrupted) {
547 		syslog(LOG_DEBUG, "mSBC frame corrputed from packet status");
548 		info->msbc_read_current_corrupted = 0;
549 		frame_head = NULL;
550 	} else {
551 		frame_head =
552 			extract_msbc_frame(info->read_buf + info->read_rp,
553 					   info->read_wp - info->read_rp, &seq);
554 		if (!frame_head)
555 			syslog(LOG_DEBUG, "Failed to extract msbc frame");
556 	}
557 
558 	/*
559 	 * Done with parsing the raw bytes just read. If mSBC frame head not
560 	 * found, we shall handle it as packet loss.
561 	 */
562 	info->read_rp += MSBC_PKT_SIZE;
563 	if (info->read_rp == info->read_wp) {
564 		info->read_rp = 0;
565 		info->read_wp = 0;
566 	}
567 	if (!frame_head)
568 		return handle_packet_loss(info);
569 
570 	/*
571 	 * Consider packet loss when found discontinuity in sequence number.
572 	 */
573 	while (seq != (info->msbc_num_in_frames % 4)) {
574 		syslog(LOG_DEBUG, "SCO packet seq unmatch");
575 		err = handle_packet_loss(info);
576 		if (err < 0)
577 			return err;
578 		pcm_read += err;
579 	}
580 
581 	/* Check if there's room for more PCM. */
582 	capture_buf = buf_write_pointer_size(info->capture_buf, &pcm_avail);
583 	if (pcm_avail < MSBC_CODE_SIZE)
584 		return pcm_read;
585 
586 	decoded = info->msbc_read->decode(info->msbc_read,
587 					  frame_head + MSBC_H2_HEADER_LEN,
588 					  MSBC_FRAME_LEN, capture_buf,
589 					  pcm_avail, &pcm_decoded);
590 	if (decoded < 0) {
591 		/*
592 		 * If mSBC frame cannot be decoded, consider this packet is
593 		 * corrupted and lost.
594 		 */
595 		syslog(LOG_ERR, "mSBC decode failed");
596 		err = handle_packet_loss(info);
597 		if (err < 0)
598 			return err;
599 		pcm_read += err;
600 	} else {
601 		/* Good mSBC frame decoded. */
602 		log_wbs_packet_received(info);
603 		buf_increment_write(info->capture_buf, pcm_decoded);
604 		info->msbc_num_in_frames++;
605 		cras_msbc_plc_handle_good_frames(info->msbc_plc, capture_buf,
606 						 capture_buf);
607 		pcm_read += pcm_decoded;
608 	}
609 	return pcm_read;
610 }
611 
hfp_read(struct hfp_info * info)612 int hfp_read(struct hfp_info *info)
613 {
614 	int err = 0;
615 	unsigned to_read;
616 	uint8_t *capture_buf;
617 
618 	capture_buf = buf_write_pointer_size(info->capture_buf, &to_read);
619 
620 	if (to_read < info->packet_size)
621 		return 0;
622 	to_read = info->packet_size;
623 
624 recv_sample:
625 	err = recv(info->fd, capture_buf, to_read, 0);
626 	if (err < 0) {
627 		syslog(LOG_ERR, "Read error %s", strerror(errno));
628 		if (errno == EINTR)
629 			goto recv_sample;
630 
631 		return err;
632 	}
633 
634 	if (err != (int)info->packet_size) {
635 		/* Allow the SCO packet size be modified from the default MTU
636 		 * value to the size of SCO data we first read. This is for
637 		 * some adapters who prefers a different value than MTU for
638 		 * transmitting SCO packet.
639 		 */
640 		if (err && (info->packet_size == info->mtu)) {
641 			info->packet_size = err;
642 		} else {
643 			syslog(LOG_ERR,
644 			       "Partially read %d bytes for %u size SCO packet",
645 			       err, info->packet_size);
646 			return -1;
647 		}
648 	}
649 
650 	buf_increment_write(info->capture_buf, err);
651 
652 	return err;
653 }
654 
655 /* Callback function to handle sample read and write.
656  * Note that we poll the SCO socket for read sample, since it reflects
657  * there is actual some sample to read while the socket always reports
658  * writable even when device buffer is full.
659  * The strategy is to synchronize read & write operations:
660  * 1. Read one chunk of MTU bytes of data.
661  * 2. When input device not attached, ignore the data just read.
662  * 3. When output device attached, write one chunk of MTU bytes of data.
663  */
hfp_info_callback(void * arg,int revents)664 static int hfp_info_callback(void *arg, int revents)
665 {
666 	struct hfp_info *info = (struct hfp_info *)arg;
667 	int err = 0;
668 
669 	if (!info->started)
670 		return 0;
671 
672 	/* Allow last read before handling error or hang-up events. */
673 	if (revents & POLLIN) {
674 		err = info->read_cb(info);
675 		if (err < 0) {
676 			syslog(LOG_ERR, "Read error");
677 			goto read_write_error;
678 		}
679 	}
680 	/* Ignore the bytes just read if input dev not in present */
681 	if (!info->input_format_bytes)
682 		buf_increment_read(info->capture_buf, err);
683 
684 	if (revents & (POLLERR | POLLHUP)) {
685 		syslog(LOG_ERR, "Error polling SCO socket, revent %d", revents);
686 		goto read_write_error;
687 	}
688 
689 	/* Without output stream's presence, we shall still send zero packets
690 	 * to HF. This is required for some HF devices to start sending non-zero
691 	 * data to AG.
692 	 */
693 	if (!info->output_format_bytes)
694 		buf_increment_write(info->playback_buf,
695 				    info->msbc_write ? err : info->packet_size);
696 
697 	err = info->write_cb(info);
698 	if (err < 0) {
699 		syslog(LOG_ERR, "Write error");
700 		goto read_write_error;
701 	}
702 
703 	return 0;
704 
705 read_write_error:
706 	/*
707 	 * This callback is executing in audio thread, so it's safe to
708 	 * unregister itself by audio_thread_rm_callback().
709 	 */
710 	audio_thread_rm_callback(info->fd);
711 	close(info->fd);
712 	info->fd = 0;
713 	info->started = 0;
714 
715 	return 0;
716 }
717 
hfp_info_create()718 struct hfp_info *hfp_info_create()
719 {
720 	struct hfp_info *info;
721 	info = (struct hfp_info *)calloc(1, sizeof(*info));
722 	if (!info)
723 		goto error;
724 
725 	info->capture_buf = byte_buffer_create(MAX_HFP_BUF_SIZE_BYTES);
726 	if (!info->capture_buf)
727 		goto error;
728 
729 	info->playback_buf = byte_buffer_create(MAX_HFP_BUF_SIZE_BYTES);
730 	if (!info->playback_buf)
731 		goto error;
732 
733 	return info;
734 
735 error:
736 	if (info) {
737 		if (info->capture_buf)
738 			byte_buffer_destroy(&info->capture_buf);
739 		if (info->playback_buf)
740 			byte_buffer_destroy(&info->playback_buf);
741 		free(info);
742 	}
743 	return NULL;
744 }
745 
hfp_info_set_wbs_logger(struct hfp_info * info,struct packet_status_logger * wbs_logger)746 void hfp_info_set_wbs_logger(struct hfp_info *info,
747 			     struct packet_status_logger *wbs_logger)
748 {
749 	info->wbs_logger = wbs_logger;
750 }
751 
hfp_info_running(struct hfp_info * info)752 int hfp_info_running(struct hfp_info *info)
753 {
754 	return info->started;
755 }
756 
hfp_info_start(int fd,unsigned int mtu,int codec,struct hfp_info * info)757 int hfp_info_start(int fd, unsigned int mtu, int codec, struct hfp_info *info)
758 {
759 	info->fd = fd;
760 	info->mtu = mtu;
761 
762 	/* Initialize to MTU, it may change when actually read the socket. */
763 	info->packet_size = mtu;
764 	buf_reset(info->playback_buf);
765 	buf_reset(info->capture_buf);
766 
767 	if (codec == HFP_CODEC_ID_MSBC) {
768 		int i;
769 		for (i = 0; wbs_supported_packet_size[i] != 0; i++) {
770 			if (info->packet_size == wbs_supported_packet_size[i])
771 				break;
772 		}
773 		/* In case of unsupported value, error log and fallback to
774 		 * MSBC_PKT_SIZE(60). */
775 		if (wbs_supported_packet_size[i] == 0) {
776 			syslog(LOG_ERR, "Unsupported packet size %u",
777 			       info->packet_size);
778 			i = 0;
779 		}
780 		info->packet_size = wbs_supported_packet_size[i];
781 		info->write_buf = (uint8_t *)malloc(wbs_hci_sco_buffer_size[i]);
782 		info->read_buf = (uint8_t *)malloc(wbs_hci_sco_buffer_size[i]);
783 
784 		info->write_cb = hfp_write_msbc;
785 		info->read_cb = hfp_read_msbc;
786 		info->msbc_read = cras_msbc_codec_create();
787 		info->msbc_write = cras_msbc_codec_create();
788 		info->msbc_plc = cras_msbc_plc_create();
789 
790 		packet_status_logger_init(info->wbs_logger);
791 	} else {
792 		info->write_cb = hfp_write;
793 		info->read_cb = hfp_read;
794 	}
795 
796 	audio_thread_add_events_callback(info->fd, hfp_info_callback, info,
797 					 POLLIN | POLLERR | POLLHUP);
798 
799 	info->started = 1;
800 	info->msbc_num_out_frames = 0;
801 	info->msbc_num_in_frames = 0;
802 	info->msbc_num_lost_frames = 0;
803 	info->write_rp = 0;
804 	info->write_wp = 0;
805 	info->read_rp = 0;
806 	info->read_wp = 0;
807 
808 	/* Mark as aligned if packet size equals to MSBC_PKT_SIZE. */
809 	info->read_align_cb =
810 		(info->packet_size == MSBC_PKT_SIZE) ? NULL : msbc_frame_align;
811 	info->msbc_read_current_corrupted = 0;
812 
813 	return 0;
814 }
815 
hfp_info_stop(struct hfp_info * info)816 int hfp_info_stop(struct hfp_info *info)
817 {
818 	if (!info->started)
819 		return 0;
820 
821 	audio_thread_rm_callback_sync(cras_iodev_list_get_audio_thread(),
822 				      info->fd);
823 
824 	close(info->fd);
825 	info->fd = 0;
826 	info->started = 0;
827 
828 	/* Unset the write/read callbacks. */
829 	info->write_cb = NULL;
830 	info->read_cb = NULL;
831 
832 	if (info->write_buf)
833 		free(info->write_buf);
834 	if (info->read_buf)
835 		free(info->read_buf);
836 
837 	if (info->msbc_read) {
838 		cras_sbc_codec_destroy(info->msbc_read);
839 		info->msbc_read = NULL;
840 	}
841 	if (info->msbc_write) {
842 		cras_sbc_codec_destroy(info->msbc_write);
843 		info->msbc_write = NULL;
844 	}
845 	if (info->msbc_plc) {
846 		cras_msbc_plc_destroy(info->msbc_plc);
847 		info->msbc_plc = NULL;
848 	}
849 
850 	if (info->msbc_num_in_frames) {
851 		cras_server_metrics_hfp_packet_loss(
852 			(float)info->msbc_num_lost_frames /
853 			info->msbc_num_in_frames);
854 	}
855 
856 	return 0;
857 }
858 
hfp_info_destroy(struct hfp_info * info)859 void hfp_info_destroy(struct hfp_info *info)
860 {
861 	if (info->capture_buf)
862 		byte_buffer_destroy(&info->capture_buf);
863 
864 	if (info->playback_buf)
865 		byte_buffer_destroy(&info->playback_buf);
866 
867 	free(info);
868 }
869