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.

当前为 2017-07-12 提交的版本,查看 最新版本

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