Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videoroom.c @ 438faca8

History | View | Annotate | Download (165 KB)

1
/*! \file   janus_videoroom.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus VideoRoom plugin
5
 * \details  This is a plugin implementing a videoconferencing SFU
6
 * (Selective Forwarding Unit) for Janus, that is an audio/video router.
7
 * This means that the plugin implements a virtual conferencing room peers
8
 * can join and leave at any time. This room is based on a Publish/Subscribe
9
 * pattern. Each peer can publish his/her own live audio/video feeds: this
10
 * feed becomes an available stream in the room the other participants can
11
 * attach to. This means that this plugin allows the realization of several
12
 * different scenarios, ranging from a simple webinar (one speaker, several
13
 * listeners) to a fully meshed video conference (each peer sending and
14
 * receiving to and from all the others).
15
 * 
16
 * For what concerns the subscriber side, there are two different ways to
17
 * attach to a publisher's feed: a generic 'listener', which can attach to
18
 * a single feed, and a more complex 'Multiplexed listener', which instead can
19
 * attach to more feeds using the same PeerConnection. The generic 'listener'
20
 * is the default, which means that if you want to watch more feeds at the
21
 * same time, you'll need to create multiple 'listeners' to attach at any
22
 * of them. The 'Multiplexed listener', instead, is a more complex alternative
23
 * that exploits the so called RTCWEB 'Plan B', which multiplexes more
24
 * streams on a single PeerConnection and in the SDP: while more efficient in terms of
25
 * resources, though, this approach is experimental, and currently only
26
 * available on Google Chrome, so use it wisely.
27
 * \note As of now, work on Plan B is still going on, and as such its support in Janus
28
 * is flaky to say the least. Don't try to attach as a Multiplexed listener or bad
29
 * things will probably happen!
30
 * 
31
 * Considering that this plugin allows for several different WebRTC PeerConnections
32
 * to be on at the same time for the same peer (specifically, each peer
33
 * potentially has 1 PeerConnection on for publishing and N on for subscriptions
34
 * from other peers), each peer may need to attach several times to the same
35
 * plugin for every stream: this means that each peer needs to have at least one
36
 * handle active for managing its relation with the plugin (joining a room,
37
 * leaving a room, muting/unmuting, publishing, receiving events), and needs
38
 * to open a new one each time he/she wants to subscribe to a feed from
39
 * another participant (or a single one in case a 'Multiplexed listener is used).
40
 * The handle used for a subscription, however, would be logically a "slave"
41
 * to the master one used for managing the room: this means that it cannot
42
 * be used, for instance, to unmute in the room, as its only purpose would
43
 * be to provide a context in which creating the sendonly PeerConnection
44
 * for the subscription to the active participant.
45
 * 
46
 * Rooms to make available are listed in the plugin configuration file.
47
 * A pre-filled configuration file is provided in \c conf/janus.plugin.videoroom.cfg
48
 * and includes a demo room for testing. The same plugin is also used
49
 * dynamically (that is, with rooms created on the fly via API) in the
50
 * Screen Sharing demo as well.
51
 * 
52
 * To add more rooms or modify the existing one, you can use the following
53
 * syntax:
54
 * 
55
 * \verbatim
56
[<unique room ID>]
57
description = This is my awesome room
58
is_private = yes|no (private rooms don't appear when you do a 'list' request)
59
secret = <optional password needed for manipulating (e.g. destroying) the room>
60
pin = <optional password needed for joining the room>
61
publishers = <max number of concurrent senders> (e.g., 6 for a video
62
             conference or 1 for a webinar)
63
bitrate = <max video bitrate for senders> (e.g., 128000)
64
fir_freq = <send a FIR to publishers every fir_freq seconds> (0=disable)
65
audiocodec = opus|isac32|isac16|pcmu|pcma|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 aqumulate*/
520
        int audio_dBov_sum;        /* participants aqumulated 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
} janus_videoroom_participant;
540
static void janus_videoroom_participant_free(janus_videoroom_participant *p);
541
static void janus_videoroom_rtp_forwarder_free_helper(gpointer data);
542
static guint32 janus_videoroom_rtp_forwarder_add_helper(janus_videoroom_participant *p,
543
        const gchar* host, int port, int pt, uint32_t ssrc, gboolean is_video, gboolean is_data);
544

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

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

    
564

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

    
585

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

    
611

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

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

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

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

    
715

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

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

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

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

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

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

    
895
        /* Show available rooms */
896
        janus_mutex_lock(&rooms_mutex);
897
        GHashTableIter iter;
898
        gpointer value;
899
        g_hash_table_iter_init(&iter, rooms);
900
        while (g_hash_table_iter_next(&iter, NULL, &value)) {
901
                janus_videoroom *vr = value;
902
                JANUS_LOG(LOG_VERB, "  ::: [%"SCNu64"][%s] %"SCNu64", max %d publishers, FIR frequency of %d seconds, %s audio codec, %s video codec\n",
903
                        vr->room_id, vr->room_name, vr->bitrate, vr->max_publishers, vr->fir_freq,
904
                        janus_videoroom_audiocodec_name(vr->acodec), janus_videoroom_videocodec_name(vr->vcodec));
905
        }
906
        janus_mutex_unlock(&rooms_mutex);
907

    
908
        g_atomic_int_set(&initialized, 1);
909

    
910
        GError *error = NULL;
911
        /* Start the sessions watchdog */
912
        watchdog = g_thread_try_new("videoroom watchdog", &janus_videoroom_watchdog, NULL, &error);
913
        if(error != NULL) {
914
                g_atomic_int_set(&initialized, 0);
915
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom watchdog thread...\n", error->code, error->message ? error->message : "??");
916
                janus_config_destroy(config);
917
                return -1;
918
        }
919
        /* Launch the thread that will handle incoming messages */
920
        handler_thread = g_thread_try_new("videoroom handler", janus_videoroom_handler, NULL, &error);
921
        if(error != NULL) {
922
                g_atomic_int_set(&initialized, 0);
923
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom handler thread...\n", error->code, error->message ? error->message : "??");
924
                janus_config_destroy(config);
925
                return -1;
926
        }
927
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_VIDEOROOM_NAME);
928
        return 0;
