Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videoroom.c @ 18943780

History | View | Annotate | Download (161 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 = <password needed for manipulating (e.g. destroying) the room>
60
publishers = <max number of concurrent senders> (e.g., 6 for a video
61
             conference or 1 for a webinar)
62
bitrate = <max video bitrate for senders> (e.g., 128000)
63
fir_freq = <send a FIR to publishers every fir_freq seconds> (0=disable)
64
record = true|false (whether this room should be recorded, default=false)
65
rec_dir = <folder where recordings should be stored, when enabled>
66
\endverbatim
67
 *
68
 * \section sfuapi Video Room API
69
 * 
70
 * The Video Room API supports several requests, some of which are
71
 * synchronous and some asynchronous. There are some situations, though,
72
 * (invalid JSON, invalid request) which will always result in a
73
 * synchronous error response even for asynchronous requests. 
74
 * 
75
 * \c create , \c destroy , \c exists, \c list and \c listparticipants
76
 * are synchronous requests, which means you'll
77
 * get a response directly within the context of the transaction.
78
 * \c create allows you to create a new video room dynamically, as an
79
 * alternative to using the configuration file; \c destroy removes a
80
 * video room and destroys it, kicking all the users out as part of the
81
 * process; \c exists allows you to check whether a specific video room
82
 * exists; finally, \c list lists all the available rooms, while \c
83
 * listparticipants lists all the participants of a specific room and
84
 * their details.
85
 * 
86
 * The \c join , \c joinandconfigure , \c configure , \c publish ,
87
 * \c unpublish , \c start , \c pause , \c switch , \c stop , \c add ,
88
 * \c remove and \c leave requests instead are all asynchronous, which
89
 * means you'll get a notification about their success or failure in
90
 * an event. \c join allows you to join a specific video room, specifying
91
 * whether that specific PeerConnection will be used for publishing or
92
 * watching; \c configure can be used to modify some of the participation
93
 * settings (e.g., bitrate cap); \c joinandconfigure combines the previous
94
 * two requests in a single one (just for publishers); \c publish can be
95
 * used to start sending media to broadcast to the other participants,
96
 * while \c unpublish does the opposite; \c start allows you to start
97
 * receiving media from a publisher you've subscribed to previously by
98
 * means of a \c join , while \c pause pauses the delivery of the media;
99
 * the \c switch request can be used to change the source of the media
100
 * flowing over a specific PeerConnection (e.g., I was watching Alice,
101
 * I want to watch Bob now) without having to create a new handle for
102
 * that; \c stop interrupts a viewer instance; \c add and \c remove
103
 * are just used when involving "Plan B", and are used to add or remove
104
 * publishers to be muxed in the single viewer PeerConnection; finally,
105
 * \c leave allows you to leave a video room for good.
106
 * 
107
 * Actual API docs: TBD.
108
 * 
109
 * \ingroup plugins
110
 * \ref plugins
111
 */
112

    
113
#include "plugin.h"
114

    
115
#include <jansson.h>
116
#include <sofia-sip/sdp.h>
117

    
118
#include "../debug.h"
119
#include "../apierror.h"
120
#include "../config.h"
121
#include "../mutex.h"
122
#include "../rtp.h"
123
#include "../rtcp.h"
124
#include "../record.h"
125
#include "../utils.h"
126
#include <sys/types.h>
127
#include <sys/socket.h>
128

    
129

    
130
/* Plugin information */
131
#define JANUS_VIDEOROOM_VERSION                        6
132
#define JANUS_VIDEOROOM_VERSION_STRING        "0.0.6"
133
#define JANUS_VIDEOROOM_DESCRIPTION                "This is a plugin implementing a videoconferencing SFU (Selective Forwarding Unit) for Janus, that is an audio/video router."
134
#define JANUS_VIDEOROOM_NAME                        "JANUS VideoRoom plugin"
135
#define JANUS_VIDEOROOM_AUTHOR                        "Meetecho s.r.l."
136
#define JANUS_VIDEOROOM_PACKAGE                        "janus.plugin.videoroom"
137

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

    
160
/* Plugin setup */
161
static janus_plugin janus_videoroom_plugin =
162
        JANUS_PLUGIN_INIT (
163
                .init = janus_videoroom_init,
164
                .destroy = janus_videoroom_destroy,
165

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

    
186
/* Plugin creator */
187
janus_plugin *create(void) {
188
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_VIDEOROOM_NAME);
189
        return &janus_videoroom_plugin;
190
}
191

    
192

    
193
/* Useful stuff */
194
static volatile gint initialized = 0, stopping = 0;
195
static janus_callbacks *gateway = NULL;
196
static GThread *handler_thread;
197
static GThread *watchdog;
198
static su_home_t *sdphome = NULL;
199
static void *janus_videoroom_handler(void *data);
200
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data);
201
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data);
202

    
203
typedef enum janus_videoroom_p_type {
204
        janus_videoroom_p_type_none = 0,
205
        janus_videoroom_p_type_subscriber,                        /* Generic listener/subscriber */
206
        janus_videoroom_p_type_subscriber_muxed,        /* Multiplexed listener/subscriber */
207
        janus_videoroom_p_type_publisher,                        /* Participant/publisher */
208
} janus_videoroom_p_type;
209

    
210
typedef struct janus_videoroom_message {
211
        janus_plugin_session *handle;
212
        char *transaction;
213
        json_t *message;
214
        char *sdp_type;
215
        char *sdp;
216
} janus_videoroom_message;
217
static GAsyncQueue *messages = NULL;
218

    
219
static void janus_videoroom_message_free(janus_videoroom_message *msg) {
220
        if(!msg)
221
                return;
222

    
223
        msg->handle = NULL;
224

    
225
        g_free(msg->transaction);
226
        msg->transaction = NULL;
227
        if(msg->message)
228
                json_decref(msg->message);
229
        msg->message = NULL;
230
        g_free(msg->sdp_type);
231
        msg->sdp_type = NULL;
232
        g_free(msg->sdp);
233
        msg->sdp = NULL;
234

    
235
        g_free(msg);
236
}
237

    
238

    
239
typedef struct janus_videoroom {
240
        guint64 room_id;                        /* Unique room ID */
241
        gchar *room_name;                        /* Room description */
242
        gchar *room_secret;                        /* Secret needed to manipulate (e.g., destroy) this room */
243
        gboolean is_private;                        /* Whether this room is 'private' (as in hidden) or not */
244
        int max_publishers;                        /* Maximum number of concurrent publishers */
245
        uint64_t bitrate;                        /* Global bitrate limit */
246
        uint16_t fir_freq;                        /* Regular FIR frequency (0=disabled) */
247
        gboolean record;                        /* Whether the feeds from publishers in this room should be recorded */
248
        char *rec_dir;                                /* Where to save the recordings of this room, if enabled */
249
        gint64 destroyed;                        /* Value to flag the room for destruction, done lazily */
250
        GHashTable *participants;        /* Map of potential publishers (we get listeners from them) */
251
        janus_mutex participants_mutex;/* Mutex to protect room properties */
252
} janus_videoroom;
253
static GHashTable *rooms;
254
static janus_mutex rooms_mutex;
255
static GList *old_rooms;
256
static void janus_videoroom_free(janus_videoroom *room);
257

    
258
typedef struct janus_videoroom_session {
259
        janus_plugin_session *handle;
260
        janus_videoroom_p_type participant_type;
261
        gpointer participant;
262
        gboolean started;
263
        gboolean stopping;
264
        volatile gint hangingup;
265
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
266
} janus_videoroom_session;
267
static GHashTable *sessions;
268
static GList *old_sessions;
269
static janus_mutex sessions_mutex;
270

    
271
/* a host whose ports gets streamed rtp packets of the corresponding type. */
272
typedef struct rtp_forwarder {
273
        int is_video;
274
        struct sockaddr_in serv_addr;
275
} rtp_forwarder;
276

    
277
typedef struct janus_videoroom_participant {
278
        janus_videoroom_session *session;
279
        janus_videoroom *room;        /* Room */
280
        guint64 user_id;        /* Unique ID in the room */
281
        gchar *display;        /* Display name (just for fun) */
282
        gchar *sdp;                        /* The SDP this publisher negotiated, if any */
283
        gboolean audio, video, data;                /* Whether audio, video and/or data is going to be sent by this publisher */
284
        guint32 audio_ssrc;                /* Audio SSRC of this publisher */
285
        guint32 video_ssrc;                /* Video SSRC of this publisher */
286
        gboolean audio_active;
287
        gboolean video_active;
288
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
289
        uint64_t bitrate;
290
        gint64 remb_startup;/* Incremental changes on REMB to reach the target at startup */
291
        gint64 remb_latest;        /* Time of latest sent REMB (to avoid flooding) */
292
        gint64 fir_latest;        /* Time of latest sent FIR (to avoid flooding) */
293
        gint fir_seq;                /* FIR sequence number */
294
        gboolean recording_active;        /* Whether this publisher has to be recorded or not */
295
        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 */
296
        janus_recorder *arc;        /* The Janus recorder instance for this publisher's audio, if enabled */
297
        janus_recorder *vrc;        /* The Janus recorder instance for this publisher's video, if enabled */
298
        GSList *listeners;
299
        janus_mutex listeners_mutex;
300
        GHashTable *rtp_forwarders;
301
        janus_mutex rtp_forwarders_mutex;
302
        int udp_sock; /* The udp socket on which to forward rtp packets */
303
} janus_videoroom_participant;
304
static void janus_videoroom_participant_free(janus_videoroom_participant *p);
305
static void janus_rtp_forwarder_free_helper(gpointer data);
306
static guint32 janus_rtp_forwarder_add_helper(janus_videoroom_participant *p, const gchar* host, int port, int is_video);
307
typedef struct janus_videoroom_listener_context {
308
        /* Needed to fix seq and ts in case of publisher switching */
309
        uint32_t a_last_ssrc, a_last_ts, a_base_ts, a_base_ts_prev,
310
                        v_last_ssrc, v_last_ts, v_base_ts, v_base_ts_prev;
311
        uint16_t a_last_seq, a_base_seq, a_base_seq_prev,
312
                        v_last_seq, v_base_seq, v_base_seq_prev;
313
} janus_videoroom_listener_context;
314

    
315
typedef struct janus_videoroom_listener {
316
        janus_videoroom_session *session;
317
        janus_videoroom *room;        /* Room */
318
        janus_videoroom_participant *feed;        /* Participant this listener is subscribed to */
319
        janus_videoroom_listener_context context;        /* Needed in case there are publisher switches on this listener */
320
        gboolean audio, video, data;                /* Whether audio, video and/or data must be sent to this publisher */
321
        struct janus_videoroom_listener_muxed *parent;        /* Overall subscriber, if this is a sub-listener in a Multiplexed one */
322
        gboolean paused;
323
} janus_videoroom_listener;
324
static void janus_videoroom_listener_free(janus_videoroom_listener *l);
325

    
326
typedef struct janus_videoroom_listener_muxed {
327
        janus_videoroom_session *session;
328
        janus_videoroom *room;        /* Room */
329
        GSList *listeners;        /* List of listeners (as a Multiplexed listener can be subscribed to more publishers at the same time) */
330
        janus_mutex listeners_mutex;
331
} janus_videoroom_listener_muxed;
332
static void janus_videoroom_muxed_listener_free(janus_videoroom_listener_muxed *l);
333

    
334
typedef struct janus_videoroom_rtp_relay_packet {
335
        rtp_header *data;
336
        gint length;
337
        gint is_video;
338
        uint32_t timestamp;
339
        uint16_t seq_number;
340
} janus_videoroom_rtp_relay_packet;
341

    
342
/* SDP offer/answer templates */
343
#define OPUS_PT                111
344
#define VP8_PT                100
345
#define sdp_template \
346
                "v=0\r\n" \
347
                "o=- %"SCNu64" %"SCNu64" IN IP4 127.0.0.1\r\n"        /* We need current time here */ \
348
                "s=%s\r\n"                                                        /* Video room name */ \
349
                "t=0 0\r\n" \
350
                "%s%s%s"                                /* Audio, video and/or data channel m-lines */
351
#define sdp_a_template \
352
                "m=audio 1 RTP/SAVPF %d\r\n"                /* Opus payload type */ \
353
                "c=IN IP4 1.1.1.1\r\n" \
354
                "a=%s\r\n"                                                        /* Media direction */ \
355
                "a=rtpmap:%d opus/48000/2\r\n"                /* Opus payload type */
356
#define sdp_v_template \
357
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP8 payload type */ \
358
                "c=IN IP4 1.1.1.1\r\n" \
359
                "b=AS:%d\r\n"                                                /* Bandwidth */ \
360
                "a=%s\r\n"                                                        /* Media direction */ \
361
                "a=rtpmap:%d VP8/90000\r\n"                        /* VP8 payload type */ \
362
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP8 payload type */ \
363
                "a=rtcp-fb:%d nack\r\n"                                /* VP8 payload type */ \
364
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP8 payload type */ \
365
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP8 payload type */
366
#define sdp_d_template \
367
                "m=application 1 DTLS/SCTP 5000\r\n" \
368
                "c=IN IP4 1.1.1.1\r\n" \
369
                "a=sctpmap:5000 webrtc-datachannel 16\r\n"
370

    
371

    
372
/* Error codes */
373
#define JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR                499
374
#define JANUS_VIDEOROOM_ERROR_NO_MESSAGE                421
375
#define JANUS_VIDEOROOM_ERROR_INVALID_JSON                422
376
#define JANUS_VIDEOROOM_ERROR_INVALID_REQUEST        423
377
#define JANUS_VIDEOROOM_ERROR_JOIN_FIRST                424
378
#define JANUS_VIDEOROOM_ERROR_ALREADY_JOINED        425
379
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM                426
380
#define JANUS_VIDEOROOM_ERROR_ROOM_EXISTS                427
381
#define JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED                428
382
#define JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT        429
383
#define JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT        430
384
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE        431
385
#define JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL        432
386
#define JANUS_VIDEOROOM_ERROR_UNAUTHORIZED                433
387
#define JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED        434
388
#define JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED                435
389
#define JANUS_VIDEOROOM_ERROR_ID_EXISTS                        436
390
#define JANUS_VIDEOROOM_ERROR_INVALID_SDP                437
391

    
392

    
393
/* Multiplexing helpers */
394
int janus_videoroom_muxed_subscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
395
int janus_videoroom_muxed_unsubscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction);
396
int janus_videoroom_muxed_offer(janus_videoroom_listener_muxed *muxed_listener, char *transaction, char *event_text);
397

    
398
static guint32 janus_rtp_forwarder_add_helper(janus_videoroom_participant* p, const gchar* host, int port, int is_video) {
399
        if(!p || !host) {
400
                return 0;
401
        }
402
        rtp_forwarder* forward = malloc(sizeof(rtp_forwarder));
403
        forward->is_video = is_video;
404
        forward->serv_addr.sin_family = AF_INET;
405
        inet_pton(AF_INET, host, &(forward->serv_addr.sin_addr));
406
        forward->serv_addr.sin_port = htons(port);
407
        janus_mutex_lock(&p->rtp_forwarders_mutex);
408
        guint32 stream_id = g_random_int();
409
        while(g_hash_table_lookup(p->rtp_forwarders, GUINT_TO_POINTER(stream_id)) != NULL) {
410
                stream_id = g_random_int();
411
        }
412
        g_hash_table_insert(p->rtp_forwarders, GUINT_TO_POINTER(stream_id), forward);
413
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
414
        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);
415
        return stream_id;
416
}
417

    
418

    
419
/* Convenience function for freeing a session */
420
static void session_free(gpointer data) {
421
        if(data) {
422
                janus_videoroom_session* session = (janus_videoroom_session*)data;
423
                switch(session->participant_type) {
424
                case janus_videoroom_p_type_publisher: 
425
                        janus_videoroom_participant_free(session->participant);
426
                        break;   
427
                case janus_videoroom_p_type_subscriber:
428
                        janus_videoroom_listener_free(session->participant);
429
                        break;
430
                case janus_videoroom_p_type_subscriber_muxed:
431
                        janus_videoroom_muxed_listener_free(session->participant);
432
                        break;
433
                default:
434
                        break;
435
                }
436
                session->handle = NULL;
437
                g_free(session);
438
                session = NULL;
439
        }
440
}
441

    
442
static void janus_rtp_forwarder_free_helper(gpointer data) {
443
        if(data) {
444
                rtp_forwarder* forward = (rtp_forwarder*)data;
445
                if(forward) {
446
                        free(forward);
447
                        forward = NULL;
448
                }
449
        }
450
}
451

    
452
/* Convenience wrapper function for session_free that corresponds to GHRFunc() format for hash table cleanup */
453
static gboolean session_hash_table_remove(gpointer key, gpointer value, gpointer not_used) {
454
        if(value) {
455
                session_free(value);
456
        }
457
        return TRUE;
458
}
459

    
460
/* VideoRoom watchdog/garbage collector (sort of) */
461
void *janus_videoroom_watchdog(void *data);
462
void *janus_videoroom_watchdog(void *data) {
463
        JANUS_LOG(LOG_INFO, "VideoRoom watchdog started\n");
464
        gint64 now = 0, room_now = 0;
465
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
466
                janus_mutex_lock(&sessions_mutex);
467
                /* Iterate on all the participants/listeners and check if we need to remove any of them */
468
                now = janus_get_monotonic_time();
469
                if(old_sessions != NULL) {
470
                        GList *sl = old_sessions;
471
                        JANUS_LOG(LOG_HUGE, "Checking %d old VideoRoom sessions...\n", g_list_length(old_sessions));
472
                        while(sl) {
473
                                janus_videoroom_session *session = (janus_videoroom_session *)sl->data;
474
                                /* If we are stopping, their is no point to continue to iterate */
475
                                if(!initialized || stopping) {
476
                                        break;
477
                                }
478
                                if(!session) {
479
                                        sl = sl->next;
480
                                        continue;
481
                                }
482
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
483
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
484
                                        JANUS_LOG(LOG_VERB, "Freeing old VideoRoom session\n");
485
                                        GList *rm = sl->next;
486
                                        old_sessions = g_list_delete_link(old_sessions, sl);
487
                                        sl = rm;
488
                                        g_hash_table_steal(sessions, session->handle);
489
                                        session_free(session);
490
                                        continue;
491
                                }
492
                                sl = sl->next;
493
                        }
494
                }
495
                janus_mutex_unlock(&sessions_mutex);
496
                janus_mutex_lock(&rooms_mutex);
497
                if(old_rooms != NULL) {
498
                        GList *rl = old_rooms;
499
                        room_now = janus_get_monotonic_time();
500
                        while(rl) {
501
                                janus_videoroom* room = (janus_videoroom*)rl->data;
502
                                if(!initialized || stopping){
503
                                        break;
504
                                }
505
                                if(!room) {
506
                                        rl = rl->next;
507
                                        continue;
508
                                }
509
                                if(room_now - room->destroyed >= 5*G_USEC_PER_SEC) {
510
                                        GList *rm = rl->next;
511
                                        old_rooms = g_list_delete_link(old_rooms, rl);
512
                                        rl = rm;
513
                                        g_hash_table_remove(rooms, GUINT_TO_POINTER(room->room_id));
514
                                        continue;
515
                                }
516
                                rl = rl->next;
517
                        }
518
                }
519
                janus_mutex_unlock(&rooms_mutex);
520
                g_usleep(500000);
521
        }
522
        JANUS_LOG(LOG_INFO, "VideoRoom watchdog stopped\n");
523
        return NULL;
524
}
525

    
526

    
527
/* Plugin implementation */
528
int janus_videoroom_init(janus_callbacks *callback, const char *config_path) {
529
        if(g_atomic_int_get(&stopping)) {
530
                /* Still stopping from before */
531
                return -1;
532
        }
533
        if(callback == NULL || config_path == NULL) {
534
                /* Invalid arguments */
535
                return -1;
536
        }
537
        sdphome = su_home_new(sizeof(su_home_t));
538
        if(su_home_init(sdphome) < 0) {
539
                JANUS_LOG(LOG_FATAL, "Ops, error setting up sofia-sdp?\n");
540
                return -1;
541
        }
542

    
543
        /* Read configuration */
544
        char filename[255];
545
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_VIDEOROOM_PACKAGE);
546
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
547
        janus_config *config = janus_config_parse(filename);
548
        if(config != NULL)
549
                janus_config_print(config);
550

    
551
        rooms = g_hash_table_new_full(NULL, NULL, NULL,
552
                                      (GDestroyNotify) janus_videoroom_free);
553
        janus_mutex_init(&rooms_mutex);
554
        sessions = g_hash_table_new(NULL, NULL);
555
        janus_mutex_init(&sessions_mutex);
556

    
557
        messages = g_async_queue_new_full((GDestroyNotify) janus_videoroom_message_free);
558

    
559
        /* This is the callback we'll need to invoke to contact the gateway */
560
        gateway = callback;
561

    
562
        /* Parse configuration to populate the rooms list */
