-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.c
More file actions
1179 lines (992 loc) · 34.6 KB
/
Copy pathserver.c
File metadata and controls
1179 lines (992 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* A simple RTSP server implementation using libevent [1].
*
* To obtain `audio.g711a` and `video.h264`:
*
* $ ffmpeg -i http://docs.evostream.com/sample_content/assets/bun33s.mp4 \
* -acodec pcm_mulaw -f mulaw -ar 8000 -ac 1 audio.g711a \
* -vcodec h264 -x264opts aud=1 video.h264
*
* [1] https://libevent.org/
*/
#include <compy.h>
#include "compy-libevent.h"
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#define ENABLE_AUDIO
#define ENABLE_VIDEO
/* Media files loaded at startup via mmap */
static uint8_t *media_video = NULL;
static size_t media_video_len = 0;
static uint8_t *media_audio = NULL;
static size_t media_audio_len = 0;
static int media_video_fps = 30;
/* Authentication (NULL = disabled) */
static Compy_Auth *g_auth = NULL;
/* TLS/SRTP globals */
#ifdef COMPY_HAS_TLS
static Compy_TlsContext *g_tls_ctx = NULL;
static bool g_srtp_enabled = false;
static Compy_SrtpKeyMaterial g_srtp_key;
#endif
/* Pre-indexed NAL unit table (built once at startup) */
typedef struct {
uint8_t *data; /* pointer to first byte after start code (NAL header) */
size_t len; /* length of NAL unit (header + payload, no start code) */
uint8_t nal_type; /* H.264 NAL unit type */
} NalEntry;
static NalEntry *g_nal_table = NULL;
static size_t g_nal_count = 0;
static size_t g_nal_start_idx = 0; /* index of first SPS for clean start */
static void build_nal_index(void) {
if (!media_video || media_video_len == 0)
return;
U8Slice99 video = U8Slice99_new(media_video, media_video_len);
Compy_NalStartCodeTester tester = compy_determine_start_code(video);
if (!tester)
return;
/* First pass: count NALs */
size_t count = 0;
U8Slice99 scan = video;
while (!U8Slice99_is_empty(scan)) {
size_t sc = tester(scan);
if (sc > 0) {
count++;
scan = U8Slice99_advance(scan, sc);
} else {
scan = U8Slice99_advance(scan, 1);
}
}
g_nal_table = malloc(count * sizeof(NalEntry));
assert(g_nal_table);
/* Second pass: record offsets */
scan = video;
size_t idx = 0;
uint8_t *prev_nal = NULL;
while (!U8Slice99_is_empty(scan)) {
size_t sc = tester(scan);
if (sc > 0) {
if (prev_nal && idx > 0) {
g_nal_table[idx - 1].len = (size_t)(scan.ptr - prev_nal);
}
scan = U8Slice99_advance(scan, sc);
prev_nal = scan.ptr;
g_nal_table[idx].data = scan.ptr;
g_nal_table[idx].nal_type = scan.ptr[0] & 0x1F;
g_nal_table[idx].len = 0;
idx++;
} else {
scan = U8Slice99_advance(scan, 1);
}
}
/* Last NAL extends to end of file */
if (idx > 0 && prev_nal) {
g_nal_table[idx - 1].len =
(size_t)(media_video + media_video_len - prev_nal);
}
g_nal_count = idx;
/* Find first SPS for clean decoder start */
g_nal_start_idx = 0;
for (size_t i = 0; i < g_nal_count; i++) {
if (g_nal_table[i].nal_type == COMPY_H264_NAL_UNIT_SPS) {
g_nal_start_idx = i;
break;
}
}
printf(
"Indexed %zu NALs (starting at #%zu, type %u)\n", g_nal_count,
g_nal_start_idx,
g_nal_count > 0 ? g_nal_table[g_nal_start_idx].nal_type : 0);
}
static int mmap_file(const char *path, uint8_t **out, size_t *out_len) {
int fd = open(path, O_RDONLY);
if (fd == -1) {
perror(path);
return -1;
}
struct stat st;
if (fstat(fd, &st) == -1) {
perror("fstat");
close(fd);
return -1;
}
*out_len = (size_t)st.st_size;
*out = mmap(NULL, *out_len, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (*out == MAP_FAILED) {
perror("mmap");
*out = NULL;
return -1;
}
return 0;
}
#define SERVER_PORT 8554
#define AUDIO_PCMU_PAYLOAD_TYPE 0
#define AUDIO_SAMPLE_RATE 8000
#define AUDIO_SAMPLES_PER_PACKET 160
#define AUDIO_PACKETIZATION_TIME_US \
(1e6 / (AUDIO_SAMPLE_RATE / AUDIO_SAMPLES_PER_PACKET))
#define VIDEO_PAYLOAD_TYPE 96 // dynamic PT
#define VIDEO_SAMPLE_RATE 90000
#define VIDEO_FPS 30
#define RTCP_INTERVAL_SEC 5
#define BACKCHANNEL_PAYLOAD_TYPE 0 // PCMU
#define BACKCHANNEL_SAMPLE_RATE 8000
#define AUDIO_STREAM_ID 0
#define VIDEO_STREAM_ID 1
#define BACKCHANNEL_STREAM_ID 2
#define MAX_STREAMS 3
typedef struct {
uint64_t session_id;
Compy_RtpTransport *transport;
Compy_Rtcp *rtcp;
struct event *ev;
struct event *rtcp_ev;
Compy_Droppable ctx;
} Stream;
/* Backchannel audio receiver — logs received audio for demonstration */
typedef struct {
size_t total_bytes;
} BackchannelReceiver;
static void BackchannelReceiver_on_audio(
VSelf, uint8_t payload_type, uint32_t timestamp, uint32_t ssrc,
U8Slice99 payload) {
VSELF(BackchannelReceiver);
(void)timestamp;
(void)ssrc;
self->total_bytes += payload.len;
printf(
"Backchannel: received %zu bytes (PT=%u, total=%zu)\n", payload.len,
payload_type, self->total_bytes);
}
impl(Compy_AudioReceiver, BackchannelReceiver);
typedef struct {
struct event_base *base;
struct bufferevent *bev;
struct sockaddr_storage addr;
size_t addr_len;
Stream streams[MAX_STREAMS];
int streams_playing;
bool backchannel_supported;
Compy_Backchannel *backchannel;
BackchannelReceiver backchannel_recv;
} Client;
declImpl(Compy_Controller, Client);
static void listener_cb(
struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa,
int socklen, void *ctx);
static void on_event_cb(struct bufferevent *bev, short events, void *ctx);
static void on_sigint_cb(evutil_socket_t sig, short events, void *ctx);
static int setup_transport(
Client *self, Compy_Context *ctx, const Compy_Request *req,
Compy_Transport *t, Compy_Transport *rtcp_t);
static int setup_tcp(
Compy_Context *ctx, Compy_Transport *t, Compy_Transport *rtcp_t,
Compy_TransportConfig config);
static int setup_udp(
const struct sockaddr *addr, Compy_Context *ctx, Compy_Transport *t,
Compy_Transport *rtcp_t, Compy_TransportConfig config);
typedef struct {
Compy_RtpTransport *transport;
size_t i;
struct event *ev;
struct bufferevent *bev;
int *streams_playing;
} AudioCtx;
static Compy_Droppable play_audio(
struct event_base *base, struct bufferevent *bev, Compy_RtpTransport *t,
struct event **ev, int *streams_playing);
static void send_audio_packet_cb(evutil_socket_t fd, short events, void *arg);
typedef struct {
Compy_NalTransport *transport;
uint32_t timestamp;
size_t nal_idx; /* current index into g_nal_table */
struct event *ev;
struct bufferevent *bev;
int *streams_playing;
} VideoCtx;
static Compy_Droppable play_video(
struct event_base *base, struct bufferevent *bev, Compy_RtpTransport *t,
struct event **ev, int *streams_playing);
static void send_video_packet_cb(evutil_socket_t fd, short events, void *arg);
/* Auth credential lookup callback */
static bool auth_lookup(
const char *username, char *password_out, size_t password_max,
void *user_data) {
const char *expected_creds = user_data; /* "user:pass" */
const char *colon = strchr(expected_creds, ':');
if (!colon)
return false;
size_t user_len = (size_t)(colon - expected_creds);
if (strlen(username) != user_len)
return false;
if (strncmp(username, expected_creds, user_len) != 0)
return false;
strncpy(password_out, colon + 1, password_max - 1);
password_out[password_max - 1] = '\0';
return true;
}
static void print_usage(const char *prog) {
fprintf(
stderr,
"Usage: %s [options]\n"
" -v <file.h264> H.264 video file (Annex B)\n"
" -a <file.g711a> G.711 mu-law audio file\n"
" -f <fps> Video frame rate (default: 30)\n"
" -p <port> Server port (default: %d)\n"
" -u <user:pass> Enable Digest authentication\n"
#ifdef COMPY_HAS_TLS
" -t <cert.pem> TLS certificate (enables RTSPS)\n"
" -k <key.pem> TLS private key\n"
" -s Enable SRTP/SRTCP encryption\n"
#endif
,
prog, SERVER_PORT);
}
int main(int argc, char *argv[]) {
srand(time(NULL));
const char *video_path = "media/bbb/bbb_sunflower_1080p_30fps_normal.h264";
const char *audio_path = "media/bbb/bbb_sunflower_1080p_30fps_normal.g711a";
int port = SERVER_PORT;
const char *auth_creds = NULL;
#ifdef COMPY_HAS_TLS
const char *tls_cert = NULL;
const char *tls_key = NULL;
#endif
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-v") == 0 && i + 1 < argc) {
video_path = argv[++i];
} else if (strcmp(argv[i], "-a") == 0 && i + 1 < argc) {
audio_path = argv[++i];
} else if (strcmp(argv[i], "-f") == 0 && i + 1 < argc) {
media_video_fps = atoi(argv[++i]);
} else if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) {
port = atoi(argv[++i]);
} else if (strcmp(argv[i], "-u") == 0 && i + 1 < argc) {
auth_creds = argv[++i];
#ifdef COMPY_HAS_TLS
} else if (strcmp(argv[i], "-t") == 0 && i + 1 < argc) {
tls_cert = argv[++i];
} else if (strcmp(argv[i], "-k") == 0 && i + 1 < argc) {
tls_key = argv[++i];
} else if (strcmp(argv[i], "-s") == 0) {
g_srtp_enabled = true;
#endif
} else {
print_usage(argv[0]);
return EXIT_FAILURE;
}
}
/* Set up authentication */
if (auth_creds) {
if (!strchr(auth_creds, ':')) {
fprintf(stderr, "Auth format: user:pass\n");
return EXIT_FAILURE;
}
g_auth = Compy_Auth_new("Compy", auth_lookup, (void *)auth_creds);
printf(
"Authentication enabled (user: %.*s)\n",
(int)(strchr(auth_creds, ':') - auth_creds), auth_creds);
}
#ifdef COMPY_HAS_TLS
/* Set up TLS */
if (tls_cert && tls_key) {
g_tls_ctx = Compy_TlsContext_new(
(Compy_TlsConfig){.cert_path = tls_cert, .key_path = tls_key});
if (!g_tls_ctx) {
fprintf(stderr, "Failed to load TLS cert/key\n");
return EXIT_FAILURE;
}
printf("RTSPS enabled (cert: %s)\n", tls_cert);
}
/* Set up SRTP key material */
if (g_srtp_enabled) {
if (compy_srtp_generate_key(&g_srtp_key) != 0) {
fprintf(stderr, "Failed to generate SRTP key\n");
return EXIT_FAILURE;
}
printf("SRTP/SRTCP enabled (AES-128-CM + HMAC-SHA1-80)\n");
}
#endif
if (mmap_file(video_path, &media_video, &media_video_len) == -1) {
fprintf(stderr, "Failed to load video: %s\n", video_path);
return EXIT_FAILURE;
}
if (mmap_file(audio_path, &media_audio, &media_audio_len) == -1) {
fprintf(stderr, "Failed to load audio: %s\n", audio_path);
return EXIT_FAILURE;
}
printf(
"Loaded video: %s (%zu bytes, %d fps)\n"
"Loaded audio: %s (%zu bytes)\n",
video_path, media_video_len, media_video_fps, audio_path,
media_audio_len);
build_nal_index();
struct event_base *base;
if ((base = event_base_new()) == NULL) {
fputs("event_base_new failed.\n", stderr);
return EXIT_FAILURE;
}
/* Dual-stack: try IPv6 first, fall back to IPv4 */
struct sockaddr_in6 sin6 = {
.sin6_family = AF_INET6,
.sin6_port = htons(port),
.sin6_addr = in6addr_any,
};
struct evconnlistener *listener;
listener = evconnlistener_new_bind(
base, listener_cb, (void *)base,
LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr *)&sin6,
sizeof sin6);
if (listener == NULL) {
/* IPv6 failed, try IPv4 */
struct sockaddr_in sin4 = {
.sin_family = AF_INET,
.sin_port = htons(port),
};
listener = evconnlistener_new_bind(
base, listener_cb, (void *)base,
LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1,
(struct sockaddr *)&sin4, sizeof sin4);
}
if (listener == NULL) {
fputs("evconnlistener_new_bind failed.\n", stderr);
return EXIT_FAILURE;
}
struct event *sigint_handler;
if ((sigint_handler =
evsignal_new(base, SIGINT, on_sigint_cb, (void *)base)) == NULL) {
fputs("evsignal_new failed.\n", stderr);
return EXIT_FAILURE;
}
if (event_add(sigint_handler, NULL) < 0) {
fputs("event_add failed.\n", stderr);
return EXIT_FAILURE;
}
printf("Server started on port %d.\n", port);
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(sigint_handler);
event_base_free(base);
if (g_auth) {
Compy_Auth_free(g_auth);
}
#ifdef COMPY_HAS_TLS
if (g_tls_ctx) {
Compy_TlsContext_free(g_tls_ctx);
}
#endif
puts("Done.");
return EXIT_SUCCESS;
}
static void listener_cb(
struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa,
int socklen, void *arg) {
(void)listener;
(void)fd;
(void)socklen;
struct event_base *base = arg;
struct bufferevent *bev;
if ((bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE)) ==
NULL) {
fputs("bufferevent_socket_new failed.\n", stderr);
event_base_loopbreak(base);
return;
}
Client *client = calloc(1, sizeof *client);
assert(client);
client->base = base;
client->bev = bev;
memcpy(&client->addr, sa, socklen);
client->addr_len = socklen;
Compy_Controller controller = DYN(Client, Compy_Controller, client);
void *ctx = compy_libevent_ctx(controller);
bufferevent_setcb(bev, compy_libevent_cb, NULL, on_event_cb, ctx);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
static void on_event_cb(struct bufferevent *bev, short events, void *ctx) {
if (events & BEV_EVENT_EOF) {
puts("Connection closed.");
} else if (events & BEV_EVENT_ERROR) {
perror("Got an error on the connection");
}
bufferevent_free(bev);
compy_libevent_ctx_free(ctx);
}
static void on_sigint_cb(evutil_socket_t sig, short events, void *ctx) {
(void)sig;
(void)events;
struct event_base *base = ctx;
puts("Caught an interrupt signal; exiting cleanly in two seconds.");
struct timeval delay = {2, 0};
event_base_loopexit(base, &delay);
}
static void send_rtcp_sr_cb(evutil_socket_t fd, short events, void *arg) {
(void)fd;
(void)events;
Compy_Rtcp *rtcp = arg;
if (Compy_Rtcp_send_sr(rtcp) == -1) {
perror("Failed to send RTCP SR");
}
}
static void Client_drop(VSelf) {
VSELF(Client);
for (size_t i = 0; i < MAX_STREAMS; i++) {
/* Stop stream timer first to prevent callbacks on freed memory */
if (self->streams[i].ev) {
event_del(self->streams[i].ev);
}
if (self->streams[i].rtcp) {
int bye_ret __attribute__((unused)) =
Compy_Rtcp_send_bye(self->streams[i].rtcp);
if (self->streams[i].rtcp_ev) {
event_del(self->streams[i].rtcp_ev);
event_free(self->streams[i].rtcp_ev);
}
VCALL(
DYN(Compy_Rtcp, Compy_Droppable, self->streams[i].rtcp), drop);
}
if (self->streams[i].ctx.vptr != NULL) {
VCALL(self->streams[i].ctx, drop);
}
}
if (self->backchannel) {
VCALL(DYN(Compy_Backchannel, Compy_Droppable, self->backchannel), drop);
}
free(self);
}
impl(Compy_Droppable, Client);
static void
Client_options(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
(void)self;
(void)req;
compy_header(
ctx, COMPY_HEADER_PUBLIC,
"DESCRIBE, SETUP, PLAY, PAUSE, TEARDOWN, GET_PARAMETER");
compy_respond_ok(ctx);
}
static void
Client_describe(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
/* Check if client requests backchannel via ONVIF Require tag */
self->backchannel_supported = compy_require_has_tag(
&req->header_map, COMPY_REQUIRE_ONVIF_BACKCHANNEL);
char sdp_buf[2048] = {0};
Compy_Writer sdp = compy_string_writer(sdp_buf);
ssize_t ret = 0;
/* Detect true IPv6 vs IPv4-mapped IPv6 (::ffff:x.x.x.x) */
bool is_ipv6 = false;
if (self->addr.ss_family == AF_INET6) {
const struct sockaddr_in6 *a6 =
(const struct sockaddr_in6 *)&self->addr;
is_ipv6 = !IN6_IS_ADDR_V4MAPPED(&a6->sin6_addr);
}
const char *ip_ver = is_ipv6 ? "IP6" : "IP4";
const char *ip_any = is_ipv6 ? "::" : "0.0.0.0";
// clang-format off
COMPY_SDP_DESCRIBE(
ret, sdp,
(COMPY_SDP_VERSION, "0"),
(COMPY_SDP_ORIGIN, "Compy 3855320066 3855320129 IN %s %s", ip_ver, ip_any),
(COMPY_SDP_SESSION_NAME, "Compy example"),
(COMPY_SDP_CONNECTION, "IN %s %s", ip_ver, ip_any),
(COMPY_SDP_TIME, "0 0"));
#ifdef ENABLE_VIDEO
COMPY_SDP_DESCRIBE(
ret, sdp,
(COMPY_SDP_MEDIA, "video 0 RTP/AVP %d", VIDEO_PAYLOAD_TYPE),
(COMPY_SDP_ATTR, "control:video"),
(COMPY_SDP_ATTR, "recvonly"),
(COMPY_SDP_ATTR, "rtpmap:%d H264/%" PRIu32, VIDEO_PAYLOAD_TYPE, VIDEO_SAMPLE_RATE),
(COMPY_SDP_ATTR, "fmtp:%d packetization-mode=1", VIDEO_PAYLOAD_TYPE),
(COMPY_SDP_ATTR, "framerate:%d", media_video_fps));
#endif
#ifdef ENABLE_AUDIO
COMPY_SDP_DESCRIBE(
ret, sdp,
(COMPY_SDP_MEDIA, "audio 0 RTP/AVP %d", AUDIO_PCMU_PAYLOAD_TYPE),
(COMPY_SDP_ATTR, "control:audio"),
(COMPY_SDP_ATTR, "recvonly"));
#endif
if (self->backchannel_supported) {
COMPY_SDP_DESCRIBE(
ret, sdp,
(COMPY_SDP_MEDIA, "audio 0 RTP/AVP %d", BACKCHANNEL_PAYLOAD_TYPE),
(COMPY_SDP_ATTR, "control:audioback"),
(COMPY_SDP_ATTR, "rtpmap:%d PCMU/%d", BACKCHANNEL_PAYLOAD_TYPE, BACKCHANNEL_SAMPLE_RATE),
(COMPY_SDP_ATTR, "sendonly"));
}
#ifdef COMPY_HAS_TLS
if (g_srtp_enabled) {
char crypto_attr[128];
if (compy_srtp_format_crypto_attr(
crypto_attr, sizeof crypto_attr, 1,
Compy_SrtpSuite_AES_CM_128_HMAC_SHA1_80, &g_srtp_key) < 0) {
fprintf(stderr, "Failed to format SRTP crypto attribute\n");
}
COMPY_SDP_DESCRIBE(
ret, sdp,
(COMPY_SDP_ATTR, "crypto:%s", crypto_attr));
}
#endif
// clang-format on
assert(ret > 0);
compy_header(ctx, COMPY_HEADER_CONTENT_TYPE, "application/sdp");
compy_body(ctx, CharSlice99_from_str(sdp_buf));
compy_respond_ok(ctx);
}
static void Client_setup(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
Compy_Transport transport, rtcp_transport;
if (setup_transport(self, ctx, req, &transport, &rtcp_transport) == -1) {
return;
}
size_t stream_id;
if (CharSlice99_primitive_ends_with(
req->start_line.uri, CharSlice99_from_str("/audioback"))) {
stream_id = BACKCHANNEL_STREAM_ID;
} else if (CharSlice99_primitive_ends_with(
req->start_line.uri, CharSlice99_from_str("/audio"))) {
stream_id = AUDIO_STREAM_ID;
} else {
stream_id = VIDEO_STREAM_ID;
}
Stream *stream = &self->streams[stream_id];
const bool aggregate_control_requested =
Compy_HeaderMap_contains_key(&req->header_map, COMPY_HEADER_SESSION);
if (aggregate_control_requested) {
uint64_t session_id;
if (compy_scanf_header(
&req->header_map, COMPY_HEADER_SESSION, "%" SCNu64,
&session_id) != 1) {
compy_respond(ctx, COMPY_STATUS_BAD_REQUEST, "Malformed `Session'");
return;
}
stream->session_id = session_id;
} else {
{
uint64_t sid;
FILE *f = fopen("/dev/urandom", "r");
assert(f);
assert(fread(&sid, sizeof sid, 1, f) == 1);
fclose(f);
stream->session_id = sid;
}
}
if (BACKCHANNEL_STREAM_ID == stream_id) {
/* Backchannel: no outbound RTP transport needed, create receiver */
stream->transport = NULL;
self->backchannel_recv = (BackchannelReceiver){.total_bytes = 0};
self->backchannel = Compy_Backchannel_new(
Compy_BackchannelConfig_default(),
DYN(BackchannelReceiver, Compy_AudioReceiver,
&self->backchannel_recv));
/* RTCP transport not used for backchannel in this example */
VCALL_SUPER(rtcp_transport, Compy_Droppable, drop);
VCALL_SUPER(transport, Compy_Droppable, drop);
} else if (AUDIO_STREAM_ID == stream_id) {
stream->transport = Compy_RtpTransport_new(
transport, AUDIO_PCMU_PAYLOAD_TYPE, AUDIO_SAMPLE_RATE);
stream->rtcp =
Compy_Rtcp_new(stream->transport, rtcp_transport, "compy@camera");
} else {
stream->transport = Compy_RtpTransport_new(
transport, VIDEO_PAYLOAD_TYPE, VIDEO_SAMPLE_RATE);
stream->rtcp =
Compy_Rtcp_new(stream->transport, rtcp_transport, "compy@camera");
}
compy_header(ctx, COMPY_HEADER_SESSION, "%" PRIu64, stream->session_id);
compy_respond_ok(ctx);
}
static void Client_play(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
uint64_t session_id;
if (compy_scanf_header(
&req->header_map, COMPY_HEADER_SESSION, "%" SCNu64, &session_id) !=
1) {
compy_respond(ctx, COMPY_STATUS_BAD_REQUEST, "Malformed `Session'");
return;
}
bool played = false;
for (size_t i = 0; i < MAX_STREAMS; i++) {
if (self->streams[i].session_id == session_id) {
if (AUDIO_STREAM_ID == i) {
self->streams[i].ctx = play_audio(
self->base, self->bev, self->streams[i].transport,
&self->streams[i].ev, &self->streams_playing);
} else {
self->streams[i].ctx = play_video(
self->base, self->bev, self->streams[i].transport,
&self->streams[i].ev, &self->streams_playing);
}
/* Start RTCP SR timer */
if (self->streams[i].rtcp && self->streams[i].rtcp_ev == NULL) {
self->streams[i].rtcp_ev = event_new(
self->base, -1, EV_PERSIST | EV_TIMEOUT, send_rtcp_sr_cb,
self->streams[i].rtcp);
assert(self->streams[i].rtcp_ev);
event_add(
self->streams[i].rtcp_ev,
&(const struct timeval){.tv_sec = RTCP_INTERVAL_SEC,
.tv_usec = 0});
}
played = true;
}
}
if (!played) {
compy_respond(
ctx, COMPY_STATUS_SESSION_NOT_FOUND, "Invalid Session ID");
return;
}
compy_header(ctx, COMPY_HEADER_RANGE, "npt=now-");
compy_respond_ok(ctx);
}
static void
Client_teardown(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
uint64_t session_id;
if (compy_scanf_header(
&req->header_map, COMPY_HEADER_SESSION, "%" SCNu64, &session_id) !=
1) {
compy_respond(ctx, COMPY_STATUS_BAD_REQUEST, "Malformed `Session'");
return;
}
bool teardowned = false;
for (size_t i = 0; i < MAX_STREAMS; i++) {
if (self->streams[i].session_id == session_id) {
event_del(self->streams[i].ev);
teardowned = true;
}
}
if (!teardowned) {
compy_respond(
ctx, COMPY_STATUS_SESSION_NOT_FOUND, "Invalid Session ID");
return;
}
compy_respond_ok(ctx);
}
static void
Client_pause_method(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
(void)self;
(void)req;
compy_respond_ok(ctx);
}
static void
Client_get_parameter(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
(void)self;
(void)req;
/* Keepalive — just respond 200 OK */
compy_respond_ok(ctx);
}
static void
Client_unknown(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
(void)self;
(void)req;
compy_respond(ctx, COMPY_STATUS_NOT_IMPLEMENTED, "Not Implemented");
}
static Compy_ControlFlow
Client_before(VSelf, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
(void)self;
printf(
"%s %s CSeq=%" PRIu32 ".\n",
CharSlice99_alloca_c_str(req->start_line.method),
CharSlice99_alloca_c_str(req->start_line.uri), req->cseq);
/* Digest authentication check */
if (g_auth && compy_auth_check(g_auth, ctx, req) != 0) {
return Compy_ControlFlow_Break;
}
return Compy_ControlFlow_Continue;
}
static void
Client_after(VSelf, ssize_t ret, Compy_Context *ctx, const Compy_Request *req) {
VSELF(Client);
(void)self;
(void)ctx;
(void)req;
if (ret < 0) {
perror("Failed to respond");
}
}
impl(Compy_Controller, Client);
static int setup_transport(
Client *self, Compy_Context *ctx, const Compy_Request *req,
Compy_Transport *t, Compy_Transport *rtcp_t) {
CharSlice99 transport_val;
const bool transport_found = Compy_HeaderMap_find(
&req->header_map, COMPY_HEADER_TRANSPORT, &transport_val);
if (!transport_found) {
compy_respond(ctx, COMPY_STATUS_BAD_REQUEST, "`Transport' not present");
return -1;
}
Compy_TransportConfig config;
if (compy_parse_transport(&config, transport_val) == -1) {
compy_respond(ctx, COMPY_STATUS_BAD_REQUEST, "Malformed `Transport'");
return -1;
}
switch (config.lower) {
case Compy_LowerTransport_TCP:
if (setup_tcp(ctx, t, rtcp_t, config) == -1) {
compy_respond_internal_error(ctx);
return -1;
}
break;
case Compy_LowerTransport_UDP:
if (setup_udp(
(const struct sockaddr *)&self->addr, ctx, t, rtcp_t, config) ==
-1) {
compy_respond_internal_error(ctx);
return -1;
}
break;
}
return 0;
}
static int setup_tcp(
Compy_Context *ctx, Compy_Transport *t, Compy_Transport *rtcp_t,
Compy_TransportConfig config) {
ifLet(config.interleaved, Compy_ChannelPair_Some, interleaved) {
*t = compy_transport_tcp(
Compy_Context_get_writer(ctx), interleaved->rtp_channel, 0);
*rtcp_t = compy_transport_tcp(
Compy_Context_get_writer(ctx), interleaved->rtcp_channel, 0);
compy_header(
ctx, COMPY_HEADER_TRANSPORT,
"RTP/AVP/TCP;unicast;interleaved=%" PRIu8 "-%" PRIu8,
interleaved->rtp_channel, interleaved->rtcp_channel);
return 0;
}
compy_respond(ctx, COMPY_STATUS_BAD_REQUEST, "`interleaved' not found");
return -1;
}
static int setup_udp(
const struct sockaddr *addr, Compy_Context *ctx, Compy_Transport *t,
Compy_Transport *rtcp_t, Compy_TransportConfig config) {
ifLet(config.client_port, Compy_PortPair_Some, client_port) {
int fd;
if ((fd = compy_dgram_socket(
addr->sa_family, compy_sockaddr_ip(addr),
client_port->rtp_port)) == -1) {
return -1;
}
int rtcp_fd;
if ((rtcp_fd = compy_dgram_socket(
addr->sa_family, compy_sockaddr_ip(addr),
client_port->rtcp_port)) == -1) {
close(fd);
return -1;
}
/* Determine the local ports */
struct sockaddr_storage local_addr;
socklen_t local_len = sizeof local_addr;
uint16_t server_rtp_port = 0, server_rtcp_port = 0;
if (getsockname(fd, (struct sockaddr *)&local_addr, &local_len) == 0) {
if (local_addr.ss_family == AF_INET) {
server_rtp_port =
ntohs(((struct sockaddr_in *)&local_addr)->sin_port);
} else {
server_rtp_port =
ntohs(((struct sockaddr_in6 *)&local_addr)->sin6_port);
}
}
local_len = sizeof local_addr;
if (getsockname(rtcp_fd, (struct sockaddr *)&local_addr, &local_len) ==
0) {
if (local_addr.ss_family == AF_INET) {
server_rtcp_port =
ntohs(((struct sockaddr_in *)&local_addr)->sin_port);
} else {
server_rtcp_port =
ntohs(((struct sockaddr_in6 *)&local_addr)->sin6_port);
}
}
*t = compy_transport_udp(fd);
*rtcp_t = compy_transport_udp(rtcp_fd);
#ifdef COMPY_HAS_TLS
if (g_srtp_enabled) {
*t = compy_transport_srtp(
*t, Compy_SrtpSuite_AES_CM_128_HMAC_SHA1_80, &g_srtp_key);
*rtcp_t = compy_transport_srtcp(
*rtcp_t, Compy_SrtpSuite_AES_CM_128_HMAC_SHA1_80, &g_srtp_key);
}
#endif
compy_header(
ctx, COMPY_HEADER_TRANSPORT,
"RTP/AVP/UDP;unicast;client_port=%" PRIu16 "-%" PRIu16
";server_port=%" PRIu16 "-%" PRIu16,
client_port->rtp_port, client_port->rtcp_port, server_rtp_port,
server_rtcp_port);
return 0;
}