FYTE /Fast YouTube Embedded/ Player

Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. Optionally a fast simple HTML5 direct playback (720p max) can be selected if available for the video.

当前为 2021-01-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name FYTE /Fast YouTube Embedded/ Player
  3. // @description Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. Optionally a fast simple HTML5 direct playback (720p max) can be selected if available for the video.
  4. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются заглушки для видео, которые можно щелкнуть для загрузки плеера, и почти сразу же появляются кавер-картинки с названием видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  5. //
  6. // @version 2.12.7
  7. //
  8. // @include *
  9. // @exclude /^https:\/\/(www\.)?youtube\.com\/(?!embed)/
  10. // @exclude https://accounts.google.*/o/oauth2/postmessageRelay*
  11. // @exclude https://clients*.google.*/youtubei/*
  12. // @exclude https://clients*.google.*/static/proxy*
  13. //
  14. // @author wOxxOm
  15. // @namespace wOxxOm.scripts
  16. // @license MIT License
  17. //
  18. // @grant GM_getValue
  19. // @grant GM_listValues
  20. // @grant GM_deleteValue
  21. // @grant GM_setValue
  22. // @grant GM_addStyle
  23. // @grant GM_xmlhttpRequest
  24. //
  25. // @connect www.youtube.com
  26. // @connect youtube.com
  27. //
  28. // @run-at document-start
  29. //
  30. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACABAMAAAAxEHz4AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAwUExURUxpcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJuxkb8AAAAPdFJOUwDvH0biMvjOZFW6pxJ6kh7r3iMAAAPDSURBVGje7ZlNaBNBFMeXhNDWpkKgFg9iYlBB6SGwiPQkftaCYATjTaRKiwi1xVaKXpqTpHhosR66p4pQhb209CQGbSweK/TiRYwfFy+NkWBM2pR2nHm73abJzuceRMj/kEzSvl92Z9689+atpjXUUEMN1WgpoRupbH41nTbNUaxzlkIhe0C+M810Ov8zmzL0RGeNeeDThUEkof72N/Fqe/8LJK07sR173yJS0EbEATxFSurZtm9DilqxAV9VAZuWfbPbLBOFqtSBP9f/WxIAV2Bc6H5owiKPG7p+IpFIRG11LsPbEfyVrhvTqeyX1dfmaBiM9gFgjgwrTzJSfncMFq7s3EExJuu5/rHte3hPBvfkff84sbuEBxPkUiLygCC5hDV7CvpUtt81axICZBN9UwHsxYalOMxhIaIC8IVhFlvJtlALIWQl57Um/LquBpjBpkOwin1qADKLB7RD9moqiPz2TcAMqQGa4OI9Av5op/DrMzXAHmz6mw4IxEQA67AW825/bhngAVoBMEHzZD+aFQCsQUCkAAor/M2wCYAVdwCqxJmANgD8cmJjPQDt5wK22AD0nAVoBsAiE1BMcgAbAJikAqoTYP1CA4BEtBgdgC6yARUuAC3QI7sDiLMAxUk2YAwiIwNAn4YAhGU+YKcOqAUMCgJQziugHGMALmNAhANAWxkaoEgABS4ADdMyiyiglPMIcJ0GKQAayDAAGQEAuu8VUB/gJAH1AS4IgLAwAA24AAoygAeuAPFbqHPHoNwc1HuCJCDncRl7NG8At7Ak48qugVEGsOBxO7snB58T0ngASlwWjomFpMegOusxrFOLBCexsFMbvUzxCyVXRqEkBpjlpXdOgcEqFlsEKpRynFviMIus0md+kcUEDAuUeaxCcysjUGgySt1yTKTUZRTbOaFim17unxUr92doBw4f9zTKObGInZl+//NTW592VP3g+Q4Onh6Ovjfgt5vsPoSCJuDuPRz/58CFmhEtKPIEvY8kZAd3VxRxRJJSyIXcUu0/VOz3okITJRC2ex9kGdB5ecBVZLtgCyt70fUB2nGTTjOu/HFZohsXXLoOrbQKfDps1ePtTj9wSter2oGWoBnYRZqB+bQ5OnLaShpnrNAz6N6R7OW1I1HJjnmPVFuit7eDV1jNvuAkpJNqgJ0DQPCHiv3dqmULfJe3P7hrB/oej3T0S/Tme7tf1Xp/MArPB/Ayp82X5OlAaJfI8wHsJ2/zWXg6EGV4XXB5CbuN3mUYxnQKNI6HU9i3op0y3tpQQw39b/oLfDt0HcsiqWsAAAAASUVORK5CYII=
  31. //
  32. // @compatible chrome
  33. // @compatible firefox
  34. // @compatible opera
  35. // ==/UserScript==
  36.  
  37. 'use strict';
  38.  
  39. // keep video info cache for a month since last time it's shown
  40. const CACHE_STALE_DURATION = 30 * 24 * 3600e3;
  41. const cfg = {
  42. width: 1280,
  43. height: 720,
  44. invidious: false,
  45. resize: 'Fit to width',
  46. pinnable: 'on',
  47. pinnedWidth: 400,
  48. playHTML5: false,
  49. playHTML5Shown: false,
  50. showStoryboard: true,
  51. skipCustom: true,
  52. };
  53. const checked = [];
  54. let _, fytedom, styledom, iframes, objects, persite, playbtn;
  55.  
  56. if (location.hostname === 'www.youtube.com') {
  57. if ((unsafeWindow.chrome || 0).app && window !== top)
  58. setupYoutubeFullscreenRelay();
  59. } else {
  60. for (const [k, def] of Object.entries(cfg)) {
  61. const v = GM_getValue(k, def);
  62. cfg[k] = typeof v === typeof def ? v : def;
  63. }
  64. _ = initTL();
  65. persite = getPersiteRule();
  66. fytedom = document.getElementsByClassName('instant-youtube-container');
  67. iframes = document.getElementsByTagName('iframe');
  68. objects = document.getElementsByTagName('object');
  69. updateCustomSize();
  70. findEmbeds([]);
  71. injectStylesIfNeeded();
  72. new MutationObserver(findEmbeds)
  73. .observe(document, {subtree: true, childList: true});
  74. document.addEventListener('DOMContentLoaded', e => {
  75. injectStylesIfNeeded();
  76. adjustNodesIfNeeded(e);
  77. setTimeout(cleanupCache, 60e3);
  78. }, {once: true});
  79. addEventListener('resize', adjustNodesIfNeeded, true);
  80. addEventListener('message', onMessageHost);
  81. }
  82.  
  83. function setupYoutubeFullscreenRelay() {
  84. parent.postMessage('FYTE-toggle-fullscreen-init', '*');
  85. addEventListener('message', function onMessage(e) {
  86. if (e.source !== parent ||
  87. e.data !== 'FYTE-toggle-fullscreen-init-confirmed')
  88. return;
  89. removeEventListener('message', onMessage);
  90. const fsbtn = document.getElementsByClassName('ytp-fullscreen-button');
  91. new MutationObserver(function () {
  92. if (fsbtn[0]) {
  93. this.disconnect();
  94. fsbtn[0].outerHTML = fsbtn[0].outerHTML.replace('aria-disabled="true"', '');
  95. fsbtn[0].addEventListener('click', () => {
  96. window.parent.postMessage('FYTE-toggle-fullscreen', '*');
  97. });
  98. }
  99. }).observe(document, {subtree: true, childList: true});
  100. });
  101. }
  102.  
  103. function getPersiteRule() {
  104. const h = '.' + location.hostname;
  105. const rule =
  106. h === '.developers.google.com' && {
  107. match: '[data-video-id]',
  108. src: e => '//youtube.com/embed/' + e.dataset.videoId,
  109. } ||
  110. h === '.play.google.com' && {
  111. eatparent: 0,
  112. } ||
  113. h.includes('.google.') && /(^|\.)google\.\w{2,3}(\.\w{2,3})?$/.test(h) && {
  114. id: 'wp-tabs-container',
  115. query: 'a[href*="youtube.com/watch"] img',
  116. src: e => e.closest('a').href,
  117. eatparent: 2,
  118. } ||
  119. h === '.pikabu.ru' && {
  120. cls: 'b-video',
  121. match: '[data-url*="youtube.com/embed"]',
  122. attr: 'data-url',
  123. } ||
  124. h === '.androidauthority.com' && {
  125. eatparent: '.video-container',
  126. } ||
  127. h === '.reddit.com' && {
  128. match: '[data-url*="youtube.com/"] [src*="/mediaembed"],' +
  129. '[data-url*="youtu.be/"] [src*="/mediaembed"]',
  130. src: e => e.closest('[data-url*="youtube.com/"], [data-url*="youtu.be/"]').dataset.url,
  131. } ||
  132. h.endsWith('.theverge.com') && {
  133. eatparent: '.p-scalable-video',
  134. } ||
  135. h === '.9gag.com' && {
  136. eatparent: 0,
  137. } ||
  138. h === '.reddit.com' && {
  139. match: '[data-url*="youtube.com"] iframe[src*="redditmedia.com/mediaembed"]',
  140. src: e => e.closest('[data-url*="youtube.com"]').dataset.url,
  141. } ||
  142. h === '.anilist.co' && {
  143. eatparent: '.youtube',
  144. };
  145. if (rule) {
  146. let {cls, id, match, query, tag} = rule;
  147. if (!tag && !cls)
  148. tag = 'iframe';
  149. if (!match && !query)
  150. match = '[src*="youtube.com/embed"]';
  151. if (!id)
  152. rule.nodes = cls ?
  153. document.getElementsByClassName(cls) :
  154. document.getElementsByTagName(tag);
  155. rule.match = match ?
  156. e => e.matches(match) ? e : null :
  157. e => e.querySelector(query);
  158. return rule;
  159. }
  160. }
  161.  
  162. function onMessageHost(e) {
  163. switch (e.data) {
  164. case 'FYTE-toggle-fullscreen-init':
  165. if (findFrameElement(e.source))
  166. e.source.postMessage('FYTE-toggle-fullscreen-init-confirmed', '*');
  167. break;
  168. case 'FYTE-toggle-fullscreen': {
  169. const el = findFrameElement(e.source);
  170. if (el)
  171. goFullscreen(el,
  172. !(document.fullscreenElement || document.fullScreen || document.mozFullScreen));
  173. break;
  174. }
  175. case 'iframe-allowfs':
  176. $$('iframe:not([allowfullscreen])').some(iframe => {
  177. if (iframe.contentWindow === e.source) {
  178. iframe.allowFullscreen = true;
  179. return true;
  180. }
  181. });
  182. if (window !== top)
  183. parent.postMessage('iframe-allowfs', '*');
  184. break;
  185. }
  186. }
  187.  
  188. function findFrameElement(frameWindow) {
  189. return $$('iframe[allowfullscreen]').find(el => el.contentWindow === frameWindow);
  190. }
  191.  
  192. function findEmbeds(mutations) {
  193. if (mutations.length === 1) {
  194. const added = mutations[0].addedNodes;
  195. if (!added[0] || !added[1] && added[0].nodeType === 3)
  196. return;
  197. }
  198. if (persite)
  199. for (let el of persite.id ? [document.getElementById(persite.id)] : persite.nodes)
  200. if (el && (el = persite.match(el)))
  201. processEmbed(el, persite.src && persite.src(el) || el.getAttribute(persite.attr));
  202. for (const el of iframes) {
  203. if (!checked.includes(el)) {
  204. checked.push(el);
  205. const src = el.src || el.getAttribute('data-src') || '';
  206. if (src.includes('yout') && /youtube(-nocookie)?\.com|youtu\.be/i.test(src))
  207. processEmbed(el, src);
  208. }
  209. }
  210. for (const el of objects) {
  211. if (!checked.includes(el)) {
  212. checked.push(el);
  213. const {src, value} = $('embed, [value*="youtu.be"], [value*="youtube.com"]', el) || {};
  214. if (src)
  215. processEmbed(el, src || el.getAttribute('data-src') ||
  216. `https://${value.match(/youtu\.be.*|youtube\.com.*/)[0]}`);
  217. }
  218. }
  219. }
  220.  
  221. function decodeEmbedUrl(url) {
  222. return /youtube(-nocookie)?\.com%2Fembed/.test(url) ?
  223. decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube(-nocookie)?\.com%2Fembed[^&]+).*$/i, '$1')) :
  224. url;
  225. }
  226.  
  227. function processEmbed(node, src) {
  228. src = src || node.src || node.href || '';
  229. let n = node;
  230. let np = n.parentNode;
  231. const srcFixed = decodeEmbedUrl(src)
  232. .replace(/\/(watch\?v=|v\/)/, '/embed/')
  233. .replace(/^([^?&]+)&/, '$1?');
  234. if (src.indexOf('cdn.embedly.com/') > 0 ||
  235. cfg.resize !== 'Original' && np && np.children.length === 1 && !np.className && !np.id) {
  236. n = location.hostname === 'disqus.com' ? np.parentNode : np;
  237. np = n.parentElement;
  238. }
  239. if (!np ||
  240. !np.parentNode ||
  241. cfg.skipCustom && srcFixed.includes('enablejsapi=1') ||
  242. srcFixed.includes('/embed/videoseries') ||
  243. node.matches('.instant-youtube-embed, .YTLT-embed, .ihvyoutube') ||
  244. node.style.position === 'fixed' ||
  245. node.onload // skip some retarded loaders
  246. )
  247. return;
  248.  
  249. let id = srcFixed.match(
  250. /(?:^(?:https?:)?\/\/)(?:www\.)?(?:youtube(?:-nocookie)?\.com\/(?:embed\/(?:v=)?|\/.*?[&?/]v[=/])|youtu\.be\/)([^\s,.()[\]?]+?)(?:[&?/].*|$)/);
  251. if (!id)
  252. return;
  253. id = id[1];
  254.  
  255. if (np.localName === 'object') {
  256. n = np;
  257. np = n.parentElement;
  258. }
  259.  
  260. let eatparent = persite && persite.eatparent || 0;
  261. if (typeof eatparent === 'string') {
  262. n = np.closest(eatparent) || n;
  263. } else {
  264. while (eatparent--) {
  265. n = np;
  266. np = n.parentElement;
  267. }
  268. }
  269.  
  270. createFYTE(node, n, id, setUrl(srcFixed));
  271. stopOriginalEmbed(node);
  272. }
  273.  
  274. function createFYTE(node, n, id, srcFixed, force) {
  275. if (!document.contains(n))
  276. return;
  277. const cache = tryJSONparse(localStorage[`FYTE-cache-${id}`]) || {id};
  278. const autoplay = /[?&](autoplay=1|ps=play)(&|$)/.test(srcFixed);
  279. const img = $create('img.thumbnail');
  280. if (!autoplay) {
  281. img.src = setUrl(cache.cover || `https://i.ytimg.com/vi/${id}/maxresdefault.jpg`);
  282. img.onerror = onCoverError;
  283. }
  284.  
  285. if (document.readyState !== 'complete' && !force) {
  286. const args = [...arguments];
  287. args[createFYTE.length - 1] = true;
  288. setTimeout(createFYTE, 0, ...args);
  289. return;
  290. }
  291.  
  292. injectStylesIfNeeded('force');
  293.  
  294. const div = $create('div.container');
  295. div.FYTE = {
  296. state: 'querying',
  297. srcEmbed: srcFixed.replace(/&$/, ''),
  298. originalWidth: /%/.test(node.width) ? 320 : node.width | 0 || n.clientWidth | 0,
  299. originalHeight: /%/.test(node.height) ? 200 : node.height | 0 || n.clientHeight | 0,
  300. cache: cache,
  301. };
  302. div.FYTE.srcEmbedFixed =
  303. div.FYTE.srcEmbed.replace(/^http:/, 'https:')
  304. .replace(/([&?])(wmode=\w+|feature=oembed)&?/, '$1')
  305. .replace(/[&?]$/, '');
  306. div.FYTE.srcWatchFixed =
  307. div.FYTE.srcEmbedFixed.replace('/embed/', '/watch?v=').replace(/(\?.*?)\?/, '$1&');
  308.  
  309. cache.lastUsed = Date.now();
  310. localStorage[`FYTE-cache-${id}`] = JSON.stringify(cache);
  311.  
  312. if (cache.reason)
  313. div.setAttribute('disabled', '');
  314.  
  315. const divSize = calcContainerSize(div, n);
  316. const origStyle = getComputedStyle(n);
  317. overrideCSS(div, Object.assign(
  318. {
  319. height: persite && persite.eatparent === 0 ? '100%' : divSize.h + 'px',
  320. 'min-width': Math.min(divSize.w, div.FYTE.originalWidth) + 'px',
  321. 'min-height': Math.min(divSize.h, div.FYTE.originalHeight) + 'px',
  322. 'max-width': divSize.w + 'px',
  323. },
  324. origStyle.transform && {
  325. transform: origStyle.transform,
  326. },
  327. !autoplay && {
  328. 'background-color': 'transparent',
  329. transition: 'background-color 2s',
  330. },
  331. // eslint-disable-next-line no-proto
  332. ...Object.keys(origStyle.hasOwnProperty('position') ? origStyle : origStyle.__proto__ /*FF*/)
  333. .filter(k => /^(position|left|right|top|bottom)$/.test(k) &&
  334. !/^(auto|static|block)$/.test(origStyle[k]))
  335. .map(k => ({[k]: origStyle[k]})),
  336. origStyle.display === 'inline' && {
  337. display: 'inline-block',
  338. width: '100%',
  339. },
  340. cfg.resize === 'Fit to width' && {
  341. width: '100%',
  342. }));
  343. if (!autoplay) {
  344. setTimeout(() => div.style.removeProperty('background-color'));
  345. setTimeout(() => div.style.removeProperty('transition'), 2000);
  346. }
  347.  
  348. const wrapper = $create('div.wrapper', {}, [
  349. img,
  350. $create('a.title', {target: '_blank', href: div.FYTE.srcWatchFixed},
  351. cache.title || cache.reason
  352. ? [
  353. $create('strong', {}, cache.title || cache.reason || ''),
  354. cache.duration && $create('span', {}, cache.duration),
  355. cache.fps && $create('i', {}, `${cache.fps}fps`),
  356. ]
  357. : '\xA0'),
  358. (playbtn || initPlayButton()).cloneNode(true),
  359. $create('span.alternative', {}, _(`msgPlay${cfg.playHTML5 ? 'HTML5' : ''}`)),
  360. $create('div.storyboard', {hidden: !cfg.showStoryboard}),
  361. $create('div.options-button', {}, _('Options')),
  362. ]);
  363. div.appendChild(wrapper);
  364.  
  365. overrideCSS(img, Object.assign({
  366. position: 'absolute',
  367. margin: 'auto',
  368. padding: 0,
  369. top: 0,
  370. left: 0,
  371. right: 0,
  372. bottom: 0,
  373. 'max-width': 'none',
  374. 'max-height': 'none',
  375. }, !cache.cover && {
  376. transition: 'opacity 0.1s ease-out',
  377. opacity: 0,
  378. }));
  379. img.FYTE = [div, divSize, autoplay];
  380. img.onload = onCoverLoad;
  381. if (cache.coverWidth || img.naturalWidth)
  382. img.onload();
  383.  
  384. n.parentNode.insertBefore(div, n);
  385. n.remove();
  386.  
  387. if (!cache.title && !cache.reason || autoplay && cfg.playHTML5)
  388. fetchInfo.call(div);
  389.  
  390. if (autoplay) {
  391. startPlaying(div);
  392. } else {
  393. div.addEventListener('click', clickHandler);
  394. div.addEventListener('mousedown', clickHandler);
  395. div.addEventListener('mouseenter', fetchInfo);
  396. }
  397. if (cfg.showStoryboard)
  398. div.addEventListener('mousemove', trackMouse);
  399. }
  400.  
  401. function fetchInfo(e) {
  402. this.FYTE.mouseEvent = e;
  403. this.removeEventListener('mouseenter', fetchInfo);
  404. if (!this.FYTE.storyboard) {
  405. GM_xmlhttpRequest({
  406. method: 'GET',
  407. url: 'https://www.youtube.com/get_video_info?video_id=' + this.FYTE.cache.id +
  408. '&hl=en_US&html5=1&el=embedded&eurl=' + encodeURIComponent(location.href),
  409. context: this,
  410. onload: parseVideoInfo,
  411. });
  412. }
  413. }
  414.  
  415. function onCoverLoad(e) {
  416. const data = [...this.FYTE || []];
  417. const div = data.shift();
  418. const cache = div.FYTE.cache;
  419. const divSize = data.shift();
  420. const autoplay = data.shift();
  421. if (this.naturalWidth <= 120 && !cache.cover)
  422. return this.onerror(e);
  423. // delete this.FYTE;
  424. let fitToWidth = true;
  425. if (this.naturalHeight || cache.coverHeight) {
  426. if (!cache.coverHeight) {
  427. cache.coverWidth = this.naturalWidth;
  428. cache.coverHeight = this.naturalHeight;
  429. localStorage[`FYTE-cache-${cache.id}`] = JSON.stringify(cache);
  430. }
  431. const ratio = cache.coverWidth / cache.coverHeight;
  432. if (ratio > 4.1 / 3 && ratio < divSize.w / divSize.h) {
  433. this.style.setProperty('width', 'auto', 'important');
  434. this.style.setProperty('height', '100%', 'important');
  435. fitToWidth = false;
  436. }
  437. }
  438. if (fitToWidth) {
  439. this.style.setProperty('width', '100%', 'important');
  440. this.style.setProperty('height', 'auto', 'important');
  441. }
  442. if (cache.videoWidth)
  443. fixThumbnailAR(div);
  444. if (!autoplay)
  445. this.style.opacity = 1;
  446. }
  447.  
  448. function onCoverError() {
  449. const src = this.src;
  450. if (src.includes('maxresdefault'))
  451. this.src = src.replace('maxresdefault', 'sddefault');
  452. else if (src.includes('sddefault'))
  453. this.src = src.replace('sddefault', 'hqdefault');
  454. }
  455.  
  456. function stopOriginalEmbed(node) {
  457. const src = 'data:,';
  458. let n = node;
  459. while (n) {
  460. if (n.src)
  461. n.src = src;
  462. if (n.dataset.src)
  463. n.dataset.src = src;
  464. n = $('embed', n);
  465. }
  466. for (const el of $$('[value*="youtu.be"], [value*="youtube.com"]', node))
  467. el.value = src;
  468. }
  469.  
  470. function adjustNodesIfNeeded(e) {
  471. if (!fytedom[0])
  472. return;
  473. if (adjustNodesIfNeeded.scheduled)
  474. clearTimeout(adjustNodesIfNeeded.scheduled);
  475. adjustNodesIfNeeded.scheduled = setTimeout(() => {
  476. adjustNodes(e);
  477. adjustNodesIfNeeded.scheduled = 0;
  478. }, 16);
  479. }
  480.  
  481. function adjustNodes(event, clickedContainer) {
  482. const force = !!clickedContainer;
  483. let nearest = force ? clickedContainer : null;
  484. let nearestCenterYpct;
  485.  
  486. const vids = $$('.instant-youtube-container:not([pinned]):not([stub])');
  487.  
  488. if (!nearest && event.type !== 'DOMContentLoaded') {
  489. let minDistance = window.innerHeight * 3 / 4 | 0;
  490. const nearTargetY = window.innerHeight / 2;
  491. for (const n of vids) {
  492. const bounds = n.getBoundingClientRect();
  493. const distance = Math.abs((bounds.bottom + bounds.top) / 2 - nearTargetY);
  494. if (distance < minDistance) {
  495. minDistance = distance;
  496. nearest = n;
  497. }
  498. }
  499. }
  500.  
  501. if (nearest) {
  502. const bounds = nearest.getBoundingClientRect();
  503. nearestCenterYpct = (bounds.top + bounds.bottom) / 2 / window.innerHeight;
  504. }
  505.  
  506. let resized = false;
  507.  
  508. for (const n of vids) {
  509. const size = calcContainerSize(n);
  510. const w = size.w;
  511. const h = size.h;
  512.  
  513. // prevent parent clipping
  514. for (let e = n.parentElement, style; e; e = e.parentElement) {
  515. if (e.style.overflow !== 'visible' &&
  516. n.offsetTop < e.clientHeight / 2 &&
  517. n.offsetTop + n.clientHeight > e.clientHeight &&
  518. (style = getComputedStyle(e)) &&
  519. /hidden|scroll/.test(style.overflow + style.overflowX + style.overflowY)) {
  520. overrideCSS(e, {
  521. overflow: 'visible',
  522. 'overflow-x': 'visible',
  523. 'overflow-y': 'visible',
  524. });
  525. }
  526. }
  527.  
  528. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  529. continue;
  530.  
  531. overrideCSS(n, Object.assign({},
  532. n.style.maxWidth !== `${w}px` && {
  533. 'max-width': `${w}px`,
  534. },
  535. n.style.height !== h + 'px' && {
  536. height: h + 'px',
  537. },
  538. parseFloat(n.style.minWidth) > w && {
  539. 'min-width': n.style.maxWidth,
  540. },
  541. parseFloat(n.style.minHeight) > h && {
  542. 'min-height': n.style.height,
  543. }));
  544.  
  545. fixThumbnailAR(n);
  546. resized = true;
  547. }
  548.  
  549. if (resized && nearest)
  550. setTimeout(() => {
  551. const bounds = nearest.getBoundingClientRect();
  552. const h = bounds.bottom - bounds.top;
  553. const projectedCenterY = nearestCenterYpct * window.innerHeight;
  554. const projectedTop = projectedCenterY - h / 2;
  555. const safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  556. window.scrollBy(0, bounds.top - safeTop);
  557. }, 16);
  558. }
  559.  
  560. function calcContainerSize(div, origNode) {
  561. origNode = origNode || div;
  562. let w, h;
  563. const np = origNode.parentElement;
  564. const style = getComputedStyle(np);
  565. let parentWidth = parseFloat(style.width) -
  566. floatPadding(np, style, 'Left') -
  567. floatPadding(np, style, 'Right');
  568. if (+style.columnCount > 1)
  569. parentWidth = (parentWidth + parseFloat(style.columnGap)) / style.columnCount -
  570. parseFloat(style.columnGap);
  571. switch (cfg.resize) {
  572. case 'Original':
  573. if (div.FYTE.originalWidth === 320 && div.FYTE.originalHeight === 200) {
  574. w = parentWidth;
  575. h = parentWidth / 16 * 9;
  576. } else {
  577. w = div.FYTE.originalWidth;
  578. h = div.FYTE.originalHeight;
  579. }
  580. break;
  581. case 'Custom':
  582. w = cfg.width;
  583. h = cfg.height;
  584. break;
  585. case '1080p':
  586. case '720p':
  587. case '480p':
  588. case '360p':
  589. h = parseInt(cfg.resize);
  590. w = h / 9 * 16;
  591. break;
  592. default: { // fit-to-width mode
  593. let n = origNode;
  594. do {
  595. n = n.parentElement;
  596. // find parent node with nonzero width (i.e. independent of our video element)
  597. } while (n && !(w = n.clientWidth));
  598. if (w)
  599. h = w / 16 * 9;
  600. else {
  601. w = origNode.clientWidth;
  602. h = origNode.clientHeight;
  603. }
  604. }
  605. }
  606. if (parentWidth > 0 && parentWidth < w) {
  607. h *= parentWidth / w;
  608. w = parentWidth;
  609. }
  610. if (cfg.resize === 'Fit to width' && h < div.FYTE.originalHeight * 0.9)
  611. h = Math.min(div.FYTE.originalHeight, w / div.FYTE.originalWidth * div.FYTE.originalHeight);
  612.  
  613. return {w: window.chrome ? w : Math.round(w), h: h};
  614. }
  615.  
  616. function parseVideoInfo(response) {
  617. const div = response.context;
  618. const txt = response.responseText;
  619. const reason = txt.match(/(^|&)reason=(.+?)(&|$)|$/)[2];
  620. const info = tryJSONparse(
  621. decodeURIComponent(txt.match(/(^|&)player_response=(.+?)(&|$)|$/)[2] || '')) || {};
  622. const vid = info.videoDetails || {};
  623. const streams = info.streamingData || {};
  624. const cache = div.FYTE.cache;
  625. let shouldUpdateCache = false;
  626.  
  627. const videoSources = [];
  628. const fmts = (streams.formats || streams.adaptiveFormats || [])
  629. .sort((a, b) => b.width - a.width || b.height - a.height);
  630. // parse width & height to adjust the thumbnail
  631. if (fmts.length &&
  632. (cache.videoWidth !== fmts[0].width || cache.videoHeight !== fmts[0].height)) {
  633. fixThumbnailAR(div, fmts[0].width, fmts[0].height);
  634. cache.videoWidth = fmts[0].width;
  635. cache.videoHeight = fmts[0].height;
  636. shouldUpdateCache = true;
  637. }
  638.  
  639. // parse video sources
  640. for (const f of fmts) {
  641. const codec = f.mimeType.match(/codecs="([^.]+)|$/)[1] || '';
  642. const type = f.mimeType.split(/[/;]/)[1];
  643. let src = f.url;
  644. if (!src && f.cipher) {
  645. const sp = {};
  646. for (const str of f.cipher.split('&')) {
  647. const [k, v] = str.split('=');
  648. sp[k] = v;
  649. }
  650. src = decodeURIComponent(sp.url);
  651. if (sp.s) src += `&${sp.sp || 'sig'}=${decodeYoutubeSignature(sp.s)}`;
  652. }
  653. videoSources.push({
  654. src,
  655. title: [
  656. f.quality,
  657. f.qualityLabel !== f.quality ? f.qualityLabel : '',
  658. type + (codec ? `:${codec}` : ''),
  659. ].filter(Boolean).join(', '),
  660. });
  661. }
  662.  
  663. let fps = new Set();
  664. for (const f of streams.adaptiveFormats || []) {
  665. if (f.fps)
  666. fps.add(f.fps);
  667. }
  668. fps = [...fps].join('/');
  669. if (fps && cache.fps !== fps) {
  670. cache.fps = fps;
  671. shouldUpdateCache = true;
  672. }
  673.  
  674. let duration = div.FYTE.duration = vid.lengthSeconds | 0;
  675. if (duration) {
  676. duration = secondsToTimeString(duration);
  677. if (cache.duration !== duration) {
  678. cache.duration = duration;
  679. shouldUpdateCache = true;
  680. }
  681. }
  682. if (duration || fps)
  683. duration = `<span>${duration}</span>${fps ? `<i>${fps}fps</i>` : ''}`;
  684.  
  685. const title = decodeURIComponent(vid.title || reason || '').replace(/\+/g, ' ');
  686. if (title) {
  687. $('.instant-youtube-title', div).innerHTML =
  688. (title ? `<strong>${title}</strong>` : '') + duration;
  689. if (cache.title !== title) {
  690. cache.title = title;
  691. shouldUpdateCache = true;
  692. }
  693. }
  694. if (cfg.pinnable !== 'off' && vid.title)
  695. makeDraggable(div);
  696.  
  697. if (reason) {
  698. div.setAttribute('disabled', '');
  699. if (cache.reason !== reason) {
  700. cache.reason = reason;
  701. shouldUpdateCache = true;
  702. }
  703. }
  704.  
  705. if (videoSources.length)
  706. div.FYTE.videoSources = videoSources;
  707.  
  708. if (txt.includes('playerStoryboardSpecRenderer') &&
  709. info.storyboards &&
  710. div.FYTE.state !== 'scheduled play') {
  711. const m = info.storyboards.playerStoryboardSpecRenderer.spec.split('|');
  712. const [w, h, len, rows, cols] = m[m.length - 1].split('#').map(Number);
  713. div.FYTE.storyboard = {w, h, len, rows, cols};
  714. if (w * h > 2000) {
  715. div.FYTE.storyboard.url = m[0].replace('?', '&').replace(
  716. '$L/$N.jpg',
  717. `${m.length - 2}/M0.jpg?sigh=${m[m.length - 1].replace(/^.+?#([^#]+)$/, '$1')}`);
  718. const elSb = $('.instant-youtube-storyboard', div);
  719. if (elSb) {
  720. elSb.dataset.loaded = '';
  721. elSb.appendChild(overrideCSS($create('div.sb-thumb', {}, '\xA0'), {
  722. width: w - 1 + 'px',
  723. height: h + 'px',
  724. }));
  725. if (cfg.showStoryboard)
  726. updateHoverHandler(div);
  727. }
  728. }
  729. }
  730.  
  731. injectStylesIfNeeded();
  732.  
  733. if (div.FYTE.state === 'scheduled play')
  734. setTimeout(startPlayingDirectly, 0, div);
  735.  
  736. div.FYTE.state = '';
  737.  
  738. try {
  739. const cover = vid.thumbnail.thumbnails.pop().url;
  740. if (cache.cover !== cover) {
  741. cache.cover = cover;
  742. shouldUpdateCache = true;
  743. const img = $('img', div);
  744. if (img.src && img.src !== cover)
  745. img.src = setUrl(cover);
  746. }
  747. } catch (e) {
  748. }
  749. if (shouldUpdateCache)
  750. localStorage[`FYTE-cache-${cache.id}`] = JSON.stringify(cache);
  751. }
  752.  
  753. function decodeYoutubeSignature(s) {
  754. const a = s.split('');
  755. a.reverse();
  756. swap(a, 24);
  757. a.reverse();
  758. swap(a, 41);
  759. a.reverse();
  760. swap(a, 2);
  761. return a.join('');
  762. }
  763.  
  764. function swap(a, b) {
  765. const c = a[0];
  766. a[0] = a[b % a.length];
  767. a[b % a.length] = c;
  768. }
  769.  
  770. function fixThumbnailAR(div, w, h) {
  771. const img = $('img', div);
  772. if (!img)
  773. return;
  774. const thw = img.naturalWidth;
  775. const
  776. thh = img.naturalHeight;
  777. if (w && h) { // means thumbnail is still loading
  778. div.FYTE.cache.videoWidth = w;
  779. div.FYTE.cache.videoHeight = h;
  780. } else {
  781. w = div.FYTE.cache.videoWidth;
  782. h = div.FYTE.cache.videoHeight;
  783. if (!w || !h)
  784. return;
  785. }
  786. const divw = div.clientWidth;
  787. const
  788. divh = div.clientHeight;
  789. // if both video and thumbnail are 4:3, fit the image to height
  790. //console.log(div, divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  791. if (Math.abs(h / w * divw / divh - 1) > 0.05 && Math.abs(thh / thw * divw / divh - 1) > 0.05) {
  792. img.style.maxHeight = img.clientHeight + 'px';
  793. if (!div.FYTE.cache.videoWidth) // skip animation if thumbnail is already loaded
  794. img.style.transition = 'height 1s ease, margin-top 1s ease';
  795. setTimeout(() => {
  796. overrideCSS(img, Object.assign(
  797. {'max-height': 'none'},
  798. h / w >= divh / divw
  799. ? {width: 'auto', height: '100%'}
  800. : {width: '100%', height: 'auto'}));
  801. setTimeout(() => img.style.removeProperty('transition'), 1000);
  802. });
  803. }
  804. }
  805.  
  806. function trackMouse(e) {
  807. this.FYTE.mouseEvent = e;
  808. }
  809.  
  810. function updateHoverHandler(div) {
  811. const fyte = div.FYTE;
  812. const sb = fyte.storyboard;
  813. const elSb = $('.instant-youtube-storyboard', div);
  814. if (!cfg.showStoryboard) {
  815. elSb.hidden = true;
  816. return;
  817. }
  818. elSb.hidden = false;
  819. let oldIndex = null;
  820. const tracker = elSb.firstElementChild;
  821. const style = tracker.style;
  822. const sbImg = $create('img');
  823. const spinner = $create('span.loading-spinner');
  824. elSb.addEventListener('mousemove', storyboardHoverHandler);
  825. elSb.addEventListener('mouseout', storyboardHoverHandler);
  826. elSb.addEventListener('click', storyboardClickHandler, {once: true});
  827. div.addEventListener('mouseover', storyboardPreloader);
  828. div.addEventListener('mouseout', storyboardPreloader);
  829. if (div.closest(':hover'))
  830. storyboardPreloader({});
  831.  
  832. function storyboardClickHandler(e) {
  833. const offsetX = e.offsetX || e.clientX - elSb.getBoundingClientRect().left;
  834. fyte.startAt = offsetX / elSb.clientWidth * fyte.duration | 0;
  835. fyte.srcEmbedFixed = setUrlParams(fyte.srcEmbedFixed, {start: fyte.startAt});
  836. startPlaying(div, {alternateMode: e.shiftKey});
  837. }
  838.  
  839. function storyboardPreloader(e) {
  840. if (e.type === 'mouseout') {
  841. spinner.remove();
  842. return;
  843. }
  844. const {len, rows, cols, preloaded} = sb || {};
  845. const lastpart = (len - 1) / (rows * cols || 1) | 0;
  846. if (lastpart <= 0 || preloaded)
  847. return;
  848. let part = 0;
  849. $create('img', {
  850. src: setStoryboardUrl(part++),
  851. onload() {
  852. if (part <= lastpart) {
  853. this.src = setStoryboardUrl(part++);
  854. return;
  855. }
  856. sb.preloaded = true;
  857. div.removeEventListener('mouseover', storyboardPreloader);
  858. div.removeEventListener('mouseout', storyboardPreloader);
  859. this.onload = null;
  860. this.src = '';
  861. spinner.remove();
  862. },
  863. });
  864. if (elSb.matches(':hover') && fyte.mouseEvent)
  865. storyboardHoverHandler(fyte.mouseEvent);
  866. }
  867.  
  868. function setStoryboardUrl(part) {
  869. return setUrl(sb.url.replace(/M\d+\.jpg\?/, `M${part}.jpg?`));
  870. }
  871.  
  872. function storyboardHoverHandler(e) {
  873. div.removeEventListener('mousemove', trackMouse);
  874. if (!cfg.showStoryboard || !sb)
  875. return;
  876. if (e.type === 'mouseout') {
  877. sbImg.onload && sbImg.onload();
  878. return;
  879. }
  880. const {w, h, cols, rows, len, preloaded} = sb;
  881. const partlen = rows * cols;
  882.  
  883. const offsetX = e.offsetX || e.clientX - elSb.getBoundingClientRect().left;
  884. const left = Math.min(elSb.clientWidth - w, Math.max(0, offsetX - w)) | 0;
  885. if (!style.left || parseInt(style.left) !== left) {
  886. style.left = `${left}px`;
  887. if (spinner.parentElement)
  888. spinner.style.cssText = important(`left:${left + w / 2 - 10}px; right:auto;`);
  889. }
  890.  
  891. let index = Math.min(offsetX / elSb.clientWidth * (len + 1) | 0, len - 1);
  892. if (index === oldIndex)
  893. return;
  894.  
  895. const part = index / partlen | 0;
  896. if (!oldIndex || part !== (oldIndex / partlen | 0)) {
  897. const url = setStoryboardUrl(part);
  898. style.setProperty('background-image', `url(${url})`, 'important');
  899. if (!preloaded) {
  900. if (spinner.timer)
  901. clearTimeout(spinner.timer);
  902. spinner.timer = setTimeout(() => {
  903. spinner.timer = 0;
  904. if (!sbImg.src)
  905. return;
  906. elSb.appendChild(spinner);
  907. spinner.style.cssText = important(`left:${left + w / 2 - 10}px; right:auto;`);
  908. }, 50);
  909. sbImg.onload = () => {
  910. clearTimeout(spinner.timer);
  911. spinner.remove();
  912. spinner.timer = 0;
  913. sbImg.onload = null;
  914. sbImg.src = '';
  915. };
  916. sbImg.src = url;
  917. }
  918. }
  919.  
  920. tracker.dataset.time = secondsToTimeString(index / (len - 1 || 1) * fyte.duration | 0);
  921. oldIndex = index;
  922. index %= partlen;
  923. style.setProperty('background-position',
  924. `-${(index % cols) * w}px -${(index / cols | 0) * h}px`, 'important');
  925. }
  926. }
  927.  
  928. function clickHandler(e) {
  929. const el = e.target;
  930. if (el.closest('a') ||
  931. e.type === 'mousedown' && e.button !== 1 ||
  932. e.type === 'click' && el.matches('.instant-youtube-options, .instant-youtube-options *'))
  933. return;
  934. if (e.type === 'click' && el.matches('.instant-youtube-options-button')) {
  935. showOptions(e);
  936. e.preventDefault();
  937. e.stopPropagation();
  938. return;
  939. }
  940.  
  941. e.preventDefault();
  942. e.stopPropagation();
  943. e.stopImmediatePropagation();
  944.  
  945. startPlaying(el.closest('.instant-youtube-container'), {
  946. alternateMode: e.shiftKey || el.matches('.instant-youtube-alternative'),
  947. fullscreen: e.button === 1,
  948. });
  949. }
  950.  
  951. function startPlaying(div, params) {
  952. div.removeEventListener('click', clickHandler);
  953. div.removeEventListener('mousedown', clickHandler);
  954.  
  955. $$remove([
  956. '.instant-youtube-alternative',
  957. '.instant-youtube-storyboard',
  958. '.instant-youtube-options-button',
  959. '.instant-youtube-options',
  960. ].join(','), div);
  961. $('svg', div).outerHTML = '<span class=instant-youtube-loading-spinner></span>';
  962.  
  963. if (cfg.pinnable !== 'off') {
  964. makePinnable(div);
  965. if (params && params.pin)
  966. $(`[pin="${params.pin}"]`, div).click();
  967. }
  968.  
  969. if (window !== top)
  970. parent.postMessage('iframe-allowfs', '*');
  971.  
  972. const fyte = div.FYTE;
  973. if ((!!cfg.playHTML5 + !!(params && params.alternateMode) === 1) &&
  974. (fyte.videoSources || fyte.state === 'querying')) {
  975. if (fyte.videoSources)
  976. startPlayingDirectly(div, params);
  977. else {
  978. // playback will start in parseVideoInfo
  979. fyte.state = 'scheduled play';
  980. // fallback to iframe in 5s
  981. setTimeout(() => {
  982. if (div.FYTE.state) {
  983. div.FYTE.state = '';
  984. switchToIFrame.call(div, params);
  985. }
  986. }, 5000);
  987. }
  988. } else
  989. switchToIFrame.call(div, params);
  990. }
  991.  
  992. function startPlayingDirectly(div, params) {
  993. const switchTimer = setTimeout(switchToIFrame.bind(div, params), 5000);
  994. const video = $create('video.embed', {
  995. autoplay: true,
  996. controls: true,
  997. volume: GM_getValue('volume', 0.5),
  998. style: {
  999. position: 'absolute',
  1000. left: 0,
  1001. top: 0,
  1002. right: 0,
  1003. bottom: 0,
  1004. padding: 0,
  1005. margin: 'auto',
  1006. opacity: 0,
  1007. width: '100%',
  1008. height: '100%',
  1009. },
  1010. oncanplay() {
  1011. this.oncanplay = null;
  1012. const fyte = div.FYTE;
  1013. if (fyte.startAt && Math.abs(this.currentTime - fyte.startAt) > 1)
  1014. this.currentTime = fyte.startAt;
  1015. clearTimeout(switchTimer);
  1016. pauseOtherVideos(this);
  1017. if (params && params.fullscreen)
  1018. return;
  1019. div.setAttribute('playing', '');
  1020. div.firstElementChild.appendChild(this);
  1021. overrideCSS(this, {opacity: 1});
  1022. },
  1023. onvolumechange() {
  1024. GM_setValue('volume', this.volume);
  1025. },
  1026. });
  1027.  
  1028. for (const src of div.FYTE.videoSources || []) {
  1029. video.appendChild($create('source', src))
  1030. .onerror = switchToIFrame.bind(div, params);
  1031. }
  1032.  
  1033. overrideCSS($('img', div), {
  1034. transition: 'opacity 1s',
  1035. opacity: '0',
  1036. });
  1037.  
  1038. if (params && params.fullscreen) {
  1039. div.firstElementChild.appendChild(video);
  1040. div.setAttribute('playing', '');
  1041. video.style.opacity = 1;
  1042. goFullscreen(video);
  1043. }
  1044.  
  1045. if (window.chrome && +navigator.userAgent.match(/Chrom\D+(\d+)|$/)[1] < 74)
  1046. video.addEventListener('click', () =>
  1047. setTimeout(() =>
  1048. video.paused ?
  1049. video.play() :
  1050. video.pause()));
  1051.  
  1052. const title = $('.instant-youtube-title', div);
  1053. if (title) {
  1054. video.onpause = () => (title.hidden = false);
  1055. video.onplay = () => (title.hidden = true);
  1056. }
  1057. }
  1058.  
  1059. function switchToIFrame(params, e) {
  1060. if (this.querySelector('iframe'))
  1061. return;
  1062. const div = this;
  1063. const wrapper = div.firstElementChild;
  1064. const fullscreen = params && params.fullscreen && !e;
  1065. if (e instanceof Event) {
  1066. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player',
  1067. div.FYTE.srcEmbed);
  1068. const video = e.target ? e.target.closest('video') : e.composedPath().pop();
  1069. video.textContent = '';
  1070. goFullscreen(video, false);
  1071. video.remove();
  1072. }
  1073.  
  1074. const url = setUrlParams(div.FYTE.srcEmbedFixed, {
  1075. html5: 1,
  1076. autoplay: 1,
  1077. autohide: 2,
  1078. border: 0,
  1079. controls: 1,
  1080. fs: 1,
  1081. showinfo: 1,
  1082. ssl: 1,
  1083. theme: 'dark',
  1084. enablejsapi: 1,
  1085. local: 'true',
  1086. quality: 'medium',
  1087. FYTEfullscreen: fullscreen | 0,
  1088. });
  1089.  
  1090. let iframe = $create('iframe.embed', {
  1091. src: url,
  1092. allow: 'autoplay; fullscreen',
  1093. allowFullscreen: true,
  1094. width: '100%',
  1095. height: '100%',
  1096. style: {
  1097. position: 'absolute',
  1098. top: 0,
  1099. left: 0,
  1100. right: 0,
  1101. padding: 0,
  1102. margin: 'auto',
  1103. opacity: 0,
  1104. border: 0,
  1105. },
  1106. });
  1107.  
  1108. if (cfg.pinnable !== 'off') {
  1109. $('[pin]', div).insertAdjacentElement('beforebegin', iframe);
  1110. } else {
  1111. wrapper.appendChild(iframe);
  1112. }
  1113.  
  1114. div.setAttribute('iframe', '');
  1115. div.setAttribute('playing', '');
  1116.  
  1117. iframe = $('iframe', div);
  1118. if (fullscreen) {
  1119. goFullscreen(iframe);
  1120. overrideCSS(iframe, {opacity: 1});
  1121. }
  1122.  
  1123. iframe.onload = () => {
  1124. addEventListener('message', YTlistener);
  1125. iframe.contentWindow.postMessage('{"event":"listening"}', '*');
  1126. if (cfg.invidious) {
  1127. overrideCSS(iframe, {opacity: 1});
  1128. $('.instant-youtube-title', div).hidden = true;
  1129. }
  1130. };
  1131. setTimeout(() => {
  1132. overrideCSS(iframe, {opacity: 1});
  1133. removeEventListener('message', YTlistener);
  1134. }, 5000);
  1135.  
  1136. function YTlistener(e) {
  1137. if (e.source !== iframe.contentWindow || !e.data)
  1138. return;
  1139. const data = tryJSONparse(e.data);
  1140. if (!data.info || data.info.playerState !== 1)
  1141. return;
  1142. removeEventListener('message', YTlistener);
  1143. pauseOtherVideos(iframe);
  1144. overrideCSS(iframe, {opacity: 1});
  1145. overrideCSS($('img', div), {display: 'none'});
  1146. $$remove('span, a', div);
  1147. }
  1148. }
  1149.  
  1150. function setUrl(url) {
  1151. if (cfg.invidious) {
  1152. const u = new URL(url);
  1153. u.hostname = 'invidio.us';
  1154. url = u.href.replace('/vi_webp/', '/vi/').replace('.webp', '.jpg');
  1155. }
  1156. return url;
  1157. }
  1158.  
  1159. function setUrlParams(url, params) {
  1160. const u = new URL(url);
  1161. for (const [k, v] of Object.entries(params))
  1162. u.searchParams.set(k, v);
  1163. return u.href;
  1164. }
  1165.  
  1166. function pauseOtherVideos(activePlayer) {
  1167. for (const v of $$('.instant-youtube-embed', activePlayer.ownerDocument)) {
  1168. if (v === activePlayer)
  1169. continue;
  1170. switch (v.localName) {
  1171. case 'video':
  1172. if (!v.paused)
  1173. v.pause();
  1174. break;
  1175. case 'iframe':
  1176. try {
  1177. v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*');
  1178. } catch (e) {}
  1179. break;
  1180. }
  1181. }
  1182. }
  1183.  
  1184. function goFullscreen(el, enable) {
  1185. if (enable !== false)
  1186. el.webkitRequestFullScreen && el.webkitRequestFullScreen() ||
  1187. el.mozRequestFullScreen && el.mozRequestFullScreen() ||
  1188. el.requestFullScreen && el.requestFullScreen();
  1189. else
  1190. document.webkitCancelFullScreen && document.webkitCancelFullScreen() ||
  1191. document.mozCancelFullScreen && document.mozCancelFullScreen() ||
  1192. document.cancelFullScreen && document.cancelFullScreen();
  1193. }
  1194.  
  1195. function makePinnable(div) {
  1196. div.firstElementChild.insertAdjacentHTML('beforeend',
  1197. '<div size-gripper></div>' +
  1198. '<div pin="top-left"></div>' +
  1199. '<div pin="top-right"></div>' +
  1200. '<div pin="bottom-right"></div>' +
  1201. '<div pin="bottom-left"></div>');
  1202.  
  1203. for (const pin of $$('[pin]', div)) {
  1204. if (cfg.pinnable === 'hide')
  1205. pin.setAttribute('transparent', '');
  1206. pin.onclick = pinClicked;
  1207. }
  1208. $('[size-gripper]', div).addEventListener('mousedown', startResize, true);
  1209.  
  1210. function pinClicked() {
  1211. const pin = this;
  1212. const pinIt = !div.hasAttribute('pinned') || !pin.hasAttribute('active');
  1213. const corner = pin.getAttribute('pin');
  1214. const video = $('video', div);
  1215. const paused = video.paused;
  1216. if (pinIt) {
  1217. for (const p of $$('[pin][active]', div))
  1218. p.removeAttribute('active');
  1219. pin.setAttribute('active', '');
  1220. if (!div.FYTE.unpinnedStyle) {
  1221. div.FYTE.unpinnedStyle = div.style.cssText;
  1222. const stub = div.cloneNode();
  1223. const img = $('img', div).cloneNode();
  1224. img.style.opacity = 1;
  1225. img.style.display = 'block';
  1226. img.title = '';
  1227. stub.appendChild(img);
  1228. stub.onclick = e => $('[pin][active]', div).onclick(e);
  1229. stub.style.setProperty('opacity', .3, 'important');
  1230. stub.setAttribute('stub', '');
  1231. div.FYTE.stub = stub;
  1232. div.parentNode.insertBefore(stub, div);
  1233. }
  1234. const size = constrainPinnedSize(div,
  1235. localStorage[`width#${location.hostname}`] || cfg.pinnedWidth);
  1236. overrideCSS(div, {
  1237. position: 'fixed',
  1238. width: size.w + 'px',
  1239. height: size.h + 'px',
  1240. top: corner.includes('top') ? 0 : 'auto',
  1241. left: corner.includes('left') ? 0 : 'auto',
  1242. right: corner.includes('right') ? 0 : 'auto',
  1243. bottom: corner.includes('bottom') ? 0 : 'auto',
  1244. 'z-index': 999999999,
  1245. });
  1246. adjustPinnedOffset(div, div, corner);
  1247. div.setAttribute('pinned', corner);
  1248. if (video && document.body)
  1249. document.body.appendChild(div);
  1250. } else { // unpin
  1251. pin.removeAttribute('active');
  1252. div.removeAttribute('pinned');
  1253. div.style.cssText = div.FYTE.unpinnedStyle;
  1254. div.FYTE.unpinnedStyle = '';
  1255. if (div.FYTE.stub) {
  1256. if (video && document.body)
  1257. div.FYTE.stub.parentNode.replaceChild(div, div.FYTE.stub);
  1258. div.FYTE.stub.remove();
  1259. div.FYTE.stub = null;
  1260. }
  1261. }
  1262. if (paused)
  1263. video.pause();
  1264. }
  1265.  
  1266. function startResize(e) {
  1267. const siteSaved = ('width#' + location.hostname) in localStorage;
  1268. let saveAs = siteSaved ? 'site' : 'global';
  1269. const oldSizeCSS = {w: div.style.width, h: div.style.height};
  1270. const oldDraggable = div.draggable;
  1271. div.draggable = false;
  1272.  
  1273. const gripper = this;
  1274. gripper.removeAttribute('tried-exceeding');
  1275. gripper.innerHTML = `<div>
  1276. <div save-as="${saveAs}"><b>S</b> = Site mode: <span>${getSiteOnlyText()}</span></div>
  1277. ${!siteSaved ? '' : '<div><b>R</b> = Reset to global size</div>'}
  1278. <div><b>Esc</b> = Cancel</div>
  1279. </div>`;
  1280. document.addEventListener('mousemove', resize);
  1281. document.addEventListener('mouseup', resizeDone);
  1282. document.addEventListener('keydown', resizeKeyDown);
  1283. e.stopImmediatePropagation();
  1284. return false;
  1285.  
  1286. function getSiteOnlyText() {
  1287. return saveAs === 'site' ? `only ${location.hostname}` : 'global';
  1288. }
  1289.  
  1290. function resize(e) {
  1291. let deltaX = e.movementX || e.webkitMovementX || e.mozMovementX || 0;
  1292. if (/right/.test(div.getAttribute('pinned')))
  1293. deltaX = -deltaX;
  1294. const newSize = constrainPinnedSize(div, div.clientWidth + deltaX);
  1295. if (newSize.w !== div.clientWidth) {
  1296. div.style.setProperty('width', newSize.w + 'px', 'important');
  1297. div.style.setProperty('height', newSize.h + 'px', 'important');
  1298. gripper.removeAttribute('tried-exceeding');
  1299. } else if (newSize.triedExceeding) {
  1300. gripper.setAttribute('tried-exceeding', '');
  1301. }
  1302. window.getSelection().removeAllRanges();
  1303. return false;
  1304. }
  1305.  
  1306. function resizeDone() {
  1307. div.draggable = oldDraggable;
  1308. gripper.removeAttribute('tried-exceeding');
  1309. gripper.innerHTML = '';
  1310. document.removeEventListener('mousemove', resize);
  1311. document.removeEventListener('mouseup', resizeDone);
  1312. document.removeEventListener('keydown', resizeKeyDown);
  1313. switch (saveAs) {
  1314. case 'site':
  1315. localStorage[`width#${location.hostname}`] = div.clientWidth;
  1316. break;
  1317. case 'global':
  1318. cfg.pinnedWidth = div.clientWidth;
  1319. GM_setValue('pinnedWidth', cfg.pinnedWidth);
  1320. // fallthrough to remove the locally saved value
  1321. case 'reset':
  1322. localStorage.removeItem(`width#${location.hostname}`);
  1323. break;
  1324. case '':
  1325. return false;
  1326. }
  1327. gripper.setAttribute('saveAs', saveAs);
  1328. setTimeout(() => gripper.removeAttribute('saveAs'), 250);
  1329. return false;
  1330. }
  1331.  
  1332. function resizeKeyDown(e) {
  1333. switch (e.code) {
  1334. case 'Escape':
  1335. saveAs = 'cancel';
  1336. div.style.width = oldSizeCSS.w;
  1337. div.style.height = oldSizeCSS.h;
  1338. break;
  1339. case 'KeyS':
  1340. saveAs = saveAs === 'site' ? 'global' : 'site';
  1341. $('[save-as]', gripper).setAttribute('save-as', saveAs);
  1342. $('[save-as] span', gripper).textContent = getSiteOnlyText();
  1343. return false;
  1344. case 'KeyR': {
  1345. if (!siteSaved)
  1346. return;
  1347. saveAs = 'reset';
  1348. const {w, h} = constrainPinnedSize(div, cfg.pinnedWidth);
  1349. div.style.width = w;
  1350. div.style.height = h;
  1351. break;
  1352. }
  1353. default:
  1354. return;
  1355. }
  1356. document.dispatchEvent(new MouseEvent('mouseup'));
  1357. return false;
  1358. }
  1359. }
  1360. }
  1361.  
  1362. function makeDraggable(div) {
  1363. div.draggable = true;
  1364. div.addEventListener('dragstart', e => {
  1365. const offsetY = e.offsetY || e.clientY - div.getBoundingClientRect().top;
  1366. if (offsetY > div.clientHeight - 30) {
  1367. e.preventDefault();
  1368. return;
  1369. }
  1370.  
  1371. e.dataTransfer.setData('text/plain', '');
  1372.  
  1373. let dropZone = $create('div.dragndrop-placeholder');
  1374. const dropZoneHeight = 400 / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight;
  1375.  
  1376. document.body.addEventListener('dragenter', dragHandler);
  1377. document.body.addEventListener('dragover', dragHandler);
  1378. document.body.addEventListener('dragend', dragHandler);
  1379. document.body.addEventListener('drop', dragHandler);
  1380.  
  1381. function dragHandler(e) {
  1382. e.stopImmediatePropagation();
  1383. e.stopPropagation();
  1384. e.preventDefault();
  1385. switch (e.type) {
  1386. case 'dragover': {
  1387. const playing = div.hasAttribute('playing');
  1388. const stub = e.target.closest('.instant-youtube-container[stub]') === div.FYTE.stub &&
  1389. div.FYTE.stub;
  1390. const gizmo = playing && !stub
  1391. ? {left: 0, top: 0, right: innerWidth, bottom: innerHeight}
  1392. : (stub || div).getBoundingClientRect();
  1393. const x = e.clientX;
  1394. const y = e.clientY;
  1395. const cx = (gizmo.left + gizmo.right) / 2;
  1396. const cy = (gizmo.top + gizmo.bottom) / 2;
  1397. const stay = !!stub || y >= cy - 200 && y <= cy + 200 && x >= cx - 200 && x <= cx + 200;
  1398. overrideCSS(dropZone, {
  1399. top: y < cy || stay ? '0' : 'auto',
  1400. bottom: y > cy || stay ? '0' : 'auto',
  1401. left: x < cx || stay ? '0' : 'auto',
  1402. right: x > cx || stay ? '0' : 'auto',
  1403. width: playing && stay && stub ? stub.clientWidth + 'px' : '400px',
  1404. height: playing && stay && stub ? stub.clientHeight + 'px' : dropZoneHeight + 'px',
  1405. margin: playing && stay ? 'auto' : '0',
  1406. position: !playing && stay || stub ? 'absolute' : 'fixed',
  1407. 'background-color': stub ?
  1408. 'rgba(0,0,255,0.5)' :
  1409. stay ? 'rgba(255,255,0,0.4)' : 'rgba(0,255,0,0.2)',
  1410. });
  1411. adjustPinnedOffset(dropZone, div);
  1412. (stay && !playing || stub ? (stub || div) : document.body).appendChild(dropZone);
  1413. break;
  1414. }
  1415. case 'dragend':
  1416. case 'drop': {
  1417. const corner = calcPinnedCorner(dropZone);
  1418. dropZone.remove();
  1419. dropZone = null;
  1420. document.body.removeEventListener('dragenter', dragHandler);
  1421. document.body.removeEventListener('dragover', dragHandler);
  1422. document.body.removeEventListener('dragend', dragHandler);
  1423. document.body.removeEventListener('drop', dragHandler);
  1424. if (e.type === 'dragend')
  1425. break;
  1426. if (div.hasAttribute('playing'))
  1427. (corner ? $(`[pin="${corner}"]`, div) : div.FYTE.stub).click();
  1428. else
  1429. startPlaying(div, {pin: corner});
  1430. }
  1431. }
  1432. }
  1433. });
  1434. }
  1435.  
  1436. function adjustPinnedOffset(el, self, corner) {
  1437. let offset = 0;
  1438. if (!corner) corner = calcPinnedCorner(el);
  1439. for (const pin of $$(`.instant-youtube-container[pinned] [pin="${corner}"][active]`)) {
  1440. const container = pin.closest('[pinned]');
  1441. if (container !== el && container !== self) {
  1442. const {top, bottom} = container.getBoundingClientRect();
  1443. offset = Math.max(offset, el.style.top === '0px' ? bottom : innerHeight - top);
  1444. }
  1445. }
  1446. if (offset)
  1447. el.style[el.style.top === '0px' ? 'top' : 'bottom'] = offset + 'px';
  1448. }
  1449.  
  1450. function calcPinnedCorner(el) {
  1451. const t = el.style.top !== 'auto';
  1452. const l = el.style.left !== 'auto';
  1453. const r = el.style.right !== 'auto';
  1454. const b = el.style.bottom !== 'auto';
  1455. return t && b && l && r ? '' : `${t ? 'top' : 'bottom'}-${l ? 'left' : 'right'}`;
  1456. }
  1457.  
  1458. function constrainPinnedSize(div, width) {
  1459. const maxWidth = window.innerWidth - 100 | 0;
  1460. const triedExceeding = (width | 0) > maxWidth;
  1461. width = Math.max(200, Math.min(maxWidth, width | 0));
  1462. return {
  1463. w: width,
  1464. h: width / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight,
  1465. triedExceeding,
  1466. };
  1467. }
  1468.  
  1469. function showOptions(e) {
  1470. const [options] = translateHTML(`
  1471. <div class=instant-youtube-options>
  1472. <span>
  1473. <label tl style="width: 100% !important;">Size:&nbsp;
  1474. <select data-action=resize>
  1475. <option tl value=Original>Original
  1476. <option tl value="Fit to width">Fit to width
  1477. <option>360p
  1478. <option>480p
  1479. <option>720p
  1480. <option>1080p
  1481. <option tl value=Custom>Custom...
  1482. </select>
  1483. </label>&nbsp;
  1484. <label data-action=resize-custom ${cfg.resize !== 'Custom' ? 'disabled' : ''}>
  1485. <input type=number min=320 max=9999 tl-placeholder=width data-action=width step=1> x
  1486. <input type=number min=240 max=9999 tl-placeholder=height data-action=height step=1>
  1487. </label>
  1488. </span>
  1489. <label tl=content,title title=msgStoryboardTip>
  1490. <input data-action=showStoryboard type=checkbox>
  1491. msgStoryboard
  1492. </label>
  1493. <span>
  1494. <label tl=content,title title=msgDirectTip>
  1495. <input data-action=playHTML5 type=checkbox>
  1496. msgDirect
  1497. </label>
  1498. &nbsp;
  1499. <label tl=content,title title=msgDirectTip>
  1500. <input data-action=playHTML5Shown type=checkbox>
  1501. msgDirectShown
  1502. </label>
  1503. </span>
  1504. <label tl=content>
  1505. <input data-action=invidious type=checkbox>
  1506. msgInvidious
  1507. </label>
  1508. <label tl=content,title title=msgSafeTip>
  1509. <input data-action=skipCustom type=checkbox>
  1510. msgSafe
  1511. </label>
  1512. <table>
  1513. <tr>
  1514. <td><label tl=content,title title=msgPinningTip>msgPinning</label></td>
  1515. <td>
  1516. <select data-action=pinnable>
  1517. <option tl value=on>msgPinningOn
  1518. <option tl value=hide>msgPinningHover
  1519. <option tl value=off>msgPinningOff
  1520. </select>
  1521. </td>
  1522. </tr>
  1523. </table>
  1524. <span data-action=buttons>
  1525. <button tl data-action=ok>OK</button>
  1526. <button tl data-action=cancel>Cancel</button>
  1527. </span>
  1528. </div>
  1529. `);
  1530. for (const [k, v] of Object.entries(cfg)) {
  1531. const el = $(`[data-action=${k}]`, options);
  1532. if (el) el[el.type === 'checkbox' ? 'checked' : 'value'] = v;
  1533. }
  1534. $('[data-action=resize]', options).onchange = function () {
  1535. const v = this.value !== 'Custom';
  1536. const e = $('[data-action=resize-custom]', options);
  1537. e.children[0].disabled = e.children[1].disabled = v;
  1538. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  1539. };
  1540. $('[data-action=buttons]', options).onclick = e => {
  1541. const btn = e.target;
  1542. if (btn.dataset.action !== 'ok') {
  1543. options.remove();
  1544. return;
  1545. }
  1546. let shouldAdjust;
  1547. const oldCfg = Object.assign({}, cfg);
  1548. for (const [k, v] of Object.entries(cfg)) {
  1549. const el = $(`[data-action=${k}]`, options);
  1550. const newVal = el && (
  1551. el.type === 'checkbox' ? el.checked :
  1552. el.type === 'number' ? el.valueAsNumber :
  1553. el.value);
  1554. if (newVal != null && newVal !== v) {
  1555. GM_setValue(k, newVal);
  1556. cfg[k] = newVal;
  1557. shouldAdjust = true;
  1558. }
  1559. }
  1560. options.remove();
  1561. if (cfg.resize === 'Custom' && (cfg.width !== oldCfg.width || cfg.height !== oldCfg.height))
  1562. updateCustomSize(cfg.width, cfg.height);
  1563. if (cfg.showStoryboard !== oldCfg.showStoryboard)
  1564. $$('.instant-youtube-container').forEach(updateHoverHandler);
  1565. if (cfg.playHTML5 !== oldCfg.playHTML5 && cfg.playHTML5Shown) {
  1566. const alt = _(`msgPlay${cfg.playHTML5 ? '' : 'HTML5'}`);
  1567. for (const e of $$('.instant-youtube-alternative'))
  1568. e.textContent = alt;
  1569. }
  1570. if (cfg.playHTML5Shown !== oldCfg.playHTML5Shown)
  1571. updateAltPlayerCSS();
  1572. if (shouldAdjust)
  1573. adjustNodes(e, btn.closest('.instant-youtube-container'));
  1574. };
  1575. e.target.insertAdjacentElement('afterend', options);
  1576. }
  1577.  
  1578. function updateCustomSize(w, h) {
  1579. cfg.width = Math.min(9999, Math.max(320, w | 0 || cfg.width | 0));
  1580. cfg.height = Math.min(9999, Math.max(240, h | 0 || cfg.height | 0));
  1581. }
  1582.  
  1583. function updateAltPlayerCSS() {
  1584. const {sheet} = styledom;
  1585. const ALT = '.instant-youtube-alternative';
  1586. let len = sheet.cssRules.length;
  1587. if (sheet.cssRules[len - 1].selectorText === ALT)
  1588. sheet.deleteRule(--len);
  1589. sheet.insertRule(/*language=CSS*/ `${ALT} {
  1590. display: ${cfg.playHTML5Shown ? 'block' : 'none'} !important;
  1591. }`, len);
  1592. }
  1593.  
  1594. function important(cssText, rx = /;/g) {
  1595. return cssText.replace(rx, '!important;');
  1596. }
  1597.  
  1598. function $(sel, base = document) {
  1599. return base.querySelector(sel) || 0;
  1600. }
  1601.  
  1602. function $$(sel, base = document) {
  1603. return [...base.querySelectorAll(sel)];
  1604. }
  1605.  
  1606. function $create(tagCls, props, children) {
  1607. const [tag, cls] = tagCls.split('.');
  1608. const el = Object.assign(document.createElement(tag), props);
  1609. if (cls)
  1610. el.className = `instant-youtube-${cls}`;
  1611. if (props && typeof props.style === 'object')
  1612. overrideCSS(el, props.style);
  1613. if (children && typeof children !== 'object')
  1614. children = document.createTextNode(children);
  1615. if (children instanceof Node)
  1616. el.appendChild(children);
  1617. else if (Array.isArray(children))
  1618. el.append(...children.filter(Boolean));
  1619. return el;
  1620. }
  1621.  
  1622. function $$remove(sel, base = document) {
  1623. for (const el of base.querySelectorAll(sel))
  1624. el.remove();
  1625. }
  1626.  
  1627. function overrideCSS(el, props) {
  1628. const names = Object.keys(props);
  1629. el.style.cssText = el.style.cssText
  1630. .replace(new RegExp(`(^|\\s|;)(${names.join('|')})(:[^;]+)`, 'gi'), '$1')
  1631. .replace(/[^;]\s*$/, '$&;')
  1632. .replace(/^\s*;\s*/, '') + names.map(n => `${n}:${props[n]}!important;`).join(' ');
  1633. return el;
  1634. }
  1635.  
  1636. // fix dumb Firefox bug
  1637. function floatPadding(node, style, dir) {
  1638. const padding = style['padding' + dir];
  1639. if (padding.indexOf('%') < 0)
  1640. return parseFloat(padding);
  1641. return parseFloat(padding) * (parseFloat(style.width) || node.clientWidth) / 100;
  1642. }
  1643.  
  1644. function cleanupCache() {
  1645. const cutoff = Date.now() - CACHE_STALE_DURATION;
  1646. for (const k in localStorage) {
  1647. if (k.startsWith('FYTE-cache-')) {
  1648. const {lastUsed} = tryJSONparse(localStorage[k]) || {};
  1649. if (!lastUsed || lastUsed < cutoff)
  1650. delete localStorage[k];
  1651. }
  1652. }
  1653. for (const k of GM_listValues())
  1654. if (k.startsWith('cache-'))
  1655. GM_deleteValue(k);
  1656. }
  1657.  
  1658. function tryJSONparse(s) {
  1659. try {
  1660. return JSON.parse(s);
  1661. } catch (e) {}
  1662. }
  1663.  
  1664. function secondsToTimeString(sec) {
  1665. const h = sec / 3600 | 0;
  1666. const m = (sec / 60 | 0) % 60;
  1667. const s = sec % 60;
  1668. return `${h ? h + ':' : ''}${h && m < 10 ? 0 : ''}${m}:${s < 10 ? 0 : ''}${s}`;
  1669. }
  1670.  
  1671. function translateHTML(html) {
  1672. const tmp = $create('div', {innerHTML: html.trim().replace(/\n\s*/g, '')});
  1673. for (const node of $$('[tl]', tmp)) {
  1674. for (const what of (node.getAttribute('tl') || 'content').split(',')) {
  1675. let child;
  1676. if (what === 'content') {
  1677. for (const n of [...node.childNodes].reverse()) {
  1678. if (n.nodeType === Node.TEXT_NODE && n.textContent.trim()) {
  1679. child = n;
  1680. break;
  1681. }
  1682. }
  1683. } else
  1684. child = node.getAttributeNode(what);
  1685. if (!child)
  1686. continue;
  1687. const src = child.textContent;
  1688. const srcTrimmed = src.trim();
  1689. const tl = src.replace(srcTrimmed, _(srcTrimmed));
  1690. if (src !== tl)
  1691. child.textContent = tl;
  1692. }
  1693. }
  1694. return [...tmp.childNodes];
  1695. }
  1696.  
  1697. function initTL() {
  1698. const tlSource = {
  1699. msgWatch: {
  1700. en: 'watch on Youtube',
  1701. ru: 'открыть на Youtube',
  1702. },
  1703. msgPlay: {
  1704. en: 'Play with Youtube player',
  1705. ru: 'Включить плеер Youtube',
  1706. },
  1707. msgPlayHTML5: {
  1708. en: 'Play directly (up to 720p)',
  1709. ru: 'Включить напрямую (макс. 720p)',
  1710. },
  1711. msgAltPlayerHint: {
  1712. en: 'Shift-click to use alternative player',
  1713. ru: 'Shift-клик для смены типа плеера',
  1714. },
  1715. Options: {
  1716. ru: 'Опции',
  1717. },
  1718. 'Size:': {
  1719. ru: 'Размер:',
  1720. },
  1721. Original: {
  1722. ru: 'Исходный',
  1723. },
  1724. 'Fit to width': {
  1725. ru: 'На всю ширину',
  1726. },
  1727. 'Custom...': {
  1728. ru: 'Настроить...',
  1729. },
  1730. width: {
  1731. ru: 'ширина',
  1732. },
  1733. height: {
  1734. ru: 'высота',
  1735. },
  1736. msgStoryboard: {
  1737. en: 'Storyboard thumbnails on hover',
  1738. ru: 'Раскадровка при наведении курсора',
  1739. },
  1740. msgStoryboardTip: {
  1741. en: 'Show storyboard preview on mouse hover at the bottom',
  1742. ru: 'Показывать миникадры при наведении мыши на низ кавер-картинки',
  1743. },
  1744. msgDirect: {
  1745. en: 'Play directly',
  1746. ru: 'Встроенный плеер браузера',
  1747. },
  1748. msgDirectTip: {
  1749. en: 'Shift-click a thumbnail to use the alternative player',
  1750. ru: 'Удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  1751. },
  1752. msgDirectShown: {
  1753. en: 'Show under play button',
  1754. ru: 'Показывать под кнопкой ►',
  1755. },
  1756. msgInvidious: {
  1757. en: 'Use https://invidio.us to play videos',
  1758. ru: 'Использовать https://invidio.us в плеере',
  1759. },
  1760. msgSafe: {
  1761. en: 'Safe (skip videos with enablejsapi=1)',
  1762. ru: 'Консервативный режим',
  1763. },
  1764. msgSafeTip: {
  1765. en: 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)',
  1766. ru: 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 ' +
  1767. '(подействует после обновления страницы)',
  1768. },
  1769. msgPinning: {
  1770. en: 'Corner pinning',
  1771. ru: 'Закрепление по углам',
  1772. },
  1773. msgPinningTip: {
  1774. en: 'Enable corner pinning controls when a video is playing.\n' +
  1775. 'To restore the video click the active corner pin or the original video placeholder.',
  1776. ru: 'Включить шпильки по углам для закрепления видео во время просмотра.\n' +
  1777. 'Для отмены можно нажать еще раз на активированный угол или на заглушку, ' +
  1778. 'где исходно было видео',
  1779. },
  1780. msgPinningOn: {
  1781. en: 'On',
  1782. ru: 'Да',
  1783. },
  1784. msgPinningHover: {
  1785. en: 'On, hover a corner to show',
  1786. ru: 'Да, при наведении курсора',
  1787. },
  1788. msgPinningOff: {
  1789. en: 'Off',
  1790. ru: 'Нет',
  1791. },
  1792. OK: {
  1793. ru: 'ОК',
  1794. },
  1795. Cancel: {
  1796. ru: 'Оменить',
  1797. },
  1798. };
  1799. const browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  1800. const browserLangMajor = browserLang.replace(/-.+/, '');
  1801. const tl = {};
  1802. for (const k of Object.keys(tlSource)) {
  1803. const langs = tlSource[k];
  1804. const text = langs[browserLang] || langs[browserLangMajor];
  1805. if (text)
  1806. tl[k] = text;
  1807. }
  1808. return src => tl[src] || src;
  1809. }
  1810.  
  1811. function initPlayButton() {
  1812. [playbtn] = translateHTML(`
  1813. <svg class="instant-youtube-play-button">
  1814. <path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z"><title tl>msgAltPlayerHint</title></path>
  1815. <polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF"
  1816. points="33.3,41.4 33.3,17.75 56,29.6"></polygon>
  1817. </svg>`);
  1818. return playbtn;
  1819. }
  1820.  
  1821. function injectStylesIfNeeded(force) {
  1822. if (!fytedom[0] && !force)
  1823. return;
  1824. styledom = styledom || GM_addStyle(/*language=CSS*/ `
  1825. [class^="instant-youtube-"]:not(#foo) {
  1826. margin: 0;
  1827. padding: 0;
  1828. transform: none;
  1829. }
  1830. ` + important(/*language=CSS*/ `
  1831. .instant-youtube-container {
  1832. contain: strict;
  1833. display: block;
  1834. position: relative;
  1835. overflow: hidden;
  1836. cursor: pointer;
  1837. padding: 0;
  1838. margin: auto;
  1839. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1840. text-align: center;
  1841. background: black;
  1842. break-inside: avoid-column;
  1843. }
  1844. .instant-youtube-container[disabled] {
  1845. background: #888;
  1846. }
  1847. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1848. display: none;
  1849. }
  1850. .instant-youtube-container[pinned] {
  1851. box-shadow: 0 0 30px black;
  1852. }
  1853. .instant-youtube-container[playing] {
  1854. contain: none;
  1855. }
  1856. .instant-youtube-wrapper {
  1857. width: 100%;
  1858. height: 100%;
  1859. }
  1860. .instant-youtube-play-button {
  1861. display: block;
  1862. position: absolute;
  1863. width: 85px;
  1864. height: 60px;
  1865. left: 0;
  1866. right: 0;
  1867. top: 0;
  1868. bottom: 0;
  1869. margin: auto;
  1870. }
  1871. .instant-youtube-loading-spinner {
  1872. display: block;
  1873. position: absolute;
  1874. width: 20px;
  1875. height: 20px;
  1876. left: 0;
  1877. right: 0;
  1878. top: 0;
  1879. bottom: 0;
  1880. padding: 0;
  1881. margin: auto;
  1882. pointer-events: none;
  1883. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1884. }
  1885. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1886. fill: #CC181E;
  1887. }
  1888. .instant-youtube-alternative {
  1889. display: block;
  1890. position: absolute;
  1891. width: 20em;
  1892. height: 20px;
  1893. top: 50%;
  1894. left: 0;
  1895. right: 0;
  1896. margin: 60px auto;
  1897. padding: 0;
  1898. border: none;
  1899. text-align: center;
  1900. text-decoration: none;
  1901. text-shadow: 1px 1px 3px black;
  1902. color: white;
  1903. z-index: 8;
  1904. font-weight: normal;
  1905. font-size: 12px;
  1906. }
  1907. .instant-youtube-alternative:hover {
  1908. text-decoration: underline;
  1909. color: white;
  1910. background: transparent;
  1911. }
  1912. .instant-youtube-embed {
  1913. z-index: 10;
  1914. background: transparent;
  1915. transition: opacity .25s;
  1916. }
  1917. .instant-youtube-title {
  1918. z-index: 20;
  1919. display: block;
  1920. position: absolute;
  1921. width: auto;
  1922. top: 0;
  1923. left: 0;
  1924. right: 0;
  1925. margin: 0;
  1926. padding: 7px;
  1927. border: none;
  1928. text-shadow: 1px 1px 2px black;
  1929. text-align: center;
  1930. text-decoration: none;
  1931. color: white;
  1932. background-color: #0008;
  1933. }
  1934. .instant-youtube-title strong {
  1935. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1936. }
  1937. .instant-youtube-title strong::after {
  1938. content: " - ${_('msgWatch')}";
  1939. font-weight: normal;
  1940. margin-right: 1ex;
  1941. }
  1942. .instant-youtube-title span {
  1943. color: white;
  1944. }
  1945. .instant-youtube-title span::before {
  1946. content: "(";
  1947. }
  1948. .instant-youtube-title span::after {
  1949. content: ")";
  1950. }
  1951. .instant-youtube-title i::before {
  1952. content: ", ";
  1953. }
  1954. .instant-youtube-container .instant-youtube-title i {
  1955. all: unset;
  1956. opacity: .5;
  1957. font-style: normal;
  1958. color: white;
  1959. }
  1960. @-webkit-keyframes instant-youtube-fadein {
  1961. from { opacity: 0 }
  1962. to { opacity: 1 }
  1963. }
  1964. @-moz-keyframes instant-youtube-fadein {
  1965. from { opacity: 0 }
  1966. to { opacity: 1 }
  1967. }
  1968. @keyframes instant-youtube-fadein {
  1969. from { opacity: 0 }
  1970. to { opacity: 1 }
  1971. }
  1972. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1973. display: none;
  1974. margin: 0;
  1975. }
  1976. .instant-youtube-title:hover {
  1977. text-decoration: underline;
  1978. }
  1979. .instant-youtube-title strong {
  1980. color: white;
  1981. }
  1982. .instant-youtube-options-button {
  1983. opacity: 0.6;
  1984. position: absolute;
  1985. right: 0;
  1986. bottom: 0;
  1987. margin: 0;
  1988. padding: 1.5ex 2ex;
  1989. font-size: 11px;
  1990. text-shadow: 1px 1px 2px black;
  1991. color: white;
  1992. }
  1993. .instant-youtube-options-button:hover {
  1994. opacity: 1;
  1995. background: rgba(0, 0, 0, 0.5);
  1996. }
  1997. .instant-youtube-options {
  1998. display: flex;
  1999. position: absolute;
  2000. right: 0;
  2001. bottom: 0;
  2002. margin: 0;
  2003. padding: 1ex 1ex 2ex 2ex;
  2004. flex-direction: column;
  2005. align-items: flex-start;
  2006. line-height: 1.5;
  2007. text-align: left;
  2008. opacity: 1;
  2009. color: white;
  2010. background: black;
  2011. z-index: 999;
  2012. }
  2013. .instant-youtube-options * {
  2014. width: auto;
  2015. height: auto;
  2016. margin: 0;
  2017. padding: 0;
  2018. font: inherit;
  2019. font-size: 13px;
  2020. vertical-align: middle;
  2021. text-transform: none;
  2022. text-align: left;
  2023. border-radius: 0;
  2024. text-decoration: none;
  2025. color: white;
  2026. background: black;
  2027. }
  2028. .instant-youtube-options > * {
  2029. margin-top: 1ex;
  2030. }
  2031. .instant-youtube-options table {
  2032. all: unset;
  2033. display: table;
  2034. }
  2035. .instant-youtube-options tr {
  2036. all: unset;
  2037. display: table-row;
  2038. }
  2039. .instant-youtube-options td {
  2040. all: unset;
  2041. display: table-cell;
  2042. padding: 2px;
  2043. }
  2044. .instant-youtube-options label > * {
  2045. display: inline;
  2046. }
  2047. .instant-youtube-options select {
  2048. padding: .5ex .25ex;
  2049. border: 1px solid #444;
  2050. -webkit-appearance: menulist;
  2051. }
  2052. .instant-youtube-options [data-action="resize-custom"] input {
  2053. width: 9ex;
  2054. padding: .5ex .5ex .4ex;
  2055. border: 1px solid #666;
  2056. }
  2057. .instant-youtube-options [data-action="buttons"] {
  2058. margin-top: 1em;
  2059. }
  2060. .instant-youtube-options button {
  2061. margin: 0 1ex 0 0;
  2062. padding: .5ex 2ex;
  2063. border: 2px solid gray;
  2064. font-weight: bold;
  2065. }
  2066. .instant-youtube-options button:hover {
  2067. border-color: white;
  2068. }
  2069. .instant-youtube-options label[disabled] {
  2070. opacity: 0.25;
  2071. }
  2072. .instant-youtube-storyboard {
  2073. height: 33%;
  2074. max-height: 90px;
  2075. display: block;
  2076. position: absolute;
  2077. left: 0;
  2078. right: 0;
  2079. bottom: 0;
  2080. overflow: visible;
  2081. transition: background-color .5s .25s;
  2082. }
  2083. .instant-youtube-storyboard[data-loaded]:hover {
  2084. background-color: #0004;
  2085. }
  2086. .instant-youtube-storyboard div {
  2087. display: block;
  2088. position: absolute;
  2089. bottom: 0;
  2090. pointer-events: none;
  2091. border: 3px solid #888;
  2092. box-shadow: 2px 2px 10px black;
  2093. transition: opacity .25s ease;
  2094. background-color: transparent;
  2095. background-origin: content-box;
  2096. opacity: 0;
  2097. }
  2098. .instant-youtube-storyboard div::after {
  2099. content: attr(data-time);
  2100. opacity: .5;
  2101. color: #fff;
  2102. background-color: #000;
  2103. font-weight: bold;
  2104. font-size: 10px;
  2105. position: absolute;
  2106. bottom: 4px;
  2107. left: 4px;
  2108. padding: 1px 3px;
  2109. }
  2110. .instant-youtube-storyboard:hover div {
  2111. opacity: 1;
  2112. }
  2113. .instant-youtube-container [pin] {
  2114. display: block;
  2115. position: absolute;
  2116. width: 0;
  2117. height: 0;
  2118. margin: 0;
  2119. padding: 0;
  2120. top: auto; bottom: auto; left: auto; right: auto;
  2121. border-style: solid;
  2122. transition: opacity 2.5s ease-in, opacity 0.4s ease-out;
  2123. opacity: 0;
  2124. z-index: 100;
  2125. }
  2126. .instant-youtube-container[playing]:hover [pin]:not([transparent]) {
  2127. opacity: 1;
  2128. }
  2129. .instant-youtube-container[playing] [pin]:hover {
  2130. cursor: alias;
  2131. opacity: 1;
  2132. transition: opacity 0s;
  2133. }
  2134. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  2135. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  2136. .instant-youtube-container [pin=top-left] {
  2137. top: 0; left: 0;
  2138. border-width: 10px 10px 0 0;
  2139. border-color: red transparent transparent transparent;
  2140. }
  2141. .instant-youtube-container [pin=top-left][transparent] {
  2142. border-width: 10px 10px 0 0;
  2143. }
  2144. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  2145. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  2146. .instant-youtube-container [pin=top-right] {
  2147. top: 0; right: 0;
  2148. border-width: 0 10px 10px 0;
  2149. border-color: transparent red transparent transparent;
  2150. }
  2151. .instant-youtube-container [pin=top-right][transparent] {
  2152. border-width: 0 10px 10px 0;
  2153. }
  2154. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  2155. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  2156. .instant-youtube-container [pin=bottom-right] {
  2157. bottom: 0; right: 0;
  2158. border-width: 0 0 10px 10px;
  2159. border-color: transparent transparent red transparent;
  2160. }
  2161. .instant-youtube-container [pin=bottom-right][transparent] {
  2162. border-width: 0 0 10px 10px;
  2163. }
  2164. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  2165. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  2166. .instant-youtube-container [pin=bottom-left] {
  2167. bottom: 0; left: 0;
  2168. border-width: 10px 0 0 10px;
  2169. border-color: transparent transparent transparent red;
  2170. }
  2171. .instant-youtube-container [pin=bottom-left][transparent] {
  2172. border-width: 10px 0 0 10px;
  2173. }
  2174. .instant-youtube-dragndrop-placeholder {
  2175. z-index: 999999999;
  2176. margin: 0;
  2177. padding: 0;
  2178. background: rgba(0, 255, 0, 0.1);
  2179. border: 2px dotted green;
  2180. box-sizing: border-box;
  2181. pointer-events: none;
  2182. }
  2183. .instant-youtube-container [size-gripper] {
  2184. width: 0;
  2185. position: absolute;
  2186. top: 0;
  2187. bottom: 0;
  2188. cursor: e-resize;
  2189. border-color: rgba(50,100,255,0.5);
  2190. border-width: 12px;
  2191. background: rgba(50,100,255,0.2);
  2192. z-index: 99;
  2193. opacity: 0;
  2194. transition: opacity .1s ease-in-out, border-color .1s ease-in-out;
  2195. }
  2196. .instant-youtube-container[pinned*="right"] [size-gripper] {
  2197. border-style: none none none solid;
  2198. left: -4px;
  2199. }
  2200. .instant-youtube-container[pinned*="left"] [size-gripper] {
  2201. border-style: none solid none none;
  2202. right: -4px;
  2203. }
  2204. .instant-youtube-container [size-gripper]:hover {
  2205. opacity: 1;
  2206. }
  2207. .instant-youtube-container [size-gripper]:active {
  2208. opacity: 1;
  2209. width: auto;
  2210. left: -4px;
  2211. right: -4px;
  2212. }
  2213. .instant-youtube-container [size-gripper][tried-exceeding] {
  2214. border-color: rgba(255,0,0,0.5);
  2215. }
  2216. .instant-youtube-container [size-gripper][saveAs="global"] {
  2217. border-color: rgba(0,255,0,0.5);
  2218. }
  2219. .instant-youtube-container [size-gripper][saveAs="site"] {
  2220. border-color: rgba(0,255,255,0.5);
  2221. }
  2222. .instant-youtube-container [size-gripper][saveAs="reset"] {
  2223. border-color: rgba(255,255,0,0.5);
  2224. }
  2225. .instant-youtube-container [size-gripper][saveAs="cancel"] {
  2226. border-color: rgba(255,0,255,0.25);
  2227. }
  2228. .instant-youtube-container [size-gripper] > div {
  2229. white-space: nowrap;
  2230. color: white;
  2231. font-weight: normal;
  2232. line-height: 1.25;
  2233. text-align: left;
  2234. position: absolute;
  2235. top: 50%;
  2236. padding: 1ex 1em 1ex;
  2237. background-color: rgba(80,150,255,0.5);
  2238. }
  2239. .instant-youtube-container [size-gripper] [save-as="site"] {
  2240. font-weight: bold;
  2241. color: yellow;
  2242. }
  2243. .instant-youtube-container[pinned*="left"] [size-gripper] > div {
  2244. right: 0;
  2245. }
  2246. `, /;\n/g));
  2247. // move our rules to the end of HEAD to increase CSS specificity
  2248. if (styledom.nextElementSibling && document.head)
  2249. document.head.appendChild(styledom);
  2250. updateAltPlayerCSS();
  2251. }