Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_recordplay.c @ 793d18b1

History | View | Annotate | Download (67.6 KB)

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

    
246
#include "plugin.h"
247

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

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

    
262

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

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

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

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

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

    
325

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

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

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

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

    
357
typedef struct janus_recordplay_recording {
358
        guint64 id;                        /* Recording unique ID */
359
        char *name;                        /* Name of the recording */
360
        char *date;                        /* Time of the recording */
361
        char *arc_file;                /* Audio file name */
362
        char *vrc_file;                /* Video file name */
363
} janus_recordplay_recording;
364
static GHashTable *recordings;
365
static janus_mutex recordings_mutex;
366

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

    
389

    
390
static char *recordings_path = NULL;
391
void janus_recordplay_update_recordings_list(void);
392
static void *janus_recordplay_playout_thread(void *data);
393

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

    
397

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

    
422

    
423
void janus_recordplay_message_free(janus_recordplay_message *msg);
424
void janus_recordplay_message_free(janus_recordplay_message *msg) {
425
        if(!msg)
426
                return;
427

    
428
        msg->handle = NULL;
429

    
430
        g_free(msg->transaction);
431
        msg->transaction = NULL;
432
        if(msg->message)
433
                json_decref(msg->message);
434
        msg->message = NULL;
435
        g_free(msg->sdp_type);
436
        msg->sdp_type = NULL;
437
        g_free(msg->sdp);
438
        msg->sdp = NULL;
439

    
440
        g_free(msg);
441
}
442

    
443

    
444
/* Error codes */
445
#define JANUS_RECORDPLAY_ERROR_NO_MESSAGE                        411
446
#define JANUS_RECORDPLAY_ERROR_INVALID_JSON                412
447
#define JANUS_RECORDPLAY_ERROR_INVALID_REQUEST        413
448
#define JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT        414
449
#define JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT        415
450
#define JANUS_RECORDPLAY_ERROR_NOT_FOUND        416
451
#define JANUS_RECORDPLAY_ERROR_INVALID_RECORDING        417
452
#define JANUS_RECORDPLAY_ERROR_INVALID_STATE        418
453
#define JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR        499
454

    
455

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

    
495

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

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

    
547
        g_atomic_int_set(&initialized, 1);
548

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

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

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

    
597
int janus_recordplay_get_version(void) {
598
        return JANUS_RECORDPLAY_VERSION;
599
}
600

    
601
const char *janus_recordplay_get_version_string(void) {
602
        return JANUS_RECORDPLAY_VERSION_STRING;
603
}
604

    
605
const char *janus_recordplay_get_description(void) {
606
        return JANUS_RECORDPLAY_DESCRIPTION;
607
}
608

    
609
const char *janus_recordplay_get_name(void) {
610
        return JANUS_RECORDPLAY_NAME;
611
}
612

    
613
const char *janus_recordplay_get_author(void) {
614
        return JANUS_RECORDPLAY_AUTHOR;
615
}
616

    
617
const char *janus_recordplay_get_package(void) {
618
        return JANUS_RECORDPLAY_PACKAGE;
619
}
620

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

    
650
        return;
651
}
652

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

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

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

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

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

    
833
                g_free(message);
834
                msg->handle = handle;
835
                msg->transaction = transaction;
836
                msg->message = root;
837
                msg->sdp_type = sdp_type;
838
                msg->sdp = sdp;
839

    
840
                g_async_queue_push(messages, msg);
841

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

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

    
864
                        char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
865
                        json_decref(response);
866
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
867
                        g_free(response_text);
868
                        return result;
869
                }
870

    
871
error:
872
                {
873
                        if(root != NULL)
874
                                json_decref(root);
875
                        g_free(transaction);
876
                        g_free(message);
877
                        g_free(sdp_type);
878
                        g_free(sdp);
879

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

    
892
}
893

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

    
917
void janus_recordplay_send_rtcp_feedback(janus_plugin_session *handle, int video, char *buf, int len) {
918
        if(video != 1)
919
                return;        /* We just do this for video, for now */
920

    
921
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
922
        char rtcpbuf[200];
923

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

    
930
        if(remb_rampup || (elapsed >= 5*G_USEC_PER_SEC)) {
931
                guint64 bitrate = session->video_bitrate;
932

    
933
                if(remb_rampup) {
934
                        bitrate = bitrate / session->video_remb_startup;
935
                        session->video_remb_startup--;
936
                }
937

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

    
957
        /* Request a keyframe on a regular basis (every session->video_keyframe_interval ms) */
958
        elapsed = now - session->video_keyframe_request_last;
959
        guint64 interval = (session->video_keyframe_interval / 1000) * G_USEC_PER_SEC;
960

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

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

    
992
                janus_recordplay_send_rtcp_feedback(handle, video, buf, len);
993
        }
994
}
995

    
996
void janus_recordplay_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
997
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
998
                return;
999
}
1000

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

    
1007
void janus_recordplay_slow_link(janus_plugin_session *handle, int uplink, int video) {
1008
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized) || !gateway)
1009
                return;
1010

    
1011
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
1012
        if(!session || session->destroyed)
1013
                return;
1014

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

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

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

    
1057
        /* FIXME Simulate a "stop" coming from the browser */
1058
        janus_recordplay_message *msg = calloc(1, sizeof(janus_recordplay_message));
1059
        msg->handle = handle;
1060
        msg->message = json_loads("{\"request\":\"stop\"}", 0, NULL);
1061
        msg->transaction = NULL;
1062
        msg->sdp_type = NULL;
1063
        msg->sdp = NULL;
1064
        g_async_queue_push(messages, msg);
1065
}
1066

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

    
1411
                /* Any SDP to handle? */
1412
                if(msg->sdp) {
1413
                        session->firefox = strstr(msg->sdp, "Mozilla") ? TRUE : FALSE;
1414
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1415
                }
1416

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

    
1462
void janus_recordplay_update_recordings_list(void) {
1463
        if(recordings_path == NULL)
1464
                return;
1465
        JANUS_LOG(LOG_VERB, "Updating recordings list in %s\n", recordings_path);
1466
        janus_mutex_lock(&recordings_mutex);
1467
        /* Open dir */
1468
        DIR *dir = opendir(recordings_path);
1469
        if(!dir) {
1470
                JANUS_LOG(LOG_ERR, "Couldn't open folder...\n");
1471
                return;
1472
        }
1473
        struct dirent *recent = NULL;
1474
        char recpath[1024];
1475
        while((recent = readdir(dir))) {
1476
                int len = strlen(recent->d_name);
1477
                if(len < 4)
1478
                        continue;
1479
                if(strcasecmp(recent->d_name+len-4, ".nfo"))
1480
                        continue;
1481
                JANUS_LOG(LOG_VERB, "Importing recording '%s'...\n", recent->d_name);
1482
                memset(recpath, 0, 1024);
1483
                g_snprintf(recpath, 1024, "%s/%s", recordings_path, recent->d_name);
1484
                janus_config *nfo = janus_config_parse(recpath);
1485
                if(nfo == NULL) { 
1486
                        JANUS_LOG(LOG_ERR, "Invalid recording '%s'...\n", recent->d_name);
1487
                        continue;
1488
                }
1489
                janus_config_category *cat = janus_config_get_categories(nfo);
1490
                if(cat == NULL) {
1491
                        JANUS_LOG(LOG_WARN, "No recording info in '%s', skipping...\n", recent->d_name);
1492
                        janus_config_destroy(nfo);
1493
                        continue;
1494
                }
1495
                guint64 id = atol(cat->name);
1496
                if(id == 0) {
1497
                        JANUS_LOG(LOG_WARN, "Invalid ID, skipping...\n");
1498
                        janus_config_destroy(nfo);
1499
                        continue;
1500
                }
1501
                janus_config_item *name = janus_config_get_item(cat, "name");
1502
                janus_config_item *date = janus_config_get_item(cat, "date");
1503
                janus_config_item *audio = janus_config_get_item(cat, "audio");
1504
                janus_config_item *video = janus_config_get_item(cat, "video");
1505
                if(!name || !name->value || strlen(name->value) == 0 || !date || !date->value || strlen(date->value) == 0) {
1506
                        JANUS_LOG(LOG_WARN, "Invalid info, skipping...\n");
1507
                        janus_config_destroy(nfo);
1508
                        continue;
1509
                }
1510
                if((!audio || !audio->value) && (!video || !video->value)) {
1511
                        JANUS_LOG(LOG_WARN, "No audio and no video, skipping...\n");
1512
                        janus_config_destroy(nfo);
1513
                        continue;
1514
                }
1515
                janus_recordplay_recording *rec = (janus_recordplay_recording *)calloc(1, sizeof(janus_recordplay_recording));
1516
                rec->id = id;
1517
                rec->name = g_strdup(name->value);
1518
                rec->date = g_strdup(date->value);
1519
                if(audio && audio->value) {
1520
                        rec->arc_file = g_strdup(audio->value);
1521
                        if(strstr(rec->arc_file, ".mjr")) {
1522
                                char *ext = strstr(rec->arc_file, ".mjr");
1523
                                *ext = '\0';
1524
                        }
1525
                }
1526
                if(video && video->value) {
1527
                        rec->vrc_file = g_strdup(video->value);
1528
                        if(strstr(rec->vrc_file, ".mjr")) {
1529
                                char *ext = strstr(rec->vrc_file, ".mjr");
1530
                                *ext = '\0';
1531
                        }
1532
                }
1533
                
1534
                janus_config_destroy(nfo);
1535

    
1536
                /* FIXME We should clean previous recordings with the same ID */
1537
                g_hash_table_remove(recordings, GUINT_TO_POINTER(id));
1538
                g_hash_table_insert(recordings, GUINT_TO_POINTER(id), rec);
1539
        }
1540
        closedir(dir);
1541
        janus_mutex_unlock(&recordings_mutex);
1542
}
1543

    
1544
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename) {
1545
        if(!dir || !filename)
1546
                return NULL;
1547
        /* Open the file */
1548
        char source[1024];
1549
        if(strstr(filename, ".mjr"))
1550
                g_snprintf(source, 1024, "%s/%s", dir, filename);
1551
        else
1552
                g_snprintf(source, 1024, "%s/%s.mjr", dir, filename);
1553
        FILE *file = fopen(source, "rb");
1554
        if(file == NULL) {
1555
                JANUS_LOG(LOG_ERR, "Could not open file %s\n", source);
1556
                return NULL;
1557
        }
1558
        fseek(file, 0L, SEEK_END);
1559
        long fsize = ftell(file);
1560
        fseek(file, 0L, SEEK_SET);
1561
        JANUS_LOG(LOG_VERB, "File is %zu bytes\n", fsize);
1562

    
1563
        /* Pre-parse */
1564
        JANUS_LOG(LOG_VERB, "Pre-parsing file %s to generate ordered index...\n", source);
1565
        int bytes = 0;
1566
        long offset = 0;
1567
        uint16_t len = 0, count = 0;
1568
        uint32_t first_ts = 0, last_ts = 0, reset = 0;        /* To handle whether there's a timestamp reset in the recording */
1569
        char prebuffer[1500];
1570
        memset(prebuffer, 0, 1500);
1571
        /* Let's look for timestamp resets first */
1572
        while(offset < fsize) {
1573
                /* Read frame header */
1574
                fseek(file, offset, SEEK_SET);
1575
                bytes = fread(prebuffer, sizeof(char), 8, file);
1576
                if(bytes != 8 || prebuffer[0] != 'M') {
1577
                        JANUS_LOG(LOG_ERR, "Invalid header...\n");
1578
                        fclose(file);
1579
                        return NULL;
1580
                }
1581
                offset += 8;
1582
                bytes = fread(&len, sizeof(uint16_t), 1, file);
1583
                len = ntohs(len);
1584
                offset += 2;
1585
                if(len == 5) {
1586
                        /* This is the main header */
1587
                        bytes = fread(prebuffer, sizeof(char), 5, file);
1588
                        if(prebuffer[0] == 'v') {
1589
                                JANUS_LOG(LOG_VERB, "This is a video recording, assuming VP8\n");
1590
                        } else if(prebuffer[0] == 'a') {
1591
                                JANUS_LOG(LOG_VERB, "This is an audio recording, assuming Opus\n");
1592
                        } else {
1593
                                JANUS_LOG(LOG_ERR, "Unsupported recording media type...\n");
1594
                                fclose(file);
1595
                                return NULL;
1596
                        }
1597
                        offset += len;
1598
                        continue;
1599
                } else if(len < 12) {
1600
                        /* Not RTP, skip */
1601
                        offset += len;
1602
                        continue;
1603
                }
1604
                /* Only read RTP header */
1605
                bytes = fread(prebuffer, sizeof(char), 16, file);
1606
                rtp_header *rtp = (rtp_header *)prebuffer;
1607
                if(last_ts == 0) {
1608
                        first_ts = ntohl(rtp->timestamp);
1609
                        if(first_ts > 1000*1000)        /* Just used to check whether a packet is pre- or post-reset */
1610
                                first_ts -= 1000*1000;
1611
                } else {
1612
                        if(ntohl(rtp->timestamp) < last_ts) {
1613
                                /* The new timestamp is smaller than the next one, is it a timestamp reset or simply out of order? */
1614
                                if(last_ts-ntohl(rtp->timestamp) > 2*1000*1000*1000) {
1615
                                        reset = ntohl(rtp->timestamp);
1616
                                        JANUS_LOG(LOG_VERB, "Timestamp reset: %"SCNu32"\n", reset);
1617
                                }
1618
                        } else if(ntohl(rtp->timestamp) < reset) {
1619
                                JANUS_LOG(LOG_VERB, "Updating timestamp reset: %"SCNu32" (was %"SCNu32")\n", ntohl(rtp->timestamp), reset);
1620
                                reset = ntohl(rtp->timestamp);
1621
                        }
1622
                }
1623
                last_ts = ntohl(rtp->timestamp);
1624
                /* Skip data for now */
1625
                offset += len;
1626
        }
1627
        /* Now let's parse the frames and order them */
1628
        offset = 0;
1629
        janus_recordplay_frame_packet *list = NULL, *last = NULL;
1630
        while(offset < fsize) {
1631
                /* Read frame header */
1632
                fseek(file, offset, SEEK_SET);
1633
                bytes = fread(prebuffer, sizeof(char), 8, file);
1634
                prebuffer[8] = '\0';
1635
                JANUS_LOG(LOG_HUGE, "Header: %s\n", prebuffer);
1636
                offset += 8;
1637
                bytes = fread(&len, sizeof(uint16_t), 1, file);
1638
                len = ntohs(len);
1639
                JANUS_LOG(LOG_HUGE, "  -- Length: %"SCNu16"\n", len);
1640
                offset += 2;
1641
                if(len < 12) {
1642
                        /* Not RTP, skip */
1643
                        JANUS_LOG(LOG_HUGE, "  -- Not RTP, skipping\n");
1644
                        offset += len;
1645
                        continue;
1646
                }
1647
                /* Only read RTP header */
1648
                bytes = fread(prebuffer, sizeof(char), 16, file);
1649
                rtp_header *rtp = (rtp_header *)prebuffer;
1650
                JANUS_LOG(LOG_HUGE, "  -- RTP packet (ssrc=%"SCNu32", pt=%"SCNu16", ext=%"SCNu16", seq=%"SCNu16", ts=%"SCNu32")\n",
1651
                                ntohl(rtp->ssrc), rtp->type, rtp->extension, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
1652
                /* Generate frame packet and insert in the ordered list */
1653
                janus_recordplay_frame_packet *p = calloc(1, sizeof(janus_recordplay_frame_packet));
1654
                if(p == NULL) {
1655
                        JANUS_LOG(LOG_ERR, "Memory error!\n");
1656
                        fclose(file);
1657
                        return NULL;
1658
                }
1659
                p->seq = ntohs(rtp->seq_number);
1660
                if(reset == 0) {
1661
                        /* Simple enough... */
1662
                        p->ts = ntohl(rtp->timestamp);
1663
                } else {
1664
                        /* Is this packet pre- or post-reset? */
1665
                        if(ntohl(rtp->timestamp) > first_ts) {
1666
                                /* Pre-reset... */
1667
                                p->ts = ntohl(rtp->timestamp);
1668
                        } else {
1669
                                /* Post-reset... */
1670
                                uint64_t max32 = UINT32_MAX;
1671
                                max32++;
1672
                                p->ts = max32+ntohl(rtp->timestamp);
1673
                        }
1674
                }
1675
                p->len = len;
1676
                p->offset = offset;
1677
                p->next = NULL;
1678
                p->prev = NULL;
1679
                if(list == NULL) {
1680
                        /* First element becomes the list itself (and the last item), at least for now */
1681
                        list = p;
1682
                        last = p;
1683
                } else {
1684
                        /* Check where we should insert this, starting from the end */
1685
                        int added = 0;
1686
                        janus_recordplay_frame_packet *tmp = last;
1687
                        while(tmp) {
1688
                                if(tmp->ts < p->ts) {
1689
                                        /* The new timestamp is greater than the last one we have, append */
1690
                                        added = 1;
1691
                                        if(tmp->next != NULL) {
1692
                                                /* We're inserting */
1693
                                                tmp->next->prev = p;
1694
                                                p->next = tmp->next;
1695
                                        } else {
1696
                                                /* Update the last packet */
1697
                                                last = p;
1698
                                        }
1699
                                        tmp->next = p;
1700
                                        p->prev = tmp;
1701
                                        break;
1702
                                } else if(tmp->ts == p->ts) {
1703
                                        /* Same timestamp, check the sequence number */
1704
                                        if(tmp->seq < p->seq && (abs(tmp->seq - p->seq) < 10000)) {
1705
                                                /* The new sequence number is greater than the last one we have, append */
1706
                                                added = 1;
1707
                                                if(tmp->next != NULL) {
1708
                                                        /* We're inserting */
1709
                                                        tmp->next->prev = p;
1710
                                                        p->next = tmp->next;
1711
                                                } else {
1712
                                                        /* Update the last packet */
1713
                                                        last = p;
1714
                                                }
1715
                                                tmp->next = p;
1716
                                                p->prev = tmp;
1717
                                                break;
1718
                                        } else if(tmp->seq > p->seq && (abs(tmp->seq - p->seq) > 10000)) {
1719
                                                /* The new sequence number (resetted) is greater than the last one we have, append */
1720
                                                added = 1;
1721
                                                if(tmp->next != NULL) {
1722
                                                        /* We're inserting */
1723
                                                        tmp->next->prev = p;
1724
                                                        p->next = tmp->next;
1725
                                                } else {
1726
                                                        /* Update the last packet */
1727
                                                        last = p;
1728
                                                }
1729
                                                tmp->next = p;
1730
                                                p->prev = tmp;
1731
                                                break;
1732
                                        }
1733
                                }
1734
                                /* If either the timestamp ot the sequence number we just got is smaller, keep going back */
1735
                                tmp = tmp->prev;
1736
                        }
1737
                        if(!added) {
1738
                                /* We reached the start */
1739
                                p->next = list;
1740
                                list->prev = p;
1741
                                list = p;
1742
                        }
1743
                }
1744
                /* Skip data for now */
1745
                offset += len;
1746
                count++;
1747
        }
1748
        
1749
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" RTP packets\n", count);
1750
        janus_recordplay_frame_packet *tmp = list;
1751
        count = 0;
1752
        while(tmp) {
1753
                count++;
1754
                JANUS_LOG(LOG_HUGE, "[%10lu][%4d] seq=%"SCNu16", ts=%"SCNu64"\n", tmp->offset, tmp->len, tmp->seq, tmp->ts);
1755
                tmp = tmp->next;
1756
        }
1757
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" frame packets\n", count);
1758
        
1759
        /* Done! */
1760
        fclose(file);
1761
        return list;
1762
}
1763

    
1764
static void *janus_recordplay_playout_thread(void *data) {
1765
        janus_recordplay_session *session = (janus_recordplay_session *)data;
1766
        if(!session) {
1767
                JANUS_LOG(LOG_ERR, "Invalid session, can't start playout thread...\n");
1768
                g_thread_unref(g_thread_self());
1769
                return NULL;
1770
        }
1771
        if(session->recorder) {
1772
                JANUS_LOG(LOG_ERR, "This is a recorder, can't start playout thread...\n");
1773
                g_thread_unref(g_thread_self());
1774
                return NULL;
1775
        }
1776
        if(!session->aframes && !session->vframes) {
1777
                JANUS_LOG(LOG_ERR, "No audio and no video frames, can't start playout thread...\n");
1778
                g_thread_unref(g_thread_self());
1779
                return NULL;
1780
        }
1781
        JANUS_LOG(LOG_INFO, "Joining playout thread\n");
1782
        /* Open the files */
1783
        FILE *afile = NULL, *vfile = NULL;
1784
        if(session->aframes) {
1785
                char source[1024];
1786
                if(strstr(session->recording->arc_file, ".mjr"))
1787
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->arc_file);
1788
                else
1789
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->arc_file);
1790
                afile = fopen(source, "rb");
