Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_videocall.c @ d223cef1

History | View | Annotate | Download (48.4 KB)

1
/*! \file   janus_videocall.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus VideoCall plugin
5
 * \details  This is a simple video call plugin for Janus, allowing two
6
 * WebRTC peers to call each other through the gateway. The idea is to
7
 * provide a similar service as the well known AppRTC demo (https://apprtc.appspot.com),
8
 * but with the media flowing through the gateway rather than being peer-to-peer.
9
 * 
10
 * The plugin provides a simple fake registration mechanism. A peer attaching
11
 * to the plugin needs to specify a username, which acts as a "phone number":
12
 * if the username is free, it is associated with the peer, which means
13
 * he/she can be "called" using that username by another peer. Peers can
14
 * either "call" another peer, by specifying their username, or wait for a call.
15
 * The approach used by this plugin is similar to the one employed by the
16
 * echo test one: all frames (RTP/RTCP) coming from one peer are relayed
17
 * to the other.
18
 * 
19
 * Just as in the janus_videocall.c plugin, there are knobs to control
20
 * whether audio and/or video should be muted or not, and if the bitrate
21
 * of the peer needs to be capped by means of REMB messages.
22
 * 
23
 * \section vcallapi Video Call API
24
 * 
25
 * All requests you can send in the Video Call API are asynchronous,
26
 * which means all responses (successes and errors) will be delivered
27
 * as events with the same transaction. 
28
 * 
29
 * The supported requests are \c list , \c register , \c call ,
30
 * \c accept , \c set and \c hangup . \c list allows you to get a list
31
 * of all the registered peers; \c register can be used to register
32
 * a username to call and be called; \c call is used to start a video
33
 * call with somebody through the plugin, while \c accept is used to
34
 * accept the call in case one is invited instead of inviting; \c set
35
 * can be used to configure some call-related settings (e.g., a cap on
36
 * the send bandwidth); finally, \c hangup can be used to terminate the
37
 * communication at any time, either to hangup an ongoing call or to
38
 * cancel/decline a call that hasn't started yet.
39
 * 
40
 * The \c list request has to be formatted as follows:
41
 * 
42
\verbatim
43
{
44
        "request" : "list"
45
}
46
\endverbatim
47
 *
48
 * A successful request will result in an array of peers to be returned:
49
 * 
50
\verbatim
51
{
52
        "videocall" : "event",
53
        "result" : {
54
                "list": [        // Array of peers
55
                        "alice78",
56
                        "bob51",
57
                        // others
58
                ]
59
        }
60
}
61
\endverbatim
62
 * 
63
 * An error instead (and the same applies to all other requests, so this
64
 * won't be repeated) would provide both an error code and a more verbose
65
 * description of the cause of the issue:
66
 * 
67
\verbatim
68
{
69
        "videocall" : "event",
70
        "error_code" : <numeric ID, check Macros below>,
71
        "error" : "<error description as a string>"
72
}
73
\endverbatim
74
 * 
75
 * To register a username to call and be called, the \c register request
76
 * can be used. This works on a "first come, first served" basis: there's
77
 * no authetication involved, you just specify the username you'd like
78
 * to use and, if free, it's assigned to you. The \c request has to be
79
 * formatted as follows:
80
 * 
81
\verbatim
82
{
83
        "request" : "register",
84
        "username" : "<desired unique username>"
85
}
86
\endverbatim
87
 * 
88
 * If successul, this will result in a \c registered event:
89
 * 
90
\verbatim
91
{
92
        "videocall" : "event",
93
        "result" : {
94
                "event" : "registered",
95
                "username" : "<same username, registered>"
96
        }
97
}
98
\endverbatim
99
 * 
100
 * Once you're registered, you can either start a new call or wait to
101
 * be called by someone else who knows your username. To start a new
102
 * call, the \c call request can be used: this request must be attached
103
 * to a JSEP offer containing the WebRTC-related info to setup a new
104
 * media session. A \c call request has to be formatted as follows:
105
 * 
106
\verbatim
107
{
108
        "request" : "call",
109
        "username" : "<username to call>"
110
}
111
\endverbatim
112
 * 
113
 * If successul, this will result in a \c calling event:
114
 * 
115
\verbatim
116
{
117
        "videocall" : "event",
118
        "result" : {
119
                "event" : "calling",
120
                "username" : "<same username, registered>"
121
        }
122
}
123
\endverbatim
124
 *
125
 * At the same time, the user being called will receive an
126
 * \c incomingcall event
127
 *  
128
\verbatim
129
{
130
        "videocall" : "event",
131
        "result" : {
132
                "event" : "incomingcall",
133
                "username" : "<your username>"
134
        }
135
}
136
\endverbatim
137
 * 
138
 * To accept the call, the \c accept request can be used. This request
139
 * must be attached to a JSEP answer containing the WebRTC-related
140
 * information to complete the actual PeerConnection setup. A \c accept
141
 * request has to be formatted as follows:
142
 * 
143
\verbatim
144
{
145
        "request" : "accept"
146
}
147
\endverbatim
148
 * 
149
 * If successul, both the caller and the callee will receive an
150
 * \c accepted event to notify them about the success of the signalling:
151
 * 
152
\verbatim
153
{
154
        "videocall" : "event",
155
        "result" : {
156
                "event" : "accepted",
157
                "username" : "<caller username>"
158
        }
159
}
160
\endverbatim
161
 *
162
 * At this point, the media-related settings of the call can be modified
163
 * on either side by means of a \c set request, which acts pretty much
164
 * as the one in the \ref echoapi . The \c set request has to be
165
 * formatted as follows. All the attributes (except \c request) are
166
 * optional, so any request can contain a subset of them:
167
 *
168
\verbatim
169
{
170
        "request" : "set",
171
        "audio" : true|false,
172
        "video" : true|false,
173
        "bitrate" : <numeric bitrate value>,
174
        "record" : true|false,
175
        "filename" : <base path/filename to use for the recording>
176
}
177
\endverbatim
178
 *
179
 * \c audio instructs the plugin to do or do not relay audio frames;
180
 * \c video does the same for video; \c bitrate caps the bandwidth to
181
 * force on the browser encoding side (e.g., 128000 for 128kbps);
182
 * \c record enables or disables the recording of this peer; in case
183
 * recording is enabled, \c filename allows to specify a base
184
 * path/filename to use for the files (-audio.mjr and -video.mjr are
185
 * automatically appended). Beware that enabling the recording only
186
 * records this user's contribution, and not the whole call: to record
187
 * both sides, you need to enable recording for both the peers in the
188
 * call.
189
 * 
190
 * A successful request will result in a \c set event:
191
 * 
192
\verbatim
193
{
194
        "videocall" : "event",
195
        "result" : {
196
                "event" : "set"
197
        }
198
}
199
\endverbatim
200
 * 
201
 * To decline an incoming call, cancel an attempt to call or simply
202
 * hangup an ongoing conversation, the \c hangup request can be used,
203
 * which has to be formatted as follows:
204
 * 
205
\verbatim
206
{
207
        "request" : "hangup"
208
}
209
\endverbatim
210
 *
211
 * Whatever the reason of a call being closed (e.g., a \c hangup request,
212
 * a PeerConnection being closed, or something else), both parties in
213
 * the communication will receive a \c hangup event:
214
 * 
215
\verbatim
216
{
217
        "videocall" : "event",
218
        "result" : {
219
                "event" : "hangup",
220
                "username" : "<username of who closed the communication>",
221
                "reason" : "<description of what happened>"
222
        }
223
}
224
\endverbatim
225
 * 
226
 * \ingroup plugins
227
 * \ref plugins
228
 */
