Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videoroom.c @ 5de69b28

History | View | Annotate | Download (168 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|g722 (audio codec to force on publishers, default=opus)
66
videocodec = vp8|vp9|h264 (video codec to force on publishers, default=vp8)
67
audiolevel_ext = yes|no (whether the ssrc-audio-level RTP extension must be
68
        negotiated/used or not for new publishers, default=yes)
69
audiolevel_event = yes|no (whether to emit event to other users or not)
70
audio_active_packets = 100 (number of packets with audio level, default=100, 2 seconds)
71
audio_level_average = 25 (average value of audio level, 127=muted, 0='too loud', default=25)
72
videoorientation_ext = yes|no (whether the video-orientation RTP extension must be
73
        negotiated/used or not for new publishers, default=yes)
74
playoutdelay_ext = yes|no (whether the playout-delay RTP extension must be
75
        negotiated/used or not for new publishers, default=yes)
76
record = true|false (whether this room should be recorded, default=false)
77
rec_dir = <folder where recordings should be stored, when enabled>
78
\endverbatim
79
 *
80
 * Note that recording will work with all codecs except iSAC.
81
 *
82
 * \section sfuapi Video Room API
83
 * 
84
 * The Video Room API supports several requests, some of which are
85
 * synchronous and some asynchronous. There are some situations, though,
86
 * (invalid JSON, invalid request) which will always result in a
87
 * synchronous error response even for asynchronous requests. 
88
 * 
89
 * \c create , \c destroy , \c exists, \c list, \c allowed, \c kick and
90
 * and \c listparticipants are synchronous requests, which means you'll
91
 * get a response directly within the context of the transaction.
92
 * \c create allows you to create a new video room dynamically, as an
93
 * alternative to using the configuration file; \c destroy removes a
94
 * video room and destroys it, kicking all the users out as part of the
95
 * process; \c exists allows you to check whether a specific video room
96
 * exists; finally, \c list lists all the available rooms, while \c
97
 * listparticipants lists all the participants of a specific room and
98
 * their details.
99
 * 
100
 * The \c join , \c joinandconfigure , \c configure , \c publish ,
101
 * \c unpublish , \c start , \c pause , \c switch , \c stop , \c add ,
102
 * \c remove and \c leave requests instead are all asynchronous, which
103
 * means you'll get a notification about their success or failure in
104
 * an event. \c join allows you to join a specific video room, specifying
105
 * whether that specific PeerConnection will be used for publishing or
106
 * watching; \c configure can be used to modify some of the participation
107
 * settings (e.g., bitrate cap); \c joinandconfigure combines the previous
108
 * two requests in a single one (just for publishers); \c publish can be
109
 * used to start sending media to broadcast to the other participants,
110
 * while \c unpublish does the opposite; \c start allows you to start
111
 * receiving media from a publisher you've subscribed to previously by
112
 * means of a \c join , while \c pause pauses the delivery of the media;
113
 * the \c switch request can be used to change the source of the media
114
 * flowing over a specific PeerConnection (e.g., I was watching Alice,
115
 * I want to watch Bob now) without having to create a new handle for
116
 * that; \c stop interrupts a viewer instance; finally, \c leave allows
117
 * you to leave a video room for good.
118
 * 
119
 * Notice that, in general, all users can create rooms. If you want to
120
 * limit this functionality, you can configure an admin \c admin_key in
121
 * the plugin settings. When configured, only "create" requests that
122
 * include the correct \c admin_key value in an "admin_key" property
123
 * will succeed, and will be rejected otherwise.
124
 * 
125
 * Actual API docs: TBD.
126
 * 
127
 * \ingroup plugins
128
 * \ref plugins
129
 */
130

    
131
#include "plugin.h"
132

    
133
#include <jansson.h>
134

    
135
#include "../debug.h"
136
#include "../apierror.h"
137
#include "../config.h"
138
#include "../mutex.h"
139
#include "../rtp.h"
140
#include "../rtcp.h"
141
#include "../record.h"
142
#include "../sdp-utils.h"
143
#include "../utils.h"
144
#include <sys/types.h>
145
#include <sys/socket.h>
146

    
147

    
148
/* Plugin information */
149
#define JANUS_VIDEOROOM_VERSION                        8
150
#define JANUS_VIDEOROOM_VERSION_STRING        "0.0.8"
151
#define JANUS_VIDEOROOM_DESCRIPTION                "This is a plugin implementing a videoconferencing SFU (Selective Forwarding Unit) for Janus, that is an audio/video router."
152
#define JANUS_VIDEOROOM_NAME                        "JANUS VideoRoom plugin"
153
#define JANUS_VIDEOROOM_AUTHOR                        "Meetecho s.r.l."
154
#define JANUS_VIDEOROOM_PACKAGE                        "janus.plugin.videoroom"
155

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

    
178
/* Plugin setup */
179
static janus_plugin janus_videoroom_plugin =
180
        JANUS_PLUGIN_INIT (
181
                .init = janus_videoroom_init,
182
                .destroy = janus_videoroom_destroy,
183

    
184
                .get_api_compatibility = janus_videoroom_get_api_compatibility,
185
                .get_version = janus_videoroom_get_version,
186
                .get_version_string = janus_videoroom_get_version_string,
187
                .get_description = janus_videoroom_get_description,
188
                .get_name = janus_videoroom_get_name,
189
                .get_author = janus_videoroom_get_author,
190
                .get_package = janus_videoroom_get_package,
191
                
192
                .create_session = janus_videoroom_create_session,
193
                .handle_message = janus_videoroom_handle_message,
194
                .setup_media = janus_videoroom_setup_media,
195
                .incoming_rtp = janus_videoroom_incoming_rtp,
196
                .incoming_rtcp = janus_videoroom_incoming_rtcp,
197
                .incoming_data = janus_videoroom_incoming_data,
198
                .slow_link = janus_videoroom_slow_link,
199
                .hangup_media = janus_videoroom_hangup_media,
200
                .destroy_session = janus_videoroom_destroy_session,
201
                .query_session = janus_videoroom_query_session,
202
        );
203

    
204
/* Plugin creator */
205
janus_plugin *create(void) {
206
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_VIDEOROOM_NAME);
207
        return &janus_videoroom_plugin;
208
}
209

    
210
/* Parameter validation */
211
static struct janus_json_parameter request_parameters[] = {
212
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
213
};
214
static struct janus_json_parameter adminkey_parameters[] = {
215
        {"admin_key", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
216
};
217
static struct janus_json_parameter create_parameters[] = {
218
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
219
        {"description", JSON_STRING, 0},
220
        {"is_private", JANUS_JSON_BOOL, 0},
221
        {"allowed", JSON_ARRAY, 0},
222
        {"secret", JSON_STRING, 0},
223
        {"pin", JSON_STRING, 0},
224
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
225
        {"fir_freq", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
226
        {"publishers", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
227
        {"audiocodec", JSON_STRING, 0},
228
        {"videocodec", JSON_STRING, 0},
229
        {"audiolevel_ext", JANUS_JSON_BOOL, 0},
230
        {"audiolevel_event", JANUS_JSON_BOOL, 0},
231
        {"audio_active_packets", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
232
        {"audio_level_average", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
233
        {"videoorient_ext", JANUS_JSON_BOOL, 0},
234
        {"playoutdelay_ext", JANUS_JSON_BOOL, 0},
235
        {"record", JANUS_JSON_BOOL, 0},
236
        {"rec_dir", JSON_STRING, 0},
237
        {"permanent", JANUS_JSON_BOOL, 0}
238
};
239
static struct janus_json_parameter room_parameters[] = {
240
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
241
};
242
static struct janus_json_parameter destroy_parameters[] = {
243
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
244
        {"permanent", JANUS_JSON_BOOL, 0}
245
};
246
static struct janus_json_parameter allowed_parameters[] = {
247
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
248
        {"secret", JSON_STRING, 0},
249
        {"action", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
250
        {"allowed", JSON_ARRAY, 0}
251
};
252
static struct janus_json_parameter kick_parameters[] = {
253
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
254
        {"secret", JSON_STRING, 0},
255
        {"id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
256
};
257
static struct janus_json_parameter join_parameters[] = {
258
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
259
        {"ptype", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
260
        {"audio", JANUS_JSON_BOOL, 0},
261
        {"video", JANUS_JSON_BOOL, 0},
262
        {"data", JANUS_JSON_BOOL, 0},
263
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
264
        {"record", JANUS_JSON_BOOL, 0},
265
        {"filename", JSON_STRING, 0}
266
};
267
static struct janus_json_parameter publish_parameters[] = {
268
        {"audio", JANUS_JSON_BOOL, 0},
269
        {"video", JANUS_JSON_BOOL, 0},
270
        {"data", JANUS_JSON_BOOL, 0},
271
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
272
        {"record", JANUS_JSON_BOOL, 0},
273
        {"filename", JSON_STRING, 0},
274
        {"display", JSON_STRING, 0}
275
};
276
static struct janus_json_parameter rtp_forward_parameters[] = {
277
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
278
        {"publisher_id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
279
        {"video_port", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
280
        {"video_ssrc", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
281
        {"video_pt", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
282
        {"audio_port", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
283
        {"audio_ssrc", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
284
        {"audio_pt", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
285
        {"data_port", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
286
        {"host", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
287
};
288
static struct janus_json_parameter stop_rtp_forward_parameters[] = {
289
        {"room", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
290
        {"publisher_id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
291
        {"stream_id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
292
};
293
static struct janus_json_parameter publisher_parameters[] = {
294
        {"id", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
295
        {"display", JSON_STRING, 0}
296
};
297
static struct janus_json_parameter configure_parameters[] = {
298
        {"audio", JANUS_JSON_BOOL, 0},
299
        {"video", JANUS_JSON_BOOL, 0},
300
        {"data", JANUS_JSON_BOOL, 0}
301
};
302
static struct janus_json_parameter listener_parameters[] = {
303
        {"feed", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE},
304
        {"private_id", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
305
        {"audio", JANUS_JSON_BOOL, 0},
306
        {"video", JANUS_JSON_BOOL, 0},
307
        {"data", JANUS_JSON_BOOL, 0}
308
};
309

    
310
/* Static configuration instance */
311
static janus_config *config = NULL;
312
static const char *config_folder = NULL;
313
static janus_mutex config_mutex;
314

    
315
/* Useful stuff */
316
static volatile gint initialized = 0, stopping = 0;
317
static gboolean notify_events = TRUE;
318
static janus_callbacks *gateway = NULL;
319
static GThread *handler_thread;
320
static GThread *watchdog;
321
static void *janus_videoroom_handler(void *data);
322
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data);
323
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data);
324

    
325
typedef enum janus_videoroom_p_type {
326
        janus_videoroom_p_type_none = 0,
327
        janus_videoroom_p_type_subscriber,                        /* Generic listener/subscriber */
328
        janus_videoroom_p_type_publisher,                        /* Participant/publisher */
329
} janus_videoroom_p_type;
330

    
331
typedef struct janus_videoroom_message {
332
        janus_plugin_session *handle;
333
        char *transaction;
334
        json_t *message;
335
        json_t *jsep;
336
} janus_videoroom_message;
337
static GAsyncQueue *messages = NULL;
338
static janus_videoroom_message exit_message;
339

    
340
static void janus_videoroom_message_free(janus_videoroom_message *msg) {
341
        if(!msg || msg == &exit_message)
342
                return;
343

    
344
        msg->handle = NULL;
345

    
346
        g_free(msg->transaction);
347
        msg->transaction = NULL;
348
        if(msg->message)
349
                json_decref(msg->message);
350
        msg->message = NULL;
351
        if(msg->jsep)
352
                json_decref(msg->jsep);
353
        msg->jsep = NULL;
354

    
355
        g_free(msg);
356
}
357

    
358
/* Payload types we'll offer internally */
359
#define OPUS_PT                111
360
#define ISAC32_PT        104
361
#define ISAC16_PT        103
362
#define PCMU_PT                0
363
#define PCMA_PT                8
364
#define G722_PT                9
365
#define VP8_PT                96
366
#define VP9_PT                101
367
#define H264_PT                107
368

    
369
typedef enum janus_videoroom_audiocodec {
370
        JANUS_VIDEOROOM_OPUS,                /* Publishers will have to use OPUS         */
371
        JANUS_VIDEOROOM_ISAC_32K,        /* Publishers will have to use ISAC 32K */
372
        JANUS_VIDEOROOM_ISAC_16K,        /* Publishers will have to use ISAC 16K */
373
        JANUS_VIDEOROOM_PCMU,                /* Publishers will have to use PCMU 8K         */
374
        JANUS_VIDEOROOM_PCMA,                /* Publishers will have to use PCMA 8K         */
375
        JANUS_VIDEOROOM_G722                /* Publishers will have to use G.722         */
376
} janus_videoroom_audiocodec;
377
static const char *janus_videoroom_audiocodec_name(janus_videoroom_audiocodec acodec) {
378
        switch(acodec) {
379
                case JANUS_VIDEOROOM_OPUS:
380
                        return "opus";
381
                case JANUS_VIDEOROOM_ISAC_32K:
382
                        return "isac32";
383
                case JANUS_VIDEOROOM_ISAC_16K:
384
                        return "isac16";
385
                case JANUS_VIDEOROOM_PCMU:
386
                        return "pcmu";
387
                case JANUS_VIDEOROOM_PCMA:
388
                        return "pcma";
389
                case JANUS_VIDEOROOM_G722:
390
                        return "g722";
391
                default:
392
                        /* Shouldn't happen */
393
                        return "opus";
394
        }
395
}
396
static int janus_videoroom_audiocodec_pt(janus_videoroom_audiocodec acodec) {
397
        switch(acodec) {
398
                case JANUS_VIDEOROOM_OPUS:
399
                        return OPUS_PT;
400
                case JANUS_VIDEOROOM_ISAC_32K:
401
                        return ISAC32_PT;
402
                case JANUS_VIDEOROOM_ISAC_16K:
403
                        return ISAC16_PT;
404
                case JANUS_VIDEOROOM_PCMU:
405
                        return PCMU_PT;
406
                case JANUS_VIDEOROOM_PCMA:
407
                        return PCMA_PT;
408
                case JANUS_VIDEOROOM_G722:
409
                        return G722_PT;
410
                default:
411
                        /* Shouldn't happen */
412
                        return OPUS_PT;
413
        }
414
}
415

    
416
typedef enum janus_videoroom_videocodec {
417
        JANUS_VIDEOROOM_VP8,        /* Publishers will have to use VP8 */
418
        JANUS_VIDEOROOM_VP9,        /* Publishers will have to use VP9 */
419
        JANUS_VIDEOROOM_H264        /* Publishers will have to use H264 */
420
} janus_videoroom_videocodec;
421
static const char *janus_videoroom_videocodec_name(janus_videoroom_videocodec vcodec) {
422
        switch(vcodec) {
423
                case JANUS_VIDEOROOM_VP8:
424
                        return "vp8";
425
                case JANUS_VIDEOROOM_VP9:
426
                        return "vp9";
427
                case JANUS_VIDEOROOM_H264:
428
                        return "h264";
429
                default:
430
                        /* Shouldn't happen */
431
                        return "vp8";
432
        }
433
}
434
static int janus_videoroom_videocodec_pt(janus_videoroom_videocodec vcodec) {
435
        switch(vcodec) {
436
                case JANUS_VIDEOROOM_VP8:
437
                        return VP8_PT;
438
                case JANUS_VIDEOROOM_VP9:
439
                        return VP9_PT;
440
                case JANUS_VIDEOROOM_H264:
441
                        return H264_PT;
442
                default:
443
                        /* Shouldn't happen */
444
                        return VP8_PT;
445
        }
446
}
447

    
448
typedef struct janus_videoroom {
449
        guint64 room_id;                        /* Unique room ID */
450
        gchar *room_name;                        /* Room description */
451
        gchar *room_secret;                        /* Secret needed to manipulate (e.g., destroy) this room */
452
        gchar *room_pin;                        /* Password needed to join this room, if any */
453
        gboolean is_private;                /* Whether this room is 'private' (as in hidden) or not */
454
        int max_publishers;                        /* Maximum number of concurrent publishers */
455
        uint64_t bitrate;                        /* Global bitrate limit */
456
        uint16_t fir_freq;                        /* Regular FIR frequency (0=disabled) */
457
        janus_videoroom_audiocodec acodec;        /* Audio codec to force on publishers*/
458
        janus_videoroom_videocodec vcodec;        /* Video codec to force on publishers*/
459
        gboolean audiolevel_ext;        /* Whether the ssrc-audio-level extension must be negotiated or not for new publishers */
460
        gboolean audiolevel_event;        /* Whether to emit event to other users about audiolevel */
461
        int audio_active_packets;        /* amount of packets with audio level for checkup */
462
        int audio_level_average;        /* average audio level */
463
        gboolean videoorient_ext;        /* Whether the video-orientation extension must be negotiated or not for new publishers */
464
        gboolean playoutdelay_ext;        /* Whether the playout-delay extension must be negotiated or not for new publishers */
465
        gboolean record;                        /* Whether the feeds from publishers in this room should be recorded */
466
        char *rec_dir;                                /* Where to save the recordings of this room, if enabled */
467
        gint64 destroyed;                        /* Value to flag the room for destruction, done lazily */
468
        GHashTable *participants;        /* Map of potential publishers (we get listeners from them) */
469
        GHashTable *private_ids;        /* Map of existing private IDs */
470
        gboolean check_tokens;                /* Whether to check tokens when participants join (see below) */
471
        GHashTable *allowed;                /* Map of participants (as tokens) allowed to join */
472
        janus_mutex participants_mutex;/* Mutex to protect room properties */
473
} janus_videoroom;
474
static GHashTable *rooms;
475
static janus_mutex rooms_mutex;
476
static GList *old_rooms;
477
static char *admin_key = NULL;
478
static void janus_videoroom_free(janus_videoroom *room);
479

    
480
typedef struct janus_videoroom_session {
481
        janus_plugin_session *handle;
482
        janus_videoroom_p_type participant_type;
483
        gpointer participant;
484
        gboolean started;
485
        gboolean stopping;
486
        volatile gint hangingup;
487
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
488
} janus_videoroom_session;
489
static GHashTable *sessions;
490
static GList *old_sessions;
491
static janus_mutex sessions_mutex;
492

    
493
/* a host whose ports gets streamed rtp packets of the corresponding type. */
494
typedef struct janus_videoroom_rtp_forwarder {
495
        gboolean is_video;
496
        gboolean is_data;
497
        uint32_t ssrc;
498
        int payload_type;
499
        struct sockaddr_in serv_addr;
500
} janus_videoroom_rtp_forwarder;
501

    
502
typedef struct janus_videoroom_participant {
503
        janus_videoroom_session *session;
504
        janus_videoroom *room;        /* Room */
505
        guint64 user_id;        /* Unique ID in the room */
506
        guint32 pvt_id;                /* This is sent to the publisher for mapping purposes, but shouldn't be shared with others */
507
        gchar *display;                /* Display name (just for fun) */
508
        gchar *sdp;                        /* The SDP this publisher negotiated, if any */
509
        gboolean audio, video, data;                /* Whether audio, video and/or data is going to be sent by this publisher */
510
        guint32 audio_pt;                /* Audio payload type (Opus) */
511
        guint32 video_pt;                /* Video payload type (depends on room configuration) */
512
        guint32 audio_ssrc;                /* Audio SSRC of this publisher */
513
        guint32 video_ssrc;                /* Video SSRC of this publisher */
514
        guint8 audio_level_extmap_id;        /* Audio level extmap ID */
515
        guint8 video_orient_extmap_id;        /* Video orientation extmap ID */
516
        guint8 playout_delay_extmap_id;        /* Playout delay extmap ID */
517
        gboolean audio_active;
518
        gboolean video_active;
519
        int audio_active_packets; /* participants number of audio packets to accumulate */
520
        int audio_dBov_sum;        /* participants accumulated dBov value for audio level*/
521
        gboolean data_active;
522
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
523
        uint64_t bitrate;
524
        gint64 remb_startup;/* Incremental changes on REMB to reach the target at startup */
525
        gint64 remb_latest;        /* Time of latest sent REMB (to avoid flooding) */
526
        gint64 fir_latest;        /* Time of latest sent FIR (to avoid flooding) */
527
        gint fir_seq;                /* FIR sequence number */
528
        gboolean recording_active;        /* Whether this publisher has to be recorded or not */
529
        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 */
530
        janus_recorder *arc;        /* The Janus recorder instance for this publisher's audio, if enabled */
531
        janus_recorder *vrc;        /* The Janus recorder instance for this publisher's video, if enabled */
532
        janus_recorder *drc;        /* The Janus recorder instance for this publisher's data, if enabled */
533
        janus_mutex rec_mutex;        /* Mutex to protect the recorders from race conditions */
534
        GSList *listeners;
535
        janus_mutex listeners_mutex;
536
        GHashTable *rtp_forwarders;
537
        janus_mutex rtp_forwarders_mutex;
538
        int udp_sock; /* The udp socket on which to forward rtp packets */
539
        gboolean kicked;        /* Whether this participant has been kicked */
540
} janus_videoroom_participant;
541
static void janus_videoroom_participant_free(janus_videoroom_participant *p);
542
static void janus_videoroom_rtp_forwarder_free_helper(gpointer data);
543
static guint32 janus_videoroom_rtp_forwarder_add_helper(janus_videoroom_participant *p,
544
        const gchar* host, int port, int pt, uint32_t ssrc, gboolean is_video, gboolean is_data);
545

    
546
typedef struct janus_videoroom_listener {
547
        janus_videoroom_session *session;
548
        janus_videoroom *room;        /* Room */
549
        janus_videoroom_participant *feed;        /* Participant this listener is subscribed to */
550
        guint32 pvt_id;                /* Private ID of the participant that is subscribing (if available/provided) */
551
        janus_rtp_switching_context context;        /* Needed in case there are publisher switches on this listener */
552
        gboolean audio, video, data;                /* Whether audio, video and/or data must be sent to this publisher */
553
        gboolean paused;
554
} janus_videoroom_listener;
555
static void janus_videoroom_listener_free(janus_videoroom_listener *l);
556

    
557
typedef struct janus_videoroom_rtp_relay_packet {
558
        rtp_header *data;
559
        gint length;
560
        gboolean is_video;
561
        uint32_t timestamp;
562
        uint16_t seq_number;
563
} janus_videoroom_rtp_relay_packet;
564

    
565

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

    
586

    
587
static guint32 janus_videoroom_rtp_forwarder_add_helper(janus_videoroom_participant *p,
588
                const gchar* host, int port, int pt, uint32_t ssrc, gboolean is_video, gboolean is_data) {
589
        if(!p || !host) {
590
                return 0;
591
        }
592
        janus_videoroom_rtp_forwarder *forward = g_malloc0(sizeof(janus_videoroom_rtp_forwarder));
593
        forward->is_video = is_video;
594
        forward->payload_type = pt;
595
        forward->ssrc = ssrc;
596
        forward->is_data = is_data;
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",
608
                is_data ? "data" : (is_video ? "video" : "audio"), p->user_id, host, port, stream_id);
609
        return stream_id;
610
}
611

    
612

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

    
633
static void janus_videoroom_rtp_forwarder_free_helper(gpointer data) {
634
        if(data) {
635
                janus_videoroom_rtp_forwarder* forward = (janus_videoroom_rtp_forwarder*)data;
636
                if(forward) {
637
                        g_free(forward);
638
                        forward = NULL;
639
                }
640
        }
641
}
642

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

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

    
716

    
717
/* Plugin implementation */
718
int janus_videoroom_init(janus_callbacks *callback, const char *config_path) {
719
        if(g_atomic_int_get(&stopping)) {
720
                /* Still stopping from before */
721
                return -1;
722
        }
723
        if(callback == NULL || config_path == NULL) {
724
                /* Invalid arguments */
725
                return -1;
726
        }
727

    
728
        /* Read configuration */
729
        char filename[255];
730
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_VIDEOROOM_PACKAGE);
731
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
732
        config = janus_config_parse(filename);
733
        config_folder = config_path;
734
        if(config != NULL)
735
                janus_config_print(config);
736
        janus_mutex_init(&config_mutex);
737

    
738
        rooms = g_hash_table_new_full(g_int64_hash, g_int64_equal,
739
                (GDestroyNotify)g_free, (GDestroyNotify) janus_videoroom_free);
740
        janus_mutex_init(&rooms_mutex);
741
        sessions = g_hash_table_new(NULL, NULL);
742
        janus_mutex_init(&sessions_mutex);
743

    
744
        messages = g_async_queue_new_full((GDestroyNotify) janus_videoroom_message_free);
745

    
746
        /* This is the callback we'll need to invoke to contact the gateway */
747
        gateway = callback;
748

    
749
        /* Parse configuration to populate the rooms list */
750
        if(config != NULL) {
751
                /* Any admin key to limit who can "create"? */
752
                janus_config_item *key = janus_config_get_item_drilldown(config, "general", "admin_key");
753
                if(key != NULL && key->value != NULL)
754
                        admin_key = g_strdup(key->value);
755
                janus_config_item *events = janus_config_get_item_drilldown(config, "general", "events");
756
                if(events != NULL && events->value != NULL)
757
                        notify_events = janus_is_true(events->value);
758
                if(!notify_events && callback->events_is_enabled()) {
759
                        JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_VIDEOROOM_NAME);
760
                }
761
                /* Iterate on all rooms */
762
                GList *cl = janus_config_get_categories(config);
763
                while(cl != NULL) {
764
                        janus_config_category *cat = (janus_config_category *)cl->data;
765
                        if(cat->name == NULL || !strcasecmp(cat->name, "general")) {
766
                                cl = cl->next;
767
                                continue;
768
                        }
769
                        JANUS_LOG(LOG_VERB, "Adding video room '%s'\n", cat->name);
770
                        janus_config_item *desc = janus_config_get_item(cat, "description");
771
                        janus_config_item *priv = janus_config_get_item(cat, "is_private");
772
                        janus_config_item *secret = janus_config_get_item(cat, "secret");
773
                        janus_config_item *pin = janus_config_get_item(cat, "pin");
774
                        janus_config_item *bitrate = janus_config_get_item(cat, "bitrate");
775
                        janus_config_item *maxp = janus_config_get_item(cat, "publishers");
776
                        janus_config_item *firfreq = janus_config_get_item(cat, "fir_freq");
777
                        janus_config_item *audiocodec = janus_config_get_item(cat, "audiocodec");
778
                        janus_config_item *videocodec = janus_config_get_item(cat, "videocodec");
779
                        janus_config_item *audiolevel_ext = janus_config_get_item(cat, "audiolevel_ext");
780
                        janus_config_item *audiolevel_event = janus_config_get_item(cat, "audiolevel_event");
781
                        janus_config_item *audio_active_packets = janus_config_get_item(cat, "audio_active_packets");
782
                        janus_config_item *audio_level_average = janus_config_get_item(cat, "audio_level_average");
783
                        janus_config_item *videoorient_ext = janus_config_get_item(cat, "videoorient_ext");
784
                        janus_config_item *playoutdelay_ext = janus_config_get_item(cat, "playoutdelay_ext");
785
                        janus_config_item *record = janus_config_get_item(cat, "record");
786
                        janus_config_item *rec_dir = janus_config_get_item(cat, "rec_dir");
787
                        /* Create the video room */
788
                        janus_videoroom *videoroom = g_malloc0(sizeof(janus_videoroom));
789
                        videoroom->room_id = g_ascii_strtoull(cat->name, NULL, 0);
790
                        char *description = NULL;
791
                        if(desc != NULL && desc->value != NULL && strlen(desc->value) > 0)
792
                                description = g_strdup(desc->value);
793
                        else
794
                                description = g_strdup(cat->name);
795
                        videoroom->room_name = description;
796
                        if(secret != NULL && secret->value != NULL) {
797
                                videoroom->room_secret = g_strdup(secret->value);
798
                        }
799
                        if(pin != NULL && pin->value != NULL) {
800
                                videoroom->room_pin = g_strdup(pin->value);
801
                        }
802
                        videoroom->is_private = priv && priv->value && janus_is_true(priv->value);
803
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
804
                        if(maxp != NULL && maxp->value != NULL)
805
                                videoroom->max_publishers = atol(maxp->value);
806
                        if(videoroom->max_publishers < 0)
807
                                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
808
                        videoroom->bitrate = 0;
809
                        if(bitrate != NULL && bitrate->value != NULL)
810
                                videoroom->bitrate = atol(bitrate->value);
811
                        if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
812
                                videoroom->bitrate = 64000;        /* Don't go below 64k */
813
                        videoroom->fir_freq = 0;
814
                        if(firfreq != NULL && firfreq->value != NULL)
815
                                videoroom->fir_freq = atol(firfreq->value);
816
                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
817
                        if(audiocodec && audiocodec->value) {
818
                                if(!strcasecmp(audiocodec->value, "opus"))
819
                                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
820
                                else if(!strcasecmp(audiocodec->value, "isac32"))
821
                                        videoroom->acodec = JANUS_VIDEOROOM_ISAC_32K;
822
                                else if(!strcasecmp(audiocodec->value, "isac16"))
823
                                        videoroom->acodec = JANUS_VIDEOROOM_ISAC_16K;
824
                                else if(!strcasecmp(audiocodec->value, "pcmu"))
825
                                        videoroom->acodec = JANUS_VIDEOROOM_PCMU;
826
                                else if(!strcasecmp(audiocodec->value, "pcma"))
827
                                        videoroom->acodec = JANUS_VIDEOROOM_PCMA;
828
                                else if(!strcasecmp(audiocodec->value, "g722"))
829
                                        videoroom->acodec = JANUS_VIDEOROOM_G722;
830
                                else {
831
                                        JANUS_LOG(LOG_WARN, "Unsupported audio codec '%s', falling back to OPUS\n", audiocodec->value);
832
                                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
833
                                }
834
                        }
835
                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
836
                        if(videocodec && videocodec->value) {
837
                                if(!strcasecmp(videocodec->value, "vp8"))
838
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
839
                                else if(!strcasecmp(videocodec->value, "vp9"))
840
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP9;
841
                                else if(!strcasecmp(videocodec->value, "h264"))
842
                                        videoroom->vcodec = JANUS_VIDEOROOM_H264;
843
                                else {
844
                                        JANUS_LOG(LOG_WARN, "Unsupported video codec '%s', falling back to VP8\n", videocodec->value);
845
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
846
                                }
847
                        }
848
                        videoroom->audiolevel_ext = TRUE;
849
                        if(audiolevel_ext != NULL && audiolevel_ext->value != NULL)
850
                                videoroom->audiolevel_ext = janus_is_true(audiolevel_ext->value);
851
                        videoroom->audiolevel_event = FALSE;
852
                        if(audiolevel_event != NULL && audiolevel_event->value != NULL)
853
                                videoroom->audiolevel_event = janus_is_true(audiolevel_event->value);
854
                        if(videoroom->audiolevel_event) {
855
                                videoroom->audio_active_packets = 100;
856
                                if(audio_active_packets != NULL && audio_active_packets->value != NULL){
857
                                        if(atoi(audio_active_packets->value) > 0) {
858
                                                videoroom->audio_active_packets = atoi(audio_active_packets->value);
859
                                        } else {
860
                                                JANUS_LOG(LOG_WARN, "Invalid audio_active_packets value, using default: %d\n", videoroom->audio_active_packets);
861
                                        }
862
                                }
863
                                videoroom->audio_level_average = 25;
864
                                if(audio_level_average != NULL && audio_level_average->value != NULL) {
865
                                        if(atoi(audio_level_average->value) > 0) {
866
                                                videoroom->audio_level_average = atoi(audio_level_average->value);
867
                                        } else {
868
                                                JANUS_LOG(LOG_WARN, "Invalid audio_level_average value provided, using default: %d\n", videoroom->audio_level_average);
869
                                        }
870
                                }
871
                        }
872
                        videoroom->videoorient_ext = TRUE;
873
                        if(videoorient_ext != NULL && videoorient_ext->value != NULL)
874
                                videoroom->videoorient_ext = janus_is_true(videoorient_ext->value);
875
                        videoroom->playoutdelay_ext = TRUE;
876
                        if(playoutdelay_ext != NULL && playoutdelay_ext->value != NULL)
877
                                videoroom->playoutdelay_ext = janus_is_true(playoutdelay_ext->value);
878
                        if(record && record->value) {
879
                                videoroom->record = janus_is_true(record->value);
880
                        }
881
                        if(rec_dir && rec_dir->value) {
882
                                videoroom->rec_dir = g_strdup(rec_dir->value);
883
                        }
884
                        videoroom->destroyed = 0;
885
                        janus_mutex_init(&videoroom->participants_mutex);
886
                        videoroom->participants = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
887
                        videoroom->private_ids = g_hash_table_new(NULL, NULL);
888
                        videoroom->check_tokens = FALSE;        /* Static rooms can't have an "allowed" list yet, no hooks to the configuration file */
889
                        videoroom->allowed = g_hash_table_new_full(g_str_hash, g_str_equal, (GDestroyNotify)g_free, NULL);
890
                        janus_mutex_lock(&rooms_mutex);
891
                        g_hash_table_insert(rooms, janus_uint64_dup(videoroom->room_id), videoroom);
892
                        janus_mutex_unlock(&rooms_mutex);
893
                        JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, %s/%s codecs, secret: %s, pin: %s)\n",
894
                                videoroom->room_id, videoroom->room_name,
895
                                videoroom->is_private ? "private" : "public",
896
                                janus_videoroom_audiocodec_name(videoroom->acodec),
897
                                janus_videoroom_videocodec_name(videoroom->vcodec),
898
                                videoroom->room_secret ? videoroom->room_secret : "no secret",
899
                                videoroom->room_pin ? videoroom->room_pin : "no pin");
900
                        if(videoroom->record) {
901
                                JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
902
                        }
903
                        cl = cl->next;
904
                }
905
                /* Done: we keep the configuration file open in case we get a "create" or "destroy" with permanent=true */
906
        }
907

    
908
        /* Show available rooms */
909
        janus_mutex_lock(&rooms_mutex);
910
        GHashTableIter iter;
911
        gpointer value;
912
        g_hash_table_iter_init(&iter, rooms);
913
        while (g_hash_table_iter_next(&iter, NULL, &value)) {
914
                janus_videoroom *vr = value;
915
                JANUS_LOG(LOG_VERB, "  ::: [%"SCNu64"][%s] %"SCNu64", max %d publishers, FIR frequency of %d seconds, %s audio codec, %s video codec\n",
916
                        vr->room_id, vr->room_name, vr->bitrate, vr->max_publishers, vr->fir_freq,
917
                        janus_videoroom_audiocodec_name(vr->acodec), janus_videoroom_videocodec_name(vr->vcodec));
918
        }
919
        janus_mutex_unlock(&rooms_mutex);
920

    
921
        g_atomic_int_set(&initialized, 1);
922

    
923
        GError *error = NULL;
924
        /* Start the sessions watchdog */
925
        watchdog = g_thread_try_new("videoroom watchdog", &janus_videoroom_watchdog, NULL, &error);
926
        if(error != NULL) {
927
                g_atomic_int_set(&initialized, 0);
928
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom watchdog thread...\n", error->code, error->message ? error->message : "??");
929
                janus_config_destroy(config);
930
                return -1;
931
        }
932
        /* Launch the thread that will handle incoming messages */
933
        handler_thread = g_thread_try_new("videoroom handler", janus_videoroom_handler, NULL, &error);
934
        if(error != NULL) {
935
                g_atomic_int_set(&initialized, 0);
936
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom handler thread...\n", error->code, error->message ? error->message : "??");
937
                janus_config_destroy(config);
938
                return -1;
939
        }
940
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_VIDEOROOM_NAME);
941
        return 0;
942
}
943

    
944
void janus_videoroom_destroy(void) {
945
        if(!g_atomic_int_get(&initialized))
946
                return;
947
        g_atomic_int_set(&stopping, 1);
948

    
949
        g_async_queue_push(messages, &exit_message);
950
        if(handler_thread != NULL) {
951
                g_thread_join(handler_thread);
952
                handler_thread = NULL;
953
        }
954
        if(watchdog != NULL) {
955
                g_thread_join(watchdog);
956
                watchdog = NULL;
957
        }
958

    
959
        /* FIXME We should destroy the sessions cleanly */
960
        janus_mutex_lock(&sessions_mutex);
961
        g_hash_table_foreach_remove(sessions, (GHRFunc)session_hash_table_remove, NULL);
962
        g_hash_table_destroy(sessions);
963
        sessions = NULL;
964
        janus_mutex_unlock(&sessions_mutex);
965

    
966
        janus_mutex_lock(&rooms_mutex);
967
        g_hash_table_destroy(rooms);
968
        rooms = NULL;
969
        janus_mutex_unlock(&rooms_mutex);
970
        janus_mutex_destroy(&rooms_mutex);
971

    
972
        g_async_queue_unref(messages);
973
        messages = NULL;
974

    
975
        janus_config_destroy(config);
976
        g_free(admin_key);
977

    
978
        g_atomic_int_set(&initialized, 0);
979
        g_atomic_int_set(&stopping, 0);
980
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOROOM_NAME);
981
}
982

    
983
int janus_videoroom_get_api_compatibility(void) {
984
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
985
        return JANUS_PLUGIN_API_VERSION;
986
}
987

    
988
int janus_videoroom_get_version(void) {
989
        return JANUS_VIDEOROOM_VERSION;
990
}
991

    
992
const char *janus_videoroom_get_version_string(void) {
993
        return JANUS_VIDEOROOM_VERSION_STRING;
994
}
995

    
996
const char *janus_videoroom_get_description(void) {
997
        return JANUS_VIDEOROOM_DESCRIPTION;
998
}
999

    
1000
const char *janus_videoroom_get_name(void) {
1001
        return JANUS_VIDEOROOM_NAME;
1002
}
1003

    
1004
const char *janus_videoroom_get_author(void) {
1005
        return JANUS_VIDEOROOM_AUTHOR;
1006
}
1007

    
1008
const char *janus_videoroom_get_package(void) {
1009
        return JANUS_VIDEOROOM_PACKAGE;
1010
}
1011

    
1012
void janus_videoroom_create_session(janus_plugin_session *handle, int *error) {
1013
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1014
                *error = -1;
1015
                return;
1016
        }        
1017
        janus_videoroom_session *session = (janus_videoroom_session *)g_malloc0(sizeof(janus_videoroom_session));
1018
        session->handle = handle;
1019
        session->participant_type = janus_videoroom_p_type_none;
1020
        session->participant = NULL;
1021
        session->destroyed = 0;
1022
        g_atomic_int_set(&session->hangingup, 0);
1023
        handle->plugin_handle = session;
1024
        janus_mutex_lock(&sessions_mutex);
1025
        g_hash_table_insert(sessions, handle, session);
1026
        janus_mutex_unlock(&sessions_mutex);
1027

    
1028
        return;
1029
}
1030

    
1031
static void janus_videoroom_notify_participants(janus_videoroom_participant *participant, json_t *msg) {
1032
        /* participant->room->participants_mutex has to be locked. */
1033
        GHashTableIter iter;
1034
        gpointer value;
1035
        g_hash_table_iter_init(&iter, participant->room->participants);
1036
        while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1037
                janus_videoroom_participant *p = value;
1038
                if(p && p->session && p != participant) {
1039
                        JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1040
                        int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, msg, NULL);
1041
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1042
                }
1043
        }
1044
}
1045

    
1046
static void janus_videoroom_leave_or_unpublish(janus_videoroom_participant *participant, gboolean is_leaving, gboolean kicked) {
1047
        /* we need to check if the room still exists, may have been destroyed already */
1048
        if(participant->room && !participant->room->destroyed) {
1049
                json_t *event = json_object();
1050
                json_object_set_new(event, "videoroom", json_string("event"));
1051
                json_object_set_new(event, "room", json_integer(participant->room->room_id));
1052
                json_object_set_new(event, is_leaving ? (kicked ? "kicked" : "leaving") : "unpublished",
1053
                        json_integer(participant->user_id));
1054
                janus_mutex_lock(&participant->room->participants_mutex);
1055
                janus_videoroom_notify_participants(participant, event);
1056
                if(is_leaving) {
1057
                        g_hash_table_remove(participant->room->participants, &participant->user_id);
1058
                        g_hash_table_remove(participant->room->private_ids, GUINT_TO_POINTER(participant->pvt_id));
1059
                }
1060
                janus_mutex_unlock(&participant->room->participants_mutex);
1061
                json_decref(event);
1062
        }
1063
}
1064

    
1065
void janus_videoroom_destroy_session(janus_plugin_session *handle, int *error) {
1066
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1067
                *error = -1;
1068
                return;
1069
        }        
1070
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle; 
1071
        if(!session) {
1072
                JANUS_LOG(LOG_ERR, "No VideoRoom session associated with this handle...\n");
1073
                *error = -2;
1074
                return;
1075
        }
1076
        if(session->destroyed) {
1077
                JANUS_LOG(LOG_WARN, "VideoRoom session already marked as destroyed...\n");
1078
                return;
1079
        }
1080
        JANUS_LOG(LOG_VERB, "Removing VideoRoom session...\n");
1081
        /* Cleaning up and removing the session is done in a lazy way */
1082
        janus_mutex_lock(&sessions_mutex);
1083
        if(!session->destroyed) {
1084
                /* Any related WebRTC PeerConnection is not available anymore either */
1085
                janus_videoroom_hangup_media(handle);
1086
                session->destroyed = janus_get_monotonic_time();
1087
                old_sessions = g_list_append(old_sessions, session);
1088
                if(session->participant_type == janus_videoroom_p_type_publisher) {
1089
                        /* Get rid of publisher */
1090
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1091
                        participant->audio = FALSE;
1092
                        participant->video = FALSE;
1093
                        participant->data = FALSE;
1094
                        participant->audio_active = FALSE;
1095
                        participant->video_active = FALSE;
1096
                        participant->data_active = FALSE;
1097
                        participant->recording_active = FALSE;
1098
                        if(participant->recording_base)
1099
                                g_free(participant->recording_base);
1100
                        participant->recording_base = NULL;
1101
                        session->participant_type = janus_videoroom_p_type_none;
1102
                        janus_videoroom_leave_or_unpublish(participant, TRUE, FALSE);
1103
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1104
                        /* Detaching this listener from its publisher is already done by hangup_media */
1105
                }
1106
        }
1107
        janus_mutex_unlock(&sessions_mutex);
1108

    
1109
        return;
1110
}
1111

    
1112
json_t *janus_videoroom_query_session(janus_plugin_session *handle) {
1113
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1114
                return NULL;
1115
        }        
1116
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1117
        if(!session) {
1118
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1119
                return NULL;
1120
        }
1121
        /* Show the participant/room info, if any */
1122
        json_t *info = json_object();
1123
        if(session->participant) {
1124
                if(session->participant_type == janus_videoroom_p_type_none) {
1125
                        json_object_set_new(info, "type", json_string("none"));
1126
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
1127
                        json_object_set_new(info, "type", json_string("publisher"));
1128
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1129
                        if(participant) {
1130
                                janus_videoroom *room = participant->room; 
1131
                                json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
1132
                                json_object_set_new(info, "id", json_integer(participant->user_id));
1133
                                json_object_set_new(info, "private_id", json_integer(participant->pvt_id));
1134
                                if(participant->display)
1135
                                        json_object_set_new(info, "display", json_string(participant->display));
1136
                                if(participant->listeners)
1137
                                        json_object_set_new(info, "viewers", json_integer(g_slist_length(participant->listeners)));
1138
                                json_t *media = json_object();
1139
                                json_object_set_new(media, "audio", json_integer(participant->audio));
1140
                                json_object_set_new(media, "video", json_integer(participant->video));
1141
                                json_object_set_new(media, "data", json_integer(participant->data));
1142
                                json_object_set_new(info, "media", media);
1143
                                json_object_set_new(info, "bitrate", json_integer(participant->bitrate));
1144
                                if(participant->arc || participant->vrc || participant->drc) {
1145
                                        json_t *recording = json_object();
1146
                                        if(participant->arc && participant->arc->filename)
1147
                                                json_object_set_new(recording, "audio", json_string(participant->arc->filename));
1148
                                        if(participant->vrc && participant->vrc->filename)
1149
                                                json_object_set_new(recording, "video", json_string(participant->vrc->filename));
1150
                                        if(participant->drc && participant->drc->filename)
1151
                                                json_object_set_new(recording, "data", json_string(participant->drc->filename));
1152
                                        json_object_set_new(info, "recording", recording);
1153
                                }
1154
                        }
1155
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1156
                        json_object_set_new(info, "type", json_string("listener"));
1157
                        janus_videoroom_listener *participant = (janus_videoroom_listener *)session->participant;
1158
                        if(participant) {
1159
                                janus_videoroom_participant *feed = (janus_videoroom_participant *)participant->feed;
1160
                                if(feed) {
1161
                                        janus_videoroom *room = feed->room; 
1162
                                        json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
1163
                                        json_object_set_new(info, "private_id", json_integer(participant->pvt_id));
1164
                                        json_object_set_new(info, "feed_id", json_integer(feed->user_id));
1165
                                        if(feed->display)
1166
                                                json_object_set_new(info, "feed_display", json_string(feed->display));
1167
                                }
1168
                                json_t *media = json_object();
1169
                                json_object_set_new(media, "audio", json_integer(participant->audio));
1170
                                json_object_set_new(media, "video", json_integer(participant->video));
1171
                                json_object_set_new(media, "data", json_integer(participant->data));
1172
                                json_object_set_new(info, "media", media);
1173
                        }
1174
                }
1175
        }
1176
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
1177
        return info;
1178
}
1179

    
1180
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) {
1181
        /* rooms_mutex has to be locked */
1182
        int error_code = 0;
1183
        json_t *room = json_object_get(root, "room");
1184
        guint64 room_id = json_integer_value(room);
1185
        *videoroom = g_hash_table_lookup(rooms, &room_id);
1186
        if(*videoroom == NULL) {
1187
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1188
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1189
                if(error_cause)
1190
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1191
                return error_code;
1192
        }
1193
        if((*videoroom)->destroyed) {
1194
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1195
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1196
                if(error_cause)
1197
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1198
                return error_code;
1199
        }
1200
        if(check_secret) {
1201
                char error_cause2[100];
1202
                JANUS_CHECK_SECRET((*videoroom)->room_secret, root, "secret", error_code, error_cause2,
1203
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1204
                if(error_code != 0) {
1205
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1206
                        return error_code;
1207
                }
1208
        }
1209
        if(check_pin) {
1210
                char error_cause2[100];
1211
                JANUS_CHECK_SECRET((*videoroom)->room_pin, root, "pin", error_code, error_cause2,
1212
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1213
                if(error_code != 0) {
1214
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1215
                        return error_code;
1216
                }
1217
        }
1218
        return 0;
1219
}
1220

    
1221
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1222
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1223
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1224
        
1225
        /* Pre-parse the message */
1226
        int error_code = 0;
1227
        char error_cause[512];
1228
        json_t *root = message;
1229
        json_t *response = NULL;
1230

    
1231
        if(message == NULL) {
1232
                JANUS_LOG(LOG_ERR, "No message??\n");
1233
                error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
1234
                g_snprintf(error_cause, 512, "%s", "No message??");
1235
                goto plugin_response;
1236
        }
1237

    
1238
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1239
        if(!session) {
1240
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1241
                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1242
                g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
1243
                goto plugin_response;
1244
        }
1245
        if(session->destroyed) {
1246
                JANUS_LOG(LOG_ERR, "Session has already been marked as destroyed...\n");
1247
                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1248
                g_snprintf(error_cause, 512, "%s", "Session has already been marked as destroyed...");
1249
                goto plugin_response;
1250
        }
1251
        if(!json_is_object(root)) {
1252
                JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1253
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_JSON;
1254
                g_snprintf(error_cause, 512, "JSON error: not an object");
1255
                goto plugin_response;
1256
        }
1257
        /* Get the request first */
1258
        JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1259
                error_code, error_cause, TRUE,
1260
                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1261
        if(error_code != 0)
1262
                goto plugin_response;
1263
        json_t *request = json_object_get(root, "request");
1264
        /* Some requests ('create', 'destroy', 'exists', 'list') can be handled synchronously */
1265
        const char *request_text = json_string_value(request);
1266
        if(!strcasecmp(request_text, "create")) {
1267
                /* Create a new videoroom */
1268
                JANUS_LOG(LOG_VERB, "Creating a new videoroom\n");
1269
                JANUS_VALIDATE_JSON_OBJECT(root, create_parameters,
1270
                        error_code, error_cause, TRUE,
1271
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1272
                if(error_code != 0)
1273
                        goto plugin_response;
1274
                if(admin_key != NULL) {
1275
                        /* An admin key was specified: make sure it was provided, and that it's valid */
1276
                        JANUS_VALIDATE_JSON_OBJECT(root, adminkey_parameters,
1277
                                error_code, error_cause, TRUE,
1278
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1279
                        if(error_code != 0)
1280
                                goto plugin_response;
1281
                        JANUS_CHECK_SECRET(admin_key, root, "admin_key", error_code, error_cause,
1282
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1283
                        if(error_code != 0)
1284
                                goto plugin_response;
1285
                }
1286
                json_t *desc = json_object_get(root, "description");
1287
                json_t *is_private = json_object_get(root, "is_private");
1288
                json_t *secret = json_object_get(root, "secret");
1289
                json_t *pin = json_object_get(root, "pin");
1290
                json_t *bitrate = json_object_get(root, "bitrate");
1291
                json_t *fir_freq = json_object_get(root, "fir_freq");
1292
                json_t *publishers = json_object_get(root, "publishers");
1293
                json_t *allowed = json_object_get(root, "allowed");
1294
                json_t *audiocodec = json_object_get(root, "audiocodec");
1295
                if(audiocodec) {
1296
                        const char *audiocodec_value = json_string_value(audiocodec);
1297
                        if(!strcasecmp(audiocodec_value, "opus") && !strcasecmp(audiocodec_value, "g722") &&
1298
                                        !strcasecmp(audiocodec_value, "isac32") && !strcasecmp(audiocodec_value, "isac16") &&
1299
                                        !strcasecmp(audiocodec_value, "pcmu") && !strcasecmp(audiocodec_value, "pcma")) {
1300
                                JANUS_LOG(LOG_ERR, "Invalid element (audiocodec can only be opus, isac32, isac16, pcmu, pcma or g722)\n");
1301
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1302
                                g_snprintf(error_cause, 512, "Invalid element (audiocodec can only be opus, isac32, isac16, pcmu, pcma or g722)");
1303
                                goto plugin_response;
1304
                        }
1305
                }
1306
                json_t *videocodec = json_object_get(root, "videocodec");
1307
                if(videocodec) {
1308
                        const char *videocodec_value = json_string_value(videocodec);
1309
                        if(!strcasecmp(videocodec_value, "vp8") && !strcasecmp(videocodec_value, "vp9") && !strcasecmp(videocodec_value, "h264")) {
1310
                                JANUS_LOG(LOG_ERR, "Invalid element (videocodec can only be vp8, vp9 or h264)\n");
1311
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1312
                                g_snprintf(error_cause, 512, "Invalid element (videocodec can only be vp8, vp9 or h264)");
1313
                                goto plugin_response;
1314
                        }
1315
                }
1316
                json_t *audiolevel_ext = json_object_get(root, "audiolevel_ext");
1317
                json_t *audiolevel_event = json_object_get(root, "audiolevel_event");
1318
                json_t *audio_active_packets = json_object_get(root, "audio_active_packets");
1319
                json_t *audio_level_average = json_object_get(root, "audio_level_average");
1320
                json_t *videoorient_ext = json_object_get(root, "videoorient_ext");
1321
                json_t *playoutdelay_ext = json_object_get(root, "playoutdelay_ext");
1322
                json_t *record = json_object_get(root, "record");
1323
                json_t *rec_dir = json_object_get(root, "rec_dir");
1324
                json_t *permanent = json_object_get(root, "permanent");
1325
                if(allowed) {
1326
                        /* Make sure the "allowed" array only contains strings */
1327
                        gboolean ok = TRUE;
1328
                        if(json_array_size(allowed) > 0) {
1329
                                size_t i = 0;
1330
                                for(i=0; i<json_array_size(allowed); i++) {
1331
                                        json_t *a = json_array_get(allowed, i);
1332
                                        if(!a || !json_is_string(a)) {
1333
                                                ok = FALSE;
1334
                                                break;
1335
                                        }
1336
                                }
1337
                        }
1338
                        if(!ok) {
1339
                                JANUS_LOG(LOG_ERR, "Invalid element in the allowed array (not a string)\n");
1340
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1341
                                g_snprintf(error_cause, 512, "Invalid element in the allowed array (not a string)");
1342
                                goto plugin_response;
1343
                        }
1344
                }
1345
                gboolean save = permanent ? json_is_true(permanent) : FALSE;
1346
                if(save && config == NULL) {
1347
                        JANUS_LOG(LOG_ERR, "No configuration file, can't create permanent room\n");
1348
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1349
                        g_snprintf(error_cause, 512, "No configuration file, can't create permanent room");
1350
                        goto plugin_response;
1351
                }
1352
                guint64 room_id = 0;
1353
                json_t *room = json_object_get(root, "room");
1354
                if(room) {
1355
                        room_id = json_integer_value(room);
1356
                        if(room_id == 0) {
1357
                                JANUS_LOG(LOG_WARN, "Desired room ID is 0, which is not allowed... picking random ID instead\n");
1358
                        }
1359
                }
1360
                janus_mutex_lock(&rooms_mutex);
1361
                if(room_id > 0) {
1362
                        /* Let's make sure the room doesn't exist already */
1363
                        if(g_hash_table_lookup(rooms, &room_id) != NULL) {
1364
                                /* It does... */
1365
                                janus_mutex_unlock(&rooms_mutex);
1366
                                JANUS_LOG(LOG_ERR, "Room %"SCNu64" already exists!\n", room_id);
1367
                                error_code = JANUS_VIDEOROOM_ERROR_ROOM_EXISTS;
1368
                                g_snprintf(error_cause, 512, "Room %"SCNu64" already exists", room_id);
1369
                                goto plugin_response;
1370
                        }
1371
                }
1372
                /* Create the room */
1373
                janus_videoroom *videoroom = g_malloc0(sizeof(janus_videoroom));
1374
                /* Generate a random ID */
1375
                if(room_id == 0) {
1376
                        while(room_id == 0) {
1377
                                room_id = janus_random_uint64();
1378
                                if(g_hash_table_lookup(rooms, &room_id) != NULL) {
1379
                                        /* Room ID already taken, try another one */
1380
                                        room_id = 0;
1381
                                }
1382
                        }
1383
                }
1384
                videoroom->room_id = room_id;
1385
                char *description = NULL;
1386
                if(desc != NULL && strlen(json_string_value(desc)) > 0) {
1387
                        description = g_strdup(json_string_value(desc));
1388
                } else {
1389
                        char roomname[255];
1390
                        g_snprintf(roomname, 255, "Room %"SCNu64"", videoroom->room_id);
1391
                        description = g_strdup(roomname);
1392
                }
1393
                videoroom->room_name = description;
1394
                videoroom->is_private = is_private ? json_is_true(is_private) : FALSE;
1395
                if(secret)
1396
                        videoroom->room_secret = g_strdup(json_string_value(secret));
1397
                if(pin)
1398
                        videoroom->room_pin = g_strdup(json_string_value(pin));
1399
                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
1400
                if(publishers)
1401
                        videoroom->max_publishers = json_integer_value(publishers);
1402
                if(videoroom->max_publishers < 0)
1403
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
1404
                videoroom->bitrate = 0;
1405
                if(bitrate)
1406
                        videoroom->bitrate = json_integer_value(bitrate);
1407
                if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
1408
                        videoroom->bitrate = 64000;        /* Don't go below 64k */
1409
                videoroom->fir_freq = 0;
1410
                if(fir_freq)
1411
                        videoroom->fir_freq = json_integer_value(fir_freq);
1412
                videoroom->acodec = JANUS_VIDEOROOM_OPUS;
1413
                if(audiocodec) {
1414
                        const char *audiocodec_value = json_string_value(audiocodec);
1415
                        if(!strcasecmp(audiocodec_value, "opus"))
1416
                                videoroom->acodec = JANUS_VIDEOROOM_OPUS;
1417
                        else if(!strcasecmp(audiocodec_value, "isac32"))
1418
                                videoroom->acodec = JANUS_VIDEOROOM_ISAC_32K;
1419
                        else if(!strcasecmp(audiocodec_value, "isac16"))
1420
                                videoroom->acodec = JANUS_VIDEOROOM_ISAC_16K;
1421
                        else if(!strcasecmp(audiocodec_value, "pcmu"))
1422
                                videoroom->acodec = JANUS_VIDEOROOM_PCMU;
1423
                        else if(!strcasecmp(audiocodec_value, "pcma"))
1424
                                videoroom->acodec = JANUS_VIDEOROOM_PCMA;
1425
                        else if(!strcasecmp(audiocodec_value, "g722"))
1426
                                videoroom->acodec = JANUS_VIDEOROOM_G722;
1427
                        else {
1428
                                JANUS_LOG(LOG_WARN, "Unsupported audio codec '%s', falling back to OPUS\n", audiocodec_value);
1429
                                videoroom->acodec = JANUS_VIDEOROOM_OPUS;
1430
                        }
1431
                }
1432
                videoroom->vcodec = JANUS_VIDEOROOM_VP8;
1433
                if(videocodec) {
1434
                        const char *videocodec_value = json_string_value(videocodec);
1435
                        if(!strcasecmp(videocodec_value, "vp8"))
1436
                                videoroom->vcodec = JANUS_VIDEOROOM_VP8;
1437
                        else if(!strcasecmp(videocodec_value, "vp9"))
1438
                                videoroom->vcodec = JANUS_VIDEOROOM_VP9;
1439
                        else if(!strcasecmp(videocodec_value, "h264"))
1440
                                videoroom->vcodec = JANUS_VIDEOROOM_H264;
1441
                        else {
1442
                                JANUS_LOG(LOG_WARN, "Unsupported video codec '%s', falling back to VP8\n", videocodec_value);
1443
                                videoroom->vcodec = JANUS_VIDEOROOM_VP8;
1444
                        }
1445
                }
1446
                videoroom->audiolevel_ext = audiolevel_ext ? json_is_true(audiolevel_ext) : TRUE;
1447
                videoroom->audiolevel_event = audiolevel_event ? json_is_true(audiolevel_event) : FALSE;
1448
                if(videoroom->audiolevel_event) {
1449
                        videoroom->audio_active_packets = 100;
1450
                        if(json_integer_value(audio_active_packets) > 0) {
1451
                                videoroom->audio_active_packets = json_integer_value(audio_active_packets);
1452
                        } else {
1453
                                JANUS_LOG(LOG_WARN, "Invalid audio_active_packets value provided, using default: %d\n", videoroom->audio_active_packets);
1454
                        }
1455
                        videoroom->audio_level_average = 25;
1456
                        if(json_integer_value(audio_level_average) > 0) {
1457
                                videoroom->audio_level_average = json_integer_value(audio_level_average);
1458
                        } else {
1459
                                JANUS_LOG(LOG_WARN, "Invalid audio_level_average value provided, using default: %d\n", videoroom->audio_level_average);
1460
                        }
1461
                }
1462
                videoroom->videoorient_ext = videoorient_ext ? json_is_true(videoorient_ext) : TRUE;
1463
                videoroom->playoutdelay_ext = playoutdelay_ext ? json_is_true(playoutdelay_ext) : TRUE;
1464
                if(record) {
1465
                        videoroom->record = json_is_true(record);
1466
                }
1467
                if(rec_dir) {
1468
                        videoroom->rec_dir = g_strdup(json_string_value(rec_dir));
1469
                }
1470
                videoroom->destroyed = 0;
1471
                janus_mutex_init(&videoroom->participants_mutex);
1472
                videoroom->participants = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
1473
                videoroom->private_ids = g_hash_table_new(NULL, NULL);
1474
                videoroom->allowed = g_hash_table_new_full(g_str_hash, g_str_equal, (GDestroyNotify)g_free, NULL);
1475
                if(allowed != NULL) {
1476
                        /* Populate the "allowed" list as an ACL for people trying to join */
1477
                        if(json_array_size(allowed) > 0) {
1478
                                size_t i = 0;
1479
                                for(i=0; i<json_array_size(allowed); i++) {
1480
                                        const char *token = json_string_value(json_array_get(allowed, i));
1481
                                        if(!g_hash_table_lookup(videoroom->allowed, token))
1482
                                                g_hash_table_insert(videoroom->allowed, g_strdup(token), GINT_TO_POINTER(TRUE));
1483
                                }
1484
                        }
1485
                        videoroom->check_tokens = TRUE;
1486
                }
1487
                JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, %s/%s codecs, secret: %s, pin: %s)\n",
1488
                        videoroom->room_id, videoroom->room_name,
1489
                        videoroom->is_private ? "private" : "public",
1490
                        janus_videoroom_audiocodec_name(videoroom->acodec),
1491
                        janus_videoroom_videocodec_name(videoroom->vcodec),
1492
                        videoroom->room_secret ? videoroom->room_secret : "no secret",
1493
                        videoroom->room_pin ? videoroom->room_pin : "no pin");
1494
                if(videoroom->record) {
1495
                        JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
1496
                }
1497
                if(save) {
1498
                        /* This room is permanent: save to the configuration file too
1499
                         * FIXME: We should check if anything fails... */
1500
                        JANUS_LOG(LOG_VERB, "Saving room %"SCNu64" permanently in config file\n", videoroom->room_id);
1501
                        janus_mutex_lock(&config_mutex);
1502
                        char cat[BUFSIZ], value[BUFSIZ];
1503
                        /* The room ID is the category */
1504
                        g_snprintf(cat, BUFSIZ, "%"SCNu64, videoroom->room_id);
1505
                        janus_config_add_category(config, cat);
1506
                        /* Now for the values */
1507
                        janus_config_add_item(config, cat, "description", videoroom->room_name);
1508
                        if(videoroom->is_private)
1509
                                janus_config_add_item(config, cat, "is_private", "yes");
1510
                        g_snprintf(value, BUFSIZ, "%"SCNu64, videoroom->bitrate);
1511
                        janus_config_add_item(config, cat, "bitrate", value);
1512
                        g_snprintf(value, BUFSIZ, "%d", videoroom->max_publishers);
1513
                        janus_config_add_item(config, cat, "publishers", value);
1514
                        if(videoroom->fir_freq) {
1515
                                g_snprintf(value, BUFSIZ, "%"SCNu16, videoroom->fir_freq);
1516
                                janus_config_add_item(config, cat, "fir_freq", value);
1517
                        }
1518
                        janus_config_add_item(config, cat, "audiocodec", janus_videoroom_audiocodec_name(videoroom->acodec));
1519
                        janus_config_add_item(config, cat, "videocodec", janus_videoroom_videocodec_name(videoroom->vcodec));
1520
                        if(videoroom->room_secret)
1521
                                janus_config_add_item(config, cat, "secret", videoroom->room_secret);
1522
                        if(videoroom->room_pin)
1523
                                janus_config_add_item(config, cat, "pin", videoroom->room_pin);
1524
                        if(videoroom->record)
1525
                                janus_config_add_item(config, cat, "record", "yes");
1526
                        if(videoroom->rec_dir)
1527
                                janus_config_add_item(config, cat, "rec_dir", videoroom->rec_dir);
1528
                        /* Save modified configuration */
1529
                        if(janus_config_save(config, config_folder, JANUS_VIDEOROOM_PACKAGE) < 0)
1530
                                save = FALSE;        /* This will notify the user the room is not permanent */
1531
                        janus_mutex_unlock(&config_mutex);
1532
                }
1533
                /* Show updated rooms list */
1534
                GHashTableIter iter;
1535
                gpointer value;
1536
                g_hash_table_insert(rooms, janus_uint64_dup(videoroom->room_id), videoroom);
1537
                g_hash_table_iter_init(&iter, rooms);
1538
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1539
                        janus_videoroom *vr = value;
1540
                        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);
1541
                }
1542
                janus_mutex_unlock(&rooms_mutex);
1543
                /* Send info back */
1544
                response = json_object();
1545
                json_object_set_new(response, "videoroom", json_string("created"));
1546
                json_object_set_new(response, "room", json_integer(videoroom->room_id));
1547
                json_object_set_new(response, "permanent", save ? json_true() : json_false());
1548
                /* Also notify event handlers */
1549
                if(notify_events && gateway->events_is_enabled()) {
1550
                        json_t *info = json_object();
1551
                        json_object_set_new(info, "event", json_string("created"));
1552
                        json_object_set_new(info, "room", json_integer(videoroom->room_id));
1553
                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
1554
                }
1555
                goto plugin_response;
1556
        } else if(!strcasecmp(request_text, "destroy")) {
1557
                JANUS_LOG(LOG_VERB, "Attempt to destroy an existing videoroom room\n");
1558
                JANUS_VALIDATE_JSON_OBJECT(root, destroy_parameters,
1559
                        error_code, error_cause, TRUE,
1560
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1561
                if(error_code != 0)
1562
                        goto plugin_response;
1563
                json_t *room = json_object_get(root, "room");
1564
                json_t *permanent = json_object_get(root, "permanent");
1565
                gboolean save = permanent ? json_is_true(permanent) : FALSE;
1566
                if(save && config == NULL) {
1567
                        JANUS_LOG(LOG_ERR, "No configuration file, can't destroy room permanently\n");
1568
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1569
                        g_snprintf(error_cause, 512, "No configuration file, can't destroy room permanently");
1570
                        goto plugin_response;
1571
                }
1572
                guint64 room_id = json_integer_value(room);
1573
                janus_mutex_lock(&rooms_mutex);
1574
                janus_videoroom *videoroom = NULL;
1575
                error_code = janus_videoroom_access_room(root, TRUE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1576
                if(error_code != 0) {
1577
                        janus_mutex_unlock(&rooms_mutex);
1578
                        goto plugin_response;
1579
                }
1580
                /* Notify all participants that the fun is over, and that they'll be kicked */
1581
                JANUS_LOG(LOG_VERB, "Notifying all participants\n");
1582
                json_t *destroyed = json_object();
1583
                json_object_set_new(destroyed, "videoroom", json_string("destroyed"));
1584
                json_object_set_new(destroyed, "room", json_integer(videoroom->room_id));
1585
                GHashTableIter iter;
1586
                gpointer value;
1587
                /* Remove room lazily*/
1588
                videoroom->destroyed = janus_get_monotonic_time();
1589
                old_rooms = g_list_append(old_rooms, videoroom);
1590
                janus_mutex_lock(&videoroom->participants_mutex);
1591
                g_hash_table_iter_init(&iter, videoroom->participants);
1592
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1593
                        janus_videoroom_participant *p = value;
1594
                        if(p && p->session) {
1595
                                /* Notify the user we're going to destroy the room... */
1596
                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, destroyed, NULL);
1597
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1598
                                /* ... and then ask the core to remove the handle */
1599
                                gateway->end_session(p->session->handle);
1600
                        }
1601
                }
1602
                json_decref(destroyed);
1603
                janus_mutex_unlock(&videoroom->participants_mutex);
1604
                /* Also notify event handlers */
1605
                if(notify_events && gateway->events_is_enabled()) {
1606
                        json_t *info = json_object();
1607
                        json_object_set_new(info, "event", json_string("destroyed"));
1608
                        json_object_set_new(info, "room", json_integer(room_id));
1609
                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
1610
                }
1611
                janus_mutex_unlock(&rooms_mutex);
1612
                if(save) {
1613
                        /* This change is permanent: save to the configuration file too
1614
                         * FIXME: We should check if anything fails... */
1615
                        JANUS_LOG(LOG_VERB, "Destroying room %"SCNu64" permanently in config file\n", room_id);
1616
                        janus_mutex_lock(&config_mutex);
1617
                        char cat[BUFSIZ];
1618
                        /* The room ID is the category */
1619
                        g_snprintf(cat, BUFSIZ, "%"SCNu64, room_id);
1620
                        janus_config_remove_category(config, cat);
1621
                        /* Save modified configuration */
1622
                        janus_config_save(config, config_folder, JANUS_VIDEOROOM_PACKAGE);
1623
                        janus_mutex_unlock(&config_mutex);
1624
                }
1625
                /* Done */
1626
                response = json_object();
1627
                json_object_set_new(response, "videoroom", json_string("destroyed"));
1628
                json_object_set_new(response, "room", json_integer(room_id));
1629
                goto plugin_response;
1630
        } else if(!strcasecmp(request_text, "list")) {
1631
                /* List all rooms (but private ones) and their details (except for the secret, of course...) */
1632
                json_t *list = json_array();
1633
                JANUS_LOG(LOG_VERB, "Getting the list of video rooms\n");
1634
                janus_mutex_lock(&rooms_mutex);
1635
                GHashTableIter iter;
1636
                gpointer value;
1637
                g_hash_table_iter_init(&iter, rooms);
1638
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
1639
                        janus_videoroom *room = value;
1640
                        if(!room)
1641
                                continue;
1642
                        if(room->is_private) {
1643
                                /* Skip private room */
1644
                                JANUS_LOG(LOG_VERB, "Skipping private room '%s'\n", room->room_name);
1645
                                continue;
1646
                        }
1647
                        if(!room->destroyed) {
1648
                                json_t *rl = json_object();
1649
                                json_object_set_new(rl, "room", json_integer(room->room_id));
1650
                                json_object_set_new(rl, "description", json_string(room->room_name));
1651
                                json_object_set_new(rl, "pin_required", room->room_pin ? json_true() : json_false());
1652
                                json_object_set_new(rl, "max_publishers", json_integer(room->max_publishers));
1653
                                json_object_set_new(rl, "bitrate", json_integer(room->bitrate));
1654
                                json_object_set_new(rl, "fir_freq", json_integer(room->fir_freq));
1655
                                json_object_set_new(rl, "audiocodec", json_string(janus_videoroom_audiocodec_name(room->acodec)));
1656
                                json_object_set_new(rl, "videocodec", json_string(janus_videoroom_videocodec_name(room->vcodec)));
1657
                                json_object_set_new(rl, "record", room->record ? json_true() : json_false());
1658
                                json_object_set_new(rl, "rec_dir", json_string(room->rec_dir));
1659
                                /* TODO: Should we list participants as well? or should there be a separate API call on a specific room for this? */
1660
                                json_object_set_new(rl, "num_participants", json_integer(g_hash_table_size(room->participants)));
1661
                                json_array_append_new(list, rl);
1662
                        }
1663
                }
1664
                janus_mutex_unlock(&rooms_mutex);
1665
                response = json_object();
1666
                json_object_set_new(response, "videoroom", json_string("success"));
1667
                json_object_set_new(response, "list", list);
1668
                goto plugin_response;
1669
        } else if(!strcasecmp(request_text, "rtp_forward")) {
1670
                JANUS_VALIDATE_JSON_OBJECT(root, rtp_forward_parameters,
1671
                        error_code, error_cause, TRUE,
1672
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1673
                if(error_code != 0)
1674
                        goto plugin_response;
1675
                json_t *room = json_object_get(root, "room");
1676
                json_t *pub_id = json_object_get(root, "publisher_id");
1677
                int video_port = -1, video_pt = 0;
1678
                uint32_t video_ssrc = 0;
1679
                int audio_port = -1, audio_pt = 0;
1680
                uint32_t audio_ssrc = 0;
1681
                int data_port = -1;
1682
                json_t *vid_port = json_object_get(root, "video_port");
1683
                if(vid_port) {
1684
                        video_port = json_integer_value(vid_port);
1685
                        json_t *pt = json_object_get(root, "video_pt");
1686
                        if(pt)
1687
                                video_pt = json_integer_value(pt);
1688
                        json_t *ssrc = json_object_get(root, "video_ssrc");
1689
                        if(ssrc)
1690
                                video_ssrc = json_integer_value(ssrc);
1691
                }
1692
                json_t *au_port = json_object_get(root, "audio_port");
1693
                if(au_port) {
1694
                        audio_port = json_integer_value(au_port);
1695
                        json_t *pt = json_object_get(root, "audio_pt");
1696
                        if(pt)
1697
                                audio_pt = json_integer_value(pt);
1698
                        json_t *ssrc = json_object_get(root, "audio_ssrc");
1699
                        if(ssrc)
1700
                                audio_ssrc = json_integer_value(ssrc);
1701
                }
1702
                json_t *d_port = json_object_get(root, "data_port");
1703
                if(d_port) {
1704
                        data_port = json_integer_value(d_port);
1705
                }
1706
                json_t *json_host = json_object_get(root, "host");
1707
                
1708
                guint64 room_id = json_integer_value(room);
1709
                guint64 publisher_id = json_integer_value(pub_id);
1710
                const gchar* host = json_string_value(json_host);
1711
                janus_mutex_lock(&rooms_mutex);
1712
                janus_videoroom *videoroom = NULL;
1713
                error_code = janus_videoroom_access_room(root, TRUE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1714
                janus_mutex_unlock(&rooms_mutex);
1715
                if(error_code != 0)
1716
                        goto plugin_response;
1717
                janus_mutex_lock(&videoroom->participants_mutex);
1718
                janus_videoroom_participant* publisher = g_hash_table_lookup(videoroom->participants, &publisher_id);
1719
                if(publisher == NULL) {
1720
                        janus_mutex_unlock(&videoroom->participants_mutex);
1721
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1722
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1723
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1724
                        goto plugin_response;
1725
                }
1726
                if(publisher->udp_sock <= 0) {
1727
                        publisher->udp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1728
                        if(publisher->udp_sock <= 0) {
1729
                                janus_mutex_unlock(&videoroom->participants_mutex);
1730
                                JANUS_LOG(LOG_ERR, "Could not open UDP socket for rtp stream for publisher (%"SCNu64")\n", publisher_id);
1731
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1732
                                g_snprintf(error_cause, 512, "Could not open UDP socket for rtp stream");
1733
                                goto plugin_response;
1734
                        }
1735
                }
1736
                guint32 audio_handle = 0;
1737
                guint32 video_handle = 0;
1738
                guint32 data_handle = 0;
1739
                if(audio_port > 0) {
1740
                        audio_handle = janus_videoroom_rtp_forwarder_add_helper(publisher, host, audio_port, audio_pt, audio_ssrc, FALSE, FALSE);
1741
                }
1742
                if(video_port > 0) {
1743
                        video_handle = janus_videoroom_rtp_forwarder_add_helper(publisher, host, video_port, video_pt, video_ssrc, TRUE, FALSE);
1744
                }
1745
                if(data_port > 0) {
1746
                        data_handle = janus_videoroom_rtp_forwarder_add_helper(publisher, host, data_port, 0, 0, FALSE, TRUE);
1747
                }
1748
                janus_mutex_unlock(&videoroom->participants_mutex);
1749
                response = json_object();
1750
                json_t* rtp_stream = json_object();
1751
                if(audio_handle > 0) {
1752
                        json_object_set_new(rtp_stream, "audio_stream_id", json_integer(audio_handle));
1753
                        json_object_set_new(rtp_stream, "audio", json_integer(audio_port));
1754
                }
1755
                if(video_handle > 0) {
1756
                        /* Send a FIR to the new RTP forward publisher */
1757
                        char buf[20];
1758
                        janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
1759
                        JANUS_LOG(LOG_VERB, "New RTP forward publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
1760
                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
1761
                        /* Send a PLI too, just in case... */
1762
                        janus_rtcp_pli((char *)&buf, 12);
1763
                        JANUS_LOG(LOG_VERB, "New RTP forward publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
1764
                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
1765
                        /* Done */
1766
                        json_object_set_new(rtp_stream, "video_stream_id", json_integer(video_handle));
1767
                        json_object_set_new(rtp_stream, "video", json_integer(video_port));
1768
                }
1769
                if(data_handle > 0) {
1770
                        json_object_set_new(rtp_stream, "data_stream_id", json_integer(data_handle));
1771
                        json_object_set_new(rtp_stream, "data", json_integer(data_port));
1772
                }
1773
                json_object_set_new(rtp_stream, "host", json_string(host));
1774
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1775
                json_object_set_new(response, "rtp_stream", rtp_stream);
1776
                json_object_set_new(response, "room", json_integer(room_id));
1777
                json_object_set_new(response, "videoroom", json_string("rtp_forward"));
1778
                goto plugin_response;
1779
        } else if(!strcasecmp(request_text, "stop_rtp_forward")) {
1780
                JANUS_VALIDATE_JSON_OBJECT(root, stop_rtp_forward_parameters,
1781
                        error_code, error_cause, TRUE,
1782
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1783
                if(error_code != 0)
1784
                        goto plugin_response;
1785
                json_t *room = json_object_get(root, "room");
1786
                json_t *pub_id = json_object_get(root, "publisher_id");
1787
                json_t *id = json_object_get(root, "stream_id");
1788

    
1789
                guint64 room_id = json_integer_value(room);
1790
                guint64 publisher_id = json_integer_value(pub_id);
1791
                guint32 stream_id = json_integer_value(id);
1792
                janus_mutex_lock(&rooms_mutex);
1793
                janus_videoroom *videoroom = NULL;
1794
                error_code = janus_videoroom_access_room(root, TRUE, FALSE, &videoroom, error_cause, sizeof(error_cause));
1795
                janus_mutex_unlock(&rooms_mutex);
1796
                if(error_code != 0)
1797
                        goto plugin_response;
1798
                janus_mutex_lock(&videoroom->participants_mutex);
1799
                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &publisher_id);
1800
                if(publisher == NULL) {
1801
                        janus_mutex_unlock(&videoroom->participants_mutex);
1802
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1803
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1804
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1805
                        goto plugin_response;
1806
                }
1807
                janus_mutex_lock(&publisher->rtp_forwarders_mutex);
1808
                if(g_hash_table_lookup(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id)) == NULL) {
1809
                        janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1810
                        janus_mutex_unlock(&videoroom->participants_mutex);
1811
                        JANUS_LOG(LOG_ERR, "No such stream (%"SCNu32")\n", stream_id);
1812
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1813
                        g_snprintf(error_cause, 512, "No such stream (%"SCNu32")", stream_id);
1814
                        goto plugin_response;
1815
                }
1816
                g_hash_table_remove(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id));
1817
                janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1818
                janus_mutex_unlock(&videoroom->participants_mutex);
1819
                response = json_object();
1820
                json_object_set_new(response, "videoroom", json_string("stop_rtp_forward"));
1821
                json_object_set_new(response, "room", json_integer(room_id));
1822
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1823
                json_object_set_new(response, "stream_id", json_integer(stream_id));
1824
                goto plugin_response;
1825
        } else if(!strcasecmp(request_text, "exists")) {
1826
                /* Check whether a given room exists or not, returns true/false */        
1827
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
1828
                        error_code, error_cause, TRUE,
1829
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1830
                if(error_code != 0)
1831
                        goto plugin_response;
1832
                json_t *room = json_object_get(root, "room");
1833
                guint64 room_id = json_integer_value(room);
1834
                janus_mutex_lock(&rooms_mutex);
1835
                gboolean room_exists = g_hash_table_contains(rooms, &room_id);
1836
                janus_mutex_unlock(&rooms_mutex);
1837
                response = json_object();
1838
                json_object_set_new(response, "videoroom", json_string("success"));
1839
                json_object_set_new(response, "room", json_integer(room_id));
1840
                json_object_set_new(response, "exists", room_exists ? json_true() : json_false());
1841
                goto plugin_response;
1842
        } else if(!strcasecmp(request_text, "allowed")) {
1843
                JANUS_LOG(LOG_VERB, "Attempt to edit the list of allowed participants in an existing videoroom room\n");
1844
                JANUS_VALIDATE_JSON_OBJECT(root, allowed_parameters,
1845
                        error_code, error_cause, TRUE,
1846
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1847
                if(error_code != 0)
1848
                        goto plugin_response;
1849
                json_t *action = json_object_get(root, "action");
1850
                json_t *room = json_object_get(root, "room");
1851
                json_t *allowed = json_object_get(root, "allowed");
1852
                const char *action_text = json_string_value(action);
1853
                if(strcasecmp(action_text, "enable") && strcasecmp(action_text, "disable") &&
1854
                                strcasecmp(action_text, "add") && strcasecmp(action_text, "remove")) {
1855
                        JANUS_LOG(LOG_ERR, "Unsupported action '%s' (allowed)\n", action_text);
1856
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1857
                        g_snprintf(error_cause, 512, "Unsupported action '%s' (allowed)", action_text);
1858
                        goto plugin_response;
1859
                }
1860
                guint64 room_id = json_integer_value(room);
1861
                janus_mutex_lock(&rooms_mutex);
1862
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, &room_id);
1863
                if(videoroom == NULL) {
1864
                        janus_mutex_unlock(&rooms_mutex);
1865
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1866
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1867
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1868
                        goto plugin_response;
1869
                }
1870
                /* A secret may be required for this action */
1871
                JANUS_CHECK_SECRET(videoroom->room_secret, root, "secret", error_code, error_cause,
1872
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1873
                if(error_code != 0) {
1874
                        janus_mutex_unlock(&rooms_mutex);
1875
                        goto plugin_response;
1876
                }
1877
                if(!strcasecmp(action_text, "enable")) {
1878
                        JANUS_LOG(LOG_VERB, "Enabling the check on allowed authorization tokens for room %"SCNu64"\n", room_id);
1879
                        videoroom->check_tokens = TRUE;
1880
                } else if(!strcasecmp(action_text, "disable")) {
1881
                        JANUS_LOG(LOG_VERB, "Disabling the check on allowed authorization tokens for room %"SCNu64" (free entry)\n", room_id);
1882
                        videoroom->check_tokens = FALSE;
1883
                } else {
1884
                        gboolean add = !strcasecmp(action_text, "add");
1885
                        if(allowed) {
1886
                                /* Make sure the "allowed" array only contains strings */
1887
                                gboolean ok = TRUE;
1888
                                if(json_array_size(allowed) > 0) {
1889
                                        size_t i = 0;
1890
                                        for(i=0; i<json_array_size(allowed); i++) {
1891
                                                json_t *a = json_array_get(allowed, i);
1892
                                                if(!a || !json_is_string(a)) {
1893
                                                        ok = FALSE;
1894
                                                        break;
1895
                                                }
1896
                                        }
1897
                                }
1898
                                if(!ok) {
1899
                                        JANUS_LOG(LOG_ERR, "Invalid element in the allowed array (not a string)\n");
1900
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1901
                                        g_snprintf(error_cause, 512, "Invalid element in the allowed array (not a string)");
1902
                                        janus_mutex_unlock(&rooms_mutex);
1903
                                        goto plugin_response;
1904
                                }
1905
                                size_t i = 0;
1906
                                for(i=0; i<json_array_size(allowed); i++) {
1907
                                        const char *token = json_string_value(json_array_get(allowed, i));
1908
                                        if(add) {
1909
                                                if(!g_hash_table_lookup(videoroom->allowed, token))
1910
                                                        g_hash_table_insert(videoroom->allowed, g_strdup(token), GINT_TO_POINTER(TRUE));
1911
                                        } else {
1912
                                                g_hash_table_remove(videoroom->allowed, token);
1913
                                        }
1914
                                }
1915
                        }
1916
                }
1917
                /* Prepare response */
1918
                response = json_object();
1919
                json_object_set_new(response, "videoroom", json_string("success"));
1920
                json_object_set_new(response, "room", json_integer(videoroom->room_id));
1921
                json_t *list = json_array();
1922
                if(strcasecmp(action_text, "disable")) {
1923
                        if(g_hash_table_size(videoroom->allowed) > 0) {
1924
                                GHashTableIter iter;
1925
                                gpointer key;
1926
                                g_hash_table_iter_init(&iter, videoroom->allowed);
1927
                                while(g_hash_table_iter_next(&iter, &key, NULL)) {
1928
                                        char *token = key;
1929
                                        json_array_append_new(list, json_string(token));
1930
                                }
1931
                        }
1932
                        json_object_set_new(response, "allowed", list);
1933
                }
1934
                /* Done */
1935
                janus_mutex_unlock(&rooms_mutex);
1936
                JANUS_LOG(LOG_VERB, "VideoRoom room allowed list updated\n");
1937
                goto plugin_response;
1938
        } else if(!strcasecmp(request_text, "kick")) {
1939
                JANUS_LOG(LOG_VERB, "Attempt to kick a participant from an existing videoroom room\n");
1940
                JANUS_VALIDATE_JSON_OBJECT(root, kick_parameters,
1941
                        error_code, error_cause, TRUE,
1942
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1943
                if(error_code != 0)
1944
                        goto plugin_response;
1945
                json_t *room = json_object_get(root, "room");
1946
                json_t *id = json_object_get(root, "id");
1947
                guint64 room_id = json_integer_value(room);
1948
                janus_mutex_lock(&rooms_mutex);
1949
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, &room_id);
1950
                if(videoroom == NULL) {
1951
                        janus_mutex_unlock(&rooms_mutex);
1952
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1953
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1954
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1955
                        goto plugin_response;
1956
                }
1957
                janus_mutex_lock(&videoroom->participants_mutex);
1958
                /* A secret may be required for this action */
1959
                JANUS_CHECK_SECRET(videoroom->room_secret, root, "secret", error_code, error_cause,
1960
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1961
                if(error_code != 0) {
1962
                        janus_mutex_unlock(&videoroom->participants_mutex);
1963
                        janus_mutex_unlock(&rooms_mutex);
1964
                        goto plugin_response;
1965
                }
1966
                guint64 user_id = json_integer_value(id);
1967
                janus_videoroom_participant *participant = g_hash_table_lookup(videoroom->participants, &user_id);
1968
                if(participant == NULL) {
1969
                        janus_mutex_unlock(&videoroom->participants_mutex);
1970
                        janus_mutex_unlock(&rooms_mutex);
1971
                        JANUS_LOG(LOG_ERR, "No such user %"SCNu64" in room %"SCNu64"\n", user_id, room_id);
1972
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1973
                        g_snprintf(error_cause, 512, "No such user %"SCNu64" in room %"SCNu64, user_id, room_id);
1974
                        goto plugin_response;
1975
                }
1976
                participant->audio_active = FALSE;
1977
                participant->video_active = FALSE;
1978
                participant->data_active = FALSE;
1979
                /* Prepare an event for this */
1980
                json_t *kicked = json_object();
1981
                json_object_set_new(kicked, "videoroom", json_string("event"));
1982
                json_object_set_new(kicked, "room", json_integer(participant->room->room_id));
1983
                json_object_set_new(kicked, "leaving", json_string("ok"));
1984
                json_object_set_new(kicked, "reason", json_string("kicked"));
1985
                int ret = gateway->push_event(participant->session->handle, &janus_videoroom_plugin, NULL, kicked, NULL);
1986
                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1987
                json_decref(kicked);
1988
                participant->kicked = TRUE;
1989
                participant->session->started = FALSE;
1990
                janus_mutex_unlock(&videoroom->participants_mutex);
1991
                /* This publisher is leaving, tell everybody */
1992
                janus_videoroom_leave_or_unpublish(participant, TRUE, TRUE);
1993
                /* Tell the core to tear down the PeerConnection, hangup_media will do the rest
1994
                 *         FIXME: this only kicks the publisher, but not the subscriptions it created */
1995
                if(participant && participant->session)
1996
                        gateway->close_pc(participant->session->handle);
1997
                JANUS_LOG(LOG_VERB, "Kicked user %"SCNu64" from room %"SCNu64"\n", user_id, room_id);
1998
                /* Prepare response */
1999
                response = json_object();
2000
                json_object_set_new(response, "videoroom", json_string("success"));
2001
                /* Done */
2002
                janus_mutex_unlock(&rooms_mutex);
2003
                goto plugin_response;
2004
        } else if(!strcasecmp(request_text, "listparticipants")) {
2005
                /* List all participants in a room, specifying whether they're publishers or just attendees */        
2006
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
2007
                        error_code, error_cause, TRUE,
2008
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2009
                if(error_code != 0)
2010
                        goto plugin_response;
2011
                json_t *room = json_object_get(root, "room");
2012
                guint64 room_id = json_integer_value(room);
2013
                janus_mutex_lock(&rooms_mutex);
2014
                janus_videoroom *videoroom = NULL;
2015
                error_code = janus_videoroom_access_room(root, FALSE, FALSE, &videoroom, error_cause, sizeof(error_cause));
2016
                janus_mutex_unlock(&rooms_mutex);
2017
                if(error_code != 0)
2018
                        goto plugin_response;
2019
                /* Return a list of all participants (whether they're publishing or not) */
2020
                json_t *list = json_array();
2021
                GHashTableIter iter;
2022
                gpointer value;
2023
                janus_mutex_lock(&videoroom->participants_mutex);
2024
                g_hash_table_iter_init(&iter, videoroom->participants);
2025
                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2026
                        janus_videoroom_participant *p = value;
2027
                        json_t *pl = json_object();
2028
                        json_object_set_new(pl, "id", json_integer(p->user_id));
2029
                        if(p->display)
2030
                                json_object_set_new(pl, "display", json_string(p->display));
2031
                        json_object_set_new(pl, "publisher", (p->sdp && p->session->started) ? json_true() : json_false());
2032
                        if ((p->sdp && p->session->started)) {
2033
                                json_object_set_new(pl, "internal_audio_ssrc", json_integer(p->audio_ssrc));
2034
                                json_object_set_new(pl, "internal_video_ssrc", json_integer(p->video_ssrc));
2035
                        }
2036
                        json_array_append_new(list, pl);
2037
                }
2038
                janus_mutex_unlock(&videoroom->participants_mutex);
2039
                response = json_object();
2040
                json_object_set_new(response, "videoroom", json_string("participants"));
2041
                json_object_set_new(response, "room", json_integer(room_id));
2042
                json_object_set_new(response, "participants", list);
2043
                goto plugin_response;
2044
        } else if(!strcasecmp(request_text, "listforwarders")) {
2045
                /* List all forwarders in a room */        
2046
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
2047
                        error_code, error_cause, TRUE,
2048
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2049
                if(error_code != 0)
2050
                        goto plugin_response;
2051
                json_t *room = json_object_get(root, "room");
2052
                guint64 room_id = json_integer_value(room);
2053
                janus_mutex_lock(&rooms_mutex);
2054
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, &room_id);
2055
                if(videoroom == NULL) {
2056
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
2057
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2058
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
2059
                        janus_mutex_unlock(&rooms_mutex);
2060
                        goto plugin_response;
2061
                }
2062
                if(videoroom->destroyed) {
2063
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
2064
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2065
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
2066
                        janus_mutex_unlock(&rooms_mutex);
2067
                        goto plugin_response;
2068
                }
2069
                /* A secret may be required for this action */
2070
                JANUS_CHECK_SECRET(videoroom->room_secret, root, "secret", error_code, error_cause,
2071
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
2072
                if(error_code != 0) {
2073
                        janus_mutex_unlock(&rooms_mutex);
2074
                        goto plugin_response;
2075
                }
2076
                /* Return a list of all forwarders */
2077
                json_t *list = json_array();
2078
                GHashTableIter iter;
2079
                gpointer value;
2080
                janus_mutex_lock(&videoroom->participants_mutex);
2081
                g_hash_table_iter_init(&iter, videoroom->participants);
2082
                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2083
                        janus_videoroom_participant *p = value;
2084
                        janus_mutex_lock(&p->rtp_forwarders_mutex);
2085
                        if(g_hash_table_size(p->rtp_forwarders) == 0) {
2086
                                janus_mutex_unlock(&p->rtp_forwarders_mutex);
2087
                                continue;
2088
                        }
2089
                        json_t *pl = json_object();
2090
                        json_object_set_new(pl, "publisher_id", json_integer(p->user_id));
2091
                        if(p->display)
2092
                                json_object_set_new(pl, "display", json_string(p->display));
2093
                        json_t *flist = json_array();
2094
                        GHashTableIter iter_f;
2095
                        gpointer key_f, value_f;                        
2096
                        g_hash_table_iter_init(&iter_f, p->rtp_forwarders);
2097
                        while(g_hash_table_iter_next(&iter_f, &key_f, &value_f)) {                                
2098
                                json_t *fl = json_object();
2099
                                guint32 rpk = GPOINTER_TO_UINT(key_f);
2100
                                janus_videoroom_rtp_forwarder *rpv = value_f;
2101
                                json_object_set_new(fl, "ip", json_string(inet_ntoa(rpv->serv_addr.sin_addr)));
2102
                                if(rpv->is_data) {
2103
                                        json_object_set_new(fl, "data_stream_id", json_integer(rpk));
2104
                                        json_object_set_new(fl, "port", json_integer(ntohs(rpv->serv_addr.sin_port)));
2105
                                } else if(rpv->is_video) {
2106
                                        json_object_set_new(fl, "video_stream_id", json_integer(rpk));
2107
                                        json_object_set_new(fl, "port", json_integer(ntohs(rpv->serv_addr.sin_port)));
2108
                                        if(rpv->payload_type)
2109
                                                json_object_set_new(fl, "pt", json_integer(rpv->payload_type));
2110
                                        if(rpv->ssrc)
2111
                                                json_object_set_new(fl, "ssrc", json_integer(rpv->ssrc));
2112
                                } else {
2113
                                        json_object_set_new(fl, "audio_stream_id", json_integer(rpk));
2114
                                        json_object_set_new(fl, "port", json_integer(ntohs(rpv->serv_addr.sin_port)));
2115
                                        if(rpv->payload_type)
2116
                                                json_object_set_new(fl, "pt", json_integer(rpv->payload_type));
2117
                                        if(rpv->ssrc)
2118
                                                json_object_set_new(fl, "ssrc", json_integer(rpv->ssrc));
2119
                                }
2120
                                json_array_append_new(flist, fl);
2121
                        }                
2122
                        janus_mutex_unlock(&p->rtp_forwarders_mutex);
2123
                        json_object_set_new(pl, "rtp_forwarder", flist);
2124
                        json_array_append_new(list, pl);
2125
                }
2126
                janus_mutex_unlock(&videoroom->participants_mutex);
2127
                janus_mutex_unlock(&rooms_mutex);
2128
                response = json_object();
2129
                json_object_set_new(response, "room", json_integer(room_id));
2130
                json_object_set_new(response, "rtp_forwarders", list);
2131
                goto plugin_response;
2132
        } else if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")
2133
                        || !strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish") || !strcasecmp(request_text, "unpublish")
2134
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "pause") || !strcasecmp(request_text, "switch") || !strcasecmp(request_text, "stop")
2135
                        || !strcasecmp(request_text, "add") || !strcasecmp(request_text, "remove") || !strcasecmp(request_text, "leave")) {
2136
                /* These messages are handled asynchronously */
2137

    
2138
                janus_videoroom_message *msg = g_malloc0(sizeof(janus_videoroom_message));
2139
                msg->handle = handle;
2140
                msg->transaction = transaction;
2141
                msg->message = root;
2142
                msg->jsep = jsep;
2143
                g_async_queue_push(messages, msg);
2144

    
2145
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
2146
        } else {
2147
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
2148
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
2149
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
2150
        }
2151

    
2152
plugin_response:
2153
                {
2154
                        if(error_code == 0 && !response) {
2155
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2156
                                g_snprintf(error_cause, 512, "Invalid response");
2157
                        }
2158
                        if(error_code != 0) {
2159
                                /* Prepare JSON error event */
2160
                                json_t *event = json_object();
2161
                                json_object_set_new(event, "videoroom", json_string("event"));
2162
                                json_object_set_new(event, "error_code", json_integer(error_code));
2163
                                json_object_set_new(event, "error", json_string(error_cause));
2164
                                response = event;
2165
                        }
2166
                        if(root != NULL)
2167
                                json_decref(root);
2168
                        if(jsep != NULL)
2169
                                json_decref(jsep);
2170
                        g_free(transaction);
2171

    
2172
                        return janus_plugin_result_new(JANUS_PLUGIN_OK, NULL, response);
2173
                }
2174

    
2175
}
2176

    
2177
void janus_videoroom_setup_media(janus_plugin_session *handle) {
2178
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
2179
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2180
                return;
2181
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2182
        if(!session) {
2183
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2184
                return;
2185
        }
2186
        if(session->destroyed)
2187
                return;
2188
        g_atomic_int_set(&session->hangingup, 0);
2189

    
2190
        /* Media relaying can start now */
2191
        session->started = TRUE;
2192

    
2193
        if(session->participant) {
2194
                /* If this is a publisher, notify all listeners about the fact they can
2195
                 * now subscribe; if this is a listener, instead, ask the publisher a FIR */
2196
                if(session->participant_type == janus_videoroom_p_type_publisher) {
2197
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2198
                        /* Notify all other participants that there's a new boy in town */
2199
                        json_t *list = json_array();
2200
                        json_t *pl = json_object();
2201
                        json_object_set_new(pl, "id", json_integer(participant->user_id));
2202
                        if(participant->display)
2203
                                json_object_set_new(pl, "display", json_string(participant->display));
2204
                        json_array_append_new(list, pl);
2205
                        json_t *pub = json_object();
2206
                        json_object_set_new(pub, "videoroom", json_string("event"));
2207
                        json_object_set_new(pub, "room", json_integer(participant->room->room_id));
2208
                        json_object_set_new(pub, "publishers", list);
2209
                        GHashTableIter iter;
2210
                        gpointer value;
2211
                        janus_videoroom *videoroom = participant->room;
2212
                        janus_mutex_lock(&videoroom->participants_mutex);
2213
                        g_hash_table_iter_init(&iter, videoroom->participants);
2214
                        while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2215
                                janus_videoroom_participant *p = value;
2216
                                if(p == participant) {
2217
                                        continue;        /* Skip the new publisher itself */
2218
                                }
2219
                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2220
                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, pub, NULL);
2221
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2222
                        }
2223
                        json_decref(pub);
2224
                        janus_mutex_unlock(&videoroom->participants_mutex);
2225
                        /* Also notify event handlers */
2226
                        if(notify_events && gateway->events_is_enabled()) {
2227
                                json_t *info = json_object();
2228
                                json_object_set_new(info, "event", json_string("published"));
2229
                                json_object_set_new(info, "room", json_integer(participant->room->room_id));
2230
                                json_object_set_new(info, "id", json_integer(participant->user_id));
2231
                                gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2232
                        }
2233
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2234
                        janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
2235
                        if(l && l->feed) {
2236
                                janus_videoroom_participant *p = l->feed;
2237
                                if(p && p->session) {
2238
                                        /* Send a FIR */
2239
                                        char buf[20];
2240
                                        janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
2241
                                        JANUS_LOG(LOG_VERB, "New listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2242
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 20);
2243
                                        /* Send a PLI too, just in case... */
2244
                                        janus_rtcp_pli((char *)&buf, 12);
2245
                                        JANUS_LOG(LOG_VERB, "New listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2246
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 12);
2247
                                        /* Also notify event handlers */
2248
                                        if(notify_events && gateway->events_is_enabled()) {
2249
                                                json_t *info = json_object();
2250
                                                json_object_set_new(info, "event", json_string("subscribed"));
2251
                                                json_object_set_new(info, "room", json_integer(p->room->room_id));
2252
                                                json_object_set_new(info, "feed", json_integer(p->user_id));
2253
                                                gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2254
                                        }
2255
                                }
2256
                        }
2257
                }
2258
        }
2259
}
2260

    
2261
void janus_videoroom_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
2262
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2263
                return;
2264
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2265
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2266
                return;
2267
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2268
        janus_videoroom *videoroom = participant->room;
2269

    
2270
        if(participant->kicked)
2271
                return;
2272
        /* In case this is an audio packet and we're doing talk detection, check the audio level extension */
2273
        if(!video && videoroom->audiolevel_event && participant->audio_active) {
2274
                int level = 0;
2275
                if(janus_rtp_header_extension_parse_audio_level(buf, len, participant->audio_level_extmap_id, &level) == 0) {
2276
                        participant->audio_dBov_sum += level;
2277
                        participant->audio_active_packets++;
2278
                        if(participant->audio_active_packets > 0 && participant->audio_active_packets == videoroom->audio_active_packets) {
2279
                                if((float)participant->audio_dBov_sum/(float)participant->audio_active_packets < videoroom->audio_level_average) {
2280
                                        /* Notify all participants */
2281
                                        janus_mutex_lock(&participant->room->participants_mutex);
2282
                                        json_t *event = json_object();
2283
                                        json_object_set_new(event, "videoroom", json_string("talking"));
2284
                                        json_object_set_new(event, "room", json_integer(participant->room->room_id));
2285
                                        json_object_set_new(event, "id", json_integer(participant->user_id));
2286
                                        janus_videoroom_notify_participants(participant, event);
2287
                                        json_decref(event);
2288
                                        janus_mutex_unlock(&participant->room->participants_mutex);
2289
                                        /* Also notify event handlers */
2290
                                        if(notify_events && gateway->events_is_enabled()) {
2291
                                                json_t *info = json_object();
2292
                                                json_object_set_new(info, "videoroom", json_string("talking"));
2293
                                                json_object_set_new(info, "room", json_integer(participant->room->room_id));
2294
                                                json_object_set_new(info, "id", json_integer(participant->user_id));
2295
                                                gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2296
                                        }
2297
                                }
2298
                                participant->audio_active_packets = 0;
2299
                                participant->audio_dBov_sum = 0;
2300
                        }
2301
                }
2302
        }
2303

    
2304
        if((!video && participant->audio_active) || (video && participant->video_active)) {
2305
                /* Update payload type and SSRC */
2306
                janus_mutex_lock(&participant->rtp_forwarders_mutex);
2307
                rtp_header *rtp = (rtp_header *)buf;
2308
                rtp->type = video ? participant->video_pt : participant->audio_pt;
2309
                rtp->ssrc = htonl(video ? participant->video_ssrc : participant->audio_ssrc);
2310
                /* Forward RTP to the appropriate port for the rtp_forwarders associated with this publisher, if there are any */
2311
                GHashTableIter iter;
2312
                gpointer value;
2313
                g_hash_table_iter_init(&iter, participant->rtp_forwarders);
2314
                while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
2315
                        janus_videoroom_rtp_forwarder* rtp_forward = (janus_videoroom_rtp_forwarder*)value;
2316
                        /* Check if payload type and/or SSRC need to be overwritten for this forwarder */
2317
                        int pt = rtp->type;
2318
                        uint32_t ssrc = ntohl(rtp->ssrc);
2319
                        if(rtp_forward->payload_type > 0)
2320
                                rtp->type = rtp_forward->payload_type;
2321
                        if(rtp_forward->ssrc > 0)
2322
                                rtp->ssrc = htonl(rtp_forward->ssrc);
2323
                        if(video && rtp_forward->is_video) {
2324
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2325
                        }
2326
                        else if(!video && !rtp_forward->is_video && !rtp_forward->is_data) {
2327
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2328
                        }
2329
                        /* Restore original values of payload type and SSRC before going on */
2330
                        rtp->type = pt;
2331
                        rtp->ssrc = htonl(ssrc);
2332
                }
2333
                janus_mutex_unlock(&participant->rtp_forwarders_mutex);
2334
                /* Save the frame if we're recording */
2335
                janus_recorder_save_frame(video ? participant->vrc : participant->arc, buf, len);
2336
                /* Done, relay it */
2337
                janus_videoroom_rtp_relay_packet packet;
2338
                packet.data = rtp;
2339
                packet.length = len;
2340
                packet.is_video = video;
2341
                /* Backup the actual timestamp and sequence number set by the publisher, in case switching is involved */
2342
                packet.timestamp = ntohl(packet.data->timestamp);
2343
                packet.seq_number = ntohs(packet.data->seq_number);
2344
                /* Go */
2345
                g_slist_foreach(participant->listeners, janus_videoroom_relay_rtp_packet, &packet);
2346
                
2347
                /* Check if we need to send any REMB, FIR or PLI back to this publisher */
2348
                if(video && participant->video_active) {
2349
                        /* Did we send a REMB already, or is it time to send one? */
2350
                        gboolean send_remb = FALSE;
2351
                        if(participant->remb_latest == 0 && participant->remb_startup > 0) {
2352
                                /* Still in the starting phase, send the ramp-up REMB feedback */
2353
                                send_remb = TRUE;
2354
                        } else if(participant->remb_latest > 0 && janus_get_monotonic_time()-participant->remb_latest >= 5*G_USEC_PER_SEC) {
2355
                                /* 5 seconds have passed since the last REMB, send a new one */
2356
                                send_remb = TRUE;
2357
                        }                
2358
                        if(send_remb) {
2359
                                /* We send a few incremental REMB messages at startup */
2360
                                uint64_t bitrate = (participant->bitrate ? participant->bitrate : 256*1024);
2361
                                if(participant->remb_startup > 0) {
2362
                                        bitrate = bitrate/participant->remb_startup;
2363
                                        participant->remb_startup--;
2364
                                }
2365
                                JANUS_LOG(LOG_VERB, "Sending REMB (%s, %"SCNu64")\n", participant->display, bitrate);
2366
                                char rtcpbuf[24];
2367
                                janus_rtcp_remb((char *)(&rtcpbuf), 24, bitrate);
2368
                                gateway->relay_rtcp(handle, video, rtcpbuf, 24);
2369
                                if(participant->remb_startup == 0)
2370
                                        participant->remb_latest = janus_get_monotonic_time();
2371
                        }
2372
                        /* Generate FIR/PLI too, if needed */
2373
                        if(video && participant->video_active && (participant->room->fir_freq > 0)) {
2374
                                /* FIXME Very ugly hack to generate RTCP every tot seconds/frames */
2375
                                gint64 now = janus_get_monotonic_time();
2376
                                if((now-participant->fir_latest) >= (participant->room->fir_freq*G_USEC_PER_SEC)) {
2377
                                        /* FIXME We send a FIR every tot seconds */
2378
                                        participant->fir_latest = now;
2379
                                        char rtcpbuf[24];
2380
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &participant->fir_seq);
2381
                                        JANUS_LOG(LOG_VERB, "Sending FIR to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2382
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 20);
2383
                                        /* Send a PLI too, just in case... */
2384
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2385
                                        JANUS_LOG(LOG_VERB, "Sending PLI to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2386
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 12);
2387
                                }
2388
                        }
2389
                }
2390
        }
2391
}
2392

    
2393
void janus_videoroom_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
2394
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2395
                return;
2396
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2397
        if(!session) {
2398
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2399
                return;
2400
        }
2401
        if(session->destroyed)
2402
                return;
2403
        if(session->participant_type == janus_videoroom_p_type_subscriber) {
2404
                /* A listener sent some RTCP, check what it is and if we need to forward it to the publisher */
2405
                janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
2406
                if(!l || !l->video)
2407
                        return;        /* The only feedback we handle is video related anyway... */
2408
                if(janus_rtcp_has_fir(buf, len)) {
2409
                        /* We got a FIR, forward it to the publisher */
2410
                        if(l->feed) {
2411
                                janus_videoroom_participant *p = l->feed;
2412
                                if(p && p->session) {
2413
                                        char rtcpbuf[20];
2414
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &p->fir_seq);
2415
                                        JANUS_LOG(LOG_VERB, "Got a FIR from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2416
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 20);
2417
                                }
2418
                        }
2419
                }
2420
                if(janus_rtcp_has_pli(buf, len)) {
2421
                        /* We got a PLI, forward it to the publisher */
2422
                        if(l->feed) {
2423
                                janus_videoroom_participant *p = l->feed;
2424
                                if(p && p->session) {
2425
                                        char rtcpbuf[12];
2426
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2427
                                        JANUS_LOG(LOG_VERB, "Got a PLI from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2428
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 12);
2429
                                }
2430
                        }
2431
                }
2432
                uint64_t bitrate = janus_rtcp_get_remb(buf, len);
2433
                if(bitrate > 0) {
2434
                        /* FIXME We got a REMB from this listener, should we do something about it? */
2435
                }
2436
        }
