Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_recordplay.c @ a972337c

History | View | Annotate | Download (71.9 KB)

1
/*! \file   janus_recordplay.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus Record&Play plugin
5
 * \details  This is a simple application that implements two different
6
 * features: it allows you to record a message you send with WebRTC in
7
 * the format defined in recorded.c (MJR recording) and subsequently
8
 * replay this recording (or other previously recorded) through WebRTC
9
 * as well.
10
 * 
11
 * This application aims at showing how easy recording frames sent by
12
 * a peer is, and how this recording can be re-used directly, without
13
 * necessarily involving a post-processing process (e.g., through the
14
 * tool we provide in janus-pp-rec.c).
15
 * 
16
 * The configuration process is quite easy: just choose where the
17
 * recordings should be saved. The same folder will also be used to list
18
 * the available recordings that can be replayed.
19
 * 
20
 * \note The application creates a special file in INI format with
21
 * \c .nfo extension for each recording that is saved. This is necessary
22
 * to map a specific audio .mjr file to a different video .mjr one, as
23
 * they always get saved in different files. If you want to replay
24
 * recordings you took in a different application (e.g., the streaming
25
 * or videoroom plugins) just copy the related files in the folder you
26
 * configured this plugin to use and create a .nfo file in the same
27
 * folder to create a mapping, e.g.:
28
 * 
29
 *                 [12345678]
30
 *                 name = My videoroom recording
31
 *                 date = 2014-10-14 17:11:26
32
 *                 audio = mcu-audio.mjr
33
 *                 video = mcu-video.mjr
34
 * 
35
 * \section recplayapi Record&Play API
36
 * 
37
 * The Record&Play API supports several requests, some of which are
38
 * synchronous and some asynchronous. There are some situations, though,
39
 * (invalid JSON, invalid request) which will always result in a
40
 * synchronous error response even for asynchronous requests. 
41
 * 
42
 * \c list and \c update are synchronous requests, which means you'll
43
 * get a response directly within the context of the transaction. \c list
44
 * lists all the available recordings, while \c update forces the plugin
45
 * to scan the folder of recordings again in case some were added manually
46
 * and not indexed in the meanwhile.
47
 * 
48
 * The \c record , \c play , \c start and \c stop requests instead are
49
 * all asynchronous, which means you'll get a notification about their
50
 * success or failure in an event. \c record asks the plugin to start
51
 * recording a session; \c play asks the plugin to prepare the playout
52
 * of one of the previously recorded sessions; \c start starts the
53
 * actual playout, and \c stop stops whatever the session was for, i.e.,
54
 * recording or replaying.
55
 * 
56
 * The \c list request has to be formatted as follows:
57
 *
58
\verbatim
59
{
60
        "request" : "list"
61
}
62
\endverbatim
63
 *
64
 * A successful request will result in an array of recordings:
65
 * 
66
\verbatim
67
{
68
        "recordplay" : "list",
69
        "list": [        // Array of recording objects
70
                {                        // Recording #1
71
                        "id": <numeric ID>,
72
                        "name": "<Name of the recording>",
73
                        "date": "<Date of the recording>",
74
                        "audio": "<Audio rec file, if any; optional>",
75
                        "video": "<Video rec file, if any; optional>"
76
                },
77
                <other recordings>
78
        ]
79
}
80
\endverbatim
81
 * 
82
 * An error instead (and the same applies to all other requests, so this
83
 * won't be repeated) would provide both an error code and a more verbose
84
 * description of the cause of the issue:
85
 * 
86
\verbatim
87
{
88
        "recordplay" : "event",
89
        "error_code" : <numeric ID, check Macros below>,
90
        "error" : "<error description as a string>"
91
}
92
\endverbatim
93
 * 
94
 * The \c update request instead has to be formatted as follows:
95
 *
96
\verbatim
97
{
98
        "request" : "update"
99
}
100
\endverbatim
101
 *
102
 * which will always result in an immediate ack ( \c ok ):
103
 * 
104
\verbatim
105
{
106
        "recordplay" : "ok",
107
}
108
\endverbatim
109
 *
110
 * Coming to the asynchronous requests, \c record has to be attached to
111
 * a JSEP offer (failure to do so will result in an error) and has to be
112
 * formatted as follows:
113
 *
114
\verbatim
115
{
116
        "request" : "record",
117
        "name" : "<Pretty name for the recording>"
118
}
119
\endverbatim
120
 *
121
 * A successful management of this request will result in a \c recording
122
 * event which will include the unique ID of the recording and a JSEP
123
 * answer to complete the setup of the associated PeerConnection to record:
124
 * 
125
\verbatim
126
{
127
        "recordplay" : "event",
128
        "result": {
129
                "status" : "recording",
130
                "id" : <unique numeric ID>
131
        }
132
}
133
\endverbatim
134
 *
135
 * A \c stop request can interrupt the recording process and tear the
136
 * associated PeerConnection down:
137
 * 
138
\verbatim
139
{
140
        "request" : "stop",
141
}
142
\endverbatim
143
 * 
144
 * This will result in a \c stopped status:
145
 * 
146
\verbatim
147
{
148
        "recordplay" : "event",
149
        "result": {
150
                "status" : "stopped",
151
                "id" : <unique numeric ID of the interrupted recording>
152
        }
153
}
154
\endverbatim
155
 * 
156
 * For what concerns the playout, instead, the process is slightly
157
 * different: you first choose a recording to replay, using \c play ,
158
 * and then start its playout using a \c start request. Just as before,
159
 * a \c stop request will interrupt the playout and tear the PeerConnection
160
 * down. It's very important to point out that no JSEP offer must be
161
 * sent for replaying a recording: in this case, it will always be the
162
 * plugin to generate a JSON offer (in response to a \c play request),
163
 * which means you'll then have to provide a JSEP answer within the
164
 * context of the following \c start request which will close the circle.
165
 * 
166
 * A \c play request has to be formatted as follows:
167
 * 
168
\verbatim
169
{
170
        "request" : "play",
171
        "id" : <unique numeric ID of the recording to replay>
172
}
173
\endverbatim
174
 * 
175
 * This will result in a \c preparing status notification which will be
176
 * attached to the JSEP offer originated by the plugin in order to
177
 * match the media available in the recording:
178
 * 
179
\verbatim
180
{
181
        "recordplay" : "event",
182
        "result": {
183
                "status" : "preparing",
184
                "id" : <unique numeric ID of the recording>
185
        }
186
}
187
\endverbatim
188
 * 
189
 * A \c start request, which as anticipated must be attached to the JSEP
190
 * answer to the previous offer sent by the plugin, has to be formatted
191
 * as follows:
192
 * 
193
\verbatim
194
{
195
        "request" : "start",
196
}
197
\endverbatim
198
 * 
199
 * This will result in a \c playing status notification:
200
 * 
201
\verbatim
202
{
203
        "recordplay" : "event",
204
        "result": {
205
                "status" : "playing"
206
        }
207
}
208
\endverbatim
209
 * 
210
 * Just as before, a \c stop request can interrupt the playout process at
211
 * any time, and tear the associated PeerConnection down:
212
 * 
213
\verbatim
214
{
215
        "request" : "stop",
216
}
217
\endverbatim
218
 * 
219
 * This will result in a \c stopped status:
220
 * 
221
\verbatim
222
{
223
        "recordplay" : "event",
224
        "result": {
225
                "status" : "stopped"
226
        }
227
}
228
\endverbatim
229
 * 
230
 * If the plugin detects a loss of the associated PeerConnection, whether
231
 * as a result of a \c stop request or because the 10 seconds passed, a
232
 * \c done result notification is triggered to inform the application
233
 * the recording/playout session is over:
234
 * 
235
\verbatim
236
{
237
        "recordplay" : "event",
238
        "result": "done"
239
}
240
\endverbatim
241
 *
242
 * \ingroup plugins
243
 * \ref plugins
244
 */
245

    
246
#include "plugin.h"
247

    
248
#include <dirent.h>
249
#include <arpa/inet.h>
250
#include <sys/stat.h>
251
#include <sys/time.h>
252
#include <jansson.h>
253

    
254
#include "../debug.h"
255
#include "../apierror.h"
256
#include "../config.h"
257
#include "../mutex.h"
258
#include "../record.h"
259
#include "../rtp.h"
260
#include "../rtcp.h"
261
#include "../utils.h"
262

    
263

    
264
/* Plugin information */
265
#define JANUS_RECORDPLAY_VERSION                        3
266
#define JANUS_RECORDPLAY_VERSION_STRING                "0.0.3"
267
#define JANUS_RECORDPLAY_DESCRIPTION                "This is a trivial Record&Play plugin for Janus, to record WebRTC sessions and replay them."
268
#define JANUS_RECORDPLAY_NAME                                "JANUS Record&Play plugin"
269
#define JANUS_RECORDPLAY_AUTHOR                                "Meetecho s.r.l."
270
#define JANUS_RECORDPLAY_PACKAGE                        "janus.plugin.recordplay"
271

    
272
/* Plugin methods */
273
janus_plugin *create(void);
274
int janus_recordplay_init(janus_callbacks *callback, const char *onfig_path);
275
void janus_recordplay_destroy(void);
276
int janus_recordplay_get_api_compatibility(void);
277
int janus_recordplay_get_version(void);
278
const char *janus_recordplay_get_version_string(void);
279
const char *janus_recordplay_get_description(void);
280
const char *janus_recordplay_get_name(void);
281
const char *janus_recordplay_get_author(void);
282
const char *janus_recordplay_get_package(void);
283
void janus_recordplay_create_session(janus_plugin_session *handle, int *error);
284
struct janus_plugin_result *janus_recordplay_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep);
285
void janus_recordplay_setup_media(janus_plugin_session *handle);
286
void janus_recordplay_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
287
void janus_recordplay_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
288
void janus_recordplay_incoming_data(janus_plugin_session *handle, char *buf, int len);
289
void janus_recordplay_slow_link(janus_plugin_session *handle, int uplink, int video);
290
void janus_recordplay_hangup_media(janus_plugin_session *handle);
291
void janus_recordplay_destroy_session(janus_plugin_session *handle, int *error);
292
json_t *janus_recordplay_query_session(janus_plugin_session *handle);
293

    
294
/* Plugin setup */
295
static janus_plugin janus_recordplay_plugin =
296
        JANUS_PLUGIN_INIT (
297
                .init = janus_recordplay_init,
298
                .destroy = janus_recordplay_destroy,
299

    
300
                .get_api_compatibility = janus_recordplay_get_api_compatibility,
301
                .get_version = janus_recordplay_get_version,
302
                .get_version_string = janus_recordplay_get_version_string,
303
                .get_description = janus_recordplay_get_description,
304
                .get_name = janus_recordplay_get_name,
305
                .get_author = janus_recordplay_get_author,
306
                .get_package = janus_recordplay_get_package,
307
                
308
                .create_session = janus_recordplay_create_session,
309
                .handle_message = janus_recordplay_handle_message,
310
                .setup_media = janus_recordplay_setup_media,
311
                .incoming_rtp = janus_recordplay_incoming_rtp,
312
                .incoming_rtcp = janus_recordplay_incoming_rtcp,
313
                .incoming_data = janus_recordplay_incoming_data,
314
                .slow_link = janus_recordplay_slow_link,
315
                .hangup_media = janus_recordplay_hangup_media,
316
                .destroy_session = janus_recordplay_destroy_session,
317
                .query_session = janus_recordplay_query_session,
318
        );
