Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videoroom.c @ 887df302

History | View | Annotate | Download (177 KB)

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

    
119
#include "plugin.h"
120

    
121
#include <jansson.h>
122
#include <sofia-sip/sdp.h>
123

    
124
#include "../debug.h"
125
#include "../apierror.h"
126
#include "../config.h"
127
#include "../mutex.h"
128
#include "../rtp.h"
129
#include "../rtcp.h"
130
#include "../record.h"
131
#include "../utils.h"
132
#include <sys/types.h>
133
#include <sys/socket.h>
134

    
135

    
136
/* Plugin information */
137
#define JANUS_VIDEOROOM_VERSION                        6
138
#define JANUS_VIDEOROOM_VERSION_STRING        "0.0.6"
139
#define JANUS_VIDEOROOM_DESCRIPTION                "This is a plugin implementing a videoconferencing SFU (Selective Forwarding Unit) for Janus, that is an audio/video router."
140
#define JANUS_VIDEOROOM_NAME                        "JANUS VideoRoom plugin"
141
#define JANUS_VIDEOROOM_AUTHOR                        "Meetecho s.r.l."
142
#define JANUS_VIDEOROOM_PACKAGE                        "janus.plugin.videoroom"
143

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

    
166
/* Plugin setup */
167
static janus_plugin janus_videoroom_plugin =
168
        JANUS_PLUGIN_INIT (
169
                .init = janus_videoroom_init,
170
                .destroy = janus_videoroom_destroy,
171

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

    
192
/* Plugin creator */
193
janus_plugin *create(void) {
194
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_VIDEOROOM_NAME);
195
        return &janus_videoroom_plugin;
196
}
197

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

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

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

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

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

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

    
313
        msg->handle = NULL;
314

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

    
325
        g_free(msg);
326
}
327

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

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

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

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

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

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

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

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

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

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

    
556

    
557
/* Error codes */
558
#define JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR                499
559
#define JANUS_VIDEOROOM_ERROR_NO_MESSAGE                421
560
#define JANUS_VIDEOROOM_ERROR_INVALID_JSON                422
561
#define JANUS_VIDEOROOM_ERROR_INVALID_REQUEST        423
562
#define JANUS_VIDEOROOM_ERROR_JOIN_FIRST                424
563
#define JANUS_VIDEOROOM_ERROR_ALREADY_JOINED        425
564
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM                426
565
#define JANUS_VIDEOROOM_ERROR_ROOM_EXISTS                427
566
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED                428
567
#define JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT        429
568
#define JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT        430
569
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE        431
570
#define JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL        432
571
#define JANUS_VIDEOROOM_ERROR_UNAUTHORIZED                433
572
#define JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED        434
573
#define JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED                435
574
#define JANUS_VIDEOROOM_ERROR_ID_EXISTS                        436
575
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP                437
576

    
577

    
578
/* Multiplexing helpers */
579
int janus_videoroom_muxed_subscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
580
int janus_videoroom_muxed_unsubscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
581
int janus_videoroom_muxed_offer(janus_videoroom_listener_muxed *muxed_listener, char *transaction, char *event_text);
582

    
583
static guint32 janus_rtp_forwarder_add_helper(janus_videoroom_participant *p, const gchar* host, int port, int is_video) {
584
        if(!p || !host) {
585
                return 0;
586
        }
587
        rtp_forwarder *forward = g_malloc0(sizeof(rtp_forwarder));
588
        forward->is_video = is_video;
589
        forward->serv_addr.sin_family = AF_INET;
590
        inet_pton(AF_INET, host, &(forward->serv_addr.sin_addr));
591
        forward->serv_addr.sin_port = htons(port);
592
        janus_mutex_lock(&p->rtp_forwarders_mutex);
593
        guint32 stream_id = g_random_int();
594
        while(g_hash_table_lookup(p->rtp_forwarders, GUINT_TO_POINTER(stream_id)) != NULL) {
595
                stream_id = g_random_int();
596
        }
597
        g_hash_table_insert(p->rtp_forwarders, GUINT_TO_POINTER(stream_id), forward);
598
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
599
        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);
600
        return stream_id;