229

    
230
#include "plugin.h"
231

    
232
#include <jansson.h>
233

    
234
#include "../debug.h"
235
#include "../apierror.h"
236
#include "../config.h"
237
#include "../mutex.h"
238
#include "../record.h"
239
#include "../rtcp.h"
240
#include "../utils.h"
241

    
242

    
243
/* Plugin information */
244
#define JANUS_VIDEOCALL_VERSION                        5
245
#define JANUS_VIDEOCALL_VERSION_STRING        "0.0.5"
246
#define JANUS_VIDEOCALL_DESCRIPTION                "This is a simple video call plugin for Janus, allowing two WebRTC peers to call each other through the gateway."
247
#define JANUS_VIDEOCALL_NAME                        "JANUS VideoCall plugin"
248
#define JANUS_VIDEOCALL_AUTHOR                        "Meetecho s.r.l."
249
#define JANUS_VIDEOCALL_PACKAGE                        "janus.plugin.videocall"
250

    
251
/* Plugin methods */
252
janus_plugin *create(void);
253
int janus_videocall_init(janus_callbacks *callback, const char *config_path);
254
void janus_videocall_destroy(void);
255
int janus_videocall_get_api_compatibility(void);
256
int janus_videocall_get_version(void);
257
const char *janus_videocall_get_version_string(void);
258
const char *janus_videocall_get_description(void);
259
const char *janus_videocall_get_name(void);
260
const char *janus_videocall_get_author(void);
261
const char *janus_videocall_get_package(void);
262
void janus_videocall_create_session(janus_plugin_session *handle, int *error);
263
struct janus_plugin_result *janus_videocall_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp);
264
void janus_videocall_setup_media(janus_plugin_session *handle);
265
void janus_videocall_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
266
void janus_videocall_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
267
void janus_videocall_incoming_data(janus_plugin_session *handle, char *buf, int len);
268
void janus_videocall_slow_link(janus_plugin_session *handle, int uplink, int video);
269
void janus_videocall_hangup_media(janus_plugin_session *handle);
270
void janus_videocall_destroy_session(janus_plugin_session *handle, int *error);
271
char *janus_videocall_query_session(janus_plugin_session *handle);
272

    
273
/* Plugin setup */
274
static janus_plugin janus_videocall_plugin =
275
        JANUS_PLUGIN_INIT (
276
                .init = janus_videocall_init,
277
                .destroy = janus_videocall_destroy,
278

    
279
                .get_api_compatibility = janus_videocall_get_api_compatibility,
280
                .get_version = janus_videocall_get_version,
281
                .get_version_string = janus_videocall_get_version_string,
282
                .get_description = janus_videocall_get_description,
283
                .get_name = janus_videocall_get_name,
284
                .get_author = janus_videocall_get_author,
285
                .get_package = janus_videocall_get_package,
286
                
287
                .create_session = janus_videocall_create_session,
288
                .handle_message = janus_videocall_handle_message,
289
                .setup_media = janus_videocall_setup_media,
290
                .incoming_rtp = janus_videocall_incoming_rtp,
291
                .incoming_rtcp = janus_videocall_incoming_rtcp,
292
                .incoming_data = janus_videocall_incoming_data,
293
                .slow_link = janus_videocall_slow_link,
294
                .hangup_media = janus_videocall_hangup_media,
295
                .destroy_session = janus_videocall_destroy_session,
296
                .query_session = janus_videocall_query_session,
297
        );
298

    
299
/* Plugin creator */
300
janus_plugin *create(void) {
301
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_VIDEOCALL_NAME);
302
        return &janus_videocall_plugin;