563
        if(config != NULL) {
564
                janus_config_category *cat = janus_config_get_categories(config);
565
                while(cat != NULL) {
566
                        if(cat->name == NULL) {
567
                                cat = cat->next;
568
                                continue;
569
                        }
570
                        JANUS_LOG(LOG_VERB, "Adding video room '%s'\n", cat->name);
571
                        janus_config_item *desc = janus_config_get_item(cat, "description");
572
                        janus_config_item *priv = janus_config_get_item(cat, "is_private");
573
                        janus_config_item *secret = janus_config_get_item(cat, "secret");
574
                        janus_config_item *bitrate = janus_config_get_item(cat, "bitrate");
575
                        janus_config_item *maxp = janus_config_get_item(cat, "publishers");
576
                        janus_config_item *firfreq = janus_config_get_item(cat, "fir_freq");
577
                        janus_config_item *record = janus_config_get_item(cat, "record");
578
                        janus_config_item *rec_dir = janus_config_get_item(cat, "rec_dir");
579
                        /* Create the video room */
580
                        janus_videoroom *videoroom = calloc(1, sizeof(janus_videoroom));
581
                        if(videoroom == NULL) {
582
                                JANUS_LOG(LOG_FATAL, "Memory error!\n");
583
                                continue;
584
                        }
585
                        videoroom->room_id = atoi(cat->name);
586
                        char *description = NULL;
587
                        if(desc != NULL && desc->value != NULL && strlen(desc->value) > 0)
588
                                description = g_strdup(desc->value);
589
                        else
590
                                description = g_strdup(cat->name);
591
                        if(description == NULL) {
592
                                JANUS_LOG(LOG_FATAL, "Memory error!\n");
593
                                continue;
594
                        }
595
                        videoroom->room_name = description;
596
                        if(secret != NULL && secret->value != NULL) {
597
                                videoroom->room_secret = g_strdup(secret->value);
598
                        }
599
                        videoroom->is_private = priv && priv->value && janus_is_true(priv->value);
600
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
601
                        if(maxp != NULL && maxp->value != NULL)
602
                                videoroom->max_publishers = atol(maxp->value);
603
                        if(videoroom->max_publishers < 0)
604
                                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
605
                        videoroom->bitrate = 0;
606
                        if(bitrate != NULL && bitrate->value != NULL)
607
                                videoroom->bitrate = atol(bitrate->value);
608
                        if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
609
                                videoroom->bitrate = 64000;        /* Don't go below 64k */
610
                        videoroom->fir_freq = 0;
611
                        if(firfreq != NULL && firfreq->value != NULL)
612
                                videoroom->fir_freq = atol(firfreq->value);
613
                        if(record && record->value) {
614
                                videoroom->record = janus_is_true(record->value);
615
                                if(rec_dir && rec_dir->value) {
616
                                        videoroom->rec_dir = g_strdup(rec_dir->value);
617
                                }
618
                        }
619
                        videoroom->destroyed = 0;
620
                        janus_mutex_init(&videoroom->participants_mutex);
621
                        videoroom->participants = g_hash_table_new(NULL, NULL);
622
                        janus_mutex_lock(&rooms_mutex);
623
                        g_hash_table_insert(rooms, GUINT_TO_POINTER(videoroom->room_id), videoroom);
624
                        janus_mutex_unlock(&rooms_mutex);
625
                        JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, secret: %s)\n", videoroom->room_id, videoroom->room_name, videoroom->is_private ? "private" : "public", videoroom->room_secret ? videoroom->room_secret : "no secret");
626
                        if(videoroom->record) {
627
                                JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
628
                        }
629
                        cat = cat->next;
630
                }
631
                /* Done */
632
                janus_config_destroy(config);
633
                config = NULL;
634
        }
635

    
636
        /* Show available rooms */
637
        janus_mutex_lock(&rooms_mutex);
638
        GHashTableIter iter;
639
        gpointer value;
640
        g_hash_table_iter_init(&iter, rooms);
641
        while (g_hash_table_iter_next(&iter, NULL, &value)) {
642
                janus_videoroom *vr = value;
643
                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);
644
        }
645
        janus_mutex_unlock(&rooms_mutex);
646

    
647
        g_atomic_int_set(&initialized, 1);
648

    
649
        GError *error = NULL;
650
        /* Start the sessions watchdog */
651
        watchdog = g_thread_try_new("vroom watchdog", &janus_videoroom_watchdog, NULL, &error);
652
        if(error != NULL) {
653
                g_atomic_int_set(&initialized, 0);
654
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom watchdog thread...\n", error->code, error->message ? error->message : "??");
655
                return -1;
656
        }
657
        /* Launch the thread that will handle incoming messages */
658
        handler_thread = g_thread_try_new("janus videoroom handler", janus_videoroom_handler, NULL, &error);
659
        if(error != NULL) {
660
                g_atomic_int_set(&initialized, 0);
661
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoRoom handler thread...\n", error->code, error->message ? error->message : "??");
662
                return -1;
663
        }
664
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_VIDEOROOM_NAME);
665
        return 0;
666
}
667

    
668
void janus_videoroom_destroy(void) {
669
        if(!g_atomic_int_get(&initialized))
670
                return;
671
        g_atomic_int_set(&stopping, 1);
672
        if(handler_thread != NULL) {
673
                g_thread_join(handler_thread);
674
                handler_thread = NULL;
675
        }
676
        if(watchdog != NULL) {
677
                g_thread_join(watchdog);
678
                watchdog = NULL;
679
        }
680
        su_home_deinit(sdphome);
681
        su_home_unref(sdphome);
682
        sdphome = NULL;
683

    
684
        /* FIXME We should destroy the sessions cleanly */
685
        janus_mutex_lock(&sessions_mutex);
686
        g_hash_table_foreach_remove(sessions, (GHRFunc)session_hash_table_remove, NULL);
687
        g_hash_table_destroy(sessions);
688
        sessions = NULL;
689
        janus_mutex_unlock(&sessions_mutex);
690

    
691
        janus_mutex_lock(&rooms_mutex);
692

    
693
        g_hash_table_destroy(rooms);
694
        rooms = NULL;
695
        janus_mutex_unlock(&rooms_mutex);
696
        janus_mutex_destroy(&rooms_mutex);
697

    
698
        g_async_queue_unref(messages);
699
        messages = NULL;
700

    
701
        g_atomic_int_set(&initialized, 0);
702
        g_atomic_int_set(&stopping, 0);
703
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOROOM_NAME);
704
}
705

    
706
int janus_videoroom_get_api_compatibility(void) {
707
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
708
        return JANUS_PLUGIN_API_VERSION;
709
}
710

    
711
int janus_videoroom_get_version(void) {
712
        return JANUS_VIDEOROOM_VERSION;
713
}
714

    
715
const char *janus_videoroom_get_version_string(void) {
716
        return JANUS_VIDEOROOM_VERSION_STRING;
717
}
718

    
719
const char *janus_videoroom_get_description(void) {
720
        return JANUS_VIDEOROOM_DESCRIPTION;
721
}
722

    
723
const char *janus_videoroom_get_name(void) {
724
        return JANUS_VIDEOROOM_NAME;
725
}
726

    
727
const char *janus_videoroom_get_author(void) {
728
        return JANUS_VIDEOROOM_AUTHOR;
729
}
730

    
731
const char *janus_videoroom_get_package(void) {
732
        return JANUS_VIDEOROOM_PACKAGE;
733
}
734

    
735
void janus_videoroom_create_session(janus_plugin_session *handle, int *error) {
736
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
737
                *error = -1;
738
                return;
739
        }        
740
        janus_videoroom_session *session = (janus_videoroom_session *)calloc(1, sizeof(janus_videoroom_session));
741
        if(session == NULL) {
742
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
743
                *error = -2;
744
                return;
745
        }
746
        session->handle = handle;
747
        session->participant_type = janus_videoroom_p_type_none;
748
        session->participant = NULL;
749
        session->destroyed = 0;
750
        g_atomic_int_set(&session->hangingup, 0);
751
        handle->plugin_handle = session;
752
        janus_mutex_lock(&sessions_mutex);
753
        g_hash_table_insert(sessions, handle, session);
754
        janus_mutex_unlock(&sessions_mutex);
755

    
756
        return;
757
}
758

    
759
void janus_videoroom_destroy_session(janus_plugin_session *handle, int *error) {
760
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
761
                *error = -1;
762
                return;
763
        }        
764
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle; 
765
        if(!session) {
766
                JANUS_LOG(LOG_ERR, "No VideoRoom session associated with this handle...\n");
767
                *error = -2;
768
                return;
769
        }
770
        if(session->destroyed) {
771
                JANUS_LOG(LOG_WARN, "VideoRoom session already marked as destroyed...\n");
772
                return;
773
        }
774
        JANUS_LOG(LOG_VERB, "Removing VideoRoom session...\n");
775
        /* Cleaning up and removing the session is done in a lazy way */
776
        janus_mutex_lock(&sessions_mutex);
777
        if(!session->destroyed) {
778
                /* Any related WebRTC PeerConnection is not available anymore either */
779
                janus_videoroom_hangup_media(handle);
780
                session->destroyed = janus_get_monotonic_time();
781
                old_sessions = g_list_append(old_sessions, session);
782
                if(session->participant_type == janus_videoroom_p_type_publisher) {
783
                        /* Get rid of publisher */
784
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
785
                        participant->audio = FALSE;
786
                        participant->video = FALSE;
787
                        participant->data = FALSE;
788
                        participant->audio_active = FALSE;
789
                        participant->video_active = FALSE;
790
                        participant->recording_active = FALSE;
791
                        if(participant->recording_base)
792
                                g_free(participant->recording_base);
793
                        participant->recording_base = NULL;
794
                        json_t *event = json_object();
795
                        json_object_set_new(event, "videoroom", json_string("event"));
796
                        json_object_set_new(event, "room", json_integer(participant->room->room_id));
797
                        json_object_set_new(event, "leaving", json_integer(participant->user_id));
798
                        char *leaving_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
799
                        json_decref(event);
800
                        GHashTableIter iter;
801
                        gpointer value;
802
                        /* we need to check if the room still exists, may have been destroyed already */
803
                        if(participant->room) {
804
                                if(!participant->room->destroyed) {
805
                                        janus_mutex_lock(&participant->room->participants_mutex);
806
                                        g_hash_table_iter_init(&iter, participant->room->participants);
807
                                        while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
808
                                                janus_videoroom_participant *p = value;
809
                                                if(p == participant) {
810
                                                        continue;        /* Skip the leaving publisher itself */
811
                                                }
812
                                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
813
                                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, leaving_text, NULL, NULL);
814
                                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
815
                                        }
816
                                        g_hash_table_remove(participant->room->participants, GUINT_TO_POINTER(participant->user_id));
817
                                        janus_mutex_unlock(&participant->room->participants_mutex);
818
                                }
819
                        }
820
                        g_free(leaving_text);
821
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
822
                        /* Detaching this listener from its publisher is already done by hangup_media */
823
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
824
                        /* Detaching this listener from its publishers is already done by hangup_media */
825
                }
826
        }
827
        janus_mutex_unlock(&sessions_mutex);
828

    
829
        return;
830
}
831

    
832
char *janus_videoroom_query_session(janus_plugin_session *handle) {
833
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
834
                return NULL;
835
        }        
836
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
837
        if(!session) {
838
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
839
                return NULL;
840
        }
841
        /* Show the participant/room info, if any */
842
        json_t *info = json_object();
843
        if(session->participant) {
844
                if(session->participant_type == janus_videoroom_p_type_none) {
845
                        json_object_set_new(info, "type", json_string("none"));
846
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
847
                        json_object_set_new(info, "type", json_string("publisher"));
848
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
849
                        if(participant) {
850
                                janus_videoroom *room = participant->room; 
851
                                json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
852
                                json_object_set_new(info, "id", json_integer(participant->user_id));
853
                                if(participant->display)
854
                                        json_object_set_new(info, "display", json_string(participant->display));
855
                                if(participant->listeners)
856
                                        json_object_set_new(info, "viewers", json_integer(g_slist_length(participant->listeners)));
857
                                json_t *media = json_object();
858
                                json_object_set_new(media, "audio", json_integer(participant->audio));
859
                                json_object_set_new(media, "video", json_integer(participant->video));
860
                                json_object_set_new(media, "data", json_integer(participant->data));
861
                                json_object_set_new(info, "media", media);
862
                        }
863
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
864
                        json_object_set_new(info, "type", json_string("listener"));
865
                        janus_videoroom_listener *participant = (janus_videoroom_listener *)session->participant;
866
                        if(participant) {
867
                                janus_videoroom_participant *feed = (janus_videoroom_participant *)participant->feed;
868
                                if(feed) {
869
                                        janus_videoroom *room = feed->room; 
870
                                        json_object_set_new(info, "room", room ? json_integer(room->room_id) : NULL);
871
                                        json_object_set_new(info, "feed_id", json_integer(feed->user_id));
872
                                        if(feed->display)
873
                                                json_object_set_new(info, "feed_display", json_string(feed->display));
874
                                }
875
                                json_t *media = json_object();
876
                                json_object_set_new(media, "audio", json_integer(participant->audio));
877
                                json_object_set_new(media, "video", json_integer(participant->video));
878
                                json_object_set_new(media, "data", json_integer(participant->data));
879
                                json_object_set_new(info, "media", media);
880
                        }
881
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
882
                        json_object_set_new(info, "type", json_string("muxed-listener"));
883
                        /* TODO */
884
                }
885
        }
886
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
887
        char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
888
        json_decref(info);
889
        return info_text;
890
}
891

    
892
struct janus_plugin_result *janus_videoroom_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
893
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
894
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
895
        
896
        /* Pre-parse the message */
897
        int error_code = 0;
898
        char error_cause[512];
899
        json_t *root = NULL;
900
        json_t *response = NULL;
901

    
902
        if(message == NULL) {
903
                JANUS_LOG(LOG_ERR, "No message??\n");
904
                error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
905
                g_snprintf(error_cause, 512, "%s", "No message??");
906
                goto error;
907
        }
908
        JANUS_LOG(LOG_VERB, "Handling message: %s\n", message);
909

    
910
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
911
        if(!session) {
912
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
913
                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
914
                g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
915
                goto error;
916
        }
917
        if(session->destroyed) {
918
                JANUS_LOG(LOG_ERR, "Session has already been marked as destroyed...\n");
919
                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
920
                g_snprintf(error_cause, 512, "%s", "Session has already been marked as destroyed...");
921
                goto error;
922
        }
923
        json_error_t error;
924
        root = json_loads(message, 0, &error);
925
        if(!root) {
926
                JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
927
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_JSON;
928
                g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
929
                goto error;
930
        }
931
        if(!json_is_object(root)) {
932
                JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
933
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_JSON;
934
                g_snprintf(error_cause, 512, "JSON error: not an object");
935
                goto error;
936
        }
937
        /* Get the request first */
938
        json_t *request = json_object_get(root, "request");
939
        if(!request) {
940
                JANUS_LOG(LOG_ERR, "Missing element (request)\n");
941
                error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
942
                g_snprintf(error_cause, 512, "Missing element (request)");
943
                goto error;
944
        }
945
        if(!json_is_string(request)) {
946
                JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
947
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
948
                g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
949
                goto error;
950
        }
951
        /* Some requests ('create', 'destroy', 'exists', 'list') can be handled synchronously */
952
        const char *request_text = json_string_value(request);
953
        if(!strcasecmp(request_text, "create")) {
954
                /* Create a new videoroom */
955
                JANUS_LOG(LOG_VERB, "Creating a new videoroom\n");
956
                json_t *desc = json_object_get(root, "description");
957
                if(desc && !json_is_string(desc)) {
958
                        JANUS_LOG(LOG_ERR, "Invalid element (description should be a string)\n");
959
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
960
                        g_snprintf(error_cause, 512, "Invalid element (description should be a string)");
961
                        goto error;
962
                }
963
                json_t *is_private = json_object_get(root, "is_private");
964
                if(is_private && !json_is_boolean(is_private)) {
965
                        JANUS_LOG(LOG_ERR, "Invalid element (is_private should be a boolean)\n");
966
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
967
                        g_snprintf(error_cause, 512, "Invalid value (is_private should be a boolean)");
968
                        goto error;
969
                }
970
                json_t *secret = json_object_get(root, "secret");
971
                if(secret && !json_is_string(secret)) {
972
                        JANUS_LOG(LOG_ERR, "Invalid element (secret should be a string)\n");
973
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
974
                        g_snprintf(error_cause, 512, "Invalid element (secret should be a string)");
975
                        goto error;
976
                }
977
                json_t *bitrate = json_object_get(root, "bitrate");
978
                if(bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
979
                        JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
980
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
981
                        g_snprintf(error_cause, 512, "Invalid element (bitrate should be a positive integer)");
982
                        goto error;
983
                }
984
                json_t *fir_freq = json_object_get(root, "fir_freq");
985
                if(fir_freq && (!json_is_integer(fir_freq) || json_integer_value(fir_freq) < 0)) {
986
                        JANUS_LOG(LOG_ERR, "Invalid element (fir_freq should be a positive integer)\n");
987
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
988
                        g_snprintf(error_cause, 512, "Invalid element (fir_freq should be a positive integer)");
989
                        goto error;
990
                }
991
                json_t *publishers = json_object_get(root, "publishers");
992
                if(publishers && (!json_is_integer(publishers) || json_integer_value(publishers) < 0)) {
993
                        JANUS_LOG(LOG_ERR, "Invalid element (publishers should be a positive integer)\n");
994
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
995
                        g_snprintf(error_cause, 512, "Invalid element (publishers should be a positive integer)");
996
                        goto error;
997
                }
998
                json_t *record = json_object_get(root, "record");
999
                if(record && !json_is_boolean(record)) {
1000
                        JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
1001
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1002
                        g_snprintf(error_cause, 512, "Invalid element (record should be a boolean)");
1003
                        goto error;
1004
                }
1005
                json_t *rec_dir = json_object_get(root, "rec_dir");
1006
                if(rec_dir && !json_is_string(rec_dir)) {
1007
                        JANUS_LOG(LOG_ERR, "Invalid element (rec_dir should be a string)\n");
1008
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1009
                        g_snprintf(error_cause, 512, "Invalid element (rec_dir should be a string)");
1010
                        goto error;
1011
                }
1012
                guint64 room_id = 0;
1013
                json_t *room = json_object_get(root, "room");
1014
                if(room && (!json_is_integer(room) || json_integer_value(room) < 0)) {
1015
                        JANUS_LOG(LOG_ERR, "Invalid element (room should be a positive integer)\n");
1016
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1017
                        g_snprintf(error_cause, 512, "Invalid element (room should be a positive integer)");
1018
                        goto error;
1019
                } else {
1020
                        room_id = json_integer_value(room);
1021
                        if(room_id == 0) {
1022
                                JANUS_LOG(LOG_WARN, "Desired room ID is 0, which is not allowed... picking random ID instead\n");
1023
                        }
1024
                }
1025
                janus_mutex_lock(&rooms_mutex);
1026
                if(room_id > 0) {
1027
                        /* Let's make sure the room doesn't exist already */
1028
                        if(g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id)) != NULL) {
1029
                                /* It does... */
1030
                                janus_mutex_unlock(&rooms_mutex);
1031
                                JANUS_LOG(LOG_ERR, "Room %"SCNu64" already exists!\n", room_id);
1032
                                error_code = JANUS_VIDEOROOM_ERROR_ROOM_EXISTS;
1033
                                g_snprintf(error_cause, 512, "Room %"SCNu64" already exists", room_id);
1034
                                goto error;
1035
                        }
1036
                }
1037
                /* Create the room */
1038
                janus_videoroom *videoroom = calloc(1, sizeof(janus_videoroom));
1039
                if(videoroom == NULL) {
1040
                        janus_mutex_unlock(&rooms_mutex);
1041
                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
1042
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1043
                        g_snprintf(error_cause, 512, "Memory error");
1044
                        goto error;
1045
                }
1046
                /* Generate a random ID */
1047
                if(room_id == 0) {
1048
                        while(room_id == 0) {
1049
                                room_id = g_random_int();
1050
                                if(g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id)) != NULL) {
1051
                                        /* Room ID already taken, try another one */
1052
                                        room_id = 0;
1053
                                }
1054
                        }
1055
                }
1056
                videoroom->room_id = room_id;
1057
                char *description = NULL;
1058
                if(desc != NULL && strlen(json_string_value(desc)) > 0) {
1059
                        description = g_strdup(json_string_value(desc));
1060
                } else {
1061
                        char roomname[255];
1062
                        g_snprintf(roomname, 255, "Room %"SCNu64"", videoroom->room_id);
1063
                        description = g_strdup(roomname);
1064
                }
1065
                if(description == NULL) {
1066
                        janus_mutex_unlock(&rooms_mutex);
1067
                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
1068
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1069
                        g_snprintf(error_cause, 512, "Memory error");
1070
                        goto error;
1071
                }
1072
                videoroom->room_name = description;
1073
                videoroom->is_private = is_private ? json_is_true(is_private) : FALSE;
1074
                if(secret)
1075
                        videoroom->room_secret = g_strdup(json_string_value(secret));
1076
                videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
1077
                if(publishers)
1078
                        videoroom->max_publishers = json_integer_value(publishers);
1079
                if(videoroom->max_publishers < 0)
1080
                        videoroom->max_publishers = 3;        /* FIXME How should we choose a default? */
1081
                videoroom->bitrate = 0;
1082
                if(bitrate)
1083
                        videoroom->bitrate = json_integer_value(bitrate);
1084
                if(videoroom->bitrate > 0 && videoroom->bitrate < 64000)
1085
                        videoroom->bitrate = 64000;        /* Don't go below 64k */
1086
                videoroom->fir_freq = 0;
1087
                if(fir_freq)
1088
                        videoroom->fir_freq = json_integer_value(fir_freq);
