Created
November 6, 2012 22:41
-
-
Save pascalduez/4028165 to your computer and use it in GitHub Desktop.
Webcam auto timelapse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var http = require('http') | |
, url = require('url') | |
, path = require('path') | |
, fs = require('fs') | |
, async = require('async') | |
, exec = require('child_process').exec | |
, imgUrl | |
, options | |
, dir | |
, count | |
, maxCount | |
, delay | |
; | |
////////////////////////////// | |
// Config | |
////////////////////////////// | |
imgUrl = 'http://webcam-cayeux.dyndns.org:8080/record/current.jpg'; | |
imgUrl += '?rand=' + Math.floor(Math.random() * 1000000); | |
dir = __dirname + '/img'; | |
count = 0; | |
maxCount = 500; | |
delay = 3000; | |
////////////////////////////// | |
options = { | |
hostname: url.parse(imgUrl).hostname | |
, port: url.parse(imgUrl).port || 80 | |
, path: url.parse(imgUrl).pathname | |
}; | |
(function mkdir() { | |
fs.mkdir(dir, function (err) { | |
if (err) { | |
if (err.code === 'EEXIST') { | |
fs.rmdir(dir, mkdir); | |
} | |
else { | |
throw err; | |
} | |
} | |
}) | |
}()); | |
function downloadImg (cb) { | |
var request, filename, stream; | |
request = http.get(options, function (res) { | |
fileName = path.join(dir, 'image_' + count + '.jpg'); | |
stream = fs.createWriteStream(fileName); | |
res.pipe(stream); | |
res.on('end', function (err) { | |
if (err) throw err; | |
console.log('Image ' + count + ' saved.'); | |
cb(); | |
}); | |
}); | |
request.on('error', function (err) { | |
console.log('Oops, something went wrong: ' + err.message); | |
}); | |
} | |
function encodeMovie () { | |
var movieName, cmd, child; | |
movieName = 'webcam_timelapse.mp4'; | |
cmd = 'ffmpeg -start_number 0 -i img/image_%d.jpg -r 24 -vcodec h264 ' + movieName; | |
fs.exists(movieName, function (exists) { | |
if (exists) { | |
fs.unlink(movieName, function (err) { | |
if (err) throw err; | |
}); | |
} | |
}); | |
child = exec(cmd, function (err, stdout, stderr) { | |
console.log('stdout: ' + stdout); | |
console.log('stderr: ' + stderr); | |
if (err !== null) { | |
console.log('exec err: ' + err); | |
} | |
else { | |
console.log('All done!'); | |
} | |
process.exit(); | |
}); | |
} | |
async.whilst( | |
function () { return count < maxCount; }, | |
function (cb) { | |
count++; | |
setTimeout(function() { | |
downloadImg(cb); | |
}, delay); | |
}, | |
function (err) { | |
if (err) throw err; | |
encodeMovie(); | |
} | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment