Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_recordplay.c @ 8d5a4270

History | View | Annotate | Download (63.1 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_hangup_media(janus_plugin_session *handle);
289
void janus_recordplay_destroy_session(janus_plugin_session *handle, int *error);
290
char *janus_recordplay_query_session(janus_plugin_session *handle);
291

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

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

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

    
323

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

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

    
340
typedef struct janus_recordplay_rtp_header_extension {
341
        uint16_t type;
342
        uint16_t length;
343
} janus_recordplay_rtp_header_extension;
344

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

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

    
365
typedef struct janus_recordplay_session {
366
        janus_plugin_session *handle;
367
        gboolean active;
368
        gboolean recorder;                /* Whether this session is used to record or to replay a WebRTC session */
369
        gboolean firefox;        /* We send Firefox users a different kind of FIR */
370
        janus_recordplay_recording *recording;
371
        janus_recorder *arc;        /* Audio recorder */
372
        janus_recorder *vrc;        /* Video recorder */
373
        janus_recordplay_frame_packet *aframes;        /* Audio frames (for playout) */
374
        janus_recordplay_frame_packet *vframes;        /* Video frames (for playout) */
375
        guint remb_video_startup;
376
        guint64 remb_video_last;
377
        guint64 video_bitrate;
378
        guint64 destroyed;        /* Time at which this session was marked as destroyed */
379
} janus_recordplay_session;
380
static GHashTable *sessions;
381
static GList *old_sessions;
382
static janus_mutex sessions_mutex;
383

    
384

    
385
static char *recordings_path = NULL;
386
void janus_recordplay_update_recordings_list(void);
387
static void *janus_recordplay_playout_thread(void *data);
388

    
389

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

    
414

    
415
void janus_recordplay_message_free(janus_recordplay_message *msg);
416
void janus_recordplay_message_free(janus_recordplay_message *msg) {
417
        if(!msg)
418
                return;
419

    
420
        msg->handle = NULL;
421

    
422
        g_free(msg->transaction);
423
        msg->transaction = NULL;
424
        g_free(msg->message);
425
        msg->message = NULL;
426
        g_free(msg->sdp_type);
427
        msg->sdp_type = NULL;
428
        g_free(msg->sdp);
429
        msg->sdp = NULL;
430

    
431
        g_free(msg);
432
}
433

    
434

    
435
/* Error codes */
436
#define JANUS_RECORDPLAY_ERROR_NO_MESSAGE                        411
437
#define JANUS_RECORDPLAY_ERROR_INVALID_JSON                412
438
#define JANUS_RECORDPLAY_ERROR_INVALID_REQUEST        413
439
#define JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT        414
440
#define JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT        415
441
#define JANUS_RECORDPLAY_ERROR_NOT_FOUND        416
442
#define JANUS_RECORDPLAY_ERROR_INVALID_RECORDING        417
443
#define JANUS_RECORDPLAY_ERROR_INVALID_STATE        418
444
#define JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR        499
445

    
446

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

    
486

    
487
/* Plugin implementation */
488
int janus_recordplay_init(janus_callbacks *callback, const char *config_path) {
489
        if(g_atomic_int_get(&stopping)) {
490
                /* Still stopping from before */
491
                return -1;
492
        }
493
        if(callback == NULL || config_path == NULL) {
494
                /* Invalid arguments */
495
                return -1;
496
        }
497

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

    
538
        g_atomic_int_set(&initialized, 1);
539

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

    
559
void janus_recordplay_destroy(void) {
560
        if(!g_atomic_int_get(&initialized))
561
                return;
562
        g_atomic_int_set(&stopping, 1);
563
        if(handler_thread != NULL) {
564
                g_thread_join(handler_thread);
565
                handler_thread = NULL;
566
        }
567
        if(watchdog != NULL) {
568
                g_thread_join(watchdog);
569
                watchdog = NULL;
570
        }
571
        /* FIXME We should destroy the sessions cleanly */
572
        janus_mutex_lock(&sessions_mutex);
573
        g_hash_table_destroy(sessions);
574
        janus_mutex_unlock(&sessions_mutex);
575
        g_async_queue_unref(messages);
576
        messages = NULL;
577
        sessions = NULL;
578
        g_atomic_int_set(&initialized, 0);
579
        g_atomic_int_set(&stopping, 0);
580
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_RECORDPLAY_NAME);
581
}
582

    
583
int janus_recordplay_get_api_compatibility(void) {
584
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
585
        return JANUS_PLUGIN_API_VERSION;
586
}
587

    
588
int janus_recordplay_get_version(void) {
589
        return JANUS_RECORDPLAY_VERSION;
590
}
591

    
592
const char *janus_recordplay_get_version_string(void) {
593
        return JANUS_RECORDPLAY_VERSION_STRING;
594
}
595

    
596
const char *janus_recordplay_get_description(void) {
597
        return JANUS_RECORDPLAY_DESCRIPTION;
598
}
599

    
600
const char *janus_recordplay_get_name(void) {
601
        return JANUS_RECORDPLAY_NAME;
602
}
603

    
604
const char *janus_recordplay_get_author(void) {
605
        return JANUS_RECORDPLAY_AUTHOR;
606
}
607

    
608
const char *janus_recordplay_get_package(void) {
609
        return JANUS_RECORDPLAY_PACKAGE;
610
}
611

    
612
void janus_recordplay_create_session(janus_plugin_session *handle, int *error) {
613
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
614
                *error = -1;
615
                return;
616
        }        
617
        janus_recordplay_session *session = (janus_recordplay_session *)calloc(1, sizeof(janus_recordplay_session));
618
        if(session == NULL) {
619
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
620
                *error = -2;
621
                return;
622
        }
623
        session->handle = handle;
624
        session->active = FALSE;
625
        session->recorder = FALSE;
626
        session->firefox = FALSE;
627
        session->arc = NULL;
628
        session->vrc = NULL;
629
        session->destroyed = 0;
630
        session->remb_video_startup = 4;
631
        session->remb_video_last = janus_get_monotonic_time();
632
        session->video_bitrate = 1024 * 1024; // 1 megabit
633
        handle->plugin_handle = session;
634
        janus_mutex_lock(&sessions_mutex);
635
        g_hash_table_insert(sessions, handle, session);
636
        janus_mutex_unlock(&sessions_mutex);
637

    
638
        return;
639
}
640

    
641
void janus_recordplay_destroy_session(janus_plugin_session *handle, int *error) {
642
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
643
                *error = -1;
644
                return;
645
        }        
646
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
647
        if(!session) {
648
                JANUS_LOG(LOG_ERR, "No Record&Play session associated with this handle...\n");
649
                *error = -2;
650
                return;
651
        }
652
        if(session->destroyed) {
653
                JANUS_LOG(LOG_WARN, "Record&Play session already destroyed...\n");
654
                return;
655
        }
656
        JANUS_LOG(LOG_VERB, "Removing Record&Play session...\n");
657
        janus_mutex_lock(&sessions_mutex);
658
        g_hash_table_remove(sessions, handle);
659
        janus_mutex_unlock(&sessions_mutex);
660
        /* Cleaning up and removing the session is done in a lazy way */
661
        session->destroyed = janus_get_monotonic_time();
662
        janus_mutex_lock(&sessions_mutex);
663
        old_sessions = g_list_append(old_sessions, session);
664
        janus_mutex_unlock(&sessions_mutex);
665
        return;
666
}
667

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

    
690
struct janus_plugin_result *janus_recordplay_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
691
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
692
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
693
        JANUS_LOG(LOG_VERB, "%s\n", message);
694

    
695
        /* Pre-parse the message */
696
        int error_code = 0;