319

    
320
/* Plugin creator */
321
janus_plugin *create(void) {
322
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_RECORDPLAY_NAME);
323
        return &janus_recordplay_plugin;
324
}
325

    
326
/* Parameter validation */
327
static struct janus_json_parameter request_parameters[] = {
328
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
329
};
330
static struct janus_json_parameter configure_parameters[] = {
331
        {"video-bitrate-max", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE},
332
        {"video-keyframe-interval", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
333
};
334
static struct janus_json_parameter record_parameters[] = {
335
        {"name", JSON_STRING, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_NONEMPTY},
336
        {"filename", JSON_STRING, 0}
337
};
338
static struct janus_json_parameter play_parameters[] = {
339
        {"id", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
340
};
341

    
342
/* Useful stuff */
343
static volatile gint initialized = 0, stopping = 0;
344
static janus_callbacks *gateway = NULL;
345
static GThread *handler_thread;
346
static GThread *watchdog;
347
static void *janus_recordplay_handler(void *data);
348

    
349
typedef struct janus_recordplay_message {
350
        janus_plugin_session *handle;
351
        char *transaction;
352
        json_t *message;
353
        json_t *jsep;
354
} janus_recordplay_message;
355
static GAsyncQueue *messages = NULL;
356
static janus_recordplay_message exit_message;
357

    
358
typedef struct janus_recordplay_rtp_header_extension {
359
        uint16_t type;
360
        uint16_t length;
361
} janus_recordplay_rtp_header_extension;
362

    
363
typedef struct janus_recordplay_frame_packet {
364
        uint16_t seq;        /* RTP Sequence number */
365
        uint64_t ts;        /* RTP Timestamp */
366
        int len;                /* Length of the data */
367
        long offset;        /* Offset of the data in the file */
368
        struct janus_recordplay_frame_packet *next;
369
        struct janus_recordplay_frame_packet *prev;
370
} janus_recordplay_frame_packet;
371
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename);
372

    
373
typedef struct janus_recordplay_recording {
374
        guint64 id;                        /* Recording unique ID */
375
        char *name;                        /* Name of the recording */
376
        char *date;                        /* Time of the recording */
377
        char *arc_file;                /* Audio file name */
378
        char *vrc_file;                /* Video file name */
379
        gboolean completed;        /* Whether this recording was completed or still going on */
380
        GList *viewers;                /* List of users watching this recording */
381
        gint64 destroyed;        /* Lazy timestamp to mark recordings as destroyed */
382
        janus_mutex mutex;        /* Mutex for this recording */
383
} janus_recordplay_recording;
384
static GHashTable *recordings = NULL;
385
static janus_mutex recordings_mutex;
386

    
387
typedef struct janus_recordplay_session {
388
        janus_plugin_session *handle;
389
        gboolean active;
390
        gboolean recorder;                /* Whether this session is used to record or to replay a WebRTC session */
391
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
392
        janus_recordplay_recording *recording;
393
        janus_recorder *arc;        /* Audio recorder */
394
        janus_recorder *vrc;        /* Video recorder */
395
        janus_mutex rec_mutex;        /* Mutex to protect the recorders from race conditions */
396
        janus_recordplay_frame_packet *aframes;        /* Audio frames (for playout) */
397
        janus_recordplay_frame_packet *vframes;        /* Video frames (for playout) */
398
        guint video_remb_startup;
399
        guint64 video_remb_last;
400
        guint64 video_bitrate;
401
        guint video_keyframe_interval; /* keyframe request interval (ms) */
402
        guint64 video_keyframe_request_last; /* timestamp of last keyframe request sent */
403
        gint video_fir_seq;
404
        volatile gint hangingup;
405
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
406
} janus_recordplay_session;
407
static GHashTable *sessions;
408
static GList *old_sessions;
409
static janus_mutex sessions_mutex;
410

    
411

    
412
static char *recordings_path = NULL;
413
void janus_recordplay_update_recordings_list(void);
414
static void *janus_recordplay_playout_thread(void *data);
415

    
416
/* Helper to send RTCP feedback back to recorders, if needed */
417
void janus_recordplay_send_rtcp_feedback(janus_plugin_session *handle, int video, char *buf, int len);
418

    
419

    
420
/* SDP offer/answer templates for the playout */
421
#define OPUS_PT                111
422
#define VP8_PT                100
423
#define sdp_template \
424
                "v=0\r\n" \
425
                "o=- %"SCNu64" %"SCNu64" IN IP4 127.0.0.1\r\n"        /* We need current time here */ \
426
                "s=%s\r\n"                                                        /* Recording playout id */ \
427
                "t=0 0\r\n" \
428
                "%s%s"                                                                /* Audio and/or video m-lines */
429
#define sdp_a_template \
430
                "m=audio 1 RTP/SAVPF %d\r\n"                /* Opus payload type */ \
431
                "c=IN IP4 1.1.1.1\r\n" \
432
                "a=%s\r\n"                                                        /* Media direction */ \
433
                "a=rtpmap:%d opus/48000/2\r\n"                /* Opus payload type */
434
#define sdp_v_template \
435
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP8 payload type */ \
436
                "c=IN IP4 1.1.1.1\r\n" \
437
                "a=%s\r\n"                                                        /* Media direction */ \
438
                "a=rtpmap:%d VP8/90000\r\n"                        /* VP8 payload type */ \
439
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP8 payload type */ \
440
                "a=rtcp-fb:%d nack\r\n"                                /* VP8 payload type */ \
441
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP8 payload type */ \
442
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP8 payload type */
443

    
444

    
445
static void janus_recordplay_message_free(janus_recordplay_message *msg) {
446
        if(!msg || msg == &exit_message)
447
                return;
448

    
449
        msg->handle = NULL;
450

    
451
        g_free(msg->transaction);
452
        msg->transaction = NULL;
453
        if(msg->message)
454
                json_decref(msg->message);
455
        msg->message = NULL;
456
        if(msg->jsep)
457
                json_decref(msg->jsep);
458
        msg->jsep = NULL;
459

    
460
        g_free(msg);
461
}
462

    
463

    
464
/* Error codes */
465
#define JANUS_RECORDPLAY_ERROR_NO_MESSAGE                        411
466
#define JANUS_RECORDPLAY_ERROR_INVALID_JSON                412
467
#define JANUS_RECORDPLAY_ERROR_INVALID_REQUEST        413
468
#define JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT        414
469
#define JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT        415
470
#define JANUS_RECORDPLAY_ERROR_NOT_FOUND        416
471
#define JANUS_RECORDPLAY_ERROR_INVALID_RECORDING        417
472
#define JANUS_RECORDPLAY_ERROR_INVALID_STATE        418
473
#define JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR        499
474

    
475

    
476
/* Record&Play watchdog/garbage collector (sort of) */
477
void *janus_recordplay_watchdog(void *data);
478
void *janus_recordplay_watchdog(void *data) {
479
        JANUS_LOG(LOG_INFO, "Record&Play watchdog started\n");
480
        gint64 now = 0;
481
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
482
                janus_mutex_lock(&sessions_mutex);
483
                /* Iterate on all the sessions */
484
                now = janus_get_monotonic_time();
485
                if(old_sessions != NULL) {
486
                        GList *sl = old_sessions;
487
                        JANUS_LOG(LOG_HUGE, "Checking %d old Record&Play sessions...\n", g_list_length(old_sessions));
488
                        while(sl) {
489
                                janus_recordplay_session *session = (janus_recordplay_session *)sl->data;
490
                                if(!session) {
491
                                        sl = sl->next;
492
                                        continue;
493
                                }
494
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
495
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
496
                                        JANUS_LOG(LOG_VERB, "Freeing old Record&Play session\n");
497
                                        GList *rm = sl->next;
498
                                        old_sessions = g_list_delete_link(old_sessions, sl);
499
                                        sl = rm;
500
                                        session->handle = NULL;
501
                                        g_free(session);
502
                                        session = NULL;
503
                                        continue;
504
                                }
505
                                sl = sl->next;
506
                        }
507
                }
508
                janus_mutex_unlock(&sessions_mutex);
509
                g_usleep(500000);
510
        }
511
        JANUS_LOG(LOG_INFO, "Record&Play watchdog stopped\n");
512
        return NULL;
513
}
514

    
515

    
516
/* Plugin implementation */
517
int janus_recordplay_init(janus_callbacks *callback, const char *config_path) {
518
        if(g_atomic_int_get(&stopping)) {
519
                /* Still stopping from before */
520
                return -1;
521
        }
522
        if(callback == NULL || config_path == NULL) {
523
                /* Invalid arguments */
524
                return -1;
525
        }
526

    
527
        /* Read configuration */
528
        char filename[255];
529
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_RECORDPLAY_PACKAGE);
530
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
531
        janus_config *config = janus_config_parse(filename);
532
        if(config != NULL)
533
                janus_config_print(config);
534
        /* Parse configuration */
535
        if(config != NULL) {
536
                janus_config_item *path = janus_config_get_item_drilldown(config, "general", "path");
537
                if(path && path->value)
538
                        recordings_path = g_strdup(path->value);
539
                /* Done */
540
                janus_config_destroy(config);
541
                config = NULL;
542
        }
543
        if(recordings_path == NULL) {
544
                recordings_path = g_strdup("/tmp");
545
                JANUS_LOG(LOG_WARN, "No recordings path specified, using /tmp...\n");
546
        }
547
        /* Create the folder, if needed */
548
        struct stat st = {0};
549
        if(stat(recordings_path, &st) == -1) {
550
                int res = janus_mkdir(recordings_path, 0755);
551
                JANUS_LOG(LOG_VERB, "Creating folder: %d\n", res);
552
                if(res != 0) {
553
                        JANUS_LOG(LOG_ERR, "%s", strerror(res));
554
                        return -1;        /* No point going on... */
555
                }
556
        }
557
        recordings = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
558
        janus_mutex_init(&recordings_mutex);
559
        janus_recordplay_update_recordings_list();
560
        
561
        sessions = g_hash_table_new(NULL, NULL);
562
        janus_mutex_init(&sessions_mutex);
563
        messages = g_async_queue_new_full((GDestroyNotify) janus_recordplay_message_free);
564
        /* This is the callback we'll need to invoke to contact the gateway */
565
        gateway = callback;
566

    
567
        g_atomic_int_set(&initialized, 1);
568

    
569
        GError *error = NULL;
570
        /* Start the sessions watchdog */
571
        watchdog = g_thread_try_new("recordplay watchdog", &janus_recordplay_watchdog, NULL, &error);
572
        if(error != NULL) {
573
                g_atomic_int_set(&initialized, 0);
574
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play watchdog thread...\n", error->code, error->message ? error->message : "??");
575
                return -1;
576
        }
577
        /* Launch the thread that will handle incoming messages */
578
        handler_thread = g_thread_try_new("recordplay handler", janus_recordplay_handler, NULL, &error);
