1 /*
2  * Copyright (c) 2024 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/bluetooth/audio/bap.h>
8 #include <zephyr/bluetooth/iso.h>
9 #include <zephyr/logging/log.h>
10 #include <zephyr/logging/log_core.h>
11 #include <zephyr/net_buf.h>
12 
13 #include "common.h"
14 #include <string.h>
15 
16 LOG_MODULE_REGISTER(bap_stream_rx, LOG_LEVEL_INF);
17 
log_stream_rx(struct bt_bap_stream * stream,const struct bt_iso_recv_info * info,struct net_buf * buf)18 static void log_stream_rx(struct bt_bap_stream *stream, const struct bt_iso_recv_info *info,
19 			  struct net_buf *buf)
20 {
21 	struct audio_test_stream *test_stream = audio_test_stream_from_bap_stream(stream);
22 
23 	LOG_INF("[%zu]: Incoming audio on stream %p len %u, flags 0x%02X, seq_num %u and ts %u",
24 		test_stream->rx_cnt, stream, buf->len, info->flags, info->seq_num, info->ts);
25 }
26 
bap_stream_rx_recv_cb(struct bt_bap_stream * stream,const struct bt_iso_recv_info * info,struct net_buf * buf)27 void bap_stream_rx_recv_cb(struct bt_bap_stream *stream, const struct bt_iso_recv_info *info,
28 			   struct net_buf *buf)
29 {
30 	struct audio_test_stream *test_stream = audio_test_stream_from_bap_stream(stream);
31 
32 	if ((test_stream->rx_cnt % 50U) == 0U) {
33 		log_stream_rx(stream, info, buf);
34 	}
35 
36 	if (test_stream->rx_cnt > 0U && info->ts == test_stream->last_info.ts) {
37 		log_stream_rx(stream, info, buf);
38 		FAIL("Duplicated timestamp received: %u\n", test_stream->last_info.ts);
39 		return;
40 	}
41 
42 	if (test_stream->rx_cnt > 0U && info->seq_num == test_stream->last_info.seq_num) {
43 		log_stream_rx(stream, info, buf);
44 		FAIL("Duplicated PSN received: %u\n", test_stream->last_info.seq_num);
45 		return;
46 	}
47 
48 	if (info->flags & BT_ISO_FLAGS_ERROR) {
49 		/* Fail the test if we have not received what we expected */
50 		if (!TEST_FLAG(flag_audio_received)) {
51 			log_stream_rx(stream, info, buf);
52 			FAIL("ISO receive error\n");
53 		}
54 
55 		return;
56 	}
57 
58 	if (info->flags & BT_ISO_FLAGS_LOST) {
59 		log_stream_rx(stream, info, buf);
60 		FAIL("ISO receive lost\n");
61 		return;
62 	}
63 
64 	if (memcmp(buf->data, mock_iso_data, buf->len) == 0) {
65 		test_stream->rx_cnt++;
66 
67 		if (test_stream->rx_cnt >= MIN_SEND_COUNT) {
68 			/* We set the flag is just one stream has received the expected */
69 			SET_FLAG(flag_audio_received);
70 		}
71 	} else {
72 		log_stream_rx(stream, info, buf);
73 		FAIL("Unexpected data received\n");
74 	}
75 }
76