1089
                if(record) {
1090
                        videoroom->record = json_is_true(record);
1091
                        if(videoroom->record && rec_dir) {
1092
                                videoroom->rec_dir = g_strdup(json_string_value(rec_dir));
1093
                        }
1094
                }
1095
                videoroom->destroyed = 0;
1096
                janus_mutex_init(&videoroom->participants_mutex);
1097
                videoroom->participants = g_hash_table_new(NULL, NULL);
1098
                JANUS_LOG(LOG_VERB, "Created videoroom: %"SCNu64" (%s, %s, secret: %s)\n", videoroom->room_id, videoroom->room_name, videoroom->is_private ? "private" : "public", videoroom->room_secret ? videoroom->room_secret : "no secret");
1099
                if(videoroom->record) {
1100
                        JANUS_LOG(LOG_VERB, "  -- Room is going to be recorded in %s\n", videoroom->rec_dir ? videoroom->rec_dir : "the current folder");
1101
                }
1102
                /* Show updated rooms list */
1103
                GHashTableIter iter;
1104
                gpointer value;
1105
                g_hash_table_insert(rooms, GUINT_TO_POINTER(videoroom->room_id), videoroom);
1106
                g_hash_table_iter_init(&iter, rooms);
1107
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1108
                        janus_videoroom *vr = value;
1109
                        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);
1110
                }
1111
                janus_mutex_unlock(&rooms_mutex);
1112
                /* Send info back */
1113
                response = json_object();
1114
                json_object_set_new(response, "videoroom", json_string("created"));
1115
                json_object_set_new(response, "room", json_integer(videoroom->room_id));
1116
                goto plugin_response;
1117
        } else if(!strcasecmp(request_text, "destroy")) {
1118
                JANUS_LOG(LOG_VERB, "Attempt to destroy an existing videoroom room\n");
1119
                json_t *room = json_object_get(root, "room");
1120
                if(!room) {
1121
                        JANUS_LOG(LOG_ERR, "Missing element (room)\n");
1122
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1123
                        g_snprintf(error_cause, 512, "Missing element (room)");
1124
                        goto error;
1125
                }
1126
                if(!json_is_integer(room) || json_integer_value(room) < 0) {
1127
                        JANUS_LOG(LOG_ERR, "Invalid element (room should be a positive integer)\n");
1128
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1129
                        g_snprintf(error_cause, 512, "Invalid element (room should be a positive integer)");
1130
                        goto error;
1131
                }
1132
                guint64 room_id = json_integer_value(room);
1133
                janus_mutex_lock(&rooms_mutex);
1134
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
1135
                if(videoroom == NULL) {
1136
                        janus_mutex_unlock(&rooms_mutex);
1137
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1138
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1139
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1140
                        goto error;
1141
                }
1142
                
1143
                if(videoroom->destroyed) {
1144
                        janus_mutex_unlock(&rooms_mutex)
1145
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", videoroom->room_id);
1146
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1147
                        g_snprintf(error_cause, 512, "Videoroom (%"SCNu64")", videoroom->room_id);
1148
                        goto error;
1149
                }
1150
                if(videoroom->room_secret) {
1151
                        /* A secret is required for this action */
1152
                        json_t *secret = json_object_get(root, "secret");
1153
                        if(!secret) {
1154
                                janus_mutex_unlock(&rooms_mutex);
1155
                                JANUS_LOG(LOG_ERR, "Missing element (secret)\n");
1156
                                error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1157
                                g_snprintf(error_cause, 512, "Missing element (secret)");
1158
                                goto error;
1159
                        }
1160
                        if(!json_is_string(secret)) {
1161
                                janus_mutex_unlock(&rooms_mutex);
1162
                                JANUS_LOG(LOG_ERR, "Invalid element (secret should be a string)\n");
1163
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1164
                                g_snprintf(error_cause, 512, "Invalid element (secret should be a string)");
1165
                                goto error;
1166
                        }
1167
                        if(!janus_strcmp_const_time(videoroom->room_secret, json_string_value(secret))) {
1168
                                janus_mutex_unlock(&rooms_mutex);
1169
                                JANUS_LOG(LOG_ERR, "Unauthorized (wrong secret)\n");
1170
                                error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
1171
                                g_snprintf(error_cause, 512, "Unauthorized (wrong secret)");
1172
                                goto error;
1173
                        }
1174
                }
1175
                /* Notify all participants that the fun is over, and that they'll be kicked */
1176
                JANUS_LOG(LOG_VERB, "Notifying all participants\n");
1177
                json_t *destroyed = json_object();
1178
                json_object_set_new(destroyed, "videoroom", json_string("destroyed"));
1179
                json_object_set_new(destroyed, "room", json_integer(videoroom->room_id));
1180
                char *destroyed_text = json_dumps(destroyed, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1181
                GHashTableIter iter;
1182
                gpointer value;
1183
                /* Remove room lazily*/
1184
                videoroom->destroyed = janus_get_monotonic_time();
1185
                old_rooms = g_list_append(old_rooms, videoroom);
1186
                janus_mutex_lock(&videoroom->participants_mutex);
1187
                g_hash_table_iter_init(&iter, videoroom->participants);
1188
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1189
                        janus_videoroom_participant *p = value;
1190
                        if(p && p->session) {
1191
                                /* Notify the user we're going to destroy the room... */
1192
                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, destroyed_text, NULL, NULL);
1193
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1194
                                /* ... and then ask the core to remove the handle */
1195
                                gateway->end_session(p->session->handle);
1196
                        }
1197
                }
1198
                json_decref(destroyed);
1199
                g_free(destroyed_text);
1200
                janus_mutex_unlock(&videoroom->participants_mutex);
1201
                janus_mutex_unlock(&rooms_mutex);
1202
                /* Done */
1203
                response = json_object();
1204
                json_object_set_new(response, "videoroom", json_string("destroyed"));
1205
                json_object_set_new(response, "room", json_integer(room_id));
1206
                goto plugin_response;
1207
        } else if(!strcasecmp(request_text, "list")) {
1208
                /* List all rooms (but private ones) and their details (except for the secret, of course...) */
1209
                json_t *list = json_array();
1210
                JANUS_LOG(LOG_VERB, "Getting the list of video rooms\n");
1211
                janus_mutex_lock(&rooms_mutex);
1212
                GHashTableIter iter;
1213
                gpointer value;
1214
                g_hash_table_iter_init(&iter, rooms);
1215
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
1216
                        janus_videoroom *room = value;
1217
                        if(!room)
1218
                                continue;
1219
                        if(room->is_private) {
1220
                                /* Skip private room */
1221
                                JANUS_LOG(LOG_VERB, "Skipping private room '%s'\n", room->room_name);
1222
                                continue;
1223
                        }
1224
                        if(!room->destroyed) {
1225
                                json_t *rl = json_object();
1226
                                json_object_set_new(rl, "room", json_integer(room->room_id));
1227
                                json_object_set_new(rl, "description", json_string(room->room_name));
1228
                                json_object_set_new(rl, "max_publishers", json_integer(room->max_publishers));
1229
                                json_object_set_new(rl, "bitrate", json_integer(room->bitrate));
1230
                                json_object_set_new(rl, "fir_freq", json_integer(room->fir_freq));
1231
                                json_object_set_new(rl, "record", json_string(room->record ? "true" : "false"));
1232
                                json_object_set_new(rl, "rec_dir", json_string(room->rec_dir));
1233
                                /* TODO: Should we list participants as well? or should there be a separate API call on a specific room for this? */
1234
                                json_object_set_new(rl, "num_participants", json_integer(g_hash_table_size(room->participants)));
1235
                                json_array_append_new(list, rl);
1236
                        }
1237
                }
1238
                janus_mutex_unlock(&rooms_mutex);
1239
                response = json_object();
1240
                json_object_set_new(response, "videoroom", json_string("success"));
1241
                json_object_set_new(response, "list", list);
1242
                goto plugin_response;
1243
        } else if(!strcasecmp(request_text, "rtp_forward")) {
1244
                json_t *room = json_object_get(root, "room");
1245
                if(!room) {
1246
                        JANUS_LOG(LOG_ERR, "Missing element (room)\n");
1247
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1248
                        g_snprintf(error_cause, 512, "Missing element (room)");
1249
                        goto error;
1250
                }
1251
                if(!json_is_integer(room) || json_integer_value(room) < 0 ) {
1252
                        JANUS_LOG(LOG_ERR, "Invalid element (room should be a positive integer)\n");
1253
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1254
                        g_snprintf(error_cause, 512, "Invalid element (room should be a positive integer)");
1255
                        goto error;
1256
                }
1257
                json_t *pub_id = json_object_get(root, "publisher_id");
1258
                if(!pub_id) {
1259
                        JANUS_LOG(LOG_ERR, "Missing element (publisher_id)\n");
1260
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1261
                        g_snprintf(error_cause, 512, "Missing element (publisher_id)");
1262
                        goto error;
1263
                }
1264
                if(!json_is_integer(pub_id) || json_integer_value(pub_id) < 0) {
1265
                        JANUS_LOG(LOG_ERR, "Invalid element (publisher_id should be a postive integer)\n");
1266
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1267
                        g_snprintf(error_cause, 512, "Invalid element (publisher_id should be a positive integer)");
1268
                        goto error;
1269
                }
1270
                int video_port = -1;
1271
                int audio_port = -1;
1272
                json_t *vid_port = json_object_get(root, "video_port");
1273
                if(vid_port && (!json_is_integer(vid_port) || json_integer_value(vid_port) < 0)) {
1274
                        JANUS_LOG(LOG_ERR, "Invalid element (video_port should be a positive integer)\n");
1275
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1276
                        g_snprintf(error_cause, 512, "Invalid element (video_port should be a positive integer)");
1277
                        goto error;
1278
                }
1279
                if(vid_port) {
1280
                        video_port = json_integer_value(vid_port);
1281
                }
1282
                json_t *au_port = json_object_get(root, "audio_port");
1283
                if(au_port && (!json_is_integer(au_port) || json_integer_value(au_port) <0)) {
1284
                        JANUS_LOG(LOG_ERR, "Invalid element (audio_port should be a positive integer)\n");
1285
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1286
                        g_snprintf(error_cause, 512, "Invalid element (audio_port should be a positive integer)");
1287
                        goto error;
1288
                }
1289
                if(au_port) {
1290
                        audio_port = json_integer_value(au_port);
1291
                }
1292
                json_t *json_host = json_object_get(root, "host");
1293
                if(!json_host) {
1294
                        JANUS_LOG(LOG_ERR, "Missing element (host)\n");
1295
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1296
                        g_snprintf(error_cause, 512, "Missing element (host)");
1297
                        goto error;
1298
                }
1299
                if(!json_is_string(json_host)) {
1300
                        JANUS_LOG(LOG_ERR, "Invalid element (host should be a string)\n");
1301
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1302
                        g_snprintf(error_cause, 512, "Invalid element (host should be a string)");
1303
                        goto error;
1304
                }
1305
                
1306
                guint64 room_id = json_integer_value(room);
1307
                guint64 publisher_id = json_integer_value(pub_id);
1308
                const gchar* host = json_string_value(json_host);
1309
                janus_mutex_lock(&rooms_mutex);
1310
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
1311
                janus_mutex_unlock(&rooms_mutex);
1312
                if(videoroom == NULL) {
1313
                        janus_mutex_unlock(&rooms_mutex);
1314
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1315
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1316
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1317
                        goto error;
1318
                }
1319
                if(videoroom->destroyed) {
1320
                        janus_mutex_unlock(&rooms_mutex)
1321
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", videoroom->room_id);
1322
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1323
                        g_snprintf(error_cause, 512, "Videoroom (%"SCNu64")", videoroom->room_id);
1324
                        goto error;
1325
                }
1326
                if(videoroom->room_secret) {
1327
                        /* A secret is required for this action */
1328
                        json_t *secret = json_object_get(root, "secret");
1329
                        if(!secret) {
1330
                                janus_mutex_unlock(&rooms_mutex);
1331
                                JANUS_LOG(LOG_ERR, "Missing element (secret)\n");
1332
                                error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1333
                                g_snprintf(error_cause, 512, "Missing element (secret)");
1334
                                goto error;
1335
                        }
1336
                        if(!json_is_string(secret)) {
1337
                                janus_mutex_unlock(&rooms_mutex);
1338
                                JANUS_LOG(LOG_ERR, "Invalid element (secret should be a string)\n");
1339
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1340
                                g_snprintf(error_cause, 512, "Invalid element (secret should be a string)");
1341
                                goto error;
1342
                        }
1343
                        if(!janus_strcmp_const_time(videoroom->room_secret, json_string_value(secret))) {
1344
                                janus_mutex_unlock(&rooms_mutex);
1345
                                JANUS_LOG(LOG_ERR, "Unauthorized (wrong secret)\n");
1346
                                error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
1347
                                g_snprintf(error_cause, 512, "Unauthorized (wrong secret)");
1348
                                goto error;
1349
                        }
1350
                }
1351
                janus_mutex_lock(&videoroom->participants_mutex);
1352
                janus_videoroom_participant* publisher = g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(publisher_id));
1353
                if(publisher == NULL) {
1354
                        janus_mutex_unlock(&videoroom->participants_mutex);
1355
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1356
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1357
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1358
                        goto error;
1359
                }
1360
                if(publisher->udp_sock <= 0) {
1361
                        publisher->udp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1362
                        if(publisher->udp_sock <= 0) {
1363
                                janus_mutex_unlock(&videoroom->participants_mutex);
1364
                                JANUS_LOG(LOG_ERR, "Could not open UDP socket for rtp stream for publisher (%"SCNu64")\n", publisher_id);
1365
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1366
                                g_snprintf(error_cause, 512, "Could not open UDP socket for rtp stream");
1367
                                goto error;
1368
                        }
1369
                }
1370
                guint32 audio_handle = 0;
1371
                guint32 video_handle = 0;
1372
                if(audio_port > 0) {
1373
                        audio_handle = janus_rtp_forwarder_add_helper(publisher, host, audio_port, 0);
1374
                }
1375
                if(video_port > 0) {
1376
                        video_handle = janus_rtp_forwarder_add_helper(publisher, host, video_port, 1);
1377
                }
1378
                janus_mutex_unlock(&videoroom->participants_mutex);
1379
                response = json_object();
1380
                json_t* rtp_stream = json_object();
1381
                if(audio_handle > 0) {
1382
                        json_object_set_new(rtp_stream, "audio_stream_id", json_integer(audio_handle));
1383
                        json_object_set_new(rtp_stream, "audio", json_integer(audio_port));
1384
                }
1385
                if(video_handle > 0) {
1386
                        json_object_set_new(rtp_stream, "video_stream_id", json_integer(video_handle));
1387
                        json_object_set_new(rtp_stream, "video", json_integer(video_port));
1388
                }
1389
                json_object_set_new(rtp_stream, "host", json_string(host));
1390
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1391
                json_object_set_new(response, "rtp_stream", rtp_stream);
1392
                json_object_set_new(response, "room", json_integer(room_id));
1393
                json_object_set_new(response, "videoroom", json_string("rtp_forward"));
1394
                goto plugin_response;
1395
        } else if(!strcasecmp(request_text, "stop_rtp_forward")) {
1396
                json_t *room = json_object_get(root, "room");
1397
                if(!room) {
1398
                        JANUS_LOG(LOG_ERR, "Missing element (room)\n");
1399
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1400
                        g_snprintf(error_cause, 512, "Missing element (room)");
1401
                        goto error;
1402
                }
1403
                if(!json_is_integer(room) || json_integer_value(room) < 0) {
1404
                        JANUS_LOG(LOG_ERR, "Invalid element (room should be a positive integer)\n");
1405
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1406
                        g_snprintf(error_cause, 512, "Invalid element (room should be a positive integer)");
1407
                        goto error;
1408
                }
1409
                json_t *pub_id = json_object_get(root, "publisher_id");
1410
                if(!pub_id) {
1411
                        JANUS_LOG(LOG_ERR, "Missing element (publisher_id)\n");
1412
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1413
                        g_snprintf(error_cause, 512, "Missing element (publisher_id)");
1414
                        goto error;
1415
                }
1416
                if(!json_is_integer(pub_id) || json_integer_value(pub_id) < 0) {
1417
                        JANUS_LOG(LOG_ERR, "Invalid element (publisher_id should be a positive integer)\n");
1418
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1419
                        g_snprintf(error_cause, 512, "Invalid element (publisher_id should be a positive integer)");
1420
                        goto error;
1421
                }
1422
                json_t *id = json_object_get(root, "stream_id");
1423
                if(!id) {
1424
                        JANUS_LOG(LOG_ERR, "Missing element (stream_id)\n");
1425
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1426
                        g_snprintf(error_cause, 512, "Missing element (stream_id)");
1427
                        goto error;
1428
                }
1429
                if(!json_is_integer(id) || json_integer_value(id) < 0) {
1430
                        JANUS_LOG(LOG_ERR, "Invalid element (stream_id should be a positive integer)\n");
1431
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1432
                        g_snprintf(error_cause, 512, "Invalid element (stream_id should be a positive integer)");
1433
                        goto error;
1434
                }
1435

    
1436
                guint64 room_id = json_integer_value(room);
1437
                guint64 publisher_id = json_integer_value(pub_id);
1438
                int stream_id = json_integer_value(id);
1439
                janus_mutex_lock(&rooms_mutex);
1440
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
1441
                janus_mutex_unlock(&rooms_mutex);
1442
                if(videoroom == NULL) {
1443
                        janus_mutex_unlock(&rooms_mutex);
1444
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1445
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1446
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1447
                        goto error;
1448
                }
1449
                if(videoroom->destroyed) {
1450
                        janus_mutex_unlock(&rooms_mutex)
1451
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", videoroom->room_id);
1452
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1453
                        g_snprintf(error_cause, 512, "Videoroom (%"SCNu64")", videoroom->room_id);
1454
                        goto error;
1455
                }
1456
                if(videoroom->room_secret) {
1457
                        /* A secret is required for this action */
1458
                        json_t *secret = json_object_get(root, "secret");
1459
                        if(!secret) {
1460
                                janus_mutex_unlock(&rooms_mutex);
1461
                                JANUS_LOG(LOG_ERR, "Missing element (secret)\n");
1462
                                error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1463
                                g_snprintf(error_cause, 512, "Missing element (secret)");
1464
                                goto error;
1465
                        }
1466
                        if(!json_is_string(secret)) {
1467
                                janus_mutex_unlock(&rooms_mutex);
1468
                                JANUS_LOG(LOG_ERR, "Invalid element (secret should be a string)\n");
1469
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
1470
                                g_snprintf(error_cause, 512, "Invalid element (secret should be a string)");
1471
                                goto error;
1472
                        }
1473
                        if(!janus_strcmp_const_time(videoroom->room_secret, json_string_value(secret))) {
1474
                                janus_mutex_unlock(&rooms_mutex);
1475
                                JANUS_LOG(LOG_ERR, "Unauthorized (wrong secret)\n");
1476
                                error_code = JANUS_VIDEOROOM_ERROR_UNAUTHORIZED;
1477
                                g_snprintf(error_cause, 512, "Unauthorized (wrong secret)");
1478
                                goto error;
1479
                        }
1480
                }
1481
                janus_mutex_lock(&videoroom->participants_mutex);
1482
                janus_videoroom_participant* publisher = g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(publisher_id));
1483
                if(publisher == NULL) {
1484
                        janus_mutex_unlock(&videoroom->participants_mutex);
1485
                        JANUS_LOG(LOG_ERR, "No such publisher (%"SCNu64")\n", publisher_id);
1486
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
1487
                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", publisher_id);
1488
                        goto error;
1489
                }
1490
                janus_mutex_lock(&publisher->rtp_forwarders_mutex);
1491
                g_hash_table_remove(publisher->rtp_forwarders, GUINT_TO_POINTER(stream_id));
1492
                janus_mutex_unlock(&publisher->rtp_forwarders_mutex);
1493
                janus_mutex_unlock(&videoroom->participants_mutex);
1494
                response = json_object();
1495
                json_object_set_new(response, "videoroom", json_string("stop_rtp_forward"));
1496
                json_object_set_new(response, "room", json_integer(room_id));
1497
                json_object_set_new(response, "publisher_id", json_integer(publisher_id));
1498
                json_object_set_new(response, "stream_id", json_integer(stream_id));
1499
                goto plugin_response;
