Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_recordplay.c @ 71a04f89

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

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

    
263

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

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

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

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

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

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

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

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

    
360
typedef struct janus_recordplay_rtp_header_extension {
361
        uint16_t type;
362
        uint16_t length;
363
} janus_recordplay_rtp_header_extension;
364

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

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

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

    
413

    
414
static char *recordings_path = NULL;
415
void janus_recordplay_update_recordings_list(void);
416
static void *janus_recordplay_playout_thread(void *data);
417

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

    
421

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

    
446

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

    
451
        msg->handle = NULL;
452

    
453
        g_free(msg->transaction);
454
        msg->transaction = NULL;
455
        if(msg->message)
456
                json_decref(msg->message);
457
        msg->message = NULL;
458
        g_free(msg->sdp_type);
459
        msg->sdp_type = NULL;
460
        g_free(msg->sdp);
461
        msg->sdp = NULL;
462

    
463
        g_free(msg);
464
}
465

    
466

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

    
478

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

    
518

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

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

    
576
        g_atomic_int_set(&initialized, 1);
577

    
578
        GError *error = NULL;
579
        /* Start the sessions watchdog */
580
        watchdog = g_thread_try_new("rplay watchdog", &janus_recordplay_watchdog, NULL, &error);
581
        if(error != NULL) {
582
                g_atomic_int_set(&initialized, 0);
583
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play watchdog thread...\n", error->code, error->message ? error->message : "??");
584
                return -1;
585
        }
586
        /* Launch the thread that will handle incoming messages */
587
        handler_thread = g_thread_try_new("janus recordplay handler", janus_recordplay_handler, NULL, &error);
588
        if(error != NULL) {
589
                g_atomic_int_set(&initialized, 0);
590
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play handler thread...\n", error->code, error->message ? error->message : "??");
591
                return -1;
592
        }
593
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_RECORDPLAY_NAME);
594
        return 0;
595
}
596

    
597
void janus_recordplay_destroy(void) {
598
        if(!g_atomic_int_get(&initialized))
599
                return;
600
        g_atomic_int_set(&stopping, 1);
601

    
602
        g_async_queue_push(messages, &exit_message);
603
        if(handler_thread != NULL) {
604
                g_thread_join(handler_thread);
605
                handler_thread = NULL;
606
        }
607
        if(watchdog != NULL) {
608
                g_thread_join(watchdog);
609
                watchdog = NULL;
610
        }
611
        /* FIXME We should destroy the sessions cleanly */
612
        janus_mutex_lock(&sessions_mutex);
613
        g_hash_table_destroy(sessions);
614
        janus_mutex_unlock(&sessions_mutex);
615
        g_async_queue_unref(messages);
616
        messages = NULL;
617
        sessions = NULL;
618
        g_atomic_int_set(&initialized, 0);
619
        g_atomic_int_set(&stopping, 0);
620
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_RECORDPLAY_NAME);
621
}
622

    
623
int janus_recordplay_get_api_compatibility(void) {
624
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
625
        return JANUS_PLUGIN_API_VERSION;
626
}
627

    
628
int janus_recordplay_get_version(void) {
629
        return JANUS_RECORDPLAY_VERSION;
630
}
631

    
632
const char *janus_recordplay_get_version_string(void) {
633
        return JANUS_RECORDPLAY_VERSION_STRING;
634
}
635

    
636
const char *janus_recordplay_get_description(void) {
637
        return JANUS_RECORDPLAY_DESCRIPTION;
638
}
639

    
640
const char *janus_recordplay_get_name(void) {
641
        return JANUS_RECORDPLAY_NAME;
642
}
643

    
644
const char *janus_recordplay_get_author(void) {
645
        return JANUS_RECORDPLAY_AUTHOR;
646
}
647

    
648
const char *janus_recordplay_get_package(void) {
649
        return JANUS_RECORDPLAY_PACKAGE;
650
}
651

    
652
void janus_recordplay_create_session(janus_plugin_session *handle, int *error) {
653
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
654
                *error = -1;
655
                return;
656
        }        
657
        janus_recordplay_session *session = (janus_recordplay_session *)g_malloc0(sizeof(janus_recordplay_session));
658
        if(session == NULL) {
659
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
660
                *error = -2;
661
                return;
662
        }
663
        session->handle = handle;
664
        session->active = FALSE;
665
        session->recorder = FALSE;
666
        session->firefox = FALSE;
667
        session->arc = NULL;