697
        char error_cause[512];        /* FIXME 512 should be enough, but anyway... */
698
        json_t *root = NULL;
699
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
700
        if(!session) {
701
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
702
                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
703
                g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
704
                goto error;
705
        }
706
        if(session->destroyed) {
707
                JANUS_LOG(LOG_ERR, "Session has already been destroyed...\n");
708
                error_code = JANUS_RECORDPLAY_ERROR_UNKNOWN_ERROR;
709
                g_snprintf(error_cause, 512, "%s", "Session has already been destroyed...");
710
                goto error;
711
        }
712
        error_code = 0;
713
        JANUS_LOG(LOG_VERB, "Handling message: %s\n", message);
714
        if(message == NULL) {
715
                JANUS_LOG(LOG_ERR, "No message??\n");
716
                error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
717
                g_snprintf(error_cause, 512, "%s", "No message??");
718
                goto error;
719
        }
720
        json_error_t error;
721
        root = json_loads(message, 0, &error);
722
        if(!root) {
723
                JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
724
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_JSON;
725
                g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
726
                goto error;
727
        }
728
        if(!json_is_object(root)) {
729
                JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
730
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_JSON;
731
                g_snprintf(error_cause, 512, "JSON error: not an object");
732
                goto error;
733
        }
734
        /* Get the request first */
735
        json_t *request = json_object_get(root, "request");
736
        if(!request) {
737
                JANUS_LOG(LOG_ERR, "Missing element (request)\n");
738
                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
739
                g_snprintf(error_cause, 512, "Missing element (request)");
740
                goto error;
741
        }
742
        if(!json_is_string(request)) {
743
                JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
744
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
745
                g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
746
                goto error;
747
        }
748
        /* Some requests ('create' and 'destroy') can be handled synchronously */
749
        const char *request_text = json_string_value(request);
750
        if(!strcasecmp(request_text, "update")) {
751
                /* Update list of available recordings, scanning the folder again */
752
                janus_recordplay_update_recordings_list();
753
                /* Send info back */
754
                json_t *response = json_object();
755
                json_object_set_new(response, "recordplay", json_string("ok"));
756
                char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
757
                json_decref(response);
758
                janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
759
                g_free(response_text);
760
                return result;
761
        } else if(!strcasecmp(request_text, "list")) {
762
                json_t *list = json_array();
763
                JANUS_LOG(LOG_VERB, "Request for the list of recordings\n");
764
                /* Return a list of all available recordings */
765
                janus_mutex_lock(&recordings_mutex);
766
                GHashTableIter iter;
767
                gpointer value;
768
                g_hash_table_iter_init(&iter, recordings);
769
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
770
                        janus_recordplay_recording *rec = value;
771
                        json_t *ml = json_object();
772
                        json_object_set_new(ml, "id", json_integer(rec->id));
773
                        json_object_set_new(ml, "name", json_string(rec->name));
774
                        json_object_set_new(ml, "date", json_string(rec->date));
775
                        json_object_set_new(ml, "audio", json_string(rec->arc_file ? "false" : "true"));
776
                        json_object_set_new(ml, "video", json_string(rec->vrc_file ? "false" : "true"));
777
                        json_array_append_new(list, ml);
778
                }
779
                janus_mutex_unlock(&recordings_mutex);
780
                /* Send info back */
781
                json_t *response = json_object();
782
                json_object_set_new(response, "recordplay", json_string("list"));
783
                json_object_set_new(response, "list", list);
784
                char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
785
                json_decref(response);
786
                janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, response_text);
787
                g_free(response_text);
788
                return result;
789
        } else if(!strcasecmp(request_text, "record") || !strcasecmp(request_text, "play")
790
                        || !strcasecmp(request_text, "start") || !strcasecmp(request_text, "stop")) {
791
                /* These messages are handled asynchronously */
792
                goto async;
793
        } else {
794
                JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
795
                error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
796
                g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
797
                goto error;
798
        }
799

    
800
error:
801
                {
802
                        if(root != NULL)
803
                                json_decref(root);
804
                        /* Prepare JSON error event */
805
                        json_t *event = json_object();
806
                        json_object_set_new(event, "recordplay", json_string("event"));
807
                        json_object_set_new(event, "error_code", json_integer(error_code));
808
                        json_object_set_new(event, "error", json_string(error_cause));
809
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
810
                        json_decref(event);
811
                        janus_plugin_result *result = janus_plugin_result_new(JANUS_PLUGIN_OK, event_text);
812
                        g_free(event_text);
813
                        return result;
814
                }
815

    
816
async:
817
                {
818
                        /* All the other requests to this plugin are handled asynchronously */
819
                        janus_recordplay_message *msg = calloc(1, sizeof(janus_recordplay_message));
820
                        if(msg == NULL) {
821
                                JANUS_LOG(LOG_FATAL, "Memory error!\n");
822
                                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, "Memory error");
823
                        }
824
                        msg->handle = handle;
825
                        msg->transaction = transaction;
826
                        msg->message = root;
827
                        msg->sdp_type = sdp_type;
828
                        msg->sdp = sdp;
829

    
830
                        g_async_queue_push(messages, msg);
831

    
832
                        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
833
                }
834
}
835

    
836
void janus_recordplay_setup_media(janus_plugin_session *handle) {
837
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
838
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
839
                return;
840
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
841
        if(!session) {
842
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
843
                return;
844
        }
845
        if(session->destroyed)
846
                return;
847
        /* Take note of the fact that the session is now active */
848
        session->active = TRUE;
849
        if(!session->recorder) {
850
                GError *error = NULL;
851
                g_thread_try_new("recordplay playout thread", &janus_recordplay_playout_thread, session, &error);
852
                if(error != NULL) {
853
                        /* FIXME Should we notify this back to the user somehow? */
854
                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Record&Play playout thread...\n", error->code, error->message ? error->message : "??");
855
                }
856
        }
857
}
858

    
859
void janus_recordplay_send_rtcp_feedback(janus_plugin_session *handle, int video, char *buf, int len) {
860
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
861

    
862
        if (video != 1) { return; } // we just do this for video, for now
863

    
864
        // TODO: send PLI if we lost packets (comparing sequence numbers)
865
        // memset(rtcpbuf, 0, 12);
866
        // janus_rtcp_pli((char *)&rtcpbuf, 12);
867
        // gateway->relay_rtcp(handle, video, rtcpbuf, 12);
868

    
869
        // send REMB every second
870
        gint64 now = janus_get_monotonic_time();
871
        guint64 elapsed = now - session->remb_video_last;
872

    
873
        if (elapsed < G_USEC_PER_SEC) { return; }
874

    
875
        session->remb_video_last = now;
876
        uint64_t bitrate = session->video_bitrate;
877

    
878
        // Turns out ramp-up is not doing anything (Chrome)
879
        if (session->remb_video_startup > 0) {
880
                bitrate = bitrate / session->remb_video_startup;
881
                session->remb_video_startup--;
882
        }
883

    
884
        char rtcpbuf[200];
885
        memset(rtcpbuf, 0, 200);
886
        /* FIXME First put a RR (fake)... */
887
        int rrlen = 32;
888
        rtcp_rr *rr = (rtcp_rr *)&rtcpbuf;
889
        rr->header.version = 2;
890
        rr->header.type = RTCP_RR;
891
        rr->header.rc = 1;
892
        rr->header.length = htons((rrlen/4)-1);
893
        /* ... then put a SDES... */
894
        int sdeslen = janus_rtcp_sdes((char *)(&rtcpbuf)+rrlen, 200-rrlen, "janusvideo", 10);
895

    
896
        if(sdeslen > 0) {
897
                /* ... and then finally a REMB */
898
                janus_rtcp_remb((char *)(&rtcpbuf)+rrlen+sdeslen, 24, bitrate);
899
                gateway->relay_rtcp(handle, video, rtcpbuf, rrlen+sdeslen+24);
900
        }
901
}
902

    
903
void janus_recordplay_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
904
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
905
                return;