303
}
304

    
305
/* Parameter validation */
306
static struct janus_json_parameter request_parameters[] = {
307
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
308
};
309
static struct janus_json_parameter username_parameters[] = {
310
        {"username", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
311
};
312
static struct janus_json_parameter set_parameters[] = {
313
        {"audio", JANUS_JSON_BOOL, 0},
314
        {"video", JANUS_JSON_BOOL, 0},
315
        {"bitrate", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
316
        {"record", JANUS_JSON_BOOL, 0},
317
        {"filename", JSON_STRING, 0}
318
};
319

    
320
/* Useful stuff */
321
static volatile gint initialized = 0, stopping = 0;
322
static janus_callbacks *gateway = NULL;
323
static GThread *handler_thread;
324
static GThread *watchdog;
325
static void *janus_videocall_handler(void *data);
326

    
327
typedef struct janus_videocall_message {
328
        janus_plugin_session *handle;
329
        char *transaction;
330
        char *message;
331
        char *sdp_type;
332
        char *sdp;
333
} janus_videocall_message;
334
static GAsyncQueue *messages = NULL;
335
static janus_videocall_message exit_message;
336

    
337
static void janus_videocall_message_free(janus_videocall_message *msg) {
338
        if(!msg || msg == &exit_message)
339
                return;
340

    
341
        msg->handle = NULL;
342

    
343
        g_free(msg->transaction);
344
        msg->transaction = NULL;
345
        g_free(msg->message);
346
        msg->message = NULL;
347
        g_free(msg->sdp_type);
348
        msg->sdp_type = NULL;
349
        g_free(msg->sdp);
350
        msg->sdp = NULL;
351

    
352
        g_free(msg);
353
}
354

    
355
typedef struct janus_videocall_session {
356
        janus_plugin_session *handle;
357
        gchar *username;
358
        gboolean has_audio;
359
        gboolean has_video;
360
        gboolean audio_active;
361
        gboolean video_active;
362
        uint64_t bitrate;
363
        guint16 slowlink_count;
364
        struct janus_videocall_session *peer;
365
        janus_recorder *arc;        /* The Janus recorder instance for this user's audio, if enabled */
366
        janus_recorder *vrc;        /* The Janus recorder instance for this user's video, if enabled */
367
        janus_mutex rec_mutex;        /* Mutex to protect the recorders from race conditions */
368
        volatile gint hangingup;
369
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
370
} janus_videocall_session;
371
static GHashTable *sessions;
372
static GList *old_sessions;
373
static janus_mutex sessions_mutex;
374

    
375

    
376
/* Error codes */
377
#define JANUS_VIDEOCALL_ERROR_UNKNOWN_ERROR                        499
378
#define JANUS_VIDEOCALL_ERROR_NO_MESSAGE                        470
379
#define JANUS_VIDEOCALL_ERROR_INVALID_JSON                        471
380
#define JANUS_VIDEOCALL_ERROR_INVALID_REQUEST                472
381
#define JANUS_VIDEOCALL_ERROR_REGISTER_FIRST                473
382
#define JANUS_VIDEOCALL_ERROR_INVALID_ELEMENT                474
383
#define JANUS_VIDEOCALL_ERROR_MISSING_ELEMENT                475
384
#define JANUS_VIDEOCALL_ERROR_USERNAME_TAKEN                476
385
#define JANUS_VIDEOCALL_ERROR_ALREADY_REGISTERED        477
386
#define JANUS_VIDEOCALL_ERROR_NO_SUCH_USERNAME                478
387
#define JANUS_VIDEOCALL_ERROR_USE_ECHO_TEST                        479
388
#define JANUS_VIDEOCALL_ERROR_ALREADY_IN_CALL                480
389
#define JANUS_VIDEOCALL_ERROR_NO_CALL                                481
390
#define JANUS_VIDEOCALL_ERROR_MISSING_SDP                        482
391

    
392

    
393
/* VideoCall watchdog/garbage collector (sort of) */
394
void *janus_videocall_watchdog(void *data);
395
void *janus_videocall_watchdog(void *data) {
396
        JANUS_LOG(LOG_INFO, "VideoCall watchdog started\n");
397
        gint64 now = 0;
398
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
399
                janus_mutex_lock(&sessions_mutex);
400
                /* Iterate on all the sessions */
401
                now = janus_get_monotonic_time();
402
                if(old_sessions != NULL) {
403
                        GList *sl = old_sessions;
404
                        JANUS_LOG(LOG_HUGE, "Checking %d old VideoCall sessions...\n", g_list_length(old_sessions));
405
                        while(sl) {
406
                                janus_videocall_session *session = (janus_videocall_session *)sl->data;
407
                                if(!session) {
408
                                        sl = sl->next;
409
                                        continue;
410
                                }
411
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
412
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
413
                                        JANUS_LOG(LOG_VERB, "Freeing old VideoCall session\n");
414
                                        GList *rm = sl->next;
415
                                        old_sessions = g_list_delete_link(old_sessions, sl);
416
                                        sl = rm;
417
                                        session->handle = NULL;
418
                                        g_free(session);
419
                                        session = NULL;
420
                                        continue;
421
                                }
422
                                sl = sl->next;
423
                        }
424
                }
425
                janus_mutex_unlock(&sessions_mutex);
426
                g_usleep(500000);
427
        }
428
        JANUS_LOG(LOG_INFO, "VideoCall watchdog stopped\n");
429
        return NULL;
430
}
431

    
432

    
433
/* Plugin implementation */
434
int janus_videocall_init(janus_callbacks *callback, const char *config_path) {
435
        if(g_atomic_int_get(&stopping)) {
436
                /* Still stopping from before */
437
                return -1;
438
        }
439
        if(callback == NULL || config_path == NULL) {
440
                /* Invalid arguments */
441
                return -1;
442
        }
443

    
444
        /* Read configuration */
445
        char filename[255];
446
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_VIDEOCALL_PACKAGE);
447
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
448
        janus_config *config = janus_config_parse(filename);
449
        if(config != NULL)
450
                janus_config_print(config);
451
        /* This plugin actually has nothing to configure... */
452
        janus_config_destroy(config);
453
        config = NULL;
454
        
455
        sessions = g_hash_table_new(g_str_hash, g_str_equal);
456
        janus_mutex_init(&sessions_mutex);
457
        messages = g_async_queue_new_full((GDestroyNotify) janus_videocall_message_free);
458
        /* This is the callback we'll need to invoke to contact the gateway */
459
        gateway = callback;
460

    
461
        g_atomic_int_set(&initialized, 1);
462

    
463
        GError *error = NULL;
464
        /* Start the sessions watchdog */
465
        watchdog = g_thread_try_new("vcall watchdog", &janus_videocall_watchdog, NULL, &error);
466
        if(error != NULL) {
467
                g_atomic_int_set(&initialized, 0);
468
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoCall watchdog thread...\n", error->code, error->message ? error->message : "??");
469
                return -1;
470
        }
471
        /* Launch the thread that will handle incoming messages */
472
        handler_thread = g_thread_try_new("janus videocall handler", janus_videocall_handler, NULL, &error);
473
        if(error != NULL) {
474
                g_atomic_int_set(&initialized, 0);
475
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the VideoCall handler thread...\n", error->code, error->message ? error->message : "??");
476
                return -1;
477
        }
478
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_VIDEOCALL_NAME);
479
        return 0;
480
}
481

    
482
void janus_videocall_destroy(void) {
483
        if(!g_atomic_int_get(&initialized))
484
                return;
485
        g_atomic_int_set(&stopping, 1);
486

    
487
        g_async_queue_push(messages, &exit_message);
488
        if(handler_thread != NULL) {
489
                g_thread_join(handler_thread);
490
                handler_thread = NULL;
491
        }
492
        if(watchdog != NULL) {
493
                g_thread_join(watchdog);
494
                watchdog = NULL;
495
        }
496
        /* FIXME We should destroy the sessions cleanly */
497
        janus_mutex_lock(&sessions_mutex);
498
        g_hash_table_destroy(sessions);
499
        janus_mutex_unlock(&sessions_mutex);
500
        g_async_queue_unref(messages);
501
        messages = NULL;
502
        sessions = NULL;
503
        g_atomic_int_set(&initialized, 0);
504
        g_atomic_int_set(&stopping, 0);
505
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_VIDEOCALL_NAME);
506
}
507

    
508
int janus_videocall_get_api_compatibility(void) {
509
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
510
        return JANUS_PLUGIN_API_VERSION;
511
}
512

    
513
int janus_videocall_get_version(void) {
514
        return JANUS_VIDEOCALL_VERSION;
515
}
516

    
517
const char *janus_videocall_get_version_string(void) {
518
        return JANUS_VIDEOCALL_VERSION_STRING;
519
}
520

    
521
const char *janus_videocall_get_description(void) {
522
        return JANUS_VIDEOCALL_DESCRIPTION;
523
}
524

    
525
const char *janus_videocall_get_name(void) {
526
        return JANUS_VIDEOCALL_NAME;
527
}
528

    
529
const char *janus_videocall_get_author(void) {
530
        return JANUS_VIDEOCALL_AUTHOR;
531
}
532

    
533
const char *janus_videocall_get_package(void) {
534
        return JANUS_VIDEOCALL_PACKAGE;
535
}
536

    
537
void janus_videocall_create_session(janus_plugin_session *handle, int *error) {
538
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
539
                *error = -1;
540
                return;
541
        }        
542
        janus_videocall_session *session = (janus_videocall_session *)g_malloc0(sizeof(janus_videocall_session));
543
        if(session == NULL) {
544
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
545
                *error = -2;
546
                return;
547
        }
548
        session->handle = handle;
549
        session->has_audio = FALSE;
550
        session->has_video = FALSE;
551
        session->audio_active = TRUE;