1791
                if(afile == NULL) {
1792
                        JANUS_LOG(LOG_ERR, "Could not open audio file %s, can't start playout thread...\n", source);
1793
                        g_thread_unref(g_thread_self());
1794
                        return NULL;
1795
                }
1796
        }
1797
        if(session->vframes) {
1798
                char source[1024];
1799
                if(strstr(session->recording->vrc_file, ".mjr"))
1800
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->vrc_file);
1801
                else
1802
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->vrc_file);
1803
                vfile = fopen(source, "rb");
1804
                if(vfile == NULL) {
1805
                        JANUS_LOG(LOG_ERR, "Could not open video file %s, can't start playout thread...\n", source);
1806
                        if(afile)
1807
                                fclose(afile);
1808
                        afile = NULL;
1809
                        g_thread_unref(g_thread_self());
1810
                        return NULL;
1811
                }
1812
        }
1813
        
1814
        /* Timer */
1815
        gboolean asent = FALSE, vsent = FALSE;
1816
        struct timeval now, abefore, vbefore;
1817
        time_t d_s, d_us;
1818
        gettimeofday(&now, NULL);
1819
        gettimeofday(&abefore, NULL);
1820
        gettimeofday(&vbefore, NULL);
1821

    
1822
        janus_recordplay_frame_packet *audio = session->aframes, *video = session->vframes;
