Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_recordplay.c @ 78955474

History | View | Annotate | Download (74.3 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/time.h>
251
#include <jansson.h>
252

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

    
262

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

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

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

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

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

    
325

    
326
/* Useful stuff */
327
static gint initialized = 0, stopping = 0;
328
static janus_callbacks *gateway = NULL;
329
static GThread *handler_thread;
330
static GThread *watchdog;
331
static void *janus_recordplay_handler(void *data);
332

    
333
typedef struct janus_recordplay_message {
334
        janus_plugin_session *handle;
335
        char *transaction;
336
        json_t *message;
337
        char *sdp_type;
338
        char *sdp;
339
} janus_recordplay_message;
340
static GAsyncQueue *messages = NULL;
341

    
342
typedef struct janus_recordplay_rtp_header_extension {
343
        uint16_t type;
344
        uint16_t length;
345
} janus_recordplay_rtp_header_extension;
346

    
347
typedef struct janus_recordplay_frame_packet {
348
        uint16_t seq;        /* RTP Sequence number */
349
        uint64_t ts;        /* RTP Timestamp */
350
        int len;                /* Length of the data */
351
        long offset;        /* Offset of the data in the file */
352
        struct janus_recordplay_frame_packet *next;
353
        struct janus_recordplay_frame_packet *prev;
354
} janus_recordplay_frame_packet;
355
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename);
356

    
357
typedef struct janus_recordplay_recording {
358
        guint64 id;                        /* Recording unique ID */
359
        char *name;                        /* Name of the recording */
360
        char *date;                        /* Time of the recording */
361
        char *arc_file;                /* Audio file name */
362
        char *vrc_file;                /* Video file name */
363
        GList *viewers;                /* List of users watching this recording */
364
        gint64 destroyed;        /* Lazy timestamp to mark recordings as destroyed */
365
        janus_mutex mutex;        /* Mutex for this recording */
366
} janus_recordplay_recording;
367
static GHashTable *recordings = NULL;
368
static janus_mutex recordings_mutex;
369

    
370
typedef struct janus_recordplay_session {
371
        janus_plugin_session *handle;
372
        gboolean active;
373
        gboolean recorder;                /* Whether this session is used to record or to replay a WebRTC session */
374
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
375
        janus_recordplay_recording *recording;
376
        janus_recorder *arc;        /* Audio recorder */
377
        janus_recorder *vrc;        /* Video recorder */
378
        janus_recordplay_frame_packet *aframes;        /* Audio frames (for playout) */
379
        janus_recordplay_frame_packet *vframes;        /* Video frames (for playout) */
380
        guint video_remb_startup;
381
        guint64 video_remb_last;
382
        guint64 video_bitrate;
383
        guint video_keyframe_interval; /* keyframe request interval (ms) */
384
        guint64 video_keyframe_request_last; /* timestamp of last keyframe request sent */
385
        gint video_fir_seq;
386
        gboolean hangingup;
387
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
388
} janus_recordplay_session;
389
static GHashTable *sessions;
390
static GList *old_sessions;
391
static janus_mutex sessions_mutex;
392

    
393

    
394
static char *recordings_path = NULL;
395
void janus_recordplay_update_recordings_list(void);
396
static void *janus_recordplay_playout_thread(void *data);
397

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

    
401

    
402
/* SDP offer/answer templates for the playout */
403
#define OPUS_PT                111
404
#define VP8_PT                100
405
#define sdp_template \
406
                "v=0\r\n" \
407
                "o=- %"SCNu64" %"SCNu64" IN IP4 127.0.0.1\r\n"        /* We need current time here */ \
408
                "s=%s\r\n"                                                        /* Recording playout id */ \
409
                "t=0 0\r\n" \
410
                "%s%s"                                                                /* Audio and/or video m-lines */
411
#define sdp_a_template \
412
                "m=audio 1 RTP/SAVPF %d\r\n"                /* Opus payload type */ \
413
                "c=IN IP4 1.1.1.1\r\n" \
414
                "a=%s\r\n"                                                        /* Media direction */ \
415
                "a=rtpmap:%d opus/48000/2\r\n"                /* Opus payload type */
416
#define sdp_v_template \
417
                "m=video 1 RTP/SAVPF %d\r\n"                /* VP8 payload type */ \
418
                "c=IN IP4 1.1.1.1\r\n" \
419
                "a=%s\r\n"                                                        /* Media direction */ \
420
                "a=rtpmap:%d VP8/90000\r\n"                        /* VP8 payload type */ \
421
                "a=rtcp-fb:%d ccm fir\r\n"                        /* VP8 payload type */ \
422
                "a=rtcp-fb:%d nack\r\n"                                /* VP8 payload type */ \
423
                "a=rtcp-fb:%d nack pli\r\n"                        /* VP8 payload type */ \
424
                "a=rtcp-fb:%d goog-remb\r\n"                /* VP8 payload type */
425

    
426

    
427
void janus_recordplay_message_free(janus_recordplay_message *msg);
428
void janus_recordplay_message_free(janus_recordplay_message *msg) {
429
        if(!msg)
430
                return;
431

    
432
        msg->handle = NULL;
433

    
434
        g_free(msg->transaction);
435
        msg->transaction = NULL;
436
        if(msg->message)
437
                json_decref(msg->message);
438
        msg->message = NULL;
439
        g_free(msg->sdp_type);
440
        msg->sdp_type = NULL;
441
        g_free(msg->sdp);
442
        msg->sdp = NULL;
443

    
444
        g_free(msg);
445
}
446

    
447

    
448
/* Error codes */
449
#define JANUS_RECORDPLAY_ERROR_NO_MESSAGE                        411
450
#define JANUS_RECORDPLAY_ERROR_INVALID_JSON                412
451
#define JANUS_RECORDPLAY_ERROR_INVALID_REQUEST        413
452
#define JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT        414
453
#define JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT        415
454
#define JANUS_RECORDPLAY_ERROR_NOT_FOUND        416
455
#define JANUS_RECORDPLAY_ERROR_INVALID_RECORDING        417
456
#define JANUS_RECORDPLAY_ERROR_INVALID_STATE        418
457
#define JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR        499
458

    
459

    
460
/* Record&Play watchdog/garbage collector (sort of) */
461
void *janus_recordplay_watchdog(void *data);
462
void *janus_recordplay_watchdog(void *data) {
463
        JANUS_LOG(LOG_INFO, "Record&Play watchdog started\n");
464
        gint64 now = 0;
465
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
466
                janus_mutex_lock(&sessions_mutex);
467
                /* Iterate on all the sessions */
468
                now = janus_get_monotonic_time();
469
                if(old_sessions != NULL) {
470
                        GList *sl = old_sessions;
471
                        JANUS_LOG(LOG_HUGE, "Checking %d old Record&Play sessions...\n", g_list_length(old_sessions));
472
                        while(sl) {
473
                                janus_recordplay_session *session = (janus_recordplay_session *)sl->data;
474
                                if(!session) {
475
                                        sl = sl->next;
476
                                        continue;
477
                                }
478
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
479
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
480
                                        JANUS_LOG(LOG_VERB, "Freeing old Record&Play session\n");
481
                                        GList *rm = sl->next;
482
                                        old_sessions = g_list_delete_link(old_sessions, sl);
483
                                        sl = rm;
484
                                        session->handle = NULL;
485
                                        g_free(session);
486
                                        session = NULL;
487
                                        continue;
488
                                }
489
                                sl = sl->next;
490
                        }
491
                }
492
                janus_mutex_unlock(&sessions_mutex);
493
                g_usleep(500000);
494
        }
495
        JANUS_LOG(LOG_INFO, "Record&Play watchdog stopped\n");
496
        return NULL;
497
}
498

    
499

    
500
/* Plugin implementation */
501
int janus_recordplay_init(janus_callbacks *callback, const char *config_path) {
502
        if(g_atomic_int_get(&stopping)) {
503
                /* Still stopping from before */
504
                return -1;
505
        }
506
        if(callback == NULL || config_path == NULL) {
507
                /* Invalid arguments */
508
                return -1;
509
        }
510

    
511
        /* Read configuration */
512
        char filename[255];
513
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_RECORDPLAY_PACKAGE);
514
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
515
        janus_config *config = janus_config_parse(filename);
516
        if(config != NULL)
517
                janus_config_print(config);
518
        /* Parse configuration */
519
        if(config != NULL) {
520
                janus_config_item *path = janus_config_get_item_drilldown(config, "general", "path");
521
                if(path && path->value)
522
                        recordings_path = g_strdup(path->value);
523
                /* Done */
524
                janus_config_destroy(config);
525
                config = NULL;
526
        }
527
        if(recordings_path == NULL) {
528
                recordings_path = g_strdup("/tmp");
529
                JANUS_LOG(LOG_WARN, "No recordings path specified, using /tmp...\n");
530
        }
531
        /* Create the folder, if needed */
532
        struct stat st = {0};
533
        if(stat(recordings_path, &st) == -1) {
534
                int res = janus_mkdir(recordings_path, 0755);
535
                JANUS_LOG(LOG_VERB, "Creating folder: %d\n", res);
536
                if(res != 0) {
537
                        JANUS_LOG(LOG_ERR, "%s", strerror(res));
538
                        return -1;        /* No point going on... */
539
                }
540
        }
541
        recordings = g_hash_table_new(NULL, NULL);
542
        janus_mutex_init(&recordings_mutex);
543
        janus_recordplay_update_recordings_list();
544
        
545
        sessions = g_hash_table_new(NULL, NULL);
546
        janus_mutex_init(&sessions_mutex);
547
        messages = g_async_queue_new_full((GDestroyNotify) janus_recordplay_message_free);
548
        /* This is the callback we'll need to invoke to contact the gateway */
549
        gateway = callback;
550

    
551
        g_atomic_int_set(&initialized, 1);
552

    
553
        GError *error = NULL;
554
        /* Start the sessions watchdog */
555
        watchdog = g_thread_try_new("rplay watchdog", &janus_recordplay_watchdog, NULL, &error);