929
}
930

    
931
void janus_videoroom_destroy(void) {
932
        if(!g_atomic_int_get(&initialized))
933
                return;
934
        g_atomic_int_set(&stopping, 1);
935

    
936
        g_async_queue_push(messages, &exit_message);
937
        if(handler_thread != NULL) {
938
                g_thread_join(handler_thread);
939
                handler_thread = NULL;
940
        }
941
        if(watchdog != NULL) {
942
                g_thread_join(watchdog);
943
                watchdog = NULL;
944
        }
945

    
946
        /* FIXME We should destroy the sessions cleanly */
947
        janus_mutex_lock(&sessions_mutex);
948
        g_hash_table_foreach_remove(sessions, (GHRFunc)session_hash_table_remove, NULL);
949
        g_hash_table_destroy(sessions);
950
        sessions = NULL;
951
        janus_mutex_unlock(&sessions_mutex);
952

    
953
        janus_mutex_lock(&rooms_mutex);
954
        g_hash_table_destroy(rooms);
955
        rooms = NULL;
956
        janus_mutex_unlock(&rooms_mutex);
957
        janus_mutex_destroy(&rooms_mutex);
958

    
959
        g_async_queue_unref(messages);
960
        messages = NULL;
961

    
962
        janus_config_destroy(config);
963
        g_free(admin_key);
964

    
965
        g_atomic_int_set(&initialized, 0);
966
        g_atomic_int_set(&stopping, 0);
967
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOROOM_NAME);
968
}
969

    
970
int janus_videoroom_get_api_compatibility(void) {
971
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
972
        return JANUS_PLUGIN_API_VERSION;
973
}
974

    
975
int janus_videoroom_get_version(void) {
976
        return JANUS_VIDEOROOM_VERSION;
977
}
978

    
979
const char *janus_videoroom_get_version_string(void) {
980
        return JANUS_VIDEOROOM_VERSION_STRING;
981
}
982

    
983
const char *janus_videoroom_get_description(void) {
984
        return JANUS_VIDEOROOM_DESCRIPTION;
985
}
986

    
987
const char *janus_videoroom_get_name(void) {
988
        return JANUS_VIDEOROOM_NAME;
989
}
990

    
991
const char *janus_videoroom_get_author(void) {
992
        return JANUS_VIDEOROOM_AUTHOR;
993
}
994

    
995
const char *janus_videoroom_get_package(void) {
996
        return JANUS_VIDEOROOM_PACKAGE;
997
}
998

    
999
void janus_videoroom_create_session(janus_plugin_session *handle, int *error) {
1000
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1001
                *error = -1;
1002
                return;
1003
        }        
1004
        janus_videoroom_session *session = (janus_videoroom_session *)g_malloc0(sizeof(janus_videoroom_session));
1005
        session->handle = handle;
1006
        session->participant_type = janus_videoroom_p_type_none;
1007
        session->participant = NULL;
1008
        session->destroyed = 0;
1009
        g_atomic_int_set(&session->hangingup, 0);
1010
        handle->plugin_handle = session;
1011
        janus_mutex_lock(&sessions_mutex);
1012
        g_hash_table_insert(sessions, handle, session);
1013
        janus_mutex_unlock(&sessions_mutex);
1014

    
1015
        return;
1016
}
1017

    
1018
static void janus_videoroom_notify_participants(janus_videoroom_participant *participant, json_t *msg) {
1019
        /* participant->room->participants_mutex has to be locked. */
1020
        GHashTableIter iter;
1021
        gpointer value;
1022
        g_hash_table_iter_init(&iter, participant->room->participants);
1023
        while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1024
                janus_videoroom_participant *p = value;
1025
                if(p && p->session && p != participant) {
1026
                        JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1027
                        int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, msg, NULL);
1028
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1029
                }
1030
        }
1031
}
1032

    
1033
static void janus_videoroom_leave_or_unpublish(janus_videoroom_participant *participant, gboolean is_leaving) {
1034
        /* we need to check if the room still exists, may have been destroyed already */
1035
        if(participant->room && !participant->room->destroyed) {
1036
                json_t *event = json_object();
1037
                json_object_set_new(event, "videoroom", json_string("event"));
1038
                json_object_set_new(event, "room", json_integer(participant->room->room_id));
1039
                json_object_set_new(event, is_leaving ? "leaving" : "unpublished", json_integer(participant->user_id));
1040
                janus_mutex_lock(&participant->room->participants_mutex);
1041
                janus_videoroom_notify_participants(participant, event);
1042
                if(is_leaving) {
1043
                        g_hash_table_remove(participant->room->participants, &participant->user_id);
1044
                        g_hash_table_remove(participant->room->private_ids, GUINT_TO_POINTER(participant->pvt_id));
1045
                }
1046
                janus_mutex_unlock(&participant->room->participants_mutex);
1047
                json_decref(event);
1048
        }
1049
}
1050

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

    
1094
        return;
