-
Notifications
You must be signed in to change notification settings - Fork 7
/
videoStream.js
executable file
·85 lines (66 loc) · 2.55 KB
/
videoStream.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
let lastFrameObj = {
lastFrame: null
};
let videoStream = {
getLastFrame: () => {
return lastFrameObj.lastFrame;
},
acceptConnections: function(expressApp, cameraOptions, resourcePath, isVerbose){
const raspberryPiCamera = require('raspberry-pi-camera-native');
if(!cameraOptions){
cameraOptions = {
width: 1280,
height: 720,
fps: 16,
encoding: 'JPEG',
quality: 7
};
}
// start capture
raspberryPiCamera.start(cameraOptions);
if(isVerbose) {
console.log('Camera started.');
}
if(typeof resourcePath === 'undefined' || !resourcePath){
resourcePath = '/stream.mjpg';
}
expressApp.get(resourcePath, (req, res) => {
res.writeHead(200, {
'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0',
Pragma: 'no-cache',
Connection: 'close',
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary'
});
if(isVerbose)
console.log('Accepting connection: '+req.hostname);
// add frame data event listener
let isReady = true;
let frameHandler = (frameData) => {
try{
if(!isReady){
return;
}
isReady = false;
if(isVerbose)
console.log('Writing frame: '+frameData.length);
lastFrameObj.lastFrame = frameData;
res.write(`--myboundary\nContent-Type: image/jpg\nContent-length: ${frameData.length}\n\n`);
res.write(frameData, function(){
isReady = true;
});
}
catch(ex){
if(isVerbose)
console.log('Unable to send frame: '+ex);
}
}
let frameEmitter = raspberryPiCamera.on('frame', frameHandler);
req.on('close', ()=>{
frameEmitter.removeListener('frame', frameHandler);
if(isVerbose)
console.log('Connection terminated: '+req.hostname);
});
});
}
}
module.exports = videoStream;