1823
        char *buffer = (char *)calloc(1500, sizeof(char));
1824
        memset(buffer, 0, 1500);
1825
        int bytes = 0;
1826
        int64_t ts_diff = 0, passed = 0;
1827
        
1828
        while(!session->destroyed && session->active && (audio || video)) {
1829
                if(!asent && !vsent) {
1830
                        /* We skipped the last round, so sleep a bit (5ms) */
1831
                        usleep(5000);
1832
                }
1833
                asent = FALSE;
1834
                vsent = FALSE;
1835
                if(audio) {
1836
                        if(audio == session->aframes) {
1837
                                /* First packet, send now */
1838
                                fseek(afile, audio->offset, SEEK_SET);
1839
                                bytes = fread(buffer, sizeof(char), audio->len, afile);
1840
                                if(bytes != audio->len)
1841
                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1842
                                /* Update payload type */
1843
                                rtp_header *rtp = (rtp_header *)buffer;
1844
                                rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1845
                                if(gateway != NULL)
1846
                                        gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1847
                                gettimeofday(&now, NULL);
1848
                                abefore.tv_sec = now.tv_sec;
1849
                                abefore.tv_usec = now.tv_usec;
1850
                                asent = TRUE;
1851
                                audio = audio->next;
1852
                        } else {
1853
                                /* What's the timestamp skip from the previous packet? */
1854
                                ts_diff = audio->ts - audio->prev->ts;
1855
                                ts_diff = (ts_diff*1000)/48;        /* FIXME Again, we're assuming Opus and it's 48khz */
1856
                                /* Check if it's time to send */
1857
                                gettimeofday(&now, NULL);
1858
                                d_s = now.tv_sec - abefore.tv_sec;
1859
                                d_us = now.tv_usec - abefore.tv_usec;
1860
                                if(d_us < 0) {
1861
                                        d_us += 1000000;
1862
                                        --d_s;
1863
                                }
1864
                                passed = d_s*1000000 + d_us;
1865
                                if(passed < (ts_diff-5000)) {
1866
                                        asent = FALSE;
1867
                                } else {
1868
                                        /* Update the reference time */
1869
                                        abefore.tv_usec += ts_diff%1000000;
1870
                                        if(abefore.tv_usec > 1000000) {
1871
                                                abefore.tv_sec++;
1872
                                                abefore.tv_usec -= 1000000;
1873
                                        }
1874
                                        if(ts_diff/1000000 > 0) {
1875
                                                abefore.tv_sec += ts_diff/1000000;
1876
                                                abefore.tv_usec -= ts_diff/1000000;
1877
                                        }
1878
                                        /* Send now */
1879
                                        fseek(afile, audio->offset, SEEK_SET);
1880
                                        bytes = fread(buffer, sizeof(char), audio->len, afile);
1881
                                        if(bytes != audio->len)
1882
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1883
                                        /* Update payload type */
1884
                                        rtp_header *rtp = (rtp_header *)buffer;
1885
                                        rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1886
                                        if(gateway != NULL)
1887
                                                gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1888
                                        asent = TRUE;
1889
                                        audio = audio->next;
1890
                                }
1891
                        }
1892
                }
1893
                if(video) {
1894
                        if(video == session->vframes) {
1895
                                /* First packets: there may be many of them with the same timestamp, send them all */
1896
                                uint64_t ts = video->ts;
1897
                                while(video && video->ts == ts) {
1898
                                        fseek(vfile, video->offset, SEEK_SET);
1899
                                        bytes = fread(buffer, sizeof(char), video->len, vfile);
1900
                                        if(bytes != video->len)
1901
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
1902
                                        /* Update payload type */
1903
                                        rtp_header *rtp = (rtp_header *)buffer;
1904
                                        rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
1905
                                        if(gateway != NULL)
1906
                                                gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
1907
                                        video = video->next;
1908
                                }
1909
                                vsent = TRUE;
1910
                                gettimeofday(&now, NULL);
1911
                                vbefore.tv_sec = now.tv_sec;
1912
                                vbefore.tv_usec = now.tv_usec;
1913
                        } else {
1914
                                /* What's the timestamp skip from the previous packet? */
1915
                                ts_diff = video->ts - video->prev->ts;
1916
                                ts_diff = (ts_diff*1000)/90;
1917
                                /* Check if it's time to send */
1918
                                gettimeofday(&now, NULL);
1919
                                d_s = now.tv_sec - vbefore.tv_sec;
1920
                                d_us = now.tv_usec - vbefore.tv_usec;
1921
                                if(d_us < 0) {
1922
                                        d_us += 1000000;
1923
                                        --d_s;
1924
                                }
1925
                                passed = d_s*1000000 + d_us;
1926
                                if(passed < (ts_diff-5000)) {
1927
                                        vsent = FALSE;
1928
                                } else {
1929
                                        /* Update the reference time */
1930
                                        vbefore.tv_usec += ts_diff%1000000;
1931
                                        if(vbefore.tv_usec > 1000000) {
1932
                                                vbefore.tv_sec++;
1933
                                                vbefore.tv_usec -= 1000000;
1934
                                        }
1935
                                        if(ts_diff/1000000 > 0) {
1936
                                                vbefore.tv_sec += ts_diff/1000000;
1937
                                                vbefore.tv_usec -= ts_diff/1000000;
1938
                                        }
1939
                                        /* There may be multiple packets with the same timestamp, send them all */
1940
                                        uint64_t ts = video->ts;
1941
                                        while(video && video->ts == ts) {
1942
                                                /* Send now */
1943
                                                fseek(vfile, video->offset, SEEK_SET);
1944
                                                bytes = fread(buffer, sizeof(char), video->len, vfile);
1945
                                                if(bytes != video->len)
1946
                                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
1947
                                                /* Update payload type */
1948
                                                rtp_header *rtp = (rtp_header *)buffer;
1949
                                                rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
1950
                                                if(gateway != NULL)
1951
                                                        gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
1952
                                                video = video->next;
1953
                                        }
1954
                                        vsent = TRUE;
1955
                                }
1956
                        }
1957
                }
1958
        }
1959
        
1960
        g_free(buffer);
1961

    
1962
        /* Get rid of the indexes */
1963
        janus_recordplay_frame_packet *tmp = NULL;
1964
        audio = session->aframes;
1965
        while(audio) {
1966
                tmp = audio->next;
1967
                g_free(audio);
1968
                audio = tmp;
1969
        }
1970
        session->aframes = NULL;
1971
        video = session->vframes;
1972
        while(video) {
1973
                tmp = video->next;
1974
                g_free(video);
1975
                video = tmp;
1976
        }
1977
        session->vframes = NULL;
1978

    
1979
        if(afile)
1980
                fclose(afile);
1981
        afile = NULL;
1982
        if(vfile)
1983
                fclose(vfile);
1984
        vfile = NULL;
1985

    
1986
        /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
1987
        gateway->close_pc(session->handle);
1988
        
1989
        JANUS_LOG(LOG_INFO, "Leaving playout thread\n");
1990
        g_thread_unref(g_thread_self());
1991
        return NULL;
1992
}