601
}
602

    
603

    
604
/* Convenience function for freeing a session */
605
static void session_free(gpointer data) {
606
        if(data) {
607
                janus_videoroom_session* session = (janus_videoroom_session*)data;
608
                switch(session->participant_type) {
609
                case janus_videoroom_p_type_publisher: 
610
                        janus_videoroom_participant_free(session->participant);
611
                        break;   
612
                case janus_videoroom_p_type_subscriber:
613
                        janus_videoroom_listener_free(session->participant);
614
                        break;
615
                case janus_videoroom_p_type_subscriber_muxed:
616
                        janus_videoroom_muxed_listener_free(session->participant);
617
                        break;
618
                default:
619
                        break;
620
                }
621
                session->handle = NULL;
622
                g_free(session);
623
                session = NULL;
624
        }
625
}
626

    
627
static void janus_rtp_forwarder_free_helper(gpointer data) {
628
        if(data) {
629
                rtp_forwarder* forward = (rtp_forwarder*)data;
630
                if(forward) {
631
                        g_free(forward);
632
                        forward = NULL;
633
                }
634
        }
635
}
636

    
637
/* Convenience wrapper function for session_free that corresponds to GHRFunc() format for hash table cleanup */
638
static gboolean session_hash_table_remove(gpointer key, gpointer value, gpointer not_used) {
639
        if(value) {
640
                session_free(value);
641
        }
642
        return TRUE;
643
}
644

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

    
711

    
712
/* Plugin implementation */
713
int janus_videoroom_init(janus_callbacks *callback, const char *config_path) {
714
        if(g_atomic_int_get(&stopping)) {
715
                /* Still stopping from before */
716
                return -1;
717
        }
718
        if(callback == NULL || config_path == NULL) {
719
                /* Invalid arguments */
720
                return -1;
721
        }
722
        sdphome = su_home_new(sizeof(su_home_t));
723
        if(su_home_init(sdphome) < 0) {
724
                JANUS_LOG(LOG_FATAL, "Ops, error setting up sofia-sdp?\n");
725
                return -1;
726
        }
727

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

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

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

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

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

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

    
877
        g_atomic_int_set(&initialized, 1);
878

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

    
900
void janus_videoroom_destroy(void) {
901
        if(!g_atomic_int_get(&initialized))
902
                return;
903
        g_atomic_int_set(&stopping, 1);
904

    
905
        g_async_queue_push(messages, &exit_message);
906
        if(handler_thread != NULL) {
907
                g_thread_join(handler_thread);
908
                handler_thread = NULL;
909
        }
910
        if(watchdog != NULL) {
911
                g_thread_join(watchdog);
912
                watchdog = NULL;
913
        }
914
        su_home_deinit(sdphome);
915
        su_home_unref(sdphome);
916
        sdphome = NULL;
917

    
918
        /* FIXME We should destroy the sessions cleanly */
919
        janus_mutex_lock(&sessions_mutex);
920
        g_hash_table_foreach_remove(sessions, (GHRFunc)session_hash_table_remove, NULL);
921
        g_hash_table_destroy(sessions);
922
        sessions = NULL;
923
        janus_mutex_unlock(&sessions_mutex);
924

    
925
        janus_mutex_lock(&rooms_mutex);
926

    
927
        g_hash_table_destroy(rooms);
928
        rooms = NULL;
929
        janus_mutex_unlock(&rooms_mutex);
930
        janus_mutex_destroy(&rooms_mutex);
931

    
932
        g_async_queue_unref(messages);
933
        messages = NULL;
934

    
935
        janus_config_destroy(config);
936

    
937
        g_atomic_int_set(&initialized, 0);
938
        g_atomic_int_set(&stopping, 0);
939
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOROOM_NAME);
940
}
941

    
942
int janus_videoroom_get_api_compatibility(void) {
943
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
944
        return JANUS_PLUGIN_API_VERSION;
945
}
946

    
947
int janus_videoroom_get_version(void) {
948
        return JANUS_VIDEOROOM_VERSION;
949
}
950

    
951
const char *janus_videoroom_get_version_string(void) {
952
        return JANUS_VIDEOROOM_VERSION_STRING;
953
}
954

    
955
const char *janus_videoroom_get_description(void) {
956
        return JANUS_VIDEOROOM_DESCRIPTION;
957
}
958

    
959
const char *janus_videoroom_get_name(void) {
960
        return JANUS_VIDEOROOM_NAME;
961
}
962

    
963
const char *janus_videoroom_get_author(void) {
964
        return JANUS_VIDEOROOM_AUTHOR;
965
}
966

    
967
const char *janus_videoroom_get_package(void) {
968
        return JANUS_VIDEOROOM_PACKAGE;
969
}
970

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

    
992
        return;
993
}
994

    
995
void janus_videoroom_destroy_session(janus_plugin_session *handle, int *error) {
996
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
997
                *error = -1;
998
                return;
999
        }        
1000
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle; 
1001
        if(!session) {
1002
                JANUS_LOG(LOG_ERR, "No VideoRoom session associated with this handle...\n");
1003
                *error = -2;
1004
                return;
1005
        }
1006
        if(session->destroyed) {
1007
                JANUS_LOG(LOG_WARN, "VideoRoom session already marked as destroyed...\n");
1008
                return;
1009
        }
1010
        JANUS_LOG(LOG_VERB, "Removing VideoRoom session...\n");
1011
        /* Cleaning up and removing the session is done in a lazy way */
1012
        janus_mutex_lock(&sessions_mutex);
1013
        if(!session->destroyed) {
1014
                /* Any related WebRTC PeerConnection is not available anymore either */
1015
                janus_videoroom_hangup_media(handle);
1016
                session->destroyed = janus_get_monotonic_time();
1017
                old_sessions = g_list_append(old_sessions, session);
1018
                if(session->participant_type == janus_videoroom_p_type_publisher) {
1019
                        /* Get rid of publisher */
1020
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1021
                        participant->audio = FALSE;
1022
                        participant->video = FALSE;
1023
                        participant->data = FALSE;
1024
                        participant->audio_active = FALSE;
1025
                        participant->video_active = FALSE;
1026
                        participant->recording_active = FALSE;
1027
                        if(participant->recording_base)
1028
                                g_free(participant->recording_base);
1029
                        participant->recording_base = NULL;
1030
                        json_t *event = json_object();
1031
                        json_object_set_new(event, "videoroom", json_string("event"));
1032
                        json_object_set_new(event, "room", json_integer(participant->room->room_id));
1033
                        json_object_set_new(event, "leaving", json_integer(participant->user_id));
1034
                        char *leaving_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1035
                        json_decref(event);
1036
                        GHashTableIter iter;
1037
                        gpointer value;
1038
                        /* we need to check if the room still exists, may have been destroyed already */
1039
                        if(participant->room) {
1040
                                if(!participant->room->destroyed) {
1041
                                        janus_mutex_lock(&participant->room->participants_mutex);
1042
                                        g_hash_table_iter_init(&iter, participant->room->participants);
1043
                                        while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1044
                                                janus_videoroom_participant *p = value;
1045
                                                if(p == participant) {
1046
                                                        continue;        /* Skip the leaving publisher itself */
1047
                                                }
1048
                                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1049
                                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, leaving_text, NULL, NULL);
1050
                                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1051
                                        }
1052
                                        g_hash_table_remove(participant->room->participants, GUINT_TO_POINTER(participant->user_id));
1053
                                        janus_mutex_unlock(&participant->room->participants_mutex);
1054
                                }
1055
                        }