579
        if(error != NULL) {
580
                g_atomic_int_set(&initialized, 0);
581
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play handler thread...\n", error->code, error->message ? error->message : "??");
582
                return -1;
583
        }
584
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_RECORDPLAY_NAME);
585
        return 0;
586
}
587

    
588
void janus_recordplay_destroy(void) {
589
        if(!g_atomic_int_get(&initialized))
590
                return;
591
        g_atomic_int_set(&stopping, 1);
592

    
593
        g_async_queue_push(messages, &exit_message);
594
        if(handler_thread != NULL) {
595
                g_thread_join(handler_thread);
596
                handler_thread = NULL;
597
        }
598
        if(watchdog != NULL) {
599
                g_thread_join(watchdog);
600
                watchdog = NULL;
601
        }
602
        /* FIXME We should destroy the sessions cleanly */
603
        janus_mutex_lock(&sessions_mutex);
604
        g_hash_table_destroy(sessions);
605
        janus_mutex_unlock(&sessions_mutex);
606
        g_async_queue_unref(messages);
607
        messages = NULL;
608
        sessions = NULL;
609
        g_atomic_int_set(&initialized, 0);
610
        g_atomic_int_set(&stopping, 0);
611
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_RECORDPLAY_NAME);
612
}
613

    
614
int janus_recordplay_get_api_compatibility(void) {
615
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
616
        return JANUS_PLUGIN_API_VERSION;
617
}
618

    
619
int janus_recordplay_get_version(void) {
620
        return JANUS_RECORDPLAY_VERSION;
621
}
622

    
623
const char *janus_recordplay_get_version_string(void) {
624
        return JANUS_RECORDPLAY_VERSION_STRING;
625
}
626

    
627
const char *janus_recordplay_get_description(void) {
628
        return JANUS_RECORDPLAY_DESCRIPTION;
629
}
630

    
631
const char *janus_recordplay_get_name(void) {
632
        return JANUS_RECORDPLAY_NAME;
633
}
634

    
635
const char *janus_recordplay_get_author(void) {
636
        return JANUS_RECORDPLAY_AUTHOR;
637
}
638

    
639
const char *janus_recordplay_get_package(void) {
640
        return JANUS_RECORDPLAY_PACKAGE;
641
}
642

    
643
void janus_recordplay_create_session(janus_plugin_session *handle, int *error) {
644
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
645
                *error = -1;
646
                return;
647
        }        
648
        janus_recordplay_session *session = (janus_recordplay_session *)g_malloc0(sizeof(janus_recordplay_session));
649
        session->handle = handle;
650
        session->active = FALSE;
651
        session->recorder = FALSE;
652
        session->firefox = FALSE;
653
        session->arc = NULL;
654
        session->vrc = NULL;
655
        janus_mutex_init(&session->rec_mutex);
656
        session->destroyed = 0;
657
        g_atomic_int_set(&session->hangingup, 0);
658
        session->video_remb_startup = 4;
659
        session->video_remb_last = janus_get_monotonic_time();
660
        session->video_bitrate = 1024 * 1024;                 /* This is 1mbps by default */
661
        session->video_keyframe_request_last = 0;
662
        session->video_keyframe_interval = 15000;         /* 15 seconds by default */
663
        session->video_fir_seq = 0;
664
        handle->plugin_handle = session;
665
        janus_mutex_lock(&sessions_mutex);
666
        g_hash_table_insert(sessions, handle, session);
667
        janus_mutex_unlock(&sessions_mutex);
668

    
669
        return;
670
}
671

    
672
void janus_recordplay_destroy_session(janus_plugin_session *handle, int *error) {
673
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
674
                *error = -1;
675
                return;
676
        }        
677
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
678
        if(!session) {
679
                JANUS_LOG(LOG_ERR, "No Record&Play session associated with this handle...\n");
680
                *error = -2;
681
                return;
682
        }
683
        janus_mutex_lock(&sessions_mutex);
684
        if(!session->destroyed) {
685
                JANUS_LOG(LOG_VERB, "Removing Record&Play session...\n");
686
                janus_recordplay_hangup_media(handle);
687
                session->destroyed = janus_get_monotonic_time();
688
                g_hash_table_remove(sessions, handle);
689
                /* Cleaning up and removing the session is done in a lazy way */
690
                old_sessions = g_list_append(old_sessions, session);
691
        }
692
        janus_mutex_unlock(&sessions_mutex);
693
        return;
694
}
695

    
696
json_t *janus_recordplay_query_session(janus_plugin_session *handle) {
697
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
698
                return NULL;
699
        }        
700
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
701
        if(!session) {
702
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
703
                return NULL;
704
        }
705
        /* In the echo test, every session is the same: we just provide some configure info */
706
        json_t *info = json_object();
707
        json_object_set_new(info, "type", json_string(session->recorder ? "recorder" : (session->recording ? "player" : "none")));
708
        if(session->recording) {
709
                json_object_set_new(info, "recording_id", json_integer(session->recording->id));
710
                json_object_set_new(info, "recording_name", json_string(session->recording->name));
711
        }
712
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
713
        return info;
714
}
715

    
716
struct janus_plugin_result *janus_recordplay_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
717
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
718
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
719

    
720
        /* Pre-parse the message */
721
        int error_code = 0;
722
        char error_cause[512];
723
        json_t *root = message;
724
        json_t *response = NULL;
725
        
726
        if(message == NULL) {
727
                JANUS_LOG(LOG_ERR, "No message??\n");
728
                error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
729
                g_snprintf(error_cause, 512, "%s", "No message??");
730
                goto plugin_response;
731
        }
732

    
733
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
734
        if(!session) {
735
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
736
                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
737
                g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
738
                goto plugin_response;
739
        }
740
        if(session->destroyed) {
741
                JANUS_LOG(LOG_ERR, "Session has already been destroyed...\n");
742
                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
743
                g_snprintf(error_cause, 512, "%s", "Session has already been destroyed...");
744
                goto plugin_response;
745
        }
746
        if(!json_is_object(root)) {
747
                JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
748
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_JSON;
749
                g_snprintf(error_cause, 512, "JSON error: not an object");
750
                goto plugin_response;
751
        }
752
        /* Get the request first */
753
        JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
754
                error_code, error_cause, TRUE,
755
                JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT, JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT);
756
        if(error_code != 0)
757
                goto plugin_response;
758
        json_t *request = json_object_get(root, "request");
759
        /* Some requests ('create' and 'destroy') can be handled synchronously */
760
        const char *request_text = json_string_value(request);
761
        if(!strcasecmp(request_text, "update")) {
762
                /* Update list of available recordings, scanning the folder again */
763
                janus_recordplay_update_recordings_list();
764
                /* Send info back */
765
                response = json_object();
766
                json_object_set_new(response, "recordplay", json_string("ok"));
767
                goto plugin_response;
768
        } else if(!strcasecmp(request_text, "list")) {
769
                json_t *list = json_array();
770
                JANUS_LOG(LOG_VERB, "Request for the list of recordings\n");
771
                /* Return a list of all available recordings */
772
                janus_mutex_lock(&recordings_mutex);
773
                GHashTableIter iter;
774
                gpointer value;
775
                g_hash_table_iter_init(&iter, recordings);
776
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
777
                        janus_recordplay_recording *rec = value;
778
                        if(!rec->completed)        /* Ongoing recording, skip */
779
                                continue;
780
                        json_t *ml = json_object();
781
                        json_object_set_new(ml, "id", json_integer(rec->id));
782
                        json_object_set_new(ml, "name", json_string(rec->name));
783
                        json_object_set_new(ml, "date", json_string(rec->date));
784
                        json_object_set_new(ml, "audio", rec->arc_file ? json_true() : json_false());
785
                        json_object_set_new(ml, "video", rec->vrc_file ? json_true() : json_false());
786
                        json_array_append_new(list, ml);
787
                }
788
                janus_mutex_unlock(&recordings_mutex);
789
                /* Send info back */
790
                response = json_object();
791
                json_object_set_new(response, "recordplay", json_string("list"));
792
                json_object_set_new(response, "list", list);
793
                goto plugin_response;
794
        } else if(!strcasecmp(request_text, "configure")) {
795
                JANUS_VALIDATE_JSON_OBJECT(root, configure_parameters,
796
                        error_code, error_cause, TRUE,
797
                        JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT, JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT);
798
                if(error_code != 0)
799
                        goto plugin_response;
800
                json_t *video_bitrate_max = json_object_get(root, "video-bitrate-max");
801
                if(video_bitrate_max) {
802
                        session->video_bitrate = json_integer_value(video_bitrate_max);
803
                        JANUS_LOG(LOG_VERB, "Video bitrate has been set to %"SCNu64"\n", session->video_bitrate);
804
                }
805
                json_t *video_keyframe_interval= json_object_get(root, "video-keyframe-interval");
806
                if(video_keyframe_interval) {
807
                        session->video_keyframe_interval = json_integer_value(video_keyframe_interval);
808
                        JANUS_LOG(LOG_VERB, "Video keyframe interval has been set to %u\n", session->video_keyframe_interval);
809
                }
810
                response = json_object();
811
                json_object_set_new(response, "recordplay", json_string("configure"));
812
                json_object_set_new(response, "status", json_string("ok"));
813
                /* Return a success, and also let the client be aware of what changed, to allow crosschecks */
814
                json_t *settings = json_object();
815
                json_object_set_new(settings, "video-keyframe-interval", json_integer(session->video_keyframe_interval)); 
816
                json_object_set_new(settings, "video-bitrate-max", json_integer(session->video_bitrate)); 
817
                json_object_set_new(response, "settings", settings); 
818
                goto plugin_response;
819
        } else if(!strcasecmp(request_text, "record") || !strcasecmp(request_text, "play")
820
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "stop")) {
821
                /* These messages are handled asynchronously */
822
                janus_recordplay_message *msg = g_malloc0(sizeof(janus_recordplay_message));
823
                msg->handle = handle;
824
                msg->transaction = transaction;
825
                msg->message = root;
826
                msg->jsep = jsep;
827

    
828
                g_async_queue_push(messages, msg);
829

    
830
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
831
        } else {
832
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
833
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
834
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
835
        }
836

    
837
plugin_response:
838
                {
839
                        if(error_code == 0 && !response) {
840
                                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
841
                                g_snprintf(error_cause, 512, "Invalid response");
842
                        }
843
                        if(error_code != 0) {
844
                                /* Prepare JSON error event */
845
                                json_t *event = json_object();
846
                                json_object_set_new(event, "recordplay", json_string("event"));
847
                                json_object_set_new(event, "error_code", json_integer(error_code));
848
                                json_object_set_new(event, "error", json_string(error_cause));
849
                                response = event;
850
                        }
851
                        if(root != NULL)
852
                                json_decref(root);
853
                        if(jsep != NULL)
854
                                json_decref(jsep);
855
                        g_free(transaction);
856

    
857
                        return janus_plugin_result_new(JANUS_PLUGIN_OK, NULL, response);
858
                }
