Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videoroom.c @ cd5a86e5

History | View | Annotate | Download (191 KB)

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

    
130
#include "plugin.h"
131

    
132
#include <jansson.h>
133

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

    
146

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

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

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

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

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

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

    
305
/* Static configuration instance */
306
static janus_config *config = NULL;
307
static const char *config_folder = NULL;
308
static janus_mutex config_mutex;
309

    
310
/* Useful stuff */
311
static volatile gint initialized = 0, stopping = 0;
312
static gboolean notify_events = TRUE;
313
static janus_callbacks *gateway = NULL;
314
static GThread *handler_thread;
315
static GThread *watchdog;
316
static void *janus_videoroom_handler(void *data);
317
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data);
318
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data);
319

    
320
typedef enum janus_videoroom_p_type {
321
        janus_videoroom_p_type_none = 0,
322
        janus_videoroom_p_type_subscriber,                        /* Generic listener/subscriber */
323
        janus_videoroom_p_type_subscriber_muxed,        /* Multiplexed listener/subscriber */
324
        janus_videoroom_p_type_publisher,                        /* Participant/publisher */
325
} janus_videoroom_p_type;
326

    
327
typedef struct janus_videoroom_message {
328
        janus_plugin_session *handle;
329
        char *transaction;
330
        json_t *message;
331
        json_t *jsep;
332
} janus_videoroom_message;
333
static GAsyncQueue *messages = NULL;
334
static janus_videoroom_message exit_message;
335

    
336
static void janus_videoroom_message_free(janus_videoroom_message *msg) {
337
        if(!msg || msg == &exit_message)
338
                return;
339

    
340
        msg->handle = NULL;
341

    
342
        g_free(msg->transaction);
343
        msg->transaction = NULL;
344
        if(msg->message)
345
                json_decref(msg->message);
346
        msg->message = NULL;
347
        if(msg->jsep)
348
                json_decref(msg->jsep);
349
        msg->jsep = NULL;
350

    
351
        g_free(msg);
352
}
353

    
354
typedef enum janus_videoroom_audiocodec {
355
        JANUS_VIDEOROOM_OPUS,                /* Publishers will have to use OPUS         */
356
        JANUS_VIDEOROOM_ISAC_32K,        /* Publishers will have to use ISAC 32K */
357
        JANUS_VIDEOROOM_ISAC_16K,        /* Publishers will have to use ISAC 16K */
358
        JANUS_VIDEOROOM_PCMU,                /* Publishers will have to use PCMU 8K         */
359
        JANUS_VIDEOROOM_PCMA                /* Publishers will have to use PCMA 8K         */
360
} janus_videoroom_audiocodec;
361
static const char *janus_videoroom_audiocodec_name(janus_videoroom_audiocodec acodec) {
362
        switch(acodec) {
363
                case JANUS_VIDEOROOM_OPUS:
364
                        return "opus";
365
                case JANUS_VIDEOROOM_ISAC_32K:
366
                        return "isac32";
367
                case JANUS_VIDEOROOM_ISAC_16K:
368
                        return "isac16";
369
                case JANUS_VIDEOROOM_PCMU:
370
                        return "pcmu";
371
                case JANUS_VIDEOROOM_PCMA:
372
                        return "pcma";
373
                default:
374
                        /* Shouldn't happen */
375
                        return "opus";
376
        }
377
}
378

    
379
typedef enum janus_videoroom_videocodec {
380
        JANUS_VIDEOROOM_VP8,        /* Publishers will have to use VP8 */
381
        JANUS_VIDEOROOM_VP9,        /* Publishers will have to use VP9 */
382
        JANUS_VIDEOROOM_H264        /* Publishers will have to use H264 */
383
} janus_videoroom_videocodec;
384
static const char *janus_videoroom_videocodec_name(janus_videoroom_videocodec vcodec) {
385
        switch(vcodec) {
386
                case JANUS_VIDEOROOM_VP8:
387
                        return "vp8";
388
                case JANUS_VIDEOROOM_VP9:
389
                        return "vp9";
390
                case JANUS_VIDEOROOM_H264:
391
                        return "h264";
392
                default:
393
                        /* Shouldn't happen */
394
                        return "vp8";
395
        }
396
}
397

    
398
typedef struct janus_videoroom {
399
        guint64 room_id;                        /* Unique room ID */
400
        gchar *room_name;                        /* Room description */
401
        gchar *room_secret;                        /* Secret needed to manipulate (e.g., destroy) this room */
402
        gchar *room_pin;                        /* Password needed to join this room, if any */
403
        gboolean is_private;                /* Whether this room is 'private' (as in hidden) or not */
404
        int max_publishers;                        /* Maximum number of concurrent publishers */
405
        uint64_t bitrate;                        /* Global bitrate limit */
406
        uint16_t fir_freq;                        /* Regular FIR frequency (0=disabled) */
407
        janus_videoroom_audiocodec acodec;        /* Audio codec to force on publishers*/
408
        janus_videoroom_videocodec vcodec;        /* Video codec to force on publishers*/
409
        gboolean audiolevel_ext;        /* Whether the ssrc-audio-level extension must be negotiated or not for new publishers */
410
        gboolean videoorient_ext;        /* Whether the video-orientation extension must be negotiated or not for new publishers */
411
        gboolean playoutdelay_ext;        /* Whether the playout-delay extension must be negotiated or not for new publishers */
412
        gboolean record;                        /* Whether the feeds from publishers in this room should be recorded */
413
        char *rec_dir;                                /* Where to save the recordings of this room, if enabled */
414
        gint64 destroyed;                        /* Value to flag the room for destruction, done lazily */
415
        GHashTable *participants;        /* Map of potential publishers (we get listeners from them) */
416
        GHashTable *private_ids;        /* Map of existing private IDs */
417
        gboolean check_tokens;                /* Whether to check tokens when participants join (see below) */
418
        GHashTable *allowed;                /* Map of participants (as tokens) allowed to join */
419
        janus_mutex participants_mutex;/* Mutex to protect room properties */
420
} janus_videoroom;
421
static GHashTable *rooms;
422
static janus_mutex rooms_mutex;
423
static GList *old_rooms;
424
static char *admin_key = NULL;
425
static void janus_videoroom_free(janus_videoroom *room);
426

    
427
typedef struct janus_videoroom_session {
428
        janus_plugin_session *handle;
429
        janus_videoroom_p_type participant_type;
430
        gpointer participant;
431
        gboolean started;
432
        gboolean stopping;
433
        volatile gint hangingup;
434
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
435
} janus_videoroom_session;
436
static GHashTable *sessions;
437
static GList *old_sessions;
438
static janus_mutex sessions_mutex;
439

    
440
/* a host whose ports gets streamed rtp packets of the corresponding type. */
441
typedef struct janus_videoroom_rtp_forwarder {
442
        gboolean is_video;
443
        uint32_t ssrc;
444
        int payload_type;
445
        struct sockaddr_in serv_addr;
446
} janus_videoroom_rtp_forwarder;
447

    
448
typedef struct janus_videoroom_participant {
449
        janus_videoroom_session *session;
450
        janus_videoroom *room;        /* Room */
451
        guint64 user_id;        /* Unique ID in the room */
452
        guint32 pvt_id;                /* This is sent to the publisher for mapping purposes, but shouldn't be shared with others */
453
        gchar *display;                /* Display name (just for fun) */
454
        gchar *sdp;                        /* The SDP this publisher negotiated, if any */
455
        gboolean audio, video, data;                /* Whether audio, video and/or data is going to be sent by this publisher */
456
        guint32 audio_pt;                /* Audio payload type (Opus) */
457
        guint32 video_pt;                /* Video payload type (depends on room configuration) */
458
        guint32 audio_ssrc;                /* Audio SSRC of this publisher */
459
        guint32 video_ssrc;                /* Video SSRC of this publisher */
460
        guint8 audio_level_extmap_id;        /* Audio level extmap ID */
461
        guint8 video_orient_extmap_id;        /* Video orientation extmap ID */
462
        guint8 playout_delay_extmap_id;        /* Playout delay extmap ID */
463
        gboolean audio_active;
464
        gboolean video_active;
465
        int audio_active_packets; /* number of packets received with audio_levl extmap sdp header */
466
        int audio_dBov_sum;
467
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
468
        uint64_t bitrate;
469
        gint64 remb_startup;/* Incremental changes on REMB to reach the target at startup */
470
        gint64 remb_latest;        /* Time of latest sent REMB (to avoid flooding) */
471
        gint64 fir_latest;        /* Time of latest sent FIR (to avoid flooding) */
472
        gint fir_seq;                /* FIR sequence number */
473
        gboolean recording_active;        /* Whether this publisher has to be recorded or not */
474
        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 */
475
        janus_recorder *arc;        /* The Janus recorder instance for this publisher's audio, if enabled */
476
        janus_recorder *vrc;        /* The Janus recorder instance for this publisher's video, if enabled */
477
        janus_mutex rec_mutex;        /* Mutex to protect the recorders from race conditions */
478
        GSList *listeners;
479
        janus_mutex listeners_mutex;
480
        GHashTable *rtp_forwarders;
481
        janus_mutex rtp_forwarders_mutex;
482
        int udp_sock; /* The udp socket on which to forward rtp packets */
483
} janus_videoroom_participant;
484
static void janus_videoroom_participant_free(janus_videoroom_participant *p);
485
static void janus_videoroom_rtp_forwarder_free_helper(gpointer data);
486
static guint32 janus_videoroom_rtp_forwarder_add_helper(janus_videoroom_participant *p, const gchar* host, int port, int pt, uint32_t ssrc, gboolean is_video);
487
typedef struct janus_videoroom_listener_context {
488
        /* Needed to fix seq and ts in case of publisher switching */
489
        uint32_t a_last_ssrc, a_last_ts, a_base_ts, a_base_ts_prev,
490
                        v_last_ssrc, v_last_ts, v_base_ts, v_base_ts_prev;
491
        uint16_t a_last_seq, a_base_seq, a_base_seq_prev,
492
                        v_last_seq, v_base_seq, v_base_seq_prev;
493
        gboolean a_seq_reset, v_seq_reset;
494
} janus_videoroom_listener_context;
495

    
496
typedef struct janus_videoroom_listener {
497
        janus_videoroom_session *session;
498
        janus_videoroom *room;        /* Room */
499
        janus_videoroom_participant *feed;        /* Participant this listener is subscribed to */
500
        guint32 pvt_id;                /* Private ID of the participant that is subscribing (if available/provided) */
501
        janus_videoroom_listener_context context;        /* Needed in case there are publisher switches on this listener */
502
        gboolean audio, video, data;                /* Whether audio, video and/or data must be sent to this publisher */
503
        struct janus_videoroom_listener_muxed *parent;        /* Overall subscriber, if this is a sub-listener in a Multiplexed one */
504
        gboolean paused;
505
} janus_videoroom_listener;
506
static void janus_videoroom_listener_free(janus_videoroom_listener *l);
507

    
508
typedef struct janus_videoroom_listener_muxed {
509
        janus_videoroom_session *session;
510
        janus_videoroom *room;        /* Room */
511
        GSList *listeners;        /* List of listeners (as a Multiplexed listener can be subscribed to more publishers at the same time) */
512
        janus_mutex listeners_mutex;
513
} janus_videoroom_listener_muxed;
514
static void janus_videoroom_muxed_listener_free(janus_videoroom_listener_muxed *l);
515

    
516
typedef struct janus_videoroom_rtp_relay_packet {
517
        rtp_header *data;
518
        gint length;
519
        gboolean is_video;
520
        uint32_t timestamp;
521
        uint16_t seq_number;
522
} janus_videoroom_rtp_relay_packet;
523

    
524
/* SDP offer/answer templates */
525
#define OPUS_PT        111
526
#define ISAC32_PT        104
527
#define ISAC16_PT        103
528
#define PCMU_PT        0
529
#define PCMA_PT        8
530
#define VP8_PT                100
531
#define VP9_PT                101
532
#define H264_PT        107
533
#define sdp_template \
534
                "v=0\r\n" \
535
                "o=- %"SCNu64" %"SCNu64" IN IP4 127.0.0.1\r\n"        /* We need current time here */ \
536
                "s=%s\r\n"                                                        /* Video room name */ \
537
                "t=0 0\r\n" \
538
                "%s%s%s"                                /* Audio, video and/or data channel m-lines */
539
#define sdp_a_template_opus \
540
                "m=audio 1 RTP/SAVPF %d\r\n"                /* Opus payload type */ \
541
                "c=IN IP4 1.1.1.1\r\n" \
542
                "a=%s\r\n"                                                        /* Media direction */ \
543
                "a=rtpmap:%d opus/48000/2\r\n"                /* Opus payload type */ \
544
                "%s"                                                                /* extmap(s), if any */
545
#define sdp_a_template_isac32 \
546
                "m=audio 1 RTP/SAVPF %d\r\n"                /* ISAC32_PT payload type */ \
547
                "c=IN IP4 1.1.1.1\r\n" \
548
                "a=%s\r\n"                                                        /* Media direction */ \
549
                "a=rtpmap:%d ISAC/32000\r\n"                /* ISAC32_PT payload type */ \
550
                "%s"                                                                /* extmap(s), if any */
551
#define sdp_a_template_isac16 \
552
                "m=audio 1 RTP/SAVPF %d\r\n"                /* ISAC16_PT payload type */ \
553
                "c=IN IP4 1.1.1.1\r\n" \
554
                "a=%s\r\n"                                                        /* Media direction */ \
555
                "a=rtpmap:%d ISAC/16000\r\n"                /* ISAC16_PT payload type */ \
556
                "%s"                                                                /* extmap(s), if any */
557
#define sdp_a_template_pcmu \
558
                "m=audio 1 RTP/SAVPF %d\r\n"                /* PCMU_PT payload type */ \
559
                "c=IN IP4 1.1.1.1\r\n" \
560
                "a=%s\r\n"                                                        /* Media direction */ \
561
                "a=rtpmap:%d PCMU/8000\r\n"                    /* PCMU_PT payload type */ \
562
                "%s"                                                                /* extmap(s), if any */
563
#define sdp_a_template_pcma \
564
                "m=audio 1 RTP/SAVPF %d\r\n"                /* PCMA_PT payload type */ \