906
        if(gateway) {
907
                janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;        
908
                if(!session) {
909
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
910
                        return;
911
                }
912
                if(session->destroyed)
913
                        return;
914
                /* Are we recording? */
915
                if(session->recorder) {
916
                        if(video && session->vrc)
917
                                janus_recorder_save_frame(session->vrc, buf, len);
918
                        else if(!video && session->arc)
919
                                janus_recorder_save_frame(session->arc, buf, len);
920
                }
921

    
922
                janus_recordplay_send_rtcp_feedback(handle, video, buf, len);
923
        }
924
}
925

    
926
void janus_recordplay_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
927
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
928
                return;
929
}
930

    
931
void janus_recordplay_incoming_data(janus_plugin_session *handle, char *buf, int len) {
932
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
933
                return;
934
        /* FIXME We don't care */
935
}
936

    
937
void janus_recordplay_hangup_media(janus_plugin_session *handle) {
938
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
939
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
940
                return;
941
        janus_recordplay_session *session = (janus_recordplay_session *)handle->plugin_handle;
942
        if(!session) {
943
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
944
                return;
945
        }
946
        if(session->destroyed)
947
                return;
948
        session->active = FALSE;
949
        if(!session->recorder)
950
                return;
951

    
952
        /* Send an event to the browser and tell it's over */
953
        json_t *event = json_object();
954
        json_object_set_new(event, "recordplay", json_string("event"));
955
        json_object_set_new(event, "result", json_string("done"));
956
        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
957
        json_decref(event);
958
        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
959
        int ret = gateway->push_event(handle, &janus_recordplay_plugin, NULL, event_text, NULL, NULL);
960
        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
961
        g_free(event_text);
962

    
963
        /* FIXME Simulate a "stop" coming from the browser */
964
        janus_recordplay_message *msg = calloc(1, sizeof(janus_recordplay_message));
965
        msg->handle = handle;
966
        msg->message = json_loads("{\"request\":\"stop\"}", 0, NULL);
967
        msg->transaction = NULL;
968
        msg->sdp_type = NULL;
969
        msg->sdp = NULL;
970
        g_async_queue_push(messages, msg);
971
}
972

    
973
/* Thread to handle incoming messages */
974
static void *janus_recordplay_handler(void *data) {
975
        JANUS_LOG(LOG_VERB, "Joining Record&Play handler thread\n");
976
        janus_recordplay_message *msg = NULL;
977
        int error_code = 0;
978
        char *error_cause = calloc(512, sizeof(char));        /* FIXME 512 should be enough, but anyway... */
979
        if(error_cause == NULL) {
980
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
981
                return NULL;
982
        }
983
        json_t *root = NULL;
984
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
985
                if(!messages || (msg = g_async_queue_try_pop(messages)) == NULL) {
986
                        usleep(50000);
987
                        continue;
988
                }
989
                janus_recordplay_session *session = (janus_recordplay_session *)msg->handle->plugin_handle;
990
                if(!session) {
991
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
992
                        janus_recordplay_message_free(msg);
993
                        continue;
994
                }
995
                if(session->destroyed) {
996
                        janus_recordplay_message_free(msg);
997
                        continue;
998
                }
999
                /* Handle request */
1000
                error_code = 0;
1001
                root = NULL;
1002
                if(msg->message == NULL) {
1003
                        JANUS_LOG(LOG_ERR, "No message??\n");
1004
                        error_code = JANUS_RECORDPLAY_ERROR_NO_MESSAGE;
1005
                        g_snprintf(error_cause, 512, "%s", "No message??");
1006
                        goto error;
1007
                }
1008
                root = msg->message;
1009
                /* Get the request first */
1010
                json_t *request = json_object_get(root, "request");
1011
                if(!request) {
1012
                        JANUS_LOG(LOG_ERR, "Missing element (request)\n");
1013
                        error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1014
                        g_snprintf(error_cause, 512, "Missing element (request)");
1015
                        goto error;
1016
                }
1017
                if(!json_is_string(request)) {
1018
                        JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
1019
                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1020
                        g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
1021
                        goto error;
1022
                }
1023
                const char *request_text = json_string_value(request);
1024
                json_t *event = NULL;
1025
                json_t *result = NULL;
1026
                char *sdp = NULL;
1027
                const char *filename_text = NULL;
1028
                if(!strcasecmp(request_text, "record")) {
1029
                        if(!msg->sdp) {
1030
                                JANUS_LOG(LOG_ERR, "Missing SDP offer\n");
1031
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1032
                                g_snprintf(error_cause, 512, "Missing SDP offer");
1033
                                goto error;
1034
                        }
1035
                        json_t *name = json_object_get(root, "name");
1036
                        if(!name) {
1037
                                JANUS_LOG(LOG_ERR, "Missing element (name)\n");
1038
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1039
                                g_snprintf(error_cause, 512, "Missing element (name)");
1040
                                goto error;
1041
                        }
1042
                        if(!json_is_string(name)) {
1043
                                JANUS_LOG(LOG_ERR, "Invalid element (name should be a string)\n");
1044
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1045
                                g_snprintf(error_cause, 512, "Invalid element (name should be a string)");
1046
                                goto error;
1047
                        }
1048
                        json_t *filename = json_object_get(root, "filename");
1049
                        if (filename) {
1050
                                if(!json_is_string(name)) {
1051
                                        JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
1052
                                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1053
                                        g_snprintf(error_cause, 512, "Invalid element (filename should be a string)");
1054
                                        goto error;
1055
                                }
1056
                                filename_text = json_string_value(filename);
1057
                        }
1058
                        const char *name_text = json_string_value(name);
1059
                        guint64 id = 0;
1060
                        while(id == 0) {
1061
                                id = g_random_int();
1062
                                if(g_hash_table_lookup(recordings, GUINT_TO_POINTER(id)) != NULL) {
1063
                                        /* Room ID already taken, try another one */
1064
                                        id = 0;
1065
                                }
1066
                        }
1067
                        JANUS_LOG(LOG_VERB, "Starting new recording with ID %"SCNu64"\n", id);
1068
                        janus_recordplay_recording *rec = (janus_recordplay_recording *)calloc(1, sizeof(janus_recordplay_recording));
1069
                        rec->id = id;
1070
                        rec->name = g_strdup(name_text);
1071
                        /* Create a date string */
1072
                        time_t t = time(NULL);
1073
                        struct tm *tmv = localtime(&t);
1074
                        char outstr[200];
1075
                        strftime(outstr, sizeof(outstr), "%Y-%m-%d %H:%M:%S", tmv);
1076
                        rec->date = g_strdup(outstr);
1077
                        if(strstr(msg->sdp, "m=audio")) {
1078
                                char filename[256];
1079
                                if (filename_text != NULL) {
1080
                                        g_snprintf(filename, 256, "%s-audio", filename_text);
1081
                                } else {
1082
                                        g_snprintf(filename, 256, "rec-%"SCNu64"-audio", id);
1083
                                }
1084
                                rec->arc_file = g_strdup(filename);
1085
                                session->arc = janus_recorder_create(recordings_path, 0, rec->arc_file);
1086
                        }
1087
                        if(strstr(msg->sdp, "m=video")) {
1088
                                char filename[256];
1089
                                if (filename_text != NULL) {
1090
                                        g_snprintf(filename, 256, "%s-video", filename_text);
1091
                                } else {
1092
                                        g_snprintf(filename, 256, "rec-%"SCNu64"-video", id);
1093
                                }
1094
                                rec->vrc_file = g_strdup(filename);
1095
                                session->vrc = janus_recorder_create(recordings_path, 1, rec->vrc_file);
1096
                        }
1097
                        session->recorder = TRUE;
1098
                        session->recording = rec;
1099
                        janus_mutex_lock(&recordings_mutex);
1100
                        g_hash_table_insert(recordings, GINT_TO_POINTER(rec->id), rec);
1101
                        janus_mutex_unlock(&recordings_mutex);
1102
                        /* We need to prepare an answer */
1103
                        int opus_pt = 0, vp8_pt = 0;
1104
                        opus_pt = janus_get_opus_pt(msg->sdp);
1105
                        JANUS_LOG(LOG_VERB, "Opus payload type is %d\n", opus_pt);
1106
                        vp8_pt = janus_get_vp8_pt(msg->sdp);
1107
                        JANUS_LOG(LOG_VERB, "VP8 payload type is %d\n", vp8_pt);
1108
                        char sdptemp[1024], audio_mline[256], video_mline[512];
1109
                        if(opus_pt > 0) {
1110
                                g_snprintf(audio_mline, 256, sdp_a_template,
1111
                                        opus_pt,                                                /* Opus payload type */
1112
                                        "recvonly",                                                /* Recording is recvonly */
1113
                                        opus_pt);                                                 /* Opus payload type */
1114
                        } else {
1115
                                audio_mline[0] = '\0';
1116
                        }
1117
                        if(vp8_pt > 0) {
1118
                                g_snprintf(video_mline, 512, sdp_v_template,
1119
                                        vp8_pt,                                                        /* VP8 payload type */
1120
                                        "recvonly",                                                /* Recording is recvonly */
1121
                                        vp8_pt,                                                 /* VP8 payload type */
1122
                                        vp8_pt,                                                 /* VP8 payload type */
1123
                                        vp8_pt,                                                 /* VP8 payload type */
1124
                                        vp8_pt,                                                 /* VP8 payload type */
1125
                                        vp8_pt);                                                 /* VP8 payload type */
1126
                        } else {
1127
                                video_mline[0] = '\0';
1128
                        }
1129
                        g_snprintf(sdptemp, 1024, sdp_template,
1130
                                janus_get_monotonic_time(),                /* We need current time here */
1131
                                janus_get_monotonic_time(),                /* We need current time here */
1132
                                session->recording->name,                /* Playout session */
1133
                                audio_mline,                                        /* Audio m-line, if any */
1134
                                video_mline);                                        /* Video m-line, if any */
1135
                        sdp = g_strdup(sdptemp);
1136
                        JANUS_LOG(LOG_VERB, "Going to answer this SDP:\n%s\n", sdp);
1137
                        /* Done! */
1138
                        result = json_object();
1139
                        json_object_set_new(result, "status", json_string("recording"));
1140
                        json_object_set_new(result, "id", json_integer(id));
1141
                } else if(!strcasecmp(request_text, "play")) {
1142
                        if(msg->sdp) {
1143
                                JANUS_LOG(LOG_ERR, "A play request can't contain an SDP\n");
1144
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1145
                                g_snprintf(error_cause, 512, "A play request can't contain an SDP");
1146
                                goto error;
1147
                        }
1148
                        JANUS_LOG(LOG_VERB, "Replaying a recording\n");
1149
                        json_t *id = json_object_get(root, "id");
1150
                        if(!id) {
1151
                                JANUS_LOG(LOG_ERR, "Missing element (id)\n");
1152
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1153
                                g_snprintf(error_cause, 512, "Missing element (id)");
1154
                                goto error;
1155
                        }
1156
                        if(!json_is_integer(id)) {
1157
                                JANUS_LOG(LOG_ERR, "Invalid element (id should be an integer)\n");
1158
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_ELEMENT;
1159
                                g_snprintf(error_cause, 512, "Invalid element (id should be an integer)");
1160
                                goto error;
1161
                        }
1162
                        guint64 id_value = json_integer_value(id);
1163
                        /* Look for this recording */
1164
                        janus_mutex_lock(&recordings_mutex);
1165
                        janus_recordplay_recording *rec = g_hash_table_lookup(recordings, GINT_TO_POINTER(id_value));
1166
                        janus_mutex_unlock(&recordings_mutex);
1167
                        if(rec == NULL) {
1168
                                JANUS_LOG(LOG_ERR, "No such recording\n");
1169
                                error_code = JANUS_RECORDPLAY_ERROR_NOT_FOUND;
1170
                                g_snprintf(error_cause, 512, "No such recording");
1171
                                goto error;
1172
                        }
1173
                        /* Access the frames */
1174
                        if(rec->arc_file) {
1175
                                session->aframes = janus_recordplay_get_frames(recordings_path, rec->arc_file);
1176
                                if(session->aframes == NULL) {
1177
                                        JANUS_LOG(LOG_ERR, "Error opening audio recording\n");
1178
                                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_RECORDING;
1179
                                        g_snprintf(error_cause, 512, "Error opening audio recording");
1180
                                        goto error;
1181
                                }
1182
                        }
1183
                        if(rec->vrc_file) {
1184
                                session->vframes = janus_recordplay_get_frames(recordings_path, rec->vrc_file);
1185
                                if(session->vframes == NULL) {
1186
                                        JANUS_LOG(LOG_ERR, "Error opening video recording\n");
1187
                                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_RECORDING;
1188
                                        g_snprintf(error_cause, 512, "Error opening video recording");
1189
                                        goto error;
1190
                                }
1191
                        }
1192
                        session->recording = rec;
1193
                        session->recorder = FALSE;
1194
                        /* We need to prepare an offer */
1195
                        char sdptemp[1024], audio_mline[256], video_mline[512];
1196
                        if(session->recording->arc_file) {
1197
                                g_snprintf(audio_mline, 256, sdp_a_template,
1198
                                        OPUS_PT,                                                /* Opus payload type */
1199
                                        "sendonly",                                                /* Playout is sendonly */
1200
                                        OPUS_PT);                                                 /* Opus payload type */
1201
                        } else {
1202
                                audio_mline[0] = '\0';
1203
                        }
1204
                        if(session->recording->vrc_file) {
1205
                                g_snprintf(video_mline, 512, sdp_v_template,
1206
                                        VP8_PT,                                                        /* VP8 payload type */
1207
                                        "sendonly",                                                /* Playout is sendonly */
1208
                                        VP8_PT,                                                 /* VP8 payload type */
1209
                                        VP8_PT,                                                 /* VP8 payload type */
1210
                                        VP8_PT,                                                 /* VP8 payload type */
1211
                                        VP8_PT,                                                 /* VP8 payload type */
1212
                                        VP8_PT);                                                 /* VP8 payload type */
1213
                        } else {
1214
                                video_mline[0] = '\0';
1215
                        }
1216
                        g_snprintf(sdptemp, 1024, sdp_template,
1217
                                janus_get_monotonic_time(),                /* We need current time here */
1218
                                janus_get_monotonic_time(),                /* We need current time here */
1219
                                session->recording->name,                /* Playout session */
1220
                                audio_mline,                                        /* Audio m-line, if any */
1221
                                video_mline);                                        /* Video m-line, if any */
1222
                        sdp = g_strdup(sdptemp);
1223
                        JANUS_LOG(LOG_VERB, "Going to offer this SDP:\n%s\n", sdp);
1224
                        /* Done! */
1225
                        result = json_object();
1226
                        json_object_set_new(result, "status", json_string("preparing"));
1227
                        json_object_set_new(result, "id", json_integer(id_value));
1228
                } else if(!strcasecmp(request_text, "start")) {
1229
                        if(!session->aframes && !session->vframes) {
1230
                                JANUS_LOG(LOG_ERR, "Not a playout session, can't start\n");
1231
                                error_code = JANUS_RECORDPLAY_ERROR_INVALID_STATE;
1232
                                g_snprintf(error_cause, 512, "Not a playout session, can't start");
1233
                                goto error;
1234
                        }
1235
                        /* Just a final message we make use of, e.g., to receive an ANSWER to our OFFER for a playout */
1236
                        if(!msg->sdp) {
1237
                                JANUS_LOG(LOG_ERR, "Missing SDP answer\n");
1238
                                error_code = JANUS_RECORDPLAY_ERROR_MISSING_ELEMENT;
1239
                                g_snprintf(error_cause, 512, "Missing SDP answer");
1240
                                goto error;
1241
                        }
1242
                        /* Done! */
1243
                        result = json_object();
1244
                        json_object_set_new(result, "status", json_string("playing"));
1245
                } else if(!strcasecmp(request_text, "stop")) {
1246
                        /* Stop the recording/playout */
1247
                        session->active = FALSE;
1248
                        if(session->arc) {
1249
                                janus_recorder_close(session->arc);
1250
                                JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1251
                        }
1252
                        session->arc = NULL;
1253
                        if(session->vrc) {
1254
                                janus_recorder_close(session->vrc);
1255
                                JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1256
                        }
1257
                        session->vrc = NULL;
1258
                        if(session->recorder) {
1259
                                /* Create a .nfo file for this recording */
1260
                                char nfofile[1024], nfo[1024];
1261
                                g_snprintf(nfofile, 1024, "%s/%"SCNu64".nfo", recordings_path, session->recording->id);
1262
                                FILE *file = fopen(nfofile, "wt");
1263
                                if(file == NULL) {
1264
                                        JANUS_LOG(LOG_ERR, "Error creating file %s...\n", nfofile);
1265
                                } else {
1266
                                        if(session->recording->arc_file && session->recording->vrc_file) {
1267
                                                g_snprintf(nfo, 1024,
1268
                                                        "[%"SCNu64"]\r\n"
1269
                                                        "name = %s\r\n"
1270
                                                        "date = %s\r\n"
1271
                                                        "audio = %s.mjr\r\n"
1272
                                                        "video = %s.mjr\r\n",
1273
                                                                session->recording->id, session->recording->name, session->recording->date,
1274
                                                                session->recording->arc_file, session->recording->vrc_file);
1275
                                        } else if(session->recording->arc_file) {
1276
                                                g_snprintf(nfo, 1024,
1277
                                                        "[%"SCNu64"]\r\n"
1278
                                                        "name = %s\r\n"
1279
                                                        "date = %s\r\n"
1280
                                                        "audio = %s.mjr\r\n",
1281
                                                                session->recording->id, session->recording->name, session->recording->date,
1282
                                                                session->recording->arc_file);
1283
                                        } else if(session->recording->vrc_file) {
1284
                                                g_snprintf(nfo, 1024,
1285
                                                        "[%"SCNu64"]\r\n"
1286
                                                        "name = %s\r\n"
1287
                                                        "date = %s\r\n"
1288
                                                        "video = %s.mjr\r\n",
1289
                                                                session->recording->id, session->recording->name, session->recording->date,
1290
                                                                session->recording->vrc_file);
1291
                                        }
1292
                                        /* Write to the file now */
1293
                                        fwrite(nfo, strlen(nfo), sizeof(char), file);
1294
                                        fclose(file);
1295
                                }
1296
                        }
1297
                        /* Done! */
1298
                        result = json_object();
1299
                        json_object_set_new(result, "status", json_string("stopped"));
1300
                        if(session->recording)
1301
                                json_object_set_new(result, "id", json_integer(session->recording->id));
1302
                } else {
1303
                        JANUS_LOG(LOG_ERR, "Unknown request '%s'\n", request_text);
1304
                        error_code = JANUS_RECORDPLAY_ERROR_INVALID_REQUEST;
1305
                        g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
1306
                        goto error;
1307
                }
1308

    
1309
                /* Any SDP to handle? */
1310
                if(msg->sdp) {
1311
                        session->firefox = strstr(msg->sdp, "Mozilla") ? TRUE : FALSE;
1312
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1313
                }
1314

    
1315
                /* Prepare JSON event */
1316
                event = json_object();
1317
                json_object_set_new(event, "recordplay", json_string("event"));
1318
                if(result != NULL)
1319
                        json_object_set(event, "result", result);
1320
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1321
                json_decref(event);
1322
                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1323
                if(!sdp) {
1324
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, NULL, NULL);
1325
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1326
                } else {
1327
                        const char *type = session->recorder ? "answer" : "offer";
1328
                        /* How long will the gateway take to push the event? */
1329
                        gint64 start = janus_get_monotonic_time();
1330
                        int res = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, type, sdp);
