- Works in IE9

- Fix issue with Quality Label not changing
- Immediately displays loading spinner on resolution change
- Listens to 'timeupdate', 'loadedmetadata', and 'loadeddata' events when resolution changes, because these events are fired inconsistently depending on device (iOS mostly), browser, and filetype.
- Auto-formatted file (spaces to tabs)
This commit is contained in:
DerekZiemba 2017-03-01 22:01:59 -06:00
parent 85f1e51c8b
commit 03d8a35516

View file

@ -1,367 +1,377 @@
/// <reference path="../videojs-5.14.1.js" />
/* https://github.com/kmoskwiak/videojs-resolution-switcher
* This library is using the dev branch (9/13/2016) because it fixes some IE9 issues. https://github.com/kmoskwiak/videojs-resolution-switcher/blob/dev/lib/videojs-resolution-switcher.js
* (12/20/2016) Modified to fix an issue with the Quality Label not changing.
* (1/13/2017) Modified player.currentResolution to pause video when switching resolution and to show loading spinner.
* (1/20/2017) Modified player.currentResolution to listen to timeupdate, loadedmetadata, and loadeddata to fix iOS safari issue.
*/
/*! videojs-resolution-switcher - 2015-7-26 /*! videojs-resolution-switcher - 2015-7-26
* Copyright (c) 2016 Kasper Moskwiak * Copyright (c) 2016 Kasper Moskwiak
* Modified by Pierre Kraft and Derk-Jan Hartman * Modified by Pierre Kraft and Derk-Jan Hartman
* Licensed under the Apache-2.0 license. */ * Licensed under the Apache-2.0 license.
*/
(function () {
/* jshint eqnull: true*/
/* global require */
'use strict';
var videojs = null;
if (typeof window.videojs === 'undefined' && typeof require === 'function') {
videojs = require('video.js');
} else {
videojs = window.videojs;
}
(function() { (function (window, videojs) {
/* jshint eqnull: true*/ var videoJsResolutionSwitcher,
/* global require */ defaults = {
'use strict'; ui: true
var videojs = null; };
if(typeof window.videojs === 'undefined' && typeof require === 'function') {
videojs = require('video.js');
} else {
videojs = window.videojs;
}
(function(window, videojs) { /*
var videoJsResolutionSwitcher, * Resolution menu item
defaults = { */
ui: true var MenuItem = videojs.getComponent('MenuItem');
}; var ResolutionMenuItem = videojs.extend(MenuItem, {
constructor: function (player, options) {
options.selectable = true;
// Sets this.player_, this.options_ and initializes the component
MenuItem.call(this, player, options);
this.src = options.src;
/* player.on('resolutionchange', videojs.bind(this, this.update));
* Resolution menu item }
*/ });
var MenuItem = videojs.getComponent('MenuItem'); ResolutionMenuItem.prototype.handleClick = function (event) {
var ResolutionMenuItem = videojs.extend(MenuItem, { MenuItem.prototype.handleClick.call(this, event);
constructor: function(player, options){ this.player_.currentResolution(this.options_.label);
options.selectable = true; };
// Sets this.player_, this.options_ and initializes the component ResolutionMenuItem.prototype.update = function () {
MenuItem.call(this, player, options); var selection = this.player_.currentResolution();
this.src = options.src; this.selected(this.options_.label === selection.label);
};
videojs.registerComponent('ResolutionMenuItem', ResolutionMenuItem);
player.on('resolutionchange', videojs.bind(this, this.update)); /*
} * Resolution menu button
} ); */
ResolutionMenuItem.prototype.handleClick = function(event){ var MenuButton = videojs.getComponent('MenuButton');
MenuItem.prototype.handleClick.call(this,event); var ResolutionMenuButton = videojs.extend(MenuButton, {
this.player_.currentResolution(this.options_.label); constructor: function (player, options) {
}; this.label = document.createElement('span');
ResolutionMenuItem.prototype.update = function(){ options.label = 'Quality';
var selection = this.player_.currentResolution(); // Sets this.player_, this.options_ and initializes the component
this.selected(this.options_.label === selection.label); MenuButton.call(this, player, options);
}; this.el().setAttribute('aria-label', 'Quality');
MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem); this.controlText('Quality');
/* if (options.dynamicLabel) {
* Resolution menu button videojs.addClass(this.label, 'vjs-resolution-button-label');
*/ this.el().appendChild(this.label);
var MenuButton = videojs.getComponent('MenuButton'); } else {
var ResolutionMenuButton = videojs.extend(MenuButton, { var staticLabel = document.createElement('span');
constructor: function(player, options){ videojs.addClass(staticLabel, 'vjs-menu-icon');
this.label = document.createElement('span'); this.el().appendChild(staticLabel);
options.label = 'Quality'; }
// Sets this.player_, this.options_ and initializes the component player.on('updateSources', videojs.bind(this, this.update));
MenuButton.call(this, player, options); player.on('resolutionchange', videojs.bind(this, this.updateLabel));
this.el().setAttribute('aria-label','Quality'); }
this.controlText('Quality'); });
ResolutionMenuButton.prototype.createItems = function () {
var menuItems = [];
var labels = (this.sources && this.sources.label) || {};
if(options.dynamicLabel){ // FIXME order is not guaranteed here.
videojs.addClass(this.label, 'vjs-resolution-button-label'); for (var key in labels) {
this.el().appendChild(this.label); if (labels.hasOwnProperty(key)) {
}else{ menuItems.push(new ResolutionMenuItem(
var staticLabel = document.createElement('span'); this.player_,
videojs.addClass(staticLabel, 'vjs-menu-icon'); {
this.el().appendChild(staticLabel); label: key,
} src: labels[key],
player.on('updateSources', videojs.bind( this, this.update ) ); selected: key === (this.currentSelection ? this.currentSelection.label : false)
} })
} ); );
ResolutionMenuButton.prototype.createItems = function(){ }
var menuItems = []; }
var labels = (this.sources && this.sources.label) || {}; return menuItems;
};
ResolutionMenuButton.prototype.update = function () {
this.sources = this.player_.getGroupedSrc();
this.currentSelection = this.player_.currentResolution();
this.label.innerHTML = this.currentSelection ? this.currentSelection.label : '';
return MenuButton.prototype.update.call(this);
};
ResolutionMenuButton.prototype.updateLabel = function () {
var label = this.player_.controlBar.resolutionSwitcher.getElementsByClassName('vjs-resolution-button-label')[0];
label.innerHTML = this.player_.currentResolutionState.label;
};
ResolutionMenuButton.prototype.buildCSSClass = function () {
return MenuButton.prototype.buildCSSClass.call(this) + ' vjs-resolution-button';
};
videojs.registerComponent('ResolutionMenuButton', ResolutionMenuButton);
// FIXME order is not guaranteed here. /**
for (var key in labels) { * Initialize the plugin.
if (labels.hasOwnProperty(key)) { * @param {object} [options] configuration for the plugin
menuItems.push(new ResolutionMenuItem( */
this.player_, videoJsResolutionSwitcher = function (options) {
{ var settings = videojs.mergeOptions(defaults, options),
label: key, player = this,
src: labels[key], groupedSrc = {},
selected: key === (this.currentSelection ? this.currentSelection.label : false) currentSources = {},
}) currentResolutionState = {};
);
}
}
return menuItems;
};
ResolutionMenuButton.prototype.update = function(){
this.sources = this.player_.getGroupedSrc();
this.currentSelection = this.player_.currentResolution();
this.label.innerHTML = this.currentSelection ? this.currentSelection.label : '';
return MenuButton.prototype.update.call(this);
};
ResolutionMenuButton.prototype.buildCSSClass = function(){
return MenuButton.prototype.buildCSSClass.call( this ) + ' vjs-resolution-button';
};
MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton);
/** /**
* Initialize the plugin. * Updates player sources or returns current source URL
* @param {object} [options] configuration for the plugin * @param {Array} [src] array of sources [{src: '', type: '', label: '', res: ''}]
*/ * @returns {Object|String|Array} videojs player object if used as setter or current source URL, object, or array of sources
videoJsResolutionSwitcher = function(options) { */
var settings = videojs.mergeOptions(defaults, options), player.updateSrc = function (src) {
player = this, //Return current src if src is not given
groupedSrc = {}, if (!src) { return player.src(); }
currentSources = {},
currentResolutionState = {};
/** // Only add those sources which we can (maybe) play
* Updates player sources or returns current source URL src = src.filter(function (source) {
* @param {Array} [src] array of sources [{src: '', type: '', label: '', res: ''}] try {
* @returns {Object|String|Array} videojs player object if used as setter or current source URL, object, or array of sources return (player.canPlayType(source.type) !== '');
*/ } catch (e) {
player.updateSrc = function(src){ // If a Tech doesn't yet have canPlayType just add it
//Return current src if src is not given return true;
if(!src){ return player.src(); } }
});
//Sort sources
this.currentSources = src.sort(compareResolutions);
this.groupedSrc = bucketSources(this.currentSources);
// Pick one by default
var chosen = chooseSrc(this.groupedSrc, this.currentSources);
this.currentResolutionState = {
label: chosen.label,
sources: chosen.sources
};
// Only add those sources which we can (maybe) play player.trigger('updateSources');
src = src.filter( function(source) { player.setSourcesSanitized(chosen.sources, chosen.label);
try { player.trigger('resolutionchange');
return ( player.canPlayType( source.type ) !== '' ); return player;
} catch (e) { };
// If a Tech doesn't yet have canPlayType just add it
return true;
}
});
//Sort sources
this.currentSources = src.sort(compareResolutions);
this.groupedSrc = bucketSources(this.currentSources);
// Pick one by default
var chosen = chooseSrc(this.groupedSrc, this.currentSources);
this.currentResolutionState = {
label: chosen.label,
sources: chosen.sources
};
player.trigger('updateSources'); /**
player.setSourcesSanitized(chosen.sources, chosen.label); * Returns current resolution or sets one when label is specified
player.trigger('resolutionchange'); * @param {String} [label] label name
return player; * @param {Function} [customSourcePicker] custom function to choose source. Takes 2 arguments: sources, label. Must return player object.
}; * @returns {Object} current resolution object {label: '', sources: []} if used as getter or player object if used as setter
*/
player.currentResolution = function (label, customSourcePicker) {
if (label == null) { return this.currentResolutionState; }
/** // Lookup sources for label
* Returns current resolution or sets one when label is specified if (!this.groupedSrc || !this.groupedSrc.label || !this.groupedSrc.label[label]) {
* @param {String} [label] label name return;
* @param {Function} [customSourcePicker] custom function to choose source. Takes 2 arguments: sources, label. Must return player object. }
* @returns {Object} current resolution object {label: '', sources: []} if used as getter or player object if used as setter var sources = this.groupedSrc.label[label];
*/ // Remember player state
player.currentResolution = function(label, customSourcePicker){ var currentTime = player.currentTime();
if(label == null) { return this.currentResolutionState; } var isPaused = player.paused();
player.pause();
player.loadingSpinner.show();
// Lookup sources for label // Hide bigPlayButton
if(!this.groupedSrc || !this.groupedSrc.label || !this.groupedSrc.label[label]){ if (!isPaused && this.player_.options_.bigPlayButton) {
return; this.player_.bigPlayButton.hide();
} }
var sources = this.groupedSrc.label[label]; player.setSourcesSanitized(sources, label, customSourcePicker || settings.customSourcePicker);
// Remember player state
var currentTime = player.currentTime();
var isPaused = player.paused();
// Hide bigPlayButton //The event is fired inconsistently across devices and different filetypes. So listen for all of them;
if(!isPaused && this.player_.options_.bigPlayButton){ player.one('timeupdate', handleLoad).one('loadedmetadata', handleLoad).one('loadeddata', handleLoad);
this.player_.bigPlayButton.hide(); function handleLoad() {
} player.off('timeupdate', handleLoad).off('loadedmetadata', handleLoad).off('loadeddata', handleLoad);
player.currentTime(currentTime);
player.handleTechSeeked_();
if (!isPaused) {
// Start playing and hide loadingSpinner (flash issue ?)
player.play().handleTechSeeked_();
}
player.trigger('resolutionchange');
}
return player;
};
// Change player source and wait for loadeddata event, then play video /**
// loadedmetadata doesn't work right now for flash. * Returns grouped sources by label, resolution and type
// Probably because of https://github.com/videojs/video-js-swf/issues/124 * @returns {Object} grouped sources: { label: { key: [] }, res: { key: [] }, type: { key: [] } }
// If player preload is 'none' and then loadeddata not fired. So, we need timeupdate event for seek handle (timeupdate doesn't work properly with flash) */
var handleSeekEvent = 'loadeddata'; player.getGroupedSrc = function () {
if(this.player_.techName_ !== 'Youtube' && this.player_.preload() === 'none' && this.player_.techName_ !== 'Flash') { return this.groupedSrc;
handleSeekEvent = 'timeupdate'; };
}
player
.setSourcesSanitized(sources, label, customSourcePicker || settings.customSourcePicker)
.one(handleSeekEvent, function() {
player.currentTime(currentTime);
player.handleTechSeeked_();
if(!isPaused){
// Start playing and hide loadingSpinner (flash issue ?)
player.play().handleTechSeeked_();
}
player.trigger('resolutionchange');
});
return player;
};
/** player.setSourcesSanitized = function (sources, label, customSourcePicker) {
* Returns grouped sources by label, resolution and type this.currentResolutionState = {
* @returns {Object} grouped sources: { label: { key: [] }, res: { key: [] }, type: { key: [] } } label: label,
*/ sources: sources
player.getGroupedSrc = function(){ };
return this.groupedSrc; if (typeof customSourcePicker === 'function') {
}; return customSourcePicker(player, sources, label);
}
player.src(sources.map(function (src) {
return { src: src.src, type: src.type, res: src.res };
}));
return player;
};
player.setSourcesSanitized = function(sources, label, customSourcePicker) { /**
this.currentResolutionState = { * Method used for sorting list of sources
label: label, * @param {Object} a - source object with res property
sources: sources * @param {Object} b - source object with res property
}; * @returns {Number} result of comparation
if(typeof customSourcePicker === 'function'){ */
return customSourcePicker(player, sources, label); function compareResolutions(a, b) {
} if (!a.res || !b.res) { return 0; }
player.src(sources.map(function(src) { return (+b.res) - (+a.res);
return {src: src.src, type: src.type, res: src.res}; }
}));
return player;
};
/** /**
* Method used for sorting list of sources * Group sources by label, resolution and type
* @param {Object} a - source object with res property * @param {Array} src Array of sources
* @param {Object} b - source object with res property * @returns {Object} grouped sources: { label: { key: [] }, res: { key: [] }, type: { key: [] } }
* @returns {Number} result of comparation */
*/ function bucketSources(src) {
function compareResolutions(a, b){ var resolutions = {
if(!a.res || !b.res){ return 0; } label: {},
return (+b.res)-(+a.res); res: {},
} type: {}
};
src.map(function (source) {
initResolutionKey(resolutions, 'label', source);
initResolutionKey(resolutions, 'res', source);
initResolutionKey(resolutions, 'type', source);
/** appendSourceToKey(resolutions, 'label', source);
* Group sources by label, resolution and type appendSourceToKey(resolutions, 'res', source);
* @param {Array} src Array of sources appendSourceToKey(resolutions, 'type', source);
* @returns {Object} grouped sources: { label: { key: [] }, res: { key: [] }, type: { key: [] } } });
*/ return resolutions;
function bucketSources(src){ }
var resolutions = {
label: {},
res: {},
type: {}
};
src.map(function(source) {
initResolutionKey(resolutions, 'label', source);
initResolutionKey(resolutions, 'res', source);
initResolutionKey(resolutions, 'type', source);
appendSourceToKey(resolutions, 'label', source); function initResolutionKey(resolutions, key, source) {
appendSourceToKey(resolutions, 'res', source); if (resolutions[key][source[key]] == null) {
appendSourceToKey(resolutions, 'type', source); resolutions[key][source[key]] = [];
}); }
return resolutions; }
}
function initResolutionKey(resolutions, key, source) { function appendSourceToKey(resolutions, key, source) {
if(resolutions[key][source[key]] == null) { resolutions[key][source[key]].push(source);
resolutions[key][source[key]] = []; }
}
}
function appendSourceToKey(resolutions, key, source) { /**
resolutions[key][source[key]].push(source); * Choose src if option.default is specified
} * @param {Object} groupedSrc {res: { key: [] }}
* @param {Array} src Array of sources sorted by resolution used to find high and low res
* @returns {Object} {res: string, sources: []}
*/
function chooseSrc(groupedSrc, src) {
var selectedRes = settings['default']; // use array access as default is a reserved keyword
var selectedLabel = '';
if (selectedRes === 'high') {
selectedRes = src[0].res;
selectedLabel = src[0].label;
} else if (selectedRes === 'low' || selectedRes == null || !groupedSrc.res[selectedRes]) {
// Select low-res if default is low or not set
selectedRes = src[src.length - 1].res;
selectedLabel = src[src.length - 1].label;
} else if (groupedSrc.res[selectedRes]) {
selectedLabel = groupedSrc.res[selectedRes][0].label;
}
/** return { res: selectedRes, label: selectedLabel, sources: groupedSrc.res[selectedRes] };
* Choose src if option.default is specified }
* @param {Object} groupedSrc {res: { key: [] }}
* @param {Array} src Array of sources sorted by resolution used to find high and low res
* @returns {Object} {res: string, sources: []}
*/
function chooseSrc(groupedSrc, src){
var selectedRes = settings['default']; // use array access as default is a reserved keyword
var selectedLabel = '';
if (selectedRes === 'high') {
selectedRes = src[0].res;
selectedLabel = src[0].label;
} else if (selectedRes === 'low' || selectedRes == null || !groupedSrc.res[selectedRes]) {
// Select low-res if default is low or not set
selectedRes = src[src.length - 1].res;
selectedLabel = src[src.length -1].label;
} else if (groupedSrc.res[selectedRes]) {
selectedLabel = groupedSrc.res[selectedRes][0].label;
}
return {res: selectedRes, label: selectedLabel, sources: groupedSrc.res[selectedRes]}; function initResolutionForYt(player) {
} // Map youtube qualities names
var _yts = {
highres: { res: 1080, label: '1080', yt: 'highres' },
hd1080: { res: 1080, label: '1080', yt: 'hd1080' },
hd720: { res: 720, label: '720', yt: 'hd720' },
large: { res: 480, label: '480', yt: 'large' },
medium: { res: 360, label: '360', yt: 'medium' },
small: { res: 240, label: '240', yt: 'small' },
tiny: { res: 144, label: '144', yt: 'tiny' },
auto: { res: 0, label: 'auto', yt: 'auto' }
};
// Overwrite default sourcePicker function
var _customSourcePicker = function (_player, _sources, _label) {
// Note that setPlayebackQuality is a suggestion. YT does not always obey it.
player.tech_.ytPlayer.setPlaybackQuality(_sources[0]._yt);
player.trigger('updateSources');
return player;
};
settings.customSourcePicker = _customSourcePicker;
function initResolutionForYt(player){ // Init resolution
// Map youtube qualities names player.tech_.ytPlayer.setPlaybackQuality('auto');
var _yts = {
highres: {res: 1080, label: '1080', yt: 'highres'},
hd1080: {res: 1080, label: '1080', yt: 'hd1080'},
hd720: {res: 720, label: '720', yt: 'hd720'},
large: {res: 480, label: '480', yt: 'large'},
medium: {res: 360, label: '360', yt: 'medium'},
small: {res: 240, label: '240', yt: 'small'},
tiny: {res: 144, label: '144', yt: 'tiny'},
auto: {res: 0, label: 'auto', yt: 'auto'}
};
// Overwrite default sourcePicker function
var _customSourcePicker = function(_player, _sources, _label){
// Note that setPlayebackQuality is a suggestion. YT does not always obey it.
player.tech_.ytPlayer.setPlaybackQuality(_sources[0]._yt);
player.trigger('updateSources');
return player;
};
settings.customSourcePicker = _customSourcePicker;
// Init resolution // This is triggered when the resolution actually changes
player.tech_.ytPlayer.setPlaybackQuality('auto'); player.tech_.ytPlayer.addEventListener('onPlaybackQualityChange', function (event) {
for (var res in _yts) {
if (res.yt === event.data) {
player.currentResolution(res.label, _customSourcePicker);
return;
}
}
});
// This is triggered when the resolution actually changes // We must wait for play event
player.tech_.ytPlayer.addEventListener('onPlaybackQualityChange', function(event){ player.one('play', function () {
for(var res in _yts) { var qualities = player.tech_.ytPlayer.getAvailableQualityLevels();
if(res.yt === event.data) { var _sources = [];
player.currentResolution(res.label, _customSourcePicker);
return;
}
}
});
// We must wait for play event qualities.map(function (q) {
player.one('play', function(){ _sources.push({
var qualities = player.tech_.ytPlayer.getAvailableQualityLevels(); src: player.src().src,
var _sources = []; type: player.src().type,
label: _yts[q].label,
res: _yts[q].res,
_yt: _yts[q].yt
});
});
qualities.map(function(q){ player.groupedSrc = bucketSources(_sources);
_sources.push({ var chosen = { label: 'auto', res: 0, sources: player.groupedSrc.label.auto };
src: player.src().src,
type: player.src().type,
label: _yts[q].label,
res: _yts[q].res,
_yt: _yts[q].yt
});
});
player.groupedSrc = bucketSources(_sources); this.currentResolutionState = {
var chosen = {label: 'auto', res: 0, sources: player.groupedSrc.label.auto}; label: chosen.label,
sources: chosen.sources
};
this.currentResolutionState = { player.trigger('updateSources');
label: chosen.label, player.setSourcesSanitized(chosen.sources, chosen.label, _customSourcePicker);
sources: chosen.sources });
}; }
player.trigger('updateSources'); player.ready(function () {
player.setSourcesSanitized(chosen.sources, chosen.label, _customSourcePicker); if (settings.ui) {
}); var menuButton = new ResolutionMenuButton(player, settings);
} player.controlBar.resolutionSwitcher = player.controlBar.el_.insertBefore(menuButton.el_, player.controlBar.getChild('fullscreenToggle').el_);
player.controlBar.resolutionSwitcher.dispose = function () {
this.parentNode.removeChild(this);
};
}
if (player.options_.sources.length > 1) {
// tech: Html5 and Flash
// Create resolution switcher for videos form <source> tag inside <video>
player.updateSrc(player.options_.sources);
}
player.ready(function(){ if (player.techName_ === 'Youtube') {
if( settings.ui ) { // tech: YouTube
var menuButton = new ResolutionMenuButton(player, settings); initResolutionForYt(player);
player.controlBar.resolutionSwitcher = player.controlBar.el_.insertBefore(menuButton.el_, player.controlBar.getChild('fullscreenToggle').el_); }
player.controlBar.resolutionSwitcher.dispose = function(){ });
this.parentNode.removeChild(this);
};
}
if(player.options_.sources.length > 1){
// tech: Html5 and Flash
// Create resolution switcher for videos form <source> tag inside <video>
player.updateSrc(player.options_.sources);
}
if(player.techName_ === 'Youtube'){ };
// tech: YouTube
initResolutionForYt(player);
}
});
}; // register the plugin
videojs.plugin('videoJsResolutionSwitcher', videoJsResolutionSwitcher);
// register the plugin })(window, videojs);
videojs.plugin('videoJsResolutionSwitcher', videoJsResolutionSwitcher);
})(window, videojs);
})(); })();