565
                "c=IN IP4 1.1.1.1\r\n" \
566
                "a=%s\r\n"                                                        /* Media direction */ \
567
                "a=rtpmap:%d PCMA/8000\r\n"                    /* PCMA_PT payload type */ \
568
                "%s"                                                                /* extmap(s), if any */
569
#define sdp_v_template_vp8 \
570
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP8 payload type */ \
571
                "c=IN IP4 1.1.1.1\r\n" \
572
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
573
                "a=%s\r\n"                                                        /* Media direction */ \
574
                "a=rtpmap:%d VP8/90000\r\n"                        /* VP8 payload type */ \
575
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP8 payload type */ \
576
                "a=rtcp-fb:%d nack\r\n"                                /* VP8 payload type */ \
577
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP8 payload type */ \
578
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP8 payload type */ \
579
                "%s"                                                                /* extmap(s), if any */
580
#define sdp_v_template_vp9 \
581
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP9 payload type */ \
582
                "c=IN IP4 1.1.1.1\r\n" \
583
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
584
                "a=%s\r\n"                                                        /* Media direction */ \
585
                "a=rtpmap:%d VP9/90000\r\n"                        /* VP9 payload type */ \
586
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP9 payload type */ \
587
                "a=rtcp-fb:%d nack\r\n"                                /* VP9 payload type */ \
588
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP9 payload type */ \
589
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP9 payload type */ \
590
                "%s"                                                                /* extmap(s), if any */
591
#define sdp_v_template_h264 \
592
                "m=video 1 RTP/SAVPF %d\r\n"                /* H264 payload type */ \
593
                "c=IN IP4 1.1.1.1\r\n" \
594
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
595
                "a=%s\r\n"                                                        /* Media direction */ \
596
                "a=rtpmap:%d H264/90000\r\n"                /* H264 payload type */ \
597
                "a=fmtp:%d profile-level-id=42e01f;packetization-mode=1\r\n" \
598
                "a=rtcp-fb:%d ccm fir\r\n"                        /* H264 payload type */ \
599
                "a=rtcp-fb:%d nack\r\n"                                /* H264 payload type */ \
600
                "a=rtcp-fb:%d nack pli\r\n"                        /* H264 payload type */ \
601
                "a=rtcp-fb:%d goog-remb\r\n"                /* H264 payload type */ \
602
                "%s"                                                                /* extmap(s), if any */
603
#ifdef HAVE_SCTP
604
#define sdp_d_template \
605
                "m=application 1 DTLS/SCTP 5000\r\n" \
606
                "c=IN IP4 1.1.1.1\r\n" \
607
                "a=sctpmap:5000 webrtc-datachannel 16\r\n"
608
#else
609
#define sdp_d_template \
610
                "m=application 0 DTLS/SCTP 0\r\n" \
611
                "c=IN IP4 1.1.1.1\r\n"
612
#endif
613

    
614

    
615
/* Error codes */
616
#define JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR                499
617
#define JANUS_VIDEOROOM_ERROR_NO_MESSAGE                421
618
#define JANUS_VIDEOROOM_ERROR_INVALID_JSON                422
619
#define JANUS_VIDEOROOM_ERROR_INVALID_REQUEST        423
620
#define JANUS_VIDEOROOM_ERROR_JOIN_FIRST                424
621
#define JANUS_VIDEOROOM_ERROR_ALREADY_JOINED        425
622
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM                426
623
#define JANUS_VIDEOROOM_ERROR_ROOM_EXISTS                427
624
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED                428
625
#define JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT        429
626
#define JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT        430
627
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE        431
628
#define JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL        432
629
#define JANUS_VIDEOROOM_ERROR_UNAUTHORIZED                433
630
#define JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED        434
631
#define JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED                435
632
#define JANUS_VIDEOROOM_ERROR_ID_EXISTS                        436
633
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP                437
634

    
635

    
636
/* Multiplexing helpers */
637
int janus_videoroom_muxed_subscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
638
int janus_videoroom_muxed_unsubscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
639
int janus_videoroom_muxed_offer(janus_videoroom_listener_muxed *muxed_listener, char *transaction, json_t *event);
640

    
641
static guint32 janus_videoroom_rtp_forwarder_add_helper(janus_videoroom_participant *p, const gchar* host, int port, int pt, uint32_t ssrc, gboolean is_video) {
642
        if(!p || !host) {
643
                return 0;
644
        }
645
        janus_videoroom_rtp_forwarder *forward = g_malloc0(sizeof(janus_videoroom_rtp_forwarder));
646
        forward->is_video = is_video;
647
        forward->payload_type = pt;
648
        forward->ssrc = ssrc;
649
        forward->serv_addr.sin_family = AF_INET;
650
        inet_pton(AF_INET, host, &(forward->serv_addr.sin_addr));
651
        forward->serv_addr.sin_port = htons(port);
652
        janus_mutex_lock(&p->rtp_forwarders_mutex);
653
        guint32 stream_id = janus_random_uint32();
654
        while(g_hash_table_lookup(p->rtp_forwarders, GUINT_TO_POINTER(stream_id)) != NULL) {
655
                stream_id = janus_random_uint32();
656
        }
657
        g_hash_table_insert(p->rtp_forwarders, GUINT_TO_POINTER(stream_id), forward);
658
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
659
        JANUS_LOG(LOG_VERB, "Added %s rtp_forward to participant %"SCNu64" host: %s:%d stream_id: %"SCNu32"\n", is_video ? "video":"audio", p->user_id, host, port, stream_id);
660
        return stream_id;
661
}
662

    
663

    
664
/* Convenience function for freeing a session */
665
static void session_free(gpointer data) {
666
        if(data) {
667
                janus_videoroom_session* session = (janus_videoroom_session*)data;
668
                switch(session->participant_type) {
669
                case janus_videoroom_p_type_publisher: 
670
                        janus_videoroom_participant_free(session->participant);
671
                        break;   
672
                case janus_videoroom_p_type_subscriber:
673
                        janus_videoroom_listener_free(session->participant);
674
                        break;
675
                case janus_videoroom_p_type_subscriber_muxed:
676
                        janus_videoroom_muxed_listener_free(session->participant);
677
                        break;
678
                default:
679
                        break;
680
                }
681
                session->handle = NULL;
682
                g_free(session);
683
                session = NULL;
684
        }
685
}
686

    
687
static void janus_videoroom_rtp_forwarder_free_helper(gpointer data) {
688
        if(data) {
689
                janus_videoroom_rtp_forwarder* forward = (janus_videoroom_rtp_forwarder*)data;
690
                if(forward) {
691
                        g_free(forward);
692
                        forward = NULL;
693
                }
694
        }
695
}
696

    
697
/* Convenience wrapper function for session_free that corresponds to GHRFunc() format for hash table cleanup */
698
static gboolean session_hash_table_remove(gpointer key, gpointer value, gpointer not_used) {
699
        if(value) {
700
                session_free(value);
701
        }
702
        return TRUE;
703
}
704

    
705
/* VideoRoom watchdog/garbage collector (sort of) */
706
void *janus_videoroom_watchdog(void *data);
707
void *janus_videoroom_watchdog(void *data) {
708
        JANUS_LOG(LOG_INFO, "VideoRoom watchdog started\n");
709
        gint64 now = 0, room_now = 0;
710
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
711
                janus_mutex_lock(&sessions_mutex);
712
                /* Iterate on all the participants/listeners and check if we need to remove any of them */
713
                now = janus_get_monotonic_time();
714
                if(old_sessions != NULL) {
715
                        GList *sl = old_sessions;
716
                        JANUS_LOG(LOG_HUGE, "Checking %d old VideoRoom sessions...\n", g_list_length(old_sessions));
717
                        while(sl) {
718
                                janus_videoroom_session *session = (janus_videoroom_session *)sl->data;
719
                                /* If we are stopping, their is no point to continue to iterate */
720
                                if(!initialized || stopping) {
721
                                        break;
722
                                }
723
                                if(!session) {
724
                                        sl = sl->next;
725
                                        continue;
726
                                }
727
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
728
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
729
                                        JANUS_LOG(LOG_VERB, "Freeing old VideoRoom session\n");
730
                                        GList *rm = sl->next;
731
                                        old_sessions = g_list_delete_link(old_sessions, sl);
732
                                        sl = rm;
733
                                        g_hash_table_steal(sessions, session->handle);
734
                                        session_free(session);
735
                                        continue;
736
                                }
737
                                sl = sl->next;
738
                        }
739
                }
740
                janus_mutex_unlock(&sessions_mutex);
741
                janus_mutex_lock(&rooms_mutex);
742
                if(old_rooms != NULL) {
743
                        GList *rl = old_rooms;
744
                        room_now = janus_get_monotonic_time();
745
                        while(rl) {
746
                                janus_videoroom* room = (janus_videoroom*)rl->data;
747
                                if(!initialized || stopping){
748
                                        break;
749
                                }
750
                                if(!room) {
751
                                        rl = rl->next;
752
                                        continue;
753
                                }
754
                                if(room_now - room->destroyed >= 5*G_USEC_PER_SEC) {
755
                                        GList *rm = rl->next;
756
                                        old_rooms = g_list_delete_link(old_rooms, rl);
757
                                        rl = rm;
758
                                        g_hash_table_remove(rooms, &room->room_id);
759
                                        continue;
760
                                }
761
                                rl = rl->next;
762
                        }
763
                }
764
                janus_mutex_unlock(&rooms_mutex);
765
                g_usleep(500000);
766
        }
767
        JANUS_LOG(LOG_INFO, "VideoRoom watchdog stopped\n");
768
        return NULL;
769
}
770

    
771

    
772
/* Plugin implementation */
773
int janus_videoroom_init(janus_callbacks *callback, const char *config_path) {
774
        if(g_atomic_int_get(&stopping)) {
775
                /* Still stopping from before */
776
                return -1;
777
        }
778
        if(callback == NULL || config_path == NULL) {
779
                /* Invalid arguments */
780
                return -1;
781
        }
782

    
783
        /* Read configuration */
784
        char filename[255];
785
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_VIDEOROOM_PACKAGE);
786
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
787
        config = janus_config_parse(filename);
788
        config_folder = config_path;
789
        if(config != NULL)
790
                janus_config_print(config);
791
        janus_mutex_init(&config_mutex);
792

    
793
        rooms = g_hash_table_new_full(g_int64_hash, g_int64_equal,
794
                (GDestroyNotify)g_free, (GDestroyNotify) janus_videoroom_free);
795
        janus_mutex_init(&rooms_mutex);
796
        sessions = g_hash_table_new(NULL, NULL);
797
        janus_mutex_init(&sessions_mutex);
798

    
799
        messages = g_async_queue_new_full((GDestroyNotify) janus_videoroom_message_free);
800

    
801
        /* This is the callback we'll need to invoke to contact the gateway */
802
        gateway = callback;
803

    
804
        /* Parse configuration to populate the rooms list */
805
        if(config != NULL) {
806
                /* Any admin key to limit who can "create"? */
807
                janus_config_item *key = janus_config_get_item_drilldown(config, "general", "admin_key");
808
                if(key != NULL && key->value != NULL)
809
                        admin_key = g_strdup(key->value);
810
                janus_config_item *events = janus_config_get_item_drilldown(config, "general", "events");
811
                if(events != NULL && events->value != NULL)
812
                        notify_events = janus_is_true(events->value);
813
                if(!notify_events && callback->events_is_enabled()) {
814
                        JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_VIDEOROOM_NAME);
815
                }
816
                /* Iterate on all rooms */
817
                GList *cl = janus_config_get_categories(config);