1331
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
1332
                                res, janus_get_monotonic_time()-start);
1333
                }
1334
                g_free(event_text);
1335
                janus_recordplay_message_free(msg);
1336
                continue;
1337
                
1338
error:
1339
                {
1340
                        /* Prepare JSON error event */
1341
                        json_t *event = json_object();
1342
                        json_object_set_new(event, "recordplay", json_string("event"));
1343
                        json_object_set_new(event, "error_code", json_integer(error_code));
1344
                        json_object_set_new(event, "error", json_string(error_cause));
1345
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1346
                        json_decref(event);
1347
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
1348
                        int ret = gateway->push_event(msg->handle, &janus_recordplay_plugin, msg->transaction, event_text, NULL, NULL);
1349
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
1350
                        g_free(event_text);
1351
                        janus_recordplay_message_free(msg);
1352
                }
1353
        }
1354
        g_free(error_cause);
1355
        JANUS_LOG(LOG_VERB, "LeavingRecord&Play handler thread\n");
1356
        return NULL;
1357
}
1358

    
1359
void janus_recordplay_update_recordings_list(void) {
1360
        if(recordings_path == NULL)
1361
                return;
1362
        JANUS_LOG(LOG_VERB, "Updating recordings list in %s\n", recordings_path);
1363
        janus_mutex_lock(&recordings_mutex);
1364
        /* Open dir */
1365
        DIR *dir = opendir(recordings_path);
1366
        if(!dir) {
1367
                JANUS_LOG(LOG_ERR, "Couldn't open folder...\n");
1368
                return;
1369
        }
1370
        struct dirent *recent = NULL;
1371
        char recpath[1024];
1372
        while((recent = readdir(dir))) {
1373
                int len = strlen(recent->d_name);
1374
                if(len < 4)
1375
                        continue;
1376
                if(strcasecmp(recent->d_name+len-4, ".nfo"))
1377
                        continue;
1378
                JANUS_LOG(LOG_VERB, "Importing recording '%s'...\n", recent->d_name);
1379
                memset(recpath, 0, 1024);
1380
                g_snprintf(recpath, 1024, "%s/%s", recordings_path, recent->d_name);
1381
                janus_config *nfo = janus_config_parse(recpath);
1382
                if(nfo == NULL) { 
1383
                        JANUS_LOG(LOG_ERR, "Invalid recording '%s'...\n", recent->d_name);
1384
                        continue;
1385
                }
1386
                janus_config_category *cat = janus_config_get_categories(nfo);
1387
                if(cat == NULL) {
1388
                        JANUS_LOG(LOG_WARN, "No recording info in '%s', skipping...\n", recent->d_name);
1389
                        janus_config_destroy(nfo);
1390
                        continue;
1391
                }
1392
                guint64 id = atol(cat->name);
1393
                if(id == 0) {
1394
                        JANUS_LOG(LOG_WARN, "Invalid ID, skipping...\n");
1395
                        janus_config_destroy(nfo);
1396
                        continue;
1397
                }
1398
                janus_config_item *name = janus_config_get_item(cat, "name");
1399
                janus_config_item *date = janus_config_get_item(cat, "date");
1400
                janus_config_item *audio = janus_config_get_item(cat, "audio");
1401
                janus_config_item *video = janus_config_get_item(cat, "video");
1402
                if(!name || !name->value || !date || !date->value) {
1403
                        JANUS_LOG(LOG_WARN, "Invalid info, skipping...\n");
1404
                        janus_config_destroy(nfo);
1405
                        continue;
1406
                }
1407
                if((!audio || !audio->value) && (!video || !video->value)) {
1408
                        JANUS_LOG(LOG_WARN, "No audio and no video, skipping...\n");
1409
                        janus_config_destroy(nfo);
1410
                        continue;
1411
                }
1412
                janus_recordplay_recording *rec = (janus_recordplay_recording *)calloc(1, sizeof(janus_recordplay_recording));
1413
                rec->id = id;
1414
                rec->name = g_strdup(name->value);
1415
                rec->date = g_strdup(date->value);
1416
                rec->arc_file = g_strdup(audio->value);
1417
                if(strstr(rec->arc_file, ".mjr")) {
1418
                        char *ext = strstr(rec->arc_file, ".mjr");
1419
                        *ext = '\0';
1420
                }
1421
                rec->vrc_file = g_strdup(video->value);
1422
                if(strstr(rec->vrc_file, ".mjr")) {
1423
                        char *ext = strstr(rec->vrc_file, ".mjr");
1424
                        *ext = '\0';
1425
                }
1426

    
1427
                janus_config_destroy(nfo);
1428

    
1429
                /* FIXME We should clean previous recordings with the same ID */
1430
                g_hash_table_remove(recordings, GUINT_TO_POINTER(id));
1431
                g_hash_table_insert(recordings, GUINT_TO_POINTER(id), rec);
1432
        }
1433
        closedir(dir);
1434
        janus_mutex_unlock(&recordings_mutex);
1435
}
1436

    
1437
janus_recordplay_frame_packet *janus_recordplay_get_frames(const char *dir, const char *filename) {
1438
        if(!dir || !filename)
1439
                return NULL;
1440
        /* Open the file */
1441
        char source[1024];
1442
        if(strstr(filename, ".mjr"))
1443
                g_snprintf(source, 1024, "%s/%s", dir, filename);
1444
        else
1445
                g_snprintf(source, 1024, "%s/%s.mjr", dir, filename);
1446
        FILE *file = fopen(source, "rb");
1447
        if(file == NULL) {
1448
                JANUS_LOG(LOG_ERR, "Could not open file %s\n", source);
1449
                return NULL;
1450
        }
1451
        fseek(file, 0L, SEEK_END);
1452
        long fsize = ftell(file);
1453
        fseek(file, 0L, SEEK_SET);
1454
        JANUS_LOG(LOG_VERB, "File is %zu bytes\n", fsize);
1455

    
1456
        /* Pre-parse */
1457
        JANUS_LOG(LOG_VERB, "Pre-parsing file %s to generate ordered index...\n", source);
1458
        int bytes = 0;
1459
        long offset = 0;
1460
        uint16_t len = 0, count = 0;
1461
        uint32_t first_ts = 0, last_ts = 0, reset = 0;        /* To handle whether there's a timestamp reset in the recording */
1462
        char prebuffer[1500];
1463
        memset(prebuffer, 0, 1500);
1464
        /* Let's look for timestamp resets first */
1465
        while(offset < fsize) {
1466
                /* Read frame header */
1467
                fseek(file, offset, SEEK_SET);
1468
                bytes = fread(prebuffer, sizeof(char), 8, file);
1469
                if(bytes != 8 || prebuffer[0] != 'M') {
1470
                        JANUS_LOG(LOG_ERR, "Invalid header...\n");
1471
                        fclose(file);
1472
                        return NULL;
1473
                }
1474
                offset += 8;
1475
                bytes = fread(&len, sizeof(uint16_t), 1, file);
1476
                len = ntohs(len);
1477
                offset += 2;
1478
                if(len == 5) {
1479
                        /* This is the main header */
1480
                        bytes = fread(prebuffer, sizeof(char), 5, file);
1481
                        if(prebuffer[0] == 'v') {
1482
                                JANUS_LOG(LOG_VERB, "This is a video recording, assuming VP8\n");
1483
                        } else if(prebuffer[0] == 'a') {
1484
                                JANUS_LOG(LOG_VERB, "This is an audio recording, assuming Opus\n");
1485
                        } else {
1486
                                JANUS_LOG(LOG_ERR, "Unsupported recording media type...\n");
1487
                                fclose(file);
1488
                                return NULL;
1489
                        }
1490
                        offset += len;
1491
                        continue;
1492
                } else if(len < 12) {
1493
                        /* Not RTP, skip */
1494
                        offset += len;
1495
                        continue;
1496
                }
1497
                /* Only read RTP header */
1498
                bytes = fread(prebuffer, sizeof(char), 16, file);
1499
                rtp_header *rtp = (rtp_header *)prebuffer;
1500
                if(last_ts == 0) {
1501
                        first_ts = ntohl(rtp->timestamp);
1502
                        if(first_ts > 1000*1000)        /* Just used to check whether a packet is pre- or post-reset */
1503
                                first_ts -= 1000*1000;
1504
                } else {
1505
                        if(ntohl(rtp->timestamp) < last_ts) {
1506
                                /* The new timestamp is smaller than the next one, is it a timestamp reset or simply out of order? */
1507
                                if(last_ts-ntohl(rtp->timestamp) > 2*1000*1000*1000) {
1508
                                        reset = ntohl(rtp->timestamp);
1509
                                        JANUS_LOG(LOG_VERB, "Timestamp reset: %"SCNu32"\n", reset);
1510
                                }
1511
                        } else if(ntohl(rtp->timestamp) < reset) {
1512
                                JANUS_LOG(LOG_VERB, "Updating timestamp reset: %"SCNu32" (was %"SCNu32")\n", ntohl(rtp->timestamp), reset);
1513
                                reset = ntohl(rtp->timestamp);
1514
                        }
1515
                }
1516
                last_ts = ntohl(rtp->timestamp);
1517
                /* Skip data for now */
1518
                offset += len;
1519
        }
1520
        /* Now let's parse the frames and order them */
1521
        offset = 0;
1522
        janus_recordplay_frame_packet *list = NULL, *last = NULL;
1523
        while(offset < fsize) {
1524
                /* Read frame header */
1525
                fseek(file, offset, SEEK_SET);
1526
                bytes = fread(prebuffer, sizeof(char), 8, file);
1527
                prebuffer[8] = '\0';
1528
                JANUS_LOG(LOG_HUGE, "Header: %s\n", prebuffer);
1529
                offset += 8;
1530
                bytes = fread(&len, sizeof(uint16_t), 1, file);
1531
                len = ntohs(len);
1532
                JANUS_LOG(LOG_HUGE, "  -- Length: %"SCNu16"\n", len);
1533
                offset += 2;
1534
                if(len < 12) {
1535
                        /* Not RTP, skip */
1536
                        JANUS_LOG(LOG_HUGE, "  -- Not RTP, skipping\n");
1537
                        offset += len;
1538
                        continue;
1539
                }
1540
                /* Only read RTP header */
1541
                bytes = fread(prebuffer, sizeof(char), 16, file);
1542
                rtp_header *rtp = (rtp_header *)prebuffer;
1543
                JANUS_LOG(LOG_HUGE, "  -- RTP packet (ssrc=%"SCNu32", pt=%"SCNu16", ext=%"SCNu16", seq=%"SCNu16", ts=%"SCNu32")\n",
1544
                                ntohl(rtp->ssrc), rtp->type, rtp->extension, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
1545
                /* Generate frame packet and insert in the ordered list */
1546
                janus_recordplay_frame_packet *p = calloc(1, sizeof(janus_recordplay_frame_packet));
1547
                if(p == NULL) {
1548
                        JANUS_LOG(LOG_ERR, "Memory error!\n");
1549
                        fclose(file);
1550
                        return NULL;
1551
                }
1552
                p->seq = ntohs(rtp->seq_number);
1553
                if(reset == 0) {
1554
                        /* Simple enough... */
1555
                        p->ts = ntohl(rtp->timestamp);
1556
                } else {
1557
                        /* Is this packet pre- or post-reset? */
1558
                        if(ntohl(rtp->timestamp) > first_ts) {
1559
                                /* Pre-reset... */
1560
                                p->ts = ntohl(rtp->timestamp);
1561
                        } else {
1562
                                /* Post-reset... */
1563
                                uint64_t max32 = UINT32_MAX;
1564
                                max32++;
1565
                                p->ts = max32+ntohl(rtp->timestamp);
1566
                        }
1567
                }
1568
                p->len = len;
1569
                p->offset = offset;
1570
                p->next = NULL;
1571
                p->prev = NULL;
1572
                if(list == NULL) {
1573
                        /* First element becomes the list itself (and the last item), at least for now */
1574
                        list = p;
1575
                        last = p;
1576
                } else {
1577
                        /* Check where we should insert this, starting from the end */
1578
                        int added = 0;
1579
                        janus_recordplay_frame_packet *tmp = last;
1580
                        while(tmp) {
1581
                                if(tmp->ts < p->ts) {
1582
                                        /* The new timestamp is greater than the last one we have, append */
1583
                                        added = 1;
1584
                                        if(tmp->next != NULL) {
1585
                                                /* We're inserting */
1586
                                                tmp->next->prev = p;
1587
                                                p->next = tmp->next;
1588
                                        } else {
1589
                                                /* Update the last packet */
1590
                                                last = p;
1591
                                        }
1592
                                        tmp->next = p;
1593
                                        p->prev = tmp;
1594
                                        break;
1595
                                } else if(tmp->ts == p->ts) {
1596
                                        /* Same timestamp, check the sequence number */
1597
                                        if(tmp->seq < p->seq && (abs(tmp->seq - p->seq) < 10000)) {
1598
                                                /* The new sequence number is greater than the last one we have, append */
1599
                                                added = 1;
1600
                                                if(tmp->next != NULL) {
1601
                                                        /* We're inserting */
1602
                                                        tmp->next->prev = p;
1603
                                                        p->next = tmp->next;
1604
                                                } else {
1605
                                                        /* Update the last packet */
1606
                                                        last = p;
1607
                                                }
1608
                                                tmp->next = p;
1609
                                                p->prev = tmp;
1610
                                                break;
1611
                                        } else if(tmp->seq > p->seq && (abs(tmp->seq - p->seq) > 10000)) {
1612
                                                /* The new sequence number (resetted) is greater than the last one we have, append */
1613
                                                added = 1;
1614
                                                if(tmp->next != NULL) {
1615
                                                        /* We're inserting */
1616
                                                        tmp->next->prev = p;
1617
                                                        p->next = tmp->next;
1618
                                                } else {
1619
                                                        /* Update the last packet */
1620
                                                        last = p;
1621
                                                }
1622
                                                tmp->next = p;
1623
                                                p->prev = tmp;
1624
                                                break;
1625
                                        }
1626
                                }
1627
                                /* If either the timestamp ot the sequence number we just got is smaller, keep going back */
1628
                                tmp = tmp->prev;
1629
                        }
1630
                        if(!added) {
1631
                                /* We reached the start */
1632
                                p->next = list;
1633
                                list->prev = p;
1634
                                list = p;
1635
                        }
1636
                }
1637
                /* Skip data for now */
1638
                offset += len;
1639
                count++;
1640
        }
1641
        
1642
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" RTP packets\n", count);
1643
        janus_recordplay_frame_packet *tmp = list;
1644
        count = 0;
1645
        while(tmp) {
1646
                count++;
1647
                JANUS_LOG(LOG_HUGE, "[%10lu][%4d] seq=%"SCNu16", ts=%"SCNu64"\n", tmp->offset, tmp->len, tmp->seq, tmp->ts);
1648
                tmp = tmp->next;
1649
        }
1650
        JANUS_LOG(LOG_VERB, "Counted %"SCNu16" frame packets\n", count);
1651
        
1652
        /* Done! */
1653
        fclose(file);
1654
        return list;
1655
}
1656

    
1657
static void *janus_recordplay_playout_thread(void *data) {
1658
        janus_recordplay_session *session = (janus_recordplay_session *)data;
1659
        if(!session) {
1660
                JANUS_LOG(LOG_ERR, "Invalid session, can't start playout thread...\n");
1661
                g_thread_unref(g_thread_self());
1662
                return NULL;
1663
        }
1664
        if(session->recorder) {
1665
                JANUS_LOG(LOG_ERR, "This is a recorder, can't start playout thread...\n");
1666
                g_thread_unref(g_thread_self());
1667
                return NULL;
1668
        }
1669
        if(!session->aframes || !session->vframes) {
1670
                JANUS_LOG(LOG_ERR, "No audio and no video frames, can't start playout thread...\n");
1671
                g_thread_unref(g_thread_self());
1672
                return NULL;
1673
        }
1674
        JANUS_LOG(LOG_INFO, "Joining playout thread\n");
1675
        /* Open the files */
1676
        FILE *afile = NULL, *vfile = NULL;
1677
        if(session->aframes) {
1678
                char source[1024];
1679
                if(strstr(session->recording->arc_file, ".mjr"))
1680
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->arc_file);
1681
                else
1682
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->arc_file);
1683
                afile = fopen(source, "rb");