2437
}
2438

    
2439
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len) {
2440
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2441
                return;
2442
        if(buf == NULL || len <= 0)
2443
                return;
2444
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2445
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2446
                return;
2447
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2448
        if(!participant->data_active || participant->kicked)
2449
                return;
2450
        /* Any forwarder involved? */
2451
        janus_mutex_lock(&participant->rtp_forwarders_mutex);
2452
        /* Forward RTP to the appropriate port for the rtp_forwarders associated with this publisher, if there are any */
2453
        GHashTableIter iter;
2454
        gpointer value;
2455
        g_hash_table_iter_init(&iter, participant->rtp_forwarders);
2456
        while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
2457
                janus_videoroom_rtp_forwarder* rtp_forward = (janus_videoroom_rtp_forwarder*)value;
2458
                if(rtp_forward->is_data) {
2459
                        sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2460
                }
2461
        }
2462
        janus_mutex_unlock(&participant->rtp_forwarders_mutex);
2463
        /* Get a string out of the data */
2464
        char *text = g_malloc0(len+1);
2465
        memcpy(text, buf, len);
2466
        *(text+len) = '\0';
2467
        JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
2468
        /* Save the message if we're recording */
2469
        janus_recorder_save_frame(participant->drc, text, strlen(text));
2470
        /* Relay to all listeners */