818
                while(cl != NULL) {
819
                        janus_config_category *cat = (janus_config_category *)cl->data;
820
                        if(cat->name == NULL || !strcasecmp(cat->name, "general")) {
821
                                cl = cl->next;
822
                                continue;
823
                        }
824
                        JANUS_LOG(LOG_VERB, "Adding video room '%s'\n", cat->name);
825
                        janus_config_item *desc = janus_config_get_item(cat, "description");
826
                        janus_config_item *priv = janus_config_get_item(cat, "is_private");
827
                        janus_config_item *secret = janus_config_get_item(cat, "secret");
828
                        janus_config_item *pin = janus_config_get_item(cat, "pin");
829
                        janus_config_item *bitrate = janus_config_get_item(cat, "bitrate");
830
                        janus_config_item *maxp = janus_config_get_item(cat, "publishers");
831
                        janus_config_item *firfreq = janus_config_get_item(cat, "fir_freq");
832
                        janus_config_item *audiocodec = janus_config_get_item(cat, "audiocodec");
833
                        janus_config_item *videocodec = janus_config_get_item(cat, "videocodec");
834
                        janus_config_item *audiolevel_ext = janus_config_get_item(cat, "audiolevel_ext");
835
                        janus_config_item *videoorient_ext = janus_config_get_item(cat, "videoorient_ext");
836
                        janus_config_item *playoutdelay_ext = janus_config_get_item(cat, "playoutdelay_ext");
837
                        janus_config_item *record = janus_config_get_item(cat, "record");
838
                        janus_config_item *rec_dir = janus_config_get_item(cat, "rec_dir");
839
                        /* Create the video room */
840
                        janus_videoroom *videoroom = g_malloc0(sizeof(janus_videoroom));
841
                        videoroom->room_id = g_ascii_strtoull(cat->name, NULL, 0);
842
                        char *description = NULL;
843
                        if(desc != NULL && desc->value != NULL && strlen(desc->value) > 0)
844
                                description = g_strdup(desc->value);
845
                        else
846
                                description = g_strdup(cat->name);
847
                        videoroom->room_name = description;
848
                        if(secret != NULL && secret->value != NULL) {
849
                                videoroom->room_secret = g_strdup(secret->value);
850
                        }
851
                        if(pin != NULL && pin->value != NULL) {
852
                                videoroom->room_pin = g_strdup(pin->value);
853
                        }
854
                        videoroom->is_private = priv && priv->value && janus_is_true(priv->value);
855
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
856
                        if(maxp != NULL && maxp->value != NULL)
857
                                videoroom->max_publishers = atol(maxp->value);
858
                        if(videoroom->max_publishers < 0)
859
                                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
860
                        videoroom->bitrate = 0;
861
                        if(bitrate != NULL && bitrate->value != NULL)
862
                                videoroom->bitrate = atol(bitrate->value);
863
                        if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
864
                                videoroom->bitrate = 64000;        /* Don't go below 64k */
865
                        videoroom->fir_freq = 0;
866
                        if(firfreq != NULL && firfreq->value != NULL)
867
                                videoroom->fir_freq = atol(firfreq->value);
868
                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
869
                        if(audiocodec && audiocodec->value) {
870
                                if(!strcasecmp(audiocodec->value, "opus"))
871
                                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
872
                                else if(!strcasecmp(audiocodec->value, "isac32"))
873
                                        videoroom->acodec = JANUS_VIDEOROOM_ISAC_32K;
874
                                else if(!strcasecmp(audiocodec->value, "isac16"))
875
                                        videoroom->acodec = JANUS_VIDEOROOM_ISAC_16K;
876
                                else if(!strcasecmp(audiocodec->value, "pcmu"))
877
                                        videoroom->acodec = JANUS_VIDEOROOM_PCMU;
878
                                else if(!strcasecmp(audiocodec->value, "pcma"))
879
                                        videoroom->acodec = JANUS_VIDEOROOM_PCMA;
880
                                else {
881
                                        JANUS_LOG(LOG_WARN, "Unsupported audio codec '%s', falling back to OPUS\n", audiocodec->value);
882
                                        videoroom->acodec = JANUS_VIDEOROOM_OPUS;
883
                                }
884
                        }
885
                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
886
                        if(videocodec && videocodec->value) {
887
                                if(!strcasecmp(videocodec->value, "vp8"))
888
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
889
                                else if(!strcasecmp(videocodec->value, "vp9"))
890
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP9;
891
                                else if(!strcasecmp(videocodec->value, "h264"))
892
                                        videoroom->vcodec = JANUS_VIDEOROOM_H264;
893
                                else {
894
                                        JANUS_LOG(LOG_WARN, "Unsupported video codec '%s', falling back to VP8\n", videocodec->value);
895
                                        videoroom->vcodec = JANUS_VIDEOROOM_VP8;
896
                                }
897
                        }
898
                        videoroom->audiolevel_ext = TRUE;
899
                        if(audiolevel_ext != NULL && audiolevel_ext->value != NULL)
900
                                videoroom->audiolevel_ext = janus_is_true(audiolevel_ext->value);
901
                        videoroom->videoorient_ext = TRUE;
902
                        if(videoorient_ext != NULL && videoorient_ext->value != NULL)
903
                                videoroom->videoorient_ext = janus_is_true(videoorient_ext->value);
904
                        videoroom->playoutdelay_ext = TRUE;
905
                        if(playoutdelay_ext != NULL && playoutdelay_ext->value != NULL)
906
                                videoroom->playoutdelay_ext = janus_is_true(playoutdelay_ext->value);
907
                        if(record && record->value) {
908
                                videoroom->record = janus_is_true(record->value);
909
                        }
910
                        if(rec_dir && rec_dir->value) {
911
                                videoroom->rec_dir = g_strdup(rec_dir->value);
912
                        }
913
                        videoroom->destroyed = 0;
914
                        janus_mutex_init(&videoroom->participants_mutex);
915
                        videoroom->participants = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
916
                        videoroom->private_ids = g_hash_table_new(NULL, NULL);
917
                        videoroom->check_tokens = FALSE;        /* Static rooms can't have an "allowed" list yet, no hooks to the configuration file */
918
                        videoroom->allowed = g_hash_table_new_full(g_str_hash, g_str_equal, (GDestroyNotify)g_free, NULL);
919
                        janus_mutex_lock(&rooms_mutex);
920
                        g_hash_table_insert(rooms, janus_uint64_dup(videoroom->room_id), videoroom);
921
                        janus_mutex_unlock(&rooms_mutex);
922
                        JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, %s/%s codecs, secret: %s, pin: %s)\n",
923
                                videoroom->room_id, videoroom->room_name,
924
                                videoroom->is_private ? "private" : "public",
925
                                janus_videoroom_audiocodec_name(videoroom->acodec),
926
                                janus_videoroom_videocodec_name(videoroom->vcodec),
927
                                videoroom->room_secret ? videoroom->room_secret : "no secret",
928
                                videoroom->room_pin ? videoroom->room_pin : "no pin");
929
                        if(videoroom->record) {
930
                                JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
931
                        }
932
                        cl = cl->next;
933
                }
934
                /* Done: we keep the configuration file open in case we get a "create" or "destroy" with permanent=true */
935
        }
936

    
937
        /* Show available rooms */
938
        janus_mutex_lock(&rooms_mutex);
939
        GHashTableIter iter;
940
        gpointer value;
941
        g_hash_table_iter_init(&iter, rooms);
942
        while (g_hash_table_iter_next(&iter, NULL, &value)) {
943
                janus_videoroom *vr = value;
944
                JANUS_LOG(LOG_VERB, "  ::: [%"SCNu64"][%s] %"SCNu64", max %d publishers, FIR frequency of %d seconds, %s audio codec, %s video codec\n",
945
                        vr->room_id, vr->room_name, vr->bitrate, vr->max_publishers, vr->fir_freq,
946
                        janus_videoroom_audiocodec_name(vr->acodec), janus_videoroom_videocodec_name(vr->vcodec));
947
        }
948
        janus_mutex_unlock(&rooms_mutex);
949

    
950
        g_atomic_int_set(&initialized, 1);
951

    
952
        GError *error = NULL;
953
        /* Start the sessions watchdog */
954
        watchdog = g_thread_try_new("videoroom watchdog", &janus_videoroom_watchdog, NULL, &error);
955
        if(error != NULL) {
956
                g_atomic_int_set(&initialized, 0);
957
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom watchdog thread...\n", error->code, error->message ? error->message : "??");
958
                janus_config_destroy(config);
959
                return -1;
960
        }
961
        /* Launch the thread that will handle incoming messages */
962
        handler_thread = g_thread_try_new("videoroom handler", janus_videoroom_handler, NULL, &error);
963
        if(error != NULL) {
964
                g_atomic_int_set(&initialized, 0);
965
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom handler thread...\n", error->code, error->message ? error->message : "??");
966
                janus_config_destroy(config);
967
                return -1;
968
        }
969
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_VIDEOROOM_NAME);
970
        return 0;
971
}
972

    
973
void janus_videoroom_destroy(void) {
974
        if(!g_atomic_int_get(&initialized))
975
                return;
976
        g_atomic_int_set(&stopping, 1);
977

    
978
        g_async_queue_push(messages, &exit_message);
979
        if(handler_thread != NULL) {
980
                g_thread_join(handler_thread);
981
                handler_thread = NULL;
982
        }
983
        if(watchdog != NULL) {
984
                g_thread_join(watchdog);
985
                watchdog = NULL;
986
        }
987

    
988
        /* FIXME We should destroy the sessions cleanly */
989
        janus_mutex_lock(&sessions_mutex);
990
        g_hash_table_foreach_remove(sessions, (GHRFunc)session_hash_table_remove, NULL);
991
        g_hash_table_destroy(sessions);
992
        sessions = NULL;
993
        janus_mutex_unlock(&sessions_mutex);
994

    
995
        janus_mutex_lock(&rooms_mutex);
996
        g_hash_table_destroy(rooms);
997
        rooms = NULL;
998
        janus_mutex_unlock(&rooms_mutex);
999
        janus_mutex_destroy(&rooms_mutex);
1000

    
1001
        g_async_queue_unref(messages);
1002
        messages = NULL;
1003

    
1004
        janus_config_destroy(config);
1005
        g_free(admin_key);
1006

    
1007
        g_atomic_int_set(&initialized, 0);
1008
        g_atomic_int_set(&stopping, 0);
1009
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOROOM_NAME);
1010
}
1011

    
1012
int janus_videoroom_get_api_compatibility(void) {
1013
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
1014
        return JANUS_PLUGIN_API_VERSION;
1015
}
1016

    
1017
int janus_videoroom_get_version(void) {
1018
        return JANUS_VIDEOROOM_VERSION;
1019
}
1020

    
1021
const char *janus_videoroom_get_version_string(void) {
1022
        return JANUS_VIDEOROOM_VERSION_STRING;
1023
}
1024

    
1025
const char *janus_videoroom_get_description(void) {
1026
        return JANUS_VIDEOROOM_DESCRIPTION;
1027
}
1028

    
1029
const char *janus_videoroom_get_name(void) {
1030
        return JANUS_VIDEOROOM_NAME;
1031
}
1032

    
1033
const char *janus_videoroom_get_author(void) {
1034
        return JANUS_VIDEOROOM_AUTHOR;
1035
}
1036

    
1037
const char *janus_videoroom_get_package(void) {
1038
        return JANUS_VIDEOROOM_PACKAGE;
1039
}
1040

    
1041
void janus_videoroom_create_session(janus_plugin_session *handle, int *error) {
1042
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1043
                *error = -1;
1044
                return;
1045
        }        
1046
        janus_videoroom_session *session = (janus_videoroom_session *)g_malloc0(sizeof(janus_videoroom_session));
1047
        session->handle = handle;
1048
        session->participant_type = janus_videoroom_p_type_none;
1049
        session->participant = NULL;
1050
        session->destroyed = 0;
1051
        g_atomic_int_set(&session->hangingup, 0);
1052
        handle->plugin_handle = session;
1053
        janus_mutex_lock(&sessions_mutex);
1054
        g_hash_table_insert(sessions, handle, session);
1055
        janus_mutex_unlock(&sessions_mutex);
1056

    
1057
        return;
1058
}
1059

    
1060
static void janus_videoroom_notify_participants(janus_videoroom_participant *participant, json_t *msg) {
1061
        /* participant->room->participants_mutex has to be locked. */
1062
        GHashTableIter iter;
1063
        gpointer value;
1064
        g_hash_table_iter_init(&iter, participant->room->participants);
1065
        while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1066
                janus_videoroom_participant *p = value;
1067
                if(p && p->session && p != participant) {
1068
                        JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1069
                        int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, msg, NULL);
1070
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1071
                }
1072
        }
1073
}
1074

    
1075
static void janus_videoroom_leave_or_unpublish(janus_videoroom_participant *participant, gboolean is_leaving) {
1076
        /* we need to check if the room still exists, may have been destroyed already */
1077
        if(participant->room && !participant->room->destroyed) {
1078
                json_t *event = json_object();
1079
                json_object_set_new(event, "videoroom", json_string("event"));
1080
                json_object_set_new(event, "room", json_integer(participant->room->room_id));
1081
                json_object_set_new(event, is_leaving ? "leaving" : "unpublished", json_integer(participant->user_id));
1082
                janus_mutex_lock(&participant->room->participants_mutex);
1083
                janus_videoroom_notify_participants(participant, event);
1084
                if(is_leaving) {
1085
                        g_hash_table_remove(participant->room->participants, &participant->user_id);
1086
                        g_hash_table_remove(participant->room->private_ids, GUINT_TO_POINTER(participant->pvt_id));
1087
                }
1088
                janus_mutex_unlock(&participant->room->participants_mutex);
1089
                json_decref(event);
1090
        }
1091
}
1092

    
1093
void janus_videoroom_destroy_session(janus_plugin_session *handle, int *error) {
1094
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1095
                *error = -1;
1096
                return;
1097
        }        
1098
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle; 
1099
        if(!session) {
1100
                JANUS_LOG(LOG_ERR, "No VideoRoom session associated with this handle...\n");
1101
                *error = -2;
1102
                return;
1103
        }
1104
        if(session->destroyed) {
1105
                JANUS_LOG(LOG_WARN, "VideoRoom session already marked as destroyed...\n");
1106
                return;
1107
        }
1108
        JANUS_LOG(LOG_VERB, "Removing VideoRoom session...\n");
1109
        /* Cleaning up and removing the session is done in a lazy way */
1110
        janus_mutex_lock(&sessions_mutex);
1111
        if(!session->destroyed) {
1112
                /* Any related WebRTC PeerConnection is not available anymore either */
1113
                janus_videoroom_hangup_media(handle);
1114
                session->destroyed = janus_get_monotonic_time();
1115
                old_sessions = g_list_append(old_sessions, session);
1116
                if(session->participant_type == janus_videoroom_p_type_publisher) {
1117
                        /* Get rid of publisher */
1118
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1119
                        participant->audio = FALSE;
1120
                        participant->video = FALSE;
1121
                        participant->data = FALSE;
1122
                        participant->audio_active = FALSE;
1123
                        participant->video_active = FALSE;
1124
                        participant->recording_active = FALSE;
1125
                        if(participant->recording_base)
1126
                                g_free(participant->recording_base);
1127
                        participant->recording_base = NULL;
1128
                        janus_videoroom_leave_or_unpublish(participant, TRUE);
1129
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1130
                        /* Detaching this listener from its publisher is already done by hangup_media */
1131
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1132
                        /* Detaching this listener from its publishers is already done by hangup_media */
1133
                }
1134
        }
1135
        janus_mutex_unlock(&sessions_mutex);
1136

    
1137
        return;
1138
}
1139

    
1140
json_t *janus_videoroom_query_session(janus_plugin_session *handle) {
1141
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1142
                return NULL;
1143
        }        
1144
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1145
        if(!session) {
1146
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1147
                return NULL;
1148
        }
1149
        /* Show the participant/room info, if any */
1150
        json_t *info = json_object();