1684
                if(afile == NULL) {
1685
                        JANUS_LOG(LOG_ERR, "Could not open audio file %s, can't start playout thread...\n", source);
1686
                        g_thread_unref(g_thread_self());
1687
                        return NULL;
1688
                }
1689
        }
1690
        if(session->vframes) {
1691
                char source[1024];
1692
                if(strstr(session->recording->vrc_file, ".mjr"))
1693
                        g_snprintf(source, 1024, "%s/%s", recordings_path, session->recording->vrc_file);
1694
                else
1695
                        g_snprintf(source, 1024, "%s/%s.mjr", recordings_path, session->recording->vrc_file);
1696
                vfile = fopen(source, "rb");
1697
                if(vfile == NULL) {
1698
                        JANUS_LOG(LOG_ERR, "Could not open video file %s, can't start playout thread...\n", source);
1699
                        if(afile)
1700
                                fclose(afile);
1701
                        afile = NULL;
1702
                        g_thread_unref(g_thread_self());
1703
                        return NULL;
1704
                }
1705
        }
1706
        
1707
        /* Timer */
1708
        gboolean asent = FALSE, vsent = FALSE;
1709
        struct timeval now, abefore, vbefore;
1710
        time_t d_s, d_us;
1711
        gettimeofday(&now, NULL);
