-
Notifications
You must be signed in to change notification settings - Fork 7
/
mp4wasm.html
217 lines (191 loc) · 6.13 KB
/
mp4wasm.html
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<html>
<script src="mp4box.all.js"></script>
<script src="mp4wasm.js"></script>
<script>
async function reencode(file) {
const startNow = performance.now();
let decoder;
let encoder;
let mp4wasm;
let mp4wasmOutputFile;
let mp4wasmMux;
let track = null;
let decodedFrameIndex = 0;
let encodedFrameIndex = 0;
let nextKeyFrameTimestamp = 0;
let sampleDurations = [];
const mp4boxInputFile = MP4Box.createFile();
mp4boxInputFile.onError = error => console.error(error);
mp4boxInputFile.onReady = async (info) => {
track = info.videoTracks[0];
mp4wasm = await new MP4Wasm();
mp4wasmOutputFile = createVirtualFile();
const trak = mp4boxInputFile.getTrackById(track.id);
const duration = (trak.samples_duration / trak.mdia.mdhd.timescale) * 1000;
const fps = Math.round((track.nb_samples / duration) * 1000);
mp4wasmMux = mp4wasm.create_muxer(
{
width: track.track_width,
height: track.track_height,
fps,
fragmentation: true,
sequential: false,
hevc: false,
},
function mux_write(data_ptr, size, offset) {
mp4wasmOutputFile.seek(offset);
const data = mp4wasm.HEAPU8.subarray(data_ptr, data_ptr + size);
return mp4wasmOutputFile.write(data) !== data.byteLength;
}
);
decoder = new VideoDecoder({
async output(inputFrame) {
const bitmap = await createImageBitmap(inputFrame);
const outputFrame = new VideoFrame(bitmap, {
timestamp: inputFrame.timestamp,
});
const keyFrameEveryHowManySeconds = 2;
let keyFrame = false;
if (inputFrame.timestamp >= nextKeyFrameTimestamp) {
keyFrame = true;
nextKeyFrameTimestamp = inputFrame.timestamp + keyFrameEveryHowManySeconds * 1e6;
}
encoder.encode(outputFrame, { keyFrame });
inputFrame.close();
outputFrame.close();
decodedFrameIndex++;
displayProgress();
},
error(error) {
console.error(error);
}
});
let description;
for (const entry of trak.mdia.minf.stbl.stsd.entries) {
if (entry.avcC || entry.hvcC) {
const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);
if (entry.avcC) {
entry.avcC.write(stream);
} else {
entry.hvcC.write(stream);
}
description = new Uint8Array(stream.buffer, 8); // Remove the box header.
break;
}
}
decoder.configure({
codec: track.codec,
codedHeight: track.track_width,
codedWidth: track.track_width,
hardwareAcceleration: 'prefer-hardware',
description,
});
encoder = new VideoEncoder({
output(chunk) {
let uint8 = new Uint8Array(chunk.byteLength);
chunk.copyTo(uint8);
const p = mp4wasm._malloc(uint8.byteLength);
mp4wasm.HEAPU8.set(uint8, p);
mp4wasm.mux_nal(mp4wasmMux, p, uint8.byteLength);
mp4wasm._free(p);
encodedFrameIndex++;
displayProgress();
},
error(error) {
console.error(error);
}
});
encoder.configure({
codec: 'avc1.4d0034',
width: track.track_width,
height: track.track_height,
avc: {
format: 'annexb',
},
hardwareAcceleration: 'prefer-hardware',
bitrate: 14_000_000,
alpha: 'discard',
bitrateMode: 'variable',
latencyMode: 'realtime',
});
mp4boxInputFile.setExtractionOptions(track.id, null, {nbSamples: Infinity});
mp4boxInputFile.start();
};
function displayProgress() {
progress.innerText =
"Decoding frame " + decodedFrameIndex + " (" + Math.round(100 * decodedFrameIndex / track.nb_samples) + "%)\n" +
"Encoding frame " + encodedFrameIndex + " (" + Math.round(100 * encodedFrameIndex / track.nb_samples) + "%)\n";
}
mp4boxInputFile.onSamples = async (track_id, ref, samples) => {
for (const sample of samples) {
decoder.decode(new EncodedVideoChunk({
type: sample.is_sync ? "key" : "delta",
timestamp: sample.cts * 1_000_000 / sample.timescale,
duration: sample.duration * 1_000_000 / sample.timescale,
data: sample.data
}));
}
await decoder.flush();
await encoder.flush();
encoder.close();
decoder.close();
mp4wasm.finalize_muxer(mp4wasmMux);
const data = mp4wasmOutputFile.contents();
let url = URL.createObjectURL(new Blob([data], { type: "video/mp4" }));
let anchor = document.createElement("a");
anchor.href = url;
anchor.download = "mp4wasm.mp4";
anchor.click();
const seconds = (performance.now() - startNow) / 1000;
progress.innerText =
"Re-encoded " + encodedFrameIndex + " frames in " + (Math.round(seconds * 100) / 100) + "s at " +
Math.round(encodedFrameIndex / seconds) + " fps";
};
var reader = new FileReader();
reader.onload = function() {
this.result.fileStart = 0;
mp4boxInputFile.appendBuffer(this.result);
mp4boxInputFile.flush();
};
reader.readAsArrayBuffer(file);
}
function createVirtualFile(initialCapacity = 1024 * 1024) {
let cursor = 0;
let usedBytes = 0;
let contents = new Uint8Array(initialCapacity);
return {
contents: function () {
return contents.slice(0, usedBytes);
},
seek: function (offset) {
// offset in bytes
cursor = offset;
},
write: function (data) {
const size = data.byteLength;
expand(cursor + size);
contents.set(data, cursor);
cursor += size;
usedBytes = Math.max(usedBytes, cursor);
return size;
},
};
function expand(newCapacity) {
var prevCapacity = contents.length;
if (prevCapacity >= newCapacity) {
return; // No need to expand, the storage was already large enough.
}
newCapacity = Math.max(newCapacity, (prevCapacity * 2.0) >>> 0);
const oldContents = contents;
contents = new Uint8Array(newCapacity); // Allocate new storage.
if (usedBytes > 0) {
contents.set(oldContents.subarray(0, usedBytes), 0);
}
}
}
</script>
<p>
Select a video to re-encode:
<input type="file" onchange="reencode(event.target.files[0])"></input>
<div id="progress"></div>
</p>