2471
        g_slist_foreach(participant->listeners, janus_videoroom_relay_data_packet, text);
2472
        g_free(text);
2473
}
2474

    
2475
void janus_videoroom_slow_link(janus_plugin_session *handle, int uplink, int video) {
2476
        /* The core is informing us that our peer got too many NACKs, are we pushing media too hard? */
2477
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2478
                return;
2479
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2480
        if(!session || session->destroyed || !session->participant)
2481
                return;
2482
        /* Check if it's an uplink (publisher) or downlink (viewer) issue */
2483
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2484
                if(!uplink) {
2485
                        janus_videoroom_participant *publisher = (janus_videoroom_participant *)session->participant;
2486
                        if(publisher) {
2487
                                /* Send an event on the handle to notify the application: it's
2488
                                 * up to the application to then choose a policy and enforce it */
2489
                                json_t *event = json_object();
2490
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2491
                                /* Also add info on what the current bitrate cap is */
2492
                                uint64_t bitrate = (publisher->bitrate ? publisher->bitrate : 256*1024);
2493
                                json_object_set_new(event, "current-bitrate", json_integer(bitrate));
2494
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2495
                                json_decref(event);
2496
                        }
2497
                } else {
2498
                        JANUS_LOG(LOG_WARN, "Got a slow uplink on a VideoRoom publisher? Weird, because it doesn't receive media...\n");
2499
                }
2500
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2501
                if(uplink) {
2502
                        janus_videoroom_listener *viewer = (janus_videoroom_listener *)session->participant;
2503
                        if(viewer) {
2504
                                /* Send an event on the handle to notify the application: it's
2505
                                 * up to the application to then choose a policy and enforce it */
2506
                                json_t *event = json_object();
2507
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2508
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2509
                                json_decref(event);
2510
                        }
2511
                } else {
2512
                        JANUS_LOG(LOG_WARN, "Got a slow downlink on a VideoRoom viewer? Weird, because it doesn't send media...\n");
2513
                }
2514
        }