1056
                        g_free(leaving_text);
1057
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1058
                        /* Detaching this listener from its publisher is already done by hangup_media */
1059
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1060
                        /* Detaching this listener from its publishers is already done by hangup_media */
1061
                }
1062
        }
1063
        janus_mutex_unlock(&sessions_mutex);
1064

    
1065
        return;
1066
}
1067

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

    
1136
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
1137
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1138
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
1139
        
1140
        /* Pre-parse the message */
1141
        int error_code = 0;
1142
        char error_cause[512];
1143
        json_t *root = NULL;
1144
        json_t *response = NULL;
1145

    
1146
        if(message == NULL) {
1147
                JANUS_LOG(LOG_ERR, "No message??\n");
1148
                error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
1149
                g_snprintf(error_cause, 512, "%s", "No message??");
1150
                goto error;
1151
        }
1152
        JANUS_LOG(LOG_VERB, "Handling message: %s\n", message);
1153

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

    
1669
                guint64 room_id = json_integer_value(room);
1670
                guint64 publisher_id = json_integer_value(pub_id);
1671
                guint32 stream_id = json_integer_value(id);
1672
                janus_mutex_lock(&rooms_mutex);
1673
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
1674
                if(videoroom == NULL) {
1675
                        janus_mutex_unlock(&rooms_mutex);
1676
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1677
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1678
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1679
                        goto error;
1680
                }
1681
                if(videoroom->destroyed) {
1682
                        janus_mutex_unlock(&rooms_mutex)
1683
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", videoroom->room_id);
1684
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1685
                        g_snprintf(error_cause, 512, "Videoroom (%"SCNu64")", videoroom->room_id);
1686
                        goto error;
1687
                }
1688
                if(videoroom->room_secret) {
1689
                        /* A secret is required for this action */
1690
                        JANUS_VALIDATE_JSON_OBJECT(root, secret_parameters,
1691
                                error_code, error_cause, TRUE,
1692
                                JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1693
                        if(error_code != 0) {
1694
                                janus_mutex_unlock(&rooms_mutex);
1695
                                goto error;
1696
                        }
1697
                        json_t *secret = json_object_get(root, "secret");
1698
                        if(!janus_strcmp_const_time(videoroom->room_secret, json_string_value(secret))) {
1699
                                janus_mutex_unlock(&rooms_mutex);
1700
                                JANUS_LOG(LOG_ERR, "Unauthorized (wrong secret)\n");
1701
                                error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
1702
                                g_snprintf(error_cause, 512, "Unauthorized (wrong secret)");
1703
                                goto error;
1704
                        }
1705
                }
1706
                janus_mutex_unlock(&rooms_mutex);
1707
                janus_mutex_lock(&videoroom->participants_mutex);
1708
                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(publisher_id));
1709
                if(publisher == NULL) {
1710
                        janus_mutex_unlock(&videoroom->participants_mutex);
1711
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1712
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1713
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1714
                        goto error;
1715
                }
1716
                janus_mutex_lock(&publisher->rtp_forwarders_mutex);
1717
                if(g_hash_table_lookup(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id)) == NULL) {
1718
                        janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1719
                        janus_mutex_unlock(&videoroom->participants_mutex);
1720
                        JANUS_LOG(LOG_ERR, "No such stream (%"SCNu32")\n", stream_id);
1721
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1722
                        g_snprintf(error_cause, 512, "No such stream (%"SCNu32")", stream_id);
1723
                        goto error;
1724
                }
1725
                g_hash_table_remove(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id));
1726
                janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1727
                janus_mutex_unlock(&videoroom->participants_mutex);
1728
                response = json_object();
1729
                json_object_set_new(response, "videoroom", json_string("stop_rtp_forward"));
1730
                json_object_set_new(response, "room", json_integer(room_id));
1731
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1732
                json_object_set_new(response, "stream_id", json_integer(stream_id));
1733
                goto plugin_response;
