This repository has been archived by the owner on Mar 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathlibjanus_rtpbroadcast.c
3925 lines (3472 loc) · 138 KB
/
libjanus_rtpbroadcast.c
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
/*! \file cm_rtpbcast.c
* \author Lorenzo Miniero <[email protected]>
* \copyright GNU General Public License v3
* \brief Janus Streaming plugin
* \details This is a streaming plugin for Janus, allowing WebRTC peers
* to watch/listen to pre-recorded files or media generated by another tool.
* Specifically, the plugin currently supports three different type of streams:
*
* -# on-demand streaming of pre-recorded media files (different
* streaming context for each peer);
* -# live streaming of pre-recorded media files (shared streaming
* context for all peers attached to the stream);
* -# live streaming of media generated by another tool (shared
* streaming context for all peers attached to the stream).
*
* For what concerns types 1. and 2., considering the proof of concept
* nature of the implementation the only pre-recorded media files
* that the plugins supports right now are raw mu-Law and a-Law files:
* support is of course planned for other additional widespread formats
* as well.
*
* For what concerns type 3., instead, the plugin is configured
* to listen on a couple of ports for RTP: this means that the plugin
* is implemented to receive RTP on those ports and relay them to all
* peers attached to that stream. Any tool that can generate audio/video
* RTP streams and specify a destination is good for the purpose: the
* examples section contains samples that make use of GStreamer (http://gstreamer.freedesktop.org/)
* but other tools like FFmpeg (http://www.ffmpeg.org/), LibAV (http://libav.org/)
* or others are fine as well. This makes it really easy to capture and
* encode whatever you want using your favourite tool, and then have it
* transparently broadcasted via WebRTC using Janus.
*
* Streams to make available are listed in the plugin configuration file.
* A pre-filled configuration file is provided in \c conf/janus.plugin.streaming.cfg
* and includes a stream of every type.
*
* To add more streams or modify the existing ones, you can use the following
* syntax:
*
* \verbatim
[stream-name]
type = rtp|live|ondemand|rtsp
rtp = stream originated by an external tool (e.g., gstreamer or
ffmpeg) and sent to the plugin via RTP
live = local file streamed live to multiple listeners
(multiple listeners = same streaming context)
ondemand = local file streamed on-demand to a single listener
(multiple listeners = different streaming contexts)
rtsp = stream originated by an external RTSP feed (only
available if libcurl support was compiled)
id = <unique numeric ID>
description = This is my awesome stream
is_private = yes|no (private streams don't appear when you do a 'list' request)
filename = path to the local file to stream (only for live/ondemand)
secret = <optional password needed for manipulating (e.g., destroying
or enabling/disabling) the stream>
pin = <optional password needed for watching the stream>
audio = yes|no (do/don't stream audio)
video = yes|no (do/don't stream video)
The following options are only valid for the 'rtp' type:
audioport = local port for receiving audio frames
audiomcast = multicast group port for receiving audio frames, if any
audiopt = <audio RTP payload type> (e.g., 111)
audiortpmap = RTP map of the audio codec (e.g., opus/48000/2)
audiofmtp = Codec specific parameters, if any
videoport = local port for receiving video frames (only for rtp)
videomcast = multicast group port for receiving video frames, if any
videopt = <video RTP payload type> (e.g., 100)
videortpmap = RTP map of the video codec (e.g., VP8/90000)
videofmtp = Codec specific parameters, if any
The following options are only valid for the 'rstp' type:
url = RTSP stream URL (only if type=rtsp)
\endverbatim
*
* \section streamapi Streaming API
*
* The Streaming API supports several requests, some of which are
* synchronous and some asynchronous. There are some situations, though,
* (invalid JSON, invalid request) which will always result in a
* synchronous error response even for asynchronous requests.
*
* \c list , \c create , \c destroy , \c recording , \c enable and
* \c disable are synchronous requests, which means you'll
* get a response directly within the context of the transaction. \c list
* lists all the available streams; \c create allows you to create a new
* mountpoint dynamically, as an alternative to using the configuration
* file; \c destroy removes a mountpoint and destroys it; \c recording
* instructs the plugin on whether or not a live RTP stream should be
* recorded while it's broadcasted; \c enable and \c disable respectively
* enable and disable a mountpoint, that is decide whether or not a
* mountpoint should be available to users without destroying it.
*
* The \c watch , \c start , \c pause , \c switch and \c stop requests
* instead are all asynchronous, which means you'll get a notification
* about their success or failure in an event. \c watch asks the plugin
* to prepare the playout of one of the available streams; \c start
* starts the actual playout; \c pause allows you to pause a playout
* without tearing down the PeerConnection; \c switch allows you to
* switch to a different mountpoint of the same kind (note: only live
* RTP mountpoints supported as of now) without having to stop and watch
* the new one; \c stop stops the playout and tears the PeerConnection
* down.
*
* Actual API docs: TBD.
*
* \ingroup plugins
* \ref plugins
*/
#include "janus/plugin.h"
#include <jansson.h>
#include <errno.h>
/* TODO @landswellsong those are not really portable, are they? */
#include <sys/poll.h>
#include <sys/time.h>
#include <netdb.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <ftw.h>
#include <libgen.h>
#include "janus/debug.h"
#include "janus/apierror.h"
#include "janus/config.h"
#include "janus/mutex.h"
#include "janus/rtp.h"
#include "janus/rtcp.h"
#include "janus/record.h"
#include "janus/utils.h"
#define _XOPEN_SOURCE 500
#define FTW_DEPTH 8
#define FTW_PHYS 1
#define FTW_DP 5
struct FTW {
int base;
int level;
};
/* Plugin information */
#define CM_RTPBCAST_VERSION 5
#define CM_RTPBCAST_VERSION_STRING "0.0.5"
#define CM_RTPBCAST_DESCRIPTION "This is a streaming plugin for Janus, allowing WebRTC peers to watch/listen to pre-recorded files or media generated by gstreamer."
#define CM_RTPBCAST_NAME "JANUS CM video plugin"
#define CM_RTPBCAST_AUTHOR "Meetecho s.r.l."
#define CM_RTPBCAST_PACKAGE "janus.plugin.cm.rtpbroadcast"
/* Plugin methods */
janus_plugin *create(void);
int cm_rtpbcast_init(janus_callbacks *callback, const char *config_path);
void cm_rtpbcast_destroy(void);
int cm_rtpbcast_get_api_compatibility(void);
int cm_rtpbcast_get_version(void);
const char *cm_rtpbcast_get_version_string(void);
const char *cm_rtpbcast_get_description(void);
const char *cm_rtpbcast_get_name(void);
const char *cm_rtpbcast_get_author(void);
const char *cm_rtpbcast_get_package(void);
void cm_rtpbcast_create_session(janus_plugin_session *handle, int *error);
struct janus_plugin_result *cm_rtpbcast_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp);
void cm_rtpbcast_setup_media(janus_plugin_session *handle);
void cm_rtpbcast_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
void cm_rtpbcast_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
void cm_rtpbcast_hangup_media(janus_plugin_session *handle);
void cm_rtpbcast_destroy_session(janus_plugin_session *handle, int *error);
char *cm_rtpbcast_query_session(janus_plugin_session *handle);
/* Plugin setup */
static janus_plugin cm_rtpbcast_plugin =
JANUS_PLUGIN_INIT (
.init = cm_rtpbcast_init,
.destroy = cm_rtpbcast_destroy,
.get_api_compatibility = cm_rtpbcast_get_api_compatibility,
.get_version = cm_rtpbcast_get_version,
.get_version_string = cm_rtpbcast_get_version_string,
.get_description = cm_rtpbcast_get_description,
.get_name = cm_rtpbcast_get_name,
.get_author = cm_rtpbcast_get_author,
.get_package = cm_rtpbcast_get_package,
.create_session = cm_rtpbcast_create_session,
.handle_message = cm_rtpbcast_handle_message,
.setup_media = cm_rtpbcast_setup_media,
.incoming_rtp = cm_rtpbcast_incoming_rtp,
.incoming_rtcp = cm_rtpbcast_incoming_rtcp,
.hangup_media = cm_rtpbcast_hangup_media,
.destroy_session = cm_rtpbcast_destroy_session,
.query_session = cm_rtpbcast_query_session,
);
/* Plugin creator */
janus_plugin *create(void) {
JANUS_LOG(LOG_VERB, "%s created!\n", CM_RTPBCAST_NAME);
return &cm_rtpbcast_plugin;
}
typedef struct cm_rtpbcast_rtp_source cm_rtpbcast_rtp_source;
/* Useful stuff */
static volatile gint initialized = 0, stopping = 0;
static janus_callbacks *gateway = NULL;
static GThread *handler_thread;
static GThread *watchdog;
static GThread *udp_relay;
static void *cm_rtpbcast_handler(void *data);
static void cm_rtpbcast_relay_rtp_packet(gpointer data, gpointer user_data);
static void *cm_rtpbcast_relay_thread(void *data);
static gboolean cm_rtpbcast_vp8_is_frame_complete (GList *packets);
static char *str_replace(char *instr, const char *needle, const char *replace);
/* Helper to remove insane code duplication everywhere
Sample illustrating use:
something things[] = { X, Y, Z };
_foreach(i, things) {
print(things[i]);
}
Note, iterator variable exported in the current scope;
*/
#define _foreach(var, container) size_t var; for (var = 0; var < sizeof(container)/sizeof(container[0]); var++)
/* To remove unnecessary duplication all over, all things are arrays of 2 now
i.e. instead of audio_port you have port[AUDIO]
As a bonus, av_names[AUDIO] is "audio" string and so on
*/
#define AUDIO 0
#define VIDEO 1
#define AV 2
const char *av_names[] = { "audio", "video" };
static struct {
const char *hostname;
guint minport, maxport;
const char *job_path;
const char *job_temp_path;
const char *job_pattern;
const char *archive_path;
const char *recording_pattern;
const char *thumbnailing_pattern;
guint thumbnailing_interval;
guint mountpoint_info_interval;
guint keyframe_distance_alert;
guint udp_relay_interval;
gboolean recording_enabled;
gboolean simulate_bad_connection;
guint packet_loss_rate;
gboolean udp_relay_queue_enabled;
gboolean autoswitch;
} cm_rtpbcast_settings;
typedef struct cm_rtpbcast_codecs {
gint pt[AV];
char *rtpmap[AV];
char *fmtp[AV];
gint codec[AV];
} cm_rtpbcast_codecs;
#define STAT_SECOND 1000000
typedef struct cm_rtpbcast_stats {
gdouble cur;
/* FIXME do we need minmax here? */
gdouble packet_loss_rate;
guint64 packet_loss_count;
guint64 start_usec;
guint64 last_avg_usec;
guint64 bytes_since_start;
guint64 bytes_since_last_avg;
guint32 start_seq;
guint32 last_avg_seq;
guint32 max_seq_since_last_avg;
guint64 packets_since_start;
guint64 packets_since_last_avg;
janus_mutex stat_mutex;
} cm_rtpbcast_stats;
static void cm_rtpbcast_stats_restart(cm_rtpbcast_stats *);
static void cm_rtpbcast_stats_update(cm_rtpbcast_stats *, gsize, guint32, int);
typedef struct cm_rtpbcast_recorder {
janus_recorder *r;
cm_rtpbcast_rtp_source *source;
gboolean had_keyframe; /* if any keyframe has been passed to the recorder */
} cm_rtpbcast_recorder;
/* Forward declaration for pointer */
typedef struct cm_rtpbcast_session cm_rtpbcast_session;
typedef struct cm_rtpbcast_mountpoint {
char *id;
char *uid;
char *name;
char *description;
gboolean enabled;
gboolean recorded; /* Only sources[0] is recorded by default */
cm_rtpbcast_recorder *rc[AV]; /* The Janus recorder instance for this mountpoint's audio/video, if enabled */
cm_rtpbcast_recorder *trc[1]; /* Thumbnailing recorder, array for generic code sake */
guint64 last_thumbnail; /* Positon (frames/time) of last thumbnail taken */
gboolean whitelisted;
struct in_addr allowed_ip;
GArray *sources; // of type cm_rtpbcast_rtp_source*
gint64 destroyed;
cm_rtpbcast_session *session;
} cm_rtpbcast_mountpoint;
GHashTable *mountpoints;
static GList *old_mountpoints;
janus_mutex mountpoints_mutex;
/* TODO @landswellsong per-source recording */
static void cm_rtpbcast_start_recording(cm_rtpbcast_mountpoint *, int);
static void cm_rtpbcast_stop_recording(cm_rtpbcast_mountpoint *, int);
static void cm_rtpbcast_start_thumbnailing(cm_rtpbcast_mountpoint *, int);
static void cm_rtpbcast_stop_thumbnailing(cm_rtpbcast_mountpoint *, int);
typedef struct cm_rtpbcast_rtp_keyframe {
gboolean enabled;
/* If enabled, we store the packets of the last keyframe, to immediately send them for new viewers */
GList *latest_keyframe;
/* This is where we store packets while we're still collecting the whole keyframe */
GList *temp_keyframe;
guint32 temp_ts;
janus_mutex mutex;
} cm_rtpbcast_rtp_keyframe;
typedef struct cm_rtpbcast_vp8_payload_dscr {
gboolean is_sbit;
gboolean is_xbit;
gboolean is_ibit;
gboolean is_mbit;
gboolean is_pbit;
gboolean is_keyframe;
int width;
int height;
int width_scale;
int height_scale;
} cm_rtpbcast_vp8_payload_dscr;
typedef struct cm_rtpbcast_h264_payload_dscr {
gboolean is_keyframe;
} cm_rtpbcast_h264_payload_dscr;
cm_rtpbcast_vp8_payload_dscr *cm_rtpbcast_vp8_parse_payload(char* buffer, int len);
cm_rtpbcast_h264_payload_dscr *cm_rtpbcast_h264_parse_payload(char* buffer, int len);
typedef struct cm_rtpbcast_rtp_source {
gboolean active;
guint port[AV];
in_addr_t mcast[AV];
int fd[AV];
cm_rtpbcast_codecs codecs;
cm_rtpbcast_stats stats[AV];
cm_rtpbcast_mountpoint *mp;
gboolean enabled;
gint64 destroyed;
int index;
int frame_width;
int frame_height;
int frame_x_scale;
int frame_y_scale;
guint32 frame_count;
guint32 frame_last_count;
guint64 frame_last_usec;
guint32 frame_rate;
guint32 frame_key_last;
guint32 frame_key_distance;
gboolean frame_key_overdue;
GList/*<unowned cm_rtpbcast_session>*/ *listeners;
GList/*<unowned cm_rtpbcast_session>*/ *waiters; /* listeners waiting for keyframe */
cm_rtpbcast_rtp_keyframe keyframe;
janus_mutex mutex;
} cm_rtpbcast_rtp_source;
#define CM_RTPBCAST_VP8 0
#define CM_RTPBCAST_H264 1
#define CM_RTPBCAST_VP9 2
static cm_rtpbcast_rtp_source* cm_rtpbcast_pick_source(GArray/* cm_rtpbcast_rtp_source* */ *, guint64);
static void cm_rtpbcast_schedule_switch(cm_rtpbcast_session *sessid, cm_rtpbcast_rtp_source *newsrc);
static void cm_rtpbcast_unschedule_switch(cm_rtpbcast_session *sessid);
static void cm_rtpbcast_process_switchers(cm_rtpbcast_rtp_source *src);
json_t *cm_rtpbcast_source_to_json(cm_rtpbcast_rtp_source *src, cm_rtpbcast_session *session);
json_t *cm_rtpbcast_sources_to_json(GArray *sources, cm_rtpbcast_session *session);
json_t *cm_rtpbcast_mountpoint_to_json(cm_rtpbcast_mountpoint *mountpoint, cm_rtpbcast_session *session);
json_t *cm_rtpbcast_mountpoints_to_json(cm_rtpbcast_session *session);
/* The idea is, keep pointers to sources in hash table and keep track of
available ports in the shuffled list. When a port is fred, it is inserted
at a random poisition back in the list, thus the computatonally intensive
operations are carried at startup and at source destruction only
*/
static struct {
GHashTable *used_ports;
GList *free_ports;
janus_mutex used_ports_mutex;
guint ports_available; /* GList doesn't keep track of size */
} port_manager;
static void cm_rtpbcast_port_manager_init();
static guint cm_rtpbcast_port_manager_assign(gpointer);
static void cm_rtpbcast_port_manager_free(guint);
static void cm_rtpbcast_port_manager_destroy();
static void cm_rtpbcast_mountpoint_free(cm_rtpbcast_mountpoint *mp);
static void cm_rtpbcast_mountpoint_destroy(gpointer data, gpointer user_data);
/* Helper to create an RTP live source (e.g., from gstreamer/ffmpeg/vlc/etc.) */
typedef struct cm_rtpbcast_rtp_source_request {
char *mcast[AV];
uint8_t codec[AV];
char *rtpmap[AV];
char *fmtp[AV];
} cm_rtpbcast_rtp_source_request;
typedef struct cm_rtpbcast_rtp_relay_thread_data {
cm_rtpbcast_mountpoint *mp;
guint i;
} cm_rtpbcast_rtp_relay_thread_data;
cm_rtpbcast_mountpoint *cm_rtpbcast_create_rtp_source(
char* id, char *name, char *desc, gboolean recorded,
const char *allowed_ip, GArray *requests);
typedef struct cm_rtpbcast_message {
janus_plugin_session *handle;
char *transaction;
json_t *message;
char *sdp_type;
char *sdp;
} cm_rtpbcast_message;
static GAsyncQueue *messages = NULL;
void cm_rtpbcast_message_free(cm_rtpbcast_message *msg);
void cm_rtpbcast_message_free(cm_rtpbcast_message *msg) {
if(!msg)
return;
msg->handle = NULL;
g_free(msg->transaction);
msg->transaction = NULL;
if(msg->message)
json_decref(msg->message);
msg->message = NULL;
g_free(msg->sdp_type);
msg->sdp_type = NULL;
g_free(msg->sdp);
msg->sdp = NULL;
g_free(msg);
}
typedef struct cm_rtpbcast_context {
/* Needed to fix seq and ts in case of stream switching */
uint32_t last_ssrc[AV], last_ts[AV], base_ts[AV], base_ts_prev[AV];
uint16_t last_seq[AV], base_seq[AV], base_seq_prev[AV];
} cm_rtpbcast_context;
typedef struct cm_rtpbcast_udp_relay_gateway {
cm_rtpbcast_rtp_source *source;
struct sockaddr_in sin[AV];
gboolean valid[AV];
int fd;
} cm_rtpbcast_udp_relay_gateway;
gboolean cm_rtpbcast_construct_address(char *hostname, int port, struct sockaddr_in *sin);
typedef struct cm_rtpbcast_session {
janus_plugin_session *handle;
cm_rtpbcast_rtp_source *source;
cm_rtpbcast_rtp_source *nextsource; /* Source to switch after a keyframe */
gboolean super_user;
/* REMB and auxillary vars for math */
guint64 remb;
guint64 last_remb_usec;
guint64 last_switch;
gboolean autoswitch;
GArray *relay_udp_gateways; /*cm_rtpbcast_udp_relay_gateway*/
gboolean started;
gboolean paused;
cm_rtpbcast_context context;
GList/*cm_rtpbcast_mountpoint*/ *mps;
gboolean stopping;
volatile gint hangingup;
gint64 destroyed; /* Time at which this session was marked as destroyed */
janus_mutex mutex;
} cm_rtpbcast_session;
static GHashTable *sessions;
static GList *old_sessions;
static GList *super_sessions;
static janus_mutex sessions_mutex;
static void cm_rtpbcast_store_event(json_t* , const char *);
static void cm_rtpbcast_notify_supers(json_t*);
static void cm_rtpbcast_notify_session(gpointer, gpointer);
/* Stops UDP relays for the given session. Second parameter specifies the source pointer
* which has a mutex locked within current context and thus doesn't need locking */
static void cm_rtpbcast_stop_udp_relays(cm_rtpbcast_session *, cm_rtpbcast_rtp_source *);
/* Packets we get from gstreamer and relay */
typedef struct cm_rtpbcast_rtp_relay_packet {
rtp_header *data;
gint length;
gint is_video;
gint is_keyframe;
guint source_index;
uint32_t timestamp;
uint16_t seq_number;
} cm_rtpbcast_rtp_relay_packet;
/* Error codes */
#define CM_RTPBCAST_ERROR_NO_MESSAGE 450
#define CM_RTPBCAST_ERROR_INVALID_JSON 451
#define CM_RTPBCAST_ERROR_INVALID_REQUEST 452
#define CM_RTPBCAST_ERROR_MISSING_ELEMENT 453
#define CM_RTPBCAST_ERROR_INVALID_ELEMENT 454
#define CM_RTPBCAST_ERROR_NO_SUCH_MOUNTPOINT 455
#define CM_RTPBCAST_ERROR_CANT_CREATE 456
#define CM_RTPBCAST_ERROR_UNAUTHORIZED 457
#define CM_RTPBCAST_ERROR_CANT_SWITCH 458
#define CM_RTPBCAST_ERROR_UNKNOWN_ERROR 470
/* UDP relay queue */
typedef struct cm_rtpbcast_udp_relay_queue_node {
void *data;
guint len;
struct sockaddr_in dst;
} cm_rtpbcast_udp_relay_queue_node;
GList* /* cm_rtpbcast_udp_relay_queue_node* */ udp_relay_queue;
janus_mutex udp_relay_mutex;
/* Puts a packet in the queue */
void cm_rtpbcast_udp_enqueue(void *data, guint len, struct sockaddr_in *dst) {
/* Copy data over */
cm_rtpbcast_udp_relay_queue_node *nd = g_malloc0(sizeof(cm_rtpbcast_udp_relay_queue_node));
nd->len = len;
nd->data = g_malloc0(len);
memcpy(nd->data, data, len);
memcpy(&nd->dst, dst, sizeof(struct sockaddr_in));
/* Note this adds element from the front. Relay thread reverses the list.
* Also relay thread deallocates memory. */
janus_mutex_lock(&udp_relay_mutex);
udp_relay_queue = g_list_prepend(udp_relay_queue, nd);
janus_mutex_unlock(&udp_relay_mutex);
}
/* FIXME: what to do if socket() fails and thread exists? */
void *cm_rtpbcast_udp_relay_thread(void *data) {
JANUS_LOG(LOG_INFO, "UDP:Relay: thread started\n");
/* As frugal as we are, only one socket for all the UDP */
int fd;
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
JANUS_LOG(LOG_ERR, "UDP:Relay: cannot create socket! Reason: %s\n", strerror(errno));
return NULL;
}
/* On timer event, thread swaps udp_relay_queue with this one */
/* @landswellsong: currently it just creates a fresh list each round. Maybe
* there is some rationale to send only certain amount of packets and
* swap queues? I can't tell upfront where the bottleneck is. */
GList *queue = NULL;
while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
gint64 start = janus_get_monotonic_time();
janus_mutex_lock(&udp_relay_mutex);
queue = udp_relay_queue;
udp_relay_queue = NULL;
janus_mutex_unlock(&udp_relay_mutex);
/* Elements are prepended for performance, traverse from the back */
guint n = 0, success = 0;
while (queue) {
GList *last = g_list_last(queue);
cm_rtpbcast_udp_relay_queue_node *nd = last->data;
/* Send the packet */
n++;
if (sendto(fd, nd->data, nd->len, 0, (struct sockaddr *) &nd->dst, sizeof(struct sockaddr_in)) == -1)
JANUS_LOG(LOG_ERR, "UDP:Relay: cannot send message! Reason %s\n", strerror(errno));
else
success++;
/* Deallocate stuff */
g_free(nd->data);
g_free(nd);
/* Remove the last one */
queue = g_list_delete_link(queue, last);
}
gint64 ms_worked = janus_get_monotonic_time() - start;
if (n > 0) {
JANUS_LOG(LOG_HUGE, "UDP:Relay: done, queue was %d, sent %d successfully, job time %d usec.\n", n, success, ms_worked);
}
/* FIXME add configuration option */
/* If we worked more than timeout, don't sleep. Otherwise sleep the remaining time */
gint64 to_sleep = cm_rtpbcast_settings.udp_relay_interval - ms_worked;
g_usleep(to_sleep > 0 ? to_sleep : 0);
}
/* FIXME: should we bother removing the queue too? */
close(fd);
return NULL;
}
/* Streaming watchdog/garbage collector (sort of) */
void *cm_rtpbcast_watchdog(void *data);
void *cm_rtpbcast_watchdog(void *data) {
JANUS_LOG(LOG_INFO, "CM RTP Broadcast watchdog started\n");
gint64 now = 0;
gint64 session_update = 0;
while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
/* Iterate on all the sessions */
now = janus_get_monotonic_time();
if(old_sessions != NULL) {
GList *sl = old_sessions;
JANUS_LOG(LOG_HUGE, "Checking %d old CM RTP Broadcast sessions...\n", g_list_length(old_sessions));
while(sl) {
cm_rtpbcast_session *session = (cm_rtpbcast_session *)sl->data;
if(!session) {
sl = sl->next;
continue;
}
if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
/* We're lazy and actually get rid of the stuff only after a few seconds */
JANUS_LOG(LOG_VERB, "Freeing old CM RTP Broadcast session\n");
GList *rm = sl->next;
old_sessions = g_list_delete_link(old_sessions, sl);
sl = rm;
session->handle = NULL;
g_free(session);
session = NULL;
continue;
}
sl = sl->next;
}
}
janus_mutex_lock(&sessions_mutex);
if (now-session_update >= cm_rtpbcast_settings.mountpoint_info_interval * G_USEC_PER_SEC) {
if(sessions && g_hash_table_size(sessions) > 0) {
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, sessions);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
cm_rtpbcast_session *session = (cm_rtpbcast_session *) value;
if (!session || session->stopping || session->paused) {
continue;
}
if (session->source != NULL) {
json_t *event = json_object();
json_t *result = json_object();
json_object_set_new(event, "streaming", json_string("event"));
json_object_set_new(result, "event", json_string("mountpoint-info"));
json_t *st = cm_rtpbcast_sources_to_json(session->source->mp->sources, session);
json_object_set_new(result, "streams", st);
json_t *config = json_object();
json_object_set_new(config, "mountpoint-info-interval", json_integer(cm_rtpbcast_settings.mountpoint_info_interval));
json_object_set_new(result, "config", config);
json_object_set_new(event, "result", result);
char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
gateway->push_event(session->handle, &cm_rtpbcast_plugin, NULL, event_text, NULL, NULL);
}
}
}
session_update = janus_get_monotonic_time();
}
janus_mutex_unlock(&sessions_mutex);
janus_mutex_lock(&mountpoints_mutex);
/* Iterate on all the mountpoints */
if(old_mountpoints != NULL) {
GList *sl = old_mountpoints;
JANUS_LOG(LOG_HUGE, "Checking %d old CM RTP Broadcast mountpoints...\n", g_list_length(old_mountpoints));
while(sl) {
cm_rtpbcast_mountpoint *mountpoint = (cm_rtpbcast_mountpoint *)sl->data;
if(!mountpoint) {
sl = sl->next;
continue;
}
if(now-mountpoint->destroyed >= 5*G_USEC_PER_SEC) {
/* We're lazy and actually get rid of the stuff only after a few seconds */
JANUS_LOG(LOG_VERB, "Freeing old CM RTP Broadcast mountpoint\n");
GList *rm = sl->next;
old_mountpoints = g_list_delete_link(old_mountpoints, sl);
sl = rm;
cm_rtpbcast_mountpoint_free(mountpoint);
mountpoint = NULL;
continue;
}
sl = sl->next;
}
}
janus_mutex_unlock(&mountpoints_mutex);
g_usleep(500000);
}
JANUS_LOG(LOG_INFO, "CM RTP Broadcast watchdog stopped\n");
return NULL;
}
/* Plugin implementation */
int cm_rtpbcast_init(janus_callbacks *callback, const char *config_path) {
if(g_atomic_int_get(&stopping)) {
/* Still stopping from before */
return -1;
}
if(callback == NULL || config_path == NULL) {
/* Invalid arguments */
return -1;
}
/* Read configuration */
char filename[255];
g_snprintf(filename, 255, "%s/%s.cfg", config_path, CM_RTPBCAST_PACKAGE);
JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
janus_config *config = janus_config_parse(filename);
if(config != NULL)
janus_config_print(config);
/* Defauts */
cm_rtpbcast_settings.hostname = g_strdup("localhost");
cm_rtpbcast_settings.minport = 8000;
cm_rtpbcast_settings.maxport = 9000;
cm_rtpbcast_settings.mountpoint_info_interval = 10;
cm_rtpbcast_settings.udp_relay_interval = 50000;
cm_rtpbcast_settings.job_path = g_strdup("/tmp/jobs");
cm_rtpbcast_settings.job_temp_path = g_strdup("/tmp/jobs-temp");
cm_rtpbcast_settings.job_pattern = g_strdup("job-#{md5}");
cm_rtpbcast_settings.archive_path = g_strdup("/tmp/recordings");
cm_rtpbcast_settings.recording_pattern = g_strdup("rec-#{id}-#{time}-#{type}");
cm_rtpbcast_settings.thumbnailing_pattern = g_strdup("thum-#{id}-#{time}-#{type}");
cm_rtpbcast_settings.thumbnailing_interval = 60;
cm_rtpbcast_settings.keyframe_distance_alert = 600;
cm_rtpbcast_settings.recording_enabled = TRUE;
cm_rtpbcast_settings.simulate_bad_connection = FALSE;
cm_rtpbcast_settings.packet_loss_rate = 0;
cm_rtpbcast_settings.udp_relay_queue_enabled = FALSE;
cm_rtpbcast_settings.autoswitch = FALSE;
mountpoints = g_hash_table_new_full(
g_str_hash, /* Hashing func */
g_str_equal, /* Key comparator */
g_free, /* Key destructor */
NULL); /* Value destructor, we don't want this done automatically */
janus_mutex_init(&mountpoints_mutex);
/* Parse configuration to populate the mountpoints */
if(config != NULL) {
/* Boolean */
{
const char *inames [] = {
"recording_enabled",
"simulate_bad_connection",
"udp_relay_queue_enabled",
"autoswitch",
};
gboolean *ivars [] = {
&cm_rtpbcast_settings.recording_enabled,
&cm_rtpbcast_settings.simulate_bad_connection,
&cm_rtpbcast_settings.udp_relay_queue_enabled,
&cm_rtpbcast_settings.autoswitch,
};
_foreach(i, ivars) {
janus_config_item *itm = janus_config_get_item_drilldown(config, "general", inames[i]);
if (itm && itm->value) {
*ivars[i] = janus_is_true(itm->value);
}
}
}
/* Integers */
{
const char *inames [] = {
"minport",
"maxport",
"thumbnailing_interval",
"mountpoint_info_interval",
"keyframe_distance_alert",
"packet_loss_rate",
"udp_relay_interval",
};
guint *ivars [] = {
&cm_rtpbcast_settings.minport,
&cm_rtpbcast_settings.maxport,
&cm_rtpbcast_settings.thumbnailing_interval,
&cm_rtpbcast_settings.mountpoint_info_interval,
&cm_rtpbcast_settings.keyframe_distance_alert,
&cm_rtpbcast_settings.packet_loss_rate,
&cm_rtpbcast_settings.udp_relay_interval,
};
_foreach(i, ivars) {
janus_config_item *itm = janus_config_get_item_drilldown(config, "general", inames[i]);
if (itm && itm->value) {
guint res = g_ascii_strtoull(itm->value, NULL, 10);
if (res != 0)
*ivars[i] = res;
}
}
}
/* Strings */
{
const char *inames [] = {
"hostname",
"job_path",
"job_temp_path",
"job_pattern",
"archive_path",
"recording_pattern",
"thumbnailing_pattern"
};
const char **ivars [] = {
&cm_rtpbcast_settings.hostname,
&cm_rtpbcast_settings.job_path,
&cm_rtpbcast_settings.job_temp_path,
&cm_rtpbcast_settings.job_pattern,
&cm_rtpbcast_settings.archive_path,
&cm_rtpbcast_settings.recording_pattern,
&cm_rtpbcast_settings.thumbnailing_pattern
};
_foreach(i, ivars) {
janus_config_item *itm = janus_config_get_item_drilldown(config, "general", inames[i]);
if (itm && itm->value) {
g_free((gpointer)*ivars[i]);
*ivars[i] = g_strdup(itm->value);
}
}
}
if(cm_rtpbcast_settings.minport > cm_rtpbcast_settings.maxport) {
g_atomic_int_set(&initialized, 0);
JANUS_LOG(LOG_ERR, "Configuration error: minport %d is bigger than maxport %d\n",
cm_rtpbcast_settings.minport, cm_rtpbcast_settings.maxport);
return -1;
}
/* Done */
janus_config_destroy(config);
config = NULL;
}
cm_rtpbcast_port_manager_init(cm_rtpbcast_settings.minport, cm_rtpbcast_settings.maxport);
JANUS_LOG(LOG_INFO, "%s: Initializing...\n", CM_RTPBCAST_NAME);
/* In case of crash, segfault, kill, restart let's see if there are some unfinished Events */
/* Move Events from temporary path to final job path */
cm_rtpbcast_import_events_from_path(cm_rtpbcast_settings.job_temp_path);
JANUS_LOG(LOG_INFO, "%s: Imported waiting events from %s into %s\n", CM_RTPBCAST_NAME, cm_rtpbcast_settings.job_temp_path, cm_rtpbcast_settings.job_path);
filesystem_rmrf(cm_rtpbcast_settings.job_temp_path);
JANUS_LOG(LOG_INFO, "%s: Cleaned-up imported events at %s\n", CM_RTPBCAST_NAME, cm_rtpbcast_settings.job_temp_path);
/* Not showing anything, no mountpoint configured at startup */
sessions = g_hash_table_new(NULL, NULL);
super_sessions = NULL;
janus_mutex_init(&sessions_mutex);
messages = g_async_queue_new_full((GDestroyNotify) cm_rtpbcast_message_free);
/* This is the callback we'll need to invoke to contact the gateway */
gateway = callback;
g_atomic_int_set(&initialized, 1);
GError *error = NULL;
/* Start the sessions watchdog */
watchdog = g_thread_try_new("rtpbroadcast watchdog", &cm_rtpbcast_watchdog, NULL, &error);
if(!watchdog) {
g_atomic_int_set(&initialized, 0);
JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP broadcast watchdog thread...\n", error->code, error->message ? error->message : "??");
return -1;
}
/* Start the UDP relay thread */
janus_mutex_init(&udp_relay_mutex);
udp_relay_queue = NULL;
if (cm_rtpbcast_settings.udp_relay_queue_enabled) {
udp_relay = g_thread_try_new("rtpbroadcast udp relay", &cm_rtpbcast_udp_relay_thread, NULL, &error);
if(!udp_relay) {
g_atomic_int_set(&initialized, 0);
JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP broadcast UDP relay thread...\n", error->code, error->message ? error->message : "??");
return -1;
}
}
/* Launch the thread that will handle incoming messages */
handler_thread = g_thread_try_new("janus rtpbroadcast handler", cm_rtpbcast_handler, NULL, &error);
if(error != NULL) {
g_atomic_int_set(&initialized, 0);
JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP broadcast handler thread...\n", error->code, error->message ? error->message : "??");
return -1;
}
JANUS_LOG(LOG_INFO, "%s: Initialized!\n", CM_RTPBCAST_NAME);
return 0;
}
void cm_rtpbcast_destroy(void) {
if(!g_atomic_int_get(&initialized))
return;
g_atomic_int_set(&stopping, 1);
if(handler_thread != NULL) {
g_thread_join(handler_thread);
handler_thread = NULL;
}
/* Remove all mountpoints */
janus_mutex_lock(&mountpoints_mutex);
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, mountpoints);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
cm_rtpbcast_mountpoint *mp = value;
if(!mp->destroyed) {
mp->destroyed = janus_get_monotonic_time();
old_mountpoints = g_list_append(old_mountpoints, mp);
}
}
janus_mutex_unlock(&mountpoints_mutex);
if(watchdog != NULL) {
g_thread_join(watchdog);
watchdog = NULL;
}
if(udp_relay != NULL) {
g_thread_join(udp_relay);
udp_relay = NULL;
}
/* FIXME We should destroy the sessions cleanly */
usleep(500000);
janus_mutex_lock(&mountpoints_mutex);
g_hash_table_destroy(mountpoints); /* TODO: @landswellsong do we need to free them? */
janus_mutex_unlock(&mountpoints_mutex);
janus_mutex_lock(&sessions_mutex);
g_hash_table_destroy(sessions);
janus_mutex_unlock(&sessions_mutex);
if (old_sessions)
g_list_free(old_sessions);
JANUS_LOG(LOG_INFO, "8\n");
if (super_sessions)
g_list_free(super_sessions);
cm_rtpbcast_port_manager_destroy();
g_async_queue_unref(messages);
messages = NULL;
sessions = NULL;
/* Freeing configuration strings */
g_free((gpointer)cm_rtpbcast_settings.hostname);
g_free((gpointer)cm_rtpbcast_settings.job_path);
g_free((gpointer)cm_rtpbcast_settings.job_temp_path);
g_free((gpointer)cm_rtpbcast_settings.job_pattern);
g_free((gpointer)cm_rtpbcast_settings.archive_path);
g_free((gpointer)cm_rtpbcast_settings.recording_pattern);
g_free((gpointer)cm_rtpbcast_settings.thumbnailing_pattern);
g_atomic_int_set(&initialized, 0);
g_atomic_int_set(&stopping, 0);
JANUS_LOG(LOG_INFO, "%s destroyed!\n", CM_RTPBCAST_NAME);
}
int cm_rtpbcast_get_api_compatibility(void) {
/* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
return JANUS_PLUGIN_API_VERSION;
}