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

  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.3
  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. cls: 'g-blk',
  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, match, query, tag} = rule;
  146. if (!tag && !cls)
  147. tag = 'iframe';
  148. if (!match && !query)
  149. match = '[src*="youtube.com/embed"]';
  150. rule.nodes = cls ?
  151. document.getElementsByClassName(cls) :
  152. document.getElementsByTagName(tag);
  153. rule.match = match ?
  154. e => e.matches(match) ? e : null :
  155. e => e.querySelector(query);
  156. return rule;
  157. }
  158. }
  159.  
  160. function onMessageHost(e) {
  161. switch (e.data) {
  162. case 'FYTE-toggle-fullscreen-init':
  163. if (findFrameElement(e.source))
  164. e.source.postMessage('FYTE-toggle-fullscreen-init-confirmed', '*');
  165. break;
  166. case 'FYTE-toggle-fullscreen': {
  167. const el = findFrameElement(e.source);
  168. if (el)
  169. goFullscreen(el,
  170. !(document.fullScreenElement || document.fullScreen || document.mozFullScreen));
  171. break;
  172. }
  173. case 'iframe-allowfs':
  174. $$('iframe:not([allowfullscreen])').some(iframe => {
  175. if (iframe.contentWindow === e.source) {
  176. iframe.allowFullscreen = true;
  177. return true;
  178. }
  179. });
  180. if (window !== top)
  181. parent.postMessage('iframe-allowfs', '*');
  182. break;
  183. }
  184. }
  185.  
  186. function findFrameElement(frameWindow) {
  187. return $$('iframe[allowfullscreen]').find(el => el.contentWindow === frameWindow);
  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 switchTimer = setTimeout(switchToIFrame.bind(div, params), 5000);
  992. const video = $create('video.embed', {
  993. autoplay: true,
  994. controls: true,
  995. volume: GM_getValue('volume', 0.5),
  996. style: {
  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. oncanplay() {
  1009. this.oncanplay = null;
  1010. const fyte = div.FYTE;
  1011. if (fyte.startAt && Math.abs(this.currentTime - fyte.startAt) > 1)
  1012. this.currentTime = fyte.startAt;
  1013. clearTimeout(switchTimer);
  1014. pauseOtherVideos(this);
  1015. if (params && params.fullscreen)
  1016. return;
  1017. div.setAttribute('playing', '');
  1018. div.firstElementChild.appendChild(this);
  1019. overrideCSS(this, {opacity: 1});
  1020. },
  1021. onvolumechange() {
  1022. GM_setValue('volume', this.volume);
  1023. },
  1024. });
  1025.  
  1026. for (const src of div.FYTE.videoSources || []) {
  1027. video.appendChild($create('source', src))
  1028. .onerror = switchToIFrame.bind(div, params);
  1029. }
  1030.  
  1031. overrideCSS($('img', div), {
  1032. transition: 'opacity 1s',
  1033. opacity: '0',
  1034. });
  1035.  
  1036. if (params && params.fullscreen) {
  1037. div.firstElementChild.appendChild(video);
  1038. div.setAttribute('playing', '');
  1039. video.style.opacity = 1;
  1040. goFullscreen(video);
  1041. }
  1042.  
  1043. if (window.chrome && +navigator.userAgent.match(/Chrom\D+(\d+)|$/)[1] < 74)
  1044. video.addEventListener('click', () =>
  1045. setTimeout(() =>
  1046. video.paused ?
  1047. video.play() :
  1048. video.pause()));
  1049.  
  1050. const title = $('.instant-youtube-title', div);
  1051. if (title) {
  1052. video.onpause = () => (title.hidden = false);
  1053. video.onplay = () => (title.hidden = true);
  1054. }
  1055. }
  1056.  
  1057. function switchToIFrame(params, e) {
  1058. if (this.querySelector('iframe'))
  1059. return;
  1060. const div = this;
  1061. const wrapper = div.firstElementChild;
  1062. const fullscreen = params && params.fullscreen && !e;
  1063. if (e instanceof Event) {
  1064. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player',
  1065. div.FYTE.srcEmbed);
  1066. const video = e.target ? e.target.closest('video') : e.composedPath().pop();
  1067. video.textContent = '';
  1068. goFullscreen(video, false);
  1069. video.remove();
  1070. }
  1071.  
  1072. const url = setUrlParams(div.FYTE.srcEmbedFixed, {
  1073. html5: 1,
  1074. autoplay: 1,
  1075. autohide: 2,
  1076. border: 0,
  1077. controls: 1,
  1078. fs: 1,
  1079. showinfo: 1,
  1080. ssl: 1,
  1081. theme: 'dark',
  1082. enablejsapi: 1,
  1083. local: 'true',
  1084. quality: 'medium',
  1085. FYTEfullscreen: fullscreen | 0,
  1086. });
  1087.  
  1088. let iframe = $create('iframe.embed', {
  1089. src: url,
  1090. allow: 'autoplay; fullscreen',
  1091. allowfullscreen: true,
  1092. width: '100%',
  1093. height: '100%',
  1094. style: {
  1095. position: 'absolute',
  1096. top: 0,
  1097. left: 0,
  1098. right: 0,
  1099. padding: 0,
  1100. margin: 'auto',
  1101. opacity: 0,
  1102. border: 0,
  1103. },
  1104. });
  1105.  
  1106. if (cfg.pinnable !== 'off') {
  1107. $('[pin]', div).insertAdjacentElement('beforebegin', iframe);
  1108. } else {
  1109. wrapper.appendChild(iframe);
  1110. }
  1111.  
  1112. div.setAttribute('iframe', '');
  1113. div.setAttribute('playing', '');
  1114.  
  1115. iframe = $('iframe', div);
  1116. if (fullscreen) {
  1117. goFullscreen(iframe);
  1118. overrideCSS(iframe, {opacity: 1});
  1119. }
  1120.  
  1121. iframe.onload = () => {
  1122. addEventListener('message', YTlistener);
  1123. iframe.contentWindow.postMessage('{"event":"listening"}', '*');
  1124. if (cfg.invidious) {
  1125. overrideCSS(iframe, {opacity: 1});
  1126. $('.instant-youtube-title', div).hidden = true;
  1127. }
  1128. };
  1129. setTimeout(() => {
  1130. overrideCSS(iframe, {opacity: 1});
  1131. removeEventListener('message', YTlistener);
  1132. }, 5000);
  1133.  
  1134. function YTlistener(e) {
  1135. if (e.source !== iframe.contentWindow || !e.data)
  1136. return;
  1137. const data = tryJSONparse(e.data);
  1138. if (!data.info || data.info.playerState !== 1)
  1139. return;
  1140. removeEventListener('message', YTlistener);
  1141. pauseOtherVideos(iframe);
  1142. overrideCSS(iframe, {opacity: 1});
  1143. overrideCSS($('img', div), {display: 'none'});
  1144. $$remove('span, a', div);
  1145. }
  1146. }
  1147.  
  1148. function setUrl(url) {
  1149. if (cfg.invidious) {
  1150. const u = new URL(url);
  1151. u.hostname = 'invidio.us';
  1152. url = u.href.replace('/vi_webp/', '/vi/').replace('.webp', '.jpg');
  1153. }
  1154. return url;
  1155. }
  1156.  
  1157. function setUrlParams(url, params) {
  1158. const u = new URL(url);
  1159. for (const [k, v] of Object.entries(params))
  1160. u.searchParams.set(k, v);
  1161. return u.href;
  1162. }
  1163.  
  1164. function pauseOtherVideos(activePlayer) {
  1165. for (const v of $$('.instant-youtube-embed', activePlayer.ownerDocument)) {
  1166. if (v === activePlayer)
  1167. continue;
  1168. switch (v.localName) {
  1169. case 'video':
  1170. if (!v.paused)
  1171. v.pause();
  1172. break;
  1173. case 'iframe':
  1174. try {
  1175. v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*');
  1176. } catch (e) {}
  1177. break;
  1178. }
  1179. }
  1180. }
  1181.  
  1182. function goFullscreen(el, enable) {
  1183. if (enable !== false)
  1184. el.webkitRequestFullScreen && el.webkitRequestFullScreen() ||
  1185. el.mozRequestFullScreen && el.mozRequestFullScreen() ||
  1186. el.requestFullScreen && el.requestFullScreen();
  1187. else
  1188. document.webkitCancelFullScreen && document.webkitCancelFullScreen() ||
  1189. document.mozCancelFullScreen && document.mozCancelFullScreen() ||
  1190. document.cancelFullScreen && document.cancelFullScreen();
  1191. }
  1192.  
  1193. function makePinnable(div) {
  1194. div.firstElementChild.insertAdjacentHTML('beforeend',
  1195. '<div size-gripper></div>' +
  1196. '<div pin="top-left"></div>' +
  1197. '<div pin="top-right"></div>' +
  1198. '<div pin="bottom-right"></div>' +
  1199. '<div pin="bottom-left"></div>');
  1200.  
  1201. for (const pin of $$('[pin]', div)) {
  1202. if (cfg.pinnable === 'hide')
  1203. pin.setAttribute('transparent', '');
  1204. pin.onclick = pinClicked;
  1205. }
  1206. $('[size-gripper]', div).addEventListener('mousedown', startResize, true);
  1207.  
  1208. function pinClicked() {
  1209. const pin = this;
  1210. const pinIt = !div.hasAttribute('pinned') || !pin.hasAttribute('active');
  1211. const corner = pin.getAttribute('pin');
  1212. const video = $('video', div);
  1213. const paused = video.paused;
  1214. if (pinIt) {
  1215. for (const p of $$('[pin][active]', div))
  1216. p.removeAttribute('active');
  1217. pin.setAttribute('active', '');
  1218. if (!div.FYTE.unpinnedStyle) {
  1219. div.FYTE.unpinnedStyle = div.style.cssText;
  1220. const stub = div.cloneNode();
  1221. const img = $('img', div).cloneNode();
  1222. img.style.opacity = 1;
  1223. img.style.display = 'block';
  1224. img.title = '';
  1225. stub.appendChild(img);
  1226. stub.onclick = e => $('[pin][active]', div).onclick(e);
  1227. stub.style.setProperty('opacity', .3, 'important');
  1228. stub.setAttribute('stub', '');
  1229. div.FYTE.stub = stub;
  1230. div.parentNode.insertBefore(stub, div);
  1231. }
  1232. const size = constrainPinnedSize(div,
  1233. localStorage[`width#${location.hostname}`] || cfg.pinnedWidth);
  1234. overrideCSS(div, {
  1235. position: 'fixed',
  1236. width: size.w + 'px',
  1237. height: size.h + 'px',
  1238. top: corner.includes('top') ? 0 : 'auto',
  1239. left: corner.includes('left') ? 0 : 'auto',
  1240. right: corner.includes('right') ? 0 : 'auto',
  1241. bottom: corner.includes('bottom') ? 0 : 'auto',
  1242. 'z-index': 999999999,
  1243. });
  1244. adjustPinnedOffset(div, div, corner);
  1245. div.setAttribute('pinned', corner);
  1246. if (video && document.body)
  1247. document.body.appendChild(div);
  1248. } else { // unpin
  1249. pin.removeAttribute('active');
  1250. div.removeAttribute('pinned');
  1251. div.style.cssText = div.FYTE.unpinnedStyle;
  1252. div.FYTE.unpinnedStyle = '';
  1253. if (div.FYTE.stub) {
  1254. if (video && document.body)
  1255. div.FYTE.stub.parentNode.replaceChild(div, div.FYTE.stub);
  1256. div.FYTE.stub.remove();
  1257. div.FYTE.stub = null;
  1258. }
  1259. }
  1260. if (paused)
  1261. video.pause();
  1262. }
  1263.  
  1264. function startResize(e) {
  1265. const siteSaved = ('width#' + location.hostname) in localStorage;
  1266. let saveAs = siteSaved ? 'site' : 'global';
  1267. const oldSizeCSS = {w: div.style.width, h: div.style.height};
  1268. const oldDraggable = div.draggable;
  1269. div.draggable = false;
  1270.  
  1271. const gripper = this;
  1272. gripper.removeAttribute('tried-exceeding');
  1273. gripper.innerHTML = `<div>
  1274. <div save-as="${saveAs}"><b>S</b> = Site mode: <span>${getSiteOnlyText()}</span></div>
  1275. ${!siteSaved ? '' : '<div><b>R</b> = Reset to global size</div>'}
  1276. <div><b>Esc</b> = Cancel</div>
  1277. </div>`;
  1278. document.addEventListener('mousemove', resize);
  1279. document.addEventListener('mouseup', resizeDone);
  1280. document.addEventListener('keydown', resizeKeyDown);
  1281. e.stopImmediatePropagation();
  1282. return false;
  1283.  
  1284. function getSiteOnlyText() {
  1285. return saveAs === 'site' ? `only ${location.hostname}` : 'global';
  1286. }
  1287.  
  1288. function resize(e) {
  1289. let deltaX = e.movementX || e.webkitMovementX || e.mozMovementX || 0;
  1290. if (/right/.test(div.getAttribute('pinned')))
  1291. deltaX = -deltaX;
  1292. const newSize = constrainPinnedSize(div, div.clientWidth + deltaX);
  1293. if (newSize.w !== div.clientWidth) {
  1294. div.style.setProperty('width', newSize.w + 'px', 'important');
  1295. div.style.setProperty('height', newSize.h + 'px', 'important');
  1296. gripper.removeAttribute('tried-exceeding');
  1297. } else if (newSize.triedExceeding) {
  1298. gripper.setAttribute('tried-exceeding', '');
  1299. }
  1300. window.getSelection().removeAllRanges();
  1301. return false;
  1302. }
  1303.  
  1304. function resizeDone() {
  1305. div.draggable = oldDraggable;
  1306. gripper.removeAttribute('tried-exceeding');
  1307. gripper.innerHTML = '';
  1308. document.removeEventListener('mousemove', resize);
  1309. document.removeEventListener('mouseup', resizeDone);
  1310. document.removeEventListener('keydown', resizeKeyDown);
  1311. switch (saveAs) {
  1312. case 'site':
  1313. localStorage[`width#${location.hostname}`] = div.clientWidth;
  1314. break;
  1315. case 'global':
  1316. cfg.pinnedWidth = div.clientWidth;
  1317. GM_setValue('pinnedWidth', cfg.pinnedWidth);
  1318. // fallthrough to remove the locally saved value
  1319. case 'reset':
  1320. localStorage.removeItem(`width#${location.hostname}`);
  1321. break;
  1322. case '':
  1323. return false;
  1324. }
  1325. gripper.setAttribute('saveAs', saveAs);
  1326. setTimeout(() => gripper.removeAttribute('saveAs'), 250);
  1327. return false;
  1328. }
  1329.  
  1330. function resizeKeyDown(e) {
  1331. switch (e.code) {
  1332. case 'Escape':
  1333. saveAs = 'cancel';
  1334. div.style.width = oldSizeCSS.w;
  1335. div.style.height = oldSizeCSS.h;
  1336. break;
  1337. case 'KeyS':
  1338. saveAs = saveAs === 'site' ? 'global' : 'site';
  1339. $('[save-as]', gripper).setAttribute('save-as', saveAs);
  1340. $('[save-as] span', gripper).textContent = getSiteOnlyText();
  1341. return false;
  1342. case 'KeyR': {
  1343. if (!siteSaved)
  1344. return;
  1345. saveAs = 'reset';
  1346. const {w, h} = constrainPinnedSize(div, cfg.pinnedWidth);
  1347. div.style.width = w;
  1348. div.style.height = h;
  1349. break;
  1350. }
  1351. default:
  1352. return;
  1353. }
  1354. document.dispatchEvent(new MouseEvent('mouseup'));
  1355. return false;
  1356. }
  1357. }
  1358. }
  1359.  
  1360. function makeDraggable(div) {
  1361. div.draggable = true;
  1362. div.addEventListener('dragstart', e => {
  1363. const offsetY = e.offsetY || e.clientY - div.getBoundingClientRect().top;
  1364. if (offsetY > div.clientHeight - 30) {
  1365. e.preventDefault();
  1366. return;
  1367. }
  1368.  
  1369. e.dataTransfer.setData('text/plain', '');
  1370.  
  1371. let dropZone = $create('div.dragndrop-placeholder');
  1372. const dropZoneHeight = 400 / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight;
  1373.  
  1374. document.body.addEventListener('dragenter', dragHandler);
  1375. document.body.addEventListener('dragover', dragHandler);
  1376. document.body.addEventListener('dragend', dragHandler);
  1377. document.body.addEventListener('drop', dragHandler);
  1378.  
  1379. function dragHandler(e) {
  1380. e.stopImmediatePropagation();
  1381. e.stopPropagation();
  1382. e.preventDefault();
  1383. switch (e.type) {
  1384. case 'dragover': {
  1385. const playing = div.hasAttribute('playing');
  1386. const stub = e.target.closest('.instant-youtube-container[stub]') === div.FYTE.stub &&
  1387. div.FYTE.stub;
  1388. const gizmo = playing && !stub
  1389. ? {left: 0, top: 0, right: innerWidth, bottom: innerHeight}
  1390. : (stub || div).getBoundingClientRect();
  1391. const x = e.clientX;
  1392. const y = e.clientY;
  1393. const cx = (gizmo.left + gizmo.right) / 2;
  1394. const cy = (gizmo.top + gizmo.bottom) / 2;
  1395. const stay = !!stub || y >= cy - 200 && y <= cy + 200 && x >= cx - 200 && x <= cx + 200;
  1396. overrideCSS(dropZone, {
  1397. top: y < cy || stay ? '0' : 'auto',
  1398. bottom: y > cy || stay ? '0' : 'auto',
  1399. left: x < cx || stay ? '0' : 'auto',
  1400. right: x > cx || stay ? '0' : 'auto',
  1401. width: playing && stay && stub ? stub.clientWidth + 'px' : '400px',
  1402. height: playing && stay && stub ? stub.clientHeight + 'px' : dropZoneHeight + 'px',
  1403. margin: playing && stay ? 'auto' : '0',
  1404. position: !playing && stay || stub ? 'absolute' : 'fixed',
  1405. 'background-color': stub ?
  1406. 'rgba(0,0,255,0.5)' :
  1407. stay ? 'rgba(255,255,0,0.4)' : 'rgba(0,255,0,0.2)',
  1408. });
  1409. adjustPinnedOffset(dropZone, div);
  1410. (stay && !playing || stub ? (stub || div) : document.body).appendChild(dropZone);
  1411. break;
  1412. }
  1413. case 'dragend':
  1414. case 'drop': {
  1415. const corner = calcPinnedCorner(dropZone);
  1416. dropZone.remove();
  1417. dropZone = null;
  1418. document.body.removeEventListener('dragenter', dragHandler);
  1419. document.body.removeEventListener('dragover', dragHandler);
  1420. document.body.removeEventListener('dragend', dragHandler);
  1421. document.body.removeEventListener('drop', dragHandler);
  1422. if (e.type === 'dragend')
  1423. break;
  1424. if (div.hasAttribute('playing'))
  1425. (corner ? $(`[pin="${corner}"]`, div) : div.FYTE.stub).click();
  1426. else
  1427. startPlaying(div, {pin: corner});
  1428. }
  1429. }
  1430. }
  1431. });
  1432. }
  1433.  
  1434. function adjustPinnedOffset(el, self, corner) {
  1435. let offset = 0;
  1436. if (!corner) corner = calcPinnedCorner(el);
  1437. for (const pin of $$(`.instant-youtube-container[pinned] [pin="${corner}"][active]`)) {
  1438. const container = pin.closest('[pinned]');
  1439. if (container !== el && container !== self) {
  1440. const {top, bottom} = container.getBoundingClientRect();
  1441. offset = Math.max(offset, el.style.top === '0px' ? bottom : innerHeight - top);
  1442. }
  1443. }
  1444. if (offset)
  1445. el.style[el.style.top === '0px' ? 'top' : 'bottom'] = offset + 'px';
  1446. }
  1447.  
  1448. function calcPinnedCorner(el) {
  1449. const t = el.style.top !== 'auto';
  1450. const l = el.style.left !== 'auto';
  1451. const r = el.style.right !== 'auto';
  1452. const b = el.style.bottom !== 'auto';
  1453. return t && b && l && r ? '' : `${t ? 'top' : 'bottom'}-${l ? 'left' : 'right'}`;
  1454. }
  1455.  
  1456. function constrainPinnedSize(div, width) {
  1457. const maxWidth = window.innerWidth - 100 | 0;
  1458. const triedExceeding = (width | 0) > maxWidth;
  1459. width = Math.max(200, Math.min(maxWidth, width | 0));
  1460. return {
  1461. w: width,
  1462. h: width / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight,
  1463. triedExceeding,
  1464. };
  1465. }
  1466.  
  1467. function showOptions(e) {
  1468. const [options] = translateHTML(`
  1469. <div class=instant-youtube-options>
  1470. <span>
  1471. <label tl style="width: 100% !important;">Size:&nbsp;
  1472. <select data-action=resize>
  1473. <option tl value=Original>Original
  1474. <option tl value="Fit to width">Fit to width
  1475. <option>360p
  1476. <option>480p
  1477. <option>720p
  1478. <option>1080p
  1479. <option tl value=Custom>Custom...
  1480. </select>
  1481. </label>&nbsp;
  1482. <label data-action=resize-custom ${cfg.resize !== 'Custom' ? 'disabled' : ''}>
  1483. <input type=number min=320 max=9999 tl-placeholder=width data-action=width step=1> x
  1484. <input type=number min=240 max=9999 tl-placeholder=height data-action=height step=1>
  1485. </label>
  1486. </span>
  1487. <label tl=content,title title=msgStoryboardTip>
  1488. <input data-action=showStoryboard type=checkbox>
  1489. msgStoryboard
  1490. </label>
  1491. <span>
  1492. <label tl=content,title title=msgDirectTip>
  1493. <input data-action=playHTML5 type=checkbox>
  1494. msgDirect
  1495. </label>
  1496. &nbsp;
  1497. <label tl=content,title title=msgDirectTip>
  1498. <input data-action=playHTML5Shown type=checkbox>
  1499. msgDirectShown
  1500. </label>
  1501. </span>
  1502. <label tl=content>
  1503. <input data-action=invidious type=checkbox>
  1504. msgInvidious
  1505. </label>
  1506. <label tl=content,title title=msgSafeTip>
  1507. <input data-action=skipCustom type=checkbox>
  1508. msgSafe
  1509. </label>
  1510. <table>
  1511. <tr>
  1512. <td><label tl=content,title title=msgPinningTip>msgPinning</label></td>
  1513. <td>
  1514. <select data-action=pinnable>
  1515. <option tl value=on>msgPinningOn
  1516. <option tl value=hide>msgPinningHover
  1517. <option tl value=off>msgPinningOff
  1518. </select>
  1519. </td>
  1520. </tr>
  1521. </table>
  1522. <span data-action=buttons>
  1523. <button tl data-action=ok>OK</button>
  1524. <button tl data-action=cancel>Cancel</button>
  1525. </span>
  1526. </div>
  1527. `);
  1528. for (const [k, v] of Object.entries(cfg)) {
  1529. const el = $(`[data-action=${k}]`, options);
  1530. if (el) el[el.type === 'checkbox' ? 'checked' : 'value'] = v;
  1531. }
  1532. $('[data-action=resize]', options).onchange = function () {
  1533. const v = this.value !== 'Custom';
  1534. const e = $('[data-action=resize-custom]', options);
  1535. e.children[0].disabled = e.children[1].disabled = v;
  1536. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  1537. };
  1538. $('[data-action=buttons]', options).onclick = e => {
  1539. const btn = e.target;
  1540. if (btn.dataset.action !== 'ok') {
  1541. options.remove();
  1542. return;
  1543. }
  1544. let shouldAdjust;
  1545. const oldCfg = Object.assign({}, cfg);
  1546. for (const [k, v] of Object.entries(cfg)) {
  1547. const el = $(`[data-action=${k}]`, options);
  1548. const newVal = el && (
  1549. el.type === 'checkbox' ? el.checked :
  1550. el.type === 'number' ? el.valueAsNumber :
  1551. el.value);
  1552. if (newVal != null && newVal !== v) {
  1553. GM_setValue(k, newVal);
  1554. cfg[k] = newVal;
  1555. shouldAdjust = true;
  1556. }
  1557. }
  1558. options.remove();
  1559. if (cfg.resize === 'Custom' && (cfg.width !== oldCfg.width || cfg.height !== oldCfg.height))
  1560. updateCustomSize(cfg.width, cfg.height);
  1561. if (cfg.showStoryboard !== oldCfg.showStoryboard)
  1562. $$('.instant-youtube-container').forEach(updateHoverHandler);
  1563. if (cfg.playHTML5 !== oldCfg.playHTML5 && cfg.playHTML5Shown) {
  1564. const alt = _(`msgPlay${cfg.playHTML5 ? '' : 'HTML5'}`);
  1565. for (const e of $$('.instant-youtube-alternative'))
  1566. e.textContent = alt;
  1567. }
  1568. if (cfg.playHTML5Shown !== oldCfg.playHTML5Shown)
  1569. updateAltPlayerCSS();
  1570. if (shouldAdjust)
  1571. adjustNodes(e, btn.closest('.instant-youtube-container'));
  1572. };
  1573. e.target.insertAdjacentElement('afterend', options);
  1574. }
  1575.  
  1576. function updateCustomSize(w, h) {
  1577. cfg.width = Math.min(9999, Math.max(320, w | 0 || cfg.width | 0));
  1578. cfg.height = Math.min(9999, Math.max(240, h | 0 || cfg.height | 0));
  1579. }
  1580.  
  1581. function updateAltPlayerCSS() {
  1582. const {sheet} = styledom;
  1583. const ALT = '.instant-youtube-alternative';
  1584. let len = sheet.cssRules.length;
  1585. if (sheet.cssRules[len - 1].selectorText === ALT)
  1586. sheet.deleteRule(--len);
  1587. sheet.insertRule(/*language=CSS*/ `${ALT} {
  1588. display: ${cfg.playHTML5Shown ? 'block' : 'none'} !important;
  1589. }`, len);
  1590. }
  1591.  
  1592. function important(cssText, rx = /;/g) {
  1593. return cssText.replace(rx, '!important;');
  1594. }
  1595.  
  1596. function $(sel, base = document) {
  1597. return base.querySelector(sel) || 0;
  1598. }
  1599.  
  1600. function $$(sel, base = document) {
  1601. return [...base.querySelectorAll(sel)];
  1602. }
  1603.  
  1604. function $create(tagCls, props, children) {
  1605. const [tag, cls] = tagCls.split('.');
  1606. const el = Object.assign(document.createElement(tag), props);
  1607. if (cls)
  1608. el.className = `instant-youtube-${cls}`;
  1609. if (props && typeof props.style === 'object')
  1610. overrideCSS(el, props.style);
  1611. if (children && typeof children !== 'object')
  1612. children = document.createTextNode(children);
  1613. if (children instanceof Node)
  1614. el.appendChild(children);
  1615. else if (Array.isArray(children))
  1616. el.append(...children.filter(Boolean));
  1617. return el;
  1618. }
  1619.  
  1620. function $$remove(sel, base = document) {
  1621. for (const el of base.querySelectorAll(sel))
  1622. el.remove();
  1623. }
  1624.  
  1625. function overrideCSS(el, props) {
  1626. const names = Object.keys(props);
  1627. el.style.cssText = el.style.cssText
  1628. .replace(new RegExp(`(^|\\s|;)(${names.join('|')})(:[^;]+)`, 'gi'), '$1')
  1629. .replace(/[^;]\s*$/, '$&;')
  1630. .replace(/^\s*;\s*/, '') + names.map(n => `${n}:${props[n]}!important;`).join(' ');
  1631. return el;
  1632. }
  1633.  
  1634. // fix dumb Firefox bug
  1635. function floatPadding(node, style, dir) {
  1636. const padding = style['padding' + dir];
  1637. if (padding.indexOf('%') < 0)
  1638. return parseFloat(padding);
  1639. return parseFloat(padding) * (parseFloat(style.width) || node.clientWidth) / 100;
  1640. }
  1641.  
  1642. function cleanupCache() {
  1643. const cutoff = Date.now() - CACHE_STALE_DURATION;
  1644. for (const k in localStorage) {
  1645. if (k.startsWith('FYTE-cache-')) {
  1646. const {lastUsed} = tryJSONparse(localStorage[k]) || {};
  1647. if (!lastUsed || lastUsed < cutoff)
  1648. delete localStorage[k];
  1649. }
  1650. }
  1651. for (const k of GM_listValues())
  1652. if (k.startsWith('cache-'))
  1653. GM_deleteValue(k);
  1654. }
  1655.  
  1656. function tryJSONparse(s) {
  1657. try {
  1658. return JSON.parse(s);
  1659. } catch (e) {}
  1660. }
  1661.  
  1662. function secondsToTimeString(sec) {
  1663. const h = sec / 3600 | 0;
  1664. const m = (sec / 60 | 0) % 60;
  1665. const s = sec % 60;
  1666. return `${h ? h + ':' : ''}${h && m < 10 ? 0 : ''}${m}:${s < 10 ? 0 : ''}${s}`;
  1667. }
  1668.  
  1669. function translateHTML(html) {
  1670. const tmp = $create('div', {innerHTML: html.trim().replace(/\n\s*/g, '')});
  1671. for (const node of $$('[tl]', tmp)) {
  1672. for (const what of (node.getAttribute('tl') || 'content').split(',')) {
  1673. let child;
  1674. if (what === 'content') {
  1675. for (const n of [...node.childNodes].reverse()) {
  1676. if (n.nodeType === Node.TEXT_NODE && n.textContent.trim()) {
  1677. child = n;
  1678. break;
  1679. }
  1680. }
  1681. } else
  1682. child = node.getAttributeNode(what);
  1683. if (!child)
  1684. continue;
  1685. const src = child.textContent;
  1686. const srcTrimmed = src.trim();
  1687. const tl = src.replace(srcTrimmed, _(srcTrimmed));
  1688. if (src !== tl)
  1689. child.textContent = tl;
  1690. }
  1691. }
  1692. return [...tmp.childNodes];
  1693. }
  1694.  
  1695. function initTL() {
  1696. const tlSource = {
  1697. msgWatch: {
  1698. en: 'watch on Youtube',
  1699. ru: 'открыть на Youtube',
  1700. },
  1701. msgPlay: {
  1702. en: 'Play with Youtube player',
  1703. ru: 'Включить плеер Youtube',
  1704. },
  1705. msgPlayHTML5: {
  1706. en: 'Play directly (up to 720p)',
  1707. ru: 'Включить напрямую (макс. 720p)',
  1708. },
  1709. msgAltPlayerHint: {
  1710. en: 'Shift-click to use alternative player',
  1711. ru: 'Shift-клик для смены типа плеера',
  1712. },
  1713. Options: {
  1714. ru: 'Опции',
  1715. },
  1716. 'Size:': {
  1717. ru: 'Размер:',
  1718. },
  1719. Original: {
  1720. ru: 'Исходный',
  1721. },
  1722. 'Fit to width': {
  1723. ru: 'На всю ширину',
  1724. },
  1725. 'Custom...': {
  1726. ru: 'Настроить...',
  1727. },
  1728. width: {
  1729. ru: 'ширина',
  1730. },
  1731. height: {
  1732. ru: 'высота',
  1733. },
  1734. msgStoryboard: {
  1735. en: 'Storyboard thumbnails on hover',
  1736. ru: 'Раскадровка при наведении курсора',
  1737. },
  1738. msgStoryboardTip: {
  1739. en: 'Show storyboard preview on mouse hover at the bottom',
  1740. ru: 'Показывать миникадры при наведении мыши на низ кавер-картинки',
  1741. },
  1742. msgDirect: {
  1743. en: 'Play directly',
  1744. ru: 'Встроенный плеер браузера',
  1745. },
  1746. msgDirectTip: {
  1747. en: 'Shift-click a thumbnail to use the alternative player',
  1748. ru: 'Удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  1749. },
  1750. msgDirectShown: {
  1751. en: 'Show under play button',
  1752. ru: 'Показывать под кнопкой ►',
  1753. },
  1754. msgInvidious: {
  1755. en: 'Use https://invidio.us to play videos',
  1756. ru: 'Использовать https://invidio.us в плеере',
  1757. },
  1758. msgSafe: {
  1759. en: 'Safe (skip videos with enablejsapi=1)',
  1760. ru: 'Консервативный режим',
  1761. },
  1762. msgSafeTip: {
  1763. en: 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)',
  1764. ru: 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 ' +
  1765. '(подействует после обновления страницы)',
  1766. },
  1767. msgPinning: {
  1768. en: 'Corner pinning',
  1769. ru: 'Закрепление по углам',
  1770. },
  1771. msgPinningTip: {
  1772. en: 'Enable corner pinning controls when a video is playing.\n' +
  1773. 'To restore the video click the active corner pin or the original video placeholder.',
  1774. ru: 'Включить шпильки по углам для закрепления видео во время просмотра.\n' +
  1775. 'Для отмены можно нажать еще раз на активированный угол или на заглушку, ' +
  1776. 'где исходно было видео',
  1777. },
  1778. msgPinningOn: {
  1779. en: 'On',
  1780. ru: 'Да',
  1781. },
  1782. msgPinningHover: {
  1783. en: 'On, hover a corner to show',
  1784. ru: 'Да, при наведении курсора',
  1785. },
  1786. msgPinningOff: {
  1787. en: 'Off',
  1788. ru: 'Нет',
  1789. },
  1790. OK: {
  1791. ru: 'ОК',
  1792. },
  1793. Cancel: {
  1794. ru: 'Оменить',
  1795. },
  1796. };
  1797. const browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  1798. const browserLangMajor = browserLang.replace(/-.+/, '');
  1799. const tl = {};
  1800. for (const k of Object.keys(tlSource)) {
  1801. const langs = tlSource[k];
  1802. const text = langs[browserLang] || langs[browserLangMajor];
  1803. if (text)
  1804. tl[k] = text;
  1805. }
  1806. return src => tl[src] || src;
  1807. }
  1808.  
  1809. function initPlayButton() {
  1810. [playbtn] = translateHTML(`
  1811. <svg class="instant-youtube-play-button">
  1812. <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>
  1813. <polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF"
  1814. points="33.3,41.4 33.3,17.75 56,29.6"></polygon>
  1815. </svg>`);
  1816. return playbtn;
  1817. }
  1818.  
  1819. function injectStylesIfNeeded(force) {
  1820. if (!fytedom[0] && !force)
  1821. return;
  1822. styledom = styledom || GM_addStyle(important(/*language=CSS*/ `
  1823. .instant-youtube-container,
  1824. .instant-youtube-wrapper * {
  1825. transform: translate3D(0,0,0);
  1826. }
  1827. .instant-youtube-container {
  1828. all: unset;
  1829. contain: strict;
  1830. display: block;
  1831. position: relative;
  1832. overflow: hidden;
  1833. cursor: pointer;
  1834. padding: 0;
  1835. margin: auto;
  1836. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1837. text-align: center;
  1838. background: black;
  1839. break-inside: avoid-column;
  1840. }
  1841. .instant-youtube-container[disabled] {
  1842. background: #888;
  1843. }
  1844. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1845. display: none;
  1846. }
  1847. .instant-youtube-container[pinned] {
  1848. box-shadow: 0 0 30px black;
  1849. }
  1850. .instant-youtube-container[playing] {
  1851. contain: none;
  1852. }
  1853. .instant-youtube-wrapper {
  1854. width: 100%;
  1855. height: 100%;
  1856. }
  1857. .instant-youtube-play-button {
  1858. display: block;
  1859. position: absolute;
  1860. width: 85px;
  1861. height: 60px;
  1862. left: 0;
  1863. right: 0;
  1864. top: 0;
  1865. bottom: 0;
  1866. margin: auto;
  1867. }
  1868. .instant-youtube-loading-spinner {
  1869. display: block;
  1870. position: absolute;
  1871. width: 20px;
  1872. height: 20px;
  1873. left: 0;
  1874. right: 0;
  1875. top: 0;
  1876. bottom: 0;
  1877. padding: 0;
  1878. margin: auto;
  1879. pointer-events: none;
  1880. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1881. }
  1882. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1883. fill: #CC181E;
  1884. }
  1885. .instant-youtube-alternative {
  1886. display: block;
  1887. position: absolute;
  1888. width: 20em;
  1889. height: 20px;
  1890. top: 50%;
  1891. left: 0;
  1892. right: 0;
  1893. margin: 60px auto;
  1894. padding: 0;
  1895. border: none;
  1896. text-align: center;
  1897. text-decoration: none;
  1898. text-shadow: 1px 1px 3px black;
  1899. color: white;
  1900. z-index: 8;
  1901. font-weight: normal;
  1902. font-size: 12px;
  1903. }
  1904. .instant-youtube-alternative:hover {
  1905. text-decoration: underline;
  1906. color: white;
  1907. background: transparent;
  1908. }
  1909. .instant-youtube-embed {
  1910. z-index: 10;
  1911. background: transparent;
  1912. transition: opacity .25s;
  1913. }
  1914. .instant-youtube-title {
  1915. z-index: 20;
  1916. display: block;
  1917. position: absolute;
  1918. width: auto;
  1919. top: 0;
  1920. left: 0;
  1921. right: 0;
  1922. margin: 0;
  1923. padding: 7px;
  1924. border: none;
  1925. text-shadow: 1px 1px 2px black;
  1926. text-align: center;
  1927. text-decoration: none;
  1928. color: white;
  1929. background-color: #0008;
  1930. }
  1931. .instant-youtube-title strong {
  1932. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1933. }
  1934. .instant-youtube-title strong::after {
  1935. content: " - ${_('msgWatch')}";
  1936. font-weight: normal;
  1937. margin-right: 1ex;
  1938. }
  1939. .instant-youtube-title span {
  1940. color: white;
  1941. }
  1942. .instant-youtube-title span::before {
  1943. content: "(";
  1944. }
  1945. .instant-youtube-title span::after {
  1946. content: ")";
  1947. }
  1948. .instant-youtube-title i::before {
  1949. content: ", ";
  1950. }
  1951. .instant-youtube-container .instant-youtube-title i {
  1952. all: unset;
  1953. opacity: .5;
  1954. font-style: normal;
  1955. color: white;
  1956. }
  1957. @-webkit-keyframes instant-youtube-fadein {
  1958. from { opacity: 0 }
  1959. to { opacity: 1 }
  1960. }
  1961. @-moz-keyframes instant-youtube-fadein {
  1962. from { opacity: 0 }
  1963. to { opacity: 1 }
  1964. }
  1965. @keyframes instant-youtube-fadein {
  1966. from { opacity: 0 }
  1967. to { opacity: 1 }
  1968. }
  1969. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1970. display: none;
  1971. margin: 0;
  1972. }
  1973. .instant-youtube-title:hover {
  1974. text-decoration: underline;
  1975. }
  1976. .instant-youtube-title strong {
  1977. color: white;
  1978. }
  1979. .instant-youtube-options-button {
  1980. opacity: 0.6;
  1981. position: absolute;
  1982. right: 0;
  1983. bottom: 0;
  1984. margin: 0;
  1985. padding: 1.5ex 2ex;
  1986. font-size: 11px;
  1987. text-shadow: 1px 1px 2px black;
  1988. color: white;
  1989. }
  1990. .instant-youtube-options-button:hover {
  1991. opacity: 1;
  1992. background: rgba(0, 0, 0, 0.5);
  1993. }
  1994. .instant-youtube-options {
  1995. display: flex;
  1996. position: absolute;
  1997. right: 0;
  1998. bottom: 0;
  1999. margin: 0;
  2000. padding: 1ex 1ex 2ex 2ex;
  2001. flex-direction: column;
  2002. align-items: flex-start;
  2003. line-height: 1.5;
  2004. text-align: left;
  2005. opacity: 1;
  2006. color: white;
  2007. background: black;
  2008. z-index: 999;
  2009. }
  2010. .instant-youtube-options * {
  2011. width: auto;
  2012. height: auto;
  2013. margin: 0;
  2014. padding: 0;
  2015. font: inherit;
  2016. font-size: 13px;
  2017. vertical-align: middle;
  2018. text-transform: none;
  2019. text-align: left;
  2020. border-radius: 0;
  2021. text-decoration: none;
  2022. color: white;
  2023. background: black;
  2024. }
  2025. .instant-youtube-options > * {
  2026. margin-top: 1ex;
  2027. }
  2028. .instant-youtube-options table {
  2029. all: unset;
  2030. display: table;
  2031. }
  2032. .instant-youtube-options tr {
  2033. all: unset;
  2034. display: table-row;
  2035. }
  2036. .instant-youtube-options td {
  2037. all: unset;
  2038. display: table-cell;
  2039. padding: 2px;
  2040. }
  2041. .instant-youtube-options label > * {
  2042. display: inline;
  2043. }
  2044. .instant-youtube-options select {
  2045. padding: .5ex .25ex;
  2046. border: 1px solid #444;
  2047. -webkit-appearance: menulist;
  2048. }
  2049. .instant-youtube-options [data-action="resize-custom"] input {
  2050. width: 9ex;
  2051. padding: .5ex .5ex .4ex;
  2052. border: 1px solid #666;
  2053. }
  2054. .instant-youtube-options [data-action="buttons"] {
  2055. margin-top: 1em;
  2056. }
  2057. .instant-youtube-options button {
  2058. margin: 0 1ex 0 0;
  2059. padding: .5ex 2ex;
  2060. border: 2px solid gray;
  2061. font-weight: bold;
  2062. }
  2063. .instant-youtube-options button:hover {
  2064. border-color: white;
  2065. }
  2066. .instant-youtube-options label[disabled] {
  2067. opacity: 0.25;
  2068. }
  2069. .instant-youtube-storyboard {
  2070. height: 33%;
  2071. max-height: 90px;
  2072. display: block;
  2073. position: absolute;
  2074. left: 0;
  2075. right: 0;
  2076. bottom: 0;
  2077. overflow: visible;
  2078. transition: background-color .5s .25s;
  2079. }
  2080. .instant-youtube-storyboard[data-loaded]:hover {
  2081. background-color: #0004;
  2082. }
  2083. .instant-youtube-storyboard div {
  2084. display: block;
  2085. position: absolute;
  2086. bottom: 0;
  2087. pointer-events: none;
  2088. border: 3px solid #888;
  2089. box-shadow: 2px 2px 10px black;
  2090. transition: opacity .25s ease;
  2091. background-color: transparent;
  2092. background-origin: content-box;
  2093. opacity: 0;
  2094. }
  2095. .instant-youtube-storyboard div::after {
  2096. content: attr(data-time);
  2097. opacity: .5;
  2098. color: #fff;
  2099. background-color: #000;
  2100. font-weight: bold;
  2101. font-size: 10px;
  2102. position: absolute;
  2103. bottom: 4px;
  2104. left: 4px;
  2105. padding: 1px 3px;
  2106. }
  2107. .instant-youtube-storyboard:hover div {
  2108. opacity: 1;
  2109. }
  2110. .instant-youtube-container [pin] {
  2111. position: absolute;
  2112. width: 0;
  2113. height: 0;
  2114. margin: 0;
  2115. padding: 0;
  2116. top: auto; bottom: auto; left: auto; right: auto;
  2117. border-style: solid;
  2118. transition: opacity 2.5s ease-in, opacity 0.4s ease-out;
  2119. opacity: 0;
  2120. z-index: 100;
  2121. }
  2122. .instant-youtube-container[playing]:hover [pin]:not([transparent]) {
  2123. opacity: 1;
  2124. }
  2125. .instant-youtube-container[playing] [pin]:hover {
  2126. cursor: alias;
  2127. opacity: 1;
  2128. transition: opacity 0s;
  2129. }
  2130. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  2131. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  2132. .instant-youtube-container [pin=top-left] {
  2133. top: 0; left: 0;
  2134. border-width: 10px 10px 0 0;
  2135. border-color: red transparent transparent transparent;
  2136. }
  2137. .instant-youtube-container [pin=top-left][transparent] {
  2138. border-width: 10px 10px 0 0;
  2139. }
  2140. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  2141. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  2142. .instant-youtube-container [pin=top-right] {
  2143. top: 0; right: 0;
  2144. border-width: 0 10px 10px 0;
  2145. border-color: transparent red transparent transparent;
  2146. }
  2147. .instant-youtube-container [pin=top-right][transparent] {
  2148. border-width: 0 10px 10px 0;
  2149. }
  2150. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  2151. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  2152. .instant-youtube-container [pin=bottom-right] {
  2153. bottom: 0; right: 0;
  2154. border-width: 0 0 10px 10px;
  2155. border-color: transparent transparent red transparent;
  2156. }
  2157. .instant-youtube-container [pin=bottom-right][transparent] {
  2158. border-width: 0 0 10px 10px;
  2159. }
  2160. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  2161. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  2162. .instant-youtube-container [pin=bottom-left] {
  2163. bottom: 0; left: 0;
  2164. border-width: 10px 0 0 10px;
  2165. border-color: transparent transparent transparent red;
  2166. }
  2167. .instant-youtube-container [pin=bottom-left][transparent] {
  2168. border-width: 10px 0 0 10px;
  2169. }
  2170. .instant-youtube-dragndrop-placeholder {
  2171. z-index: 999999999;
  2172. margin: 0;
  2173. padding: 0;
  2174. background: rgba(0, 255, 0, 0.1);
  2175. border: 2px dotted green;
  2176. box-sizing: border-box;
  2177. pointer-events: none;
  2178. }
  2179. .instant-youtube-container [size-gripper] {
  2180. width: 0;
  2181. position: absolute;
  2182. top: 0;
  2183. bottom: 0;
  2184. cursor: e-resize;
  2185. border-color: rgba(50,100,255,0.5);
  2186. border-width: 12px;
  2187. background: rgba(50,100,255,0.2);
  2188. z-index: 99;
  2189. opacity: 0;
  2190. transition: opacity .1s ease-in-out, border-color .1s ease-in-out;
  2191. }
  2192. .instant-youtube-container[pinned*="right"] [size-gripper] {
  2193. border-style: none none none solid;
  2194. left: -4px;
  2195. }
  2196. .instant-youtube-container[pinned*="left"] [size-gripper] {
  2197. border-style: none solid none none;
  2198. right: -4px;
  2199. }
  2200. .instant-youtube-container [size-gripper]:hover {
  2201. opacity: 1;
  2202. }
  2203. .instant-youtube-container [size-gripper]:active {
  2204. opacity: 1;
  2205. width: auto;
  2206. left: -4px;
  2207. right: -4px;
  2208. }
  2209. .instant-youtube-container [size-gripper][tried-exceeding] {
  2210. border-color: rgba(255,0,0,0.5);
  2211. }
  2212. .instant-youtube-container [size-gripper][saveAs="global"] {
  2213. border-color: rgba(0,255,0,0.5);
  2214. }
  2215. .instant-youtube-container [size-gripper][saveAs="site"] {
  2216. border-color: rgba(0,255,255,0.5);
  2217. }
  2218. .instant-youtube-container [size-gripper][saveAs="reset"] {
  2219. border-color: rgba(255,255,0,0.5);
  2220. }
  2221. .instant-youtube-container [size-gripper][saveAs="cancel"] {
  2222. border-color: rgba(255,0,255,0.25);
  2223. }
  2224. .instant-youtube-container [size-gripper] > div {
  2225. white-space: nowrap;
  2226. color: white;
  2227. font-weight: normal;
  2228. line-height: 1.25;
  2229. text-align: left;
  2230. position: absolute;
  2231. top: 50%;
  2232. padding: 1ex 1em 1ex;
  2233. background-color: rgba(80,150,255,0.5);
  2234. }
  2235. .instant-youtube-container [size-gripper] [save-as="site"] {
  2236. font-weight: bold;
  2237. color: yellow;
  2238. }
  2239. .instant-youtube-container[pinned*="left"] [size-gripper] > div {
  2240. right: 0;
  2241. }
  2242. `, /;\n/g));
  2243. // move our rules to the end of HEAD to increase CSS specificity
  2244. if (styledom.nextElementSibling && document.head)
  2245. document.head.appendChild(styledom);
  2246. updateAltPlayerCSS();
  2247. }