1734
        } else if(!strcasecmp(request_text, "exists")) {
1735
                /* Check whether a given room exists or not, returns true/false */        
1736
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
1737
                        error_code, error_cause, TRUE,
1738
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1739
                if(error_code != 0)
1740
                        goto error;
1741
                json_t *room = json_object_get(root, "room");
1742
                guint64 room_id = json_integer_value(room);
1743
                janus_mutex_lock(&rooms_mutex);
1744
                gboolean room_exists = g_hash_table_contains(rooms, GUINT_TO_POINTER(room_id));
1745
                janus_mutex_unlock(&rooms_mutex);
1746
                response = json_object();
1747
                json_object_set_new(response, "videoroom", json_string("success"));
1748
                json_object_set_new(response, "room", json_integer(room_id));
1749
                json_object_set_new(response, "exists", json_string(room_exists ? "true" : "false"));
1750
                goto plugin_response;
1751
        } else if(!strcasecmp(request_text, "listparticipants")) {
1752
                /* List all participants in a room, specifying whether they're publishers or just attendees */        
1753
                JANUS_VALIDATE_JSON_OBJECT(root, room_parameters,
1754
                        error_code, error_cause, TRUE,
1755
                        JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT, JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT);
1756
                if(error_code != 0)
1757
                        goto error;
1758
                json_t *room = json_object_get(root, "room");
1759
                guint64 room_id = json_integer_value(room);
1760
                janus_mutex_lock(&rooms_mutex);
1761
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
1762
                janus_mutex_unlock(&rooms_mutex);
1763
                if(videoroom == NULL) {
1764
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1765
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1766
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1767
                        goto error;
1768
                }
1769
                if(videoroom->destroyed) {
1770
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1771
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1772
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1773
                        goto error;
1774
                }
1775
                /* Return a list of all participants (whether they're publishing or not) */
1776
                json_t *list = json_array();
1777
                GHashTableIter iter;
1778
                gpointer value;
1779
                janus_mutex_lock(&videoroom->participants_mutex);
1780
                g_hash_table_iter_init(&iter, videoroom->participants);
1781
                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1782
                        janus_videoroom_participant *p = value;
1783
                        json_t *pl = json_object();
1784
                        json_object_set_new(pl, "id", json_integer(p->user_id));
1785
                        if(p->display)
1786
                                json_object_set_new(pl, "display", json_string(p->display));
1787
                        json_object_set_new(pl, "publisher", json_string(p->sdp ? "true" : "false"));
1788
                        json_array_append_new(list, pl);
1789
                }
1790
                janus_mutex_unlock(&videoroom->participants_mutex);
1791
                response = json_object();
1792
                json_object_set_new(response, "videoroom", json_string("participants"));
1793
                json_object_set_new(response, "room", json_integer(room_id));
1794
                json_object_set_new(response, "participants", list);
1795
                goto plugin_response;
1796
        } else if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")
1797
                        || !strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish") || !strcasecmp(request_text, "unpublish")
1798
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "pause") || !strcasecmp(request_text, "switch") || !strcasecmp(request_text, "stop")
1799
                        || !strcasecmp(request_text, "add") || !strcasecmp(request_text, "remove") || !strcasecmp(request_text, "leave")) {
1800
                /* These messages are handled asynchronously */
1801

    
1802
                janus_videoroom_message *msg = g_malloc0(sizeof(janus_videoroom_message));
1803
                if(msg == NULL) {
1804
                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
1805
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1806
                        g_snprintf(error_cause, 512, "Memory error");
1807
                        goto error;
1808
                }
1809

    
1810
                g_free(message);
1811
                msg->handle = handle;
1812
                msg->transaction = transaction;
1813
                msg->message = root;
1814
                msg->sdp_type = sdp_type;
1815
                msg->sdp = sdp;
1816
                g_async_queue_push(messages, msg);
1817

    
1818
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
1819
        } else {
1820
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
1821
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
1822
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
1823
                goto error;
1824
        }
1825

    
1826
plugin_response:
1827
                {
1828
                        if (!response) {
1829
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1830
                                g_snprintf(error_cause, 512, "Invalid response");
1831
                                goto error;
1832
                        }
1833
                        if(root != NULL)
1834
                                json_decref(root);
1835
                        g_free(transaction);
1836
                        g_free(message);
1837
                        g_free(sdp_type);
1838
                        g_free(sdp);
1839

    
1840
                        char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1841
                        json_decref(response);
1842
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
1843
                        g_free(response_text);
1844
                        return result;
1845
                }
1846

    
1847
error:
1848
                {
1849
                        if(root != NULL)
1850
                                json_decref(root);
1851
                        g_free(transaction);
1852
                        g_free(message);
1853
                        g_free(sdp_type);
1854
                        g_free(sdp);
1855

    
1856
                        /* Prepare JSON error event */
1857
                        json_t *event = json_object();
1858
                        json_object_set_new(event, "videoroom", json_string("event"));
1859
                        json_object_set_new(event, "error_code", json_integer(error_code));
1860
                        json_object_set_new(event, "error", json_string(error_cause));
1861
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1862
                        json_decref(event);
1863
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, event_text);
1864
                        g_free(event_text);
1865
                        return result;
1866
                }
