forked from illuspas/Node-Media-Server
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.js
195 lines (164 loc) · 5.88 KB
/
helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
const spawn = require('child_process').spawn;
const axios = require('axios');
const fs = require('fs');
const mkdirp = require('mkdirp');
const Logger = require('../../node_core_logger');
const config = require('../config');
const cmd = config.ffmpeg_path;
const express = require('express');
const bodyParser = require('body-parser');
const router = context => {
const router = express.Router();
router.use(
bodyParser.urlencoded({
extended: true
})
);
router.use(bodyParser.json());
router.post('/stop', (req, res) => {
const { stream } = req.body;
const path = '/live/' + stream;
const id = context.publishers.get(path);
if (!id) {
return res.end();
}
const session = context.sessions.get(id);
if (!session) {
return res.end();
}
// Stop thumbnail generation cron
if(session.task) session.task.stop();
session.reject();
});
return router;
};
const auth = (data, callback) => {
if(data.config.misc.ignore_auth){
callback();
return;
}
if(!data || !data.publishStreamPath || data.publishStreamPath.indexOf('/live/') !== 0){
data.sendStatusMessage(data.publishStreamId, 'error', 'NetStream.publish.Unauthorized', 'Authorization required.');
return;
}
axios.post(
`${data.config.misc.api_endpoint}/live/publish`,
`name=${data.publishArgs.token}&tcUrl=${data.publishStreamPath}`, {
maxRedirects: 0,
validateStatus: (status) => {
// Bypass redirect
return status == 304 || (status >= 200 && status < 300);
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
console.info('Response from auth', response);
callback();
}).catch(error => {
console.error(error);
Logger.log(`[rtmp publish] Unauthorized. id=${data.id} streamPath=${data.publishStreamPath} streamId=${data.publishStreamId} token=${data.publishArgs.token} `);
data.sendStatusMessage(data.publishStreamId, 'error', 'NetStream.publish.Unauthorized', 'Authorization required.');
});
};
const generateStreamThumbnail = (streamPath) => {
const args = [
'-i', `media${streamPath}/index.m3u8`,
'-vcodec' ,'png',
'-frames:v', '2',
'-an',
'-f', 'rawvideo',
//'-vf', 'scale=-2:300', // see if disabling scaling reduces CPU
'-ss', '00:00:01',
'-y',
`media${streamPath}/thumbnail.png`,
];
Logger.log('[Thumbnail generation] screenshot', args)
let inst = spawn(cmd, args, {
});
inst.stdout.on('data', function(data) {
//console.log('stdout: ' + data);
});
inst.stderr.on('data', function(data) {
//console.log('stderr: ' + data);
});
inst.unref();
};
const removeStreamThumbnail = (streamPath) => {
let path = `media${streamPath}/thumbnail.png`;
fs.unlink(path, (error) => {
if(error) Logger.log('[Thumbnail removal] screenshot', error)
})
};
const parseProgressLine = (line) => {
var progress = {};
// Remove all spaces after = and trim
line = line.replace(/=\s+/g, '=').trim();
var progressParts = line.split(' ');
// Split every progress part by "=" to get key and value
for (var i = 0; i < progressParts.length; i++) {
var progressSplit = progressParts[i].split('=', 2);
var key = progressSplit[0];
var value = progressSplit[1];
// This is not a progress line
if (typeof value === 'undefined')
return null;
progress[key] = value;
}
return progress;
};
const extractProgress = (command, stderrLine) => {
var progress = parseProgressLine(stderrLine);
if (progress) {
// build progress report object
var ret = {
frames: parseInt(progress.frame, 10),
currentFps: parseInt(progress.fps, 10),
currentKbps: progress.bitrate ? parseFloat(progress.bitrate.replace('kbits/s', '')) : 0,
targetSize: parseInt(progress.size || progress.Lsize, 10),
timemark: progress.time
};
command.emit('progress', ret);
}
};
const ABRTemplate = (name, transcodeEnabled = false) => {
let line = `#EXTM3U\n#EXT-X-VERSION:4\n`;
line += `#EXT-X-MEDIA:TYPE=VIDEO,GROUP-ID="src",NAME="src",DEFAULT=YES,AUTOSELECT=YES,LANGUAGE="en"\n`;
if (transcodeEnabled) {
line += `#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=800000,RESOLUTION=640x360,VIDEO="low"\n./../../live/${name}/index_low.m3u8\n`;
line += `#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1400000,RESOLUTION=842x480,VIDEO="medium"\n./../../live/${name}/index_medium.m3u8\n`;
line += `#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2800000,RESOLUTION=1280x720,VIDEO="high"\n./../../live/${name}/index_high.m3u8\n`;
}
line += `#EXT-X-STREAM-INF::PROGRAM-ID=1,BANDWIDTH=5000000,RESOLUTION=1920x1080,VIDEO="src"\n./../../live/${name}/index.m3u8`;
return line;
};
const makeABRPlaylist = (ouPath, name, transcodeEnabled) => {
return new Promise((resolve, reject) => {
const playlist = `${ouPath}/abr.m3u8`;
fs.open(playlist, 'w', (err, fd) => {
if (err) {
reject(err.message);
} else {
fs.writeFile(fd, ABRTemplate(name, transcodeEnabled), errWrite => {
if (errWrite) {
reject(errWrite.message);
return;
} else {
fs.close(fd, () => {
resolve();
});
}
});
}
});
});
};
module.exports = {
router,
auth,
generateStreamThumbnail,
removeStreamThumbnail,
extractProgress,
makeABRPlaylist
};