556
        if(error != NULL) {
557
                g_atomic_int_set(&initialized, 0);
558
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play watchdog thread...\n", error->code, error->message ? error->message : "??");
559
                return -1;
560
        }
561
        /* Launch the thread that will handle incoming messages */
562
        handler_thread = g_thread_try_new("janus recordplay handler", janus_recordplay_handler, NULL, &error);
563
        if(error != NULL) {
564
                g_atomic_int_set(&initialized, 0);
565
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play handler thread...\n", error->code, error->message ? error->message : "??");
566
                return -1;
567
        }
568
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_RECORDPLAY_NAME);
569
        return 0;
570
}
571

    
572
void janus_recordplay_destroy(void) {
573
        if(!g_atomic_int_get(&initialized))
574
                return;
575
        g_atomic_int_set(&stopping, 1);
576
        if(handler_thread != NULL) {
577
                g_thread_join(handler_thread);
578
                handler_thread = NULL;
579
        }
580
        if(watchdog != NULL) {
581
                g_thread_join(watchdog);
582
                watchdog = NULL;
583
        }
584
        /* FIXME We should destroy the sessions cleanly */
585
        janus_mutex_lock(&sessions_mutex);
586
        g_hash_table_destroy(sessions);
587
        janus_mutex_unlock(&sessions_mutex);
588
        g_async_queue_unref(messages);
589
        messages = NULL;
590
        sessions = NULL;
591
        g_atomic_int_set(&initialized, 0);
592
        g_atomic_int_set(&stopping, 0);
593
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_RECORDPLAY_NAME);
594
}
595

    
596
int janus_recordplay_get_api_compatibility(void) {
597
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
598
        return JANUS_PLUGIN_API_VERSION;
599
}
600

    
601
int janus_recordplay_get_version(void) {
602
        return JANUS_RECORDPLAY_VERSION;
603
}
604

    
605
const char *janus_recordplay_get_version_string(void) {
606
        return JANUS_RECORDPLAY_VERSION_STRING;
607
}
608

    
609
const char *janus_recordplay_get_description(void) {
610
        return JANUS_RECORDPLAY_DESCRIPTION;
611
}
612

    
613
const char *janus_recordplay_get_name(void) {
614
        return JANUS_RECORDPLAY_NAME;
615
}
616

    
617
const char *janus_recordplay_get_author(void) {
618
        return JANUS_RECORDPLAY_AUTHOR;
619
}
620

    
621
const char *janus_recordplay_get_package(void) {
622
        return JANUS_RECORDPLAY_PACKAGE;
623
}
624

    
625
void janus_recordplay_create_session(janus_plugin_session *handle, int *error) {
626
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
627
                *error = -1;
628
                return;
629
        }        
630
        janus_recordplay_session *session = (janus_recordplay_session *)calloc(1, sizeof(janus_recordplay_session));
631
        if(session == NULL) {
632
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
633
                *error = -2;
634
                return;
635
        }
636
        session->handle = handle;
637
        session->active = FALSE;
638
        session->recorder = FALSE;
639
        session->firefox = FALSE;
640
        session->arc = NULL;
641
        session->vrc = NULL;
642
        session->destroyed = 0;
643
        session->video_remb_startup = 4;
644
        session->video_remb_last = janus_get_monotonic_time();
645
        session->video_bitrate = 1024 * 1024;                 /* This is 1mbps by default */
646
        session->video_keyframe_request_last = 0;
647
        session->video_keyframe_interval = 15000;         /* 15 seconds by default */
648
        session->video_fir_seq = 0;
649
        handle->plugin_handle = session;
650
        janus_mutex_lock(&sessions_mutex);
651
        g_hash_table_insert(sessions, handle, session);
652
        janus_mutex_unlock(&sessions_mutex);
653

    
654
        return;
655
}
656

    
657
void janus_recordplay_destroy_session(janus_plugin_session *handle, int *error) {
658
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
659
                *error = -1;
660
                return;
661
        }        
662
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
663
        if(!session) {
664
                JANUS_LOG(LOG_ERR, "No Record&Play session associated with this handle...\n");
665
                *error = -2;
666
                return;
667
        }
668
        janus_mutex_lock(&sessions_mutex);
669
        if(!session->destroyed) {
670
                session->destroyed = janus_get_monotonic_time();
671
                JANUS_LOG(LOG_VERB, "Removing Record&Play session...\n");
672
                g_hash_table_remove(sessions, handle);
673
                /* Cleaning up and removing the session is done in a lazy way */
674
                old_sessions = g_list_append(old_sessions, session);
675
        }
676
        janus_mutex_unlock(&sessions_mutex);
677
        return;
678
}
679

    
680
char *janus_recordplay_query_session(janus_plugin_session *handle) {
681
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
682
                return NULL;
683
        }        
684
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
685
        if(!session) {
686
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
687
                return NULL;
688
        }
689
        /* In the echo test, every session is the same: we just provide some configure info */
690
        json_t *info = json_object();
691
        json_object_set_new(info, "type", json_string(session->recorder ? "recorder" : (session->recording ? "player" : "none")));
692
        if(session->recording) {
693
                json_object_set_new(info, "recording_id", json_integer(session->recording->id));
694
                json_object_set_new(info, "recording_name", json_string(session->recording->name));
695
        }
696
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
697
        char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
698
        json_decref(info);
699
        return info_text;
700
}
701

    
702
struct janus_plugin_result *janus_recordplay_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
703
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
704
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
705

    
706
        /* Pre-parse the message */
707
        int error_code = 0;
708
        char error_cause[512];
709
        json_t *root = NULL;
710
        json_t *response = NULL;
711
        
712
        if(message == NULL) {
713
                JANUS_LOG(LOG_ERR, "No message??\n");
714
                error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
715
                g_snprintf(error_cause, 512, "%s", "No message??");
716
                goto error;
717
        }
718
        JANUS_LOG(LOG_VERB, "Handling message: %s\n", message);
719

    
720
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
721
        if(!session) {
722
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
723
                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
724
                g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
725
                goto error;
726
        }
727
        if(session->destroyed) {
728
                JANUS_LOG(LOG_ERR, "Session has already been destroyed...\n");
729
                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
730
                g_snprintf(error_cause, 512, "%s", "Session has already been destroyed...");
731
                goto error;
732
        }
733
        json_error_t error;
734
        root = json_loads(message, 0, &error);
735
        if(!root) {
736
                JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
737
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_JSON;
738
                g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
739
                goto error;
740
        }
741
        if(!json_is_object(root)) {
742
                JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
743
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_JSON;
744
                g_snprintf(error_cause, 512, "JSON error: not an object");
745
                goto error;
746
        }
747
        /* Get the request first */
748
        json_t *request = json_object_get(root, "request");
749
        if(!request) {
750
                JANUS_LOG(LOG_ERR, "Missing element (request)\n");
751
                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
752
                g_snprintf(error_cause, 512, "Missing element (request)");
753
                goto error;
754
        }
755
        if(!json_is_string(request)) {
756
                JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
757
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
758
                g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
759
                goto error;
760
        }
761
        /* Some requests ('create' and 'destroy') can be handled synchronously */
762
        const char *request_text = json_string_value(request);
763
        if(!strcasecmp(request_text, "update")) {
764
                /* Update list of available recordings, scanning the folder again */
765
                janus_recordplay_update_recordings_list();
766
                /* Send info back */
767
                response = json_object();
768
                json_object_set_new(response, "recordplay", json_string("ok"));
769
                goto plugin_response;
770
        } else if(!strcasecmp(request_text, "list")) {
771
                json_t *list = json_array();
772
                JANUS_LOG(LOG_VERB, "Request for the list of recordings\n");
773
                /* Return a list of all available recordings */
774
                janus_mutex_lock(&recordings_mutex);
775
                GHashTableIter iter;
776
                gpointer value;
777
                g_hash_table_iter_init(&iter, recordings);
778
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
779
                        janus_recordplay_recording *rec = value;
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", json_string(rec->arc_file ? "false" : "true"));
785
                        json_object_set_new(ml, "video", json_string(rec->vrc_file ? "false" : "true"));
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
                json_t *video_bitrate_max = json_object_get(root, "video-bitrate-max");
796
                if(video_bitrate_max) {
797
                        if(!json_is_integer(video_bitrate_max) || json_integer_value(video_bitrate_max) < 0) {
798
                                JANUS_LOG(LOG_ERR, "Invalid element (video-bitrate-max should be a positive integer)\n");
799
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
800
                                g_snprintf(error_cause, 512, "Invalid element (video-bitrate-max should be a positive integer)");
801
                                goto error;
802
                        }
803
                        session->video_bitrate = json_integer_value(video_bitrate_max);
804
                        JANUS_LOG(LOG_VERB, "Video bitrate has been set to %"SCNu64"\n", session->video_bitrate);
805
                }
806
                json_t *video_keyframe_interval= json_object_get(root, "video-keyframe-interval");
807
                if(video_keyframe_interval) {
808
                        if(!json_is_integer(video_keyframe_interval) || json_integer_value(video_keyframe_interval) < 0) {
809
                                JANUS_LOG(LOG_ERR, "Invalid element (video-keyframe-interval should be a positive integer)\n");
810
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
811
                                g_snprintf(error_cause, 512, "Invalid element (video-keyframe-interval should be a positive integer)");
812
                                goto error;
813
                        }
814
                        session->video_keyframe_interval = json_integer_value(video_keyframe_interval);
815
                        JANUS_LOG(LOG_VERB, "Video keyframe interval has been set to %u\n", session->video_keyframe_interval);
816
                }
817
                response = json_object();
818
                json_object_set_new(response, "recordplay", json_string("configure"));
819
                json_object_set_new(response, "status", json_string("ok"));
820
                /* Return a success, and also let the client be aware of what changed, to allow crosschecks */
821
                json_t *settings = json_object();
822
                json_object_set_new(settings, "video-keyframe-interval", json_integer(session->video_keyframe_interval)); 
823
                json_object_set_new(settings, "video-bitrate-max", json_integer(session->video_bitrate)); 
824
                json_object_set_new(response, "settings", settings); 
825
                goto plugin_response;
826
        } else if(!strcasecmp(request_text, "record") || !strcasecmp(request_text, "play")
827
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "stop")) {
828
                /* These messages are handled asynchronously */
829
                janus_recordplay_message *msg = calloc(1, sizeof(janus_recordplay_message));
830
                if(msg == NULL) {
831
                        JANUS_LOG(LOG_FATAL, "Memory error!\n");
832
                        error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
833
                        g_snprintf(error_cause, 512, "Memory error");
834
                        goto error;
835
                }
836

    
837
                g_free(message);
838
                msg->handle = handle;
839
                msg->transaction = transaction;
840
                msg->message = root;
841
                msg->sdp_type = sdp_type;
842
                msg->sdp = sdp;
843

    
844
                g_async_queue_push(messages, msg);
845

    
846
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
847
        } else {
848
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
849
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
850
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
851
                goto error;
852
        }