1500
        } else if(!strcasecmp(request_text, "exists")) {
1501
                /* Check whether a given room exists or not, returns true/false */        
1502
                json_t *room = json_object_get(root, "room");
1503
                if(!room || !json_is_integer(room) || json_integer_value(room) < 0) {
1504
                        JANUS_LOG(LOG_ERR, "Invalid request, room number must be included in request and must be a positive integer\n");
1505
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1506
                        g_snprintf(error_cause, 512, "Missing element (room)");
1507
                        goto error;
1508
                }
1509
                guint64 room_id = json_integer_value(room);
1510
                janus_mutex_lock(&rooms_mutex);
1511
                gboolean room_exists = g_hash_table_contains(rooms, GUINT_TO_POINTER(room_id));
1512
                janus_mutex_unlock(&rooms_mutex);
1513
                response = json_object();
1514
                json_object_set_new(response, "videoroom", json_string("success"));
1515
                json_object_set_new(response, "room", json_integer(room_id));
1516
                json_object_set_new(response, "exists", json_string(room_exists ? "true" : "false"));
1517
                goto plugin_response;
1518
        } else if(!strcasecmp(request_text, "listparticipants")) {
1519
                /* List all participants in a room, specifying whether they're publishers or just attendees */        
1520
                json_t *room = json_object_get(root, "room");
1521
                if(!room || !json_is_integer(room) || json_integer_value(room) < 0) {
1522
                        JANUS_LOG(LOG_ERR, "Invalid request, room number must be included in request and must be a positive integer\n");
1523
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
1524
                        g_snprintf(error_cause, 512, "Missing element (room)");
1525
                        goto error;
1526
                }
1527
                guint64 room_id = json_integer_value(room);
1528
                janus_mutex_lock(&rooms_mutex);
1529
                janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
1530
                janus_mutex_unlock(&rooms_mutex);
1531
                if(videoroom == NULL) {
1532
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1533
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1534
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1535
                        goto error;
1536
                }
1537
                if(videoroom->destroyed) {
1538
                        JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
1539
                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
1540
                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
1541
                        goto error;
1542
                }
1543
                /* Return a list of all participants (whether they're publishing or not) */
1544
                json_t *list = json_array();
1545
                GHashTableIter iter;
1546
                gpointer value;
1547
                janus_mutex_lock(&videoroom->participants_mutex);
1548
                g_hash_table_iter_init(&iter, videoroom->participants);
1549
                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1550
                        janus_videoroom_participant *p = value;
1551
                        json_t *pl = json_object();
1552
                        json_object_set_new(pl, "id", json_integer(p->user_id));
1553
                        if(p->display)
1554
                                json_object_set_new(pl, "display", json_string(p->display));
1555
                        json_object_set_new(pl, "publisher", json_string(p->sdp ? "true" : "false"));
1556
                        json_array_append_new(list, pl);
1557
                }
1558
                janus_mutex_unlock(&videoroom->participants_mutex);
1559
                response = json_object();
1560
                json_object_set_new(response, "videoroom", json_string("participants"));
1561
                json_object_set_new(response, "room", json_integer(room_id));
1562
                json_object_set_new(response, "participants", list);
1563
                goto plugin_response;
1564
        } else if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")
1565
                        || !strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish") || !strcasecmp(request_text, "unpublish")
1566
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "pause") || !strcasecmp(request_text, "switch") || !strcasecmp(request_text, "stop")
1567
                        || !strcasecmp(request_text, "add") || !strcasecmp(request_text, "remove") || !strcasecmp(request_text, "leave")) {
1568
                /* These messages are handled asynchronously */
1569

    
1570
                janus_videoroom_message *msg = calloc(1, sizeof(janus_videoroom_message));
1571
                if(msg == NULL) {
1572
                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
1573
                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1574
                        g_snprintf(error_cause, 512, "Memory error");
1575
                        goto error;
1576
                }
1577

    
1578
                g_free(message);
1579
                msg->handle = handle;
1580
                msg->transaction = transaction;
1581
                msg->message = root;
1582
                msg->sdp_type = sdp_type;
1583
                msg->sdp = sdp;
1584
                g_async_queue_push(messages, msg);
1585

    
1586
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
1587
        } else {
1588
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
1589
                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
1590
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
1591
                goto error;
1592
        }
1593

    
1594
plugin_response:
1595
                {
1596
                        if (!response) {
1597
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
1598
                                g_snprintf(error_cause, 512, "Invalid response");
1599
                                goto error;
1600
                        }
1601
                        if(root != NULL)
1602
                                json_decref(root);
1603
                        g_free(transaction);
1604
                        g_free(message);
1605
                        g_free(sdp_type);
1606
                        g_free(sdp);
1607

    
1608
                        char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1609
                        json_decref(response);
1610
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
1611
                        g_free(response_text);
1612
                        return result;
1613
                }
1614

    
1615
error:
1616
                {
1617
                        if(root != NULL)
1618
                                json_decref(root);
1619
                        g_free(transaction);
1620
                        g_free(message);
1621
                        g_free(sdp_type);
1622
                        g_free(sdp);
1623

    
1624
                        /* Prepare JSON error event */
1625
                        json_t *event = json_object();
1626
                        json_object_set_new(event, "videoroom", json_string("event"));
1627
                        json_object_set_new(event, "error_code", json_integer(error_code));
1628
                        json_object_set_new(event, "error", json_string(error_cause));
1629
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1630
                        json_decref(event);
1631
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, event_text);
1632
                        g_free(event_text);
1633
                        return result;
1634
                }
1635

    
1636
}
1637

    
1638
void janus_videoroom_setup_media(janus_plugin_session *handle) {
1639
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
1640
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1641
                return;
1642
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1643
        if(!session) {
1644
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1645
                return;
1646
        }
1647
        if(session->destroyed)
1648
                return;
1649
        g_atomic_int_set(&session->hangingup, 0);
1650
        /* Media relaying can start now */
1651
        session->started = TRUE;
1652
        /* If this is a listener, ask the publisher a FIR */
1653
        if(session->participant) {
1654
                if(session->participant_type == janus_videoroom_p_type_subscriber) {
1655
                        janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
1656
                        if(l && l->feed) {
1657
                                janus_videoroom_participant *p = l->feed;
1658
                                if(p && p->session) {
1659
                                        /* Send a FIR */
1660
                                        char buf[20];
1661
                                        memset(buf, 0, 20);
1662
                                        janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
1663
                                        JANUS_LOG(LOG_VERB, "New listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1664
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 20);
1665
                                        /* Send a PLI too, just in case... */
1666
                                        memset(buf, 0, 12);
1667
                                        janus_rtcp_pli((char *)&buf, 12);
1668
                                        JANUS_LOG(LOG_VERB, "New listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1669
                                        gateway->relay_rtcp(p->session->handle, 1, buf, 12);
1670
                                }
1671
                        }
1672
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1673
                        /* Do the same, but for all feeds */
1674
                        janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
1675
                        if(listener == NULL)
1676
                                return;
1677
                        GSList *ps = listener->listeners;
1678
                        while(ps) {
1679
                                janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
1680
                                if(l && l->feed) {
1681
                                        janus_videoroom_participant *p = l->feed;
1682
                                        if(p && p->session) {
1683
                                                /* Send a FIR */
1684
                                                char buf[20];
1685
                                                memset(buf, 0, 20);
1686
                                                janus_rtcp_fir((char *)&buf, 20, &p->fir_seq);
1687
                                                JANUS_LOG(LOG_VERB, "New Multiplexed listener available, sending FIR to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1688
                                                gateway->relay_rtcp(p->session->handle, 1, buf, 20);
1689
                                                /* Send a PLI too, just in case... */
1690
                                                memset(buf, 0, 12);
1691
                                                janus_rtcp_pli((char *)&buf, 12);
1692
                                                JANUS_LOG(LOG_VERB, "New Multiplexed listener available, sending PLI to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1693
                                                gateway->relay_rtcp(p->session->handle, 1, buf, 12);
1694
                                        }
1695
                                }
1696
                                ps = ps->next;
1697
                        }
1698
                }
1699
        }
1700
}
1701

    
1702
void janus_videoroom_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1703
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1704
                return;
1705
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1706
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
1707
                return;
1708
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1709
        if((!video && participant->audio_active) || (video && participant->video_active)) {
1710
                /* Update payload type and SSRC */
1711
                rtp_header *rtp = (rtp_header *)buf;
1712
                rtp->type = video ? VP8_PT : OPUS_PT;
1713
                rtp->ssrc = htonl(video ? participant->video_ssrc : participant->audio_ssrc);
1714
                /* Forward RTP to the appropriate port for the rtp_forwarders associated wih this publisher, if there are any */
1715
                GHashTableIter iter;
1716
                gpointer value;
1717
                g_hash_table_iter_init(&iter, participant->rtp_forwarders);
1718
                janus_mutex_lock(&participant->rtp_forwarders_mutex);
1719
                while(participant->udp_sock > 0 && g_hash_table_iter_next(&iter, NULL, &value)) {
1720
                        rtp_forwarder* rtp_forward = (rtp_forwarder*)value;
1721
                        if(video && rtp_forward->is_video) {
1722
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
1723
                        }
1724
                        else if(!video && !rtp_forward->is_video) {
1725
                                sendto(participant->udp_sock, buf, len, 0, (struct sockaddr*)&rtp_forward->serv_addr, sizeof(rtp_forward->serv_addr));
1726
                        }
1727
                }
1728
                janus_mutex_unlock(&participant->rtp_forwarders_mutex);
1729
                /* Save the frame if we're recording */
1730
                if(video && participant->vrc)
1731
                        janus_recorder_save_frame(participant->vrc, buf, len);
1732
                else if(!video && participant->arc)
1733
                        janus_recorder_save_frame(participant->arc, buf, len);
1734
                /* Done, relay it */
1735
                janus_videoroom_rtp_relay_packet packet;
1736
                packet.data = rtp;
1737
                packet.length = len;
1738
                packet.is_video = video;
1739
                /* Backup the actual timestamp and sequence number set by the publisher, in case switching is involved */
1740
                packet.timestamp = ntohl(packet.data->timestamp);
1741
                packet.seq_number = ntohs(packet.data->seq_number);
1742
                /* Go */
1743
                g_slist_foreach(participant->listeners, janus_videoroom_relay_rtp_packet, &packet);
1744
                
1745
                /* Check if we need to send any REMB, FIR or PLI back to this publisher */
1746
                if(video && participant->video_active) {
1747
                        /* Did we send a REMB already, or is it time to send one? */
1748
                        gboolean send_remb = FALSE;
1749
                        if(participant->remb_latest == 0 && participant->remb_startup > 0) {
1750
                                /* Still in the starting phase, send the ramp-up REMB feedback */
1751
                                send_remb = TRUE;
1752
                        } else if(participant->remb_latest > 0 && janus_get_monotonic_time()-participant->remb_latest >= 5*G_USEC_PER_SEC) {
1753
                                /* 5 seconds have passed since the last REMB, send a new one */
1754
                                send_remb = TRUE;
1755
                        }                
1756
                        if(send_remb) {
1757
                                /* We send a few incremental REMB messages at startup */
1758
                                uint64_t bitrate = (participant->bitrate ? participant->bitrate : 256*1024);
1759
                                if(participant->remb_startup > 0) {
1760
                                        bitrate = bitrate/participant->remb_startup;
1761
                                        participant->remb_startup--;
1762
                                }
1763
                                char rtcpbuf[200];
1764
                                memset(rtcpbuf, 0, 200);
1765
                                /* FIXME First put a RR (fake)... */
1766
                                int rrlen = 32;
1767
                                rtcp_rr *rr = (rtcp_rr *)&rtcpbuf;
1768
                                rr->header.version = 2;
1769
                                rr->header.type = RTCP_RR;
1770
                                rr->header.rc = 1;
1771
                                rr->header.length = htons((rrlen/4)-1);
1772
                                /* ... then put a SDES... */
1773
                                int sdeslen = janus_rtcp_sdes((char *)(&rtcpbuf)+rrlen, 200-rrlen, "janusvideo", 10);
1774
                                if(sdeslen > 0) {
1775
                                        /* ... and then finally a REMB */
1776
                                        janus_rtcp_remb((char *)(&rtcpbuf)+rrlen+sdeslen, 24, bitrate);
1777
                                        gateway->relay_rtcp(handle, video, rtcpbuf, rrlen+sdeslen+24);
1778
                                }
1779
                                JANUS_LOG(LOG_VERB, "Sending REMB\n");
1780
                                if(participant->remb_startup == 0)
1781
                                        participant->remb_latest = janus_get_monotonic_time();
1782
                        }
1783
                        /* Generate FIR/PLI too, if needed */
1784
                        if(video && participant->video_active && (participant->room->fir_freq > 0)) {
1785
                                /* FIXME Very ugly hack to generate RTCP every tot seconds/frames */
1786
                                gint64 now = janus_get_monotonic_time();
1787
                                if((now-participant->fir_latest) >= (participant->room->fir_freq*G_USEC_PER_SEC)) {
1788
                                        /* FIXME We send a FIR every tot seconds */
1789
                                        participant->fir_latest = now;
1790
                                        char rtcpbuf[24];
1791
                                        memset(rtcpbuf, 0, 24);
1792
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &participant->fir_seq);
1793
                                        JANUS_LOG(LOG_VERB, "Sending FIR to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
1794
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 20);
1795
                                        /* Send a PLI too, just in case... */
1796
                                        memset(rtcpbuf, 0, 12);
1797
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
1798
                                        JANUS_LOG(LOG_VERB, "Sending PLI to %"SCNu64" (%s)\n", participant->user_id, participant->display ? participant->display : "??");
1799
                                        gateway->relay_rtcp(handle, video, rtcpbuf, 12);
1800
                                }
1801
                        }
1802
                }
1803
        }
1804
}
1805

    
1806
void janus_videoroom_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1807
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1808
                return;
1809
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1810
        if(!session) {
1811
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1812
                return;
1813
        }
1814
        if(session->destroyed)
1815
                return;
1816
        if(session->participant_type == janus_videoroom_p_type_subscriber) {
1817
                /* A listener sent some RTCP, check what it is and if we need to forward it to the publisher */
1818
                janus_videoroom_listener *l = (janus_videoroom_listener *)session->participant;
1819
                if(!l->video)
1820
                        return;        /* The only feedback we handle is video related anyway... */
1821
                if(janus_rtcp_has_fir(buf, len)) {
1822
                        /* We got a FIR, forward it to the publisher */
1823
                        if(l && l->feed) {
1824
                                janus_videoroom_participant *p = l->feed;
1825
                                if(p && p->session) {
1826
                                        char rtcpbuf[20];
1827
                                        memset(rtcpbuf, 0, 20);
1828
                                        janus_rtcp_fir((char *)&rtcpbuf, 20, &p->fir_seq);
1829
                                        JANUS_LOG(LOG_VERB, "Got a FIR from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1830
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 20);
1831
                                }
1832
                        }
1833
                }
1834
                if(janus_rtcp_has_pli(buf, len)) {
1835
                        /* We got a PLI, forward it to the publisher */
1836
                        if(l && l->feed) {
1837
                                janus_videoroom_participant *p = l->feed;
1838
                                if(p && p->session) {
1839
                                        char rtcpbuf[12];
1840
                                        memset(rtcpbuf, 0, 12);
1841
                                        janus_rtcp_pli((char *)&rtcpbuf, 12);
1842
                                        JANUS_LOG(LOG_VERB, "Got a PLI from a listener, forwarding it to %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1843
                                        gateway->relay_rtcp(p->session->handle, 1, rtcpbuf, 12);
1844
                                }
1845
                        }
1846
                }
1847
                uint64_t bitrate = janus_rtcp_get_remb(buf, len);
1848
                if(bitrate > 0) {
1849
                        /* FIXME We got a REMB from this listener, should we do something about it? */
1850
                }
1851
        }
1852
}
1853

    
1854
void janus_videoroom_incoming_data(janus_plugin_session *handle, char *buf, int len) {
1855
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1856
                return;
1857
        if(buf == NULL || len <= 0)
1858
                return;
1859
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1860
        if(!session || session->destroyed || !session->participant || session->participant_type != janus_videoroom_p_type_publisher)
1861
                return;
1862
        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1863
        /* Get a string out of the data */
1864
        char *text = g_malloc0(len+1);
1865
        memcpy(text, buf, len);
1866
        *(text+len) = '\0';
1867
        JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
1868
        g_slist_foreach(participant->listeners, janus_videoroom_relay_data_packet, text);
1869
        g_free(text);
1870
}
1871

    
1872
void janus_videoroom_slow_link(janus_plugin_session *handle, int uplink, int video) {
1873
        /* The core is informing us that our peer got too many NACKs, are we pushing media too hard? */
1874
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1875
                return;
1876
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;
1877
        if(!session || session->destroyed || !session->participant)
1878
                return;
1879
        /* Check if it's an uplink (publisher) or downlink (viewer) issue */
1880
        if(session->participant_type == janus_videoroom_p_type_publisher) {
1881
                if(!uplink) {
1882
                        janus_videoroom_participant *publisher = (janus_videoroom_participant *)session->participant;
1883
                        if(publisher) {
1884
                                /* Send an event on the handle to notify the application: it's
1885
                                 * up to the application to then choose a policy and enforce it */
1886
                                json_t *event = json_object();
1887
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
1888
                                /* Also add info on what the current bitrate cap is */
1889
                                uint64_t bitrate = (publisher->bitrate ? publisher->bitrate : 256*1024);
1890
                                json_object_set_new(event, "current-bitrate", json_integer(bitrate));
1891
                                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1892
                                json_decref(event);
1893
                                event = NULL;
1894
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event_text, NULL, NULL);
1895
                                g_free(event_text);
1896
                                event_text = NULL;
1897
                        }
1898
                } else {
1899
                        JANUS_LOG(LOG_WARN, "Got a slow uplink on a VideoRoom publisher? Weird, because it doesn't receive media...\n");
1900
                }
1901
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1902
                if(uplink) {
1903
                        janus_videoroom_listener *viewer = (janus_videoroom_listener *)session->participant;
1904
                        if(viewer) {
1905
                                /* Send an event on the handle to notify the application: it's
1906
                                 * up to the application to then choose a policy and enforce it */
1907
                                json_t *event = json_object();
1908
                                json_object_set_new(event, "videoroom", json_string("slow_link"));
1909
                                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1910
                                json_decref(event);
1911
                                event = NULL;
1912
                                gateway->push_event(session->handle, &janus_videoroom_plugin, NULL, event_text, NULL, NULL);
1913
                                g_free(event_text);
1914
                                event_text = NULL;
1915
                        }
1916
                } else {
1917
                        JANUS_LOG(LOG_WARN, "Got a slow downlink on a VideoRoom viewer? Weird, because it doesn't send media...\n");
1918
                }
1919
        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
1920
                /* TBD. */
1921
        }
1922
}
1923

    
1924
void janus_videoroom_hangup_media(janus_plugin_session *handle) {
1925
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1926
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1927
                return;
1928
        janus_videoroom_session *session = (janus_videoroom_session *)handle->plugin_handle;        
1929
        if(!session) {
1930
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1931
                return;
1932
        }
1933
        session->started = FALSE;
1934
        if(session->destroyed)
1935
                return;
1936
        if(g_atomic_int_add(&session->hangingup, 1))
1937
                return;
1938
        /* Send an event to the browser and tell the PeerConnection is over */
1939
        if(session->participant_type == janus_videoroom_p_type_publisher) {
1940
                /* This publisher just 'unpublished' */
1941
                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
1942
                if(participant->sdp)
1943
                        g_free(participant->sdp);
1944
                participant->sdp = NULL;
1945
                participant->firefox = FALSE;
1946
                participant->audio_active = FALSE;
1947
                participant->video_active = FALSE;
1948
                participant->remb_startup = 4;
1949
                participant->remb_latest = 0;
1950
                participant->fir_latest = 0;
1951
                participant->fir_seq = 0;
1952
                /* Get rid of the recorders, if available */
1953
                if(participant->arc) {
1954
                        janus_recorder_close(participant->arc);
1955
                        JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", participant->arc->filename ? participant->arc->filename : "??");
1956
                        janus_recorder_free(participant->arc);
1957
                }
1958
                participant->arc = NULL;
1959
                if(participant->vrc) {
1960
                        janus_recorder_close(participant->vrc);
1961
                        JANUS_LOG(LOG_INFO, "Closed video recording %s\n", participant->vrc->filename ? participant->vrc->filename : "??");
1962
                        janus_recorder_free(participant->vrc);
1963
                }
1964
                participant->vrc = NULL;
1965
                janus_mutex_lock(&participant->listeners_mutex);
1966
                while(participant->listeners) {
1967
                        janus_videoroom_listener *l = (janus_videoroom_listener *)participant->listeners->data;
1968
                        if(l) {
1969
                                participant->listeners = g_slist_remove(participant->listeners, l);
1970
                                l->feed = NULL;
1971
                        }
1972
                }
1973
                janus_mutex_unlock(&participant->listeners_mutex);
1974
                json_t *event = json_object();
1975
                json_object_set_new(event, "videoroom", json_string("event"));
1976
                json_object_set_new(event, "room", json_integer(participant->room->room_id));
1977
                json_object_set_new(event, "unpublished", json_integer(participant->user_id));
1978
                char *unpub_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1979
                json_decref(event);
1980
                GHashTableIter iter;
1981
                gpointer value;
1982
                if(participant && participant->room) {
1983
                        if(!participant->room->destroyed) {
1984
                                janus_mutex_lock(&participant->room->participants_mutex);
1985
                                g_hash_table_iter_init(&iter, participant->room->participants);
1986
                                while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
1987
                                        janus_videoroom_participant *p = value;
1988
                                        if(p && p->session && p != participant) {
1989
                                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
1990
                                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, unpub_text, NULL, NULL);
1991
                                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1992
                                        }
1993
                                }
1994
                                janus_mutex_unlock(&participant->room->participants_mutex);
1995
                        }
1996
                }
1997
                g_free(unpub_text);
1998
        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
1999
                /* Get rid of listener */
2000
                janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2001
                if(listener) {
2002
                        listener->paused = TRUE;
2003
                        janus_videoroom_participant *publisher = listener->feed;
2004
                        if(publisher != NULL) {
2005
                                janus_mutex_lock(&publisher->listeners_mutex);
2006
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
2007
                                janus_mutex_unlock(&publisher->listeners_mutex);
2008
                                listener->feed = NULL;
2009
                        }
2010
                }
2011
                /* TODO Should we close the handle as well? */
2012
        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
2013
                /* Do the same, but for all sub-listener */
2014
                janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
2015
                GSList *ps = listener->listeners;
