Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videoroom.c @ ae62ca8f

History | View | Annotate | Download (165 KB)

1
/*! \file   janus_videoroom.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus VideoRoom plugin
5
 * \details  This is a plugin implementing a videoconferencing SFU
6
 * (Selective Forwarding Unit) for Janus, that is an audio/video router.
7
 * This means that the plugin implements a virtual conferencing room peers
8
 * can join and leave at any time. This room is based on a Publish/Subscribe
9
 * pattern. Each peer can publish his/her own live audio/video feeds: this
10
 * feed becomes an available stream in the room the other participants can
11
 * attach to. This means that this plugin allows the realization of several
12
 * different scenarios, ranging from a simple webinar (one speaker, several
13
 * listeners) to a fully meshed video conference (each peer sending and
14
 * receiving to and from all the others).
15
 * 
16
 * For what concerns the subscriber side, there are two different ways to
17
 * attach to a publisher's feed: a generic 'listener', which can attach to
18
 * a single feed, and a more complex 'Multiplexed listener', which instead can
19
 * attach to more feeds using the same PeerConnection. The generic 'listener'
20
 * is the default, which means that if you want to watch more feeds at the
21
 * same time, you'll need to create multiple 'listeners' to attach at any
22
 * of them. The 'Multiplexed listener', instead, is a more complex alternative
23
 * that exploits the so called RTCWEB 'Plan B', which multiplexes more
24
 * streams on a single PeerConnection and in the SDP: while more efficient in terms of
25
 * resources, though, this approach is experimental, and currently only
26
 * available on Google Chrome, so use it wisely.
27
 * \note As of now, work on Plan B is still going on, and as such its support in Janus
28
 * is flaky to say the least. Don't try to attach as a Multiplexed listener or bad
29
 * things will probably happen!
30
 * 
31
 * Considering that this plugin allows for several different WebRTC PeerConnections
32
 * to be on at the same time for the same peer (specifically, each peer
33
 * potentially has 1 PeerConnection on for publishing and N on for subscriptions
34
 * from other peers), each peer may need to attach several times to the same
35
 * plugin for every stream: this means that each peer needs to have at least one
36
 * handle active for managing its relation with the plugin (joining a room,
37
 * leaving a room, muting/unmuting, publishing, receiving events), and needs
38
 * to open a new one each time he/she wants to subscribe to a feed from
39
 * another participant (or a single one in case a 'Multiplexed listener is used).
40
 * The handle used for a subscription, however, would be logically a "slave"
41
 * to the master one used for managing the room: this means that it cannot
42
 * be used, for instance, to unmute in the room, as its only purpose would
43
 * be to provide a context in which creating the sendonly PeerConnection
44
 * for the subscription to the active participant.
45
 * 
46
 * Rooms to make available are listed in the plugin configuration file.
47
 * A pre-filled configuration file is provided in \c conf/janus.plugin.videoroom.cfg
48
 * and includes a demo room for testing. The same plugin is also used
49
 * dynamically (that is, with rooms created on the fly via API) in the
50
 * Screen Sharing demo as well.
51
 * 
52
 * To add more rooms or modify the existing one, you can use the following
53
 * syntax:
54
 * 
55
 * \verbatim
56
[<unique room ID>]
57
description = This is my awesome room
58
is_private = yes|no (private rooms don't appear when you do a 'list' request)
59
secret = <optional password needed for manipulating (e.g. destroying) the room>
60
pin = <optional password needed for joining the room>
61
publishers = <max number of concurrent senders> (e.g., 6 for a video
62
             conference or 1 for a webinar)
63
bitrate = <max video bitrate for senders> (e.g., 128000)
64
fir_freq = <send a FIR to publishers every fir_freq seconds> (0=disable)
65
audiocodec = opus|isac32|isac16|pcmu|pcma (audio codec to force on publishers, default=opus)
66
videocodec = vp8|vp9|h264 (video codec to force on publishers, default=vp8)
67
record = true|false (whether this room should be recorded, default=false)
68
rec_dir = <folder where recordings should be stored, when enabled>
69
\endverbatim
70
 *
71
 * Note that recording will work with all codecs except iSAC.
72
 *
73
 * \section sfuapi Video Room API
74
 * 
75
 * The Video Room API supports several requests, some of which are
76
 * synchronous and some asynchronous. There are some situations, though,
77
 * (invalid JSON, invalid request) which will always result in a
78
 * synchronous error response even for asynchronous requests. 
79
 * 
80
 * \c create , \c destroy , \c exists, \c list and \c listparticipants
81
 * are synchronous requests, which means you'll
82
 * get a response directly within the context of the transaction.
83
 * \c create allows you to create a new video room dynamically, as an
84
 * alternative to using the configuration file; \c destroy removes a
85
 * video room and destroys it, kicking all the users out as part of the
86
 * process; \c exists allows you to check whether a specific video room
87
 * exists; finally, \c list lists all the available rooms, while \c
88
 * listparticipants lists all the participants of a specific room and
89
 * their details.
90
 * 
91
 * The \c join , \c joinandconfigure , \c configure , \c publish ,
92
 * \c unpublish , \c start , \c pause , \c switch , \c stop , \c add ,
93
 * \c remove and \c leave requests instead are all asynchronous, which
94
 * means you'll get a notification about their success or failure in
95
 * an event. \c join allows you to join a specific video room, specifying
96
 * whether that specific PeerConnection will be used for publishing or
97
 * watching; \c configure can be used to modify some of the participation
98
 * settings (e.g., bitrate cap); \c joinandconfigure combines the previous
99
 * two requests in a single one (just for publishers); \c publish can be
100
 * used to start sending media to broadcast to the other participants,
101
 * while \c unpublish does the opposite; \c start allows you to start
102
 * receiving media from a publisher you've subscribed to previously by
103
 * means of a \c join , while \c pause pauses the delivery of the media;
104
 * the \c switch request can be used to change the source of the media
105
 * flowing over a specific PeerConnection (e.g., I was watching Alice,
106
 * I want to watch Bob now) without having to create a new handle for
107
 * that; \c stop interrupts a viewer instance; \c add and \c remove
108
 * are just used when involving "Plan B", and are used to add or remove
109
 * publishers to be muxed in the single viewer PeerConnection; finally,
110
 * \c leave allows you to leave a video room for good.
111
 * 
112
 * Notice that, in general, all users can create rooms. If you want to
113
 * limit this functionality, you can configure an admin \c admin_key in
114
 * the plugin settings. When configured, only "create" requests that
115
 * include the correct \c admin_key value in an "admin_key" property
116
 * will succeed, and will be rejected otherwise.
117
 * 
118
 * Actual API docs: TBD.
119
 * 
120
 * \ingroup plugins
121
 * \ref plugins
122
 */
123

    
124
#include "plugin.h"
125

    
126
#include <jansson.h>
127
#include <sofia-sip/sdp.h>
128

    
129
#include "../debug.h"
130
#include "../apierror.h"
131
#include "../config.h"
132
#include "../mutex.h"
133
#include "../rtp.h"
134
#include "../rtcp.h"
135
#include "../record.h"
136
#include "../utils.h"
137
#include <sys/types.h>
138
#include <sys/socket.h>
139

    
140

    
141
/* Plugin information */
142
#define JANUS_VIDEOROOM_VERSION                        7
143
#define JANUS_VIDEOROOM_VERSION_STRING        "0.0.7"
144
#define JANUS_VIDEOROOM_DESCRIPTION                "This is a plugin implementing a videoconferencing SFU (Selective Forwarding Unit) for Janus, that is an audio/video router."
145
#define JANUS_VIDEOROOM_NAME                        "JANUS VideoRoom plugin"
146
#define JANUS_VIDEOROOM_AUTHOR                        "Meetecho s.r.l."
147
#define JANUS_VIDEOROOM_PACKAGE                        "janus.plugin.videoroom"
148

    
149
/* Plugin methods */
150
janus_plugin *create(void);
151
int janus_videoroom_init(janus_callbacks *callback, const char *config_path);
152
void janus_videoroom_destroy(void);
153
int janus_videoroom_get_api_compatibility(void);
154
int janus_videoroom_get_version(void);
155
const char *janus_videoroom_get_version_string(void);
156
const char *janus_videoroom_get_description(void);
157
const char *janus_videoroom_get_name(void);
158
const char *janus_videoroom_get_author(void);
159
const char *janus_videoroom_get_package(void);
160
void janus_videoroom_create_session(janus_plugin_session *handle, int *error);
161
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep);
162
void janus_videoroom_setup_media(janus_plugin_session *handle);
163
void janus_videoroom_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
164
void janus_videoroom_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
165
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len);
166
void janus_videoroom_slow_link(janus_plugin_session *handle, int uplink, int video);
167
void janus_videoroom_hangup_media(janus_plugin_session *handle);
168
void janus_videoroom_destroy_session(janus_plugin_session *handle, int *error);
169
json_t *janus_videoroom_query_session(janus_plugin_session *handle);
170

    
171
/* Plugin setup */
172
static janus_plugin janus_videoroom_plugin =
173
        JANUS_PLUGIN_INIT (
174
                .init = janus_videoroom_init,
175
                .destroy = janus_videoroom_destroy,
176

    
177
                .get_api_compatibility = janus_videoroom_get_api_compatibility,
178
                .get_version = janus_videoroom_get_version,
179
                .get_version_string = janus_videoroom_get_version_string,
180
                .get_description = janus_videoroom_get_description,
181
                .get_name = janus_videoroom_get_name,
182
                .get_author = janus_videoroom_get_author,
183
                .get_package = janus_videoroom_get_package,
184
                
185
                .create_session = janus_videoroom_create_session,
186
                .handle_message = janus_videoroom_handle_message,
187
                .setup_media = janus_videoroom_setup_media,
188
                .incoming_rtp = janus_videoroom_incoming_rtp,
189
                .incoming_rtcp = janus_videoroom_incoming_rtcp,
190
                .incoming_data = janus_videoroom_incoming_data,
191
                .slow_link = janus_videoroom_slow_link,
192
                .hangup_media = janus_videoroom_hangup_media,
193
                .destroy_session = janus_videoroom_destroy_session,
194
                .query_session = janus_videoroom_query_session,
195
        );
196

    
197
/* Plugin creator */
198
janus_plugin *create(void) {
199
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_VIDEOROOM_NAME);
200
        return &janus_videoroom_plugin;
