Created
December 18, 2016 15:54
-
-
Save fantasywind/54917557131f13cfa3ab694705cb5f4e to your computer and use it in GitHub Desktop.
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
import ffmpeg from 'fluent-ffmpeg'; | |
import Canvas from 'canvas'; | |
import path from 'path'; | |
import debug from 'debug'; | |
import { Readable } from 'stream'; | |
import fs from 'fs'; | |
const HWM = 90000; | |
const debugFFMPEG = debug('VoteLive:FFMPEG'); | |
const debugCanvas = debug('VoteLive:Canvas'); | |
let index = 0; | |
class CanvasStream extends Readable { | |
constructor(options) { | |
super({ | |
...options, | |
}); | |
this.canvas = new Canvas(1280, 720); | |
this.ctx = this.canvas.getContext('2d'); | |
this.start = Date.now(); | |
} | |
draw() { | |
this.ctx.fillStyle = '#08c'; | |
this.ctx.fillRect(20, 20, 1240, 680); | |
this.ctx.font = '72px sans-serif'; | |
this.ctx.fillStyle = '#4a4a4a'; | |
this.ctx.fillText(`Started ${Date.now() - this.start} ms`, 500, 240); | |
} | |
_read() { | |
this.draw(); | |
this.imgBuf = this.canvas.toBuffer(); | |
index += 1; | |
console.log(`Frame: ${index}\tBuffer Len: ${this._readableState.length}\tImage Len: ${this.imgBuf.length}`); | |
if (index > 200) { | |
this.push(null); | |
} else { | |
this.push(this.imgBuf); | |
} | |
} | |
} | |
const canvasStream = new CanvasStream(); | |
ffmpeg(canvasStream) | |
.inputOptions('-r 20') | |
.inputOptions('-video_size 1280x720') | |
.inputOptions('-pix_fmt yuv420p') | |
.on('start', (command) => { | |
debugFFMPEG(`Spawn ffmpeg: ${command}`); | |
}) | |
.on('codecData', (data) => { | |
debugFFMPEG('Input is ' + data.audio + ' audio ' + 'with ' + data.video + ' video'); | |
}) | |
.on('progress', (progress) => { | |
if (progress.percent) { | |
debugFFMPEG('Processing: ' + progress.percent + '% done', progress); | |
} else { | |
debugFFMPEG(`Processing: ${progress.frames} frames done.\t${progress.timemark} (FPS: ${progress.currentFps})`); | |
} | |
}) | |
.on('error', (err, stdout, stderr) => { | |
debugFFMPEG(`error: ${err.message}`); | |
debugFFMPEG(`stdout: ${stdout}`); | |
debugFFMPEG(`stderr: ${stderr}`); | |
}) | |
.on('end', () => { | |
debugFFMPEG('FFMPEG end.'); | |
}) | |
.addOptions([ | |
'-bufsize 50000', | |
'-c:v libx264', | |
'-crf 28', | |
'-preset ultrafast', | |
'-r 30', | |
]) | |
.format('flv') | |
.save('./test.flv'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment