Introducing h264-mp4-encoder
Encode directly to H264 and ouput as an MP4 in node or on the web with WebAssembly! Works with the HTML5 Canvas :)

npm install h264-mp4-encoder
Example
Web:
<script src="https://unpkg.com/h264-mp4-encoder/embuild/dist/h264-mp4-encoder.web.js"></script>
JavaScript:
const HME = require("h264-mp4-encoder");
TypeScript:
import * as HME from "h264-mp4-encoder";
Example:
HME.createH264MP4Encoder().then(encoder => {
encoder.width = 100;
encoder.height = 100;
encoder.initialize();
encoder.addFrameRgba(new Uint8Array(encoder.width * encoder.height * 4).fill(128))
encoder.finalize();
const uint8Array = encoder.FS.readFile(encoder.outputFilename);
console.log(uint8Array);
encoder.delete();
})
You can also use await
:
const encoder = await HME.createH264MP4Encoder();
API
async function createH264MP4Encoder(): Promise<H264MP4Encoder>;
interface H264MP4Encoder {
outputFilename: number;
width: number;
height: number;
frameRate: number;
kbps: number;
speed: number;
quantizationParameter: number;
groupOfPictures: number;
temporalDenoise: number;
desiredNaluBytes: number;
debug: number;
initialize(): void;
addFrameYuv(buffer: ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | string): void;
addFrameRgba(buffer: ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | string): void;
finalize(): void;
delete(): void;
FS: typeof FS;
}
How?
This library brings together the public domain minih264 H264 encoder, as well as the MPL 1.1 licenced libmp4v2 to write the H264 NAL unit data into an MP4 file. Both of these are compiled in Emscripten within a Docker image and Webpacked to create easily importable modules. This repo uses submodules that are forks of those two libraries with changes for Emscripten (and to comply with the MPL 1.1 license).
Where is the WebAssembly?
To make packaging considerably easier, I built with Emscripten's -s SINGLE_FILE=1
which base64 encodes the wasm inside the JavaScript file. You're welcome to remove this option to get a wasm file, but you'll need to handle Webpack importing as well as the locateFile
within the Emscripten Module object.
Building on Ubuntu
You must have docker installed, however all other depdendencies for building for node/web are within the Docker container).
./build.sh
To run the C++ code natively (not using Emscripten) you must have cmake and a compiler:
git submodule update --init --recursive
mkdir build
cd build
cmake ..
cmake --build --parallel .