I am using ffmpeg to stream an mp4 video to an rtmp server then display in on the front end using websocket and the process works fine. The problem i'm having is once the video nears its end the web socket connection on the front end disconnects and video stops playing. This is happening because ffmpeg has finished pushing the stream but not all frames are displayed on the front end yet because of stream lag. How can I keep the web socket from disconnecting when ffmpeg finishes streaming so that the full video will be played? Thanks in advance.
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const fluent = require('fluent-ffmpeg');
fluent.setFfmpegPath(ffmpegPath);
const executeFfmpeg = args => {
let command = fluent().output(' '); // pass "Invalid output" validation
command._outputs[0].isFile = false; // disable adding "-y" argument
command._outputs[0].target = ""; // bypass "Unable to find a suitable output format for ' '"
command._global.get = () => { // append custom arguments
return typeof args === "string" ? args.split(' ') : args;
};
return command;
};
function streamVideo() {
executeFfmpeg(`-re -i ${path.join(__dirname, '..', 'test.mp4')} -c:v libx264 -preset veryfast -tune zerolatency -c:a aac -ar 44100 -f flv rtmp://localhost:PORT/live/test`)
.on('start', commandLine => console.log('start', commandLine))
.on('codecData', codecData => console.log('codecData', codecData))
.on('error', error => console.log('error', error))
.on('stderr', stderr => console.log('error', error))
.on('end', commandLine => console.log('video_live end', commandLine))
.run();
}
streamVideo()
<script src="https://cdn.bootcss.com/flv.js/1.5.0/flv.min.js"></script>
<video id="streamElement" autoplay>
</video>
<script>
if (flvjs.isSupported()) {
var streamElement = document.getElementById('streamElement');
var flvPlayer = flvjs.createPlayer({
type: 'flv',
url: 'ws://localhost:PORT/live/test.flv'
});
flvPlayer.attachMediaElement(streamElement);
flvPlayer.load();
flvPlayer.play();
}
</script>
The node media server module starts an rtmp, http and web socket server.
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000,
allow_origin: '*'
}
};
var nms = new NodeMediaServer(config)
nms.run();