668
        session->vrc = NULL;
669
        janus_mutex_init(&session->rec_mutex);
670
        session->destroyed = 0;
671
        g_atomic_int_set(&session->hangingup, 0);
672
        session->video_remb_startup = 4;
673
        session->video_remb_last = janus_get_monotonic_time();
674
        session->video_bitrate = 1024 * 1024;                 /* This is 1mbps by default */
675
        session->video_keyframe_request_last = 0;
676
        session->video_keyframe_interval = 15000;         /* 15 seconds by default */
677
        session->video_fir_seq = 0;
678
        handle->plugin_handle = session;
679
        janus_mutex_lock(&sessions_mutex);
680
        g_hash_table_insert(sessions, handle, session);
681
        janus_mutex_unlock(&sessions_mutex);
682

    
683
        return;
684
}
685

    
686
void janus_recordplay_destroy_session(janus_plugin_session *handle, int *error) {
687
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
688
                *error = -1;
689
                return;
690
        }        
691
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
692
        if(!session) {
693
                JANUS_LOG(LOG_ERR, "No Record&Play session associated with this handle...\n");
694
                *error = -2;
695
                return;
696
        }
697
        janus_mutex_lock(&sessions_mutex);
698
        if(!session->destroyed) {
699
                JANUS_LOG(LOG_VERB, "Removing Record&Play session...\n");
700
                janus_recordplay_hangup_media(handle);
701
                session->destroyed = janus_get_monotonic_time();
702
                g_hash_table_remove(sessions, handle);
703
                /* Cleaning up and removing the session is done in a lazy way */
704
                old_sessions = g_list_append(old_sessions, session);
705
        }
706
        janus_mutex_unlock(&sessions_mutex);
707
        return;
708
}
709

    
710
char *janus_recordplay_query_session(janus_plugin_session *handle) {
711
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
712
                return NULL;
713
        }        
714
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
715
        if(!session) {
716
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
717
                return NULL;
718
        }
719
        /* In the echo test, every session is the same: we just provide some configure info */
720
        json_t *info = json_object();
721
        json_object_set_new(info, "type", json_string(session->recorder ? "recorder" : (session->recording ? "player" : "none")));
722
        if(session->recording) {
723
                json_object_set_new(info, "recording_id", json_integer(session->recording->id));
724
                json_object_set_new(info, "recording_name", json_string(session->recording->name));
725
        }
726
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
727
        char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
728
        json_decref(info);
729
        return info_text;
730
}
731

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

    
736
        /* Pre-parse the message */
737
        int error_code = 0;
738
        char error_cause[512];
739
        json_t *root = NULL;
740
        json_t *response = NULL;
741
        
742
        if(message == NULL) {
743
                JANUS_LOG(LOG_ERR, "No message??\n");
744
                error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
745
                g_snprintf(error_cause, 512, "%s", "No message??");
746
                goto error;
747
        }
748
        JANUS_LOG(LOG_VERB, "Handling message: %s\n", message);
749

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

    
855
                g_free(message);
856
                msg->handle = handle;
857
                msg->transaction = transaction;
858
                msg->message = root;
859
                msg->sdp_type = sdp_type;
860
                msg->sdp = sdp;
861

    
862
                g_async_queue_push(messages, msg);
863

    
864
                return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
865
        } else {
866
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
867
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
868
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
869
                goto error;
870
        }
871

    
872
plugin_response:
873
                {
874
                        if (!response) {
875
                                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
876
                                g_snprintf(error_cause, 512, "Invalid response");
877
                                goto error;
878
                        }
879
                        if(root != NULL)
880
                                json_decref(root);
881
                        g_free(transaction);
882
                        g_free(message);
883
                        g_free(sdp_type);
884
                        g_free(sdp);
885

    
886
                        char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
887
                        json_decref(response);
888
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
889
                        g_free(response_text);
890
                        return result;
891
                }
892

    
893
error:
894
                {
895
                        if(root != NULL)
896
                                json_decref(root);
897
                        g_free(transaction);
898
                        g_free(message);
899
                        g_free(sdp_type);
900
                        g_free(sdp);
901

    
902
                        /* Prepare JSON error event */
903
                        json_t *event = json_object();
904
                        json_object_set_new(event, "recordplay", json_string("event"));
905
                        json_object_set_new(event, "error_code", json_integer(error_code));
906
                        json_object_set_new(event, "error", json_string(error_cause));
907
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
908
                        json_decref(event);
909
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, event_text);
910
                        g_free(event_text);