2016
                while(ps) {
2017
                        janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
2018
                        if(l) {
2019
                                l->paused = TRUE;
2020
                                janus_videoroom_participant *publisher = l->feed;
2021
                                if(publisher != NULL) {
2022
                                        janus_mutex_lock(&publisher->listeners_mutex);
2023
                                        publisher->listeners = g_slist_remove(publisher->listeners, listener);
2024
                                        janus_mutex_unlock(&publisher->listeners_mutex);
2025
                                        l->feed = NULL;
2026
                                }
2027
                        }
2028
                        /* TODO Should we close the handle as well? */
2029
                        ps = ps->next;
2030
                }
2031
                /* TODO Should we close the handle as well? */
2032
        }
2033
}
2034

    
2035
/* Thread to handle incoming messages */
2036
static void *janus_videoroom_handler(void *data) {
2037
        JANUS_LOG(LOG_VERB, "Joining VideoRoom handler thread\n");
2038
        janus_videoroom_message *msg = NULL;
2039
        int error_code = 0;
2040
        char *error_cause = calloc(512, sizeof(char));        /* FIXME 512 should be enough, but anyway... */
2041
        if(error_cause == NULL) {
2042
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
2043
                return NULL;
2044
        }
2045
        json_t *root = NULL;
2046
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
2047
                if(!messages || (msg = g_async_queue_try_pop(messages)) == NULL) {
2048
                        usleep(50000);
2049
                        continue;
2050
                }
2051

    
2052
                janus_videoroom_session *session = (janus_videoroom_session *)msg->handle->plugin_handle;        
2053
                if(!session) {
2054
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
2055
                        janus_videoroom_message_free(msg);
2056
                        continue;
2057
                }
2058
                if(session->destroyed) {
2059
                        janus_videoroom_message_free(msg);
2060
                        continue;
2061
                }
2062
                /* Handle request */
2063
                error_code = 0;
2064
                root = NULL;
2065
                if(msg->message == NULL) {
2066
                        JANUS_LOG(LOG_ERR, "No message??\n");
2067
                        error_code = JANUS_VIDEOROOM_ERROR_NO_MESSAGE;
2068
                        g_snprintf(error_cause, 512, "%s", "No message??");
2069
                        goto error;
2070
                }
2071
                root = msg->message;
2072
                /* Get the request first */
2073
                json_t *request = json_object_get(root, "request");
2074
                if(!request) {
2075
                        JANUS_LOG(LOG_ERR, "Missing element (request)\n");
2076
                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
2077
                        g_snprintf(error_cause, 512, "Missing element (request)");
2078
                        goto error;
2079
                }
2080
                if(!json_is_string(request)) {
2081
                        JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
2082
                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2083
                        g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
2084
                        goto error;
2085
                }
2086
                const char *request_text = json_string_value(request);
2087
                json_t *event = NULL;
2088
                /* 'create' and 'destroy' are handled synchronously: what kind of participant is this session referring to? */
2089
                if(session->participant_type == janus_videoroom_p_type_none) {
2090
                        JANUS_LOG(LOG_VERB, "Configuring new participant\n");
2091
                        /* Not configured yet, we need to do this now */
2092
                        if(strcasecmp(request_text, "join") && strcasecmp(request_text, "joinandconfigure")) {
2093
                                JANUS_LOG(LOG_ERR, "Invalid request on unconfigured participant\n");
2094
                                error_code = JANUS_VIDEOROOM_ERROR_JOIN_FIRST;
2095
                                g_snprintf(error_cause, 512, "Invalid request on unconfigured participant");
2096
                                goto error;
2097
                        }
2098
                        json_t *room = json_object_get(root, "room");
2099
                        if(!room) {
2100
                                JANUS_LOG(LOG_ERR, "Missing element (room)\n");
2101
                                g_snprintf(error_cause, 512, "Missing element (room)");
2102
                                goto error;
2103
                        }
2104
                        if(!json_is_integer(room) || json_integer_value(room) < 0) {
2105
                                JANUS_LOG(LOG_ERR, "Invalid element (room should be a positive integer)\n");
2106
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2107
                                g_snprintf(error_cause, 512, "Invalid element (room should be a positive integer)");
2108
                                goto error;
2109
                        }
2110
                        guint64 room_id = json_integer_value(room);
2111
                        janus_mutex_lock(&rooms_mutex);
2112
                        janus_videoroom *videoroom = g_hash_table_lookup(rooms, GUINT_TO_POINTER(room_id));
2113
                        janus_mutex_unlock(&rooms_mutex);
2114
                        if(videoroom == NULL) {
2115
                                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
2116
                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2117
                                g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
2118
                                goto error;
2119
                        }
2120
                        if(videoroom->destroyed) {
2121
                                JANUS_LOG(LOG_ERR, "No such room (%"SCNu64")\n", room_id);
2122
                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2123
                                g_snprintf(error_cause, 512, "No such room (%"SCNu64")", room_id);
2124
                                goto error;
2125
                        }
2126
                        json_t *ptype = json_object_get(root, "ptype");
2127
                        if(!ptype) {
2128
                                JANUS_LOG(LOG_ERR, "Missing element (ptype)\n");
2129
                                error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
2130
                                g_snprintf(error_cause, 512, "Missing element (ptype)");
2131
                                goto error;
2132
                        }
2133
                        if(!json_is_string(ptype)) {
2134
                                JANUS_LOG(LOG_ERR, "Invalid element (ptype should be a string)\n");
2135
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2136
                                g_snprintf(error_cause, 512, "Invalid element (ptype should be a string)");
2137
                                goto error;
2138
                        }
2139
                        const char *ptype_text = json_string_value(ptype);
2140
                        if(!strcasecmp(ptype_text, "publisher")) {
2141
                                JANUS_LOG(LOG_VERB, "Configuring new publisher\n");
2142
                                json_t *display = json_object_get(root, "display");
2143
                                if(display && !json_is_string(display)) {
2144
                                        JANUS_LOG(LOG_ERR, "Invalid element (display should be a string)\n");
2145
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2146
                                        g_snprintf(error_cause, 512, "Invalid element (display should be a string)");
2147
                                        goto error;
2148
                                }
2149
                                const char *display_text = display ? json_string_value(display) : NULL;
2150
                                guint64 user_id = 0;
2151
                                json_t *id = json_object_get(root, "id");
2152
                                if(id) {
2153
                                        if(!json_is_integer(id) || json_integer_value(id) < 0) {
2154
                                                JANUS_LOG(LOG_ERR, "Invalid element (id should be a positive integer)\n");
2155
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2156
                                                g_snprintf(error_cause, 512, "Invalid element (id should be a positive integer)");
2157
                                                goto error;
2158
                                        }
2159
                                        user_id = json_integer_value(id);
2160
                                        janus_mutex_lock(&videoroom->participants_mutex);
2161
                                        if(g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(user_id)) != NULL) {
2162
                                                janus_mutex_unlock(&videoroom->participants_mutex);
2163
                                                /* User ID already taken */
2164
                                                JANUS_LOG(LOG_ERR, "User ID %"SCNu64" already exists\n", user_id);
2165
                                                error_code = JANUS_VIDEOROOM_ERROR_ID_EXISTS;
2166
                                                g_snprintf(error_cause, 512, "User ID %"SCNu64" already exists", user_id);
2167
                                                goto error;
2168
                                        }
2169
                                        janus_mutex_unlock(&videoroom->participants_mutex);
2170
                                }
2171
                                if(user_id == 0) {
2172
                                        /* Generate a random ID */
2173
                                        janus_mutex_lock(&videoroom->participants_mutex);
2174
                                        while(user_id == 0) {
2175
                                                user_id = g_random_int();
2176
                                                if(g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(user_id)) != NULL) {
2177
                                                        /* User ID already taken, try another one */
2178
                                                        user_id = 0;
2179
                                                }
2180
                                        }
2181
                                        janus_mutex_unlock(&videoroom->participants_mutex);
2182
                                }
2183
                                JANUS_LOG(LOG_VERB, "  -- Publisher ID: %"SCNu64"\n", user_id);
2184
                                json_t *audio = NULL, *video = NULL, *bitrate = NULL, *record = NULL, *recfile = NULL;
2185
                                if(!strcasecmp(request_text, "joinandconfigure")) {
2186
                                        /* Also configure (or publish a new feed) audio/video/bitrate for this new publisher */
2187
                                        audio = json_object_get(root, "audio");
2188
                                        if(audio && !json_is_boolean(audio)) {
2189
                                                JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
2190
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2191
                                                g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
2192
                                                goto error;
2193
                                        }
2194
                                        video = json_object_get(root, "video");
2195
                                        if(video && !json_is_boolean(video)) {
2196
                                                JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
2197
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2198
                                                g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
2199
                                                goto error;
2200
                                        }
2201
                                        bitrate = json_object_get(root, "bitrate");
2202
                                        if(bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
2203
                                                JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
2204
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2205
                                                g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)");
2206
                                                goto error;
2207
                                        }
2208
                                        record = json_object_get(root, "record");
2209
                                        if(record && !json_is_boolean(record)) {
2210
                                                JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
2211
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2212
                                                g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)");
2213
                                                goto error;
2214
                                        }
2215
                                        recfile = json_object_get(root, "filename");
2216
                                        if(recfile && !json_is_string(recfile)) {
2217
                                                JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
2218
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2219
                                                g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
2220
                                                goto error;
2221
                                        }
2222
                                }
2223
                                janus_videoroom_participant *publisher = calloc(1, sizeof(janus_videoroom_participant));
2224
                                if(publisher == NULL) {
2225
                                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
2226
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2227
                                        g_snprintf(error_cause, 512, "Memory error");
2228
                                        goto error;
2229
                                }
2230
                                publisher->session = session;
2231
                                publisher->room = videoroom;
2232
                                publisher->user_id = user_id;
2233
                                publisher->display = display_text ? g_strdup(display_text) : NULL;
2234
                                publisher->sdp = NULL;                /* We'll deal with this later */
2235
                                publisher->audio = FALSE;        /* We'll deal with this later */
2236
                                publisher->video = FALSE;        /* We'll deal with this later */
2237
                                publisher->data = FALSE;        /* We'll deal with this later */
2238
                                publisher->audio_active = FALSE;
2239
                                publisher->video_active = FALSE;
2240
                                publisher->recording_active = FALSE;
2241
                                publisher->recording_base = NULL;
2242
                                publisher->arc = NULL;
2243
                                publisher->vrc = NULL;
2244
                                publisher->firefox = FALSE;
2245
                                publisher->bitrate = videoroom->bitrate;
2246
                                publisher->listeners = NULL;
2247
                                janus_mutex_init(&publisher->listeners_mutex);
2248
                                publisher->audio_ssrc = g_random_int();
2249
                                publisher->video_ssrc = g_random_int();
2250
                                publisher->remb_startup = 4;
2251
                                publisher->remb_latest = 0;
2252
                                publisher->fir_latest = 0;
2253
                                publisher->fir_seq = 0;
2254
                                janus_mutex_init(&publisher->rtp_forwarders_mutex);
2255
                                publisher->rtp_forwarders = g_hash_table_new_full(NULL, NULL, NULL, (GDestroyNotify)janus_rtp_forwarder_free_helper);
2256
                                publisher->udp_sock = -1;
2257
                                /* In case we also wanted to configure */
2258
                                if(audio) {
2259
                                        publisher->audio_active = json_is_true(audio);
2260
                                        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);
2261
                                }
2262
                                if(video) {
2263
                                        publisher->video_active = json_is_true(video);
2264
                                        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);
2265
                                }
2266
                                if(bitrate) {
2267
                                        publisher->bitrate = json_integer_value(bitrate);
2268
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", publisher->bitrate, publisher->room->room_id, publisher->user_id);
2269
                                }
2270
                                if(record) {
2271
                                        publisher->recording_active = json_is_true(record);
2272
                                        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);
2273
                                }
2274
                                if(recfile) {
2275
                                        publisher->recording_base = g_strdup(json_string_value(recfile));
2276
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", publisher->recording_base, publisher->room->room_id, publisher->user_id);
2277
                                }
2278
                                /* Done */
2279
                                session->participant_type = janus_videoroom_p_type_publisher;
2280
                                session->participant = publisher;
2281
                                /* Return a list of all available publishers (those with an SDP available, that is) */
2282
                                json_t *list = json_array();
2283
                                GHashTableIter iter;
2284
                                gpointer value;
2285
                                janus_mutex_lock(&videoroom->participants_mutex);
2286
                                g_hash_table_insert(videoroom->participants, GUINT_TO_POINTER(user_id), publisher);
2287
                                g_hash_table_iter_init(&iter, videoroom->participants);
2288
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2289
                                        janus_videoroom_participant *p = value;
2290
                                        if(p == publisher || !p->sdp) {
2291
                                                continue;
2292
                                        }
2293
                                        json_t *pl = json_object();
2294
                                        json_object_set_new(pl, "id", json_integer(p->user_id));
2295
                                        if(p->display)
2296
                                                json_object_set_new(pl, "display", json_string(p->display));
2297
                                        json_array_append_new(list, pl);
2298
                                }
2299
                                janus_mutex_unlock(&videoroom->participants_mutex);
2300
                                event = json_object();
2301
                                json_object_set_new(event, "videoroom", json_string("joined"));
2302
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
2303
                                json_object_set_new(event, "description", json_string(videoroom->room_name));
2304
                                json_object_set_new(event, "id", json_integer(user_id));
2305
                                json_object_set_new(event, "publishers", list);
2306
                        } else if(!strcasecmp(ptype_text, "listener")) {
2307
                                JANUS_LOG(LOG_VERB, "Configuring new listener\n");
2308
                                /* This is a new listener */
2309
                                json_t *feed = json_object_get(root, "feed");
2310
                                if(!feed) {
2311
                                        JANUS_LOG(LOG_ERR, "Missing element (feed)\n");
2312
                                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
2313
                                        g_snprintf(error_cause, 512, "Missing element (feed)");
2314
                                        goto error;
2315
                                }
2316
                                if(!json_is_integer(feed) || json_integer_value(feed) < 0) {
2317
                                        JANUS_LOG(LOG_ERR, "Invalid element (feed should be a positive integer)\n");
2318
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2319
                                        g_snprintf(error_cause, 512, "Invalid element (feed should be a positive integer)");
2320
                                        goto error;
2321
                                }
2322
                                guint64 feed_id = json_integer_value(feed);
2323
                                json_t *audio = json_object_get(root, "audio");
2324
                                if(audio && !json_is_boolean(audio)) {
2325
                                        JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
2326
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2327
                                        g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
2328
                                        goto error;
2329
                                }
2330
                                json_t *video = json_object_get(root, "video");
2331
                                if(video && !json_is_boolean(video)) {
2332
                                        JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
2333
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2334
                                        g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
2335
                                        goto error;
2336
                                }
2337
                                json_t *data = json_object_get(root, "data");
2338
                                if(data && !json_is_boolean(data)) {
2339
                                        JANUS_LOG(LOG_ERR, "Invalid element (data should be a boolean)\n");
2340
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2341
                                        g_snprintf(error_cause, 512, "Invalid value (data should be a boolean)");
2342
                                        goto error;
2343
                                }
2344
                                janus_mutex_lock(&videoroom->participants_mutex);
2345
                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(feed_id));
2346
                                janus_mutex_unlock(&videoroom->participants_mutex);
2347
                                if(publisher == NULL || publisher->sdp == NULL) {
2348
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2349
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2350
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2351
                                        goto error;
2352
                                } else {
2353
                                        janus_videoroom_listener *listener = calloc(1, sizeof(janus_videoroom_listener));
2354
                                        if(listener == NULL) {
2355
                                                JANUS_LOG(LOG_FATAL, "Memory error!\n");
2356
                                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2357
                                                g_snprintf(error_cause, 512, "Memory error");
2358
                                                goto error;
2359
                                        }
2360
                                        listener->session = session;
2361
                                        listener->room = videoroom;
2362
                                        listener->feed = publisher;
2363
                                        /* Initialize the listener context */
2364
                                        listener->context.a_last_ssrc = 0;
2365
                                        listener->context.a_last_ssrc = 0;
2366
                                        listener->context.a_last_ts = 0;
2367
                                        listener->context.a_base_ts = 0;
2368
                                        listener->context.a_base_ts_prev = 0;
2369
                                        listener->context.v_last_ssrc = 0;
2370
                                        listener->context.v_last_ts = 0;
2371
                                        listener->context.v_base_ts = 0;
2372
                                        listener->context.v_base_ts_prev = 0;
2373
                                        listener->context.a_last_seq = 0;
2374
                                        listener->context.a_base_seq = 0;
2375
                                        listener->context.a_base_seq_prev = 0;
2376
                                        listener->context.v_last_seq = 0;
2377
                                        listener->context.v_base_seq = 0;
2378
                                        listener->context.v_base_seq_prev = 0;
2379
                                        listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
2380
                                        if(!publisher->audio)
2381
                                                listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
2382
                                        listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
2383
                                        if(!publisher->video)
2384
                                                listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
2385
                                        listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
2386
                                        if(!publisher->data)
2387
                                                listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
2388
                                        listener->paused = TRUE;        /* We need an explicit start from the listener */
2389
                                        listener->parent = NULL;
2390
                                        session->participant = listener;
2391
                                        janus_mutex_lock(&publisher->listeners_mutex);
2392
                                        publisher->listeners = g_slist_append(publisher->listeners, listener);
2393
                                        janus_mutex_unlock(&publisher->listeners_mutex);
2394
                                        event = json_object();
2395
                                        json_object_set_new(event, "videoroom", json_string("attached"));
2396
                                        json_object_set_new(event, "room", json_integer(videoroom->room_id));
2397
                                        json_object_set_new(event, "id", json_integer(feed_id));
2398
                                        if(publisher->display)
2399
                                                json_object_set_new(event, "display", json_string(publisher->display));
2400
                                        session->participant_type = janus_videoroom_p_type_subscriber;
2401
                                        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
2402
                                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2403
                                        json_decref(event);
2404
                                        /* Negotiate by sending the selected publisher SDP back */
2405
                                        if(publisher->sdp != NULL) {
2406
                                                /* How long will the gateway take to push the event? */
2407
                                                gint64 start = janus_get_monotonic_time();
2408
                                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, "offer", publisher->sdp);
2409
                                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
2410
                                                JANUS_LOG(LOG_VERB, "  >> %d\n", res);
2411
                                                g_free(event_text);
2412
                                                root = NULL;
2413
                                                janus_videoroom_message_free(msg);
2414
                                                continue;
2415
                                        }
2416
                                        g_free(event_text);
2417
                                }
2418
                        } else if(!strcasecmp(ptype_text, "muxed-listener")) {
2419
                                /* This is a new Multiplexed listener */
2420
                                JANUS_LOG(LOG_INFO, "Configuring new Multiplexed listener\n");
2421
                                /* Any feed we want to attach to already? */
2422
                                GList *list = NULL;
2423
                                json_t *feeds = json_object_get(root, "feeds");
2424
                                if(feeds && !json_is_array(feeds)) {
2425
                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds should be an array)\n");
2426
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2427
                                        g_snprintf(error_cause, 512, "Invalid element (feeds should be an array)");
2428
                                        goto error;
2429
                                }
2430
                                if(feeds && json_array_size(feeds) > 0) {
2431
                                        unsigned int i = 0;
2432
                                        int problem = 0;
2433
                                        for(i=0; i<json_array_size(feeds); i++) {
2434
                                                if(videoroom->destroyed) {
2435
                                                        problem = 1;
2436
                                                        JANUS_LOG(LOG_ERR, "Room destroyed");
2437
                                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2438
                                                        g_snprintf(error_cause, 512, "Room destroyed");
2439
                                                        break;
2440
                                                }
2441
                                                json_t *feed = json_array_get(feeds, i);
2442
                                                if(!feed || !json_is_integer(feed)) {
2443
                                                        problem = 1;
2444
                                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
2445
                                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2446
                                                        g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
2447
                                                        break;
2448
                                                }
2449
                                                uint64_t feed_id = json_integer_value(feed);
2450
                                                janus_mutex_lock(&videoroom->participants_mutex);
2451
                                                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(feed_id));
2452
                                                janus_mutex_unlock(&videoroom->participants_mutex);
2453
                                                if(publisher == NULL) { //~ || publisher->sdp == NULL) {
2454
                                                        /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
2455
                                                        problem = 1;
2456
                                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2457
                                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2458
                                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2459
                                                        break;
2460
                                                }
2461
                                                list = g_list_prepend(list, GUINT_TO_POINTER(feed_id));
2462
                                                JANUS_LOG(LOG_INFO, "  -- Subscribing to feed %"SCNu64"\n", feed_id);
2463
                                        }
2464
                                        if(problem) {
2465
                                                goto error;
2466
                                        }
2467
                                }
2468
                                /* Allocate listener */
2469
                                janus_videoroom_listener_muxed *listener = calloc(1, sizeof(janus_videoroom_listener_muxed));
2470
                                if(listener == NULL) {
2471
                                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
2472
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2473
                                        g_snprintf(error_cause, 512, "Memory error");
2474
                                        goto error;
2475
                                }
2476
                                listener->session = session;
2477
                                listener->room = videoroom;
2478
                                session->participant_type = janus_videoroom_p_type_subscriber_muxed;
2479
                                session->participant = listener;
2480
                                /* Ack that we created the listener */
2481
                                event = json_object();
2482
                                json_object_set_new(event, "videoroom", json_string("muxed-created"));