859

    
860
}
861

    
862
void janus_recordplay_setup_media(janus_plugin_session *handle) {
863
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
864
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
865
                return;
866
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
867
        if(!session) {
868
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
869
                return;
870
        }
871
        if(session->destroyed)
872
                return;
873
        g_atomic_int_set(&session->hangingup, 0);
874
        /* Take note of the fact that the session is now active */
875
        session->active = TRUE;
876
        if(!session->recorder) {
877
                GError *error = NULL;
878
                g_thread_try_new("recordplay playout thread", &janus_recordplay_playout_thread, session, &error);
879
                if(error != NULL) {
880
                        /* FIXME Should we notify this back to the user somehow? */
881
                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play playout thread...\n", error->code, error->message ? error->message : "??");
882
                }
883
        }
884
}
885

    
886
void janus_recordplay_send_rtcp_feedback(janus_plugin_session *handle, int video, char *buf, int len) {
887
        if(video != 1)
888
                return;        /* We just do this for video, for now */
889

    
890
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
891
        char rtcpbuf[24];
892

    
893
        /* Send a RR+SDES+REMB every five seconds, or ASAP while we are still
894
         * ramping up (first 4 RTP packets) */
895
        gint64 now = janus_get_monotonic_time();
896
        guint64 elapsed = now - session->video_remb_last;
897
        gboolean remb_rampup = session->video_remb_startup > 0;
898

    
899
        if(remb_rampup || (elapsed >= 5*G_USEC_PER_SEC)) {
900
                guint64 bitrate = session->video_bitrate;
901

    
902
                if(remb_rampup) {
903
                        bitrate = bitrate / session->video_remb_startup;
904
                        session->video_remb_startup--;
905
                }
906

    
907
                /* Send a new REMB back */
908
                char rtcpbuf[24];
909
                janus_rtcp_remb((char *)(&rtcpbuf), 24, bitrate);
910
                gateway->relay_rtcp(handle, video, rtcpbuf, 24);
911

    
912
                session->video_remb_last = now;
913
        }
914

    
915
        /* Request a keyframe on a regular basis (every session->video_keyframe_interval ms) */
916
        elapsed = now - session->video_keyframe_request_last;
917
        guint64 interval = (session->video_keyframe_interval / 1000) * G_USEC_PER_SEC;
918

    
919
        if(elapsed >= interval) {
920
                /* Send both a FIR and a PLI, just to be sure */
921
                memset(rtcpbuf, 0, 20);
922
                janus_rtcp_fir((char *)&rtcpbuf, 20, &session->video_fir_seq);
923
                gateway->relay_rtcp(handle, video, rtcpbuf, 20);
924
                memset(rtcpbuf, 0, 12);
925
                janus_rtcp_pli((char *)&rtcpbuf, 12);
926
                gateway->relay_rtcp(handle, video, rtcpbuf, 12);
927
                session->video_keyframe_request_last = now;
928
        }
929
}
930

    
931
void janus_recordplay_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
932
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
933
                return;
934
        if(gateway) {
935
                janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
936
                if(!session) {
937
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
938
                        return;
939
                }
940
                if(session->destroyed)
941
                        return;
942
                /* Are we recording? */
943
                if(session->recorder) {
944
                        janus_recorder_save_frame(video ? session->vrc : session->arc, buf, len);
945
                }
946

    
947
                janus_recordplay_send_rtcp_feedback(handle, video, buf, len);
948
        }
949
}
950

    
951
void janus_recordplay_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
952
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
953
                return;
954
}
955

    
956
void janus_recordplay_incoming_data(janus_plugin_session *handle, char *buf, int len) {
957
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
958
                return;
959
        /* FIXME We don't care */
960
}
961

    
962
void janus_recordplay_slow_link(janus_plugin_session *handle, int uplink, int video) {
963
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
964
                return;
965

    
966
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
967
        if(!session || session->destroyed)
968
                return;
969

    
970
        json_t *event = json_object();
971
        json_object_set_new(event, "recordplay", json_string("event"));
972
        json_t *result = json_object();
973
        json_object_set_new(result, "status", json_string("slow_link"));
974
        /* What is uplink for the server is downlink for the client, so turn the tables */
975
        json_object_set_new(result, "current-bitrate", json_integer(session->video_bitrate));
976
        json_object_set_new(result, "uplink", json_integer(uplink ? 0 : 1));
977
        json_object_set_new(event, "result", result);
978
        gateway->push_event(session->handle, &janus_recordplay_plugin, NULL, event, NULL);
979
        json_decref(event);
980
}
981

    
982
void janus_recordplay_hangup_media(janus_plugin_session *handle) {
983
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
984
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
985
                return;
986
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
987
        if(!session) {
988
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
989
                return;
990
        }
991
        session->active = FALSE;
992
        if(session->destroyed || !session->recorder)
993
                return;
994
        if(g_atomic_int_add(&session->hangingup, 1))
995
                return;
996

    
997
        /* Send an event to the browser and tell it's over */
998
        json_t *event = json_object();
999
        json_object_set_new(event, "recordplay", json_string("event"));
1000
        json_object_set_new(event, "result", json_string("done"));
1001
        int ret = gateway->push_event(handle, &janus_recordplay_plugin, NULL, event, NULL);
1002
        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
1003
        json_decref(event);
1004

    
1005
        /* FIXME Simulate a "stop" coming from the browser */
1006
        janus_recordplay_message *msg = g_malloc0(sizeof(janus_recordplay_message));
1007
        msg->handle = handle;
1008
        msg->message = json_pack("{ss}", "request", "stop");
1009
        msg->transaction = NULL;
1010
        msg->jsep = NULL;
1011
        g_async_queue_push(messages, msg);
1012
}
1013

    
1014
/* Thread to handle incoming messages */
1015
static void *janus_recordplay_handler(void *data) {
1016
        JANUS_LOG(LOG_VERB, "Joining Record&Play handler thread\n");
1017
        janus_recordplay_message *msg = NULL;
1018
        int error_code = 0;
1019
        char error_cause[512];
1020
        json_t *root = NULL;
1021
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1022
                msg = g_async_queue_pop(messages);
1023
                if(msg == NULL)
1024
                        continue;
1025
                if(msg == &exit_message)
1026
                        break;
1027
                if(msg->handle == NULL) {
1028
                        janus_recordplay_message_free(msg);
1029
                        continue;
1030
                }
1031
                janus_recordplay_session *session = NULL;
1032
                janus_mutex_lock(&sessions_mutex);
1033
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1034
                        session = (janus_recordplay_session *)msg->handle->plugin_handle;
1035
                }
1036
                janus_mutex_unlock(&sessions_mutex);
1037
                if(!session) {
1038
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1039
                        janus_recordplay_message_free(msg);
1040
                        continue;
1041
                }
1042
                if(session->destroyed) {
1043
                        janus_recordplay_message_free(msg);
1044
                        continue;
1045
                }
1046
                /* Handle request */
1047
                error_code = 0;
1048
                root = NULL;
1049
                if(msg->message == NULL) {
1050
                        JANUS_LOG(LOG_ERR, "No message??\n");
1051
                        error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
1052
                        g_snprintf(error_cause, 512, "%s", "No message??");
1053
                        goto error;
1054
                }
1055
                root = msg->message;
1056
                /* Get the request first */
1057
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1058
                        error_code, error_cause, TRUE,
1059
                        JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT, JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT);
1060
                if(error_code != 0)
1061
                        goto error;
1062
                const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1063
                const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1064
                json_t *request = json_object_get(root, "request");
1065
                const char *request_text = json_string_value(request);
1066
                json_t *event = NULL;
1067
                json_t *result = NULL;
1068
                char *sdp = NULL;
1069
                const char *filename_text = NULL;