911
                        return result;
912
                }
913

    
914
}
915

    
916
void janus_recordplay_setup_media(janus_plugin_session *handle) {
917
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
918
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
919
                return;
920
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
921
        if(!session) {
922
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
923
                return;
924
        }
925
        if(session->destroyed)
926
                return;
927
        g_atomic_int_set(&session->hangingup, 0);
928
        /* Take note of the fact that the session is now active */
929
        session->active = TRUE;
930
        if(!session->recorder) {
931
                GError *error = NULL;
932
                g_thread_try_new("recordplay playout thread", &janus_recordplay_playout_thread, session, &error);
933
                if(error != NULL) {
934
                        /* FIXME Should we notify this back to the user somehow? */
935
                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play playout thread...\n", error->code, error->message ? error->message : "??");
936
                }
937
        }
938
}
939

    
940
void janus_recordplay_send_rtcp_feedback(janus_plugin_session *handle, int video, char *buf, int len) {
941
        if(video != 1)
942
                return;        /* We just do this for video, for now */
943

    
944
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
945
        char rtcpbuf[24];
946

    
947
        /* Send a RR+SDES+REMB every five seconds, or ASAP while we are still
948
         * ramping up (first 4 RTP packets) */
949
        gint64 now = janus_get_monotonic_time();
950
        guint64 elapsed = now - session->video_remb_last;
951
        gboolean remb_rampup = session->video_remb_startup > 0;
952

    
953
        if(remb_rampup || (elapsed >= 5*G_USEC_PER_SEC)) {
954
                guint64 bitrate = session->video_bitrate;
955

    
956
                if(remb_rampup) {
957
                        bitrate = bitrate / session->video_remb_startup;
958
                        session->video_remb_startup--;
959
                }
960

    
961
                /* Send a new REMB back */
962
                char rtcpbuf[24];
963
                janus_rtcp_remb((char *)(&rtcpbuf), 24, bitrate);
964
                gateway->relay_rtcp(handle, video, rtcpbuf, 24);
965

    
966
                session->video_remb_last = now;
967
        }
968

    
969
        /* Request a keyframe on a regular basis (every session->video_keyframe_interval ms) */
970
        elapsed = now - session->video_keyframe_request_last;
971
        guint64 interval = (session->video_keyframe_interval / 1000) * G_USEC_PER_SEC;
972

    
973
        if(elapsed >= interval) {
974
                /* Send both a FIR and a PLI, just to be sure */
975
                memset(rtcpbuf, 0, 20);
976
                janus_rtcp_fir((char *)&rtcpbuf, 20, &session->video_fir_seq);
977
                gateway->relay_rtcp(handle, video, rtcpbuf, 20);
978
                memset(rtcpbuf, 0, 12);
979
                janus_rtcp_pli((char *)&rtcpbuf, 12);
980
                gateway->relay_rtcp(handle, video, rtcpbuf, 12);
981
                session->video_keyframe_request_last = now;
982
        }
983
}
984

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

    
1001
                janus_recordplay_send_rtcp_feedback(handle, video, buf, len);
1002
        }
1003
}
1004

    
1005
void janus_recordplay_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1006
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1007
                return;
1008
}
1009

    
1010
void janus_recordplay_incoming_data(janus_plugin_session *handle, char *buf, int len) {
1011
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1012
                return;
1013
        /* FIXME We don't care */
1014
}
1015

    
1016
void janus_recordplay_slow_link(janus_plugin_session *handle, int uplink, int video) {
1017
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1018
                return;
1019

    
1020
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
1021
        if(!session || session->destroyed)
1022
                return;
1023

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

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

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

    
1065
        /* FIXME Simulate a "stop" coming from the browser */
1066
        janus_recordplay_message *msg = g_malloc0(sizeof(janus_recordplay_message));
1067
        msg->handle = handle;
1068
        msg->message = json_loads("{\"request\":\"stop\"}", 0, NULL);
1069
        msg->transaction = NULL;
1070
        msg->sdp_type = NULL;
1071
        msg->sdp = NULL;
1072
        g_async_queue_push(messages, msg);
1073
}
1074

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

    
1435
                /* Any SDP to handle? */
1436
                if(msg->sdp) {
1437
                        session->firefox = strstr(msg->sdp, "Mozilla") ? TRUE : FALSE;
1438
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1439
                }
1440

    
1441
                /* Prepare JSON event */
