How do you use Node.js to stream an MP4 file with ffmpeg? How do you use Node.js to stream an MP4 file with ffmpeg? node.js node.js

How do you use Node.js to stream an MP4 file with ffmpeg?


One of the main issues here is that you cannot seek on a piped stream. So you would have to store the file first. However, if you want to just stream from the beginning you can use a slightly different construction and pipe. Here is an example of the most straight forward way to do it.

// can just create an in-memory read stream without savingvar stream = aws.s3(s3Bucket).getObject(s3Path).createReadStream();// fluent-ffmpeg supports a readstream as an arg in constructorvar proc = new ffmpeg(stream)    .outputOptions(['-movflags isml+frag_keyframe'])    .toFormat('mp4')    .withAudioCodec('copy')    //.seekInput(offset) this is a problem with piping    .on('error', function(err,stdout,stderr) {        console.log('an error happened: ' + err.message);        console.log('ffmpeg stdout: ' + stdout);        console.log('ffmpeg stderr: ' + stderr);    })    .on('end', function() {        console.log('Processing finished !');    })    .on('progress', function(progress) {        console.log('Processing: ' + progress.percent + '% done');    })    .pipe(res, {end: true});


Blockquote How can I stream the mp4 file from s3, without storing it locally as a file first? How do I get ffmpeg to do this without transcoding the file too? The following is the code I have at the moment which isn't working. Note that it attempts to pass the s3 file as a stream to ffmpeg and it's also transcoding it into an mp3, which I'd prefer not to do.

AFAIK - if the moov atom is in the right place in media file, for S3 hosted mp4, nothing special is require for streaming because you can rely on http for that. If the client request "chunked" encoding it will get just that, a chunked stream terminated by the "END-OF" marker shown below.

0\r\n\r\n 

By including the chunked header, the client is saying " I want a stream" . Under the covers, S3 is just nginx or apache isn't it? They both honor the headers.

test it with curl CLI as your client...

> User-Agent: curl/7.28.1-DEV> Host: S3.domain> Accept: */*> Transfer-Encoding: chunked> Content-Type: video/mp4> Expect: 100-continue

May want to try out adding the codecs to the "Content-Type:" header. I dont know, but dont think it would be required for this type of streaming ( the atom resolves that stuff )


I had an issue buffering file streams from the S3 file object. The s3 filestream does not have the correct headers set and it seems it does not implement piping correctly.

I think a better solution is to use this nodejs module called s3-streams. It sets the correct headers and buffers the output so that the stream can be correctly piped to the output response socket. It saves you from saving the filestream locally first before restreaming it.