1867

    
1868
}
1869

    
1870
void janus_videoroom_setup_media(janus_plugin_session *handle) {
1871
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
1872
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1873
                return;
1874
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1875
        if(!session) {
1876
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1877
                return;
1878
        }
1879
        if(session->destroyed)
1880
                return;
1881
        g_atomic_int_set(&session->hangingup, 0);
1882
        /* Media relaying can start now */
1883
        session->started = TRUE;
1884
        /* If this is a listener, ask the publisher a FIR */
1885
        if(session->participant) {
1886
                if(session->participant_type == janus_videoroom_p_type_subscriber) {
1887
                        janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
1888
                        if(l && l->feed) {
1889
                                janus_videoroom_participant *p = l->feed;
1890
                                if(p && p->session) {
1891
                                        /* Send a FIR */
1892
                                        char buf[20];
1893
                                        memset(buf, 0, 20);
1894
                                        janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
1895
                                        JANUS_LOG(LOG_VERB, "New listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1896
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 20);
1897
                                        /* Send a PLI too, just in case... */
1898
                                        memset(buf, 0, 12);
1899
                                        janus_rtcp_pli((char *)&buf, 12);
1900
                                        JANUS_LOG(LOG_VERB, "New listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1901
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 12);
1902
                                }
1903
                        }
1904
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1905
                        /* Do the same, but for all feeds */
1906
                        janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
1907
                        if(listener == NULL)
1908
                                return;
1909
                        GSList *ps = listener->listeners;
1910
                        while(ps) {
1911
                                janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
1912
                                if(l && l->feed) {
1913
                                        janus_videoroom_participant *p = l->feed;
1914
                                        if(p && p->session) {
1915
                                                /* Send a FIR */
1916
                                                char buf[20];
1917
                                                memset(buf, 0, 20);
1918
                                                janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
1919
                                                JANUS_LOG(LOG_VERB, "New Multiplexed listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1920
                                                gateway->relay_rtcp(p->session->handle, 1, buf, 20);
1921
                                                /* Send a PLI too, just in case... */
1922
                                                memset(buf, 0, 12);
1923
                                                janus_rtcp_pli((char *)&buf, 12);
1924
                                                JANUS_LOG(LOG_VERB, "New Multiplexed listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1925
                                                gateway->relay_rtcp(p->session->handle, 1, buf, 12);
1926
                                        }
1927
                                }
1928
                                ps = ps->next;
1929
                        }
1930
                }
1931
        }
1932
}
1933

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

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

    
2073
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len) {
2074
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
2075
                return;
2076
        if(buf == NULL || len <= 0)
2077
                return;
2078
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
2079
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
2080
                return;
2081
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2082
        /* Get a string out of the data */
2083
        char *text = g_malloc0(len+1);
2084
        memcpy(text, buf, len);
2085
        *(text+len) = '\0';
2086
        JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
2087
        g_slist_foreach(participant->listeners, janus_videoroom_relay_data_packet, text);
2088
        g_free(text);
2089
}
2090

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

    
2143
void janus_videoroom_hangup_media(janus_plugin_session *handle) {
2144
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
2145
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
2146
                return;
2147
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
2148
        if(!session) {
2149
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2150
                return;
2151
        }
2152
        session->started = FALSE;
2153
        if(session->destroyed)
2154
                return;
2155
        if(g_atomic_int_add(&session->hangingup, 1))
2156
                return;
2157
        /* Send an event to the browser and tell the PeerConnection is over */
2158
        if(session->participant_type == janus_videoroom_p_type_publisher) {
2159
                /* This publisher just 'unpublished' */
2160
                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2161
                if(participant->sdp)
2162
                        g_free(participant->sdp);
2163
                participant->sdp = NULL;
2164
                participant->firefox = FALSE;
2165
                participant->audio_active = FALSE;
2166
                participant->video_active = FALSE;
2167
                participant->remb_startup = 4;
2168
                participant->remb_latest = 0;
2169
                participant->fir_latest = 0;
2170
                participant->fir_seq = 0;
2171
                /* Get rid of the recorders, if available */
2172
                if(participant->arc) {
2173
                        janus_recorder_close(participant->arc);
2174
                        JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", participant->arc->filename ? participant->arc->filename : "??");
2175
                        janus_recorder_free(participant->arc);
2176
                }
2177
                participant->arc = NULL;
2178
                if(participant->vrc) {
2179
                        janus_recorder_close(participant->vrc);
2180
                        JANUS_LOG(LOG_INFO, "Closed video recording %s\n", participant->vrc->filename ? participant->vrc->filename : "??");
2181
                        janus_recorder_free(participant->vrc);
2182
                }
2183
                participant->vrc = NULL;
2184
                janus_mutex_lock(&participant->listeners_mutex);
2185
                while(participant->listeners) {
2186
                        janus_videoroom_listener *l = (janus_videoroom_listener *)participant->listeners->data;
2187
                        if(l) {
2188
                                participant->listeners = g_slist_remove(participant->listeners, l);
2189
                                l->feed = NULL;
2190
                        }
2191
                }
2192
                janus_mutex_unlock(&participant->listeners_mutex);
2193
                json_t *event = json_object();
2194
                json_object_set_new(event, "videoroom", json_string("event"));
2195
                json_object_set_new(event, "room", json_integer(participant->room->room_id));
2196
                json_object_set_new(event, "unpublished", json_integer(participant->user_id));
2197
                char *unpub_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2198
                json_decref(event);
2199
                GHashTableIter iter;
2200
                gpointer value;
2201
                if(participant && participant->room) {
2202
                        if(!participant->room->destroyed) {
2203
                                janus_mutex_lock(&participant->room->participants_mutex);
2204
                                g_hash_table_iter_init(&iter, participant->room->participants);
2205
                                while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2206
                                        janus_videoroom_participant *p = value;
2207
                                        if(p && p->session && p != participant) {
2208
                                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2209
                                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, unpub_text, NULL, NULL);
2210
                                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2211
                                        }
2212
                                }
2213
                                janus_mutex_unlock(&participant->room->participants_mutex);
2214
                        }
2215
                }
2216
                g_free(unpub_text);
2217
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2218
                /* Get rid of listener */
2219
                janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2220
                if(listener) {
2221
                        listener->paused = TRUE;
2222
                        janus_videoroom_participant *publisher = listener->feed;
2223
                        if(publisher != NULL) {
2224
                                janus_mutex_lock(&publisher->listeners_mutex);
2225
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
2226
                                janus_mutex_unlock(&publisher->listeners_mutex);
2227
                                listener->feed = NULL;
2228
                        }
2229
                }
2230
                /* TODO Should we close the handle as well? */
2231
        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
2232
                /* Do the same, but for all sub-listener */
2233
                janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
2234
                GSList *ps = listener->listeners;
2235
                while(ps) {
2236
                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
2237
                        if(l) {
2238
                                l->paused = TRUE;
2239
                                janus_videoroom_participant *publisher = l->feed;
2240
                                if(publisher != NULL) {
2241
                                        janus_mutex_lock(&publisher->listeners_mutex);
2242
                                        publisher->listeners = g_slist_remove(publisher->listeners, l);
2243
                                        janus_mutex_unlock(&publisher->listeners_mutex);
2244
                                        l->feed = NULL;
2245
                                }
2246
                        }
2247
                        /* TODO Should we close the handle as well? */
2248
                        ps = ps->next;
2249
                }
2250
                /* TODO Should we close the handle as well? */
2251
        }
