forked from licson/node-YouTubeStreamer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
normal.js
75 lines (67 loc) · 2.06 KB
/
normal.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
// # node-YouTubeStreamer
// _by Licson Lee <[email protected]>_
//
// This is the normal streaming module for node-YouTubeStreamer.
//Require the libraries needed.
var request = require('request');
var qs = require('querystring');
var spawn = require('child_process').spawn;
//Here's our normal stream handler.
module.exports = function(query, data, options){
//Get the streams from the API response
var streams = String(data.url_encoded_fmt_stream_map).split(',');
//Loop througn all streams
for(var i = 0; i < streams.length; i++){
//Parse the stream
var stream = qs.parse(streams[i]);
//If the stream is compatable with the video type,
//we return a function that can stream the video to the client.
//Note: we **DO NOT** stream HD videos to save bandwidth.
if(String(stream.type).indexOf(query.type) > -1
&& (
//Should we stream HD videos?
//When using audio conversion, we force the stream not to be
//in HD to reduce processing times
(options.useHDVideos
&& (
!!query.audio
&& options.convertAudio
)
) ?
(
true
) :
//stream regular quality videos
(
stream.quality == "large"
|| stream.quality == "medium"
|| stream.quality == "small"
)
)
){
return function(res){
//Convert video to audio in real-time using FFMpeg
if(!!query.audio && options.convertAudio){
var ffmpeg = spawn('ffmpeg',['-i','-','-vn','-ac',2,'-ar',44100,'-ab','128k','-f','mp3','-']);
var video = request(stream.url+'&signature=' + (stream.sig || stream.s));
res.writeHead(200,{
'Content-type': 'audio/mpeg'
});
ffmpeg.stdout.on('end', function(){
ffmpeg.kill();
});
video.pipe(ffmpeg.stdin);
ffmpeg.stdout.pipe(res);
return;
}
//Pipe the stream out
request(stream.url + '&signature=' + (stream.sig || stream.s)).pipe(res);
};
}
}
//No streams can be found with the format specified
//Return an error message
return function(res){
res.end("No compatable streams can be found!");
};
};