1070
                if(!strcasecmp(request_text, "record")) {
1071
                        if(!msg_sdp) {
1072
                                JANUS_LOG(LOG_ERR, "Missing SDP offer\n");
1073
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1074
                                g_snprintf(error_cause, 512, "Missing SDP offer");
1075
                                goto error;
1076
                        }
1077
                        JANUS_VALIDATE_JSON_OBJECT(root, record_parameters,
1078
                                error_code, error_cause, TRUE,
1079
                                JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT, JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT);
1080
                        if(error_code != 0)
1081
                                goto error;
1082
                        json_t *name = json_object_get(root, "name");
1083
                        const char *name_text = json_string_value(name);
1084
                        json_t *filename = json_object_get(root, "filename");
1085
                        if(filename) {
1086
                                filename_text = json_string_value(filename);
1087
                        }
1088
                        guint64 id = 0;
1089
                        while(id == 0) {
1090
                                id = janus_random_uint64();
1091
                                if(g_hash_table_lookup(recordings, &id) != NULL) {
1092
                                        /* Room ID already taken, try another one */
1093
                                        id = 0;
1094
                                }
1095
                        }
1096
                        JANUS_LOG(LOG_VERB, "Starting new recording with ID %"SCNu64"\n", id);
1097
                        janus_recordplay_recording *rec = (janus_recordplay_recording *)g_malloc0(sizeof(janus_recordplay_recording));
1098
                        rec->id = id;
1099
                        rec->name = g_strdup(name_text);
1100
                        rec->viewers = NULL;
1101
                        rec->destroyed = 0;
1102
                        rec->completed = FALSE;
1103
                        janus_mutex_init(&rec->mutex);
1104
                        /* Create a date string */
1105
                        time_t t = time(NULL);
1106
                        struct tm *tmv = localtime(&t);
1107
                        char outstr[200];
1108
                        strftime(outstr, sizeof(outstr), "%Y-%m-%d %H:%M:%S", tmv);
1109
                        rec->date = g_strdup(outstr);
1110
                        if(strstr(msg_sdp, "m=audio")) {
1111
                                char filename[256];
1112
                                if(filename_text != NULL) {
1113
                                        g_snprintf(filename, 256, "%s-audio", filename_text);
1114
                                } else {
1115
                                        g_snprintf(filename, 256, "rec-%"SCNu64"-audio", id);
1116
                                }
1117
                                rec->arc_file = g_strdup(filename);
1118
                                /* FIXME Assuming Opus */
1119
                                session->arc = janus_recorder_create(recordings_path, "opus", rec->arc_file);
1120
                        }
1121
                        if(strstr(msg_sdp, "m=video")) {
1122
                                char filename[256];
1123
                                if(filename_text != NULL) {
1124
                                        g_snprintf(filename, 256, "%s-video", filename_text);
1125
                                } else {
1126
                                        g_snprintf(filename, 256, "rec-%"SCNu64"-video", id);
1127
                                }
1128
                                rec->vrc_file = g_strdup(filename);
1129
                                /* FIXME Assuming VP8 */
1130
                                session->vrc = janus_recorder_create(recordings_path, "vp8", rec->vrc_file);
1131
                        }
1132
                        session->recorder = TRUE;
1133
                        session->recording = rec;
1134
                        janus_mutex_lock(&recordings_mutex);
1135
                        g_hash_table_insert(recordings, janus_uint64_dup(rec->id), rec);
1136
                        janus_mutex_unlock(&recordings_mutex);
1137
                        /* We need to prepare an answer */
1138
                        int opus_pt = 0, vp8_pt = 0;
1139
                        opus_pt = janus_get_codec_pt(msg_sdp, "opus");
1140
                        JANUS_LOG(LOG_VERB, "Opus payload type is %d\n", opus_pt);
1141
                        vp8_pt = janus_get_codec_pt(msg_sdp, "vp8");
1142
                        JANUS_LOG(LOG_VERB, "VP8 payload type is %d\n", vp8_pt);
1143
                        char sdptemp[1024], audio_mline[256], video_mline[512];
1144
                        if(opus_pt > 0) {
1145
                                g_snprintf(audio_mline, 256, sdp_a_template,
1146
                                        opus_pt,                                                /* Opus payload type */
1147
                                        "recvonly",                                                /* Recording is recvonly */
1148
                                        opus_pt);                                                 /* Opus payload type */
1149
                        } else {
1150
                                audio_mline[0] = '\0';
1151
                        }
1152
                        if(vp8_pt > 0) {
1153
                                g_snprintf(video_mline, 512, sdp_v_template,
1154
                                        vp8_pt,                                                        /* VP8 payload type */
1155
                                        "recvonly",                                                /* Recording is recvonly */
1156
                                        vp8_pt,                                                 /* VP8 payload type */
1157
                                        vp8_pt,                                                 /* VP8 payload type */
1158
                                        vp8_pt,                                                 /* VP8 payload type */
1159
                                        vp8_pt,                                                 /* VP8 payload type */
1160
                                        vp8_pt);                                                 /* VP8 payload type */
1161
                        } else {
1162
                                video_mline[0] = '\0';
1163
                        }
1164
                        g_snprintf(sdptemp, 1024, sdp_template,
1165
                                janus_get_real_time(),                        /* We need current time here */
1166
                                janus_get_real_time(),                        /* We need current time here */
1167
                                session->recording->name,                /* Playout session */
1168
                                audio_mline,                                        /* Audio m-line, if any */
1169
                                video_mline);                                        /* Video m-line, if any */
1170
                        sdp = g_strdup(sdptemp);
1171
                        JANUS_LOG(LOG_VERB, "Going to answer this SDP:\n%s\n", sdp);
1172
                        /* Done! */
1173
                        result = json_object();
1174
                        json_object_set_new(result, "status", json_string("recording"));
1175
                        json_object_set_new(result, "id", json_integer(id));
1176
                } else if(!strcasecmp(request_text, "play")) {
1177
                        if(msg_sdp) {
1178
                                JANUS_LOG(LOG_ERR, "A play request can't contain an SDP\n");
1179
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1180
                                g_snprintf(error_cause, 512, "A play request can't contain an SDP");
1181
                                goto error;
1182
                        }
1183
                        JANUS_LOG(LOG_VERB, "Replaying a recording\n");
1184
                        JANUS_VALIDATE_JSON_OBJECT(root, play_parameters,
1185
                                error_code, error_cause, TRUE,
1186
                                JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT, JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT);
1187
                        if(error_code != 0)
1188
                                goto error;
1189
                        json_t *id = json_object_get(root, "id");
1190
                        guint64 id_value = json_integer_value(id);
1191
                        /* Look for this recording */
1192
                        janus_mutex_lock(&recordings_mutex);
1193
                        janus_recordplay_recording *rec = g_hash_table_lookup(recordings, &id_value);
1194
                        janus_mutex_unlock(&recordings_mutex);
1195
                        if(rec == NULL || rec->destroyed) {
1196
                                JANUS_LOG(LOG_ERR, "No such recording\n");
1197
                                error_code = JANUS_RECORDPLAY_ERROR_NOT_FOUND;
1198
                                g_snprintf(error_cause, 512, "No such recording");
1199
                                goto error;
1200
                        }
1201
                        /* Access the frames */
1202
                        const char *warning = NULL;
1203
                        if(rec->arc_file) {
1204
                                session->aframes = janus_recordplay_get_frames(recordings_path, rec->arc_file);
1205
                                if(session->aframes == NULL) {
1206
                                        JANUS_LOG(LOG_WARN, "Error opening audio recording, trying to go on anyway\n");
1207
                                        warning = "Broken audio file, playing video only";
1208
                                }
1209
                        }
1210
                        if(rec->vrc_file) {
1211
                                session->vframes = janus_recordplay_get_frames(recordings_path, rec->vrc_file);
1212
                                if(session->vframes == NULL) {
1213
                                        JANUS_LOG(LOG_WARN, "Error opening video recording, trying to go on anyway\n");
1214
                                        warning = "Broken video file, playing audio only";
1215
                                }
1216
                        }
1217
                        if(session->aframes == NULL && session->vframes == NULL) {
1218
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_RECORDING;
1219
                                g_snprintf(error_cause, 512, "Error opening recording files");
1220
                                goto error;
1221
                        }
1222
                        session->recording = rec;
1223
                        session->recorder = FALSE;
1224
                        rec->viewers = g_list_append(rec->viewers, session);
1225
                        /* We need to prepare an offer */
1226
                        char sdptemp[1024], audio_mline[256], video_mline[512];
1227
                        if(session->aframes) {
1228
                                g_snprintf(audio_mline, 256, sdp_a_template,
1229
                                        OPUS_PT,                                                /* Opus payload type */
1230
                                        "sendonly",                                                /* Playout is sendonly */
1231
                                        OPUS_PT);                                                 /* Opus payload type */
1232
                        } else {
1233
                                audio_mline[0] = '\0';
1234
                        }
1235
                        if(session->vframes) {
1236
                                g_snprintf(video_mline, 512, sdp_v_template,
1237
                                        VP8_PT,                                                        /* VP8 payload type */
1238
                                        "sendonly",                                                /* Playout is sendonly */
1239
                                        VP8_PT,                                                 /* VP8 payload type */
1240
                                        VP8_PT,                                                 /* VP8 payload type */
1241
                                        VP8_PT,                                                 /* VP8 payload type */
1242
                                        VP8_PT,                                                 /* VP8 payload type */
1243
                                        VP8_PT);                                                 /* VP8 payload type */
1244
                        } else {
1245
                                video_mline[0] = '\0';
1246
                        }
1247
                        g_snprintf(sdptemp, 1024, sdp_template,
1248
                                janus_get_real_time(),                        /* We need current time here */
1249
                                janus_get_real_time(),                        /* We need current time here */
1250
                                session->recording->name,                /* Playout session */
1251
                                audio_mline,                                        /* Audio m-line, if any */
1252
                                video_mline);                                        /* Video m-line, if any */
1253
                        sdp = g_strdup(sdptemp);
1254
                        JANUS_LOG(LOG_VERB, "Going to offer this SDP:\n%s\n", sdp);
1255
                        /* Done! */
1256
                        result = json_object();
1257
                        json_object_set_new(result, "status", json_string("preparing"));
1258
                        json_object_set_new(result, "id", json_integer(id_value));
1259
                        if(warning)
1260
                                json_object_set_new(result, "warning", json_string(warning));
1261
                } else if(!strcasecmp(request_text, "start")) {
1262
                        if(!session->aframes && !session->vframes) {
1263
                                JANUS_LOG(LOG_ERR, "Not a playout session, can't start\n");
1264
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_STATE;
1265
                                g_snprintf(error_cause, 512, "Not a playout session, can't start");
1266
                                goto error;
1267
                        }
1268
                        /* Just a final message we make use of, e.g., to receive an ANSWER to our OFFER for a playout */
1269
                        if(!msg_sdp) {
1270
                                JANUS_LOG(LOG_ERR, "Missing SDP answer\n");
1271
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1272
                                g_snprintf(error_cause, 512, "Missing SDP answer");
1273
                                goto error;
1274
                        }
1275
                        /* Done! */
1276
                        result = json_object();
1277
                        json_object_set_new(result, "status", json_string("playing"));
1278
                } else if(!strcasecmp(request_text, "stop")) {
1279
                        /* Stop the recording/playout */
1280
                        session->active = FALSE;
1281
                        janus_mutex_lock(&session->rec_mutex);
1282
                        if(session->arc) {
1283
                                janus_recorder_close(session->arc);
1284
                                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1285
                                janus_recorder_free(session->arc);
1286
                        }
1287
                        session->arc = NULL;
1288
                        if(session->vrc) {
1289
                                janus_recorder_close(session->vrc);
1290
                                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1291
                                janus_recorder_free(session->vrc);
1292
                        }
1293
                        session->vrc = NULL;
1294
                        janus_mutex_unlock(&session->rec_mutex);
1295
                        if(session->recorder) {
1296
                                /* Create a .nfo file for this recording */
1297
                                char nfofile[1024], nfo[1024];
1298
                                g_snprintf(nfofile, 1024, "%s/%"SCNu64".nfo", recordings_path, session->recording->id);
1299
                                FILE *file = fopen(nfofile, "wt");
1300
                                if(file == NULL) {
1301
                                        JANUS_LOG(LOG_ERR, "Error creating file %s...\n", nfofile);
1302
                                } else {
1303
                                        if(session->recording->arc_file && session->recording->vrc_file) {
1304
                                                g_snprintf(nfo, 1024,
1305
                                                        "[%"SCNu64"]\r\n"
1306
                                                        "name = %s\r\n"
1307
                                                        "date = %s\r\n"
1308
                                                        "audio = %s.mjr\r\n"
1309
                                                        "video = %s.mjr\r\n",
1310
                                                                session->recording->id, session->recording->name, session->recording->date,
1311
                                                                session->recording->arc_file, session->recording->vrc_file);
1312
                                        } else if(session->recording->arc_file) {
1313
                                                g_snprintf(nfo, 1024,
1314
                                                        "[%"SCNu64"]\r\n"
1315
                                                        "name = %s\r\n"
1316
                                                        "date = %s\r\n"
1317
                                                        "audio = %s.mjr\r\n",
1318
                                                                session->recording->id, session->recording->name, session->recording->date,
1319
                                                                session->recording->arc_file);
1320
                                        } else if(session->recording->vrc_file) {
1321
                                                g_snprintf(nfo, 1024,
1322
                                                        "[%"SCNu64"]\r\n"
1323
                                                        "name = %s\r\n"
1324
                                                        "date = %s\r\n"
1325
                                                        "video = %s.mjr\r\n",
1326
                                                                session->recording->id, session->recording->name, session->recording->date,
1327
                                                                session->recording->vrc_file);
1328
                                        }
1329
                                        /* Write to the file now */
1330
                                        fwrite(nfo, strlen(nfo), sizeof(char), file);
1331
                                        fclose(file);
1332
                                        session->recording->completed = TRUE;
1333
                                }
1334
                        }
1335
                        /* Done! */
1336
                        result = json_object();
1337
                        json_object_set_new(result, "status", json_string("stopped"));
1338
                        if(session->recording)
1339
                                json_object_set_new(result, "id", json_integer(session->recording->id));
1340
                } else {
1341
                        JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
1342
                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
1343
                        g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
1344
                        goto error;
1345
                }
1346

    
1347
                /* Any SDP to handle? */
1348
                if(msg_sdp) {
1349
                        session->firefox = strstr(msg_sdp, "Mozilla") ? TRUE : FALSE;
1350
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
1351
                }
1352

    
1353
                /* Prepare JSON event */
1354
                event = json_object();
1355
                json_object_set_new(event, "recordplay", json_string("event"));
1356
                if(result != NULL)
1357
                        json_object_set_new(event, "result", result);
1358
                if(!sdp) {
1359
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event, NULL);
1360
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
1361
                        json_decref(event);
