forked from mozilla/popcorn-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
popcorn.js
1996 lines (1520 loc) · 55.8 KB
/
popcorn.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
(function(global, document) {
// Popcorn.js does not support archaic browsers
if ( !document.addEventListener ) {
global.Popcorn = {
isSupported: false
};
var methods = ( "removeInstance addInstance getInstanceById removeInstanceById " +
"forEach extend effects error guid sizeOf isArray nop position disable enable destroy" +
"addTrackEvent removeTrackEvent getTrackEvents getTrackEvent getLastTrackEventId " +
"timeUpdate plugin removePlugin compose effect xhr getJSONP getScript" ).split(/\s+/);
while ( methods.length ) {
global.Popcorn[ methods.shift() ] = function() {};
}
return;
}
var
AP = Array.prototype,
OP = Object.prototype,
forEach = AP.forEach,
slice = AP.slice,
hasOwn = OP.hasOwnProperty,
toString = OP.toString,
// Copy global Popcorn (may not exist)
_Popcorn = global.Popcorn,
// Ready fn cache
readyStack = [],
readyBound = false,
readyFired = false,
// Non-public internal data object
internal = {
events: {
hash: {},
apis: {}
}
},
// Non-public `requestAnimFrame`
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = (function(){
return global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function( callback, element ) {
global.setTimeout( callback, 16 );
};
}()),
// Non-public `getKeys`, return an object's keys as an array
getKeys = function( obj ) {
return Object.keys ? Object.keys( obj ) : (function( obj ) {
var item,
list = [];
for ( item in obj ) {
if ( hasOwn.call( obj, item ) ) {
list.push( item );
}
}
return list;
})( obj );
},
// Declare constructor
// Returns an instance object.
Popcorn = function( entity, options ) {
// Return new Popcorn object
return new Popcorn.p.init( entity, options || null );
};
// Popcorn API version, automatically inserted via build system.
Popcorn.version = "@VERSION";
// Boolean flag allowing a client to determine if Popcorn can be supported
Popcorn.isSupported = true;
// Instance caching
Popcorn.instances = [];
// Declare a shortcut (Popcorn.p) to and a definition of
// the new prototype for our Popcorn constructor
Popcorn.p = Popcorn.prototype = {
init: function( entity, options ) {
var matches,
self = this;
// Supports Popcorn(function () { /../ })
// Originally proposed by Daniel Brooks
if ( typeof entity === "function" ) {
// If document ready has already fired
if ( document.readyState === "complete" ) {
entity( document, Popcorn );
return;
}
// Add `entity` fn to ready stack
readyStack.push( entity );
// This process should happen once per page load
if ( !readyBound ) {
// set readyBound flag
readyBound = true;
var DOMContentLoaded = function() {
readyFired = true;
// Remove global DOM ready listener
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// Execute all ready function in the stack
for ( var i = 0, readyStackLength = readyStack.length; i < readyStackLength; i++ ) {
readyStack[ i ].call( document, Popcorn );
}
// GC readyStack
readyStack = null;
};
// Register global DOM ready listener
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
}
return;
}
if ( typeof entity === "string" ) {
try {
matches = document.querySelector( entity );
} catch( e ) {
throw new Error( "Popcorn.js Error: Invalid media element selector: " + entity );
}
}
// Get media element by id or object reference
this.media = matches || entity;
// Create an audio or video element property reference
this[ ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video" ] = this.media;
// Register new instance
Popcorn.instances.push( this );
this.options = options || {};
this.isDestroyed = false;
this.data = {
// data structure of all
running: {
cue: []
},
// Executed by either timeupdate event or in rAF loop
timeUpdate: Popcorn.nop,
// Allows disabling a plugin per instance
disabled: {},
// Stores DOM event queues by type
events: {},
// Stores Special event hooks data
hooks: {},
// Store track event history data
history: [],
// Stores ad-hoc state related data]
state: {
volume: this.media.volume
},
// Store track event object references by trackId
trackRefs: {},
// Playback track event queues
trackEvents: {
byStart: [{
start: -1,
end: -1
}],
byEnd: [{
start: -1,
end: -1
}],
animating: [],
startIndex: 0,
endIndex: 0,
previousUpdateTime: -1
}
};
// function to fire when video is ready
var isReady = function() {
// chrome bug: http://code.google.com/p/chromium/issues/detail?id=119598
// it is possible the video's time is less than 0
// this has the potential to call track events more than once, when they should not
// start: 0, end: 1 will start, end, start again, when it should just start
// just setting it to 0 if it is below 0 fixes this issue
if ( self.media.currentTime < 0 ) {
self.media.currentTime = 0;
}
self.media.removeEventListener( "loadeddata", isReady, false );
var duration, videoDurationPlus,
runningPlugins, runningPlugin, rpLength, rpNatives;
// Adding padding to the front and end of the arrays
// this is so we do not fall off either end
duration = self.media.duration;
// Check for no duration info (NaN)
videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1;
Popcorn.addTrackEvent( self, {
start: videoDurationPlus,
end: videoDurationPlus
});
if ( self.options.frameAnimation ) {
// if Popcorn is created with frameAnimation option set to true,
// requestAnimFrame is used instead of "timeupdate" media event.
// This is for greater frame time accuracy, theoretically up to
// 60 frames per second as opposed to ~4 ( ~every 15-250ms)
self.data.timeUpdate = function () {
Popcorn.timeUpdate( self, {} );
// fire frame for each enabled active plugin of every type
Popcorn.forEach( Popcorn.manifest, function( key, val ) {
runningPlugins = self.data.running[ val ];
// ensure there are running plugins on this type on this instance
if ( runningPlugins ) {
rpLength = runningPlugins.length;
for ( var i = 0; i < rpLength; i++ ) {
runningPlugin = runningPlugins[ i ];
rpNatives = runningPlugin._natives;
rpNatives && rpNatives.frame &&
rpNatives.frame.call( self, {}, runningPlugin, self.currentTime() );
}
}
});
self.emit( "timeupdate" );
!self.isDestroyed && requestAnimFrame( self.data.timeUpdate );
};
!self.isDestroyed && requestAnimFrame( self.data.timeUpdate );
} else {
self.data.timeUpdate = function( event ) {
Popcorn.timeUpdate( self, event );
};
if ( !self.isDestroyed ) {
self.media.addEventListener( "timeupdate", self.data.timeUpdate, false );
}
}
};
Object.defineProperty( this, "error", {
get: function() {
return self.media.error;
}
});
if ( self.media.readyState >= 2 ) {
isReady();
} else {
self.media.addEventListener( "loadeddata", isReady, false );
}
return this;
}
};
// Extend constructor prototype to instance prototype
// Allows chaining methods to instances
Popcorn.p.init.prototype = Popcorn.p;
Popcorn.forEach = function( obj, fn, context ) {
if ( !obj || !fn ) {
return {};
}
context = context || this;
var key, len;
// Use native whenever possible
if ( forEach && obj.forEach === forEach ) {
return obj.forEach( fn, context );
}
if ( toString.call( obj ) === "[object NodeList]" ) {
for ( key = 0, len = obj.length; key < len; key++ ) {
fn.call( context, obj[ key ], key, obj );
}
return obj;
}
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
fn.call( context, obj[ key ], key, obj );
}
}
return obj;
};
Popcorn.extend = function( obj ) {
var dest = obj, src = slice.call( arguments, 1 );
Popcorn.forEach( src, function( copy ) {
for ( var prop in copy ) {
dest[ prop ] = copy[ prop ];
}
});
return dest;
};
// A Few reusable utils, memoized onto Popcorn
Popcorn.extend( Popcorn, {
noConflict: function( deep ) {
if ( deep ) {
global.Popcorn = _Popcorn;
}
return Popcorn;
},
error: function( msg ) {
throw new Error( msg );
},
guid: function( prefix ) {
Popcorn.guid.counter++;
return ( prefix ? prefix : "" ) + ( +new Date() + Popcorn.guid.counter );
},
sizeOf: function( obj ) {
var size = 0;
for ( var prop in obj ) {
size++;
}
return size;
},
isArray: Array.isArray || function( array ) {
return toString.call( array ) === "[object Array]";
},
nop: function() {},
position: function( elem ) {
var clientRect = elem.getBoundingClientRect(),
bounds = {},
doc = elem.ownerDocument,
docElem = document.documentElement,
body = document.body,
clientTop, clientLeft, scrollTop, scrollLeft, top, left;
// Determine correct clientTop/Left
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
// Determine correct scrollTop/Left
scrollTop = ( global.pageYOffset && docElem.scrollTop || body.scrollTop );
scrollLeft = ( global.pageXOffset && docElem.scrollLeft || body.scrollLeft );
// Temp top/left
top = Math.ceil( clientRect.top + scrollTop - clientTop );
left = Math.ceil( clientRect.left + scrollLeft - clientLeft );
for ( var p in clientRect ) {
bounds[ p ] = Math.round( clientRect[ p ] );
}
return Popcorn.extend({}, bounds, { top: top, left: left });
},
disable: function( instance, plugin ) {
if ( !instance.data.disabled[ plugin ] ) {
instance.data.disabled[ plugin ] = true;
for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) {
event = instance.data.running[ plugin ][ i ];
event._natives.end.call( instance, null, event );
}
}
return instance;
},
enable: function( instance, plugin ) {
if ( instance.data.disabled[ plugin ] ) {
instance.data.disabled[ plugin ] = false;
for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) {
event = instance.data.running[ plugin ][ i ];
event._natives.start.call( instance, null, event );
}
}
return instance;
},
destroy: function( instance ) {
var events = instance.data.events,
singleEvent, item, fn, plugin;
// Iterate through all events and remove them
for ( item in events ) {
singleEvent = events[ item ];
for ( fn in singleEvent ) {
delete singleEvent[ fn ];
}
events[ item ] = null;
}
// remove all plugins off the given instance
for ( plugin in Popcorn.registryByName ) {
Popcorn.removePlugin( instance, plugin );
}
if ( !instance.isDestroyed ) {
instance.data.timeUpdate && instance.media.removeEventListener( "timeupdate", instance.data.timeUpdate, false );
instance.isDestroyed = true;
}
}
});
// Memoized GUID Counter
Popcorn.guid.counter = 1;
// Factory to implement getters, setters and controllers
// as Popcorn instance methods. The IIFE will create and return
// an object with defined methods
Popcorn.extend(Popcorn.p, (function() {
var methods = "load play pause currentTime playbackRate volume duration preload playbackRate " +
"autoplay loop controls muted buffered readyState seeking paused played seekable ended",
ret = {};
// Build methods, store in object that is returned and passed to extend
Popcorn.forEach( methods.split( /\s+/g ), function( name ) {
ret[ name ] = function( arg ) {
var previous;
if ( typeof this.media[ name ] === "function" ) {
// Support for shorthanded play(n)/pause(n) jump to currentTime
// If arg is not null or undefined and called by one of the
// allowed shorthandable methods, then set the currentTime
// Supports time as seconds or SMPTE
if ( arg != null && /play|pause/.test( name ) ) {
this.media.currentTime = Popcorn.util.toSeconds( arg );
}
this.media[ name ]();
return this;
}
if ( arg != null ) {
// Capture the current value of the attribute property
previous = this.media[ name ];
// Set the attribute property with the new value
this.media[ name ] = arg;
// If the new value is not the same as the old value
// emit an "attrchanged event"
if ( previous !== arg ) {
this.emit( "attrchange", {
attribute: name,
previousValue: previous,
currentValue: arg
});
}
return this;
}
return this.media[ name ];
};
});
return ret;
})()
);
Popcorn.forEach( "enable disable".split(" "), function( method ) {
Popcorn.p[ method ] = function( plugin ) {
return Popcorn[ method ]( this, plugin );
};
});
Popcorn.extend(Popcorn.p, {
// Rounded currentTime
roundTime: function() {
return -~this.media.currentTime;
},
// Attach an event to a single point in time
exec: function( time, fn ) {
// Creating a one second track event with an empty end
Popcorn.addTrackEvent( this, {
start: time,
end: time + 1,
_running: false,
_natives: {
start: fn || Popcorn.nop,
end: Popcorn.nop,
type: "cue"
}
});
return this;
},
// Mute the calling media, optionally toggle
mute: function( toggle ) {
var event = toggle == null || toggle === true ? "muted" : "unmuted";
// If `toggle` is explicitly `false`,
// unmute the media and restore the volume level
if ( event === "unmuted" ) {
this.media.muted = false;
this.media.volume = this.data.state.volume;
}
// If `toggle` is either null or undefined,
// save the current volume and mute the media element
if ( event === "muted" ) {
this.data.state.volume = this.media.volume;
this.media.muted = true;
}
// Trigger either muted|unmuted event
this.emit( event );
return this;
},
// Convenience method, unmute the calling media
unmute: function( toggle ) {
return this.mute( toggle == null ? false : !toggle );
},
// Get the client bounding box of an instance element
position: function() {
return Popcorn.position( this.media );
},
// Toggle a plugin's playback behaviour (on or off) per instance
toggle: function( plugin ) {
return Popcorn[ this.data.disabled[ plugin ] ? "enable" : "disable" ]( this, plugin );
},
// Set default values for plugin options objects per instance
defaults: function( plugin, defaults ) {
// If an array of default configurations is provided,
// iterate and apply each to this instance
if ( Popcorn.isArray( plugin ) ) {
Popcorn.forEach( plugin, function( obj ) {
for ( var name in obj ) {
this.defaults( name, obj[ name ] );
}
}, this );
return this;
}
if ( !this.options.defaults ) {
this.options.defaults = {};
}
if ( !this.options.defaults[ plugin ] ) {
this.options.defaults[ plugin ] = {};
}
Popcorn.extend( this.options.defaults[ plugin ], defaults );
return this;
}
});
Popcorn.Events = {
UIEvents: "blur focus focusin focusout load resize scroll unload",
MouseEvents: "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave click dblclick",
Events: "loadstart progress suspend emptied stalled play pause error " +
"loadedmetadata loadeddata waiting playing canplay canplaythrough " +
"seeking seeked timeupdate ended ratechange durationchange volumechange"
};
Popcorn.Events.Natives = Popcorn.Events.UIEvents + " " +
Popcorn.Events.MouseEvents + " " +
Popcorn.Events.Events;
internal.events.apiTypes = [ "UIEvents", "MouseEvents", "Events" ];
// Privately compile events table at load time
(function( events, data ) {
var apis = internal.events.apiTypes,
eventsList = events.Natives.split( /\s+/g ),
idx = 0, len = eventsList.length, prop;
for( ; idx < len; idx++ ) {
data.hash[ eventsList[idx] ] = true;
}
apis.forEach(function( val, idx ) {
data.apis[ val ] = {};
var apiEvents = events[ val ].split( /\s+/g ),
len = apiEvents.length,
k = 0;
for ( ; k < len; k++ ) {
data.apis[ val ][ apiEvents[ k ] ] = true;
}
});
})( Popcorn.Events, internal.events );
Popcorn.events = {
isNative: function( type ) {
return !!internal.events.hash[ type ];
},
getInterface: function( type ) {
if ( !Popcorn.events.isNative( type ) ) {
return false;
}
var eventApi = internal.events,
apis = eventApi.apiTypes,
apihash = eventApi.apis,
idx = 0, len = apis.length, api, tmp;
for ( ; idx < len; idx++ ) {
tmp = apis[ idx ];
if ( apihash[ tmp ][ type ] ) {
api = tmp;
break;
}
}
return api;
},
// Compile all native events to single array
all: Popcorn.Events.Natives.split( /\s+/g ),
// Defines all Event handling static functions
fn: {
trigger: function( type, data ) {
var eventInterface, evt;
// setup checks for custom event system
if ( this.data.events[ type ] && Popcorn.sizeOf( this.data.events[ type ] ) ) {
eventInterface = Popcorn.events.getInterface( type );
if ( eventInterface ) {
evt = document.createEvent( eventInterface );
evt.initEvent( type, true, true, global, 1 );
this.media.dispatchEvent( evt );
return this;
}
// Custom events
Popcorn.forEach( this.data.events[ type ], function( obj, key ) {
obj.call( this, data );
}, this );
}
return this;
},
listen: function( type, fn ) {
var self = this,
hasEvents = true,
eventHook = Popcorn.events.hooks[ type ],
origType = type,
tmp;
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
hasEvents = false;
}
// Check and setup event hooks
if ( eventHook ) {
// Execute hook add method if defined
if ( eventHook.add ) {
eventHook.add.call( this, {}, fn );
}
// Reassign event type to our piggyback event type if defined
if ( eventHook.bind ) {
type = eventHook.bind;
}
// Reassign handler if defined
if ( eventHook.handler ) {
tmp = fn;
fn = function wrapper( event ) {
eventHook.handler.call( self, event, tmp );
};
}
// assume the piggy back event is registered
hasEvents = true;
// Setup event registry entry
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
// Toggle if the previous assumption was untrue
hasEvents = false;
}
}
// Register event and handler
this.data.events[ type ][ fn.name || ( fn.toString() + Popcorn.guid() ) ] = fn;
// only attach one event of any type
if ( !hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) {
this.media.addEventListener( type, function( event ) {
Popcorn.forEach( self.data.events[ type ], function( obj, key ) {
if ( typeof obj === "function" ) {
obj.call( self, event );
}
});
}, false);
}
return this;
},
unlisten: function( type, fn ) {
if ( this.data.events[ type ] && this.data.events[ type ][ fn ] ) {
delete this.data.events[ type ][ fn ];
return this;
}
this.data.events[ type ] = null;
return this;
}
},
hooks: {
canplayall: {
bind: "canplaythrough",
add: function( event, callback ) {
var state = false;
if ( this.media.readyState ) {
callback.call( this, event );
state = true;
}
this.data.hooks.canplayall = {
fired: state
};
},
// declare special handling instructions
handler: function canplayall( event, callback ) {
if ( !this.data.hooks.canplayall.fired ) {
// trigger original user callback once
callback.call( this, event );
this.data.hooks.canplayall.fired = true;
}
}
}
}
};
// Extend Popcorn.events.fns (listen, unlisten, trigger) to all Popcorn instances
// Extend aliases (on, off, emit)
Popcorn.forEach( [ [ "trigger", "emit" ], [ "listen", "on" ], [ "unlisten", "off" ] ], function( key ) {
Popcorn.p[ key[ 0 ] ] = Popcorn.p[ key[ 1 ] ] = Popcorn.events.fn[ key[ 0 ] ];
});
// Internal Only - Adds track events to the instance object
Popcorn.addTrackEvent = function( obj, track ) {
// Determine if this track has default options set for it
// If so, apply them to the track object
if ( track && track._natives && track._natives.type &&
( obj.options.defaults && obj.options.defaults[ track._natives.type ] ) ) {
track = Popcorn.extend( {}, obj.options.defaults[ track._natives.type ], track );
}
if ( track._natives ) {
// Supports user defined track event id
track._id = !track.id ? Popcorn.guid( track._natives.type ) : track.id;
// Push track event ids into the history
obj.data.history.push( track._id );
}
track.start = Popcorn.util.toSeconds( track.start, obj.options.framerate );
track.end = Popcorn.util.toSeconds( track.end, obj.options.framerate );
// Store this definition in an array sorted by times
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
startIndex, endIndex;
for ( startIndex = byStart.length - 1; startIndex >= 0; startIndex-- ) {
if ( track.start >= byStart[ startIndex ].start ) {
byStart.splice( startIndex + 1, 0, track );
break;
}
}
for ( endIndex = byEnd.length - 1; endIndex >= 0; endIndex-- ) {
if ( track.end > byEnd[ endIndex ].end ) {
byEnd.splice( endIndex + 1, 0, track );
break;
}
}
// Display track event immediately if it's enabled and current
if ( track.end > obj.media.currentTime &&
track.start <= obj.media.currentTime ) {
track._running = true;
obj.data.running[ track._natives.type ].push( track );
if ( !obj.data.disabled[ track._natives.type ] ) {
track._natives.start.call( obj, null, track );
}
}
// update startIndex and endIndex
if ( startIndex <= obj.data.trackEvents.startIndex &&
track.start <= obj.data.trackEvents.previousUpdateTime ) {
obj.data.trackEvents.startIndex++;
}
if ( endIndex <= obj.data.trackEvents.endIndex &&
track.end < obj.data.trackEvents.previousUpdateTime ) {
obj.data.trackEvents.endIndex++;
}
this.timeUpdate( obj, null, true );
// Store references to user added trackevents in ref table
if ( track._id ) {
Popcorn.addTrackEvent.ref( obj, track );
}
};
// Internal Only - Adds track event references to the instance object's trackRefs hash table
Popcorn.addTrackEvent.ref = function( obj, track ) {
obj.data.trackRefs[ track._id ] = track;
return obj;
};
Popcorn.removeTrackEvent = function( obj, removeId ) {
var start, end, animate,
historyLen = obj.data.history.length,
length = obj.data.trackEvents.byStart.length,
index = 0,
indexWasAt = 0,
byStart = [],
byEnd = [],
animating = [],
history = [];
while ( --length > -1 ) {
start = obj.data.trackEvents.byStart[ index ];
end = obj.data.trackEvents.byEnd[ index ];
// Padding events will not have _id properties.
// These should be safely pushed onto the front and back of the
// track event array
if ( !start._id ) {
byStart.push( start );
byEnd.push( end );
}
// Filter for user track events (vs system track events)
if ( start._id ) {
// If not a matching start event for removal
if ( start._id !== removeId ) {
byStart.push( start );
}
// If not a matching end event for removal
if ( end._id !== removeId ) {
byEnd.push( end );
}
// If the _id is matched, capture the current index
if ( start._id === removeId ) {
indexWasAt = index;
// If a _teardown function was defined,
// enforce for track event removals
if ( start._natives._teardown ) {
start._natives._teardown.call( obj, start );
}
}
}
// Increment the track index
index++;
}
// Reset length to be used by the condition below to determine
// if animating track events should also be filtered for removal.
// Reset index below to be used by the reverse while as an
// incrementing counter
length = obj.data.trackEvents.animating.length;
index = 0;
if ( length ) {
while ( --length > -1 ) {
animate = obj.data.trackEvents.animating[ index ];
// Padding events will not have _id properties.
// These should be safely pushed onto the front and back of the
// track event array
if ( !animate._id ) {