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-06-16 提交的版本,查看 最新版本

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