/
node-mux.js
89 lines (79 loc) · 2.19 KB
/
node-mux.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const loadEncoder = require("../");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const readFile = promisify(fs.readFile);
(async () => {
const Encoder = await loadEncoder();
const stream = fs.createWriteStream(
path.resolve(__dirname, "outputs/foreman.mp4")
);
const width = 352;
const height = 288;
const mux = Encoder.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/foreman.264");
const buffer = await readFile(file);
for (let chunk of readNAL(buffer)) {
// malloc() / free() a pointer
const p = Encoder.create_buffer(chunk.byteLength);
// set data in memory
Encoder.HEAPU8.set(chunk, p);
// write NAL units with AnnexB format
// <Uint8Array [startcode] | [NAL] | [startcode] | [NAL] ...>
Encoder.mux_nal(mux, p, chunk.byteLength);
Encoder.free_buffer(p);
}
// Note: this may trigger more writes
Encoder.finalize_muxer(mux);
function write(pointer, size, offset) {
const buf = Encoder.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;
}
}