2483
                                json_object_set_new(event, "room", json_integer(videoroom->room_id));
2484
                                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
2485
                                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2486
                                json_decref(event);
2487
                                /* How long will the gateway take to push the event? */
2488
                                gint64 start = janus_get_monotonic_time();
2489
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, NULL, NULL);
2490
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
2491
                                JANUS_LOG(LOG_VERB, "  >> %d\n", res);
2492
                                g_free(event_text);
2493
                                root = NULL;
2494
                                /* Attach to feeds if needed */
2495
                                if(list != NULL) {
2496
                                        JANUS_LOG(LOG_INFO, "Subscribing to %d feeds\n", g_list_length(list));
2497
                                        list = g_list_reverse(list);
2498
                                        if(videoroom->destroyed || janus_videoroom_muxed_subscribe(listener, list, msg->transaction) < 0) {
2499
                                                JANUS_LOG(LOG_ERR, "Error subscribing!\n");
2500
                                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
2501
                                                g_snprintf(error_cause, 512, "Error subscribing!");
2502
                                                goto error;
2503
                                        }
2504
                                }
2505
                                janus_videoroom_message_free(msg);
2506
                                continue;
2507
                        } else {
2508
                                JANUS_LOG(LOG_ERR, "Invalid element (ptype)\n");
2509
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2510
                                g_snprintf(error_cause, 512, "Invalid element (ptype)");
2511
                                goto error;
2512
                        }
2513
                } else if(session->participant_type == janus_videoroom_p_type_publisher) {
2514
                        /* Handle this publisher */
2515
                        janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
2516
                        if(participant == NULL) {
2517
                                JANUS_LOG(LOG_ERR, "Invalid participant instance\n");
2518
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2519
                                g_snprintf(error_cause, 512, "Invalid participant instance");
2520
                                goto error;
2521
                        }
2522
                        if(!strcasecmp(request_text, "join") || !strcasecmp(request_text, "joinandconfigure")) {
2523
                                JANUS_LOG(LOG_ERR, "Already in as a publisher on this handle\n");
2524
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
2525
                                g_snprintf(error_cause, 512, "Already in as a publisher on this handle");
2526
                                goto error;
2527
                        } else if(!strcasecmp(request_text, "configure") || !strcasecmp(request_text, "publish")) {
2528
                                if(!strcasecmp(request_text, "publish") && participant->sdp) {
2529
                                        JANUS_LOG(LOG_ERR, "Can't publish, already published\n");
2530
                                        error_code = JANUS_VIDEOROOM_ERROR_ALREADY_PUBLISHED;
2531
                                        g_snprintf(error_cause, 512, "Can't publish, already published");
2532
                                        goto error;
2533
                                }
2534
                                /* Configure (or publish a new feed) audio/video/bitrate for this publisher */
2535
                                json_t *audio = json_object_get(root, "audio");
2536
                                if(audio && !json_is_boolean(audio)) {
2537
                                        JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
2538
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2539
                                        g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
2540
                                        goto error;
2541
                                }
2542
                                json_t *video = json_object_get(root, "video");
2543
                                if(video && !json_is_boolean(video)) {
2544
                                        JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
2545
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2546
                                        g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
2547
                                        goto error;
2548
                                }
2549
                                json_t *bitrate = json_object_get(root, "bitrate");
2550
                                if(bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
2551
                                        JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
2552
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2553
                                        g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)");
2554
                                        goto error;
2555
                                }
2556
                                json_t *record = json_object_get(root, "record");
2557
                                if(record && !json_is_boolean(record)) {
2558
                                        JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
2559
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2560
                                        g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)");
2561
                                        goto error;
2562
                                }
2563
                                json_t *recfile = json_object_get(root, "filename");
2564
                                if(recfile && !json_is_string(recfile)) {
2565
                                        JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
2566
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2567
                                        g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
2568
                                        goto error;
2569
                                }
2570
                                if(audio) {
2571
                                        participant->audio_active = json_is_true(audio);
2572
                                        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);
2573
                                }
2574
                                if(video) {
2575
                                        participant->video_active = json_is_true(video);
2576
                                        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);
2577
                                }
2578
                                if(bitrate) {
2579
                                        participant->bitrate = json_integer_value(bitrate);
2580
                                        JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64" (room %"SCNu64", user %"SCNu64")\n", participant->bitrate, participant->room->room_id, participant->user_id);
2581
                                        /* Send a new REMB */
2582
                                        participant->remb_latest = janus_get_monotonic_time();
2583
                                        char rtcpbuf[200];
2584
                                        memset(rtcpbuf, 0, 200);
2585
                                        /* FIXME First put a RR (fake)... */
2586
                                        int rrlen = 32;
2587
                                        rtcp_rr *rr = (rtcp_rr *)&rtcpbuf;
2588
                                        rr->header.version = 2;
2589
                                        rr->header.type = RTCP_RR;
2590
                                        rr->header.rc = 1;
2591
                                        rr->header.length = htons((rrlen/4)-1);
2592
                                        /* ... then put a SDES... */
2593
                                        int sdeslen = janus_rtcp_sdes((char *)(&rtcpbuf)+rrlen, 200-rrlen, "janusvideo", 10);
2594
                                        if(sdeslen > 0) {
2595
                                                /* ... and then finally a REMB */
2596
                                                janus_rtcp_remb((char *)(&rtcpbuf)+rrlen+sdeslen, 24, participant->bitrate ? participant->bitrate : 256*1024);
2597
                                                gateway->relay_rtcp(msg->handle, 1, rtcpbuf, rrlen+sdeslen+24);
2598
                                        }
2599
                                }
2600
                                gboolean prev_recording_active = participant->recording_active;
2601
                                if(record) {
2602
                                        participant->recording_active = json_is_true(record);
2603
                                        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);
2604
                                }
2605
                                if(recfile) {
2606
                                        participant->recording_base = g_strdup(json_string_value(recfile));
2607
                                        JANUS_LOG(LOG_VERB, "Setting recording basename: %s (room %"SCNu64", user %"SCNu64")\n", participant->recording_base, participant->room->room_id, participant->user_id);
2608
                                }
2609
                                /* Do we need to do something with the recordings right now? */
2610
                                if(participant->recording_active != prev_recording_active) {
2611
                                        /* Something changed */
2612
                                        if(!participant->recording_active) {
2613
                                                /* Not recording (anymore?) */
2614
                                                if(participant->arc) {
2615
                                                        janus_recorder_close(participant->arc);
2616
                                                        JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", participant->arc->filename ? participant->arc->filename : "??");
2617
                                                        janus_recorder_free(participant->arc);
2618
                                                }
2619
                                                participant->arc = NULL;
2620
                                                if(participant->vrc) {
2621
                                                        janus_recorder_close(participant->vrc);
2622
                                                        JANUS_LOG(LOG_INFO, "Closed video recording %s\n", participant->vrc->filename ? participant->vrc->filename : "??");
2623
                                                        janus_recorder_free(participant->vrc);
2624
                                                }
2625
                                                participant->vrc = NULL;
2626
                                        } else if(participant->recording_active && participant->sdp) {
2627
                                                /* We've started recording, send a PLI/FIR and go on */
2628
                                                char filename[255];
2629
                                                gint64 now = janus_get_monotonic_time();
2630
                                                if(strstr(participant->sdp, "m=audio")) {
2631
                                                        memset(filename, 0, 255);
2632
                                                        if(participant->recording_base) {
2633
                                                                /* Use the filename and path we have been provided */
2634
                                                                g_snprintf(filename, 255, "%s-audio", participant->recording_base);
2635
                                                                participant->arc = janus_recorder_create(NULL, 0, filename);
2636
                                                                if(participant->arc == NULL) {
2637
                                                                        JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2638
                                                                }
2639
                                                        } else {
2640
                                                                /* Build a filename */
2641
                                                                g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-audio",
2642
                                                                        participant->room->room_id, participant->user_id, now);
2643
                                                                participant->arc = janus_recorder_create(participant->room->rec_dir, 0, filename);
2644
                                                                if(participant->arc == NULL) {
2645
                                                                        JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
2646
                                                                }
2647
                                                        }
2648
                                                }
2649
                                                if(strstr(participant->sdp, "m=video")) {
2650
                                                        memset(filename, 0, 255);
2651
                                                        if(participant->recording_base) {
2652
                                                                /* Use the filename and path we have been provided */
2653
                                                                g_snprintf(filename, 255, "%s-video", participant->recording_base);
2654
                                                                participant->vrc = janus_recorder_create(NULL, 1, filename);
2655
                                                                if(participant->vrc == NULL) {
2656
                                                                        JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2657
                                                                }
2658
                                                        } else {
2659
                                                                /* Build a filename */
2660
                                                                g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-video",
2661
                                                                        participant->room->room_id, participant->user_id, now);
2662
                                                                participant->vrc = janus_recorder_create(participant->room->rec_dir, 1, filename);
2663
                                                                if(participant->vrc == NULL) {
2664
                                                                        JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
2665
                                                                }
2666
                                                        }
2667
                                                        /* Send a FIR */
2668
                                                        char buf[20];
2669
                                                        memset(buf, 0, 20);
2670
                                                        janus_rtcp_fir((char *)&buf, 20, &participant->fir_seq);
2671
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending FIR to %"SCNu64" (%s)\n",
2672
                                                                participant->user_id, participant->display ? participant->display : "??");
2673
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 20);
2674
                                                        /* Send a PLI too, just in case... */
2675
                                                        memset(buf, 0, 12);
2676
                                                        janus_rtcp_pli((char *)&buf, 12);
2677
                                                        JANUS_LOG(LOG_VERB, "Recording video, sending PLI to %"SCNu64" (%s)\n",
2678
                                                                participant->user_id, participant->display ? participant->display : "??");
2679
                                                        gateway->relay_rtcp(participant->session->handle, 1, buf, 12);
2680
                                                }
2681
                                        }
2682
                                }
2683
                                /* Done */
2684
                                event = json_object();
2685
                                json_object_set_new(event, "videoroom", json_string("event"));
2686
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
2687
                                json_object_set_new(event, "configured", json_string("ok"));
2688
                        } else if(!strcasecmp(request_text, "unpublish")) {
2689
                                /* This participant wants to unpublish */
2690
                                if(!participant->sdp) {
2691
                                        JANUS_LOG(LOG_ERR, "Can't unpublish, not published\n");
2692
                                        error_code = JANUS_VIDEOROOM_ERROR_NOT_PUBLISHED;
2693
                                        g_snprintf(error_cause, 512, "Can't unpublish, not published");
2694
                                        goto error;
2695
                                }
2696
                                /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
2697
                                gateway->close_pc(session->handle);
2698
                                /* Done */
2699
                                event = json_object();
2700
                                json_object_set_new(event, "videoroom", json_string("event"));
2701
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
2702
                                json_object_set_new(event, "unpublished", json_string("ok"));
2703
                        } else if(!strcasecmp(request_text, "leave")) {
2704
                                /* This publisher is leaving, tell everybody */
2705
                                event = json_object();
2706
                                json_object_set_new(event, "videoroom", json_string("event"));
2707
                                json_object_set_new(event, "room", json_integer(participant->room->room_id));
2708
                                json_object_set_new(event, "leaving", json_integer(participant->user_id));
2709
                                char *leaving_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2710
                                GHashTableIter iter;
2711
                                gpointer value;
2712
                                if(participant->room) {
2713
                                        if(!participant->room->destroyed) {
2714
                                                janus_mutex_lock(&participant->room->participants_mutex);
2715
                                                g_hash_table_iter_init(&iter, participant->room->participants);
2716
                                                while (!participant->room->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
2717
                                                        janus_videoroom_participant *p = value;
2718
                                                        if(p == participant) {
2719
                                                                continue;        /* Skip the new publisher itself */
2720
                                                        }
2721
                                                        JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
2722
                                                        int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, leaving_text, NULL, NULL);
2723
                                                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2724
                                                }
2725
                                                janus_mutex_unlock(&participant->room->participants_mutex);
2726
                                        }
2727
                                }
2728
                                g_free(leaving_text);
2729
                                /* Done */
2730
                                participant->audio_active = FALSE;
2731
                                participant->video_active = FALSE;
2732
                                session->started = FALSE;
2733
                                //~ session->destroy = TRUE;
2734
                        } else {
2735
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
2736
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
2737
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
2738
                                goto error;
2739
                        }
2740
                } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
2741
                        /* Handle this listener */
2742
                        janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
2743
                        if(listener == NULL) {
2744
                                JANUS_LOG(LOG_ERR, "Invalid listener instance\n");
2745
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2746
                                g_snprintf(error_cause, 512, "Invalid listener instance");
2747
                                goto error;
2748
                        }
2749
                        if(!strcasecmp(request_text, "join")) {
2750
                                JANUS_LOG(LOG_ERR, "Already in as a listener on this handle\n");
2751
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
2752
                                g_snprintf(error_cause, 512, "Already in as a listener on this handle");
2753
                                goto error;
2754
                        } else if(!strcasecmp(request_text, "start")) {
2755
                                /* Start/restart receiving the publisher streams */
2756
                                janus_videoroom_participant *publisher = listener->feed;
2757
                                listener->paused = FALSE;
2758
                                event = json_object();
2759
                                json_object_set_new(event, "videoroom", json_string("event"));
2760
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2761
                                json_object_set_new(event, "started", json_string("ok"));
2762
                                if(publisher) {
2763
                                        /* Send a FIR */
2764
                                        char buf[20];
2765
                                        memset(buf, 0, 20);
2766
                                        janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
2767
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
2768
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
2769
                                        /* Send a PLI too, just in case... */
2770
                                        memset(buf, 0, 12);
2771
                                        janus_rtcp_pli((char *)&buf, 12);
2772
                                        JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
2773
                                        gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
2774
                                }
2775
                        } else if(!strcasecmp(request_text, "configure")) {
2776
                                json_t *audio = json_object_get(root, "audio");
2777
                                if(audio && !json_is_boolean(audio)) {
2778
                                        JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
2779
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2780
                                        g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
2781
                                        goto error;
2782
                                }
2783
                                json_t *video = json_object_get(root, "video");
2784
                                if(video && !json_is_boolean(video)) {
2785
                                        JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
2786
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2787
                                        g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
2788
                                        goto error;
2789
                                }
2790
                                json_t *data = json_object_get(root, "data");
2791
                                if(data && !json_is_boolean(data)) {
2792
                                        JANUS_LOG(LOG_ERR, "Invalid element (data should be a boolean)\n");
2793
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2794
                                        g_snprintf(error_cause, 512, "Invalid value (data should be a boolean)");
2795
                                        goto error;
2796
                                }
2797
                                /* Update the audio/video/data flags, if set */
2798
                                janus_videoroom_participant *publisher = listener->feed;
2799
                                if(publisher) {
2800
                                        if(audio && publisher->audio)
2801
                                                listener->audio = json_is_true(audio);
2802
                                        if(video && publisher->video)
2803
                                                listener->video = json_is_true(video);
2804
                                        if(data && publisher->data)
2805
                                                listener->data = json_is_true(data);
2806
                                }
2807
                                event = json_object();
2808
                                json_object_set_new(event, "videoroom", json_string("event"));
2809
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2810
                                json_object_set_new(event, "configured", json_string("ok"));
2811
                        } else if(!strcasecmp(request_text, "pause")) {
2812
                                /* Stop receiving the publisher streams for a while */
2813
                                listener->paused = TRUE;
2814
                                event = json_object();
2815
                                json_object_set_new(event, "videoroom", json_string("event"));
2816
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2817
                                json_object_set_new(event, "paused", json_string("ok"));
2818
                        } else if(!strcasecmp(request_text, "switch")) {
2819
                                /* This listener wants to switch to a different publisher */
2820
                                json_t *feed = json_object_get(root, "feed");
2821
                                if(!feed) {
2822
                                        JANUS_LOG(LOG_ERR, "Missing element (feed)\n");
2823
                                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
2824
                                        g_snprintf(error_cause, 512, "Missing element (feed)");
2825
                                        goto error;
2826
                                }
2827
                                if(!json_is_integer(feed) || json_integer_value(feed) < 0) {
2828
                                        JANUS_LOG(LOG_ERR, "Invalid element (feed should be a positive integer)\n");
2829
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2830
                                        g_snprintf(error_cause, 512, "Invalid element (feed should be a positive integer)");
2831
                                        goto error;
2832
                                }
2833
                                guint64 feed_id = json_integer_value(feed);
2834
                                json_t *audio = json_object_get(root, "audio");
2835
                                if(audio && !json_is_boolean(audio)) {
2836
                                        JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
2837
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2838
                                        g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
2839
                                        goto error;
2840
                                }
2841
                                json_t *video = json_object_get(root, "video");
2842
                                if(video && !json_is_boolean(video)) {
2843
                                        JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
2844
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2845
                                        g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
2846
                                        goto error;
2847
                                }
2848
                                json_t *data = json_object_get(root, "data");
2849
                                if(data && !json_is_boolean(data)) {
2850
                                        JANUS_LOG(LOG_ERR, "Invalid element (data should be a boolean)\n");
2851
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2852
                                        g_snprintf(error_cause, 512, "Invalid value (data should be a boolean)");
2853
                                        goto error;
2854
                                }
2855
                                if(!listener->room) {
2856
                                        JANUS_LOG(LOG_ERR, "Room Destroyed \n");
2857
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2858
                                        g_snprintf(error_cause, 512, "No such room ");
2859
                                        goto error;
2860
                                }
2861
                                if(listener->room->destroyed) {
2862
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")\n", listener->room->room_id);
2863
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2864
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
2865
                                        goto error;
2866
                                }
2867
                                janus_mutex_lock(&listener->room->participants_mutex);
2868
                                janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, GUINT_TO_POINTER(feed_id));
2869
                                janus_mutex_unlock(&listener->room->participants_mutex);
2870
                                if(publisher == NULL || publisher->sdp == NULL) {
2871
                                        JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
2872
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
2873
                                        g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
2874
                                        goto error;
2875
                                }
2876
                                gboolean paused = listener->paused;
2877
                                listener->paused = TRUE;
2878
                                /* Unsubscribe from the previous publisher */
2879
                                janus_videoroom_participant *prev_feed = listener->feed;
2880
                                if(prev_feed) {
2881
                                        janus_mutex_lock(&prev_feed->listeners_mutex);
2882
                                        prev_feed->listeners = g_slist_remove(prev_feed->listeners, listener);
2883
                                        janus_mutex_unlock(&prev_feed->listeners_mutex);
2884
                                        listener->feed = NULL;
2885
                                }
2886
                                /* Subscribe to the new one */
2887
                                listener->audio = audio ? json_is_true(audio) : TRUE;        /* True by default */
2888
                                if(!publisher->audio)
2889
                                        listener->audio = FALSE;        /* ... unless the publisher isn't sending any audio */
2890
                                listener->video = video ? json_is_true(video) : TRUE;        /* True by default */
2891
                                if(!publisher->video)
2892
                                        listener->video = FALSE;        /* ... unless the publisher isn't sending any video */
2893
                                listener->data = data ? json_is_true(data) : TRUE;        /* True by default */
2894
                                if(!publisher->data)
2895
                                        listener->data = FALSE;        /* ... unless the publisher isn't sending any data */
2896
                                janus_mutex_lock(&publisher->listeners_mutex);
2897
                                publisher->listeners = g_slist_append(publisher->listeners, listener);
2898
                                janus_mutex_unlock(&publisher->listeners_mutex);
2899
                                listener->feed = publisher;
2900
                                /* Send a FIR to the new publisher */
2901
                                char buf[20];
2902
                                memset(buf, 0, 20);
2903
                                janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
2904
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
2905
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
2906
                                /* Send a PLI too, just in case... */
2907
                                memset(buf, 0, 12);
2908
                                janus_rtcp_pli((char *)&buf, 12);
2909
                                JANUS_LOG(LOG_VERB, "Switching existing listener to new publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
2910
                                gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
2911
                                /* Done */
2912
                                listener->paused = paused;
2913
                                event = json_object();
2914
                                json_object_set_new(event, "videoroom", json_string("event"));
2915
                                json_object_set_new(event, "switched", json_string("ok"));
2916
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2917
                                json_object_set_new(event, "id", json_integer(feed_id));
2918
                                if(publisher->display)
2919
                                        json_object_set_new(event, "display", json_string(publisher->display));
2920
                        } else if(!strcasecmp(request_text, "leave")) {
2921
                                janus_videoroom_participant *publisher = listener->feed;
2922
                                if(publisher != NULL) {
2923
                                        janus_mutex_lock(&publisher->listeners_mutex);
2924
                                        publisher->listeners = g_slist_remove(publisher->listeners, listener);
2925
                                        janus_mutex_unlock(&publisher->listeners_mutex);
2926
                                        listener->feed = NULL;
2927
                                }
2928
                                event = json_object();
2929
                                json_object_set_new(event, "videoroom", json_string("event"));
2930
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
2931
                                json_object_set_new(event, "left", json_string("ok"));
2932
                                session->started = FALSE;
2933
                        } else {
2934
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
2935
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
2936
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
2937
                                goto error;
2938
                        }
2939
                } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
2940
                        /* Handle this Multiplexed listener */
2941
                        janus_videoroom_listener_muxed *listener = (janus_videoroom_listener_muxed *)session->participant;
2942
                        if(listener == NULL) {
2943
                                JANUS_LOG(LOG_ERR, "Invalid Multiplexed listener instance\n");
2944
                                error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;
2945
                                g_snprintf(error_cause, 512, "Invalid Multiplexed listener instance");
2946
                                goto error;
2947
                        }
