NodeJS 视频流实时转码
NodeJS video streaming transcode on the fly
我正在构建一个 nodejs 应用程序,用于将视频从磁盘流式传输给用户。感谢 this 问题,我有一个存储在磁盘上的 "static" 视频文件的工作视频源,到目前为止一切正常。
我的问题是我需要即时对视频进行转码,为此我使用了 fluent-ffmpeg 并成功实现了转码,但 HTML5 播放器只显示前 3- 4s 的视频,然后停止。我猜问题是文件大小,但即使我对它进行 harcode 也没有任何改变。
有什么想法吗?非常感谢:)
var file = 'Big_Buck_Bunny_1080p_surround_FrostWire.com.mp4';
fs.stat(file, function(err, stats) {
var range = req.headers.range
if (!range) { // 416 Wrong range
return res.sendStatus(416)
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
})
var stream = fs.createReadStream(file, { start: start, end: end, autoclose: true })
.on("open", function() {
const ffmpegCommand = ffmpeg()
.input(stream)
.outputFormat('mp4')
.outputOptions([ '-movflags faststart', '-frag_size 4096', '-cpu-used 2', '-deadline realtime', '-threads 4' ])
.videoBitrate(640, true)
.audioBitrate(128)
.audioCodec('aac')
.videoCodec('libx264')
.output(res)
.run()
}).on("error", function(err) {
res.end(err)
})
})
最终,我找到的最佳解决方案是使用更多 "streaming-friendly" 格式,所以我切换到 HLS,现在一切都更简单并且工作正常:)
我觉得你应该放弃 .output(res)
.run()
并使用 .stream().pipe(res, { end: true})
代替
我正在构建一个 nodejs 应用程序,用于将视频从磁盘流式传输给用户。感谢 this 问题,我有一个存储在磁盘上的 "static" 视频文件的工作视频源,到目前为止一切正常。
我的问题是我需要即时对视频进行转码,为此我使用了 fluent-ffmpeg 并成功实现了转码,但 HTML5 播放器只显示前 3- 4s 的视频,然后停止。我猜问题是文件大小,但即使我对它进行 harcode 也没有任何改变。
有什么想法吗?非常感谢:)
var file = 'Big_Buck_Bunny_1080p_surround_FrostWire.com.mp4';
fs.stat(file, function(err, stats) {
var range = req.headers.range
if (!range) { // 416 Wrong range
return res.sendStatus(416)
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
})
var stream = fs.createReadStream(file, { start: start, end: end, autoclose: true })
.on("open", function() {
const ffmpegCommand = ffmpeg()
.input(stream)
.outputFormat('mp4')
.outputOptions([ '-movflags faststart', '-frag_size 4096', '-cpu-used 2', '-deadline realtime', '-threads 4' ])
.videoBitrate(640, true)
.audioBitrate(128)
.audioCodec('aac')
.videoCodec('libx264')
.output(res)
.run()
}).on("error", function(err) {
res.end(err)
})
})
最终,我找到的最佳解决方案是使用更多 "streaming-friendly" 格式,所以我切换到 HLS,现在一切都更简单并且工作正常:)
我觉得你应该放弃 .output(res)
.run()
并使用 .stream().pipe(res, { end: true})
代替