853

    
854
plugin_response:
855
                {
856
                        if (!response) {
857
                                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
858
                                g_snprintf(error_cause, 512, "Invalid response");
859
                                goto error;
860
                        }
861
                        if(root != NULL)
862
                                json_decref(root);
863
                        g_free(transaction);
864
                        g_free(message);
865
                        g_free(sdp_type);
866
                        g_free(sdp);
867

    
868
                        char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
869
                        json_decref(response);
870
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
871
                        g_free(response_text);
872
                        return result;
873
                }
874

    
875
error:
876
                {
877
                        if(root != NULL)
878
                                json_decref(root);
879
                        g_free(transaction);
880
                        g_free(message);
881
                        g_free(sdp_type);
882
                        g_free(sdp);
883

    
884
                        /* Prepare JSON error event */
885
                        json_t *event = json_object();
886
                        json_object_set_new(event, "recordplay", json_string("event"));
887
                        json_object_set_new(event, "error_code", json_integer(error_code));
888
                        json_object_set_new(event, "error", json_string(error_cause));
889
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
890
                        json_decref(event);
891
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, event_text);
892
                        g_free(event_text);
893
                        return result;
894
                }
895

    
896
}
897

    
898
void janus_recordplay_setup_media(janus_plugin_session *handle) {
899
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
900
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
901
                return;
902
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
903
        if(!session) {
904
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
905
                return;
906
        }
907
        if(session->destroyed)
908
                return;
909
        /* Take note of the fact that the session is now active */
910
        session->active = TRUE;
911
        if(!session->recorder) {
912
                GError *error = NULL;
913
                g_thread_try_new("recordplay playout thread", &janus_recordplay_playout_thread, session, &error);
914
                if(error != NULL) {
915
                        /* FIXME Should we notify this back to the user somehow? */
916
                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play playout thread...\n", error->code, error->message ? error->message : "??");
917
                }
918
        }
919
}
920

    
921
void janus_recordplay_send_rtcp_feedback(janus_plugin_session *handle, int video, char *buf, int len) {
922
        if(video != 1)
923
                return;        /* We just do this for video, for now */
924

    
925
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
926
        char rtcpbuf[200];
927

    
928
        /* Send a RR+SDES+REMB every five seconds, or ASAP while we are still
929
         * ramping up (first 4 RTP packets) */
930
        gint64 now = janus_get_monotonic_time();
931
        guint64 elapsed = now - session->video_remb_last;
932
        gboolean remb_rampup = session->video_remb_startup > 0;
933

    
934
        if(remb_rampup || (elapsed >= 5*G_USEC_PER_SEC)) {
935
                guint64 bitrate = session->video_bitrate;
936

    
937
                if(remb_rampup) {
938
                        bitrate = bitrate / session->video_remb_startup;
939
                        session->video_remb_startup--;
940
                }
941

    
942
                memset(rtcpbuf, 0, 200);
943
                /* FIXME First put a RR (fake)... */
944
                int rrlen = 32;
945
                rtcp_rr *rr = (rtcp_rr *)&rtcpbuf;
946
                rr->header.version = 2;
947
                rr->header.type = RTCP_RR;
948
                rr->header.rc = 1;
949
                rr->header.length = htons((rrlen/4)-1);
950
                /* ... then put a SDES... */
951
                int sdeslen = janus_rtcp_sdes((char *)(&rtcpbuf)+rrlen, 200-rrlen, "janusvideo", 10);
952
                if(sdeslen > 0) {
953
                        /* ... and then finally a REMB */
954
                        janus_rtcp_remb((char *)(&rtcpbuf)+rrlen+sdeslen, 24, bitrate);
955
                        gateway->relay_rtcp(handle, video, rtcpbuf, rrlen+sdeslen+24);
956
                }
957
                
958
                session->video_remb_last = now;
959
        }
960

    
961
        /* Request a keyframe on a regular basis (every session->video_keyframe_interval ms) */
962
        elapsed = now - session->video_keyframe_request_last;
963
        guint64 interval = (session->video_keyframe_interval / 1000) * G_USEC_PER_SEC;
964

    
965
        if(elapsed >= interval) {
966
                /* Send both a FIR and a PLI, just to be sure */
967
                memset(rtcpbuf, 0, 20);
968
                janus_rtcp_fir((char *)&rtcpbuf, 20, &session->video_fir_seq);
969
                gateway->relay_rtcp(handle, video, rtcpbuf, 20);
970
                memset(rtcpbuf, 0, 12);
971
                janus_rtcp_pli((char *)&rtcpbuf, 12);
972
                gateway->relay_rtcp(handle, video, rtcpbuf, 12);
973
                session->video_keyframe_request_last = now;
974
        }
975
}
976

    
977
void janus_recordplay_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
978
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
979
                return;
980
        if(gateway) {
981
                janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
982
                if(!session) {
983
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
984
                        return;
985
                }
986
                if(session->destroyed)
987
                        return;
988
                /* Are we recording? */
989
                if(session->recorder) {
990
                        if(video && session->vrc)
991
                                janus_recorder_save_frame(session->vrc, buf, len);
992
                        else if(!video && session->arc)
993
                                janus_recorder_save_frame(session->arc, buf, len);
994
                }
995

    
996
                janus_recordplay_send_rtcp_feedback(handle, video, buf, len);
997
        }
998
}
999

    
1000
void janus_recordplay_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1001
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1002
                return;
1003
}
1004

    
1005
void janus_recordplay_incoming_data(janus_plugin_session *handle, char *buf, int len) {
1006
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1007
                return;
1008
        /* FIXME We don't care */
1009
}
1010

    
1011
void janus_recordplay_slow_link(janus_plugin_session *handle, int uplink, int video) {
1012
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1013
                return;
1014

    
1015
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
1016
        if(!session || session->destroyed)
1017
                return;
1018

    
1019
        json_t *event = json_object();
1020
        json_object_set_new(event, "recordplay", json_string("event"));
1021
        json_t *result = json_object();
1022
        json_object_set_new(result, "status", json_string("slow_link"));
1023
        /* What is uplink for the server is downlink for the client, so turn the tables */
1024
        json_object_set_new(result, "current-bitrate", json_integer(session->video_bitrate));
1025
        json_object_set_new(result, "uplink", json_integer(uplink ? 0 : 1));
1026
        json_object_set_new(event, "result", result);
1027
        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1028
        json_decref(event);
1029
        json_decref(result);
1030
        event = NULL;
1031
        gateway->push_event(session->handle, &janus_recordplay_plugin, NULL, event_text, NULL, NULL);
1032
        g_free(event_text);
1033
}
1034

    
1035
void janus_recordplay_hangup_media(janus_plugin_session *handle) {
1036
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1037
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1038
                return;
1039
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
1040
        if(!session) {
1041
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1042
                return;
1043
        }
1044
        session->active = FALSE;
1045
        if(session->destroyed || !session->recorder || session->hangingup)
1046
                return;
1047
        session->hangingup = TRUE;
1048

    
1049
        /* Send an event to the browser and tell it's over */
1050
        json_t *event = json_object();
1051
        json_object_set_new(event, "recordplay", json_string("event"));
1052
        json_object_set_new(event, "result", json_string("done"));
1053
        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1054
        json_decref(event);
1055
        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1056
        int ret = gateway->push_event(handle, &janus_recordplay_plugin, NULL, event_text, NULL, NULL);
1057
        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1058
        g_free(event_text);
1059

    
1060
        /* FIXME Simulate a "stop" coming from the browser */
1061
        janus_recordplay_message *msg = calloc(1, sizeof(janus_recordplay_message));
1062
        msg->handle = handle;
1063
        msg->message = json_loads("{\"request\":\"stop\"}", 0, NULL);
1064
        msg->transaction = NULL;
1065
        msg->sdp_type = NULL;
1066
        msg->sdp = NULL;
1067
        g_async_queue_push(messages, msg);
1068
        /* Done */
1069
        session->hangingup = FALSE;
1070
}
1071

    
1072
/* Thread to handle incoming messages */
1073
static void *janus_recordplay_handler(void *data) {
1074
        JANUS_LOG(LOG_VERB, "Joining Record&Play handler thread\n");
1075
        janus_recordplay_message *msg = NULL;
1076
        int error_code = 0;
1077
        char *error_cause = calloc(512, sizeof(char));
1078
        if(error_cause == NULL) {
1079
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
1080
                return NULL;
1081
        }
1082
        json_t *root = NULL;
1083
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1084
                if(!messages || (msg = g_async_queue_try_pop(messages)) == NULL) {
1085
                        usleep(50000);
1086
                        continue;
1087
                }
1088
                janus_recordplay_session *session = (janus_recordplay_session *)msg->handle->plugin_handle;
1089
                if(!session) {
1090
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1091
                        janus_recordplay_message_free(msg);
1092
                        continue;
1093
                }
1094
                if(session->destroyed) {
1095
                        janus_recordplay_message_free(msg);
1096
                        continue;
1097
                }
1098
                /* Handle request */
1099
                error_code = 0;
1100
                root = NULL;
1101
                if(msg->message == NULL) {
1102
                        JANUS_LOG(LOG_ERR, "No message??\n");
1103
                        error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
1104
                        g_snprintf(error_cause, 512, "%s", "No message??");
1105
                        goto error;
1106
                }
1107
                root = msg->message;
1108
                /* Get the request first */
1109
                json_t *request = json_object_get(root, "request");
1110
                if(!request) {
1111
                        JANUS_LOG(LOG_ERR, "Missing element (request)\n");
1112
                        error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1113
                        g_snprintf(error_cause, 512, "Missing element (request)");
1114
                        goto error;
1115
                }
1116
                if(!json_is_string(request)) {
1117
                        JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
1118
                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1119
                        g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
1120
                        goto error;
1121
                }
1122
                const char *request_text = json_string_value(request);
1123
                json_t *event = NULL;
1124
                json_t *result = NULL;
1125
                char *sdp = NULL;
1126
                const char *filename_text = NULL;
1127
                if(!strcasecmp(request_text, "record")) {
1128
                        if(!msg->sdp) {
1129
                                JANUS_LOG(LOG_ERR, "Missing SDP offer\n");
1130
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1131
                                g_snprintf(error_cause, 512, "Missing SDP offer");
1132
                                goto error;
1133
                        }
1134
                        json_t *name = json_object_get(root, "name");
1135
                        if(!name) {
1136
                                JANUS_LOG(LOG_ERR, "Missing element (name)\n");
1137
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1138
                                g_snprintf(error_cause, 512, "Missing element (name)");
1139
                                goto error;
1140
                        }
1141
                        if(!json_is_string(name)) {
1142
                                JANUS_LOG(LOG_ERR, "Invalid element (name should be a string)\n");
1143
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1144
                                g_snprintf(error_cause, 512, "Invalid element (name should be a string)");
1145
                                goto error;
1146
                        }
1147
                        const char *name_text = json_string_value(name);
1148
                        if(strlen(name_text) == 0) {
1149
                                JANUS_LOG(LOG_ERR, "Invalid element (name is an empty string)\n");
1150
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1151
                                g_snprintf(error_cause, 512, "Invalid element (name is an empty string)");
1152
                                goto error;
1153
                        }
1154
                        json_t *filename = json_object_get(root, "filename");
1155
                        if(filename) {
1156
                                if(!json_is_string(name)) {
1157
                                        JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
1158
                                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1159
                                        g_snprintf(error_cause, 512, "Invalid element (filename should be a string)");
1160
                                        goto error;
1161
                                }
1162
                                filename_text = json_string_value(filename);
1163
                        }
1164
                        guint64 id = 0;
1165
                        while(id == 0) {
1166
                                id = g_random_int();
1167
                                if(g_hash_table_lookup(recordings, GUINT_TO_POINTER(id)) != NULL) {
1168
                                        /* Room ID already taken, try another one */
1169
                                        id = 0;
1170
                                }
1171
                        }
1172
                        JANUS_LOG(LOG_VERB, "Starting new recording with ID %"SCNu64"\n", id);
1173
                        janus_recordplay_recording *rec = (janus_recordplay_recording *)calloc(1, sizeof(janus_recordplay_recording));
1174
                        rec->id = id;
1175
                        rec->name = g_strdup(name_text);
1176
                        rec->viewers = NULL;
1177
                        rec->destroyed = 0;
1178
                        janus_mutex_init(&rec->mutex);
1179
                        /* Create a date string */
1180
                        time_t t = time(NULL);
1181
                        struct tm *tmv = localtime(&t);
1182
                        char outstr[200];
1183
                        strftime(outstr, sizeof(outstr), "%Y-%m-%d %H:%M:%S", tmv);
1184
                        rec->date = g_strdup(outstr);
1185
                        if(strstr(msg->sdp, "m=audio")) {
1186
                                char filename[256];
1187
                                if(filename_text != NULL) {
1188
                                        g_snprintf(filename, 256, "%s-audio", filename_text);
1189
                                } else {
1190
                                        g_snprintf(filename, 256, "rec-%"SCNu64"-audio", id);
1191
                                }
1192
                                rec->arc_file = g_strdup(filename);
1193
                                session->arc = janus_recorder_create(recordings_path, 0, rec->arc_file);
1194
                        }
1195
                        if(strstr(msg->sdp, "m=video")) {
1196
                                char filename[256];
1197
                                if(filename_text != NULL) {
1198
                                        g_snprintf(filename, 256, "%s-video", filename_text);
1199
                                } else {
1200
                                        g_snprintf(filename, 256, "rec-%"SCNu64"-video", id);
1201
                                }
1202
                                rec->vrc_file = g_strdup(filename);
1203
                                session->vrc = janus_recorder_create(recordings_path, 1, rec->vrc_file);
1204
                        }
1205
                        session->recorder = TRUE;
1206
                        session->recording = rec;
1207
                        janus_mutex_lock(&recordings_mutex);
1208
                        g_hash_table_insert(recordings, GINT_TO_POINTER(rec->id), rec);
1209
                        janus_mutex_unlock(&recordings_mutex);
1210
                        /* We need to prepare an answer */
1211
                        int opus_pt = 0, vp8_pt = 0;
1212
                        opus_pt = janus_get_opus_pt(msg->sdp);
1213
                        JANUS_LOG(LOG_VERB, "Opus payload type is %d\n", opus_pt);
1214
                        vp8_pt = janus_get_vp8_pt(msg->sdp);
1215
                        JANUS_LOG(LOG_VERB, "VP8 payload type is %d\n", vp8_pt);
1216
                        char sdptemp[1024], audio_mline[256], video_mline[512];
1217
                        if(opus_pt > 0) {
1218
                                g_snprintf(audio_mline, 256, sdp_a_template,
1219
                                        opus_pt,                                                /* Opus payload type */
1220
                                        "recvonly",                                                /* Recording is recvonly */
1221
                                        opus_pt);                                                 /* Opus payload type */
1222
                        } else {
1223
                                audio_mline[0] = '\0';
1224
                        }
1225
                        if(vp8_pt > 0) {
1226
                                g_snprintf(video_mline, 512, sdp_v_template,
1227
                                        vp8_pt,                                                        /* VP8 payload type */
1228
                                        "recvonly",                                                /* Recording is recvonly */
1229
                                        vp8_pt,                                                 /* VP8 payload type */
1230
                                        vp8_pt,                                                 /* VP8 payload type */
1231
                                        vp8_pt,                                                 /* VP8 payload type */
1232
                                        vp8_pt,                                                 /* VP8 payload type */
1233
                                        vp8_pt);                                                 /* VP8 payload type */
1234
                        } else {
1235
                                video_mline[0] = '\0';
1236
                        }
1237
                        g_snprintf(sdptemp, 1024, sdp_template,
1238
                                janus_get_monotonic_time(),                /* We need current time here */
1239
                                janus_get_monotonic_time(),                /* We need current time here */
1240
                                session->recording->name,                /* Playout session */
1241
                                audio_mline,                                        /* Audio m-line, if any */
1242
                                video_mline);                                        /* Video m-line, if any */
1243
                        sdp = g_strdup(sdptemp);
1244
                        JANUS_LOG(LOG_VERB, "Going to answer this SDP:\n%s\n", sdp);
1245
                        /* Done! */
1246
                        result = json_object();
1247
                        json_object_set_new(result, "status", json_string("recording"));
1248
                        json_object_set_new(result, "id", json_integer(id));
1249
                } else if(!strcasecmp(request_text, "play")) {
1250
                        if(msg->sdp) {
1251
                                JANUS_LOG(LOG_ERR, "A play request can't contain an SDP\n");
1252
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1253
                                g_snprintf(error_cause, 512, "A play request can't contain an SDP");
1254
                                goto error;
1255
                        }
1256
                        JANUS_LOG(LOG_VERB, "Replaying a recording\n");
1257
                        json_t *id = json_object_get(root, "id");
1258
                        if(!id) {
1259
                                JANUS_LOG(LOG_ERR, "Missing element (id)\n");
1260
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1261
                                g_snprintf(error_cause, 512, "Missing element (id)");
1262
                                goto error;
1263
                        }
1264
                        if(!json_is_integer(id) || json_integer_value(id) < 0) {
1265
                                JANUS_LOG(LOG_ERR, "Invalid element (id should be a positive integer)\n");
1266
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1267
                                g_snprintf(error_cause, 512, "Invalid element (id should be a positive integer)");
1268
                                goto error;
1269
                        }
1270
                        guint64 id_value = json_integer_value(id);
1271
                        /* Look for this recording */
1272
                        janus_mutex_lock(&recordings_mutex);
1273
                        janus_recordplay_recording *rec = g_hash_table_lookup(recordings, GINT_TO_POINTER(id_value));
1274
                        janus_mutex_unlock(&recordings_mutex);
1275
                        if(rec == NULL || rec->destroyed) {
1276
                                JANUS_LOG(LOG_ERR, "No such recording\n");
1277
                                error_code = JANUS_RECORDPLAY_ERROR_NOT_FOUND;
1278
                                g_snprintf(error_cause, 512, "No such recording");
1279
                                goto error;
1280
                        }
1281
                        /* Access the frames */
1282
                        if(rec->arc_file) {
1283
                                session->aframes = janus_recordplay_get_frames(recordings_path, rec->arc_file);
1284
                                if(session->aframes == NULL) {
1285
                                        JANUS_LOG(LOG_ERR, "Error opening audio recording\n");
1286
                                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_RECORDING;
1287
                                        g_snprintf(error_cause, 512, "Error opening audio recording");
1288
                                        goto error;
1289
                                }
1290
                        }
1291
                        if(rec->vrc_file) {
1292
                                session->vframes = janus_recordplay_get_frames(recordings_path, rec->vrc_file);
1293
                                if(session->vframes == NULL) {
1294
                                        JANUS_LOG(LOG_ERR, "Error opening video recording\n");
1295
                                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_RECORDING;
1296
                                        g_snprintf(error_cause, 512, "Error opening video recording");
1297
                                        goto error;
1298
                                }
1299
                        }
1300
                        session->recording = rec;
1301
                        session->recorder = FALSE;
1302
                        rec->viewers = g_list_append(rec->viewers, session);
1303
                        /* We need to prepare an offer */
1304
                        char sdptemp[1024], audio_mline[256], video_mline[512];
1305
                        if(session->recording->arc_file) {
1306
                                g_snprintf(audio_mline, 256, sdp_a_template,
1307
                                        OPUS_PT,                                                /* Opus payload type */
1308
                                        "sendonly",                                                /* Playout is sendonly */
1309
                                        OPUS_PT);                                                 /* Opus payload type */
1310
                        } else {
1311
                                audio_mline[0] = '\0';
1312
                        }
1313
                        if(session->recording->vrc_file) {
1314
                                g_snprintf(video_mline, 512, sdp_v_template,
1315
                                        VP8_PT,                                                        /* VP8 payload type */
1316
                                        "sendonly",                                                /* Playout is sendonly */
1317
                                        VP8_PT,                                                 /* VP8 payload type */
1318
                                        VP8_PT,                                                 /* VP8 payload type */
1319
                                        VP8_PT,                                                 /* VP8 payload type */
1320
                                        VP8_PT,                                                 /* VP8 payload type */
1321
                                        VP8_PT);                                                 /* VP8 payload type */
1322
                        } else {
1323
                                video_mline[0] = '\0';
1324
                        }
1325
                        g_snprintf(sdptemp, 1024, sdp_template,
1326
                                janus_get_monotonic_time(),                /* We need current time here */
1327
                                janus_get_monotonic_time(),                /* We need current time here */
1328
                                session->recording->name,                /* Playout session */
1329
                                audio_mline,                                        /* Audio m-line, if any */
1330
                                video_mline);                                        /* Video m-line, if any */
1331
                        sdp = g_strdup(sdptemp);
1332
                        JANUS_LOG(LOG_VERB, "Going to offer this SDP:\n%s\n", sdp);
1333
                        /* Done! */
1334
                        result = json_object();
1335
                        json_object_set_new(result, "status", json_string("preparing"));
1336
                        json_object_set_new(result, "id", json_integer(id_value));
1337
                } else if(!strcasecmp(request_text, "start")) {
1338
                        if(!session->aframes && !session->vframes) {
1339
                                JANUS_LOG(LOG_ERR, "Not a playout session, can't start\n");
1340
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_STATE;
1341
                                g_snprintf(error_cause, 512, "Not a playout session, can't start");
1342
                                goto error;
1343
                        }
1344
                        /* Just a final message we make use of, e.g., to receive an ANSWER to our OFFER for a playout */
1345
                        if(!msg->sdp) {
1346
                                JANUS_LOG(LOG_ERR, "Missing SDP answer\n");
1347
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1348
                                g_snprintf(error_cause, 512, "Missing SDP answer");
1349
                                goto error;
1350
                        }
1351
                        /* Done! */
1352
                        result = json_object();
1353
                        json_object_set_new(result, "status", json_string("playing"));
1354
                } else if(!strcasecmp(request_text, "stop")) {
1355
                        /* Stop the recording/playout */
1356
                        session->active = FALSE;
1357
                        if(session->arc) {
1358
                                janus_recorder_close(session->arc);
1359
                                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1360
                                janus_recorder_free(session->arc);
1361
                        }
1362
                        session->arc = NULL;
1363
                        if(session->vrc) {
1364
                                janus_recorder_close(session->vrc);
1365
                                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1366
                                janus_recorder_free(session->vrc);
1367
                        }
1368
                        session->vrc = NULL;
1369
                        if(session->recorder) {
1370
                                /* Create a .nfo file for this recording */
1371
                                char nfofile[1024], nfo[1024];
1372
                                g_snprintf(nfofile, 1024, "%s/%"SCNu64".nfo", recordings_path, session->recording->id);
1373
                                FILE *file = fopen(nfofile, "wt");
1374
                                if(file == NULL) {
1375
                                        JANUS_LOG(LOG_ERR, "Error creating file %s...\n", nfofile);
1376
                                } else {
1377
                                        if(session->recording->arc_file && session->recording->vrc_file) {
1378
                                                g_snprintf(nfo, 1024,
1379
                                                        "[%"SCNu64"]\r\n"
1380
                                                        "name = %s\r\n"
1381
                                                        "date = %s\r\n"
1382
                                                        "audio = %s.mjr\r\n"
1383
                                                        "video = %s.mjr\r\n",
1384
                                                                session->recording->id, session->recording->name, session->recording->date,
1385
                                                                session->recording->arc_file, session->recording->vrc_file);
1386
                                        } else if(session->recording->arc_file) {
1387
                                                g_snprintf(nfo, 1024,
1388
                                                        "[%"SCNu64"]\r\n"
1389
                                                        "name = %s\r\n"
1390
                                                        "date = %s\r\n"
1391
                                                        "audio = %s.mjr\r\n",
1392
                                                                session->recording->id, session->recording->name, session->recording->date,
1393
                                                                session->recording->arc_file);
1394
                                        } else if(session->recording->vrc_file) {
1395
                                                g_snprintf(nfo, 1024,
1396
                                                        "[%"SCNu64"]\r\n"
1397
                                                        "name = %s\r\n"
1398
                                                        "date = %s\r\n"
1399
                                                        "video = %s.mjr\r\n",
1400
                                                                session->recording->id, session->recording->name, session->recording->date,
1401
                                                                session->recording->vrc_file);
1402
                                        }
1403
                                        /* Write to the file now */
1404
                                        fwrite(nfo, strlen(nfo), sizeof(char), file);
1405
                                        fclose(file);
1406
                                }
1407
                        }
1408
                        /* Done! */
1409
                        result = json_object();
1410
                        json_object_set_new(result, "status", json_string("stopped"));
1411
                        if(session->recording)
1412
                                json_object_set_new(result, "id", json_integer(session->recording->id));
1413
                } else {
1414
                        JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
1415
                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
1416
                        g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
1417
                        goto error;
1418
                }
1419

    
1420
                /* Any SDP to handle? */
1421
                if(msg->sdp) {
1422
                        session->firefox = strstr(msg->sdp, "Mozilla") ? TRUE : FALSE;
1423
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1424
                }
1425

    
1426
                /* Prepare JSON event */
1427
                event = json_object();
1428
                json_object_set_new(event, "recordplay", json_string("event"));
1429
                if(result != NULL)
1430
                        json_object_set_new(event, "result", result);
1431
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1432
                json_decref(event);
1433
                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1434
                if(!sdp) {
1435
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, NULL, NULL);
1436
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1437
                } else {
1438
                        const char *type = session->recorder ? "answer" : "offer";
1439
                        /* How long will the gateway take to push the event? */
1440
                        gint64 start = janus_get_monotonic_time();
1441
                        int res = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, type, sdp);