2948
                        if(!strcasecmp(request_text, "join")) {
2949
                                JANUS_LOG(LOG_ERR, "Already in as a Multiplexed listener on this handle\n");
2950
                                error_code = JANUS_VIDEOROOM_ERROR_ALREADY_JOINED;
2951
                                g_snprintf(error_cause, 512, "Already in as a Multiplexed listener on this handle");
2952
                                goto error;
2953
                        } else if(!strcasecmp(request_text, "add")) {
2954
                                /* Add new streams to subscribe to */
2955
                                GList *list = NULL;
2956
                                json_t *feeds = json_object_get(root, "feeds");
2957
                                if(!feeds) {
2958
                                        JANUS_LOG(LOG_ERR, "Missing element (feeds)\n");
2959
                                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
2960
                                        g_snprintf(error_cause, 512, "Missing element (feeds)");
2961
                                        goto error;
2962
                                }
2963
                                if(!json_is_array(feeds) || json_array_size(feeds) == 0) {
2964
                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds should be a non-empty array)\n");
2965
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2966
                                        g_snprintf(error_cause, 512, "Invalid element (feeds should be a non-empty array)");
2967
                                        goto error;
2968
                                }
2969
                                unsigned int i = 0;
2970
                                int problem = 0;
2971
                                if(!listener->room) {
2972
                                        JANUS_LOG(LOG_ERR, "Room Destroyed ");
2973
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2974
                                        g_snprintf(error_cause, 512, "No such room ");
2975
                                        goto error;
2976
                                }
2977
                                if(listener->room->destroyed) {
2978
                                        JANUS_LOG(LOG_ERR, "Room Destroyed (%"SCNu64")", listener->room->room_id);
2979
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2980
                                        g_snprintf(error_cause, 512, "No such room (%"SCNu64")", listener->room->room_id);
2981
                                        goto error;
2982
                                }
2983
                                for(i=0; i<json_array_size(feeds); i++) {
2984
                                        json_t *feed = json_array_get(feeds, i);
2985
                                        if(listener->room->destroyed) {
2986
                                                problem = 1;
2987
                                                JANUS_LOG(LOG_ERR, "Room destroyed");
2988
                                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
2989
                                                g_snprintf(error_cause, 512, "Room destroyed");
2990
                                                break;
2991
                                        }
2992
                                        if(!feed || !json_is_integer(feed)) {
2993
                                                problem = 1;
2994
                                                JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
2995
                                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
2996
                                                g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
2997
                                                break;
2998
                                        }
2999
                                        uint64_t feed_id = json_integer_value(feed);
3000
                                        janus_mutex_lock(&listener->room->participants_mutex);
3001
                                        janus_videoroom_participant *publisher = g_hash_table_lookup(listener->room->participants, GUINT_TO_POINTER(feed_id));
3002
                                        janus_mutex_unlock(&listener->room->participants_mutex);
3003
                                        if(publisher == NULL) { //~ || publisher->sdp == NULL) {
3004
                                                /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
3005
                                                problem = 1;
3006
                                                JANUS_LOG(LOG_ERR, "No such feed (%"SCNu64")\n", feed_id);
3007
                                                error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_FEED;
3008
                                                g_snprintf(error_cause, 512, "No such feed (%"SCNu64")", feed_id);
3009
                                                break;
3010
                                        }
3011
                                        list = g_list_prepend(list, GUINT_TO_POINTER(feed_id));
3012
                                }
3013
                                if(problem) {
3014
                                        goto error;
3015
                                }
3016
                                list = g_list_reverse(list);
3017
                                if(janus_videoroom_muxed_subscribe(listener, list, msg->transaction) < 0) {
3018
                                        JANUS_LOG(LOG_ERR, "Error subscribing!\n");
3019
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3020
                                        g_snprintf(error_cause, 512, "Error subscribing!");
3021
                                        goto error;
3022
                                }
3023
                                continue;
3024
                        } else if(!strcasecmp(request_text, "remove")) {
3025
                                /* Remove subscribed streams */
3026
                                GList *list = NULL;
3027
                                json_t *feeds = json_object_get(root, "feeds");
3028
                                if(!feeds) {
3029
                                        JANUS_LOG(LOG_ERR, "Missing element (feeds)\n");
3030
                                        error_code = JANUS_VIDEOROOM_ERROR_MISSING_ELEMENT;
3031
                                        g_snprintf(error_cause, 512, "Missing element (feeds)");
3032
                                        goto error;
3033
                                }
3034
                                if(!json_is_array(feeds) || json_array_size(feeds) == 0) {
3035
                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds should be a non-empty array)\n");
3036
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3037
                                        g_snprintf(error_cause, 512, "Invalid element (feeds should be a non-empty array)");
3038
                                        goto error;
3039
                                }
3040
                                unsigned int i = 0;
3041
                                int error = 0;
3042
                                for(i=0; i<json_array_size(feeds); i++) {
3043
                                        json_t *feed = json_array_get(feeds, i);
3044
                                        if(!feed || !json_is_integer(feed)) {
3045
                                                error = 1;
3046
                                                break;
3047
                                        }
3048
                                        list = g_list_prepend(list, GUINT_TO_POINTER(json_integer_value(feed)));
3049
                                }
3050
                                if(error) {
3051
                                        JANUS_LOG(LOG_ERR, "Invalid element (feeds in the array must be integers)\n");
3052
                                        error_code = JANUS_VIDEOROOM_ERROR_INVALID_ELEMENT;
3053
                                        g_snprintf(error_cause, 512, "Invalid element (feeds in the array must be integers)");
3054
                                        goto error;
3055
                                }
3056
                                list = g_list_reverse(list);
3057
                                
3058
                                if(!listener->room) {
3059
                                        JANUS_LOG(LOG_ERR, "Error unsubscribing!\n");
3060
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3061
                                        g_snprintf(error_cause, 512, "Error unsubscribing!");
3062
                                        goto error;
3063
                                }
3064
                                if(janus_videoroom_muxed_unsubscribe(listener, list, msg->transaction) < 0) {
3065
                                        JANUS_LOG(LOG_ERR, "Error unsubscribing!\n");
3066
                                        error_code = JANUS_VIDEOROOM_ERROR_UNKNOWN_ERROR;        /* FIXME */
3067
                                        g_snprintf(error_cause, 512, "Error unsubscribing!");
3068
                                        goto error;
3069
                                }
3070
                                continue;
3071
                        } else if(!strcasecmp(request_text, "start")) {
3072
                                /* Start/restart receiving the publishers streams */
3073
                                /* TODO */
3074
                                event = json_object();
3075
                                json_object_set_new(event, "videoroom", json_string("event"));
3076
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3077
                                json_object_set_new(event, "started", json_string("ok"));
3078
                                //~ /* Send a FIR */
3079
                                //~ char buf[20];
3080
                                //~ memset(buf, 0, 20);
3081
                                //~ janus_rtcp_fir((char *)&buf, 20, &publisher->fir_seq);
3082
                                //~ JANUS_LOG(LOG_VERB, "Resuming publisher, sending FIR to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3083
                                //~ gateway->relay_rtcp(publisher->session->handle, 1, buf, 20);
3084
                                //~ /* Send a PLI too, just in case... */
3085
                                //~ memset(buf, 0, 12);
3086
                                //~ janus_rtcp_pli((char *)&buf, 12);
3087
                                //~ JANUS_LOG(LOG_VERB, "Resuming publisher, sending PLI to %"SCNu64" (%s)\n", publisher->user_id, publisher->display ? publisher->display : "??");
3088
                                //~ gateway->relay_rtcp(publisher->session->handle, 1, buf, 12);
3089
                        } else if(!strcasecmp(request_text, "pause")) {
3090
                                /* Stop receiving the publishers streams for a while */
3091
                                /* TODO */
3092
                                event = json_object();
3093
                                json_object_set_new(event, "videoroom", json_string("event"));
3094
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3095
                                json_object_set_new(event, "paused", json_string("ok"));
3096
                        } else if(!strcasecmp(request_text, "leave")) {
3097
                                /* TODO */
3098
                                event = json_object();
3099
                                json_object_set_new(event, "videoroom", json_string("event"));
3100
                                json_object_set_new(event, "room", json_integer(listener->room->room_id));
3101
                                json_object_set_new(event, "left", json_string("ok"));
3102
                                session->started = FALSE;
3103
                        } else {
3104
                                JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
3105
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_REQUEST;
3106
                                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
3107
                                goto error;
3108
                        }
3109
                }
3110

    
3111
                /* Prepare JSON event */
3112
                JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3113
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3114
                json_decref(event);
3115
                /* Any SDP to handle? */
3116
                if(!msg->sdp) {
3117
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, NULL, NULL);
3118
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3119
                } else {
3120
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
3121
                        const char *type = NULL;
3122
                        if(!strcasecmp(msg->sdp_type, "offer")) {
3123
                                /* We need to answer */
3124
                                type = "answer";
3125
                        } else if(!strcasecmp(msg->sdp_type, "answer")) {
3126
                                /* We got an answer (from a listener?), no need to negotiate */
3127
                                int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, NULL, NULL);
3128
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3129
                        } else {
3130
                                /* TODO We don't support anything else right now... */
3131
                                JANUS_LOG(LOG_ERR, "Unknown SDP type '%s'\n", msg->sdp_type);
3132
                                error_code = JANUS_VIDEOROOM_ERROR_INVALID_SDP_TYPE;
3133
                                g_snprintf(error_cause, 512, "Unknown SDP type '%s'", msg->sdp_type);
3134
                                goto error;
3135
                        }
3136
                        if(session->participant_type == janus_videoroom_p_type_publisher) {
3137
                                /* This is a new publisher: is there room? */
3138
                                janus_videoroom_participant *participant = (janus_videoroom_participant *)session->participant;
3139
                                janus_videoroom *videoroom = participant->room;
3140
                                int count = 0;
3141
                                GHashTableIter iter;
3142
                                gpointer value;
3143
                                if(!videoroom) {
3144
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3145
                                        goto error;
3146
                                }
3147
                                if(videoroom->destroyed) {
3148
                                        error_code = JANUS_VIDEOROOM_ERROR_NO_SUCH_ROOM;
3149
                                        goto error;
3150
                                }
3151
                                janus_mutex_lock(&videoroom->participants_mutex);
3152
                                g_hash_table_iter_init(&iter, videoroom->participants);
3153
                                while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3154
                                        janus_videoroom_participant *p = value;
3155
                                        if(p != participant && p->sdp)
3156
                                                count++;
3157
                                }
3158
                                janus_mutex_unlock(&videoroom->participants_mutex);
3159
                                if(count == videoroom->max_publishers) {
3160
                                        participant->audio_active = FALSE;
3161
                                        participant->video_active = FALSE;
3162
                                        JANUS_LOG(LOG_ERR, "Maximum number of publishers (%d) already reached\n", videoroom->max_publishers);
3163
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3164
                                        g_snprintf(error_cause, 512, "Maximum number of publishers (%d) already reached", videoroom->max_publishers);
3165
                                        goto error;
3166
                                }
3167
                                /* Now prepare the SDP to give back */
3168
                                if(strstr(msg->sdp, "Mozilla")) {
3169
                                        participant->firefox = TRUE;
3170
                                }
3171
                                /* Which media are available? */
3172
                                int audio = 0, video = 0, data = 0;
3173
                                const char *audio_mode = NULL, *video_mode = NULL;
3174
                                sdp_parser_t *parser = sdp_parse(sdphome, msg->sdp, strlen(msg->sdp), 0);
3175
                                sdp_session_t *parsed_sdp = sdp_session(parser);
3176
                                if(!parsed_sdp) {
3177
                                        /* Invalid SDP */
3178
                                        JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", sdp_parsing_error(parser));
3179
                                        error_code = JANUS_VIDEOROOM_ERROR_PUBLISHERS_FULL;
3180
                                        g_snprintf(error_cause, 512, "Error parsing SDP: %s", sdp_parsing_error(parser));
3181
                                        sdp_parser_free(parser);
3182
                                        goto error;
3183
                                }
3184
                                sdp_media_t *m = parsed_sdp->sdp_media;
3185
                                while(m) {
3186
                                        if(m->m_type == sdp_media_audio && m->m_port > 0) {
3187
                                                audio++;
3188
                                                participant->audio = TRUE;
3189
                                                if(audio > 1) {
3190
                                                        m = m->m_next;
3191
                                                        continue;
3192
                                                }
3193
                                        } else if(m->m_type == sdp_media_video && m->m_port > 0) {
3194
                                                video++;
3195
                                                participant->video = TRUE;
3196
                                                if(video > 1) {
3197
                                                        m = m->m_next;
3198
                                                        continue;
3199
                                                }
3200
#ifdef HAVE_SCTP
3201
                                        } else if(m->m_type == sdp_media_application && m->m_port > 0) {
3202
                                                data++;
3203
                                                participant->data = TRUE;
3204
                                                if(data > 1) {
3205
                                                        m = m->m_next;
3206
                                                        continue;
3207
                                                }
3208
#endif
3209
                                        }
3210
                                        if(m->m_type != sdp_media_application) {
3211
                                                /* What is the direction? */
3212
                                                switch(m->m_mode) {
3213
                                                        case sdp_recvonly:
3214
                                                                /* If we're getting a 'recvonly' publisher, we're going to answer with 'inactive' */
3215
                                                        case sdp_inactive:
3216
                                                                if(m->m_type == sdp_media_audio) {
3217
                                                                        audio_mode = "inactive";
3218
                                                                } else {
3219
                                                                        video_mode = "inactive";
3220
                                                                }
3221
                                                                break;
3222
                                                        case sdp_sendonly:
3223
                                                                /* What we expect, turn this into 'recvonly' */
3224
                                                        case sdp_sendrecv:
3225
                                                        default:
3226
                                                                if(m->m_type == sdp_media_audio) {
3227
                                                                        audio_mode = "recvonly";
3228
                                                                } else {
3229
                                                                        video_mode = "recvonly";
3230
                                                                }
3231
                                                                break;
3232
                                                }
3233
                                        }
3234
                                        m = m->m_next;
3235
                                }
3236
                                sdp_parser_free(parser);
3237
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send an audio stream\n", audio ? "is" : "is NOT");
3238
                                if(audio) {
3239
                                        JANUS_LOG(LOG_VERB, "  -- Will answer with media direction '%s'\n", audio_mode);
3240
                                }
3241
                                JANUS_LOG(LOG_VERB, "The publisher %s going to send a video stream\n", video ? "is" : "is NOT");
3242
                                if(video) {
3243
                                        JANUS_LOG(LOG_VERB, "  -- Will answer with media direction '%s'\n", video_mode);
3244
                                }
3245
                                JANUS_LOG(LOG_VERB, "The publisher %s going to open a data channel\n", data ? "is" : "is NOT");
3246
                                /* Also add a bandwidth SDP attribute if we're capping the bitrate in the room */
3247
                                int b = 0;
3248
                                if(participant->firefox)        /* Don't add any b=AS attribute for Chrome */
3249
                                        b = (int)(videoroom->bitrate/1000);
3250
                                char sdp[1280], audio_mline[256], video_mline[512], data_mline[256];
3251
                                if(audio) {
3252
                                        g_snprintf(audio_mline, 256, sdp_a_template,
3253
                                                OPUS_PT,                                                /* Opus payload type */
3254
                                                audio_mode,                                                /* The publisher gets a recvonly or inactive back */
3255
                                                OPUS_PT);                                                 /* Opus payload type */
3256
                                } else {
3257
                                        audio_mline[0] = '\0';
3258
                                }
3259
                                if(video) {
3260
                                        g_snprintf(video_mline, 512, sdp_v_template,
3261
                                                VP8_PT,                                                        /* VP8 payload type */
3262
                                                b,                                                                /* Bandwidth */
3263
                                                video_mode,                                                /* The publisher gets a recvonly or inactive back */
3264
                                                VP8_PT,                                                 /* VP8 payload type */
3265
                                                VP8_PT,                                                 /* VP8 payload type */
3266
                                                VP8_PT,                                                 /* VP8 payload type */
3267
                                                VP8_PT,                                                 /* VP8 payload type */
3268
                                                VP8_PT);                                                 /* VP8 payload type */
3269
                                } else {
3270
                                        video_mline[0] = '\0';
3271
                                }
3272
                                if(data) {
3273
                                        g_snprintf(data_mline, 256, sdp_d_template);
3274
                                } else {
3275
                                        data_mline[0] = '\0';
3276
                                }
3277
                                g_snprintf(sdp, 1280, sdp_template,
3278
                                        janus_get_monotonic_time(),                /* We need current time here */
3279
                                        janus_get_monotonic_time(),                /* We need current time here */
3280
                                        participant->room->room_name,        /* Video room name */
3281
                                        audio_mline,                                        /* Audio m-line, if any */
3282
                                        video_mline,                                        /* Video m-line, if any */
3283
                                        data_mline);                                        /* Data channel m-line, if any */
3284

    
3285
                                char *newsdp = g_strdup(sdp);
3286
                                if(video && b == 0) {
3287
                                        /* Remove useless bandwidth attribute */
3288
                                        newsdp = janus_string_replace(newsdp, "b=AS:0\r\n", "");
3289
                                }
3290
                                /* Is this room recorded? */
3291
                                if(videoroom->record || participant->recording_active) {
3292
                                        char filename[255];
3293
                                        gint64 now = janus_get_monotonic_time();
3294
                                        if(audio) {
3295
                                                memset(filename, 0, 255);
3296
                                                if(participant->recording_base) {
3297
                                                        /* Use the filename and path we have been provided */
3298
                                                        g_snprintf(filename, 255, "%s-audio", participant->recording_base);
3299
                                                        participant->arc = janus_recorder_create(NULL, 0, filename);
3300
                                                        if(participant->arc == NULL) {
3301
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
3302
                                                        }
3303
                                                } else {
3304
                                                        /* Build a filename */
3305
                                                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-audio",
3306
                                                                videoroom->room_id, participant->user_id, now);
3307
                                                        participant->arc = janus_recorder_create(videoroom->rec_dir, 0, filename);
3308
                                                        if(participant->arc == NULL) {
3309
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this publisher!\n");
3310
                                                        }
3311
                                                }
3312
                                        }
3313
                                        if(video) {
3314
                                                memset(filename, 0, 255);
3315
                                                if(participant->recording_base) {
3316
                                                        /* Use the filename and path we have been provided */
3317
                                                        g_snprintf(filename, 255, "%s-video", participant->recording_base);
3318
                                                        participant->vrc = janus_recorder_create(NULL, 1, filename);
3319
                                                        if(participant->vrc == NULL) {
3320
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
3321
                                                        }
3322
                                                } else {
3323
                                                        /* Build a filename */
3324
                                                        g_snprintf(filename, 255, "videoroom-%"SCNu64"-user-%"SCNu64"-%"SCNi64"-video",
3325
                                                                videoroom->room_id, participant->user_id, now);
3326
                                                        participant->vrc = janus_recorder_create(videoroom->rec_dir, 1, filename);
3327
                                                        if(participant->vrc == NULL) {
3328
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this publisher!\n");
3329
                                                        }
3330
                                                }
3331
                                        }
3332
                                }
3333

    
3334
                                JANUS_LOG(LOG_VERB, "Handling publisher: turned this into an '%s':\n%s\n", type, newsdp);
3335
                                /* How long will the gateway take to push the event? */
3336
                                gint64 start = janus_get_monotonic_time();
3337
                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, type, newsdp);
3338
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3339
                                if(strstr(newsdp, "recvonly"))
3340
                                        newsdp = janus_string_replace(newsdp, "recvonly", "sendonly");
3341
                                if(res != JANUS_OK) {
3342
                                        /* TODO Failed to negotiate? We should remove this publisher */
3343
                                } else {
3344
                                        /* Store the participant's SDP for interested listeners */
3345
                                        participant->sdp = newsdp;
3346
                                        /* Notify all other participants that there's a new boy in town */
3347
                                        json_t *list = json_array();
3348
                                        json_t *pl = json_object();
3349
                                        json_object_set_new(pl, "id", json_integer(participant->user_id));
3350
                                        if(participant->display)
3351
                                                json_object_set_new(pl, "display", json_string(participant->display));
3352
                                        json_array_append_new(list, pl);
3353
                                        json_t *pub = json_object();
3354
                                        json_object_set_new(pub, "videoroom", json_string("event"));
3355
                                        json_object_set_new(pub, "room", json_integer(participant->room->room_id));
3356
                                        json_object_set_new(pub, "publishers", list);
3357
                                        char *pub_text = json_dumps(pub, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3358
                                        json_decref(pub);
3359
                                        GHashTableIter iter;
3360
                                        gpointer value;
3361
                                        janus_mutex_lock(&videoroom->participants_mutex);
3362
                                        g_hash_table_iter_init(&iter, videoroom->participants);
3363
                                        while (!videoroom->destroyed && g_hash_table_iter_next(&iter, NULL, &value)) {
3364
                                                janus_videoroom_participant *p = value;
3365
                                                if(p == participant) {
3366
                                                        continue;        /* Skip the new publisher itself */
3367
                                                }
3368
                                                JANUS_LOG(LOG_VERB, "Notifying participant %"SCNu64" (%s)\n", p->user_id, p->display ? p->display : "??");
3369
                                                int ret = gateway->push_event(p->session->handle, &janus_videoroom_plugin, NULL, pub_text, NULL, NULL);
3370
                                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3371
                                        }
3372
                                        g_free(pub_text);
3373
                                        janus_mutex_unlock(&videoroom->participants_mutex);
3374
                                        /* Let's wait for the setup_media event */
3375
                                }
3376
                        } else if(session->participant_type == janus_videoroom_p_type_subscriber) {
3377
                                /* Negotiate by sending the selected publisher SDP back */
3378
                                janus_videoroom_listener *listener = (janus_videoroom_listener *)session->participant;
3379
                                /* FIXME We should handle the case where the participant has no SDP... */
3380
                                if(listener != NULL) {
3381
                                        janus_videoroom_participant *feed = (janus_videoroom_participant *)listener->feed;
3382
                                        if(feed != NULL && feed->sdp != NULL) {
3383
                                                /* How long will the gateway take to push the event? */
3384
                                                gint64 start = janus_get_monotonic_time();
3385
                                                int res = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, type, feed->sdp);
3386
                                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3387
                                                if(res != JANUS_OK) {
3388
                                                        /* TODO Failed to negotiate? We should remove this listener */
3389
                                                } else {
3390
                                                        /* Let's wait for the setup_media event */
3391
                                                }
3392
                                        }
3393
                                }