1095
}
1096

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

    
1165
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) {
1166
        /* rooms_mutex has to be locked */
1167
        int error_code = 0;
1168
        json_t *room = json_object_get(root, "room");
1169
        guint64 room_id = json_integer_value(room);
1170
        *videoroom = g_hash_table_lookup(rooms, &room_id);
1171
        if(*videoroom == NULL) {
1172
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1173
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1174
                if(error_cause)
1175
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1176
                return error_code;
1177
        }
1178
        if((*videoroom)->destroyed) {
1179
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1180
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1181
                if(error_cause)
1182
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1183
                return error_code;
1184
        }
1185
        if(check_secret) {
1186
                char error_cause2[100];
1187
                JANUS_CHECK_SECRET((*videoroom)->room_secret, root, "secret", error_code, error_cause2,
1188
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1189
                if(error_code != 0) {
1190
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1191
                        return error_code;
1192
                }
1193
        }
1194
        if(check_pin) {
1195
                char error_cause2[100];
1196
                JANUS_CHECK_SECRET((*videoroom)->room_pin, root, "pin", error_code, error_cause2,
1197
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1198
                if(error_code != 0) {
1199
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1200
                        return error_code;
1201
                }
1202
        }
1203
        return 0;
1204
}
1205

    
1206
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1207
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1208
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1209
        
1210
        /* Pre-parse the message */
1211
        int error_code = 0;
1212
        char error_cause[512];
1213
        json_t *root = message;
1214
        json_t *response = NULL;
1215

    
1216
        if(message == NULL) {
1217
                JANUS_LOG(LOG_ERR, "No message??\n");
1218
                error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
1219
                g_snprintf(error_cause, 512, "%s", "No message??");
1220
                goto plugin_response;
1221
        }
1222

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

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

    
2095
                janus_videoroom_message *msg = g_malloc0(sizeof(janus_videoroom_message));
2096
                msg->handle = handle;
2097
                msg->transaction = transaction;
2098
                msg->message = root;
2099
                msg->jsep = jsep;
2100
                g_async_queue_push(messages, msg);
2101

    
2102
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
2103
        } else {
2104
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
2105
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
2106
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
2107
        }
2108

    
2109
plugin_response:
2110
                {
2111
                        if(error_code == 0 && !response) {
2112
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2113
                                g_snprintf(error_cause, 512, "Invalid response");
2114
                        }
2115
                        if(error_code != 0) {
2116
                                /* Prepare JSON error event */
2117
                                json_t *event = json_object();
2118
                                json_object_set_new(event, "videoroom", json_string("event"));
2119
                                json_object_set_new(event, "error_code", json_integer(error_code));
2120
                                json_object_set_new(event, "error", json_string(error_cause));
2121
                                response = event;
2122
                        }
2123
                        if(root != NULL)
2124
                                json_decref(root);
2125
                        if(jsep != NULL)
2126
                                json_decref(jsep);
2127
                        g_free(transaction);
2128

    
2129
                        return janus_plugin_result_new(JANUS_PLUGIN_OK, NULL, response);
2130
                }
2131

    
2132
}
2133

    
2134
void janus_videoroom_setup_media(janus_plugin_session *handle) {
2135
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
2136
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2137
                return;
2138
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2139
        if(!session) {
2140
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2141
                return;
2142
        }
2143
        if(session->destroyed)
2144
                return;
2145
        g_atomic_int_set(&session->hangingup, 0);
2146

    
2147
        /* Media relaying can start now */
2148
        session->started = TRUE;
2149

    
2150
        if(session->participant) {
2151
                /* If this is a publisher, notify all listeners about the fact they can
2152
                 * now subscribe; if this is a listener, instead, ask the publisher a FIR */
2153
                if(session->participant_type == janus_videoroom_p_type_publisher) {
2154
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2155
                        /* Notify all other participants that there's a new boy in town */
2156
                        json_t *list = json_array();
2157
                        json_t *pl = json_object();
2158
                        json_object_set_new(pl, "id", json_integer(participant->user_id));
2159
                        if(participant->display)
2160
                                json_object_set_new(pl, "display", json_string(participant->display));
2161
                        json_array_append_new(list, pl);
2162
                        json_t *pub = json_object();
2163
                        json_object_set_new(pub, "videoroom", json_string("event"));
2164
                        json_object_set_new(pub, "room", json_integer(participant->room->room_id));
2165
                        json_object_set_new(pub, "publishers", list);
2166
                        GHashTableIter iter;
2167
                        gpointer value;
2168
                        janus_videoroom *videoroom = participant->room;
2169
                        janus_mutex_lock(&videoroom->participants_mutex);
2170
                        g_hash_table_iter_init(&iter, videoroom->participants);
2171
                        while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2172
                                janus_videoroom_participant *p = value;
2173
                                if(p == participant) {
2174
                                        continue;        /* Skip the new publisher itself */
2175
                                }
2176
                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2177
                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, pub, NULL);
2178
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2179
                        }
2180
                        json_decref(pub);
2181
                        janus_mutex_unlock(&videoroom->participants_mutex);
2182
                        /* Also notify event handlers */
2183
                        if(notify_events && gateway->events_is_enabled()) {
2184
                                json_t *info = json_object();
2185
                                json_object_set_new(info, "event", json_string("published"));
2186
                                json_object_set_new(info, "room", json_integer(participant->room->room_id));
2187
                                json_object_set_new(info, "id", json_integer(participant->user_id));
2188
                                gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2189
                        }
2190
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2191
                        janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
2192
                        if(l && l->feed) {
2193
                                janus_videoroom_participant *p = l->feed;
2194
                                if(p && p->session) {
2195
                                        /* Send a FIR */
2196
                                        char buf[20];
2197
                                        janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
2198
                                        JANUS_LOG(LOG_VERB, "New listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2199
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 20);
2200
                                        /* Send a PLI too, just in case... */
2201
                                        janus_rtcp_pli((char *)&buf, 12);
2202
                                        JANUS_LOG(LOG_VERB, "New listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2203
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 12);
2204
                                        /* Also notify event handlers */
2205
                                        if(notify_events && gateway->events_is_enabled()) {
2206
                                                json_t *info = json_object();
2207
                                                json_object_set_new(info, "event", json_string("subscribed"));
2208
                                                json_object_set_new(info, "room", json_integer(p->room->room_id));
2209
                                                json_object_set_new(info, "feed", json_integer(p->user_id));
2210
                                                gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2211
                                        }
2212
                                }
2213
                        }
2214
                }
2215
        }
2216
}
2217

    
2218
void janus_videoroom_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
2219
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2220
                return;
2221
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2222
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2223
                return;
2224
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2225
        janus_videoroom *videoroom = participant->room;
2226

    
2227
        if(videoroom->audiolevel_event && participant->audio_active) {
2228
                int level = 0;
2229
                if(janus_rtp_header_extension_parse_audio_level(buf, len, participant->audio_level_extmap_id, &level) == 0) {
2230
                        /* JANUS_LOG(LOG_INFO, "Audio level is %d\n", level); */
2231
                        participant->audio_dBov_sum = participant->audio_dBov_sum + level;
2232
                        participant->audio_active_packets = participant->audio_active_packets + 1;
2233
                        /* 2 seconds of talking (100 packets) with average of ~25 dBow */
2234
                        if(participant->audio_active_packets == videoroom->audio_active_packets) {
2235
                                if((float)participant->audio_dBov_sum/(float)participant->audio_active_packets < videoroom->audio_level_average) {
2236
                                        // Notify participants
2237
                                        json_t *event = json_object();
2238
                                        json_object_set_new(event, "event", json_string("talking"));
2239
                                        json_object_set_new(event, "user", json_string(participant->display));
2240
                                        janus_videoroom_notify_participants(participant, event);
2241
                                        json_decref(event);
2242
                                        /* JANUS_LOG(LOG_ERR, "AVG audio_level %f\n", (float)participant->audio_dBov_sum/(float)participant->audio_active_packets); */
2243
                                        /* Also notify event handlers */
2244
                                        if(notify_events && gateway->events_is_enabled()) {
2245
                                                json_t *info = json_object();
2246
                                                json_object_set_new(info, "event", json_string("talking"));
2247
                                                json_object_set_new(info, "room", json_integer(participant->room->room_id));
2248
                                                json_object_set_new(info, "user", json_string(participant->display));
2249
                                                gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2250
                                        }
2251
                                }
2252
                                participant->audio_active_packets = 0;
2253
                                participant->audio_dBov_sum = 0;
2254
                        }
2255
                }
2256
        }
2257
        if((!video && participant->audio_active) || (video && participant->video_active)) {
2258
                /* Update payload type and SSRC */
2259
                janus_mutex_lock(&participant->rtp_forwarders_mutex);
2260
                rtp_header *rtp = (rtp_header *)buf;
2261
                rtp->type = video ? participant->video_pt : participant->audio_pt;
2262
                rtp->ssrc = htonl(video ? participant->video_ssrc : participant->audio_ssrc);
2263
                /* Forward RTP to the appropriate port for the rtp_forwarders associated with this publisher, if there are any */
2264
                GHashTableIter iter;
2265
                gpointer value;
2266
                g_hash_table_iter_init(&iter, participant->rtp_forwarders);
2267
                while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
2268
                        janus_videoroom_rtp_forwarder* rtp_forward = (janus_videoroom_rtp_forwarder*)value;
2269
                        /* Check if payload type and/or SSRC need to be overwritten for this forwarder */
2270
                        int pt = rtp->type;
2271
                        uint32_t ssrc = ntohl(rtp->ssrc);
2272
                        if(rtp_forward->payload_type > 0)
2273
                                rtp->type = rtp_forward->payload_type;
2274
                        if(rtp_forward->ssrc > 0)
2275
                                rtp->ssrc = htonl(rtp_forward->ssrc);
2276
                        if(video && rtp_forward->is_video) {
2277
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2278
                        }
2279
                        else if(!video && !rtp_forward->is_video && !rtp_forward->is_data) {
2280
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2281
                        }
2282
                        /* Restore original values of payload type and SSRC before going on */
2283
                        rtp->type = pt;
2284
                        rtp->ssrc = htonl(ssrc);
2285
                }
