From 79c12c5f0fa532ac928b085b7724b8b0ebfefc52 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Tue, 15 Mar 2011 11:44:58 -0400 Subject: [PATCH] [#140] Updated for core engine changes --- players/youtube/popcorn.youtube.html | 86 ++++--- players/youtube/popcorn.youtube.js | 279 +++++++++++++++------- players/youtube/popcorn.youtube.unit.html | 2 +- players/youtube/popcorn.youtube.unit.js | 79 +++++- popcorn.js | 51 ++-- test/popcorn.unit.js | 76 ------ 6 files changed, 326 insertions(+), 247 deletions(-) diff --git a/players/youtube/popcorn.youtube.html b/players/youtube/popcorn.youtube.html index c3d8344..d874f24 100644 --- a/players/youtube/popcorn.youtube.html +++ b/players/youtube/popcorn.youtube.html @@ -4,32 +4,36 @@ Popcorn Youtube Player Example +
@@ -74,6 +86,7 @@ +
  • Status: Not Ready
  • @@ -81,6 +94,7 @@
  • Video Duration (s):
+ Footnote:
diff --git a/players/youtube/popcorn.youtube.js b/players/youtube/popcorn.youtube.js index 2f7125c..b9aa7d5 100644 --- a/players/youtube/popcorn.youtube.js +++ b/players/youtube/popcorn.youtube.js @@ -1,4 +1,6 @@ -// Popcorn Youtube Player Warpper +// Popcorn Youtube Player Wrapper + +var onYouTubePlayerReady; ( function( Popcorn ) { /** @@ -21,46 +23,131 @@ var undef; // Config parameters - var debug = true; - var timeupdateInterval = 33; // 33 is suitable for 30 fps - var progressInterval = 250; // as specified by WHATWG + // 33 ms per update is suitable for 30 fps + // 0.05 sec tolerance between old and new times to determine if currentTime has been set programatically + // 250 ms progress interval as specified by WHATWG + var timeupdateInterval = 33, + timeCheckInterval = 0.5 + progressInterval = 250; // Ready State Constants - var READY_STATE_HAVE_NOTHING = 0; - var READY_STATE_HAVE_METADATA = 1; - var READY_STATE_HAVE_CURRENT_DATA = 2; - var READY_STATE_HAVE_FUTURE_DATA = 3; - var READY_STATE_HAVE_ENOUGH_DATA = 4; + var READY_STATE_HAVE_NOTHING = 0, + READY_STATE_HAVE_METADATA = 1, + READY_STATE_HAVE_CURRENT_DATA = 2, + READY_STATE_HAVE_FUTURE_DATA = 3, + READY_STATE_HAVE_ENOUGH_DATA = 4; // Youtube State Constants - var YOUTUBE_STATE_UNSTARTED = -1; - var YOUTUBE_STATE_ENDED = 0; - var YOUTUBE_STATE_PLAYING = 1; - var YOUTUBE_STATE_PAUSED = 2; - var YOUTUBE_STATE_BUFFERING = 3; - var YOUTUBE_STATE_CUED = 5; - - Popcorn.youtube = function( elementId ) { - return new Popcorn.youtube.init( elementId ); + var YOUTUBE_STATE_UNSTARTED = -1, + YOUTUBE_STATE_ENDED = 0, + YOUTUBE_STATE_PLAYING = 1, + YOUTUBE_STATE_PAUSED = 2, + YOUTUBE_STATE_BUFFERING = 3, + YOUTUBE_STATE_CUED = 5; + + // Collection of all Youtube players + var registry = {}, + loadedPlayers = {}; + + var abs = Math.abs; + + // Extract the id from a web url + function extractIdFromUrl( url ) { + if ( !url ) { + return; + } + + var matches = url.match( /((http:\/\/)?www\.)?youtube\.[a-z]+\/watch\?v\=[a-z0-9]+/i ); + + // Return id, which comes after first equals sign + return !matches || matches[0].split( "=" )[1]; }; + + function cueDelayedDurationCheck ( evt ) { + var self = this, + durSetEvt; + + durSetEvt = function() { + this.duration = this.video.getDuration(); + this.dispatchEvent( "durationchange" ); + }; + + this.eventListeners[evt] = this.eventListeners[evt] || []; + + this.eventListeners[evt].unshift(durSetEvt); + } + + function getPlayerAddress( id ) { + if( !id ) { + return; + } + + return "http://www.youtube.com/e/"+id; + } + + // Called when a player is loaded + // Playerid must match the element id + onYouTubePlayerReady = function ( playerId ) { + var vid = registry[playerId]; + + loadedPlayers[playerId] = 1; + + // Video hadn't loaded yet when ctor was called + if( !vid.video ) { + vid.video = document.getElementById( playerId ); + } + + // Set up stuff that requires the API to be loaded + vid.registerYoutubeEventHandlers(); + vid.registerInternalEventHandlers(); + + // Issue load event + vid.dispatchEvent( 'load' ); + } - Popcorn.youtube.init = function( elementId ) { + Popcorn.youtube = function( elementId, url ) { + return new Popcorn.youtube.init( elementId, url ); + }; + + Popcorn.youtube.init = function( elementId, url ) { if ( !elementId ) { throw "Element id is invalid."; } + + var self = this, + durEvtType; this.video = document.getElementById( elementId ); this.readyState = READY_STATE_HAVE_NOTHING; - this.duration = this.video.getDuration(); this.eventListeners = {}; this.loadStarted = false; this.loadedData = false; this.fullyLoaded = false; this.timeUpdater = null; this.progressUpdater = null; - this.registerYoutubeEventHandlers(); - this.registerInternalEventHandlers(); - }; // end Popcorn.youtube.init + + this.playerId = elementId; + this.duration = Number.MAX_VALUE; + + // The video id for youtube + this.vidId = extractIdFromUrl( url ); + + if ( this.vidId ) { + this.addEventListener( "load", function() { + self.video.cueVideoByUrl( getPlayerAddress( self.vidId ) ); + cueDelayedDurationCheck.call( self, "playing" ); + }); + } else { + cueDelayedDurationCheck.call( this, "load" ); + } + + registry[elementId] = this; + + if ( loadedPlayers[elementId] ) { + this.dispatchEvent( "load" ); + } + }; + // end Popcorn.youtube.init Popcorn.extend( Popcorn.youtube.init.prototype, { @@ -70,6 +157,7 @@ var youcorn = this, stateChangeHandler = 'Popcorn.youtube.stateChangeEventHandler', errorHandler = 'Popcorn.youtube.errorEventHandler'; + this.video.addEventListener( 'onStateChange', stateChangeHandler ); this.video.addEventListener( 'onError', errorHandler ); @@ -78,37 +166,35 @@ * separately here. */ Popcorn.youtube.stateChangeEventHandler = function( state ) { - if ( debug ) { - console.log( 'Youtube state updated: ' + state ); - } - if ( state == YOUTUBE_STATE_UNSTARTED ) { - youcorn.readyState = READY_STATE_HAVE_METADATA; - youcorn.raiseEvent('loadedmetadata'); - } else if ( state == YOUTUBE_STATE_ENDED ) { - youcorn.raiseEvent('ended'); - } else if ( state == YOUTUBE_STATE_PLAYING ) { + // In case ctor has been called many times for many ctors + // Only use latest ctor call for each player id + var self = registry[youcorn.playerId]; + + if ( state === YOUTUBE_STATE_UNSTARTED ) { + self.readyState = READY_STATE_HAVE_METADATA; + self.dispatchEvent( 'loadedmetadata' ); + } else if ( state === YOUTUBE_STATE_ENDED ) { + self.dispatchEvent( 'ended' ); + } else if ( state === YOUTUBE_STATE_PLAYING ) { // Being able to play means current data is loaded. if ( !this.loadedData ) { this.loadedData = true; - youcorn.raiseEvent( 'loadeddata' ); + self.dispatchEvent( 'loadeddata' ); } - youcorn.readyState = READY_STATE_HAVE_CURRENT_DATA; - youcorn.raiseEvent( 'playing' ); - } else if ( state == YOUTUBE_STATE_PAUSED ) { - youcorn.raiseEvent( 'pause' ); - } else if ( state == YOUTUBE_STATE_BUFFERING ) { - youcorn.raiseEvent( 'waiting' ); - } else if ( state == YOUTUBE_STATE_CUED ) { + self.readyState = READY_STATE_HAVE_CURRENT_DATA; + self.dispatchEvent( 'playing' ); + } else if ( state === YOUTUBE_STATE_PAUSED ) { + self.dispatchEvent( 'pause' ); + } else if ( state === YOUTUBE_STATE_BUFFERING ) { + self.dispatchEvent( 'waiting' ); + } else if ( state === YOUTUBE_STATE_CUED ) { // not handled } }; Popcorn.youtube.errorEventHandler = function( state ) { - if ( debug ) { - console.log( 'Youtube error encountered: ' + error ); - } - youcorn.raiseEvent( 'error' ); + youcorn.dispatchEvent( 'error' ); }; }, @@ -124,7 +210,7 @@ }, play: function() { - this.raiseEvent( 'play' ); + this.dispatchEvent( 'play' ); this.video.playVideo(); }, @@ -137,11 +223,11 @@ this.video.playVideo(); this.video.pauseVideo(); }, + + currentTime: 0, + previousCurrentTime: 0, - currentTime: function( time ) { - if ( time === undef ) { - return this.video.getCurrentTime(); - } + seekTo: function( time ) { var playing = this.video.getPlayerState() == YOUTUBE_STATE_PLAYING; this.video.seekTo( time, true ); @@ -156,51 +242,58 @@ } // Raise event. - this.raiseEvent( 'seeked' ); + this.dispatchEvent( 'seeked' ); }, duration: function() { return this.video.getDuration(); }, + // Mute is toggleable mute: function() { - if ( this.video.getVolume() != 0 ) { + if ( this.video.isMuted() ) { + this.video.unMute(); + this.dispatchEvent( 'volumechange' ); + } else { this.video.mute(); - this.raiseEvent( 'volumechange' ); + this.dispatchEvent( 'volumechange' ); } }, - - volume: function( vol ) { - if ( vol == undef ) { - return this.video.getVolume() / 100; - } - if ( vol != this.volume() ) { - this.video.setVolume( vol * 100 ); - this.raiseEvent( 'volumechange' ); - } + + volume: 0, + previousVolume: 0, + + // Expects beteween 0 and 1 + setVolume: function( vol ) { + this.volume = this.previousVolume = vol; + this.video.setVolume( vol * 100 ); + this.dispatchEvent( 'volumechange' ); }, - addEventListener: function( eventName, func ) { - if ( !this.eventListeners[eventName] ) { - this.eventListeners[eventName] = []; + addEventListener: function( evt, func ) { + var evtName = evt.type || evt; + + if ( !this.eventListeners[evtName] ) { + this.eventListeners[evtName] = []; } - this.eventListeners[eventName].push( func ); + + this.eventListeners[evtName].push( func ); }, /** * Notify event listeners about an event. */ - raiseEvent: function( name ) { - if ( debug ) { - console.log( 'Raising event: ' + name ); - } - if ( !this.eventListeners[name] ) { + dispatchEvent: function( name ) { + var evtName = name.type || name; + if ( !this.eventListeners[evtName] ) { return; } - for ( var i in this.eventListeners[name] ) { - // @TODO should we mimic the event object sent by HTMLMediaElement? - this.eventListeners[name][i].call( this, null ); - } + + var self = this; + + Popcorn.forEach( this.eventListeners[evtName], function( evt ) { + evt.call( self, null ); + }); }, /* Unsupported methods. */ @@ -215,23 +308,34 @@ function startTimeUpdater( youcorn ) { youcorn.timeUpdater = setInterval(function() { + var state = youcorn.video.getPlayerState(); - if ( (state == YOUTUBE_STATE_ENDED) || (state == YOUTUBE_STATE_PAUSED) ) { - clearInterval(youcorn.timeUpdater); - return; + + + + if ( state !== YOUTUBE_STATE_ENDED && state !== YOUTUBE_STATE_PAUSED ) { + if ( abs( youcorn.currentTime - youcorn.previousCurrentTime ) > timeCheckInterval ) { + // Has programatically set the currentTime + youcorn.previousCurrentTime = youcorn.currentTime - timeCheckInterval; + youcorn.seekTo( youcorn.currentTime ); + } else { + youcorn.previousCurrentTime = youcorn.currentTime; + youcorn.currentTime = youcorn.video.getCurrentTime(); + } + } + + if ( youcorn.volume !== youcorn.previousVolume ) { + youcorn.setVolume( youcorn.volume ); } - youcorn.raiseEvent( 'timeupdate' ); + + youcorn.dispatchEvent( 'timeupdate' ); }, timeupdateInterval); } function startProgressUpdater( youcorn ) { youcorn.progressUpdater = setInterval(function() { - var bytesLoaded = youcorn.video.getVideoBytesLoaded(); - var bytesToLoad = youcorn.video.getVideoBytesTotal(); - if ( debug ) { - console.log( 'Bytes loaded: ' + bytesLoaded ); - console.log( 'Bytes to load: ' + bytesToLoad ); - } + var bytesLoaded = youcorn.video.getVideoBytesLoaded(), + bytesToLoad = youcorn.video.getVideoBytesTotal(); // do nothing if size is not yet determined if ( bytesToLoad == 0 ) { @@ -241,19 +345,19 @@ // raise an event if load has just started if ( !youcorn.loadStarted ) { youcorn.loadStarted = true; - youcorn.raiseEvent( 'loadstart' ); + youcorn.dispatchEvent( 'loadstart' ); } // fully loaded if ( bytesLoaded >= bytesToLoad ) { youcorn.fullyLoaded = true; youcorn.readyState = READY_STATE_HAVE_ENOUGH_DATA; - youcorn.raiseEvent( 'canplaythrough' ); + youcorn.dispatchEvent( 'canplaythrough' ); clearInterval( youcorn.progressUpdater ); return; } - youcorn.raiseEvent( 'progress' ); + youcorn.dispatchEvent( 'progress' ); }, progressInterval); } @@ -268,7 +372,6 @@ * * canplay * * seeking * * ratechange - * * durationchange */ })( Popcorn ); diff --git a/players/youtube/popcorn.youtube.unit.html b/players/youtube/popcorn.youtube.unit.html index 16e1751..93d5b1d 100644 --- a/players/youtube/popcorn.youtube.unit.html +++ b/players/youtube/popcorn.youtube.unit.html @@ -30,7 +30,7 @@

diff --git a/players/youtube/popcorn.youtube.unit.js b/players/youtube/popcorn.youtube.unit.js index 7aba180..29e4b6a 100644 --- a/players/youtube/popcorn.youtube.unit.js +++ b/players/youtube/popcorn.youtube.unit.js @@ -1,7 +1,9 @@ -var ytReady = false; -function onYouTubePlayerReady() { +var ytReady = false, + popcorn = Popcorn( Popcorn.youtube( 'video' ) ); + +popcorn.listen( "load", function onYouTubePlayerReady() { ytReady = true; -} +}); test( "Popcorn YouTube Plugin Startup", function() { var time = 0, @@ -34,8 +36,7 @@ test( "Popcorn YouTube Plugin Event Tests", function() { ok( false, "YouTube did not start." ); return; } - - var popcorn = Popcorn( new Popcorn.youtube( 'video' ) ); + popcorn.volume(1); // is muted later // check time sync @@ -59,13 +60,16 @@ test( "Popcorn YouTube Plugin Event Tests", function() { 'play', 'playing', 'seeked', + 'volumechange', + 'volumechange', + 'volumechange', 'playing', 'pause', 'ended' ]; var expectedEventCount = expectedEvents.length; - expect(expectedEventCount + 2); + expect(expectedEventCount + 5); // register each events var eventCount = 0; @@ -79,7 +83,7 @@ test( "Popcorn YouTube Plugin Event Tests", function() { } } - popcorn.listen( event, function() { + popcorn.listen( event, function() { eventCount++; var expected = expectedEvents.shift(); if ( expected == event ) { @@ -92,9 +96,6 @@ test( "Popcorn YouTube Plugin Event Tests", function() { })( expectedEvents[i] ); } - // begin the test - popcorn.play(); - // operations set1 var set1Executed = false; popcorn.listen( 'playing', function() { @@ -105,7 +106,7 @@ test( "Popcorn YouTube Plugin Event Tests", function() { // toggle volume 1 second after playing setTimeout(function() { - popcorn.volume(0); + popcorn.volume(0.5); }, 1000); // pause 3 seconds after playing @@ -116,6 +117,9 @@ test( "Popcorn YouTube Plugin Event Tests", function() { set1Executed = true; }); + // begin the test + popcorn.play(); + // operations set2 var set2Executed = false; popcorn.listen( 'pause', function() { @@ -135,6 +139,25 @@ test( "Popcorn YouTube Plugin Event Tests", function() { set2Executed = true; }); + + // operations set3 + var set3Executed = false; + popcorn.listen( 'seeked', function() { + if ( set3Executed ) { + return; + } + + popcorn.volume(1); + + popcorn.mute(); + equals( popcorn.volume(), 0, "Muted" ); + + popcorn.mute(); + ok( popcorn.volume() !== 0, "Not Muted" ); + equals( popcorn.volume(), 1, "Back to volume of 1" ); + + set3Executed = true; + }); var time = 0, wait = 100, @@ -154,3 +177,37 @@ test( "Popcorn YouTube Plugin Event Tests", function() { }, wait ); }); +test( "Popcorn YouTube Plugin Url and Duration Tests", function() { + function plus(){ + if ( ++count == expects ) { + start(); + } + } + + QUnit.reset(); + + var count = 0, + expects = 4, + rawTube = Popcorn.youtube( 'video', 'http://www.youtube.com/watch?v=9oar9glUCL0' ); + + expect( expects ); + stop( 5000 ); + + equals( rawTube.vidId, '9oar9glUCL0', 'Video id set' ); + plus(); + + equals( rawTube.duration, Number.MAX_VALUE, 'Duration starts as Max Value'); + plus(); + + rawTube.addEventListener( "playing", function() { + notEqual( rawTube.duration, Number.MAX_VALUE, "Duration has been changed from max value" ); + plus(); + notEqual( rawTube.duration, 0, "Duration is non-zero" ); + plus(); + + rawTube.pause(); + }); + + rawTube.play(); + +}); \ No newline at end of file diff --git a/popcorn.js b/popcorn.js index 64215bc..24ba6c7 100644 --- a/popcorn.js +++ b/popcorn.js @@ -128,17 +128,15 @@ return; } - if ( (typeof entity) == "string" ) { - matches = rIdExp.exec( entity ); + // check if entity is a valid string id + matches = rIdExp.exec( entity ); - if ( matches.length && matches[2] ) { - elem = document.getElementById(matches[2]); - } + // get video element by id or reference + this.video = matches && matches.length && matches[ 2 ] ? + document.getElementById( matches[ 2 ] ) : + entity; - this.video = elem ? elem : null; - } else if ( entity instanceof Object ) { - this.video = entity; - } + Popcorn.addInstance( this ); this.data = { history: [], @@ -165,11 +163,6 @@ // this is so we do not fall off either end var duration = that.video.duration; - - if( typeof that.video.duration === "function") { - duration = that.video.duration(); - } - // Check for no duration info (NaN) var videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1; @@ -186,11 +179,6 @@ tracksByEnd = tracks.byEnd, tracksByStart = tracks.byStart; - - if (typeof this.currentTime === "function") { - currentTime = this.currentTime(); - } - // Playbar advancing if ( previousTime < currentTime ) { @@ -277,9 +265,7 @@ } }; - if ( this.video ) { - isReady( this ); - } + isReady( this ); return this; } @@ -353,7 +339,6 @@ // todo: play, pause, mute should toggle var methods = "load play pause currentTime playbackRate mute volume duration", - noArgMethods = /load|play|pause|mute/, ret = {}; @@ -362,21 +347,18 @@ ret[ name ] = function( arg ) { - var isFunc = typeof this.video[name] === "function"; - - if ( noArgMethods.test( name ) || ( arg !== false && arg !== null && typeof arg !== "undefined" ) ) { - - if ( isFunc ) { - this.video[ name ]( arg ); - } else { - this.video[ name ] = arg; - } + if ( typeof this.video[name] === "function" ) { + this.video[ name ](); return this; } - if ( isFunc ) { - return this.video[ name ](); + + if ( arg !== false && arg !== null && typeof arg !== "undefined" ) { + + this.video[ name ] = arg; + + return this; } return this.video[ name ]; @@ -1175,4 +1157,3 @@ }, false ); })(window, window.document); - diff --git a/test/popcorn.unit.js b/test/popcorn.unit.js index 574b6e6..32294c6 100755 --- a/test/popcorn.unit.js +++ b/test/popcorn.unit.js @@ -375,82 +375,6 @@ test("Stored By Type", function () { }); -test("Passed an object", function () { - - QUnit.reset(); - - var evtMethods = "addEventListener dispatchEvent".split(/\s+/), - methods = "load play pause currentTime playbackRate mute volume duration".split(/\s+/), - attributes = "readyState autoplay".split(/\s+/), - obj = {}, - p, - playEvent, - count = 0, - wants; - - function plus(){ - - if ( ++count === wants ) { - start(); - } - } - - Popcorn.forEach( methods, function( method ) { - obj[method] = (function() { - var calledWithArgs = 0, - calledWithoutArgs = 0; - - return function( arg ) { - if ( arg && !calledWithArgs ) { - calledWithArgs = 1; - ok(true, method+" called with argument"); - plus(); - } else if ( !arg && !calledWithoutArgs ) { - calledWithoutArgs = 1; - ok(true, method+" called without argument"); - plus(); - } - } - })(); - }); - - Popcorn.forEach( evtMethods, function( method ) { - obj[method] = (function() { - var hasCalled = 0; - - return function() { - if ( hasCalled ) { - return; - } - - hasCalled = 1; - ok(true, method+" called"); - plus(); - }; - })() - }); - - Popcorn.forEach( attributes, function( attr ) { - obj[attr] = 3; - }); - - p = Popcorn( obj ); - wants = methods.length*2 + evtMethods.length; - - expect( wants ); - stop( 10000 ); - - p.listen( "play", Popcorn.nop ); - - Popcorn.forEach( methods, function( method ) { - p[method](); - p[method]( 1 ); - }); - - p.trigger( "play" ); -}); - - test("Simulated", function () { QUnit.reset(); -- 2.43.0