Debian Codegraph @

examples/crf-listener.c

raw
1 /*
2 * Copyright (c) 2018, Intel Corporation
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 *
7 * * Redistributions of source code must retain the above copyright notice,
8 * this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of Intel Corporation nor the names of its contributors
13 * may be used to endorse or promote products derived from this software
14 * without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 /* CRF Listener example.
29 *
30 * This example implements a very simple CRF listener application which receives
31 * CRF packets from the network and recovers media clock.
32 * Additionally, it operates as AAF listener or AAF talker according to the
33 * operation mode option passed via command-line argument.
34 *
35 * When operating as AAF talker, it sends dummy AAF packets with presentation
36 * time that align with the reference clock. AAF packets are sent only after
37 * the first CRF packet is received.
38 *
39 * When operating as AAF listener, it receives AAF packets and checks if their
40 * presentation time is aligned with the clock reference provided by the CRF
41 * stream.
42 *
43 * Note that the application running on AAF listener mode should be started
44 * before the application running on AAF talker mode so the former is able to
45 * recover the media clock and check for AAF stream alignment.
46 *
47 * TSN stream parameters (e.g. destination mac address and mode) are passed
48 * via command-line arguments. Run 'crf-listener --help' for more information.
49 *
50 * This example relies on the system clock to keep the transmission interval
51 * when operating in AAF talker mode. So make sure the system clock is
52 * synchronized with PTP time. For further information on how to synchronize
53 * those clocks see ptp4l(8) and phc2sys(8) man pages. Additionally, make sure
54 * you have configured FQTSS feature from your NIC according (for further
55 * information see tc-cbs(8)).
56 *
57 * Below we provide an example to setup ptp4l, phc2sys and to configure
58 * the qdiscs to transmit an AAF stream with 48 kHz sampling rate, 16-bit
59 * sample size, stereo.
60 *
61 * On PTP slave host: Replace $IFNAME by your PTP capable NIC name. The
62 * gPTP.cfg file mentioned below can be found in /usr/share/doc/linuxptp/
63 * (depending on your distro).
64 * $ ptp4l -f gPTP.cfg -i $IFNAME -s
65 * $ phc2sys -f gPTP.cfg -a -r
66 *
67 * Configure mpqrio (replace $HANDLE_ID by an unused handle ID):
68 * $ tc qdisc add dev $IFNAME parent root handle $HANDLE_ID mqprio \
69 * num_tc 3 map 2 2 1 0 2 2 2 2 2 2 2 2 2 2 2 2 \
70 * queues 1@0 1@1 2@2 hw 0
71 *
72 * Configure cbs:
73 * $ tc qdisc replace dev $IFNAME parent $HANDLE_ID:1 cbs idleslope 5760 \
74 * sendslope -994240 hicredit 9 locredit -89 offload 1
75 *
76 * Finally, the AAF listener mode implemented by this example application is
77 * limited and doesn't work with multiple AAF talkers.
78 */
79
80 #include <assert.h>
81 #include <argp.h>
82 #include <arpa/inet.h>
83 #include <linux/if.h>
84 #include <linux/if_ether.h>
85 #include <linux/if_packet.h>
86 #include <poll.h>
87 #include <stdbool.h>
88 #include <stdint.h>
89 #include <stdio.h>
90 #include <stdlib.h>
91 #include <string.h>
92 #include <sys/ioctl.h>
93 #include <sys/param.h>
94 #include <sys/queue.h>
95 #include <sys/timerfd.h>
96 #include <unistd.h>
97 #include <math.h>
98 #include <inttypes.h>
99
100 #include "avtp.h"
101 #include "avtp_crf.h"
102 #include "avtp_aaf.h"
103 #include "examples/common.h"
104
105 #define AAF_STREAM_ID 0xAABBCCDDEEFF0001
106 #define AAF_NUM_SAMPLES 6 /* Number of samples per packet. */
107 #define AAF_SAMPLE_SIZE 2 /* Sample size in bytes. */
108 #define AAF_NUM_CHANNELS 2 /* Number of channels per frame */
109 #define AAF_DATA_LEN (AAF_NUM_SAMPLES * AAF_SAMPLE_SIZE * AAF_NUM_CHANNELS)
110 #define AAF_PDU_SIZE (sizeof(struct avtp_stream_pdu) + AAF_DATA_LEN)
111 #define AAF_SAMPLE_RATE 48000
112
113 #define CRF_STREAM_ID 0xAABBCCDDEEFF0002
114 /* Values based on Spec 1722 Table 28 recommendation. */
115 #define CRF_SAMPLE_RATE 48000
116 #define CRF_TIMESTAMPS_PER_SEC 300
117 #define TIMESTAMPS_PER_PKT 6
118 #define CRF_DATA_LEN (sizeof(uint64_t) * TIMESTAMPS_PER_PKT)
119 #define CRF_PDU_SIZE (sizeof(struct avtp_crf_pdu) + CRF_DATA_LEN)
120
121 #define MAX_PDU_SIZE MAX(AAF_PDU_SIZE, CRF_PDU_SIZE)
122 #define TIME_PERIOD_NS ((double)NSEC_PER_SEC / CRF_SAMPLE_RATE)
123 #define AAF_PERIOD (NSEC_PER_SEC * AAF_NUM_SAMPLES / AAF_SAMPLE_RATE)
124 #define MCLK_PERIOD AAF_PERIOD
125 #define MCLKLIST_TS_PER_CRF (CRF_SAMPLE_RATE / CRF_TIMESTAMPS_PER_SEC)
126
127 #define NSEC_PER_SEC 1000000000ULL
128 #define NSEC_PER_MSEC 1000000ULL
129
130 struct media_clock_entry {
131 STAILQ_ENTRY(media_clock_entry) mclk_entries;
132 uint64_t timestamp;
133 };
134
135 static enum {
136 MODE_TALKER,
137 MODE_LISTENER,
138 } mode;
139
140 static char ifname[IFNAMSIZ];
141 static uint8_t crf_macaddr[ETH_ALEN];
142 static uint8_t aaf_macaddr[ETH_ALEN];
143 static int priority = -1;
144 static int mtt;
145 static bool prev_state;
146 static bool first_aaf_pdu = true;
147 static bool need_mclk_lookup = true;
148 static uint8_t crf_seq_num;
149 static uint8_t aaf_seq_num;
150 static uint64_t prev_mclk_timestamp, rounded_mtt;
151 static STAILQ_HEAD(timestamp_queue, media_clock_entry) mclk_timestamps;
152
153 static struct argp_option options[] = {
154 {"crf-addr", 'c', "MACADDR", 0, "CRF Stream Destination MAC address" },
155 {"aaf-addr", 'a', "MACADDR", 0, "AAF Stream Destination MAC address" },
156 {"ifname", 'i', "IFNAME", 0, "Network Interface" },
157 {"prio", 'p', "NUM", 0, "SO_PRIORITY to be set in AAF stream" },
158 {"mtt", 'm', "MSEC", 0, "Max Transit time from AAF stream (in ms)" },
159 {"mode", 'o', "talker|listener", 0, "AAF operation mode"},
160 { 0 }
161 };
162
163 static error_t parser(int key, char *arg, struct argp_state *state)
164 {
165 int res;
166
167 switch (key) {
168 case 'c':
169 res = sscanf(arg, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
170 &crf_macaddr[0], &crf_macaddr[1], &crf_macaddr[2],
171 &crf_macaddr[3], &crf_macaddr[4], &crf_macaddr[5]);
172 if (res != 6) {
173 fprintf(stderr, "Invalid CRF address\n");
174 exit(EXIT_FAILURE);
175 }
176
177 break;
178 case 'a':
179 res = sscanf(arg, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
180 &aaf_macaddr[0], &aaf_macaddr[1], &aaf_macaddr[2],
181 &aaf_macaddr[3], &aaf_macaddr[4], &aaf_macaddr[5]);
182 if (res != 6) {
183 fprintf(stderr, "Invalid AAF address\n");
184 exit(EXIT_FAILURE);
185 }
186
187 break;
188 case 'm':
189 mtt = atoi(arg) * NSEC_PER_MSEC;
190 break;
191 case 'i':
192 strncpy(ifname, arg, sizeof(ifname) - 1);
193 break;
194 case 'p':
195 priority = atoi(arg);
196 break;
197 case 'o':
198 if (strcmp(arg, "talker") == 0)
199 mode = MODE_TALKER;
200 else if (strcmp(arg, "listener") == 0)
201 mode = MODE_LISTENER;
202 else {
203 fprintf(stderr, "Invalid mode\n");
204 exit(EXIT_FAILURE);
205 }
206 break;
207 }
208
209 return 0;
210 }
211
212 static struct argp argp = { options, parser };
213
214 static uint64_t mclk_dequeue_ts(void)
215 {
216 uint64_t mclk_timestamp;
217 struct media_clock_entry *mclk_entry;
218
219 mclk_entry = STAILQ_FIRST(&mclk_timestamps);
220 mclk_timestamp = mclk_entry->timestamp;
221 STAILQ_REMOVE_HEAD(&mclk_timestamps, mclk_entries);
222 free(mclk_entry);
223
224 return mclk_timestamp;
225 }
226
227 static int mclk_enqueue_ts(uint64_t ts)
228 {
229 struct media_clock_entry *mclk_entry;
230
231 mclk_entry = malloc(sizeof(*mclk_entry));
232 if (!mclk_entry) {
233 fprintf(stderr, "Failed to allocate memory\n");
234 return -1;
235 }
236
237 mclk_entry->timestamp = ts;
238 STAILQ_INSERT_TAIL(&mclk_timestamps, mclk_entry, mclk_entries);
239
240 return 0;
241 }
242
243 static uint64_t get_next_mclk_timestamp(void)
244 {
245 uint64_t mclk_timestamp;
246
247 if (STAILQ_EMPTY(&mclk_timestamps)) {
248 mclk_timestamp = prev_mclk_timestamp + MCLK_PERIOD;
249 need_mclk_lookup = true;
250 } else {
251 mclk_timestamp = mclk_dequeue_ts();
252 }
253
254 prev_mclk_timestamp = mclk_timestamp;
255
256 return mclk_timestamp;
257 }
258
259 static uint64_t mclk_lookup(uint32_t avtp_time)
260 {
261 uint64_t mclk_timestamp = get_next_mclk_timestamp();
262
263 while (mclk_timestamp % (1ULL << 32) != avtp_time)
264 mclk_timestamp = get_next_mclk_timestamp();
265
266 return mclk_timestamp;
267 }
268
269 static bool is_valid_crf_pdu(struct avtp_crf_pdu *pdu)
270 {
271 int res;
272 uint32_t val32;
273 uint64_t val64;
274 struct avtp_common_pdu *common = (struct avtp_common_pdu *) pdu;
275
276 res = avtp_pdu_get(common, AVTP_FIELD_SUBTYPE, &val32);
277 if (res < 0) {
278 fprintf(stderr, "Failed to get CRF subtype field: %d\n", res);
279 return false;
280 }
281 if (val32 != AVTP_SUBTYPE_CRF)
282 return false;
283
284 res = avtp_pdu_get(common, AVTP_FIELD_VERSION, &val32);
285 if (res < 0) {
286 fprintf(stderr, "Failed to get CRF version field: %d\n", res);
287 return false;
288 }
289 if (val32 != 0) {
290 fprintf(stderr, "CRF: Version mismatch: expected %u, got %u\n",
291 0, val32);
292 return false;
293 }
294
295 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_SV, &val64);
296 if (res < 0) {
297 fprintf(stderr, "Failed to get CRF sv field: %d\n", res);
298 return false;
299 }
300 if (val64 != 1) {
301 fprintf(stderr, "CRF: sv mismatch: expected %u, got %" PRIu64 "\n",
302 1, val64);
303 return false;
304 }
305
306 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_FS, &val64);
307 if (res < 0) {
308 fprintf(stderr, "Failed to get CRF fs field: %d\n", res);
309 return false;
310 }
311 if (val64 != 0) {
312 fprintf(stderr, "CRF: fs mismatch: expected %u, got %" PRIu64 "\n",
313 0, val64);
314 return false;
315 }
316
317 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_SEQ_NUM, &val64);
318 if (res < 0) {
319 fprintf(stderr, "Failed to get CRF sequence num field: %d\n",
320 res);
321 return false;
322 }
323 if (val64 != crf_seq_num) {
324 /* If we have a sequence number mismatch, we simply log the
325 * issue and continue to process the packet. We don't want to
326 * invalidate it since it is a valid packet after all.
327 */
328 fprintf(stderr, "CRF: Sequence number mismatch: expected %u, got %" PRIu64 "\n",
329 crf_seq_num, val64);
330
331 crf_seq_num = val64;
332 }
333
334 crf_seq_num++;
335
336 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_TYPE, &val64);
337 if (res < 0) {
338 fprintf(stderr, "Failed to get CRF format field: %d\n", res);
339 return false;
340 }
341 if (val64 != AVTP_CRF_TYPE_AUDIO_SAMPLE) {
342 fprintf(stderr, "CRF: Format mismatch: expected %u, got %" PRIu64 "\n",
343 AVTP_CRF_TYPE_AUDIO_SAMPLE, val64);
344 return false;
345 }
346
347 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_STREAM_ID, &val64);
348 if (res < 0) {
349 fprintf(stderr, "Failed to get CRF stream ID field: %d\n",
350 res);
351 return false;
352 }
353 if (val64 != CRF_STREAM_ID) {
354 fprintf(stderr, "CRF: Stream ID mismatch: expected %" PRIu64 ", got %" PRIu64 "\n",
355 CRF_STREAM_ID, val64);
356 return false;
357 }
358
359 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_PULL, &val64);
360 if (res < 0) {
361 fprintf(stderr, "Failed to get CRF multiplier modifier field: %d\n",
362 res);
363 return false;
364 }
365 if (val64 != AVTP_CRF_PULL_MULT_BY_1) {
366 fprintf(stderr, "CRF Pull mismatch: expected %u, got %" PRIu64 "\n",
367 AVTP_CRF_PULL_MULT_BY_1, val64);
368 return false;
369 }
370
371 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_BASE_FREQ, &val64);
372 if (res < 0) {
373 fprintf(stderr, "Failed to get CRF base frequency field: %d\n",
374 res);
375 return false;
376 }
377 if (val64 != CRF_SAMPLE_RATE) {
378 fprintf(stderr, "CRF Base frequency: expected %u, got %" PRIu64 "\n",
379 CRF_SAMPLE_RATE, val64);
380 return false;
381 }
382
383 res = avtp_crf_pdu_get(pdu, AVTP_CRF_FIELD_CRF_DATA_LEN, &val64);
384 if (res < 0) {
385 fprintf(stderr, "Failed to get CRF data length field: %d\n",
386 res);
387 return false;
388 }
389 if (val64 != CRF_DATA_LEN) {
390 fprintf(stderr, "CRF Data length mismatch: expected %zu, got %" PRIu64 "\n",
391 CRF_DATA_LEN, val64);
392 return false;
393 }
394
395 return true;
396 }
397
398 static bool is_valid_aaf_pdu(struct avtp_stream_pdu *pdu)
399 {
400 struct avtp_common_pdu *common = (struct avtp_common_pdu *) pdu;
401 uint64_t val64;
402 uint32_t val32;
403 int res;
404
405 res = avtp_pdu_get(common, AVTP_FIELD_VERSION, &val32);
406 if (res < 0) {
407 fprintf(stderr, "AAF: Failed to get version field: %d\n", res);
408 return false;
409 }
410 if (val32 != 0) {
411 fprintf(stderr, "AAF: Version mismatch: expected %u, got %u\n",
412 0, val32);
413 return false;
414 }
415
416 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_TV, &val64);
417 if (res < 0) {
418 fprintf(stderr, "AAF: Failed to get tv field: %d\n", res);
419 return false;
420 }
421 if (val64 != 1) {
422 fprintf(stderr, "AAF: tv mismatch: expected %u, got %" PRIu64 "\n",
423 1, val64);
424 return false;
425 }
426
427 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_SP, &val64);
428 if (res < 0) {
429 fprintf(stderr, "AAF: Failed to get sp field: %d\n", res);
430 return false;
431 }
432 if (val64 != AVTP_AAF_PCM_SP_NORMAL) {
433 fprintf(stderr, "AAF: tv mismatch: expected %u, got %" PRIu64 "\n",
434 1, val64);
435 return false;
436 }
437
438 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_STREAM_ID, &val64);
439 if (res < 0) {
440 fprintf(stderr, "AAF: Failed to get stream ID field: %d\n",
441 res);
442 return false;
443 }
444 if (val64 != AAF_STREAM_ID) {
445 fprintf(stderr, "AAF: Stream ID mismatch: expected %" PRIu64 ", got %" PRIu64 "\n",
446 AAF_STREAM_ID, val64);
447 return false;
448 }
449
450 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_SEQ_NUM, &val64);
451 if (res < 0) {
452 fprintf(stderr, "AAF: Failed to get sequence num field: %d\n",
453 res);
454 return false;
455 }
456
457 if (val64 != aaf_seq_num) {
458 /* If we have a sequence number mismatch, we simply log the
459 * issue and continue to process the packet. We don't want to
460 * invalidate it since it is a valid packet after all.
461 */
462 fprintf(stderr, "AAF Sequence number mismatch: expected %u, got %" PRIu64 "\n",
463 aaf_seq_num, val64);
464
465 aaf_seq_num = val64;
466 }
467
468 aaf_seq_num++;
469
470 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_FORMAT, &val64);
471 if (res < 0) {
472 fprintf(stderr, "AAF: Failed to get format field: %d\n", res);
473 return false;
474 }
475 if (val64 != AVTP_AAF_FORMAT_INT_16BIT) {
476 fprintf(stderr, "AAF: Format mismatch: expected %u, got %" PRIu64 "\n",
477 AVTP_AAF_FORMAT_INT_16BIT, val64);
478 return false;
479 }
480
481 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_NSR, &val64);
482 if (res < 0) {
483 fprintf(stderr, "AAF: Failed to get sample rate field: %d\n",
484 res);
485 return false;
486 }
487 if (val64 != AVTP_AAF_PCM_NSR_48KHZ) {
488 fprintf(stderr, "AAF: Sample rate mismatch: expected %u, got %" PRIu64 "\n",
489 AVTP_AAF_PCM_NSR_48KHZ, val64);
490 return false;
491 }
492
493 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_CHAN_PER_FRAME, &val64);
494 if (res < 0) {
495 fprintf(stderr, "AAF: Failed to get channels field: %d\n",
496 res);
497 return false;
498 }
499 if (val64 != AAF_NUM_CHANNELS) {
500 fprintf(stderr, "AAF: Channels mismatch: expected %u, got %" PRIu64 "\n",
501 AAF_NUM_CHANNELS, val64);
502 return false;
503 }
504
505 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_BIT_DEPTH, &val64);
506 if (res < 0) {
507 fprintf(stderr, "AAF: Failed to get depth field: %d\n", res);
508 return false;
509 }
510 if (val64 != 16) {
511 fprintf(stderr, "AAF: Depth mismatch: expected %u, got %" PRIu64 "\n",
512 16, val64);
513 return false;
514 }
515
516 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_STREAM_DATA_LEN, &val64);
517 if (res < 0) {
518 fprintf(stderr, "AAF: Failed to get data_len field: %d\n",
519 res);
520 return false;
521 }
522 if (val64 != AAF_DATA_LEN) {
523 fprintf(stderr, "AAF: Data len mismatch: expected %u, got %" PRIu64 "\n",
524 AAF_DATA_LEN, val64);
525 return false;
526 }
527
528 return true;
529 }
530
531 static int init_aaf_pdu(struct avtp_stream_pdu *pdu)
532 {
533 int res;
534
535 res = avtp_aaf_pdu_init(pdu);
536 if (res < 0)
537 return -1;
538
539 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_TV, 1);
540 if (res < 0)
541 return -1;
542
543 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_STREAM_ID, AAF_STREAM_ID);
544 if (res < 0)
545 return -1;
546
547 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_FORMAT,
548 AVTP_AAF_FORMAT_INT_16BIT);
549 if (res < 0)
550 return -1;
551
552 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_NSR,
553 AVTP_AAF_PCM_NSR_48KHZ);
554 if (res < 0)
555 return -1;
556
557 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_CHAN_PER_FRAME,
558 AAF_NUM_CHANNELS);
559 if (res < 0)
560 return -1;
561
562 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_BIT_DEPTH, 16);
563 if (res < 0)
564 return -1;
565
566 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_STREAM_DATA_LEN,
567 AAF_DATA_LEN);
568 if (res < 0)
569 return -1;
570
571 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_SP,
572 AVTP_AAF_PCM_SP_NORMAL);
573 if (res < 0)
574 return -1;
575
576 return 0;
577 }
578
579 static int aaf_talker_tx_timeout(int fd_timer, int fd_sk,
580 const struct sockaddr_ll *addr,
581 struct avtp_stream_pdu *pdu)
582 {
583 int res;
584 ssize_t n;
585 uint64_t expirations;
586 uint32_t avtp_time = 0;
587
588 n = read(fd_timer, &expirations, sizeof(uint64_t));
589 if (n < 0) {
590 perror("Failed to read timerfd");
591 return -1;
592 }
593
594 while (expirations--) {
595 avtp_time = get_next_mclk_timestamp();
596
597 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_TIMESTAMP,
598 avtp_time);
599 if (res < 0)
600 return res;
601
602 res = avtp_aaf_pdu_set(pdu, AVTP_AAF_FIELD_SEQ_NUM,
603 aaf_seq_num++);
604 if (res < 0)
605 return res;
606
607 n = sendto(fd_sk, pdu, AAF_PDU_SIZE, 0,
608 (struct sockaddr *) addr,
609 sizeof(*addr));
610 if (n < 0) {
611 perror("Failed to send data");
612 return -1;
613 }
614 if (n != AAF_PDU_SIZE) {
615 fprintf(stderr, "AAF: wrote %zd bytes, expected %zd\n",
616 n, AAF_PDU_SIZE);
617 }
618 }
619
620 return 0;
621 }
622
623 /* This routine generates media clock timestamps using timestamps from CRF
624 * stream.
625 */
626 static int recover_mclk(struct avtp_crf_pdu *pdu)
627 {
628 int res, idx;
629 uint64_t ts_mclk, ts_crf;
630
631 /* For simplicity's sake, we consider only the first timestamp from
632 * CRF PDU to recover the media clock.
633 */
634 ts_crf = be64toh(pdu->crf_data[0]);
635
636 for (idx = 0; idx < MCLKLIST_TS_PER_CRF; idx++) {
637 ts_mclk = ts_crf + (idx * MCLK_PERIOD);
638
639 if (mode == MODE_TALKER) {
640 /* If we are operating in talker mode, the max transit
641 * time is added to the recovered timestamp, rounding
642 * it up to the nearest multiple fo the media clock.
643 */
644 ts_mclk += rounded_mtt;
645 }
646
647 if (ts_mclk <= prev_mclk_timestamp)
648 /* If the recovered timestamp is less than the
649 * timestamp from the last AAF pdu received, we discard
650 * it. This situation happens when the CRF pdu is
651 * received late and the media clock has already
652 * freewheeled.
653 */
654 continue;
655
656 res = mclk_enqueue_ts(ts_mclk);
657 if (res < 0)
658 return res;
659 }
660
661 return 0;
662 }
663
664 static int is_ts_aligned(uint32_t mclk_ts, uint32_t avtp_ts)
665 {
666 int n = 0;
667 int t_offset, delta_ll, delta_hl;
668
669 t_offset = avtp_ts - mclk_ts;
670
671 delta_ll = (n * TIME_PERIOD_NS) - (TIME_PERIOD_NS/4);
672 delta_hl = (n * TIME_PERIOD_NS) + (TIME_PERIOD_NS/4);
673
674 /* Equation 16 defined in spec 1722:
675 * ((n * Ps) - Ps/4) < Toffset < ((n * Ps) + Ps/4)
676 * Toffset: timestamp offset in nanoseconds between the
677 AVTP Presentation Timestamp of the media stream
678 and the timestamp of the CRF stream
679 * n : positive integer chosen for the implementation
680 * Ps : the sample period of the CRF stream in nanoseconds
681 */
682 if (delta_ll > t_offset || t_offset > delta_hl)
683 return false;
684
685 return true;
686 }
687
688 static int handle_crf_pdu(struct avtp_crf_pdu *pdu)
689 {
690 if (!is_valid_crf_pdu(pdu))
691 return 0;
692
693 return recover_mclk(pdu);
694 }
695
696 static int handle_aaf_pdu(struct avtp_stream_pdu *pdu)
697 {
698 int res;
699 bool state;
700 uint64_t val;
701 uint32_t avtp_time, mclk_time;
702
703 if (!is_valid_aaf_pdu(pdu))
704 return 0;
705
706 res = avtp_aaf_pdu_get(pdu, AVTP_AAF_FIELD_TIMESTAMP, &val);
707 if (res < 0) {
708 fprintf(stderr, "Failed to get AVTP time from PDU\n");
709 return res;
710 }
711 avtp_time = val;
712
713 if (need_mclk_lookup) {
714 mclk_time = mclk_lookup(avtp_time);
715 need_mclk_lookup = false;
716 } else {
717 mclk_time = get_next_mclk_timestamp();
718 }
719
720 state = is_ts_aligned(mclk_time, avtp_time);
721 if (prev_state != state) {
722 if (state)
723 printf("AAF Stream is aligned with common media clock\n");
724 else
725 printf("AAF Stream is not aligned with common media clock\n");
726 }
727 prev_state = state;
728
729 return 0;
730 }
731
732 static int aaf_talker_recv_pdu(int fd_sk, int fd_timer)
733 {
734 int res;
735 ssize_t n;
736 struct avtp_crf_pdu *pdu = alloca(CRF_PDU_SIZE);
737
738 memset(pdu, 0, CRF_PDU_SIZE);
739
740 n = recv(fd_sk, pdu, CRF_PDU_SIZE, 0);
741 if (n < 0) {
742 perror("Failed to receive data");
743 return -1;
744 }
745
746 /* The protocol type from rx socket is set to ETH_P_ALL so we receive
747 * non-AVTP packets as well. In order to filter out those packets, we
748 * check the number of bytes received. If it doesn't match the CRF pdu
749 * size we drop the packet.
750 */
751 if (n != CRF_PDU_SIZE)
752 return 0;
753
754 res = handle_crf_pdu(pdu);
755 if (res < 0)
756 return -1;
757
758 /* Arm the timer for the first time to start sending AAF stream. */
759 if (first_aaf_pdu) {
760 struct itimerspec itspec = { 0 };
761 uint64_t ts = mclk_dequeue_ts();
762
763 first_aaf_pdu = false;
764
765 itspec.it_value.tv_sec = ts / NSEC_PER_SEC;
766 itspec.it_value.tv_nsec = ts % NSEC_PER_SEC;
767 itspec.it_interval.tv_sec = 0;
768 itspec.it_interval.tv_nsec = AAF_PERIOD;
769 res = timerfd_settime(fd_timer, TFD_TIMER_ABSTIME, &itspec,
770 NULL);
771 if (res < 0) {
772 perror("Failed to set timer");
773 return -1;
774 }
775 }
776 return 0;
777 }
778
779 static int aaf_listener_recv_pdu(int fd)
780 {
781 int res;
782 ssize_t n;
783 uint32_t val;
784 void *pdu = alloca(MAX_PDU_SIZE);
785 struct avtp_common_pdu *common = (struct avtp_common_pdu *) pdu;
786
787 memset(pdu, 0, MAX_PDU_SIZE);
788
789 n = recv(fd, pdu, MAX_PDU_SIZE, 0);
790 if (n < 0) {
791 perror("Failed to receive data");
792 return -1;
793 }
794
795 /* The protocol type from rx socket is set to ETH_P_ALL so we receive
796 * non-AVTP packets as well. In order to filter out those packets, we
797 * check the number of bytes received. If it doesn't match the CRF or
798 * AAF pdu size we drop the packet.
799 */
800 if (n != AAF_PDU_SIZE && n != CRF_PDU_SIZE)
801 return 0;
802
803 res = avtp_pdu_get(common, AVTP_FIELD_SUBTYPE, &val);
804 if (res < 0) {
805 fprintf(stderr, "Failed to get subtype field: %d\n", res);
806 return -1;
807 }
808
809 switch (val) {
810 case AVTP_SUBTYPE_CRF:
811 res = handle_crf_pdu(pdu);
812 break;
813 case AVTP_SUBTYPE_AAF:
814 res = handle_aaf_pdu(pdu);
815 break;
816 }
817
818 return res;
819 }
820
821 static int setup_rx_socket(void)
822 {
823 int res, fd;
824 struct ifreq req = {0};
825 struct packet_mreq mreq = {0};
826
827 /* In case this example is running on the same host where crf-talker is
828 * running, we set protocol type to ETH_P_ALL to allow CRF traffic to
829 * loop back.
830 */
831 fd = create_listener_socket(ifname, crf_macaddr, ETH_P_ALL);
832 if (fd < 0) {
833 perror("Failed to open socket");
834 return -1;
835 }
836
837 if (mode == MODE_LISTENER) {
838 snprintf(req.ifr_name, sizeof(req.ifr_name), "%s", ifname);
839 res = ioctl(fd, SIOCGIFINDEX, &req);
840 if (res < 0) {
841 perror("Failed to get interface index");
842 goto err;
843 }
844
845 mreq.mr_ifindex = req.ifr_ifindex;
846 mreq.mr_type = PACKET_MR_MULTICAST;
847 mreq.mr_alen = ETH_ALEN;
848 memcpy(&mreq.mr_address, aaf_macaddr, ETH_ALEN);
849
850 res = setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq,
851 sizeof(struct packet_mreq));
852 if (res < 0) {
853 perror("Couldn't add membership for AAF stream");
854 goto err;
855 }
856 }
857
858 return fd;
859
860 err:
861 close(fd);
862 return -1;
863 }
864
865 static int aaf_talker(int fd_rx)
866 {
867 int res, fd_tx, fd_timer;
868 struct pollfd poll_fd[2];
869 struct sockaddr_ll sk_addr = {0};
870 struct ifreq req = {0};
871 struct avtp_stream_pdu *pdu;
872
873 fd_tx = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_TSN));
874 if (fd_tx < 0) {
875 perror("Failed to open socket");
876 return -1;
877 }
878
879 if (priority != -1) {
880 res = setsockopt(fd_tx, SOL_SOCKET, SO_PRIORITY, &priority,
881 sizeof(priority));
882 if (res < 0) {
883 perror("Failed to set priority");
884 goto fd_tx_close;
885 }
886 }
887
888 snprintf(req.ifr_name, sizeof(req.ifr_name), "%s", ifname);
889 res = ioctl(fd_tx, SIOCGIFINDEX, &req);
890 if (res < 0) {
891 perror("Failed to get interface index");
892 goto fd_tx_close;
893 }
894
895 sk_addr.sll_family = AF_PACKET;
896 sk_addr.sll_protocol = htons(ETH_P_TSN);
897 sk_addr.sll_halen = ETH_ALEN;
898 sk_addr.sll_ifindex = req.ifr_ifindex;
899 memcpy(&sk_addr.sll_addr, aaf_macaddr, ETH_ALEN);
900
901 fd_timer = timerfd_create(CLOCK_REALTIME, 0);
902 if (fd_timer < 0)
903 goto fd_tx_close;
904
905 pdu = alloca(AAF_PDU_SIZE);
906 res = init_aaf_pdu(pdu);
907 if (res < 0)
908 goto fd_timer_close;
909 memset(pdu->avtp_payload, 0, AAF_DATA_LEN);
910
911 poll_fd[0].fd = fd_rx;
912 poll_fd[0].events = POLLIN;
913 poll_fd[1].fd = fd_timer;
914 poll_fd[1].events = POLLIN;
915
916 while (1) {
917 res = poll(poll_fd, 2, -1);
918 if (res < 0) {
919 perror("Failed to poll() fds");
920 goto fd_timer_close;
921 }
922
923 if (poll_fd[0].revents & POLLIN) {
924 res = aaf_talker_recv_pdu(fd_rx, fd_timer);
925 if (res < 0)
926 goto fd_timer_close;
927 }
928
929 if (poll_fd[1].revents & POLLIN) {
930 res = aaf_talker_tx_timeout(fd_timer, fd_tx, &sk_addr,
931 pdu);
932 if (res < 0)
933 goto fd_timer_close;
934 }
935 }
936
937 close(fd_timer);
938 close(fd_tx);
939 return 0;
940
941 fd_timer_close:
942 close(fd_timer);
943 fd_tx_close:
944 close(fd_tx);
945 return 1;
946 }
947
948 static int aaf_listener(int fd_rx)
949 {
950 int res;
951
952 while (1) {
953 res = aaf_listener_recv_pdu(fd_rx);
954 if (res < 0)
955 return -1;
956 }
957 }
958
959 int main(int argc, char *argv[])
960 {
961 int fd_rx;
962
963 argp_parse(&argp, argc, argv, 0, NULL, NULL);
964
965 STAILQ_INIT(&mclk_timestamps);
966 rounded_mtt = ceil((double)mtt / MCLK_PERIOD) * MCLK_PERIOD;
967
968 fd_rx = setup_rx_socket();
969 if (fd_rx < 0)
970 return 1;
971
972 switch (mode) {
973 case MODE_LISTENER:
974 aaf_listener(fd_rx);
975 break;
976 case MODE_TALKER:
977 aaf_talker(fd_rx);
978 break;
979 }
980
981 close(fd_rx);
982 return 0;
983 }