3394
                        } else if(session->participant_type == janus_videoroom_p_type_subscriber_muxed) {
3395
                                /* FIXME We shouldn't be here, we always offer ourselves */
3396
                        }
3397
                }
3398
                g_free(event_text);
3399
                janus_videoroom_message_free(msg);
3400

    
3401
                continue;
3402
                
3403
error:
3404
                {
3405
                        /* Prepare JSON error event */
3406
                        json_t *event = json_object();
3407
                        json_object_set_new(event, "videoroom", json_string("event"));
3408
                        json_object_set_new(event, "error_code", json_integer(error_code));
3409
                        json_object_set_new(event, "error", json_string(error_cause));
3410
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3411
                        json_decref(event);
3412
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
3413
                        int ret = gateway->push_event(msg->handle, &janus_videoroom_plugin, msg->transaction, event_text, NULL, NULL);
3414
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
3415
                        g_free(event_text);
3416
                        janus_videoroom_message_free(msg);
3417
                }
3418
        }
3419
        g_free(error_cause);
3420
        JANUS_LOG(LOG_VERB, "Leaving VideoRoom handler thread\n");
3421
        return NULL;
3422
}
3423

    
3424

    
3425
/* Multiplexing helpers */
3426
int janus_videoroom_muxed_subscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction) {
3427
        if(!muxed_listener || !feeds)
3428
                return -1;
3429
        janus_mutex_lock(&muxed_listener->listeners_mutex);
3430
        JANUS_LOG(LOG_VERB, "Subscribing to %d feeds\n", g_list_length(feeds));
3431
        janus_videoroom *videoroom = muxed_listener->room;
3432
        GList *ps = feeds;
3433
        json_t *list = json_array();
3434
        int added_feeds = 0;
3435
        while(ps) {
3436
                uint64_t feed_id = GPOINTER_TO_UINT(ps->data);
3437
                janus_videoroom_participant *publisher = g_hash_table_lookup(videoroom->participants, GUINT_TO_POINTER(feed_id));
3438
                if(publisher == NULL) { //~ || publisher->sdp == NULL) {
3439
                        /* FIXME For muxed listeners, we accept subscriptions to existing participants who haven't published yet */
3440
                        JANUS_LOG(LOG_WARN, "No such feed (%"SCNu64"), skipping\n", feed_id);
3441
                        ps = ps->next;
3442
                        continue;
3443
                }
3444
                /* Are we already subscribed? */
3445
                gboolean subscribed = FALSE;
3446
                GSList *ls = muxed_listener->listeners;
3447
                while(ls) {
3448
                        janus_videoroom_listener *l = (janus_videoroom_listener *)ls->data;
3449
                        if(l && (l->feed == publisher)) {
3450
                                subscribed = TRUE;
3451
                                JANUS_LOG(LOG_WARN, "Already subscribed to feed %"SCNu64", skipping\n", feed_id);
3452
                                break;
3453
                        }
3454
                        ls = ls->next;
3455
                }
3456
                if(subscribed) {
3457
                        ps = ps->next;
3458
                        continue;
3459
                }
3460
                janus_videoroom_listener *listener = calloc(1, sizeof(janus_videoroom_listener));
3461
                if(listener == NULL) {
3462
                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
3463
                        ps = ps->next;
3464
                        continue;
3465
                }
3466
                listener->session = muxed_listener->session;
3467
                listener->room = videoroom;
3468
                listener->feed = publisher;
3469
                //~ listener->paused = TRUE;        /* We need an explicit start from the listener */
3470
                listener->paused = FALSE;
3471
                listener->parent = muxed_listener;
3472
                janus_mutex_lock(&publisher->listeners_mutex);
3473
                publisher->listeners = g_slist_append(publisher->listeners, listener);
3474
                janus_mutex_unlock(&publisher->listeners_mutex);
3475
                muxed_listener->listeners = g_slist_append(muxed_listener->listeners, listener);
3476
                JANUS_LOG(LOG_VERB, "Now subscribed to %d feeds\n", g_slist_length(muxed_listener->listeners));
3477
                /* Add to feeds in the answer */
3478
                added_feeds++;
3479
                json_t *f = json_object();
3480
                json_object_set_new(f, "id", json_integer(feed_id));
3481
                if(publisher->display)
3482
                        json_object_set_new(f, "display", json_string(publisher->display));
3483
                json_array_append_new(list, f);
3484
                ps = ps->next;
3485
        }
3486
        janus_mutex_unlock(&muxed_listener->listeners_mutex);
3487
        if(added_feeds == 0) {
3488
                /* Nothing changed */
3489
                return 0;
3490
        }
3491
        /* Prepare event */
3492
        json_t *event = json_object();
3493
        json_object_set_new(event, "videoroom", json_string("muxed-attached"));
3494
        json_object_set_new(event, "room", json_integer(videoroom->room_id));
3495
        json_object_set_new(event, "feeds", list);
3496
        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3497
        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3498
        json_decref(event);
3499
        /* Send the updated offer */
3500
        return janus_videoroom_muxed_offer(muxed_listener, transaction, event_text);
3501
}
3502

    
3503
int janus_videoroom_muxed_unsubscribe(janus_videoroom_listener_muxed *muxed_listener, GList *feeds, char *transaction) {
3504
        janus_mutex_lock(&muxed_listener->listeners_mutex);
3505
        JANUS_LOG(LOG_VERB, "Unsubscribing from %d feeds\n", g_list_length(feeds));
3506
        janus_videoroom *videoroom = muxed_listener->room;
3507
        GList *ps = feeds;
3508
        json_t *list = json_array();
3509
        int removed_feeds = 0;
3510
        while(ps) {
3511
                uint64_t feed_id = GPOINTER_TO_UINT(ps->data);
3512
                GSList *ls = muxed_listener->listeners;
3513
                while(ls) {
3514
                        janus_videoroom_listener *listener = (janus_videoroom_listener *)ls->data;
3515
                        if(listener) {
3516
                                janus_videoroom_participant *publisher = listener->feed;
3517
                                if(publisher == NULL || publisher->user_id != feed_id) {
3518
                                        /* Not the publisher we're looking for */
3519
                                        ls = ls->next;
3520
                                        continue;
3521
                                }
3522
                                janus_mutex_lock(&publisher->listeners_mutex);
3523
                                publisher->listeners = g_slist_remove(publisher->listeners, listener);
3524
                                janus_mutex_unlock(&publisher->listeners_mutex);
3525
                                listener->feed = NULL;
3526
                                muxed_listener->listeners = g_slist_remove(muxed_listener->listeners, listener);
3527
                                JANUS_LOG(LOG_VERB, "Now subscribed to %d feeds\n", g_slist_length(muxed_listener->listeners));
3528
                                /* Add to feeds in the answer */
3529
                                removed_feeds++;
3530
                                json_t *f = json_object();
3531
                                json_object_set_new(f, "id", json_integer(feed_id));
3532
                                json_array_append_new(list, f);
3533
                                break;
3534
                        }
3535
                        ls = ls->next;
3536
                }
3537
                ps = ps->next;
3538
        }
3539
        janus_mutex_unlock(&muxed_listener->listeners_mutex);
3540
        if(removed_feeds == 0) {
3541
                /* Nothing changed */
3542
                return 0;
3543
        }
3544
        /* Prepare event */
3545
        json_t *event = json_object();
3546
        json_object_set_new(event, "videoroom", json_string("muxed-detached"));
3547
        json_object_set_new(event, "room", json_integer(videoroom->room_id));
3548
        json_object_set_new(event, "feeds", list);
3549
        JANUS_LOG(LOG_VERB, "Preparing JSON event as a reply\n");
3550
        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
3551
        json_decref(event);
3552
        /* Send the updated offer */
3553
        return janus_videoroom_muxed_offer(muxed_listener, transaction, event_text);
3554
}
3555

    
3556
int janus_videoroom_muxed_offer(janus_videoroom_listener_muxed *muxed_listener, char *transaction, char *event_text) {
3557
        if(muxed_listener == NULL)
3558
                return -1;
3559
        /* Negotiate by placing a 'muxed' fake attribute for each publisher we subscribed to,
3560
         * that will translate to multiple SSRCs when merging the SDP */
3561
        int audio = 0, video = 0;
3562
        char audio_muxed[1024], video_muxed[1024], temp[255];
3563
        char sdp[2048], audio_mline[512], video_mline[512], data_mline[1];
3564
        data_mline[0] = '\0'; /* Multiplexed streams do not support data channels */
3565
        memset(audio_muxed, 0, 1024);
3566
        memset(video_muxed, 0, 1024);
3567
        memset(audio_mline, 0, 512);
3568
        memset(video_mline, 0, 512);
3569
        /* Prepare the m-lines (FIXME this will result in an audio line even for video-only rooms, but we don't care) */
3570
        g_snprintf(audio_mline, 512, sdp_a_template,
3571
                OPUS_PT,                                                /* Opus payload type */
3572
                "sendonly",                                                /* The publisher gets a recvonly back */
3573
                OPUS_PT);                                                 /* Opus payload type */
3574
        g_snprintf(video_mline, 512, sdp_v_template,
3575
                VP8_PT,                                                        /* VP8 payload type */
3576
                0,                                                                /* Bandwidth */
3577
                "sendonly",                                                /* The publisher gets a recvonly back */
3578
                VP8_PT,                                                 /* VP8 payload type */
3579
                VP8_PT,                                                 /* VP8 payload type */
3580
                VP8_PT,                                                 /* VP8 payload type */
3581
                VP8_PT,                                                 /* VP8 payload type */
3582
                VP8_PT);                                                 /* VP8 payload type */
3583
        /* FIXME Add a fake user/SSRC just to avoid the "Failed to set max send bandwidth for video content" bug */
3584
        g_strlcat(audio_muxed, "a=planb:sfu0 1\r\n", 1024);
3585
        g_strlcat(video_muxed, "a=planb:sfu0 2\r\n", 1024);
3586
        /* Go through all the available publishers */
3587
        GSList *ps = muxed_listener->listeners;
3588
        while(ps) {
3589
                janus_videoroom_listener *l = (janus_videoroom_listener *)ps->data;
3590
                if(l && l->feed) { //~ && l->feed->sdp) {
3591
                        if(strstr(l->feed->sdp, "m=audio")) {
3592
                                audio++;
3593
                                g_snprintf(temp, 255, "a=planb:sfu%"SCNu64" %"SCNu32"\r\n", l->feed->user_id, l->feed->audio_ssrc);
3594
                                g_strlcat(audio_muxed, temp, 1024);
3595
                        }
3596
                        if(strstr(l->feed->sdp, "m=video")) {
3597
                                video++;
3598
                                g_snprintf(temp, 255, "a=planb:sfu%"SCNu64" %"SCNu32"\r\n", l->feed->user_id, l->feed->video_ssrc);
3599
                                g_strlcat(video_muxed, temp, 1024);
3600
                        }
3601
                }
3602
                ps = ps->next;
3603
        }
3604
        /* Also add a bandwidth SDP attribute if we're capping the bitrate in the room */
3605
        if(audio) {
3606
                g_strlcat(audio_mline, audio_muxed, 2048);
3607
        }
3608
        if(video) {
3609
                g_strlcat(video_mline, video_muxed, 2048);
3610
        }
3611
        g_snprintf(sdp, 2048, sdp_template,
3612
                janus_get_monotonic_time(),                /* We need current time here */
3613
                janus_get_monotonic_time(),                /* We need current time here */
3614
                muxed_listener->room->room_name,        /* Video room name */
3615
                audio_mline,                                        /* Audio m-line */
3616
                video_mline,                                        /* Video m-line */
3617
                data_mline);                                        /* Data channel m-line */
3618
        char *newsdp = g_strdup(sdp);
3619
        if(video) {
3620
                /* Remove useless bandwidth attribute, if any */
3621
                newsdp = janus_string_replace(newsdp, "b=AS:0\r\n", "");
3622
        }
3623
        JANUS_LOG(LOG_VERB, "%s", newsdp);
3624
        /* How long will the gateway take to push the event? */
3625
        gint64 start = janus_get_monotonic_time();
3626
        int res = gateway->push_event(muxed_listener->session->handle, &janus_videoroom_plugin, transaction, event_text, "offer", newsdp);
3627
        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time()-start);
3628
        if(res != JANUS_OK) {
3629
                /* TODO Failed to negotiate? We should remove this listener */
3630
        } else {
3631
                /* Let's wait for the setup_media event */
3632
        }
3633
        return 0;
3634
}
3635

    
3636

    
3637
/* Helper to quickly relay RTP packets from publishers to subscribers */
3638
static void janus_videoroom_relay_rtp_packet(gpointer data, gpointer user_data) {
3639
        janus_videoroom_rtp_relay_packet *packet = (janus_videoroom_rtp_relay_packet *)user_data;
3640
        if(!packet || !packet->data || packet->length < 1) {
3641
                JANUS_LOG(LOG_ERR, "Invalid packet...\n");
3642
                return;
3643
        }
3644
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3645
        if(!listener || !listener->session) {
3646
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3647
                return;
3648
        }
3649
        if(listener->paused) {
3650
                // JANUS_LOG(LOG_ERR, "This listener paused the stream...\n");
3651
                return;
3652
        }
3653
        janus_videoroom_session *session = listener->session;
3654
        if(!session || !session->handle) {
3655
                // JANUS_LOG(LOG_ERR, "Invalid session...\n");
3656
                return;
3657
        }
3658
        if(!session->started) {
3659
                // JANUS_LOG(LOG_ERR, "Streaming not started yet for this session...\n");
3660
                return;
3661
        }
3662
        
3663
        /* Make sure there hasn't been a publisher switch by checking the SSRC */
3664
        if(packet->is_video) {
3665
                /* Check if this listener is subscribed to this medium */
3666
                if(!listener->video) {
3667
                        /* Nope, don't relay */
3668
                        return;
3669
                }
3670
                if(ntohl(packet->data->ssrc) != listener->context.v_last_ssrc) {
3671
                        listener->context.v_last_ssrc = ntohl(packet->data->ssrc);
3672
                        listener->context.v_base_ts_prev = listener->context.v_last_ts;
3673
                        listener->context.v_base_ts = packet->timestamp;
3674
                        listener->context.v_base_seq_prev = listener->context.v_last_seq;
3675
                        listener->context.v_base_seq = packet->seq_number;
3676
                }
3677
                /* Compute a coherent timestamp and sequence number */
3678
                listener->context.v_last_ts = (packet->timestamp-listener->context.v_base_ts)
3679
                        + listener->context.v_base_ts_prev+4500;        /* FIXME When switching, we assume 15fps */
3680
                listener->context.v_last_seq = (packet->seq_number-listener->context.v_base_seq)+listener->context.v_base_seq_prev+1;
3681
                /* Update the timestamp and sequence number in the RTP packet, and send it */
3682
                packet->data->timestamp = htonl(listener->context.v_last_ts);
3683
                packet->data->seq_number = htons(listener->context.v_last_seq);
3684
                if(gateway != NULL)
3685
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3686
                /* Restore the timestamp and sequence number to what the publisher set them to */
3687
                packet->data->timestamp = htonl(packet->timestamp);
3688
                packet->data->seq_number = htons(packet->seq_number);
3689
        } else {
3690
                /* Check if this listener is subscribed to this medium */
3691
                if(!listener->audio) {
3692
                        /* Nope, don't relay */
3693
                        return;
3694
                }
3695
                if(ntohl(packet->data->ssrc) != listener->context.a_last_ssrc) {
3696
                        listener->context.a_last_ssrc = ntohl(packet->data->ssrc);
3697
                        listener->context.a_base_ts_prev = listener->context.a_last_ts;
3698
                        listener->context.a_base_ts = packet->timestamp;
3699
                        listener->context.a_base_seq_prev = listener->context.a_last_seq;
3700
                        listener->context.a_base_seq = packet->seq_number;
3701
                }
3702
                /* Compute a coherent timestamp and sequence number */
3703
                listener->context.a_last_ts = (packet->timestamp-listener->context.a_base_ts)
3704
                        + listener->context.a_base_ts_prev+960;        /* FIXME When switching, we assume Opus and so a 960 ts step */
3705
                listener->context.a_last_seq = (packet->seq_number-listener->context.a_base_seq)+listener->context.a_base_seq_prev+1;
3706
                /* Update the timestamp and sequence number in the RTP packet, and send it */
3707
                packet->data->timestamp = htonl(listener->context.a_last_ts);
3708
                packet->data->seq_number = htons(listener->context.a_last_seq);
3709
                if(gateway != NULL)
3710
                        gateway->relay_rtp(session->handle, packet->is_video, (char *)packet->data, packet->length);
3711
                /* Restore the timestamp and sequence number to what the publisher set them to */
3712
                packet->data->timestamp = htonl(packet->timestamp);
3713
                packet->data->seq_number = htons(packet->seq_number);
3714
        }
3715

    
3716
        return;
3717
}
3718

    
3719
static void janus_videoroom_relay_data_packet(gpointer data, gpointer user_data) {
3720
        char *text = (char *)user_data;
3721
        janus_videoroom_listener *listener = (janus_videoroom_listener *)data;
3722
        if(!listener || !listener->session || !listener->data || listener->paused) {
3723
                return;
3724
        }
3725
        janus_videoroom_session *session = listener->session;
3726
        if(!session || !session->handle) {
3727
                return;
3728
        }
3729
        if(!session->started) {
3730
                return;
3731
        }
3732
        if(gateway != NULL && text != NULL) {
3733
                JANUS_LOG(LOG_VERB, "Forwarding DataChannel message (%zu bytes) to viewer: %s\n", strlen(text), text);
3734
                gateway->relay_data(session->handle, text, strlen(text));
3735
        }
3736
        return;
3737
}
3738

    
3739
/* Helper to free janus_videoroom structs. */
3740
static void janus_videoroom_free(janus_videoroom *room) {
3741
        if(room) {
3742
                janus_mutex_lock(&room->participants_mutex);
3743
                g_free(room->room_name);
3744
                g_free(room->room_secret);
3745
                g_free(room->rec_dir);
3746
                g_hash_table_unref(room->participants);
3747
                janus_mutex_unlock(&room->participants_mutex);
3748
                janus_mutex_destroy(&room->participants_mutex);
3749
                free(room);
3750
                room = NULL;
3751
        }
3752
}
3753

    
3754
static void janus_videoroom_listener_free(janus_videoroom_listener *l) {
3755
        JANUS_LOG(LOG_VERB, "Freeing listener\n");
3756
        free(l);
3757
}
3758

    
3759
static void janus_videoroom_muxed_listener_free(janus_videoroom_listener_muxed *l) {
3760
        JANUS_LOG(LOG_VERB, "Freeing muxed-listener\n");
3761
        free(l);
3762
}
3763

    
3764
static void janus_videoroom_participant_free(janus_videoroom_participant *p) {
3765
        JANUS_LOG(LOG_VERB, "Freeing publisher\n");
3766
        g_free(p->display);
3767
        g_free(p->sdp);
3768

    
3769
        if(p->arc) {
3770
                janus_recorder_free(p->arc);
3771
                p->arc = NULL;
3772
        }
3773
        if(p->vrc) {
3774
                janus_recorder_free(p->vrc);
3775
                p->vrc = NULL;
3776
        }
3777

    
3778
        janus_mutex_lock(&p->listeners_mutex);
3779
        while(p->listeners) {
3780
                janus_videoroom_listener *l = (janus_videoroom_listener *)p->listeners->data;
3781
                if(l) {
3782
                        p->listeners = g_slist_remove(p->listeners, l);
3783
                        l->feed = NULL;
3784
                }
3785
        }
3786
        janus_mutex_unlock(&p->listeners_mutex);
3787
        janus_mutex_lock(&p->rtp_forwarders_mutex);
3788
        if(p->udp_sock > 0) {
3789
                close(p->udp_sock);
3790
                p->udp_sock = 0;
3791
        }
3792
        g_hash_table_destroy(p->rtp_forwarders);
3793
        p->rtp_forwarders = NULL;
3794
        janus_mutex_unlock(&p->rtp_forwarders_mutex);
3795
        g_slist_free(p->listeners);
3796

    
3797
        janus_mutex_destroy(&p->listeners_mutex);
3798
        janus_mutex_destroy(&p->rtp_forwarders_mutex);
3799
        free(p);
3800
}