player.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. 'use strict';
  2. var player_data = JSON.parse(document.getElementById('player_data').textContent);
  3. var video_data = JSON.parse(document.getElementById('video_data').textContent);
  4. var options = {
  5. liveui: true,
  6. playbackRates: [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0],
  7. controlBar: {
  8. children: [
  9. 'playToggle',
  10. 'volumePanel',
  11. 'currentTimeDisplay',
  12. 'timeDivider',
  13. 'durationDisplay',
  14. 'progressControl',
  15. 'remainingTimeDisplay',
  16. 'Spacer',
  17. 'captionsButton',
  18. 'audioTrackButton',
  19. 'qualitySelector',
  20. 'playbackRateMenuButton',
  21. 'fullscreenToggle'
  22. ]
  23. },
  24. html5: {
  25. preloadTextTracks: false,
  26. vhs: {
  27. overrideNative: true
  28. }
  29. }
  30. };
  31. if (player_data.aspect_ratio) {
  32. options.aspectRatio = player_data.aspect_ratio;
  33. }
  34. var embed_url = new URL(location);
  35. embed_url.searchParams.delete('v');
  36. var short_url = location.origin + '/' + video_data.id + embed_url.search;
  37. embed_url = location.origin + '/embed/' + video_data.id + embed_url.search;
  38. var save_player_pos_key = 'save_player_pos';
  39. videojs.Vhs.xhr.beforeRequest = function(options) {
  40. // set local if requested not videoplayback
  41. if (!options.uri.includes('videoplayback')) {
  42. if (!options.uri.includes('local=true'))
  43. options.uri += '?local=true';
  44. }
  45. return options;
  46. };
  47. var player = videojs('player', options);
  48. player.on('error', function () {
  49. if (video_data.params.quality === 'dash') return;
  50. var localNotDisabled = (
  51. !player.currentSrc().includes('local=true') && !video_data.local_disabled
  52. );
  53. var reloadMakesSense = (
  54. player.error().code === MediaError.MEDIA_ERR_NETWORK ||
  55. player.error().code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
  56. );
  57. if (localNotDisabled) {
  58. // add local=true to all current sources
  59. player.src(player.currentSources().map(function (source) {
  60. source.src += '&local=true';
  61. return source;
  62. }));
  63. } else if (reloadMakesSense) {
  64. setTimeout(function () {
  65. console.warn('An error occurred in the player, reloading...');
  66. // After load() all parameters are reset. Save them
  67. var currentTime = player.currentTime();
  68. var playbackRate = player.playbackRate();
  69. var paused = player.paused();
  70. player.load();
  71. if (currentTime > 0.5) currentTime -= 0.5;
  72. player.currentTime(currentTime);
  73. player.playbackRate(playbackRate);
  74. if (!paused) player.play();
  75. }, 5000);
  76. }
  77. });
  78. if (video_data.params.quality === 'dash') {
  79. player.reloadSourceOnError({
  80. errorInterval: 10
  81. });
  82. }
  83. /**
  84. * Function for add time argument to url
  85. *
  86. * @param {String} url
  87. * @param {String} [base]
  88. * @returns {URL} urlWithTimeArg
  89. */
  90. function addCurrentTimeToURL(url, base) {
  91. var urlUsed = new URL(url, base);
  92. urlUsed.searchParams.delete('start');
  93. var currentTime = Math.ceil(player.currentTime());
  94. if (currentTime > 0)
  95. urlUsed.searchParams.set('t', currentTime);
  96. else if (urlUsed.searchParams.has('t'))
  97. urlUsed.searchParams.delete('t');
  98. return urlUsed;
  99. }
  100. /**
  101. * Global variable to save the last timestamp (in full seconds) at which the external
  102. * links were updated by the 'timeupdate' callback below.
  103. *
  104. * It is initialized to 5s so that the video will always restart from the beginning
  105. * if the user hasn't really started watching before switching to the other website.
  106. */
  107. var timeupdate_last_ts = 5;
  108. /**
  109. * Callback that updates the timestamp on all external links
  110. */
  111. player.on('timeupdate', function () {
  112. // Only update once every second
  113. let current_ts = Math.floor(player.currentTime());
  114. if (current_ts > timeupdate_last_ts) timeupdate_last_ts = current_ts;
  115. else return;
  116. // YouTube links
  117. let elem_yt_watch = document.getElementById('link-yt-watch');
  118. let elem_yt_embed = document.getElementById('link-yt-embed');
  119. let base_url_yt_watch = elem_yt_watch.getAttribute('data-base-url');
  120. let base_url_yt_embed = elem_yt_embed.getAttribute('data-base-url');
  121. elem_yt_watch.href = addCurrentTimeToURL(base_url_yt_watch);
  122. elem_yt_embed.href = addCurrentTimeToURL(base_url_yt_embed);
  123. // Invidious links
  124. let domain = window.location.origin;
  125. let elem_iv_embed = document.getElementById('link-iv-embed');
  126. let elem_iv_other = document.getElementById('link-iv-other');
  127. let base_url_iv_embed = elem_iv_embed.getAttribute('data-base-url');
  128. let base_url_iv_other = elem_iv_other.getAttribute('data-base-url');
  129. elem_iv_embed.href = addCurrentTimeToURL(base_url_iv_embed, domain);
  130. elem_iv_other.href = addCurrentTimeToURL(base_url_iv_other, domain);
  131. });
  132. var shareOptions = {
  133. socials: ['fbFeed', 'tw', 'reddit', 'email'],
  134. get url() {
  135. return addCurrentTimeToURL(short_url);
  136. },
  137. title: player_data.title,
  138. description: player_data.description,
  139. image: player_data.thumbnail,
  140. get embedCode() {
  141. // Single quotes inside here required. HTML inserted as is into value attribute of input
  142. return "<iframe id='ivplayer' width='640' height='360' src='" +
  143. addCurrentTimeToURL(embed_url) + "' style='border:none;'></iframe>";
  144. }
  145. };
  146. if (location.pathname.startsWith('/embed/')) {
  147. var overlay_content = '<h1><a rel="noopener" target="_blank" href="' + location.origin + '/watch?v=' + video_data.id + '">' + player_data.title + '</a></h1>';
  148. player.overlay({
  149. overlays: [
  150. { start: 'loadstart', content: overlay_content, end: 'playing', align: 'top'},
  151. { start: 'pause', content: overlay_content, end: 'playing', align: 'top'}
  152. ]
  153. });
  154. }
  155. // Detect mobile users and initialize mobileUi for better UX
  156. // Detection code taken from https://stackoverflow.com/a/20293441
  157. function isMobile() {
  158. try{ document.createEvent('TouchEvent'); return true; }
  159. catch(e){ return false; }
  160. }
  161. if (isMobile()) {
  162. player.mobileUi({ touchControls: { seekSeconds: 5 * player.playbackRate() } });
  163. var buttons = ['playToggle', 'volumePanel', 'captionsButton'];
  164. if (!video_data.params.listen && video_data.params.quality === 'dash') buttons.push('audioTrackButton');
  165. if (video_data.params.listen || video_data.params.quality !== 'dash') buttons.push('qualitySelector');
  166. // Create new control bar object for operation buttons
  167. const ControlBar = videojs.getComponent('controlBar');
  168. let operations_bar = new ControlBar(player, {
  169. children: [],
  170. playbackRates: [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0]
  171. });
  172. buttons.slice(1).forEach(function (child) {operations_bar.addChild(child);});
  173. // Remove operation buttons from primary control bar
  174. var primary_control_bar = player.getChild('controlBar');
  175. buttons.forEach(function (child) {primary_control_bar.removeChild(child);});
  176. var operations_bar_element = operations_bar.el();
  177. operations_bar_element.classList.add('mobile-operations-bar');
  178. player.addChild(operations_bar);
  179. // Playback menu doesn't work when it's initialized outside of the primary control bar
  180. var playback_element = document.getElementsByClassName('vjs-playback-rate')[0];
  181. operations_bar_element.append(playback_element);
  182. // The share and http source selector element can't be fetched till the players ready.
  183. player.one('playing', function () {
  184. var share_element = document.getElementsByClassName('vjs-share-control')[0];
  185. operations_bar_element.append(share_element);
  186. if (!video_data.params.listen && video_data.params.quality === 'dash') {
  187. var http_source_selector = document.getElementsByClassName('vjs-http-source-selector vjs-menu-button')[0];
  188. operations_bar_element.append(http_source_selector);
  189. }
  190. });
  191. }
  192. // Enable VR video support
  193. if (!video_data.params.listen && video_data.vr && video_data.params.vr_mode) {
  194. player.crossOrigin('anonymous');
  195. switch (video_data.projection_type) {
  196. case 'EQUIRECTANGULAR':
  197. player.vr({projection: 'equirectangular'});
  198. default: // Should only be 'MESH' but we'll use this as a fallback.
  199. player.vr({projection: 'EAC'});
  200. }
  201. }
  202. // Add markers
  203. if (video_data.params.video_start > 0 || video_data.params.video_end > 0) {
  204. var markers = [{ time: video_data.params.video_start, text: 'Start' }];
  205. if (video_data.params.video_end < 0) {
  206. markers.push({ time: video_data.length_seconds - 0.5, text: 'End' });
  207. } else {
  208. markers.push({ time: video_data.params.video_end, text: 'End' });
  209. }
  210. player.markers({
  211. onMarkerReached: function (marker) {
  212. if (marker.text === 'End')
  213. player.loop() ? player.markers.prev('Start') : player.pause();
  214. },
  215. markers: markers
  216. });
  217. player.currentTime(video_data.params.video_start);
  218. }
  219. player.volume(video_data.params.volume / 100);
  220. player.playbackRate(video_data.params.speed);
  221. /**
  222. * Method for getting the contents of a cookie
  223. *
  224. * @param {String} name Name of cookie
  225. * @returns {String|null} cookieValue
  226. */
  227. function getCookieValue(name) {
  228. var cookiePrefix = name + '=';
  229. var matchedCookie = document.cookie.split(';').find(function (item) {return item.includes(cookiePrefix);});
  230. if (matchedCookie)
  231. return matchedCookie.replace(cookiePrefix, '');
  232. return null;
  233. }
  234. /**
  235. * Method for updating the 'PREFS' cookie (or creating it if missing)
  236. *
  237. * @param {number} newVolume New volume defined (null if unchanged)
  238. * @param {number} newSpeed New speed defined (null if unchanged)
  239. */
  240. function updateCookie(newVolume, newSpeed) {
  241. var volumeValue = newVolume !== null ? newVolume : video_data.params.volume;
  242. var speedValue = newSpeed !== null ? newSpeed : video_data.params.speed;
  243. var cookieValue = getCookieValue('PREFS');
  244. var cookieData;
  245. if (cookieValue !== null) {
  246. var cookieJson = JSON.parse(decodeURIComponent(cookieValue));
  247. cookieJson.volume = volumeValue;
  248. cookieJson.speed = speedValue;
  249. cookieData = encodeURIComponent(JSON.stringify(cookieJson));
  250. } else {
  251. cookieData = encodeURIComponent(JSON.stringify({ 'volume': volumeValue, 'speed': speedValue }));
  252. }
  253. // Set expiration in 2 year
  254. var date = new Date();
  255. date.setFullYear(date.getFullYear() + 2);
  256. var ipRegex = /^((\d+\.){3}\d+|[\dA-Fa-f]*:[\d:A-Fa-f]*:[\d:A-Fa-f]+)$/;
  257. var domainUsed = location.hostname;
  258. // Fix for a bug in FF where the leading dot in the FQDN is not ignored
  259. if (domainUsed.charAt(0) !== '.' && !ipRegex.test(domainUsed) && domainUsed !== 'localhost')
  260. domainUsed = '.' + location.hostname;
  261. var secure = location.protocol.startsWith("https") ? " Secure;" : "";
  262. document.cookie = 'PREFS=' + cookieData + '; SameSite=Lax; path=/; domain=' +
  263. domainUsed + '; expires=' + date.toGMTString() + ';' + secure;
  264. video_data.params.volume = volumeValue;
  265. video_data.params.speed = speedValue;
  266. }
  267. player.on('ratechange', function () {
  268. updateCookie(null, player.playbackRate());
  269. if (isMobile()) {
  270. player.mobileUi({ touchControls: { seekSeconds: 5 * player.playbackRate() } });
  271. }
  272. });
  273. player.on('volumechange', function () {
  274. updateCookie(Math.ceil(player.volume() * 100), null);
  275. });
  276. player.on('waiting', function () {
  277. if (player.playbackRate() > 1 && player.liveTracker.isLive() && player.liveTracker.atLiveEdge()) {
  278. console.info('Player has caught up to source, resetting playbackRate');
  279. player.playbackRate(1);
  280. }
  281. });
  282. if (video_data.premiere_timestamp && Math.round(new Date() / 1000) < video_data.premiere_timestamp) {
  283. player.getChild('bigPlayButton').hide();
  284. }
  285. if (video_data.params.save_player_pos) {
  286. const url = new URL(location);
  287. const hasTimeParam = url.searchParams.has('t');
  288. const rememberedTime = get_video_time();
  289. let lastUpdated = 0;
  290. if(!hasTimeParam) {
  291. if (rememberedTime >= video_data.length_seconds - 20)
  292. set_seconds_after_start(0);
  293. else
  294. set_seconds_after_start(rememberedTime);
  295. }
  296. player.on('timeupdate', function () {
  297. const raw = player.currentTime();
  298. const time = Math.floor(raw);
  299. if(lastUpdated !== time && raw <= video_data.length_seconds - 15) {
  300. save_video_time(time);
  301. lastUpdated = time;
  302. }
  303. });
  304. }
  305. else remove_all_video_times();
  306. if (video_data.params.autoplay) {
  307. var bpb = player.getChild('bigPlayButton');
  308. bpb.hide();
  309. player.ready(function () {
  310. new Promise(function (resolve, reject) {
  311. setTimeout(function () {resolve(1);}, 1);
  312. }).then(function (result) {
  313. var promise = player.play();
  314. if (promise !== undefined) {
  315. promise.then(function () {
  316. }).catch(function (error) {
  317. bpb.show();
  318. });
  319. }
  320. });
  321. });
  322. }
  323. if (!video_data.params.listen && video_data.params.quality === 'dash') {
  324. player.httpSourceSelector();
  325. if (video_data.params.quality_dash !== 'auto') {
  326. player.ready(function () {
  327. player.on('loadedmetadata', function () {
  328. const qualityLevels = Array.from(player.qualityLevels()).sort(function (a, b) {return a.height - b.height;});
  329. let targetQualityLevel;
  330. switch (video_data.params.quality_dash) {
  331. case 'best':
  332. targetQualityLevel = qualityLevels.length - 1;
  333. break;
  334. case 'worst':
  335. targetQualityLevel = 0;
  336. break;
  337. default:
  338. const targetHeight = parseInt(video_data.params.quality_dash);
  339. for (let i = 0; i < qualityLevels.length; i++) {
  340. if (qualityLevels[i].height <= targetHeight)
  341. targetQualityLevel = i;
  342. else
  343. break;
  344. }
  345. }
  346. qualityLevels.forEach(function (level, index) {
  347. level.enabled = (index === targetQualityLevel);
  348. });
  349. });
  350. });
  351. }
  352. }
  353. player.vttThumbnails({
  354. src: '/api/v1/storyboards/' + video_data.id + '?height=90',
  355. showTimestamp: true
  356. });
  357. // Enable annotations
  358. if (!video_data.params.listen && video_data.params.annotations) {
  359. addEventListener('load', function (e) {
  360. addEventListener('__ar_annotation_click', function (e) {
  361. const url = e.detail.url,
  362. target = e.detail.target,
  363. seconds = e.detail.seconds;
  364. var path = new URL(url);
  365. if (path.href.startsWith('https://www.youtube.com/watch?') && seconds) {
  366. path.search += '&t=' + seconds;
  367. }
  368. path = path.pathname + path.search;
  369. if (target === 'current') {
  370. location.href = path;
  371. } else if (target === 'new') {
  372. open(path, '_blank');
  373. }
  374. });
  375. helpers.xhr('GET', '/api/v1/annotations/' + video_data.id, {
  376. responseType: 'text',
  377. timeout: 60000
  378. }, {
  379. on200: function (response) {
  380. var video_container = document.getElementById('player');
  381. videojs.registerPlugin('youtubeAnnotationsPlugin', youtubeAnnotationsPlugin);
  382. if (player.paused()) {
  383. player.one('play', function (event) {
  384. player.youtubeAnnotationsPlugin({ annotationXml: response, videoContainer: video_container });
  385. });
  386. } else {
  387. player.youtubeAnnotationsPlugin({ annotationXml: response, videoContainer: video_container });
  388. }
  389. }
  390. });
  391. });
  392. }
  393. function change_volume(delta) {
  394. const curVolume = player.volume();
  395. let newVolume = curVolume + delta;
  396. newVolume = helpers.clamp(newVolume, 0, 1);
  397. player.volume(newVolume);
  398. }
  399. function toggle_muted() {
  400. player.muted(!player.muted());
  401. }
  402. function skip_seconds(delta) {
  403. const duration = player.duration();
  404. const curTime = player.currentTime();
  405. let newTime = curTime + delta;
  406. newTime = helpers.clamp(newTime, 0, duration);
  407. player.currentTime(newTime);
  408. }
  409. function set_seconds_after_start(delta) {
  410. const start = video_data.params.video_start;
  411. player.currentTime(start + delta);
  412. }
  413. function save_video_time(seconds) {
  414. const all_video_times = get_all_video_times();
  415. all_video_times[video_data.id] = seconds;
  416. helpers.storage.set(save_player_pos_key, all_video_times);
  417. }
  418. function get_video_time() {
  419. return get_all_video_times()[video_data.id] || 0;
  420. }
  421. function get_all_video_times() {
  422. return helpers.storage.get(save_player_pos_key) || {};
  423. }
  424. function remove_all_video_times() {
  425. helpers.storage.remove(save_player_pos_key);
  426. }
  427. function set_time_percent(percent) {
  428. const duration = player.duration();
  429. const newTime = duration * (percent / 100);
  430. player.currentTime(newTime);
  431. }
  432. function play() { player.play(); }
  433. function pause() { player.pause(); }
  434. function stop() { player.pause(); player.currentTime(0); }
  435. function toggle_play() { player.paused() ? play() : pause(); }
  436. const toggle_captions = (function () {
  437. let toggledTrack = null;
  438. function bindChange(onOrOff) {
  439. player.textTracks()[onOrOff]('change', function (e) {
  440. toggledTrack = null;
  441. });
  442. }
  443. // Wrapper function to ignore our own emitted events and only listen
  444. // to events emitted by Video.js on click on the captions menu items.
  445. function setMode(track, mode) {
  446. bindChange('off');
  447. track.mode = mode;
  448. setTimeout(function () {
  449. bindChange('on');
  450. }, 0);
  451. }
  452. bindChange('on');
  453. return function () {
  454. if (toggledTrack !== null) {
  455. if (toggledTrack.mode !== 'showing') {
  456. setMode(toggledTrack, 'showing');
  457. } else {
  458. setMode(toggledTrack, 'disabled');
  459. }
  460. toggledTrack = null;
  461. return;
  462. }
  463. // Used as a fallback if no captions are currently active.
  464. // TODO: Make this more intelligent by e.g. relying on browser language.
  465. let fallbackCaptionsTrack = null;
  466. const tracks = player.textTracks();
  467. for (let i = 0; i < tracks.length; i++) {
  468. const track = tracks[i];
  469. if (track.kind !== 'captions') continue;
  470. if (fallbackCaptionsTrack === null) {
  471. fallbackCaptionsTrack = track;
  472. }
  473. if (track.mode === 'showing') {
  474. setMode(track, 'disabled');
  475. toggledTrack = track;
  476. return;
  477. }
  478. }
  479. // Fallback if no captions are currently active.
  480. if (fallbackCaptionsTrack !== null) {
  481. setMode(fallbackCaptionsTrack, 'showing');
  482. toggledTrack = fallbackCaptionsTrack;
  483. }
  484. };
  485. })();
  486. function toggle_fullscreen() {
  487. player.isFullscreen() ? player.exitFullscreen() : player.requestFullscreen();
  488. }
  489. function increase_playback_rate(steps) {
  490. const maxIndex = options.playbackRates.length - 1;
  491. const curIndex = options.playbackRates.indexOf(player.playbackRate());
  492. let newIndex = curIndex + steps;
  493. newIndex = helpers.clamp(newIndex, 0, maxIndex);
  494. player.playbackRate(options.playbackRates[newIndex]);
  495. }
  496. addEventListener('keydown', function (e) {
  497. if (e.target.tagName.toLowerCase() === 'input') {
  498. // Ignore input when focus is on certain elements, e.g. form fields.
  499. return;
  500. }
  501. // See https://github.com/ctd1500/videojs-hotkeys/blob/bb4a158b2e214ccab87c2e7b95f42bc45c6bfd87/videojs.hotkeys.js#L310-L313
  502. const isPlayerFocused = false
  503. || e.target === document.querySelector('.video-js')
  504. || e.target === document.querySelector('.vjs-tech')
  505. || e.target === document.querySelector('.iframeblocker')
  506. || e.target === document.querySelector('.vjs-control-bar')
  507. ;
  508. let action = null;
  509. const code = e.keyCode;
  510. const decoratedKey =
  511. e.key
  512. + (e.altKey ? '+alt' : '')
  513. + (e.ctrlKey ? '+ctrl' : '')
  514. + (e.metaKey ? '+meta' : '')
  515. ;
  516. switch (decoratedKey) {
  517. case ' ':
  518. case 'k':
  519. case 'MediaPlayPause':
  520. action = toggle_play;
  521. break;
  522. case 'MediaPlay': action = play; break;
  523. case 'MediaPause': action = pause; break;
  524. case 'MediaStop': action = stop; break;
  525. case 'ArrowUp':
  526. if (isPlayerFocused) action = change_volume.bind(this, 0.1);
  527. break;
  528. case 'ArrowDown':
  529. if (isPlayerFocused) action = change_volume.bind(this, -0.1);
  530. break;
  531. case 'm':
  532. action = toggle_muted;
  533. break;
  534. case 'ArrowRight':
  535. case 'MediaFastForward':
  536. action = skip_seconds.bind(this, 5 * player.playbackRate());
  537. break;
  538. case 'ArrowLeft':
  539. case 'MediaTrackPrevious':
  540. action = skip_seconds.bind(this, -5 * player.playbackRate());
  541. break;
  542. case 'l':
  543. action = skip_seconds.bind(this, 10 * player.playbackRate());
  544. break;
  545. case 'j':
  546. action = skip_seconds.bind(this, -10 * player.playbackRate());
  547. break;
  548. case '0':
  549. case '1':
  550. case '2':
  551. case '3':
  552. case '4':
  553. case '5':
  554. case '6':
  555. case '7':
  556. case '8':
  557. case '9':
  558. // Ignore numpad numbers
  559. if (code > 57) break;
  560. const percent = (code - 48) * 10;
  561. action = set_time_percent.bind(this, percent);
  562. break;
  563. case 'c': action = toggle_captions; break;
  564. case 'f': action = toggle_fullscreen; break;
  565. case 'N':
  566. case 'MediaTrackNext':
  567. action = next_video;
  568. break;
  569. case 'P':
  570. case 'MediaTrackPrevious':
  571. // TODO: Add support to play back previous video.
  572. break;
  573. // TODO: More precise step. Now FPS is taken equal to 29.97
  574. // Common FPS: https://forum.videohelp.com/threads/81868#post323588
  575. // Possible solution is new HTMLVideoElement.requestVideoFrameCallback() https://wicg.github.io/video-rvfc/
  576. case ',': action = function () { pause(); skip_seconds(-1/29.97); }; break;
  577. case '.': action = function () { pause(); skip_seconds( 1/29.97); }; break;
  578. case '>': action = increase_playback_rate.bind(this, 1); break;
  579. case '<': action = increase_playback_rate.bind(this, -1); break;
  580. default:
  581. console.info('Unhandled key down event: %s:', decoratedKey, e);
  582. break;
  583. }
  584. if (action) {
  585. e.preventDefault();
  586. action();
  587. }
  588. }, false);
  589. // Add support for controlling the player volume by scrolling over it. Adapted from
  590. // https://github.com/ctd1500/videojs-hotkeys/blob/bb4a158b2e214ccab87c2e7b95f42bc45c6bfd87/videojs.hotkeys.js#L292-L328
  591. (function () {
  592. const pEl = document.getElementById('player');
  593. var volumeHover = false;
  594. var volumeSelector = pEl.querySelector('.vjs-volume-menu-button') || pEl.querySelector('.vjs-volume-panel');
  595. if (volumeSelector !== null) {
  596. volumeSelector.onmouseover = function () { volumeHover = true; };
  597. volumeSelector.onmouseout = function () { volumeHover = false; };
  598. }
  599. function mouseScroll(event) {
  600. // When controls are disabled, hotkeys will be disabled as well
  601. if (!player.controls() || !volumeHover) return;
  602. event.preventDefault();
  603. var wheelMove = event.wheelDelta || -event.detail;
  604. var volumeSign = Math.sign(wheelMove);
  605. change_volume(volumeSign * 0.05); // decrease/increase by 5%
  606. }
  607. player.on('mousewheel', mouseScroll);
  608. player.on('DOMMouseScroll', mouseScroll);
  609. }());
  610. // Since videojs-share can sometimes be blocked, we defer it until last
  611. if (player.share) player.share(shareOptions);
  612. // show the preferred caption by default
  613. if (player_data.preferred_caption_found) {
  614. player.ready(function () {
  615. if (!video_data.params.listen && video_data.params.quality === 'dash') {
  616. // play.textTracks()[0] on DASH mode is showing some debug messages
  617. player.textTracks()[1].mode = 'showing';
  618. } else {
  619. player.textTracks()[0].mode = 'showing';
  620. }
  621. });
  622. }
  623. // Safari audio double duration fix
  624. if (navigator.vendor === 'Apple Computer, Inc.' && video_data.params.listen) {
  625. player.on('loadedmetadata', function () {
  626. player.on('timeupdate', function () {
  627. if (player.remainingTime() < player.duration() / 2 && player.remainingTime() >= 2) {
  628. player.currentTime(player.duration() - 1);
  629. }
  630. });
  631. });
  632. }
  633. // Safari screen timeout on looped video playback fix
  634. if (navigator.vendor === 'Apple Computer, Inc.' && !video_data.params.listen && video_data.params.video_loop) {
  635. player.loop(false);
  636. player.ready(function () {
  637. player.on('ended', function () {
  638. player.currentTime(0);
  639. player.play();
  640. });
  641. });
  642. }
  643. // Watch on Invidious link
  644. if (location.pathname.startsWith('/embed/')) {
  645. const Button = videojs.getComponent('Button');
  646. let watch_on_invidious_button = new Button(player);
  647. // Create hyperlink for current instance
  648. var redirect_element = document.createElement('a');
  649. redirect_element.setAttribute('href', location.pathname.replace('/embed/', '/watch?v='));
  650. redirect_element.appendChild(document.createTextNode('Invidious'));
  651. watch_on_invidious_button.el().appendChild(redirect_element);
  652. watch_on_invidious_button.addClass('watch-on-invidious');
  653. var cb = player.getChild('ControlBar');
  654. cb.addChild(watch_on_invidious_button);
  655. }
  656. addEventListener('DOMContentLoaded', function () {
  657. // Save time during redirection on another instance
  658. const changeInstanceLink = document.querySelector('#watch-on-another-invidious-instance > a');
  659. if (changeInstanceLink) changeInstanceLink.addEventListener('click', function () {
  660. changeInstanceLink.href = addCurrentTimeToURL(changeInstanceLink.href);
  661. });
  662. });