1712
        gettimeofday(&abefore, NULL);
1713
        gettimeofday(&vbefore, NULL);
1714

    
1715
        janus_recordplay_frame_packet *audio = session->aframes, *video = session->vframes;
1716
        char *buffer = (char *)calloc(1500, sizeof(char));
1717
        memset(buffer, 0, 1500);
1718
        int bytes = 0;
1719
        int64_t ts_diff = 0, passed = 0;
1720
        
1721
        while(!session->destroyed && session->active && (audio || video)) {
1722
                if(!asent && !vsent) {
1723
                        /* We skipped the last round, so sleep a bit (5ms) */
1724
                        usleep(5000);
1725
                }
1726
                asent = FALSE;
1727
                vsent = FALSE;
1728
                if(audio) {
1729
                        if(audio == session->aframes) {
1730
                                /* First packet, send now */
1731
                                fseek(afile, audio->offset, SEEK_SET);
1732
                                bytes = fread(buffer, sizeof(char), audio->len, afile);
1733
                                if(bytes != audio->len)
1734
                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1735
                                /* Update payload type */
1736
                                rtp_header *rtp = (rtp_header *)buffer;
1737
                                rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1738
                                if(gateway != NULL)
1739
                                        gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1740
                                gettimeofday(&now, NULL);
1741
                                abefore.tv_sec = now.tv_sec;
1742
                                abefore.tv_usec = now.tv_usec;
1743
                                asent = TRUE;
1744
                                audio = audio->next;
1745
                        } else {
1746
                                /* What's the timestamp skip from the previous packet? */
1747
                                ts_diff = audio->ts - audio->prev->ts;
1748
                                ts_diff = (ts_diff*1000)/48;        /* FIXME Again, we're assuming Opus and it's 48khz */
1749
                                /* Check if it's time to send */
1750
                                gettimeofday(&now, NULL);
1751
                                d_s = now.tv_sec - abefore.tv_sec;
1752
                                d_us = now.tv_usec - abefore.tv_usec;
1753
                                if(d_us < 0) {
1754
                                        d_us += 1000000;
1755
                                        --d_s;
1756
                                }
1757
                                passed = d_s*1000000 + d_us;
1758
                                if(passed < (ts_diff-5000)) {
1759
                                        asent = FALSE;
1760
                                } else {
1761
                                        /* Update the reference time */
1762
                                        abefore.tv_usec += ts_diff%1000000;
1763
                                        if(abefore.tv_usec > 1000000) {
1764
                                                abefore.tv_sec++;
1765
                                                abefore.tv_usec -= 1000000;
1766
                                        }
1767
                                        if(ts_diff/1000000 > 0) {
1768
                                                abefore.tv_sec += ts_diff/1000000;
1769
                                                abefore.tv_usec -= ts_diff/1000000;
1770
                                        }
1771
                                        /* Send now */
1772
                                        fseek(afile, audio->offset, SEEK_SET);
1773
                                        bytes = fread(buffer, sizeof(char), audio->len, afile);
1774
                                        if(bytes != audio->len)
1775
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, audio->len);
1776
                                        /* Update payload type */
1777
                                        rtp_header *rtp = (rtp_header *)buffer;
1778
                                        rtp->type = OPUS_PT;        /* FIXME We assume it's Opus */
1779
                                        if(gateway != NULL)
1780
                                                gateway->relay_rtp(session->handle, 0, (char *)buffer, bytes);
1781
                                        asent = TRUE;
1782
                                        audio = audio->next;
1783
                                }
1784
                        }
1785
                }