552
        session->video_active = TRUE;
553
        session->bitrate = 0;        /* No limit */
554
        session->peer = NULL;
555
        session->username = NULL;
556
        janus_mutex_init(&session->rec_mutex);
557
        session->destroyed = 0;
558
        g_atomic_int_set(&session->hangingup, 0);
559
        handle->plugin_handle = session;
560

    
561
        return;
562
}
563

    
564
void janus_videocall_destroy_session(janus_plugin_session *handle, int *error) {
565
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
566
                *error = -1;
567
                return;
568
        }
569
        janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle; 
570
        if(!session) {
571
                JANUS_LOG(LOG_ERR, "No VideoCall session associated with this handle...\n");
572
                *error = -2;
573
                return;
574
        }
575
        janus_mutex_lock(&sessions_mutex);
576
        if(!session->destroyed) {
577
                JANUS_LOG(LOG_VERB, "Removing VideoCall user %s session...\n", session->username ? session->username : "'unknown'");
578
                janus_videocall_hangup_media(handle);
579
                session->destroyed = janus_get_monotonic_time();
580
                if(session->username != NULL) {
581
                        int res = g_hash_table_remove(sessions, (gpointer)session->username);
582
                        JANUS_LOG(LOG_VERB, "  -- Removed: %d\n", res);
583
                }
584
                /* Cleaning up and removing the session is done in a lazy way */
585
                old_sessions = g_list_append(old_sessions, session);
586
        }
587
        janus_mutex_unlock(&sessions_mutex);
588
        return;
589
}
590

    
591
char *janus_videocall_query_session(janus_plugin_session *handle) {
592
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
593
                return NULL;
594
        }        
595
        janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;
596
        if(!session) {
597
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
598
                return NULL;
599
        }
600
        /* Provide some generic info, e.g., if we're in a call and with whom */
601
        json_t *info = json_object();
602
        json_object_set_new(info, "state", json_string(session->peer ? "incall" : "idle"));
603
        json_object_set_new(info, "username", session->username ? json_string(session->username) : NULL);
604
        if(session->peer) {
605
                json_object_set_new(info, "peer", session->peer->username ? json_string(session->peer->username) : NULL);
606
                json_object_set_new(info, "audio_active", json_string(session->audio_active ? "true" : "false"));
607
                json_object_set_new(info, "video_active", json_string(session->video_active ? "true" : "false"));
608
                json_object_set_new(info, "bitrate", json_integer(session->bitrate));
609
                json_object_set_new(info, "slowlink_count", json_integer(session->slowlink_count));
610
        }
611
        if(session->arc || session->vrc) {
612
                json_t *recording = json_object();
613
                if(session->arc && session->arc->filename)
614
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
615
                if(session->vrc && session->vrc->filename)
616
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
617
                json_object_set_new(info, "recording", recording);
618
        }
619
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
620
        char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
621
        json_decref(info);
622
        return info_text;
623
}
624

    
625
struct janus_plugin_result *janus_videocall_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
626
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
627
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
628
        janus_videocall_message *msg = g_malloc0(sizeof(janus_videocall_message));
629
        if(msg == NULL) {
630
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
631
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, "Memory error");
632
        }
633
        msg->handle = handle;
634
        msg->transaction = transaction;
635
        msg->message = message;
636
        msg->sdp_type = sdp_type;
637
        msg->sdp = sdp;
638
        g_async_queue_push(messages, msg);
639

    
640
        /* All the requests to this plugin are handled asynchronously */
641
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
642
}
643

    
644
void janus_videocall_setup_media(janus_plugin_session *handle) {
645
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
646
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
647
                return;
648
        janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;        
649
        if(!session) {
650
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
651
                return;
652
        }
653
        if(session->destroyed)
654
                return;
655
        g_atomic_int_set(&session->hangingup, 0);
656
        /* We really don't care, as we only relay RTP/RTCP we get in the first place anyway */
657
}
658

    
659
void janus_videocall_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
660
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
661
                return;
662
        if(gateway) {
663
                /* Honour the audio/video active flags */
664
                janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;        
665
                if(!session) {
666
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
667
                        return;
668
                }
669
                if(!session->peer) {
670
                        JANUS_LOG(LOG_ERR, "Session has no peer...\n");
671
                        return;
672
                }
673
                if(session->destroyed || session->peer->destroyed)
674
                        return;
675
                if((!video && session->audio_active) || (video && session->video_active)) {
676
                        /* Save the frame if we're recording */
677
                        janus_recorder_save_frame(video ? session->vrc : session->arc, buf, len);
678
                        /* Forward the packet to the peer */
679
                        gateway->relay_rtp(session->peer->handle, video, buf, len);
680
                }
681
        }
682
}
683

    
684
void janus_videocall_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
685
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
686
                return;
687
        if(gateway) {
688
                janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;        
689
                if(!session) {
690
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
691
                        return;
692
                }
693
                if(!session->peer) {
694
                        JANUS_LOG(LOG_ERR, "Session has no peer...\n");
695
                        return;
696
                }
697
                if(session->destroyed || session->peer->destroyed)
698
                        return;
699
                if(session->bitrate > 0)
700
                        janus_rtcp_cap_remb(buf, len, session->bitrate);
701
                gateway->relay_rtcp(session->peer->handle, video, buf, len);
702
        }