1442
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
1443
                                res, janus_get_monotonic_time()-start);
1444
                        g_free(sdp);
1445
                }
1446
                g_free(event_text);
1447
                janus_recordplay_message_free(msg);
1448
                continue;
1449
                
1450
error:
1451
                {
1452
                        /* Prepare JSON error event */
1453
                        json_t *event = json_object();
1454
                        json_object_set_new(event, "recordplay", json_string("event"));
1455
                        json_object_set_new(event, "error_code", json_integer(error_code));
1456
                        json_object_set_new(event, "error", json_string(error_cause));
1457
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1458
                        json_decref(event);
1459
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1460
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, NULL, NULL);
1461
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1462
                        g_free(event_text);
1463
                        janus_recordplay_message_free(msg);
1464
                }
1465
        }
1466
        g_free(error_cause);
1467
        JANUS_LOG(LOG_VERB, "LeavingRecord&Play handler thread\n");
1468
        return NULL;
1469
}
1470

    
1471
void janus_recordplay_update_recordings_list(void) {
1472
        if(recordings_path == NULL)
1473
                return;
1474
        JANUS_LOG(LOG_VERB, "Updating recordings list in %s\n", recordings_path);
1475
        janus_mutex_lock(&recordings_mutex);
1476
        /* First of all, let's keep track of which recordings are currently available */
1477
        GList *old_recordings = NULL;
1478
        if(recordings != NULL && g_hash_table_size(recordings) > 0) {
1479
                GHashTableIter iter;
1480
                gpointer value;
1481
                g_hash_table_iter_init(&iter, recordings);
1482
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
1483
                        janus_recordplay_recording *rec = value;
1484
                        if(rec) {
1485
                                old_recordings = g_list_append(old_recordings, GUINT_TO_POINTER(rec->id));
1486
                        }
1487
                }
1488
                janus_mutex_unlock(&recordings_mutex);
1489
        }
1490
        /* Open dir */
1491
        DIR *dir = opendir(recordings_path);
1492
        if(!dir) {
1493
                JANUS_LOG(LOG_ERR, "Couldn't open folder...\n");
1494
                g_list_free(old_recordings);
1495
                return;
1496
        }
1497
        struct dirent *recent = NULL;
1498
        char recpath[1024];