201
}
202

    
203
/* Parameter validation */
204
static struct janus_json_parameter request_parameters[] = {
205
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
206
};
207
static struct janus_json_parameter adminkey_parameters[] = {
208
        {"admin_key", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
209
};
210
static struct janus_json_parameter create_parameters[] = {
211
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
212
        {"description", JSON_STRING, 0},
213
        {"is_private", JANUS_JSON_BOOL, 0},
214
        {"secret", JSON_STRING, 0},
215
        {"pin", JSON_STRING, 0},
216
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
217
        {"fir_freq", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
218
        {"publishers", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
219
        {"audiocodec", JSON_STRING, 0},
220
        {"videocodec", JSON_STRING, 0},
221
        {"record", JANUS_JSON_BOOL, 0},
222
        {"rec_dir", JSON_STRING, 0},
223
        {"permanent", JANUS_JSON_BOOL, 0}
224
};
225
static struct janus_json_parameter room_parameters[] = {
226
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
227
};
228
static struct janus_json_parameter destroy_parameters[] = {
229
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
230
        {"permanent", JANUS_JSON_BOOL, 0}
231
};
232
static struct janus_json_parameter join_parameters[] = {
233
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
234
        {"ptype", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
235
        {"audio", JANUS_JSON_BOOL, 0},
236
        {"video", JANUS_JSON_BOOL, 0},
237
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
238
        {"record", JANUS_JSON_BOOL, 0},
239
        {"filename", JSON_STRING, 0}
240
};
241
static struct janus_json_parameter publish_parameters[] = {
242
        {"audio", JANUS_JSON_BOOL, 0},
243
        {"video", JANUS_JSON_BOOL, 0},
244
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
245
        {"record", JANUS_JSON_BOOL, 0},
246
        {"filename", JSON_STRING, 0}
247
};
248
static struct janus_json_parameter rtp_forward_parameters[] = {
249
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
250
        {"publisher_id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
251
        {"video_port", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
252
        {"audio_port", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
253
        {"host", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
254
};
255
static struct janus_json_parameter stop_rtp_forward_parameters[] = {
256
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
257
        {"publisher_id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
258
        {"stream_id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
259
};
260
static struct janus_json_parameter publisher_parameters[] = {
261
        {"id", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
262
        {"display", JSON_STRING, 0}
263
};
264
static struct janus_json_parameter configure_parameters[] = {
265
        {"audio", JANUS_JSON_BOOL, 0},
266
        {"video", JANUS_JSON_BOOL, 0},
267
        {"data", JANUS_JSON_BOOL, 0}
268
};
269
static struct janus_json_parameter listener_parameters[] = {
270
        {"feed", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
271
        {"audio", JANUS_JSON_BOOL, 0},
272
        {"video", JANUS_JSON_BOOL, 0},
273
        {"data", JANUS_JSON_BOOL, 0}
274
};
275
static struct janus_json_parameter feeds_parameters[] = {
276
        {"feeds", JSON_ARRAY, JANUS_JSON_PARAM_NONEMPTY}
277
};
278

    
279
/* Static configuration instance */
280
static janus_config *config = NULL;
281
static const char *config_folder = NULL;
282
static janus_mutex config_mutex;
283

    
284
/* Useful stuff */
285
static volatile gint initialized = 0, stopping = 0;
286
static janus_callbacks *gateway = NULL;
287
static GThread *handler_thread;
288
static GThread *watchdog;
289
static su_home_t *sdphome = NULL;
290
static void *janus_videoroom_handler(void *data);
291
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data);
292
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data);
293

    
294
typedef enum janus_videoroom_p_type {
295
        janus_videoroom_p_type_none = 0,
296
        janus_videoroom_p_type_subscriber,                        /* Generic listener/subscriber */
297
        janus_videoroom_p_type_subscriber_muxed,        /* Multiplexed listener/subscriber */
298
        janus_videoroom_p_type_publisher,                        /* Participant/publisher */
299
} janus_videoroom_p_type;
300

    
301
typedef struct janus_videoroom_message {
302
        janus_plugin_session *handle;
303
        char *transaction;
304
        json_t *message;
305
        json_t *jsep;
306
} janus_videoroom_message;
307
static GAsyncQueue *messages = NULL;
308
static janus_videoroom_message exit_message;
309

    
310
static void janus_videoroom_message_free(janus_videoroom_message *msg) {
311
        if(!msg || msg == &exit_message)
312
                return;
313

    
314
        msg->handle = NULL;
315

    
316
        g_free(msg->transaction);
317
        msg->transaction = NULL;
318
        if(msg->message)
319
                json_decref(msg->message);
320
        msg->message = NULL;
321
        if(msg->jsep)
322
                json_decref(msg->jsep);
323
        msg->jsep = NULL;
324

    
325
        g_free(msg);
326
}
327

    
328
typedef enum janus_videoroom_audiocodec {
329
        JANUS_VIDEOROOM_OPUS,                /* Publishers will have to use OPUS         */
330
        JANUS_VIDEOROOM_ISAC_32K,        /* Publishers will have to use ISAC 32K */
331
        JANUS_VIDEOROOM_ISAC_16K,        /* Publishers will have to use ISAC 16K */
332
        JANUS_VIDEOROOM_PCMU,                /* Publishers will have to use PCMU 8K         */
333
        JANUS_VIDEOROOM_PCMA                /* Publishers will have to use PCMA 8K         */
334
} janus_videoroom_audiocodec;
335
static const char *janus_videoroom_audiocodec_name(janus_videoroom_audiocodec acodec) {
336
        switch(acodec) {
337
                case JANUS_VIDEOROOM_OPUS:
338
                        return "opus";
339
                case JANUS_VIDEOROOM_ISAC_32K:
340
                        return "isac32";
341
                case JANUS_VIDEOROOM_ISAC_16K:
342
                        return "isac16";
343
                case JANUS_VIDEOROOM_PCMU:
344
                        return "pcmu";
345
                case JANUS_VIDEOROOM_PCMA:
346
                        return "pcma";
347
                default:
348
                        /* Shouldn't happen */
349
                        return "opus";
350
        }
351
}
352

    
353
typedef enum janus_videoroom_videocodec {
354
        JANUS_VIDEOROOM_VP8,        /* Publishers will have to use VP8 */
355
        JANUS_VIDEOROOM_VP9,        /* Publishers will have to use VP9 */
356
        JANUS_VIDEOROOM_H264        /* Publishers will have to use H264 */
357
} janus_videoroom_videocodec;
358
static const char *janus_videoroom_videocodec_name(janus_videoroom_videocodec vcodec) {
359
        switch(vcodec) {
360
                case JANUS_VIDEOROOM_VP8:
361
                        return "vp8";
362
                case JANUS_VIDEOROOM_VP9:
363
                        return "vp9";
364
                case JANUS_VIDEOROOM_H264:
365
                        return "h264";
366
                default:
367
                        /* Shouldn't happen */
368
                        return "vp8";
369
        }
370
}
371

    
372
typedef struct janus_videoroom {
373
        guint64 room_id;                        /* Unique room ID */
374
        gchar *room_name;                        /* Room description */
375
        gchar *room_secret;                        /* Secret needed to manipulate (e.g., destroy) this room */
376
        gchar *room_pin;                        /* Password needed to join this room, if any */
377
        gboolean is_private;                /* Whether this room is 'private' (as in hidden) or not */
378
        int max_publishers;                        /* Maximum number of concurrent publishers */
379
        uint64_t bitrate;                        /* Global bitrate limit */
380
        uint16_t fir_freq;                        /* Regular FIR frequency (0=disabled) */
381
        janus_videoroom_audiocodec acodec;        /* Audio codec to force on publishers*/
382
        janus_videoroom_videocodec vcodec;        /* Video codec to force on publishers*/
383
        gboolean record;                        /* Whether the feeds from publishers in this room should be recorded */
384
        char *rec_dir;                                /* Where to save the recordings of this room, if enabled */
385
        gint64 destroyed;                        /* Value to flag the room for destruction, done lazily */
386
        GHashTable *participants;        /* Map of potential publishers (we get listeners from them) */
387
        janus_mutex participants_mutex;/* Mutex to protect room properties */
388
} janus_videoroom;
389
static GHashTable *rooms;
390
static janus_mutex rooms_mutex;
391
static GList *old_rooms;
392
static char *admin_key = NULL;
393
static void janus_videoroom_free(janus_videoroom *room);
394

    
395
typedef struct janus_videoroom_session {
396
        janus_plugin_session *handle;
397
        janus_videoroom_p_type participant_type;
398
        gpointer participant;
399
        gboolean started;
400
        gboolean stopping;
401
        volatile gint hangingup;
402
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
403
} janus_videoroom_session;
404
static GHashTable *sessions;
405
static GList *old_sessions;
406
static janus_mutex sessions_mutex;
407

    
408
/* a host whose ports gets streamed rtp packets of the corresponding type. */
409
typedef struct rtp_forwarder {
410
        int is_video;
411
        struct sockaddr_in serv_addr;
412
} rtp_forwarder;
413

    
414
typedef struct janus_videoroom_participant {
415
        janus_videoroom_session *session;
416
        janus_videoroom *room;        /* Room */
417
        guint64 user_id;        /* Unique ID in the room */
418
        gchar *display;        /* Display name (just for fun) */
419
        gchar *sdp;                        /* The SDP this publisher negotiated, if any */
420
        gboolean audio, video, data;                /* Whether audio, video and/or data is going to be sent by this publisher */
421
        guint32 audio_pt;                /* Audio payload type (Opus) */
422
        guint32 video_pt;                /* Video payload type (depends on room configuration) */
423
        guint32 audio_ssrc;                /* Audio SSRC of this publisher */
424
        guint32 video_ssrc;                /* Video SSRC of this publisher */
425
        gboolean audio_active;
426
        gboolean video_active;
427
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
428
        uint64_t bitrate;
429
        gint64 remb_startup;/* Incremental changes on REMB to reach the target at startup */
430
        gint64 remb_latest;        /* Time of latest sent REMB (to avoid flooding) */
431
        gint64 fir_latest;        /* Time of latest sent FIR (to avoid flooding) */
432
        gint fir_seq;                /* FIR sequence number */
433
        gboolean recording_active;        /* Whether this publisher has to be recorded or not */
434
        gchar *recording_base;        /* Base name for the recording (e.g., /path/to/filename, will generate /path/to/filename-audio.mjr and/or /path/to/filename-video.mjr */
435
        janus_recorder *arc;        /* The Janus recorder instance for this publisher's audio, if enabled */
436
        janus_recorder *vrc;        /* The Janus recorder instance for this publisher's video, if enabled */
437
        janus_mutex rec_mutex;        /* Mutex to protect the recorders from race conditions */
438
        GSList *listeners;
439
        janus_mutex listeners_mutex;
440
        GHashTable *rtp_forwarders;
441
        janus_mutex rtp_forwarders_mutex;
442
        int udp_sock; /* The udp socket on which to forward rtp packets */
443
} janus_videoroom_participant;
444
static void janus_videoroom_participant_free(janus_videoroom_participant *p);
445
static void janus_rtp_forwarder_free_helper(gpointer data);
446
static guint32 janus_rtp_forwarder_add_helper(janus_videoroom_participant *p, const gchar* host, int port, int is_video);
447
typedef struct janus_videoroom_listener_context {
448
        /* Needed to fix seq and ts in case of publisher switching */
449
        uint32_t a_last_ssrc, a_last_ts, a_base_ts, a_base_ts_prev,
450
                        v_last_ssrc, v_last_ts, v_base_ts, v_base_ts_prev;
451
        uint16_t a_last_seq, a_base_seq, a_base_seq_prev,
452
                        v_last_seq, v_base_seq, v_base_seq_prev;
453
} janus_videoroom_listener_context;
454

    
455
typedef struct janus_videoroom_listener {
456
        janus_videoroom_session *session;
457
        janus_videoroom *room;        /* Room */
458
        janus_videoroom_participant *feed;        /* Participant this listener is subscribed to */
459
        janus_videoroom_listener_context context;        /* Needed in case there are publisher switches on this listener */
460
        gboolean audio, video, data;                /* Whether audio, video and/or data must be sent to this publisher */
461
        struct janus_videoroom_listener_muxed *parent;        /* Overall subscriber, if this is a sub-listener in a Multiplexed one */
462
        gboolean paused;
463
} janus_videoroom_listener;
464
static void janus_videoroom_listener_free(janus_videoroom_listener *l);
465

    
466
typedef struct janus_videoroom_listener_muxed {
467
        janus_videoroom_session *session;
468
        janus_videoroom *room;        /* Room */
469
        GSList *listeners;        /* List of listeners (as a Multiplexed listener can be subscribed to more publishers at the same time) */
470
        janus_mutex listeners_mutex;
471
} janus_videoroom_listener_muxed;
472
static void janus_videoroom_muxed_listener_free(janus_videoroom_listener_muxed *l);
473

    
474
typedef struct janus_videoroom_rtp_relay_packet {
475
        rtp_header *data;
476
        gint length;
477
        gint is_video;
478
        uint32_t timestamp;
479
        uint16_t seq_number;
480
} janus_videoroom_rtp_relay_packet;
481

    
482
/* SDP offer/answer templates */
483
#define OPUS_PT        111
484
#define ISAC32_PT        104
485
#define ISAC16_PT        103
486
#define PCMU_PT        0
487
#define PCMA_PT        8
488
#define VP8_PT                100
489
#define VP9_PT                101
490
#define H264_PT        107
491
#define sdp_template \
492
                "v=0\r\n" \
493
                "o=- %"SCNu64" %"SCNu64" IN IP4 127.0.0.1\r\n"        /* We need current time here */ \
494
                "s=%s\r\n"                                                        /* Video room name */ \
495
                "t=0 0\r\n" \
496
                "%s%s%s"                                /* Audio, video and/or data channel m-lines */
497
#define sdp_a_template_opus \
498
                "m=audio 1 RTP/SAVPF %d\r\n"                /* Opus payload type */ \
499
                "c=IN IP4 1.1.1.1\r\n" \
500
                "a=%s\r\n"                                                        /* Media direction */ \
501
                "a=rtpmap:%d opus/48000/2\r\n"                /* Opus payload type */
502
#define sdp_a_template_isac32 \
503
                "m=audio 1 RTP/SAVPF %d\r\n"                /* ISAC32_PT payload type */ \
504
                "c=IN IP4 1.1.1.1\r\n" \
505
                "a=%s\r\n"                                                        /* Media direction */ \
506
                "a=rtpmap:%d ISAC/32000\r\n"                /* ISAC32_PT payload type */
507
#define sdp_a_template_isac16 \
508
                "m=audio 1 RTP/SAVPF %d\r\n"                /* ISAC16_PT payload type */ \
509
                "c=IN IP4 1.1.1.1\r\n" \
510
                "a=%s\r\n"                                                        /* Media direction */ \
511
                "a=rtpmap:%d ISAC/16000\r\n"                /* ISAC16_PT payload type */
512
#define sdp_a_template_pcmu \
513
                "m=audio 1 RTP/SAVPF %d\r\n"                /* PCMU_PT payload type */ \
514
                "c=IN IP4 1.1.1.1\r\n" \
515
                "a=%s\r\n"                                                        /* Media direction */ \
516
                "a=rtpmap:%d PCMU/8000\r\n"                    /* PCMU_PT payload type */
517
#define sdp_a_template_pcma \
518
                "m=audio 1 RTP/SAVPF %d\r\n"                /* PCMA_PT payload type */ \
519
                "c=IN IP4 1.1.1.1\r\n" \
520
                "a=%s\r\n"                                                        /* Media direction */ \
521
                "a=rtpmap:%d PCMA/8000\r\n"                    /* PCMA_PT payload type */
522
#define sdp_v_template_vp8 \
523
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP8 payload type */ \
524
                "c=IN IP4 1.1.1.1\r\n" \
525
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
526
                "a=%s\r\n"                                                        /* Media direction */ \
527
                "a=rtpmap:%d VP8/90000\r\n"                        /* VP8 payload type */ \
528
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP8 payload type */ \
529
                "a=rtcp-fb:%d nack\r\n"                                /* VP8 payload type */ \
530
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP8 payload type */ \
531
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP8 payload type */
532
#define sdp_v_template_vp9 \
533
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP9 payload type */ \
534
                "c=IN IP4 1.1.1.1\r\n" \
535
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
536
                "a=%s\r\n"                                                        /* Media direction */ \
537
                "a=rtpmap:%d VP9/90000\r\n"                        /* VP9 payload type */ \
538
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP9 payload type */ \
539
                "a=rtcp-fb:%d nack\r\n"                                /* VP9 payload type */ \
540
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP9 payload type */ \
541
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP9 payload type */
542
#define sdp_v_template_h264 \
543
                "m=video 1 RTP/SAVPF %d\r\n"                /* H264 payload type */ \
544
                "c=IN IP4 1.1.1.1\r\n" \
545
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
546
                "a=%s\r\n"                                                        /* Media direction */ \
547
                "a=rtpmap:%d H264/90000\r\n"                /* H264 payload type */ \
548
                "a=fmtp:%d profile-level-id=42e01f;packetization-mode=1\r\n" \
549
                "a=rtcp-fb:%d ccm fir\r\n"                        /* H264 payload type */ \
550
                "a=rtcp-fb:%d nack\r\n"                                /* H264 payload type */ \
551
                "a=rtcp-fb:%d nack pli\r\n"                        /* H264 payload type */ \
552
                "a=rtcp-fb:%d goog-remb\r\n"                /* H264 payload type */
553
#ifdef HAVE_SCTP
554
#define sdp_d_template \
555
                "m=application 1 DTLS/SCTP 5000\r\n" \
556
                "c=IN IP4 1.1.1.1\r\n" \
557
                "a=sctpmap:5000 webrtc-datachannel 16\r\n"
558
#else
559
#define sdp_d_template \
560
                "m=application 0 DTLS/SCTP 0\r\n" \
561
                "c=IN IP4 1.1.1.1\r\n"
562
#endif
563

    
564

    
565
/* Error codes */
566
#define JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR                499
567
#define JANUS_VIDEOROOM_ERROR_NO_MESSAGE                421
568
#define JANUS_VIDEOROOM_ERROR_INVALID_JSON                422
569
#define JANUS_VIDEOROOM_ERROR_INVALID_REQUEST        423
570
#define JANUS_VIDEOROOM_ERROR_JOIN_FIRST                424
571
#define JANUS_VIDEOROOM_ERROR_ALREADY_JOINED        425
572
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM                426
573
#define JANUS_VIDEOROOM_ERROR_ROOM_EXISTS                427
574
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED                428
575
#define JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT        429
576
#define JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT        430
577
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE        431
578
#define JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL        432
579
#define JANUS_VIDEOROOM_ERROR_UNAUTHORIZED                433
580
#define JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED        434
581
#define JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED                435
582
#define JANUS_VIDEOROOM_ERROR_ID_EXISTS                        436
583
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP                437
584

    
585

    
586
/* Multiplexing helpers */
587
int janus_videoroom_muxed_subscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
588
int janus_videoroom_muxed_unsubscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
589
int janus_videoroom_muxed_offer(janus_videoroom_listener_muxed *muxed_listener, char *transaction, json_t *event);
590

    
591
static guint32 janus_rtp_forwarder_add_helper(janus_videoroom_participant *p, const gchar* host, int port, int is_video) {
592
        if(!p || !host) {
593
                return 0;
594
        }
595
        rtp_forwarder *forward = g_malloc0(sizeof(rtp_forwarder));
596
        forward->is_video = is_video;
597
        forward->serv_addr.sin_family = AF_INET;
598
        inet_pton(AF_INET, host, &(forward->serv_addr.sin_addr));
599
        forward->serv_addr.sin_port = htons(port);
600
        janus_mutex_lock(&p->rtp_forwarders_mutex);
601
        guint32 stream_id = janus_random_uint32();
602
        while(g_hash_table_lookup(p->rtp_forwarders, GUINT_TO_POINTER(stream_id)) != NULL) {
603
                stream_id = janus_random_uint32();
604
        }
605
        g_hash_table_insert(p->rtp_forwarders, GUINT_TO_POINTER(stream_id), forward);
606
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
607
        JANUS_LOG(LOG_VERB, "Added %s rtp_forward to participant %"SCNu64" host: %s:%d stream_id: %"SCNu32"\n", is_video ? "video":"audio", p->user_id, host, port, stream_id);
608
        return stream_id;
609
}
610

    
611

    
612
/* Convenience function for freeing a session */
613
static void session_free(gpointer data) {
614
        if(data) {
615
                janus_videoroom_session* session = (janus_videoroom_session*)data;
616
                switch(session->participant_type) {
617
                case janus_videoroom_p_type_publisher: 
618
                        janus_videoroom_participant_free(session->participant);
619
                        break;   
620
                case janus_videoroom_p_type_subscriber:
621
                        janus_videoroom_listener_free(session->participant);
622
                        break;
623
                case janus_videoroom_p_type_subscriber_muxed:
624
                        janus_videoroom_muxed_listener_free(session->participant);
625
                        break;
626
                default:
627
                        break;
628
                }
629
                session->handle = NULL;
630
                g_free(session);
631
                session = NULL;
632
        }
633
}
634

    
635
static void janus_rtp_forwarder_free_helper(gpointer data) {
636
        if(data) {
637
                rtp_forwarder* forward = (rtp_forwarder*)data;
638
                if(forward) {
639
                        g_free(forward);
640
                        forward = NULL;
641
                }
642
        }
643
}
644

    
645
/* Convenience wrapper function for session_free that corresponds to GHRFunc() format for hash table cleanup */
646
static gboolean session_hash_table_remove(gpointer key, gpointer value, gpointer not_used) {
647
        if(value) {
648
                session_free(value);
649
        }
650
        return TRUE;
651
}
652

    
653
/* VideoRoom watchdog/garbage collector (sort of) */
654
void *janus_videoroom_watchdog(void *data);
655
void *janus_videoroom_watchdog(void *data) {
656
        JANUS_LOG(LOG_INFO, "VideoRoom watchdog started\n");
657
        gint64 now = 0, room_now = 0;
658
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
659
                janus_mutex_lock(&sessions_mutex);
660
                /* Iterate on all the participants/listeners and check if we need to remove any of them */
661
                now = janus_get_monotonic_time();
662
                if(old_sessions != NULL) {
663
                        GList *sl = old_sessions;
664
                        JANUS_LOG(LOG_HUGE, "Checking %d old VideoRoom sessions...\n", g_list_length(old_sessions));
665
                        while(sl) {
666
                                janus_videoroom_session *session = (janus_videoroom_session *)sl->data;
667
                                /* If we are stopping, their is no point to continue to iterate */
668
                                if(!initialized || stopping) {
669
                                        break;
670
                                }
671
                                if(!session) {
672
                                        sl = sl->next;
673
                                        continue;
674
                                }
675
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
676
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
677
                                        JANUS_LOG(LOG_VERB, "Freeing old VideoRoom session\n");
678
                                        GList *rm = sl->next;
679
                                        old_sessions = g_list_delete_link(old_sessions, sl);
680
                                        sl = rm;
681
                                        g_hash_table_steal(sessions, session->handle);
682
                                        session_free(session);
683
                                        continue;
684
                                }
685
                                sl = sl->next;
686
                        }
687
                }
688
                janus_mutex_unlock(&sessions_mutex);
689
                janus_mutex_lock(&rooms_mutex);
690
                if(old_rooms != NULL) {
691
                        GList *rl = old_rooms;
692
                        room_now = janus_get_monotonic_time();
693
                        while(rl) {
694
                                janus_videoroom* room = (janus_videoroom*)rl->data;
695
                                if(!initialized || stopping){
696
                                        break;
697
                                }
698
                                if(!room) {
699
                                        rl = rl->next;
700
                                        continue;
701
                                }
702
                                if(room_now - room->destroyed >= 5*G_USEC_PER_SEC) {
703
                                        GList *rm = rl->next;
704
                                        old_rooms = g_list_delete_link(old_rooms, rl);
705
                                        rl = rm;
706
                                        g_hash_table_remove(rooms, &room->room_id);
707
                                        continue;
708
                                }
709
                                rl = rl->next;
710
                        }
711
                }
712
                janus_mutex_unlock(&rooms_mutex);
713
                g_usleep(500000);
714
        }
715
        JANUS_LOG(LOG_INFO, "VideoRoom watchdog stopped\n");
716
        return NULL;
717
}
718

    
719

    
720
/* Plugin implementation */
721
int janus_videoroom_init(janus_callbacks *callback, const char *config_path) {
722
        if(g_atomic_int_get(&stopping)) {
723
                /* Still stopping from before */
724
                return -1;
725
        }
726
        if(callback == NULL || config_path == NULL) {
727
                /* Invalid arguments */
728
                return -1;
729
        }
730
        sdphome = su_home_new(sizeof(su_home_t));
731
        if(su_home_init(sdphome) < 0) {
732
                JANUS_LOG(LOG_FATAL, "Ops, error setting up sofia-sdp?\n");
733
                return -1;
734
        }
735

    
736
        /* Read configuration */
737
        char filename[255];
738
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_VIDEOROOM_PACKAGE);
739
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
740
        config = janus_config_parse(filename);
741
        config_folder = config_path;
742
        if(config != NULL)
743
                janus_config_print(config);
744
        janus_mutex_init(&config_mutex);
745

    
746
        rooms = g_hash_table_new_full(g_int64_hash, g_int64_equal,
747
                (GDestroyNotify)g_free, (GDestroyNotify) janus_videoroom_free);
748
        janus_mutex_init(&rooms_mutex);
749
        sessions = g_hash_table_new(NULL, NULL);
750
        janus_mutex_init(&sessions_mutex);
751

    
752
        messages = g_async_queue_new_full((GDestroyNotify) janus_videoroom_message_free);
753

    
754
        /* This is the callback we'll need to invoke to contact the gateway */
755
        gateway = callback;
756

    
757
        /* Parse configuration to populate the rooms list */
758
        if(config != NULL) {
759
                /* Any admin key to limit who can "create"? */
760
                janus_config_item *key = janus_config_get_item_drilldown(config, "general", "admin_key");
761
                if(key != NULL && key->value != NULL)
762
                        admin_key = g_strdup(key->value);
763
                /* Iterate on all rooms */
764
                GList *cl = janus_config_get_categories(config);
765
                while(cl != NULL) {
766
                        janus_config_category *cat = (janus_config_category *)cl->data;
767
                        if(cat->name == NULL || !strcasecmp(cat->name, "general")) {
768
                                cl = cl->next;
769
                                continue;
770
                        }
771
                        JANUS_LOG(LOG_VERB, "Adding video room '%s'\n", cat->name);
772
                        janus_config_item *desc = janus_config_get_item(cat, "description");
773
                        janus_config_item *priv = janus_config_get_item(cat, "is_private");
774
                        janus_config_item *secret = janus_config_get_item(cat, "secret");
775
                        janus_config_item *pin = janus_config_get_item(cat, "pin");
776
                        janus_config_item *bitrate = janus_config_get_item(cat, "bitrate");
777
                        janus_config_item *maxp = janus_config_get_item(cat, "publishers");
778
                        janus_config_item *firfreq = janus_config_get_item(cat, "fir_freq");
779
                        janus_config_item *audiocodec = janus_config_get_item(cat, "audiocodec");
780
                        janus_config_item *videocodec = janus_config_get_item(cat, "videocodec");
781
                        janus_config_item *record = janus_config_get_item(cat, "record");
782
                        janus_config_item *rec_dir = janus_config_get_item(cat, "rec_dir");
783
                        /* Create the video room */
784
                        janus_videoroom *videoroom = g_malloc0(sizeof(janus_videoroom));
785
                        videoroom->room_id = atol(cat->name);
786
                        char *description = NULL;
787
                        if(desc != NULL && desc->value != NULL && strlen(desc->value) > 0)
788
                                description = g_strdup(desc->value);
789
                        else
790
                                description = g_strdup(cat->name);
791
                        videoroom->room_name = description;
792
                        if(secret != NULL && secret->value != NULL) {
793
                                videoroom->room_secret = g_strdup(secret->value);
794
                        }
795
                        if(pin != NULL && pin->value != NULL) {
796
                                videoroom->room_pin = g_strdup(pin->value);
797
                        }
798
                        videoroom->is_private = priv && priv->value && janus_is_true(priv->value);
799
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
800
                        if(maxp != NULL && maxp->value != NULL)
801
                                videoroom->max_publishers = atol(maxp->value);
802
                        if(videoroom->max_publishers < 0)
803
                                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
804
                        videoroom->bitrate = 0;
805
                        if(bitrate != NULL && bitrate->value != NULL)
806
                                videoroom->bitrate = atol(bitrate->value);
807
                        if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
808
                                videoroom->bitrate = 64000;        /* Don't go below 64k */
809
                        videoroom->fir_freq = 0;
810
                        if(firfreq != NULL && firfreq->value != NULL)
811
                                videoroom->fir_freq = atol(firfreq->value);
812
                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
813
                        if(audiocodec && audiocodec->value) {
814
                                if(!strcasecmp(audiocodec->value, "opus"))
815
                                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
816
                                else if(!strcasecmp(audiocodec->value, "isac32"))
817
                                        videoroom->acodec = JANUS_VIDEOROOM_ISAC_32K;
818
                                else if(!strcasecmp(audiocodec->value, "isac16"))
819
                                        videoroom->acodec = JANUS_VIDEOROOM_ISAC_16K;
820
                                else if(!strcasecmp(audiocodec->value, "pcmu"))
821
                                        videoroom->acodec = JANUS_VIDEOROOM_PCMU;
822
                                else if(!strcasecmp(audiocodec->value, "pcma"))
823
                                        videoroom->acodec = JANUS_VIDEOROOM_PCMA;
824
                                else {
825
                                        JANUS_LOG(LOG_WARN, "Unsupported audio codec '%s', falling back to OPUS\n", audiocodec->value);
826
                                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
827
                                }
828
                        }
829
                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
830
                        if(videocodec && videocodec->value) {
831
                                if(!strcasecmp(videocodec->value, "vp8"))
832
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
833
                                else if(!strcasecmp(videocodec->value, "vp9"))
834
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP9;
835
                                else if(!strcasecmp(videocodec->value, "h264"))
836
                                        videoroom->vcodec = JANUS_VIDEOROOM_H264;
837
                                else {
838
                                        JANUS_LOG(LOG_WARN, "Unsupported video codec '%s', falling back to VP8\n", videocodec->value);
839
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
840
                                }
841
                        }
842
                        if(record && record->value) {
843
                                videoroom->record = janus_is_true(record->value);
844
                        }
845
                        if(rec_dir && rec_dir->value) {
846
                                videoroom->rec_dir = g_strdup(rec_dir->value);
847
                        }
848
                        videoroom->destroyed = 0;
849
                        janus_mutex_init(&videoroom->participants_mutex);
850
                        videoroom->participants = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
851
                        janus_mutex_lock(&rooms_mutex);
852
                        g_hash_table_insert(rooms, janus_uint64_dup(videoroom->room_id), videoroom);
853
                        janus_mutex_unlock(&rooms_mutex);
854
                        JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, %s/%s codecs, secret: %s, pin: %s)\n",
855
                                videoroom->room_id, videoroom->room_name,
856
                                videoroom->is_private ? "private" : "public",
857
                                janus_videoroom_audiocodec_name(videoroom->acodec),
858
                                janus_videoroom_videocodec_name(videoroom->vcodec),
859
                                videoroom->room_secret ? videoroom->room_secret : "no secret",
860
                                videoroom->room_pin ? videoroom->room_pin : "no pin");
861
                        if(videoroom->record) {
862
                                JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
863
                        }
864
                        cl = cl->next;
865
                }
866
                /* Done: we keep the configuration file open in case we get a "create" or "destroy" with permanent=true */
867
        }
868

    
869
        /* Show available rooms */
870
        janus_mutex_lock(&rooms_mutex);
871
        GHashTableIter iter;
872
        gpointer value;
873
        g_hash_table_iter_init(&iter, rooms);
874
        while (g_hash_table_iter_next(&iter, NULL, &value)) {
875
                janus_videoroom *vr = value;
876
                JANUS_LOG(LOG_VERB, "  ::: [%"SCNu64"][%s] %"SCNu64", max %d publishers, FIR frequency of %d seconds, %s audio codec, %s video codec\n",
877
                        vr->room_id, vr->room_name, vr->bitrate, vr->max_publishers, vr->fir_freq,
878
                        janus_videoroom_audiocodec_name(vr->acodec), janus_videoroom_videocodec_name(vr->vcodec));
879
        }
880
        janus_mutex_unlock(&rooms_mutex);
881

    
882
        g_atomic_int_set(&initialized, 1);
883

    
884
        GError *error = NULL;
885
        /* Start the sessions watchdog */
886
        watchdog = g_thread_try_new("videoroom watchdog", &janus_videoroom_watchdog, NULL, &error);
887
        if(error != NULL) {
888
                g_atomic_int_set(&initialized, 0);
889
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom watchdog thread...\n", error->code, error->message ? error->message : "??");
890
                janus_config_destroy(config);
891
                return -1;
892
        }
893
        /* Launch the thread that will handle incoming messages */
894
        handler_thread = g_thread_try_new("videoroom handler", janus_videoroom_handler, NULL, &error);
895
        if(error != NULL) {
896
                g_atomic_int_set(&initialized, 0);
897
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom handler thread...\n", error->code, error->message ? error->message : "??");
898
                janus_config_destroy(config);
899
                return -1;
900
        }
901
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_VIDEOROOM_NAME);
902
        return 0;
903
}
904

    
905
void janus_videoroom_destroy(void) {
906
        if(!g_atomic_int_get(&initialized))
907
                return;
908
        g_atomic_int_set(&stopping, 1);
909

    
910
        g_async_queue_push(messages, &exit_message);
911
        if(handler_thread != NULL) {
912
                g_thread_join(handler_thread);
913
                handler_thread = NULL;
914
        }
915
        if(watchdog != NULL) {
916
                g_thread_join(watchdog);
917
                watchdog = NULL;
918
        }
919
        su_home_deinit(sdphome);
920
        su_home_unref(sdphome);
921
        sdphome = NULL;
922

    
923
        /* FIXME We should destroy the sessions cleanly */
924
        janus_mutex_lock(&sessions_mutex);
925
        g_hash_table_foreach_remove(sessions, (GHRFunc)session_hash_table_remove, NULL);
926
        g_hash_table_destroy(sessions);
927
        sessions = NULL;
928
        janus_mutex_unlock(&sessions_mutex);
929

    
930
        janus_mutex_lock(&rooms_mutex);
931

    
932
        g_hash_table_destroy(rooms);
933
        rooms = NULL;
934
        janus_mutex_unlock(&rooms_mutex);
935
        janus_mutex_destroy(&rooms_mutex);
936

    
937
        g_async_queue_unref(messages);
938
        messages = NULL;
939

    
940
        janus_config_destroy(config);
941
        g_free(admin_key);
942

    
943
        g_atomic_int_set(&initialized, 0);
944
        g_atomic_int_set(&stopping, 0);
945
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOROOM_NAME);
946
}
947

    
948
int janus_videoroom_get_api_compatibility(void) {
949
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
950
        return JANUS_PLUGIN_API_VERSION;
951
}
952

    
953
int janus_videoroom_get_version(void) {
954
        return JANUS_VIDEOROOM_VERSION;
955
}
956

    
957
const char *janus_videoroom_get_version_string(void) {
958
        return JANUS_VIDEOROOM_VERSION_STRING;
959
}
960

    
961
const char *janus_videoroom_get_description(void) {
962
        return JANUS_VIDEOROOM_DESCRIPTION;
963
}
964

    
965
const char *janus_videoroom_get_name(void) {
966
        return JANUS_VIDEOROOM_NAME;
967
}
968

    
969
const char *janus_videoroom_get_author(void) {
970
        return JANUS_VIDEOROOM_AUTHOR;
971
}
972

    
973
const char *janus_videoroom_get_package(void) {
974
        return JANUS_VIDEOROOM_PACKAGE;
975
}
976

    
977
void janus_videoroom_create_session(janus_plugin_session *handle, int *error) {
978
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
979
                *error = -1;
980
                return;
981
        }        
982
        janus_videoroom_session *session = (janus_videoroom_session *)g_malloc0(sizeof(janus_videoroom_session));
983
        session->handle = handle;
984
        session->participant_type = janus_videoroom_p_type_none;
985
        session->participant = NULL;
986
        session->destroyed = 0;
987
        g_atomic_int_set(&session->hangingup, 0);
988
        handle->plugin_handle = session;
989
        janus_mutex_lock(&sessions_mutex);
990
        g_hash_table_insert(sessions, handle, session);
991
        janus_mutex_unlock(&sessions_mutex);
992

    
993
        return;
994
}
995

    
996
static void janus_videoroom_notify_participants(janus_videoroom_participant *participant, json_t *msg) {
997
        /* participant->room->participants_mutex has to be locked. */
998
        GHashTableIter iter;
999
        gpointer value;
1000
        g_hash_table_iter_init(&iter, participant->room->participants);
1001
        while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1002
                janus_videoroom_participant *p = value;
1003
                if(p && p->session && p != participant) {
1004
                        JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1005
                        int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, msg, NULL);
1006
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1007
                }
1008
        }
1009
}
1010

    
1011
static void janus_videoroom_leave_or_unpublish(janus_videoroom_participant *participant, gboolean is_leaving) {
1012
        json_t *event = json_object();
1013
        json_object_set_new(event, "videoroom", json_string("event"));
1014
        json_object_set_new(event, "room", json_integer(participant->room->room_id));
1015
        json_object_set_new(event, is_leaving ? "leaving" : "unpublished", json_integer(participant->user_id));
1016
        /* we need to check if the room still exists, may have been destroyed already */
1017
        if(participant->room) {
1018
                if(!participant->room->destroyed) {
1019
                        janus_mutex_lock(&participant->room->participants_mutex);
1020
                        janus_videoroom_notify_participants(participant, event);
1021
                        if(is_leaving) {
1022
                                g_hash_table_remove(participant->room->participants, &participant->user_id);
1023
                        }
1024
                        janus_mutex_unlock(&participant->room->participants_mutex);
1025
                }
1026
        }
1027
        json_decref(event);
1028
}
1029

    
1030
void janus_videoroom_destroy_session(janus_plugin_session *handle, int *error) {
1031
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1032
                *error = -1;
1033
                return;
1034
        }        
