forked from nirvanatikku/jQuery-TubePlayer-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jQuery.tubeplayer.js
798 lines (508 loc) · 17.2 KB
/
jQuery.tubeplayer.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
/*!
* jQuery TubePlayer Plugin
*
* version: 1.0.4 (12-Nov-2011)
* @requires v1.3.2 or later
*
* @imports SWFObject - http://code.google.com/p/swfobject/
* - Degrades to flash based player if not HTML5/iframe option
*
* Author: Nirvana Tikku (@ntikku / ntikku@gmail.com)
* Documentation:
* http://www.tikku.com/jquery-youtube-tubeplayer-plugin
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($){
// tubeplayer namespace
var TUBEPLAYER = ".tubeplayer",
TUBE_PLAYER_CLASS = "jquery-youtube-tubeplayer",
OPTS = "opts"+TUBEPLAYER;
//
//
// TubePlayer package
//
//
var TubePlayer = {};
// all the instances that exist
TubePlayer.ytplayers = {};
// local init functions for multiple iframe players
TubePlayer.inits = [];
// no need to import the iframe script multiple times
TubePlayer.iframeScriptInited = false;
// tubeplayer inited flag - for destroy/re-init
TubePlayer.inited = false;
//
//
// public facing defaults
//
//
$.tubeplayer = {};
/**
* These are all the events that are bound to the YouTube Player
* the events can be overridden as they are public.
*
* There are several functions that serve as wrappers to be utilized
* internally - stateChange, onError, qualityChange. Change them at your
* own risk.
*/
$.tubeplayer.defaults = {
afterReady: function($player){},
stateChange: function(player){
var _ret = this.onPlayer;
return function(state){
if(typeof(state)=="object")
state = state.data;
switch(state){
case -1: return _ret.unstarted[player]();
case 0: return _ret.ended[player]();
case 1: return _ret.playing[player]();
case 2: return _ret.paused[player]();
case 3: return _ret.buffering[player]();
case 5: return _ret.cued[player]();
default: return null;
}
}
},
onError: function(player){
var _ret = this.onErr;
return function(errorCode){
if(typeof(errorCode)=="object")
errorCode = errorCode.data;
switch(errorCode){
case 2: return _ret.invalidParameter[player]();
case 100: return _ret.notFound[player]();
case 101:
case 150: return _ret.notEmbeddable[player]();
default: return null;
}
}
},
qualityChange: function(player){
var _this = this;
return function(suggested){
if(typeof(suggested)=="object")
suggested = suggested.data;
return _this.onQualityChange[player](suggested);
}
},
onQualityChange:{},
onPlayer:{unstarted:{},ended:{},playing:{},paused:{},buffering:{},cued:{}},
onErr:{notFound:{},notEmbeddable:{},invalidParameter:{}}
};
/**
* These are the internal defaults for the TubePlayer
* plugin to work without providing any parameters. They
* are merged with the users options.
*/
var defaults = {
// public facing
width: 425,
height: 355,
allowFullScreen: "true",
initialVideo: "DkoeNLuMbcI",
start: 0,
preferredQuality: "default",
showControls: true,
showRelated: false,
annotations: true,
autoPlay: false,
autoHide: true,
loop: 0,
theme: 'dark', // 'dark' or 'light'
color: 'red', // 'red' or 'white'
showinfo: false,
modestbranding: true,
protocol: 'http', // set to 'https' for compatibility on SSL-enabled pages
// with respect to [wmode] - 'transparent' maintains z-index, but disables GPU acceleration
wmode: 'transparent', // you probably want to use 'window' when optimizing for mobile devices
swfobjectURL: "ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js", // exclude the protocol, it will be read from the 'protocol' property
loadSWFObject: true, // by default, we will attempt to load the swfobject script, if utilizing the flash player
// privately used
allowScriptAccess: "always",
playerID: "tubeplayer-player-container",
// html5 specific attrs
iframed: true,
// trigger fn's
onPlay: function(id){},
onPause: function(){},
onStop: function(){},
onSeek: function(time){},
onMute: function(){},
onUnMute: function(){},
// player fn's
onPlayerUnstarted: function(){},
onPlayerEnded: function(){},
onPlayerPlaying: function(){},
onPlayerPaused: function(){},
onPlayerBuffering: function(){},
onPlayerCued: function(){},
onQualityChange: function(){},
// error fn's
onErrorNotFound: function(){},
onErrorNotEmbeddable: function(){},
onErrorInvalidParameter: function(){}
};
/**
* The TubePlayer plugin bound to the jQuery object's prototype.
* This method acts as an interface to instantiate a TubePlayer,
* as well as invoke events that are attached - typically getters/setters
*/
$.fn.tubeplayer = function(input, xtra){
var $this = $(this);
var type = typeof input;
if( arguments.length == 0 || type == "object" )
return $this.each(function(){
TubePlayer.init( $(this), input );
});
else if( type == "string" )
return $this.triggerHandler( input+TUBEPLAYER, xtra || null );
};
/**
* This method is the base method for all the events
* that are bound to the TubePlayer.
*/
var buildFN = function(fn, after){
return function(evt,param){
var p = TubePlayer.getPkg(evt);
if(p.ytplayer) {
var ret = fn(evt, param, p);
if(typeof(ret)=="undefined")
ret = p.$player;
return ret;
}
return p.$player;
};
};
/**
* Public method to get all the player instances
*/
$.tubeplayer.getPlayers = function(){
return TubePlayer.ytplayers;
};
/**
* Initialize a YouTube player;
*
* First check to see if TubePlayer has been init'd
* if it has then return, otherwise:
* > add the tubeplayer class (used to denote a player)
* > provide local data access to the options and store it
* > initialize the default events on the jQuery instance
* > create the container for the player
* > initialize the player (iframe/HTML5 vs flash based)
*
* @param $player - the instance being created on
* @param opts - the user's options
*/
TubePlayer.init = function($player, opts){
if( $player.hasClass(TUBE_PLAYER_CLASS) )
return $player;
var o = $.extend({}, defaults, opts);
o.playerID = o.playerID + ( new Date().valueOf() ) + "_" + Math.random();
$player.addClass(TUBE_PLAYER_CLASS).data(OPTS, o);
for(e in PLAYER)
$player.bind(e+TUBEPLAYER, $player, PLAYER[e]);
// initialize the default event methods
TubePlayer.initDefaults($.tubeplayer.defaults, o);
// insert the player container
jQuery("<div></div>").attr("id", o.playerID).appendTo($player);
// append the player into the container
TubePlayer.initPlayer($player, o);
return $player;
};
/**
* Every method needs these items
*/
TubePlayer.getPkg = function(evt){
var $player = evt.data;
var opts = $player.data(OPTS);
var ytplayer = TubePlayer.ytplayers[opts.playerID];
return {
$player: $player,
opts: opts,
ytplayer: ytplayer
}
};
/**
* This method handles the player init. Since
* onYouTubePlayerReady is called when the script
* has been evaluated, we want all the instances
* to get init'd. For this we have a init queue.
* If the script has been init'd, we automatically
* pop the method off the queue and init the player.
*/
TubePlayer.iframeReady = function(o){
TubePlayer.inits.push(function(){
new YT.Player(o.playerID, {
videoId: o.initialVideo,
width: o.width,
height: o.height,
playerVars: {
'autoplay': (o.autoPlay?1:0),
'autohide': (o.autoHide?1:0),
'controls': (o.showControls?1:0),
'loop': (o.loop?1:0),
'playlist': (o.loop ? o.initialVideo : ""),
'rel': (o.showRelated?1:0),
'fs': (o.allowFullScreen?1:0),
'wmode': o.wmode,
'showinfo': (o.showinfo?1:0),
'modestbranding': (o.modestbranding?1:0),
'iv_load_policy': (o.annotations?1:3),
'start': o.start,
'theme': o.theme,
'color': o.color
},
events: {
'onReady': function(evt){
TubePlayer.ytplayers[o.playerID] = evt.target;
var $player = $(evt.target).parents("."+TUBE_PLAYER_CLASS);
$.tubeplayer.defaults.afterReady($player);
},
'onPlaybackQualityChange': $.tubeplayer.defaults.qualityChange(o.playerID),
'onStateChange': $.tubeplayer.defaults.stateChange(o.playerID),
'onError': $.tubeplayer.defaults.onError(o.playerID)
}
});
});
// stacked init method
if(TubePlayer.inits.length>=1 && !TubePlayer.inited){
return function(){
for(var i=0; i<TubePlayer.inits.length; i++){
TubePlayer.inits[i]();
}
TubePlayer.inited = true;
};
}
// if we've inited already, just call the init fn
if(TubePlayer.inited){
( TubePlayer.inits.pop() )();
}
return onYouTubeIframeAPIReady;
};
/**
* check to see if iframe option is plausible
*/
TubePlayer.supportsHTML5 = function(){
return !!document.createElement('video').canPlayType;
};
/**
* @param d - the defaults
* @param o - the options w/ methods to attach
*/
TubePlayer.initDefaults = function(d, o){
var ID = o.playerID;
// default onPlayer events
var dp = d.onPlayer;
dp.unstarted[ID] = o.onPlayerUnstarted;
dp.ended[ID] = o.onPlayerEnded;
dp.playing[ID] = o.onPlayerPlaying;
dp.paused[ID] = o.onPlayerPaused;
dp.buffering[ID] = o.onPlayerBuffering;
dp.cued[ID] = o.onPlayerCued;
// default onQualityChange
d.onQualityChange[ID] = o.onQualityChange;
// default onError events
var de = d.onErr;
de.notFound[ID] = o.onErrorNotFound;
de.notEmbeddable[ID] = o.onErrorNotEmbeddable;
de.invalidParameter[ID] = o.onErrorInvalidParameter;
};
/**
* init the iframed option if its requested and supported
* otherwise initialize the flash based player
* @param $player - the player that the tubeplayer binds to
* @param o - the init options
*/
TubePlayer.initPlayer = function($player, o){
if(o.iframed && TubePlayer.supportsHTML5())
TubePlayer.initIframePlayer($player, o);
else
TubePlayer.initFlashPlayer($player, o);
};
/**
* Initialize an iframe player
*/
TubePlayer.initIframePlayer = function($player, o){
if(!TubePlayer.iframeScriptInited){
// write the api script tag
var tag = document.createElement('script');
tag.src = o.protocol + "://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
TubePlayer.iframeScriptInited = true;
};
// init the iframe player
onYouTubeIframeAPIReady = TubePlayer.iframeReady(o);
};
/**
* Flash player initialization
* -> if 'loadSWFObject' is set to true, player will only be init'd
* when the swfobject script request has completed successfully
* -> if 'loadSWFObject' is set to false, assumes that you have
* imported your own SWFObject, prior to TubePlayer's initialization
* @imports swfobject automatically
*/
TubePlayer.initFlashPlayer = function($player, o){
if(o.loadSWFObject){
// cleanup swfobjectURL to re-apply the protocol
o.swfobjectURL = o.swfobjectURL.replace('http://', '');
o.swfobjectURL = o.swfobjectURL.replace('https://', '');
o.swfobjectURL = o.protocol + '://' + o.swfobjectURL;
$.getScript(o.swfobjectURL, TubePlayer.initFlashPlayerFN(o));
} else {
TubePlayer.initFlashPlayerFN(o)();
}
};
TubePlayer.initFlashPlayerFN = function(o){
return function(){
var url = ["//www.youtube.com/v/"]
url.push( o.initialVideo );
url.push( "?fs=" + (o.allowFullScreen?1:0) );
url.push( "&enablejsapi=1&version=3" );
url.push( "&playerapiid=" + o.playerID );
url.push( "&rel= " + (o.showRelated?1:0) );
url.push( "&autoplay=" + (o.autoPlay?1:0) );
url.push( "&autohide=" + (o.autoHide?1:0) );
url.push( "&loop=" + (o.loop?1:0) );
url.push( "&playlist=" + (o.loop ? o.initialVideo : ""));
url.push( "&controls=" + (o.showControls?1:0) );
url.push( "&showinfo=" + (o.showinfo?1:0) );
url.push( "&modestbranding=" + (o.modestbranding?1:0) );
url.push( "&iv_load_policy=" + (o.annotations?1:3) );
url.push( "&start=" + o.start );
url.push( "&theme=" + o.theme );
url.push( "&color=" + o.color );
swfobject.embedSWF(url.join(""), o.playerID,
o.width,
o.height,
"8", null, null,
{
allowScriptAccess: o.allowScriptAccess,
wmode: o.wmode,
allowFullScreen: o.allowFullScreen
},
{ id: o.playerID }
);
// init the player ready fn
onYouTubePlayerReady = function(playerId) {
var player = document.getElementById(playerId);
TubePlayer.ytplayers[playerId] = player;
player.addEventListener("onStateChange", "$.tubeplayer.defaults.stateChange('"+playerId+"')");
player.addEventListener("onError", "$.tubeplayer.defaults.onError('"+playerId+"')");
player.addEventListener("onPlaybackQualityChange", "$.tubeplayer.defaults.qualityChange('"+playerId+"')");
var $player = $(player).parents("."+TUBE_PLAYER_CLASS);
$.tubeplayer.defaults.afterReady($player);
};
}
};
// fmt: youtube.com/watch?x=[anything]&v=[desired-token]&
TubePlayer.getVideoIDFromURL = function(sURL){
sURL = sURL || ""; // make sure it's a string; sometimes the YT player API returns undefined, and then indexOf() below will fail
var qryParamsStart = sURL.indexOf("?");
var qryParams = sURL.substring(qryParamsStart, sURL.length);
var videoStart = qryParams.indexOf("v=");
if( videoStart > -1 ) {
var videoEnd = qryParams.indexOf("&", videoStart);
if( videoEnd == -1 ) {
videoEnd = qryParams.length;
}
return videoParam = qryParams.substring(videoStart+"v=".length, videoEnd);
}
return "";
};
/**
* All the events that are bound to a TubePlayer instance
*/
var PLAYER = {
cue: buildFN(function(evt,param,p){
p.ytplayer.cueVideoById(param, p.opts.preferredQuality);
}),
play: buildFN(function(evt,param,p){
if(typeof(param)=='object')
p.ytplayer.loadVideoById(param.id,param.time, p.opts.preferredQuality);
else if(param)
p.ytplayer.loadVideoById(param, 0, p.opts.preferredQuality);
else
p.ytplayer.playVideo();
p.opts.onPlay(param);
}),
pause: buildFN(function(evt,param,p){
p.ytplayer.pauseVideo();
p.opts.onPause();
}),
stop: buildFN(function(evt,param,p){
p.ytplayer.stopVideo();
p.opts.onStop();
}),
seek: buildFN(function(evt,param,p){
p.ytplayer.seekTo(param, true);
p.opts.onSeek(param);
}),
mute: buildFN(function(evt,param,p){
p.$player.attr("data-prev-mute-volume", p.ytplayer.getVolume());
p.ytplayer.mute();
p.opts.onMute();
}),
unmute: buildFN(function(evt,param,p){
p.ytplayer.unMute();
p.ytplayer.setVolume( ( p.$player.attr("data-prev-mute-volume") || 50 ) );
p.opts.onUnMute();
}),
isMuted: buildFN(function(evt,param,p){
return p.ytplayer.isMuted();
}),
volume: buildFN(function(evt,param,p){
if(param) {
p.ytplayer.setVolume(param);
p.$player.attr("data-prev-mute-volume", p.ytplayer.getVolume());
} else {
return p.ytplayer.getVolume() || 0; // 0 because iframe's currently in labs
}
}),
quality: buildFN(function(evt,param,p){
if(param)
p.ytplayer.setPlaybackQuality(param);
else
return p.ytplayer.getPlaybackQuality();
}),
data: buildFN(function(evt,param,p){
var ret = {};
var P = p.ytplayer;
ret.bytesLoaded = P.getVideoBytesLoaded();
ret.bytesTotal = P.getVideoBytesTotal();
ret.startBytes= P.getVideoStartBytes();
ret.state = P.getPlayerState();
ret.currentTime = P.getCurrentTime();
ret.availableQualityLevels = P.getAvailableQualityLevels();
ret.duration = P.getDuration();
ret.videoURL = P.getVideoUrl();
ret.getVideoEmbedCode = P.getVideoEmbedCode();
ret.videoID = TubePlayer.getVideoIDFromURL(ret.videoURL);
return ret;
}),
videoId: buildFN(function(evt,param,p){
return TubePlayer.getVideoIDFromURL( p.ytplayer.getVideoUrl() );
}),
size: buildFN(function(evt, param, p){
if(param.width && param.height) {
p.ytplayer.setSize(param.width, param.height);
$(p.ytplayer).css(param);
}
}),
destroy: buildFN(function(evt, param, p){
p.$player.removeClass(TUBE_PLAYER_CLASS)
.data(OPTS, null)
.unbind(TUBEPLAYER)
.html("");
delete TubePlayer.ytplayers[p.opts.playerID];
$(p.ytplayer).remove();
return null;
}),
player: buildFN(function(evt, param, p){
return p.ytplayer;
})
};
})(jQuery);