1362
                } else {
1363
                        const char *type = session->recorder ? "answer" : "offer";
1364
                        json_t *jsep = json_pack("{ssss}", "type", type, "sdp", sdp);
1365
                        /* How long will the gateway take to push the event? */
1366
                        g_atomic_int_set(&session->hangingup, 0);
1367
                        gint64 start = janus_get_monotonic_time();
1368
                        int res = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event, jsep);
1369
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
1370
                                res, janus_get_monotonic_time()-start);
1371
                        g_free(sdp);
1372
                        json_decref(event);
1373
                        json_decref(jsep);
1374
                }
1375
                janus_recordplay_message_free(msg);
1376
                continue;
1377
                
1378
error:
1379
                {
1380
                        /* Prepare JSON error event */
1381
                        json_t *event = json_object();
1382
                        json_object_set_new(event, "recordplay", json_string("event"));
1383
                        json_object_set_new(event, "error_code", json_integer(error_code));
1384
                        json_object_set_new(event, "error", json_string(error_cause));
1385
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event, NULL);
1386
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
1387
                        json_decref(event);
1388
                        janus_recordplay_message_free(msg);
1389
                }
1390
        }
1391
        JANUS_LOG(LOG_VERB, "LeavingRecord&Play handler thread\n");
1392
        return NULL;
1393
}
1394

    
1395
void janus_recordplay_update_recordings_list(void) {
1396
        if(recordings_path == NULL)
1397
                return;
1398
        JANUS_LOG(LOG_VERB, "Updating recordings list in %s\n", recordings_path);
1399
        janus_mutex_lock(&recordings_mutex);
1400
        /* First of all, let's keep track of which recordings are currently available */
1401
        GList *old_recordings = NULL;
1402
        if(recordings != NULL && g_hash_table_size(recordings) > 0) {
1403
                GHashTableIter iter;
1404
                gpointer value;
1405
                g_hash_table_iter_init(&iter, recordings);
1406
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
1407
                        janus_recordplay_recording *rec = value;
1408
                        if(rec) {
1409
                                old_recordings = g_list_append(old_recordings, &rec->id);
1410
                        }
1411
                }
1412
                janus_mutex_unlock(&recordings_mutex);
1413
        }
1414
        /* Open dir */
1415
        DIR *dir = opendir(recordings_path);
1416
        if(!dir) {
1417
                JANUS_LOG(LOG_ERR, "Couldn't open folder...\n");
1418
                g_list_free(old_recordings);
1419
                return;
1420
        }
1421
        struct dirent *recent = NULL;
1422
        char recpath[1024];
1423
        while((recent = readdir(dir))) {
1424
                int len = strlen(recent->d_name);
1425
                if(len < 4)
1426
                        continue;
1427
                if(strcasecmp(recent->d_name+len-4, ".nfo"))
1428
                        continue;
1429
                JANUS_LOG(LOG_VERB, "Importing recording '%s'...\n", recent->d_name);
1430
                memset(recpath, 0, 1024);
1431
                g_snprintf(recpath, 1024, "%s/%s", recordings_path, recent->d_name);
1432
                janus_config *nfo = janus_config_parse(recpath);
1433
                if(nfo == NULL) { 
1434
                        JANUS_LOG(LOG_ERR, "Invalid recording '%s'...\n", recent->d_name);
1435
                        continue;
1436
                }
1437
                GList *cl = janus_config_get_categories(nfo);
1438
                if(cl == NULL || cl->data == NULL) {
1439
                        JANUS_LOG(LOG_WARN, "No recording info in '%s', skipping...\n", recent->d_name);
1440
                        janus_config_destroy(nfo);
1441
                        continue;
1442
                }
1443
                janus_config_category *cat = (janus_config_category *)cl->data;
1444
                guint64 id = g_ascii_strtoull(cat->name, NULL, 0);
1445
                if(id == 0) {
1446
                        JANUS_LOG(LOG_WARN, "Invalid ID, skipping...\n");
1447
                        janus_config_destroy(nfo);
1448
                        continue;
1449
                }
1450
                janus_recordplay_recording *rec = g_hash_table_lookup(recordings, &id);
1451
                if(rec != NULL) {
1452
                        JANUS_LOG(LOG_VERB, "Skipping recording with ID %"SCNu64", it's already in the list...\n", id);
1453
                        janus_config_destroy(nfo);
1454
                        /* Mark that we updated this recording */
1455
                        old_recordings = g_list_remove(old_recordings, &rec->id);
1456
                        continue;
1457
                }
1458
                janus_config_item *name = janus_config_get_item(cat, "name");
1459
                janus_config_item *date = janus_config_get_item(cat, "date");
1460
                janus_config_item *audio = janus_config_get_item(cat, "audio");
1461
                janus_config_item *video = janus_config_get_item(cat, "video");
1462
                if(!name || !name->value || strlen(name->value) == 0 || !date || !date->value || strlen(date->value) == 0) {
1463
                        JANUS_LOG(LOG_WARN, "Invalid info for recording %"SCNu64", skipping...\n", id);
1464
                        janus_config_destroy(nfo);
1465
                        continue;
1466
                }
1467
                if((!audio || !audio->value) && (!video || !video->value)) {
1468
                        JANUS_LOG(LOG_WARN, "No audio and no video in recording %"SCNu64", skipping...\n", id);
1469
                        janus_config_destroy(nfo);
1470
                        continue;
1471
                }
1472
                rec = (janus_recordplay_recording *)g_malloc0(sizeof(janus_recordplay_recording));
1473
                rec->id = id;
1474
                rec->name = g_strdup(name->value);
1475
                rec->date = g_strdup(date->value);
1476
                if(audio && audio->value) {
1477
                        rec->arc_file = g_strdup(audio->value);
1478
                        if(strstr(rec->arc_file, ".mjr")) {
1479
                                char *ext = strstr(rec->arc_file, ".mjr");
1480
                                *ext = '\0';
1481
                        }
1482
                }
1483
                if(video && video->value) {
1484
                        rec->vrc_file = g_strdup(video->value);
1485
                        if(strstr(rec->vrc_file, ".mjr")) {
1486
                                char *ext = strstr(rec->vrc_file, ".mjr");
1487
                                *ext = '\0';
1488
                        }
1489
                }
1490
                rec->viewers = NULL;
1491
                rec->destroyed = 0;
1492
                rec->completed = TRUE;
1493
                janus_mutex_init(&rec->mutex);
1494
                
1495
                janus_config_destroy(nfo);
1496

    
1497
                /* Add to the list of recordings */
1498
                g_hash_table_insert(recordings, janus_uint64_dup(rec->id), rec);
1499
        }
1500
        closedir(dir);
1501
        /* Now let's check if any of the previously existing recordings was removed */
1502
        if(old_recordings != NULL) {
1503
                while(old_recordings != NULL) {
1504
                        guint64 id = *((guint64 *)old_recordings->data);
1505
                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" is not available anymore, removing...\n", id);
1506
                        janus_recordplay_recording *old_rec = g_hash_table_lookup(recordings, &id);
1507
                        if(old_rec != NULL) {
1508
                                /* Remove it */
1509
                                g_hash_table_remove(recordings, &id);
1510
                                /* Only destroy the object if no one's watching, though */
1511
                                janus_mutex_lock(&old_rec->mutex);
1512
                                old_rec->destroyed = janus_get_monotonic_time();
1513
                                if(old_rec->viewers == NULL) {
1514
                                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" has no viewers, destroying it now\n", id);
1515
                                        janus_mutex_unlock(&old_rec->mutex);
1516
                                        g_free(old_rec->name);
1517
                                        g_free(old_rec->date);
1518
                                        g_free(old_rec->arc_file);
1519
                                        g_free(old_rec->vrc_file);
1520
                                        g_free(old_rec);
1521
                                } else {
1522
                                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" still has viewers, delaying its destruction until later\n", id);
1523
                                        janus_mutex_unlock(&old_rec->mutex);
1524
                                }
1525
                        }
1526
                        old_recordings = old_recordings->next;
1527
                }
1528
                g_list_free(old_recordings);
1529
        }
1530
        janus_mutex_unlock(&recordings_mutex);