2252
}
2253

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

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

    
3536
                                char *newsdp = g_strdup(sdp);
3537
                                if(video && b == 0) {
3538
                                        /* Remove useless bandwidth attribute */
3539
                                        newsdp = janus_string_replace(newsdp, "b=AS:0\r\n", "");
3540
                                }
3541
                                /* Is this room recorded? */
3542
                                if(videoroom->record || participant->recording_active) {
3543
                                        char filename[255];
3544
                                        gint64 now = janus_get_real_time();
3545
                                        if(audio) {
3546
                                                memset(filename, 0, 255);
3547
                                                if(participant->recording_base) {
3548
                                                        /* Use the filename and path we have been provided */
3549
                                                        g_snprintf(filename, 255, "%s-audio", participant->recording_base);
3550
                                                        participant->arc = janus_recorder_create(videoroom->rec_dir, 0, filename);
3551
                                                        if(participant->arc == NULL) {
3552
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
3553
                                                        }
3554
                                                } else {
3555
                                                        /* Build a filename */
3556
                                                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-audio",
3557
                                                                videoroom->room_id, participant->user_id, now);
3558
                                                        participant->arc = janus_recorder_create(videoroom->rec_dir, 0, filename);
3559
                                                        if(participant->arc == NULL) {
3560
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
3561
                                                        }
3562
                                                }
3563
                                        }
3564
                                        if(video) {
3565
                                                memset(filename, 0, 255);
3566
                                                if(participant->recording_base) {
3567
                                                        /* Use the filename and path we have been provided */
3568
                                                        g_snprintf(filename, 255, "%s-video", participant->recording_base);
3569
                                                        participant->vrc = janus_recorder_create(videoroom->rec_dir, 1, filename);
3570
                                                        if(participant->vrc == NULL) {
3571
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
3572
                                                        }
3573
                                                } else {
3574
                                                        /* Build a filename */
3575
                                                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-video",
3576
                                                                videoroom->room_id, participant->user_id, now);
3577
                                                        participant->vrc = janus_recorder_create(videoroom->rec_dir, 1, filename);
3578
                                                        if(participant->vrc == NULL) {
3579
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
3580
                                                        }
3581
                                                }
3582
                                        }
3583
                                }
3584

    
3585
                                JANUS_LOG(LOG_VERB, "Handling publisher: turned this into an '%s':\n%s\n", type, newsdp);
3586
                                /* How long will the gateway take to push the event? */
3587
                                g_atomic_int_set(&session->hangingup, 0);
3588
                                gint64 start = janus_get_monotonic_time();
3589
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, type, newsdp);
3590
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3591

    
3592
                                /* Now turn the SDP into what we'll send subscribers, using the static payload types for making switching easier */