1151
        if(session->participant) {
1152
                if(session->participant_type == janus_videoroom_p_type_none) {
1153
                        json_object_set_new(info, "type", json_string("none"));
1154
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
1155
                        json_object_set_new(info, "type", json_string("publisher"));
1156
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1157
                        if(participant) {
1158
                                janus_videoroom *room = participant->room; 
1159
                                json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
1160
                                json_object_set_new(info, "id", json_integer(participant->user_id));
1161
                                json_object_set_new(info, "private_id", json_integer(participant->pvt_id));
1162
                                if(participant->display)
1163
                                        json_object_set_new(info, "display", json_string(participant->display));
1164
                                if(participant->listeners)
1165
                                        json_object_set_new(info, "viewers", json_integer(g_slist_length(participant->listeners)));
1166
                                json_t *media = json_object();
1167
                                json_object_set_new(media, "audio", json_integer(participant->audio));
1168
                                json_object_set_new(media, "video", json_integer(participant->video));
1169
                                json_object_set_new(media, "data", json_integer(participant->data));
1170
                                json_object_set_new(info, "media", media);
1171
                                json_object_set_new(info, "bitrate", json_integer(participant->bitrate));
1172
                                if(participant->arc || participant->vrc) {
1173
                                        json_t *recording = json_object();
1174
                                        if(participant->arc && participant->arc->filename)
1175
                                                json_object_set_new(recording, "audio", json_string(participant->arc->filename));
1176
                                        if(participant->vrc && participant->vrc->filename)
1177
                                                json_object_set_new(recording, "video", json_string(participant->vrc->filename));
1178
                                        json_object_set_new(info, "recording", recording);
1179
                                }
1180
                        }
1181
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1182
                        json_object_set_new(info, "type", json_string("listener"));
1183
                        janus_videoroom_listener *participant = (janus_videoroom_listener *)session->participant;
1184
                        if(participant) {
1185
                                janus_videoroom_participant *feed = (janus_videoroom_participant *)participant->feed;
1186
                                if(feed) {
1187
                                        janus_videoroom *room = feed->room; 
1188
                                        json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
1189
                                        json_object_set_new(info, "private_id", json_integer(participant->pvt_id));
1190
                                        json_object_set_new(info, "feed_id", json_integer(feed->user_id));
1191
                                        if(feed->display)
1192
                                                json_object_set_new(info, "feed_display", json_string(feed->display));
1193
                                }
1194
                                json_t *media = json_object();
1195
                                json_object_set_new(media, "audio", json_integer(participant->audio));
1196
                                json_object_set_new(media, "video", json_integer(participant->video));
1197
                                json_object_set_new(media, "data", json_integer(participant->data));
1198
                                json_object_set_new(info, "media", media);
1199
                        }
1200
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1201
                        json_object_set_new(info, "type", json_string("muxed-listener"));
1202
                        /* TODO */
1203
                }
1204
        }
1205
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
1206
        return info;
1207
}
1208

    
1209
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) {
1210
        /* rooms_mutex has to be locked */
1211
        int error_code = 0;
1212
        json_t *room = json_object_get(root, "room");
1213
        guint64 room_id = json_integer_value(room);
1214
        *videoroom = g_hash_table_lookup(rooms, &room_id);
1215
        if(*videoroom == NULL) {
1216
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1217
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1218
                if(error_cause)
1219
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1220
                return error_code;
1221
        }
1222
        if((*videoroom)->destroyed) {
1223
                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1224
                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1225
                if(error_cause)
1226
                        g_snprintf(error_cause, error_cause_size, "No such room (%"SCNu64")", room_id);
1227
                return error_code;
1228
        }
1229
        if(check_secret) {
1230
                char error_cause2[100];
1231
                JANUS_CHECK_SECRET((*videoroom)->room_secret, root, "secret", error_code, error_cause2,
1232
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1233
                if(error_code != 0) {
1234
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1235
                        return error_code;
1236
                }
1237
        }
1238
        if(check_pin) {
1239
                char error_cause2[100];
1240
                JANUS_CHECK_SECRET((*videoroom)->room_pin, root, "pin", error_code, error_cause2,
1241
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT, JANUS_VIDEOROOM_ERROR_UNAUTHORIZED);
1242
                if(error_code != 0) {
1243
                        g_strlcpy(error_cause, error_cause2, error_cause_size);
1244
                        return error_code;
1245
                }
1246
        }
1247
        return 0;
1248
}
1249

    
1250
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1251
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1252
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1253
        
1254
        /* Pre-parse the message */
1255
        int error_code = 0;
1256
        char error_cause[512];
1257
        json_t *root = message;
1258
        json_t *response = NULL;
1259

    
1260
        if(message == NULL) {
1261
                JANUS_LOG(LOG_ERR, "No message??\n");
1262
                error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
1263
                g_snprintf(error_cause, 512, "%s", "No message??");
1264
                goto plugin_response;
1265
        }
1266

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

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

    
2114
                janus_videoroom_message *msg = g_malloc0(sizeof(janus_videoroom_message));
2115
                msg->handle = handle;
2116
                msg->transaction = transaction;
2117
                msg->message = root;
2118
                msg->jsep = jsep;
2119
                g_async_queue_push(messages, msg);
2120

    
2121
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
2122
        } else {
2123
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
2124
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
2125
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
2126
        }
2127

    
2128
plugin_response:
2129
                {
2130
                        if(error_code == 0 && !response) {
2131
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2132
                                g_snprintf(error_cause, 512, "Invalid response");
2133
                        }
2134
                        if(error_code != 0) {
2135
                                /* Prepare JSON error event */
2136
                                json_t *event = json_object();
2137
                                json_object_set_new(event, "videoroom", json_string("event"));
2138
                                json_object_set_new(event, "error_code", json_integer(error_code));
2139
                                json_object_set_new(event, "error", json_string(error_cause));
2140
                                response = event;
2141
                        }
2142
                        if(root != NULL)
2143
                                json_decref(root);
2144
                        if(jsep != NULL)
2145
                                json_decref(jsep);
2146
                        g_free(transaction);
2147

    
2148
                        return janus_plugin_result_new(JANUS_PLUGIN_OK, NULL, response);
2149
                }
2150

    
2151
}
2152

    
2153
void janus_videoroom_setup_media(janus_plugin_session *handle) {
2154
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
2155
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2156
                return;
2157
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2158
        if(!session) {
2159
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2160
                return;
2161
        }
2162
        if(session->destroyed)
2163
                return;
2164
        g_atomic_int_set(&session->hangingup, 0);
2165

    
2166
        /* Media relaying can start now */
2167
        session->started = TRUE;
2168

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

    
2265
void janus_videoroom_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
2266
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2267
                return;
2268
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2269
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2270
                return;
2271
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2272
        if(participant->audio_level_extmap_id > 0 && participant->audio_active) {
2273
                int level = 0;
2274
                int audio_level = janus_rtp_header_extension_parse_audio_level_and_return(buf, len, participant->audio_level_extmap_id, &level);
2275
                participant->audio_dBov_sum = participant->audio_dBov_sum + audio_level;
2276
                participant->audio_active_packets = participant->audio_active_packets + 1;
2277
                if(participant->audio_active_packets == 150) {
2278
                        if(participant->audio_dBov_sum < 3000) {
2279
                                // Notify participants
2280
                                json_t *event = json_object();
2281
                                json_object_set_new(event, "event", json_string("talking"));
2282
                                json_object_set_new(event, "user", json_string(participant->display));
2283
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2284
                                json_decref(event);
2285
                                JANUS_LOG(LOG_ERR, "AVG audio_level %f\n", (float)participant->audio_dBov_sum/(float)participant->audio_active_packets);
2286
                        }
2287
                        participant->audio_active_packets = 0;
2288
                        participant->audio_dBov_sum = 0;
2289
                }
2290
        }
2291
        if((!video && participant->audio_active) || (video && participant->video_active)) {
2292
                /* Update payload type and SSRC */
2293
                janus_mutex_lock(&participant->rtp_forwarders_mutex);
2294
                rtp_header *rtp = (rtp_header *)buf;
2295
                rtp->type = video ? participant->video_pt : participant->audio_pt;
2296
                rtp->ssrc = htonl(video ? participant->video_ssrc : participant->audio_ssrc);
2297
                /* Forward RTP to the appropriate port for the rtp_forwarders associated with this publisher, if there are any */
2298
                GHashTableIter iter;
2299
                gpointer value;
2300
                g_hash_table_iter_init(&iter, participant->rtp_forwarders);
2301
                while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
2302
                        janus_videoroom_rtp_forwarder* rtp_forward = (janus_videoroom_rtp_forwarder*)value;
2303
                        /* Check if payload type and/or SSRC need to be overwritten for this forwarder */
2304
                        int pt = rtp->type;
2305
                        uint32_t ssrc = ntohl(rtp->ssrc);
2306
                        if(rtp_forward->payload_type > 0)
2307
                                rtp->type = rtp_forward->payload_type;
2308
                        if(rtp_forward->ssrc > 0)
2309
                                rtp->ssrc = htonl(rtp_forward->ssrc);
2310
                        if(video && rtp_forward->is_video) {
2311
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2312
                        }
2313
                        else if(!video && !rtp_forward->is_video) {
2314
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
2315
                        }
2316
                        /* Restore original values of payload type and SSRC before going on */
2317
                        rtp->type = pt;
2318
                        rtp->ssrc = htonl(ssrc);
2319
                }
2320
                janus_mutex_unlock(&participant->rtp_forwarders_mutex);
2321
                /* Save the frame if we're recording */
2322
                janus_recorder_save_frame(video ? participant->vrc : participant->arc, buf, len);
2323
                /* Done, relay it */
2324
                janus_videoroom_rtp_relay_packet packet;
2325
                packet.data = rtp;
2326
                packet.length = len;
2327
                packet.is_video = video;
2328
                /* Backup the actual timestamp and sequence number set by the publisher, in case switching is involved */
2329
                packet.timestamp = ntohl(packet.data->timestamp);
2330
                packet.seq_number = ntohs(packet.data->seq_number);
2331
                /* Go */
2332
                g_slist_foreach(participant->listeners, janus_videoroom_relay_rtp_packet, &packet);
2333
                
2334
                /* Check if we need to send any REMB, FIR or PLI back to this publisher */
2335
                if(video && participant->video_active) {
2336
                        /* Did we send a REMB already, or is it time to send one? */
2337
                        gboolean send_remb = FALSE;
2338
                        if(participant->remb_latest == 0 && participant->remb_startup > 0) {
2339
                                /* Still in the starting phase, send the ramp-up REMB feedback */
2340
                                send_remb = TRUE;
2341
                        } else if(participant->remb_latest > 0 && janus_get_monotonic_time()-participant->remb_latest >= 5*G_USEC_PER_SEC) {
2342
                                /* 5 seconds have passed since the last REMB, send a new one */
2343
                                send_remb = TRUE;
2344
                        }                
2345
                        if(send_remb) {
2346
                                /* We send a few incremental REMB messages at startup */
2347
                                uint64_t bitrate = (participant->bitrate ? participant->bitrate : 256*1024);
2348
                                if(participant->remb_startup > 0) {
2349
                                        bitrate = bitrate/participant->remb_startup;
2350
                                        participant->remb_startup--;
2351
                                }
2352
                                JANUS_LOG(LOG_VERB, "Sending REMB (%s, %"SCNu64")\n", participant->display, bitrate);
2353
                                char rtcpbuf[24];
2354
                                janus_rtcp_remb((char *)(&rtcpbuf), 24, bitrate);
2355
                                gateway->relay_rtcp(handle, video, rtcpbuf, 24);
2356
                                if(participant->remb_startup == 0)
2357
                                        participant->remb_latest = janus_get_monotonic_time();
2358
                        }
2359
                        /* Generate FIR/PLI too, if needed */
2360
                        if(video && participant->video_active && (participant->room->fir_freq > 0)) {
2361
                                /* FIXME Very ugly hack to generate RTCP every tot seconds/frames */
2362
                                gint64 now = janus_get_monotonic_time();
2363
                                if((now-participant->fir_latest) >= (participant->room->fir_freq*G_USEC_PER_SEC)) {
2364
                                        /* FIXME We send a FIR every tot seconds */
2365
                                        participant->fir_latest = now;
2366
                                        char rtcpbuf[24];
2367
                                        memset(rtcpbuf, 0, 24);
2368
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &participant->fir_seq);
2369
                                        JANUS_LOG(LOG_VERB, "Sending FIR to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2370
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 20);
2371
                                        /* Send a PLI too, just in case... */
2372
                                        memset(rtcpbuf, 0, 12);
2373
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
2374
                                        JANUS_LOG(LOG_VERB, "Sending PLI to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
2375
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 12);
2376
                                }
2377
                        }
2378
                }
2379
        }
2380
}
2381

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

    
2430
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len) {
2431
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2432
                return;
2433
        if(buf == NULL || len <= 0)
2434
                return;
2435
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2436
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2437
                return;
2438
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2439
        /* Get a string out of the data */
2440
        char *text = g_malloc0(len+1);
2441
        memcpy(text, buf, len);
2442
        *(text+len) = '\0';
2443
        JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
2444
        g_slist_foreach(participant->listeners, janus_videoroom_relay_data_packet, text);
2445
        g_free(text);
2446
}
2447

    
2448
void janus_videoroom_slow_link(janus_plugin_session *handle, int uplink, int video) {
2449
        /* The core is informing us that our peer got too many NACKs, are we pushing media too hard? */
2450
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2451
                return;
2452
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2453
        if(!session || session->destroyed || !session->participant)
2454
                return;
2455
        /* Check if it's an uplink (publisher) or downlink (viewer) issue */
2456
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2457
                if(!uplink) {
2458
                        janus_videoroom_participant *publisher = (janus_videoroom_participant *)session->participant;
2459
                        if(publisher) {
2460
                                /* Send an event on the handle to notify the application: it's
2461
                                 * up to the application to then choose a policy and enforce it */
2462
                                json_t *event = json_object();
2463
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2464
                                /* Also add info on what the current bitrate cap is */
2465
                                uint64_t bitrate = (publisher->bitrate ? publisher->bitrate : 256*1024);
2466
                                json_object_set_new(event, "current-bitrate", json_integer(bitrate));
2467
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2468
                                json_decref(event);
2469
                        }
2470
                } else {
2471
                        JANUS_LOG(LOG_WARN, "Got a slow uplink on a VideoRoom publisher? Weird, because it doesn't receive media...\n");
2472
                }
2473
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2474
                if(uplink) {
2475
                        janus_videoroom_listener *viewer = (janus_videoroom_listener *)session->participant;
2476
                        if(viewer) {
2477
                                /* Send an event on the handle to notify the application: it's
2478
                                 * up to the application to then choose a policy and enforce it */
2479
                                json_t *event = json_object();
2480
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
2481
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event, NULL);
2482
                                json_decref(event);
2483
                        }
2484
                } else {
2485
                        JANUS_LOG(LOG_WARN, "Got a slow downlink on a VideoRoom viewer? Weird, because it doesn't send media...\n");
2486
                }
2487
        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
2488
                /* TBD. */
2489
        }
