]> khamidou — GitHub mirrors - popcorn-js.git/commitdiff
Initial draft of the normalized approach.
authorBrad Chen <brad5620732@hotmail.com>
Fri, 11 Mar 2011 07:07:11 +0000 (02:07 -0500)
committerBrad Chen <brad5620732@hotmail.com>
Fri, 11 Mar 2011 07:07:11 +0000 (02:07 -0500)
players/youtube/popcorn.youtube.html [new file with mode: 0644]
players/youtube/popcorn.youtube.js [new file with mode: 0644]
players/youtube/popcorn.youtube.unit.html [new file with mode: 0644]
players/youtube/popcorn.youtube.unit.js [new file with mode: 0644]

diff --git a/players/youtube/popcorn.youtube.html b/players/youtube/popcorn.youtube.html
new file mode 100644 (file)
index 0000000..0f82bd0
--- /dev/null
@@ -0,0 +1,87 @@
+<!DOCTYPE html>\r
+<html>\r
+  <head>\r
+    <title>Popcorn Youtube Player Example</title>\r
+      <script src="../../popcorn.js"></script>\r
+      <script type="text/javascript" src="popcorn.youtube.js"></script>\r
+      <script>\r
+        // <![CDATA[\r
+\r
+        /* Some code on this page is taken from stevenaw's vimeo plug-in. */\r
+\r
+        // Helper function to get elements\r
+        function element(id) {\r
+          return document.getElementById(id);\r
+        }\r
+\r
+        // Register YouTube\r
+        function onYouTubePlayerReady() {\r
+          element( 'player-status' ).innerHTML = 'Ready';\r
+\r
+          var youcorn = Popcorn.youtube( 'video' );\r
+          var popcorn = Popcorn(youcorn);\r
+          element( 'player-duration' ).innerHTML = popcorn.duration();\r
+\r
+          // Update time\r
+          popcorn.listen( 'timeupdate', function() {\r
+            element( 'player-time' ).innerHTML = popcorn.currentTime();\r
+          });\r
+\r
+          // Update button labels\r
+          var paused = true;\r
+          popcorn.listen( 'play' , function() {\r
+            paused = false;\r
+            element( 'btn-play-pause' ).innerHTML = 'Pause';\r
+          });\r
+          popcorn.listen('pause', function() {\r
+            paused = true;\r
+            element( 'btn-play-pause' ).innerHTML = 'Play';\r
+          });\r
+\r
+          // Single play/pause button\r
+          element( 'btn-play-pause' ).addEventListener( 'click', function() {\r
+            if (paused) {\r
+              popcorn.play();\r
+            } else {\r
+              popcorn.pause();\r
+            }\r
+          }, false);\r
+\r
+          // Seek\r
+          element('btn-seek').addEventListener('click', function() {\r
+            popcorn.currentTime(30);\r
+          }, false);\r
+\r
+          // Volume\r
+          element('btn-volume').addEventListener('click', function() {\r
+            var volume = (popcorn.volume() === 1) ? 0.5 : 1;\r
+            popcorn.volume(volume);\r
+          }, false);\r
+        }\r
+      // ]]>\r
+    </script>\r
+  </head>\r
+  <body>\r
+    <div>\r
+      <object id="video" type="application/x-shockwave-flash"\r
+        data="http://www.youtube.com/e/ac7KhViaVqc?enablejsapi=1&amp;version=3"\r
+        width="250" height="200">\r
+        <param name="allowFullScreen" value="true" />\r
+        <param name="allowscriptaccess" value="always" />\r
+      </object>\r
+    </div>\r
+    <div>\r
+      <button class="simple" id="btn-play-pause">Play</button>\r
+      <button class="seek" id="btn-seek">Seek to 30</button>\r
+      <button class="volume" id="btn-volume">Toggle Volume</button>\r
+      <div>\r
+        <ul>\r
+          <li>Status: <span id="player-status">Not Ready</span></li>\r
+          <li>Current Time (s): <span id="player-time"></span></li>\r
+          <li>Video Duration (s): <span id="player-duration"></span></li>\r
+        </ul>\r
+      </div>\r
+      <div id="footnotediv" width="50%" height="50%"></div>\r
+    </div>\r
+  </body>\r
+</html>\r
diff --git a/players/youtube/popcorn.youtube.js b/players/youtube/popcorn.youtube.js
new file mode 100644 (file)
index 0000000..67e7d28
--- /dev/null
@@ -0,0 +1,269 @@
+// Popcorn Youtube Player Warpper\r
+\r
+( function( Popcorn ) {\r
+  /**\r
+   * Youtube wrapper for popcorn.\r
+   * This plug-in adds capability for Popcorn.js to deal with Youtube\r
+   * videos. This plug-in also doesn't use Popcorn's plugin() API and\r
+   * instead hacks directly into Popcorn's core.\r
+   *\r
+   * To use this plug-in, onYouTubePlayerReady() event handler needs to be\r
+   * called by the Youtube video player, before videos can be registered.\r
+   * Once videos are registered, calls to them can be made the same way as\r
+   * regular Popcorn objects. Also note that enablejsapi=1 needs to be added\r
+   * to the embed code, in order for Youtube's JavaScript API to work.\r
+   *\r
+   * Note that there are a few methods, properties and events that are not\r
+   * supported. See the bottom of this plug-in for a complete list.\r
+   */\r
+\r
+  // Intended\r
+  var undef;\r
+\r
+  // Config parameters\r
+  var debug = true;\r
+  var timeupdateInterval = 33; // 33 is suitable for 30 fps\r
+  var progressInterval = 250; // as specified by WHATWG\r
+\r
+  // Ready State Constants\r
+  var READY_STATE_HAVE_NOTHING = 0;\r
+  var READY_STATE_HAVE_METADATA = 1;\r
+  var READY_STATE_HAVE_CURRENT_DATA = 2;\r
+  var READY_STATE_HAVE_FUTURE_DATA = 3;\r
+  var READY_STATE_HAVE_ENOUGH_DATA = 4;\r
+\r
+  // Youtube State Constants\r
+  var YOUTUBE_STATE_UNSTARTED = -1;\r
+  var YOUTUBE_STATE_ENDED = 0;\r
+  var YOUTUBE_STATE_PLAYING = 1;\r
+  var YOUTUBE_STATE_PAUSED = 2;\r
+  var YOUTUBE_STATE_BUFFERING = 3;\r
+  var YOUTUBE_STATE_CUED = 5;\r
+\r
+  Popcorn.youtube = function( elementId ) {\r
+    return new Popcorn.youtube.init( elementId );\r
+  };\r
+\r
+  Popcorn.youtube.init = function( elementId ) {\r
+    if ( !elementId ) {\r
+      throw "Element id is invalid.";\r
+    }\r
+\r
+    this.video = document.getElementById( elementId );\r
+    this.readyState = READY_STATE_HAVE_NOTHING;\r
+    this.duration = this.video.getDuration();\r
+    this.eventListeners = {};\r
+    this.loadStarted = false;\r
+    this.loadedData = false;\r
+    this.fullyLoaded = false;\r
+    this.timeUpdater = null;\r
+    this.progressUpdater = null;\r
+    this.registerYoutubeEventHandlers();\r
+    this.registerInternalEventHandlers();\r
+  }; // end Popcorn.youtube.init\r
+\r
+  // For internal use only.\r
+  Popcorn.youtube.init.p.registerYoutubeEventHandlers = function() {\r
+    var youcorn = this,\r
+        stateChangeHandler = 'Popcorn.youtube.stateChangeEventHandler',\r
+        errorHandler = 'Popcorn.youtube.errorEventHandler';\r
+    this.video.addEventListener( 'onStateChange', stateChangeHandler );\r
+    this.video.addEventListener( 'onError', errorHandler );\r
+\r
+    /**\r
+     * Since Flash can only call named functions, they are declared\r
+     * separately here.\r
+     */\r
+    Popcorn.youtube.stateChangeEventHandler = function( state ) {\r
+      if ( debug ) {\r
+        console.log( 'Youtube state updated: ' + state );\r
+      }\r
+      if ( state == YOUTUBE_STATE_UNSTARTED ) {\r
+        youcorn.readyState = READY_STATE_HAVE_METADATA;\r
+        youcorn.raiseEvent('loadedmetadata');\r
+      } else if ( state == YOUTUBE_STATE_ENDED ) {\r
+        youcorn.raiseEvent('ended');\r
+      } else if ( state == YOUTUBE_STATE_PLAYING ) {\r
+        // Being able to play means current data is loaded.\r
+        if ( !this.loadedData ) {\r
+          this.loadedData = true;\r
+          youcorn.raiseEvent( 'loadeddata' );\r
+        }\r
+\r
+        youcorn.readyState = READY_STATE_HAVE_CURRENT_DATA;\r
+        youcorn.raiseEvent( 'playing' );\r
+      } else if ( state == YOUTUBE_STATE_PAUSED ) {\r
+        youcorn.raiseEvent( 'pause' );\r
+      } else if ( state == YOUTUBE_STATE_BUFFERING ) {\r
+        youcorn.raiseEvent( 'waiting' );\r
+      } else if ( state == YOUTUBE_STATE_CUED ) {\r
+        // not handled\r
+      }\r
+    };\r
+\r
+    Popcorn.youtube.errorEventHandler = function( state ) {\r
+      if ( debug ) {\r
+        console.log( 'Youtube error encountered: ' + error );\r
+      }\r
+      youcorn.raiseEvent( 'error' );\r
+    };\r
+  };\r
+\r
+  Popcorn.youtube.init.p = Popcorn.youtube.init.prototype;\r
+\r
+  // For internal use only.\r
+  Popcorn.youtube.init.p.registerInternalEventHandlers = function() {\r
+    this.addEventListener( 'playing', function() {\r
+      startTimeUpdater( this );\r
+    });\r
+    this.addEventListener( 'loadedmetadata', function() {\r
+      startProgressUpdater( this );\r
+    });\r
+  };\r
+\r
+  Popcorn.youtube.init.p.play = function() {\r
+    this.raiseEvent( 'play' );\r
+    this.video.playVideo();\r
+  };\r
+\r
+  Popcorn.youtube.init.p.pause = function() {\r
+    this.video.pauseVideo();\r
+    // pause event is raised by Youtube.\r
+  };\r
+\r
+  Popcorn.youtube.init.p.load = function() {\r
+    this.video.playVideo();\r
+    this.video.pauseVideo();\r
+  };\r
+\r
+  Popcorn.youtube.init.p.currentTime = function( time ) {\r
+    if ( time === undef ) {\r
+      return this.video.getCurrentTime();\r
+    }\r
+    var playing = this.video.getPlayerState() == YOUTUBE_STATE_PLAYING;\r
+    this.video.seekTo( time, true );\r
+\r
+    // Prevent Youtube's behaviour to start playing video after seeking.\r
+    if ( !playing ) {\r
+      this.video.pauseVideo();\r
+    }\r
+\r
+    // Data need to be loaded again.\r
+    if ( !this.fullyLoaded ) {\r
+      this.loadedData = false;\r
+    }\r
+\r
+    // Raise event.\r
+    this.raiseEvent( 'seeked' );\r
+  };\r
+\r
+  Popcorn.youtube.init.p.duration = function() {\r
+    return this.video.getDuration();\r
+  };\r
+\r
+  Popcorn.youtube.init.p.mute = function() {\r
+    if ( this.video.getVolume() != 0 ) {\r
+      this.video.mute();\r
+      this.raiseEvent( 'volumechange' );\r
+    }\r
+  };\r
+\r
+  Popcorn.youtube.init.p.volume = function( vol ) {\r
+    if ( vol == undef ) {\r
+      return this.video.getVolume() / 100;\r
+    }\r
+    if ( vol != this.volume() ) {\r
+      this.video.setVolume( vol * 100 );\r
+      this.raiseEvent( 'volumechange' );\r
+    }\r
+  };\r
+\r
+  Popcorn.youtube.init.p.addEventListener = function( eventName, func ) {\r
+    if ( !this.eventListeners[eventName] ) {\r
+      this.eventListeners[eventName] = [];\r
+    }\r
+    this.eventListeners[eventName].push( func );\r
+  };\r
+\r
+  /**\r
+   * Notify event listeners about an event.\r
+   */\r
+  Popcorn.youtube.init.p.raiseEvent = function( name ) {\r
+    if ( debug ) {\r
+      console.log( 'Raising event: ' + name );\r
+    }\r
+    if ( !this.eventListeners[name] ) {\r
+      return;\r
+    }\r
+    for ( var i in this.eventListeners[name] ) {\r
+      // @TODO should we mimic the event object sent by HTMLMediaElement?\r
+      this.eventListeners[name][i].call( this, null );\r
+    }\r
+  }\r
+\r
+  function startTimeUpdater( youcorn ) {\r
+    youcorn.timeUpdater = setInterval(function() {\r
+      var state = youcorn.video.getPlayerState();\r
+      if ( (state == YOUTUBE_STATE_ENDED) || (state == YOUTUBE_STATE_PAUSED) ) {\r
+        clearInterval(youcorn.timeUpdater);\r
+        return;\r
+      }\r
+      youcorn.raiseEvent( 'timeupdate' );\r
+    }, timeupdateInterval);\r
+  }\r
+\r
+  function startProgressUpdater( youcorn ) {\r
+    youcorn.progressUpdater = setInterval(function() {\r
+      var bytesLoaded = youcorn.video.getVideoBytesLoaded();\r
+      var bytesToLoad = youcorn.video.getVideoBytesTotal();\r
+      if ( debug ) {\r
+        console.log( 'Bytes loaded: ' + bytesLoaded );\r
+        console.log( 'Bytes to load: ' + bytesToLoad );\r
+      }\r
+\r
+      // do nothing if size is not yet determined\r
+      if ( bytesToLoad == 0 ) {\r
+        return;\r
+      }\r
+\r
+      // raise an event if load has just started\r
+      if ( !youcorn.loadStarted ) {\r
+        youcorn.loadStarted = true;\r
+        youcorn.raiseEvent( 'loadstart' );\r
+      }\r
+\r
+      // fully loaded\r
+      if ( bytesLoaded >= bytesToLoad ) {\r
+        youcorn.fullyLoaded = true;\r
+        youcorn.readyState = READY_STATE_HAVE_ENOUGH_DATA;\r
+        youcorn.raiseEvent( 'canplaythrough' );\r
+        clearInterval( youcorn.progressUpdater );\r
+        return;\r
+      }\r
+\r
+      youcorn.raiseEvent( 'progress' );\r
+    }, progressInterval);\r
+  }\r
+\r
+  /* Unsupported properties, methods and events. */\r
+\r
+  Popcorn.youtube.init.p.defaultPlaybackRate = function( arg ) {\r
+  };\r
+\r
+  Popcorn.youtube.init.p.playbackRate = function( arg ) {\r
+  };\r
+\r
+  /**\r
+   * Unsupported events are:\r
+   * * suspend\r
+   * * abort\r
+   * * emptied\r
+   * * stalled\r
+   * * canplay\r
+   * * seeking\r
+   * * ratechange\r
+   * * durationchange\r
+   */\r
+\r
+})( Popcorn );\r
+\r
diff --git a/players/youtube/popcorn.youtube.unit.html b/players/youtube/popcorn.youtube.unit.html
new file mode 100644 (file)
index 0000000..16e1751
--- /dev/null
@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Popcorn YouTube Player</title>
+  <link rel="stylesheet" href="../../test/qunit/qunit.css" type="text/css" media="screen">
+  <script src="../../test/qunit/qunit.js"></script>
+  <!-- 
+    do not move - this must be called immediately prior to popcorn.js.
+  -->
+  <script src="../../popcorn.js"></script>
+  <script src="popcorn.youtube.js"></script>
+  <script src="popcorn.youtube.unit.js"></script>
+</head>
+<body>
+  <h1 id="qunit-header">Popcorn YouTube Player Plugin</h1>
+  <h2 id="qunit-banner"></h2>
+  <div id="qunit-testrunner-toolbar"></div>
+  <h2 id="qunit-userAgent"></h2>
+  <ol id="qunit-tests"></ol>
+  <div id="qunit-fixture"></div>
+  
+  <p>
+    Note about this set of tests:
+  </p>
+  
+  <p>
+    The test assumes that the YouTube video is mostly loaded, before it is run.
+    Therefore, if failures occur for the first time, just run it again. Likely,
+    failures would disappear the second time.
+  </p>
+  <div>
+    <object id="video" type="application/x-shockwave-flash"
+      data="http://www.youtube.com/e/ac7KhViaVqc?enablejsapi=1&amp;version=3"
+      width="250" height="200">
+      <param name="allowFullScreen" value="true" />
+      <param name="allowscriptaccess" value="always" />
+    </object>
+  </div>
+</body>
+</html>
+
diff --git a/players/youtube/popcorn.youtube.unit.js b/players/youtube/popcorn.youtube.unit.js
new file mode 100644 (file)
index 0000000..4ac6662
--- /dev/null
@@ -0,0 +1,156 @@
+var ytReady = false;\r
+function onYouTubePlayerReady() {\r
+  ytReady = true;\r
+}\r
+\r
+test( "Popcorn YouTube Plugin Startup", function() {\r
+  var time = 0,\r
+      wait = 100,\r
+      timeout = 10000;\r
+      \r
+  // wait for YouTube to start\r
+  stop( timeout + wait );\r
+\r
+  // run in an interval check if YouTube has started\r
+  var interval = setInterval(function() {\r
+    time += wait;\r
+\r
+    if ( ytReady ) {\r
+      start();\r
+      ok( true, "YouTube has started." );\r
+      clearInterval( interval );\r
+      return;\r
+    }\r
+\r
+    if ( time > timeout ) {\r
+      ok( false, "YouTube cannot be started." );\r
+      clearInterval( interval );\r
+    }\r
+  }, wait);\r
+});\r
+\r
+test( "Popcorn YouTube Plugin Event Tests", function() {\r
+  if ( !ytReady ) {\r
+    ok( false, "YouTube did not start." );\r
+    return;\r
+  }\r
+\r
+  var popcorn = Popcorn( new Popcorn.youtube( 'video' ) );\r
+  popcorn.volume(1); // is muted later\r
+  \r
+  // check time sync\r
+  popcorn.exec(2, function() {\r
+    ok( popcorn.currentTime() >= 2, "Check time synchronization." );\r
+  });\r
+  popcorn.exec(49, function() {\r
+    ok( popcorn.currentTime() >= 49, "Check time synchronization." );\r
+  });\r
+  popcorn.exec(40, function() {\r
+    ok( false, "This should not be run." );\r
+  });\r
+\r
+  // events must be fired in this order\r
+  var expectedEvents = [\r
+    'play',\r
+    'loadeddata',\r
+    'playing',\r
+    'volumechange',\r
+    'pause',\r
+    'play',\r
+    'playing',\r
+    'seeked',\r
+    'playing',\r
+    'pause',\r
+    'ended'\r
+  ];\r
+\r
+  var expectedEventCount = expectedEvents.length;\r
+  expect(expectedEventCount + 2);\r
+\r
+  // register each events\r
+  var eventCount = 0;\r
+  var added = [];\r
+  for ( var i in expectedEvents ) {\r
+    (function( event ) {\r
+      // skip same listeners already added\r
+      for ( var i in added ) {\r
+        if ( added[i] == event ) {\r
+          return;\r
+        }\r
+      }\r
+      \r
+      popcorn.listen( event, function() {\r
+        eventCount++;\r
+        var expected = expectedEvents.shift();\r
+        if ( expected == event ) {\r
+          ok( true, event + " is fired." );\r
+        } else {\r
+          ok( false, event + " is fired, expecting: " + expected );\r
+        }\r
+      });\r
+      added.push( event );\r
+    })( expectedEvents[i] );\r
+  }\r
+\r
+  // begin the test\r
+  popcorn.play();\r
+\r
+  // operations set1\r
+  var set1Executed = false;\r
+  popcorn.listen( 'playing', function() {\r
+    // prevent double calling\r
+    if ( set1Executed ) {\r
+      return;\r
+    }\r
+\r
+    // toggle volume 1 second after playing\r
+    setTimeout(function() {\r
+      popcorn.volume(0);\r
+    }, 1000);\r
+\r
+    // pause 3 seconds after playing\r
+    setTimeout(function() {\r
+      popcorn.pause();\r
+    }, 3000);\r
+\r
+    set1Executed = true;\r
+  });\r
+\r
+  // operations set2\r
+  var set2Executed = false;\r
+  popcorn.listen( 'pause', function() {\r
+    if ( set2Executed ) {\r
+      return;\r
+    }\r
+\r
+    // continue to play\r
+    setTimeout(function() {\r
+      popcorn.play();\r
+    }, 500);\r
+\r
+    // seek to the end\r
+    setTimeout(function() {\r
+      popcorn.currentTime(48);\r
+    }, 1000);\r
+\r
+    set2Executed = true;\r
+  });\r
+\r
+  var time = 0,\r
+      wait = 100,\r
+      timeout = 15000;\r
+\r
+  stop( timeout + wait );\r
+  var interval = setInterval( function() {\r
+    time += wait;\r
+    if ( time > timeout ) {\r
+      clearInterval( interval );\r
+      return;\r
+    }\r
+    if ( eventCount == expectedEventCount ) {\r
+      start();\r
+      clearInterval( interval );\r
+    }\r
+  }, wait );\r
+});\r
+\r