1531
}
1532

    
1533
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename) {
1534
        if(!dir || !filename)
1535
                return NULL;
1536
        /* Open the file */
1537
        char source[1024];
1538
        if(strstr(filename, ".mjr"))
1539
                g_snprintf(source, 1024, "%s/%s", dir, filename);
1540
        else
1541
                g_snprintf(source, 1024, "%s/%s.mjr", dir, filename);
1542
        FILE *file = fopen(source, "rb");
1543
        if(file == NULL) {
1544
                JANUS_LOG(LOG_ERR, "Could not open file %s\n", source);
1545
                return NULL;
1546
        }
1547
        fseek(file, 0L, SEEK_END);
1548
        long fsize = ftell(file);
1549
        fseek(file, 0L, SEEK_SET);
1550
        JANUS_LOG(LOG_VERB, "File is %zu bytes\n", fsize);
1551

    
1552
        /* Pre-parse */
1553
        JANUS_LOG(LOG_VERB, "Pre-parsing file %s to generate ordered index...\n", source);
1554
        gboolean parsed_header = FALSE;
1555
        int bytes = 0;
1556
        long offset = 0;
1557
        uint16_t len = 0, count = 0;
1558
        uint32_t first_ts = 0, last_ts = 0, reset = 0;        /* To handle whether there's a timestamp reset in the recording */
1559
        char prebuffer[1500];
1560
        memset(prebuffer, 0, 1500);
1561
        /* Let's look for timestamp resets first */
1562
        while(offset < fsize) {
1563
                /* Read frame header */
1564
                fseek(file, offset, SEEK_SET);
1565
                bytes = fread(prebuffer, sizeof(char), 8, file);
1566
                if(bytes != 8 || prebuffer[0] != 'M') {
1567
                        JANUS_LOG(LOG_ERR, "Invalid header...\n");
1568
                        fclose(file);
1569
                        return NULL;
1570
                }
1571
                if(prebuffer[1] == 'E') {
1572
                        /* Either the old .mjr format header ('MEETECHO' header followed by 'audio' or 'video'), or a frame */
1573
                        offset += 8;
1574
                        bytes = fread(&len, sizeof(uint16_t), 1, file);
1575
                        len = ntohs(len);
1576
                        offset += 2;
1577
                        if(len == 5 && !parsed_header) {
1578
                                /* This is the main header */
1579
                                parsed_header = TRUE;
1580
                                JANUS_LOG(LOG_VERB, "Old .mjr header format\n");
1581
                                bytes = fread(prebuffer, sizeof(char), 5, file);
1582
                                if(prebuffer[0] == 'v') {
1583
                                        JANUS_LOG(LOG_INFO, "This is a video recording, assuming VP8\n");
1584
                                } else if(prebuffer[0] == 'a') {
1585
                                        JANUS_LOG(LOG_INFO, "This is an audio recording, assuming Opus\n");
1586
                                } else {
1587
                                        JANUS_LOG(LOG_WARN, "Unsupported recording media type...\n");
1588
                                        fclose(file);
1589
                                        return NULL;
1590
                                }
1591
                                offset += len;
1592
                                continue;
1593
                        } else if(len < 12) {
1594
                                /* Not RTP, skip */
1595
                                JANUS_LOG(LOG_VERB, "Skipping packet (not RTP?)\n");
1596
                                offset += len;
1597
                                continue;
1598
                        }
1599
                } else if(prebuffer[1] == 'J') {
1600
                        /* New .mjr format, the header may contain useful info */
1601
                        offset += 8;
1602
                        bytes = fread(&len, sizeof(uint16_t), 1, file);
1603
                        len = ntohs(len);
1604
                        offset += 2;
1605
                        if(len > 0 && !parsed_header) {
1606
                                /* This is the info header */
1607
                                JANUS_LOG(LOG_VERB, "New .mjr header format\n");
1608
                                bytes = fread(prebuffer, sizeof(char), len, file);
1609
                                parsed_header = TRUE;
1610
                                prebuffer[len] = '\0';
1611
                                json_error_t error;
1612
                                json_t *info = json_loads(prebuffer, 0, &error);
1613
                                if(!info) {
1614
                                        JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
1615
                                        JANUS_LOG(LOG_WARN, "Error parsing info header...\n");
1616
                                        fclose(file);
1617
                                        return NULL;
1618
                                }
1619
                                /* Is it audio or video? */
1620
                                json_t *type = json_object_get(info, "t");
1621
                                if(!type || !json_is_string(type)) {
1622
                                        JANUS_LOG(LOG_WARN, "Missing/invalid recording type in info header...\n");
1623
                                        json_decref(info);
1624
                                        fclose(file);
1625
                                        return NULL;
1626
                                }
1627
                                const char *t = json_string_value(type);
1628
                                int video = 0;
1629
                                gint64 c_time = 0, w_time = 0;
1630
                                if(!strcasecmp(t, "v")) {
1631
                                        video = 1;
1632
                                } else if(!strcasecmp(t, "a")) {
1633
                                        video = 0;
1634
                                } else {
1635
                                        JANUS_LOG(LOG_WARN, "Unsupported recording type '%s' in info header...\n", t);
1636
                                        json_decref(info);
1637
                                        fclose(file);
1638
                                        return NULL;
1639
                                }
1640
                                /* What codec was used? */
1641
                                json_t *codec = json_object_get(info, "c");
1642
                                if(!codec || !json_is_string(codec)) {
1643
                                        JANUS_LOG(LOG_WARN, "Missing recording codec in info header...\n");
1644
                                        json_decref(info);
1645
                                        fclose(file);
1646
                                        return NULL;
1647
                                }
1648
                                const char *c = json_string_value(codec);
1649
                                if(video && strcasecmp(c, "vp8")) {
1650
                                        JANUS_LOG(LOG_WARN, "The Record&Play plugin only supports VP8 video for now (was '%s')...\n", c);
1651
                                        json_decref(info);
1652
                                        fclose(file);
1653
                                        return NULL;
1654
                                } else if(!video && strcasecmp(c, "opus")) {
1655
                                        JANUS_LOG(LOG_WARN, "The Record&Play plugin only supports Opus audio for now (was '%s')...\n", c);
1656
                                        json_decref(info);
1657
                                        fclose(file);
1658
                                        return NULL;
1659
                                }
1660
                                /* When was the file created? */
1661
                                json_t *created = json_object_get(info, "s");
1662
                                if(!created || !json_is_integer(created)) {
1663
                                        JANUS_LOG(LOG_WARN, "Missing recording created time in info header...\n");
1664
                                        json_decref(info);
1665
                                        fclose(file);
1666
                                        return NULL;
1667
                                }
1668
                                c_time = json_integer_value(created);
1669
                                /* When was the first frame written? */
1670
                                json_t *written = json_object_get(info, "u");
1671
                                if(!written || !json_is_integer(written)) {
1672
                                        JANUS_LOG(LOG_WARN, "Missing recording written time in info header...\n");
1673
                                        json_decref(info);
1674
                                        fclose(file);
1675
                                        return NULL;
1676
                                }
1677
                                w_time = json_integer_value(created);
1678
                                /* Summary */
1679
                                JANUS_LOG(LOG_VERB, "This is %s recording:\n", video ? "a video" : "an audio");
1680
                                JANUS_LOG(LOG_VERB, "  -- Codec:   %s\n", c);
1681
                                JANUS_LOG(LOG_VERB, "  -- Created: %"SCNi64"\n", c_time);
1682
                                JANUS_LOG(LOG_VERB, "  -- Written: %"SCNi64"\n", w_time);
1683
                                json_decref(info);
1684
                        }
1685
                } else {
1686
                        JANUS_LOG(LOG_ERR, "Invalid header...\n");
1687
                        fclose(file);
1688
                        return NULL;
1689
                }
1690
                /* Only read RTP header */
1691
                bytes = fread(prebuffer, sizeof(char), 16, file);
1692
                rtp_header *rtp = (rtp_header *)prebuffer;
1693
                if(last_ts == 0) {
1694
                        first_ts = ntohl(rtp->timestamp);
1695
                        if(first_ts > 1000*1000)        /* Just used to check whether a packet is pre- or post-reset */
1696
                                first_ts -= 1000*1000;
1697
                } else {
1698
                        if(ntohl(rtp->timestamp) < last_ts) {
1699
                                /* The new timestamp is smaller than the next one, is it a timestamp reset or simply out of order? */
1700
                                if(last_ts-ntohl(rtp->timestamp) > 2*1000*1000*1000) {
1701
                                        reset = ntohl(rtp->timestamp);
1702
                                        JANUS_LOG(LOG_VERB, "Timestamp reset: %"SCNu32"\n", reset);
1703
                                }
1704
                        } else if(ntohl(rtp->timestamp) < reset) {
1705
                                JANUS_LOG(LOG_VERB, "Updating timestamp reset: %"SCNu32" (was %"SCNu32")\n", ntohl(rtp->timestamp), reset);
1706
                                reset = ntohl(rtp->timestamp);
1707
                        }
1708
                }
1709
                last_ts = ntohl(rtp->timestamp);
1710
                /* Skip data for now */
1711
                offset += len;
1712
        }
1713
        /* Now let's parse the frames and order them */
1714
        offset = 0;
1715
        janus_recordplay_frame_packet *list = NULL, *last = NULL;
1716
        while(offset < fsize) {
1717
                /* Read frame header */
1718
                fseek(file, offset, SEEK_SET);
1719
                bytes = fread(prebuffer, sizeof(char), 8, file);
1720
                prebuffer[8] = '\0';
1721
                JANUS_LOG(LOG_HUGE, "Header: %s\n", prebuffer);
1722
                offset += 8;
1723
                bytes = fread(&len, sizeof(uint16_t), 1, file);
1724
                len = ntohs(len);
1725
                JANUS_LOG(LOG_HUGE, "  -- Length: %"SCNu16"\n", len);
1726
                offset += 2;
1727
                if(prebuffer[1] == 'J' || len < 12) {
1728
                        /* Not RTP, skip */
1729
                        JANUS_LOG(LOG_HUGE, "  -- Not RTP, skipping\n");
1730
                        offset += len;
1731
                        continue;
1732
                }
1733
                /* Only read RTP header */
1734
                bytes = fread(prebuffer, sizeof(char), 16, file);
1735
                rtp_header *rtp = (rtp_header *)prebuffer;
1736
                JANUS_LOG(LOG_HUGE, "  -- RTP packet (ssrc=%"SCNu32", pt=%"SCNu16", ext=%"SCNu16", seq=%"SCNu16", ts=%"SCNu32")\n",
1737
                                ntohl(rtp->ssrc), rtp->type, rtp->extension, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
1738
                /* Generate frame packet and insert in the ordered list */
1739
                janus_recordplay_frame_packet *p = g_malloc0(sizeof(janus_recordplay_frame_packet));
1740
                p->seq = ntohs(rtp->seq_number);
1741
                if(reset == 0) {
1742
                        /* Simple enough... */
1743
                        p->ts = ntohl(rtp->timestamp);
1744
                } else {
1745
                        /* Is this packet pre- or post-reset? */
1746
                        if(ntohl(rtp->timestamp) > first_ts) {
1747
                                /* Pre-reset... */
1748
                                p->ts = ntohl(rtp->timestamp);
1749
                        } else {
1750
                                /* Post-reset... */
1751
                                uint64_t max32 = UINT32_MAX;
1752
                                max32++;
1753
                                p->ts = max32+ntohl(rtp->timestamp);
1754
                        }
1755
                }
1756
                p->len = len;
1757
                p->offset = offset;
1758
                p->next = NULL;
1759
                p->prev = NULL;
1760
                if(list == NULL) {
1761
                        /* First element becomes the list itself (and the last item), at least for now */
1762
                        list = p;
1763
                        last = p;
1764
                } else {
1765
                        /* Check where we should insert this, starting from the end */
1766
                        int added = 0;
1767
                        janus_recordplay_frame_packet *tmp = last;
1768
                        while(tmp) {
1769
                                if(tmp->ts < p->ts) {
1770
                                        /* The new timestamp is greater than the last one we have, append */
1771
                                        added = 1;
1772
                                        if(tmp->next != NULL) {
1773
                                                /* We're inserting */
1774
                                                tmp->next->prev = p;
1775
                                                p->next = tmp->next;
1776
                                        } else {
1777
                                                /* Update the last packet */
1778
                                                last = p;
1779
                                        }
1780
                                        tmp->next = p;
1781
                                        p->prev = tmp;
1782
                                        break;
1783
                                } else if(tmp->ts == p->ts) {
1784
                                        /* Same timestamp, check the sequence number */
1785
                                        if(tmp->seq < p->seq && (abs(tmp->seq - p->seq) < 10000)) {
1786
                                                /* The new sequence number is greater than the last one we have, append */
1787
                                                added = 1;
1788
                                                if(tmp->next != NULL) {
1789
                                                        /* We're inserting */
1790
                                                        tmp->next->prev = p;
1791
                                                        p->next = tmp->next;
1792
                                                } else {
1793
                                                        /* Update the last packet */
1794
                                                        last = p;
1795
                                                }
1796
                                                tmp->next = p;
1797
                                                p->prev = tmp;
1798
                                                break;
1799
                                        } else if(tmp->seq > p->seq && (abs(tmp->seq - p->seq) > 10000)) {
1800
                                                /* The new sequence number (resetted) is greater than the last one we have, append */
1801
                                                added = 1;
1802
                                                if(tmp->next != NULL) {
1803
                                                        /* We're inserting */
1804
                                                        tmp->next->prev = p;
1805
                                                        p->next = tmp->next;
1806
                                                } else {
1807
                                                        /* Update the last packet */
1808
                                                        last = p;
1809
                                                }
1810
                                                tmp->next = p;
1811
                                                p->prev = tmp;
1812
                                                break;
1813
                                        }
1814
                                }
1815
                                /* If either the timestamp ot the sequence number we just got is smaller, keep going back */
1816
                                tmp = tmp->prev;
1817
                        }
1818
                        if(!added) {
1819
                                /* We reached the start */
1820
                                p->next = list;
1821
                                list->prev = p;
1822
                                list = p;
1823
                        }
1824
                }
1825
                /* Skip data for now */
1826
                offset += len;
1827
                count++;
1828
        }
1829
        
1830
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" RTP packets\n", count);
1831
        janus_recordplay_frame_packet *tmp = list;
1832
        count = 0;
1833
        while(tmp) {
1834
                count++;
1835
                JANUS_LOG(LOG_HUGE, "[%10lu][%4d] seq=%"SCNu16", ts=%"SCNu64"\n", tmp->offset, tmp->len, tmp->seq, tmp->ts);
1836
                tmp = tmp->next;
1837
        }
1838
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" frame packets\n", count);
1839
        
