胡斌

use ffmpeg to record video ok,need more improvement

'use strict';
const {app, BrowserWindow} = require('electron');
const ipc = require('electron').ipcMain;
const duplexer = require('duplexer3');
const {spawn} = require('child_process');
var streamIn = null;
var ffmpeg = null;
function quit(){
if(streamIn){
streamIn.end();
streamIn = null;
}
app.quit();
}
ipc.on('close-main-window', function () {
quit();
});
var lastRenderTime = 0;
ipc.on('to-main-timer', function () {
if(Date.now() - lastRenderTime >= 10000){
quit();
}
});
var subarg = require('subarg');
... ... @@ -17,11 +45,43 @@ if (argv.d) {
console.log(args);
}
if(!argv.u){
if(!argv.u){//url
console.log("you must input the web url to record with : -u ");
return app.quit();
}
if(!argv.d){//duration
console.log("you must set the record duration in seconds with : -d ");
return app.quit();
}
if(!argv.f){//framerate
argv.f = "20";
}
function startFFmpeg(videosize) {
const args = ['-y','-f', 'rawvideo', '-pix_fmt', 'bgra', '-s' ];
var size = videosize.width + 'x' + videosize.height
args.push(size);
args.push.apply( args, ['-i', 'pipe:0'] );
args.push('-c:v');
args.push('libx264');
args.push('-b:v');
args.push('1024k');
args.push('-r:v');
args.push(argv.f);
args.push('-an');
args.push(argv._[0]);
console.log(args.join` `);
ffmpeg = spawn('ffmpeg', args);
ffmpeg.stderr.on('data', chunk => console.log(chunk.toString()));
streamIn = duplexer(ffmpeg.stdin, ffmpeg.stdout);
}
app.disableHardwareAcceleration()
let win
... ... @@ -33,17 +93,34 @@ app.once('ready', () => {
})
win.loadURL(argv.u)
var now = Date.now()
win.webContents.executeJavaScript('const ipcToMain = require("electron").ipcRenderer;function timerToMain (){ ipcToMain.send("to-main-timer");}setInterval(timerToMain,10000);');
var start = Date.now()
var duration = parseInt(argv.d)*1000
win.webContents.on("paint", function (event, dirty, image) {
if (!ffmpeg) {
startFFmpeg(image.getSize());
}
lastRenderTime = Date.now();
var elapsed = lastRenderTime - start
if (elapsed > duration) {
if (streamIn) {
streamIn.end();
streamIn = null;
}
console.log("done")
win.webContents.executeJavaScript('require("electron").ipcRenderer.send("close-main-window")');
}
else {
streamIn.write(image.getBitmap());
}
win.webContents.on("paint", function(event, dirty, image){
console.log(
"painting",
Date.now() - now,
win.webContents.isOffscreen(),
win.webContents.getFrameRate()
)
//console.log("painting", elapsed, win.webContents.isOffscreen(), win.webContents.getFrameRate())
now = Date.now()
})
win.webContents.setFrameRate(20)
win.webContents.setFrameRate(parseInt(argv.f));
})
... ...
... ... @@ -14,6 +14,8 @@
"author": "hubin",
"license": "MIT",
"dependencies": {
"child_process": "^1.0.2",
"duplexer3": "^0.1.4",
"electron": "^1.6.11",
"subarg": "^1.0.0"
},
... ...