-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvideocompositor.js
2738 lines (2468 loc) · 123 KB
/
videocompositor.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
var VideoCompositor =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
//Matthew Shotton, R&D User Experince,© BBC 2015
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; })();
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _sourcesVideosourceJs = __webpack_require__(1);
var _sourcesVideosourceJs2 = _interopRequireDefault(_sourcesVideosourceJs);
var _sourcesImagesourceJs = __webpack_require__(3);
var _sourcesImagesourceJs2 = _interopRequireDefault(_sourcesImagesourceJs);
var _sourcesCanvassourceJs = __webpack_require__(4);
var _sourcesCanvassourceJs2 = _interopRequireDefault(_sourcesCanvassourceJs);
var _effectmanagerJs = __webpack_require__(5);
var _effectmanagerJs2 = _interopRequireDefault(_effectmanagerJs);
var _audiomanagerJs = __webpack_require__(7);
var _audiomanagerJs2 = _interopRequireDefault(_audiomanagerJs);
var updateables = [];
var previousTime = undefined;
var mediaSourceMapping = new Map();
mediaSourceMapping.set("video", _sourcesVideosourceJs2["default"]).set("image", _sourcesImagesourceJs2["default"]).set("canvas", _sourcesCanvassourceJs2["default"]);
function registerUpdateable(updateable) {
updateables.push(updateable);
}
function update(time) {
if (previousTime === undefined) previousTime = time;
var dt = (time - previousTime) / 1000;
for (var i = 0; i < updateables.length; i++) {
updateables[i]._update(dt);
}
previousTime = time;
requestAnimationFrame(update);
}
update();
var VideoCompositor = (function () {
/**
* Instantiate the VideoCompositor using the passed canvas to render too.
*
* You can also pass an AudioContext for use when calling getAudioNodeForTrack. If one is not provided a context will be created internally and be accessible via the getAudioContext function.
*
* @param {Canvas} canvas - The canvas element to render too.
* @param {AudioContext} audioCtx - The AudioContext to create AudioNode's with.
*
* @example
*
* var canvas = document.getElementById('canvas');
* var audioCtx = new AudioContext();
* var videoCompositor = new VideoCompositor(canvas, audioCtx);
*/
function VideoCompositor(canvas, audioCtx) {
_classCallCheck(this, VideoCompositor);
this._canvas = canvas;
this._ctx = this._canvas.getContext("experimental-webgl", { preserveDrawingBuffer: true, alpha: false });
this._playing = false;
this._mediaSources = new Map();
//this._mediaSourcePreloadNumber = 4; // define how many mediaSources to preload. This is influenced by the number of simultaneous AJAX requests available.
this._mediaSourcePreloadLookaheadTime = 10; // define how far into the future to load mediasources.
this._mediaSourcePostPlayLifetime = 0; // set how long until after a media source has finished playing to keep it around.
this._playlist = undefined;
this._eventMappings = new Map();
this._mediaSourceListeners = new Map();
this._max_number_of_textures = this._ctx.getParameter(this._ctx.MAX_TEXTURE_IMAGE_UNITS);
this._effectManager = new _effectmanagerJs2["default"](this._ctx);
this._audioManger = new _audiomanagerJs2["default"](audioCtx);
this._currentTime = 0;
this._playbackRate = 1.0;
this.duration = 0;
registerUpdateable(this);
}
/**
* Sets how far in the future to look for preloading mediasources.
*/
_createClass(VideoCompositor, [{
key: "play",
/**
* Play the playlist. If a pause() has been called previously playback will resume from that point.
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
* videoCompositor.play();
*/
value: function play() {
this._playing = true;
this._ctx.clearColor(0.0, 0.0, 0.0, 1.0);
this._ctx.clear(this._ctx.COLOR_BUFFER_BIT | this._ctx.DEPTH_BUFFER_BIT);
var playEvent = new CustomEvent('play', { detail: { data: this._currentTime, instance: this } });
this._canvas.dispatchEvent(playEvent);
}
/**
* Pause playback of the playlist. Call play() to resume playing.
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
* videoCompositor.play();
*
* setTimeout(videoCompositor.pause, 3000); //pause after 3 seconds
*
*/
}, {
key: "pause",
value: function pause() {
this._playing = false;
this._mediaSources.forEach(function (mediaSource) {
mediaSource.pause();
});
var pauseEvent = new CustomEvent('pause', { detail: { data: this._currentTime, instance: this } });
this._canvas.dispatchEvent(pauseEvent);
}
/**
* This adds event listeners to the video compositor. Events directed at the underlying canvas are transparently
* passed through, While events that target a video like element are handled within the VideoCompositor. Currently
* the VideoCompositor only handles a limited number of video like events ("play", "pause", "ended").
*
* @param {String} type - The type of event to listen to.
* @param {Function} func - The Function to be called for the given event.
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
*
* videoCompositor.addEventListener("play", function(){console.log("Started playing")});
* videoCompositor.addEventListener("pause", function(){console.log("Paused")});
* videoCompositor.addEventListener("ended", function(){console.log("Finished playing")});
*
* videoCompositor.play();
*
*
*/
}, {
key: "addEventListener",
value: function addEventListener(type, func) {
//Pass through any event listeners through to the underlying canvas rendering element
//Catch any events and handle with a custom events dispatcher so things
if (this._eventMappings.has(type)) {
this._eventMappings.get(type).push(func);
} else {
this._eventMappings.set(type, [func]);
}
this._canvas.addEventListener(type, this._dispatchEvents, false);
}
/**
* This removes event listeners from the video compositor that were added using addEventListener.
*
* @param {String} type - The type of event to remove.
* @param {Function} func - The Function to be removed for the given event.
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
*
* var playingCallback = function(){console.log("playing");};
* videoCompositor.addEventListener("play", playingCallback);
*
* videoCompositor.play();
*
* videoCompositor.removeEventListener("play", playingCallback);
*
*/
}, {
key: "removeEventListener",
value: function removeEventListener(type, func) {
if (this._eventMappings.has(type)) {
var listenerArray = this._eventMappings.get(type);
var listenerIndex = listenerArray.indexOf(func);
if (listenerIndex !== -1) {
listenerArray.splice(listenerIndex, 1);
return true;
}
}
return false;
}
/**
* This method allows you to create a listeners for events on a specific MediaSource.
*
* To use this you must pass an object which has one or more the following function properties: play, pause, seek,
* isReady, load, destroy, render.
*
* These functions get called when the correspoinding action on the MediaSource happen. In the case of the render
* listener it will be called every time a frame is drawn so the function should aim to return as quickly as possible
* to avoid hanging the render loop.
*
* The use-case for this is synchronising external actions to a specfic media source, such as subtitle rendering or
* animations on a canvasMediaSource.
*
* The listeners get passed a reference to the internal MediaSource object and somtimes extra data relevant to that
* sepcific actions function ("seek" gets the time seeking too, "render" gets the shaders rendering parameters).
*
* @param {String} mediaSourceID - The id of the MediaSource to listen to.
* @param {Object} mediaSourceListener - An Object implementing listener functions.
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
*
* var videoListener = {
* render: function(mediaSource, renderParameters){
* //This will get called every frame.
* var time = renderParameters.progress * mediaSource.duration;
* console.log('Progress through ID', mediaSource.id, ':', time);
* },
* seek:function(mediaSource, seekTime){
* //This function will get called on seek
* console.log("Seeking ID", mediaSource.id, "to :", seekTime);
* },
* play:function(mediaSource){
* //This function will get called on play
* console.log("Plating ID", mediaSource.id);
* },
* }
*
* videoCompositor.registerMediaSourceListener("video1", videoListener);
* videoCompositor.play();
*
*/
}, {
key: "registerMediaSourceListener",
value: function registerMediaSourceListener(mediaSourceID, mediaSourceListener) {
if (this._mediaSourceListeners.has(mediaSourceID)) {
this._mediaSourceListeners.get(mediaSourceID).push(mediaSourceListener);
} else {
this._mediaSourceListeners.set(mediaSourceID, [mediaSourceListener]);
}
}
/**
* This method allows you to remove a listener from a specific MediaSource.
*
* To use this you must pass in an object which has already been registered using registerMediaSourceListener,
* @param {String} mediaSourceID - The id of the MediaSource to remove the listener from.
* @param {Object} mediaSourceListener - An Object that has been previously passed in via registerMediaSourceListener.
*/
}, {
key: "unregisterMediaSourceListener",
value: function unregisterMediaSourceListener(mediaSourceID, mediaSourceListener) {
if (!this._mediaSourceListeners.has(mediaSourceID)) {
return false;
} else {
var listenerArray = this._mediaSourceListeners.get(mediaSourceID);
var index = listenerArray.indexOf(mediaSourceListener);
if (index > -1) {
listenerArray.splice(index, 1);
}
if (this._mediaSources.has(mediaSourceID)) {
var mediaSourceListnerArray = this._mediaSources.get(mediaSourceID).mediaSourceListeners;
index = mediaSourceListnerArray.indexOf(mediaSourceListener);
if (index > -1) {
mediaSourceListnerArray.splice(index, 1);
}
}
return true;
}
}
/**
* Returns the audio context that was either passed into the constructor or created internally.
* @example <caption>Getting an audio context that was passed in</caption>
* var audioCtx = new AudioContext();
* var videoCompositor = new VideoCompositor(canvas, audioCtx);
*
* var returnedAudioContext = videoCompositor.getAudioContext();
*
* //returnedAudioContext and audiotCtx are the same object.
*
* @example <caption>Getting an AudioContext created internally</caption>
* var videoCompositor = new VideoCompositor(canvas); //Don't pass in an audio context
*
* var audioCtx = videoCompositor.getAudioContext();
* //audioCtx was created inside the VideoCompositor constructor
*
* @return {AudioContext} The audio context used to create any nodes required by calls to getAudioNodeForTrack
*/
}, {
key: "getAudioContext",
value: function getAudioContext() {
return this._audioManger.getAudioContext();
}
/**
* Starts the underlying video/image elements pre-loading. Behavior is not guaranteed and depends on how the browser treats video pre-loading under the hood.
* @example <caption>Start a playlist pre-loading so it starts playing quicker</caption>
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"}]
* ]
* }
* videoCompositor.preload();
* //now when play is called is should start quicker.
*/
}, {
key: "preload",
value: function preload() {
this._playing = true;
this._update(0.0);
this._playing = false;
}
/**
* Gets an audio bus for the given playlist track.
*
* In some instances you may want to feed the audio output of the media sources from a given track into a web audio API context. This function provides a mechanism for acquiring an audio GainNode which represents a "bus" of a given track.
*
* Note: In order for the media sources on a track to play correctly once you have an AudioNode for the track you must connect the Audio Node to the audio contexts destination (even if you want to mute them you must set the gain to 0 then connect them to the output).
* @example <caption>Muting all videos on a single track</caption>
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
*
* var audioCtx = new AudioContext();
* var canvas = document.getElementById("canvas");
* var videoCompositor = new VideoCompositor(canvas, audioCtx);
* videoCompositor.playlist = playlist;
* var trackGainNode = videoCompositor.getAudioNodeForTrack(playlist.tracks[0]);
* trackGainNode.gain.value = 0.0; // Mute the track
*
* @param {Array} track - this is track which consist of an array object of MediaSourceReferences (typically a track from a playlist object).
* @return {GainNode} this is a web audio GainNode which has the output of any audio producing media sources from the passed track played out of it.
*/
}, {
key: "getAudioNodeForTrack",
value: function getAudioNodeForTrack(track) {
var audioNode = this._audioManger.createAudioNodeFromTrack(track);
return audioNode;
}
}, {
key: "_dispatchEvents",
value: function _dispatchEvents(evt) {
//Catch events and pass them on, mangling the detail property so it looks nice in the API
for (var i = 0; i < evt.detail.instance._eventMappings.get(evt.type).length; i++) {
evt.detail.instance._eventMappings.get(evt.type)[i](evt.detail.data);
}
}
}, {
key: "_getPlaylistPlayingStatusAtTime",
value: function _getPlaylistPlayingStatusAtTime(playlist, playhead) {
var toPlay = [];
var currentlyPlaying = [];
var finishedPlaying = [];
//itterate tracks
for (var i = 0; i < playlist.tracks.length; i++) {
var track = playlist.tracks[i];
for (var j = 0; j < track.length; j++) {
var segment = track[j];
var segmentEnd = segment.start + segment.duration;
if (playhead > segmentEnd) {
finishedPlaying.push(segment);
continue;
}
if (playhead > segment.start && playhead < segmentEnd) {
currentlyPlaying.push(segment);
continue;
}
if (playhead <= segment.start) {
toPlay.push(segment);
continue;
}
}
}
return [toPlay, currentlyPlaying, finishedPlaying];
}
}, {
key: "_sortMediaSourcesByStartTime",
value: function _sortMediaSourcesByStartTime(mediaSources) {
mediaSources.sort(function (a, b) {
return a.start - b.start;
});
return mediaSources;
}
}, {
key: "_loadMediaSource",
value: function _loadMediaSource(mediaSourceReference, onReadyCallback) {
if (onReadyCallback === undefined) onReadyCallback = function () {};
var mediaSourceListeners = [];
if (this._mediaSourceListeners.has(mediaSourceReference.id)) {
mediaSourceListeners = this._mediaSourceListeners.get(mediaSourceReference.id);
}
var MediaSourceClass = mediaSourceMapping.get(mediaSourceReference.type);
if (MediaSourceClass === undefined) {
throw { "error": 5, "msg": "mediaSourceReference " + mediaSourceReference.id + " has unrecognized type " + mediaSourceReference.type, toString: function toString() {
return this.msg;
} };
}
var mediaSource = new MediaSourceClass(mediaSourceReference, this._ctx);
mediaSource.onready = onReadyCallback;
mediaSource.mediaSourceListeners = mediaSourceListeners;
mediaSource.load();
this._mediaSources.set(mediaSourceReference.id, mediaSource);
}
}, {
key: "_calculateMediaSourcesOverlap",
value: function _calculateMediaSourcesOverlap(mediaSources) {
var maxStart = 0.0;
var minEnd = undefined;
//calculate max start time
for (var i = 0; i < mediaSources.length; i++) {
var mediaSource = mediaSources[i];
if (mediaSource.start > maxStart) {
maxStart = mediaSource.start;
}
var end = mediaSource.start + mediaSource.duration;
if (minEnd === undefined || end < minEnd) {
minEnd = end;
}
}
return [maxStart, minEnd];
}
}, {
key: "_calculateActiveTransitions",
value: function _calculateActiveTransitions(currentlyPlaying, currentTime) {
if (this._playlist === undefined || this._playing === false) return [];
if (this._playlist.transitions === undefined) return [];
//Get the currently playing ID's
var currentlyPlayingIDs = [];
for (var i = 0; i < currentlyPlaying.length; i++) {
currentlyPlayingIDs.push(currentlyPlaying[i].id);
}
var activeTransitions = [];
//Get the transitions whose video sources are currently playing
var transitionKeys = Object.keys(this._playlist.transitions);
for (var i = 0; i < transitionKeys.length; i++) {
var transitionID = transitionKeys[i];
var transition = this._playlist.transitions[transitionID];
var areInputsCurrentlyPlaying = true;
for (var j = 0; j < transition.inputs.length; j++) {
var id = transition.inputs[j];
if (currentlyPlayingIDs.indexOf(id) === -1) {
areInputsCurrentlyPlaying = false;
break;
}
}
if (areInputsCurrentlyPlaying) {
var activeTransition = { transition: transition, transitionID: transitionID, mediaSources: [] };
for (var j = 0; j < transition.inputs.length; j++) {
activeTransition.mediaSources.push(this._mediaSources.get(transition.inputs[j]));
}
activeTransitions.push(activeTransition);
}
}
//Calculate the progress through the transition
for (var i = 0; i < activeTransitions.length; i++) {
var mediaSources = activeTransitions[i].mediaSources;
var _calculateMediaSourcesOverlap2 = this._calculateMediaSourcesOverlap(mediaSources);
var _calculateMediaSourcesOverlap22 = _slicedToArray(_calculateMediaSourcesOverlap2, 2);
var overlapStart = _calculateMediaSourcesOverlap22[0];
var overlapEnd = _calculateMediaSourcesOverlap22[1];
var progress = (currentTime - overlapStart) / (overlapEnd - overlapStart);
activeTransitions[i].progress = progress;
}
return activeTransitions;
}
}, {
key: "_update",
value: function _update(dt) {
if (this._playlist === undefined || this._playing === false) return;
var _getPlaylistPlayingStatusAtTime2 = this._getPlaylistPlayingStatusAtTime(this._playlist, this._currentTime);
var _getPlaylistPlayingStatusAtTime22 = _slicedToArray(_getPlaylistPlayingStatusAtTime2, 3);
var toPlay = _getPlaylistPlayingStatusAtTime22[0];
var currentlyPlaying = _getPlaylistPlayingStatusAtTime22[1];
var finishedPlaying = _getPlaylistPlayingStatusAtTime22[2];
toPlay = this._sortMediaSourcesByStartTime(toPlay);
//Check if we've finished playing and then stop
if (toPlay.length === 0 && currentlyPlaying.length === 0) {
this.pause();
var endedEvent = new CustomEvent('ended', { detail: { data: this.currentTime, instance: this } });
this.currentTime = 0;
this._canvas.dispatchEvent(endedEvent);
return;
}
// //Preload mediaSources
// for (let i = 0; i < this._mediaSourcePreloadNumber; i++) {
// if (i === toPlay.length) break;
// if (this._mediaSources.has(toPlay[i].id) === false){
// this._loadMediaSource(toPlay[i]);
// }
// }
for (var i = 0; i < toPlay.length; i++) {
//if (i === toPlay.length) break;
if (!this._mediaSources.has(toPlay[i].id)) {
if (toPlay[i].start < this._currentTime + this._mediaSourcePreloadLookaheadTime) {
this._loadMediaSource(toPlay[i]);
}
}
}
//Clean-up any mediaSources which have already been played
for (var i = 0; i < finishedPlaying.length; i++) {
var mediaSourceReference = finishedPlaying[i];
if (this._mediaSources.has(mediaSourceReference.id)) {
var mediaSource = this._mediaSources.get(mediaSourceReference.id);
if (mediaSource.start + mediaSource.duration < this._currentTime - this._mediaSourcePostPlayLifetime) {
mediaSource.destroy();
this._mediaSources["delete"](mediaSourceReference.id);
}
}
}
//Make sure all mediaSources are ready to play
var ready = true;
for (var i = 0; i < currentlyPlaying.length; i++) {
var mediaSourceID = currentlyPlaying[i].id;
//check that currently playing mediaSource exists
if (!this._mediaSources.has(mediaSourceID)) {
//if not load it
this._loadMediaSource(currentlyPlaying[i]);
ready = false;
continue;
}
if (!this._mediaSources.get(mediaSourceID).isReady()) ready = false;
}
//if all the sources aren't ready, exit function before rendering or advancing clock.
if (ready === false) {
return;
}
//Update the effects
this._effectManager.updateEffects(this._playlist.effects);
//Update the audio
this._audioManger.update(this._mediaSources, currentlyPlaying);
//Play mediaSources on the currently playing queue.
currentlyPlaying.reverse(); //reverse the currently playing queue so track 0 renders last
//let activeTransitions = this._calculateActiveTransitions(currentlyPlaying, this._currentTime);
this._ctx.viewport(0, 0, this._ctx.canvas.width, this._ctx.canvas.height);
this._ctx.clear(this._ctx.COLOR_BUFFER_BIT | this._ctx.DEPTH_BUFFER_BIT);
for (var i = 0; i < currentlyPlaying.length; i++) {
var mediaSourceID = currentlyPlaying[i].id;
var mediaSource = this._mediaSources.get(mediaSourceID);
//We must update the MediaSource object with any changes made to the MediaSourceReference
//Currently the only parameters we update are start,duration
mediaSource.play();
var progress = (this._currentTime - currentlyPlaying[i].start) / currentlyPlaying[i].duration;
//get the base render parameters
var renderParameters = { "playback_rate": this._playbackRate, "progress": progress, "duration": mediaSource.duration, "source_resolution": [mediaSource.width, mediaSource.height], "output_resolution": [this._canvas.width, this._canvas.height] };
//find the effect associated with the current mediasource
var effect = this._effectManager.getEffectForInputId(mediaSourceID);
//merge the base parameters with any custom ones
for (var key in effect.parameters) {
renderParameters[key] = effect.parameters[key];
}
mediaSource.render(effect.program, renderParameters, effect.textures);
}
this._currentTime += dt * this._playbackRate;
}
/**
* Calculate the duration of the passed playlist track.
*
* Will return the time that the last media source in the track stops playing.
* @param {Array} track - this is track which consists of an array object of MediaSourceReferences (typically a track from a playlist object).
* @return {number} The duration in seconds of the given track.
* @example
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}],
* [{type:"video", start:6, duration:4, src:"video3.mp4", id:"video3"}]
* ]
* }
* var track0Duration = VideoCompositor.calculateTrackDuration(playlist.tracks[0]);
* var track1Duration = VideoCompositor.calculateTrackDuration(playlist.tracks[1]);
* //track0Duration === 8
* //track1Duration === 10
*
* @todo Beacuse media source reference are stored in order this could implemented be far quicker.
*/
}, {
key: "preloadTime",
set: function set(time) {
this._mediaSourcePreloadLookaheadTime = time;
},
get: function get() {
return this._mediaSourcePreloadLookaheadTime;
}
/**
* Sets how long mediasources will exist for after they have been .
*/
}, {
key: "postPlayTime",
set: function set(time) {
this._mediaSourcePostPlayLifetime = time;
},
get: function get() {
return this._mediaSourcePostPlayLifetime;
}
/**
* Sets the playback rate of the video compositor. Msut be greater than 0.
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
* videoCompositor.playbackRate = 2.0; //Play at double speed
* videoCompositor.play();
*/
}, {
key: "playbackRate",
set: function set(playbackRate) {
if (typeof playbackRate === 'string' || playbackRate instanceof String) {
playbackRate = parseFloat(playbackRate);
}
if (playbackRate < 0) playbackRate = 0;
this._playbackRate = playbackRate;
},
/**
* Gets the playback rate.
*
* @example
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* console.log(videoCompositor. playbackRate); // will print 1.0.
*/
get: function get() {
return this._playbackRate;
}
/**
* Sets the current time through the playlist.
*
* Setting this is how you seek through the content. Should be frame accurate, but probably slow.
* @param {number} time - The time to seek to in seconds.
*
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
* videoCompositor.currentTime = 3; //Skip three seconds in.
* videoCompositor.play();
*/
}, {
key: "currentTime",
set: function set(currentTime) {
if (typeof currentTime === 'string' || currentTime instanceof String) {
currentTime = parseFloat(currentTime);
}
console.debug("Seeking to", currentTime);
if (this._playlist === undefined) {
return;
}
var _getPlaylistPlayingStatusAtTime3 = this._getPlaylistPlayingStatusAtTime(this._playlist, currentTime);
var _getPlaylistPlayingStatusAtTime32 = _slicedToArray(_getPlaylistPlayingStatusAtTime3, 3);
var toPlay = _getPlaylistPlayingStatusAtTime32[0];
var currentlyPlaying = _getPlaylistPlayingStatusAtTime32[1];
var finishedPlaying = _getPlaylistPlayingStatusAtTime32[2];
//clean up any nodes in the audioManager
this._audioManger.clearAudioNodeCache();
//clean-up any currently playing mediaSources
var _this = this;
this._mediaSources.forEach(function (mediaSource) {
var shouldDestory = false;
//check if the media source matches one in the new currently playing or list.
for (var i = 0; i < finishedPlaying.length; i++) {
if (mediaSource.id === finishedPlaying[i].id) {
shouldDestory = true;
}
}
//check it the media source has already been played a littlebit
if (mediaSource.playing === true) shouldDestory = true;
if (shouldDestory) {
_this._mediaSources["delete"](mediaSource.id);
mediaSource.destroy();
}
});
//this._mediaSources.clear();
//Load mediaSources
for (var i = 0; i < currentlyPlaying.length; i++) {
var mediaSourceID = currentlyPlaying[i].id;
//If the media source isn't loaded then we start loading it.
if (this._mediaSources.has(mediaSourceID) === false) {
this._loadMediaSource(currentlyPlaying[i], function (mediaSource) {
mediaSource.seek(currentTime);
});
} else {
//If the mediaSource is loaded then we seek to the proper bit
this._mediaSources.get(mediaSourceID).seek(currentTime);
}
}
this._currentTime = currentTime;
var seekEvent = new CustomEvent('seek', { detail: { data: currentTime, instance: this } });
this._canvas.dispatchEvent(seekEvent);
},
/**
* Get how far through the playlist has been played.
*
* Getting this value will give the current playhead position. Can be used for updating timelines.
* @return {number} The time in seconds through the current playlist.
*
* @example
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}]
* ]
* }
* var canvas = document.getElementById('canvas');
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
* var time = videoCompositor.currentTime;
* //time === 0
*/
get: function get() {
return this._currentTime;
}
/**
* Set the playlist object to be played.
*
* Playlist objects describe a sequence of media sources to be played along with effects to be applied to them. They can be modified as they are being played to create dynamic or user customizable content.
*
* At the top level playlist consist of tracks and effects. A track is an array of MediaSourceReferences. MediaSourceReference are an object which describe a piece of media to be played, the three fundamental MediaSourceRefernce types are "video", "image", and "canvas". Internally MediaSoureReferences are used to create MediaSources which are object that contain the underlying HTML element as well as handling loading and rendering of that element ot the output canvas.
*
* The order in which simultaneous individual tracks get rendered is determined by there index in the overall tracks list. A track at index 0 will be rendered after a track at index 1.
*
* Effects are objects consisting of GLSL vertex and fragment shaders, and a list of MediaSource ID's for them to be applied to.
* Effects get applied independently to any MediaSources in their input list.
*
* @param {Object} playlist - The playlist object to be played.
*
* @example <caption>A simple playlist with a single track of a single 4 second video</caption>
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video.mp4", id:"video"}]
* ]
* }
* var canvas = document.getElementById("canvas");
* var videoCompositor = new VideoCompositor(canvas);
* videoCompositor.playlist = playlist;
* videoCompositor.play();
*
* @example <caption>Playing the first 4 seconds of two videos, one after the other</caption>
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video.mp4", id:"video"}, {type:"video", start:4, duration:4, src:"video1.mp4", id:"video1"}]
* ]
* }
*
* @example <caption>Playing a 4 second segment from within a video (not the use of sourceStart)</caption>
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, sourceStart:10, duration:4, src:"video.mp4", id:"video"}]
* ]
* }
*
* @example <caption>A playlist with a 4 second video with a greenscreen effect applied rendered over a background image</caption>
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:10, src:"video.mp4", id:"gs-video"}],
* [{type:"image", start:0, duration:10, src:"background.png", id:"background"}]
* ]
* effects:{
* "green-screen":{ //A unique ID for this effect.
* "inputs":["gs-video"], //The id of the video to apply the effect to.
* "effect": VideoCompositor.Effects.GREENSCREEN //Use the built-in greenscreen effect shader.
* }
* }
* }
*
* @example <caption>A pseudo 2 second cross-fade between two videos.</caption>
*
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:10, src:"video1.mp4", id:"video1"}],
* [ {type:"video", start:8, duration:10, src:"video2.mp4", id:"video2"}]
* ]
* effects:{
* "fade-out":{ //A unique ID for this effect.
* "inputs":["video1"], //The id of the video to apply the effect to.
* "effect": VideoCompositor.Effects.FADEOUT2SEC //Use the built-in fade-out effect shader.
* },
* "fade-in":{ //A unique ID for this effect.
* "inputs":["video2"], //The id of the video to apply the effect to.
* "effect": VideoCompositor.Effects.FADEIN2SEC //Use the built-in fade-in effect shader.
* }
* }
* }
*/
}, {
key: "playlist",
set: function set(playlist) {
VideoCompositor.validatePlaylist(playlist);
this.duration = VideoCompositor.calculatePlaylistDuration(playlist);
this._playlist = playlist;
//clean-up any currently playing mediaSources
this._mediaSources.forEach(function (mediaSource) {
mediaSource.destroy();
});
this._mediaSources.clear();
this.currentTime = this._currentTime;
},
/**
* Get the playlist object.
* @return {Object} The playlist object
*/
get: function get() {
return this._playlist;
}
}], [{
key: "calculateTrackDuration",
value: function calculateTrackDuration(track) {
var maxPlayheadPosition = 0;
for (var j = 0; j < track.length; j++) {
var playheadPosition = track[j].start + track[j].duration;
if (playheadPosition > maxPlayheadPosition) {
maxPlayheadPosition = playheadPosition;
}
}
return maxPlayheadPosition;
}
/**
* Calculate the duration of the passed playlist.
*
* Will return the time that the last media source in the longest track stops playing.
* @param {Object} playlist - This is a playlist object.
* @return {number} The duration in seconds of the given playlist.
* @example
* var playlist = {
* tracks:[
* [{type:"video", start:0, duration:4, src:"video1.mp4", id:"video1"},{type:"video", start:4, duration:4, src:"video2.mp4", id:"video2"}],
* [{type:"video", start:6, duration:4, src:"video3.mp4", id:"video3"}]
* ]
* }
* var playilstDuration = VideoCompositor.calculateTrackDuration(playlist);
* //playlistDuration === 10
*
*/