2515
}
2516

    
2517
static void janus_videoroom_recorder_create(janus_videoroom_participant *participant, gboolean audio, gboolean video, gboolean data) {
2518
        char filename[255];
2519
        gint64 now = janus_get_real_time();
2520
        if(audio) {
2521
                memset(filename, 0, 255);
2522
                if(participant->recording_base) {
2523
                        /* Use the filename and path we have been provided */
2524
                        g_snprintf(filename, 255, "%s-audio", participant->recording_base);
2525
                        participant->arc = janus_recorder_create(participant->room->rec_dir,
2526
                                janus_videoroom_audiocodec_name(participant->room->acodec), filename);
2527
                        if(participant->arc == NULL) {
2528
                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2529
                        }
2530
                } else {
2531
                        /* Build a filename */
2532
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-audio",
2533
                                participant->room->room_id, participant->user_id, now);
2534
                        participant->arc = janus_recorder_create(participant->room->rec_dir,
2535
                                janus_videoroom_audiocodec_name(participant->room->acodec), filename);
2536
                        if(participant->arc == NULL) {
2537
                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2538
                        }
2539
                }
2540
        }
2541
        if(video) {
2542
                memset(filename, 0, 255);
2543
                if(participant->recording_base) {
2544
                        /* Use the filename and path we have been provided */
2545
                        g_snprintf(filename, 255, "%s-video", participant->recording_base);
2546
                        participant->vrc = janus_recorder_create(participant->room->rec_dir,
2547
                                janus_videoroom_videocodec_name(participant->room->vcodec), filename);
2548
                        if(participant->vrc == NULL) {
2549
                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2550
                        }
2551
                } else {
2552
                        /* Build a filename */
2553
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-video",
2554
                                participant->room->room_id, participant->user_id, now);
2555
                        participant->vrc = janus_recorder_create(participant->room->rec_dir,
2556
                                janus_videoroom_videocodec_name(participant->room->vcodec), filename);
2557
                        if(participant->vrc == NULL) {
2558
                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2559
                        }
2560
                }