1035
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle; 
1036
        if(!session) {
1037
                JANUS_LOG(LOG_ERR, "No VideoRoom session associated with this handle...\n");
1038
                *error = -2;
1039
                return;
1040
        }
1041
        if(session->destroyed) {
1042
                JANUS_LOG(LOG_WARN, "VideoRoom session already marked as destroyed...\n");
1043
                return;
1044
        }
1045
        JANUS_LOG(LOG_VERB, "Removing VideoRoom session...\n");
1046
        /* Cleaning up and removing the session is done in a lazy way */
1047
        janus_mutex_lock(&sessions_mutex);
1048
        if(!session->destroyed) {
1049
                /* Any related WebRTC PeerConnection is not available anymore either */
1050
                janus_videoroom_hangup_media(handle);
1051
                session->destroyed = janus_get_monotonic_time();
1052
                old_sessions = g_list_append(old_sessions, session);
1053
                if(session->participant_type == janus_videoroom_p_type_publisher) {
1054
                        /* Get rid of publisher */
1055
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1056
                        participant->audio = FALSE;
1057
                        participant->video = FALSE;
1058
                        participant->data = FALSE;
1059
                        participant->audio_active = FALSE;
1060
                        participant->video_active = FALSE;
1061
                        participant->recording_active = FALSE;
1062
                        if(participant->recording_base)
1063
                                g_free(participant->recording_base);
1064
                        participant->recording_base = NULL;
1065
                        janus_videoroom_leave_or_unpublish(participant, TRUE);
1066
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1067
                        /* Detaching this listener from its publisher is already done by hangup_media */
1068
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1069
                        /* Detaching this listener from its publishers is already done by hangup_media */
1070
                }
1071
        }
1072
        janus_mutex_unlock(&sessions_mutex);
1073

    
1074
        return;
1075
}
1076

    
1077
json_t *janus_videoroom_query_session(janus_plugin_session *handle) {
1078
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1079
                return NULL;
1080
        }        
1081
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1082
        if(!session) {
1083
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1084
                return NULL;
1085
        }
1086
        /* Show the participant/room info, if any */
1087
        json_t *info = json_object();
1088
        if(session->participant) {
1089
                if(session->participant_type == janus_videoroom_p_type_none) {
1090
                        json_object_set_new(info, "type", json_string("none"));
1091
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
1092
                        json_object_set_new(info, "type", json_string("publisher"));
1093
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1094
                        if(participant) {
1095
                                janus_videoroom *room = participant->room; 
1096
                                json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
1097
                                json_object_set_new(info, "id", json_integer(participant->user_id));
1098
                                if(participant->display)
1099
                                        json_object_set_new(info, "display", json_string(participant->display));
1100
                                if(participant->listeners)
1101
                                        json_object_set_new(info, "viewers", json_integer(g_slist_length(participant->listeners)));
1102
                                json_t *media = json_object();
1103
                                json_object_set_new(media, "audio", json_integer(participant->audio));
1104
                                json_object_set_new(media, "video", json_integer(participant->video));
1105
                                json_object_set_new(media, "data", json_integer(participant->data));
1106
                                json_object_set_new(info, "media", media);
1107
                                json_object_set_new(info, "bitrate", json_integer(participant->bitrate));
1108
                                if(participant->arc || participant->vrc) {
1109
                                        json_t *recording = json_object();
1110
                                        if(participant->arc && participant->arc->filename)
1111
                                                json_object_set_new(recording, "audio", json_string(participant->arc->filename));
1112
                                        if(participant->vrc && participant->vrc->filename)
1113
                                                json_object_set_new(recording, "video", json_string(participant->vrc->filename));
1114
                                        json_object_set_new(info, "recording", recording);
1115
                                }
1116
                        }
1117
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1118
                        json_object_set_new(info, "type", json_string("listener"));
1119
                        janus_videoroom_listener *participant = (janus_videoroom_listener *)session->participant;
1120
                        if(participant) {
1121
                                janus_videoroom_participant *feed = (janus_videoroom_participant *)participant->feed;
1122
                                if(feed) {
1123
                                        janus_videoroom *room = feed->room; 
1124
                                        json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
1125
                                        json_object_set_new(info, "feed_id", json_integer(feed->user_id));
1126
                                        if(feed->display)
1127
                                                json_object_set_new(info, "feed_display", json_string(feed->display));
1128
                                }
1129
                                json_t *media = json_object();
1130
                                json_object_set_new(media, "audio", json_integer(participant->audio));
1131
                                json_object_set_new(media, "video", json_integer(participant->video));
1132
                                json_object_set_new(media, "data", json_integer(participant->data));
1133
                                json_object_set_new(info, "media", media);
1134
                        }
1135
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1136
                        json_object_set_new(info, "type", json_string("muxed-listener"));
1137
                        /* TODO */
1138
                }
1139
        }
1140
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
1141
        return info;
