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.

当前为 2020-04-19 提交的版本,查看 最新版本

  1. //#region Meta
  2. // ==UserScript==
  3. // @name FYTE /Fast YouTube Embedded/ Player
  4. // @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.
  5. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются заглушки для видео, которые можно щелкнуть для загрузки плеера, и почти сразу же появляются кавер-картинки с названием видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  6.  
  7. // @version 2.12.0
  8.  
  9. // @include *
  10. // @exclude /^https:\/\/(www\.)?youtube\.com\/(?!embed)/
  11. // @exclude https://accounts.google.*/o/oauth2/postmessageRelay*
  12. // @exclude https://clients*.google.*/youtubei/*
  13. // @exclude https://clients*.google.*/static/proxy*
  14.  
  15. // @author wOxxOm
  16. // @namespace wOxxOm.scripts
  17. // @license MIT License
  18.  
  19. // @grant GM_getValue
  20. // @grant GM_listValues
  21. // @grant GM_deleteValue
  22. // @grant GM_setValue
  23. // @grant GM_addStyle
  24. // @grant GM_xmlhttpRequest
  25.  
  26. // @connect www.youtube.com
  27. // @connect youtube.com
  28.  
  29. // @run-at document-start
  30.  
  31. // @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=
  32.  
  33. // @compatible chrome
  34. // @compatible firefox
  35. // @compatible opera
  36. // ==/UserScript==
  37. //#endregion
  38.  
  39. 'use strict';
  40.  
  41. // keep video info cache for a month since last time it's shown
  42. const CACHE_STALE_DURATION = 30 * 24 * 3600e3;
  43. const cfg = {
  44. width: 1280,
  45. height: 720,
  46. invidious: false,
  47. resize: 'Fit to width',
  48. pinnable: 'on',
  49. pinnedWidth: 400,
  50. playHTML5: false,
  51. playHTML5Shown: false,
  52. showStoryboard: true,
  53. skipCustom: true,
  54. };
  55. const checked = [];
  56. let _, fytedom, styledom, iframes, objects, persite, playbtn;
  57.  
  58. if (location.hostname === 'www.youtube.com') {
  59. if ((window.chrome || 0).app && window !== top)
  60. setupYoutubeFullscreenRelay();
  61. } else {
  62. for (const [k, def] of Object.entries(cfg)) {
  63. const v = GM_getValue(k, def);
  64. cfg[k] = typeof v === typeof def ? v : def;
  65. }
  66. _ = initTL();
  67. persite = getPersiteRule();
  68. fytedom = document.getElementsByClassName('instant-youtube-container');
  69. iframes = document.getElementsByTagName('iframe');
  70. objects = document.getElementsByTagName('object');
  71. updateCustomSize();
  72. findEmbeds([]);
  73. injectStylesIfNeeded();
  74. new MutationObserver(findEmbeds)
  75. .observe(document, {subtree: true, childList: true});
  76. document.addEventListener('DOMContentLoaded', e => {
  77. injectStylesIfNeeded();
  78. adjustNodesIfNeeded(e);
  79. setTimeout(cleanupCache, 60e3);
  80. }, {once: true});
  81. addEventListener('resize', adjustNodesIfNeeded, true);
  82. addEventListener('message', onMessageHost);
  83. }
  84.  
  85. function setupYoutubeFullscreenRelay() {
  86. parent.postMessage('FYTE-toggle-fullscreen-init', '*');
  87. addEventListener('message', function onMessage(e) {
  88. if (e.source !== parent ||
  89. e.data !== 'FYTE-toggle-fullscreen-init-confirmed')
  90. return;
  91. removeEventListener('message', onMessage);
  92. const fsbtn = document.getElementsByClassName('ytp-fullscreen-button');
  93. new MutationObserver(function () {
  94. if (fsbtn[0]) {
  95. this.disconnect();
  96. fsbtn[0].outerHTML = fsbtn[0].outerHTML.replace('aria-disabled="true"', '');
  97. fsbtn[0].addEventListener('click', () => {
  98. window.parent.postMessage('FYTE-toggle-fullscreen', '*');
  99. });
  100. }
  101. }).observe(document, {subtree: true, childList: true});
  102. });
  103. }
  104.  
  105. function getPersiteRule() {
  106. const h = '.' + location.hostname;
  107. const rule =
  108. h === '.developers.google.com' && {
  109. match: '[data-video-id]',
  110. src: e => '//youtube.com/embed/' + e.dataset.videoId,
  111. } ||
  112. h === '.play.google.com' && {
  113. eatparent: 0,
  114. } ||
  115. h.includes('.google.') && /(^|\.)google\.\w{2,3}(\.\w{2,3})?$/.test(h) && {
  116. cls: 'g-blk',
  117. query: 'a[href*="youtube.com/watch"][data-ved]',
  118. eatparent: 1,
  119. } ||
  120. h === '.pikabu.ru' && {
  121. cls: 'b-video',
  122. match: '[data-url*="youtube.com/embed"]',
  123. attr: 'data-url',
  124. } ||
  125. h === '.androidauthority.com' && {
  126. eatparent: '.video-container',
  127. } ||
  128. h === '.reddit.com' && {
  129. match: '[data-url*="youtube.com/"] [src*="/mediaembed"],' +
  130. '[data-url*="youtu.be/"] [src*="/mediaembed"]',
  131. src: e => e.closest('[data-url*="youtube.com/"], [data-url*="youtu.be/"]').dataset.url,
  132. } ||
  133. h.endsWith('.theverge.com') && {
  134. eatparent: '.p-scalable-video',
  135. } ||
  136. h === '.9gag.com' && {
  137. eatparent: 0,
  138. } ||
  139. h === '.reddit.com' && {
  140. match: '[data-url*="youtube.com"] iframe[src*="redditmedia.com/mediaembed"]',
  141. src: e => e.closest('[data-url*="youtube.com"]').dataset.url,
  142. } ||
  143. h === '.anilist.co' && {
  144. eatparent: '.youtube',
  145. };
  146. if (rule) {
  147. let {cls, match, query, tag} = rule;
  148. if (!tag && !cls)
  149. tag = 'iframe';
  150. if (!match && !query)
  151. match = '[src*="youtube.com/embed"]';
  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 (e.source)
  166. e.source.postMessage('FYTE-toggle-fullscreen-init-confirmed', '*');
  167. break;
  168. case 'FYTE-toggle-fullscreen':
  169. $$('iframe[allowfullscreen]').some(iframe => {
  170. if (iframe.contentWindow === e.source) {
  171. goFullscreen(iframe,
  172. !(document.fullScreenElement || document.fullScreen || document.mozFullScreen));
  173. return true;
  174. }
  175. });
  176. break;
  177. case 'iframe-allowfs':
  178. $$('iframe:not([allowfullscreen])').some(iframe => {
  179. if (iframe.contentWindow === e.source) {
  180. iframe.allowFullscreen = true;
  181. return true;
  182. }
  183. });
  184. if (window !== top)
  185. parent.postMessage('iframe-allowfs', '*');
  186. break;
  187. }
  188. }
  189.  
  190. function findEmbeds(mutations) {
  191. if (mutations.length === 1) {
  192. const added = mutations[0].addedNodes;
  193. if (!added[0] || !added[1] && added[0].nodeType === 3)
  194. return;
  195. }
  196. if (persite)
  197. for (let el of persite.nodes)
  198. if ((el = persite.match(el)))
  199. processEmbed(el, persite.src && persite.src(el) || el.getAttribute(persite.attr));
  200. for (const el of iframes) {
  201. if (!checked.includes(el)) {
  202. checked.push(el);
  203. const src = el.src || el.getAttribute('data-src');
  204. if (src.includes('yout') && /youtube(-nocookie)?\.com|youtu\.be/i.test(src))
  205. processEmbed(el, src);
  206. }
  207. }
  208. for (const el of objects) {
  209. if (!checked.includes(el)) {
  210. checked.push(el);
  211. const {src, value} = $('embed, [value*="youtu.be"], [value*="youtube.com"]', el) || {};
  212. if (src)
  213. processEmbed(el, src || el.getAttribute('data-src') ||
  214. `https://${value.match(/youtu\.be.*|youtube\.com.*/)[0]}`);
  215. }
  216. }
  217. }
  218.  
  219. function decodeEmbedUrl(url) {
  220. return /youtube(-nocookie)?\.com%2Fembed/.test(url) ?
  221. decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube(-nocookie)?\.com%2Fembed[^&]+).*$/i, '$1')) :
  222. url;
  223. }
  224.  
  225. function processEmbed(node, src) {
  226. src = src || node.src || node.href || '';
  227. let n = node;
  228. let np = n.parentNode;
  229. const srcFixed = decodeEmbedUrl(src)
  230. .replace(/\/(watch\?v=|v\/)/, '/embed/')
  231. .replace(/^([^?&]+)&/, '$1?');
  232. if (src.indexOf('cdn.embedly.com/') > 0 ||
  233. cfg.resize !== 'Original' && np && np.children.length === 1 && !np.className && !np.id) {
  234. n = location.hostname === 'disqus.com' ? np.parentNode : np;
  235. np = n.parentElement;
  236. }
  237. if (!np ||
  238. !np.parentNode ||
  239. cfg.skipCustom && srcFixed.includes('enablejsapi=1') ||
  240. srcFixed.includes('/embed/videoseries') ||
  241. node.matches('.instant-youtube-embed, .YTLT-embed, .ihvyoutube') ||
  242. node.style.position === 'fixed' ||
  243. node.onload // skip some retarded loaders
  244. )
  245. return;
  246.  
  247. let id = srcFixed.match(
  248. /(?:^(?:https?:)?\/\/)(?:www\.)?(?:youtube(?:-nocookie)?\.com\/(?:embed\/(?:v=)?|\/.*?[&?/]v[=/])|youtu\.be\/)([^\s,.()[\]?]+?)(?:[&?/].*|$)/);
  249. if (!id)
  250. return;
  251. id = id[1];
  252.  
  253. if (np.localName === 'object') {
  254. n = np;
  255. np = n.parentElement;
  256. }
  257.  
  258. let eatparent = persite && persite.eatparent || 0;
  259. if (typeof eatparent === 'string') {
  260. n = np.closest(eatparent) || n;
  261. } else {
  262. while (eatparent--) {
  263. n = np;
  264. np = n.parentElement;
  265. }
  266. }
  267.  
  268. createFYTE(node, n, id, setUrl(srcFixed));
  269. stopOriginalEmbed(node);
  270. }
  271.  
  272. function createFYTE(node, n, id, srcFixed, force) {
  273. if (!document.contains(n))
  274. return;
  275. const cache = tryJSONparse(localStorage[`FYTE-cache-${id}`]) || {id};
  276. const autoplay = /[?&](autoplay=1|ps=play)(&|$)/.test(srcFixed);
  277. const img = $create('img.thumbnail');
  278. if (!autoplay) {
  279. img.src = setUrl(cache.cover || `https://i.ytimg.com/vi/${id}/maxresdefault.jpg`);
  280. img.onerror = onCoverError;
  281. }
  282.  
  283. if (document.readyState !== 'complete' && !force) {
  284. const args = [...arguments];
  285. args[createFYTE.length - 1] = true;
  286. setTimeout(createFYTE, 0, ...args);
  287. return;
  288. }
  289.  
  290. injectStylesIfNeeded('force');
  291.  
  292. const div = $create('div.container');
  293. div.FYTE = {
  294. state: 'querying',
  295. srcEmbed: srcFixed.replace(/&$/, ''),
  296. originalWidth: /%/.test(node.width) ? 320 : node.width | 0 || n.clientWidth | 0,
  297. originalHeight: /%/.test(node.height) ? 200 : node.height | 0 || n.clientHeight | 0,
  298. cache: cache,
  299. };
  300. div.FYTE.srcEmbedFixed =
  301. div.FYTE.srcEmbed.replace(/^http:/, 'https:')
  302. .replace(/([&?])(wmode=\w+|feature=oembed)&?/, '$1')
  303. .replace(/[&?]$/, '');
  304. div.FYTE.srcWatchFixed =
  305. div.FYTE.srcEmbedFixed.replace('/embed/', '/watch?v=').replace(/(\?.*?)\?/, '$1&');
  306.  
  307. cache.lastUsed = Date.now();
  308. localStorage[`FYTE-cache-${id}`] = JSON.stringify(cache);
  309.  
  310. if (cache.reason)
  311. div.setAttribute('disabled', '');
  312.  
  313. const divSize = calcContainerSize(div, n);
  314. const origStyle = getComputedStyle(n);
  315. overrideCSS(div, Object.assign(
  316. {
  317. height: persite && persite.eatparent === 0 ? '100%' : divSize.h + 'px',
  318. 'min-width': Math.min(divSize.w, div.FYTE.originalWidth) + 'px',
  319. 'min-height': Math.min(divSize.h, div.FYTE.originalHeight) + 'px',
  320. 'max-width': divSize.w + 'px',
  321. },
  322. origStyle.transform && {
  323. transform: origStyle.transform,
  324. },
  325. !autoplay && {
  326. 'background-color': 'transparent',
  327. transition: 'background-color 2s',
  328. },
  329. // eslint-disable-next-line no-proto
  330. ...Object.keys(origStyle.hasOwnProperty('position') ? origStyle : origStyle.__proto__ /*FF*/)
  331. .filter(k => /^(position|left|right|top|bottom)$/.test(k) &&
  332. !/^(auto|static|block)$/.test(origStyle[k]))
  333. .map(k => ({[k]: origStyle[k]})),
  334. origStyle.display === 'inline' && {
  335. display: 'inline-block',
  336. width: '100%',
  337. },
  338. cfg.resize === 'Fit to width' && {
  339. width: '100%',
  340. }));
  341. if (!autoplay) {
  342. setTimeout(() => div.style.removeProperty('background-color'));
  343. setTimeout(() => div.style.removeProperty('transition'), 2000);
  344. }
  345.  
  346. const wrapper = $create('div.wrapper', {}, [
  347. img,
  348. $create('a.title', {target: '_blank', href: div.FYTE.srcWatchFixed},
  349. cache.title || cache.reason
  350. ? [
  351. $create('strong', {}, cache.title || cache.reason || ''),
  352. cache.duration && $create('span', {}, cache.duration),
  353. cache.fps && $create('i', {}, `${cache.fps}fps`),
  354. ]
  355. : '\xA0'),
  356. (playbtn || initPlayButton()).cloneNode(true),
  357. $create('span.alternative', {}, _(`msgPlay${cfg.playHTML5 ? 'HTML5' : ''}`)),
  358. $create('div.storyboard', {hidden: !cfg.showStoryboard}),
  359. $create('div.options-button', {}, _('Options')),
  360. ]);
  361. div.appendChild(wrapper);
  362.  
  363. overrideCSS(img, Object.assign({
  364. position: 'absolute',
  365. margin: 'auto',
  366. padding: 0,
  367. top: 0,
  368. left: 0,
  369. right: 0,
  370. bottom: 0,
  371. 'max-width': 'none',
  372. 'max-height': 'none',
  373. }, !cache.cover && {
  374. transition: 'opacity 0.1s ease-out',
  375. opacity: 0,
  376. }));
  377. img.FYTE = [div, divSize, autoplay];
  378. img.onload = onCoverLoad;
  379. if (cache.coverWidth || img.naturalWidth)
  380. img.onload();
  381.  
  382. n.parentNode.insertBefore(div, n);
  383. n.remove();
  384.  
  385. if (!cache.title && !cache.reason || autoplay && cfg.playHTML5)
  386. fetchInfo.call(div);
  387.  
  388. if (autoplay) {
  389. startPlaying(div);
  390. } else {
  391. div.addEventListener('click', clickHandler);
  392. div.addEventListener('mousedown', clickHandler);
  393. div.addEventListener('mouseenter', fetchInfo);
  394. }
  395. if (cfg.showStoryboard)
  396. div.addEventListener('mousemove', trackMouse);
  397. }
  398.  
  399. function fetchInfo(e) {
  400. this.FYTE.mouseEvent = e;
  401. this.removeEventListener('mouseenter', fetchInfo);
  402. if (!this.FYTE.storyboard) {
  403. GM_xmlhttpRequest({
  404. method: 'GET',
  405. url: 'https://www.youtube.com/get_video_info?video_id=' + this.FYTE.cache.id +
  406. '&hl=en_US&html5=1&el=embedded&eurl=' + encodeURIComponent(location.href),
  407. context: this,
  408. onload: parseVideoInfo,
  409. });
  410. }
  411. }
  412.  
  413. function onCoverLoad(e) {
  414. const data = [...this.FYTE || []];
  415. const div = data.shift();
  416. const cache = div.FYTE.cache;
  417. const divSize = data.shift();
  418. const autoplay = data.shift();
  419. if (this.naturalWidth <= 120 && !cache.cover)
  420. return this.onerror(e);
  421. // delete this.FYTE;
  422. let fitToWidth = true;
  423. if (this.naturalHeight || cache.coverHeight) {
  424. if (!cache.coverHeight) {
  425. cache.coverWidth = this.naturalWidth;
  426. cache.coverHeight = this.naturalHeight;
  427. localStorage[`FYTE-cache-${cache.id}`] = JSON.stringify(cache);
  428. }
  429. const ratio = cache.coverWidth / cache.coverHeight;
  430. if (ratio > 4.1 / 3 && ratio < divSize.w / divSize.h) {
  431. this.style.setProperty('width', 'auto', 'important');
  432. this.style.setProperty('height', '100%', 'important');
  433. fitToWidth = false;
  434. }
  435. }
  436. if (fitToWidth) {
  437. this.style.setProperty('width', '100%', 'important');
  438. this.style.setProperty('height', 'auto', 'important');
  439. }
  440. if (cache.videoWidth)
  441. fixThumbnailAR(div);
  442. if (!autoplay)
  443. this.style.opacity = 1;
  444. }
  445.  
  446. function onCoverError() {
  447. const src = this.src;
  448. if (src.includes('maxresdefault'))
  449. this.src = src.replace('maxresdefault', 'sddefault');
  450. else if (src.includes('sddefault'))
  451. this.src = src.replace('sddefault', 'hqdefault');
  452. }
  453.  
  454. function stopOriginalEmbed(node) {
  455. const src = 'data:,';
  456. let n = node;
  457. while (n) {
  458. if (n.src)
  459. n.src = src;
  460. if (n.dataset.src)
  461. n.dataset.src = src;
  462. n = $('embed', n);
  463. }
  464. for (const el of $$('[value*="youtu.be"], [value*="youtube.com"]', node))
  465. el.value = src;
  466. }
  467.  
  468. function adjustNodesIfNeeded(e) {
  469. if (!fytedom[0])
  470. return;
  471. if (adjustNodesIfNeeded.scheduled)
  472. clearTimeout(adjustNodesIfNeeded.scheduled);
  473. adjustNodesIfNeeded.scheduled = setTimeout(() => {
  474. adjustNodes(e);
  475. adjustNodesIfNeeded.scheduled = 0;
  476. }, 16);
  477. }
  478.  
  479. function adjustNodes(event, clickedContainer) {
  480. const force = !!clickedContainer;
  481. let nearest = force ? clickedContainer : null;
  482. let nearestCenterYpct;
  483.  
  484. const vids = $$('.instant-youtube-container:not([pinned]):not([stub])');
  485.  
  486. if (!nearest && event.type !== 'DOMContentLoaded') {
  487. let minDistance = window.innerHeight * 3 / 4 | 0;
  488. const nearTargetY = window.innerHeight / 2;
  489. for (const n of vids) {
  490. const bounds = n.getBoundingClientRect();
  491. const distance = Math.abs((bounds.bottom + bounds.top) / 2 - nearTargetY);
  492. if (distance < minDistance) {
  493. minDistance = distance;
  494. nearest = n;
  495. }
  496. }
  497. }
  498.  
  499. if (nearest) {
  500. const bounds = nearest.getBoundingClientRect();
  501. nearestCenterYpct = (bounds.top + bounds.bottom) / 2 / window.innerHeight;
  502. }
  503.  
  504. let resized = false;
  505.  
  506. for (const n of vids) {
  507. const size = calcContainerSize(n);
  508. const w = size.w;
  509. const h = size.h;
  510.  
  511. // prevent parent clipping
  512. for (let e = n.parentElement, style; e; e = e.parentElement) {
  513. if (e.style.overflow !== 'visible' &&
  514. n.offsetTop < e.clientHeight / 2 &&
  515. n.offsetTop + n.clientHeight > e.clientHeight &&
  516. (style = getComputedStyle(e)) &&
  517. /hidden|scroll/.test(style.overflow + style.overflowX + style.overflowY)) {
  518. overrideCSS(e, {
  519. overflow: 'visible',
  520. 'overflow-x': 'visible',
  521. 'overflow-y': 'visible',
  522. });
  523. }
  524. }
  525.  
  526. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  527. continue;
  528.  
  529. overrideCSS(n, Object.assign({},
  530. n.style.maxWidth !== `${w}px` && {
  531. 'max-width': `${w}px`,
  532. },
  533. n.style.height !== h + 'px' && {
  534. height: h + 'px',
  535. },
  536. parseFloat(n.style.minWidth) > w && {
  537. 'min-width': n.style.maxWidth,
  538. },
  539. parseFloat(n.style.minHeight) > h && {
  540. 'min-height': n.style.height,
  541. }));
  542.  
  543. fixThumbnailAR(n);
  544. resized = true;
  545. }
  546.  
  547. if (resized && nearest)
  548. setTimeout(() => {
  549. const bounds = nearest.getBoundingClientRect();
  550. const h = bounds.bottom - bounds.top;
  551. const projectedCenterY = nearestCenterYpct * window.innerHeight;
  552. const projectedTop = projectedCenterY - h / 2;
  553. const safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  554. window.scrollBy(0, bounds.top - safeTop);
  555. }, 16);
  556. }
  557.  
  558. function calcContainerSize(div, origNode) {
  559. origNode = origNode || div;
  560. let w, h;
  561. const np = origNode.parentElement;
  562. const style = getComputedStyle(np);
  563. let parentWidth = parseFloat(style.width) -
  564. floatPadding(np, style, 'Left') -
  565. floatPadding(np, style, 'Right');
  566. if (+style.columnCount > 1)
  567. parentWidth = (parentWidth + parseFloat(style.columnGap)) / style.columnCount -
  568. parseFloat(style.columnGap);
  569. switch (cfg.resize) {
  570. case 'Original':
  571. if (div.FYTE.originalWidth === 320 && div.FYTE.originalHeight === 200) {
  572. w = parentWidth;
  573. h = parentWidth / 16 * 9;
  574. } else {
  575. w = div.FYTE.originalWidth;
  576. h = div.FYTE.originalHeight;
  577. }
  578. break;
  579. case 'Custom':
  580. w = cfg.width;
  581. h = cfg.height;
  582. break;
  583. case '1080p':
  584. case '720p':
  585. case '480p':
  586. case '360p':
  587. h = parseInt(cfg.resize);
  588. w = h / 9 * 16;
  589. break;
  590. default: { // fit-to-width mode
  591. let n = origNode;
  592. do {
  593. n = n.parentElement;
  594. // find parent node with nonzero width (i.e. independent of our video element)
  595. } while (n && !(w = n.clientWidth));
  596. if (w)
  597. h = w / 16 * 9;
  598. else {
  599. w = origNode.clientWidth;
  600. h = origNode.clientHeight;
  601. }
  602. }
  603. }
  604. if (parentWidth > 0 && parentWidth < w) {
  605. h *= parentWidth / w;
  606. w = parentWidth;
  607. }
  608. if (cfg.resize === 'Fit to width' && h < div.FYTE.originalHeight * 0.9)
  609. h = Math.min(div.FYTE.originalHeight, w / div.FYTE.originalWidth * div.FYTE.originalHeight);
  610.  
  611. return {w: window.chrome ? w : Math.round(w), h: h};
  612. }
  613.  
  614. function parseVideoInfo(response) {
  615. const div = response.context;
  616. const txt = response.responseText;
  617. const reason = txt.match(/(^|&)reason=(.+?)(&|$)|$/)[2];
  618. const info = tryJSONparse(
  619. decodeURIComponent(txt.match(/(^|&)player_response=(.+?)(&|$)|$/)[2] || '')) || {};
  620. const vid = info.videoDetails || {};
  621. const streams = info.streamingData || {};
  622. const cache = div.FYTE.cache;
  623. let shouldUpdateCache = false;
  624.  
  625. const videoSources = [];
  626. const fmts = (streams.formats || streams.adaptiveFormats || [])
  627. .sort((a, b) => b.width - a.width || b.height - a.height);
  628. // parse width & height to adjust the thumbnail
  629. if (fmts.length &&
  630. (cache.videoWidth !== fmts[0].width || cache.videoHeight !== fmts[0].height)) {
  631. fixThumbnailAR(div, fmts[0].width, fmts[0].height);
  632. cache.videoWidth = fmts[0].width;
  633. cache.videoHeight = fmts[0].height;
  634. shouldUpdateCache = true;
  635. }
  636.  
  637. // parse video sources
  638. for (const f of fmts) {
  639. const codec = f.mimeType.match(/codecs="([^.]+)|$/)[1] || '';
  640. const type = f.mimeType.split(/[/;]/)[1];
  641. let src = f.url;
  642. if (!src && f.cipher) {
  643. const sp = {};
  644. for (const str of f.cipher.split('&')) {
  645. const [k, v] = str.split('=');
  646. sp[k] = v;
  647. }
  648. src = decodeURIComponent(sp.url);
  649. if (sp.s) src += `&${sp.sp || 'sig'}=${decodeYoutubeSignature(sp.s)}`;
  650. }
  651. videoSources.push({
  652. src,
  653. title: [
  654. f.quality,
  655. f.qualityLabel !== f.quality ? f.qualityLabel : '',
  656. type + (codec ? `:${codec}` : ''),
  657. ].filter(Boolean).join(', '),
  658. });
  659. }
  660.  
  661. let fps = new Set();
  662. for (const f of streams.adaptiveFormats || []) {
  663. if (f.fps)
  664. fps.add(f.fps);
  665. }
  666. fps = [...fps].join('/');
  667. if (fps && cache.fps !== fps) {
  668. cache.fps = fps;
  669. shouldUpdateCache = true;
  670. }
  671.  
  672. let duration = div.FYTE.duration = vid.lengthSeconds | 0;
  673. if (duration) {
  674. duration = secondsToTimeString(duration);
  675. if (cache.duration !== duration) {
  676. cache.duration = duration;
  677. shouldUpdateCache = true;
  678. }
  679. }
  680. if (duration || fps)
  681. duration = `<span>${duration}</span>${fps ? `<i>, ${fps}fps</i>` : ''}`;
  682.  
  683. const title = decodeURIComponent(vid.title || reason || '').replace(/\+/g, ' ');
  684. if (title) {
  685. $('.instant-youtube-title', div).innerHTML =
  686. (title ? `<strong>${title}</strong>` : '') + duration;
  687. if (cache.title !== title) {
  688. cache.title = title;
  689. shouldUpdateCache = true;
  690. }
  691. }
  692. if (cfg.pinnable !== 'off' && vid.title)
  693. makeDraggable(div);
  694.  
  695. if (reason) {
  696. div.setAttribute('disabled', '');
  697. if (cache.reason !== reason) {
  698. cache.reason = reason;
  699. shouldUpdateCache = true;
  700. }
  701. }
  702.  
  703. if (videoSources.length)
  704. div.FYTE.videoSources = videoSources;
  705.  
  706. if (txt.includes('playerStoryboardSpecRenderer') &&
  707. info.storyboards &&
  708. div.FYTE.state !== 'scheduled play') {
  709. const m = info.storyboards.playerStoryboardSpecRenderer.spec.split('|');
  710. const [w, h, len, rows, cols] = m[m.length - 1].split('#').map(Number);
  711. div.FYTE.storyboard = {w, h, len, rows, cols};
  712. if (w * h > 2000) {
  713. div.FYTE.storyboard.url = m[0].replace('?', '&').replace(
  714. '$L/$N.jpg',
  715. `${m.length - 2}/M0.jpg?sigh=${m[m.length - 1].replace(/^.+?#([^#]+)$/, '$1')}`);
  716. const elSb = $('.instant-youtube-storyboard', div);
  717. if (elSb) {
  718. elSb.dataset.loaded = '';
  719. elSb.appendChild(overrideCSS($create('div', {}, '\xA0'), {
  720. width: w - 1 + 'px',
  721. height: h + 'px',
  722. }));
  723. if (cfg.showStoryboard)
  724. updateHoverHandler(div);
  725. }
  726. }
  727. }
  728.  
  729. injectStylesIfNeeded();
  730.  
  731. if (div.FYTE.state === 'scheduled play')
  732. setTimeout(startPlayingDirectly, 0, div);
  733.  
  734. div.FYTE.state = '';
  735.  
  736. try {
  737. const cover = vid.thumbnail.thumbnails.pop().url;
  738. if (cache.cover !== cover) {
  739. cache.cover = cover;
  740. shouldUpdateCache = true;
  741. const img = $('img', div);
  742. if (img.src && img.src !== cover)
  743. img.src = setUrl(cover);
  744. }
  745. } catch (e) {
  746. }
  747. if (shouldUpdateCache)
  748. localStorage[`FYTE-cache-${cache.id}`] = JSON.stringify(cache);
  749. }
  750.  
  751. function decodeYoutubeSignature(s) {
  752. const a = s.split('');
  753. a.reverse();
  754. swap(a, 24);
  755. a.reverse();
  756. swap(a, 41);
  757. a.reverse();
  758. swap(a, 2);
  759. return a.join('');
  760. }
  761.  
  762. function swap(a, b) {
  763. const c = a[0];
  764. a[0] = a[b % a.length];
  765. a[b % a.length] = c;
  766. }
  767.  
  768. function fixThumbnailAR(div, w, h) {
  769. const img = $('img', div);
  770. if (!img)
  771. return;
  772. const thw = img.naturalWidth;
  773. const
  774. thh = img.naturalHeight;
  775. if (w && h) { // means thumbnail is still loading
  776. div.FYTE.cache.videoWidth = w;
  777. div.FYTE.cache.videoHeight = h;
  778. } else {
  779. w = div.FYTE.cache.videoWidth;
  780. h = div.FYTE.cache.videoHeight;
  781. if (!w || !h)
  782. return;
  783. }
  784. const divw = div.clientWidth;
  785. const
  786. divh = div.clientHeight;
  787. // if both video and thumbnail are 4:3, fit the image to height
  788. //console.log(div, divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  789. if (Math.abs(h / w * divw / divh - 1) > 0.05 && Math.abs(thh / thw * divw / divh - 1) > 0.05) {
  790. img.style.maxHeight = img.clientHeight + 'px';
  791. if (!div.FYTE.cache.videoWidth) // skip animation if thumbnail is already loaded
  792. img.style.transition = 'height 1s ease, margin-top 1s ease';
  793. setTimeout(() => {
  794. overrideCSS(img, Object.assign(
  795. {'max-height': 'none'},
  796. h / w >= divh / divw
  797. ? {width: 'auto', height: '100%'}
  798. : {width: '100%', height: 'auto'}));
  799. setTimeout(() => img.style.removeProperty('transition'), 1000);
  800. });
  801. }
  802. }
  803.  
  804. function trackMouse(e) {
  805. this.FYTE.mouseEvent = e;
  806. }
  807.  
  808. function updateHoverHandler(div) {
  809. const fyte = div.FYTE;
  810. const sb = fyte.storyboard;
  811. const elSb = $('.instant-youtube-storyboard', div);
  812. if (!cfg.showStoryboard) {
  813. elSb.hidden = true;
  814. return;
  815. }
  816. elSb.hidden = false;
  817. let oldIndex = null;
  818. const tracker = elSb.firstElementChild;
  819. const style = tracker.style;
  820. const sbImg = $create('img');
  821. const spinner = $create('span.loading-spinner');
  822. elSb.addEventListener('mousemove', storyboardHoverHandler);
  823. elSb.addEventListener('mouseout', storyboardHoverHandler);
  824. elSb.addEventListener('click', storyboardClickHandler, {once: true});
  825. div.addEventListener('mouseover', storyboardPreloader);
  826. div.addEventListener('mouseout', storyboardPreloader);
  827. if (div.closest(':hover'))
  828. storyboardPreloader({});
  829.  
  830. function storyboardClickHandler(e) {
  831. const offsetX = e.offsetX || e.clientX - elSb.getBoundingClientRect().left;
  832. fyte.startAt = offsetX / elSb.clientWidth * fyte.duration | 0;
  833. fyte.srcEmbedFixed = setUrlParams(fyte.srcEmbedFixed, {start: fyte.startAt});
  834. startPlaying(div, {alternateMode: e.shiftKey});
  835. }
  836.  
  837. function storyboardPreloader(e) {
  838. if (e.type === 'mouseout') {
  839. spinner.remove();
  840. return;
  841. }
  842. const {len, rows, cols, preloaded} = sb || {};
  843. const lastpart = (len - 1) / (rows * cols || 1) | 0;
  844. if (lastpart <= 0 || preloaded)
  845. return;
  846. let part = 0;
  847. $create('img', {
  848. src: setStoryboardUrl(part++),
  849. onload() {
  850. if (part <= lastpart) {
  851. this.src = setStoryboardUrl(part++);
  852. return;
  853. }
  854. sb.preloaded = true;
  855. div.removeEventListener('mouseover', storyboardPreloader);
  856. div.removeEventListener('mouseout', storyboardPreloader);
  857. this.onload = null;
  858. this.src = '';
  859. spinner.remove();
  860. },
  861. });
  862. if (elSb.matches(':hover') && fyte.mouseEvent)
  863. storyboardHoverHandler(fyte.mouseEvent);
  864. }
  865.  
  866. function setStoryboardUrl(part) {
  867. return setUrl(sb.url.replace(/M\d+\.jpg\?/, `M${part}.jpg?`));
  868. }
  869.  
  870. function storyboardHoverHandler(e) {
  871. div.removeEventListener('mousemove', trackMouse);
  872. if (!cfg.showStoryboard || !sb)
  873. return;
  874. if (e.type === 'mouseout') {
  875. sbImg.onload && sbImg.onload();
  876. return;
  877. }
  878. const {w, h, cols, rows, len, preloaded} = sb;
  879. const partlen = rows * cols;
  880.  
  881. const offsetX = e.offsetX || e.clientX - elSb.getBoundingClientRect().left;
  882. const left = Math.min(elSb.clientWidth - w, Math.max(0, offsetX - w)) | 0;
  883. if (!style.left || parseInt(style.left) !== left) {
  884. style.left = `${left}px`;
  885. if (spinner.parentElement)
  886. spinner.style.cssText = important(`left:${left + w / 2 - 10}px; right:auto;`);
  887. }
  888.  
  889. let index = Math.min(offsetX / elSb.clientWidth * (len + 1) | 0, len - 1);
  890. if (index === oldIndex)
  891. return;
  892.  
  893. const part = index / partlen | 0;
  894. if (!oldIndex || part !== (oldIndex / partlen | 0)) {
  895. const url = setStoryboardUrl(part);
  896. style.setProperty('background-image', `url(${url})`, 'important');
  897. if (!preloaded) {
  898. if (spinner.timer)
  899. clearTimeout(spinner.timer);
  900. spinner.timer = setTimeout(() => {
  901. spinner.timer = 0;
  902. if (!sbImg.src)
  903. return;
  904. elSb.appendChild(spinner);
  905. spinner.style.cssText = important(`left:${left + w / 2 - 10}px; right:auto;`);
  906. }, 50);
  907. sbImg.onload = () => {
  908. clearTimeout(spinner.timer);
  909. spinner.remove();
  910. spinner.timer = 0;
  911. sbImg.onload = null;
  912. sbImg.src = '';
  913. };
  914. sbImg.src = url;
  915. }
  916. }
  917.  
  918. tracker.dataset.time = secondsToTimeString(index / (len - 1 || 1) * fyte.duration | 0);
  919. oldIndex = index;
  920. index %= partlen;
  921. style.setProperty('background-position',
  922. `-${(index % cols) * w}px -${(index / cols | 0) * h}px`, 'important');
  923. }
  924. }
  925.  
  926. function clickHandler(e) {
  927. const el = e.target;
  928. if (el.closest('a') ||
  929. e.type === 'mousedown' && e.button !== 1 ||
  930. e.type === 'click' && el.matches('.instant-youtube-options, .instant-youtube-options *'))
  931. return;
  932. if (e.type === 'click' && el.matches('.instant-youtube-options-button')) {
  933. showOptions(e);
  934. e.preventDefault();
  935. e.stopPropagation();
  936. return;
  937. }
  938.  
  939. e.preventDefault();
  940. e.stopPropagation();
  941. e.stopImmediatePropagation();
  942.  
  943. startPlaying(el.closest('.instant-youtube-container'), {
  944. alternateMode: e.shiftKey || el.matches('.instant-youtube-alternative'),
  945. fullscreen: e.button === 1,
  946. });
  947. }
  948.  
  949. function startPlaying(div, params) {
  950. div.removeEventListener('click', clickHandler);
  951. div.removeEventListener('mousedown', clickHandler);
  952.  
  953. $$remove([
  954. '.instant-youtube-alternative',
  955. '.instant-youtube-storyboard',
  956. '.instant-youtube-options-button',
  957. '.instant-youtube-options',
  958. ].join(','), div);
  959. $('svg', div).outerHTML = '<span class=instant-youtube-loading-spinner></span>';
  960.  
  961. if (cfg.pinnable !== 'off') {
  962. makePinnable(div);
  963. if (params && params.pin)
  964. $(`[pin="${params.pin}"]`, div).click();
  965. }
  966.  
  967. if (window !== top)
  968. parent.postMessage('iframe-allowfs', '*');
  969.  
  970. const fyte = div.FYTE;
  971. if ((!!cfg.playHTML5 + !!(params && params.alternateMode) === 1) &&
  972. (fyte.videoSources || fyte.state === 'querying')) {
  973. if (fyte.videoSources)
  974. startPlayingDirectly(div, params);
  975. else {
  976. // playback will start in parseVideoInfo
  977. fyte.state = 'scheduled play';
  978. // fallback to iframe in 5s
  979. setTimeout(() => {
  980. if (div.FYTE.state) {
  981. div.FYTE.state = '';
  982. switchToIFrame.call(div, params);
  983. }
  984. }, 5000);
  985. }
  986. } else
  987. switchToIFrame.call(div, params);
  988. }
  989.  
  990. function startPlayingDirectly(div, params) {
  991. const video = $create('video.embed', {
  992. autoplay: true,
  993. controls: true,
  994. volume: GM_getValue('volume', 0.5),
  995. });
  996. overrideCSS(video, {
  997. position: 'absolute',
  998. left: 0,
  999. top: 0,
  1000. right: 0,
  1001. bottom: 0,
  1002. padding: 0,
  1003. margin: 'auto',
  1004. opacity: 0,
  1005. width: '100%',
  1006. height: '100%',
  1007. });
  1008.  
  1009. for (const src of div.FYTE.videoSources || []) {
  1010. video.appendChild($create('source', src))
  1011. .onerror = switchToIFrame.bind(div, params);
  1012. }
  1013.  
  1014. overrideCSS($('img', div), {
  1015. transition: 'opacity 1s',
  1016. opacity: '0',
  1017. });
  1018.  
  1019. if (params && params.fullscreen) {
  1020. div.firstElementChild.appendChild(video);
  1021. div.setAttribute('playing', '');
  1022. video.style.opacity = 1;
  1023. goFullscreen(video);
  1024. }
  1025.  
  1026. if (window.chrome && +navigator.userAgent.match(/Chrom\D+(\d+)|$/)[1] < 74)
  1027. video.addEventListener('click', () =>
  1028. setTimeout(() =>
  1029. video.paused ?
  1030. video.play() :
  1031. video.pause()));
  1032.  
  1033. const title = $('.instant-youtube-title', div);
  1034. if (title) {
  1035. video.onpause = () => (title.hidden = false);
  1036. video.onplay = () => (title.hidden = true);
  1037. }
  1038.  
  1039. const switchTimer = setTimeout(switchToIFrame.bind(div, params), 5000);
  1040.  
  1041. video.oncanplay = () => {
  1042. video.oncanplay = null;
  1043. if (div.FYTE.startAt && Math.abs(video.currentTime - div.FYTE.startAt) > 1)
  1044. video.currentTime = div.FYTE.startAt;
  1045. clearTimeout(switchTimer);
  1046. pauseOtherVideos(video);
  1047. video.interval = setInterval(() => {
  1048. if (video.volume !== GM_getValue('volume', 0.5))
  1049. GM_setValue('volume', video.volume);
  1050. }, 1000);
  1051. if (params && params.fullscreen)
  1052. return;
  1053. div.setAttribute('playing', '');
  1054. div.firstElementChild.appendChild(video);
  1055. overrideCSS(video, {opacity: 1});
  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(important(/*language=CSS*/ `
  1825. .instant-youtube-container,
  1826. .instant-youtube-wrapper * {
  1827. transform: translate3D(0,0,0);
  1828. }
  1829. .instant-youtube-container {
  1830. all: unset;
  1831. contain: strict;
  1832. display: block;
  1833. position: relative;
  1834. overflow: hidden;
  1835. cursor: pointer;
  1836. padding: 0;
  1837. margin: auto;
  1838. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1839. text-align: center;
  1840. background: black;
  1841. break-inside: avoid-column;
  1842. }
  1843. .instant-youtube-container[disabled] {
  1844. background: #888;
  1845. }
  1846. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1847. display: none;
  1848. }
  1849. .instant-youtube-container[pinned] {
  1850. box-shadow: 0 0 30px black;
  1851. }
  1852. .instant-youtube-container[playing] {
  1853. contain: none;
  1854. }
  1855. .instant-youtube-wrapper {
  1856. width: 100%;
  1857. height: 100%;
  1858. }
  1859. .instant-youtube-play-button {
  1860. display: block;
  1861. position: absolute;
  1862. width: 85px;
  1863. height: 60px;
  1864. left: 0;
  1865. right: 0;
  1866. top: 0;
  1867. bottom: 0;
  1868. margin: auto;
  1869. }
  1870. .instant-youtube-loading-spinner {
  1871. display: block;
  1872. position: absolute;
  1873. width: 20px;
  1874. height: 20px;
  1875. left: 0;
  1876. right: 0;
  1877. top: 0;
  1878. bottom: 0;
  1879. padding: 0;
  1880. margin: auto;
  1881. pointer-events: none;
  1882. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1883. }
  1884. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1885. fill: #CC181E;
  1886. }
  1887. .instant-youtube-alternative {
  1888. display: block;
  1889. position: absolute;
  1890. width: 20em;
  1891. height: 20px;
  1892. top: 50%;
  1893. left: 0;
  1894. right: 0;
  1895. margin: 60px auto;
  1896. padding: 0;
  1897. border: none;
  1898. text-align: center;
  1899. text-decoration: none;
  1900. text-shadow: 1px 1px 3px black;
  1901. color: white;
  1902. z-index: 8;
  1903. font-weight: normal;
  1904. font-size: 12px;
  1905. }
  1906. .instant-youtube-alternative:hover {
  1907. text-decoration: underline;
  1908. color: white;
  1909. background: transparent;
  1910. }
  1911. .instant-youtube-embed {
  1912. z-index: 10;
  1913. background: transparent;
  1914. transition: opacity .25s;
  1915. }
  1916. .instant-youtube-title {
  1917. z-index: 20;
  1918. display: block;
  1919. position: absolute;
  1920. width: auto;
  1921. top: 0;
  1922. left: 0;
  1923. right: 0;
  1924. margin: 0;
  1925. padding: 7px;
  1926. border: none;
  1927. text-shadow: 1px 1px 2px black;
  1928. text-align: center;
  1929. text-decoration: none;
  1930. color: white;
  1931. background-color: #0008;
  1932. }
  1933. .instant-youtube-title strong {
  1934. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1935. }
  1936. .instant-youtube-title strong:after {
  1937. content: " - ${_('msgWatch')}";
  1938. font-weight: normal;
  1939. margin-right: 1ex;
  1940. }
  1941. .instant-youtube-title span {
  1942. color: white;
  1943. }
  1944. .instant-youtube-title span:before {
  1945. content: "(";
  1946. }
  1947. .instant-youtube-title span:after {
  1948. content: ")";
  1949. }
  1950. .instant-youtube-container .instant-youtube-title i {
  1951. all: unset;
  1952. opacity: .5;
  1953. font-style: normal;
  1954. color: white;
  1955. }
  1956. @-webkit-keyframes instant-youtube-fadein {
  1957. from { opacity: 0 }
  1958. to { opacity: 1 }
  1959. }
  1960. @-moz-keyframes instant-youtube-fadein {
  1961. from { opacity: 0 }
  1962. to { opacity: 1 }
  1963. }
  1964. @keyframes instant-youtube-fadein {
  1965. from { opacity: 0 }
  1966. to { opacity: 1 }
  1967. }
  1968. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1969. display: none;
  1970. margin: 0;
  1971. }
  1972. .instant-youtube-title:hover {
  1973. text-decoration: underline;
  1974. }
  1975. .instant-youtube-title strong {
  1976. color: white;
  1977. }
  1978. .instant-youtube-options-button {
  1979. opacity: 0.6;
  1980. position: absolute;
  1981. right: 0;
  1982. bottom: 0;
  1983. margin: 0;
  1984. padding: 1.5ex 2ex;
  1985. font-size: 11px;
  1986. text-shadow: 1px 1px 2px black;
  1987. color: white;
  1988. }
  1989. .instant-youtube-options-button:hover {
  1990. opacity: 1;
  1991. background: rgba(0, 0, 0, 0.5);
  1992. }
  1993. .instant-youtube-options {
  1994. display: flex;
  1995. position: absolute;
  1996. right: 0;
  1997. bottom: 0;
  1998. margin: 0;
  1999. padding: 1ex 1ex 2ex 2ex;
  2000. flex-direction: column;
  2001. align-items: flex-start;
  2002. line-height: 1.5;
  2003. text-align: left;
  2004. opacity: 1;
  2005. color: white;
  2006. background: black;
  2007. z-index: 999;
  2008. }
  2009. .instant-youtube-options * {
  2010. width: auto;
  2011. height: auto;
  2012. margin: 0;
  2013. padding: 0;
  2014. font: inherit;
  2015. font-size: 13px;
  2016. vertical-align: middle;
  2017. text-transform: none;
  2018. text-align: left;
  2019. border-radius: 0;
  2020. text-decoration: none;
  2021. color: white;
  2022. background: black;
  2023. }
  2024. .instant-youtube-options > * {
  2025. margin-top: 1ex;
  2026. }
  2027. .instant-youtube-options table {
  2028. all: unset;
  2029. display: table;
  2030. }
  2031. .instant-youtube-options tr {
  2032. all: unset;
  2033. display: table-row;
  2034. }
  2035. .instant-youtube-options td {
  2036. all: unset;
  2037. display: table-cell;
  2038. padding: 2px;
  2039. }
  2040. .instant-youtube-options label > * {
  2041. display: inline;
  2042. }
  2043. .instant-youtube-options select {
  2044. padding: .5ex .25ex;
  2045. border: 1px solid #444;
  2046. -webkit-appearance: menulist;
  2047. }
  2048. .instant-youtube-options [data-action="resize-custom"] input {
  2049. width: 9ex;
  2050. padding: .5ex .5ex .4ex;
  2051. border: 1px solid #666;
  2052. }
  2053. .instant-youtube-options [data-action="buttons"] {
  2054. margin-top: 1em;
  2055. }
  2056. .instant-youtube-options button {
  2057. margin: 0 1ex 0 0;
  2058. padding: .5ex 2ex;
  2059. border: 2px solid gray;
  2060. font-weight: bold;
  2061. }
  2062. .instant-youtube-options button:hover {
  2063. border-color: white;
  2064. }
  2065. .instant-youtube-options label[disabled] {
  2066. opacity: 0.25;
  2067. }
  2068. .instant-youtube-storyboard {
  2069. height: 33%;
  2070. max-height: 90px;
  2071. display: block;
  2072. position: absolute;
  2073. left: 0;
  2074. right: 0;
  2075. bottom: 0;
  2076. overflow: visible;
  2077. transition: background-color .5s .25s;
  2078. }
  2079. .instant-youtube-storyboard[data-loaded]:hover {
  2080. background-color: #0004;
  2081. }
  2082. .instant-youtube-storyboard div {
  2083. display: block;
  2084. position: absolute;
  2085. bottom: 0;
  2086. pointer-events: none;
  2087. border: 3px solid #888;
  2088. box-shadow: 2px 2px 10px black;
  2089. transition: opacity .25s ease;
  2090. background-color: transparent;
  2091. background-origin: content-box;
  2092. opacity: 0;
  2093. }
  2094. .instant-youtube-storyboard div::after {
  2095. content: attr(data-time);
  2096. opacity: .5;
  2097. color: #fff;
  2098. background-color: #000;
  2099. font-weight: bold;
  2100. font-size: 10px;
  2101. position: absolute;
  2102. bottom: 4px;
  2103. left: 4px;
  2104. padding: 1px 3px;
  2105. }
  2106. .instant-youtube-storyboard:hover div {
  2107. opacity: 1;
  2108. }
  2109. .instant-youtube-container [pin] {
  2110. position: absolute;
  2111. width: 0;
  2112. height: 0;
  2113. margin: 0;
  2114. padding: 0;
  2115. top: auto; bottom: auto; left: auto; right: auto;
  2116. border-style: solid;
  2117. transition: opacity 2.5s ease-in, opacity 0.4s ease-out;
  2118. opacity: 0;
  2119. z-index: 100;
  2120. }
  2121. .instant-youtube-container[playing]:hover [pin]:not([transparent]) {
  2122. opacity: 1;
  2123. }
  2124. .instant-youtube-container[playing] [pin]:hover {
  2125. cursor: alias;
  2126. opacity: 1;
  2127. transition: opacity 0s;
  2128. }
  2129. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  2130. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  2131. .instant-youtube-container [pin=top-left] {
  2132. top: 0; left: 0;
  2133. border-width: 10px 10px 0 0;
  2134. border-color: red transparent transparent transparent;
  2135. }
  2136. .instant-youtube-container [pin=top-left][transparent] {
  2137. border-width: 10px 10px 0 0;
  2138. }
  2139. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  2140. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  2141. .instant-youtube-container [pin=top-right] {
  2142. top: 0; right: 0;
  2143. border-width: 0 10px 10px 0;
  2144. border-color: transparent red transparent transparent;
  2145. }
  2146. .instant-youtube-container [pin=top-right][transparent] {
  2147. border-width: 0 10px 10px 0;
  2148. }
  2149. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  2150. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  2151. .instant-youtube-container [pin=bottom-right] {
  2152. bottom: 0; right: 0;
  2153. border-width: 0 0 10px 10px;
  2154. border-color: transparent transparent red transparent;
  2155. }
  2156. .instant-youtube-container [pin=bottom-right][transparent] {
  2157. border-width: 0 0 10px 10px;
  2158. }
  2159. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  2160. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  2161. .instant-youtube-container [pin=bottom-left] {
  2162. bottom: 0; left: 0;
  2163. border-width: 10px 0 0 10px;
  2164. border-color: transparent transparent transparent red;
  2165. }
  2166. .instant-youtube-container [pin=bottom-left][transparent] {
  2167. border-width: 10px 0 0 10px;
  2168. }
  2169. .instant-youtube-dragndrop-placeholder {
  2170. z-index: 999999999;
  2171. margin: 0;
  2172. padding: 0;
  2173. background: rgba(0, 255, 0, 0.1);
  2174. border: 2px dotted green;
  2175. box-sizing: border-box;
  2176. pointer-events: none;
  2177. }
  2178. .instant-youtube-container [size-gripper] {
  2179. width: 0;
  2180. position: absolute;
  2181. top: 0;
  2182. bottom: 0;
  2183. cursor: e-resize;
  2184. border-color: rgba(50,100,255,0.5);
  2185. border-width: 12px;
  2186. background: rgba(50,100,255,0.2);
  2187. z-index: 99;
  2188. opacity: 0;
  2189. transition: opacity .1s ease-in-out, border-color .1s ease-in-out;
  2190. }
  2191. .instant-youtube-container[pinned*="right"] [size-gripper] {
  2192. border-style: none none none solid;
  2193. left: -4px;
  2194. }
  2195. .instant-youtube-container[pinned*="left"] [size-gripper] {
  2196. border-style: none solid none none;
  2197. right: -4px;
  2198. }
  2199. .instant-youtube-container [size-gripper]:hover {
  2200. opacity: 1;
  2201. }
  2202. .instant-youtube-container [size-gripper]:active {
  2203. opacity: 1;
  2204. width: auto;
  2205. left: -4px;
  2206. right: -4px;
  2207. }
  2208. .instant-youtube-container [size-gripper][tried-exceeding] {
  2209. border-color: rgba(255,0,0,0.5);
  2210. }
  2211. .instant-youtube-container [size-gripper][saveAs="global"] {
  2212. border-color: rgba(0,255,0,0.5);
  2213. }
  2214. .instant-youtube-container [size-gripper][saveAs="site"] {
  2215. border-color: rgba(0,255,255,0.5);
  2216. }
  2217. .instant-youtube-container [size-gripper][saveAs="reset"] {
  2218. border-color: rgba(255,255,0,0.5);
  2219. }
  2220. .instant-youtube-container [size-gripper][saveAs="cancel"] {
  2221. border-color: rgba(255,0,255,0.25);
  2222. }
  2223. .instant-youtube-container [size-gripper] > div {
  2224. white-space: nowrap;
  2225. color: white;
  2226. font-weight: normal;
  2227. line-height: 1.25;
  2228. text-align: left;
  2229. position: absolute;
  2230. top: 50%;
  2231. padding: 1ex 1em 1ex;
  2232. background-color: rgba(80,150,255,0.5);
  2233. }
  2234. .instant-youtube-container [size-gripper] [save-as="site"] {
  2235. font-weight: bold;
  2236. color: yellow;
  2237. }
  2238. .instant-youtube-container[pinned*="left"] [size-gripper] > div {
  2239. right: 0;
  2240. }
  2241. `, /;\n/g));
  2242. // move our rules to the end of HEAD to increase CSS specificity
  2243. if (styledom.nextElementSibling && document.head)
  2244. document.head.appendChild(styledom);
  2245. updateAltPlayerCSS();
  2246. }