1840
        /* Done! */
1841
        fclose(file);
1842
        return list;
1843
}
1844

    
1845
static void *janus_recordplay_playout_thread(void *data) {
1846
        janus_recordplay_session *session = (janus_recordplay_session *)data;
1847
        if(!session) {
1848
                JANUS_LOG(LOG_ERR, "Invalid session, can't start playout thread...\n");
1849
                g_thread_unref(g_thread_self());
1850
                return NULL;
1851
        }
1852
        if(session->recorder) {
1853
                JANUS_LOG(LOG_ERR, "This is a recorder, can't start playout thread...\n");
1854
                g_thread_unref(g_thread_self());
1855
                return NULL;
1856
        }
1857
        if(!session->aframes && !session->vframes) {
1858
                JANUS_LOG(LOG_ERR, "No audio and no video frames, can't start playout thread...\n");
1859
                g_thread_unref(g_thread_self());
1860
                return NULL;
1861
        }
1862
        JANUS_LOG(LOG_INFO, "Joining playout thread\n");
1863
        /* Open the files */
1864
        FILE *afile = NULL, *vfile = NULL;
1865
        if(session->aframes) {
1866
                char source[1024];
1867
                if(strstr(session->recording->arc_file, ".mjr"))
1868
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->arc_file);
1869
                else
1870
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->arc_file);
1871
                afile = fopen(source, "rb");
1872
                if(afile == NULL) {
1873
                        JANUS_LOG(LOG_ERR, "Could not open audio file %s, can't start playout thread...\n", source);
1874
                        g_thread_unref(g_thread_self());
1875
                        return NULL;
1876
                }
1877
        }
1878
        if(session->vframes) {
1879
                char source[1024];
1880
                if(strstr(session->recording->vrc_file, ".mjr"))
1881
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->vrc_file);
1882
                else
1883
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->vrc_file);
1884
                vfile = fopen(source, "rb");
1885
                if(vfile == NULL) {
1886
                        JANUS_LOG(LOG_ERR, "Could not open video file %s, can't start playout thread...\n", source);
1887
                        if(afile)
1888
                                fclose(afile);
1889
                        afile = NULL;
1890
                        g_thread_unref(g_thread_self());
1891
                        return NULL;
1892
                }
1893
        }
1894
        
1895
        /* Timer */
1896
        gboolean asent = FALSE, vsent = FALSE;
1897
        struct timeval now, abefore, vbefore;
1898
        time_t d_s, d_us;
1899
        gettimeofday(&now, NULL);
1900
        gettimeofday(&abefore, NULL);
1901
        gettimeofday(&vbefore, NULL);
1902

    
1903
        janus_recordplay_frame_packet *audio = session->aframes, *video = session->vframes;
1904
        char *buffer = (char *)g_malloc0(1500);
1905
        memset(buffer, 0, 1500);
1906
        int bytes = 0;
1907
        int64_t ts_diff = 0, passed = 0;
1908
        
1909
        while(!session->destroyed && session->active && !session->recording->destroyed && (audio || video)) {
1910
                if(!asent && !vsent) {
1911
                        /* We skipped the last round, so sleep a bit (5ms) */
1912
                        usleep(5000);
1913
                }
1914
                asent = FALSE;
1915
                vsent = FALSE;
1916
                if(audio) {
1917
                        if(audio == session->aframes) {
1918
                                /* First packet, send now */
1919
                                fseek(afile, audio->offset, SEEK_SET);
1920
                                bytes = fread(buffer, sizeof(char), audio->len, afile);
1921
                                if(bytes != audio->len)
1922
                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1923
                                /* Update payload type */
1924
                                rtp_header *rtp = (rtp_header *)buffer;
1925
                                rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1926
                                if(gateway != NULL)
1927
                                        gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1928
                                gettimeofday(&now, NULL);
1929
                                abefore.tv_sec = now.tv_sec;
1930
                                abefore.tv_usec = now.tv_usec;
1931
                                asent = TRUE;
1932
                                audio = audio->next;
1933
                        } else {
1934
                                /* What's the timestamp skip from the previous packet? */
1935
                                ts_diff = audio->ts - audio->prev->ts;
1936
                                ts_diff = (ts_diff*1000)/48;        /* FIXME Again, we're assuming Opus and it's 48khz */
1937
                                /* Check if it's time to send */
1938
                                gettimeofday(&now, NULL);
1939
                                d_s = now.tv_sec - abefore.tv_sec;
1940
                                d_us = now.tv_usec - abefore.tv_usec;
1941
                                if(d_us < 0) {
1942
                                        d_us += 1000000;
1943
                                        --d_s;
1944
                                }
1945
                                passed = d_s*1000000 + d_us;
1946
                                if(passed < (ts_diff-5000)) {
1947
                                        asent = FALSE;
1948
                                } else {
1949
                                        /* Update the reference time */
1950
                                        abefore.tv_usec += ts_diff%1000000;
1951
                                        if(abefore.tv_usec > 1000000) {
1952
                                                abefore.tv_sec++;
1953
                                                abefore.tv_usec -= 1000000;
1954
                                        }
1955
                                        if(ts_diff/1000000 > 0) {
1956
                                                abefore.tv_sec += ts_diff/1000000;
1957
                                                abefore.tv_usec -= ts_diff/1000000;
1958
                                        }
1959
                                        /* Send now */
1960
                                        fseek(afile, audio->offset, SEEK_SET);
1961
                                        bytes = fread(buffer, sizeof(char), audio->len, afile);
1962
                                        if(bytes != audio->len)
1963
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1964
                                        /* Update payload type */
1965
                                        rtp_header *rtp = (rtp_header *)buffer;
1966
                                        rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1967
                                        if(gateway != NULL)
1968
                                                gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1969
                                        asent = TRUE;
1970
                                        audio = audio->next;
1971
                                }
1972
                        }
1973
                }
1974
                if(video) {
1975
                        if(video == session->vframes) {
1976
                                /* First packets: there may be many of them with the same timestamp, send them all */
1977
                                uint64_t ts = video->ts;
1978
                                while(video && video->ts == ts) {
1979
                                        fseek(vfile, video->offset, SEEK_SET);
1980
                                        bytes = fread(buffer, sizeof(char), video->len, vfile);
1981
                                        if(bytes != video->len)
1982
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
1983
                                        /* Update payload type */
1984
                                        rtp_header *rtp = (rtp_header *)buffer;
1985
                                        rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
1986
                                        if(gateway != NULL)
1987
                                                gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
1988
                                        video = video->next;
1989
                                }
1990
                                vsent = TRUE;
1991
                                gettimeofday(&now, NULL);
1992
                                vbefore.tv_sec = now.tv_sec;
1993
                                vbefore.tv_usec = now.tv_usec;
1994
                        } else {
1995
                                /* What's the timestamp skip from the previous packet? */
1996
                                ts_diff = video->ts - video->prev->ts;
1997
                                ts_diff = (ts_diff*1000)/90;
1998
                                /* Check if it's time to send */
1999
                                gettimeofday(&now, NULL);
2000
                                d_s = now.tv_sec - vbefore.tv_sec;
2001
                                d_us = now.tv_usec - vbefore.tv_usec;
2002
                                if(d_us < 0) {
2003
                                        d_us += 1000000;
2004
                                        --d_s;
2005
                                }
2006
                                passed = d_s*1000000 + d_us;
2007
                                if(passed < (ts_diff-5000)) {
2008
                                        vsent = FALSE;
2009
                                } else {
2010
                                        /* Update the reference time */
2011
                                        vbefore.tv_usec += ts_diff%1000000;
2012
                                        if(vbefore.tv_usec > 1000000) {
2013
                                                vbefore.tv_sec++;
2014
                                                vbefore.tv_usec -= 1000000;
2015
                                        }
2016
                                        if(ts_diff/1000000 > 0) {
2017
                                                vbefore.tv_sec += ts_diff/1000000;
2018
                                                vbefore.tv_usec -= ts_diff/1000000;
2019
                                        }
2020
                                        /* There may be multiple packets with the same timestamp, send them all */
2021
                                        uint64_t ts = video->ts;
2022
                                        while(video && video->ts == ts) {
2023
                                                /* Send now */
2024
                                                fseek(vfile, video->offset, SEEK_SET);
2025
                                                bytes = fread(buffer, sizeof(char), video->len, vfile);
2026
                                                if(bytes != video->len)
2027
                                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
2028
                                                /* Update payload type */
2029
                                                rtp_header *rtp = (rtp_header *)buffer;
2030
                                                rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
2031
                                                if(gateway != NULL)
2032
                                                        gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
2033
                                                video = video->next;
2034
                                        }
2035
                                        vsent = TRUE;
2036
                                }
2037
                        }
2038
                }
2039
        }
2040
        
2041
        g_free(buffer);
2042

    
2043
        /* Get rid of the indexes */
2044
        janus_recordplay_frame_packet *tmp = NULL;
2045
        audio = session->aframes;
2046
        while(audio) {
2047
                tmp = audio->next;
2048
                g_free(audio);
2049
                audio = tmp;
2050
        }
2051
        session->aframes = NULL;
2052
        video = session->vframes;
2053
        while(video) {
2054
                tmp = video->next;
2055
                g_free(video);
2056
                video = tmp;
2057
        }
2058
        session->vframes = NULL;
2059

    
2060
        if(afile)
2061
                fclose(afile);
2062
        afile = NULL;
2063
        if(vfile)
2064
                fclose(vfile);
2065
        vfile = NULL;
2066

    
2067
        if(session->recording->destroyed) {
2068
                /* Remove from the list of viewers */
2069
                janus_mutex_lock(&session->recording->mutex);
2070
                session->recording->viewers = g_list_remove(session->recording->viewers, session);
2071
                if(session->recording->viewers == NULL) {
2072
                        /* This was the last viewer, destroying the recording */
2073
                        JANUS_LOG(LOG_VERB, "Last viewer stopped playout of recording %"SCNu64", destroying it now\n", session->recording->id);
2074
                        janus_mutex_unlock(&session->recording->mutex);
2075
                        g_free(session->recording->name);
2076
                        g_free(session->recording->date);
2077
                        g_free(session->recording->arc_file);
2078
                        g_free(session->recording->vrc_file);
2079
                        g_free(session->recording);
2080
                        session->recording = NULL;
2081
                } else {
2082
                        /* Other viewers still on, don't do anything */
2083
                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" still has viewers, delaying its destruction until later\n", session->recording->id);
2084
                        janus_mutex_unlock(&session->recording->mutex);
2085
                }
2086
        }
2087

    
2088
        /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
2089
        gateway->close_pc(session->handle);
2090
        
2091
        JANUS_LOG(LOG_INFO, "Leaving playout thread\n");
2092
        g_thread_unref(g_thread_self());
2093
        return NULL;
2094
}