703
}
704

    
705
void janus_videocall_incoming_data(janus_plugin_session *handle, char *buf, int len) {
706
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
707
                return;
708
        if(gateway) {
709
                janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;        
710
                if(!session) {
711
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
712
                        return;
713
                }
714
                if(!session->peer) {
715
                        JANUS_LOG(LOG_ERR, "Session has no peer...\n");
716
                        return;
717
                }
718
                if(session->destroyed || session->peer->destroyed)
719
                        return;
720
                if(buf == NULL || len <= 0)
721
                        return;
722
                char *text = g_malloc0(len+1);
723
                memcpy(text, buf, len);
724
                *(text+len) = '\0';
725
                JANUS_LOG(LOG_VERB, "Got a DataChannel message (%zu bytes) to forward: %s\n", strlen(text), text);
726
                gateway->relay_data(session->peer->handle, text, strlen(text));
727
                g_free(text);
728
        }
729
}
730

    
731
void janus_videocall_slow_link(janus_plugin_session *handle, int uplink, int video) {
732
        /* The core is informing us that our peer got or sent too many NACKs, are we pushing media too hard? */
733
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
734
                return;
735
        janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;        
736
        if(!session) {
737
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
738
                return;
739
        }
740
        if(session->destroyed)
741
                return;
742
        session->slowlink_count++;
743
        if(uplink && !video && !session->audio_active) {
744
                /* We're not relaying audio and the peer is expecting it, so NACKs are normal */
745
                JANUS_LOG(LOG_VERB, "Getting a lot of NACKs (slow uplink) for audio, but that's expected, a configure disabled the audio forwarding\n");
746
        } else if(uplink && video && !session->video_active) {
747
                /* We're not relaying video and the peer is expecting it, so NACKs are normal */
748
                JANUS_LOG(LOG_VERB, "Getting a lot of NACKs (slow uplink) for video, but that's expected, a configure disabled the video forwarding\n");
749
        } else {
750
                /* Slow uplink or downlink, maybe we set the bitrate cap too high? */
751
                if(video) {
752
                        /* Halve the bitrate, but don't go too low... */
753
                        if(!uplink) {
754
                                /* Downlink issue, user has trouble sending, halve this user's bitrate cap */
755
                                session->bitrate = session->bitrate > 0 ? session->bitrate : 512*1024;
756
                                session->bitrate = session->bitrate/2;
757
                                if(session->bitrate < 64*1024)
758
                                        session->bitrate = 64*1024;
759
                        } else {
760
                                /* Uplink issue, user has trouble receiving, halve this user's peer's bitrate cap */
761
                                if(session->peer == NULL || session->peer->handle == NULL)
762
                                        return;        /* Nothing to do */
763
                                session->peer->bitrate = session->peer->bitrate > 0 ? session->peer->bitrate : 512*1024;
764
                                session->peer->bitrate = session->peer->bitrate/2;
765
                                if(session->peer->bitrate < 64*1024)
766
                                        session->peer->bitrate = 64*1024;
767
                        }
768
                        JANUS_LOG(LOG_WARN, "Getting a lot of NACKs (slow %s) for %s, forcing a lower REMB: %"SCNu64"\n",
769
                                uplink ? "uplink" : "downlink", video ? "video" : "audio", uplink ? session->peer->bitrate : session->bitrate);
770
                        /* ... and send a new REMB back */
771
                        char rtcpbuf[24];
772
                        janus_rtcp_remb((char *)(&rtcpbuf), 24, uplink ? session->peer->bitrate : session->bitrate);
773
                        gateway->relay_rtcp(uplink ? session->peer->handle : handle, 1, rtcpbuf, 24);
774
                        /* As a last thing, notify the affected user about this */
775
                        json_t *event = json_object();
776
                        json_object_set_new(event, "videocall", json_string("event"));
777
                        json_t *result = json_object();
778
                        json_object_set_new(result, "status", json_string("slow_link"));
779
                        json_object_set_new(result, "bitrate", json_integer(uplink ? session->peer->bitrate : session->bitrate));
780
                        json_object_set_new(event, "result", result);
781
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
782
                        json_decref(event);
783
                        json_decref(result);
784
                        event = NULL;
785
                        gateway->push_event(uplink ? session->peer->handle : handle, &janus_videocall_plugin, NULL, event_text, NULL, NULL);
786
                        g_free(event_text);
787
                }
788
        }
789
}
790

    
791
void janus_videocall_hangup_media(janus_plugin_session *handle) {
792
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
793
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
794
                return;
795
        janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;        
796
        if(!session) {
797
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
798
                return;
799
        }
800
        if(session->destroyed)
801
                return;
802
        if(g_atomic_int_add(&session->hangingup, 1))
803
                return;
804
        /* Get rid of the recorders, if available */
805
        janus_mutex_lock(&session->rec_mutex);
806
        if(session->arc) {
807
                janus_recorder_close(session->arc);
808
                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
809
                janus_recorder_free(session->arc);
810
        }
811
        session->arc = NULL;
812
        if(session->vrc) {
813
                janus_recorder_close(session->vrc);
814
                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
815
                janus_recorder_free(session->vrc);
816
        }
817
        session->vrc = NULL;
818
        janus_mutex_unlock(&session->rec_mutex);
819
        if(session->peer) {
820
                /* Send event to our peer too */
821
                json_t *call = json_object();
822
                json_object_set_new(call, "videocall", json_string("event"));
823
                json_t *calling = json_object();
824
                json_object_set_new(calling, "event", json_string("hangup"));
825
                json_object_set_new(calling, "username", json_string(session->username));
826
                json_object_set_new(calling, "reason", json_string("Remote hangup"));
827
                json_object_set_new(call, "result", calling);
828
                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
829
                json_decref(call);
830
                JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
831
                int ret = gateway->push_event(session->peer->handle, &janus_videocall_plugin, NULL, call_text, NULL, NULL);
832
                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
833
                g_free(call_text);
834
        }
835
        session->peer = NULL;
836
        /* Reset controls */
837
        session->has_audio = FALSE;
838
        session->has_video = FALSE;
839
        session->audio_active = TRUE;
840
        session->video_active = TRUE;
841
        session->bitrate = 0;
842
}
843

    
844
/* Thread to handle incoming messages */
845
static void *janus_videocall_handler(void *data) {
846
        JANUS_LOG(LOG_VERB, "Joining VideoCall handler thread\n");
847
        janus_videocall_message *msg = NULL;
848
        int error_code = 0;
849
        char error_cause[512];
850
        json_t *root = NULL;
851
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
852
                msg = g_async_queue_pop(messages);
853
                if(msg == NULL)
854
                        continue;
855
                if(msg == &exit_message)
856
                        break;
857
                if(msg->handle == NULL) {
858
                        janus_videocall_message_free(msg);
859
                        continue;
860
                }
861
                janus_videocall_session *session = (janus_videocall_session *)msg->handle->plugin_handle;
862
                if(!session) {
863
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
864
                        janus_videocall_message_free(msg);
865
                        continue;
866
                }
867
                if(session->destroyed) {
868
                        janus_videocall_message_free(msg);
869
                        continue;
870
                }
871
                /* Handle request */
872
                error_code = 0;
873
                root = NULL;
874
                JANUS_LOG(LOG_VERB, "Handling message: %s\n", msg->message);
875
                if(msg->message == NULL) {
876
                        JANUS_LOG(LOG_ERR, "No message??\n");
877
                        error_code = JANUS_VIDEOCALL_ERROR_NO_MESSAGE;
878
                        g_snprintf(error_cause, 512, "%s", "No message??");
879
                        goto error;
880
                }
881
                json_error_t error;
882
                root = json_loads(msg->message, 0, &error);
883
                if(!root) {
884
                        JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
885
                        error_code = JANUS_VIDEOCALL_ERROR_INVALID_JSON;
886
                        g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
887
                        goto error;
888
                }
889
                if(!json_is_object(root)) {
890
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
891
                        error_code = JANUS_VIDEOCALL_ERROR_INVALID_JSON;
892
                        g_snprintf(error_cause, 512, "JSON error: not an object");
893
                        goto error;
894
                }
895
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
896
                        error_code, error_cause, TRUE,
897
                        JANUS_VIDEOCALL_ERROR_MISSING_ELEMENT, JANUS_VIDEOCALL_ERROR_INVALID_ELEMENT);
898
                if(error_code != 0)
899
                        goto error;
900
                json_t *request = json_object_get(root, "request");
901
                const char *request_text = json_string_value(request);
902
                json_t *result = NULL;
903
                char *sdp_type = NULL, *sdp = NULL;