2490
}
2491

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

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

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

    
2649
static void janus_videoroom_sdp_a_format(char *mline, int mline_size, janus_videoroom_audiocodec acodec, int pt, const char *audio_mode, gboolean extmap, int extmap_id) {
2650
        char audio_level_extmap[100];
2651
        if(extmap) {
2652
                /* We only negotiate support (if required) for a single audio extension, audio levels */
2653
                g_snprintf(audio_level_extmap, sizeof(audio_level_extmap),
2654
                        "a=extmap:%d %s\r\n", extmap_id, JANUS_RTP_EXTMAP_AUDIO_LEVEL);
2655
        }
2656
        switch(acodec) {
2657
                case JANUS_VIDEOROOM_OPUS:
2658
                        g_snprintf(mline, mline_size, sdp_a_template_opus,
2659
                                pt,                                                /* Opus payload type */
2660
                                audio_mode,
2661
                                pt,                                                /* Opus payload type */
2662
                                extmap ? audio_level_extmap : "");
2663
                        break;
2664
                case JANUS_VIDEOROOM_ISAC_32K:
2665
                        g_snprintf(mline, mline_size, sdp_a_template_isac32,
2666
                                pt,                                                /* ISAC 32K payload type */
2667
                                audio_mode,
2668
                                pt,                                         /* ISAC 32K payload type */
2669
                                extmap ? audio_level_extmap : "");
2670
                        break;
2671
                case JANUS_VIDEOROOM_ISAC_16K:
2672
                        g_snprintf(mline, mline_size, sdp_a_template_isac16,
2673
                                pt,                                                /* ISAC 16K payload type */
2674
                                audio_mode,                                /* The publisher gets a recvonly or inactive back */
2675
                                pt,                                                /* ISAC 16K payload type */
2676
                                extmap ? audio_level_extmap : "");
2677
                        break;
2678
                case JANUS_VIDEOROOM_PCMU:
2679
                        g_snprintf(mline, mline_size, sdp_a_template_pcmu,
2680
                                pt,                                                /* PCMU payload type */
2681
                                audio_mode,                                /* The publisher gets a recvonly or inactive back */
2682
                                pt,                                                /* PCMU payload type */
2683
                                extmap ? audio_level_extmap : "");
2684
                        break;
2685
                case JANUS_VIDEOROOM_PCMA:
2686
                        g_snprintf(mline, mline_size, sdp_a_template_pcma,
2687
                                pt,                                                /* PCMA payload type */
2688
                                audio_mode,                                /* The publisher gets a recvonly or inactive back */
2689
                                pt,                                                /* PCMA payload type */
2690
                                extmap ? audio_level_extmap : "");
2691
                        break;
2692
                default:
2693
                        /* Shouldn't happen */
2694
                        mline[0] = '\0';
2695
                        break;
2696
        }
2697
}
2698

    
2699
static void janus_videoroom_sdp_v_format(char *mline, int mline_size, janus_videoroom_videocodec vcodec, int pt, int b, const char *video_mode,
2700
                gboolean vo_extmap, int vo_extmap_id, gboolean pd_extmap, int pd_extmap_id) {
2701
        char extmaps[200], temp[100];
2702
        memset(extmaps, 0, sizeof(extmaps));
2703
        memset(temp, 0, sizeof(temp));
2704
        if(vo_extmap) {
2705
                g_snprintf(temp, sizeof(temp),
2706
                        "a=extmap:%d %s\r\n", vo_extmap_id, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION);
2707
                g_strlcat(extmaps, temp, sizeof(extmaps));
2708
        }
2709
        if(pd_extmap) {
2710
                g_snprintf(temp, sizeof(temp),
2711
                        "a=extmap:%d %s\r\n", pd_extmap_id, JANUS_RTP_EXTMAP_PLAYOUT_DELAY);
2712
                g_strlcat(extmaps, temp, sizeof(extmaps));
2713
        }
2714
        switch(vcodec) {
2715
                case JANUS_VIDEOROOM_VP8:
2716
                        g_snprintf(mline, mline_size, sdp_v_template_vp8,
2717
                                pt,                                                        /* payload type */
2718
                                b,                                                        /* Bandwidth */
2719
                                video_mode,                                        /* The publisher gets a recvonly or inactive back */
2720
                                pt,                                                 /* payload type */
2721
                                pt,                                                 /* payload type */
2722
                                pt,                                                 /* payload type */
2723
                                pt,                                                 /* payload type */
2724
                                pt,                                                 /* payload type */
2725
                                (vo_extmap || pd_extmap) ? extmaps : "");
2726
                        break;
2727
                case JANUS_VIDEOROOM_VP9:
2728
                        g_snprintf(mline, mline_size, sdp_v_template_vp9,
2729
                                pt,                                                        /* payload type */
2730
                                b,                                                        /* Bandwidth */
2731
                                video_mode,                                        /* The publisher gets a recvonly or inactive back */
2732
                                pt,                                                 /* payload type */
2733
                                pt,                                                 /* payload type */
2734
                                pt,                                                 /* payload type */
2735
                                pt,                                                 /* payload type */
2736
                                pt,                                                 /* payload type */
2737
                                (vo_extmap || pd_extmap) ? extmaps : "");
2738
                        break;
2739
                case JANUS_VIDEOROOM_H264:
2740
                        g_snprintf(mline, mline_size, sdp_v_template_h264,
2741
                                pt,                                                        /* payload type */
2742
                                b,                                                        /* Bandwidth */
2743
                                video_mode,                                        /* The publisher gets a recvonly or inactive back */
2744
                                pt,                                                 /* payload type */
2745
                                pt,                                                 /* payload type */
2746
                                pt,                                                 /* payload type */
2747
                                pt,                                                 /* payload type */
2748
                                pt,                                                 /* payload type */
2749
                                pt,                                                 /* payload type */
2750
                                (vo_extmap || pd_extmap) ? extmaps : "");
2751
                        break;
2752
                default:
2753
                        /* Shouldn't happen */
2754
                        mline[0] = '\0';
2755
                        break;
2756
        }
2757
}
2758

    
2759
/* Thread to handle incoming messages */
2760
static void *janus_videoroom_handler(void *data) {
2761
        JANUS_LOG(LOG_VERB, "Joining VideoRoom handler thread\n");
2762
        janus_videoroom_message *msg = NULL;
2763
        int error_code = 0;
2764
        char error_cause[512];
2765
        json_t *root = NULL;
2766
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
2767
                msg = g_async_queue_pop(messages);
2768
                if(msg == NULL)
2769
                        continue;
2770
                if(msg == &exit_message)
2771
                        break;
2772
                if(msg->handle == NULL) {
2773
                        janus_videoroom_message_free(msg);
2774
                        continue;
2775
                }
2776
                janus_videoroom_session *session = NULL;
2777
                janus_mutex_lock(&sessions_mutex);
2778
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
2779
                        session = (janus_videoroom_session *)msg->handle->plugin_handle;
2780
                }
2781
                janus_mutex_unlock(&sessions_mutex);
2782
                if(!session) {
2783
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2784
                        janus_videoroom_message_free(msg);
2785
                        continue;
2786
                }
2787
                if(session->destroyed) {
2788
                        janus_videoroom_message_free(msg);
2789
                        continue;
2790
                }
2791
                /* Handle request */
2792
                error_code = 0;
2793
                root = NULL;
2794
                if(msg->message == NULL) {
2795
                        JANUS_LOG(LOG_ERR, "No message??\n");
2796
                        error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
2797
                        g_snprintf(error_cause, 512, "%s", "No message??");
2798
                        goto error;
2799
                }
2800
                root = msg->message;
2801
                /* Get the request first */
2802
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
2803
                        error_code, error_cause, TRUE,
2804
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2805
                if(error_code != 0)
2806
                        goto error;
2807
                json_t *request = json_object_get(root, "request");
2808
                const char *request_text = json_string_value(request);
2809
                json_t *event = NULL;
2810
                /* 'create' and 'destroy' are handled synchronously: what kind of participant is this session referring to? */
2811
                if(session->participant_type == janus_videoroom_p_type_none) {
2812
                        JANUS_LOG(LOG_VERB, "Configuring new participant\n");
2813
                        /* Not configured yet, we need to do this now */
2814
                        if(strcasecmp(request_text, "join") && strcasecmp(request_text, "joinandconfigure")) {
2815
                                JANUS_LOG(LOG_ERR, "Invalid request on unconfigured participant\n");
2816
                                error_code = JANUS_VIDEOROOM_ERROR_JOIN_FIRST;
2817
                                g_snprintf(error_cause, 512, "Invalid request on unconfigured participant");
2818
                                goto error;
2819
                        }
2820
                        JANUS_VALIDATE_JSON_OBJECT(root, join_parameters,
2821
                                error_code, error_cause, TRUE,
2822
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2823
                        if(error_code != 0)
2824
                                goto error;
2825
                        janus_mutex_lock(&rooms_mutex);
2826
                        janus_videoroom *videoroom = NULL;
2827
                        error_code = janus_videoroom_access_room(root, FALSE, TRUE, &videoroom, error_cause, sizeof(error_cause));
2828
                        janus_mutex_unlock(&rooms_mutex);
2829
                        if(error_code != 0)
2830
                                goto error;
2831
                        json_t *ptype = json_object_get(root, "ptype");
2832
                        const char *ptype_text = json_string_value(ptype);
2833
                        if(!strcasecmp(ptype_text, "publisher")) {
2834
                                JANUS_LOG(LOG_VERB, "Configuring new publisher\n");
2835
                                JANUS_VALIDATE_JSON_OBJECT(root, publisher_parameters,
2836
                                        error_code, error_cause, TRUE,
2837
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
2838
                                if(error_code != 0)
2839
                                        goto error;
2840
                                /* A token might be required to join */
2841
                                if(videoroom->check_tokens) {
2842
                                        json_t *token = json_object_get(root, "token");
2843
                                        const char *token_text = token ? json_string_value(token) : NULL;
2844
                                        if(token_text == NULL || g_hash_table_lookup(videoroom->allowed, token_text) == NULL) {
2845
                                                JANUS_LOG(LOG_ERR, "Unauthorized (not in the allowed list)\n");
2846
                                                error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
2847
                                                g_snprintf(error_cause, 512, "Unauthorized (not in the allowed list)");
2848
                                                goto error;
2849
                                        }
2850
                                }
2851
                                json_t *display = json_object_get(root, "display");
2852
                                const char *display_text = display ? json_string_value(display) : NULL;
2853
                                guint64 user_id = 0;
2854
                                json_t *id = json_object_get(root, "id");
2855
                                janus_mutex_lock(&videoroom->participants_mutex);
2856
                                if(id) {
2857
                                        user_id = json_integer_value(id);
2858
                                        if(g_hash_table_lookup(videoroom->participants, &user_id) != NULL) {
2859
                                                janus_mutex_unlock(&videoroom->participants_mutex);
2860
                                                /* User ID already taken */
2861
                                                JANUS_LOG(LOG_ERR, "User ID %"SCNu64" already exists\n", user_id);
2862
                                                error_code = JANUS_VIDEOROOM_ERROR_ID_EXISTS;
2863
                                                g_snprintf(error_cause, 512, "User ID %"SCNu64" already exists", user_id);
2864
                                                goto error;
2865
                                        }
2866
                                }
2867
                                if(user_id == 0) {
2868
                                        /* Generate a random ID */
2869
                                        while(user_id == 0) {
2870
                                                user_id = janus_random_uint64();
2871
                                                if(g_hash_table_lookup(videoroom->participants, &user_id) != NULL) {
2872
                                                        /* User ID already taken, try another one */
2873
                                                        user_id = 0;
2874
                                                }
2875
                                        }
2876
                                }
2877
                                JANUS_LOG(LOG_VERB, "  -- Publisher ID: %"SCNu64"\n", user_id);
2878
                                /* Process the request */
2879
                                json_t *audio = NULL, *video = NULL, *bitrate = NULL, *record = NULL, *recfile = NULL;
2880
                                if(!strcasecmp(request_text, "joinandconfigure")) {
2881
                                        /* Also configure (or publish a new feed) audio/video/bitrate for this new publisher */
2882
                                        /* join_parameters were validated earlier. */
2883
                                        audio = json_object_get(root, "audio");
2884
                                        video = json_object_get(root, "video");
2885
                                        bitrate = json_object_get(root, "bitrate");
2886
                                        record = json_object_get(root, "record");
2887
                                        recfile = json_object_get(root, "filename");
2888
                                }
2889
                                janus_videoroom_participant *publisher = g_malloc0(sizeof(janus_videoroom_participant));
2890
                                publisher->session = session;
2891
                                publisher->room = videoroom;
2892
                                publisher->user_id = user_id;
2893
                                publisher->display = display_text ? g_strdup(display_text) : NULL;
2894
                                publisher->sdp = NULL;                /* We'll deal with this later */
2895
                                publisher->audio = FALSE;        /* We'll deal with this later */
2896
                                publisher->video = FALSE;        /* We'll deal with this later */
2897
                                publisher->data = FALSE;        /* We'll deal with this later */
2898
                                publisher->audio_active = FALSE;
2899
                                publisher->video_active = FALSE;
2900
                                publisher->recording_active = FALSE;
2901
                                publisher->recording_base = NULL;
2902
                                publisher->arc = NULL;
2903
                                publisher->vrc = NULL;
2904
                                janus_mutex_init(&publisher->rec_mutex);
2905
                                publisher->firefox = FALSE;
2906
                                publisher->bitrate = videoroom->bitrate;
2907
                                publisher->listeners = NULL;
2908
                                janus_mutex_init(&publisher->listeners_mutex);
2909
                                publisher->audio_pt = OPUS_PT;
2910
                                switch(videoroom->acodec) {
2911
                                        case JANUS_VIDEOROOM_OPUS:
2912
                                                publisher->audio_pt = OPUS_PT;
2913
                                                break;
2914
                                        case JANUS_VIDEOROOM_ISAC_32K:
2915
                                                publisher->audio_pt = ISAC32_PT;
2916
                                                break;
2917
                                        case JANUS_VIDEOROOM_ISAC_16K:
2918
                                                publisher->audio_pt = ISAC16_PT;
2919
                                                break;
2920
                                        case JANUS_VIDEOROOM_PCMU:
2921
                                                publisher->audio_pt = PCMU_PT;
2922
                                                break;
2923
                                        case JANUS_VIDEOROOM_PCMA:
2924
                                                publisher->audio_pt = PCMA_PT;
2925
                                                break;
2926
                                        default:
2927
                                                /* Shouldn't happen */
2928
                                                publisher->audio_pt = OPUS_PT;
2929
                                                break;
2930
                                }
2931
                                switch(videoroom->vcodec) {
2932
                                        case JANUS_VIDEOROOM_VP8:
2933
                                                publisher->video_pt = VP8_PT;
2934
                                                break;
2935
                                        case JANUS_VIDEOROOM_VP9:
2936
                                                publisher->video_pt = VP9_PT;
2937
                                                break;
2938
                                        case JANUS_VIDEOROOM_H264:
2939
                                                publisher->video_pt = H264_PT;
2940
                                                break;
2941
                                        default:
2942
                                                /* Shouldn't happen */
2943
                                                publisher->video_pt = VP8_PT;
2944
                                                break;
2945
                                }
2946
                                publisher->audio_ssrc = janus_random_uint32();
2947
                                publisher->video_ssrc = janus_random_uint32();
2948
                                publisher->audio_level_extmap_id = 0;
2949
                                publisher->video_orient_extmap_id = 0;
2950
                                publisher->playout_delay_extmap_id = 0;
2951
                                publisher->remb_startup = 4;
2952
                                publisher->remb_latest = 0;
2953
                                publisher->fir_latest = 0;
2954
                                publisher->fir_seq = 0;
2955
                                janus_mutex_init(&publisher->rtp_forwarders_mutex);
2956
                                publisher->rtp_forwarders = g_hash_table_new_full(NULL, NULL, NULL, (GDestroyNotify)janus_videoroom_rtp_forwarder_free_helper);
2957
                                publisher->udp_sock = -1;
2958
                                /* Finally, generate a private ID: this is only needed in case the participant
2959
                                 * wants to allow the plugin to know which subscriptions belong to them */
2960
                                publisher->pvt_id = 0;
2961
                                while(publisher->pvt_id == 0) {
2962
                                        publisher->pvt_id = janus_random_uint32();
2963
                                        if(g_hash_table_lookup(videoroom->private_ids, GUINT_TO_POINTER(publisher->pvt_id)) != NULL) {
2964
                                                /* Private ID already taken, try another one */
2965
                                                publisher->pvt_id = 0;
2966
                                        }
2967
                                        g_hash_table_insert(videoroom->private_ids, GUINT_TO_POINTER(publisher->pvt_id), publisher);
2968
                                }
2969
                                /* In case we also wanted to configure */
2970
                                if(audio) {
2971
                                        publisher->audio_active = json_is_true(audio);
2972
                                        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);
2973
                                }
2974
                                if(video) {
2975
                                        publisher->video_active = json_is_true(video);
2976
                                        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);
2977
                                }
2978
                                if(bitrate) {
2979
                                        publisher->bitrate = json_integer_value(bitrate);
2980
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", publisher->bitrate, publisher->room->room_id, publisher->user_id);
2981
                                }
2982
                                if(record) {
2983
                                        publisher->recording_active = json_is_true(record);
2984
                                        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);
2985
                                }
2986
                                if(recfile) {
2987
                                        publisher->recording_base = g_strdup(json_string_value(recfile));
2988
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", publisher->recording_base, publisher->room->room_id, publisher->user_id);
2989
                                }
2990
                                /* Done */
2991
                                session->participant_type = janus_videoroom_p_type_publisher;
2992
                                session->participant = publisher;
2993
                                /* Return a list of all available publishers (those with an SDP available, that is) */
2994
                                json_t *list = json_array();
2995
                                GHashTableIter iter;
2996
                                gpointer value;
2997
                                g_hash_table_insert(videoroom->participants, janus_uint64_dup(publisher->user_id), publisher);
2998
                                g_hash_table_iter_init(&iter, videoroom->participants);
2999
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3000
                                        janus_videoroom_participant *p = value;
3001
                                        if(p == publisher || !p->sdp || !p->session->started) {
3002
                                                continue;
3003
                                        }
3004
                                        json_t *pl = json_object();
3005
                                        json_object_set_new(pl, "id", json_integer(p->user_id));
3006
                                        if(p->display)
3007
                                                json_object_set_new(pl, "display", json_string(p->display));
3008
                                        json_array_append_new(list, pl);
3009
                                }