1499
        while((recent = readdir(dir))) {
1500
                int len = strlen(recent->d_name);
1501
                if(len < 4)
1502
                        continue;
1503
                if(strcasecmp(recent->d_name+len-4, ".nfo"))
1504
                        continue;
1505
                JANUS_LOG(LOG_VERB, "Importing recording '%s'...\n", recent->d_name);
1506
                memset(recpath, 0, 1024);
1507
                g_snprintf(recpath, 1024, "%s/%s", recordings_path, recent->d_name);
1508
                janus_config *nfo = janus_config_parse(recpath);
1509
                if(nfo == NULL) { 
1510
                        JANUS_LOG(LOG_ERR, "Invalid recording '%s'...\n", recent->d_name);
1511
                        continue;
1512
                }
1513
                janus_config_category *cat = janus_config_get_categories(nfo);
1514
                if(cat == NULL) {
1515
                        JANUS_LOG(LOG_WARN, "No recording info in '%s', skipping...\n", recent->d_name);
1516
                        janus_config_destroy(nfo);
1517
                        continue;
1518
                }
1519
                guint64 id = atol(cat->name);
1520
                if(id == 0) {
1521
                        JANUS_LOG(LOG_WARN, "Invalid ID, skipping...\n");
1522
                        janus_config_destroy(nfo);
1523
                        continue;
1524
                }
1525
                if(g_hash_table_lookup(recordings, GUINT_TO_POINTER(id)) != NULL) {
1526
                        JANUS_LOG(LOG_VERB, "Skipping recording with ID %"SCNu64", it's already in the list...\n", id);
1527
                        janus_config_destroy(nfo);
1528
                        /* Mark that we updated this recording */
1529
                        old_recordings = g_list_remove(old_recordings, GUINT_TO_POINTER(id));
1530
                        continue;
1531
                }
1532
                janus_config_item *name = janus_config_get_item(cat, "name");
1533
                janus_config_item *date = janus_config_get_item(cat, "date");
1534
                janus_config_item *audio = janus_config_get_item(cat, "audio");
1535
                janus_config_item *video = janus_config_get_item(cat, "video");
1536
                if(!name || !name->value || strlen(name->value) == 0 || !date || !date->value || strlen(date->value) == 0) {
1537
                        JANUS_LOG(LOG_WARN, "Invalid info for recording %"SCNu64", skipping...\n", id);
1538
                        janus_config_destroy(nfo);
1539
                        continue;
1540
                }
1541
                if((!audio || !audio->value) && (!video || !video->value)) {
1542
                        JANUS_LOG(LOG_WARN, "No audio and no video in recording %"SCNu64", skipping...\n", id);
1543
                        janus_config_destroy(nfo);
1544
                        continue;
1545
                }
1546
                janus_recordplay_recording *rec = (janus_recordplay_recording *)calloc(1, sizeof(janus_recordplay_recording));
1547
                rec->id = id;
1548
                rec->name = g_strdup(name->value);
1549
                rec->date = g_strdup(date->value);
1550
                if(audio && audio->value) {
1551
                        rec->arc_file = g_strdup(audio->value);
1552
                        if(strstr(rec->arc_file, ".mjr")) {
1553
                                char *ext = strstr(rec->arc_file, ".mjr");
1554
                                *ext = '\0';
1555
                        }
1556
                }
1557
                if(video && video->value) {
1558
                        rec->vrc_file = g_strdup(video->value);
1559
                        if(strstr(rec->vrc_file, ".mjr")) {
1560
                                char *ext = strstr(rec->vrc_file, ".mjr");
1561
                                *ext = '\0';
1562
                        }
1563
                }
1564
                rec->viewers = NULL;
1565
                rec->destroyed = 0;
1566
                janus_mutex_init(&rec->mutex);
1567
                
1568
                janus_config_destroy(nfo);
1569

    
1570
                /* Add to the list of recordings */
1571
                g_hash_table_insert(recordings, GUINT_TO_POINTER(id), rec);
1572
        }
1573
        closedir(dir);
1574
        /* Now let's check if any of the previously existing recordings was removed */
1575
        if(old_recordings != NULL) {
1576
                while(old_recordings != NULL) {
1577
                        guint64 id = GPOINTER_TO_UINT(old_recordings->data);
1578
                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" is not available anymore, removing...\n", id);
1579
                        janus_recordplay_recording *old_rec = g_hash_table_lookup(recordings, GUINT_TO_POINTER(id));
1580
                        if(old_rec != NULL) {
1581
                                /* Remove it */
1582
                                g_hash_table_remove(recordings, GUINT_TO_POINTER(id));
1583
                                /* Only destroy the object if no one's watching, though */
1584
                                janus_mutex_lock(&old_rec->mutex);
1585
                                old_rec->destroyed = janus_get_monotonic_time();
1586
                                if(old_rec->viewers == NULL) {
1587
                                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" has no viewers, destroying it now\n", id);
1588
                                        janus_mutex_unlock(&old_rec->mutex);
1589
                                        g_free(old_rec->name);
1590
                                        g_free(old_rec->date);
1591
                                        g_free(old_rec->arc_file);
1592
                                        g_free(old_rec->vrc_file);
1593
                                        g_free(old_rec);
1594
                                } else {
1595
                                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" still has viewers, delaying its destruction until later\n", id);
1596
                                        janus_mutex_unlock(&old_rec->mutex);
1597
                                }
1598
                        }
1599
                        old_recordings = old_recordings->next;
1600
                }
1601
                g_list_free(old_recordings);
1602
        }
1603
        janus_mutex_unlock(&recordings_mutex);