904
                if(!strcasecmp(request_text, "list")) {
905
                        result = json_object();
906
                        json_t *list = json_array();
907
                        JANUS_LOG(LOG_VERB, "Request for the list of peers\n");
908
                        /* Return a list of all available mountpoints */
909
                        janus_mutex_lock(&sessions_mutex);
910
                        GHashTableIter iter;
911
                        gpointer value;
912
                        g_hash_table_iter_init(&iter, sessions);
913
                        while (g_hash_table_iter_next(&iter, NULL, &value)) {
914
                                janus_videocall_session *user = value;
915
                                if(user != NULL && user->username != NULL)
916
                                        json_array_append_new(list, json_string(user->username));
917
                        }
918
                        json_object_set_new(result, "list", list);
919
                        janus_mutex_unlock(&sessions_mutex);
920
                } else if(!strcasecmp(request_text, "register")) {
921
                        /* Map this handle to a username */
922
                        if(session->username != NULL) {
923
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->username);
924
                                error_code = JANUS_VIDEOCALL_ERROR_ALREADY_REGISTERED;
925
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->username);
926
                                goto error;
927
                        }
928
                        JANUS_VALIDATE_JSON_OBJECT(root, username_parameters,
929
                                error_code, error_cause, TRUE,
930
                                JANUS_VIDEOCALL_ERROR_MISSING_ELEMENT, JANUS_VIDEOCALL_ERROR_INVALID_ELEMENT);
931
                        if(error_code != 0)
932
                                goto error;
933
                        json_t *username = json_object_get(root, "username");
934
                        const char *username_text = json_string_value(username);
935
                        janus_mutex_lock(&sessions_mutex);
936
                        if(g_hash_table_lookup(sessions, username_text) != NULL) {
937
                                janus_mutex_unlock(&sessions_mutex);
938
                                JANUS_LOG(LOG_ERR, "Username '%s' already taken\n", username_text);
939
                                error_code = JANUS_VIDEOCALL_ERROR_USERNAME_TAKEN;
940
                                g_snprintf(error_cause, 512, "Username '%s' already taken", username_text);
941
                                goto error;
942
                        }
943
                        janus_mutex_unlock(&sessions_mutex);
944
                        session->username = g_strdup(username_text);
945
                        if(session->username == NULL) {
946
                                JANUS_LOG(LOG_FATAL, "Memory error!\n");
947
                                error_code = JANUS_VIDEOCALL_ERROR_UNKNOWN_ERROR;
948
                                g_snprintf(error_cause, 512, "Memory error");
949
                                goto error;
950
                        }
951
                        janus_mutex_lock(&sessions_mutex);
952
                        g_hash_table_insert(sessions, (gpointer)session->username, session);
953
                        janus_mutex_unlock(&sessions_mutex);
954
                        result = json_object();
955
                        json_object_set_new(result, "event", json_string("registered"));
956
                        json_object_set_new(result, "username", json_string(username_text));