3010
                                janus_mutex_unlock(&videoroom->participants_mutex);
3011
                                event = json_object();
3012
                                json_object_set_new(event, "videoroom", json_string("joined"));
3013
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
3014
                                json_object_set_new(event, "description", json_string(videoroom->room_name));
3015
                                json_object_set_new(event, "id", json_integer(user_id));
3016
                                json_object_set_new(event, "private_id", json_integer(publisher->pvt_id));
3017
                                json_object_set_new(event, "publishers", list);
3018
                                /* Also notify event handlers */
3019
                                if(notify_events && gateway->events_is_enabled()) {
3020
                                        json_t *info = json_object();
3021
                                        json_object_set_new(info, "event", json_string("joined"));
3022
                                        json_object_set_new(info, "room", json_integer(videoroom->room_id));
3023
                                        json_object_set_new(info, "id", json_integer(user_id));
3024
                                        json_object_set_new(info, "private_id", json_integer(publisher->pvt_id));
3025
                                        if(display_text != NULL)
3026
                                                json_object_set_new(info, "display", json_string(display_text));
3027
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3028
                                }
3029
                        } else if(!strcasecmp(ptype_text, "listener")) {
3030
                                JANUS_LOG(LOG_VERB, "Configuring new listener\n");
3031
                                /* This is a new listener */
3032
                                JANUS_VALIDATE_JSON_OBJECT(root, listener_parameters,
3033
                                        error_code, error_cause, TRUE,
3034
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3035
                                if(error_code != 0)
3036
                                        goto error;
3037
                                json_t *feed = json_object_get(root, "feed");
3038
                                guint64 feed_id = json_integer_value(feed);
3039
                                json_t *pvt = json_object_get(root, "private_id");
3040
                                guint64 pvt_id = json_integer_value(pvt);
3041
                                json_t *audio = json_object_get(root, "audio");
3042
                                json_t *video = json_object_get(root, "video");
3043
                                json_t *data = json_object_get(root, "data");
3044
                                janus_mutex_lock(&videoroom->participants_mutex);
3045
                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &feed_id);
3046
                                janus_mutex_unlock(&videoroom->participants_mutex);
3047
                                if(publisher == NULL || publisher->sdp == NULL) {
3048
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3049
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3050
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3051
                                        goto error;
3052
                                } else {
3053
                                        janus_videoroom_listener *listener = g_malloc0(sizeof(janus_videoroom_listener));
3054
                                        listener->session = session;
3055
                                        listener->room = videoroom;
3056
                                        listener->feed = publisher;
3057
                                        listener->pvt_id = pvt_id;
3058
                                        /* Initialize the listener context */
3059
                                        listener->context.a_last_ssrc = 0;
3060
                                        listener->context.a_last_ts = 0;
3061
                                        listener->context.a_base_ts = 0;
3062
                                        listener->context.a_base_ts_prev = 0;
3063
                                        listener->context.v_last_ssrc = 0;
3064
                                        listener->context.v_last_ts = 0;
3065
                                        listener->context.v_base_ts = 0;
3066
                                        listener->context.v_base_ts_prev = 0;
3067
                                        listener->context.a_last_seq = 0;
3068
                                        listener->context.a_base_seq = 0;
3069
                                        listener->context.a_base_seq_prev = 0;
3070
                                        listener->context.v_last_seq = 0;
3071
                                        listener->context.v_base_seq = 0;
3072
                                        listener->context.v_base_seq_prev = 0;
3073
                                        listener->context.a_seq_reset = FALSE;
3074
                                        listener->context.v_seq_reset = FALSE;
3075
                                        listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
3076
                                        if(!publisher->audio)
3077
                                                listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
3078
                                        listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
3079
                                        if(!publisher->video)
3080
                                                listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
3081
                                        listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
3082
                                        if(!publisher->data)
3083
                                                listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
3084
                                        listener->paused = TRUE;        /* We need an explicit start from the listener */
3085
                                        listener->parent = NULL;
3086
                                        session->participant = listener;
3087
                                        janus_mutex_lock(&publisher->listeners_mutex);
3088
                                        publisher->listeners = g_slist_append(publisher->listeners, listener);
3089
                                        janus_mutex_unlock(&publisher->listeners_mutex);
3090
                                        event = json_object();
3091
                                        json_object_set_new(event, "videoroom", json_string("attached"));
3092
                                        json_object_set_new(event, "room", json_integer(videoroom->room_id));
3093
                                        json_object_set_new(event, "id", json_integer(feed_id));
3094
                                        if(publisher->display)
3095
                                                json_object_set_new(event, "display", json_string(publisher->display));
3096
                                        session->participant_type = janus_videoroom_p_type_subscriber;
3097
                                        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3098
                                        /* Negotiate by sending the selected publisher SDP back */
3099
                                        if(publisher->sdp != NULL) {
3100
                                                json_t *jsep = json_pack("{ssss}", "type", "offer", "sdp", publisher->sdp);
3101
                                                /* How long will the gateway take to push the event? */
3102
                                                g_atomic_int_set(&session->hangingup, 0);
3103
                                                gint64 start = janus_get_monotonic_time();
3104
                                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, jsep);
3105
                                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3106
                                                json_decref(event);
3107
                                                json_decref(jsep);
3108
                                                janus_videoroom_message_free(msg);
3109
                                                /* Also notify event handlers */
3110
                                                if(notify_events && gateway->events_is_enabled()) {
3111
                                                        json_t *info = json_object();
3112
                                                        json_object_set_new(info, "event", json_string("subscribing"));
3113
                                                        json_object_set_new(info, "room", json_integer(videoroom->room_id));
3114
                                                        json_object_set_new(info, "feed", json_integer(feed_id));
3115
                                                        json_object_set_new(info, "private_id", json_integer(pvt_id));
3116
                                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3117
                                                }
3118
                                                continue;
3119
                                        }
3120
                                }
3121
                        } else if(!strcasecmp(ptype_text, "muxed-listener")) {
3122
                                /* This is a new Multiplexed listener */
3123
                                JANUS_LOG(LOG_INFO, "Configuring new Multiplexed listener\n");
3124
                                /* Any feed we want to attach to already? */
3125
                                GList *list = NULL;
3126
                                JANUS_VALIDATE_JSON_OBJECT(root, feeds_parameters,
3127
                                        error_code, error_cause, TRUE,
3128
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3129
                                if(error_code != 0)
3130
                                        goto error;
3131
                                json_t *feeds = json_object_get(root, "feeds");
3132
                                if(feeds && json_array_size(feeds) > 0) {
3133
                                        unsigned int i = 0;
3134
                                        int problem = 0;
3135
                                        for(i=0; i<json_array_size(feeds); i++) {
3136
                                                if(videoroom->destroyed) {
3137
                                                        problem = 1;
3138
                                                        JANUS_LOG(LOG_ERR, "Room destroyed");
3139
                                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3140
                                                        g_snprintf(error_cause, 512, "Room destroyed");
3141
                                                        break;
3142
                                                }
3143
                                                json_t *feed = json_array_get(feeds, i);
3144
                                                if(!feed || !json_is_integer(feed)) {
3145
                                                        problem = 1;
3146
                                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
3147
                                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3148
                                                        g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
3149
                                                        break;
3150
                                                }
3151
                                                uint64_t feed_id = json_integer_value(feed);
3152
                                                janus_mutex_lock(&videoroom->participants_mutex);
3153
                                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, &feed_id);
3154
                                                janus_mutex_unlock(&videoroom->participants_mutex);
3155
                                                if(publisher == NULL) { //~ || publisher->sdp == NULL) {
3156
                                                        /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
3157
                                                        problem = 1;
3158
                                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3159
                                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3160
                                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3161
                                                        break;
3162
                                                }
3163
                                                list = g_list_prepend(list, GUINT_TO_POINTER(feed_id));
3164
                                                JANUS_LOG(LOG_INFO, "  -- Subscribing to feed %"SCNu64"\n", feed_id);
3165
                                        }
3166
                                        if(problem) {
3167
                                                goto error;
3168
                                        }
3169
                                }
3170
                                /* Allocate listener */
3171
                                janus_videoroom_listener_muxed *listener = g_malloc0(sizeof(janus_videoroom_listener_muxed));
3172
                                listener->session = session;
3173
                                listener->room = videoroom;
3174
                                session->participant_type = janus_videoroom_p_type_subscriber_muxed;
3175
                                session->participant = listener;
3176
                                /* Ack that we created the listener */
3177
                                event = json_object();
3178
                                json_object_set_new(event, "videoroom", json_string("muxed-created"));
3179
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
3180
                                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3181
                                /* How long will the gateway take to push the event? */
3182
                                gint64 start = janus_get_monotonic_time();
3183
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3184
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3185
                                json_decref(event);
3186
                                /* Attach to feeds if needed */
3187
                                if(list != NULL) {
3188
                                        JANUS_LOG(LOG_INFO, "Subscribing to %d feeds\n", g_list_length(list));
3189
                                        list = g_list_reverse(list);
3190
                                        if(videoroom->destroyed || janus_videoroom_muxed_subscribe(listener, list, msg->transaction) < 0) {
3191
                                                JANUS_LOG(LOG_ERR, "Error subscribing!\n");
3192
                                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3193
                                                g_snprintf(error_cause, 512, "Error subscribing!");
3194
                                                goto error;
3195
                                        }
3196
                                }
3197
                                janus_videoroom_message_free(msg);
3198
                                continue;
3199
                        } else {
3200
                                JANUS_LOG(LOG_ERR, "Invalid element (ptype)\n");
3201
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3202
                                g_snprintf(error_cause, 512, "Invalid element (ptype)");
3203
                                goto error;
3204
                        }
3205
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
3206
                        /* Handle this publisher */
3207
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3208
                        if(participant == NULL) {
3209
                                JANUS_LOG(LOG_ERR, "Invalid participant instance\n");
3210
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
3211
                                g_snprintf(error_cause, 512, "Invalid participant instance");
3212
                                goto error;
3213
                        }
3214
                        if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")) {
