@revideo/2d 0.4.2-turtle.993 → 0.4.3-alpha.1001

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ import {FrameExtractor} from './mp4-parser';
2
+
3
+ // List of VideoFrameExtractors
4
+ const videoFrameExtractors = new Map<string, FrameExtractor>();
5
+
6
+ export async function getFrame(
7
+ id: string,
8
+ filePath: string,
9
+ time: number,
10
+ fps: number,
11
+ ) {
12
+ // Check if we already have a VideoFrameExtractor for this video
13
+ const extractorId = filePath + '-' + id;
14
+ let extractor = videoFrameExtractors.get(extractorId);
15
+
16
+ const frameDuration = 1 / fps;
17
+
18
+ const isOldFrame =
19
+ extractor && Math.abs(time - extractor.getLastTime()) < frameDuration / 2;
20
+
21
+ // If time has not changed, return the last frame
22
+ if (isOldFrame) {
23
+ const lastFrame = extractor!.getLastFrame();
24
+ if (!lastFrame) {
25
+ throw new Error('No last frame');
26
+ }
27
+
28
+ return lastFrame;
29
+ }
30
+
31
+ // If the video has skipped back we need to create a new extractor
32
+ if (extractor && time + frameDuration < extractor.getTime()) {
33
+ extractor.close();
34
+ videoFrameExtractors.delete(extractorId);
35
+ extractor = undefined;
36
+ }
37
+
38
+ // If the video has skipped forward we need to create a new extractor
39
+ if (extractor && time > extractor.getTime() + frameDuration) {
40
+ extractor.close();
41
+ videoFrameExtractors.delete(extractorId);
42
+ extractor = undefined;
43
+ }
44
+
45
+ if (!extractor) {
46
+ extractor = new FrameExtractor(filePath, fps, time);
47
+ await extractor.start();
48
+ videoFrameExtractors.set(extractorId, extractor);
49
+ }
50
+
51
+ // Go to the frame that is closest to the requested time
52
+ return extractor.getNextFrame();
53
+ }
@@ -0,0 +1,338 @@
1
+ import {createFile, DataStream} from 'mp4box';
2
+
3
+ // Wraps an MP4Box File as a WritableStream underlying sink.
4
+ class MP4FileSink {
5
+ private setStatus;
6
+ private file;
7
+ private offset;
8
+
9
+ public constructor(file: any, setStatus: any, offset: number = 0) {
10
+ this.file = file;
11
+ this.setStatus = setStatus;
12
+ this.offset = offset;
13
+ }
14
+
15
+ public write(chunk: any) {
16
+ const buffer = new ArrayBuffer(chunk.byteLength);
17
+ new Uint8Array(buffer).set(chunk);
18
+
19
+ // Inform MP4Box where in the file this chunk is from.
20
+ (buffer as any).fileStart = this.offset;
21
+ this.offset += buffer.byteLength;
22
+
23
+ this.setStatus('fetch', (this.offset / 1024 ** 2).toFixed(1) + ' MiB');
24
+ this.file.appendBuffer(buffer);
25
+ }
26
+
27
+ public close() {
28
+ this.setStatus('fetch', 'Done');
29
+ this.file.flush();
30
+ }
31
+ }
32
+
33
+ function description(file: any, track: any) {
34
+ const trak = file.getTrackById(track.id);
35
+ for (const entry of trak.mdia.minf.stbl.stsd.entries) {
36
+ const box = entry.avcC || entry.hvcC || entry.vpcC || entry.av1C;
37
+ if (box) {
38
+ const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);
39
+ box.write(stream);
40
+ return new Uint8Array(stream.buffer, 8); // Remove the box header.
41
+ }
42
+ }
43
+ throw new Error('avcC, hvcC, vpcC, or av1C box not found');
44
+ }
45
+
46
+ export class FrameExtractor {
47
+ private frameBuffer: VideoFrame[] = [];
48
+ private closed = false;
49
+
50
+ // URI of the video.
51
+ private uri: string;
52
+ // FPS to target when extracting frames. We use frame sampling.
53
+ private targetFps: number;
54
+ // Actual FPS of the video.
55
+ private sourceFps: number;
56
+ // Offset when the video starts.
57
+ private startTime: number;
58
+ // Number of frames that have been requested and returned.
59
+ private framesRequested = 0;
60
+ // Number of samples that have been passed to the decoder but have not been output yet.
61
+ private framesDue = 0;
62
+ // Last frame that has been output.
63
+ private lastFrame: VideoFrame | null = null;
64
+
65
+ private decoder: VideoDecoder;
66
+ private file: any;
67
+
68
+ private readMoreFromResponse: () => Promise<void> = async () => {};
69
+ private responseFinished = false;
70
+
71
+ public constructor(uri: string, targetFps: number, startTime: number) {
72
+ this.uri = uri;
73
+ this.startTime = startTime;
74
+
75
+ // Initialized after the file is loaded.
76
+ this.sourceFps = 0;
77
+ this.targetFps = targetFps;
78
+
79
+ this.decoder = new VideoDecoder({
80
+ output: this.onFrame.bind(this),
81
+ error(e) {
82
+ console.error(e);
83
+ },
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Starts streaming the video at the given URI from the given offset.
89
+ * @param file - MP4Box file. Needs to be created and configured before calling this function.
90
+ * @param uri - URI of the video file.
91
+ * @param offset - Offset to start streaming from.
92
+ * @returns - A function to read more data from the response.
93
+ */
94
+ private async startStreamingAtOffset(file: any, uri: string, offset: number) {
95
+ return fetch(uri, {
96
+ headers: {
97
+ /* eslint-disable-next-line @typescript-eslint/naming-convention */
98
+ Range: `bytes=${offset}-`,
99
+ },
100
+ }).then(async response => {
101
+ if (!response.body) {
102
+ throw new Error('Response body is null');
103
+ }
104
+
105
+ const reader = response.body.getReader();
106
+ const sink = new MP4FileSink(file, () => {}, offset);
107
+
108
+ return async () => {
109
+ return reader.read().then(({done, value}) => {
110
+ // Request is done.
111
+ if (done) {
112
+ this.responseFinished = true;
113
+ this.decoder.flush();
114
+ sink.close();
115
+ return;
116
+ }
117
+
118
+ sink.write(value);
119
+ });
120
+ };
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Loads the file at the given URI until it finds the moov box.
126
+ * Once found, it calls `setConfig` with the video configuration.
127
+ * @param uri - The URI of the video file.
128
+ * @param setConfig - Callback to set the video configuration.
129
+ * @returns
130
+ */
131
+ private async getFileInfo(
132
+ uri: string,
133
+ setConfig: (config: VideoDecoderConfig) => void,
134
+ ) {
135
+ return new Promise<any>((res, rej) => {
136
+ const file = createFile();
137
+ let found = false;
138
+
139
+ file.onReady = (info: any) => {
140
+ found = true;
141
+
142
+ const track = info.videoTracks[0];
143
+
144
+ const config = {
145
+ // Browser doesn't support parsing full vp8 codec (eg: `vp08.00.41.08`),
146
+ // they only support `vp8`.
147
+ codec: track.codec.startsWith('vp08') ? 'vp8' : track.codec,
148
+ codedHeight: track.video.height,
149
+ codedWidth: track.video.width,
150
+ description: description(file, track),
151
+ };
152
+
153
+ // Calculate FPS
154
+ if (track.nb_samples && track.timescale && info.duration) {
155
+ this.sourceFps = track.nb_samples / (info.duration / info.timescale);
156
+ }
157
+
158
+ setConfig(config);
159
+
160
+ file.setExtractionOptions(track.id);
161
+ file.start();
162
+
163
+ res(file);
164
+ };
165
+
166
+ return fetch(uri).then(async response => {
167
+ if (!response.body) {
168
+ throw new Error('Response body is null');
169
+ }
170
+
171
+ const reader = response.body.getReader();
172
+ const sink = new MP4FileSink(file, () => {});
173
+
174
+ while (!found) {
175
+ await reader.read().then(({done, value}) => {
176
+ if (done) {
177
+ file.flush();
178
+ rej('Could not find moov');
179
+ return;
180
+ }
181
+
182
+ sink.write(value);
183
+ });
184
+ }
185
+ });
186
+ });
187
+ }
188
+
189
+ /**
190
+ * Starts the extraction process.
191
+ */
192
+ public async start() {
193
+ this.file = await this.getFileInfo(
194
+ this.uri,
195
+ this.decoder.configure.bind(this.decoder),
196
+ );
197
+ this.file.onSamples = this.onSamples.bind(this);
198
+
199
+ const seekInfo = this.file.seek(this.startTime, true);
200
+ this.readMoreFromResponse = await this.startStreamingAtOffset(
201
+ this.file,
202
+ this.uri,
203
+ seekInfo.offset,
204
+ );
205
+ }
206
+
207
+ /**
208
+ * Called when we are done with the extractor.
209
+ */
210
+ public close() {
211
+ this.closed = true;
212
+ this.file.flush();
213
+ this.frameBuffer.forEach(frame => frame.close());
214
+ this.lastFrame?.close();
215
+ }
216
+
217
+ /**
218
+ * @returns - Time in seconds of the current frame (using the target FPS)
219
+ */
220
+ public getTime() {
221
+ return this.startTime + this.framesRequested / this.targetFps;
222
+ }
223
+
224
+ /**
225
+ * @returns - Time in seconds of the last frame (using the target FPS)
226
+ */
227
+ public getLastTime() {
228
+ return this.startTime + (this.framesRequested - 1) / this.targetFps;
229
+ }
230
+
231
+ public getLastFrame() {
232
+ return this.lastFrame;
233
+ }
234
+
235
+ /**
236
+ * Called when samples are available on the MP4 file.
237
+ * Sends chunks to the decoder.
238
+ */
239
+ private onSamples(_unused1: any, _unused2: any, samples: any) {
240
+ for (const sample of samples) {
241
+ const chunk = new EncodedVideoChunk({
242
+ type: sample.is_sync ? 'key' : 'delta',
243
+ timestamp: (1e6 * sample.cts) / sample.timescale,
244
+ duration: (1e6 * sample.duration) / sample.timescale,
245
+ data: sample.data,
246
+ });
247
+ this.framesDue++;
248
+ this.decoder.decode(chunk);
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Called when the decoder has a frame ready.
254
+ * Pushes the frame to the buffer so it can be consumed.
255
+ */
256
+ private onFrame(frame: VideoFrame) {
257
+ this.framesDue--;
258
+ const timestampInSeconds = frame.timestamp / 1e6;
259
+ if (timestampInSeconds < this.startTime) {
260
+ frame.close();
261
+ return;
262
+ }
263
+
264
+ // If the extractor is already closed, close the frame.
265
+ if (this.closed) {
266
+ frame.close();
267
+ return;
268
+ }
269
+
270
+ this.frameBuffer.push(frame);
271
+ }
272
+
273
+ private sum = 0;
274
+
275
+ private async populateBuffer() {
276
+ // Fetch more frames if we don't have any.
277
+ while (this.frameBuffer.length === 0 && !this.responseFinished) {
278
+ await this.readMoreFromResponse();
279
+ await new Promise(res => setTimeout(res, 0));
280
+ }
281
+
282
+ // Wait for decoder if there are frames due.
283
+ if (this.frameBuffer.length === 0 && this.framesDue) {
284
+ let maxIterations = 1000;
285
+ while (this.frameBuffer.length === 0) {
286
+ await new Promise(res => setTimeout(res, 10));
287
+ maxIterations--;
288
+
289
+ if (maxIterations === 0) {
290
+ throw new Error(
291
+ 'Timed out while waiting for VideoDecoder to produce a frame.',
292
+ );
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+ public async getNextFrame(): Promise<VideoFrame> {
299
+ const samplingRate = this.sourceFps / this.targetFps;
300
+ this.sum += samplingRate;
301
+
302
+ if (this.sum <= 1 && this.lastFrame) {
303
+ this.framesRequested++;
304
+ return this.lastFrame;
305
+ }
306
+
307
+ await this.populateBuffer();
308
+
309
+ // We're at the end of the video and there are no more frames to extract.
310
+ if (this.frameBuffer.length === 0) {
311
+ return this.lastFrame!;
312
+ }
313
+
314
+ while (this.sum >= 2) {
315
+ // Burn frame
316
+ const frame = this.frameBuffer.shift()!;
317
+ frame.close();
318
+ this.sum -= 1;
319
+
320
+ await this.populateBuffer();
321
+ if (this.frameBuffer.length === 0) {
322
+ return this.lastFrame!;
323
+ }
324
+ }
325
+
326
+ if (this.sum >= 1 || !this.lastFrame) {
327
+ this.sum -= 1;
328
+ const frame = this.frameBuffer.shift()!;
329
+ this.lastFrame?.close();
330
+ this.lastFrame = frame;
331
+ this.framesRequested++;
332
+ return frame;
333
+ }
334
+
335
+ // One of the three if statements above is always true.
336
+ throw new Error('Unreachable code');
337
+ }
338
+ }