957
                } else if(!strcasecmp(request_text, "call")) {
958
                        /* Call another peer */
959
                        if(session->username == NULL) {
960
                                JANUS_LOG(LOG_ERR, "Register a username first\n");
961
                                error_code = JANUS_VIDEOCALL_ERROR_REGISTER_FIRST;
962
                                g_snprintf(error_cause, 512, "Register a username first");
963
                                goto error;
964
                        }
965
                        if(session->peer != NULL) {
966
                                JANUS_LOG(LOG_ERR, "Already in a call\n");
967
                                error_code = JANUS_VIDEOCALL_ERROR_ALREADY_IN_CALL;
968
                                g_snprintf(error_cause, 512, "Already in a call");
969
                                goto error;
970
                        }
971
                        JANUS_VALIDATE_JSON_OBJECT(root, username_parameters,
972
                                error_code, error_cause, TRUE,
973
                                JANUS_VIDEOCALL_ERROR_MISSING_ELEMENT, JANUS_VIDEOCALL_ERROR_INVALID_ELEMENT);
974
                        if(error_code != 0)
975
                                goto error;
976
                        json_t *username = json_object_get(root, "username");
977
                        const char *username_text = json_string_value(username);
978
                        if(!strcmp(username_text, session->username)) {
979
                                JANUS_LOG(LOG_ERR, "You can't call yourself... use the EchoTest for that\n");
980
                                error_code = JANUS_VIDEOCALL_ERROR_USE_ECHO_TEST;
981
                                g_snprintf(error_cause, 512, "You can't call yourself... use the EchoTest for that");
982
                                goto error;
983
                        }
984
                        janus_mutex_lock(&sessions_mutex);
985
                        janus_videocall_session *peer = g_hash_table_lookup(sessions, username_text);
986
                        if(peer == NULL || peer->destroyed) {
987
                                janus_mutex_unlock(&sessions_mutex);
988
                                JANUS_LOG(LOG_ERR, "Username '%s' doesn't exist\n", username_text);
989
                                error_code = JANUS_VIDEOCALL_ERROR_NO_SUCH_USERNAME;
990
                                g_snprintf(error_cause, 512, "Username '%s' doesn't exist", username_text);
991
                                goto error;
992
                        }
993
                        if(peer->peer != NULL) {
994
                                janus_mutex_unlock(&sessions_mutex);
995
                                JANUS_LOG(LOG_VERB, "%s is busy\n", username_text);
996
                                result = json_object();
997
                                json_object_set_new(result, "event", json_string("hangup"));
998
                                json_object_set_new(result, "username", json_string(session->username));
999
                                json_object_set_new(result, "reason", json_string("User busy"));
1000
                        } else {
1001
                                janus_mutex_unlock(&sessions_mutex);
1002
                                /* Any SDP to handle? if not, something's wrong */
1003
                                if(!msg->sdp) {
1004
                                        JANUS_LOG(LOG_ERR, "Missing SDP\n");
1005
                                        error_code = JANUS_VIDEOCALL_ERROR_MISSING_SDP;
1006
                                        g_snprintf(error_cause, 512, "Missing SDP");
1007
                                        goto error;
1008
                                }
1009
                                janus_mutex_lock(&sessions_mutex);
1010
                                session->peer = peer;
1011
                                peer->peer = session;
1012
                                session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
1013
                                session->has_video = (strstr(msg->sdp, "m=video") != NULL);
1014
                                janus_mutex_unlock(&sessions_mutex);
1015
                                JANUS_LOG(LOG_VERB, "%s is calling %s\n", session->username, session->peer->username);
1016
                                JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1017
                                /* Send SDP to our peer */
1018
                                json_t *call = json_object();
1019
                                json_object_set_new(call, "videocall", json_string("event"));
1020
                                json_t *calling = json_object();
1021
                                json_object_set_new(calling, "event", json_string("incomingcall"));
1022
                                json_object_set_new(calling, "username", json_string(session->username));
1023
                                json_object_set_new(call, "result", calling);
1024
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1025
                                json_decref(call);
1026
                                /* Make also sure we get rid of ULPfec, red, etc. */
1027
                                char *sdp = g_strdup(msg->sdp);
1028
                                if(strstr(sdp, "ulpfec")) {
1029
                                        /* FIXME This really needs some better code */
1030
                                        sdp = janus_string_replace(sdp, "a=rtpmap:116 red/90000\r\n", "");
1031
                                        sdp = janus_string_replace(sdp, "a=rtpmap:117 ulpfec/90000\r\n", "");
1032
                                        sdp = janus_string_replace(sdp, "a=rtpmap:96 rtx/90000\r\n", "");
1033
                                        sdp = janus_string_replace(sdp, "a=fmtp:96 apt=100\r\n", "");
1034
                                        sdp = janus_string_replace(sdp, "a=rtpmap:97 rtx/90000\r\n", "");
1035
                                        sdp = janus_string_replace(sdp, "a=fmtp:97 apt=101\r\n", "");
1036
                                        sdp = janus_string_replace(sdp, "a=rtpmap:98 rtx/90000\r\n", "");
1037
                                        sdp = janus_string_replace(sdp, "a=fmtp:98 apt=116\r\n", "");
1038
                                        sdp = janus_string_replace(sdp, " 116", "");
1039
                                        sdp = janus_string_replace(sdp, " 117", "");
1040
                                        sdp = janus_string_replace(sdp, " 96", "");
1041
                                        sdp = janus_string_replace(sdp, " 97", "");
1042
                                        sdp = janus_string_replace(sdp, " 98", "");
1043
                                }
1044
                                g_atomic_int_set(&session->hangingup, 0);
1045
                                JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
1046
                                int ret = gateway->push_event(peer->handle, &janus_videocall_plugin, NULL, call_text, msg->sdp_type, sdp);
1047
                                g_free(sdp);
1048
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1049
                                g_free(call_text);
1050
                                /* Send an ack back */
1051
                                result = json_object();
1052
                                json_object_set_new(result, "event", json_string("calling"));
1053
                        }
1054
                } else if(!strcasecmp(request_text, "accept")) {
1055
                        /* Accept a call from another peer */
1056
                        if(session->peer == NULL) {
1057
                                JANUS_LOG(LOG_ERR, "No incoming call to accept\n");
1058
                                error_code = JANUS_VIDEOCALL_ERROR_NO_CALL;
1059
                                g_snprintf(error_cause, 512, "No incoming call to accept");
1060
                                goto error;
1061
                        }
1062
                        /* Any SDP to handle? if not, something's wrong */
1063
                        if(!msg->sdp) {
1064
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1065
                                error_code = JANUS_VIDEOCALL_ERROR_MISSING_SDP;
1066
                                g_snprintf(error_cause, 512, "Missing SDP");
1067
                                goto error;
1068
                        }
1069
                        JANUS_LOG(LOG_VERB, "%s is accepting a call from %s\n", session->username, session->peer->username);
1070
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1071
                        session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
1072
                        session->has_video = (strstr(msg->sdp, "m=video") != NULL);
1073
                        /* Send SDP to our peer */
1074
                        json_t *call = json_object();
1075
                        json_object_set_new(call, "videocall", json_string("event"));
1076
                        json_t *calling = json_object();
1077
                        json_object_set_new(calling, "event", json_string("accepted"));
1078
                        json_object_set_new(calling, "username", json_string(session->username));
1079
                        json_object_set_new(call, "result", calling);
1080
                        char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1081
                        json_decref(call);
1082
                        g_atomic_int_set(&session->hangingup, 0);
1083
                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
1084
                        int ret = gateway->push_event(session->peer->handle, &janus_videocall_plugin, NULL, call_text, msg->sdp_type, msg->sdp);
1085
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1086
                        g_free(call_text);
1087
                        /* Send an ack back */
1088
                        result = json_object();
1089
                        json_object_set_new(result, "event", json_string("accepted"));
1090
                } else if(!strcasecmp(request_text, "set")) {
1091
                        /* Update the local configuration (audio/video mute/unmute, bitrate cap or recording) */
1092
                        JANUS_VALIDATE_JSON_OBJECT(root, set_parameters,
1093
                                error_code, error_cause, TRUE,
1094
                                JANUS_VIDEOCALL_ERROR_MISSING_ELEMENT, JANUS_VIDEOCALL_ERROR_INVALID_ELEMENT);
1095
                        if(error_code != 0)
1096
                                goto error;
1097
                        json_t *audio = json_object_get(root, "audio");
1098
                        json_t *video = json_object_get(root, "video");
1099
                        json_t *bitrate = json_object_get(root, "bitrate");
1100
                        json_t *record = json_object_get(root, "record");
1101
                        json_t *recfile = json_object_get(root, "filename");
1102
                        if(audio) {
1103
                                session->audio_active = json_is_true(audio);
1104
                                JANUS_LOG(LOG_VERB, "Setting audio property: %s\n", session->audio_active ? "true" : "false");
1105
                        }
1106
                        if(video) {
1107
                                if(!session->video_active && json_is_true(video)) {
1108
                                        /* Send a PLI */
1109
                                        JANUS_LOG(LOG_VERB, "Just (re-)enabled video, sending a PLI to recover it\n");
1110
                                        char buf[12];
1111
                                        memset(buf, 0, 12);
1112
                                        janus_rtcp_pli((char *)&buf, 12);
1113
                                        gateway->relay_rtcp(session->handle, 1, buf, 12);
1114
                                }
1115
                                session->video_active = json_is_true(video);
1116
                                JANUS_LOG(LOG_VERB, "Setting video property: %s\n", session->video_active ? "true" : "false");
1117
                        }
1118
                        if(bitrate) {
1119
                                session->bitrate = json_integer_value(bitrate);
1120
                                JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64"\n", session->bitrate);
1121
                                if(session->bitrate > 0) {
1122
                                        /* FIXME Generate a new REMB (especially useful for Firefox, which doesn't send any we can cap later) */
1123
                                        char buf[24];
1124
                                        memset(buf, 0, 24);
1125
                                        janus_rtcp_remb((char *)&buf, 24, session->bitrate);
1126
                                        JANUS_LOG(LOG_VERB, "Sending REMB\n");
1127
                                        gateway->relay_rtcp(session->handle, 1, buf, 24);
1128
                                        /* FIXME How should we handle a subsequent "no limit" bitrate? */
1129
                                }
1130
                        }