1142
}
1143

    
1144
static int janus_videoroom_access_room(json_t *root, gboolean check_secret, gboolean check_pin, janus_videoroom **videoroom, char *error_cause, int error_cause_size) {
1145
        /* rooms_mutex has to be locked */
1146
        int error_code = 0;
1147
        json_t *room = json_object_get(root, "room");
1148
        guint64 room_id = json_integer_value(room);
1149
        *videoroom = g_hash_table_lookup(rooms, &room_id);
1150
        if(*videoroom == NULL) {
1151
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1152
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1153
                if(error_cause)
1154
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1155
                return error_code;
1156
        }
1157
        if((*videoroom)->destroyed) {
1158
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1159
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1160
                if(error_cause)
1161
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1162
                return error_code;
1163
        }
1164
        if(check_secret) {
1165
                char error_cause2[100];
1166
                JANUS_CHECK_SECRET((*videoroom)->room_secret, root, "secret", error_code, error_cause2,
1167
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1168
                if(error_code != 0) {
1169
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1170
                        return error_code;
1171
                }
1172
        }
1173
        if(check_pin) {
1174
                char error_cause2[100];
1175
                JANUS_CHECK_SECRET((*videoroom)->room_pin, root, "pin", error_code, error_cause2,
1176
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1177
                if(error_code != 0) {
1178
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1179
                        return error_code;
1180
                }
1181
        }
1182
        return 0;
1183
}
1184

    
1185
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1186
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1187
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1188
        
1189
        /* Pre-parse the message */
1190
        int error_code = 0;
1191
        char error_cause[512];
1192
        json_t *root = message;
1193
        json_t *response = NULL;
1194

    
1195
        if(message == NULL) {
1196
                JANUS_LOG(LOG_ERR, "No message??\n");
1197
                error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
1198
                g_snprintf(error_cause, 512, "%s", "No message??");
1199
                goto plugin_response;
1200
        }
1201

    
1202
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1203
        if(!session) {
1204
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1205
                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1206
                g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
1207
                goto plugin_response;
1208
        }
1209
        if(session->destroyed) {
1210
                JANUS_LOG(LOG_ERR, "Session has already been marked as destroyed...\n");
1211
                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1212
                g_snprintf(error_cause, 512, "%s", "Session has already been marked as destroyed...");
1213
                goto plugin_response;
1214
        }
1215
        if(!json_is_object(root)) {
1216
                JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1217
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_JSON;
1218
                g_snprintf(error_cause, 512, "JSON error: not an object");
1219
                goto plugin_response;
1220
        }
1221
        /* Get the request first */
1222
        JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1223
                error_code, error_cause, TRUE,
1224
                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1225
        if(error_code != 0)
1226
                goto plugin_response;
1227
        json_t *request = json_object_get(root, "request");
1228
        /* Some requests ('create', 'destroy', 'exists', 'list') can be handled synchronously */
1229
        const char *request_text = json_string_value(request);
1230
        if(!strcasecmp(request_text, "create")) {
1231
                /* Create a new videoroom */
1232
                JANUS_LOG(LOG_VERB, "Creating a new videoroom\n");
1233
                JANUS_VALIDATE_JSON_OBJECT(root, create_parameters,
1234
                        error_code, error_cause, TRUE,
1235
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1236
                if(error_code != 0)
1237
                        goto plugin_response;
1238
                if(admin_key != NULL) {
1239
                        /* An admin key was specified: make sure it was provided, and that it's valid */
1240
                        JANUS_VALIDATE_JSON_OBJECT(root, adminkey_parameters,
1241
                                error_code, error_cause, TRUE,
1242
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1243
                        if(error_code != 0)
1244
                                goto plugin_response;
1245
                        JANUS_CHECK_SECRET(admin_key, root, "admin_key", error_code, error_cause,
1246
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1247
                        if(error_code != 0)
1248
                                goto plugin_response;
1249
                }
1250
                json_t *desc = json_object_get(root, "description");
1251
                json_t *is_private = json_object_get(root, "is_private");
1252
                json_t *secret = json_object_get(root, "secret");
1253
                json_t *pin = json_object_get(root, "pin");
1254
                json_t *bitrate = json_object_get(root, "bitrate");
1255
                json_t *fir_freq = json_object_get(root, "fir_freq");
1256
                json_t *publishers = json_object_get(root, "publishers");
1257
                json_t *audiocodec = json_object_get(root, "audiocodec");
1258
                if(audiocodec) {
1259
                        const char *audiocodec_value = json_string_value(audiocodec);
1260
                        if(!strcasecmp(audiocodec_value, "opus") && !strcasecmp(audiocodec_value, "isac32") && !strcasecmp(audiocodec_value, "isac16") && !strcasecmp(audiocodec_value, "pcmu") && !strcasecmp(audiocodec_value, "pcma")) {
1261
                                JANUS_LOG(LOG_ERR, "Invalid element (audiocodec can only be opus, isac32, isac16, pcmu, or pcma)\n");
1262
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1263
                                g_snprintf(error_cause, 512, "Invalid element (audiocodec can only be opus, isac32, isac16, pcmu, or pcma)");
1264
                                goto plugin_response;
1265
                        }
1266
                }
1267
                json_t *videocodec = json_object_get(root, "videocodec");
1268
                if(videocodec) {
1269
                        const char *videocodec_value = json_string_value(videocodec);
1270
                        if(!strcasecmp(videocodec_value, "vp8") && !strcasecmp(videocodec_value, "vp9") && !strcasecmp(videocodec_value, "h264")) {
1271
                                JANUS_LOG(LOG_ERR, "Invalid element (videocodec can only be vp8, vp9 or h264)\n");
1272
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1273
                                g_snprintf(error_cause, 512, "Invalid element (videocodec can only be vp8, vp9 or h264)");
1274
                                goto plugin_response;
1275
                        }
1276
                }
1277
                json_t *record = json_object_get(root, "record");
1278
                json_t *rec_dir = json_object_get(root, "rec_dir");
1279
                json_t *permanent = json_object_get(root, "permanent");
1280
                gboolean save = permanent ? json_is_true(permanent) : FALSE;
1281
                if(save && config == NULL) {
1282
                        JANUS_LOG(LOG_ERR, "No configuration file, can't create permanent room\n");
1283
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1284
                        g_snprintf(error_cause, 512, "No configuration file, can't create permanent room");
1285
                        goto plugin_response;
1286
                }
1287
                guint64 room_id = 0;
1288
                json_t *room = json_object_get(root, "room");
1289
                if(room) {
1290
                        room_id = json_integer_value(room);
1291
                        if(room_id == 0) {
1292
                                JANUS_LOG(LOG_WARN, "Desired room ID is 0, which is not allowed... picking random ID instead\n");
1293
                        }
1294
                }
1295
                janus_mutex_lock(&rooms_mutex);
1296
                if(room_id > 0) {
1297
                        /* Let's make sure the room doesn't exist already */
1298
                        if(g_hash_table_lookup(rooms, &room_id) != NULL) {
1299
                                /* It does... */
1300
                                janus_mutex_unlock(&rooms_mutex);
1301
                                JANUS_LOG(LOG_ERR, "Room %"SCNu64" already exists!\n", room_id);
1302
                                error_code = JANUS_VIDEOROOM_ERROR_ROOM_EXISTS;
1303
                                g_snprintf(error_cause, 512, "Room %"SCNu64" already exists", room_id);
1304
                                goto plugin_response;
1305
                        }
1306
                }
1307
                /* Create the room */
1308
                janus_videoroom *videoroom = g_malloc0(sizeof(janus_videoroom));
1309
                /* Generate a random ID */
1310
                if(room_id == 0) {
1311
                        while(room_id == 0) {
1312
                                room_id = janus_random_uint64();
1313
                                if(g_hash_table_lookup(rooms, &room_id) != NULL) {
1314
                                        /* Room ID already taken, try another one */
1315
                                        room_id = 0;
1316
                                }
1317
                        }
1318
                }
1319
                videoroom->room_id = room_id;
1320
                char *description = NULL;
1321
                if(desc != NULL && strlen(json_string_value(desc)) > 0) {
1322
                        description = g_strdup(json_string_value(desc));
1323
                } else {
1324
                        char roomname[255];
1325
                        g_snprintf(roomname, 255, "Room %"SCNu64"", videoroom->room_id);
1326
                        description = g_strdup(roomname);
1327
                }
1328
                videoroom->room_name = description;
1329
                videoroom->is_private = is_private ? json_is_true(is_private) : FALSE;
1330
                if(secret)
1331
                        videoroom->room_secret = g_strdup(json_string_value(secret));
1332
                if(pin)
1333
                        videoroom->room_pin = g_strdup(json_string_value(pin));
1334
                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
1335
                if(publishers)
1336
                        videoroom->max_publishers = json_integer_value(publishers);
1337
                if(videoroom->max_publishers < 0)
1338
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
1339
                videoroom->bitrate = 0;
1340
                if(bitrate)
1341
                        videoroom->bitrate = json_integer_value(bitrate);
1342
                if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
1343
                        videoroom->bitrate = 64000;        /* Don't go below 64k */
1344
                videoroom->fir_freq = 0;
1345
                if(fir_freq)
1346
                        videoroom->fir_freq = json_integer_value(fir_freq);
1347
                videoroom->acodec = JANUS_VIDEOROOM_OPUS;
1348
                if(audiocodec) {
1349
                        const char *audiocodec_value = json_string_value(audiocodec);
1350
                        if(!strcasecmp(audiocodec_value, "opus"))
1351
                                videoroom->acodec = JANUS_VIDEOROOM_OPUS;
1352
                        else if(!strcasecmp(audiocodec_value, "isac32"))
1353
                                videoroom->acodec = JANUS_VIDEOROOM_ISAC_32K;
1354
                        else if(!strcasecmp(audiocodec_value, "isac16"))
1355
                                videoroom->acodec = JANUS_VIDEOROOM_ISAC_16K;
1356
                        else if(!strcasecmp(audiocodec_value, "pcmu"))
1357
                                videoroom->acodec = JANUS_VIDEOROOM_PCMU;
1358
                        else if(!strcasecmp(audiocodec_value, "pcma"))
1359
                                videoroom->acodec = JANUS_VIDEOROOM_PCMA;
1360
                        else {
1361
                                JANUS_LOG(LOG_WARN, "Unsupported audio codec '%s', falling back to OPUS\n", audiocodec_value);
1362
                                videoroom->acodec = JANUS_VIDEOROOM_OPUS;
1363
                        }
1364
                }
1365
                videoroom->vcodec = JANUS_VIDEOROOM_VP8;
1366
                if(videocodec) {
1367
                        const char *videocodec_value = json_string_value(videocodec);
1368
                        if(!strcasecmp(videocodec_value, "vp8"))
1369
                                videoroom->vcodec = JANUS_VIDEOROOM_VP8;
1370
                        else if(!strcasecmp(videocodec_value, "vp9"))
1371
                                videoroom->vcodec = JANUS_VIDEOROOM_VP9;
1372
                        else if(!strcasecmp(videocodec_value, "h264"))
1373
                                videoroom->vcodec = JANUS_VIDEOROOM_H264;
1374
                        else {
1375
                                JANUS_LOG(LOG_WARN, "Unsupported video codec '%s', falling back to VP8\n", videocodec_value);
1376
                                videoroom->vcodec = JANUS_VIDEOROOM_VP8;
1377
                        }
1378
                }
1379
                if(record) {
1380
                        videoroom->record = json_is_true(record);
1381
                }
1382
                if(rec_dir) {
1383
                        videoroom->rec_dir = g_strdup(json_string_value(rec_dir));
1384
                }
1385
                videoroom->destroyed = 0;
1386
                janus_mutex_init(&videoroom->participants_mutex);
1387
                videoroom->participants = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
1388
                JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, %s/%s codecs, secret: %s, pin: %s)\n",
1389
                        videoroom->room_id, videoroom->room_name,
1390
                        videoroom->is_private ? "private" : "public",
1391
                        janus_videoroom_audiocodec_name(videoroom->acodec),
1392
                        janus_videoroom_videocodec_name(videoroom->vcodec),
1393
                        videoroom->room_secret ? videoroom->room_secret : "no secret",
1394
                        videoroom->room_pin ? videoroom->room_pin : "no pin");
1395
                if(videoroom->record) {
1396
                        JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
1397
                }
1398
                if(save) {
1399
                        /* This room is permanent: save to the configuration file too
1400
                         * FIXME: We should check if anything fails... */
1401
                        JANUS_LOG(LOG_VERB, "Saving room %"SCNu64" permanently in config file\n", videoroom->room_id);
1402
                        janus_mutex_lock(&config_mutex);
1403
                        char cat[BUFSIZ], value[BUFSIZ];
1404
                        /* The room ID is the category */
1405
                        g_snprintf(cat, BUFSIZ, "%"SCNu64, videoroom->room_id);
1406
                        janus_config_add_category(config, cat);
1407
                        /* Now for the values */
1408
                        janus_config_add_item(config, cat, "description", videoroom->room_name);
1409
                        if(videoroom->is_private)
1410
                                janus_config_add_item(config, cat, "is_private", "yes");
1411
                        g_snprintf(value, BUFSIZ, "%"SCNu64, videoroom->bitrate);
1412
                        janus_config_add_item(config, cat, "bitrate", value);
1413
                        g_snprintf(value, BUFSIZ, "%d", videoroom->max_publishers);
1414
                        janus_config_add_item(config, cat, "publishers", value);
1415
                        if(videoroom->fir_freq) {
1416
                                g_snprintf(value, BUFSIZ, "%"SCNu16, videoroom->fir_freq);
1417
                                janus_config_add_item(config, cat, "fir_freq", value);
1418
                        }
1419
                        janus_config_add_item(config, cat, "audiocodec", janus_videoroom_audiocodec_name(videoroom->acodec));
1420
                        janus_config_add_item(config, cat, "videocodec", janus_videoroom_videocodec_name(videoroom->vcodec));
1421
                        if(videoroom->room_secret)
1422
                                janus_config_add_item(config, cat, "secret", videoroom->room_secret);
1423
                        if(videoroom->room_pin)
1424
                                janus_config_add_item(config, cat, "pin", videoroom->room_pin);
1425
                        if(videoroom->record)
1426
                                janus_config_add_item(config, cat, "record", "yes");
1427
                        if(videoroom->rec_dir)
1428
                                janus_config_add_item(config, cat, "rec_dir", videoroom->rec_dir);
1429
                        /* Save modified configuration */
1430
                        janus_config_save(config, config_folder, JANUS_VIDEOROOM_PACKAGE);
1431
                        janus_mutex_unlock(&config_mutex);
1432
                }
1433
                /* Show updated rooms list */
1434
                GHashTableIter iter;
1435
                gpointer value;
1436
                g_hash_table_insert(rooms, janus_uint64_dup(videoroom->room_id), videoroom);
1437
                g_hash_table_iter_init(&iter, rooms);
1438
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1439
                        janus_videoroom *vr = value;
1440
                        JANUS_LOG(LOG_VERB, "  ::: [%"SCNu64"][%s] %"SCNu64", max %d publishers, FIR frequency of %d seconds\n", vr->room_id, vr->room_name, vr->bitrate, vr->max_publishers, vr->fir_freq);
1441
                }
1442
                janus_mutex_unlock(&rooms_mutex);
1443
                /* Send info back */
1444
                response = json_object();
1445
                json_object_set_new(response, "videoroom", json_string("created"));
1446
                json_object_set_new(response, "room", json_integer(videoroom->room_id));
1447
                goto plugin_response;
1448
        } else if(!strcasecmp(request_text, "destroy")) {
1449
                JANUS_LOG(LOG_VERB, "Attempt to destroy an existing videoroom room\n");
1450
                JANUS_VALIDATE_JSON_OBJECT(root, destroy_parameters,
1451
                        error_code, error_cause, TRUE,
1452
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1453
                if(error_code != 0)
1454
                        goto plugin_response;
1455
                json_t *room = json_object_get(root, "room");
1456
                json_t *permanent = json_object_get(root, "permanent");
1457
                gboolean save = permanent ? json_is_true(permanent) : FALSE;
1458
                if(save && config == NULL) {
1459
                        JANUS_LOG(LOG_ERR, "No configuration file, can't destroy room permanently\n");
1460
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1461
                        g_snprintf(error_cause, 512, "No configuration file, can't destroy room permanently");
1462
                        goto plugin_response;
1463
                }
1464
                guint64 room_id = json_integer_value(room);
1465
                janus_mutex_lock(&rooms_mutex);
1466
                janus_videoroom *videoroom = NULL;
1467
                error_code = janus_videoroom_access_room(root, TRUE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1468
                if(error_code != 0) {
1469
                        janus_mutex_unlock(&rooms_mutex);
1470
                        goto plugin_response;
1471
                }
1472
                /* Notify all participants that the fun is over, and that they'll be kicked */
1473
                JANUS_LOG(LOG_VERB, "Notifying all participants\n");
1474
                json_t *destroyed = json_object();
1475
                json_object_set_new(destroyed, "videoroom", json_string("destroyed"));
1476
                json_object_set_new(destroyed, "room", json_integer(videoroom->room_id));
1477
                GHashTableIter iter;
1478
                gpointer value;
1479
                /* Remove room lazily*/
1480
                videoroom->destroyed = janus_get_monotonic_time();
1481
                old_rooms = g_list_append(old_rooms, videoroom);
1482
                janus_mutex_lock(&videoroom->participants_mutex);
1483
                g_hash_table_iter_init(&iter, videoroom->participants);
1484
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1485
                        janus_videoroom_participant *p = value;
1486
                        if(p && p->session) {
1487
                                /* Notify the user we're going to destroy the room... */
1488
                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, destroyed, NULL);
1489
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1490
                                /* ... and then ask the core to remove the handle */
1491
                                gateway->end_session(p->session->handle);
1492
                        }
1493
                }
1494
                json_decref(destroyed);
1495
                janus_mutex_unlock(&videoroom->participants_mutex);
1496
                janus_mutex_unlock(&rooms_mutex);
1497
                if(save) {
1498
                        /* This change is permanent: save to the configuration file too
1499
                         * FIXME: We should check if anything fails... */
1500
                        JANUS_LOG(LOG_VERB, "Destroying room %"SCNu64" permanently in config file\n", room_id);
1501
                        janus_mutex_lock(&config_mutex);
1502
                        char cat[BUFSIZ];
1503
                        /* The room ID is the category */
1504
                        g_snprintf(cat, BUFSIZ, "%"SCNu64, room_id);
1505
                        janus_config_remove_category(config, cat);
1506
                        /* Save modified configuration */
1507
                        janus_config_save(config, config_folder, JANUS_VIDEOROOM_PACKAGE);
1508
                        janus_mutex_unlock(&config_mutex);
1509
                }
1510
                /* Done */
1511
                response = json_object();
1512
                json_object_set_new(response, "videoroom", json_string("destroyed"));
1513
                json_object_set_new(response, "room", json_integer(room_id));
1514
                goto plugin_response;
1515
        } else if(!strcasecmp(request_text, "list")) {
1516
                /* List all rooms (but private ones) and their details (except for the secret, of course...) */
1517
                json_t *list = json_array();
1518
                JANUS_LOG(LOG_VERB, "Getting the list of video rooms\n");
1519
                janus_mutex_lock(&rooms_mutex);
1520
                GHashTableIter iter;
1521
                gpointer value;
1522
                g_hash_table_iter_init(&iter, rooms);
1523
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
1524
                        janus_videoroom *room = value;
1525
                        if(!room)
1526
                                continue;
1527
                        if(room->is_private) {
1528
                                /* Skip private room */
1529
                                JANUS_LOG(LOG_VERB, "Skipping private room '%s'\n", room->room_name);
1530
                                continue;
1531
                        }
1532
                        if(!room->destroyed) {
1533
                                json_t *rl = json_object();
1534
                                json_object_set_new(rl, "room", json_integer(room->room_id));
1535
                                json_object_set_new(rl, "description", json_string(room->room_name));
1536
                                json_object_set_new(rl, "max_publishers", json_integer(room->max_publishers));
1537
                                json_object_set_new(rl, "bitrate", json_integer(room->bitrate));
1538
                                json_object_set_new(rl, "fir_freq", json_integer(room->fir_freq));
1539
                                json_object_set_new(rl, "audiocodec", json_string(janus_videoroom_audiocodec_name(room->acodec)));
1540
                                json_object_set_new(rl, "videocodec", json_string(janus_videoroom_videocodec_name(room->vcodec)));
1541
                                json_object_set_new(rl, "record", room->record ? json_true() : json_false());
1542
                                json_object_set_new(rl, "rec_dir", json_string(room->rec_dir));
1543
                                /* TODO: Should we list participants as well? or should there be a separate API call on a specific room for this? */
1544
                                json_object_set_new(rl, "num_participants", json_integer(g_hash_table_size(room->participants)));
1545
                                json_array_append_new(list, rl);
1546
                        }
1547
                }
1548
                janus_mutex_unlock(&rooms_mutex);
1549
                response = json_object();
1550
                json_object_set_new(response, "videoroom", json_string("success"));
1551
                json_object_set_new(response, "list", list);
1552
                goto plugin_response;
1553
        } else if(!strcasecmp(request_text, "rtp_forward")) {
1554
                JANUS_VALIDATE_JSON_OBJECT(root, rtp_forward_parameters,
1555
                        error_code, error_cause, TRUE,
1556
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1557
                if(error_code != 0)
1558
                        goto plugin_response;
1559
                json_t *room = json_object_get(root, "room");
1560
                json_t *pub_id = json_object_get(root, "publisher_id");
1561
                int video_port = -1;
1562
                int audio_port = -1;
1563
                json_t *vid_port = json_object_get(root, "video_port");
1564
                if(vid_port) {
1565
                        video_port = json_integer_value(vid_port);
1566
                }
1567
                json_t *au_port = json_object_get(root, "audio_port");
1568
                if(au_port) {
1569
                        audio_port = json_integer_value(au_port);
1570
                }
1571
                json_t *json_host = json_object_get(root, "host");
1572
                
1573
                guint64 room_id = json_integer_value(room);
1574
                guint64 publisher_id = json_integer_value(pub_id);
1575
                const gchar* host = json_string_value(json_host);
1576
                janus_mutex_lock(&rooms_mutex);
1577
                janus_videoroom *videoroom = NULL;
1578
                error_code = janus_videoroom_access_room(root, TRUE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1579
                janus_mutex_unlock(&rooms_mutex);
1580
                if(error_code != 0)
1581
                        goto plugin_response;
1582
                janus_mutex_lock(&videoroom->participants_mutex);
1583
                janus_videoroom_participant* publisher = g_hash_table_lookup(videoroom->participants, &publisher_id);
1584
                if(publisher == NULL) {
1585
                        janus_mutex_unlock(&videoroom->participants_mutex);
1586
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1587
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1588
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1589
                        goto plugin_response;
1590
                }
1591
                if(publisher->udp_sock <= 0) {
1592
                        publisher->udp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1593
                        if(publisher->udp_sock <= 0) {
1594
                                janus_mutex_unlock(&videoroom->participants_mutex);
1595
                                JANUS_LOG(LOG_ERR, "Could not open UDP socket for rtp stream for publisher (%"SCNu64")\n", publisher_id);
1596
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1597
                                g_snprintf(error_cause, 512, "Could not open UDP socket for rtp stream");
1598
                                goto plugin_response;
1599
                        }
1600
                }
1601
                guint32 audio_handle = 0;
1602
                guint32 video_handle = 0;
1603
                if(audio_port > 0) {
1604
                        audio_handle = janus_rtp_forwarder_add_helper(publisher, host, audio_port, 0);
1605
                }
1606
                if(video_port > 0) {
1607
                        video_handle = janus_rtp_forwarder_add_helper(publisher, host, video_port, 1);
1608
                }
1609
                janus_mutex_unlock(&videoroom->participants_mutex);
1610
                response = json_object();
1611
                json_t* rtp_stream = json_object();
1612
                if(audio_handle > 0) {
1613
                        json_object_set_new(rtp_stream, "audio_stream_id", json_integer(audio_handle));
1614
                        json_object_set_new(rtp_stream, "audio", json_integer(audio_port));
1615
                }
1616
                if(video_handle > 0) {
1617
                        /* Send a FIR to the new RTP forward publisher */
1618
                        char buf[20];
1619
                        memset(buf, 0, 20);
1620
                        janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
1621
                        JANUS_LOG(LOG_VERB, "New RTP forward publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
1622
                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
1623
                        /* Send a PLI too, just in case... */
1624
                        memset(buf, 0, 12);
1625
                        janus_rtcp_pli((char *)&buf, 12);
1626
                        JANUS_LOG(LOG_VERB, "New RTP forward publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
1627
                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
1628
                        /* Done */
1629
                        json_object_set_new(rtp_stream, "video_stream_id", json_integer(video_handle));
1630
                        json_object_set_new(rtp_stream, "video", json_integer(video_port));
1631
                }
1632
                json_object_set_new(rtp_stream, "host", json_string(host));
1633
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1634
                json_object_set_new(response, "rtp_stream", rtp_stream);
1635
                json_object_set_new(response, "room", json_integer(room_id));
1636
                json_object_set_new(response, "videoroom", json_string("rtp_forward"));
1637
                goto plugin_response;
1638
        } else if(!strcasecmp(request_text, "stop_rtp_forward")) {
1639
                JANUS_VALIDATE_JSON_OBJECT(root, stop_rtp_forward_parameters,
1640
                        error_code, error_cause, TRUE,
1641
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1642
                if(error_code != 0)
1643
                        goto plugin_response;
1644
                json_t *room = json_object_get(root, "room");
1645
                json_t *pub_id = json_object_get(root, "publisher_id");
1646
                json_t *id = json_object_get(root, "stream_id");
1647

    
1648
                guint64 room_id = json_integer_value(room);
1649
                guint64 publisher_id = json_integer_value(pub_id);
1650
                guint32 stream_id = json_integer_value(id);
1651
                janus_mutex_lock(&rooms_mutex);
1652
                janus_videoroom *videoroom = NULL;
1653
                error_code = janus_videoroom_access_room(root, TRUE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1654
                janus_mutex_unlock(&rooms_mutex);
1655
                if(error_code != 0)
1656
                        goto plugin_response;
1657
                janus_mutex_lock(&videoroom->participants_mutex);
1658
                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &publisher_id);
1659
                if(publisher == NULL) {
1660
                        janus_mutex_unlock(&videoroom->participants_mutex);
1661
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1662
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1663
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1664
                        goto plugin_response;
1665
                }
1666
                janus_mutex_lock(&publisher->rtp_forwarders_mutex);
1667
                if(g_hash_table_lookup(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id)) == NULL) {
1668
                        janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1669
                        janus_mutex_unlock(&videoroom->participants_mutex);
1670
                        JANUS_LOG(LOG_ERR, "No such stream (%"SCNu32")\n", stream_id);
1671
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1672
                        g_snprintf(error_cause, 512, "No such stream (%"SCNu32")", stream_id);
1673
                        goto plugin_response;
1674
                }
1675
                g_hash_table_remove(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id));
1676
                janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1677
                janus_mutex_unlock(&videoroom->participants_mutex);
1678
                response = json_object();
1679
                json_object_set_new(response, "videoroom", json_string("stop_rtp_forward"));
1680
                json_object_set_new(response, "room", json_integer(room_id));
1681
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1682
                json_object_set_new(response, "stream_id", json_integer(stream_id));
1683
                goto plugin_response;
1684
        } else if(!strcasecmp(request_text, "exists")) {
1685
                /* Check whether a given room exists or not, returns true/false */        
1686
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
1687
                        error_code, error_cause, TRUE,
1688
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1689
                if(error_code != 0)
1690
                        goto plugin_response;
1691
                json_t *room = json_object_get(root, "room");
1692
                guint64 room_id = json_integer_value(room);
1693
                janus_mutex_lock(&rooms_mutex);
1694
                gboolean room_exists = g_hash_table_contains(rooms, &room_id);
1695
                janus_mutex_unlock(&rooms_mutex);
1696
                response = json_object();
1697
                json_object_set_new(response, "videoroom", json_string("success"));
1698
                json_object_set_new(response, "room", json_integer(room_id));
1699
                json_object_set_new(response, "exists", room_exists ? json_true() : json_false());
1700
                goto plugin_response;
1701
        } else if(!strcasecmp(request_text, "listparticipants")) {
1702
                /* List all participants in a room, specifying whether they're publishers or just attendees */        
1703
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
1704
                        error_code, error_cause, TRUE,
1705
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1706
                if(error_code != 0)
1707
                        goto plugin_response;
1708
                json_t *room = json_object_get(root, "room");
1709
                guint64 room_id = json_integer_value(room);
1710
                janus_mutex_lock(&rooms_mutex);
1711
                janus_videoroom *videoroom = NULL;
1712
                error_code = janus_videoroom_access_room(root, FALSE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1713
                janus_mutex_unlock(&rooms_mutex);
1714
                if(error_code != 0)
1715
                        goto plugin_response;
1716
                /* Return a list of all participants (whether they're publishing or not) */
1717
                json_t *list = json_array();
1718
                GHashTableIter iter;
1719
                gpointer value;
1720
                janus_mutex_lock(&videoroom->participants_mutex);
1721
                g_hash_table_iter_init(&iter, videoroom->participants);
1722
                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1723
                        janus_videoroom_participant *p = value;
1724
                        json_t *pl = json_object();
1725
                        json_object_set_new(pl, "id", json_integer(p->user_id));
1726
                        if(p->display)
1727
                                json_object_set_new(pl, "display", json_string(p->display));
1728
                        json_object_set_new(pl, "publisher", (p->sdp && p->session->started) ? json_true() : json_false());
1729
                        json_array_append_new(list, pl);
1730
                }
1731
                janus_mutex_unlock(&videoroom->participants_mutex);
1732
                response = json_object();
1733
                json_object_set_new(response, "videoroom", json_string("participants"));
1734
                json_object_set_new(response, "room", json_integer(room_id));
1735
                json_object_set_new(response, "participants", list);
1736
                goto plugin_response;
1737
        } else if(!strcasecmp(request_text, "listforwarders")) {
1738
                /* List all forwarders in a room */        
1739
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
1740
                        error_code, error_cause, TRUE,
1741
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1742
                if(error_code != 0)
1743
                        goto plugin_response;
1744
                json_t *room = json_object_get(root, "room");
1745
                guint64 room_id = json_integer_value(room);
1746
                janus_mutex_lock(&rooms_mutex);
1747
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, &room_id);
1748
                if(videoroom == NULL) {
1749
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1750
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1751
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1752
                        janus_mutex_unlock(&rooms_mutex);
1753
                        goto plugin_response;
1754
                }
1755
                if(videoroom->destroyed) {
1756
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1757
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1758
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1759
                        janus_mutex_unlock(&rooms_mutex);
1760
                        goto plugin_response;
1761
                }
1762
                /* A secret may be required for this action */
1763
                JANUS_CHECK_SECRET(videoroom->room_secret, root, "secret", error_code, error_cause,
1764
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1765
                if(error_code != 0) {
1766
                        janus_mutex_unlock(&rooms_mutex);
1767
                        goto plugin_response;
1768
                }
1769
                /* Return a list of all forwarders */
1770
                json_t *list = json_array();
1771
                GHashTableIter iter;
1772
                gpointer value;
1773
                janus_mutex_lock(&videoroom->participants_mutex);
1774
                g_hash_table_iter_init(&iter, videoroom->participants);
1775
                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1776
                        janus_videoroom_participant *p = value;
1777
                        if(g_hash_table_size(p->rtp_forwarders) == 0)
1778
                                continue;
1779
                        json_t *pl = json_object();
1780
                        json_object_set_new(pl, "publisher_id", json_integer(p->user_id));
1781
                        if(p->display)
1782
                                json_object_set_new(pl, "display", json_string(p->display));
1783
                        json_t *flist = json_array();
1784
                        GHashTableIter iter_f;
1785
                        gpointer key_f, value_f;                        
1786
                        g_hash_table_iter_init(&iter_f, p->rtp_forwarders);
1787
                        janus_mutex_lock(&p->rtp_forwarders_mutex);
1788
                        while(g_hash_table_iter_next(&iter_f, &key_f, &value_f)) {                                
1789
                                json_t *fl = json_object();
1790
                                guint32 rpk = GPOINTER_TO_UINT(key_f);
1791
                                rtp_forwarder *rpv = value_f;
1792
                                json_object_set_new(fl, "ip", json_string(inet_ntoa(rpv->serv_addr.sin_addr)));
1793
                                if(rpv->is_video > 0) {
1794
                                        json_object_set_new(fl, "video_stream_id", json_integer(rpk));
1795
                                        json_object_set_new(fl, "port", json_integer(ntohs(rpv->serv_addr.sin_port)));
1796
                                } else {
1797
                                        json_object_set_new(fl, "audio_stream_id", json_integer(rpk));
1798
                                        json_object_set_new(fl, "port", json_integer(ntohs(rpv->serv_addr.sin_port)));
1799
                                }
1800
                                json_array_append_new(flist, fl);
1801
                        }                
1802
                        janus_mutex_unlock(&p->rtp_forwarders_mutex);
1803
                        json_object_set_new(pl, "rtp_forwarder", flist);
1804
                        json_array_append_new(list, pl);
1805
                }
1806
                janus_mutex_unlock(&videoroom->participants_mutex);
1807
                janus_mutex_unlock(&rooms_mutex);
1808
                response = json_object();
1809
                json_object_set_new(response, "room", json_integer(room_id));
1810
                json_object_set_new(response, "rtp_forwarders", list);
1811
                goto plugin_response;
1812
        } else if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")
1813
                        || !strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish") || !strcasecmp(request_text, "unpublish")
1814
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "pause") || !strcasecmp(request_text, "switch") || !strcasecmp(request_text, "stop")
1815
                        || !strcasecmp(request_text, "add") || !strcasecmp(request_text, "remove") || !strcasecmp(request_text, "leave")) {
1816
                /* These messages are handled asynchronously */
1817

    
1818
                janus_videoroom_message *msg = g_malloc0(sizeof(janus_videoroom_message));
1819
                msg->handle = handle;
1820
                msg->transaction = transaction;
1821
                msg->message = root;
1822
                msg->jsep = jsep;
1823
                g_async_queue_push(messages, msg);
1824

    
1825
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
1826
        } else {
1827
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
1828
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
1829
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
1830
        }
1831

    
1832
plugin_response:
1833
                {
1834
                        if(error_code == 0 && !response) {
1835
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1836
                                g_snprintf(error_cause, 512, "Invalid response");
1837
                        }
1838
                        if(error_code != 0) {
1839
                                /* Prepare JSON error event */
1840
                                json_t *event = json_object();
1841
                                json_object_set_new(event, "videoroom", json_string("event"));
1842
                                json_object_set_new(event, "error_code", json_integer(error_code));
1843
                                json_object_set_new(event, "error", json_string(error_cause));
1844
                                response = event;
1845
                        }
1846
                        if(root != NULL)
1847
                                json_decref(root);
1848
                        if(jsep != NULL)
1849
                                json_decref(jsep);
1850
                        g_free(transaction);
1851

    
1852
                        return janus_plugin_result_new(JANUS_PLUGIN_OK, NULL, response);
1853
                }
1854

    
1855
}
1856

    
1857
void janus_videoroom_setup_media(janus_plugin_session *handle) {
1858
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
1859
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1860
                return;
1861
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1862
        if(!session) {
1863
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1864
                return;
1865
        }
1866
        if(session->destroyed)
1867
                return;
1868
        g_atomic_int_set(&session->hangingup, 0);
1869

    
1870
        /* Media relaying can start now */
1871
        session->started = TRUE;
1872

    
1873
        if(session->participant) {
1874
                /* If this is a publisher, notify all listeners about the fact they can
1875
                 * now subscribe; if this is a listener, instead, ask the publisher a FIR */
1876
                if(session->participant_type == janus_videoroom_p_type_publisher) {
1877
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1878
                        /* Notify all other participants that there's a new boy in town */
1879
                        json_t *list = json_array();
1880
                        json_t *pl = json_object();
1881
                        json_object_set_new(pl, "id", json_integer(participant->user_id));
1882
                        if(participant->display)
1883
                                json_object_set_new(pl, "display", json_string(participant->display));
1884
                        json_array_append_new(list, pl);
1885
                        json_t *pub = json_object();
1886
                        json_object_set_new(pub, "videoroom", json_string("event"));
1887
                        json_object_set_new(pub, "room", json_integer(participant->room->room_id));
1888
                        json_object_set_new(pub, "publishers", list);
1889
                        GHashTableIter iter;
1890
                        gpointer value;
1891
                        janus_videoroom *videoroom = participant->room;
1892
                        janus_mutex_lock(&videoroom->participants_mutex);
1893
                        g_hash_table_iter_init(&iter, videoroom->participants);
1894
                        while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1895
                                janus_videoroom_participant *p = value;
1896
                                if(p == participant) {
1897
                                        continue;        /* Skip the new publisher itself */
1898
                                }
1899
                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1900
                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, pub, NULL);
1901
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1902
                        }
1903
                        json_decref(pub);
1904
                        janus_mutex_unlock(&videoroom->participants_mutex);
1905
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1906
                        janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
1907
                        if(l && l->feed) {
1908
                                janus_videoroom_participant *p = l->feed;
1909
                                if(p && p->session) {
1910
                                        /* Send a FIR */
1911
                                        char buf[20];
1912
                                        memset(buf, 0, 20);
1913
                                        janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
1914
                                        JANUS_LOG(LOG_VERB, "New listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1915
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 20);
1916
                                        /* Send a PLI too, just in case... */
1917
                                        memset(buf, 0, 12);
1918
                                        janus_rtcp_pli((char *)&buf, 12);
1919
                                        JANUS_LOG(LOG_VERB, "New listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1920
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 12);
1921
                                }
1922
                        }
1923
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1924
                        /* Do the same, but for all feeds */
1925
                        janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
1926
                        if(listener == NULL)
1927
                                return;
1928
                        GSList *ps = listener->listeners;
1929
                        while(ps) {
1930
                                janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
1931
                                if(l && l->feed) {
1932
                                        janus_videoroom_participant *p = l->feed;
1933
                                        if(p && p->session) {
1934
                                                /* Send a FIR */
1935
                                                char buf[20];
1936
                                                memset(buf, 0, 20);
1937
                                                janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
1938
                                                JANUS_LOG(LOG_VERB, "New Multiplexed listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1939
                                                gateway->relay_rtcp(p->session->handle, 1, buf, 20);
1940
                                                /* Send a PLI too, just in case... */
1941
                                                memset(buf, 0, 12);
1942
                                                janus_rtcp_pli((char *)&buf, 12);
1943
                                                JANUS_LOG(LOG_VERB, "New Multiplexed listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1944
                                                gateway->relay_rtcp(p->session->handle, 1, buf, 12);
1945
                                        }
1946
                                }
1947
                                ps = ps->next;
1948
                        }
1949
                }
1950
        }
1951
}
1952

    
1953
void janus_videoroom_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1954
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1955
                return;
