-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
1362 lines (1253 loc) · 197 KB
/
worker.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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Wraps an MP4Box File as a WritableStream underlying sink.
// https://w3c.github.io/webcodecs/samples/video-decode-display/
const currentWorker = self;
const wait = (n) => new Promise((resolve) => setTimeout(resolve, n));
class MyMP4FileSink {
#setStatus = null;
#file = null;
#offset = 0;
constructor(file, setStatus) {
this.#file = file;
this.#setStatus = setStatus;
}
write(chunk) {
// MP4Box.js requires buffers to be ArrayBuffers, but we have a Uint8Array.
const buffer = new ArrayBuffer(chunk.byteLength);
new Uint8Array(buffer).set(chunk);
// Inform MP4Box where in the file this chunk is from.
buffer.fileStart = this.#offset;
this.#offset += buffer.byteLength;
// Append chunk.
this.#setStatus("fetch", (this.#offset / (1024 ** 2)).toFixed(1) + " MiB");
this.#file.appendBuffer(buffer);
}
close() {
this.#setStatus("fetch", "Done");
this.#file.flush();
}
}
// Demuxes the first video track of an MP4 file using MP4Box, calling
// `onConfig()` and `onChunk()` with appropriate WebCodecs objects.
// // https://w3c.github.io/webcodecs/samples/video-decode-display/
class MyMP4Demuxer {
#onConfig = null;
#onChunk = null;
#onFinish = null;
#setStatus = null;
#file = null;
constructor(uri, {onConfig, onChunk, onFinish, setStatus}) {
this.#onConfig = onConfig;
this.#onChunk = onChunk;
this.#onFinish = onFinish;
this.#setStatus = setStatus;
// Configure an MP4Box File for demuxing.
this.#file = MP4Box.createFile();
this.#file.onError = error => {
console.error(error);
setStatus("demux", error);
}
this.#file.onReady = this.#onReady.bind(this);
this.#file.onSamples = this.#onSamples.bind(this);
// Fetch the file and pipe the data through.
const fileSink = new MyMP4FileSink(this.#file, setStatus);
console.log("We will fetch uri:", uri);
fetch(uri).then(async response => {
// highWaterMark should be large enough for smooth streaming, but lower is better for memory usage.
await response.body.pipeTo(new WritableStream(fileSink, {highWaterMark: 2}));
await this.#file.flush();
if(this.#onFinish) this.#onFinish();
});
}
// Get the appropriate `description` for a specific track. Assumes that the
// track is H.264 or H.265.
#description(track) {
const trak = this.#file.getTrackById(track.id);
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);
}
return new Uint8Array(stream.buffer, 8); // Remove the box header.
}
}
throw "avcC or hvcC not found";
}
#onReady(info) {
this.#setStatus("demux", "Ready");
const track = info.videoTracks[0];
// Generate and emit an appropriate VideoDecoderConfig.
this.#onConfig({
codec: track.codec,
codedHeight: track.video.height,
codedWidth: track.video.width,
description: this.#description(track),
mp4boxFile: this.#file,
info: info,
});
// Start demuxing.
this.#file.setExtractionOptions(track.id);
this.#file.start();
}
async #onSamples(track_id, ref, samples) {
console.debug("Received multiple samples (aka frames): ");
// console.debug(track_id, ref, samples);
// Generate and emit an EncodedVideoChunk for each demuxed sample.
for (const sample of samples) {
// console.debug(sample.is_sync);
this.#onChunk(new EncodedVideoChunk({
type: sample.is_sync ? "key" : "delta",
timestamp: 1e6 * sample.cts / sample.timescale,
duration: 1e6 * sample.duration / sample.timescale,
data: sample.data,
}));
}
}
}
// https://stackoverflow.com/questions/6902334/how-to-let-javascript-wait-until-certain-event-happens
function getPromiseFromEvent(item, event, functionSaveListener) {
return new Promise((resolve) => {
const listener = (e) => {
item.removeEventListener(event, listener);
resolve(e);
}
if(functionSaveListener) {
functionSaveListener(listener);
}
item.addEventListener(event, listener);
})
}
// Wait for an event to trigger, run f, if f is true stops, otherwise restart until finding a valid event.
async function waitEventUntil(item, event, f, functionSaveListener) {
const e = await getPromiseFromEvent(item, event);
if (f(e)) {
return e
} else {
return await waitEventUntil(item, event, f, functionSaveListener)
}
}
async function waitEventUntilWithAbort(item, event, f, functionSaveListener, abortIfNeeded) {
console.debug("abortIfNeeded", abortIfNeeded);
const e = await abortIfNeeded(getPromiseFromEvent(item, event, functionSaveListener), "01");
if (f(e)) {
return e
} else {
return await abortIfNeeded(waitEventUntilWithAbort(item, event, f, functionSaveListener, abortIfNeeded));
}
}
// dequeue is not enough, as it seems to run before the call to output.
// the event value is the id of the newly cached frame.
const newCachedFrame = new Event("newCachedFrame");
/* self.addEventListener("newCachedFrame", (e) => {console.debug("Dummy");})
* setTimeout(() => self.dispatchEvent(newCachedFrame, 42), 2000);
* await waitEventUntil(self, "newCachedFrame", () => true);
* console.debug("Yeahhh Received!"); */
// Needed to abort everything when a new function is called by the user.
// https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#implementing_an_abortable_api
function makeMeAbortIfNeeded(promise, signal, debug) {
return new Promise((resolve, reject) =>{
// If the signal is already aborted, immediately throw in order to reject the promise.
if (signal.aborted) {
console.debug("Stopped before promise", promise);
reject(signal.reason);
}
const myListener = () => {
// Why isn't this working?? It s
console.debug("Just received a signal to abort");
// Stop the main operation
// Reject the promise with the abort reason.
// WARNING: if the promise itself contains non blocking stuff, it will still continue to run.
console.debug("Stopped during promise", promise, debug);
reject(signal.reason);
//reject(new Error(debug));
};
promise.then(x => {
signal.removeEventListener("abort", myListener);
resolve(x);
});
signal.addEventListener("abort", myListener, {once: true});
});
}
// catches the abort. Only use if you do NOT await for efficiency reasons for instance. Otherwise the
// next code will just run normally.
function silentlyAbort(promise) {
return promise.catch(error => {
console.debug("I just got error", error);
});
}
// Used to get the frames in order to
class GetAnyFrame {
constructor(videoUri, userConfig) {
this.videoUri = videoUri;
// Note that this value is not strictly respected, as we cache elements by chuncks (of size the number of
// elements between two key frames, in my tests it is often around 250). But we will start to
// garbage collect when we go over this limit after caching these elements, so in total we can go up to
// roughly this.maxNumberCachedFrames + 250. Note that the chunk just loaded cannot be garbage collected.
this.maxNumberCachedFrames = userConfig.maxNumberCachedFrames || 50;
this.nbFramesDecodeInAdvance = userConfig.minNumberCachedFrames || 30;
this.minNumberCachedFrames = Math.max(this.nbFramesDecodeInAdvance, userConfig.minNumberCachedFrames || 30);
this.maxDecodeQueueSize = Math.max(this.minNumberCachedFrames, userConfig.maxDecodeQueueSize || 30);
console.log("this.maxNumberCachedFrames", this.maxNumberCachedFrames, "this.nbFramesDecodeInAdvance", this.nbFramesDecodeInAdvance, "this.minNumberCachedFrames", this.minNumberCachedFrames, "this.maxDecodeQueueSize", this.maxDecodeQueueSize);
// cachedFrames[i] = {
// frame: frame,
// priorityRemove: // higher says that the image should be garbage collected later. Infinity means that
// the image should never be garbage collected (e.g. if we want stop point to always
// stay in the cache). See nextPriorityRemove to determine.
// }
// We use map instead of dictionaries/object since dictionaries do not provide efficient way to compute the
// length, needed to clean the cache (so use .get/.set).
// https://stackoverflow.com/questions/37382231/fast-alternative-to-object-keysobj-length
this.cachedFrames = new Map();
this.nextPriorityRemove = 0;
// This contains all non-decoded frames in format:
// {
// nonDecodedFrame: ...;
// idParentKeyFrame: id of key frame needed to decode (not the delta one)
// idNextKeyFrame: id of next key frame, needed to decode the whole block as we must restart from a key frame after a flush https://github.com/w3c/webcodecs/issues/220
// }
// It will take wayyy less memory than decoded
// frames (hopefully), while allowing fast access (and later we might be able to optimize
// it better by just storing the offset in the url file, but I am not sure how to do, so let's do
// one step at a time).
this.allNonDecodedFrames = [];
// Only needed to obtain the parent keyframe of the currently demuxed frame
this.lastDecodedFrame = null;
// One option to map the decoded frame with its ID is to use a new queue with the id of frame currently
// getting decoded. But since we reset the decoder when starting from an unrelated keyframe, it means that this queue would look like: [i, i+1, i+2, i+3, i+4, ...]. Instead, we store just "i" in the following variable,
// denoting the id of the frame that will be decoded next, and we increase it when a new frame is decoded.
this.idOfNextDecodedKeyFrame = null;
// Useful to remove the listener
this.getFrameListener = null;
// Fetch and demux the media data (i.e. basically extract the key and delta frames with decompressing them
// into a real image).
this.demuxer = new MyMP4Demuxer(this.videoUri, {
onConfig: (config) => {
this._onConfig(userConfig,config);
},
onFinish: async () => {
await this._onFinishDemuxer(userConfig);
},
// a chunk is a non decoded frame
onChunk: (chunk) => {
// Check if this is a key frame
if (chunk.type == "key") {
this.lastKeyframe = this.allNonDecodedFrames.length;
}
if (this.lastKeyframe === undefined) {
console.log("Error: the last key frame is undefined, which should NEVER appear if you start to decode from a key frame. ");
}
this.allNonDecodedFrames.push({
nonDecodedFrame: chunk,
idParentKeyFrame: this.lastKeyframe // we will add idNextKeyFrame later in _onFinishDemuxer
});
},
// TODO: make this useful
setStatus: (a, b) => {
console.debug("status:", a, b);
},
});
this.decoderConfig = null;
this.decoder = new VideoDecoder({
output: this._onDecodedFrame.bind(this),
error: (e) => {
console.debug("I just got an error during decoding:", e);
/* console.error(e); */
// This does not exist for now: more cleanly deal with error later.
setStatus("decode", e);
},
});
// So that we know if we need to reset or not
this.nextFrameToAskForDecode = 0;
this._getMainAbortSignal = userConfig._getMainAbortSignal;
}
abortIfNeeded(promise, debug) {
return makeMeAbortIfNeeded(promise, this._getMainAbortSignal(), debug);
}
getVideoWidth() {
return this.videoWidth;
}
getVideoHeight() {
return this.videoHeight;
}
_onConfig(userConfig, config) {
if(userConfig.onConfigDemuxer) userConfig.onConfigDemuxer(config);
this.decoderConfig = config;
this.decoderConfig.optimizeForLatency = true;
this.videoWidth = config.codedWidth;
this.videoHeight = config.codedHeight;
const fps = config.info.videoTracks[0].nb_samples / (config.info.videoTracks[0].samples_duration / config.info.videoTracks[0].timescale);
console.debug("fps", fps);
if (fps < 120) {
this.fps = fps;
console.log("Setting fps to " + fps);
} else {
console.log("Found weird fps settings, default to 24fps: " + fps);
this.fps = fps;
}
if (userConfig._onConfig) {
userConfig._onConfig(config);
}
if (userConfig.onConfig) {
userConfig.onConfig(config);
}
// We configure the decoder (specify which codec we use etc)
this.decoder.configure(this.decoderConfig);
}
async _onFinishDemuxer(userConfig) {
// We compute idNextKeyFrame now, by going through the array starting from the end.
// Another option might be to do it at the end of demuxing a group of frames, but I am not 100% sure
// if we always end on a keyFrame, so let's do it here for safety.
// At the very end, the lastKeyFrame will be the "next" frame (not existing in the array):
var lastKeyFrame = this.allNonDecodedFrames.length;
for(var i = this.allNonDecodedFrames.length - 1; i >= 0; i--) {
this.allNonDecodedFrames[i].idNextKeyFrame = lastKeyFrame;
if (this.allNonDecodedFrames[i].nonDecodedFrame.type == "key") {
lastKeyFrame = i;
}
}
// We just finished to demux the whole file, so this.allNonDecodedFrames is properly set.
console.log("We just finished to demux the whole file.", this.allNonDecodedFrames);
if(userConfig._onFinishDemuxer) {
await userConfig._onFinishDemuxer();
}
if(userConfig.onFinishDemuxer) {
await userConfig.onFinishDemuxer();
}
}
_onDecodedFrame(frame) {
console.debug("starting onDecodedFrame");
var idFrame = this.idOfNextDecodedKeyFrame;
this.idOfNextDecodedKeyFrame++;
// We add the frame to the cache
console.debug("We are adding to the cache the frame", idFrame, "with priority", this.nextPriorityRemove);
this.cachedFrames.set(idFrame, {
frame: frame,
lastAccessed: this.nextPriorityRemove
});
this.nextPriorityRemove++;
currentWorker.dispatchEvent(newCachedFrame, {id: idFrame});
console.debug("ending onDecodedFrame");
}
// We can specify an element not to garbage collect (useful to keey the last value that was decoded)
// Cleans the frame to ensure the memory contains only a small number of decoded frames.
_garbageCollectFrames(fromIdFrameNotToGarbageCollect, toExcludedIdFrameNotToGarbageCollect) {
console.debug("In _garbageCollectFrames");
// If there were an error, for instance we stopped the function due to a race condition, no need to garbage
// collect now.
if(toExcludedIdFrameNotToGarbageCollect < 0) {
return;
};
console.debug("garbage starting items", this.cachedFrames.size);
// we add a -1 so that we do not count the current frame
if(this.cachedFrames.size - 1 > this.maxNumberCachedFrames) {
// We sort the element to remove them.
// .entries outputs an array [key, value]
const orderedElements = [...this.cachedFrames.entries()].filter(x => x[1].priorityRemove != Infinity && (x[0] < fromIdFrameNotToGarbageCollect || x[0] >= toExcludedIdFrameNotToGarbageCollect)).sort((a, b) => a[1].priorityRemove - b[1].priorityRemove);
// nb elements beginning: this.cachedFrames.size
// nb elements end: this.minNumberCachedFrames
// nb elements to remove =
const nbElementsToRemove = Math.min(
// We cannot remove more elements as the other elements are protected from being removed
orderedElements.length,
this.cachedFrames.size - this.minNumberCachedFrames);
for (var i=0; i < nbElementsToRemove; i++) {
this.cachedFrames.get(orderedElements[i][0]).frame.close();
this.cachedFrames.delete(orderedElements[i][0]);
orderedElements[i][1].frame.close();
}
}
console.debug("garbage ending items", this.cachedFrames.size);
}
// Make sure that all elements between idFrom and idToExcluded are in the cache. It returns the last element
// that was send to decode (might be larger, like +10 due to latency of codec), useful for preserving it in the cache.
async _forceAddInCache(idFrom, idToExcluded) {
console.debug("In _forceAddInCache");
// We want to make sure we do not call this function twice (race conditions on the decoder could be fairly bad).
// So we increment a public counter when we start this function, and all functions that are currently running
// with a lower counter stop. Seems there is no other way?
// https://stackoverflow.com/questions/26298500/stop-pending-async-function-in-javascript
console.debug("Starting _forceAddInCache", "from", idFrom, "to", idToExcluded);
// Make sure they are not too large, and properly ordered
if(idFrom >= this.allNonDecodedFrames.length) { return -1 }
idToExcluded = Math.min(idToExcluded, this.allNonDecodedFrames.length);
if(idFrom >= idToExcluded) { return -1 }
// Depending on the codec, we might need to push many (~10?) frames until seing a frame.
// https://github.com/w3c/webcodecs/issues/753
// So the trick (also for efficiency), is to send decode messages until we see enough messages.
// In the examble https://webcodecs-samples.netlify.app/audio-video-player/audio_video_player.html
// they even try to saturate the decoder by keeping sending decode messages until the queue starts to grow.
// Let us try.
// We check if we can continue from where we are right now
var nextElementToDecode = null;
// If we are after the frame that will be decoded next, and if we share the same parent key, we can
// just continue to decode normally, otherwise we first need to reset:
console.debug(idFrom, this.allNonDecodedFrames[idFrom].idParentKeyFrame, this.idOfNextDecodedKeyFrame);
if (idFrom >= this.idOfNextDecodedKeyFrame
&& this.idOfNextDecodedKeyFrame !== null
&& this.allNonDecodedFrames[idFrom].idParentKeyFrame
== this.allNonDecodedFrames[this.idOfNextDecodedKeyFrame].idParentKeyFrame
) {
console.debug("I can just continue my usual work, starting to decode frame ", this.nextFrameToAskForDecode);
} else {
console.log("We will reset the decoder.");
// We restart from a completely unrelated keyframe: we need to reset the decoder. If not we reset:
this.decoder.reset();
// Resetting also gets rid of the configuration, so we need to reconfigure it (not sure if we lose
// efficiency here, but this is done only when we do a jump of frames)
this.decoder.configure(this.decoderConfig);
// If we reset, we need to restart from a key frame:
console.debug("this.allNonDecodedFrames[idFrom]", idFrom, this.allNonDecodedFrames[idFrom]);
nextElementToDecode = this.allNonDecodedFrames[idFrom].idParentKeyFrame;
this.idOfNextDecodedKeyFrame = nextElementToDecode;
this.nextFrameToAskForDecode = nextElementToDecode;
/* for(var j = this.allNonDecodedFrames[idFrom].idParentKeyFrame; j < idToExcluded; j++){
* console.debug("_forceAddInCache: decode ", j);
* this.decoder.decode(this.allNonDecodedFrames[j].nonDecodedFrame);
* } */
}
console.debug("We will start by decoding", this.nextFrameToAskForDecode);
// We send decode until we find our beloved element (we can also try to saturate even more if needed
// as done in the example). But before we remove the last element in case it is already in the cache.
if (this.cachedFrames.has(idToExcluded)) {
this.cachedFrames.get(idToExcluded).frame.close();
this.cachedFrames.delete(idToExcluded);
}
while (!this.cachedFrames.has(idToExcluded)) {
// Someone else started to run this function. Let us stop then.
if (this.decoder.decodeQueueSize > this.maxDecodeQueueSize) {
console.log("The decoder is overwhelmed, let's wait before sending new stuff in the queue of size: ", this.decoder.decodeQueueSize);
} else {
console.debug("Starting to decoding frame ", this.nextFrameToAskForDecode, this.decoder.decodeQueueSize, this.maxDecodeQueueSize);
if(this.nextFrameToAskForDecode >= this.allNonDecodedFrames.length) {
// We arrived at the end of the video: let us flush (unless someone else is already running this function)
await this.abortIfNeeded(this.decoder.flush(), "flush");
return nextElementToDecode;
} else {
this.decoder.decode(this.allNonDecodedFrames[this.nextFrameToAskForDecode].nonDecodedFrame);
this.nextFrameToAskForDecode++;
}
}
// since the decoding is asynchronously done, we need to stop temporarily the code to give
// time to the decoder to run.
// This is needed, otherwise the decoder will not have time to start its job and we will get into
// an infinite loop.
console.debug("Give a bit of time to decoder");
await this.abortIfNeeded(wait(0), "foowait");
console.debug("Decoder had enough time");
}
return nextElementToDecode;
}
getNumberOfFramesIfPossible() {
return this.allNonDecodedFrames.length;
}
async _forceAddInCacheAndGarbageCollect(idFrom, idToExcluded, idFromGC, idToGC) {
console.debug("In _forceAddInCacheAndGarbageCollect");
await this.abortIfNeeded(this._forceAddInCache(idFrom, idToExcluded), "foo _forceAddInCacheAndGarbageCollect");
if (idToGC === undefined) {
idToGC = this.nextFrameToAskForDecode;
}
if (idFromGC === undefined) {
idFromGC = idFrom;
}
this._garbageCollectFrames(idFromGC, idToGC);
}
// distance is the number of frame to try before giving up. Return either null or the id of the first frame
_findFirstNonCachedFrame(idFrame, distance) {
for (var j=0; j <= distance; j++) {
if(!this.cachedFrames.has(idFrame+j)) {
return idFrame+j;
}
}
return -1;
}
// TODO: make it work also if the frame is not yet available (loading video), or if i = Infinity to get the
// last frame. Get inspired by commented code in _drawFrameFromIndex
// The backward is an indication that we should store more frames in the cache not to always recompute the sames
// This returns -1 if the frame is out of range.
async getFrame(i, backward, forceInRange) {
// We check if the frame is in the good range
if(!forceInRange) {
if (i < 0 || i >= this.allNonDecodedFrames.length) {
return null;
}
} else {
if (i < 0) {
i = 0;
}
if (i >= this.allNonDecodedFrames.length) {
i = this.allNonDecodedFrames.length - 1;
}
}
// If we were already trying to get an image, we stop the older one.
if (this.getFrameListener) {
self.removeEventListener("newCachedFrame", this.getFrameListener);
this.getFrameListener = null;
}
// TODO: make it more robust to race conditions.
console.debug("Calling getFrame with i=", i);
// Will contain the result of _forceAddInCache
var nextElementToDecode = -1;
if (this.cachedFrames.has(i)) {
console.debug("Frame", i, "already cached.")
// The frame is already in the cache.
// This is cool to see a cached frame, but we want to start the decoding of the next frames to have them
// in due time. No need to do this optimization if we run backward (or at least not this way).
if(!backward) {
const firstNonCachedFrame = this._findFirstNonCachedFrame(i, this.nbFramesDecodeInAdvance);
// console.log("firstNonCachedFrame=",firstNonCachedFrame, "at distance smaller than ", this.nbFramesDecodeInAdvance, this.cachedFrames.has(i+this.nbFramesDecodeInAdvance), this.cachedFrames);
if (firstNonCachedFrame != -1) {
// We do not use await on purpose, otherwise it might slow down the process when it fetches new stuff
silentlyAbort(this._forceAddInCacheAndGarbageCollect(firstNonCachedFrame, i + this.nbFramesDecodeInAdvance + 1,i));
}
}
return this.cachedFrames.get(i).frame;
} else {
console.debug("Frame", i, "NOT in the cache.")
if(backward) {
// For backward, we don't care te preserve the cache since it is in the other direction.
// We do not await for efficiency reasons
silentlyAbort(this._forceAddInCacheAndGarbageCollect(
this.allNonDecodedFrames[i].idParentKeyFrame, i + 1,
this.allNonDecodedFrames[i].idParentKeyFrame, i + 1
));
} else {
console.debug("We will add in the cache", i, i + this.nbFramesDecodeInAdvance + 1);
// We do not await for efficiency reasons
silentlyAbort(this._forceAddInCacheAndGarbageCollect(i, i + this.nbFramesDecodeInAdvance + 1));
}
// If the decoder saturated, the frame might not be ready yet.
if(!this.cachedFrames.has(i)) {
console.debug("The frame is not arrived yet, I'm waiting for it to come…");
console.debug("this.decoder.decodeQueueSize", this.decoder.decodeQueueSize);
console.debug("this.abortIfNeeded 0", this.abortIfNeeded);
await this.abortIfNeeded(waitEventUntilWithAbort(
self,
"newCachedFrame",
() => this.cachedFrames.has(i),
(l) => {
this.getFrameListener = l
},
this.abortIfNeeded.bind(this)
), "foo eiaunrst");
}
console.debug("We received the frame");
return this.cachedFrames.get(i).frame;
}
}
getNumberFrame() {
// TODO: make it work if video not loaded yet
return
}
clearCache() {
this.cachedFrames.forEach((value, key) => value.frame.close());
this.cachedFrames = new Map();
this.nextPriorityRemove = 0;
}
close() {
this.clearCache();
}
}
// Throw when the user wants to do something else and cancel running code
class UsercancelledError extends Error {
constructor(message) {
super(message);
this.name = "UsercancelledError";
}
}
class BlenderpointVideoWorker {
constructor(canvas, config) {
config = config || {};
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
// We color it in all black
this.ctx.fillStyle = "pink";
this.ctx.fill();
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.isLoadingVideo = false;
this.videoWidth = 0;
this.videoHeight = 0;
this.fps = 24;
// This will help requestAnimationFrame
this.currentFrame = 0;
this.timeLastDraw = null;
this.lastDrawnFrame = -1; // helpful to know if we need to redraw the frame or not.
// playbackSpeed is the speed of playing: 0 means that it does not play, 1 it plays at normal speed forward,
// -1 it plays at normal speed backward, 1.5 it plays at speed x1.5…
this.playbackSpeed = 1;
// Contains the ID to the frame to stop at.
this.isPlayingUntil = undefined;
this.isPlayingUntilPrevious = undefined;
this.animationFrameID = null;
// This is used only to know if we are running playAtMaxSpeed that works differently
this.isPlayingMaxSpeed = false;
// we might also call request animation frame if the user wants to display something on screen
// while the video is not yet loaded, use this for that use case.
this.animationFrameIDFetching = null;
this.stops = []; // contains the list of stops
this.jsonComments = {}; // contains the content of the json in the comments of the video
this.alert = (m) => self.postMessage({alert: m});
this.frameLog = (m) => console.log(m);
// This will contain the instance of GetAnyFrame
this.anyFrame = null;
//
this._resetAbortSignal();
// resize canvas when needed
addEventListener("fullscreenchange", async (event) => {
if (!document.fullscreenElement) {
// we are quitting fullscreen mode
this.canvas.width = this.origCanvasWidth;
this.canvas.height = this.origCanvasHeight;
// we redraw the canvas as the canvas is cleared.
this.redrawWhenResolutionChanges();
}
});
// To know the starting frame/date where we started to play (or avoid a frame jump):
this.initTime = null;
this.initialFrame = null;
}
_resetAbortSignal() {
this.abortController = new AbortController();
this.mainAbortSignal = this.abortController.signal;
}
_stopOtherFunctions() {
const error = new UsercancelledError("User performed a new action");
this.abortController.abort(error);
this._resetAbortSignal();
}
_getMainAbortSignal() {
return this.mainAbortSignal;
}
abortIfNeeded(promise, debug) {
return makeMeAbortIfNeeded(promise, this._getMainAbortSignal(), debug);
}
updateAlertFunction (new_alert) {
this.alert = new_alert;
}
isPlaying() {
console.debug(this.animationFrameID);
return this.animationFrameID != null || this.isPlayingMaxSpeed;
}
setFps(fps) {
this.fps = fps;
}
setStops(stops) {
this.stops = stops;
}
getStops() {
return this.stops;
}
setStopsFromString(stops) {
this.stops = [...new Set(stops.split(",").map(e => parseInt(e)))].sort(function(a, b) {
return a - b;
});
}
// call it like:
// <input type="file" accept="video/mp4" onchange="bpVideo.loadVideoFile(this.files[0])">
// config might contain additional parameters, notably callbacks
async loadVideoFileFromFile(file, config) {
if (!config) {
config = {};
}
console.debug("File", file);
let videoObjectURL = URL.createObjectURL(file);
console.debug("url", videoObjectURL);
await this.abortIfNeeded(this.loadVideoFileFromObjectURL(videoObjectURL, config), "In loadVideoFileFromFile");
URL.revokeObjectURL(file); // revoke URL to prevent memory leak
}
// You can pass both object url, or normal url like https://leo-colisson.github.io/blenderpoint-web/Demo_24fps.mp4
async loadVideoFileFromObjectURL(videoObjectURL, userConfig) {
if (!userConfig) {
userConfig = {};
}
// turn to true when the stops are obtained
this.isReady = false;
// If we do not add bind(this), then this will refer to something else
userConfig._onFinishDemuxer = this._onFinishDemuxer.bind(this);
userConfig._onConfig = this._onConfig.bind(this);
this._ensureStoppedAnimationFrame();
this.currentFrame = 0;
this.lastDrawnFrame = -1;
// direction useful to play backward.
this.playbackSpeed = 1;
this.isLoadingVideo = true;
console.debug(videoObjectURL);
if (this.anyFrame) {
this.anyFrame.close();
}
this.userConfig = userConfig;
this.userConfig._getMainAbortSignal = this._getMainAbortSignal.bind(this);
this.anyFrame = new GetAnyFrame(videoObjectURL, userConfig);
}
_onConfig(config) {
// this.mp4boxFile = config.mp4boxFile;
const jsonComments = this._extractJsonFromVideo(config.mp4boxFile);
if (jsonComments) {
try {
this.jsonComments = JSON.parse(jsonComments);
console.debug("The video contains the following json: ", this.jsonComments);
console.debug("userjson", this.userConfig);
if (this.userConfig.stops) {
if (typeof this.userConfig.stops === 'string' || this.userConfig.stops instanceof String) {
this.setStopsFromString(this.userConfig.stops);
} else {
this.setStops(this.userConfig.stops);
}
console.debug("We got from the configuration the following list of stops:", this.stops);
} else {
if (this.jsonComments.stops) {
this.stops = this.jsonComments.stops;
} else {
this.alert("The metadata contains no information about stops: " + jsonComments)
console.debug(this.jsonComments);
}
}
} catch (e) {
console.error("Error: could not load the json due to a syntax error " + jsonComments, e);
this.alert("Error: could not load the json due to a syntax error" + jsonComments);
}
} else {
this.alert("No json in the video, you need to load it manually.");
}
console.log("The configuration is done");
// this.isReady = true;
}
// extracts the json from the video
// must be in a meta field like comment, and enclosed between BLENDERPOINTSTART and BLENDERPOINTSTOP
_extractJsonFromVideo(mp4boxFile) {
const metaBoxes = mp4boxFile.getBoxes("meta");
const decoder = new TextDecoder('utf-8');
var content = null;
metaBoxes.forEach((metaBox) => {
var str = decoder.decode(metaBox.data);
// https://stackoverflow.com/questions/1979884/how-to-use-javascript-regex-over-multiple-lines
// [\s\S] is for empty lines, *? is for the non-greedy search
const matches = [...str.matchAll(/BLENDERPOINTSTART([\s\S]*?)BLENDERPOINTSTOP/g)];
if (matches.length > 0) {
content = matches[0][1];
}
});
return content;
}
async _onFinishDemuxer() {
this.isReady = true;
// We draw the first frame
console.debug("Foo");
await this.abortIfNeeded(wait(0), "onFinishDemuxer"); // This is needed or the decoder will not get the time to run
await this.abortIfNeeded(this.gotoFrame(0), "eianlpés");
}
_ensureStoppedAnimationFrameFetching() {
if (this.animationFrameIDFetching) {
cancelAnimationFrame(this.animationFrameIDFetching)
this.animationFrameIDFetching = null;
}
}
// Basically all animations should start and stop with this._ensureStoppedAnimationFrame()
_ensureStoppedAnimationFrame() {
this.isPlayingUntil = undefined;
this.isPlayingUntilPrevious = undefined;
this._ensureStoppedAnimationFrameFetching();
if (this.animationFrameID) {
cancelAnimationFrame(this.animationFrameID)
this.animationFrameID = null;
}
}
// Draw a frame on the canvas.
// warning: for this to work, make sure to put it into an animationFrame or to call waitRedraw
_drawFrame(frame) {
// fit in the canvas while preserving the proportions
const aspectRatioCanvas = this.canvas.width/this.canvas.height;
const aspectRatioFrame = this.anyFrame.getVideoWidth()/this.anyFrame.getVideoHeight();
var w;
var h;
if (aspectRatioFrame >= aspectRatioCanvas) {
// maximum width
w = this.canvas.width;
h = w/aspectRatioFrame;
} else {
// maximum height
h = this.canvas.height;
w = h*aspectRatioFrame;
}
// fill the canvas with black
this.ctx.fillStyle = "black";
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// console.debug("I will draw the frame", frame);
this.ctx.drawImage(frame, this.canvas.width/2-w/2, this.canvas.height/2-h/2, w, h);
}
// like _drawFrame but takes as argument the index of the frame, and loops with requestAnimationFrame
// until the frame is loaded if the file is not yet ready to use.
async _drawFrameFromIndex(i, backward, forceInRange) {
console.debug("_drawFrameFromIndex", i);
this._ensureStoppedAnimationFrameFetching();
if(forceInRange) {
if (i < 0) {
i = 0;
}
if (i >= this.anyFrame.getNumberOfFramesIfPossible()) {
i = this.anyFrame.getNumberOfFramesIfPossible() - 1;
}
}
const frame = await this.abortIfNeeded(this.anyFrame.getFrame(i, backward), "tnrstn");
if (frame) {
this._drawFrame(frame);
this.currentFrame = i;
this.lastDrawnFrame = i;
this._ensureStoppedAnimationFrameFetching();
return true;
} else {
return false;
}
}
async _gotoFrame(i) {
console.debug("goto",i);
this._ensureStoppedAnimationFrame();
await this.abortIfNeeded(this._drawFrameFromIndex(i, undefined, true), "eiauyd");
// triggers a refresh
await this.abortIfNeeded(this.waitRedraw(), "nelelel");
this._ensureStoppedAnimationFrame();
}
async gotoFrame(i) {
// Make sure to stop existing functions
this._stopOtherFunctions();
await this.abortIfNeeded(this._gotoFrame(i), "rrststst");
}
async gotoPage(i) {
this._stopOtherFunctions();
const pages = [...new Set([...this.stops, 0, Infinity])];
if (i >= pages.length) {
await this.abortIfNeeded(this._gotoFrame(Infinity), "foofoo");
} else {
await this.abortIfNeeded(this._gotoFrame(pages[i]), "foo eianrst");
}
}
getCurrentPage() {
const pages = [...new Set([...this.stops, 0, Infinity])];
return pages.filter(e => e <= this.currentFrame).reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);
}
getCurrentFrame() {
return this.currentFrame;
}
getNumberOfFramesIfPossible() {
const n = this.anyFrame.getNumberOfFramesIfPossible();
if (!typeof n === "number") {
return n;
} else if (this.jsonComments?.finalVideo?.length) {
return this.jsonComments?.finalVideo?.length;
} else {
return null
}
}
getNumberOfPages() {
const nbFrames = this.getNumberOfFramesIfPossible();
if (nbFrames) {
return [...new Set([...this.stops, 0, nbFrames-1])].length;
} else {
return [...new Set([...this.stops, 0])].length;
}
}
// call "await this.waitRedraw()" to wait for animationFrame to
waitRedraw() {
return new Promise(resolve => {
this.animationFrameID = requestAnimationFrame(() => {resolve()});
});
}
// play at the max FPS allowed by the screen refresh rate.
async playAtMaxSpeed() {
this._stopOtherFunctions();
// Needed to allow stopping via the toggle play button
this.isPlayingMaxSpeed = true;
await this.abortIfNeeded(this._playAtMaxSpeed(), "einarstei");
}
// play at the max FPS allowed by the screen refresh rate.
async _playAtMaxSpeed() {
console.debug("Playing max speed", this.isPlayingMaxSpeed);
if (!this.isPlayingMaxSpeed) {
console.debug("Finished to draw, stopped by user.");
this._ensureStoppedAnimationFrame();
return;
}
const nextFrame = this.currentFrame + 1;
const notTheLastOne = await this.abortIfNeeded(this._drawFrameFromIndex(nextFrame), "xxxxxx");
if(notTheLastOne) {
await this.abortIfNeeded(this.waitRedraw(), "wreiastr");
await this.abortIfNeeded(this._playAtMaxSpeed(), "eiuarnst");
}
else {
this.isPlayingMaxSpeed = false;
console.debug("Finished to draw");
this._ensureStoppedAnimationFrame();
}
}
// frame is optional, return the next stop. It might return Infinity if there is none
getNextStop(frame) {
const initialFrame = frame || this.currentFrame;
console.debug(this.stops);
console.debug(initialFrame)
const st = this.stops.filter(e => e > initialFrame);
if (st.length == 0) {
return Infinity
} else {
return Math.min(...st);
}
}
// frame is optional
getPreviousStop(frame) {
const initialFrame = frame || this.currentFrame;
const st = this.stops.filter(e => e < initialFrame);
return Math.max(0, ...st);
}
// nextstop is optional, it will be automatially computed if needed. Set to Infinity if you want to play until the end.
async playUntilNextStop(stop) {
console.debug("I am starting playUntilNextStop");
this._stopOtherFunctions();
// If we click while playing, we jump to the stop directly:
console.debug("called playuntil");
if (!this.isReady) {
console.debug("The file is not yet ready, wait a bit more.");
return
}
if (this.isPlayingUntil != undefined) {
console.debug("I am playing until");