2286
                janus_mutex_unlock(&participant->rtp_forwarders_mutex);
2287
                /* Save the frame if we're recording */
2288
                janus_recorder_save_frame(video ? participant->vrc : participant->arc, buf, len);
2289
                /* Done, relay it */
2290
                janus_videoroom_rtp_relay_packet packet;
2291
                packet.data = rtp;
2292
                packet.length = len;
2293
                packet.is_video = video;
2294
                /* Backup the actual timestamp and sequence number set by the publisher, in case switching is involved */
2295
                packet.timestamp = ntohl(packet.data->timestamp);
2296
                packet.seq_number = ntohs(packet.data->seq_number);
2297
                /* Go */
2298
                g_slist_foreach(participant->listeners, janus_videoroom_relay_rtp_packet, &packet);
2299
                
2300
                /* Check if we need to send any REMB, FIR or PLI back to this publisher */
2301
                if(video && participant->video_active) {
2302
                        /* Did we send a REMB already, or is it time to send one? */
2303
                        gboolean send_remb = FALSE;
2304
                        if(participant->remb_latest == 0 && participant->remb_startup > 0) {
2305
                                /* Still in the starting phase, send the ramp-up REMB feedback */
2306
                                send_remb = TRUE;
2307
                        } else if(participant->remb_latest > 0 && janus_get_monotonic_time()-participant->remb_latest >= 5*G_USEC_PER_SEC) {
2308
                                /* 5 seconds have passed since the last REMB, send a new one */
2309
                                send_remb = TRUE;
2310
                        }                
2311
                        if(send_remb) {
2312
                                /* We send a few incremental REMB messages at startup */
2313
                                uint64_t bitrate = (participant->bitrate ? participant->bitrate : 256*1024);
2314
                                if(participant->remb_startup > 0) {
2315
                                        bitrate = bitrate/participant->remb_startup;
2316
                                        participant->remb_startup--;
2317
                                }
2318
                                JANUS_LOG(LOG_VERB, "Sending REMB (%s, %"SCNu64")\n", participant->display, bitrate);
2319
                                char rtcpbuf[24];
2320
                                janus_rtcp_remb((char *)(&rtcpbuf), 24, bitrate);
2321
                                gateway->relay_rtcp(handle, video, rtcpbuf, 24);
2322
                                if(participant->remb_startup == 0)
2323
                                        participant->remb_latest = janus_get_monotonic_time();
2324
                        }
2325
                        /* Generate FIR/PLI too, if needed */
2326
                        if(video && participant->video_active && (participant->room->fir_freq > 0)) {
2327
                                /* FIXME Very ugly hack to generate RTCP every tot seconds/frames */
2328
                                gint64 now = janus_get_monotonic_time();
2329
                                if((now-participant->fir_latest) >= (participant->room->fir_freq*G_USEC_PER_SEC)) {
2330
                                        /* FIXME We send a FIR every tot seconds */
2331
                                        participant->fir_latest = now;
2332
                                        char rtcpbuf[24];
2333
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &participant->fir_seq);
2334
                                        JANUS_LOG(LOG_VERB, "Sending FIR to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2335
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 20);
2336
                                        /* Send a PLI too, just in case... */
2337
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2338
                                        JANUS_LOG(LOG_VERB, "Sending PLI to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2339
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 12);
2340
                                }
2341
                        }
2342
                }
2343
        }
2344
}
2345

    
2346
void janus_videoroom_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
2347
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2348
                return;
2349
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2350
        if(!session) {
2351
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2352
                return;
2353
        }
2354
        if(session->destroyed)
2355
                return;
2356
        if(session->participant_type == janus_videoroom_p_type_subscriber) {
2357
                /* A listener sent some RTCP, check what it is and if we need to forward it to the publisher */
2358
                janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
2359
                if(!l || !l->video)
2360
                        return;        /* The only feedback we handle is video related anyway... */
2361
                if(janus_rtcp_has_fir(buf, len)) {
2362
                        /* We got a FIR, forward it to the publisher */
2363
                        if(l->feed) {
2364
                                janus_videoroom_participant *p = l->feed;
2365
                                if(p && p->session) {
2366
                                        char rtcpbuf[20];
2367
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &p->fir_seq);
2368
                                        JANUS_LOG(LOG_VERB, "Got a FIR from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2369
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 20);
2370
                                }
2371
                        }
2372
                }
2373
                if(janus_rtcp_has_pli(buf, len)) {
2374
                        /* We got a PLI, forward it to the publisher */
2375
                        if(l->feed) {
2376
                                janus_videoroom_participant *p = l->feed;
2377
                                if(p && p->session) {
2378
                                        char rtcpbuf[12];
2379
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2380
                                        JANUS_LOG(LOG_VERB, "Got a PLI from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2381
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 12);
2382
                                }
2383
                        }
2384
                }
2385
                uint64_t bitrate = janus_rtcp_get_remb(buf, len);
2386
                if(bitrate > 0) {
2387
                        /* FIXME We got a REMB from this listener, should we do something about it? */
2388
                }
2389
        }
2390
}
2391

    
2392
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len) {
2393
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2394
                return;
2395
        if(buf == NULL || len <= 0)
2396
                return;
2397
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2398
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2399
                return;
2400
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2401
        if(!participant->data_active)
2402
                return;
2403
        /* Any forwarder involved? */
2404
        janus_mutex_lock(&participant->rtp_forwarders_mutex);
2405
        /* Forward RTP to the appropriate port for the rtp_forwarders associated with this publisher, if there are any */
2406
        GHashTableIter iter;
2407
        gpointer value;
2408
        g_hash_table_iter_init(&iter, participant->rtp_forwarders);
2409
        while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
2410
                janus_videoroom_rtp_forwarder* rtp_forward = (janus_videoroom_rtp_forwarder*)value;
2411
                if(rtp_forward->is_data) {
2412
                        sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2413
                }
2414
        }
2415
        janus_mutex_unlock(&participant->rtp_forwarders_mutex);
2416
        /* Get a string out of the data */
2417
        char *text = g_malloc0(len+1);
2418
        memcpy(text, buf, len);
2419
        *(text+len) = '\0';
2420
        JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
2421
        /* Save the message if we're recording */
2422
        janus_recorder_save_frame(participant->drc, text, strlen(text));
2423
        /* Relay to all listeners */
2424
        g_slist_foreach(participant->listeners, janus_videoroom_relay_data_packet, text);
2425
        g_free(text);