1956
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1957
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
1958
                return;
1959
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1960
        if((!video && participant->audio_active) || (video && participant->video_active)) {
1961
                /* Update payload type and SSRC */
1962
                rtp_header *rtp = (rtp_header *)buf;
1963
                rtp->type = video ? participant->video_pt : participant->audio_pt;
1964
                rtp->ssrc = htonl(video ? participant->video_ssrc : participant->audio_ssrc);
1965
                /* Forward RTP to the appropriate port for the rtp_forwarders associated with this publisher, if there are any */
1966
                GHashTableIter iter;
1967
                gpointer value;
1968
                g_hash_table_iter_init(&iter, participant->rtp_forwarders);
1969
                janus_mutex_lock(&participant->rtp_forwarders_mutex);
1970
                while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
1971
                        rtp_forwarder* rtp_forward = (rtp_forwarder*)value;
1972
                        if(video && rtp_forward->is_video) {
1973
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
1974
                        }
1975
                        else if(!video && !rtp_forward->is_video) {
1976
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
1977
                        }
1978
                }
1979
                janus_mutex_unlock(&participant->rtp_forwarders_mutex);
1980
                /* Save the frame if we're recording */
1981
                janus_recorder_save_frame(video ? participant->vrc : participant->arc, buf, len);
1982
                /* Done, relay it */
1983
                janus_videoroom_rtp_relay_packet packet;
1984
                packet.data = rtp;
1985
                packet.length = len;
1986
                packet.is_video = video;
1987
                /* Backup the actual timestamp and sequence number set by the publisher, in case switching is involved */
1988
                packet.timestamp = ntohl(packet.data->timestamp);
1989
                packet.seq_number = ntohs(packet.data->seq_number);
1990
                /* Go */
1991
                g_slist_foreach(participant->listeners, janus_videoroom_relay_rtp_packet, &packet);
1992
                
1993
                /* Check if we need to send any REMB, FIR or PLI back to this publisher */
1994
                if(video && participant->video_active) {
1995
                        /* Did we send a REMB already, or is it time to send one? */
1996
                        gboolean send_remb = FALSE;
1997
                        if(participant->remb_latest == 0 && participant->remb_startup > 0) {
1998
                                /* Still in the starting phase, send the ramp-up REMB feedback */
1999
                                send_remb = TRUE;
2000
                        } else if(participant->remb_latest > 0 && janus_get_monotonic_time()-participant->remb_latest >= 5*G_USEC_PER_SEC) {
2001
                                /* 5 seconds have passed since the last REMB, send a new one */
2002
                                send_remb = TRUE;
2003
                        }                
2004
                        if(send_remb) {
2005
                                /* We send a few incremental REMB messages at startup */
2006
                                uint64_t bitrate = (participant->bitrate ? participant->bitrate : 256*1024);
2007
                                if(participant->remb_startup > 0) {
2008
                                        bitrate = bitrate/participant->remb_startup;
2009
                                        participant->remb_startup--;
2010
                                }
2011
                                JANUS_LOG(LOG_VERB, "Sending REMB (%s, %"SCNu64")\n", participant->display, bitrate);
2012
                                char rtcpbuf[24];
2013
                                janus_rtcp_remb((char *)(&rtcpbuf), 24, bitrate);
2014
                                gateway->relay_rtcp(handle, video, rtcpbuf, 24);
2015
                                if(participant->remb_startup == 0)
2016
                                        participant->remb_latest = janus_get_monotonic_time();
2017
                        }
2018
                        /* Generate FIR/PLI too, if needed */
2019
                        if(video && participant->video_active && (participant->room->fir_freq > 0)) {
2020
                                /* FIXME Very ugly hack to generate RTCP every tot seconds/frames */
2021
                                gint64 now = janus_get_monotonic_time();
2022
                                if((now-participant->fir_latest) >= (participant->room->fir_freq*G_USEC_PER_SEC)) {
2023
                                        /* FIXME We send a FIR every tot seconds */
2024
                                        participant->fir_latest = now;
2025
                                        char rtcpbuf[24];
2026
                                        memset(rtcpbuf, 0, 24);
2027
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &participant->fir_seq);
2028
                                        JANUS_LOG(LOG_VERB, "Sending FIR to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2029
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 20);
2030
                                        /* Send a PLI too, just in case... */
2031
                                        memset(rtcpbuf, 0, 12);
2032
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2033
                                        JANUS_LOG(LOG_VERB, "Sending PLI to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2034
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 12);
2035
                                }
2036
                        }
2037
                }
2038
        }
2039
}
2040

    
2041
void janus_videoroom_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
2042
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2043
                return;
2044
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2045
        if(!session) {
2046
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2047
                return;
2048
        }
2049
        if(session->destroyed)
2050
                return;
2051
        if(session->participant_type == janus_videoroom_p_type_subscriber) {
2052
                /* A listener sent some RTCP, check what it is and if we need to forward it to the publisher */
2053
                janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
2054
                if(!l->video)
2055
                        return;        /* The only feedback we handle is video related anyway... */
2056
                if(janus_rtcp_has_fir(buf, len)) {
2057
                        /* We got a FIR, forward it to the publisher */
2058
                        if(l && l->feed) {
2059
                                janus_videoroom_participant *p = l->feed;
2060
                                if(p && p->session) {
2061
                                        char rtcpbuf[20];
2062
                                        memset(rtcpbuf, 0, 20);
2063
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &p->fir_seq);
2064
                                        JANUS_LOG(LOG_VERB, "Got a FIR from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2065
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 20);
2066
                                }
2067
                        }
2068
                }
2069
                if(janus_rtcp_has_pli(buf, len)) {
2070
                        /* We got a PLI, forward it to the publisher */
2071
                        if(l && l->feed) {
2072
                                janus_videoroom_participant *p = l->feed;
2073
                                if(p && p->session) {
2074
                                        char rtcpbuf[12];
2075
                                        memset(rtcpbuf, 0, 12);
2076
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2077
                                        JANUS_LOG(LOG_VERB, "Got a PLI from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2078
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 12);
2079
                                }
2080
                        }
2081
                }
2082
                uint64_t bitrate = janus_rtcp_get_remb(buf, len);
2083
                if(bitrate > 0) {
2084
                        /* FIXME We got a REMB from this listener, should we do something about it? */
2085
                }
2086
        }
2087
}
2088

    
2089
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len) {
2090
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2091
                return;
2092
        if(buf == NULL || len <= 0)
2093
                return;
2094
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2095
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2096
                return;
2097
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2098
        /* Get a string out of the data */
2099
        char *text = g_malloc0(len+1);
2100
        memcpy(text, buf, len);
2101
        *(text+len) = '\0';
2102
        JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
2103
        g_slist_foreach(participant->listeners, janus_videoroom_relay_data_packet, text);
2104
        g_free(text);
2105
}
2106

    
2107
void janus_videoroom_slow_link(janus_plugin_session *handle, int uplink, int video) {
2108
        /* The core is informing us that our peer got too many NACKs, are we pushing media too hard? */
2109
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2110
                return;
2111
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2112
        if(!session || session->destroyed || !session->participant)
2113
                return;
2114
        /* Check if it's an uplink (publisher) or downlink (viewer) issue */
2115
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2116
                if(!uplink) {
2117
                        janus_videoroom_participant *publisher = (janus_videoroom_participant *)session->participant;
2118
                        if(publisher) {
2119
                                /* Send an event on the handle to notify the application: it's
2120
                                 * up to the application to then choose a policy and enforce it */
2121
                                json_t *event = json_object();
2122
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2123
                                /* Also add info on what the current bitrate cap is */
2124
                                uint64_t bitrate = (publisher->bitrate ? publisher->bitrate : 256*1024);
2125
                                json_object_set_new(event, "current-bitrate", json_integer(bitrate));
2126
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2127
                                json_decref(event);
2128
                        }
2129
                } else {
2130
                        JANUS_LOG(LOG_WARN, "Got a slow uplink on a VideoRoom publisher? Weird, because it doesn't receive media...\n");
2131
                }
2132
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2133
                if(uplink) {
2134
                        janus_videoroom_listener *viewer = (janus_videoroom_listener *)session->participant;
2135
                        if(viewer) {
2136
                                /* Send an event on the handle to notify the application: it's
2137
                                 * up to the application to then choose a policy and enforce it */
2138
                                json_t *event = json_object();
2139
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2140
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2141
                                json_decref(event);
2142
                        }
2143
                } else {
2144
                        JANUS_LOG(LOG_WARN, "Got a slow downlink on a VideoRoom viewer? Weird, because it doesn't send media...\n");
2145
                }
2146
        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
2147
                /* TBD. */
2148
        }
2149
}
2150

    
2151
static void janus_videoroom_recorder_create(janus_videoroom_participant *participant, gboolean audio, gboolean video) {
2152
        char filename[255];
2153
        gint64 now = janus_get_real_time();
2154
        if(audio) {
2155
                memset(filename, 0, 255);
2156
                if(participant->recording_base) {
2157
                        /* Use the filename and path we have been provided */
2158
                        g_snprintf(filename, 255, "%s-audio", participant->recording_base);
2159
                        participant->arc = janus_recorder_create(participant->room->rec_dir,
2160
                                janus_videoroom_audiocodec_name(participant->room->acodec), filename);
2161
                        if(participant->arc == NULL) {
2162
                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2163
                        }
2164
                } else {
2165
                        /* Build a filename */
2166
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-audio",
2167
                                participant->room->room_id, participant->user_id, now);
2168
                        participant->arc = janus_recorder_create(participant->room->rec_dir,
2169
                                janus_videoroom_audiocodec_name(participant->room->acodec), filename);
2170
                        if(participant->arc == NULL) {
2171
                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2172
                        }
2173
                }
2174
        }
2175
        if(video) {
2176
                memset(filename, 0, 255);
2177
                if(participant->recording_base) {
2178
                        /* Use the filename and path we have been provided */
2179
                        g_snprintf(filename, 255, "%s-video", participant->recording_base);
2180
                        participant->vrc = janus_recorder_create(participant->room->rec_dir,
2181
                                janus_videoroom_videocodec_name(participant->room->vcodec), filename);
2182
                        if(participant->vrc == NULL) {
2183
                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2184
                        }
2185
                } else {
2186
                        /* Build a filename */
2187
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-video",
2188
                                participant->room->room_id, participant->user_id, now);
2189
                        participant->vrc = janus_recorder_create(participant->room->rec_dir,
2190
                                janus_videoroom_videocodec_name(participant->room->vcodec), filename);
2191
                        if(participant->vrc == NULL) {
2192
                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2193
                        }
2194
                }
2195
        }
2196
}
2197

    
2198
static void janus_videoroom_recorder_close(janus_videoroom_participant *participant) {
2199
        if(participant->arc) {
2200
                janus_recorder_close(participant->arc);
2201
                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", participant->arc->filename ? participant->arc->filename : "??");
2202
                janus_recorder_free(participant->arc);
2203
        }
2204
        participant->arc = NULL;
2205
        if(participant->vrc) {
2206
                janus_recorder_close(participant->vrc);
2207
                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", participant->vrc->filename ? participant->vrc->filename : "??");
2208
                janus_recorder_free(participant->vrc);
2209
        }
2210
        participant->vrc = NULL;
2211
}
2212

    
2213
void janus_videoroom_hangup_media(janus_plugin_session *handle) {
2214
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
2215
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2216
                return;
2217
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2218
        if(!session) {
2219
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2220
                return;
2221
        }
2222
        session->started = FALSE;
2223
        if(session->destroyed)
2224
                return;
2225
        if(g_atomic_int_add(&session->hangingup, 1))
2226
                return;
2227
        /* Send an event to the browser and tell the PeerConnection is over */
2228
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2229
                /* This publisher just 'unpublished' */
2230
                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2231
                if(participant->sdp)
2232
                        g_free(participant->sdp);
2233
                participant->sdp = NULL;
2234
                participant->firefox = FALSE;
2235
                participant->audio_active = FALSE;
2236
                participant->video_active = FALSE;
2237
                participant->remb_startup = 4;
2238
                participant->remb_latest = 0;
2239
                participant->fir_latest = 0;
2240
                participant->fir_seq = 0;
2241
                /* Get rid of the recorders, if available */
2242
                janus_mutex_lock(&participant->rec_mutex);
2243
                janus_videoroom_recorder_close(participant);
2244
                janus_mutex_unlock(&participant->rec_mutex);
2245
                janus_mutex_lock(&participant->listeners_mutex);
2246
                while(participant->listeners) {
2247
                        janus_videoroom_listener *l = (janus_videoroom_listener *)participant->listeners->data;
2248
                        if(l) {
2249
                                participant->listeners = g_slist_remove(participant->listeners, l);
2250
                                l->feed = NULL;
2251
                        }
2252
                }
2253
                janus_mutex_unlock(&participant->listeners_mutex);
2254
                janus_videoroom_leave_or_unpublish(participant, FALSE);
2255
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2256
                /* Get rid of listener */
2257
                janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2258
                if(listener) {
2259
                        listener->paused = TRUE;
2260
                        janus_videoroom_participant *publisher = listener->feed;
2261
                        if(publisher != NULL) {
2262
                                janus_mutex_lock(&publisher->listeners_mutex);
2263
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
2264
                                janus_mutex_unlock(&publisher->listeners_mutex);
2265
                                listener->feed = NULL;
2266
                        }
2267
                }
2268
                /* TODO Should we close the handle as well? */
2269
        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
2270
                /* Do the same, but for all sub-listener */
2271
                janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
2272
                GSList *ps = listener->listeners;
2273
                while(ps) {
2274
                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
2275
                        if(l) {
2276
                                l->paused = TRUE;
2277
                                janus_videoroom_participant *publisher = l->feed;
2278
                                if(publisher != NULL) {
2279
                                        janus_mutex_lock(&publisher->listeners_mutex);
2280
                                        publisher->listeners = g_slist_remove(publisher->listeners, l);
2281
                                        janus_mutex_unlock(&publisher->listeners_mutex);
2282
                                        l->feed = NULL;
2283
                                }
2284
                        }
2285
                        /* TODO Should we close the handle as well? */
2286
                        ps = ps->next;
2287
                }
2288
                /* TODO Should we close the handle as well? */
2289
        }
2290
}
2291

    
2292
static void janus_videoroom_sdp_a_format(char *mline, int mline_size, janus_videoroom_audiocodec acodec, int pt, const char *audio_mode) {
2293
        switch(acodec) {
2294
                case JANUS_VIDEOROOM_OPUS:
2295
                        g_snprintf(mline, mline_size, sdp_a_template_opus,
2296
                                pt,                                                /* Opus payload type */
2297
                                audio_mode,
2298
                                pt);                                                 /* Opus payload type */
2299
                        break;
2300
                case JANUS_VIDEOROOM_ISAC_32K:
2301
                        g_snprintf(mline, mline_size, sdp_a_template_isac32,
2302
                                pt,                                                /* ISAC 32K payload type */
2303
                                audio_mode,
2304
                                pt);                                         /* ISAC 32K payload type */
2305
                        break;
2306
                case JANUS_VIDEOROOM_ISAC_16K:
2307
                        g_snprintf(mline, mline_size, sdp_a_template_isac16,
2308
                                pt,                                                /* ISAC 16K payload type */
2309
                                audio_mode,
2310
                                pt);                                                /* ISAC 16K payload type */
2311
                        break;
2312
                case JANUS_VIDEOROOM_PCMU:
2313
                        g_snprintf(mline, mline_size, sdp_a_template_pcmu,
2314
                                pt,                                                /* PCMU payload type */
2315
                                audio_mode,
2316
                                pt);                                                /* PCMU payload type */
2317
                        break;
2318
                case JANUS_VIDEOROOM_PCMA:
2319
                        g_snprintf(mline, mline_size, sdp_a_template_pcma,
2320
                                pt,                                                /* PCMA payload type */
2321
                                audio_mode,
2322
                                pt);                                                /* PCMA payload type */
2323
                        break;
2324
                default:
2325
                        /* Shouldn't happen */
2326
                        mline[0] = '\0';
2327
                        break;
2328
        }
2329
}
2330

    
2331
static void janus_videoroom_sdp_v_format(char *mline, int mline_size, janus_videoroom_videocodec vcodec, int pt, int b, const char *video_mode) {
2332
        switch(vcodec) {
2333
                case JANUS_VIDEOROOM_VP8:
2334
                        g_snprintf(mline, mline_size, sdp_v_template_vp8,
2335
                                pt,                                                        /* payload type */
2336
                                b,                                                                /* Bandwidth */
2337
                                video_mode,                                                /* The publisher gets a recvonly or inactive back */
2338
                                pt,                                                 /* payload type */
2339
                                pt,                                                 /* payload type */
2340
                                pt,                                                 /* payload type */
2341
                                pt,                                                 /* payload type */
2342
                                pt);                                                 /* payload type */
2343
                        break;
2344
                case JANUS_VIDEOROOM_VP9:
2345
                        g_snprintf(mline, mline_size, sdp_v_template_vp9,
2346
                                pt,                                                        /* payload type */
2347
                                b,                                                                /* Bandwidth */
2348
                                video_mode,                                                /* The publisher gets a recvonly or inactive back */
2349
                                pt,                                                 /* payload type */
2350
                                pt,                                                 /* payload type */
2351
                                pt,                                                 /* payload type */
2352
                                pt,                                                 /* payload type */
2353
                                pt);                                                 /* payload type */
2354
                        break;
2355
                case JANUS_VIDEOROOM_H264:
2356
                        g_snprintf(mline, mline_size, sdp_v_template_h264,
2357
                                pt,                                                        /* payload type */
2358
                                b,                                                                /* Bandwidth */
2359
                                video_mode,                                                /* The publisher gets a recvonly or inactive back */
2360
                                pt,                                                 /* payload type */
2361
                                pt,                                                 /* payload type */
2362
                                pt,                                                 /* payload type */
2363
                                pt,                                                 /* payload type */
2364
                                pt,                                                 /* payload type */
2365
                                pt);                                                 /* payload type */
2366
                        break;
2367
                default:
2368
                        /* Shouldn't happen */
2369
                        mline[0] = '\0';
2370
                        break;
2371
        }
2372
}
2373

    
2374
/* Thread to handle incoming messages */
2375
static void *janus_videoroom_handler(void *data) {
2376
        JANUS_LOG(LOG_VERB, "Joining VideoRoom handler thread\n");
2377
        janus_videoroom_message *msg = NULL;
2378
        int error_code = 0;
2379
        char error_cause[512];
2380
        json_t *root = NULL;
2381
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
2382
                msg = g_async_queue_pop(messages);
2383
                if(msg == NULL)
2384
                        continue;
2385
                if(msg == &exit_message)
2386
                        break;
2387
                if(msg->handle == NULL) {
2388
                        janus_videoroom_message_free(msg);
2389
                        continue;
2390
                }
2391
                janus_videoroom_session *session = NULL;
2392
                janus_mutex_lock(&sessions_mutex);
2393
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
2394
                        session = (janus_videoroom_session *)msg->handle->plugin_handle;
2395
                }
2396
                janus_mutex_unlock(&sessions_mutex);
2397
                if(!session) {
2398
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2399
                        janus_videoroom_message_free(msg);
2400
                        continue;
2401
                }
2402
                if(session->destroyed) {
2403
                        janus_videoroom_message_free(msg);
2404
                        continue;
2405
                }
2406
                /* Handle request */
2407
                error_code = 0;
2408
                root = NULL;
2409
                if(msg->message == NULL) {
2410
                        JANUS_LOG(LOG_ERR, "No message??\n");
2411
                        error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
2412
                        g_snprintf(error_cause, 512, "%s", "No message??");
2413
                        goto error;
2414
                }
2415
                root = msg->message;
2416
                /* Get the request first */
2417
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
2418
                        error_code, error_cause, TRUE,
2419
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2420
                if(error_code != 0)
2421
                        goto error;
2422
                json_t *request = json_object_get(root, "request");
2423
                const char *request_text = json_string_value(request);
2424
                json_t *event = NULL;
2425
                /* 'create' and 'destroy' are handled synchronously: what kind of participant is this session referring to? */