1604
}
1605

    
1606
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename) {
1607
        if(!dir || !filename)
1608
                return NULL;
1609
        /* Open the file */
1610
        char source[1024];
1611
        if(strstr(filename, ".mjr"))
1612
                g_snprintf(source, 1024, "%s/%s", dir, filename);
1613
        else
1614
                g_snprintf(source, 1024, "%s/%s.mjr", dir, filename);
1615
        FILE *file = fopen(source, "rb");
1616
        if(file == NULL) {
1617
                JANUS_LOG(LOG_ERR, "Could not open file %s\n", source);
1618
                return NULL;
1619
        }
1620
        fseek(file, 0L, SEEK_END);
1621
        long fsize = ftell(file);
1622
        fseek(file, 0L, SEEK_SET);
1623
        JANUS_LOG(LOG_VERB, "File is %zu bytes\n", fsize);
1624

    
1625
        /* Pre-parse */
1626
        JANUS_LOG(LOG_VERB, "Pre-parsing file %s to generate ordered index...\n", source);
1627
        gboolean parsed_header = FALSE;
1628
        int bytes = 0;
1629
        long offset = 0;
1630
        uint16_t len = 0, count = 0;
1631
        uint32_t first_ts = 0, last_ts = 0, reset = 0;        /* To handle whether there's a timestamp reset in the recording */
1632
        char prebuffer[1500];
1633
        memset(prebuffer, 0, 1500);
1634
        /* Let's look for timestamp resets first */
1635
        while(offset < fsize) {
1636
                /* Read frame header */
1637
                fseek(file, offset, SEEK_SET);
1638
                bytes = fread(prebuffer, sizeof(char), 8, file);
1639
                if(bytes != 8 || prebuffer[0] != 'M') {
1640
                        JANUS_LOG(LOG_ERR, "Invalid header...\n");
1641
                        fclose(file);
1642
                        return NULL;
1643
                }
1644
                if(prebuffer[1] == 'E') {
1645
                        /* Either the old .mjr format header ('MEETECHO' header followed by 'audio' or 'video'), or a frame */
1646
                        offset += 8;
1647
                        bytes = fread(&len, sizeof(uint16_t), 1, file);
1648
                        len = ntohs(len);
1649
                        offset += 2;
1650
                        if(len == 5 && !parsed_header) {
1651
                                /* This is the main header */
1652
                                parsed_header = TRUE;
1653
                                JANUS_LOG(LOG_VERB, "Old .mjr header format\n");
1654
                                bytes = fread(prebuffer, sizeof(char), 5, file);
1655
                                if(prebuffer[0] == 'v') {
1656
                                        JANUS_LOG(LOG_INFO, "This is a video recording, assuming VP8\n");
1657
                                } else if(prebuffer[0] == 'a') {
1658
                                        JANUS_LOG(LOG_INFO, "This is an audio recording, assuming Opus\n");
1659
                                } else {
1660
                                        JANUS_LOG(LOG_WARN, "Unsupported recording media type...\n");
1661
                                        fclose(file);
1662
                                        return NULL;
1663
                                }
1664
                                offset += len;
1665
                                continue;
1666
                        } else if(len < 12) {
1667
                                /* Not RTP, skip */
1668
                                JANUS_LOG(LOG_VERB, "Skipping packet (not RTP?)\n");
1669
                                offset += len;
1670
                                continue;
1671
                        }
1672
                } else if(prebuffer[1] == 'J') {
1673
                        /* New .mjr format, the header may contain useful info */
1674
                        offset += 8;
1675
                        bytes = fread(&len, sizeof(uint16_t), 1, file);
1676
                        len = ntohs(len);
1677
                        offset += 2;
1678
                        if(len > 0 && !parsed_header) {
1679
                                /* This is the info header */
1680
                                JANUS_LOG(LOG_VERB, "New .mjr header format\n");
1681
                                bytes = fread(prebuffer, sizeof(char), len, file);
1682
                                parsed_header = TRUE;
1683
                                prebuffer[len] = '\0';
1684
                                json_error_t error;
1685
                                json_t *info = json_loads(prebuffer, 0, &error);
1686
                                if(!info) {
1687
                                        JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
1688
                                        JANUS_LOG(LOG_WARN, "Error parsing info header...\n");
1689
                                        fclose(file);
1690
                                        return NULL;
1691
                                }
1692
                                /* Is it audio or video? */
1693
                                json_t *type = json_object_get(info, "t");
1694
                                if(!type || !json_is_string(type)) {
1695
                                        JANUS_LOG(LOG_WARN, "Missing/invalid recording type in info header...\n");
1696
                                        fclose(file);
1697
                                        return NULL;
1698
                                }
1699
                                const char *t = json_string_value(type);
1700
                                int video = 0;
1701
                                gint64 c_time = 0, w_time = 0;
1702
                                if(!strcasecmp(t, "v")) {
1703
                                        video = 1;
1704
                                } else if(!strcasecmp(t, "a")) {
1705
                                        video = 0;
1706
                                } else {
1707
                                        JANUS_LOG(LOG_WARN, "Unsupported recording type '%s' in info header...\n", t);
1708
                                        fclose(file);
1709
                                        return NULL;
1710
                                }
1711
                                /* What codec was used? */
1712
                                json_t *codec = json_object_get(info, "c");
1713
                                if(!codec || !json_is_string(codec)) {
1714
                                        JANUS_LOG(LOG_WARN, "Missing recording codec in info header...\n");
1715
                                        fclose(file);
1716
                                        return NULL;
1717
                                }
1718
                                const char *c = json_string_value(codec);
1719
                                if(video && strcasecmp(c, "vp8")) {
1720
                                        JANUS_LOG(LOG_WARN, "The post-processor only suupports VP8 video for now (was '%s')...\n", c);
1721
                                        fclose(file);
1722
                                        return NULL;
1723
                                } else if(!video && strcasecmp(c, "opus")) {
1724
                                        JANUS_LOG(LOG_WARN, "The post-processor only suupports Opus audio for now (was '%s')...\n", c);
1725
                                        fclose(file);
1726
                                        return NULL;
1727
                                }
1728
                                /* When was the file created? */
1729
                                json_t *created = json_object_get(info, "s");
1730
                                if(!created || !json_is_integer(created)) {
1731
                                        JANUS_LOG(LOG_WARN, "Missing recording created time in info header...\n");
1732
                                        fclose(file);
1733
                                        return NULL;
1734
                                }
1735
                                c_time = json_integer_value(created);
1736
                                /* When was the first frame written? */
1737
                                json_t *written = json_object_get(info, "u");
1738
                                if(!written || !json_is_integer(written)) {
1739
                                        JANUS_LOG(LOG_WARN, "Missing recording written time in info header...\n");
1740
                                        fclose(file);
1741
                                        return NULL;
1742
                                }
1743
                                w_time = json_integer_value(created);
1744
                                /* Summary */
1745
                                JANUS_LOG(LOG_VERB, "This is %s recording:\n", video ? "a video" : "an audio");
1746
                                JANUS_LOG(LOG_VERB, "  -- Codec:   %s\n", c);
1747
                                JANUS_LOG(LOG_VERB, "  -- Created: %"SCNi64"\n", c_time);
1748
                                JANUS_LOG(LOG_VERB, "  -- Written: %"SCNi64"\n", w_time);
1749
                        }
1750
                } else {
1751
                        JANUS_LOG(LOG_ERR, "Invalid header...\n");
1752
                        fclose(file);
1753
                        return NULL;
1754
                }
1755
                /* Only read RTP header */
1756
                bytes = fread(prebuffer, sizeof(char), 16, file);
1757
                rtp_header *rtp = (rtp_header *)prebuffer;
1758
                if(last_ts == 0) {
1759
                        first_ts = ntohl(rtp->timestamp);
1760
                        if(first_ts > 1000*1000)        /* Just used to check whether a packet is pre- or post-reset */
1761
                                first_ts -= 1000*1000;
1762
                } else {
1763
                        if(ntohl(rtp->timestamp) < last_ts) {
1764
                                /* The new timestamp is smaller than the next one, is it a timestamp reset or simply out of order? */
1765
                                if(last_ts-ntohl(rtp->timestamp) > 2*1000*1000*1000) {
1766
                                        reset = ntohl(rtp->timestamp);
1767
                                        JANUS_LOG(LOG_VERB, "Timestamp reset: %"SCNu32"\n", reset);
1768
                                }
1769
                        } else if(ntohl(rtp->timestamp) < reset) {
1770
                                JANUS_LOG(LOG_VERB, "Updating timestamp reset: %"SCNu32" (was %"SCNu32")\n", ntohl(rtp->timestamp), reset);
1771
                                reset = ntohl(rtp->timestamp);
1772
                        }
1773
                }
1774
                last_ts = ntohl(rtp->timestamp);
1775
                /* Skip data for now */
1776
                offset += len;
1777
        }
1778
        /* Now let's parse the frames and order them */
1779
        offset = 0;
1780
        janus_recordplay_frame_packet *list = NULL, *last = NULL;
1781
        while(offset < fsize) {
1782
                /* Read frame header */
1783
                fseek(file, offset, SEEK_SET);
1784
                bytes = fread(prebuffer, sizeof(char), 8, file);
1785
                prebuffer[8] = '\0';
1786
                JANUS_LOG(LOG_HUGE, "Header: %s\n", prebuffer);
1787
                offset += 8;
1788
                bytes = fread(&len, sizeof(uint16_t), 1, file);
1789
                len = ntohs(len);
1790
                JANUS_LOG(LOG_HUGE, "  -- Length: %"SCNu16"\n", len);
1791
                offset += 2;
1792
                if(prebuffer[1] == 'J' || len < 12) {
1793
                        /* Not RTP, skip */
1794
                        JANUS_LOG(LOG_HUGE, "  -- Not RTP, skipping\n");
1795
                        offset += len;
1796
                        continue;
1797
                }
1798
                /* Only read RTP header */
1799
                bytes = fread(prebuffer, sizeof(char), 16, file);
1800
                rtp_header *rtp = (rtp_header *)prebuffer;
1801
                JANUS_LOG(LOG_HUGE, "  -- RTP packet (ssrc=%"SCNu32", pt=%"SCNu16", ext=%"SCNu16", seq=%"SCNu16", ts=%"SCNu32")\n",
1802
                                ntohl(rtp->ssrc), rtp->type, rtp->extension, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
1803
                /* Generate frame packet and insert in the ordered list */
1804
                janus_recordplay_frame_packet *p = calloc(1, sizeof(janus_recordplay_frame_packet));
1805
                if(p == NULL) {
1806
                        JANUS_LOG(LOG_ERR, "Memory error!\n");
1807
                        fclose(file);
1808
                        return NULL;
1809
                }
1810
                p->seq = ntohs(rtp->seq_number);
1811
                if(reset == 0) {
1812
                        /* Simple enough... */
1813
                        p->ts = ntohl(rtp->timestamp);
1814
                } else {
1815
                        /* Is this packet pre- or post-reset? */
1816
                        if(ntohl(rtp->timestamp) > first_ts) {
1817
                                /* Pre-reset... */
1818
                                p->ts = ntohl(rtp->timestamp);
1819
                        } else {
1820
                                /* Post-reset... */
1821
                                uint64_t max32 = UINT32_MAX;
1822
                                max32++;
1823
                                p->ts = max32+ntohl(rtp->timestamp);
1824
                        }
1825
                }
1826
                p->len = len;
1827
                p->offset = offset;
1828
                p->next = NULL;
1829
                p->prev = NULL;
1830
                if(list == NULL) {
1831
                        /* First element becomes the list itself (and the last item), at least for now */
1832
                        list = p;
1833
                        last = p;
1834
                } else {
1835
                        /* Check where we should insert this, starting from the end */
1836
                        int added = 0;
1837
                        janus_recordplay_frame_packet *tmp = last;
1838
                        while(tmp) {
1839
                                if(tmp->ts < p->ts) {
1840
                                        /* The new timestamp is greater than the last one we have, append */
1841
                                        added = 1;
1842
                                        if(tmp->next != NULL) {
1843
                                                /* We're inserting */
1844
                                                tmp->next->prev = p;
1845
                                                p->next = tmp->next;
1846
                                        } else {
1847
                                                /* Update the last packet */
1848
                                                last = p;
1849
                                        }
1850
                                        tmp->next = p;
1851
                                        p->prev = tmp;
1852
                                        break;
1853
                                } else if(tmp->ts == p->ts) {
1854
                                        /* Same timestamp, check the sequence number */
1855
                                        if(tmp->seq < p->seq && (abs(tmp->seq - p->seq) < 10000)) {
1856
                                                /* The new sequence number is greater than the last one we have, append */
1857
                                                added = 1;
1858
                                                if(tmp->next != NULL) {
1859
                                                        /* We're inserting */
1860
                                                        tmp->next->prev = p;
1861
                                                        p->next = tmp->next;
1862
                                                } else {
1863
                                                        /* Update the last packet */
1864
                                                        last = p;
1865
                                                }
1866
                                                tmp->next = p;
1867
                                                p->prev = tmp;
1868
                                                break;
1869
                                        } else if(tmp->seq > p->seq && (abs(tmp->seq - p->seq) > 10000)) {
1870
                                                /* The new sequence number (resetted) is greater than the last one we have, append */
1871
                                                added = 1;
1872
                                                if(tmp->next != NULL) {
1873
                                                        /* We're inserting */
1874
                                                        tmp->next->prev = p;
1875
                                                        p->next = tmp->next;
1876
                                                } else {
1877
                                                        /* Update the last packet */
1878
                                                        last = p;
1879
                                                }
1880
                                                tmp->next = p;
1881
                                                p->prev = tmp;
1882
                                                break;
1883
                                        }
1884
                                }
1885
                                /* If either the timestamp ot the sequence number we just got is smaller, keep going back */
1886
                                tmp = tmp->prev;
1887
                        }
1888
                        if(!added) {
1889
                                /* We reached the start */
1890
                                p->next = list;
1891
                                list->prev = p;
1892
                                list = p;
1893
                        }
1894
                }
1895
                /* Skip data for now */
1896
                offset += len;
1897
                count++;
1898
        }
1899
        
1900
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" RTP packets\n", count);
1901
        janus_recordplay_frame_packet *tmp = list;
1902
        count = 0;
1903
        while(tmp) {
1904
                count++;
1905
                JANUS_LOG(LOG_HUGE, "[%10lu][%4d] seq=%"SCNu16", ts=%"SCNu64"\n", tmp->offset, tmp->len, tmp->seq, tmp->ts);
1906
                tmp = tmp->next;
1907
        }
1908
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" frame packets\n", count);
1909
        
1910
        /* Done! */
1911
        fclose(file);
1912
        return list;
1913
}
1914

    
1915
static void *janus_recordplay_playout_thread(void *data) {
1916
        janus_recordplay_session *session = (janus_recordplay_session *)data;
1917
        if(!session) {
1918
                JANUS_LOG(LOG_ERR, "Invalid session, can't start playout thread...\n");
1919
                g_thread_unref(g_thread_self());
1920
                return NULL;
1921
        }
1922
        if(session->recorder) {
1923
                JANUS_LOG(LOG_ERR, "This is a recorder, can't start playout thread...\n");
1924
                g_thread_unref(g_thread_self());
1925
                return NULL;
1926
        }
1927
        if(!session->aframes && !session->vframes) {
1928
                JANUS_LOG(LOG_ERR, "No audio and no video frames, can't start playout thread...\n");
1929
                g_thread_unref(g_thread_self());
1930
                return NULL;
1931
        }
1932
        JANUS_LOG(LOG_INFO, "Joining playout thread\n");
1933
        /* Open the files */
1934
        FILE *afile = NULL, *vfile = NULL;
1935
        if(session->aframes) {
1936
                char source[1024];
1937
                if(strstr(session->recording->arc_file, ".mjr"))
1938
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->arc_file);
1939
                else
1940
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->arc_file);
1941
                afile = fopen(source, "rb");