2426
}
2427

    
2428
void janus_videoroom_slow_link(janus_plugin_session *handle, int uplink, int video) {
2429
        /* The core is informing us that our peer got too many NACKs, are we pushing media too hard? */
2430
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2431
                return;
2432
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2433
        if(!session || session->destroyed || !session->participant)
2434
                return;
2435
        /* Check if it's an uplink (publisher) or downlink (viewer) issue */
2436
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2437
                if(!uplink) {
2438
                        janus_videoroom_participant *publisher = (janus_videoroom_participant *)session->participant;
2439
                        if(publisher) {
2440
                                /* Send an event on the handle to notify the application: it's
2441
                                 * up to the application to then choose a policy and enforce it */
2442
                                json_t *event = json_object();
2443
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2444
                                /* Also add info on what the current bitrate cap is */
2445
                                uint64_t bitrate = (publisher->bitrate ? publisher->bitrate : 256*1024);
2446
                                json_object_set_new(event, "current-bitrate", json_integer(bitrate));
2447
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2448
                                json_decref(event);
2449
                        }
2450
                } else {
2451
                        JANUS_LOG(LOG_WARN, "Got a slow uplink on a VideoRoom publisher? Weird, because it doesn't receive media...\n");
2452
                }
2453
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2454
                if(uplink) {
2455
                        janus_videoroom_listener *viewer = (janus_videoroom_listener *)session->participant;
2456
                        if(viewer) {
2457
                                /* Send an event on the handle to notify the application: it's
2458
                                 * up to the application to then choose a policy and enforce it */
2459
                                json_t *event = json_object();
2460
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2461
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2462
                                json_decref(event);
2463
                        }
2464
                } else {
2465
                        JANUS_LOG(LOG_WARN, "Got a slow downlink on a VideoRoom viewer? Weird, because it doesn't send media...\n");
2466
                }
2467
        }
2468
}
2469

    
2470
static void janus_videoroom_recorder_create(janus_videoroom_participant *participant, gboolean audio, gboolean video, gboolean data) {
2471
        char filename[255];
2472
        gint64 now = janus_get_real_time();
2473
        if(audio) {
2474
                memset(filename, 0, 255);
2475
                if(participant->recording_base) {
2476
                        /* Use the filename and path we have been provided */
2477
                        g_snprintf(filename, 255, "%s-audio", participant->recording_base);
2478
                        participant->arc = janus_recorder_create(participant->room->rec_dir,
2479
                                janus_videoroom_audiocodec_name(participant->room->acodec), filename);
2480
                        if(participant->arc == NULL) {
2481
                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2482
                        }
2483
                } else {
2484
                        /* Build a filename */
2485
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-audio",
2486
                                participant->room->room_id, participant->user_id, now);
2487
                        participant->arc = janus_recorder_create(participant->room->rec_dir,
2488
                                janus_videoroom_audiocodec_name(participant->room->acodec), filename);
2489
                        if(participant->arc == NULL) {
2490
                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2491
                        }
2492
                }
2493
        }
2494
        if(video) {
2495
                memset(filename, 0, 255);
2496
                if(participant->recording_base) {
2497
                        /* Use the filename and path we have been provided */
2498
                        g_snprintf(filename, 255, "%s-video", participant->recording_base);
2499
                        participant->vrc = janus_recorder_create(participant->room->rec_dir,
2500
                                janus_videoroom_videocodec_name(participant->room->vcodec), filename);
2501
                        if(participant->vrc == NULL) {
2502
                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2503
                        }
2504
                } else {
2505
                        /* Build a filename */
2506
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-video",
2507
                                participant->room->room_id, participant->user_id, now);
2508
                        participant->vrc = janus_recorder_create(participant->room->rec_dir,
2509
                                janus_videoroom_videocodec_name(participant->room->vcodec), filename);
2510
                        if(participant->vrc == NULL) {
2511
                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2512
                        }
2513
                }
2514
        }
2515
        if(data) {
2516
                memset(filename, 0, 255);
2517
                if(participant->recording_base) {
2518
                        /* Use the filename and path we have been provided */
2519
                        g_snprintf(filename, 255, "%s-data", participant->recording_base);
2520
                        participant->drc = janus_recorder_create(participant->room->rec_dir,
2521
                                "text", filename);
2522
                        if(participant->drc == NULL) {
2523
                                JANUS_LOG(LOG_ERR, "Couldn't open an data recording file for this publisher!\n");
2524
                        }
2525
                } else {
2526
                        /* Build a filename */
2527
                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-data",
2528
                                participant->room->room_id, participant->user_id, now);
2529
                        participant->drc = janus_recorder_create(participant->room->rec_dir,
2530
                                "text", filename);
2531
                        if(participant->drc == NULL) {
2532
                                JANUS_LOG(LOG_ERR, "Couldn't open an data recording file for this publisher!\n");
2533
                        }
2534
                }
2535
        }
2536
}
2537

    
2538
static void janus_videoroom_recorder_close(janus_videoroom_participant *participant) {
2539
        if(participant->arc) {
2540
                janus_recorder_close(participant->arc);
2541
                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", participant->arc->filename ? participant->arc->filename : "??");
2542
                janus_recorder_free(participant->arc);
2543
        }
2544
        participant->arc = NULL;
2545
        if(participant->vrc) {
2546
                janus_recorder_close(participant->vrc);
2547
                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", participant->vrc->filename ? participant->vrc->filename : "??");
2548
                janus_recorder_free(participant->vrc);
2549
        }
2550
        participant->vrc = NULL;
2551
        if(participant->drc) {
2552
                janus_recorder_close(participant->drc);
2553
                JANUS_LOG(LOG_INFO, "Closed data recording %s\n", participant->drc->filename ? participant->drc->filename : "??");
2554
                janus_recorder_free(participant->drc);
2555
        }
2556
        participant->drc = NULL;
2557
}
2558

    
2559
void janus_videoroom_hangup_media(janus_plugin_session *handle) {
2560
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
2561
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2562
                return;
2563
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2564
        if(!session) {
2565
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2566
                return;
2567
        }
2568
        session->started = FALSE;
2569
        if(session->destroyed)
2570
                return;
2571
        if(g_atomic_int_add(&session->hangingup, 1))
2572
                return;
2573
        /* Send an event to the browser and tell the PeerConnection is over */
2574
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2575
                /* This publisher just 'unpublished' */
2576
                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2577
                if(participant->sdp)
2578
                        g_free(participant->sdp);
2579
                participant->sdp = NULL;
2580
                participant->firefox = FALSE;
2581
                participant->audio_active = FALSE;
2582
                participant->video_active = FALSE;
2583
                participant->data_active = FALSE;
2584
                participant->remb_startup = 4;
2585
                participant->remb_latest = 0;
2586
                participant->fir_latest = 0;
2587
                participant->fir_seq = 0;
2588
                /* Get rid of the recorders, if available */
2589
                janus_mutex_lock(&participant->rec_mutex);
2590
                janus_videoroom_recorder_close(participant);
2591
                janus_mutex_unlock(&participant->rec_mutex);
2592
                janus_mutex_lock(&participant->listeners_mutex);
2593
                while(participant->listeners) {
2594
                        janus_videoroom_listener *l = (janus_videoroom_listener *)participant->listeners->data;
2595
                        if(l) {
2596
                                participant->listeners = g_slist_remove(participant->listeners, l);
2597
                                l->feed = NULL;
2598
                        }
2599
                }
2600
                janus_mutex_unlock(&participant->listeners_mutex);
2601
                janus_videoroom_leave_or_unpublish(participant, FALSE);
2602
                /* Also notify event handlers */
2603
                if(participant->room && gateway->events_is_enabled()) {
2604
                        json_t *info = json_object();
2605
                        json_object_set_new(info, "event", json_string("unpublished"));
2606
                        json_object_set_new(info, "room", json_integer(participant->room->room_id));
2607
                        json_object_set_new(info, "id", json_integer(participant->user_id));
2608
                        gateway->notify_event(&janus_videoroom_plugin, handle, info);
2609
                }
2610
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2611
                /* Get rid of listener */
2612
                janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2613
                if(listener) {
2614
                        listener->paused = TRUE;
2615
                        janus_videoroom_participant *publisher = listener->feed;
2616
                        if(publisher != NULL) {
2617
                                janus_mutex_lock(&publisher->listeners_mutex);
2618
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
2619
                                janus_mutex_unlock(&publisher->listeners_mutex);
2620
                                listener->feed = NULL;
2621
                                /* Also notify event handlers */
2622
                                if(notify_events && gateway->events_is_enabled()) {
2623
                                        json_t *info = json_object();
2624
                                        json_object_set_new(info, "event", json_string("unsubscribed"));
2625
                                        json_object_set_new(info, "room", json_integer(publisher->room->room_id));
2626
                                        json_object_set_new(info, "feed", json_integer(publisher->user_id));
2627
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
2628
                                }
2629
                        }
2630
                }
2631
                /* TODO Should we close the handle as well? */
2632
        }