2426
                if(session->participant_type == janus_videoroom_p_type_none) {
2427
                        JANUS_LOG(LOG_VERB, "Configuring new participant\n");
2428
                        /* Not configured yet, we need to do this now */
2429
                        if(strcasecmp(request_text, "join") && strcasecmp(request_text, "joinandconfigure")) {
2430
                                JANUS_LOG(LOG_ERR, "Invalid request on unconfigured participant\n");
2431
                                error_code = JANUS_VIDEOROOM_ERROR_JOIN_FIRST;
2432
                                g_snprintf(error_cause, 512, "Invalid request on unconfigured participant");
2433
                                goto error;
2434
                        }
2435
                        JANUS_VALIDATE_JSON_OBJECT(root, join_parameters,
2436
                                error_code, error_cause, TRUE,
2437
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2438
                        if(error_code != 0)
2439
                                goto error;
2440
                        janus_mutex_lock(&rooms_mutex);
2441
                        janus_videoroom *videoroom = NULL;
2442
                        error_code = janus_videoroom_access_room(root, FALSE, TRUE, &videoroom, error_cause, sizeof(error_cause));
2443
                        janus_mutex_unlock(&rooms_mutex);
2444
                        if(error_code != 0)
2445
                                goto error;
2446
                        json_t *ptype = json_object_get(root, "ptype");
2447
                        const char *ptype_text = json_string_value(ptype);
2448
                        if(!strcasecmp(ptype_text, "publisher")) {
2449
                                JANUS_LOG(LOG_VERB, "Configuring new publisher\n");
2450
                                JANUS_VALIDATE_JSON_OBJECT(root, publisher_parameters,
2451
                                        error_code, error_cause, TRUE,
2452
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2453
                                if(error_code != 0)
2454
                                        goto error;
2455
                                json_t *display = json_object_get(root, "display");
2456
                                const char *display_text = display ? json_string_value(display) : NULL;
2457
                                guint64 user_id = 0;
2458
                                json_t *id = json_object_get(root, "id");
2459
                                if(id) {
2460
                                        user_id = json_integer_value(id);
2461
                                        janus_mutex_lock(&videoroom->participants_mutex);
2462
                                        if(g_hash_table_lookup(videoroom->participants, &user_id) != NULL) {
2463
                                                janus_mutex_unlock(&videoroom->participants_mutex);
2464
                                                /* User ID already taken */
2465
                                                JANUS_LOG(LOG_ERR, "User ID %"SCNu64" already exists\n", user_id);
2466
                                                error_code = JANUS_VIDEOROOM_ERROR_ID_EXISTS;
2467
                                                g_snprintf(error_cause, 512, "User ID %"SCNu64" already exists", user_id);
2468
                                                goto error;
2469
                                        }
2470
                                        janus_mutex_unlock(&videoroom->participants_mutex);
2471
                                }
2472
                                if(user_id == 0) {
2473
                                        /* Generate a random ID */
2474
                                        janus_mutex_lock(&videoroom->participants_mutex);
2475
                                        while(user_id == 0) {
2476
                                                user_id = janus_random_uint64();
2477
                                                if(g_hash_table_lookup(videoroom->participants, &user_id) != NULL) {
2478
                                                        /* User ID already taken, try another one */
2479
                                                        user_id = 0;
2480
                                                }
2481
                                        }
2482
                                        janus_mutex_unlock(&videoroom->participants_mutex);
2483
                                }
2484
                                JANUS_LOG(LOG_VERB, "  -- Publisher ID: %"SCNu64"\n", user_id);
2485
                                json_t *audio = NULL, *video = NULL, *bitrate = NULL, *record = NULL, *recfile = NULL;
2486
                                if(!strcasecmp(request_text, "joinandconfigure")) {
2487
                                        /* Also configure (or publish a new feed) audio/video/bitrate for this new publisher */
2488
                                        /* join_parameters were validated earlier. */
2489
                                        audio = json_object_get(root, "audio");
2490
                                        video = json_object_get(root, "video");
2491
                                        bitrate = json_object_get(root, "bitrate");
2492
                                        record = json_object_get(root, "record");
2493
                                        recfile = json_object_get(root, "filename");
2494
                                }
2495
                                janus_videoroom_participant *publisher = g_malloc0(sizeof(janus_videoroom_participant));
2496
                                publisher->session = session;
2497
                                publisher->room = videoroom;
2498
                                publisher->user_id = user_id;
2499
                                publisher->display = display_text ? g_strdup(display_text) : NULL;
2500
                                publisher->sdp = NULL;                /* We'll deal with this later */
2501
                                publisher->audio = FALSE;        /* We'll deal with this later */
2502
                                publisher->video = FALSE;        /* We'll deal with this later */
2503
                                publisher->data = FALSE;        /* We'll deal with this later */
2504
                                publisher->audio_active = FALSE;
2505
                                publisher->video_active = FALSE;
2506
                                publisher->recording_active = FALSE;
2507
                                publisher->recording_base = NULL;
2508
                                publisher->arc = NULL;
2509
                                publisher->vrc = NULL;
2510
                                janus_mutex_init(&publisher->rec_mutex);
2511
                                publisher->firefox = FALSE;
2512
                                publisher->bitrate = videoroom->bitrate;
2513
                                publisher->listeners = NULL;
2514
                                janus_mutex_init(&publisher->listeners_mutex);
2515
                                publisher->audio_pt = OPUS_PT;
2516
                                switch(videoroom->acodec) {
2517
                                        case JANUS_VIDEOROOM_OPUS:
2518
                                                publisher->audio_pt = OPUS_PT;
2519
                                                break;
2520
                                        case JANUS_VIDEOROOM_ISAC_32K:
2521
                                                publisher->audio_pt = ISAC32_PT;
2522
                                                break;
2523
                                        case JANUS_VIDEOROOM_ISAC_16K:
2524
                                                publisher->audio_pt = ISAC16_PT;
2525
                                                break;
2526
                                        case JANUS_VIDEOROOM_PCMU:
2527
                                                publisher->audio_pt = PCMU_PT;
2528
                                                break;
2529
                                        case JANUS_VIDEOROOM_PCMA:
2530
                                                publisher->audio_pt = PCMA_PT;
2531
                                                break;
2532
                                        default:
2533
                                                /* Shouldn't happen */
2534
                                                publisher->audio_pt = OPUS_PT;
2535
                                                break;
2536
                                }
2537
                                switch(videoroom->vcodec) {
2538
                                        case JANUS_VIDEOROOM_VP8:
2539
                                                publisher->video_pt = VP8_PT;
2540
                                                break;
2541
                                        case JANUS_VIDEOROOM_VP9:
2542
                                                publisher->video_pt = VP9_PT;
2543
                                                break;
2544
                                        case JANUS_VIDEOROOM_H264:
2545
                                                publisher->video_pt = H264_PT;
2546
                                                break;
2547
                                        default:
2548
                                                /* Shouldn't happen */
2549
                                                publisher->video_pt = VP8_PT;
2550
                                                break;
2551
                                }
2552
                                publisher->audio_ssrc = janus_random_uint32();
2553
                                publisher->video_ssrc = janus_random_uint32();
2554
                                publisher->remb_startup = 4;
2555
                                publisher->remb_latest = 0;
2556
                                publisher->fir_latest = 0;
2557
                                publisher->fir_seq = 0;
2558
                                janus_mutex_init(&publisher->rtp_forwarders_mutex);
2559
                                publisher->rtp_forwarders = g_hash_table_new_full(NULL, NULL, NULL, (GDestroyNotify)janus_rtp_forwarder_free_helper);
2560
                                publisher->udp_sock = -1;
2561
                                /* In case we also wanted to configure */
2562
                                if(audio) {
2563
                                        publisher->audio_active = json_is_true(audio);
2564
                                        JANUS_LOG(LOG_VERB, "Setting audio property: %s (room %"SCNu64", user %"SCNu64")\n", publisher->audio_active ? "true" : "false", publisher->room->room_id, publisher->user_id);
2565
                                }
2566
                                if(video) {
2567
                                        publisher->video_active = json_is_true(video);
2568
                                        JANUS_LOG(LOG_VERB, "Setting video property: %s (room %"SCNu64", user %"SCNu64")\n", publisher->video_active ? "true" : "false", publisher->room->room_id, publisher->user_id);
2569
                                }
2570
                                if(bitrate) {
2571
                                        publisher->bitrate = json_integer_value(bitrate);
2572
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", publisher->bitrate, publisher->room->room_id, publisher->user_id);
2573
                                }
2574
                                if(record) {
2575
                                        publisher->recording_active = json_is_true(record);
2576
                                        JANUS_LOG(LOG_VERB, "Setting record property: %s (room %"SCNu64", user %"SCNu64")\n", publisher->recording_active ? "true" : "false", publisher->room->room_id, publisher->user_id);
2577
                                }
2578
                                if(recfile) {
2579
                                        publisher->recording_base = g_strdup(json_string_value(recfile));
2580
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", publisher->recording_base, publisher->room->room_id, publisher->user_id);
2581
                                }
2582
                                /* Done */
2583
                                session->participant_type = janus_videoroom_p_type_publisher;
2584
                                session->participant = publisher;
2585
                                /* Return a list of all available publishers (those with an SDP available, that is) */
2586
                                json_t *list = json_array();
2587
                                GHashTableIter iter;
2588
                                gpointer value;
2589
                                janus_mutex_lock(&videoroom->participants_mutex);
2590
                                g_hash_table_insert(videoroom->participants, janus_uint64_dup(publisher->user_id), publisher);
2591
                                g_hash_table_iter_init(&iter, videoroom->participants);
2592
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2593
                                        janus_videoroom_participant *p = value;
2594
                                        if(p == publisher || !p->sdp || !p->session->started) {
2595
                                                continue;
2596
                                        }
2597
                                        json_t *pl = json_object();
2598
                                        json_object_set_new(pl, "id", json_integer(p->user_id));
2599
                                        if(p->display)
2600
                                                json_object_set_new(pl, "display", json_string(p->display));
2601
                                        json_array_append_new(list, pl);
2602
                                }
2603
                                janus_mutex_unlock(&videoroom->participants_mutex);
2604
                                event = json_object();
2605
                                json_object_set_new(event, "videoroom", json_string("joined"));
2606
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
2607
                                json_object_set_new(event, "description", json_string(videoroom->room_name));
2608
                                json_object_set_new(event, "id", json_integer(user_id));
2609
                                json_object_set_new(event, "publishers", list);
2610
                        } else if(!strcasecmp(ptype_text, "listener")) {
2611
                                JANUS_LOG(LOG_VERB, "Configuring new listener\n");
2612
                                /* This is a new listener */
2613
                                JANUS_VALIDATE_JSON_OBJECT(root, listener_parameters,
2614
                                        error_code, error_cause, TRUE,
2615
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2616
                                if(error_code != 0)
2617
                                        goto error;
2618
                                json_t *feed = json_object_get(root, "feed");
2619
                                guint64 feed_id = json_integer_value(feed);
2620
                                json_t *audio = json_object_get(root, "audio");
2621
                                json_t *video = json_object_get(root, "video");
2622
                                json_t *data = json_object_get(root, "data");
2623
                                janus_mutex_lock(&videoroom->participants_mutex);
2624
                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &feed_id);
2625
                                janus_mutex_unlock(&videoroom->participants_mutex);
2626
                                if(publisher == NULL || publisher->sdp == NULL) {
2627
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2628
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2629
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2630
                                        goto error;
2631
                                } else {
2632
                                        janus_videoroom_listener *listener = g_malloc0(sizeof(janus_videoroom_listener));
2633
                                        listener->session = session;
2634
                                        listener->room = videoroom;
2635
                                        listener->feed = publisher;
2636
                                        /* Initialize the listener context */
2637
                                        listener->context.a_last_ssrc = 0;
2638
                                        listener->context.a_last_ssrc = 0;
2639
                                        listener->context.a_last_ts = 0;
2640
                                        listener->context.a_base_ts = 0;
2641
                                        listener->context.a_base_ts_prev = 0;
2642
                                        listener->context.v_last_ssrc = 0;
2643
                                        listener->context.v_last_ts = 0;
2644
                                        listener->context.v_base_ts = 0;
2645
                                        listener->context.v_base_ts_prev = 0;
2646
                                        listener->context.a_last_seq = 0;
2647
                                        listener->context.a_base_seq = 0;
2648
                                        listener->context.a_base_seq_prev = 0;
2649
                                        listener->context.v_last_seq = 0;
2650
                                        listener->context.v_base_seq = 0;
2651
                                        listener->context.v_base_seq_prev = 0;
2652
                                        listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
2653
                                        if(!publisher->audio)
2654
                                                listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
2655
                                        listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
2656
                                        if(!publisher->video)
2657
                                                listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
2658
                                        listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
2659
                                        if(!publisher->data)
2660
                                                listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
2661
                                        listener->paused = TRUE;        /* We need an explicit start from the listener */
2662
                                        listener->parent = NULL;
2663
                                        session->participant = listener;
2664
                                        janus_mutex_lock(&publisher->listeners_mutex);
2665
                                        publisher->listeners = g_slist_append(publisher->listeners, listener);
2666
                                        janus_mutex_unlock(&publisher->listeners_mutex);
2667
                                        event = json_object();
2668
                                        json_object_set_new(event, "videoroom", json_string("attached"));
2669
                                        json_object_set_new(event, "room", json_integer(videoroom->room_id));
2670
                                        json_object_set_new(event, "id", json_integer(feed_id));
2671
                                        if(publisher->display)
2672
                                                json_object_set_new(event, "display", json_string(publisher->display));
2673
                                        session->participant_type = janus_videoroom_p_type_subscriber;
2674
                                        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
2675
                                        /* Negotiate by sending the selected publisher SDP back */
2676
                                        if(publisher->sdp != NULL) {
2677
                                                json_t *jsep = json_pack("{ssss}", "type", "offer", "sdp", publisher->sdp);
2678
                                                /* How long will the gateway take to push the event? */
2679
                                                g_atomic_int_set(&session->hangingup, 0);
2680
                                                gint64 start = janus_get_monotonic_time();
2681
                                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, jsep);
2682
                                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
2683
                                                json_decref(event);
2684
                                                json_decref(jsep);
2685
                                                janus_videoroom_message_free(msg);
2686
                                                continue;
2687
                                        }
2688
                                }
2689
                        } else if(!strcasecmp(ptype_text, "muxed-listener")) {
2690
                                /* This is a new Multiplexed listener */
2691
                                JANUS_LOG(LOG_INFO, "Configuring new Multiplexed listener\n");
2692
                                /* Any feed we want to attach to already? */
2693
                                GList *list = NULL;
2694
                                JANUS_VALIDATE_JSON_OBJECT(root, feeds_parameters,
2695
                                        error_code, error_cause, TRUE,
2696
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2697
                                if(error_code != 0)
2698
                                        goto error;
2699
                                json_t *feeds = json_object_get(root, "feeds");
2700
                                if(feeds && json_array_size(feeds) > 0) {
2701
                                        unsigned int i = 0;
2702
                                        int problem = 0;
2703
                                        for(i=0; i<json_array_size(feeds); i++) {
2704
                                                if(videoroom->destroyed) {
2705
                                                        problem = 1;
2706
                                                        JANUS_LOG(LOG_ERR, "Room destroyed");
2707
                                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2708
                                                        g_snprintf(error_cause, 512, "Room destroyed");
2709
                                                        break;
2710
                                                }
2711
                                                json_t *feed = json_array_get(feeds, i);
2712
                                                if(!feed || !json_is_integer(feed)) {
2713
                                                        problem = 1;
2714
                                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
2715
                                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2716
                                                        g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
2717
                                                        break;
2718
                                                }
2719
                                                uint64_t feed_id = json_integer_value(feed);
2720
                                                janus_mutex_lock(&videoroom->participants_mutex);
2721
                                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &feed_id);
2722
                                                janus_mutex_unlock(&videoroom->participants_mutex);
2723
                                                if(publisher == NULL) { //~ || publisher->sdp == NULL) {
2724
                                                        /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
2725
                                                        problem = 1;
2726
                                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2727
                                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2728
                                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2729
                                                        break;
2730
                                                }
2731
                                                list = g_list_prepend(list, GUINT_TO_POINTER(feed_id));
2732
                                                JANUS_LOG(LOG_INFO, "  -- Subscribing to feed %"SCNu64"\n", feed_id);
2733
                                        }
2734
                                        if(problem) {
2735
                                                goto error;
2736
                                        }
2737
                                }
2738
                                /* Allocate listener */
2739
                                janus_videoroom_listener_muxed *listener = g_malloc0(sizeof(janus_videoroom_listener_muxed));
2740
                                listener->session = session;
2741
                                listener->room = videoroom;
2742
                                session->participant_type = janus_videoroom_p_type_subscriber_muxed;
2743
                                session->participant = listener;
2744
                                /* Ack that we created the listener */
2745
                                event = json_object();
2746
                                json_object_set_new(event, "videoroom", json_string("muxed-created"));
2747
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
2748
                                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
2749
                                /* How long will the gateway take to push the event? */
2750
                                gint64 start = janus_get_monotonic_time();
2751
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
2752
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
2753
                                json_decref(event);
2754
                                /* Attach to feeds if needed */
2755
                                if(list != NULL) {
2756
                                        JANUS_LOG(LOG_INFO, "Subscribing to %d feeds\n", g_list_length(list));
2757
                                        list = g_list_reverse(list);
2758
                                        if(videoroom->destroyed || janus_videoroom_muxed_subscribe(listener, list, msg->transaction) < 0) {
2759
                                                JANUS_LOG(LOG_ERR, "Error subscribing!\n");
2760
                                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
2761
                                                g_snprintf(error_cause, 512, "Error subscribing!");
2762
                                                goto error;
2763
                                        }
2764
                                }
2765
                                janus_videoroom_message_free(msg);
2766
                                continue;
2767
                        } else {
2768
                                JANUS_LOG(LOG_ERR, "Invalid element (ptype)\n");
2769
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2770
                                g_snprintf(error_cause, 512, "Invalid element (ptype)");
2771
                                goto error;
2772
                        }
2773
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
2774
                        /* Handle this publisher */
2775
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2776
                        if(participant == NULL) {
2777
                                JANUS_LOG(LOG_ERR, "Invalid participant instance\n");
2778
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2779
                                g_snprintf(error_cause, 512, "Invalid participant instance");
2780
                                goto error;
2781
                        }
2782
                        if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")) {
2783
                                JANUS_LOG(LOG_ERR, "Already in as a publisher on this handle\n");
2784
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
2785
                                g_snprintf(error_cause, 512, "Already in as a publisher on this handle");
2786
                                goto error;
2787
                        } else if(!strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish")) {
2788
                                if(!strcasecmp(request_text, "publish") && participant->sdp) {
2789
                                        JANUS_LOG(LOG_ERR, "Can't publish, already published\n");
2790
                                        error_code = JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED;
2791
                                        g_snprintf(error_cause, 512, "Can't publish, already published");
2792
                                        goto error;
2793
                                }
2794
                                /* Configure (or publish a new feed) audio/video/bitrate for this publisher */
2795
                                JANUS_VALIDATE_JSON_OBJECT(root, publish_parameters,
2796
                                        error_code, error_cause, TRUE,
2797
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2798
                                if(error_code != 0)
2799
                                        goto error;
2800
                                json_t *audio = json_object_get(root, "audio");
2801
                                json_t *video = json_object_get(root, "video");
2802
                                json_t *bitrate = json_object_get(root, "bitrate");
2803
                                json_t *record = json_object_get(root, "record");
2804
                                json_t *recfile = json_object_get(root, "filename");
2805
                                if(audio) {
2806
                                        participant->audio_active = json_is_true(audio);
2807
                                        JANUS_LOG(LOG_VERB, "Setting audio property: %s (room %"SCNu64", user %"SCNu64")\n", participant->audio_active ? "true" : "false", participant->room->room_id, participant->user_id);
2808
                                }
2809
                                if(video) {
2810
                                        participant->video_active = json_is_true(video);
2811
                                        JANUS_LOG(LOG_VERB, "Setting video property: %s (room %"SCNu64", user %"SCNu64")\n", participant->video_active ? "true" : "false", participant->room->room_id, participant->user_id);
2812
                                }
2813
                                if(bitrate) {
2814
                                        participant->bitrate = json_integer_value(bitrate);
2815
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", participant->bitrate, participant->room->room_id, participant->user_id);
2816
                                        /* Send a new REMB */
2817
                                        if(session->started)
2818
                                                participant->remb_latest = janus_get_monotonic_time();
2819
                                        char rtcpbuf[24];
2820
                                        janus_rtcp_remb((char *)(&rtcpbuf), 24, participant->bitrate ? participant->bitrate : 256*1024);
2821
                                        gateway->relay_rtcp(msg->handle, 1, rtcpbuf, 24);
2822
                                }
2823
                                janus_mutex_lock(&participant->rec_mutex);
2824
                                gboolean prev_recording_active = participant->recording_active;
2825
                                if(record) {
2826
                                        participant->recording_active = json_is_true(record);
2827
                                        JANUS_LOG(LOG_VERB, "Setting record property: %s (room %"SCNu64", user %"SCNu64")\n", participant->recording_active ? "true" : "false", participant->room->room_id, participant->user_id);
2828
                                }
2829
                                if(recfile) {
2830
                                        participant->recording_base = g_strdup(json_string_value(recfile));
2831
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", participant->recording_base, participant->room->room_id, participant->user_id);
2832
                                }
2833
                                /* Do we need to do something with the recordings right now? */
2834
                                if(participant->recording_active != prev_recording_active) {
2835
                                        /* Something changed */
2836
                                        if(!participant->recording_active) {
2837
                                                /* Not recording (anymore?) */
2838
                                                janus_videoroom_recorder_close(participant);
2839
                                        } else if(participant->recording_active && participant->sdp) {
2840
                                                /* We've started recording, send a PLI/FIR and go on */
2841
                                                janus_videoroom_recorder_create(participant, strstr(participant->sdp, "m=audio") != NULL, strstr(participant->sdp, "m=video") != NULL);
2842
                                                if(strstr(participant->sdp, "m=video")) {
2843
                                                        /* Send a FIR */
2844
                                                        char buf[20];
2845
                                                        memset(buf, 0, 20);
2846
                                                        janus_rtcp_fir((char *)&buf, 20, &participant->fir_seq);
2847
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending FIR to %"SCNu64" (%s)\n",
2848
                                                                participant->user_id, participant->display ? participant->display : "??");
2849
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 20);
2850
                                                        /* Send a PLI too, just in case... */
2851
                                                        memset(buf, 0, 12);
2852
                                                        janus_rtcp_pli((char *)&buf, 12);
2853
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending PLI to %"SCNu64" (%s)\n",
2854
                                                                participant->user_id, participant->display ? participant->display : "??");
2855
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 12);
2856
                                                }
2857
                                        }
2858
                                }
2859
                                janus_mutex_unlock(&participant->rec_mutex);
2860
                                /* Done */
2861
                                event = json_object();
2862
                                json_object_set_new(event, "videoroom", json_string("event"));
2863
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
2864
                                json_object_set_new(event, "configured", json_string("ok"));
2865
                        } else if(!strcasecmp(request_text, "unpublish")) {
2866
                                /* This participant wants to unpublish */
2867
                                if(!participant->sdp) {
2868
                                        JANUS_LOG(LOG_ERR, "Can't unpublish, not published\n");
2869
                                        error_code = JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED;
2870
                                        g_snprintf(error_cause, 512, "Can't unpublish, not published");
2871
                                        goto error;
2872
                                }
2873
                                /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
2874
                                gateway->close_pc(session->handle);
2875
                                /* Done */
2876
                                event = json_object();
2877
                                json_object_set_new(event, "videoroom", json_string("event"));
2878
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
2879
                                json_object_set_new(event, "unpublished", json_string("ok"));
2880
                        } else if(!strcasecmp(request_text, "leave")) {
2881
                                /* This publisher is leaving, tell everybody */
2882
                                janus_videoroom_leave_or_unpublish(participant, TRUE);
2883
                                /* Done */
2884
                                participant->audio_active = FALSE;
2885
                                participant->video_active = FALSE;
2886
                                session->started = FALSE;
2887
                                //~ session->destroy = TRUE;
2888
                        } else {
2889
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
2890
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
2891
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
2892
                                goto error;
2893
                        }
2894
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2895
                        /* Handle this listener */
2896
                        janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2897
                        if(listener == NULL) {
2898
                                JANUS_LOG(LOG_ERR, "Invalid listener instance\n");
2899
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2900
                                g_snprintf(error_cause, 512, "Invalid listener instance");
2901
                                goto error;
2902
                        }
