forked from mozilla/popcorn-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
popcorn.js
2690 lines (2092 loc) · 77.2 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 = ( "byId 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 );
},
Abstract = {
// [[Put]] props from dictionary onto |this|
// MUST BE CALLED FROM WITHIN A CONSTRUCTOR:
// Abstract.put.call( this, dictionary );
put: function( dictionary ) {
// For each own property of src, let key be the property key
// and desc be the property descriptor of the property.
for ( var key in dictionary ) {
if ( dictionary.hasOwnProperty( key ) ) {
this[ key ] = dictionary[ key ];
}
}
}
},
// 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, nodeName,
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;
// inner reference to this media element's nodeName string value
nodeName = ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video";
// Create an audio or video element property reference
this[ nodeName ] = this.media;
this.options = Popcorn.extend( {}, options ) || {};
// Resolve custom ID or default prefixed ID
this.id = this.options.id || Popcorn.guid( nodeName );
// Throw if an attempt is made to use an ID that already exists
if ( Popcorn.byId( this.id ) ) {
throw new Error( "Popcorn.js Error: Cannot use duplicate ID (" + this.id + ")" );
}
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: new TrackEvents( this )
};
// Register new instance
Popcorn.instances.push( this );
// 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( "loadedmetadata", 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.isDestroyed ) {
self.data.durationChange = function() {
var newDuration = self.media.duration,
newDurationPlus = newDuration + 1,
byStart = self.data.trackEvents.byStart,
byEnd = self.data.trackEvents.byEnd;
// Remove old padding events
byStart.pop();
byEnd.pop();
// Remove any internal tracking of events that have end times greater than duration
// otherwise their end events will never be hit.
for ( var k = byEnd.length - 1; k > 0; k-- ) {
if ( byEnd[ k ].end > newDuration ) {
self.removeTrackEvent( byEnd[ k ]._id );
}
}
// Remove any internal tracking of events that have end times greater than duration
// otherwise their end events will never be hit.
for ( var i = 0; i < byStart.length; i++ ) {
if ( byStart[ i ].end > newDuration ) {
self.removeTrackEvent( byStart[ i ]._id );
}
}
// References to byEnd/byStart are reset, so accessing it this way is
// forced upon us.
self.data.trackEvents.byEnd.push({
start: newDurationPlus,
end: newDurationPlus
});
self.data.trackEvents.byStart.push({
start: newDurationPlus,
end: newDurationPlus
});
};
// Listen for duration changes and adjust internal tracking of event timings
self.media.addEventListener( "durationchange", self.data.durationChange, false );
}
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 );
}
}
};
self.media.addEventListener( "error", function() {
self.error = self.media.error;
}, false );
// http://www.whatwg.org/specs/web-apps/current-work/#dom-media-readystate
//
// If media is in readyState (rS) >= 1, we know the media's duration,
// which is required before running the isReady function.
// If rS is 0, attach a listener for "loadedmetadata",
// ( Which indicates that the media has moved from rS 0 to 1 )
//
// This has been changed from a check for rS 2 because
// in certain conditions, Firefox can enter this code after dropping
// to rS 1 from a higher state such as 2 or 3. This caused a "loadeddata"
// listener to be attached to the media object, an event that had
// already triggered and would not trigger again. This left Popcorn with an
// instance that could never start a timeUpdate loop.
if ( self.media.readyState >= 1 ) {
isReady();
} else {
self.media.addEventListener( "loadedmetadata", isReady, false );
}
return this;
}
};
// Extend constructor prototype to instance prototype
// Allows chaining methods to instances
Popcorn.p.init.prototype = Popcorn.p;
Popcorn.byId = function( str ) {
var instances = Popcorn.instances,
length = instances.length,
i = 0;
for ( ; i < length; i++ ) {
if ( instances[ i ].id === str ) {
return instances[ i ];
}
}
return null;
};
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 ) {
if ( !elem.parentNode ) {
return null;
}
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 ] ) {
return;
}
instance.data.disabled[ plugin ] = true;
if ( plugin in Popcorn.registryByName &&
instance.data.running[ plugin ] ) {
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 );
instance.emit( "trackend",
Popcorn.extend({}, event, {
plugin: event.type,
type: "trackend"
})
);
}
}
return instance;
},
enable: function( instance, plugin ) {
if ( !instance.data.disabled[ plugin ] ) {
return;
}
instance.data.disabled[ plugin ] = false;
if ( plugin in Popcorn.registryByName &&
instance.data.running[ plugin ] ) {
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 );
instance.emit( "trackstart",
Popcorn.extend({}, event, {
plugin: event.type,
type: "trackstart",
track: event
})
);
}
}
return instance;
},
destroy: function( instance ) {
var events = instance.data.events,
trackEvents = instance.data.trackEvents,
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 );
}
// Remove all data.trackEvents #1178
trackEvents.byStart.length = 0;
trackEvents.byEnd.length = 0;
if ( !instance.isDestroyed ) {
instance.data.timeUpdate && instance.media.removeEventListener( "timeupdate", instance.data.timeUpdate, false );
instance.isDestroyed = true;
}
Popcorn.instances.splice( Popcorn.instances.indexOf( instance ), 1 );
}
});
// 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 Math.round( this.media.currentTime );
},
// Attach an event to a single point in time
exec: function( id, time, fn ) {
var length = arguments.length,
eventType = "trackadded",
trackEvent, sec, options;
// Check if first could possibly be a SMPTE string
// p.cue( "smpte string", fn );
// try/catch avoid awful throw in Popcorn.util.toSeconds
// TODO: Get rid of that, replace with NaN return?
try {
sec = Popcorn.util.toSeconds( id );
} catch ( e ) {}
// If it can be converted into a number then
// it's safe to assume that the string was SMPTE
if ( typeof sec === "number" ) {
id = sec;
}
// Shift arguments based on use case
//
// Back compat for:
// p.cue( time, fn );
if ( typeof id === "number" && length === 2 ) {
fn = time;
time = id;
id = Popcorn.guid( "cue" );
} else {
// Support for new forms
// p.cue( "empty-cue" );
if ( length === 1 ) {
// Set a time for an empty cue. It's not important what
// the time actually is, because the cue is a no-op
time = -1;
} else {
// Get the TrackEvent that matches the given id.
trackEvent = this.getTrackEvent( id );
if ( trackEvent ) {
// remove existing cue so a new one can be added via trackEvents.add
this.data.trackEvents.remove( id );
TrackEvent.end( this, trackEvent );
// Update track event references
Popcorn.removeTrackEvent.ref( this, id );
eventType = "cuechange";
// p.cue( "my-id", 12 );
// p.cue( "my-id", function() { ... });
if ( typeof id === "string" && length === 2 ) {
// p.cue( "my-id", 12 );
// The path will update the cue time.
if ( typeof time === "number" ) {
// Re-use existing TrackEvent start callback
fn = trackEvent._natives.start;
}
// p.cue( "my-id", function() { ... });
// The path will update the cue function
if ( typeof time === "function" ) {
fn = time;
// Re-use existing TrackEvent start time
time = trackEvent.start;
}
}
} else {
if ( length >= 2 ) {
// p.cue( "a", "00:00:00");
if ( typeof time === "string" ) {
try {
sec = Popcorn.util.toSeconds( time );
} catch ( e ) {}
time = sec;
}
// p.cue( "b", 11 );
// p.cue( "b", 11, function() {} );
if ( typeof time === "number" ) {
fn = fn || Popcorn.nop();
}
// p.cue( "c", function() {});
if ( typeof time === "function" ) {
fn = time;
time = -1;
}
}
}
}
}
options = {
id: id,
start: time,
end: time + 1,
_running: false,
_natives: {
start: fn || Popcorn.nop,
end: Popcorn.nop,
type: "cue"
}
};
if ( trackEvent ) {
options = Popcorn.extend( trackEvent, options );
}
if ( eventType === "cuechange" ) {
// Supports user defined track event id
options._id = options.id || options._id || Popcorn.guid( options._natives.type );
this.data.trackEvents.add( options );
TrackEvent.start( this, options );
this.timeUpdate( this, null, true );
// Store references to user added trackevents in ref table
Popcorn.addTrackEvent.ref( this, options );
this.emit( eventType, Popcorn.extend({}, options, {
id: id,
type: eventType,
previousValue: {
time: trackEvent.start,
fn: trackEvent._natives.start
},
currentValue: {
time: time,
fn: fn || Popcorn.nop
},
track: trackEvent
}));
} else {
// Creating a one second track event with an empty end
Popcorn.addTrackEvent( this, options );
}
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, clonedEvents,
events = this.data.events[ type ];
// setup checks for custom event system
if ( events ) {
eventInterface = Popcorn.events.getInterface( type );
if ( eventInterface ) {
evt = document.createEvent( eventInterface );
evt.initEvent( type, true, true, global, 1 );
this.media.dispatchEvent( evt );
return this;
}
// clone events in case callbacks remove callbacks themselves
clonedEvents = events.slice();
// iterate through all callbacks
while ( clonedEvents.length ) {
clonedEvents.shift().call( this, data );
}
}
return this;
},
listen: function( type, fn ) {
var self = this,
hasEvents = true,
eventHook = Popcorn.events.hooks[ type ],
origType = type,
clonedEvents,
tmp;
if ( typeof fn !== "function" ) {
throw new Error( "Popcorn.js Error: Listener is not a function" );
}
// Setup event registry entry
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = [];
// Toggle if the previous assumption was untrue
hasEvents = false;
}
// Check and setup event hooks