2633
}
2634

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

    
3365
                /* Prepare JSON event */
3366
                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3367
                /* Any SDP to handle? */
3368
                const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
3369
                const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
3370
                if(!msg_sdp) {
3371
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3372
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3373
                        json_decref(event);
3374
                } else {
3375
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
3376
                        const char *type = NULL;
3377
                        if(!strcasecmp(msg_sdp_type, "offer")) {
3378
                                /* We need to answer */
3379
                                type = "answer";
3380
                        } else if(!strcasecmp(msg_sdp_type, "answer")) {
3381
                                /* We got an answer (from a listener?), no need to negotiate */
3382
                                g_atomic_int_set(&session->hangingup, 0);
3383
                                int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3384
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3385
                                json_decref(event);
3386
                                janus_videoroom_message_free(msg);
3387
                                continue;
3388
                        } else {
3389
                                /* TODO We don't support anything else right now... */
3390
                                JANUS_LOG(LOG_ERR, "Unknown SDP type '%s'\n", msg_sdp_type);
3391
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3392
                                g_snprintf(error_cause, 512, "Unknown SDP type '%s'", msg_sdp_type);
3393
                                goto error;
3394
                        }
3395
                        if(session->participant_type != janus_videoroom_p_type_publisher) {
3396
                                /* We shouldn't be here, we always offer ourselves */
3397
                                JANUS_LOG(LOG_ERR, "Only publishers send offers\n");
3398
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3399
                                g_snprintf(error_cause, 512, "Only publishers send offers");
3400
                                goto error;
3401
                        } else {
3402
                                /* This is a new publisher: is there room? */
3403
                                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3404
                                janus_videoroom *videoroom = participant->room;
3405
                                int count = 0;
3406
                                GHashTableIter iter;
3407
                                gpointer value;
3408
                                if(!videoroom) {
3409
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3410
                                        goto error;
3411
                                }
3412
                                if(videoroom->destroyed) {
3413
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3414
                                        goto error;
3415
                                }
3416
                                janus_mutex_lock(&videoroom->participants_mutex);
3417
                                g_hash_table_iter_init(&iter, videoroom->participants);
3418
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3419
                                        janus_videoroom_participant *p = value;
3420
                                        if(p != participant && p->sdp)
3421
                                                count++;
3422
                                }
3423
                                janus_mutex_unlock(&videoroom->participants_mutex);
3424
                                if(count == videoroom->max_publishers) {
3425
                                        participant->audio_active = FALSE;
3426
                                        participant->video_active = FALSE;
3427
                                        participant->data_active = FALSE;
3428
                                        JANUS_LOG(LOG_ERR, "Maximum number of publishers (%d) already reached\n", videoroom->max_publishers);
3429
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3430
                                        g_snprintf(error_cause, 512, "Maximum number of publishers (%d) already reached", videoroom->max_publishers);
3431
                                        goto error;
3432
                                }
3433
                                /* Now prepare the SDP to give back */
3434
                                if(strstr(msg_sdp, "Mozilla")) {
3435
                                        participant->firefox = TRUE;
3436
                                }
3437
                                /* Start by parsing the offer */
3438
                                char error_str[512];
3439
                                janus_sdp *offer = janus_sdp_parse(msg_sdp, error_str, sizeof(error_str));
3440
                                if(offer == NULL) {
3441
                                        json_decref(event);
3442
                                        JANUS_LOG(LOG_ERR, "Error parsing offer: %s\n", error_str);
3443
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP;
3444
                                        g_snprintf(error_cause, 512, "Error parsing offer: %s", error_str);
3445
                                        goto error;
3446
                                }
3447
                                gboolean audio_level_extmap = FALSE, video_orient_extmap = FALSE, playout_delay_extmap = FALSE;
3448
                                GList *temp = offer->m_lines;
3449
                                while(temp) {
3450
                                        /* Which media are available? */
3451
                                        janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3452
                                        if(m->type == JANUS_SDP_AUDIO && m->port > 0) {
3453
                                                participant->audio = TRUE;
3454
                                        } else if(m->type == JANUS_SDP_VIDEO && m->port > 0) {
3455
                                                participant->video = TRUE;
3456
                                        } else if(m->type == JANUS_SDP_APPLICATION && m->port > 0) {
3457
                                                participant->data = TRUE;
3458
                                        }
3459
                                        if(m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO) {
3460
                                                /* Are the extmaps we care about there? */
3461
                                                GList *ma = m->attributes;
3462
                                                while(ma) {
3463
                                                        janus_sdp_attribute *a = (janus_sdp_attribute *)ma->data;
3464
                                                        if(a->value) {
3465
                                                                if(videoroom->audiolevel_ext && m->type == JANUS_SDP_AUDIO && strstr(a->value, JANUS_RTP_EXTMAP_AUDIO_LEVEL)) {
3466
                                                                        participant->audio_level_extmap_id = atoi(a->value);
3467
                                                                        audio_level_extmap = TRUE;
3468
                                                                } else if(videoroom->videoorient_ext && m->type == JANUS_SDP_VIDEO && strstr(a->value, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION)) {
3469
                                                                        participant->video_orient_extmap_id = atoi(a->value);
3470
                                                                        video_orient_extmap = TRUE;
3471
                                                                } else if(videoroom->playoutdelay_ext && m->type == JANUS_SDP_VIDEO && strstr(a->value, JANUS_RTP_EXTMAP_PLAYOUT_DELAY)) {
3472
                                                                        participant->playout_delay_extmap_id = atoi(a->value);
3473
                                                                        playout_delay_extmap = TRUE;
3474
                                                                }
3475
                                                        }
3476
                                                        ma = ma->next;
3477
                                                }
3478
                                        }
3479
                                        temp = temp->next;
3480
                                }
3481
                                /* Prepare an answer now: force the room codecs and recvonly on the Janus side */
3482
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send an audio stream\n", participant->audio ? "is" : "is NOT");
3483
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send a video stream\n", participant->video ? "is" : "is NOT");
3484
                                JANUS_LOG(LOG_VERB, "The publisher %s going to open a data channel\n", participant->data ? "is" : "is NOT");
3485
                                janus_sdp *answer = janus_sdp_generate_answer(offer,
3486
                                        JANUS_SDP_OA_AUDIO_CODEC, janus_videoroom_audiocodec_name(videoroom->acodec),
3487
                                        JANUS_SDP_OA_AUDIO_DIRECTION, JANUS_SDP_RECVONLY,
3488
                                        JANUS_SDP_OA_VIDEO_CODEC, janus_videoroom_videocodec_name(videoroom->vcodec),
3489
                                        JANUS_SDP_OA_VIDEO_DIRECTION, JANUS_SDP_RECVONLY,
3490
                                        JANUS_SDP_OA_DONE);
3491
                                janus_sdp_free(offer);
3492
                                /* Replace the session name */
3493
                                g_free(answer->s_name);
3494
                                answer->s_name = g_strdup(videoroom->room_name);
3495
                                /* Which media are REALLY available? (some may have been rejected) */
3496
                                participant->audio = FALSE;
3497
                                participant->video = FALSE;
3498
                                participant->data = FALSE;
3499
                                temp = answer->m_lines;
3500
                                while(temp) {
3501
                                        janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3502
                                        if(m->type == JANUS_SDP_AUDIO && m->port > 0) {
3503
                                                participant->audio = TRUE;
3504
                                        } else if(m->type == JANUS_SDP_VIDEO && m->port > 0) {
3505
                                                participant->video = TRUE;
3506
                                        } else if(m->type == JANUS_SDP_APPLICATION && m->port > 0) {
3507
                                                participant->data = TRUE;
3508
                                        }
3509
                                        temp = temp->next;
3510
                                }
3511
                                JANUS_LOG(LOG_VERB, "Per the answer, the publisher %s going to send an audio stream\n", participant->audio ? "is" : "is NOT");
3512
                                JANUS_LOG(LOG_VERB, "Per the answer, the publisher %s going to send a video stream\n", participant->video ? "is" : "is NOT");
3513
                                JANUS_LOG(LOG_VERB, "Per the answer, the publisher %s going to open a data channel\n", participant->data ? "is" : "is NOT");
3514
                                /* Also add a bandwidth SDP attribute if we're capping the bitrate in the room */
3515
                                if(participant->firefox) {        /* Don't add any b=AS attribute for Chrome */
3516
                                        janus_sdp_mline *m = janus_sdp_mline_find(answer, JANUS_SDP_VIDEO);
3517
                                        if(m != NULL && videoroom->bitrate > 0) {
3518
                                                m->b_name = g_strdup("AS");
3519
                                                m->b_value = (int)(videoroom->bitrate/1000);
3520
                                        }
3521
                                }
3522
                                /* Add the extmap attributes, if needed */
3523
                                if(audio_level_extmap) {
3524
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3525
                                                "%d %s\r\n", participant->audio_level_extmap_id, JANUS_RTP_EXTMAP_AUDIO_LEVEL);
3526
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(answer, JANUS_SDP_AUDIO), a);
3527
                                }
