-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_memory_inneficient.html
773 lines (719 loc) · 31.5 KB
/
index_memory_inneficient.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blenderpoint web reader</title>
</head>
<body>
<h1>Blenderpoint web video reader</h1>
<canvas id="canvasEl" width="700px" height="500px"></canvas>
<br>
<input type="file" accept="video/mp4" onchange="start(this.files[0])"/>
<button type="button" onclick="bpVideo.togglePlayPause()">Play/Pause</button>
<button type="button" onclick="bpVideo.setCanvasFullScreen()">Fullscreen</button>
<button type="button" onclick="bpVideo.gotoPreviousStop()">Previous Stop</button>
<button type="button" onclick="bpVideo.playUntilPreviousStop()">Previous Stop (continuous)</button>
<button type="button" onclick="bpVideo.playUntilNextStop()">Next Stop (continuous)</button>
<button type="button" onclick="bpVideo.gotoFrame(0)">Restart</button>
<button type="button" onclick="bpVideo.playAtMaxSpeed()">Play at max speed</button>
<p>To load the demo, click <a href="index_memory_inneficient.html?video=https://leo-colisson.github.io/blenderpoint-web/Demo_24fps.mp4">here</a>.</p>
<h2>Shortcuts</h2>
<ul>
<li><code>Arrow keys</code> or left/right click on the canvas: next/previous stop (continous: double press if you do not want to play the full animation)</li>
<li><code>p</code>: play/pause without stopping</li>
<li><code>n</code>: go to the next frame</li>
<li><code>b</code>: go to the previous frame (b = backward)</li>
<li><code>Home</code>: go to first frame</li>
<li><code>End</code>: go to last frame</li>
<li><code>F</code>: enable full screen (quit with Esc)</li>
<li><code>f</code>: go to a specific frame</li>
<li><code>g</code>: go to a specific page</li>
<li><code>l</code>: print information on the current frame in the console (<code>F12 > console</code>)</li>
<li><code>a</code>: add current frame to stops, and print the list of stops in the console (<code>F12 > console</code>)</li>
<li><code>r</code>: remove current frame from stops</li>
<li><code>S</code>: manually specify the list of stops</li>
</ul>
<h2>Documentation</h2>
<p>This plays a video and stops at specific fixed frames called "stops" (WARNING: this is still not stable, notably playing videos longer than around 1mn will crash the tab as we load all frames in memory, the reason being that browser cannot easily go to a precise frame with the default mechanism). To specify the stops (that you can obtain by using the <code>a</code> and <code>r</code> keys, cf documentation above), you can either press the <code>S</code> key, or add in the comments of the video something like this (In VLC you can see and edit the comments of a video via <code>Tools > Media information</code> or <code>Ctrl-I</code>):</p>
<code>
<pre>
BLENDERPOINTSTART
{"stops": [1,5,10]}
BLENDERPOINTSTOP</pre>
</code>
<p>This format allows more advanced options, for instance to provide information on the original position of a frame in a clip that will be documented later.</p>
<p>You can also load videos from an url: just add the (url encoded) url into the url of this page:
<code>
<pre>
https://leo-colisson.github.io/blenderpoint-web/?video=https://leo-colisson.github.io/blenderpoint-web/Demo_24fps.mp4</pre>
</code>
You can also specify the stops in the url directly if your video does not have it encoded:
<code>
<pre>
https://leo-colisson.github.io/blenderpoint-web/?video=https://leo-colisson.github.io/blenderpoint-web/Demo_24fps.mp4&stops=10,20,50</pre>
</code>
</p>
<h2>TODO and known bugs</h2>
<ul>
<li>Fix issue with large videos consuming all memory</li>
<li>Print a small icon when playing</li>
<li>Make nicer GUI</li>
<li>Document the JSON format</li>
</ul>
<script type="module">
// https://github.com/w3c/webcodecs/issues/87
// Terminology:
// track sample = frames (from https://github.com/gpac/mp4box.js: nb_samples: Number, giving the number of track samples (i.e. frames),)
// onSamples: every time mp4box reads 1000 frames, it sends it to onSamples. Each frame has its own position, whether it is a key frame or a delta frame (.is_sync), a duration (make sure to devide by timescale to get the right thing)
// random access point (rap): insert key frames at random points in the video https://aws.amazon.com/fr/blogs/media/part-1-back-to-basics-gops-explained/
// Example with web worker and really quick animation (it drops frame if not ready to display)
// https://github.com/w3c/webcodecs/blob/main/samples/video-decode-display/index.html
// https://github.com/josephrocca/getVideoFrames.js
// https://stackoverflow.com/questions/32699721/javascript-extract-video-frames-reliably
/* import getVideoFrames from "https://deno.land/x/[email protected]/mod.js" */
// must be served from https or localhost, in a nix-shell -p simple-http-server
import getVideoFrames from "./getVideoFrames.js/mod.js"
class BlenderpointVideo {
constructor(canvas, config) {
config = config || {};
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.isLoadingVideo = false;
// `frames` is a list of VideoFrame object: https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame
this.frames = [];
this.total_nb_frames = 0; // this might not even be set if the video is not fully loaded.
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;
this.isPlayingUntil = undefined;
this.isPlayingUntilPrevious = undefined;
this.animationFrameID = null;
// 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) => alert(m);
this.frameLog = (m) => console.log(m);
// add shorcuts
this.attributeKeyboardAndMouseShortcuts(config.keyboardShortcuts);
// 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();
}
});
}
updateAlertFunction (new_alert) {
this.alert = new_alert;
}
// 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;
}
isPlaying() {
console.log(this.animationFrameID);
return this.animationFrameID != null;
}
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.log("File", file);
let videoObjectURL = URL.createObjectURL(file);
console.log("url", videoObjectURL);
await this.loadVideoFileFromObjectURL(videoObjectURL, config);
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, config) {
if (!config) {
config = {};
}
// turn to true when the stops are obtained
this.isReady = false;
this._ensureStoppedAnimationFrame();
// We don’t know yet the number of frames
this.total_nb_frames = 0;
this.frames.forEach((frame) => frame.close());
this.frames = [];
this.currentFrame = 0;
this.lastDrawnFrame = -1;
// direction useful to play backward.
this.playbackSpeed = 1;
this.isLoadingVideo = true;
console.log(videoObjectURL);
self = this; // otherwise self is replaced with a new self value
await getVideoFrames({
videoUrl: videoObjectURL,
onFrame(frame) {
self.frames.push(frame);
// we print the first frame on screen
if (self.frames.length == 1) {
self._drawFrameFromIndex(0);
}
if (config.onFrame) {
config.onFrame(frame, self.frames.length);
}
},
onConfig(conf) {
self.videoWidth = conf.codedWidth;
self.videoHeight = conf.codedHeight;
if (config.onConfig) {
config.onConfig();
}
console.log(conf.mp4boxFile);
console.log(conf.info);
const fps = conf.info.videoTracks[0].nb_samples / (conf.info.videoTracks[0].samples_duration / conf.info.videoTracks[0].timescale);
console.log("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;
}
// self.mp4boxFile = conf.mp4boxFile;
const jsonComments = self.extractJsonFromVideo(conf.mp4boxFile);
if (jsonComments) {
try {
self.jsonComments = JSON.parse(jsonComments);
console.log("The video contains the following json: ", self.jsonComments)
if (config.stops) {
if (typeof config.stops === 'string' || config.stops instanceof String) {
self.setStopsFromString(config.stops);
} else {
self.setStops(config.stops);
}
console.log("We got from the configuration the following list of stops:", self.stops);
} else {
if (self.jsonComments.stops) {
self.stops = self.jsonComments.stops;
} else {
self.alert("The metadata contains no information about stops: " + jsonComments)
console.log(self.jsonComments);
}
}
} catch (e) {
console.log("Error: could not load the json due to a syntax error " + jsonComments, e);
self.alert("Error: could not load the json due to a syntax error" + jsonComments);
}
} else {
self.alert("No json in the video, you need to load it manually.");
}
self.isReady = true;
},
onFinish() {
console.log("Video loaded.");
self.isLoadingVideo = false;
self.total_nb_frames = self.frames.length;
if (config.onFinish) {
config.onFinish();
}
},
});
}
_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.videoWidth/this.videoHeight;
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);
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, silentError) {
this._ensureStoppedAnimationFrameFetching();
if (i < this.frames.length) {
this._drawFrame(this.frames[i]);
this.currentFrame = i;
this.lastDrawnFrame = i;
this._ensureStoppedAnimationFrameFetching();
return true;
} else if (this.isLoadingVideo) {
return await new Promise(resolve => {
this.animationFrameIDFetching = requestAnimationFrame(async () => {return await this._drawFrameFromIndex(i, silentError); resolve()});
});
} else if (i = Infinity) {
return await this._drawFrameFromIndex(this.frames.length-1, silentError);
} else {
if(!silentError){
const str = `Error: Unreachable frame (frame ${i} bigger than ${this.frames.length}).`;
this.alert(str);
console.log(str);
throw new Error(str);
}
return false;
}
}
async gotoFrame(i) {
console.log("goto",i);
this._ensureStoppedAnimationFrame();
await this._drawFrameFromIndex(i);
// triggers a refresh
await this.waitRedraw();
this._ensureStoppedAnimationFrame();
}
async gotoPage(i) {
const pages = [...new Set([...this.stops, 0, Infinity])];
if (i >= pages.length) {
await this.gotoFrame(Infinity)
} else {
await this.gotoFrame(pages[i])
}
}
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);
}
getNumberOfFramesIfPossible() {
if (!this.isLoadingVideo) {
return this.frames.length;
} 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;
}
}
async gotoPageGUI(i) {
const nbPages = this.getNumberOfPages();
const answer = prompt("To which page do you want to go? (currently " + this.getCurrentPage() + "/" + nbPages + ")");
if (answer) {
this.gotoPage(parseInt(answer));
}
}
async gotoFrameGUI(i) {
const nbFrames = this.getNumberOfFramesIfPossible();
const answer = prompt("To which frame do you want to go? (currently " + this.currentFrame + "/" + nbFrames + ")");
if (answer) {
this.gotoFrame(parseInt(answer));
}
}
async specifyStopsGui(i) {
const answer = prompt("Provide the list of stops to use (e.g. '1, 2, 3').");
if (answer) {
this.stops = [...new Set(answer.split(",").map(e => parseInt(e)))].sort(function(a, b) {
return a - b;
});
}
}
// 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() {
const nextFrame = this.currentFrame + 1;
const notTheLastOne = await this._drawFrameFromIndex(nextFrame, true);
if(notTheLastOne) {
await this.waitRedraw();
this.playAtMaxSpeed();
}
else {
console.log("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.log(this.stops);
console.log(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) {
// If we click while playing, we jump to the stop directly:
console.log("called playuntil");
if (!this.isReady) {
console.log("The file is not yet ready, wait a bit more.");
return
}
if (this.isPlayingUntil != undefined) {
console.log("I am playing until");
await this.gotoFrame(this.isPlayingUntil);
return
}
if (this.isPlayingUntilPrevious != undefined) {
console.log("I am playing until previous");
await this.gotoFrame(this.currentFrame);
return
}
console.log("We were apparently not playing");
// We first compute the next stop
const initialFrame = this.currentFrame;
const nextStop = stop || this.getNextStop();
console.log(nextStop, stop);
const initTime = Date.now();
this.isPlayingUntil = nextStop;
const playAux = async () => {
const deltaTime = (Date.now() - initTime)/1000;
const frameToDisplay = Math.min(Math.round(deltaTime * this.fps * this.playbackSpeed) + initialFrame, nextStop);
const notTheLastOne = await this._drawFrameFromIndex(frameToDisplay, true);
if(notTheLastOne && frameToDisplay < nextStop) {
await this.waitRedraw();
await playAux();
}
else {
console.log("stop");
this.isPlayingUntil = undefined;
this._ensureStoppedAnimationFrame();
}
}
await playAux();
}
// nextstop is optional, it will be automatially computed if needed. Set to Infinity if you want to play until the end.
async playUntilPreviousStop(stop) {
if (!this.isReady) {
console.log("The file is not yet ready, wait a bit more.");
return
}
// If we click while playing, we jump to the stop directly:
console.log("called playuntilprevious");
if (this.isPlayingUntilPrevious != undefined) {
await this.gotoFrame(this.isPlayingUntilPrevious);
return
}
// if we were playing forward, we stop here
if (this.isPlayingUntil != undefined) {
await this.gotoFrame(this.currentFrame);
return
}
// First stop the play
this._ensureStoppedAnimationFrame()
// We first compute the next stop
const initialFrame = this.currentFrame;
const nextStop = stop || this.getPreviousStop();
console.log("Will play until ", nextStop);
const initTime = Date.now();
console.log(nextStop);
this.isPlayingUntilPrevious = nextStop;
const playAux = async () => {
const deltaTime = (Date.now() - initTime)/1000;
const frameToDisplay = Math.max(-Math.round(deltaTime * this.fps * this.playbackSpeed) + initialFrame, nextStop);
const notTheLastOne = await this._drawFrameFromIndex(frameToDisplay, true);
if(notTheLastOne && frameToDisplay > nextStop) {
await this.waitRedraw();
await playAux();
}
else {
console.log("stop");
this.isPlayingUntilPrevious = undefined;
this._ensureStoppedAnimationFrame();
}
}
await playAux();
}
// stop is optional, it will be automatially computed
async gotoPreviousStop(stop) {
if (!this.isReady) {
console.log("The file is not yet ready, wait a bit more.");
return
}
// First stop the play
this._ensureStoppedAnimationFrame();
const previousStop = stop || this.getPreviousStop();
return await this.gotoFrame(previousStop);
}
async gotoPreviousFrame() {
await this.gotoFrame(this.currentFrame - 1)
}
async gotoNextFrame() {
await this.gotoFrame(this.currentFrame + 1)
}
async pause() {
this._ensureStoppedAnimationFrame();
}
async togglePlayPause() {
if (this.isPlaying()) {
this._ensureStoppedAnimationFrame();
} else {
this.playUntilNextStop(Infinity)
}
}
async setCanvasFullScreen() {
/* When the openFullscreen() function is executed, open the video in fullscreen.
Note that we must include prefixes for different browsers, as they don't support the requestFullscreen method yet */
this.origCanvasWidth = this.canvas.width;
this.origCanvasHeight = this.canvas.height;
if (this.canvas.requestFullscreen) {
await this.canvas.requestFullscreen({navigationUI: "hide"});
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
} else {
this.alert("Fullscreen not supported on your browser? Try a more recent browser.");
}
// we redraw the canvas as the canvas is cleared.
this.redrawWhenResolutionChanges()
}
async redrawWhenResolutionChanges() {
if (!this.isPlaying()) { // No need to draw if it’s already playing
await this._drawFrameFromIndex(this.currentFrame);
await this.waitRedraw();
this._ensureStoppedAnimationFrame(); // otherwise it thinks that it is still playing.
console.log("we are not playing")
} else {
console.log("we are playing")
}
}
close() {
this.frames.forEach(frame => {
frame.close();
});
}
getInfoOnFrame(frame) {
var data = {frame: frame};
if (this.jsonComments.clipsIndex) {
for (var clip of this.jsonComments.clipsIndex) {
const relativeFrame = frame - clip.absoluteStart;
if (relativeFrame >= 0 && relativeFrame < clip.length) {
data.clipFilename = clip.filename;
data.clipAbsoluteStart = clip.absoluteStart
data.frameFinalPositionFromStartClip = relativeFrame;
if (clip.frameFinalToOriginal) {
// frame number in the original clip
data.originalLocalFrame = clip.frameFinalToOriginal[relativeFrame];
}
return data
}
}
}
return data;
}
logFrame(frame) {
var info = this.getInfoOnFrame(frame);
var message = "The final frame number is " + info.frame;
if (info.clipAbsoluteStart) {
message += " (= clip starting at frame " + info.clipAbsoluteStart + " + " + info.frameFinalPositionFromStartClip + " frames)";
}
if (info.clipFilename) {
message += ", extracted from the clip " + info.clipFilename;
}
if (info.originalLocalFrame) {
message += " at original position " + info.originalLocalFrame;
}
this.frameLog(message);
}
attributeKeyboardAndMouseShortcuts(config) {
var config = config || {};
var elt = config.bindToDocument ? document : this.canvas;
// https://developer.mozilla.org/en-US/play
// https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
this.canvas.addEventListener('click', (e) => {
this.playUntilNextStop();
});
// right click
this.canvas.addEventListener('contextmenu', (e) => {
e.preventDefault();
this.playUntilPreviousStop();
return false;
}, false);
// otherwise keybords shortcut will not work
// https://stackoverflow.com/questions/12886286/addeventlistener-for-keydown-on-canvas
this.canvas.tabIndex = 1;
elt.addEventListener('keyup', (e) => {
console.log("Key is up:", e.key);
switch (e.key) {
case "ArrowRight":
case "ArrowDown":
case "PageDown":
case " ":
case "Enter":
this.playUntilNextStop()
break;
case "ArrowUp":
case "ArrowLeft":
case "PageUp":
this.playUntilPreviousStop()
break;
// p is for "play/pause"
case "p":
this.togglePlayPause()
break;
// n is for "next frame"
case "n":
this.gotoNextFrame()
break;
// b is for "next frame but Backward"
case "b":
this.gotoPreviousFrame();
break;
case "Home":
this.gotoFrame(0);
break;
case "End":
this.gotoFrame(Infinity);
break;
// "F" for "FFFull screen!!" (note the upper case, lower case is to go to a frame)
case "F":
this.setCanvasFullScreen(); // todo: quit if press twice
break;
// f is for "goto a specific frame"
case "f":
this.gotoFrameGUI();
break;
// g is for "goto a specific page"
case "g":
this.gotoPageGUI()
break;
// l is for "log info about the current frame"
case "l":
this.logFrame(this.currentFrame);
break;
// a for "add current frame to stops"
case "a":
this.stops = [...new Set([...this.stops, this.currentFrame])].sort(function(a, b) {
return a - b;
});
console.log(this.stops);
break;
// r for "remove current frame to stops"
case "r":
this.stops = this.stops.filter(x => x !== this.currentFrame)
console.log(this.stops);
break;
// s for "search based on name of the frame"
// TODO: implement
case "s":
break;
// specify stops
case "S":
this.specifyStopsGui();
break;
}
});
}
}
window.bpVideo = new BlenderpointVideo(document.getElementById("canvasEl"), {
keyboardShortcuts: {
bindToDocument: true
}
});
window.start = async function(file) {
console.log("Loading video");
console.log(window.bpVideo);
window.bpVideo.loadVideoFileFromFile(file);
/* window.bpVideo.setStops([0,25,50,100]); */
}
document.addEventListener('DOMContentLoaded', async () => {
// Check if supported
if (typeof VideoDecoder == "undefined") {
alert("It seems like you cannot use WebCodecs which are needed by this library. While Chrome supports this feature, Firefox lacks it: https://https://caniuse.com/webcodecs. If your browser supports it, make sure that you load this page from an https page or a localhost server as WebCodecs need a secure context.")
}
// we try to find a video in the url
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const video = urlParams.get('video');
const stops = urlParams.get('stops');
if (video) {
console.log("We will load ", video);
await window.bpVideo.loadVideoFileFromObjectURL(decodeURI(video), {
stops: stops
});
/* if (stops) {
* window.bpVideo.setStopsFromString(stops);
* console.log("stops configured from url: ", window.bpVideo.getStops());
* } */
}
}, false);
</script>
<!-- <script src="https://cdn.jsdelivr.net/npm/eruda"></script>
<script>
eruda.init();
</script> -->
</body>
</html>