1786
                if(video) {
1787
                        if(video == session->vframes) {
1788
                                /* First packets: there may be many of them with the same timestamp, send them all */
1789
                                uint64_t ts = video->ts;
1790
                                while(video && video->ts == ts) {
1791
                                        fseek(vfile, video->offset, SEEK_SET);
1792
                                        bytes = fread(buffer, sizeof(char), video->len, vfile);
1793
                                        if(bytes != video->len)
1794
                                                JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
1795
                                        /* Update payload type */
1796
                                        rtp_header *rtp = (rtp_header *)buffer;
1797
                                        rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
1798
                                        if(gateway != NULL)
1799
                                                gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
1800
                                        video = video->next;
1801
                                }
1802
                                vsent = TRUE;
1803
                                gettimeofday(&now, NULL);
1804
                                vbefore.tv_sec = now.tv_sec;
1805
                                vbefore.tv_usec = now.tv_usec;
1806
                        } else {
1807
                                /* What's the timestamp skip from the previous packet? */
1808
                                ts_diff = video->ts - video->prev->ts;
1809
                                ts_diff = (ts_diff*1000)/90;
1810
                                /* Check if it's time to send */
1811
                                gettimeofday(&now, NULL);
1812
                                d_s = now.tv_sec - vbefore.tv_sec;
1813
                                d_us = now.tv_usec - vbefore.tv_usec;
1814
                                if(d_us < 0) {
1815
                                        d_us += 1000000;
1816
                                        --d_s;
1817
                                }
1818
                                passed = d_s*1000000 + d_us;
1819
                                if(passed < (ts_diff-5000)) {
1820
                                        vsent = FALSE;
1821
                                } else {
1822
                                        /* Update the reference time */
1823
                                        vbefore.tv_usec += ts_diff%1000000;
1824
                                        if(vbefore.tv_usec > 1000000) {
1825
                                                vbefore.tv_sec++;
1826
                                                vbefore.tv_usec -= 1000000;
1827
                                        }
1828
                                        if(ts_diff/1000000 > 0) {
1829
                                                vbefore.tv_sec += ts_diff/1000000;
1830
                                                vbefore.tv_usec -= ts_diff/1000000;
1831
                                        }
1832
                                        /* There may be multiple packets with the same timestamp, send them all */
1833
                                        uint64_t ts = video->ts;
1834
                                        while(video && video->ts == ts) {
1835
                                                /* Send now */
1836
                                                fseek(vfile, video->offset, SEEK_SET);
1837
                                                bytes = fread(buffer, sizeof(char), video->len, vfile);
1838
                                                if(bytes != video->len)
1839
                                                        JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, video->len);
1840
                                                /* Update payload type */
1841
                                                rtp_header *rtp = (rtp_header *)buffer;
1842
                                                rtp->type = VP8_PT;        /* FIXME We assume it's VP8 */
1843
                                                if(gateway != NULL)
1844
                                                        gateway->relay_rtp(session->handle, 1, (char *)buffer, bytes);
1845
                                                video = video->next;
1846
                                        }
1847
                                        vsent = TRUE;
1848
                                }
1849
                        }
1850
                }
1851
        }
1852

    
1853
        /* Get rid of the indexes */
1854
        janus_recordplay_frame_packet *tmp = NULL;
1855
        audio = session->aframes;
1856
        while(audio) {
1857
                tmp = audio->next;
1858
                g_free(audio);
1859
                audio = tmp;
1860
        }
1861
        session->aframes = NULL;
1862
        video = session->vframes;
1863
        while(video) {
1864
                tmp = video->next;
1865
                g_free(video);
1866
                video = tmp;
1867
        }
1868
        session->vframes = NULL;
1869

    
1870
        if(afile)
1871
                fclose(afile);
1872
        afile = NULL;
1873
        if(vfile)
1874
                fclose(vfile);
1875
        vfile = NULL;
1876

    
1877
        /* Tell the core to tear down the PeerConnection, hangup_media will do the rest */
1878
        gateway->close_pc(session->handle);
1879
        
1880
        JANUS_LOG(LOG_INFO, "Leaving playout thread\n");
1881
        g_thread_unref(g_thread_self());
1882
        return NULL;
1883
}