3528
                                if(video_orient_extmap) {
3529
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3530
                                                "%d %s\r\n", participant->video_orient_extmap_id, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION);
3531
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(answer, JANUS_SDP_VIDEO), a);
3532
                                }
3533
                                if(playout_delay_extmap) {
3534
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3535
                                                "%d %s\r\n", participant->playout_delay_extmap_id, JANUS_RTP_EXTMAP_PLAYOUT_DELAY);
3536
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(answer, JANUS_SDP_VIDEO), a);
3537
                                }
3538
                                /* Generate an SDP string we can send back to the publisher */
3539
                                char *answer_sdp = janus_sdp_write(answer);
3540
                                /* Now turn the SDP into what we'll send subscribers, using the static payload types for making switching easier */
3541
                                offer = janus_sdp_generate_offer(videoroom->room_name, answer->c_addr,
3542
                                        JANUS_SDP_OA_AUDIO, participant->audio,
3543
                                        JANUS_SDP_OA_AUDIO_CODEC, janus_videoroom_audiocodec_name(videoroom->acodec),
3544
                                        JANUS_SDP_OA_AUDIO_PT, janus_videoroom_audiocodec_pt(videoroom->acodec),
3545
                                        JANUS_SDP_OA_AUDIO_DIRECTION, JANUS_SDP_SENDONLY,
3546
                                        JANUS_SDP_OA_VIDEO, participant->video,
3547
                                        JANUS_SDP_OA_VIDEO_CODEC, janus_videoroom_videocodec_name(videoroom->vcodec),
3548
                                        JANUS_SDP_OA_VIDEO_PT, janus_videoroom_videocodec_pt(videoroom->vcodec),
3549
                                        JANUS_SDP_OA_VIDEO_DIRECTION, JANUS_SDP_SENDONLY,
3550
                                        JANUS_SDP_OA_DATA, participant->data,
3551
                                        JANUS_SDP_OA_DONE);
3552
                                /* Add the extmap attributes, if needed */
3553
                                if(audio_level_extmap) {
3554
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3555
                                                "%d %s\r\n", participant->audio_level_extmap_id, JANUS_RTP_EXTMAP_AUDIO_LEVEL);
3556
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(offer, JANUS_SDP_AUDIO), a);
3557
                                }
3558
                                if(video_orient_extmap) {
3559
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3560
                                                "%d %s\r\n", participant->video_orient_extmap_id, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION);
3561
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(offer, JANUS_SDP_VIDEO), a);
3562
                                }
3563
                                if(playout_delay_extmap) {
3564
                                        janus_sdp_attribute *a = janus_sdp_attribute_create("extmap",
3565
                                                "%d %s\r\n", participant->playout_delay_extmap_id, JANUS_RTP_EXTMAP_PLAYOUT_DELAY);
3566
                                        janus_sdp_attribute_add_to_mline(janus_sdp_mline_find(offer, JANUS_SDP_VIDEO), a);
3567
                                }
3568
                                /* Generate an SDP string we can offer subscribers later on */
3569
                                char *offer_sdp = janus_sdp_write(offer);
3570
                                janus_sdp_free(offer);
3571
                                janus_sdp_free(answer);
3572
                                /* Is this room recorded? */
3573
                                janus_mutex_lock(&participant->rec_mutex);
3574
                                if(videoroom->record || participant->recording_active) {
3575
                                        janus_videoroom_recorder_create(participant, participant->audio, participant->video, participant->data);
3576
                                }
3577
                                janus_mutex_unlock(&participant->rec_mutex);
3578
                                /* Send the answer back to the publisher */
3579
                                JANUS_LOG(LOG_VERB, "Handling publisher: turned this into an '%s':\n%s\n", type, answer_sdp);
3580
                                json_t *jsep = json_pack("{ssss}", "type", type, "sdp", answer_sdp);
3581
                                g_free(answer_sdp);
3582
                                /* How long will the gateway take to push the event? */