3593
                                if(audio) {
3594
                                        switch(videoroom->acodec) {
3595
                                                case JANUS_VIDEOROOM_OPUS:
3596
                                                        if(opus_pt < 0) {
3597
                                                                audio_mline[0] = '\0';
3598
                                                        } else {
3599
                                                                g_snprintf(audio_mline, 256, sdp_a_template_opus,
3600
                                                                        OPUS_PT,                                                /* Opus payload type */
3601
                                                                        /* Subscribers gets a sendonly or inactive back */
3602
                                                                        strcmp(audio_mode, "inactive") ? "sendonly" : "inactive",
3603
                                                                        OPUS_PT);                                                 /* Opus payload type */
3604
                                                        }
3605
                                                        break;
3606
                                                case JANUS_VIDEOROOM_ISAC_32K:
3607
                                                        if(isac32_pt < 0 ) {
3608
                                                                JANUS_LOG(LOG_WARN, "Videoroom is forcing ISAC 32K, but publisher didn't offer any... rejecting audio\n");
3609
                                                                g_snprintf(audio_mline, 256, "m=audio 104 RTP/SAVPF 0\r\n");
3610
                                                        } else {
3611
                                                                g_snprintf(audio_mline, 256, sdp_a_template_isac32,
3612
                                                                        ISAC32_PT,                                                /* ISAC 32K payload type */
3613
                                                                        /* Subscribers gets a sendonly or inactive back */
3614
                                                                        strcmp(audio_mode, "inactive") ? "sendonly" : "inactive",
3615
                                                                        ISAC32_PT);                                                /* ISAC 32K payload type */
3616
                                                        }
3617
                                                        break;
3618
                                                case JANUS_VIDEOROOM_ISAC_16K:
3619
                                                        if(isac16_pt < 0) {
3620
                                                                JANUS_LOG(LOG_WARN, "Videoroom is forcing ISAC 16K, but publisher didn't offer any... rejecting audio\n");
3621
                                                                g_snprintf(audio_mline, 256, "m=audio 103 RTP/SAVPF 0\r\n");
3622
                                                        } else {
3623
                                                                g_snprintf(audio_mline, 256, sdp_a_template_isac16,
3624
                                                                        ISAC16_PT,                                                /* ISAC 16K payload type */
3625
                                                                        /* Subscribers gets a sendonly or inactive back */
3626
                                                                        strcmp(audio_mode, "inactive") ? "sendonly" : "inactive",
3627
                                                                        ISAC16_PT);                                                /* ISAC 16K payload type */
3628
                                                        }
3629
                                                        break;
3630
                                                case JANUS_VIDEOROOM_PCMU:
3631
                                                        if(pcmu_pt < 0) {
3632
                                                                JANUS_LOG(LOG_WARN, "Videoroom is forcing PCMU, but publisher didn't offer any... rejecting audio\n");
3633
                                                                g_snprintf(audio_mline, 256, "m=audio 0 RTP/SAVPF 0\r\n");
3634
                                                        } else {
3635
                                                                g_snprintf(audio_mline, 256, sdp_a_template_pcmu,
3636
                                                                        PCMU_PT,                                                /*PCMU payload type */
3637
                                                                        /* Subscribers gets a sendonly or inactive back */
3638
                                                                        strcmp(audio_mode, "inactive") ? "sendonly" : "inactive",
3639
                                                                        PCMU_PT);                                                 /*PCMU   payload type */
3640
                                                        }
3641
                                                        break;
3642
                                                case JANUS_VIDEOROOM_PCMA:
3643
                                                        if(pcma_pt < 0) {
3644
                                                                JANUS_LOG(LOG_WARN, "Videoroom is forcing PCMA, but publisher didn't offer any... rejecting audio\n");
3645
                                                                g_snprintf(audio_mline, 256, "m=audio 0 RTP/SAVPF 0\r\n");
3646
                                                        } else {
3647
                                                                g_snprintf(audio_mline, 256, sdp_a_template_pcma,
3648
                                                                        PCMA_PT,                                                /*PCMA payload type */
3649
                                                                        /* Subscribers gets a sendonly or inactive back */
3650
                                                                        strcmp(audio_mode, "inactive") ? "sendonly" : "inactive",
3651
                                                                        PCMA_PT);                                                 /*PCMA   payload type */
3652
                                                        }
3653
                                                        break;
3654
                                                default:
3655
                                                        /* Shouldn't happen */
3656
                                                        break;
3657
                                                }
3658
                                } else {
3659
                                        audio_mline[0] = '\0';
3660
                                }
3661
                                if(video) {
3662
                                        switch(videoroom->vcodec) {
3663
                                                case JANUS_VIDEOROOM_VP8:
3664
                                                        if(vp8_pt < 0) {
3665
                                                                video_mline[0] = '\0';
3666
                                                        } else {
3667
                                                                g_snprintf(video_mline, 512, sdp_v_template_vp8,
3668
                                                                        VP8_PT,                                                        /* VP8 payload type */
3669
                                                                        b,                                                                /* Bandwidth */
3670
                                                                        /* Subscribers gets a sendonly or inactive back */
3671
                                                                        strcmp(video_mode, "inactive") ? "sendonly" : "inactive",
3672
                                                                        VP8_PT,                                                 /* VP8 payload type */
3673
                                                                        VP8_PT,                                                 /* VP8 payload type */
3674
                                                                        VP8_PT,                                                 /* VP8 payload type */
3675
                                                                        VP8_PT,                                                 /* VP8 payload type */
3676
                                                                        VP8_PT);                                                 /* VP8 payload type */
3677
                                                        }
3678
                                                        break;
3679
                                                case JANUS_VIDEOROOM_VP9:
3680
                                                        if(vp9_pt < 0) {
3681
                                                                JANUS_LOG(LOG_WARN, "Videoroom is forcing VP8, but publisher didn't offer any... rejecting video\n");
3682
                                                                g_snprintf(video_mline, 512, "m=video 0 RTP/SAVPF 0\r\n");
3683
                                                        } else {
3684
                                                                g_snprintf(video_mline, 512, sdp_v_template_vp9,
3685
                                                                        VP9_PT,                                                        /* VP9 payload type */
3686
                                                                        b,                                                                /* Bandwidth */
3687
                                                                        /* Subscribers gets a sendonly or inactive back */
3688
                                                                        strcmp(video_mode, "inactive") ? "sendonly" : "inactive",
3689
                                                                        VP9_PT,                                                 /* VP9 payload type */
3690
                                                                        VP9_PT,                                                 /* VP9 payload type */
3691
                                                                        VP9_PT,                                                 /* VP9 payload type */
3692
                                                                        VP9_PT,                                                 /* VP9 payload type */
3693
                                                                        VP9_PT);                                                 /* VP9 payload type */
3694
                                                        }
3695
                                                        break;
3696
                                                case JANUS_VIDEOROOM_H264:
3697
                                                        if(h264_pt < 0) {
3698
                                                                JANUS_LOG(LOG_WARN, "Videoroom is forcing VP8, but publisher didn't offer any... rejecting video\n");
3699
                                                                g_snprintf(video_mline, 512, "m=video 0 RTP/SAVPF 0\r\n");
3700
                                                        } else {
3701
                                                                g_snprintf(video_mline, 512, sdp_v_template_h264,
3702
                                                                        H264_PT,                                                /* H264 payload type */
3703
                                                                        b,                                                                /* Bandwidth */
3704
                                                                        /* Subscribers gets a sendonly or inactive back */
3705
                                                                        strcmp(video_mode, "inactive") ? "sendonly" : "inactive",
3706
                                                                        H264_PT,                                                 /* H264 payload type */
3707
                                                                        H264_PT,                                                 /* H264 payload type */
3708
                                                                        H264_PT,                                                 /* H264 payload type */
3709
                                                                        H264_PT,                                                 /* H264 payload type */
3710
                                                                        H264_PT,                                                 /* H264 payload type */
3711
                                                                        H264_PT);                                                 /* H264 payload type */
3712
                                                        }
3713
                                                        break;
3714
                                                default:
3715
                                                        /* Shouldn't happen */
3716
                                                        break;
3717
                                        }
3718
                                } else {
3719
                                        video_mline[0] = '\0';
3720
                                }
