-
Notifications
You must be signed in to change notification settings - Fork 1
/
transcode.js
executable file
·209 lines (192 loc) · 7.58 KB
/
transcode.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/** node.js implementation of a realtime audio transcoding solution for
HD home run. It follows the HD home run URL scheme - you would access
http://127.0.0.1:8000/auto/v5.1?transcode=mobile for example to view
channel 5.1.
This script has a hardcoded IP of the HD Home run as 192.168.103.210, replace
to whatever yours is
*/
var HDHomeRunIP = "192.168.103.210";
var HDHomeRunPort = 5004;
var childKillTimeoutMs = 1000;
var parseArgs = require('minimist')(process.argv.slice(2));
// define startsWith for string
if (typeof String.prototype.startsWith != 'function') {
// see below for better implementation!
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
// Called when the response object fires the 'close' handler, kills ffmpeg
function responseCloseHandler(command) {
if (command.exited != true) {
console.log('HTTP connection disrupted, killing ffmpeg: ' + command.pid);
// Send a 'q' which signals ffmpeg to quit.
// Then wait half a second, send a nice signal, wait another half second
// and send SIGKILL
command.stdin.write('q\n');
command.stdin.destroy();
// install timeout and wait
setTimeout(function() {
if (command.exited != true) {
console.log('ffmpeg didn\'t quit on q, sending signals');
// still connected, do safe sig kills
command.kill();
try {
command.kill('SIGQUIT');
} catch (err) {}
try {
command.kill('SIGINT');
} catch (err) {}
// wait some more!
setTimeout(function() {
if (command.exited != true) {
console.log('ffmpeg didn\'t quit on signals, sending SIGKILL');
// at this point, just give up and whack it
try {
command.kill('SIGKILL');
} catch (err) {}
}
}, childKillTimeoutMs);
}
}, childKillTimeoutMs);
}
}
// Performs a proxy. Copies data from proxy_request into response
function doProxy(request,response,http,options) {
var proxy_request = http.request(options, function (proxy_response) {
proxy_response.on('data', function(chunk) {
response.write(chunk, 'binary');
});
proxy_response.on('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.on('data', function(chunk) {
proxy_request.write(chunk, 'binary');
});
// error handler
proxy_request.on('error', function(e) {
console.log('problem with request: ' + e.message);
response.writeHeader(500);
response.end();
});
proxy_request.end();
}
var child_process = require('child_process');
var auth = require('./auth');
// Performs the transcoding after the URL is validated
function doTranscode(request,response) {
//res.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Type", "video/mpeg");
response.setHeader("Connection","close");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
// always write the header
response.writeHeader(200);
// if get, spawn command stream it
if (request.method == 'GET') {
console.log('Spawning new process ' + request.url + ":" + request.method);
var command = child_process.spawn('ffmpeg',
['-i','http://' + HDHomeRunIP + ':' + HDHomeRunPort + request.url,'-vcodec','copy','-ac','2','-acodec','libfdk_aac','-b:a','128k','-f','mpegts','-'],
{ stdio: ['pipe','pipe','ignore'] });
command.exited = false;
// handler for when ffmpeg dies unexpectedly
command.on('exit',function(code,signal) {
console.log('ffmpeg has exited: ' + command.pid + ", code " + code);
// set flag saying we've quit
command.exited = true;
response.end();
});
command.on('error',function(error) {
console.log('ffmpeg error handler - unable to kill: ' + command.pid);
// on well, might as well give up
command.exited = true;
try {
command.stdin.close();
} catch (err) {}
try {
command.stdout.close();
} catch (err) {}
try {
command.stderr.close();
} catch (err) {}
response.end();
});
// handler for when client closes the URL connection - stop ffmpeg
response.on('end',function() {
responseCloseHandler(command);
});
// handler for when client closes the URL connection - stop ffmpeg
response.on('close',function() {
responseCloseHandler(command);
});
// now stream
console.log('piping ffmpeg output to client, pid ' + command.pid);
command.stdout.pipe(response);
command.stdin.on('error',function(err) {
console.log("Weird error in stdin pipe ", err);
response.end();
});
command.stdout.on('error',function(err) {
console.log("Weird error in stdout pipe ",err);
response.end();
});
}
else {
// not GET, so close response
response.end();
}
}
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("New connection from " + request.socket.remoteAddress + ":" + request.url);
if (auth.validate(request,response)) {
// first send a HEAD request to our HD Home Run with the same url to see if the address is valid.
// This prevents an ffmpeg instance to spawn when clients request invalid things - like robots.txt/etc
var options = {method: 'HEAD', hostname: HDHomeRunIP, port: HDHomeRunPort, path: request.url};
var req = http.request(options, function(res) {
// if they do a get, and it returns good status
if (request.method == "GET" &&
res.statusCode == 200 &&
res.headers["content-type"] != null &&
res.headers["content-type"].startsWith("video")) {
// transcode is possible, start it now!
doTranscode(request,response);
}
else {
// no video or error, cannot transcode, just forward the response from the HD Home run to the client
if (request.method == "HEAD") {
response.writeHead(res.statusCode,res.headers);
response.end();
}
else {
// do a 301 redirect and have the device response directly
//response.writeHead(301,{Location: 'http://' + HDHomeRunIP + ':5004' + request.url});
//response.end();
// just proxy it, that way browser doesn't redirect to HDHomeRun IP but keeps the node.js server IP
options = {method: request.method, hostname: HDHomeRunIP, port: HDHomeRunPort, path: request.url};
doProxy(request,response,http,options);
}
}
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
response.writeHeader(500);
response.end();
});
// finish the client request, rest of processing done in the async callbacks
req.end();
}
});
// turn on no delay for tcp
server.on('connection', function (socket) {
socket.setNoDelay(true);
});
// Listen on port HDHomeRunPort, or use the --port argument. IP defaults to 127.0.0.1
var listenPort = parseArgs.hasOwnProperty("port") ? parseArgs.port : HDHomeRunPort;
server.listen(listenPort);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:" + listenPort);