popcorn.jplayer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. /*
  2. * jPlayer Player Plugin for Popcorn JavaScript Library
  3. * http://www.jplayer.org
  4. *
  5. * Copyright (c) 2012 - 2014 Happyworm Ltd
  6. * Licensed under the MIT license.
  7. * http://opensource.org/licenses/MIT
  8. *
  9. * Author: Mark J Panaghiston
  10. * Version: 1.1.3
  11. * Date: 2nd April 2014
  12. *
  13. * For Popcorn Version: 1.3
  14. * For jPlayer Version: 2.6.0
  15. * Requires: jQuery 1.7+
  16. * Note: jQuery dependancy cannot be removed since jPlayer 2 is a jQuery plugin. Use of jQuery will be kept to a minimum.
  17. */
  18. /* Code verified using http://www.jshint.com/ */
  19. /*jshint asi:false, bitwise:false, boss:false, browser:true, curly:false, debug:false, eqeqeq:true, eqnull:false, evil:false, forin:false, immed:false, jquery:true, laxbreak:false, newcap:true, noarg:true, noempty:true, nonew:true, onevar:false, passfail:false, plusplus:false, regexp:false, undef:true, sub:false, strict:false, white:false, smarttabs:true */
  20. /*global Popcorn:false, console:false */
  21. (function(Popcorn) {
  22. var JQUERY_SCRIPT = '//code.jquery.com/jquery-1.11.0.min.js', // Used if jQuery not already present.
  23. JPLAYER_SCRIPT = '//www.jplayer.org/2.6.0/js/jquery.jplayer.min.js', // Used if jPlayer not already present.
  24. JPLAYER_SWFPATH = '//www.jplayer.org/2.6.0/js/Jplayer.swf', // Used if not specified in jPlayer options via SRC Object.
  25. SOLUTION = 'html,flash', // The default solution option.
  26. DEBUG = false, // Decided to leave the debugging option and console output in for the time being. Overhead is trivial.
  27. jQueryDownloading = false, // Flag to stop multiple instances from each pulling in jQuery, thus corrupting it.
  28. jPlayerDownloading = false, // Flag to stop multiple instances from each pulling in jPlayer, thus corrupting it.
  29. format = { // Duplicate of jPlayer 2.5.0 object, to avoid always requiring jQuery and jPlayer to be loaded before performing the _canPlayType() test.
  30. mp3: {
  31. codec: 'audio/mpeg; codecs="mp3"',
  32. flashCanPlay: true,
  33. media: 'audio'
  34. },
  35. m4a: { // AAC / MP4
  36. codec: 'audio/mp4; codecs="mp4a.40.2"',
  37. flashCanPlay: true,
  38. media: 'audio'
  39. },
  40. m3u8a: { // AAC / MP4 / Apple HLS
  41. codec: 'application/vnd.apple.mpegurl; codecs="mp4a.40.2"',
  42. flashCanPlay: false,
  43. media: 'audio'
  44. },
  45. m3ua: { // M3U
  46. codec: 'audio/mpegurl',
  47. flashCanPlay: false,
  48. media: 'audio'
  49. },
  50. oga: { // OGG
  51. codec: 'audio/ogg; codecs="vorbis, opus"',
  52. flashCanPlay: false,
  53. media: 'audio'
  54. },
  55. flac: { // FLAC
  56. codec: 'audio/x-flac',
  57. flashCanPlay: false,
  58. media: 'audio'
  59. },
  60. wav: { // PCM
  61. codec: 'audio/wav; codecs="1"',
  62. flashCanPlay: false,
  63. media: 'audio'
  64. },
  65. webma: { // WEBM
  66. codec: 'audio/webm; codecs="vorbis"',
  67. flashCanPlay: false,
  68. media: 'audio'
  69. },
  70. fla: { // FLV / F4A
  71. codec: 'audio/x-flv',
  72. flashCanPlay: true,
  73. media: 'audio'
  74. },
  75. rtmpa: { // RTMP AUDIO
  76. codec: 'audio/rtmp; codecs="rtmp"',
  77. flashCanPlay: true,
  78. media: 'audio'
  79. },
  80. m4v: { // H.264 / MP4
  81. codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
  82. flashCanPlay: true,
  83. media: 'video'
  84. },
  85. m3u8v: { // H.264 / AAC / MP4 / Apple HLS
  86. codec: 'application/vnd.apple.mpegurl; codecs="avc1.42E01E, mp4a.40.2"',
  87. flashCanPlay: false,
  88. media: 'video'
  89. },
  90. m3uv: { // M3U
  91. codec: 'audio/mpegurl',
  92. flashCanPlay: false,
  93. media: 'video'
  94. },
  95. ogv: { // OGG
  96. codec: 'video/ogg; codecs="theora, vorbis"',
  97. flashCanPlay: false,
  98. media: 'video'
  99. },
  100. webmv: { // WEBM
  101. codec: 'video/webm; codecs="vorbis, vp8"',
  102. flashCanPlay: false,
  103. media: 'video'
  104. },
  105. flv: { // FLV / F4V
  106. codec: 'video/x-flv',
  107. flashCanPlay: true,
  108. media: 'video'
  109. },
  110. rtmpv: { // RTMP VIDEO
  111. codec: 'video/rtmp; codecs="rtmp"',
  112. flashCanPlay: true,
  113. media: 'video'
  114. }
  115. },
  116. isObject = function(val) { // Basic check for Object
  117. if(val && typeof val === 'object' && val.hasOwnProperty) {
  118. return true;
  119. } else {
  120. return false;
  121. }
  122. },
  123. getMediaType = function(url) { // Function to gleam the media type from the URL
  124. var mediaType = false;
  125. if(/\.mp3$/i.test(url)) {
  126. mediaType = 'mp3';
  127. } else if(/\.mp4$/i.test(url) || /\.m4v$/i.test(url)) {
  128. mediaType = 'm4v';
  129. } else if(/\.m4a$/i.test(url)) {
  130. mediaType = 'm4a';
  131. } else if(/\.ogg$/i.test(url) || /\.oga$/i.test(url)) {
  132. mediaType = 'oga';
  133. } else if(/\.ogv$/i.test(url)) {
  134. mediaType = 'ogv';
  135. } else if(/\.webm$/i.test(url)) {
  136. mediaType = 'webmv';
  137. }
  138. return mediaType;
  139. },
  140. getSupplied = function(url) { // Function to generate a supplied option from an src object. ie., When supplied not specified.
  141. var supplied = '',
  142. separator = '';
  143. if(isObject(url)) {
  144. // Generate supplied option from object's properties. Non-format properties would be ignored by jPlayer. Order is unpredictable.
  145. for(var prop in url) {
  146. if(url.hasOwnProperty(prop)) {
  147. supplied += separator + prop;
  148. separator = ',';
  149. }
  150. }
  151. }
  152. if(DEBUG) console.log('getSupplied(): Generated: supplied = "' + supplied + '"');
  153. return supplied;
  154. };
  155. Popcorn.player( 'jplayer', {
  156. _canPlayType: function( containerType, url ) {
  157. // url : Either a String or an Object structured similar a jPlayer media object. ie., As used by setMedia in jPlayer.
  158. // The url object may also contain a solution and supplied property.
  159. // Define the src object structure here!
  160. var cType = containerType.toLowerCase(),
  161. srcObj = {
  162. media:{},
  163. options:{}
  164. },
  165. rVal = false, // Only a boolean false means it is not supported.
  166. mediaType;
  167. if(cType !== 'video' && cType !== 'audio') {
  168. if(typeof url === 'string') {
  169. // Check it starts with http, so the URL is absolute... Well, it is not a perfect check.
  170. if(/^http.*/i.test(url)) {
  171. mediaType = getMediaType(url);
  172. if(mediaType) {
  173. srcObj.media[mediaType] = url;
  174. srcObj.options.solution = SOLUTION;
  175. srcObj.options.supplied = mediaType;
  176. }
  177. }
  178. } else {
  179. srcObj = url; // Assume the url is an src object.
  180. }
  181. // Check for Object and appropriate minimum data structure.
  182. if(isObject(srcObj) && isObject(srcObj.media)) {
  183. if(!isObject(srcObj.options)) {
  184. srcObj.options = {};
  185. }
  186. if(!srcObj.options.solution) {
  187. srcObj.options.solution = SOLUTION;
  188. }
  189. if(!srcObj.options.supplied) {
  190. srcObj.options.supplied = getSupplied(srcObj.media);
  191. }
  192. // Figure out how jPlayer will play it.
  193. // This may not work properly when both audio and video is supplied. ie., A media player. But it should return truethy and jPlayer can figure it out.
  194. var solution = srcObj.options.solution.toLowerCase().split(","), // Create the solution array, with prority based on the order of the solution string.
  195. supplied = srcObj.options.supplied.toLowerCase().split(","); // Create the supplied formats array, with prority based on the order of the supplied formats string.
  196. for(var sol = 0; sol < solution.length; sol++) {
  197. var solutionType = solution[sol].replace(/^\s+|\s+$/g, ""), //trim
  198. checkingHtml = solutionType === 'html',
  199. checkingFlash = solutionType === 'flash',
  200. mediaElem;
  201. for(var fmt = 0; fmt < supplied.length; fmt++) {
  202. mediaType = supplied[fmt].replace(/^\s+|\s+$/g, ""); //trim
  203. if(format[mediaType]) { // Check format is valid.
  204. // Create an HTML5 media element for the type of media.
  205. if(!mediaElem && checkingHtml) {
  206. mediaElem = document.createElement(format[mediaType].media);
  207. }
  208. // See if the HTML5 media element can play the MIME / Codec type.
  209. // Flash also returns the object if the format is playable, so it is truethy, but that html property is false.
  210. // This assumes Flash is available, but that should be dealt with by jPlayer if that happens.
  211. var htmlCanPlay = !!(mediaElem && mediaElem.canPlayType && mediaElem.canPlayType(format[mediaType].codec)),
  212. htmlWillPlay = htmlCanPlay && checkingHtml,
  213. flashWillPlay = format[mediaType].flashCanPlay && checkingFlash;
  214. // The first one found will match what jPlayer uses.
  215. if(htmlWillPlay || flashWillPlay) {
  216. rVal = {
  217. html: htmlWillPlay,
  218. type: mediaType
  219. };
  220. sol = solution.length; // Exit solution loop
  221. fmt = supplied.length; // Exit supplied loop
  222. }
  223. }
  224. }
  225. }
  226. }
  227. }
  228. return rVal;
  229. },
  230. // _setup: function( options ) { // Warning: options is deprecated.
  231. _setup: function() {
  232. var media = this,
  233. myPlayer, // The jQuery selector of the jPlayer element. Usually a <div>
  234. jPlayerObj, // The jPlayer data instance. For performance and DRY code.
  235. mediaType = 'unknown',
  236. jpMedia = {},
  237. jpOptions = {},
  238. ready = false, // Used during init to override the annoying duration dependance in the track event padding during Popcorn's isReady(). ie., We is ready after loadeddata and duration can then be set real value at leisure.
  239. duration = 0, // For the durationchange event with both HTML5 and Flash solutions. Used with 'ready' to keep control during the Popcorn isReady() via loadeddata event. (Duration=0 is bad.)
  240. durationchangeId = null, // A timeout ID used with delayed durationchange event. (Because of the duration=NaN fudge to avoid Popcorn track event corruption.)
  241. canplaythrough = false,
  242. error = null, // The MediaError object.
  243. dispatchDurationChange = function() {
  244. if(ready) {
  245. if(DEBUG) console.log('Dispatched event : durationchange : ' + duration);
  246. media.dispatchEvent('durationchange');
  247. } else {
  248. if(DEBUG) console.log('DELAYED EVENT (!ready) : durationchange : ' + duration);
  249. clearTimeout(durationchangeId); // Stop multiple triggers causing multiple timeouts running in parallel.
  250. durationchangeId = setTimeout(dispatchDurationChange, 250);
  251. }
  252. },
  253. jPlayerFlashEventsPatch = function() {
  254. /* Events already supported by jPlayer Flash:
  255. * loadstart
  256. * loadedmetadata (M4A, M4V)
  257. * progress
  258. * play
  259. * pause
  260. * seeking
  261. * seeked
  262. * timeupdate
  263. * ended
  264. * volumechange
  265. * error <- See the custom handler in jPlayerInit()
  266. */
  267. /* Events patched:
  268. * loadeddata
  269. * durationchange
  270. * canplaythrough
  271. * playing
  272. */
  273. /* Events NOT patched:
  274. * suspend
  275. * abort
  276. * emptied
  277. * stalled
  278. * loadedmetadata (MP3)
  279. * waiting
  280. * canplay
  281. * ratechange
  282. */
  283. // Triggering patched events through the jPlayer Object so the events are homogeneous. ie., The contain the event.jPlayer data structure.
  284. var checkDuration = function(event) {
  285. if(event.jPlayer.status.duration !== duration) {
  286. duration = event.jPlayer.status.duration;
  287. dispatchDurationChange();
  288. }
  289. },
  290. checkCanPlayThrough = function(event) {
  291. if(!canplaythrough && event.jPlayer.status.seekPercent === 100) {
  292. canplaythrough = true;
  293. setTimeout(function() {
  294. if(DEBUG) console.log('Trigger : canplaythrough');
  295. jPlayerObj._trigger($.jPlayer.event.canplaythrough);
  296. }, 0);
  297. }
  298. };
  299. myPlayer.bind($.jPlayer.event.loadstart, function() {
  300. setTimeout(function() {
  301. if(DEBUG) console.log('Trigger : loadeddata');
  302. jPlayerObj._trigger($.jPlayer.event.loadeddata);
  303. }, 0);
  304. })
  305. .bind($.jPlayer.event.progress, function(event) {
  306. checkDuration(event);
  307. checkCanPlayThrough(event);
  308. })
  309. .bind($.jPlayer.event.timeupdate, function(event) {
  310. checkDuration(event);
  311. checkCanPlayThrough(event);
  312. })
  313. .bind($.jPlayer.event.play, function() {
  314. setTimeout(function() {
  315. if(DEBUG) console.log('Trigger : playing');
  316. jPlayerObj._trigger($.jPlayer.event.playing);
  317. }, 0);
  318. });
  319. if(DEBUG) console.log('Created CUSTOM event handlers for FLASH');
  320. },
  321. jPlayerInit = function() {
  322. (function($) {
  323. myPlayer = $('#' + media.id);
  324. if(typeof media.src === 'string') {
  325. mediaType = getMediaType(media.src);
  326. jpMedia[mediaType] = media.src;
  327. jpOptions.supplied = mediaType;
  328. jpOptions.solution = SOLUTION;
  329. } else if(isObject(media.src)) {
  330. jpMedia = isObject(media.src.media) ? media.src.media : {};
  331. jpOptions = isObject(media.src.options) ? media.src.options : {};
  332. jpOptions.solution = jpOptions.solution || SOLUTION;
  333. jpOptions.supplied = jpOptions.supplied || getSupplied(media.src.media);
  334. }
  335. // Allow the swfPath to be set to local server. ie., If the jPlayer Plugin is local and already on the page, then you can also use the local SWF.
  336. jpOptions.swfPath = jpOptions.swfPath || JPLAYER_SWFPATH;
  337. myPlayer.bind($.jPlayer.event.ready, function(event) {
  338. if(event.jPlayer.flash.used) {
  339. jPlayerFlashEventsPatch();
  340. }
  341. // Set the media andd load it, so that the Flash solution behaves similar to HTML5 solution.
  342. // This also allows the loadstart event to be used to know jPlayer is ready.
  343. $(this).jPlayer('setMedia', jpMedia).jPlayer('load');
  344. });
  345. // Do not auto-bubble the reserved events, nor the loadeddata and durationchange event, since the duration must be carefully handled when loadeddata event occurs.
  346. // See the duration property code for more details. (Ranting.)
  347. var reservedEvents = $.jPlayer.reservedEvent + ' loadeddata durationchange',
  348. reservedEvent = reservedEvents.split(/\s+/g);
  349. // Generate event handlers for all the standard HTML5 media events. (Except durationchange)
  350. var bindEvent = function(name) {
  351. myPlayer.bind($.jPlayer.event[name], function(event) {
  352. if(DEBUG) console.log('Dispatched event: ' + name + (event && event.jPlayer ? ' (' + event.jPlayer.status.currentTime + 's)' : '')); // Must be after dispatch for some reason on Firefox/Opera
  353. media.dispatchEvent(name);
  354. });
  355. if(DEBUG) console.log('Created event handler for: ' + name);
  356. };
  357. for(var eventName in $.jPlayer.event) {
  358. if($.jPlayer.event.hasOwnProperty(eventName)) {
  359. var nativeEvent = true;
  360. for(var iRes in reservedEvent) {
  361. if(reservedEvent.hasOwnProperty(iRes)) {
  362. if(reservedEvent[iRes] === eventName) {
  363. nativeEvent = false;
  364. break;
  365. }
  366. }
  367. }
  368. if(nativeEvent) {
  369. bindEvent(eventName);
  370. } else {
  371. if(DEBUG) console.log('Skipped auto event handler creation for: ' + eventName);
  372. }
  373. }
  374. }
  375. myPlayer.bind($.jPlayer.event.loadeddata, function(event) {
  376. if(DEBUG) console.log('Dispatched event: loadeddata' + (event && event.jPlayer ? ' (' + event.jPlayer.status.currentTime + 's)' : ''));
  377. media.dispatchEvent('loadeddata');
  378. ready = true;
  379. });
  380. if(DEBUG) console.log('Created CUSTOM event handler for: loadeddata');
  381. myPlayer.bind($.jPlayer.event.durationchange, function(event) {
  382. duration = event.jPlayer.status.duration;
  383. dispatchDurationChange();
  384. });
  385. if(DEBUG) console.log('Created CUSTOM event handler for: durationchange');
  386. // The error event is a special case. Plus jPlayer error event assumes it is a broken URL. (It could also be a decoder error... Or aborted or a Network error.)
  387. myPlayer.bind($.jPlayer.event.error, function(event) {
  388. // Not sure how to handle the error situation. Popcorn does not appear to have the error or error.code property documented here: http://popcornjs.org/popcorn-docs/media-methods/
  389. // If any error event happens, then something has gone pear shaped.
  390. error = event.jPlayer.error; // Saving object pointer, not a copy of the object. Possible garbage collection issue... But the player is dead anyway, so don't care.
  391. if(error.type === $.jPlayer.error.URL) {
  392. error.code = 4; // MEDIA_ERR_SRC_NOT_SUPPORTED since jPlayer makes this assumption. It is the most common error, then the decode error. Never seen either of the other 2 error types occur.
  393. } else {
  394. error.code = 0; // It was a jPlayer error, not an HTML5 media error.
  395. }
  396. if(DEBUG) console.log('Dispatched event: error');
  397. if(DEBUG) console.dir(error);
  398. media.dispatchEvent('error');
  399. });
  400. if(DEBUG) console.log('Created CUSTOM event handler for: error');
  401. Popcorn.player.defineProperty( media, 'error', {
  402. set: function() {
  403. // Read-only property
  404. return error;
  405. },
  406. get: function() {
  407. return error;
  408. }
  409. });
  410. Popcorn.player.defineProperty( media, 'currentTime', {
  411. set: function( val ) {
  412. if(jPlayerObj.status.paused) {
  413. myPlayer.jPlayer('pause', val);
  414. } else {
  415. myPlayer.jPlayer('play', val);
  416. }
  417. return val;
  418. },
  419. get: function() {
  420. return jPlayerObj.status.currentTime;
  421. }
  422. });
  423. /* The joy of duration and the loadeddata event isReady() handler
  424. * The duration is assumed to be a NaN or a valid duration.
  425. * jPlayer uses zero instead of a NaN and this screws up the Popcorn track event start/end arrays padding.
  426. * This line here:
  427. * videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1;
  428. * Not sure why it is not simply:
  429. * videoDurationPlus = Number.MAX_VALUE; // Who cares if the padding is close to the real duration?
  430. * So if you trigger loadeddata before the duration is correct, the track event padding is screwed up. (It pads the start, not the end... Well, duration+1 = 0+1 = 1s)
  431. * That line makes the MP3 Flash fallback difficult to setup. The whole MP3 will need to load before the duration is known.
  432. * Planning on using a NaN for duration until a >0 value is found... Except with MP3, where seekPercent must be 100% before setting the duration.
  433. * Why not just use a NaN during init... And then correct the duration later?
  434. */
  435. Popcorn.player.defineProperty( media, 'duration', {
  436. set: function() {
  437. // Read-only property
  438. if(ready) {
  439. return duration;
  440. } else {
  441. return NaN;
  442. }
  443. },
  444. get: function() {
  445. if(ready) {
  446. return duration; // Popcorn has initialized, we can now use duration zero or whatever without fear.
  447. } else {
  448. return NaN; // Keep the duration a NaN until after loadeddata event has occurred. Otherwise Popcorn track event padding is corrupted.
  449. }
  450. }
  451. });
  452. Popcorn.player.defineProperty( media, 'muted', {
  453. set: function( val ) {
  454. myPlayer.jPlayer('mute', val);
  455. return jPlayerObj.options.muted;
  456. },
  457. get: function() {
  458. return jPlayerObj.options.muted;
  459. }
  460. });
  461. Popcorn.player.defineProperty( media, 'volume', {
  462. set: function( val ) {
  463. myPlayer.jPlayer('volume', val);
  464. return jPlayerObj.options.volume;
  465. },
  466. get: function() {
  467. return jPlayerObj.options.volume;
  468. }
  469. });
  470. Popcorn.player.defineProperty( media, 'paused', {
  471. set: function() {
  472. // Read-only property
  473. return jPlayerObj.status.paused;
  474. },
  475. get: function() {
  476. return jPlayerObj.status.paused;
  477. }
  478. });
  479. media.play = function() {
  480. myPlayer.jPlayer('play');
  481. };
  482. media.pause = function() {
  483. myPlayer.jPlayer('pause');
  484. };
  485. myPlayer.jPlayer(jpOptions); // Instance jPlayer. Note that the options should not have a ready event defined... Kill it by default?
  486. jPlayerObj = myPlayer.data('jPlayer');
  487. }(jQuery));
  488. },
  489. jPlayerCheck = function() {
  490. if (!jQuery.jPlayer) {
  491. if (!jPlayerDownloading) {
  492. jPlayerDownloading = true;
  493. Popcorn.getScript(JPLAYER_SCRIPT, function() {
  494. jPlayerDownloading = false;
  495. jPlayerInit();
  496. });
  497. } else {
  498. setTimeout(jPlayerCheck, 250);
  499. }
  500. } else {
  501. jPlayerInit();
  502. }
  503. },
  504. jQueryCheck = function() {
  505. if (!window.jQuery) {
  506. if (!jQueryDownloading) {
  507. jQueryDownloading = true;
  508. Popcorn.getScript(JQUERY_SCRIPT, function() {
  509. jQueryDownloading = false;
  510. jPlayerCheck();
  511. });
  512. } else {
  513. setTimeout(jQueryCheck, 250);
  514. }
  515. } else {
  516. jPlayerCheck();
  517. }
  518. };
  519. jQueryCheck();
  520. },
  521. _teardown: function() {
  522. jQuery('#' + this.id).jPlayer('destroy');
  523. }
  524. });
  525. }(Popcorn));