3215
                                JANUS_LOG(LOG_ERR, "Already in as a publisher on this handle\n");
3216
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
3217
                                g_snprintf(error_cause, 512, "Already in as a publisher on this handle");
3218
                                goto error;
3219
                        } else if(!strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish")) {
3220
                                if(!strcasecmp(request_text, "publish") && participant->sdp) {
3221
                                        JANUS_LOG(LOG_ERR, "Can't publish, already published\n");
3222
                                        error_code = JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED;
3223
                                        g_snprintf(error_cause, 512, "Can't publish, already published");
3224
                                        goto error;
3225
                                }
3226
                                /* Configure (or publish a new feed) audio/video/bitrate for this publisher */
3227
                                JANUS_VALIDATE_JSON_OBJECT(root, publish_parameters,
3228
                                        error_code, error_cause, TRUE,
3229
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3230
                                if(error_code != 0)
3231
                                        goto error;
3232
                                json_t *audio = json_object_get(root, "audio");
3233
                                json_t *video = json_object_get(root, "video");
3234
                                json_t *bitrate = json_object_get(root, "bitrate");
3235
                                json_t *record = json_object_get(root, "record");
3236
                                json_t *recfile = json_object_get(root, "filename");
3237
                                if(audio) {
3238
                                        gboolean audio_active = json_is_true(audio);
3239
                                        if(session->started && audio_active && !participant->audio_active) {
3240
                                                /* Audio was just resumed, try resetting the RTP headers for viewers */
3241
                                                janus_mutex_lock(&participant->listeners_mutex);
3242
                                                GSList *ps = participant->listeners;
3243
                                                while(ps) {
3244
                                                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
3245
                                                        if(l)
3246
                                                                l->context.a_seq_reset = TRUE;
3247
                                                        ps = ps->next;
3248
                                                }
3249
                                                janus_mutex_unlock(&participant->listeners_mutex);
3250
                                        }
3251
                                        participant->audio_active = audio_active;
3252
                                        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);
3253
                                }
3254
                                if(video) {
3255
                                        gboolean video_active = json_is_true(video);
3256
                                        if(session->started && video_active && !participant->video_active) {
3257
                                                /* Video was just resumed, try resetting the RTP headers for viewers */
3258
                                                janus_mutex_lock(&participant->listeners_mutex);
3259
                                                GSList *ps = participant->listeners;
3260
                                                while(ps) {
3261
                                                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
3262
                                                        if(l)
3263
                                                                l->context.v_seq_reset = TRUE;
3264
                                                        ps = ps->next;
3265
                                                }
3266
                                                janus_mutex_unlock(&participant->listeners_mutex);
3267
                                        }
3268
                                        participant->video_active = video_active;
3269
                                        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);
3270
                                }
3271
                                if(bitrate) {
3272
                                        participant->bitrate = json_integer_value(bitrate);
3273
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", participant->bitrate, participant->room->room_id, participant->user_id);
3274
                                        /* Send a new REMB */
3275
                                        if(session->started)
3276
                                                participant->remb_latest = janus_get_monotonic_time();
3277
                                        char rtcpbuf[24];
3278
                                        janus_rtcp_remb((char *)(&rtcpbuf), 24, participant->bitrate ? participant->bitrate : 256*1024);
3279
                                        gateway->relay_rtcp(msg->handle, 1, rtcpbuf, 24);
3280
                                }
3281
                                janus_mutex_lock(&participant->rec_mutex);
3282
                                gboolean prev_recording_active = participant->recording_active;
3283
                                if(record) {
3284
                                        participant->recording_active = json_is_true(record);
3285
                                        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);
3286
                                }
3287
                                if(recfile) {
3288
                                        participant->recording_base = g_strdup(json_string_value(recfile));
3289
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", participant->recording_base, participant->room->room_id, participant->user_id);
3290
                                }
3291
                                /* Do we need to do something with the recordings right now? */
3292
                                if(participant->recording_active != prev_recording_active) {
3293
                                        /* Something changed */
3294
                                        if(!participant->recording_active) {
3295
                                                /* Not recording (anymore?) */
3296
                                                janus_videoroom_recorder_close(participant);
3297
                                        } else if(participant->recording_active && participant->sdp) {
3298
                                                /* We've started recording, send a PLI/FIR and go on */
3299
                                                janus_videoroom_recorder_create(participant, strstr(participant->sdp, "m=audio") != NULL, strstr(participant->sdp, "m=video") != NULL);
3300
                                                if(strstr(participant->sdp, "m=video")) {
3301
                                                        /* Send a FIR */
3302
                                                        char buf[20];
3303
                                                        memset(buf, 0, 20);
3304
                                                        janus_rtcp_fir((char *)&buf, 20, &participant->fir_seq);
3305
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending FIR to %"SCNu64" (%s)\n",
3306
                                                                participant->user_id, participant->display ? participant->display : "??");
3307
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 20);
3308
                                                        /* Send a PLI too, just in case... */
3309
                                                        memset(buf, 0, 12);
3310
                                                        janus_rtcp_pli((char *)&buf, 12);
3311
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending PLI to %"SCNu64" (%s)\n",
3312
                                                                participant->user_id, participant->display ? participant->display : "??");
3313
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 12);
3314
                                                }
3315
                                        }
3316
                                }
3317
                                janus_mutex_unlock(&participant->rec_mutex);
3318
                                /* Done */
3319
                                event = json_object();
3320
                                json_object_set_new(event, "videoroom", json_string("event"));
3321
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
3322
                                json_object_set_new(event, "configured", json_string("ok"));
3323
                                /* Also notify event handlers */
3324
                                if(notify_events && gateway->events_is_enabled()) {
3325
                                        json_t *info = json_object();
3326
                                        json_object_set_new(info, "event", json_string("configured"));
3327
                                        json_object_set_new(info, "room", json_integer(participant->room->room_id));
3328
                                        json_object_set_new(info, "id", json_integer(participant->user_id));
3329
                                        json_object_set_new(info, "audio_active", participant->audio_active ? json_true() : json_false());
3330
                                        json_object_set_new(info, "video_active", participant->video_active ? json_true() : json_false());
3331
                                        json_object_set_new(info, "bitrate", json_integer(participant->bitrate));
3332
                                        if(participant->arc || participant->vrc) {
3333
                                                json_t *recording = json_object();
3334
                                                if(participant->arc && participant->arc->filename)
3335
                                                        json_object_set_new(recording, "audio", json_string(participant->arc->filename));
3336
                                                if(participant->vrc && participant->vrc->filename)
3337
                                                        json_object_set_new(recording, "video", json_string(participant->vrc->filename));
3338
                                                json_object_set_new(info, "recording", recording);
3339
                                        }
3340
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3341
                                }
3342
                        } else if(!strcasecmp(request_text, "unpublish")) {
3343
                                /* This participant wants to unpublish */
3344
                                if(!participant->sdp) {
3345
                                        JANUS_LOG(LOG_ERR, "Can't unpublish, not published\n");
3346
                                        error_code = JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED;
3347
                                        g_snprintf(error_cause, 512, "Can't unpublish, not published");
3348
                                        goto error;
3349
                                }
3350
                                /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
3351
                                gateway->close_pc(session->handle);
3352
                                /* Done */
3353
                                event = json_object();
3354
                                json_object_set_new(event, "videoroom", json_string("event"));
3355
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
3356
                                json_object_set_new(event, "unpublished", json_string("ok"));
3357
                        } else if(!strcasecmp(request_text, "leave")) {
3358
                                /* Prepare an event to confirm the request */
3359
                                event = json_object();
3360
                                json_object_set_new(event, "videoroom", json_string("event"));
3361
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
3362
                                json_object_set_new(event, "leaving", json_string("ok"));
3363
                                /* This publisher is leaving, tell everybody */
3364
                                janus_videoroom_leave_or_unpublish(participant, TRUE);
3365
                                /* Done */
3366
                                participant->audio_active = FALSE;
3367
                                participant->video_active = FALSE;
3368
                                session->started = FALSE;
3369
                                //~ session->destroy = TRUE;
3370
                        } else {
3371
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3372
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3373
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3374
                                goto error;
3375
                        }
3376
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
3377
                        /* Handle this listener */
3378
                        janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
3379
                        if(listener == NULL) {
3380
                                JANUS_LOG(LOG_ERR, "Invalid listener instance\n");
3381
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
3382
                                g_snprintf(error_cause, 512, "Invalid listener instance");
3383
                                goto error;
3384
                        }
3385
                        if(!strcasecmp(request_text, "join")) {
3386
                                JANUS_LOG(LOG_ERR, "Already in as a listener on this handle\n");
3387
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
3388
                                g_snprintf(error_cause, 512, "Already in as a listener on this handle");
3389
                                goto error;
3390
                        } else if(!strcasecmp(request_text, "start")) {
3391
                                /* Start/restart receiving the publisher streams */
3392
                                janus_videoroom_participant *publisher = listener->feed;
3393
                                listener->paused = FALSE;
3394
                                event = json_object();
3395
                                json_object_set_new(event, "videoroom", json_string("event"));
3396
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3397
                                json_object_set_new(event, "started", json_string("ok"));
3398
                                if(publisher) {
3399
                                        /* Send a FIR */
3400
                                        char buf[20];
3401
                                        memset(buf, 0, 20);
3402
                                        janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3403
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3404
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3405
                                        /* Send a PLI too, just in case... */
3406
                                        memset(buf, 0, 12);
3407
                                        janus_rtcp_pli((char *)&buf, 12);
3408
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3409
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3410
                                }
3411
                        } else if(!strcasecmp(request_text, "configure")) {
3412
                                JANUS_VALIDATE_JSON_OBJECT(root, configure_parameters,
3413
                                        error_code, error_cause, TRUE,
3414
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3415
                                if(error_code != 0)
3416
                                        goto error;
3417
                                json_t *audio = json_object_get(root, "audio");
3418
                                json_t *video = json_object_get(root, "video");
3419
                                json_t *data = json_object_get(root, "data");
3420
                                /* Update the audio/video/data flags, if set */
3421
                                janus_videoroom_participant *publisher = listener->feed;
3422
                                if(publisher) {
3423
                                        if(audio && publisher->audio)
3424
                                                listener->audio = json_is_true(audio);
3425
                                        if(video && publisher->video)
3426
                                                listener->video = json_is_true(video);
3427
                                        if(data && publisher->data)
3428
                                                listener->data = json_is_true(data);
3429
                                }
3430
                                event = json_object();
3431
                                json_object_set_new(event, "videoroom", json_string("event"));
3432
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3433
                                json_object_set_new(event, "configured", json_string("ok"));
3434
                        } else if(!strcasecmp(request_text, "pause")) {
3435
                                /* Stop receiving the publisher streams for a while */
3436
                                listener->paused = TRUE;
3437
                                event = json_object();
3438
                                json_object_set_new(event, "videoroom", json_string("event"));
3439
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3440
                                json_object_set_new(event, "paused", json_string("ok"));
3441
                        } else if(!strcasecmp(request_text, "switch")) {
3442
                                /* This listener wants to switch to a different publisher */
3443
                                JANUS_VALIDATE_JSON_OBJECT(root, listener_parameters,
3444
                                        error_code, error_cause, TRUE,
3445
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3446
                                if(error_code != 0)
3447
                                        goto error;
3448
                                json_t *feed = json_object_get(root, "feed");
3449
                                guint64 feed_id = json_integer_value(feed);
3450
                                json_t *audio = json_object_get(root, "audio");
3451
                                json_t *video = json_object_get(root, "video");
3452
                                json_t *data = json_object_get(root, "data");
3453
                                if(!listener->room) {
3454
                                        JANUS_LOG(LOG_ERR, "Room Destroyed \n");
3455
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3456
                                        g_snprintf(error_cause, 512, "No such room ");
3457
                                        goto error;
3458
                                }
3459
                                if(listener->room->destroyed) {
3460
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")\n", listener->room->room_id);
3461
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3462
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
3463
                                        goto error;
3464
                                }
3465
                                janus_mutex_lock(&listener->room->participants_mutex);
3466
                                janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, &feed_id);
3467
                                janus_mutex_unlock(&listener->room->participants_mutex);
3468
                                if(publisher == NULL || publisher->sdp == NULL) {
3469
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3470
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3471
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3472
                                        goto error;
3473
                                }
3474
                                gboolean paused = listener->paused;
3475
                                listener->paused = TRUE;
3476
                                /* Unsubscribe from the previous publisher */
3477
                                janus_videoroom_participant *prev_feed = listener->feed;
3478
                                if(prev_feed) {
3479
                                        janus_mutex_lock(&prev_feed->listeners_mutex);
3480
                                        prev_feed->listeners = g_slist_remove(prev_feed->listeners, listener);
3481
                                        janus_mutex_unlock(&prev_feed->listeners_mutex);
3482
                                        listener->feed = NULL;
3483
                                }
3484
                                /* Subscribe to the new one */
3485
                                listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
3486
                                if(!publisher->audio)
3487
                                        listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
3488
                                listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
3489
                                if(!publisher->video)
3490
                                        listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
3491
                                listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
3492
                                if(!publisher->data)
3493
                                        listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
3494
                                janus_mutex_lock(&publisher->listeners_mutex);
3495
                                publisher->listeners = g_slist_append(publisher->listeners, listener);
3496
                                janus_mutex_unlock(&publisher->listeners_mutex);
3497
                                listener->feed = publisher;
3498
                                /* Send a FIR to the new publisher */
3499
                                char buf[20];
3500
                                memset(buf, 0, 20);
3501
                                janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3502
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3503
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3504
                                /* Send a PLI too, just in case... */
3505
                                memset(buf, 0, 12);
3506
                                janus_rtcp_pli((char *)&buf, 12);
3507
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3508
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3509
                                /* Done */
3510
                                listener->paused = paused;
3511
                                event = json_object();
3512
                                json_object_set_new(event, "videoroom", json_string("event"));
3513
                                json_object_set_new(event, "switched", json_string("ok"));
3514
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3515
                                json_object_set_new(event, "id", json_integer(feed_id));
3516
                                if(publisher->display)
3517
                                        json_object_set_new(event, "display", json_string(publisher->display));
3518
                                /* Also notify event handlers */
3519
                                if(notify_events && gateway->events_is_enabled()) {
3520
                                        json_t *info = json_object();
3521
                                        json_object_set_new(info, "event", json_string("switched"));
3522
                                        json_object_set_new(info, "room", json_integer(publisher->room->room_id));
3523
                                        json_object_set_new(info, "feed", json_integer(publisher->user_id));
3524
                                        gateway->notify_event(&janus_videoroom_plugin, session->handle, info);
3525
                                }
3526
                        } else if(!strcasecmp(request_text, "leave")) {
3527
                                janus_videoroom_participant *publisher = listener->feed;
3528
                                if(publisher != NULL) {
3529
                                        janus_mutex_lock(&publisher->listeners_mutex);
3530
                                        publisher->listeners = g_slist_remove(publisher->listeners, listener);
3531
                                        janus_mutex_unlock(&publisher->listeners_mutex);
3532
                                        listener->feed = NULL;
3533
                                }
3534
                                event = json_object();
3535
                                json_object_set_new(event, "videoroom", json_string("event"));
3536
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3537
                                json_object_set_new(event, "left", json_string("ok"));
3538
                                session->started = FALSE;
3539
                        } else {
3540
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3541
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3542
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3543
                                goto error;
3544
                        }
