videojs-resolution-switcher.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /* @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt Apache-2.0 */
  2. /*! videojs-resolution-switcher for VideoJS Version 7+ - 2020-7-17
  3. * Copyright (c) 2016 Kasper Moskwiak
  4. * Modified by Bari Artz from Poko - https://facebook.com/pokonimeii
  5. * Licensed under the Apache-2.0 license. */
  6. (function() {
  7. /* jshint eqnull: true*/
  8. /* global require */
  9. 'use strict';
  10. var videojs = null;
  11. if(typeof window.videojs === 'undefined' && typeof require === 'function') {
  12. videojs = require('video.js');
  13. } else {
  14. videojs = window.videojs;
  15. }
  16. (function(window, videojs) {
  17. var videoJsResolutionSwitcher,
  18. defaults = {
  19. ui: true
  20. };
  21. /*
  22. * Resolution menu item
  23. */
  24. var MenuItem = videojs.getComponent('MenuItem');
  25. var ResolutionMenuItem = videojs.extend(MenuItem, {
  26. constructor: function(player, options){
  27. options.selectable = true;
  28. // Sets this.player_, this.options_ and initializes the component
  29. MenuItem.call(this, player, options);
  30. this.src = options.src;
  31. player.on('resolutionchange', videojs.bind(this, this.update));
  32. }
  33. } );
  34. ResolutionMenuItem.prototype.handleClick = function(event){
  35. MenuItem.prototype.handleClick.call(this,event);
  36. this.player_.currentResolution(this.options_.label);
  37. };
  38. ResolutionMenuItem.prototype.update = function(){
  39. var selection = this.player_.currentResolution();
  40. this.selected(this.options_.label === selection.label);
  41. };
  42. MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem);
  43. /*
  44. * Resolution menu button
  45. */
  46. var MenuButton = videojs.getComponent('MenuButton');
  47. var ResolutionMenuButton = videojs.extend(MenuButton, {
  48. constructor: function(player, options){
  49. this.label = document.createElement('span');
  50. options.label = 'Quality';
  51. // Sets this.player_, this.options_ and initializes the component
  52. MenuButton.call(this, player, options);
  53. this.el().setAttribute('aria-label','Quality');
  54. this.controlText('Quality');
  55. if(options.dynamicLabel){
  56. videojs.dom.addClass(this.label, 'vjs-resolution-button-label');
  57. this.el().appendChild(this.label);
  58. }else{
  59. var staticLabel = document.createElement('span');
  60. videojs.dom.addClass(staticLabel, 'vjs-menu-icon');
  61. this.el().appendChild(staticLabel);
  62. }
  63. player.on('updateSources', videojs.bind( this, this.update ) );
  64. }
  65. } );
  66. ResolutionMenuButton.prototype.createItems = function(){
  67. var menuItems = [];
  68. var labels = (this.sources && this.sources.label) || {};
  69. // FIXME order is not guaranteed here.
  70. for (var key in labels) {
  71. if (labels.hasOwnProperty(key)) {
  72. menuItems.push(new ResolutionMenuItem(
  73. this.player_,
  74. {
  75. label: key,
  76. src: labels[key],
  77. selected: key === (this.currentSelection ? this.currentSelection.label : false)
  78. })
  79. );
  80. }
  81. }
  82. return menuItems;
  83. };
  84. ResolutionMenuButton.prototype.update = function(){
  85. this.sources = this.player_.getGroupedSrc();
  86. this.currentSelection = this.player_.currentResolution();
  87. this.label.innerHTML = this.currentSelection ? this.currentSelection.label : '';
  88. return MenuButton.prototype.update.call(this);
  89. };
  90. ResolutionMenuButton.prototype.buildCSSClass = function(){
  91. return MenuButton.prototype.buildCSSClass.call( this ) + ' vjs-resolution-button';
  92. };
  93. MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton);
  94. /**
  95. * Initialize the plugin.
  96. * @param {object} [options] configuration for the plugin
  97. */
  98. videoJsResolutionSwitcher = function(options) {
  99. var settings = videojs.mergeOptions(defaults, options),
  100. player = this,
  101. groupedSrc = {},
  102. currentSources = {},
  103. currentResolutionState = {};
  104. /**
  105. * Updates player sources or returns current source URL
  106. * @param {Array} [src] array of sources [{src: '', type: '', label: '', res: ''}]
  107. * @returns {Object|String|Array} videojs player object if used as setter or current source URL, object, or array of sources
  108. */
  109. player.updateSrc = function(src){
  110. //Return current src if src is not given
  111. if(!src){ return player.src(); }
  112. // Only add those sources which we can (maybe) play
  113. src = src.filter( function(source) {
  114. try {
  115. return ( player.canPlayType( source.type ) !== '' );
  116. } catch (e) {
  117. // If a Tech doesn't yet have canPlayType just add it
  118. return true;
  119. }
  120. });
  121. //Sort sources
  122. this.currentSources = src.sort(compareResolutions);
  123. this.groupedSrc = bucketSources(this.currentSources);
  124. // Pick one by default
  125. var chosen = chooseSrc(this.groupedSrc, this.currentSources);
  126. this.currentResolutionState = {
  127. label: chosen.label,
  128. sources: chosen.sources
  129. };
  130. player.trigger('updateSources');
  131. player.setSourcesSanitized(chosen.sources, chosen.label);
  132. player.trigger('resolutionchange');
  133. return player;
  134. };
  135. /**
  136. * Returns current resolution or sets one when label is specified
  137. * @param {String} [label] label name
  138. * @param {Function} [customSourcePicker] custom function to choose source. Takes 2 arguments: sources, label. Must return player object.
  139. * @returns {Object} current resolution object {label: '', sources: []} if used as getter or player object if used as setter
  140. */
  141. player.currentResolution = function(label, customSourcePicker){
  142. if(label == null) { return this.currentResolutionState; }
  143. // Lookup sources for label
  144. if(!this.groupedSrc || !this.groupedSrc.label || !this.groupedSrc.label[label]){
  145. return;
  146. }
  147. var sources = this.groupedSrc.label[label];
  148. // Remember player state
  149. var currentTime = player.currentTime();
  150. var isPaused = player.paused();
  151. // Hide bigPlayButton
  152. if(!isPaused && this.player_.options_.bigPlayButton){
  153. this.player_.bigPlayButton.hide();
  154. }
  155. // Change player source and wait for loadeddata event, then play video
  156. // loadedmetadata doesn't work right now for flash.
  157. // Probably because of https://github.com/videojs/video-js-swf/issues/124
  158. // 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)
  159. var handleSeekEvent = 'loadeddata';
  160. if(this.player_.techName_ !== 'Youtube' && this.player_.preload() === 'none' && this.player_.techName_ !== 'Flash') {
  161. handleSeekEvent = 'timeupdate';
  162. }
  163. player
  164. .setSourcesSanitized(sources, label, customSourcePicker || settings.customSourcePicker)
  165. .one(handleSeekEvent, function() {
  166. player.currentTime(currentTime);
  167. if (!isPaused && player.paused()) {
  168. player.play()
  169. }
  170. player.trigger('resolutionchange');
  171. });
  172. return player;
  173. };
  174. /**
  175. * Returns grouped sources by label, resolution and type
  176. * @returns {Object} grouped sources: { label: { key: [] }, res: { key: [] }, type: { key: [] } }
  177. */
  178. player.getGroupedSrc = function(){
  179. return this.groupedSrc;
  180. };
  181. player.setSourcesSanitized = function(sources, label, customSourcePicker) {
  182. this.currentResolutionState = {
  183. label: label,
  184. sources: sources
  185. };
  186. if(typeof customSourcePicker === 'function'){
  187. return customSourcePicker(player, sources, label);
  188. }
  189. player.src(sources.map(function(src) {
  190. return {src: src.src, type: src.type, res: src.res};
  191. }));
  192. return player;
  193. };
  194. /**
  195. * Method used for sorting list of sources
  196. * @param {Object} a - source object with res property
  197. * @param {Object} b - source object with res property
  198. * @returns {Number} result of comparation
  199. */
  200. function compareResolutions(a, b){
  201. if(!a.res || !b.res){ return 0; }
  202. return (+b.res)-(+a.res);
  203. }
  204. /**
  205. * Group sources by label, resolution and type
  206. * @param {Array} src Array of sources
  207. * @returns {Object} grouped sources: { label: { key: [] }, res: { key: [] }, type: { key: [] } }
  208. */
  209. function bucketSources(src){
  210. var resolutions = {
  211. label: {},
  212. res: {},
  213. type: {}
  214. };
  215. src.map(function(source) {
  216. initResolutionKey(resolutions, 'label', source);
  217. initResolutionKey(resolutions, 'res', source);
  218. initResolutionKey(resolutions, 'type', source);
  219. appendSourceToKey(resolutions, 'label', source);
  220. appendSourceToKey(resolutions, 'res', source);
  221. appendSourceToKey(resolutions, 'type', source);
  222. });
  223. return resolutions;
  224. }
  225. function initResolutionKey(resolutions, key, source) {
  226. if(resolutions[key][source[key]] == null) {
  227. resolutions[key][source[key]] = [];
  228. }
  229. }
  230. function appendSourceToKey(resolutions, key, source) {
  231. resolutions[key][source[key]].push(source);
  232. }
  233. /**
  234. * Choose src if option.default is specified
  235. * @param {Object} groupedSrc {res: { key: [] }}
  236. * @param {Array} src Array of sources sorted by resolution used to find high and low res
  237. * @returns {Object} {res: string, sources: []}
  238. */
  239. function chooseSrc(groupedSrc, src){
  240. var selectedRes = settings['default']; // use array access as default is a reserved keyword
  241. var selectedLabel = '';
  242. if (selectedRes === 'high') {
  243. selectedRes = src[0].res;
  244. selectedLabel = src[0].label;
  245. } else if (selectedRes === 'low' || selectedRes == null || !groupedSrc.res[selectedRes]) {
  246. // Select low-res if default is low or not set
  247. selectedRes = src[src.length - 1].res;
  248. selectedLabel = src[src.length -1].label;
  249. } else if (groupedSrc.res[selectedRes]) {
  250. selectedLabel = groupedSrc.res[selectedRes][0].label;
  251. }
  252. return {res: selectedRes, label: selectedLabel, sources: groupedSrc.res[selectedRes]};
  253. }
  254. function initResolutionForYt(player){
  255. // Map youtube qualities names
  256. var _yts = {
  257. highres: {res: 1080, label: '1080', yt: 'highres'},
  258. hd1080: {res: 1080, label: '1080', yt: 'hd1080'},
  259. hd720: {res: 720, label: '720', yt: 'hd720'},
  260. large: {res: 480, label: '480', yt: 'large'},
  261. medium: {res: 360, label: '360', yt: 'medium'},
  262. small: {res: 240, label: '240', yt: 'small'},
  263. tiny: {res: 144, label: '144', yt: 'tiny'},
  264. auto: {res: 0, label: 'auto', yt: 'auto'}
  265. };
  266. // Overwrite default sourcePicker function
  267. var _customSourcePicker = function(_player, _sources, _label){
  268. // Note that setPlayebackQuality is a suggestion. YT does not always obey it.
  269. player.tech_.ytPlayer.setPlaybackQuality(_sources[0]._yt);
  270. player.trigger('updateSources');
  271. return player;
  272. };
  273. settings.customSourcePicker = _customSourcePicker;
  274. // Init resolution
  275. player.tech_.ytPlayer.setPlaybackQuality('auto');
  276. // This is triggered when the resolution actually changes
  277. player.tech_.ytPlayer.addEventListener('onPlaybackQualityChange', function(event){
  278. for(var res in _yts) {
  279. if(res.yt === event.data) {
  280. player.currentResolution(res.label, _customSourcePicker);
  281. return;
  282. }
  283. }
  284. });
  285. // We must wait for play event
  286. player.one('play', function(){
  287. var qualities = player.tech_.ytPlayer.getAvailableQualityLevels();
  288. var _sources = [];
  289. qualities.map(function(q){
  290. _sources.push({
  291. src: player.src().src,
  292. type: player.src().type,
  293. label: _yts[q].label,
  294. res: _yts[q].res,
  295. _yt: _yts[q].yt
  296. });
  297. });
  298. player.groupedSrc = bucketSources(_sources);
  299. var chosen = {label: 'auto', res: 0, sources: player.groupedSrc.label.auto};
  300. this.currentResolutionState = {
  301. label: chosen.label,
  302. sources: chosen.sources
  303. };
  304. player.trigger('updateSources');
  305. player.setSourcesSanitized(chosen.sources, chosen.label, _customSourcePicker);
  306. });
  307. }
  308. player.ready(function(){
  309. if( settings.ui ) {
  310. var menuButton = new ResolutionMenuButton(player, settings);
  311. player.controlBar.resolutionSwitcher = player.controlBar.el_.insertBefore(menuButton.el_, player.controlBar.getChild('fullscreenToggle').el_);
  312. player.controlBar.resolutionSwitcher.dispose = function(){
  313. this.parentNode.removeChild(this);
  314. };
  315. }
  316. if(player.options_.sources.length > 1){
  317. // tech: Html5 and Flash
  318. // Create resolution switcher for videos form <source> tag inside <video>
  319. player.updateSrc(player.options_.sources);
  320. }
  321. if(player.techName_ === 'Youtube'){
  322. // tech: YouTube
  323. initResolutionForYt(player);
  324. }
  325. });
  326. };
  327. // register the plugin
  328. videojs.registerPlugin('videoJsResolutionSwitcher', videoJsResolutionSwitcher);
  329. })(window, videojs);
  330. })();
  331. /* @license-end */