3721
                                if(data) {
3722
                                        g_snprintf(data_mline, 256, sdp_d_template);
3723
                                } else {
3724
                                        data_mline[0] = '\0';
3725
                                }
3726
                                g_snprintf(sdp, 1280, sdp_template,
3727
                                        janus_get_real_time(),                        /* We need current time here */
3728
                                        janus_get_real_time(),                        /* We need current time here */
3729
                                        participant->room->room_name,        /* Video room name */
3730
                                        audio_mline,                                        /* Audio m-line, if any */
3731
                                        video_mline,                                        /* Video m-line, if any */
3732
                                        data_mline);                                        /* Data channel m-line, if any */
3733
                                g_free(newsdp);
3734
                                newsdp = g_strdup(sdp);
3735
                                if(video && b == 0) {
3736
                                        /* Remove useless bandwidth attribute */
3737
                                        newsdp = janus_string_replace(newsdp, "b=AS:0\r\n", "");
3738
                                }
3739

    
3740
                                /* Done */
3741
                                if(res != JANUS_OK) {
3742
                                        /* TODO Failed to negotiate? We should remove this publisher */
3743
                                } else {
3744
                                        /* Store the participant's SDP for interested listeners */
3745
                                        participant->sdp = newsdp;
3746
                                        /* Notify all other participants that there's a new boy in town */
3747
                                        json_t *list = json_array();
3748
                                        json_t *pl = json_object();
3749
                                        json_object_set_new(pl, "id", json_integer(participant->user_id));
3750
                                        if(participant->display)
3751
                                                json_object_set_new(pl, "display", json_string(participant->display));
3752
                                        json_array_append_new(list, pl);
3753
                                        json_t *pub = json_object();
3754
                                        json_object_set_new(pub, "videoroom", json_string("event"));
3755
                                        json_object_set_new(pub, "room", json_integer(participant->room->room_id));
3756
                                        json_object_set_new(pub, "publishers", list);
3757
                                        char *pub_text = json_dumps(pub, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3758
                                        json_decref(pub);
3759
                                        GHashTableIter iter;
3760
                                        gpointer value;
3761
                                        janus_mutex_lock(&videoroom->participants_mutex);
3762
                                        g_hash_table_iter_init(&iter, videoroom->participants);
3763
                                        while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3764
                                                janus_videoroom_participant *p = value;
3765
                                                if(p == participant) {
3766
                                                        continue;        /* Skip the new publisher itself */
3767
                                                }
3768
                                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
3769
                                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, pub_text, NULL, NULL);
3770
                                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3771
                                        }
3772
                                        g_free(pub_text);
3773
                                        janus_mutex_unlock(&videoroom->participants_mutex);
3774
                                        /* Let's wait for the setup_media event */
3775
                                }
3776
                        }
3777
                }
3778
                g_free(event_text);
3779
                janus_videoroom_message_free(msg);
3780

    
3781
                continue;
3782
                
3783
error:
3784
                {
3785
                        /* Prepare JSON error event */
3786
                        json_t *event = json_object();
3787
                        json_object_set_new(event, "videoroom", json_string("event"));
3788
                        json_object_set_new(event, "error_code", json_integer(error_code));
3789
                        json_object_set_new(event, "error", json_string(error_cause));
3790
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3791
                        json_decref(event);
3792
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
3793
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, NULL, NULL);
3794
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3795
                        g_free(event_text);
3796
                        janus_videoroom_message_free(msg);
3797
                }
3798
        }
3799
        JANUS_LOG(LOG_VERB, "Leaving VideoRoom handler thread\n");