This repository has been archived by the owner on May 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
serve.js
189 lines (152 loc) · 4.72 KB
/
serve.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
var fs = require('fs');
var http = require('http');
var videoUtils = require('./videoUtils');
var files = {
'/': ['text/html', fs.readFileSync('page.html').toString()],
'/MediaStreamRecorder.js': ['application/javascript', fs.readFileSync('node_modules/msr/MediaStreamRecorder.js').toString()]
};
var mimeTypes = {
'js': 'application/javascript',
'html': 'text/html',
'ts': 'video/mp2t',
'mp4': 'video/mp4',
'webm': 'video/webm',
'm3u8': 'application/x-mpegURL'
};
var fileDataArrs = {};
var PORT = 8001;
var LIVE = true;
var PREV_ITEMS_IN_LIVE = 4;
function lastN(arr, n) { // non-destructive
arr = arr.slice();
var l = arr.length;
var i = l - n;
if (i < 0) { i = 0; }
return arr.splice(i, n);
}
function respond(res, pair, code) {
res.writeHeader(
code || 200,
{
'Content-Type': pair[0],
'Access-Control-Allow-Origin': '*'
}
);
res.write(pair[1]);
res.end();
}
http.createServer(function(req, res) {
var u = req.url;
console.log(u);
var f = files[u];
if (f) {
respond(res, f);
}
else if ((/^\/videos\/?$/).test(u)) {
fs.readdir('videos', function(err, dirs) {
if (err) {
return respond(res, ['text/plain', err.toString(), 500]);
}
dirs = JSON.stringify(dirs);
respond(res, ['application/json', dirs]);
});
}
else if (u.indexOf('/chunk/') === 0) {
var parts = u.split('/');
var prefix = parts[2];
var num = parts[3];
var isFirst = false;
var isLast = !!parts[4];
if ((/^0+$/).test(num)) {
fs.mkdirSync('videos/' + prefix);
isFirst = true;
}
var fp = 'videos/' + prefix + '/' + num + '.webm';
var msg = 'got ' + fp;
console.log(msg);
console.log('isFirst:%s, isLast:%s', isFirst, isLast);
var stream = fs.createWriteStream(fp, {encoding:'binary'});
/*stream.on('end', function() {
respond(res, ['text/plain', msg]);
});*/
//req.setEncoding('binary');
req.pipe(stream);
req.on('end', function() {
respond(res, ['text/plain', msg]);
if (!LIVE) { return; }
videoUtils.findVideoDuration(fp, function(err, duration) {
if (err) { return console.error(err); }
console.log('duration: %s', duration.toFixed(2));
var fd = {
fileName: num + '.webm',
filePath: fp,
duration: duration
};
var fileDataArr;
if (isFirst) {
fileDataArr = [];
fileDataArrs[ prefix ] = fileDataArr;
}
else {
fileDataArr = fileDataArrs[ prefix ];
}
fileDataArr.push(fd);
videoUtils.computeStartTimes(fileDataArr);
videoUtils.webm2Mpegts(fd, function(err, mpegtsFp) {
if (err) { return console.error(err); }
console.log('created %s', mpegtsFp);
var playlistFp = 'videos/' + prefix + '/playlist.m3u8';
var fileDataArr2 = (isLast ? fileDataArr : lastN(fileDataArr, PREV_ITEMS_IN_LIVE));
var action = (isFirst ? 'created' : (isLast ? 'finished' : 'updated') );
videoUtils.generateM3u8Playlist(fileDataArr2, playlistFp, !isLast, function(err) {
console.log('playlist %s %s', playlistFp, (err ? err.toString() : action) );
});
});
});
});
}
else {
// serve files, supporting ranged requests
var path = u.substring(1);
var mimeType = mimeTypes[ u.split('.').pop() ];
fs.stat('./' + path, function(err, stats) {
if (err) {
return respond(res, ['text/plain', '404', 404]);
}
var total = stats.size;
if (req.headers.range) { // ranged request
var range = req.headers.range;
var parts = range.replace(/bytes=/, '').split('-');
var partialStart = parts[0];
var partialEnd = parts[1];
var start = parseInt(partialStart, 10);
var end = partialEnd ? parseInt(partialEnd, 10) : total-1;
var chunkSize = (end - start) + 1;
var fStream = fs.createReadStream(path, {
start: start,
end: end
});
var rangeS = ['bytes ', start, '-', end, '/', total].join('');
res.writeHead(206, { // ranged download
'Content-Range': rangeS,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize,
'Content-Type': mimeType,
'Access-Control-Allow-Origin': '*'
});
console.log([u, 206, mimeType, rangeS].join(' '));
fStream.pipe(res);
}
else { // regular request
res.writeHead(200, { // regular download
'Content-Length': total,
'Content-Type': mimeType,
'Access-Control-Allow-Origin': '*'
});
console.log([u, 200, mimeType, 'all'].join(' '));
fs.createReadStream(path).pipe(res);
}
});
}
}).listen(PORT);
console.log('webcam2hls server listening on port %s...', PORT);