2561
        }
2562
        if(data) {
2563
                memset(filename, 0, 255);
2564
                if(participant->recording_base) {
2565
                        /* Use the filename and path we have been provided */
2566
                        g_snprintf(filename, 255, "%s-data", participant->recording_base);
2567
                        participant->drc = janus_recorder_create(participant->room->rec_dir,
2568
                                "text", filename);
2569
                        if(participant->drc == NULL) {
2570
                                JANUS_LOG(LOG_ERR, "Couldn't open an data recording file for this publisher!\n");
2571
                        }
2572
                } else {
2573
                        /* Build a filename */
2574
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-data",
2575
                                participant->room->room_id, participant->user_id, now);
2576
                        participant->drc = janus_recorder_create(participant->room->rec_dir,
2577
                                "text", filename);
2578
                        if(participant->drc == NULL) {
2579
                                JANUS_LOG(LOG_ERR, "Couldn't open an data recording file for this publisher!\n");
2580
                        }
2581
                }
2582
        }
2583
}
2584

    
2585
static void janus_videoroom_recorder_close(janus_videoroom_participant *participant) {
2586
        if(participant->arc) {
2587
                janus_recorder_close(participant->arc);
2588
                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", participant->arc->filename ? participant->arc->filename : "??");
2589
                janus_recorder_free(participant->arc);
2590
        }
2591
        participant->arc = NULL;
2592
        if(participant->vrc) {
2593
                janus_recorder_close(participant->vrc);
2594
                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", participant->vrc->filename ? participant->vrc->filename : "??");
2595
                janus_recorder_free(participant->vrc);
2596
        }
2597
        participant->vrc = NULL;
2598
        if(participant->drc) {
2599
                janus_recorder_close(participant->drc);
2600
                JANUS_LOG(LOG_INFO, "Closed data recording %s\n", participant->drc->filename ? participant->drc->filename : "??");
2601
                janus_recorder_free(participant->drc);
2602
        }
2603
        participant->drc = NULL;
2604
}
2605

    
2606
void janus_videoroom_hangup_media(janus_plugin_session *handle) {
2607
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
2608
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2609
                return;
2610
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2611
        if(!session) {
2612
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2613
                return;
2614
        }
2615
        session->started = FALSE;
2616
        if(session->destroyed)
2617
                return;
2618
        if(g_atomic_int_add(&session->hangingup, 1))
2619
                return;
2620
        /* Send an event to the browser and tell the PeerConnection is over */
2621
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2622
                /* This publisher just 'unpublished' */
2623
                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2624
                if(participant->sdp)
2625
                        g_free(participant->sdp);
2626
                participant->sdp = NULL;
2627
                participant->firefox = FALSE;
2628
                participant->audio_active = FALSE;
2629
                participant->video_active = FALSE;
2630
                participant->data_active = FALSE;
2631
                participant->audio_active_packets = 0;
2632
                participant->audio_dBov_sum = 0;
2633
                participant->remb_startup = 4;
2634
                participant->remb_latest = 0;
2635
                participant->fir_latest = 0;
2636
                participant->fir_seq = 0;
2637
                /* Get rid of the recorders, if available */
2638
                janus_mutex_lock(&participant->rec_mutex);
2639
                janus_videoroom_recorder_close(participant);
2640
                janus_mutex_unlock(&participant->rec_mutex);
2641
                janus_mutex_lock(&participant->listeners_mutex);
2642
                while(participant->listeners) {
2643
                        janus_videoroom_listener *l = (janus_videoroom_listener *)participant->listeners->data;
2644
                        if(l) {
2645
                                participant->listeners = g_slist_remove(participant->listeners, l);
2646
                                l->feed = NULL;
2647
                        }
2648
                }
2649
                janus_mutex_unlock(&participant->listeners_mutex);
2650
                janus_videoroom_leave_or_unpublish(participant, FALSE, FALSE);
2651
                /* Also notify event handlers */
2652
                if(participant->room && gateway->events_is_enabled()) {
2653
                        json_t *info = json_object();
2654
                        json_object_set_new(info, "event", json_string("unpublished"));
2655
                        json_object_set_new(info, "room", json_integer(participant->room->room_id));
2656
                        json_object_set_new(info, "id", json_integer(participant->user_id));
2657
                        gateway->notify_event(&janus_videoroom_plugin, handle, info);
2658
                }
2659
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2660
                /* Get rid of listener */
2661
                janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2662
                if(listener) {
2663
                        listener->paused = TRUE;
2664
                        janus_videoroom_participant *publisher = listener->feed;
2665
                        if(publisher != NULL) {
2666
                                janus_mutex_lock(&publisher->listeners_mutex);
2667
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
2668
                                janus_mutex_unlock(&publisher->listeners_mutex);
2669
                                listener->feed = NULL;
2670
                                /* Also notify event handlers */
2671
                                if(notify_events && gateway->events_is_enabled()) {
2672
                                        json_t *info = json_object();
2673
                                        json_object_set_new(info, "event", json_string("unsubscribed"));
2674
                                        json_object_set_new(info, "room", json_integer(publisher->room->room_id));
2675
                                        json_object_set_new(info, "feed", json_integer(publisher->user_id));
2676
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2677
                                }
2678
                        }
2679
                }
2680
                /* TODO Should we close the handle as well? */
2681
        }