1942
                if(afile == NULL) {
1943
                        JANUS_LOG(LOG_ERR, "Could not open audio file %s, can't start playout thread...\n", source);
1944
                        g_thread_unref(g_thread_self());
1945
                        return NULL;
1946
                }
1947
        }
1948
        if(session->vframes) {
1949
                char source[1024];
1950
                if(strstr(session->recording->vrc_file, ".mjr"))
1951
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->vrc_file);
1952
                else
1953
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->vrc_file);
1954
                vfile = fopen(source, "rb");
1955
                if(vfile == NULL) {
1956
                        JANUS_LOG(LOG_ERR, "Could not open video file %s, can't start playout thread...\n", source);
1957
                        if(afile)
1958
                                fclose(afile);
1959
                        afile = NULL;
1960
                        g_thread_unref(g_thread_self());
1961
                        return NULL;
1962
                }
1963
        }
1964
        
1965
        /* Timer */
1966
        gboolean asent = FALSE, vsent = FALSE;
1967
        struct timeval now, abefore, vbefore;
1968
        time_t d_s, d_us;
1969
        gettimeofday(&now, NULL);
1970
        gettimeofday(&abefore, NULL);
1971
        gettimeofday(&vbefore, NULL);
1972

    
1973
        janus_recordplay_frame_packet *audio = session->aframes, *video = session->vframes;
1974
        char *buffer = (char *)calloc(1500, sizeof(char));
1975
        memset(buffer, 0, 1500);
1976
        int bytes = 0;
1977
        int64_t ts_diff = 0, passed = 0;
1978
        
1979
        while(!session->destroyed && session->active && !session->recording->destroyed && (audio || video)) {
1980
                if(!asent && !vsent) {
1981
                        /* We skipped the last round, so sleep a bit (5ms) */
1982
                        usleep(5000);
1983
                }
1984
                asent = FALSE;
1985
                vsent = FALSE;
1986
                if(audio) {
1987
                        if(audio == session->aframes) {
1988
                                /* First packet, send now */
1989
                                fseek(afile, audio->offset, SEEK_SET);
1990
                                bytes = fread(buffer, sizeof(char), audio->len, afile);
1991
                                if(bytes != audio->len)
1992
                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1993
                                /* Update payload type */
1994
                                rtp_header *rtp = (rtp_header *)buffer;
1995
                                rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1996
                                if(gateway != NULL)
1997
                                        gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1998
                                gettimeofday(&now, NULL);
1999
                                abefore.tv_sec = now.tv_sec;
2000
                                abefore.tv_usec = now.tv_usec;
2001
                                asent = TRUE;
2002
                                audio = audio->next;
2003
                        } else {
2004
                                /* What's the timestamp skip from the previous packet? */
2005
                                ts_diff = audio->ts - audio->prev->ts;
2006
                                ts_diff = (ts_diff*1000)/48;        /* FIXME Again, we're assuming Opus and it's 48khz */
2007
                                /* Check if it's time to send */
2008
                                gettimeofday(&now, NULL);
2009
                                d_s = now.tv_sec - abefore.tv_sec;
2010
                                d_us = now.tv_usec - abefore.tv_usec;
2011
                                if(d_us < 0) {
2012
                                        d_us += 1000000;
2013
                                        --d_s;
2014
                                }
2015
                                passed = d_s*1000000 + d_us;
2016
                                if(passed < (ts_diff-5000)) {
2017
                                        asent = FALSE;
2018
                                } else {
2019
                                        /* Update the reference time */
2020
                                        abefore.tv_usec += ts_diff%1000000;
2021
                                        if(abefore.tv_usec > 1000000) {
2022
                                                abefore.tv_sec++;
2023
                                                abefore.tv_usec -= 1000000;
2024
                                        }
2025
                                        if(ts_diff/1000000 > 0) {
2026
                                                abefore.tv_sec += ts_diff/1000000;
2027
                                                abefore.tv_usec -= ts_diff/1000000;
2028
                                        }
2029
                                        /* Send now */
2030
                                        fseek(afile, audio->offset, SEEK_SET);
2031
                                        bytes = fread(buffer, sizeof(char), audio->len, afile);
2032
                                        if(bytes != audio->len)
2033
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
2034
                                        /* Update payload type */
2035
                                        rtp_header *rtp = (rtp_header *)buffer;
2036
                                        rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
2037
                                        if(gateway != NULL)
2038
                                                gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
2039
                                        asent = TRUE;
2040
                                        audio = audio->next;
2041
                                }
2042
                        }
2043
                }
2044
                if(video) {
2045
                        if(video == session->vframes) {
2046
                                /* First packets: there may be many of them with the same timestamp, send them all */
2047
                                uint64_t ts = video->ts;
2048
                                while(video && video->ts == ts) {
2049
                                        fseek(vfile, video->offset, SEEK_SET);
2050
                                        bytes = fread(buffer, sizeof(char), video->len, vfile);
2051
                                        if(bytes != video->len)
2052
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
2053
                                        /* Update payload type */
2054
                                        rtp_header *rtp = (rtp_header *)buffer;
2055
                                        rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
2056
                                        if(gateway != NULL)
2057
                                                gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
2058
                                        video = video->next;
2059
                                }
2060
                                vsent = TRUE;
2061
                                gettimeofday(&now, NULL);
2062
                                vbefore.tv_sec = now.tv_sec;
2063
                                vbefore.tv_usec = now.tv_usec;
2064
                        } else {
2065
                                /* What's the timestamp skip from the previous packet? */
2066
                                ts_diff = video->ts - video->prev->ts;
2067
                                ts_diff = (ts_diff*1000)/90;
2068
                                /* Check if it's time to send */
2069
                                gettimeofday(&now, NULL);
2070
                                d_s = now.tv_sec - vbefore.tv_sec;
2071
                                d_us = now.tv_usec - vbefore.tv_usec;
2072
                                if(d_us < 0) {
2073
                                        d_us += 1000000;
2074
                                        --d_s;
2075
                                }
2076
                                passed = d_s*1000000 + d_us;
2077
                                if(passed < (ts_diff-5000)) {
2078
                                        vsent = FALSE;
2079
                                } else {
2080
                                        /* Update the reference time */
2081
                                        vbefore.tv_usec += ts_diff%1000000;
2082
                                        if(vbefore.tv_usec > 1000000) {
2083
                                                vbefore.tv_sec++;
2084
                                                vbefore.tv_usec -= 1000000;
2085
                                        }
2086
                                        if(ts_diff/1000000 > 0) {
2087
                                                vbefore.tv_sec += ts_diff/1000000;
2088
                                                vbefore.tv_usec -= ts_diff/1000000;
2089
                                        }
2090
                                        /* There may be multiple packets with the same timestamp, send them all */
2091
                                        uint64_t ts = video->ts;
2092
                                        while(video && video->ts == ts) {
2093
                                                /* Send now */
2094
                                                fseek(vfile, video->offset, SEEK_SET);
2095
                                                bytes = fread(buffer, sizeof(char), video->len, vfile);
2096
                                                if(bytes != video->len)
2097
                                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
2098
                                                /* Update payload type */
2099
                                                rtp_header *rtp = (rtp_header *)buffer;
2100
                                                rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
2101
                                                if(gateway != NULL)
2102
                                                        gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
2103
                                                video = video->next;
2104
                                        }
2105
                                        vsent = TRUE;
2106
                                }
2107
                        }
2108
                }
2109
        }
2110
        
2111
        g_free(buffer);
2112

    
2113
        /* Get rid of the indexes */
2114
        janus_recordplay_frame_packet *tmp = NULL;
2115
        audio = session->aframes;
2116
        while(audio) {
2117
                tmp = audio->next;
2118
                g_free(audio);
2119
                audio = tmp;
2120
        }
2121
        session->aframes = NULL;
2122
        video = session->vframes;
2123
        while(video) {
2124
                tmp = video->next;
2125
                g_free(video);
2126
                video = tmp;
2127
        }
2128
        session->vframes = NULL;
2129

    
2130
        if(afile)
2131
                fclose(afile);
2132
        afile = NULL;
2133
        if(vfile)
2134
                fclose(vfile);
2135
        vfile = NULL;
2136

    
2137
        if(session->recording->destroyed) {
2138
                /* Remove from the list of viewers */
2139
                janus_mutex_lock(&session->recording->mutex);
2140
                session->recording->viewers = g_list_remove(session->recording->viewers, session);
2141
                if(session->recording->viewers == NULL) {
2142
                        /* This was the last viewer, destroying the recording */
2143
                        JANUS_LOG(LOG_VERB, "Last viewer stopped playout of recording %"SCNu64", destroying it now\n", session->recording->id);
2144
                        janus_mutex_unlock(&session->recording->mutex);
2145
                        g_free(session->recording->name);
2146
                        g_free(session->recording->date);
2147
                        g_free(session->recording->arc_file);
2148
                        g_free(session->recording->vrc_file);
2149
                        g_free(session->recording);
2150
                        session->recording = NULL;
2151
                } else {
2152
                        /* Other viewers still on, don't do anything */
2153
                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" still has viewers, delaying its destruction until later\n", session->recording->id);
2154
                        janus_mutex_unlock(&session->recording->mutex);
2155
                }
2156
        }
2157

    
2158
        /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
2159
        gateway->close_pc(session->handle);
2160
        
2161
        JANUS_LOG(LOG_INFO, "Leaving playout thread\n");
2162
        g_thread_unref(g_thread_self());
2163
        return NULL;
2164
}