const loadMP4Module = require("../build/mp4.node");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const readFile = promisify(fs.readFile);
const width = 1920;
const height = 1080;
const { createCanvas, loadImage } = require('canvas')
var MP4;
var stream;
const drawFrame = (interpolant) => {
ctx.fillStyle = "#0000FF";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width * interpolant, canvas.height * interpolant);
};
function write(pointer, size, offset) {
const buf = MP4.HEAPU8.slice(pointer, pointer + size);
// Write the MP4-muxed chunk directly into a .mp4 stream
stream.write(buf);
return 0;
}
// For an arbitrary stream of data, yield/iterate
// on each AnnexB NAL chunk (including the startcode)
function* readNAL(buffer, offset = 0) {
let h264Size = buffer.byteLength;
while (h264Size > 0) {
const nal_size = getNALSize(buffer, offset, h264Size);
if (nal_size < 4) {
offset += 1;
h264Size -= 1;
continue;
}
yield buffer.subarray(offset, offset + nal_size);
offset += nal_size;
h264Size -= nal_size;
}
function getNALSize(buf, ptr, size) {
let pos = 3;
while (size - pos > 3) {
if (
buf[ptr + pos] == 0 &&
buf[ptr + pos + 1] == 0 &&
buf[ptr + pos + 2] == 1
)
return pos;
if (
buf[ptr + pos] == 0 &&
buf[ptr + pos + 1] == 0 &&
buf[ptr + pos + 2] == 0 &&
buf[ptr + pos + 3] == 1
)
return pos;
pos++;
}
return size;
}
}
(async () => {
const canvas = createCanvas(width, height)
const ctx = canvas.getContext('2d')
// Write "Awesome!"
ctx.font = '30px Impact'
ctx.rotate(0.1)
ctx.fillText('Awesome!', 50, 100)
// Draw line under text
var text = ctx.measureText('Awesome!')
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
ctx.beginPath()
ctx.lineTo(50, 102)
ctx.lineTo(50 + text.width, 102)
ctx.stroke()
stream = fs.createWriteStream(
path.resolve(__dirname, "outputs/composition.mp4")
);
const fps = 60;
const duration = 4;
let frame = 0;
let totalFrames = Math.round(fps * duration);
console.time("encode");
MP4 = await loadMP4Module();
const mux = MP4.create_muxer(
{
width,
height,
// Needed to write sequentially to a file
// i.e. no 'offset' parameter needed
sequential: true,
},
write
);
const file = path.resolve(__dirname, "fixtures/composition");
// JPEG-encoded, 50% quality
const buffer = canvas.toBuffer('image/jpeg', { quality: 0.5 })
for (let chunk of readNAL(buffer)) {
// malloc() / free() a pointer
const p = MP4.create_buffer(chunk.byteLength);
// set data in memory
MP4.HEAPU8.set(chunk, p);
// write NAL units with AnnexB format
// <Uint8Array [startcode] | [NAL] | [startcode] | [NAL] ...>
MP4.mux_nal(mux, p, chunk.byteLength);
MP4.free_buffer(p);
}
// Note: this may trigger more writes
MP4.finalize_muxer(mux);
})();