1442
                event = json_object();
1443
                json_object_set_new(event, "recordplay", json_string("event"));
1444
                if(result != NULL)
1445
                        json_object_set_new(event, "result", result);
1446
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1447
                json_decref(event);
1448
                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1449
                if(!sdp) {
1450
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, NULL, NULL);
1451
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1452
                } else {
1453
                        const char *type = session->recorder ? "answer" : "offer";
1454
                        /* How long will the gateway take to push the event? */
1455
                        g_atomic_int_set(&session->hangingup, 0);
1456
                        gint64 start = janus_get_monotonic_time();
1457
                        int res = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, type, sdp);
1458
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
1459
                                res, janus_get_monotonic_time()-start);
1460
                        g_free(sdp);
1461
                }
1462
                g_free(event_text);
1463
                janus_recordplay_message_free(msg);
1464
                continue;
1465
                
1466
error:
1467
                {
1468
                        /* Prepare JSON error event */
1469
                        json_t *event = json_object();
1470
                        json_object_set_new(event, "recordplay", json_string("event"));
1471
                        json_object_set_new(event, "error_code", json_integer(error_code));
1472
                        json_object_set_new(event, "error", json_string(error_cause));
1473
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1474
                        json_decref(event);
1475
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1476
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, NULL, NULL);
1477
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1478
                        g_free(event_text);
1479
                        janus_recordplay_message_free(msg);
1480
                }
1481
        }
1482
        JANUS_LOG(LOG_VERB, "LeavingRecord&Play handler thread\n");
1483
        return NULL;
1484
}
1485

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

    
1588
                /* Add to the list of recordings */
1589
                g_hash_table_insert(recordings, janus_uint64_dup(rec->id), rec);
1590
        }
1591
        closedir(dir);
1592
        /* Now let's check if any of the previously existing recordings was removed */
1593
        if(old_recordings != NULL) {
1594
                while(old_recordings != NULL) {
1595
                        guint64 id = *((guint64 *)old_recordings->data);
1596
                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" is not available anymore, removing...\n", id);
1597
                        janus_recordplay_recording *old_rec = g_hash_table_lookup(recordings, &id);
1598
                        if(old_rec != NULL) {
1599
                                /* Remove it */
1600
                                g_hash_table_remove(recordings, &id);
1601
                                /* Only destroy the object if no one's watching, though */
1602
                                janus_mutex_lock(&old_rec->mutex);
1603
                                old_rec->destroyed = janus_get_monotonic_time();
1604
                                if(old_rec->viewers == NULL) {
1605
                                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" has no viewers, destroying it now\n", id);
1606
                                        janus_mutex_unlock(&old_rec->mutex);
1607
                                        g_free(old_rec->name);
1608
                                        g_free(old_rec->date);
1609
                                        g_free(old_rec->arc_file);
1610
                                        g_free(old_rec->vrc_file);
1611
                                        g_free(old_rec);
1612
                                } else {
1613
                                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" still has viewers, delaying its destruction until later\n", id);
1614
                                        janus_mutex_unlock(&old_rec->mutex);
1615
                                }
1616
                        }
1617
                        old_recordings = old_recordings->next;
1618
                }
1619
                g_list_free(old_recordings);
1620
        }
1621
        janus_mutex_unlock(&recordings_mutex);