3545
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
3546
                        /* Handle this Multiplexed listener */
3547
                        janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
3548
                        if(listener == NULL) {
3549
                                JANUS_LOG(LOG_ERR, "Invalid Multiplexed listener instance\n");
3550
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
3551
                                g_snprintf(error_cause, 512, "Invalid Multiplexed listener instance");
3552
                                goto error;
3553
                        }
3554
                        if(!strcasecmp(request_text, "join")) {
3555
                                JANUS_LOG(LOG_ERR, "Already in as a Multiplexed listener on this handle\n");
3556
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
3557
                                g_snprintf(error_cause, 512, "Already in as a Multiplexed listener on this handle");
3558
                                goto error;
3559
                        } else if(!strcasecmp(request_text, "add")) {
3560
                                /* Add new streams to subscribe to */
3561
                                GList *list = NULL;
3562
                                JANUS_VALIDATE_JSON_OBJECT(root, feeds_parameters,
3563
                                        error_code, error_cause, TRUE,
3564
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3565
                                if(error_code != 0)
3566
                                        goto error;
3567
                                json_t *feeds = json_object_get(root, "feeds");
3568
                                unsigned int i = 0;
3569
                                int problem = 0;
3570
                                if(!listener->room) {
3571
                                        JANUS_LOG(LOG_ERR, "Room Destroyed ");
3572
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3573
                                        g_snprintf(error_cause, 512, "No such room ");
3574
                                        goto error;
3575
                                }
3576
                                if(listener->room->destroyed) {
3577
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")", listener->room->room_id);
3578
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3579
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
3580
                                        goto error;
3581
                                }
3582
                                for(i=0; i<json_array_size(feeds); i++) {
3583
                                        json_t *feed = json_array_get(feeds, i);
3584
                                        if(listener->room->destroyed) {
3585
                                                problem = 1;
3586
                                                JANUS_LOG(LOG_ERR, "Room destroyed");
3587
                                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3588
                                                g_snprintf(error_cause, 512, "Room destroyed");
3589
                                                break;
3590
                                        }
3591
                                        if(!feed || !json_is_integer(feed)) {
3592
                                                problem = 1;
3593
                                                JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
3594
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3595
                                                g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
3596
                                                break;
3597
                                        }
3598
                                        uint64_t feed_id = json_integer_value(feed);
3599
                                        janus_mutex_lock(&listener->room->participants_mutex);
3600
                                        janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, &feed_id);
3601
                                        janus_mutex_unlock(&listener->room->participants_mutex);
3602
                                        if(publisher == NULL) { //~ || publisher->sdp == NULL) {
3603
                                                /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
3604
                                                problem = 1;
3605
                                                JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3606
                                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3607
                                                g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3608
                                                break;
3609
                                        }
3610
                                        list = g_list_prepend(list, GUINT_TO_POINTER(feed_id));
3611
                                }
3612
                                if(problem) {
3613
                                        goto error;
3614
                                }
3615
                                list = g_list_reverse(list);
3616
                                if(janus_videoroom_muxed_subscribe(listener, list, msg->transaction) < 0) {
3617
                                        JANUS_LOG(LOG_ERR, "Error subscribing!\n");
3618
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3619
                                        g_snprintf(error_cause, 512, "Error subscribing!");
3620
                                        goto error;
3621
                                }
3622
                                janus_videoroom_message_free(msg);
3623
                                continue;
3624
                        } else if(!strcasecmp(request_text, "remove")) {
3625
                                /* Remove subscribed streams */
3626
                                GList *list = NULL;
3627
                                JANUS_VALIDATE_JSON_OBJECT(root, feeds_parameters,
3628
                                        error_code, error_cause, TRUE,
3629
                                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
3630
                                if(error_code != 0)
3631
                                        goto error;
3632
                                json_t *feeds = json_object_get(root, "feeds");
3633
                                unsigned int i = 0;
3634
                                int error = 0;
3635
                                for(i=0; i<json_array_size(feeds); i++) {
3636
                                        json_t *feed = json_array_get(feeds, i);
3637
                                        if(!feed || !json_is_integer(feed)) {
3638
                                                error = 1;
3639
                                                break;
3640
                                        }
3641
                                        list = g_list_prepend(list, GUINT_TO_POINTER(json_integer_value(feed)));
3642
                                }
3643
                                if(error) {
3644
                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
3645
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3646
                                        g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
3647
                                        goto error;
3648
                                }
3649
                                list = g_list_reverse(list);
3650
                                
3651
                                if(!listener->room) {
3652
                                        JANUS_LOG(LOG_ERR, "Error unsubscribing!\n");
3653
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3654
                                        g_snprintf(error_cause, 512, "Error unsubscribing!");
3655
                                        goto error;
3656
                                }
3657
                                if(janus_videoroom_muxed_unsubscribe(listener, list, msg->transaction) < 0) {
3658
                                        JANUS_LOG(LOG_ERR, "Error unsubscribing!\n");
3659
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3660
                                        g_snprintf(error_cause, 512, "Error unsubscribing!");
3661
                                        goto error;
3662
                                }
3663
                                janus_videoroom_message_free(msg);
3664
                                continue;
3665
                        } else if(!strcasecmp(request_text, "start")) {
3666
                                /* Start/restart receiving the publishers streams */
3667
                                /* TODO */
3668
                                event = json_object();
3669
                                json_object_set_new(event, "videoroom", json_string("event"));
3670
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3671
                                json_object_set_new(event, "started", json_string("ok"));
3672
                                //~ /* Send a FIR */
3673
                                //~ char buf[20];
3674
                                //~ memset(buf, 0, 20);
3675
                                //~ janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3676
                                //~ JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3677
                                //~ gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3678
                                //~ /* Send a PLI too, just in case... */
3679
                                //~ memset(buf, 0, 12);
3680
                                //~ janus_rtcp_pli((char *)&buf, 12);
3681
                                //~ JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3682
                                //~ gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3683
                        } else if(!strcasecmp(request_text, "pause")) {
3684
                                /* Stop receiving the publishers streams for a while */
3685
                                /* TODO */
3686
                                event = json_object();
3687
                                json_object_set_new(event, "videoroom", json_string("event"));
3688
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3689
                                json_object_set_new(event, "paused", json_string("ok"));
3690
                        } else if(!strcasecmp(request_text, "leave")) {
3691
                                /* TODO */
3692
                                event = json_object();
3693
                                json_object_set_new(event, "videoroom", json_string("event"));
3694
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3695
                                json_object_set_new(event, "left", json_string("ok"));
3696
                                session->started = FALSE;
3697
                        } else {
3698
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3699
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3700
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3701
                                goto error;
3702
                        }
3703
                }
3704

    
3705
                /* Prepare JSON event */
3706
                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3707
                /* Any SDP to handle? */
3708
                const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
3709
                const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
3710
                if(!msg_sdp) {
3711
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3712
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3713
                        json_decref(event);
3714
                } else {
3715
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
3716
                        const char *type = NULL;
3717
                        if(!strcasecmp(msg_sdp_type, "offer")) {
3718
                                /* We need to answer */
3719
                                type = "answer";
3720
                        } else if(!strcasecmp(msg_sdp_type, "answer")) {
3721
                                /* We got an answer (from a listener?), no need to negotiate */
3722
                                g_atomic_int_set(&session->hangingup, 0);
3723
                                int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event, NULL);
3724
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3725
                                json_decref(event);
3726
                                janus_videoroom_message_free(msg);
3727
                                continue;
3728
                        } else {
3729
                                /* TODO We don't support anything else right now... */
3730
                                JANUS_LOG(LOG_ERR, "Unknown SDP type '%s'\n", msg_sdp_type);
3731
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3732
                                g_snprintf(error_cause, 512, "Unknown SDP type '%s'", msg_sdp_type);
3733
                                goto error;
3734
                        }
3735
                        if(session->participant_type != janus_videoroom_p_type_publisher) {
3736
                                /* We shouldn't be here, we always offer ourselves */
3737
                                JANUS_LOG(LOG_ERR, "Only publishers send offers\n");
3738
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3739
                                g_snprintf(error_cause, 512, "Only publishers send offers");
3740
                                goto error;
3741
                        } else {
3742
                                /* This is a new publisher: is there room? */
3743
                                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3744
                                janus_videoroom *videoroom = participant->room;
3745
                                int count = 0;
3746
                                GHashTableIter iter;
3747
                                gpointer value;
3748
                                if(!videoroom) {
3749
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3750
                                        goto error;
3751
                                }
3752
                                if(videoroom->destroyed) {
3753
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3754
                                        goto error;
3755
                                }
3756
                                janus_mutex_lock(&videoroom->participants_mutex);
3757
                                g_hash_table_iter_init(&iter, videoroom->participants);
3758
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3759
                                        janus_videoroom_participant *p = value;
3760
                                        if(p != participant && p->sdp)
3761
                                                count++;
3762
                                }
3763
                                janus_mutex_unlock(&videoroom->participants_mutex);
3764
                                if(count == videoroom->max_publishers) {
3765
                                        participant->audio_active = FALSE;
3766
                                        participant->video_active = FALSE;
3767
                                        JANUS_LOG(LOG_ERR, "Maximum number of publishers (%d) already reached\n", videoroom->max_publishers);
3768
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3769
                                        g_snprintf(error_cause, 512, "Maximum number of publishers (%d) already reached", videoroom->max_publishers);
3770
                                        goto error;
3771
                                }
3772
                                /* Now prepare the SDP to give back */
3773
                                if(strstr(msg_sdp, "Mozilla")) {
3774
                                        participant->firefox = TRUE;
3775
                                }
3776
                                /* Which media are available? */
3777
                                int audio = 0, video = 0, data = 0;
3778
                                const char *audio_mode = NULL, *video_mode = NULL;
3779
                                gboolean audio_level_extmap = FALSE, video_orient_extmap = FALSE, playout_delay_extmap = FALSE;
3780
                                char error_str[100];
3781
                                janus_sdp *parsed_sdp = janus_sdp_parse(msg_sdp, error_str, sizeof(error_str));
3782
                                if(!parsed_sdp) {
3783
                                        /* Invalid SDP */
3784
                                        JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", error_str);
3785
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3786
                                        g_snprintf(error_cause, 512, "Error parsing SDP: %s", error_str);
3787
                                        goto error;
3788
                                }
3789
                                GList *temp = parsed_sdp->m_lines;
3790
                                while(temp) {
3791
                                        janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3792
                                        if(m->type == JANUS_SDP_AUDIO && m->port > 0) {
3793
                                                audio++;
3794
                                                participant->audio = TRUE;
3795
                                                if(audio > 1) {
3796
                                                        temp = temp->next;
3797
                                                        continue;
3798
                                                }
3799
                                        } else if(m->type == JANUS_SDP_VIDEO && m->port > 0) {
3800
                                                video++;
3801
                                                participant->video = TRUE;
3802
                                                if(video > 1) {
3803
                                                        temp = temp->next;
3804
                                                        continue;
3805
                                                }
3806
                                        } else if(m->type == JANUS_SDP_APPLICATION && m->port > 0) {
3807
                                                data++;
3808
                                                participant->data = TRUE;
3809
                                                if(data > 1) {
3810
                                                        temp = temp->next;
3811
                                                        continue;
3812
                                                }
3813
                                        }
3814
                                        if(m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO) {
3815
                                                /* What is the direction? */
3816
                                                switch(m->direction) {
3817
                                                        case JANUS_SDP_RECVONLY:
3818
                                                                /* If we're getting a 'recvonly' publisher, we're going to answer with 'inactive' */
3819
                                                        case JANUS_SDP_INACTIVE:
3820
                                                                if(m->type == JANUS_SDP_AUDIO) {
3821
                                                                        audio_mode = "inactive";
3822
                                                                } else {
3823
                                                                        video_mode = "inactive";
3824
                                                                }
3825
                                                                break;
3826
                                                        case JANUS_SDP_SENDONLY:
3827
                                                                /* What we expect, turn this into 'recvonly' */
3828
                                                        case JANUS_SDP_SENDRECV:
3829
                                                        default:
3830
                                                                if(m->type == JANUS_SDP_AUDIO) {
3831
                                                                        audio_mode = "recvonly";
3832
                                                                } else {
3833
                                                                        video_mode = "recvonly";
3834
                                                                }
3835
                                                                break;
3836
                                                }
3837
                                                /* Are the extmaps we care about there? */
3838
                                                GList *ma = m->attributes;
3839
                                                while(ma) {
3840
                                                        janus_sdp_attribute *a = (janus_sdp_attribute *)ma->data;
3841
                                                        if(a->value) {
3842
                                                                if(videoroom->audiolevel_ext && m->type == JANUS_SDP_AUDIO && strstr(a->value, JANUS_RTP_EXTMAP_AUDIO_LEVEL)) {
3843
                                                                        participant->audio_level_extmap_id = atoi(a->value);
3844
                                                                        audio_level_extmap = TRUE;
3845
                                                                } else if(videoroom->videoorient_ext && m->type == JANUS_SDP_VIDEO && strstr(a->value, JANUS_RTP_EXTMAP_VIDEO_ORIENTATION)) {
3846