2903
                        if(!strcasecmp(request_text, "join")) {
2904
                                JANUS_LOG(LOG_ERR, "Already in as a listener on this handle\n");
2905
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
2906
                                g_snprintf(error_cause, 512, "Already in as a listener on this handle");
2907
                                goto error;
2908
                        } else if(!strcasecmp(request_text, "start")) {
2909
                                /* Start/restart receiving the publisher streams */
2910
                                janus_videoroom_participant *publisher = listener->feed;
2911
                                listener->paused = FALSE;
2912
                                event = json_object();
2913
                                json_object_set_new(event, "videoroom", json_string("event"));
2914
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2915
                                json_object_set_new(event, "started", json_string("ok"));
2916
                                if(publisher) {
2917
                                        /* Send a FIR */
2918
                                        char buf[20];
2919
                                        memset(buf, 0, 20);
2920
                                        janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
2921
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
2922
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
2923
                                        /* Send a PLI too, just in case... */
2924
                                        memset(buf, 0, 12);
2925
                                        janus_rtcp_pli((char *)&buf, 12);
2926
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
2927
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
2928
                                }
2929
                        } else if(!strcasecmp(request_text, "configure")) {
2930
                                JANUS_VALIDATE_JSON_OBJECT(root, configure_parameters,
2931
                                        error_code, error_cause, TRUE,
2932
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2933
                                if(error_code != 0)
2934
                                        goto error;
2935
                                json_t *audio = json_object_get(root, "audio");
2936
                                json_t *video = json_object_get(root, "video");
2937
                                json_t *data = json_object_get(root, "data");
2938
                                /* Update the audio/video/data flags, if set */
2939
                                janus_videoroom_participant *publisher = listener->feed;
2940
                                if(publisher) {
2941
                                        if(audio && publisher->audio)
2942
                                                listener->audio = json_is_true(audio);
2943
                                        if(video && publisher->video)
2944
                                                listener->video = json_is_true(video);
2945
                                        if(data && publisher->data)
2946
                                                listener->data = json_is_true(data);
2947
                                }
2948
                                event = json_object();
2949
                                json_object_set_new(event, "videoroom", json_string("event"));
2950
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2951
                                json_object_set_new(event, "configured", json_string("ok"));
2952
                        } else if(!strcasecmp(request_text, "pause")) {
2953
                                /* Stop receiving the publisher streams for a while */
2954
                                listener->paused = TRUE;
2955
                                event = json_object();
2956
                                json_object_set_new(event, "videoroom", json_string("event"));
2957
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2958
                                json_object_set_new(event, "paused", json_string("ok"));
2959
                        } else if(!strcasecmp(request_text, "switch")) {
2960
                                /* This listener wants to switch to a different publisher */
2961
                                JANUS_VALIDATE_JSON_OBJECT(root, listener_parameters,
2962
                                        error_code, error_cause, TRUE,
2963
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2964
                                if(error_code != 0)
2965
                                        goto error;
2966
                                json_t *feed = json_object_get(root, "feed");
2967
                                guint64 feed_id = json_integer_value(feed);
2968
                                json_t *audio = json_object_get(root, "audio");
2969
                                json_t *video = json_object_get(root, "video");
2970
                                json_t *data = json_object_get(root, "data");
2971
                                if(!listener->room) {
2972
                                        JANUS_LOG(LOG_ERR, "Room Destroyed \n");
2973
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2974
                                        g_snprintf(error_cause, 512, "No such room ");
2975
                                        goto error;
2976
                                }
2977
                                if(listener->room->destroyed) {
2978
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")\n", listener->room->room_id);
2979
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2980
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
2981
                                        goto error;
2982
                                }
2983
                                janus_mutex_lock(&listener->room->participants_mutex);
2984
                                janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, &feed_id);
2985
                                janus_mutex_unlock(&listener->room->participants_mutex);
2986
                                if(publisher == NULL || publisher->sdp == NULL) {
2987
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2988
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2989
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2990
                                        goto error;
2991
                                }
2992
                                gboolean paused = listener->paused;
2993
                                listener->paused = TRUE;
2994
                                /* Unsubscribe from the previous publisher */
2995
                                janus_videoroom_participant *prev_feed = listener->feed;
2996
                                if(prev_feed) {
2997
                                        janus_mutex_lock(&prev_feed->listeners_mutex);
2998
                                        prev_feed->listeners = g_slist_remove(prev_feed->listeners, listener);
2999
                                        janus_mutex_unlock(&prev_feed->listeners_mutex);
3000
                                        listener->feed = NULL;
3001
                                }
3002
                                /* Subscribe to the new one */
3003
                                listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
3004
                                if(!publisher->audio)
3005
                                        listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
3006
                                listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
3007
                                if(!publisher->video)
3008
                                        listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
3009
                                listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
3010
                                if(!publisher->data)
3011
                                        listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
3012
                                janus_mutex_lock(&publisher->listeners_mutex);
3013
                                publisher->listeners = g_slist_append(publisher->listeners, listener);
3014
                                janus_mutex_unlock(&publisher->listeners_mutex);
3015
                                listener->feed = publisher;
3016
                                /* Send a FIR to the new publisher */
3017
                                char buf[20];
3018
                                memset(buf, 0, 20);
3019
                                janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3020
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3021
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3022
                                /* Send a PLI too, just in case... */
3023
                                memset(buf, 0, 12);
3024
                                janus_rtcp_pli((char *)&buf, 12);
3025
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3026
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3027
                                /* Done */
3028
                                listener->paused = paused;
3029
                                event = json_object();
3030
                                json_object_set_new(event, "videoroom", json_string("event"));
3031
                                json_object_set_new(event, "switched", json_string("ok"));
3032
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3033
                                json_object_set_new(event, "id", json_integer(feed_id));
3034
                                if(publisher->display)
3035
                                        json_object_set_new(event, "display", json_string(publisher->display));
3036
                        } else if(!strcasecmp(request_text, "leave")) {
3037
                                janus_videoroom_participant *publisher = listener->feed;
3038
                                if(publisher != NULL) {
3039
                                        janus_mutex_lock(&publisher->listeners_mutex);
3040
                                        publisher->listeners = g_slist_remove(publisher->listeners, listener);
3041
                                        janus_mutex_unlock(&publisher->listeners_mutex);
3042
                                        listener->feed = NULL;
3043
                                }
3044
                                event = json_object();
3045
                                json_object_set_new(event, "videoroom", json_string("event"));
3046
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3047
                                json_object_set_new(event, "left", json_string("ok"));
3048
                                session->started = FALSE;
3049
                        } else {
3050
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3051
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3052
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3053
                                goto error;
3054
                        }
3055
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
3056
                        /* Handle this Multiplexed listener */
3057
                        janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
3058
                        if(listener == NULL) {
3059
                                JANUS_LOG(LOG_ERR, "Invalid Multiplexed listener instance\n");
3060
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
3061
                                g_snprintf(error_cause, 512, "Invalid Multiplexed listener instance");
3062
                                goto error;
3063
                        }
3064
                        if(!strcasecmp(request_text, "join")) {
3065
                                JANUS_LOG(LOG_ERR, "Already in as a Multiplexed listener on this handle\n");
3066
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
3067
                                g_snprintf(error_cause, 512, "Already in as a Multiplexed listener on this handle");
3068
                                goto error;
3069
                        } else if(!strcasecmp(request_text, "add")) {
3070
                                /* Add new streams to subscribe to */
3071
                                GList *list = NULL;
3072
                                JANUS_VALIDATE_JSON_OBJECT(root, feeds_parameters,
3073
                                        error_code, error_cause, TRUE,
3074
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3075
                                if(error_code != 0)
3076
                                        goto error;
3077
                                json_t *feeds = json_object_get(root, "feeds");
3078
                                unsigned int i = 0;
3079
                                int problem = 0;
3080
                                if(!listener->room) {
3081
                                        JANUS_LOG(LOG_ERR, "Room Destroyed ");
3082
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3083
                                        g_snprintf(error_cause, 512, "No such room ");
3084
                                        goto error;
3085
                                }
3086
                                if(listener->room->destroyed) {
3087
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")", listener->room->room_id);
3088
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3089
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
3090
                                        goto error;
3091
                                }
3092
                                for(i=0; i<json_array_size(feeds); i++) {
3093
                                        json_t *feed = json_array_get(feeds, i);
3094
                                        if(listener->room->destroyed) {
3095
                                                problem = 1;
3096
                                                JANUS_LOG(LOG_ERR, "Room destroyed");
3097
                                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3098
                                                g_snprintf(error_cause, 512, "Room destroyed");
3099
                                                break;
3100
                                        }
3101
                                        if(!feed || !json_is_integer(feed)) {
3102
                                                problem = 1;
3103
                                                JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
3104
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3105
                                                g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
3106
                                                break;
3107
                                        }
3108
                                        uint64_t feed_id = json_integer_value(feed);
3109
                                        janus_mutex_lock(&listener->room->participants_mutex);
3110
                                        janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, &feed_id);
3111
                                        janus_mutex_unlock(&listener->room->participants_mutex);
3112
                                        if(publisher == NULL) { //~ || publisher->sdp == NULL) {
3113
                                                /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
3114
                                                problem = 1;
3115
                                                JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3116
                                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3117
                                                g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3118
                                                break;
3119
                                        }
3120
                                        list = g_list_prepend(list, GUINT_TO_POINTER(feed_id));
3121
                                }
3122
                                if(problem) {
3123
                                        goto error;
3124
                                }
3125
                                list = g_list_reverse(list);
3126
                                if(janus_videoroom_muxed_subscribe(listener, list, msg->transaction) < 0) {
3127
                                        JANUS_LOG(LOG_ERR, "Error subscribing!\n");
3128
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3129
                                        g_snprintf(error_cause, 512, "Error subscribing!");
3130
                                        goto error;
3131
                                }
3132
                                janus_videoroom_message_free(msg);
3133
                                continue;
3134
                        } else if(!strcasecmp(request_text, "remove")) {
3135
                                /* Remove subscribed streams */
3136
                                GList *list = NULL;
3137
                                JANUS_VALIDATE_JSON_OBJECT(root, feeds_parameters,
3138
                                        error_code, error_cause, TRUE,
3139
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3140
                                if(error_code != 0)
3141
                                        goto error;
3142
                                json_t *feeds = json_object_get(root, "feeds");
3143
                                unsigned int i = 0;
3144
                                int error = 0;
3145
                                for(i=0; i<json_array_size(feeds); i++) {
3146
                                        json_t *feed = json_array_get(feeds, i);
3147
                                        if(!feed || !json_is_integer(feed)) {
3148
                                                error = 1;
3149
                                                break;
3150
                                        }
3151
                                        list = g_list_prepend(list, GUINT_TO_POINTER(json_integer_value(feed)));
3152
                                }
3153
                                if(error) {
3154
                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
3155
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3156
                                        g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
3157
                                        goto error;
3158
                                }
3159
                                list = g_list_reverse(list);
3160
                                
3161
                                if(!listener->room) {
3162
                                        JANUS_LOG(LOG_ERR, "Error unsubscribing!\n");
3163
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3164
                                        g_snprintf(error_cause, 512, "Error unsubscribing!");
3165
                                        goto error;
3166
                                }
3167
                                if(janus_videoroom_muxed_unsubscribe(listener, list, msg->transaction) < 0) {
3168
                                        JANUS_LOG(LOG_ERR, "Error unsubscribing!\n");
3169
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3170
                                        g_snprintf(error_cause, 512, "Error unsubscribing!");
3171
                                        goto error;
3172
                                }
3173
                                janus_videoroom_message_free(msg);
3174
                                continue;
3175
                        } else if(!strcasecmp(request_text, "start")) {
3176
                                /* Start/restart receiving the publishers streams */
3177
                                /* TODO */
3178
                                event = json_object();
3179
                                json_object_set_new(event, "videoroom", json_string("event"));
3180
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3181
                                json_object_set_new(event, "started", json_string("ok"));
3182
                                //~ /* Send a FIR */
3183
                                //~ char buf[20];
3184
                                //~ memset(buf, 0, 20);
3185
                                //~ janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3186
                                //~ JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3187
                                //~ gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3188
                                //~ /* Send a PLI too, just in case... */
3189
                                //~ memset(buf, 0, 12);
3190
                                //~ janus_rtcp_pli((char *)&buf, 12);
3191
                                //~ JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3192
                                //~ gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3193
                        } else if(!strcasecmp(request_text, "pause")) {
3194
                                /* Stop receiving the publishers streams for a while */
3195
                                /* TODO */
3196
                                event = json_object();
3197
                                json_object_set_new(event, "videoroom", json_string("event"));
3198
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3199
                                json_object_set_new(event, "paused", json_string("ok"));
3200
                        } else if(!strcasecmp(request_text, "leave")) {
3201
                                /* TODO */
3202
                                event = json_object();
3203
                                json_object_set_new(event, "videoroom", json_string("event"));
3204
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3205
                                json_object_set_new(event, "left", json_string("ok"));
3206
                                session->started = FALSE;
3207
                        } else {
3208
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3209
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3210
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3211
                                goto error;
3212
                        }
3213
                }
3214

    
3215
                /* Prepare JSON event */
3216
                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3217
                /* Any SDP to handle? */
3218
                const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
3219
                const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
3220
                if(!msg_sdp) {
3221
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3222
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3223
                        json_decref(event);
3224
                } else {
3225
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
3226
                        const char *type = NULL;
3227
                        if(!strcasecmp(msg_sdp_type, "offer")) {
3228
                                /* We need to answer */
3229
                                type = "answer";
3230
                        } else if(!strcasecmp(msg_sdp_type, "answer")) {
3231
                                /* We got an answer (from a listener?), no need to negotiate */
3232
                                g_atomic_int_set(&session->hangingup, 0);
3233
                                int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3234
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3235
                                json_decref(event);
3236
                                janus_videoroom_message_free(msg);
3237
                                continue;
3238
                        } else {
3239
                                /* TODO We don't support anything else right now... */
3240
                                JANUS_LOG(LOG_ERR, "Unknown SDP type '%s'\n", msg_sdp_type);
3241
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3242
                                g_snprintf(error_cause, 512, "Unknown SDP type '%s'", msg_sdp_type);
3243
                                goto error;
3244
                        }
3245
                        if(session->participant_type != janus_videoroom_p_type_publisher) {
3246
                                /* We shouldn't be here, we always offer ourselves */
3247
                                JANUS_LOG(LOG_ERR, "Only publishers send offers\n");
3248
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3249
                                g_snprintf(error_cause, 512, "Only publishers send offers");
3250
                                goto error;
3251
                        } else {
3252
                                /* This is a new publisher: is there room? */
3253
                                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3254
                                janus_videoroom *videoroom = participant->room;
3255
                                int count = 0;
3256
                                GHashTableIter iter;
3257
                                gpointer value;
3258
                                if(!videoroom) {
3259
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3260
                                        goto error;
3261
                                }
3262
                                if(videoroom->destroyed) {
3263
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3264
                                        goto error;
3265
                                }
3266
                                janus_mutex_lock(&videoroom->participants_mutex);
3267
                                g_hash_table_iter_init(&iter, videoroom->participants);
3268
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3269
                                        janus_videoroom_participant *p = value;
3270
                                        if(p != participant && p->sdp)
3271
                                                count++;
3272
                                }
3273
                                janus_mutex_unlock(&videoroom->participants_mutex);
3274
                                if(count == videoroom->max_publishers) {
3275
                                        participant->audio_active = FALSE;
3276
                                        participant->video_active = FALSE;
3277
                                        JANUS_LOG(LOG_ERR, "Maximum number of publishers (%d) already reached\n", videoroom->max_publishers);
3278
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3279
                                        g_snprintf(error_cause, 512, "Maximum number of publishers (%d) already reached", videoroom->max_publishers);
3280
                                        goto error;
3281
                                }
3282
                                /* Now prepare the SDP to give back */
3283
                                if(strstr(msg_sdp, "Mozilla")) {
3284
                                        participant->firefox = TRUE;
3285
                                }
3286
                                /* Which media are available? */
3287
                                int audio = 0, video = 0, data = 0;
3288
                                const char *audio_mode = NULL, *video_mode = NULL;
3289
                                sdp_parser_t *parser = sdp_parse(sdphome, msg_sdp, strlen(msg_sdp), 0);
3290
                                sdp_session_t *parsed_sdp = sdp_session(parser);
3291
                                if(!parsed_sdp) {
3292
                                        /* Invalid SDP */
3293
                                        JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", sdp_parsing_error(parser));
3294
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3295
                                        g_snprintf(error_cause, 512, "Error parsing SDP: %s", sdp_parsing_error(parser));
3296
                                        sdp_parser_free(parser);
3297
                                        goto error;
3298
                                }
3299
                                sdp_media_t *m = parsed_sdp->sdp_media;
3300
                                while(m) {
3301
                                        if(m->m_type == sdp_media_audio && m->m_port > 0) {
3302
                                                audio++;
3303
                                                participant->audio = TRUE;
3304
                                                if(audio > 1) {
3305
                                                        m = m->m_next;
3306
                                                        continue;
3307
                                                }
3308
                                        } else if(m->m_type == sdp_media_video && m->m_port > 0) {
3309
                                                video++;
3310
                                                participant->video = TRUE;
3311
                                                if(video > 1) {
3312
                                                        m = m->m_next;
3313
                                                        continue;
3314
                                                }
3315
                                        } else if(m->m_type == sdp_media_application && m->m_port > 0) {
3316
                                                data++;
3317
                                                participant->data = TRUE;
3318
                                                if(data > 1) {
3319
                                                        m = m->m_next;
3320
                                                        continue;
3321
                                                }
3322
                                        }
3323
                                        if(m->m_type != sdp_media_application) {
3324
                                                /* What is the direction? */
3325
                                                switch(m->m_mode) {
3326
                                                        case sdp_recvonly:
3327
                                                                /* If we're getting a 'recvonly' publisher, we're going to answer with 'inactive' */
3328
                                                        case sdp_inactive:
3329
                                                                if(m->m_type == sdp_media_audio) {
3330
                                                                        audio_mode = "inactive";
3331
                                                                } else {
3332
                                                                        video_mode = "inactive";
3333
                                                                }
3334
                                                                break;
3335
                                                        case sdp_sendonly:
3336
                                                                /* What we expect, turn this into 'recvonly' */
3337
                                                        case sdp_sendrecv:
3338
                                                        default:
3339
                                                                if(m->m_type == sdp_media_audio) {
3340
                                                                        audio_mode = "recvonly";
3341
                                                                } else {
3342
                                                                        video_mode = "recvonly";
3343
                                                                }
3344
                                                                break;
3345
                                                }
3346
                                        }
3347
                                        m = m->m_next;
3348
                                }
3349
                                sdp_parser_free(parser);
3350
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send an audio stream\n", audio ? "is" : "is NOT");
3351
                                int opus_pt = 0, isac32_pt = 0, isac16_pt = 0, pcmu_pt = 0, pcma_pt = 0,
3352
                                        vp8_pt = 0, vp9_pt = 0, h264_pt = 0;
3353
                                if(audio) {
3354
                                        JANUS_LOG(LOG_VERB, "  -- Will answer with media direction '%s'\n", audio_mode);
3355
                                        opus_pt = janus_get_codec_pt(msg_sdp, "opus");
3356
                                        if(opus_pt > 0) {
3357
                                                JANUS_LOG(LOG_VERB, "  -- -- Opus payload type is %d\n", opus_pt);
3358
                                        }
3359
                                        isac32_pt = janus_get_codec_pt(msg_sdp, "isac32");
3360
                                        if(isac32_pt > 0) {
3361
                                                JANUS_LOG(LOG_VERB, "  -- -- ISAC 32K payload type is %d\n", isac32_pt);
3362
                                        }
3363
                                        isac16_pt = janus_get_codec_pt(msg_sdp, "isac16");
3364
                                        if(isac16_pt > 0) {
3365
                                                JANUS_LOG(LOG_VERB, "  -- -- ISAC 16K payload type is %d\n", isac16_pt);
3366
                                        }
3367
                                        pcmu_pt = janus_get_codec_pt(msg_sdp, "pcmu");
3368
                                        if(pcmu_pt > 0) {
3369
                                                JANUS_LOG(LOG_VERB, "  -- -- PCMU payload type is %d\n", pcmu_pt);
3370
                                        }
3371
                                        pcma_pt = janus_get_codec_pt(msg_sdp, "pcma");
3372
                                        if(pcma_pt > 0) {
3373
                                                JANUS_LOG(LOG_VERB, "  -- -- PCMA payload type is %d\n", pcma_pt);
3374
                                        }
3375
                                }
3376
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send a video stream\n", video ? "is" : "is NOT");
3377
                                if(video) {
3378
                                        JANUS_LOG(LOG_VERB, "  -- Will answer with media direction '%s'\n", video_mode);
3379
                                        vp8_pt = janus_get_codec_pt(msg_sdp, "vp8");
3380
                                        if(vp8_pt > 0) {
3381
                                                JANUS_LOG(LOG_VERB, "  -- -- VP8 payload type is %d\n", vp8_pt);
3382
                                        }
3383
                                        vp9_pt = janus_get_codec_pt(msg_sdp, "vp9");
3384
                                        if(vp9_pt > 0) {
3385
                                                JANUS_LOG(LOG_VERB, "  -- -- VP9 payload type is %d\n", vp9_pt);
3386
                                        }
3387
                                        h264_pt = janus_get_codec_pt(msg_sdp, "h264");
3388
                                        if(h264_pt > 0) {
3389
                                                JANUS_LOG(LOG_VERB, "  -- -- H264 payload type is %d\n", h264_pt);
3390
                                        }
3391
                                }
3392
                                JANUS_LOG(LOG_VERB, "The publisher %s going to open a data channel\n", data ? "is" : "is NOT");
3393
                                /* Also add a bandwidth SDP attribute if we're capping the bitrate in the room */
3394
                                int b = 0;
3395
                                if(participant->firefox)        /* Don't add any b=AS attribute for Chrome */
3396
                                        b = (int)(videoroom->bitrate/1000);
3397
                                char sdp[1280], audio_mline[256], video_mline[512], data_mline[256];
3398
                                char *newsdp = NULL;
3399
                                int res = 0;
3400
                                int pass = 0;
3401
                                for(pass = 1; pass <= 2; pass++) {
3402
                                        if(pass == 2) {
3403
                                                /* Now turn the SDP into what we'll send subscribers, using the static payload types for making switching easier */
3404
                                                if(audio_mode && strcmp(audio_mode, "inactive"))
3405
                                                        /* The publisher gets a recvonly or inactive back */
3406
                                                        /* Subscribers gets a sendonly or inactive back */
3407
                                                        audio_mode = "sendonly";
3408
                                                if(video_mode && strcmp(video_mode, "inactive"))
3409
                                                        video_mode = "sendonly";
3410
                                        }
3411
                                        audio_mline[0] = '\0';
3412
                                        if(audio) {
3413
                                                int pt = -1;
3414
                                                switch(videoroom->acodec) {
3415
                                                        case JANUS_VIDEOROOM_OPUS:
3416
                                                                if(opus_pt >= 0)
3417
                                                                        pt = (pass == 1 ? opus_pt : OPUS_PT);
3418
                                                                break;
3419
                                                        case JANUS_VIDEOROOM_ISAC_32K:
3420
                                                                if(isac32_pt >= 0)
3421
                                                                        pt = (pass == 1 ? isac32_pt : ISAC32_PT);
3422
                                                                break;
3423
                                                        case JANUS_VIDEOROOM_ISAC_16K:
3424
                                                                if(isac16_pt >= 0)
3425
                                                                        pt = (pass == 1 ? isac16_pt : ISAC16_PT);
3426
                                                                break;
3427
                                                        case JANUS_VIDEOROOM_PCMU:
3428
                                                                if(pcmu_pt >= 0)
3429
                                                                        pt = (pass == 1 ? pcmu_pt : PCMU_PT);
3430
                                                                break;
3431
                                                        case JANUS_VIDEOROOM_PCMA:
3432
                                                                if(pcma_pt >= 0)
3433
                                                                        pt = (pass == 1 ? pcma_pt : PCMA_PT);
3434
                                                                break;
3435
                                                        default:
3436
                                                                /* Shouldn't happen */
3437
                                                                break;
3438
                                                }
3439
                                                if(pass == 1 && pt < 0)
3440
                                                        JANUS_LOG(LOG_WARN, "Videoroom is forcing %s, but publisher didn't offer any... rejecting audio\n", janus_videoroom_audiocodec_name(videoroom->acodec));
3441
                                                if(pt >= 0)
3442
                                                        janus_videoroom_sdp_a_format(audio_mline, 256, videoroom->acodec, pt, audio_mode);
3443
                                                if(audio_mline[0] == '\0' && pass == 1) {
3444
                                                        /* Remove "pass == 1" if the listener also should get a line with port=0. */
3445
                                                        g_snprintf(audio_mline, 256, "m=audio 0 RTP/SAVPF 0\r\n");
3446
                                                }
3447
                                        }
3448
                                        video_mline[0] = '\0';
3449
                                        if(video) {
3450
                                                int pt = -1;
3451
                                                switch(videoroom->vcodec) {
3452
                                                        case JANUS_VIDEOROOM_VP8:
3453
                                                                if(vp8_pt >= 0)
3454
                                                                        pt = (pass == 1 ? vp8_pt : VP8_PT);
3455
                                                                break;
3456
                                                        case JANUS_VIDEOROOM_VP9:
3457
                                                                if(vp9_pt >= 0)
3458
                                                                        pt = (pass == 1 ? vp9_pt : VP9_PT);
3459
                                                                break;
3460
                                                        case JANUS_VIDEOROOM_H264:
3461
                                                                if(h264_pt >= 0)
3462
                                                                        pt = (pass == 1 ? h264_pt : H264_PT);
3463
                                                                break;
3464
                                                        default:
3465
                                                                /* Shouldn't happen */
3466
                                                                break;
3467
                                                }
3468
                                                if(pass == 1 && pt < 0)
3469
                                                        JANUS_LOG(LOG_WARN, "Videoroom is forcing %s, but publisher didn't offer any... rejecting video\n", janus_videoroom_videocodec_name(videoroom->vcodec));
3470
                                                if(pt >= 0)
3471
                                                        janus_videoroom_sdp_v_format(video_mline, 512, videoroom->vcodec, pt, b, video_mode);
3472
                                                if(video_mline[0] == '\0' && pass == 1) {
3473
                                                        /* Remove "pass == 1" if the listener also should get a line with port=0. */
3474
                                                        g_snprintf(video_mline, 512, "m=video 0 RTP/SAVPF 0\r\n");
3475
                                                }
3476
                                        }
3477
                                        if(data) {
3478
                                                g_snprintf(data_mline, 256, sdp_d_template);
3479
                                        } else {
3480
                                                data_mline[0] = '\0';
3481
                                        }
3482
                                        g_snprintf(sdp, 1280, sdp_template,
3483
                                                janus_get_real_time(),                        /* We need current time here */
3484
                                                janus_get_real_time(),                        /* We need current time here */
3485
                                                participant->room->room_name,        /* Video room name */
3486
                                                audio_mline,                                        /* Audio m-line, if any */
3487
                                                video_mline,                                        /* Video m-line, if any */
3488
                                                data_mline);                                        /* Data channel m-line, if any */
3489
                                        newsdp = g_strdup(sdp);
3490
                                        if(video && b == 0) {
3491
                                                /* Remove useless bandwidth attribute */
3492
                                                newsdp = janus_string_replace(newsdp, "b=AS:0\r\n", "");
3493
                                        }
3494
                                        if(pass == 2)
3495
                                                break;
3496
                                        /* Is this room recorded? */
3497
                                        janus_mutex_lock(&participant->rec_mutex);
3498
                                        if(videoroom->record || participant->recording_active) {
3499
                                                janus_videoroom_recorder_create(participant, audio, video);
3500
                                        }
3501
                                        janus_mutex_unlock(&participant->rec_mutex);
3502

    
3503
                                        JANUS_LOG(LOG_VERB, "Handling publisher: turned this into an '%s':\n%s\n", type, newsdp);
3504
                                        json_t *jsep = json_pack("{ssss}", "type", type, "sdp", newsdp);
3505
                                        /* How long will the gateway take to push the event? */
3506
                                        g_atomic_int_set(&session->hangingup, 0);
3507
                                        gint64 start = janus_get_monotonic_time();
3508
                                        res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, jsep);
3509
                                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3510
                                        json_decref(event);
3511
                                        json_decref(jsep);
3512
                                        g_free(newsdp);
3513
                                }