2682
}
2683

    
2684
/* Thread to handle incoming messages */
2685
static void *janus_videoroom_handler(void *data) {
2686
        JANUS_LOG(LOG_VERB, "Joining VideoRoom handler thread\n");
2687
        janus_videoroom_message *msg = NULL;
2688
        int error_code = 0;
2689
        char error_cause[512];
2690
        json_t *root = NULL;
2691
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
2692
                msg = g_async_queue_pop(messages);
2693
                if(msg == NULL)
2694
                        continue;
2695
                if(msg == &exit_message)
2696
                        break;
2697
                if(msg->handle == NULL) {
2698
                        janus_videoroom_message_free(msg);
2699
                        continue;
2700
                }
2701
                janus_videoroom_session *session = NULL;
2702
                janus_mutex_lock(&sessions_mutex);
2703
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
2704
                        session = (janus_videoroom_session *)msg->handle->plugin_handle;
2705
                }
2706
                janus_mutex_unlock(&sessions_mutex);
2707
                if(!session) {
2708
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2709
                        janus_videoroom_message_free(msg);
2710
                        continue;
2711
                }
2712
                if(session->destroyed) {
2713
                        janus_videoroom_message_free(msg);
2714
                        continue;
2715
                }
2716
                /* Handle request */
2717
                error_code = 0;
2718
                root = NULL;
2719
                if(msg->message == NULL) {
2720
                        JANUS_LOG(LOG_ERR, "No message??\n");
2721
                        error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
2722
                        g_snprintf(error_cause, 512, "%s", "No message??");
2723
                        goto error;
2724
                }
2725
                root = msg->message;
2726
                /* Get the request first */
2727
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
2728
                        error_code, error_cause, TRUE,
2729
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2730
                if(error_code != 0)
2731
                        goto error;
2732
                json_t *request = json_object_get(root, "request");
2733
                const char *request_text = json_string_value(request);
2734
                json_t *event = NULL;
2735
                /* 'create' and 'destroy' are handled synchronously: what kind of participant is this session referring to? */
2736
                if(session->participant_type == janus_videoroom_p_type_none) {
2737
                        JANUS_LOG(LOG_VERB, "Configuring new participant\n");
2738
                        /* Not configured yet, we need to do this now */
2739
                        if(strcasecmp(request_text, "join") && strcasecmp(request_text, "joinandconfigure")) {
2740
                                JANUS_LOG(LOG_ERR, "Invalid request on unconfigured participant\n");
2741
                                error_code = JANUS_VIDEOROOM_ERROR_JOIN_FIRST;
2742
                                g_snprintf(error_cause, 512, "Invalid request on unconfigured participant");
2743
                                goto error;
2744
                        }
2745
                        JANUS_VALIDATE_JSON_OBJECT(root, join_parameters,
2746
                                error_code, error_cause, TRUE,
2747
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2748
                        if(error_code != 0)
2749
                                goto error;
2750
                        janus_mutex_lock(&rooms_mutex);
2751
                        janus_videoroom *videoroom = NULL;
2752
                        error_code = janus_videoroom_access_room(root, FALSE, TRUE, &videoroom, error_cause, sizeof(error_cause));
2753
                        janus_mutex_unlock(&rooms_mutex);
2754
                        if(error_code != 0)
2755
                                goto error;
2756
                        json_t *ptype = json_object_get(root, "ptype");
2757
                        const char *ptype_text = json_string_value(ptype);
2758
                        if(!strcasecmp(ptype_text, "publisher")) {
2759
                                JANUS_LOG(LOG_VERB, "Configuring new publisher\n");
2760
                                JANUS_VALIDATE_JSON_OBJECT(root, publisher_parameters,
2761
                                        error_code, error_cause, TRUE,
2762
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2763
                                if(error_code != 0)
2764
                                        goto error;
2765
                                /* A token might be required to join */
2766
                                if(videoroom->check_tokens) {
2767
                                        json_t *token = json_object_get(root, "token");
2768
                                        const char *token_text = token ? json_string_value(token) : NULL;
2769
                                        if(token_text == NULL || g_hash_table_lookup(videoroom->allowed, token_text) == NULL) {
2770
                                                JANUS_LOG(LOG_ERR, "Unauthorized (not in the allowed list)\n");
2771
                                                error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
2772
                                                g_snprintf(error_cause, 512, "Unauthorized (not in the allowed list)");
2773
                                                goto error;
2774
                                        }
2775
                                }
2776
                                json_t *display = json_object_get(root, "display");
2777
                                const char *display_text = display ? json_string_value(display) : NULL;
2778
                                guint64 user_id = 0;
2779
                                json_t *id = json_object_get(root, "id");
2780
                                janus_mutex_lock(&videoroom->participants_mutex);
2781
                                if(id) {
2782
                                        user_id = json_integer_value(id);
2783
                                        if(g_hash_table_lookup(videoroom->participants, &user_id) != NULL) {
2784
                                                janus_mutex_unlock(&videoroom->participants_mutex);
2785
                                                /* User ID already taken */
2786
                                                JANUS_LOG(LOG_ERR, "User ID %"SCNu64" already exists\n", user_id);
2787
                                                error_code = JANUS_VIDEOROOM_ERROR_ID_EXISTS;
2788
                                                g_snprintf(error_cause, 512, "User ID %"SCNu64" already exists", user_id);
2789
                                                goto error;
2790
                                        }
2791
                                }
2792
                                if(user_id == 0) {
2793
                                        /* Generate a random ID */
2794
                                        while(user_id == 0) {
2795
                                                user_id = janus_random_uint64();
2796
                                                if(g_hash_table_lookup(videoroom->participants, &user_id) != NULL) {
2797
                                                        /* User ID already taken, try another one */
2798
                                                        user_id = 0;
2799
                                                }
2800
                                        }
2801
                                }
2802
                                JANUS_LOG(LOG_VERB, "  -- Publisher ID: %"SCNu64"\n", user_id);
2803
                                /* Process the request */
2804
                                json_t *audio = NULL, *video = NULL, *data = NULL,
2805
                                        *bitrate = NULL, *record = NULL, *recfile = NULL;
2806
                                if(!strcasecmp(request_text, "joinandconfigure")) {
2807
                                        /* Also configure (or publish a new feed) audio/video/bitrate for this new publisher */
2808
                                        /* join_parameters were validated earlier. */
2809
                                        audio = json_object_get(root, "audio");
2810
                                        video = json_object_get(root, "video");
2811
                                        data = json_object_get(root, "data");
2812
                                        bitrate = json_object_get(root, "bitrate");
2813
                                        record = json_object_get(root, "record");
2814
                                        recfile = json_object_get(root, "filename");
2815
                                }
2816
                                janus_videoroom_participant *publisher = g_malloc0(sizeof(janus_videoroom_participant));
2817
                                publisher->session = session;
2818
                                publisher->room = videoroom;
2819
                                publisher->user_id = user_id;
2820
                                publisher->display = display_text ? g_strdup(display_text) : NULL;
2821
                                publisher->sdp = NULL;                /* We'll deal with this later */
2822
                                publisher->audio = FALSE;        /* We'll deal with this later */
2823
                                publisher->video = FALSE;        /* We'll deal with this later */
2824
                                publisher->data = FALSE;        /* We'll deal with this later */
2825
                                publisher->audio_active = FALSE;
2826
                                publisher->video_active = FALSE;
2827
                                publisher->data_active = FALSE;
2828
                                publisher->recording_active = FALSE;
2829
                                publisher->recording_base = NULL;
2830
                                publisher->arc = NULL;
2831
                                publisher->vrc = NULL;
2832
                                publisher->drc = NULL;
2833
                                janus_mutex_init(&publisher->rec_mutex);
2834
                                publisher->firefox = FALSE;
2835
                                publisher->bitrate = videoroom->bitrate;
2836
                                publisher->listeners = NULL;
2837
                                janus_mutex_init(&publisher->listeners_mutex);
2838
                                publisher->audio_pt = OPUS_PT;
2839
                                switch(videoroom->acodec) {
2840
                                        case JANUS_VIDEOROOM_OPUS:
2841
                                                publisher->audio_pt = OPUS_PT;
2842
                                                break;
2843
                                        case JANUS_VIDEOROOM_ISAC_32K:
2844
                                                publisher->audio_pt = ISAC32_PT;
2845
                                                break;
2846
                                        case JANUS_VIDEOROOM_ISAC_16K:
2847
                                                publisher->audio_pt = ISAC16_PT;
2848
                                                break;
2849
                                        case JANUS_VIDEOROOM_PCMU:
2850
                                                publisher->audio_pt = PCMU_PT;
2851
                                                break;
2852
                                        case JANUS_VIDEOROOM_PCMA:
2853
                                                publisher->audio_pt = PCMA_PT;
2854
                                                break;
2855
                                        case JANUS_VIDEOROOM_G722:
2856
                                                publisher->audio_pt = G722_PT;
2857
                                                break;
2858
                                        default:
2859
                                                /* Shouldn't happen */
2860
                                                publisher->audio_pt = OPUS_PT;
2861
                                                break;
2862
                                }
2863
                                switch(videoroom->vcodec) {
2864
                                        case JANUS_VIDEOROOM_VP8:
2865
                                                publisher->video_pt = VP8_PT;
2866
                                                break;
2867
                                        case JANUS_VIDEOROOM_VP9:
2868
                                                publisher->video_pt = VP9_PT;
2869
                                                break;
2870
                                        case JANUS_VIDEOROOM_H264:
2871
                                                publisher->video_pt = H264_PT;
2872
                                                break;
2873
                                        default:
2874
                                                /* Shouldn't happen */
2875
                                                publisher->video_pt = VP8_PT;
2876
                                                break;
2877
                                }
2878
                                publisher->audio_ssrc = janus_random_uint32();
2879
                                publisher->video_ssrc = janus_random_uint32();
2880
                                publisher->audio_level_extmap_id = 0;
2881
                                publisher->video_orient_extmap_id = 0;
2882
                                publisher->playout_delay_extmap_id = 0;
2883
                                publisher->remb_startup = 4;
2884
                                publisher->remb_latest = 0;
2885
                                publisher->fir_latest = 0;
2886
                                publisher->fir_seq = 0;
2887
                                janus_mutex_init(&publisher->rtp_forwarders_mutex);
2888
                                publisher->rtp_forwarders = g_hash_table_new_full(NULL, NULL, NULL, (GDestroyNotify)janus_videoroom_rtp_forwarder_free_helper);
2889
                                publisher->udp_sock = -1;
2890
                                /* Finally, generate a private ID: this is only needed in case the participant
2891
                                 * wants to allow the plugin to know which subscriptions belong to them */
2892
                                publisher->pvt_id = 0;
2893
                                while(publisher->pvt_id == 0) {
2894
                                        publisher->pvt_id = janus_random_uint32();
2895
                                        if(g_hash_table_lookup(videoroom->private_ids, GUINT_TO_POINTER(publisher->pvt_id)) != NULL) {
2896
                                                /* Private ID already taken, try another one */
2897
                                                publisher->pvt_id = 0;
2898
                                        }
2899
                                        g_hash_table_insert(videoroom->private_ids, GUINT_TO_POINTER(publisher->pvt_id), publisher);
2900
                                }
2901
                                /* In case we also wanted to configure */
2902
                                if(audio) {
2903
                                        publisher->audio_active = json_is_true(audio);
2904
                                        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);
2905
                                }
2906
                                if(video) {
2907
                                        publisher->video_active = json_is_true(video);
2908
                                        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);
2909
                                }
2910
                                if(data) {
2911
                                        publisher->data_active = json_is_true(data);
2912
                                        JANUS_LOG(LOG_VERB, "Setting data property: %s (room %"SCNu64", user %"SCNu64")\n", publisher->data_active ? "true" : "false", publisher->room->room_id, publisher->user_id);
2913
                                }
2914
                                if(bitrate) {
2915
                                        publisher->bitrate = json_integer_value(bitrate);
2916
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", publisher->bitrate, publisher->room->room_id, publisher->user_id);
2917
                                }
2918
                                if(record) {
2919
                                        publisher->recording_active = json_is_true(record);
2920
                                        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);
2921
                                }
2922
                                if(recfile) {
2923
                                        publisher->recording_base = g_strdup(json_string_value(recfile));
2924
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", publisher->recording_base, publisher->room->room_id, publisher->user_id);
2925
                                }
2926
                                /* Done */
2927
                                session->participant_type = janus_videoroom_p_type_publisher;
2928
                                session->participant = publisher;
2929
                                /* Return a list of all available publishers (those with an SDP available, that is) */
2930
                                json_t *list = json_array();
2931
                                GHashTableIter iter;
2932
                                gpointer value;
2933
                                g_hash_table_insert(videoroom->participants, janus_uint64_dup(publisher->user_id), publisher);
2934
                                g_hash_table_iter_init(&iter, videoroom->participants);
2935
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2936
                                        janus_videoroom_participant *p = value;
2937
                                        if(p == publisher || !p->sdp || !p->session->started) {
2938
                                                continue;
2939
                                        }
2940
                                        json_t *pl = json_object();
2941
                                        json_object_set_new(pl, "id", json_integer(p->user_id));
2942
                                        if(p->display)
2943
                                                json_object_set_new(pl, "display", json_string(p->display));
2944
                                        json_array_append_new(list, pl);
2945
                                }
2946
                                janus_mutex_unlock(&videoroom->participants_mutex);
2947
                                event = json_object();