1622
}
1623

    
1624
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename) {
1625
        if(!dir || !filename)
1626
                return NULL;
1627
        /* Open the file */
1628
        char source[1024];
1629
        if(strstr(filename, ".mjr"))
1630
                g_snprintf(source, 1024, "%s/%s", dir, filename);
1631
        else
1632
                g_snprintf(source, 1024, "%s/%s.mjr", dir, filename);
1633
        FILE *file = fopen(source, "rb");
1634
        if(file == NULL) {
1635
                JANUS_LOG(LOG_ERR, "Could not open file %s\n", source);
1636
                return NULL;
1637
        }
1638
        fseek(file, 0L, SEEK_END);
1639
        long fsize = ftell(file);
1640
        fseek(file, 0L, SEEK_SET);
1641
        JANUS_LOG(LOG_VERB, "File is %zu bytes\n", fsize);
1642

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

    
1941
static void *janus_recordplay_playout_thread(void *data) {
1942
        janus_recordplay_session *session = (janus_recordplay_session *)data;
1943
        if(!session) {
1944
                JANUS_LOG(LOG_ERR, "Invalid session, can't start playout thread...\n");
1945
                g_thread_unref(g_thread_self());
1946
                return NULL;
1947
        }
1948
        if(session->recorder) {
1949
                JANUS_LOG(LOG_ERR, "This is a recorder, can't start playout thread...\n");
1950
                g_thread_unref(g_thread_self());
1951
                return NULL;
1952
        }
1953
        if(!session->aframes && !session->vframes) {
1954
                JANUS_LOG(LOG_ERR, "No audio and no video frames, can't start playout thread...\n");
1955
                g_thread_unref(g_thread_self());
1956
                return NULL;
1957
        }
1958
        JANUS_LOG(LOG_INFO, "Joining playout thread\n");
1959
        /* Open the files */
1960
        FILE *afile = NULL, *vfile = NULL;
1961
        if(session->aframes) {
1962
                char source[1024];
1963
                if(strstr(session->recording->arc_file, ".mjr"))
1964
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->arc_file);
1965
                else
1966
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->arc_file);
1967
                afile = fopen(source, "rb");
1968
                if(afile == NULL) {
1969
                        JANUS_LOG(LOG_ERR, "Could not open audio file %s, can't start playout thread...\n", source);
1970
                        g_thread_unref(g_thread_self());
1971
                        return NULL;
1972
                }
1973
        }
1974
        if(session->vframes) {
1975
                char source[1024];
1976
                if(strstr(session->recording->vrc_file, ".mjr"))
1977
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->vrc_file);
1978
                else
1979
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->vrc_file);
1980
                vfile = fopen(source, "rb");
1981
                if(vfile == NULL) {
1982
                        JANUS_LOG(LOG_ERR, "Could not open video file %s, can't start playout thread...\n", source);
1983
                        if(afile)
1984
                                fclose(afile);
1985
                        afile = NULL;
1986
                        g_thread_unref(g_thread_self());
1987
                        return NULL;
1988
                }
1989
        }
1990
        
1991
        /* Timer */
1992
        gboolean asent = FALSE, vsent = FALSE;
1993
        struct timeval now, abefore, vbefore;
1994
        time_t d_s, d_us;
1995
        gettimeofday(&now, NULL);
1996
        gettimeofday(&abefore, NULL);
1997
        gettimeofday(&vbefore, NULL);
1998

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

    
2139
        /* Get rid of the indexes */
2140
        janus_recordplay_frame_packet *tmp = NULL;
2141
        audio = session->aframes;
2142
        while(audio) {
2143
                tmp = audio->next;
2144
                g_free(audio);
2145
                audio = tmp;
2146
        }
2147
        session->aframes = NULL;
2148
        video = session->vframes;
2149
        while(video) {
2150
                tmp = video->next;
2151
                g_free(video);
2152
                video = tmp;
2153
        }
2154
        session->vframes = NULL;
2155

    
2156
        if(afile)
2157
                fclose(afile);
2158
        afile = NULL;
2159
        if(vfile)
2160
                fclose(vfile);
2161
        vfile = NULL;
2162

    
2163
        if(session->recording->destroyed) {
2164
                /* Remove from the list of viewers */
2165
                janus_mutex_lock(&session->recording->mutex);
2166
                session->recording->viewers = g_list_remove(session->recording->viewers, session);
2167
                if(session->recording->viewers == NULL) {
2168
                        /* This was the last viewer, destroying the recording */
2169
                        JANUS_LOG(LOG_VERB, "Last viewer stopped playout of recording %"SCNu64", destroying it now\n", session->recording->id);
2170
                        janus_mutex_unlock(&session->recording->mutex);
2171
                        g_free(session->recording->name);
2172
                        g_free(session->recording->date);
2173
                        g_free(session->recording->arc_file);
2174
                        g_free(session->recording->vrc_file);
2175
                        g_free(session->recording);
2176
                        session->recording = NULL;
2177
                } else {
2178
                        /* Other viewers still on, don't do anything */
2179
                        JANUS_LOG(LOG_VERB, "Recording %"SCNu64" still has viewers, delaying its destruction until later\n", session->recording->id);
2180
                        janus_mutex_unlock(&session->recording->mutex);
2181
                }
2182
        }
2183

    
2184
        /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
2185
        gateway->close_pc(session->handle);
2186
        
2187
        JANUS_LOG(LOG_INFO, "Leaving playout thread\n");
2188
        g_thread_unref(g_thread_self());
2189
        return NULL;
2190
}