3514
                                /* Done */
3515
                                if(res != JANUS_OK) {
3516
                                        /* TODO Failed to negotiate? We should remove this publisher */
3517
                                        g_free(newsdp);
3518
                                } else {
3519
                                        /* Store the participant's SDP for interested listeners */
3520
                                        participant->sdp = newsdp;
3521
                                        /* We'll wait for the setup_media event before actually telling listeners */
3522
                                }
3523
                        }
3524
                }
3525
                janus_videoroom_message_free(msg);
3526

    
3527
                continue;
3528
                
3529
error:
3530
                {
3531
                        /* Prepare JSON error event */
3532
                        json_t *event = json_object();
3533
                        json_object_set_new(event, "videoroom", json_string("event"));
3534
                        json_object_set_new(event, "error_code", json_integer(error_code));
3535
                        json_object_set_new(event, "error", json_string(error_cause));
3536
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3537
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
3538
                        json_decref(event);
3539
                        janus_videoroom_message_free(msg);
3540
                }
3541
        }
3542
        JANUS_LOG(LOG_VERB, "Leaving VideoRoom handler thread\n");
3543
        return NULL;
3544
}
3545

    
3546

    
3547
/* Multiplexing helpers */
3548
int janus_videoroom_muxed_subscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction) {
3549
        if(!muxed_listener || !feeds)
3550
                return -1;
3551
        janus_mutex_lock(&muxed_listener->listeners_mutex);
3552
        JANUS_LOG(LOG_VERB, "Subscribing to %d feeds\n", g_list_length(feeds));
3553
        janus_videoroom *videoroom = muxed_listener->room;
3554
        GList *ps = feeds;
3555
        json_t *list = json_array();
3556
        int added_feeds = 0;
3557
        while(ps) {
3558
                uint64_t feed_id = GPOINTER_TO_UINT(ps->data);
3559
                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &feed_id);
3560
                if(publisher == NULL) { //~ || publisher->sdp == NULL) {
3561
                        /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
3562
                        JANUS_LOG(LOG_WARN, "No such feed (%"SCNu64"), skipping\n", feed_id);
3563
                        ps = ps->next;
3564
                        continue;
3565
                }
3566
                /* Are we already subscribed? */
3567
                gboolean subscribed = FALSE;
3568
                GSList *ls = muxed_listener->listeners;
3569
                while(ls) {
3570
                        janus_videoroom_listener *l = (janus_videoroom_listener *)ls->data;
3571
                        if(l && (l->feed == publisher)) {
3572
                                subscribed = TRUE;
3573
                                JANUS_LOG(LOG_WARN, "Already subscribed to feed %"SCNu64", skipping\n", feed_id);
3574
                                break;
3575
                        }
3576
                        ls = ls->next;
3577
                }
3578
                if(subscribed) {
3579
                        ps = ps->next;
3580
                        continue;
3581
                }
3582
                janus_videoroom_listener *listener = g_malloc0(sizeof(janus_videoroom_listener));
3583
                listener->session = muxed_listener->session;
3584
                listener->room = videoroom;
3585
                listener->feed = publisher;
3586
                //~ listener->paused = TRUE;        /* We need an explicit start from the listener */
3587
                listener->paused = FALSE;
3588
                listener->parent = muxed_listener;
3589
                janus_mutex_lock(&publisher->listeners_mutex);
3590
                publisher->listeners = g_slist_append(publisher->listeners, listener);
3591
                janus_mutex_unlock(&publisher->listeners_mutex);
3592
                muxed_listener->listeners = g_slist_append(muxed_listener->listeners, listener);
3593
                JANUS_LOG(LOG_VERB, "Now subscribed to %d feeds\n", g_slist_length(muxed_listener->listeners));
3594
                /* Add to feeds in the answer */
3595
                added_feeds++;
3596
                json_t *f = json_object();
3597
                json_object_set_new(f, "id", json_integer(feed_id));
3598
                if(publisher->display)
3599
                        json_object_set_new(f, "display", json_string(publisher->display));
3600
                json_array_append_new(list, f);
3601
                ps = ps->next;
3602
        }
3603
        janus_mutex_unlock(&muxed_listener->listeners_mutex);
3604
        if(added_feeds == 0) {
3605
                /* Nothing changed */
3606
                return 0;
3607
        }
3608
        /* Prepare event */
3609
        json_t *event = json_object();
3610
        json_object_set_new(event, "videoroom", json_string("muxed-attached"));
3611
        json_object_set_new(event, "room", json_integer(videoroom->room_id));
3612
        json_object_set_new(event, "feeds", list);
3613
        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3614
        /* Send the updated offer */
3615
        return janus_videoroom_muxed_offer(muxed_listener, transaction, event);
3616
}
3617

    
3618
int janus_videoroom_muxed_unsubscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction) {
3619
        janus_mutex_lock(&muxed_listener->listeners_mutex);
3620
        JANUS_LOG(LOG_VERB, "Unsubscribing from %d feeds\n", g_list_length(feeds));
3621
        janus_videoroom *videoroom = muxed_listener->room;
3622
        GList *ps = feeds;
3623
        json_t *list = json_array();
3624
        int removed_feeds = 0;
3625
        while(ps) {
3626
                uint64_t feed_id = GPOINTER_TO_UINT(ps->data);
3627
                GSList *ls = muxed_listener->listeners;
3628
                while(ls) {
3629
                        janus_videoroom_listener *listener = (janus_videoroom_listener *)ls->data;
3630
                        if(listener) {
3631
                                janus_videoroom_participant *publisher = listener->feed;
3632
                                if(publisher == NULL || publisher->user_id != feed_id) {
3633
                                        /* Not the publisher we're looking for */
3634
                                        ls = ls->next;
3635
                                        continue;
3636
                                }
3637
                                janus_mutex_lock(&publisher->listeners_mutex);
3638
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
3639
                                janus_mutex_unlock(&publisher->listeners_mutex);
3640
                                listener->feed = NULL;
3641
                                muxed_listener->listeners = g_slist_remove(muxed_listener->listeners, listener);
3642
                                JANUS_LOG(LOG_VERB, "Now subscribed to %d feeds\n", g_slist_length(muxed_listener->listeners));
3643
                                janus_videoroom_listener_free(listener);
3644
                                /* Add to feeds in the answer */
3645
                                removed_feeds++;
3646
                                json_t *f = json_object();
3647
                                json_object_set_new(f, "id", json_integer(feed_id));
3648
                                json_array_append_new(list, f);
3649
                                break;
3650
                        }
3651
                        ls = ls->next;
3652
                }
3653
                ps = ps->next;
3654
        }
3655
        janus_mutex_unlock(&muxed_listener->listeners_mutex);
3656
        if(removed_feeds == 0) {
3657
                /* Nothing changed */
3658
                return 0;
3659
        }
3660
        /* Prepare event */
3661
        json_t *event = json_object();
3662
        json_object_set_new(event, "videoroom", json_string("muxed-detached"));
3663
        json_object_set_new(event, "room", json_integer(videoroom->room_id));
3664
        json_object_set_new(event, "feeds", list);
3665
        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3666
        /* Send the updated offer */
3667
        return janus_videoroom_muxed_offer(muxed_listener, transaction, event);
3668
}
3669

    
3670
int janus_videoroom_muxed_offer(janus_videoroom_listener_muxed *muxed_listener, char *transaction, json_t *event) {
3671
        if(muxed_listener == NULL)
3672
                return -1;
3673
        /* Negotiate by placing a 'muxed' fake attribute for each publisher we subscribed to,
3674
         * that will translate to multiple SSRCs when merging the SDP */
3675
        int audio = 0, video = 0;
3676
        char audio_muxed[1024], video_muxed[1024], temp[255];
3677
        char sdp[2048], audio_mline[512], video_mline[512], data_mline[1];
3678
        data_mline[0] = '\0'; /* Multiplexed streams do not support data channels */
3679
        memset(audio_muxed, 0, 1024);
3680
        memset(video_muxed, 0, 1024);
3681
        memset(audio_mline, 0, 512);
3682
        memset(video_mline, 0, 512);
3683
        /* Prepare the m-lines (FIXME this will result in an audio line even for video-only rooms, but we don't care) */
3684
        int pt = -1;
3685
        switch(muxed_listener->room->acodec) {
3686
                case JANUS_VIDEOROOM_OPUS:
3687
                        pt = OPUS_PT;
3688
                        break;
3689
                case JANUS_VIDEOROOM_ISAC_32K:
3690
                        pt = ISAC32_PT;
3691
                        break;
3692
                case JANUS_VIDEOROOM_ISAC_16K:
3693
                        pt = ISAC16_PT;
3694
                        break;
3695
                case JANUS_VIDEOROOM_PCMU:
3696
                        pt = PCMU_PT;
3697
                        break;
3698
                case JANUS_VIDEOROOM_PCMA:
3699
                        pt = PCMA_PT;
3700
                        break;
3701
                default:
3702
                        /* Shouldn't happen */
3703
                        break;
3704
        }
3705
        janus_videoroom_sdp_a_format(audio_mline, 512, muxed_listener->room->acodec, pt, "sendonly");
3706
        pt = -1;
3707
        switch(muxed_listener->room->vcodec) {
3708
                case JANUS_VIDEOROOM_VP8:
3709
                        pt = VP8_PT;
3710
                        break;
3711
                case JANUS_VIDEOROOM_VP9:
3712
                        pt = VP9_PT;
3713
                        break;
3714
                case JANUS_VIDEOROOM_H264:
3715
                        pt = H264_PT;
3716
                        break;
3717
                default:
3718
                        /* Shouldn't happen */
3719
                        break;
3720
        }
3721
        janus_videoroom_sdp_v_format(video_mline, 512, muxed_listener->room->vcodec, pt, 0, "sendonly");
3722
        /* FIXME Add a fake user/SSRC just to avoid the "Failed to set max send bandwidth for video content" bug */
3723
        g_strlcat(audio_muxed, "a=planb:sfu0 1\r\n", 1024);
3724
        g_strlcat(video_muxed, "a=planb:sfu0 2\r\n", 1024);
3725
        /* Go through all the available publishers */
3726
        GSList *ps = muxed_listener->listeners;
3727
        while(ps) {
3728
                janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
3729
                if(l && l->feed) { //~ && l->feed->sdp) {
3730
                        if(strstr(l->feed->sdp, "m=audio")) {
3731
                                audio++;
3732
                                g_snprintf(temp, 255, "a=planb:sfu%"SCNu64" %"SCNu32"\r\n", l->feed->user_id, l->feed->audio_ssrc);
3733
                                g_strlcat(audio_muxed, temp, 1024);
3734
                        }
3735
                        if(strstr(l->feed->sdp, "m=video")) {
3736
                                video++;
3737
                                g_snprintf(temp, 255, "a=planb:sfu%"SCNu64" %"SCNu32"\r\n", l->feed->user_id, l->feed->video_ssrc);
3738
                                g_strlcat(video_muxed, temp, 1024);
3739
                        }
3740
                }
3741
                ps = ps->next;
3742
        }
3743
        /* Also add a bandwidth SDP attribute if we're capping the bitrate in the room */
3744
        if(audio) {
3745
                g_strlcat(audio_mline, audio_muxed, 2048);
3746
        }
3747
        if(video) {
3748
                g_strlcat(video_mline, video_muxed, 2048);
3749
        }
3750
        g_snprintf(sdp, 2048, sdp_template,
3751
                janus_get_real_time(),                        /* We need current time here */
3752
                janus_get_real_time(),                        /* We need current time here */
3753
                muxed_listener->room->room_name,        /* Video room name */
3754
                audio_mline,                                        /* Audio m-line */
3755
                video_mline,                                        /* Video m-line */
3756
                data_mline);                                        /* Data channel m-line */
3757
        char *newsdp = g_strdup(sdp);
3758
        if(video) {
3759
                /* Remove useless bandwidth attribute, if any */
3760
                newsdp = janus_string_replace(newsdp, "b=AS:0\r\n", "");
3761
        }
3762
        JANUS_LOG(LOG_VERB, "%s", newsdp);
3763
        json_t *jsep = json_pack("{ssss}", "type", "offer", "sdp", newsdp);
3764
        /* How long will the gateway take to push the event? */
3765
        gint64 start = janus_get_monotonic_time();
3766
        int res = gateway->push_event(muxed_listener->session->handle, &janus_videoroom_plugin, transaction, event, jsep);
3767
        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3768
        json_decref(event);
3769
        json_decref(jsep);
3770
        if(res != JANUS_OK) {
3771
                /* TODO Failed to negotiate? We should remove this listener */
3772
        } else {
3773
                /* Let's wait for the setup_media event */
3774
        }
3775
        return 0;
3776
}
3777

    
3778

    
3779
/* Helper to quickly relay RTP packets from publishers to subscribers */
3780
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data) {
3781
        janus_videoroom_rtp_relay_packet *packet = (janus_videoroom_rtp_relay_packet *)user_data;
3782
        if(!packet || !packet->data || packet->length < 1) {
3783
                JANUS_LOG(LOG_ERR, "Invalid packet...\n");
3784
                return;
3785
        }
3786
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3787
        if(!listener || !listener->session) {
3788
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3789
                return;
3790
        }
3791
        if(listener->paused) {
3792
                // JANUS_LOG(LOG_ERR, "This listener paused the stream...\n");
3793
                return;
3794
        }
3795
        janus_videoroom_session *session = listener->session;
3796
        if(!session || !session->handle) {
3797
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3798
                return;
3799
        }
3800
        if(!session->started) {
3801
                // JANUS_LOG(LOG_ERR, "Streaming not started yet for this session...\n");
3802
                return;
3803
        }
3804
        
3805
        /* Make sure there hasn't been a publisher switch by checking the SSRC */
3806
        if(packet->is_video) {
3807
                /* Check if this listener is subscribed to this medium */
3808
                if(!listener->video) {
3809
                        /* Nope, don't relay */
3810
                        return;
3811
                }
3812
                if(ntohl(packet->data->ssrc) != listener->context.v_last_ssrc) {
3813
                        listener->context.v_last_ssrc = ntohl(packet->data->ssrc);
3814
                        listener->context.v_base_ts_prev = listener->context.v_last_ts;
3815
                        listener->context.v_base_ts = packet->timestamp;
3816
                        listener->context.v_base_seq_prev = listener->context.v_last_seq;
3817
                        listener->context.v_base_seq = packet->seq_number;
3818
                }
3819
                /* Compute a coherent timestamp and sequence number */
3820
                listener->context.v_last_ts = (packet->timestamp-listener->context.v_base_ts)
3821
                        + listener->context.v_base_ts_prev+4500;        /* FIXME When switching, we assume 15fps */
3822
                listener->context.v_last_seq = (packet->seq_number-listener->context.v_base_seq)+listener->context.v_base_seq_prev+1;
3823
                /* Update the timestamp and sequence number in the RTP packet, and send it */
3824
                packet->data->timestamp = htonl(listener->context.v_last_ts);
3825
                packet->data->seq_number = htons(listener->context.v_last_seq);
3826
                if(gateway != NULL)
3827
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3828
                /* Restore the timestamp and sequence number to what the publisher set them to */
3829
                packet->data->timestamp = htonl(packet->timestamp);
3830
                packet->data->seq_number = htons(packet->seq_number);
3831
        } else {
3832
                /* Check if this listener is subscribed to this medium */
3833
                if(!listener->audio) {
3834
                        /* Nope, don't relay */
3835
                        return;
3836
                }
3837
                if(ntohl(packet->data->ssrc) != listener->context.a_last_ssrc) {
3838
                        listener->context.a_last_ssrc = ntohl(packet->data->ssrc);
3839
                        listener->context.a_base_ts_prev = listener->context.a_last_ts;
3840
                        listener->context.a_base_ts = packet->timestamp;
3841
                        listener->context.a_base_seq_prev = listener->context.a_last_seq;
3842
                        listener->context.a_base_seq = packet->seq_number;
3843
                }
3844
                /* Compute a coherent timestamp and sequence number */
3845
                listener->context.a_last_ts = (packet->timestamp-listener->context.a_base_ts)
3846
                        + listener->context.a_base_ts_prev+960;        /* FIXME When switching, we assume Opus and so a 960 ts step */
3847
                listener->context.a_last_seq = (packet->seq_number-listener->context.a_base_seq)+listener->context.a_base_seq_prev+1;
3848
                /* Update the timestamp and sequence number in the RTP packet, and send it */
3849
                packet->data->timestamp = htonl(listener->context.a_last_ts);
3850
                packet->data->seq_number = htons(listener->context.a_last_seq);
3851
                if(gateway != NULL)
3852
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3853
                /* Restore the timestamp and sequence number to what the publisher set them to */
3854
                packet->data->timestamp = htonl(packet->timestamp);
3855
                packet->data->seq_number = htons(packet->seq_number);
3856
        }
3857

    
3858
        return;
3859
}
3860

    
3861
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data) {
3862
        char *text = (char *)user_data;
3863
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3864
        if(!listener || !listener->session || !listener->data || listener->paused) {
3865
                return;
3866
        }
3867
        janus_videoroom_session *session = listener->session;
3868
        if(!session || !session->handle) {
3869
                return;
3870
        }
3871
        if(!session->started) {
3872
                return;
3873
        }
3874
        if(gateway != NULL && text != NULL) {
3875
                JANUS_LOG(LOG_VERB, "Forwarding DataChannel message (%zu bytes) to viewer: %s\n", strlen(text), text);
3876
                gateway->relay_data(session->handle, text, strlen(text));
3877
        }
3878
        return;
3879
}
3880

    
3881
/* Helper to free janus_videoroom structs. */
3882
static void janus_videoroom_free(janus_videoroom *room) {
3883
        if(room) {
3884
                janus_mutex_lock(&room->participants_mutex);
3885
                g_free(room->room_name);
3886
                g_free(room->room_secret);
3887
                g_free(room->room_pin);
3888
                g_free(room->rec_dir);
3889
                g_hash_table_unref(room->participants);
3890
                janus_mutex_unlock(&room->participants_mutex);
3891
                janus_mutex_destroy(&room->participants_mutex);
3892
                g_free(room);
3893
                room = NULL;
3894
        }
3895
}
3896

    
3897
static void janus_videoroom_listener_free(janus_videoroom_listener *l) {
3898
        JANUS_LOG(LOG_VERB, "Freeing listener\n");
3899
        g_free(l);
3900
}
3901

    
3902
static void janus_videoroom_muxed_listener_free(janus_videoroom_listener_muxed *l) {
3903
        JANUS_LOG(LOG_VERB, "Freeing muxed-listener\n");
3904
        GSList *ls = l->listeners;
3905
        while(ls) {
3906
                janus_videoroom_listener *listener = (janus_videoroom_listener *)ls->data;
3907
                if(listener) {
3908
                        janus_videoroom_listener_free(listener);