2948
                                json_object_set_new(event, "videoroom", json_string("joined"));
2949
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
2950
                                json_object_set_new(event, "description", json_string(videoroom->room_name));
2951
                                json_object_set_new(event, "id", json_integer(user_id));
2952
                                json_object_set_new(event, "private_id", json_integer(publisher->pvt_id));
2953
                                json_object_set_new(event, "publishers", list);
2954
                                /* Also notify event handlers */
2955
                                if(notify_events && gateway->events_is_enabled()) {
2956
                                        json_t *info = json_object();
2957
                                        json_object_set_new(info, "event", json_string("joined"));
2958
                                        json_object_set_new(info, "room", json_integer(videoroom->room_id));
2959
                                        json_object_set_new(info, "id", json_integer(user_id));
2960
                                        json_object_set_new(info, "private_id", json_integer(publisher->pvt_id));
2961
                                        if(display_text != NULL)
2962
                                                json_object_set_new(info, "display", json_string(display_text));
2963
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2964
                                }
2965
                        } else if(!strcasecmp(ptype_text, "listener")) {
2966
                                JANUS_LOG(LOG_VERB, "Configuring new listener\n");
2967
                                /* This is a new listener */
2968
                                JANUS_VALIDATE_JSON_OBJECT(root, listener_parameters,
2969
                                        error_code, error_cause, TRUE,
2970
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2971
                                if(error_code != 0)
2972
                                        goto error;
2973
                                json_t *feed = json_object_get(root, "feed");
2974
                                guint64 feed_id = json_integer_value(feed);
2975
                                json_t *pvt = json_object_get(root, "private_id");
2976
                                guint64 pvt_id = json_integer_value(pvt);
2977
                                json_t *audio = json_object_get(root, "audio");
2978
                                json_t *video = json_object_get(root, "video");
2979
                                json_t *data = json_object_get(root, "data");
2980
                                janus_mutex_lock(&videoroom->participants_mutex);
2981
                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &feed_id);
2982
                                janus_mutex_unlock(&videoroom->participants_mutex);
2983
                                if(publisher == NULL || publisher->sdp == NULL) {
2984
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2985
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2986
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2987
                                        goto error;
2988
                                } else {
2989
                                        janus_videoroom_listener *listener = g_malloc0(sizeof(janus_videoroom_listener));
2990
                                        listener->session = session;
2991
                                        listener->room = videoroom;
2992
                                        listener->feed = publisher;
2993
                                        listener->pvt_id = pvt_id;
2994
                                        /* Initialize the listener context */
2995
                                        janus_rtp_switching_context_reset(&listener->context);
2996
                                        listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
2997
                                        if(!publisher->audio)
2998
                                                listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
2999
                                        listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
3000
                                        if(!publisher->video)
3001
                                                listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
3002
                                        listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
3003
                                        if(!publisher->data)
3004
                                                listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
3005
                                        listener->paused = TRUE;        /* We need an explicit start from the listener */
3006
                                        session->participant = listener;
3007
                                        janus_mutex_lock(&publisher->listeners_mutex);
3008
                                        publisher->listeners = g_slist_append(publisher->listeners, listener);
3009
                                        janus_mutex_unlock(&publisher->listeners_mutex);
3010
                                        event = json_object();
3011
                                        json_object_set_new(event, "videoroom", json_string("attached"));
3012
                                        json_object_set_new(event, "room", json_integer(videoroom->room_id));
3013
                                        json_object_set_new(event, "id", json_integer(feed_id));
3014
                                        if(publisher->display)
3015
                                                json_object_set_new(event, "display", json_string(publisher->display));
3016
                                        session->participant_type = janus_videoroom_p_type_subscriber;
3017
                                        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3018
                                        /* Negotiate by sending the selected publisher SDP back */
3019
                                        if(publisher->sdp != NULL) {
3020
                                                json_t *jsep = json_pack("{ssss}", "type", "offer", "sdp", publisher->sdp);
3021
                                                /* How long will the gateway take to push the event? */
3022
                                                g_atomic_int_set(&session->hangingup, 0);
3023
                                                gint64 start = janus_get_monotonic_time();
3024
                                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, jsep);
3025
                                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3026
                                                json_decref(event);
3027
                                                json_decref(jsep);
3028
                                                janus_videoroom_message_free(msg);
3029
                                                /* Also notify event handlers */
3030
                                                if(notify_events && gateway->events_is_enabled()) {
3031
                                                        json_t *info = json_object();
3032
                                                        json_object_set_new(info, "event", json_string("subscribing"));
3033
                                                        json_object_set_new(info, "room", json_integer(videoroom->room_id));
3034
                                                        json_object_set_new(info, "feed", json_integer(feed_id));
3035
                                                        json_object_set_new(info, "private_id", json_integer(pvt_id));
3036
                                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3037
                                                }
3038
                                                continue;
3039
                                        }
3040
                                }
3041
                        } else {
3042
                                JANUS_LOG(LOG_ERR, "Invalid element (ptype)\n");
3043
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3044
                                g_snprintf(error_cause, 512, "Invalid element (ptype)");
3045
                                goto error;
3046
                        }
3047
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
3048
                        /* Handle this publisher */
3049
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3050
                        if(participant == NULL) {
3051
                                JANUS_LOG(LOG_ERR, "Invalid participant instance\n");
3052
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
3053
                                g_snprintf(error_cause, 512, "Invalid participant instance");
3054
                                goto error;
3055
                        }
3056
                        if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")) {
3057
                                JANUS_LOG(LOG_ERR, "Already in as a publisher on this handle\n");
3058
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
3059
                                g_snprintf(error_cause, 512, "Already in as a publisher on this handle");
3060
                                goto error;
3061
                        } else if(!strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish")) {
3062
                                if(!strcasecmp(request_text, "publish") && participant->sdp) {
3063
                                        JANUS_LOG(LOG_ERR, "Can't publish, already published\n");
3064
                                        error_code = JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED;
3065
                                        g_snprintf(error_cause, 512, "Can't publish, already published");
3066
                                        goto error;
3067
                                }
3068
                                if(participant->kicked) {
3069
                                        JANUS_LOG(LOG_ERR, "Unauthorized, you have been kicked\n");
3070
                                        error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
3071
                                        g_snprintf(error_cause, 512, "Unauthorized, you have been kicked");
3072
                                        goto error;
3073
                                }
3074
                                /* Configure (or publish a new feed) audio/video/bitrate for this publisher */
3075
                                JANUS_VALIDATE_JSON_OBJECT(root, publish_parameters,
3076
                                        error_code, error_cause, TRUE,
3077
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3078
                                if(error_code != 0)
3079
                                        goto error;
3080
                                json_t *audio = json_object_get(root, "audio");
3081
                                json_t *video = json_object_get(root, "video");
3082
                                json_t *data = json_object_get(root, "data");
3083
                                json_t *bitrate = json_object_get(root, "bitrate");
3084
                                json_t *record = json_object_get(root, "record");
3085
                                json_t *recfile = json_object_get(root, "filename");
3086
                                json_t *display = json_object_get(root, "display");
3087
                                if(audio) {
3088
                                        gboolean audio_active = json_is_true(audio);
3089
                                        if(session->started && audio_active && !participant->audio_active) {
3090
                                                /* Audio was just resumed, try resetting the RTP headers for viewers */
3091
                                                janus_mutex_lock(&participant->listeners_mutex);
3092
                                                GSList *ps = participant->listeners;
3093
                                                while(ps) {
3094
                                                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
3095
                                                        if(l)
3096
                                                                l->context.a_seq_reset = TRUE;
3097
                                                        ps = ps->next;
3098
                                                }
3099
                                                janus_mutex_unlock(&participant->listeners_mutex);
3100
                                        }
3101
                                        participant->audio_active = audio_active;
3102
                                        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);
3103
                                }
3104
                                if(video) {
3105
                                        gboolean video_active = json_is_true(video);
3106
                                        if(session->started && video_active && !participant->video_active) {
3107
                                                /* Video was just resumed, try resetting the RTP headers for viewers */
3108
                                                janus_mutex_lock(&participant->listeners_mutex);
3109
                                                GSList *ps = participant->listeners;
3110
                                                while(ps) {
3111
                                                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
3112
                                                        if(l)
3113
                                                                l->context.v_seq_reset = TRUE;
3114
                                                        ps = ps->next;
3115
                                                }
3116
                                                janus_mutex_unlock(&participant->listeners_mutex);
3117
                                        }
3118
                                        participant->video_active = video_active;
3119
                                        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);
3120
                                }
3121
                                if(data) {
3122
                                        gboolean data_active = json_is_true(data);
3123
                                        participant->data_active = data_active;
3124
                                        JANUS_LOG(LOG_VERB, "Setting data property: %s (room %"SCNu64", user %"SCNu64")\n", participant->data_active ? "true" : "false", participant->room->room_id, participant->user_id);
3125
                                }
3126
                                if(bitrate) {
3127
                                        participant->bitrate = json_integer_value(bitrate);
3128
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", participant->bitrate, participant->room->room_id, participant->user_id);
3129
                                        /* Send a new REMB */
3130
                                        if(session->started)
3131
                                                participant->remb_latest = janus_get_monotonic_time();
3132
                                        char rtcpbuf[24];
3133
                                        janus_rtcp_remb((char *)(&rtcpbuf), 24, participant->bitrate ? participant->bitrate : 256*1024);
3134
                                        gateway->relay_rtcp(msg->handle, 1, rtcpbuf, 24);
3135
                                }
3136
                                janus_mutex_lock(&participant->rec_mutex);
3137
                                gboolean prev_recording_active = participant->recording_active;
3138
                                if(record) {
3139
                                        participant->recording_active = json_is_true(record);
3140
                                        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);
3141
                                }
3142
                                if(recfile) {
3143
                                        participant->recording_base = g_strdup(json_string_value(recfile));
3144
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", participant->recording_base, participant->room->room_id, participant->user_id);
3145
                                }
3146
                                /* Do we need to do something with the recordings right now? */
3147
                                if(participant->recording_active != prev_recording_active) {
3148
                                        /* Something changed */
3149
                                        if(!participant->recording_active) {
3150
                                                /* Not recording (anymore?) */
3151
                                                janus_videoroom_recorder_close(participant);
3152
                                        } else if(participant->recording_active && participant->sdp) {
3153
                                                /* We've started recording, send a PLI/FIR and go on */
3154
                                                janus_videoroom_recorder_create(
3155
                                                        participant, strstr(participant->sdp, "m=audio") != NULL,
3156
                                                        strstr(participant->sdp, "m=video") != NULL,
3157
                                                        strstr(participant->sdp, "m=application") != NULL);
3158
                                                if(strstr(participant->sdp, "m=video")) {
3159
                                                        /* Send a FIR */
3160
                                                        char buf[20];
3161
                                                        memset(buf, 0, 20);
3162
                                                        janus_rtcp_fir((char *)&buf, 20, &participant->fir_seq);
3163
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending FIR to %"SCNu64" (%s)\n",
3164
                                                                participant->user_id, participant->display ? participant->display : "??");
3165
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 20);
3166
                                                        /* Send a PLI too, just in case... */
3167
                                                        janus_rtcp_pli((char *)&buf, 12);
3168
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending PLI to %"SCNu64" (%s)\n",
3169
                                                                participant->user_id, participant->display ? participant->display : "??");
3170
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 12);
3171
                                                }
3172
                                        }
3173
                                }
3174
                                janus_mutex_unlock(&participant->rec_mutex);
3175
                                if(display) {
3176
                                        janus_mutex_lock(&participant->room->participants_mutex);
3177
                                        char *old_display = participant->display;
3178
                                        char *new_display = g_strdup(json_string_value(display));
3179
                                        participant->display = new_display;
3180
                                        g_free(old_display);
3181
                                        json_t *display_event = json_object();
3182
                                        json_object_set_new(display_event, "videoroom", json_string("event"));
3183
                                        json_object_set_new(display_event, "id", json_integer(participant->user_id));
3184
                                        json_object_set_new(display_event, "display", json_string(participant->display));
3185
                                        if(participant->room && !participant->room->destroyed) {
3186
                                                janus_videoroom_notify_participants(participant, display_event);
3187
                                        }
3188
                                        janus_mutex_unlock(&participant->room->participants_mutex);
3189
                                        json_decref(display_event);
3190
                                }
3191
                                /* Done */
3192
                                event = json_object();
3193
                                json_object_set_new(event, "videoroom", json_string("event"));
3194
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
3195
                                json_object_set_new(event, "configured", json_string("ok"));
3196
                                /* Also notify event handlers */
3197
                                if(notify_events && gateway->events_is_enabled()) {
3198
                                        json_t *info = json_object();
3199
                                        json_object_set_new(info, "event", json_string("configured"));
3200
                                        json_object_set_new(info, "room", json_integer(participant->room->room_id));
3201
                                        json_object_set_new(info, "id", json_integer(participant->user_id));
3202
                                        json_object_set_new(info, "audio_active", participant->audio_active ? json_true() : json_false());
3203
                                        json_object_set_new(info, "video_active", participant->video_active ? json_true() : json_false());
3204
                                        json_object_set_new(info, "data_active", participant->data_active ? json_true() : json_false());
3205
                                        json_object_set_new(info, "bitrate", json_integer(participant->bitrate));
3206
                                        if(participant->arc || participant->vrc || participant->drc) {
3207
                                                json_t *recording = json_object();
3208
                                                if(participant->arc && participant->arc->filename)
3209
                                                        json_object_set_new(recording, "audio", json_string(participant->arc->filename));
3210
                                                if(participant->vrc && participant->vrc->filename)
3211
                                                        json_object_set_new(recording, "video", json_string(participant->vrc->filename));
3212
                                                if(participant->drc && participant->drc->filename)
3213
                                                        json_object_set_new(recording, "data", json_string(participant->drc->filename));
3214
                                                json_object_set_new(info, "recording", recording);
3215
                                        }
3216
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3217
                                }
3218
                        } else if(!strcasecmp(request_text, "unpublish")) {
3219
                                /* This participant wants to unpublish */
3220
                                if(!participant->sdp) {
3221
                                        JANUS_LOG(LOG_ERR, "Can't unpublish, not published\n");
3222
                                        error_code = JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED;
3223
                                        g_snprintf(error_cause, 512, "Can't unpublish, not published");
3224
                                        goto error;
3225
                                }
3226
                                /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
3227
                                gateway->close_pc(session->handle);
3228
                                /* Done */
3229
                                event = json_object();
3230
                                json_object_set_new(event, "videoroom", json_string("event"));
3231
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
3232
                                json_object_set_new(event, "unpublished", json_string("ok"));
3233
                        } else if(!strcasecmp(request_text, "leave")) {
3234
                                /* Prepare an event to confirm the request */
3235
                                event = json_object();
3236
                                json_object_set_new(event, "videoroom", json_string("event"));
3237
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
3238
                                json_object_set_new(event, "leaving", json_string("ok"));
3239
                                /* This publisher is leaving, tell everybody */
3240
                                session->participant_type = janus_videoroom_p_type_none;
3241
                                janus_videoroom_leave_or_unpublish(participant, TRUE, FALSE);
3242
                                /* Done */
3243
                                participant->audio_active = FALSE;
3244
                                participant->video_active = FALSE;
3245
                                participant->data_active = FALSE;
3246
                                session->started = FALSE;
3247
                                //~ session->destroy = TRUE;
3248
                        } else {
3249
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3250
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3251
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3252
                                goto error;
3253
                        }
3254
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
3255
                        /* Handle this listener */
3256
                        janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
3257
                        if(listener == NULL) {
3258
                                JANUS_LOG(LOG_ERR, "Invalid listener instance\n");
3259
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
3260
                                g_snprintf(error_cause, 512, "Invalid listener instance");
3261
                                goto error;
3262
                        }
3263
                        if(!strcasecmp(request_text, "join")) {
3264
                                JANUS_LOG(LOG_ERR, "Already in as a listener on this handle\n");
3265
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
3266
                                g_snprintf(error_cause, 512, "Already in as a listener on this handle");
3267
                                goto error;
3268
                        } else if(!strcasecmp(request_text, "start")) {
3269
                                /* Start/restart receiving the publisher streams */
3270
                                janus_videoroom_participant *publisher = listener->feed;
3271
                                listener->paused = FALSE;
3272
                                event = json_object();
3273
                                json_object_set_new(event, "videoroom", json_string("event"));
3274
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3275
                                json_object_set_new(event, "started", json_string("ok"));
3276
                                if(publisher) {
3277
                                        /* Send a FIR */
3278
                                        char buf[20];
3279
                                        janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3280
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3281
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3282
                                        /* Send a PLI too, just in case... */
3283
                                        janus_rtcp_pli((char *)&buf, 12);
3284
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3285
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3286
                                }
3287
                        } else if(!strcasecmp(request_text, "configure")) {
3288
                                JANUS_VALIDATE_JSON_OBJECT(root, configure_parameters,
3289
                                        error_code, error_cause, TRUE,
3290
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3291
                                if(error_code != 0)
3292
                                        goto error;
3293
                                json_t *audio = json_object_get(root, "audio");
3294
                                json_t *video = json_object_get(root, "video");
3295
                                json_t *data = json_object_get(root, "data");
3296
                                /* Update the audio/video/data flags, if set */
3297
                                janus_videoroom_participant *publisher = listener->feed;
3298
                                if(publisher) {
3299
                                        if(audio && publisher->audio)
3300
                                                listener->audio = json_is_true(audio);
3301
                                        if(video && publisher->video)
3302
                                                listener->video = json_is_true(video);
3303
                                        if(data && publisher->data)
3304
                                                listener->data = json_is_true(data);
3305
                                }
3306
                                event = json_object();
3307
                                json_object_set_new(event, "videoroom", json_string("event"));
3308
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3309
                                json_object_set_new(event, "configured", json_string("ok"));
3310
                        } else if(!strcasecmp(request_text, "pause")) {
3311
                                /* Stop receiving the publisher streams for a while */
3312
                                listener->paused = TRUE;
3313
                                event = json_object();
3314
                                json_object_set_new(event, "videoroom", json_string("event"));
3315
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3316
                                json_object_set_new(event, "paused", json_string("ok"));
3317
                        } else if(!strcasecmp(request_text, "switch")) {
3318
                                /* This listener wants to switch to a different publisher */
3319
                                JANUS_VALIDATE_JSON_OBJECT(root, listener_parameters,
3320
                                        error_code, error_cause, TRUE,
3321
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3322
                                if(error_code != 0)
3323
                                        goto error;
3324
                                json_t *feed = json_object_get(root, "feed");
3325
                                guint64 feed_id = json_integer_value(feed);
3326
                                json_t *audio = json_object_get(root, "audio");
3327
                                json_t *video = json_object_get(root, "video");
3328
                                json_t *data = json_object_get(root, "data");
3329
                                if(!listener->room) {
3330
                                        JANUS_LOG(LOG_ERR, "Room Destroyed \n");
3331
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3332
                                        g_snprintf(error_cause, 512, "No such room ");
3333
                                        goto error;
3334
                                }
3335
                                if(listener->room->destroyed) {
3336
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")\n", listener->room->room_id);
3337
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3338
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
3339
                                        goto error;
3340
                                }
3341
                                janus_mutex_lock(&listener->room->participants_mutex);
3342
                                janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, &feed_id);
3343
                                janus_mutex_unlock(&listener->room->participants_mutex);
3344
                                if(publisher == NULL || publisher->sdp == NULL) {
3345
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3346
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3347
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3348
                                        goto error;
3349
                                }
3350
                                gboolean paused = listener->paused;
3351
                                listener->paused = TRUE;
3352
                                /* Unsubscribe from the previous publisher */
3353
                                janus_videoroom_participant *prev_feed = listener->feed;
3354
                                if(prev_feed) {
3355
                                        janus_mutex_lock(&prev_feed->listeners_mutex);
3356
                                        prev_feed->listeners = g_slist_remove(prev_feed->listeners, listener);
3357
                                        janus_mutex_unlock(&prev_feed->listeners_mutex);
3358
                                        listener->feed = NULL;
3359
                                }
3360
                                /* Subscribe to the new one */
3361
                                listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
3362
                                if(!publisher->audio)
3363
                                        listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
3364
                                listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
3365
                                if(!publisher->video)
3366
                                        listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
3367
                                listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
3368
                                if(!publisher->data)
3369
                                        listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
3370
                                janus_mutex_lock(&publisher->listeners_mutex);
3371
                                publisher->listeners = g_slist_append(publisher->listeners, listener);
3372
                                janus_mutex_unlock(&publisher->listeners_mutex);
3373
                                listener->feed = publisher;
3374
                                /* Send a FIR to the new publisher */
3375
                                char buf[20];
3376
                                janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3377
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3378
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3379
                                /* Send a PLI too, just in case... */
3380
                                janus_rtcp_pli((char *)&buf, 12);
3381
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3382
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3383
                                /* Done */
3384
                                listener->paused = paused;
3385
                                event = json_object();
3386
                                json_object_set_new(event, "videoroom", json_string("event"));
3387
                                json_object_set_new(event, "switched", json_string("ok"));
3388
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3389
                                json_object_set_new(event, "id", json_integer(feed_id));
3390
                                if(publisher->display)
3391
                                        json_object_set_new(event, "display", json_string(publisher->display));
3392
                                /* Also notify event handlers */
3393
                                if(notify_events && gateway->events_is_enabled()) {
3394
                                        json_t *info = json_object();
3395
                                        json_object_set_new(info, "event", json_string("switched"));
3396
                                        json_object_set_new(info, "room", json_integer(publisher->room->room_id));
3397
                                        json_object_set_new(info, "feed", json_integer(publisher->user_id));
3398
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3399
                                }
3400
                        } else if(!strcasecmp(request_text, "leave")) {
3401
                                janus_videoroom_participant *publisher = listener->feed;
3402
                                if(publisher != NULL) {
3403
                                        janus_mutex_lock(&publisher->listeners_mutex);
3404
                                        publisher->listeners = g_slist_remove(publisher->listeners, listener);
3405
                                        janus_mutex_unlock(&publisher->listeners_mutex);
3406
                                        listener->feed = NULL;
3407
                                }
3408
                                session->participant_type = janus_videoroom_p_type_none;
3409
                                event = json_object();
3410
                                json_object_set_new(event, "videoroom", json_string("event"));
3411
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3412
                                json_object_set_new(event, "left", json_string("ok"));
3413
                                session->started = FALSE;
3414
                        } else {
3415
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3416
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3417
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3418
                                goto error;
3419
                        }
3420
                }
3421

    
3422
                /* Prepare JSON event */
3423
                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3424
                /* Any SDP to handle? */
3425
                const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
3426
                const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
3427
                if(!msg_sdp) {
3428
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3429
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3430
                        json_decref(event);
3431
                } else {
3432
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
3433
                        const char *type = NULL;
3434
                        if(!strcasecmp(msg_sdp_type, "offer")) {
3435
                                /* We need to answer */
3436
                                type = "answer";
3437
                        } else if(!strcasecmp(msg_sdp_type, "answer")) {
3438
                                /* We got an answer (from a listener?), no need to negotiate */
3439
                                g_atomic_int_set(&session->hangingup, 0);
3440
                                int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3441
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3442
                                json_decref(event);
3443
                                janus_videoroom_message_free(msg);
3444
                                continue;
3445
                        } else {
3446
                                /* TODO We don't support anything else right now... */
3447
                                JANUS_LOG(LOG_ERR, "Unknown SDP type '%s'\n", msg_sdp_type);
3448
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3449
                                g_snprintf(error_cause, 512, "Unknown SDP type '%s'", msg_sdp_type);
3450
                                goto error;
3451
                        }
3452
                        if(session->participant_type != janus_videoroom_p_type_publisher) {
3453
                                /* We shouldn't be here, we always offer ourselves */
3454
                                JANUS_LOG(LOG_ERR, "Only publishers send offers\n");
3455
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3456
                                g_snprintf(error_cause, 512, "Only publishers send offers");
3457
                                goto error;
3458
                        } else {
3459
                                /* This is a new publisher: is there room? */
3460
                                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3461
                                janus_videoroom *videoroom = participant->room;
3462
                                int count = 0;
3463
                                GHashTableIter iter;
3464
                                gpointer value;
3465
                                if(!videoroom) {
3466
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3467
                                        goto error;
3468
                                }
3469
                                if(videoroom->destroyed) {
3470
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3471
                                        goto error;
3472
                                }
3473
                                janus_mutex_lock(&videoroom->participants_mutex);
3474
                                g_hash_table_iter_init(&iter, videoroom->participants);
3475
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3476
                                        janus_videoroom_participant *p = value;
3477
                                        if(p != participant && p->sdp)
3478
                                                count++;
3479
                                }
3480
                                janus_mutex_unlock(&videoroom->participants_mutex);
3481
                                if(count == videoroom->max_publishers) {
3482
                                        participant->audio_active = FALSE;
3483
                                        participant->video_active = FALSE;
3484
                                        participant->data_active = FALSE;
3485
                                        JANUS_LOG(LOG_ERR, "Maximum number of publishers (%d) already reached\n", videoroom->max_publishers);
3486
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3487
                                        g_snprintf(error_cause, 512, "Maximum number of publishers (%d) already reached", videoroom->max_publishers);
3488
                                        goto error;
3489
                                }
3490
                                /* Now prepare the SDP to give back */
3491
                                if(strstr(msg_sdp, "Mozilla")) {
3492
                                        participant->firefox = TRUE;
3493
                                }
3494
                                /* Start by parsing the offer */
3495
                                char error_str[512];
3496
                                janus_sdp *offer = janus_sdp_parse(msg_sdp, error_str, sizeof(error_str));
3497
                                if(offer == NULL) {
3498
                                        json_decref(event);
3499
                                        JANUS_LOG(LOG_ERR, "Error parsing offer: %s\n", error_str);
3500
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP;
3501
                                        g_snprintf(error_cause, 512, "Error parsing offer: %s", error_str);
3502
                                        goto error;
3503
                                }
3504
                                gboolean audio_level_extmap = FALSE, video_orient_extmap = FALSE, playout_delay_extmap = FALSE;
3505
                                janus_sdp_mdirection audio_level_mdir = JANUS_SDP_SENDRECV,
3506
                                        video_orient_mdir = JANUS_SDP_SENDRECV,
3507
                                        playout_delay_mdir = JANUS_SDP_SENDRECV;
3508
                                GList *temp = offer->m_lines;
3509
                                while(temp) {
3510
                                        /* Which media are available? */
3511
                                        janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3512
                                        if(m->type == JANUS_SDP_AUDIO && m->port > 0) {
3513
                                                participant->audio = TRUE;
3514
                                        } else if(m->type == JANUS_SDP_VIDEO && m->port > 0) {
3515
                                                participant->video = TRUE;
3516
                                        } else if(m->type == JANUS_SDP_APPLICATION && m->port > 0) {
3517
                                                participant->data = TRUE;
3518
                                        }
3519
                                        if(m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO) {
3520
                                                /* Are the extmaps we care about there? */
3521
                                                GList *ma = m->attributes;
3522
                                                while(ma) {
3523
                                                        janus_sdp_attribute *a = (janus_sdp_attribute *)ma->data;
3524
                                                        if(a->value) {
3525
                                                                if(videoroom->audiolevel_ext && m->type == JANUS_SDP_AUDIO && strstr(a->value, JANUS_RTP_EXTMAP_AUDIO_LEVEL)) {
3526
                                                                        participant->audio_level_extmap_id = atoi(a->value);
3527
                                                                        audio_level_extmap = TRUE;
3528
                                                                        audio_level_mdir = a->direction;
3529
                                                                } else if(videoroom->videoorient_ext && m->type == JANUS_SDP_VIDEO && strstr(a->value, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION)) {
3530
                                                                        participant->video_orient_extmap_id = atoi(a->value);
3531
                                                                        video_orient_extmap = TRUE;
3532
                                                                        video_orient_mdir = a->direction;
3533
                                                                } else if(videoroom->playoutdelay_ext && m->type == JANUS_SDP_VIDEO && strstr(a->value, JANUS_RTP_EXTMAP_PLAYOUT_DELAY)) {
3534
                                                                        participant->playout_delay_extmap_id = atoi(a->value);
3535
                                                                        playout_delay_extmap = TRUE;
3536
                                                                        playout_delay_mdir = a->direction;
3537
                                                                }
3538
                                                        }
3539
                                                        ma = ma->next;
3540
                                                }
3541
                                        }
3542
                                        temp = temp->next;
3543
                                }
3544
                                /* Prepare an answer now: force the room codecs and recvonly on the Janus side */
3545
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send an audio stream\n", participant->audio ? "is" : "is NOT");
3546
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send a video stream\n", participant->video ? "is" : "is NOT");
3547
                                JANUS_LOG(LOG_VERB, "The publisher %s going to open a data channel\n", participant->data ? "is" : "is NOT");
3548
                                janus_sdp *answer = janus_sdp_generate_answer(offer,
3549
                                        JANUS_SDP_OA_AUDIO_CODEC, janus_videoroom_audiocodec_name(videoroom->acodec),
3550
                                        JANUS_SDP_OA_AUDIO_DIRECTION, JANUS_SDP_RECVONLY,
3551
                                        JANUS_SDP_OA_VIDEO_CODEC, janus_videoroom_videocodec_name(videoroom->vcodec),
3552
                                        JANUS_SDP_OA_VIDEO_DIRECTION, JANUS_SDP_RECVONLY,
3553
                                        JANUS_SDP_OA_DONE);
3554
                                janus_sdp_free(offer);
3555
                                /* Replace the session name */
3556
                                g_free(answer->s_name);
3557
                                answer->s_name = g_strdup(videoroom->room_name);
3558
                                /* Which media are REALLY available? (some may have been rejected) */
3559
                                participant->audio = FALSE;
3560
                                participant->video = FALSE;
3561
                                participant->data = FALSE;
3562
                                temp = answer->m_lines;
3563
                                while(temp) {
3564
                                        janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3565
                                        if(m->type == JANUS_SDP_AUDIO && m->port > 0) {
3566
                                                participant->audio = TRUE;
3567
                                        } else if(m->type == JANUS_SDP_VIDEO && m->port > 0) {
3568
                                                participant->video = TRUE;
3569
                                        } else if(m->type == JANUS_SDP_APPLICATION && m->port > 0) {
3570
                                                participant->data = TRUE;
3571
                                        }
3572
                                        temp = temp->next;
3573
                                }
3574
                                JANUS_LOG(LOG_VERB, "Per the answer, the publisher %s going to send an audio stream\n", participant->audio ? "is" : "is NOT");
3575
                                JANUS_LOG(LOG_VERB, "Per the answer, the publisher %s going to send a video stream\n", participant->video ? "is" : "is NOT");
3576
                                JANUS_LOG(LOG_VERB, "Per the answer, the publisher %s going to open a data channel\n", participant->data ? "is" : "is NOT");
3577
                                /* Also add a bandwidth SDP attribute if we're capping the bitrate in the room */
3578
                                if(participant->firefox) {        /* Don't add any b=AS attribute for Chrome */
3579
                                        janus_sdp_mline *m = janus_sdp_mline_find(answer, JANUS_SDP_VIDEO);
3580
                                        if(m != NULL && videoroom->bitrate > 0) {
3581
                                                m->b_name = g_strdup("AS");
3582
                                                m->b_value = (int)(videoroom->bitrate/1000);
3583
                                        }
3584
                                }
3585
                                /* Add the extmap attributes, if needed */
3586
                                if(audio_level_extmap) {
3587
                                        /* First of all, let's check if the extmap attribute had a direction */
3588
                                        const char *direction = NULL;
3589
                                        switch(audio_level_mdir) {
3590
                                                case JANUS_SDP_SENDONLY:
3591
                                                        direction = "/recvonly";
3592
                                                        break;
3593
                                                case JANUS_SDP_RECVONLY:
3594
                                                case JANUS_SDP_INACTIVE:
3595
                                                        direction = "/inactive";
3596
                                                        break;
3597
                                                default:
3598
                                                        direction = "";
3599
                                                        break;
3600
                                        }
3601
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3602
                                                "%d%s %s\r\n", participant->audio_level_extmap_id, direction, JANUS_RTP_EXTMAP_AUDIO_LEVEL);
3603
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(answer, JANUS_SDP_AUDIO), a);
3604
                                }
3605
                                if(video_orient_extmap) {
3606
                                        /* First of all, let's check if the extmap attribute had a direction */
3607
                                        const char *direction = NULL;
3608
                                        switch(video_orient_mdir) {
3609
                                                case JANUS_SDP_SENDONLY:
3610
                                                        direction = "/recvonly";
3611
                                                        break;
3612
                                                case JANUS_SDP_RECVONLY:
3613
                                                case JANUS_SDP_INACTIVE:
3614
                                                        direction = "/inactive";
3615
                                                        break;
3616
                                                default:
3617
                                                        direction = "";
3618
                                                        break;
3619
                                        }
3620
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3621
                                                "%d%s %s\r\n", participant->video_orient_extmap_id, direction, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION);
3622
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(answer, JANUS_SDP_VIDEO), a);
3623
                                }
3624
                                if(playout_delay_extmap) {
3625
                                        /* First of all, let's check if the extmap attribute had a direction */
3626
                                        const char *direction = NULL;
3627
                                        switch(playout_delay_mdir) {
3628
                                                case JANUS_SDP_SENDONLY:
3629
                                                        direction = "/recvonly";
3630
                                                        break;
3631
                                                case JANUS_SDP_RECVONLY:
3632
                                                case JANUS_SDP_INACTIVE:
3633
                                                        direction = "/inactive";
3634
                                                        break;
3635
                                                default:
3636
                                                        direction = "";
3637
                                                        break;
3638
                                        }
3639
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3640
                                                "%d%s %s\r\n", participant->playout_delay_extmap_id, direction, JANUS_RTP_EXTMAP_PLAYOUT_DELAY);
3641
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(answer, JANUS_SDP_VIDEO), a);
3642
                                }
3643
                                /* Generate an SDP string we can send back to the publisher */
3644
                                char *answer_sdp = janus_sdp_write(answer);
3645
                                /* Now turn the SDP into what we'll send subscribers, using the static payload types for making switching easier */
3646
                                offer = janus_sdp_generate_offer(videoroom->room_name, answer->c_addr,
3647
                                        JANUS_SDP_OA_AUDIO, participant->audio,
3648
                                        JANUS_SDP_OA_AUDIO_CODEC, janus_videoroom_audiocodec_name(videoroom->acodec),
3649
                                        JANUS_SDP_OA_AUDIO_PT, janus_videoroom_audiocodec_pt(videoroom->acodec),
3650
                                        JANUS_SDP_OA_AUDIO_DIRECTION, JANUS_SDP_SENDONLY,
3651
                                        JANUS_SDP_OA_VIDEO, participant->video,
3652
                                        JANUS_SDP_OA_VIDEO_CODEC, janus_videoroom_videocodec_name(videoroom->vcodec),
3653
                                        JANUS_SDP_OA_VIDEO_PT, janus_videoroom_videocodec_pt(videoroom->vcodec),
3654
                                        JANUS_SDP_OA_VIDEO_DIRECTION, JANUS_SDP_SENDONLY,
3655
                                        JANUS_SDP_OA_DATA, participant->data,
3656
                                        JANUS_SDP_OA_DONE);
3657
                                /* Add the extmap attributes, if needed */
3658
                                if(audio_level_extmap) {
3659
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3660
                                                "%d %s\r\n", participant->audio_level_extmap_id, JANUS_RTP_EXTMAP_AUDIO_LEVEL);
3661
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(offer, JANUS_SDP_AUDIO), a);
3662
                                }
3663
                                if(video_orient_extmap) {
3664
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3665
                                                "%d %s\r\n", participant->video_orient_extmap_id, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION);
3666
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(offer, JANUS_SDP_VIDEO), a);
3667
                                }
3668
                                if(playout_delay_extmap) {
3669
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3670
                                                "%d %s\r\n", participant->playout_delay_extmap_id, JANUS_RTP_EXTMAP_PLAYOUT_DELAY);
3671
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(offer, JANUS_SDP_VIDEO), a);
3672
                                }
3673
                                /* Generate an SDP string we can offer subscribers later on */
3674
                                char *offer_sdp = janus_sdp_write(offer);
3675
                                janus_sdp_free(offer);
3676
                                janus_sdp_free(answer);
3677
                                /* Is this room recorded? */
3678
                                janus_mutex_lock(&participant->rec_mutex);
3679
                                if(videoroom->record || participant->recording_active) {
3680
                                        janus_videoroom_recorder_create(participant, participant->audio, participant->video, participant->data);
3681
                                }
3682
                                janus_mutex_unlock(&participant->rec_mutex);
3683
                                /* Send the answer back to the publisher */
3684
                                JANUS_LOG(LOG_VERB, "Handling publisher: turned this into an '%s':\n%s\n", type, answer_sdp);
3685
                                json_t *jsep = json_pack("{ssss}", "type", type, "sdp", answer_sdp);
3686
                                g_free(answer_sdp);
3687
                                /* How long will the gateway take to push the event? */
3688
                                g_atomic_int_set(&session->hangingup, 0);
3689
                                gint64 start = janus_get_monotonic_time();
3690
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, jsep);
3691
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3692
                                /* Done */
3693
                                if(res != JANUS_OK) {
3694
                                        /* TODO Failed to negotiate? We should remove this publisher */
3695
                                        g_free(offer_sdp);
3696
                                } else {
3697
                                        /* Store the participant's SDP for interested listeners */
3698
                                        participant->sdp = offer_sdp;
3699
                                        /* We'll wait for the setup_media event before actually telling listeners */
3700
                                }
3701
                                json_decref(event);
3702
                                json_decref(jsep);
3703
                        }
3704
                }
3705
                janus_videoroom_message_free(msg);
3706

    
3707
                continue;
3708
                
3709
error:
3710
                {
3711
                        /* Prepare JSON error event */
3712
                        json_t *event = json_object();
3713
                        json_object_set_new(event, "videoroom", json_string("event"));
3714
                        json_object_set_new(event, "error_code", json_integer(error_code));
3715
                        json_object_set_new(event, "error", json_string(error_cause));
3716
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3717
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
3718
                        json_decref(event);
3719
                        janus_videoroom_message_free(msg);
3720
                }
3721
        }
3722
        JANUS_LOG(LOG_VERB, "Leaving VideoRoom handler thread\n");
3723
        return NULL;
3724
}
3725

    
3726

    
3727
/* Helper to quickly relay RTP packets from publishers to subscribers */
3728
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data) {
3729
        janus_videoroom_rtp_relay_packet *packet = (janus_videoroom_rtp_relay_packet *)user_data;
3730
        if(!packet || !packet->data || packet->length < 1) {
3731
                JANUS_LOG(LOG_ERR, "Invalid packet...\n");
3732
                return;
3733
        }
3734
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3735
        if(!listener || !listener->session) {
3736
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3737
                return;
3738
        }
3739
        if(listener->paused) {
3740
                // JANUS_LOG(LOG_ERR, "This listener paused the stream...\n");
3741
                return;
3742
        }
3743
        janus_videoroom_session *session = listener->session;
3744
        if(!session || !session->handle) {
3745
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3746
                return;
3747
        }
3748
        if(!session->started) {
3749
                // JANUS_LOG(LOG_ERR, "Streaming not started yet for this session...\n");
3750
                return;
3751
        }
3752
        
3753
        /* Make sure there hasn't been a publisher switch by checking the SSRC */
3754
        if(packet->is_video) {
3755
                /* Check if this listener is subscribed to this medium */
3756
                if(!listener->video) {
3757
                        /* Nope, don't relay */
3758
                        return;
3759
                }
3760
                /* Fix sequence number and timestamp (publisher switching may be involved) */
3761
                janus_rtp_header_update(packet->data, &listener->context, TRUE, 4500);
3762
                if(gateway != NULL)
3763
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3764
                /* Restore the timestamp and sequence number to what the publisher set them to */
3765
                packet->data->timestamp = htonl(packet->timestamp);
3766
                packet->data->seq_number = htons(packet->seq_number);
3767
        } else {
3768
                /* Check if this listener is subscribed to this medium */
3769
                if(!listener->audio) {
3770
                        /* Nope, don't relay */
3771
                        return;
3772
                }
3773
                /* Fix sequence number and timestamp (publisher switching may be involved) */
3774
                janus_rtp_header_update(packet->data, &listener->context, FALSE, 960);
3775
                if(gateway != NULL)
3776
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3777
                /* Restore the timestamp and sequence number to what the publisher set them to */
3778
                packet->data->timestamp = htonl(packet->timestamp);
3779
                packet->data->seq_number = htons(packet->seq_number);
3780
        }
3781

    
3782
        return;
3783
}
3784

    
3785
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data) {
3786
        char *text = (char *)user_data;
3787
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3788
        if(!listener || !listener->session || !listener->data || listener->paused) {
3789
                return;
3790
        }
3791
        janus_videoroom_session *session = listener->session;
3792
        if(!session || !session->handle) {
3793
                return;
3794
        }
3795
        if(!session->started) {
3796
                return;
3797
        }
3798
        if(gateway != NULL && text != NULL) {
3799
                JANUS_LOG(LOG_VERB, "Forwarding DataChannel message (%zu bytes) to viewer: %s\n", strlen(text), text);
3800
                gateway->relay_data(session->handle, text, strlen(text));
3801
        }
3802
        return;
3803
}
3804

    
3805
/* Helper to free janus_videoroom structs. */
3806
static void janus_videoroom_free(janus_videoroom *room) {
3807
        if(room) {
3808
                janus_mutex_lock(&room->participants_mutex);
3809
                g_free(room->room_name);
3810
                g_free(room->room_secret);
3811
                g_free(room->room_pin);
3812
                g_free(room->rec_dir);
3813
                g_hash_table_unref(room->participants);
3814
                g_hash_table_unref(room->private_ids);
3815
                g_hash_table_destroy(room->allowed);
3816
                janus_mutex_unlock(&room->participants_mutex);
3817
                janus_mutex_destroy(&room->participants_mutex);
3818
                g_free(room);
3819
                room = NULL;
3820
        }
3821
}
3822

    
3823
static void janus_videoroom_listener_free(janus_videoroom_listener *l) {
3824
        JANUS_LOG(LOG_VERB, "Freeing listener\n");
3825
        g_free(l);
3826
}
3827

    
3828
static void janus_videoroom_participant_free(janus_videoroom_participant *p) {
3829
        JANUS_LOG(LOG_VERB, "Freeing publisher\n");
3830
        g_free(p->display);
3831
        g_free(p->sdp);
3832

    
3833
        if(p->arc) {
3834
                janus_recorder_free(p->arc);
3835
                p->arc = NULL;
3836
        }
3837
        if(p->vrc) {
3838
                janus_recorder_free(p->vrc);
3839
                p->vrc = NULL;
3840
        }
3841
        if(p->drc) {
3842
                janus_recorder_free(p->drc);
3843
                p->drc = NULL;
3844
        }
3845

    
3846
        janus_mutex_lock(&p->listeners_mutex);
3847
        while(p->listeners) {
3848
                janus_videoroom_listener *l = (janus_videoroom_listener *)p->listeners->data;
3849
                if(l) {
3850
                        p->listeners = g_slist_remove(p->listeners, l);
3851
                        l->feed = NULL;
3852
                }
3853
        }
3854
        janus_mutex_unlock(&p->listeners_mutex);
3855
        janus_mutex_lock(&p->rtp_forwarders_mutex);
3856
        if(p->udp_sock > 0) {
3857
                close(p->udp_sock);
3858
                p->udp_sock = 0;
3859
        }
3860
        g_hash_table_destroy(p->rtp_forwarders);
3861
        p->rtp_forwarders = NULL;
3862
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
3863
        g_slist_free(p->listeners);
3864

    
3865
        janus_mutex_destroy(&p->listeners_mutex);
3866
        janus_mutex_destroy(&p->rtp_forwarders_mutex);
3867
        g_free(p);
3868
}