3583
                                g_atomic_int_set(&session->hangingup, 0);
3584
                                gint64 start = janus_get_monotonic_time();
3585
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, jsep);
3586
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3587
                                /* Done */
3588
                                if(res != JANUS_OK) {
3589
                                        /* TODO Failed to negotiate? We should remove this publisher */
3590
                                        g_free(offer_sdp);
3591
                                } else {
3592
                                        /* Store the participant's SDP for interested listeners */
3593
                                        participant->sdp = offer_sdp;
3594
                                        /* We'll wait for the setup_media event before actually telling listeners */
3595
                                }
3596
                                json_decref(event);
3597
                                json_decref(jsep);
3598
                        }
3599
                }
3600
                janus_videoroom_message_free(msg);
3601

    
3602
                continue;
3603
                
3604
error:
3605
                {
3606
                        /* Prepare JSON error event */
3607
                        json_t *event = json_object();
3608
                        json_object_set_new(event, "videoroom", json_string("event"));
3609
                        json_object_set_new(event, "error_code", json_integer(error_code));
3610
                        json_object_set_new(event, "error", json_string(error_cause));
3611
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3612
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
3613
                        json_decref(event);
3614
                        janus_videoroom_message_free(msg);
3615
                }
3616
        }
3617
        JANUS_LOG(LOG_VERB, "Leaving VideoRoom handler thread\n");
3618
        return NULL;
3619
}
3620

    
3621

    
3622
/* Helper to quickly relay RTP packets from publishers to subscribers */
3623
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data) {
3624
        janus_videoroom_rtp_relay_packet *packet = (janus_videoroom_rtp_relay_packet *)user_data;
3625
        if(!packet || !packet->data || packet->length < 1) {
3626
                JANUS_LOG(LOG_ERR, "Invalid packet...\n");
3627
                return;
3628
        }
3629
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3630
        if(!listener || !listener->session) {
3631
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3632
                return;
3633
        }
3634
        if(listener->paused) {
3635
                // JANUS_LOG(LOG_ERR, "This listener paused the stream...\n");
3636
                return;
3637
        }
3638
        janus_videoroom_session *session = listener->session;
3639
        if(!session || !session->handle) {
3640
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3641
                return;
3642
        }
3643
        if(!session->started) {
3644
                // JANUS_LOG(LOG_ERR, "Streaming not started yet for this session...\n");
3645
                return;
3646
        }
3647
        
3648
        /* Make sure there hasn't been a publisher switch by checking the SSRC */
3649
        if(packet->is_video) {
3650
                /* Check if this listener is subscribed to this medium */
3651
                if(!listener->video) {
3652
                        /* Nope, don't relay */
3653
                        return;
3654
                }
3655
                /* Fix sequence number and timestamp (publisher switching may be involved) */
3656
                janus_rtp_header_update(packet->data, &listener->context, TRUE, 4500);
3657
                if(gateway != NULL)
3658
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3659
                /* Restore the timestamp and sequence number to what the publisher set them to */
3660
                packet->data->timestamp = htonl(packet->timestamp);
3661
                packet->data->seq_number = htons(packet->seq_number);
3662
        } else {
3663
                /* Check if this listener is subscribed to this medium */
3664
                if(!listener->audio) {
3665
                        /* Nope, don't relay */
3666
                        return;
3667
                }
3668
                /* Fix sequence number and timestamp (publisher switching may be involved) */
3669
                janus_rtp_header_update(packet->data, &listener->context, FALSE, 960);
3670
                if(gateway != NULL)
3671
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3672
                /* Restore the timestamp and sequence number to what the publisher set them to */
3673
                packet->data->timestamp = htonl(packet->timestamp);
3674
                packet->data->seq_number = htons(packet->seq_number);
3675
        }
3676

    
3677
        return;
3678
}
3679

    
3680
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data) {
3681
        char *text = (char *)user_data;
3682
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3683
        if(!listener || !listener->session || !listener->data || listener->paused) {
3684
                return;
3685
        }
3686
        janus_videoroom_session *session = listener->session;
3687
        if(!session || !session->handle) {
3688
                return;
3689
        }
3690
        if(!session->started) {
3691
                return;
3692
        }
3693
        if(gateway != NULL && text != NULL) {
3694
                JANUS_LOG(LOG_VERB, "Forwarding DataChannel message (%zu bytes) to viewer: %s\n", strlen(text), text);
3695
                gateway->relay_data(session->handle, text, strlen(text));
3696
        }
3697
        return;
3698
}
3699

    
3700
/* Helper to free janus_videoroom structs. */
3701
static void janus_videoroom_free(janus_videoroom *room) {
3702
        if(room) {
3703
                janus_mutex_lock(&room->participants_mutex);
3704
                g_free(room->room_name);
3705
                g_free(room->room_secret);
3706
                g_free(room->room_pin);
3707
                g_free(room->rec_dir);
3708
                g_hash_table_unref(room->participants);
3709
                g_hash_table_unref(room->private_ids);
3710
                g_hash_table_destroy(room->allowed);
3711
                janus_mutex_unlock(&room->participants_mutex);
3712
                janus_mutex_destroy(&room->participants_mutex);
3713
                g_free(room);
3714
                room = NULL;
3715
        }
3716
}
3717

    
3718
static void janus_videoroom_listener_free(janus_videoroom_listener *l) {
3719
        JANUS_LOG(LOG_VERB, "Freeing listener\n");
3720
        g_free(l);
3721
}
3722

    
3723
static void janus_videoroom_participant_free(janus_videoroom_participant *p) {
3724
        JANUS_LOG(LOG_VERB, "Freeing publisher\n");
3725
        g_free(p->display);
3726
        g_free(p->sdp);
3727

    
3728
        if(p->arc) {
3729
                janus_recorder_free(p->arc);
3730
                p->arc = NULL;
3731
        }
3732
        if(p->vrc) {
3733
                janus_recorder_free(p->vrc);
3734
                p->vrc = NULL;
3735
        }
3736
        if(p->drc) {
3737
                janus_recorder_free(p->drc);
3738
                p->drc = NULL;
3739
        }
3740

    
3741
        janus_mutex_lock(&p->listeners_mutex);
3742
        while(p->listeners) {
3743
                janus_videoroom_listener *l = (janus_videoroom_listener *)p->listeners->data;
3744
                if(l) {
3745
                        p->listeners = g_slist_remove(p->listeners, l);
3746
                        l->feed = NULL;
3747
                }
3748
        }
3749
        janus_mutex_unlock(&p->listeners_mutex);
3750
        janus_mutex_lock(&p->rtp_forwarders_mutex);
3751
        if(p->udp_sock > 0) {
3752
                close(p->udp_sock);
3753
                p->udp_sock = 0;
3754
        }
3755
        g_hash_table_destroy(p->rtp_forwarders);
3756
        p->rtp_forwarders = NULL;
3757
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
3758
        g_slist_free(p->listeners);
3759

    
3760
        janus_mutex_destroy(&p->listeners_mutex);
3761
        janus_mutex_destroy(&p->rtp_forwarders_mutex);
3762
        g_free(p);
3763
}