1131
                        if(record) {
1132
                                if(msg->sdp) {
1133
                                        session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
1134
                                        session->has_video = (strstr(msg->sdp, "m=video") != NULL);
1135
                                }
1136
                                gboolean recording = json_is_true(record);
1137
                                const char *recording_base = json_string_value(recfile);
1138
                                JANUS_LOG(LOG_VERB, "Recording %s (base filename: %s)\n", recording ? "enabled" : "disabled", recording_base ? recording_base : "not provided");
1139
                                janus_mutex_lock(&session->rec_mutex);
1140
                                if(!recording) {
1141
                                        /* Not recording (anymore?) */
1142
                                        if(session->arc) {
1143
                                                janus_recorder_close(session->arc);
1144
                                                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1145
                                                janus_recorder_free(session->arc);
1146
                                        }
1147
                                        session->arc = NULL;
1148
                                        if(session->vrc) {
1149
                                                janus_recorder_close(session->vrc);
1150
                                                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1151
                                                janus_recorder_free(session->vrc);
1152
                                        }
1153
                                        session->vrc = NULL;
1154
                                } else {
1155
                                        /* We've started recording, send a PLI and go on */
1156
                                        char filename[255];
1157
                                        gint64 now = janus_get_real_time();
1158
                                        if(session->has_audio) {
1159
                                                /* FIXME We assume we're recording Opus, here */
1160
                                                memset(filename, 0, 255);
1161
                                                if(recording_base) {
1162
                                                        /* Use the filename and path we have been provided */
1163
                                                        g_snprintf(filename, 255, "%s-audio", recording_base);
1164
                                                        session->arc = janus_recorder_create(NULL, "opus", filename);
1165
                                                        if(session->arc == NULL) {
1166
                                                                /* FIXME We should notify the fact the recorder could not be created */
1167
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this VideoCall user!\n");
1168
                                                        }
1169
                                                } else {
1170
                                                        /* Build a filename */
1171
                                                        g_snprintf(filename, 255, "videocall-%s-%s-%"SCNi64"-audio",
1172
                                                                session->username ? session->username : "unknown",
1173
                                                                (session->peer && session->peer->username) ? session->peer->username : "unknown",
1174
                                                                now);
1175
                                                        session->arc = janus_recorder_create(NULL, "opus", filename);
1176
                                                        if(session->arc == NULL) {
1177
                                                                /* FIXME We should notify the fact the recorder could not be created */
1178
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this VideoCall user!\n");
1179
                                                        }
1180
                                                }
1181
                                        }
1182
                                        if(session->has_video) {
1183
                                                /* FIXME We assume we're recording VP8, here */
1184
                                                memset(filename, 0, 255);
1185
                                                if(recording_base) {
1186
                                                        /* Use the filename and path we have been provided */
1187
                                                        g_snprintf(filename, 255, "%s-video", recording_base);
1188
                                                        session->vrc = janus_recorder_create(NULL, "vp8", filename);
1189
                                                        if(session->vrc == NULL) {
1190
                                                                /* FIXME We should notify the fact the recorder could not be created */
1191
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this VideoCall user!\n");
1192
                                                        }
1193
                                                } else {
1194
                                                        /* Build a filename */
1195
                                                        g_snprintf(filename, 255, "videocall-%s-%s-%"SCNi64"-video",
1196
                                                                session->username ? session->username : "unknown",
1197
                                                                (session->peer && session->peer->username) ? session->peer->username : "unknown",
1198
                                                                now);
1199
                                                        session->vrc = janus_recorder_create(NULL, "vp8", filename);
1200
                                                        if(session->vrc == NULL) {
1201
                                                                /* FIXME We should notify the fact the recorder could not be created */
1202
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this VideoCall user!\n");
1203
                                                        }
1204
                                                }
1205
                                                /* Send a PLI */
1206
                                                JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
1207
                                                char buf[12];
1208
                                                memset(buf, 0, 12);
1209
                                                janus_rtcp_pli((char *)&buf, 12);
1210
                                                gateway->relay_rtcp(session->handle, 1, buf, 12);
1211
                                        }
1212
                                }
1213
                                janus_mutex_unlock(&session->rec_mutex);
1214
                        }
1215
                        /* Send an ack back */
1216
                        result = json_object();
1217
                        json_object_set_new(result, "event", json_string("set"));
1218
                } else if(!strcasecmp(request_text, "hangup")) {
1219
                        /* Hangup an ongoing call or reject an incoming one */
1220
                        janus_mutex_lock(&sessions_mutex);
1221
                        janus_videocall_session *peer = session->peer;
1222
                        if(peer == NULL) {
1223
                                JANUS_LOG(LOG_WARN, "No call to hangup\n");
1224
                        } else {
1225
                                JANUS_LOG(LOG_VERB, "%s is hanging up the call with %s\n", session->username, peer->username);
1226
                                session->peer = NULL;
1227
                                peer->peer = NULL;
1228
                        }
1229
                        janus_mutex_unlock(&sessions_mutex);
1230
                        /* Notify the success as an hangup message */
1231
                        result = json_object();
1232
                        json_object_set_new(result, "event", json_string("hangup"));
1233
                        json_object_set_new(result, "username", json_string(session->username));
1234
                        json_object_set_new(result, "reason", json_string("We did the hangup"));
1235
                        if(peer != NULL) {
1236
                                /* Send event to our peer too */
1237
                                json_t *call = json_object();
1238
                                json_object_set_new(call, "videocall", json_string("event"));
1239
                                json_t *calling = json_object();
1240
                                json_object_set_new(calling, "event", json_string("hangup"));
1241
                                json_object_set_new(calling, "username", json_string(session->username));
1242
                                json_object_set_new(calling, "reason", json_string("Remote hangup"));
1243
                                json_object_set_new(call, "result", calling);
1244
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1245
                                json_decref(call);
1246
                                JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
1247
                                int ret = gateway->push_event(peer->handle, &janus_videocall_plugin, NULL, call_text, NULL, NULL);
1248
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1249
                                g_free(call_text);
1250
                        }
1251
                } else {
1252
                        JANUS_LOG(LOG_ERR, "Unknown request (%s)\n", request_text);
1253
                        error_code = JANUS_VIDEOCALL_ERROR_INVALID_REQUEST;
1254
                        g_snprintf(error_cause, 512, "Unknown request (%s)", request_text);
1255
                        goto error;
1256
                }
1257

    
1258
                json_decref(root);
1259
                /* Prepare JSON event */
1260
                json_t *event = json_object();
1261
                json_object_set_new(event, "videocall", json_string("event"));
1262
                if(result != NULL)
1263
                        json_object_set_new(event, "result", result);
1264
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1265
                json_decref(event);
1266
                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1267
                int ret = gateway->push_event(msg->handle, &janus_videocall_plugin, msg->transaction, event_text, sdp_type, sdp);
1268
                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1269
                g_free(event_text);
1270
                if(sdp)
1271
                        g_free(sdp);
1272
                janus_videocall_message_free(msg);
1273
                continue;
1274
                
1275
error:
1276
                {
1277
                        if(root != NULL)
1278
                                json_decref(root);
1279
                        /* Prepare JSON error event */
1280
                        json_t *event = json_object();
1281
                        json_object_set_new(event, "videocall", json_string("event"));
1282
                        json_object_set_new(event, "error_code", json_integer(error_code));
1283
                        json_object_set_new(event, "error", json_string(error_cause));
1284
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1285
                        json_decref(event);
1286
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1287
                        int ret = gateway->push_event(msg->handle, &janus_videocall_plugin, msg->transaction, event_text, NULL, NULL);
1288
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1289
                        g_free(event_text);
1290
                        janus_videocall_message_free(msg);
1291
                }
1292
        }
1293
        JANUS_LOG(LOG_VERB, "Leaving VideoCall handler thread\n");
1294
        return NULL;
1295
}