Search code examples
javascriptnode.jsraspberry-pimp4h.264

Convert or wrap h264 file to mp4 with Node JS


I am taking video on a Raspberry Pi and am looking to convert the raw h264 file to an mp4 file or maybe wrap it in an mp4 as is done using the command line/Python. I however, am looking to do this in NodeJS. There seem to be many node JS libraries that use the Raspberry Pi's mp4-box library on npm. However, none of them have proper documentation or seem to fit the needs of my project. I do not know If I am missing something or if this is impossible.


Solution

  • There is not a direct way to embed a H.264 encoded file into a MP4 container without actually building the entire file structure from scratch. This is doable but in order to do that you would need to understand the mp4 container format (which is heavily based on the Quicktime MOV container) and build it using TypedArrays which result you can save out as a MP4 file (I created a paste here describing the container file structure).

    An alternative approach is to spawn FFmpeg from Node.js (or simply use that software directly) and provide the H.264 as input and save it out as a MP4 file. It's pretty straight forward. The command would be something like:

    ffmpeg -i yourH264encodedFileHere -c:v copy mp4FileContainer.mp4
    

    To run that from Node can use spawn (see example).

    An alternative to this bare-bone approach is to install and use the fluent-ffmpeg NPM module which does all the heavy lifting.

    Example

    var ffmpeg = require("fluent-ffmpeg");
    var inFilename = "video.h264";
    var outFilename = "video.mp4";
    
    ffmpeg(inFilename)
      .outputOptions("-c:v", "copy") // this will copy the data instead or reencode it
      .save(outFilename);
    

    A couple of notes:

    • fluent can be picky with filenames (spaces etc.).
    • FFmpeg needs to be preinstalled and available in the global path. If you don't want it to be, you can use the ffmpeg.setFfmpegPath(pathToFFmpegBin) instead.
    • To install FFmpeg on RPI, this resource may be useful.