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. A fast simple HTML5 direct playback (720p max) can be selected if available for the video.

当前为 2016-07-31 提交的版本,查看 最新版本

  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. A fast simple HTML5 direct playback (720p max) can be selected if available for the video.
  4. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются заглушки для видео, которые можно щелкнуть для загрузки плеера, и почти сразу же появляются кавер-картинки с названием видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  5. // @version 2.5.3
  6. // @include *
  7. // @exclude https://www.youtube.com/*
  8. // @author wOxxOm
  9. // @namespace wOxxOm.scripts
  10. // @license MIT License
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_addStyle
  14. // @grant GM_xmlhttpRequest
  15. // @connect www.youtube.com
  16. // @connect youtube.com
  17. // @run-at document-start
  18. // @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=
  19. // @compatible chrome
  20. // @compatible firefox
  21. // @compatible opera
  22. // ==/UserScript==
  23.  
  24. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  25.  
  26. var resizeMode = GM_getValue('resize', 'Fit to width');
  27. if (typeof resizeMode != 'string')
  28. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  29.  
  30. var resizeWidth = GM_getValue('width', 1280) |0;
  31. var resizeHeight = GM_getValue('height', 720) |0;
  32. updateCustomSize();
  33.  
  34. var playDirectly = !!GM_getValue('playHTML5', false);
  35. var skipCustom = !!GM_getValue('skipCustom', true);
  36. var showStoryboard = !!GM_getValue('showStoryboard', true);
  37. var pinnable = !!GM_getValue('pinnable', true);
  38.  
  39. var _ = initTL();
  40.  
  41. var imageLoader = document.createElement('img');
  42. var imageLoader2 = document.createElement('img');
  43.  
  44. var iframes = document.getElementsByTagName('iframe');
  45. var oembeds = document.getElementsByTagName('embed');
  46. var persite = (function() {
  47. var rules = [
  48. {host: /(^|\.)google\.\w{2,3}(\.\w{2,3})?$/, class:'g-blk', query: 'a[href*="youtube.com/watch"][data-ved]', eatparent: 1},
  49. {host: /(^|\.)pikabu\.ru$/, class:'b-video', match: '[data-url*="youtube.com/embed"]', attr: 'data-url'},
  50. {host: /(^|\.)androidauthority\.com$/, tag:'iframe', match: '[src*="youtube.com/embed"]', eatparent: '.video-container'},
  51. {host: /(^|\.)reddit\.com$/, tag:'iframe',
  52. match: '[data-url*="youtube.com/"] [src*="/mediaembed"], [data-url*="youtu.be/"] [src*="/mediaembed"]',
  53. src: function(e) { return e.closest('[data-url*="youtube.com/"], [data-url*="youtu.be/"]').dataset.url }},
  54. ];
  55. for (var i=0, rule; (i<rules.length) && (rule=rules[i]); i++) {
  56. if (rule.host && location.hostname.match(rule.host) && (rule.class || rule.tag))
  57. return {
  58. nodes: rule.class ? document.getElementsByClassName(rule.class) : document.getElementsByTagName(rule.tag),
  59. match: rule.match ? function(e) { return e.matches(rule.match) ? e : null }
  60. : function(e) { return e.querySelector(rule.query) },
  61. attr: rule.attr,
  62. src: rule.src,
  63. eatparent: rule.eatparent,
  64. };
  65. }
  66. })();
  67.  
  68. findEmbeds();
  69. injectStylesIfNeeded();
  70. new MutationObserver(findEmbeds).observe(document, {subtree:true, childList:true});
  71.  
  72. document.addEventListener('DOMContentLoaded', function(e) {
  73. injectStylesIfNeeded();
  74. adjustNodesIfNeeded(e);
  75. });
  76. window.addEventListener('resize', adjustNodesIfNeeded, true);
  77. window.addEventListener('message', function(e) {
  78. if (e.data == 'iframe-allowfs') {
  79. $$('iframe:not([allowfullscreen])').some(function(iframe) {
  80. if (iframe.contentWindow == e.source) {
  81. iframe.allowFullscreen = true;
  82. return true;
  83. }
  84. });
  85. if (window != window.top)
  86. window.parent.postMessage('iframe-allowfs', '*');
  87. }
  88. });
  89.  
  90. function findEmbeds(mutations) {
  91. var i, len, e;
  92. if (mutations && mutations.length == 1 && !mutations[0].addedNodes.length)
  93. return;
  94. if (persite)
  95. for (i=0, len=persite.nodes.length; (i<len) && (e=persite.nodes[i]); i++)
  96. if (e = persite.match(e))
  97. processEmbed(e, persite.src && persite.src(e) || e.getAttribute(persite.attr));
  98. for (i=0, len=iframes.length; (i<len) && (e=iframes[i]); i++)
  99. if (/youtube\.com(\/|%2F)(embed|v)(\/|%2F)/i.test(e.src))
  100. processEmbed(e);
  101. for (i=0, len=oembeds.length; (i<len) && (e=oembeds[i]); i++)
  102. if (/youtube\.com(\/|%2F)(embed|v)\//i.test(e.src))
  103. processEmbed(e);
  104. }
  105.  
  106. function processEmbed(node, src) {
  107. function decodeEmbedUrl(url) {
  108. return url.indexOf('youtube.com%2Fembed') > 0
  109. ? decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube.com%2Fembed[^&]+).*$/i, '$1'))
  110. : url;
  111. }
  112. src = src || node.src || node.href || '';
  113. var n = node;
  114. var np = n.parentNode, npw;
  115. var srcFixed = decodeEmbedUrl(src).replace(/\/(watch\?v=|v\/)/, '/embed/');
  116. if (src.indexOf('cdn.embedly.com/') > 0 ||
  117. resizeMode != 'Original' && np && np.children.length == 1 && !np.className && !np.id)
  118. {
  119. n = location.hostname == 'disqus.com' ? np.parentNode : np;
  120. np = n.parentElement;
  121. }
  122. if (!np ||
  123. !np.parentNode ||
  124. skipCustom && srcFixed.indexOf('enablejsapi=1') > 0 ||
  125. node.matches('.instant-youtube-embed, .YTLT-embed') ||
  126. node.onload // skip some retarded loaders
  127. )
  128. return;
  129.  
  130. var id = srcFixed.match(/(?:embed\/|v[=\/]|youtu\.be\/)([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  131. if (!id)
  132. return;
  133. id = id[1];
  134.  
  135. var autoplay = srcFixed.indexOf('autoplay=1') > 0;
  136.  
  137. if (np.localName == 'object')
  138. n = np, np = n.parentElement;
  139.  
  140. var eatparent = persite && persite.eatparent || 0;
  141. if (typeof eatparent == 'string')
  142. n = np.closest(eatparent) || n, np = n.parentElement;
  143. else
  144. while (eatparent--)
  145. n = np, np = n.parentElement;
  146.  
  147. var div = document.createElement('div');
  148. div.className = 'instant-youtube-container';
  149. div.FYTE = {
  150. state: 'querying',
  151. srcEmbed: srcFixed.replace(/&$/, ''),
  152. videoID: id,
  153. originalWidth: /%/.test(node.width) ? 320 : node.width|0 || n.clientWidth|0,
  154. originalHeight: /%/.test(node.height) ? 200 : node.height|0 || n.clientHeight|0,
  155. };
  156. div.FYTE.srcEmbedFixed = div.FYTE.srcEmbed.replace(/^http:/, 'https:').replace(/&?wmode=\w+/, '').replace(/[?&]feature=oembed/, '');
  157. div.FYTE.srcWatchFixed = div.FYTE.srcEmbedFixed.replace(/\/embed\//, '/watch?v=');
  158.  
  159. var divSize = calcContainerSize(div, n);
  160. var origStyle = getComputedStyle(n);
  161. div.style.cssText = important('background-color:transparent; transition:background-color 2s;' +
  162. (origStyle.hasOwnProperty('position') ? Object.keys(origStyle) : Object.keys(origStyle.__proto__) /*FF*/)
  163. .filter(function(k) { return !!k.match(/^(position|left|right|top|bottom)$/) })
  164. .map(function(k) { return k + ':' + origStyle[k] })
  165. .join(';')
  166. .replace(/\b[^;:]+:\s*(auto|static|block)\s*(!\s*important)?;/g, '') +
  167. (origStyle.display == 'inline' ? ';display:inline-block;width:100%' : '') +
  168. ';min-width:' + Math.min(divSize.w, div.FYTE.originalWidth) + 'px' +
  169. ';min-height:' + Math.min(divSize.h, div.FYTE.originalHeight) + 'px' +
  170. (resizeMode == 'Fit to width' ? ';width:100%' : '') +
  171. ';max-width:' + divSize.w + 'px; height:' + divSize.h + 'px;');
  172. if (!autoplay) {
  173. setTimeout(function() { div.style.backgroundColor = '' }, 0);
  174. setTimeout(function() { div.style.transition = '' }, 2000);
  175. }
  176.  
  177. // consume parents of retardedly positioned videos
  178. if (div.style.position.match('absolute|relative')) {
  179. if (np.children.length == 1 && floatPadding(np, getComputedStyle(np, ':after'), 'Top') >= div.FYTE.originalHeight)
  180. n = np, np = n.parentElement;
  181. div.style.cssText = div.style.cssText.replace(/\b(position|left|top|right|bottom):[^;]+/g, '');
  182. }
  183.  
  184. var wrapper = div.appendChild(document.createElement('div'));
  185. wrapper.className = 'instant-youtube-wrapper';
  186.  
  187. var img = wrapper.appendChild(document.createElement('img'));
  188. img.className = 'instant-youtube-thumbnail';
  189. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  190. img.style.cssText = important('transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0; max-width:none; max-height:none;');
  191.  
  192. img.title = _('Shift-click to use alternative player');
  193. img.onload = function(e) {
  194. if (img.naturalWidth <= 120)
  195. return img.onerror(e);
  196. var fitToWidth = true;
  197. if (img.naturalHeight) {
  198. var ratio = img.naturalWidth / img.naturalHeight;
  199. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  200. img.style.cssText += important('width:auto; height:100%;');
  201. fitToWidth = false;
  202. }
  203. }
  204. if (fitToWidth) {
  205. img.style.cssText += important('width:100%; height:auto;');
  206. }
  207. if (div.FYTE.videoWidth)
  208. fixThumbnailAR(div);
  209. if (!autoplay)
  210. img.style.opacity = 1;
  211. };
  212. img.onerror = function(e) {
  213. if (img.src.indexOf('maxresdefault') > 0)
  214. img.src = img.src.replace('maxresdefault','hqdefault');
  215. };
  216.  
  217. GM_xmlhttpRequest({
  218. method: 'GET',
  219. url: 'https://www.youtube.com/get_video_info?video_id=' + div.FYTE.videoID + '&el=detailpage',
  220. headers: {'Accept-Encoding': 'gzip'},
  221. context: div,
  222. onload: parseVideoInfo
  223. });
  224.  
  225. translateHTML(wrapper, 'beforeend', '\
  226. <a class="instant-youtube-title" target="_blank" href="' + div.FYTE.srcWatchFixed + '">&nbsp;</a>\
  227. <svg class="instant-youtube-play-button"><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"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>\
  228. <span tl class="instant-youtube-link">' + (playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  229. <div tl class="instant-youtube-options-button">Options</div>\
  230. ');
  231.  
  232. np.insertBefore(div, n);
  233. n.remove();
  234.  
  235. if (autoplay)
  236. return startPlaying(div);
  237.  
  238. div.addEventListener('click', clickHandler);
  239. }
  240.  
  241. function adjustNodesIfNeeded(e) {
  242. if (adjustNodesIfNeeded.scheduled)
  243. clearTimeout(adjustNodesIfNeeded.scheduled);
  244. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  245. adjustNodes(e);
  246. adjustNodesIfNeeded.scheduled = 0;
  247. }, 16);
  248. }
  249.  
  250. function adjustNodes(e, clickedContainer) {
  251. var force = !!clickedContainer;
  252. var nearest = force ? clickedContainer : null;
  253.  
  254. var vids = $$('div.instant-youtube-container:not([pinned])');
  255.  
  256. if (!nearest && e.type != 'DOMContentLoaded') {
  257. var minDistance = window.innerHeight*3/4 |0;
  258. var nearTargetY = window.innerHeight/2;
  259. vids.forEach(function(n) {
  260. var bounds = n.getBoundingClientRect();
  261. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  262. if (distance < minDistance) {
  263. minDistance = distance;
  264. nearest = n;
  265. }
  266. });
  267. }
  268.  
  269. if (nearest) {
  270. var bounds = nearest.getBoundingClientRect();
  271. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  272. }
  273.  
  274. var resized = false;
  275.  
  276. vids.forEach(function(n) {
  277. var size = calcContainerSize(n);
  278. var w = size.w, h = size.h;
  279.  
  280. // prevent parent clipping
  281. for (var e=n.parentElement, style; e; e=e.parentElement)
  282. if (e.style.overflow != 'visible' && (style=getComputedStyle(e)))
  283. if ((style.overflow+style.overflowX+style.overflowY).match(/hidden|scroll/))
  284. if (n.offsetTop < e.clientHeight / 2 && n.offsetTop + n.clientHeight > e.clientHeight)
  285. e.style.cssText = e.style.cssText.replace(/\boverflow(-[xy])?:[^;]+/g, '') +
  286. important('overflow:visible;overflow-x:visible;overflow-y:visible;');
  287.  
  288. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  289. return;
  290.  
  291. if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
  292. if (n.style.height != h + 'px') n.style.height = h + 'px';
  293. if (parseFloat(n.style.minWidth) > w) n.style.minWidth = n.style.maxWidth;
  294. if (parseFloat(n.style.minHeight) > h) n.style.minHeight = n.style.height;
  295.  
  296. fixThumbnailAR(n);
  297. resized = true;
  298. });
  299.  
  300. if (resized && nearest)
  301. setTimeout(function() {
  302. var bounds = nearest.getBoundingClientRect();
  303. var h = bounds.bottom - bounds.top;
  304. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  305. var projectedTop = projectedCenterY - h/2;
  306. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  307. window.scrollBy(0, bounds.top - safeTop);
  308. }, 16);
  309. }
  310.  
  311. function calcContainerSize(div, origNode) {
  312. var w, h;
  313. origNode = origNode || div;
  314. switch (resizeMode) {
  315. case 'Original':
  316. w = div.FYTE.originalWidth;
  317. h = div.FYTE.originalHeight;
  318. break;
  319. case 'Custom':
  320. w = resizeWidth;
  321. h = resizeHeight;
  322. break;
  323. case '1080p':
  324. case '720p':
  325. case '480p':
  326. case '360p':
  327. h = parseInt(resizeMode);
  328. w = h / 9 * 16;
  329. break;
  330. default: // fit-to-width mode
  331. var n = origNode;
  332. do {
  333. n = n.parentElement;
  334. // find parent node with nonzero width (i.e. independent of our video element)
  335. } while (n && !(w = n.clientWidth));
  336. if (w)
  337. h = w / 16 * 9;
  338. else {
  339. w = origNode.clientWidth;
  340. h = origNode.clientHeight;
  341. }
  342. }
  343. var np = origNode.parentElement;
  344. var style = getComputedStyle(np);
  345. var parentWidth = parseFloat(style.width) - floatPadding(np, style, 'Left') - floatPadding(np, style, 'Right');
  346. if (parentWidth > 0 && parentWidth < w) {
  347. h = parentWidth / w * h;
  348. w = parentWidth;
  349. }
  350. if (resizeMode == 'Fit to width' && h < div.FYTE.originalHeight*0.9)
  351. h = Math.min(div.FYTE.originalHeight, w / div.FYTE.originalWidth * div.FYTE.originalHeight);
  352.  
  353. return {w: window.chrome ? w : Math.round(w), h:h};
  354. }
  355.  
  356. function parseVideoInfo(response) {
  357. var div = response.context;
  358. var txt = response.responseText;
  359. var info = tryCatch(function() { return JSON.parse(txt.replace(/(\w+)=?(.*?)(&|$)/g, '"$1":"$2",').replace(/^(.+?),?$/, '{$1}')) }) || {};
  360. var videoSources = [];
  361.  
  362. // parse width & height to adjust the thumbnail
  363. var m = decodeURIComponent(info.adaptive_fmts || '').match(/size=(\d+)x(\d+)\b/) ||
  364. decodeURIComponent(txt).match(/\/(\d+)x(\d+)\//);
  365. if (m)
  366. fixThumbnailAR(div, m[1]|0, m[2]|0);
  367.  
  368. // parse video sources
  369. if (info.url_encoded_fmt_stream_map && info.fmt_list) {
  370. var streams = {};
  371. decodeURIComponent(info.url_encoded_fmt_stream_map).split(',').forEach(function(stream) {
  372. var params = {};
  373. stream.split('&').forEach(function(kv) {
  374. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  375. });
  376. streams[params.itag] = params;
  377. });
  378. decodeURIComponent(info.fmt_list).split(',').forEach(function(fmt) {
  379. var itag = fmt.split('/')[0];
  380. var dimensions = fmt.split('/')[1];
  381. var stream = streams[itag];
  382. if (stream) {
  383. videoSources.push({
  384. src: stream.url,
  385. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  386. });
  387. }
  388. });
  389. } else {
  390. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  391. var text = decodeURIComponent(txt).split('url_encoded_fmt_stream_map')[1];
  392. while (m = rx.exec(text)) {
  393. videoSources.push({
  394. src: decodeURIComponent(decodeURIComponent(m[1]))
  395. });
  396. }
  397. }
  398.  
  399. var duration = div.FYTE.duration = info.length_seconds|0 || '';
  400. if (duration) {
  401. var d = new Date(null);
  402. d.setSeconds(duration);
  403. duration = d.toISOString().replace(/^.+?T[0:]{0,4}(.+?)\..+$/, '<span>$1</span>');
  404. }
  405. var title = decodeURIComponent(info.title || info.reason || '').replace(/\+/g, ' ');
  406. if (title || duration) {
  407. $(div, '.instant-youtube-title').innerHTML = (title ? '<strong>' + title + '</strong>' : '') + duration;
  408. }
  409. if (info.reason)
  410. div.setAttribute('disabled', '');
  411.  
  412. if (videoSources.length)
  413. div.FYTE.videoSources = videoSources;
  414.  
  415. if (info.storyboard_spec) {
  416. m = decodeURIComponent(decodeURIComponent(info.storyboard_spec)).split('|');
  417. div.FYTE.storyboard = JSON.parse(m[m.length-1].replace(/^(\d+)#(\d+)#(\d+)#(\d+)#(\d+)#.+$/, '{"w":$1, "h":$2, "len":$3, "rows":$4, "cols":$5}'));
  418. div.FYTE.storyboard.url = m[0].replace('$L/$N.jpg', (m.length-2) + '/M0.jpg?sigh=' + m[m.length-1].replace(/^.+?#([^#]+)$/, '$1'));
  419. $(div, '.instant-youtube-options-button').insertAdjacentHTML('beforebegin',
  420. '<div class="instant-youtube-storyboard"' + (showStoryboard ? '' : ' disabled') + '>' +
  421. important('<div style="width:' + (div.FYTE.storyboard.w-1) + 'px; height:' + div.FYTE.storyboard.h + 'px;') +
  422. '">&nbsp;</div>' +
  423. '</div>');
  424. if (showStoryboard)
  425. updateHoverHandler(div);
  426. }
  427.  
  428. injectStylesIfNeeded();
  429.  
  430. if (div.FYTE.state == 'scheduled play')
  431. setTimeout(function() { startPlayingDirectly(div) }, 0);
  432.  
  433. div.FYTE.state = '';
  434. }
  435.  
  436. function fixThumbnailAR(div, w, h) {
  437. var img = $(div, 'img');
  438. var thw = img.naturalWidth, thh = img.naturalHeight;
  439. if (w && h) { // means thumbnail is still loading
  440. div.FYTE.videoWidth = w;
  441. div.FYTE.videoHeight = h;
  442. } else {
  443. w = div.FYTE.videoWidth;
  444. h = div.FYTE.videoHeight;
  445. if (!w || !h)
  446. return;
  447. }
  448. var divw = div.clientWidth, divh = div.clientHeight;
  449. // if both video and thumbnail are 4:3, fit the image to height
  450. //console.log(div, divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  451. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  452. img.style.maxHeight = img.clientHeight + 'px';
  453. if (!div.FYTE.videoWidth) // skip animation if thumbnail is already loaded
  454. img.style.transition = 'height 1s ease, margin-top 1s ease';
  455. setTimeout(function() {
  456. img.style.maxHeight = 'none';
  457. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  458. setTimeout(function() {
  459. img.style.transition = '';
  460. }, 1000);
  461. }, 0);
  462. }
  463. }
  464.  
  465. function updateHoverHandler(div) {
  466. var sb = $(div, '.instant-youtube-storyboard');
  467. if (!showStoryboard) {
  468. if (!sb.getAttribute('disabled'))
  469. sb.setAttribute('disabled', '');
  470. return;
  471. }
  472. if (sb.hasAttribute('disabled'))
  473. sb.removeAttribute('disabled');
  474.  
  475. sb.addEventListener('click', storyboardClickHandler);
  476.  
  477. var oldIndex = null;
  478. var style = sb.firstElementChild.style;
  479. sb.addEventListener('mousemove', storyboardHoverHandler);
  480. sb.addEventListener('mouseout', storyboardHoverHandler);
  481.  
  482. div.addEventListener('mouseover', storyboardPreloader);
  483. div.addEventListener('mouseout', storyboardPreloader);
  484.  
  485. var spinner = document.createElement('span');
  486. spinner.className = 'instant-youtube-loading-button';
  487.  
  488. function storyboardClickHandler(e) {
  489. sb.removeEventListener('click', storyboardClickHandler);
  490. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  491. div.FYTE.startAt = offsetX / this.clientWidth * div.FYTE.duration |0;
  492. div.FYTE.srcEmbedFixed = setUrlParams(div.FYTE.srcEmbedFixed, {start: div.FYTE.startAt});
  493. startPlaying(div, e.shiftKey);
  494. }
  495.  
  496. function storyboardPreloader(e) {
  497. if (e.type == 'mouseout') {
  498. imageLoader.onload = null; imageLoader.src = '';
  499. spinner.remove();
  500. return;
  501. }
  502. if (!div.FYTE.storyboard || div.FYTE.storyboard.preloaded)
  503. return;
  504. var lastpart = (div.FYTE.storyboard.len-1)/(div.FYTE.storyboard.rows * div.FYTE.storyboard.cols) |0;
  505. if (lastpart <= 0)
  506. return;
  507. var part = 0;
  508. imageLoader.src = setStoryboardUrl(part++);
  509. imageLoader.onload = function() {
  510. if (part > lastpart) {
  511. div.FYTE.storyboard.preloaded = true;
  512. div.removeEventListener('mouseover', storyboardPreloader);
  513. div.removeEventListener('mouseout', storyboardPreloader);
  514. imageLoader.onload = null;
  515. imageLoader.src = '';
  516. spinner.remove();
  517. return;
  518. }
  519. imageLoader.src = setStoryboardUrl(part++);
  520. };
  521. }
  522.  
  523. function setStoryboardUrl(part) {
  524. return div.FYTE.storyboard.url.replace(/M\d+\.jpg\?/, 'M' + part + '.jpg?');
  525. }
  526.  
  527. function storyboardHoverHandler(e) {
  528. if (!showStoryboard || !div.FYTE.storyboard)
  529. return;
  530. if (e.type == 'mouseout')
  531. return imageLoader2.onload && imageLoader2.onload();
  532. var w = div.FYTE.storyboard.w;
  533. var h = div.FYTE.storyboard.h;
  534. var cols = div.FYTE.storyboard.cols;
  535. var rows = div.FYTE.storyboard.rows;
  536. var len = div.FYTE.storyboard.len;
  537. var partlen = rows * cols;
  538.  
  539. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  540. var left = Math.min(this.clientWidth - w, Math.max(0, offsetX - w)) |0;
  541. if (!style.left || parseInt(style.left) != left) {
  542. style.left = left + 'px';
  543. if (spinner.parentElement)
  544. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  545. }
  546.  
  547. var index = Math.min(offsetX / this.clientWidth * (len+1) |0, len - 1);
  548. if (index == oldIndex)
  549. return;
  550.  
  551. var part = index/partlen|0;
  552. if (!oldIndex || part != (oldIndex/partlen|0)) {
  553. style.cssText = style.cssText.replace(/$|background-image[^;]+;/,
  554. 'background-image: url(' + setStoryboardUrl(part) + ')!important;');
  555. if (!div.FYTE.storyboard.preloaded) {
  556. if (spinner.timer)
  557. clearTimeout(spinner.timer);
  558. spinner.timer = setTimeout(function() {
  559. spinner.timer = 0;
  560. if (!imageLoader2.src)
  561. return;
  562. this.appendChild(spinner);
  563. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  564. }.bind(this), 50);
  565. imageLoader2.onload = function() {
  566. clearTimeout(spinner.timer);
  567. spinner.remove();
  568. spinner.timer = 0;
  569. imageLoader2.onload = null;
  570. imageLoader2.src = '';
  571. };
  572. imageLoader2.src = setStoryboardUrl(part);
  573. }
  574. }
  575.  
  576. oldIndex = index;
  577. index = index % partlen;
  578. style.backgroundPosition = '-' + (index % cols) * w + 'px -' + (index / cols |0) * h + 'px';
  579. }
  580. }
  581.  
  582. function clickHandler(e) {
  583. if (e.target.href)
  584. return;
  585. if (e.target.matches('.instant-youtube-options-button')) {
  586. showOptions(e);
  587. e.preventDefault();
  588. e.stopPropagation();
  589. return;
  590. }
  591. if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  592. return;
  593.  
  594. e.preventDefault();
  595. e.stopPropagation();
  596.  
  597. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  598. startPlaying(e.target.closest('.instant-youtube-container'), alternateMode);
  599. }
  600.  
  601. function startPlaying(div, alternateMode) {
  602. div.removeEventListener('click', clickHandler);
  603.  
  604. $$(div, '.instant-youtube-wrapper > *:not(img):not(a)').forEach(function(e) { e.style.cssText = 'display:none!important' });
  605. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  606.  
  607. div.firstElementChild.insertAdjacentHTML('beforeend',
  608. '<div pin="top-left"></div><div pin="top-right"></div><div pin="bottom-right"></div><div pin="bottom-left"></div>');
  609. $$(div, '[pin]').forEach(function(pin) {
  610. pin.onclick = function(e) {
  611. var pinIt = !div.hasAttribute('pinned') || !pin.hasAttribute('active');
  612. var corner = pin.getAttribute('pin');
  613. var video = $(div, 'video');
  614. if (pinIt) {
  615. $$(div, '[pin][active]').forEach(function(p) { p.removeAttribute('active') });
  616. pin.setAttribute('active', '');
  617. if (!div.FYTE.unpinnedStyle) {
  618. div.FYTE.unpinnedStyle = div.style.cssText;
  619. var stub = div.cloneNode();
  620. var img = $(div, 'img').cloneNode();
  621. img.style.opacity = 1;
  622. img.style.display = 'block';
  623. img.title = '';
  624. stub.appendChild(img);
  625. stub.onclick = function(e) { $(div, '[pin][active]').onclick(e) };
  626. stub.style.cssText += 'opacity:0.3!important;';
  627. div.FYTE.stub = stub;
  628. div.parentNode.insertBefore(stub, div);
  629. }
  630. div.setAttribute('pinned', '');
  631. div.style.cssText = important(
  632. 'position: fixed;' +
  633. 'contain: inherit;' +
  634. 'width: 400px;' +
  635. 'z-index: 999999999;' +
  636. 'height:' + (400 / div.FYTE.videoWidth * div.FYTE.videoHeight) + 'px;' +
  637. 'top:' + (corner.indexOf('top') >= 0 ? '0' : 'auto') + ';' +
  638. 'bottom:' + (corner.indexOf('bottom') >= 0 ? '0' : 'auto') + ';' +
  639. 'left:' + (corner.indexOf('left') >= 0 ? '0' : 'auto') + ';' +
  640. 'right:' + (corner.indexOf('right') >= 0 ? '0' : 'auto') + ';'
  641. );
  642. if (video)
  643. document.body.appendChild(div);
  644. } else {
  645. pin.removeAttribute('active');
  646. div.removeAttribute('pinned');
  647. div.style.cssText = div.FYTE.unpinnedStyle;
  648. div.FYTE.unpinnedStyle = '';
  649. if (div.FYTE.stub) {
  650. if (video)
  651. div.FYTE.stub.parentNode.appendChild(div, div.FYTE.stub);
  652. div.FYTE.stub.remove();
  653. div.FYTE.stub = null;
  654. }
  655. }
  656. if (video && video.paused)
  657. video.play();
  658. };
  659. });
  660.  
  661. if (window != window.top)
  662. window.parent.postMessage('iframe-allowfs', '*');
  663.  
  664. if ((!!playDirectly + !!alternateMode == 1) && (div.FYTE.videoSources || div.FYTE.state == 'querying')) {
  665. if (div.FYTE.videoSources)
  666. startPlayingDirectly(div);
  667. else {
  668. // playback will start in parseVideoInfo
  669. div.FYTE.state = 'scheduled play';
  670. // fallback to iframe in 5s
  671. setTimeout(function() {
  672. if (div.FYTE.state) {
  673. div.FYTE.state = '';
  674. switchToIFrame.call(div);
  675. }
  676. }, 5000);
  677. }
  678. }
  679. else
  680. switchToIFrame.call(div);
  681. }
  682.  
  683. function startPlayingDirectly(div) {
  684. var video = document.createElement('video');
  685. video.controls = true;
  686. video.autoplay = true;
  687. video.style.cssText = important(
  688. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0; transition:opacity 2s;' +
  689. 'width:100%; height:100%;');
  690. video.className = 'instant-youtube-embed';
  691. video.volume = GM_getValue('volume', 0.5);
  692.  
  693. div.FYTE.videoSources.forEach(function(src) {
  694. var srcdom = video.appendChild(document.createElement('source'));
  695. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  696. srcdom.onerror = switchToIFrame.bind(div);
  697. });
  698.  
  699.  
  700. if (window.chrome) {
  701. video.addEventListener('click', function(e) {
  702. this.paused ? this.play() : this.pause();
  703. });
  704. }
  705. video.interval = (function() {
  706. return setInterval(function() {
  707. if (video.volume != GM_getValue('volume', 0.5))
  708. GM_setValue('volume', video.volume);
  709. }, 1000);
  710. })();
  711. var title = $(div, '.instant-youtube-title');
  712. if (title) {
  713. video.onpause = function() { title.removeAttribute('hidden') };
  714. video.onplay = function() { title.setAttribute('hidden', true) };
  715. }
  716. video.onloadedmetadata = div.FYTE.startAt && function(e) {
  717. video.currentTime = div.FYTE.startAt;
  718. };
  719. video.onloadeddata = function(e) {
  720. pauseOtherVideos(this);
  721. div.style.cssText += 'contain:inherit!important'; // allow fullscreen
  722. div.firstElementChild.appendChild(this);
  723. div.setAttribute('playing', '');
  724. this.style.opacity = 1;
  725. var img = $(div, 'img');
  726. img.style.transition = 'opacity 1s';
  727. img.style.opacity = 0;
  728. };
  729. }
  730.  
  731. function switchToIFrame(e) {
  732. var div = this;
  733. var wrapper = div.firstElementChild;
  734. if (e) {
  735. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  736. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  737. while (video.lastElementChild)
  738. video.lastElementChild.remove();
  739. }
  740.  
  741. $(div, '[pin]').insertAdjacentHTML('beforebegin',
  742. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
  743. setUrlParams(div.FYTE.srcEmbedFixed, {
  744. html5: 1,
  745. autoplay: 1,
  746. autohide: 2,
  747. border: 0,
  748. controls: 1,
  749. fs: 1,
  750. showinfo: 1,
  751. ssl: 1,
  752. theme: 'dark',
  753. enablejsapi: 1,
  754. }) + '" frameborder="0" allowfullscreen width="100%" height="100%"></iframe>');
  755.  
  756. $(div, 'iframe').onload = function() {
  757. pauseOtherVideos(this);
  758. this.style.cssText = important(
  759. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:1; transition:opacity 2s;');
  760.  
  761. div.setAttribute('iframe', '');
  762. div.setAttribute('playing', '');
  763. div.style.cssText += 'contain:none!important'; // allow fullscreen
  764. setTimeout(function() {
  765. $(div, 'img').style.display = 'none';
  766. var title = $(div, '.instant-youtube-title');
  767. if (title)
  768. title.remove();
  769. }, 2000);
  770. };
  771. }
  772.  
  773. function setUrlParams(url, params) {
  774. var names = Object.keys(params);
  775. url = url.replace(new RegExp('[?&](' + names.join('|') + ')(=[^?&]*)?', 'gi'), '');
  776. return url +
  777. (url.indexOf('?') > 0 ? '&' : '?') +
  778. names.map(function(n) { return n + '=' + params[n] }).join('&');
  779. }
  780.  
  781. function pauseOtherVideos(activePlayer) {
  782. $$(activePlayer.ownerDocument, '.instant-youtube-embed').forEach(function(v) {
  783. if (v == activePlayer)
  784. return;
  785. switch (v.localName) {
  786. case 'video':
  787. if (!v.paused)
  788. v.pause();
  789. break;
  790. case 'iframe':
  791. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  792. break;
  793. }
  794. });
  795. }
  796.  
  797. function showOptions(e) {
  798. var optionsButton = e.target;
  799. translateHTML(optionsButton, 'afterend', '\
  800. <div class="instant-youtube-options">\
  801. <label tl style="width: 100% !important;">Size:<br>\
  802. <select data-action="size-mode">\
  803. <option tl value="Original">Original\
  804. <option tl value="Fit to width">Fit to width\
  805. <option>360p\
  806. <option>480p\
  807. <option>720p\
  808. <option>1080p\
  809. <option tl value="Custom">Custom...\
  810. </select>\
  811. </label>\
  812. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  813. <input type="number" min="320" max="9999" tl-placeholder="width" data-action="width" step="1" value="' + (resizeWidth||'') + '">\
  814. x\
  815. <input type="number" min="240" max="9999" tl-placeholder="height" data-action="height" step="1" value="' + (resizeHeight||'') + '">\
  816. </label>\
  817. <label tl="content,title" title="Show storyboard preview on mouse hover at the bottom">\
  818. <input data-action="storyboard" type="checkbox" ' + (showStoryboard ? 'checked' : '') + '>\
  819. Storyboard thumbs\
  820. </label>\
  821. <label tl="content,title" title="Tip: shift-clicking thumbnails will use alternative player">\
  822. <input data-action="direct" type="checkbox" ' + (playDirectly ? 'checked' : '') + '>\
  823. Play directly\
  824. </label>\
  825. <label tl="content,title" title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
  826. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  827. Safe\
  828. </label>\
  829. <label tl="content,title" title="Enable corner pinning controls when a video is playing">\
  830. <input data-action="pinnable" type="checkbox" ' + (pinnable ? 'checked' : '') + '>\
  831. Corner pins\
  832. </label>\
  833. <span data-action="buttons">\
  834. <button tl data-action="ok">OK</button>\
  835. <button tl data-action="cancel">Cancel</button>\
  836. </span>\
  837. </div>\
  838. ');
  839. var options = optionsButton.nextElementSibling;
  840.  
  841. options.addEventListener('keydown', function(e) {
  842. if (e.target.localName == 'input' &&
  843. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  844. return false;
  845. });
  846.  
  847. $(options, '[data-action="size-mode"]').value = resizeMode;
  848. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  849. var v = this.value != 'Custom';
  850. var e = $(options, '[data-action="size-custom"]');
  851. e.children[0].disabled = e.children[1].disabled = v;
  852. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  853. });
  854.  
  855. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  856. if (e.target.dataset.action != 'ok') {
  857. options.remove();
  858. return;
  859. }
  860. var v, shouldAdjust;
  861. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  862. GM_setValue('resize', resizeMode = v);
  863. shouldAdjust = true;
  864. }
  865. if (resizeMode == 'Custom') {
  866. var w = $(options, '[data-action="width"]').value |0;
  867. var h = $(options, '[data-action="height"]').value |0;
  868. if (resizeWidth != w || resizeHeight != h) {
  869. updateCustomSize(w, h);
  870. GM_setValue('width', resizeWidth);
  871. GM_setValue('height', resizeHeight);
  872. shouldAdjust = true;
  873. }
  874. }
  875. if (showStoryboard != (v = $(options, '[data-action="storyboard"]').checked)) {
  876. GM_setValue('showStoryboard', showStoryboard = v);
  877. $$('.instant-youtube-container').forEach(updateHoverHandler);
  878. }
  879. if (playDirectly != (v = $(options, '[data-action="direct"]').checked)) {
  880. GM_setValue('playHTML5', playDirectly = v);
  881. $$('.instant-youtube-container .instant-youtube-link').forEach(function(e) {
  882. e.textContent = playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  883. });
  884. }
  885. if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
  886. GM_setValue('skipCustom', skipCustom = v);
  887. }
  888. if (pinnable != (v = $(options, '[data-action="pinnable"]').checked)) {
  889. GM_setValue('pinnable', pinnable = v);
  890. }
  891.  
  892. options.remove();
  893.  
  894. if (shouldAdjust)
  895. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  896. });
  897. }
  898.  
  899. function updateCustomSize(w, h) {
  900. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  901. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  902. }
  903.  
  904. function important(cssText) {
  905. return cssText.replace(/;/g, '!important;');
  906. }
  907.  
  908. function tryCatch(func) {
  909. try {
  910. return func();
  911. } catch(e) {
  912. console.log(e);
  913. }
  914. }
  915.  
  916. function getFunctionComment(fn) {
  917. return fn.toString().match(/\/\*([\s\S]*?)\*\/\s*\}$/)[1];
  918. }
  919.  
  920. function $(selORnode, sel) {
  921. return sel ? selORnode.querySelector(sel)
  922. : document.querySelector(selORnode);
  923. }
  924.  
  925. function $$(selORnode, sel) {
  926. return Array.prototype.slice.call(
  927. sel ? selORnode.querySelectorAll(sel)
  928. : document.querySelectorAll(selORnode));
  929. }
  930.  
  931. function overrideCSS(e, params) {
  932. var names = Object.keys(params);
  933. var style = e.style.cssText.replace(new RegExp('(^|\s|;)(' + names.join('|') + ')(:[^;]+)', 'gi'), '$1');
  934. e.style.cssText = style.replace(/[^;]\s*$/, '$&;').replace(/^\s*;\s*/, '') +
  935. names.map(function(n) { return n + ':' + params[n] + '!important' }).join(';') + ';';
  936. }
  937.  
  938. // fix dumb Firefox bug
  939. function floatPadding(node, style, dir) {
  940. var padding = style['padding' + dir];
  941. if (padding.indexOf('%') < 0)
  942. return parseFloat(padding);
  943. return parseFloat(padding) * (parseFloat(style.width) || node.clientWidth) / 100;
  944. }
  945.  
  946. function translateHTML(baseElement, place, html) {
  947. var tmp = document.createElement('div');
  948. tmp.innerHTML = html;
  949. $$(tmp, '[tl]').forEach(function(node) {
  950. (node.getAttribute('tl') || 'content').split(',').forEach(function(what) {
  951. var child, src, tl;
  952. if (what == 'content') {
  953. for (var i = node.childNodes.length-1, n; (i>=0) && (n=node.childNodes[i]); i--) {
  954. if (n.nodeType == Node.TEXT_NODE && n.textContent.trim()) {
  955. child = n;
  956. break;
  957. }
  958. }
  959. } else
  960. child = node.getAttributeNode(what);
  961. if (!child)
  962. return;
  963. src = child.textContent;
  964. srcTrimmed = src.trim();
  965. tl = src.replace(srcTrimmed, _(srcTrimmed));
  966. if (src != tl)
  967. child.textContent = tl;
  968. });
  969. });
  970. baseElement.insertAdjacentHTML(place, tmp.innerHTML);
  971. }
  972.  
  973. function initTL(src) {
  974. var tlSource = {
  975. 'watch on Youtube': {
  976. 'ru': 'открыть на Youtube',
  977. },
  978. 'Play with Youtube player': {
  979. 'ru': 'Включить плеер Youtube',
  980. },
  981. 'Play directly (up to 720p)': {
  982. 'ru': 'Включить напрямую (макс. 720p)',
  983. },
  984. 'Shift-click to use alternative player': {
  985. 'ru': 'Shift-клик для смены типа плеера',
  986. },
  987. 'Options': {
  988. 'ru': 'Опции',
  989. },
  990. 'Size:': {
  991. 'ru': 'Размер:',
  992. },
  993. 'Original': {
  994. 'ru': 'Исходный',
  995. },
  996. 'Fit to width': {
  997. 'ru': 'На всю ширину',
  998. },
  999. 'Custom...': {
  1000. 'ru': 'Настроить...',
  1001. },
  1002. 'width': {
  1003. 'ru': 'ширина',
  1004. },
  1005. 'height': {
  1006. 'ru': 'высота',
  1007. },
  1008. 'Storyboard thumbs': {
  1009. 'ru': 'Раскадровка',
  1010. },
  1011. 'Show storyboard preview on mouse hover at the bottom': {
  1012. 'ru': 'Показывать миникадры при наведении мыши на низ кавер-картинки',
  1013. },
  1014. 'Play directly': {
  1015. 'ru': 'Плеер браузера',
  1016. },
  1017. 'Tip: shift-clicking thumbnails will use alternative player': {
  1018. 'ru': 'Удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  1019. },
  1020. 'Safe': {
  1021. 'ru': 'Консервативный режим',
  1022. },
  1023. 'Corner pins': {
  1024. 'ru': 'Угловые шпильки',
  1025. },
  1026. 'Enable corner pinning controls when a video is playing': {
  1027. 'ru': 'Включить угловые шпильки для закрепления видео во время просмотра',
  1028. },
  1029. 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)': {
  1030. 'ru': 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 (подействует после обновления страницы)',
  1031. },
  1032. 'OK': {
  1033. 'ru': 'ОК',
  1034. },
  1035. 'Cancel': {
  1036. 'ru': 'Оменить',
  1037. },
  1038. };
  1039. var browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  1040. var browserLangMajor = browserLang.replace(/-.+/, '');
  1041. var tl = {};
  1042. Object.keys(tlSource).forEach(function(k) {
  1043. var langs = tlSource[k];
  1044. var text = langs[browserLang] || langs[browserLangMajor];
  1045. if (text)
  1046. tl[k] = text;
  1047. });
  1048. return function(src) { return tl[src] || src };
  1049. }
  1050.  
  1051. function injectStylesIfNeeded() {
  1052. var styledom = $('style#instant-youtube-styles');
  1053. if (styledom) {
  1054. // move our rules to the end of HEAD to increase CSS specificity
  1055. if (styledom.nextElementSibling && document.head)
  1056. document.head.insertBefore(styledom, null);
  1057. return;
  1058. }
  1059. styledom = (document.head || document.documentElement).appendChild(document.createElement('style'));
  1060. styledom.id = 'instant-youtube-styles';
  1061. styledom.textContent = important(getFunctionComment(function() { /*
  1062. .instant-youtube-container {
  1063. contain: strict;
  1064. position: relative;
  1065. overflow: hidden;
  1066. cursor: pointer;
  1067. padding: 0;
  1068. margin: 0;
  1069. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1070. text-align: center;
  1071. background: black;
  1072. }
  1073. .instant-youtube-container[disabled] {
  1074. background: #888;
  1075. }
  1076. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1077. display: none;
  1078. }
  1079. .instant-youtube-container .instant-youtube-wrapper {
  1080. width: 100%;
  1081. height: 100%;
  1082. }
  1083. .instant-youtube-container .instant-youtube-play-button {
  1084. display: block;
  1085. position: absolute;
  1086. width: 85px;
  1087. height: 60px;
  1088. left: 0;
  1089. right: 0;
  1090. top: 0;
  1091. bottom: 0;
  1092. margin: auto;
  1093. }
  1094. .instant-youtube-container .instant-youtube-loading-button {
  1095. display: block;
  1096. position: absolute;
  1097. width: 20px;
  1098. height: 20px;
  1099. left: 0;
  1100. right: 0;
  1101. top: 0;
  1102. bottom: 0;
  1103. padding: 0;
  1104. margin: auto;
  1105. pointer-events: none;
  1106. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1107. }
  1108. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1109. fill: #CC181E;
  1110. }
  1111. .instant-youtube-container .instant-youtube-link {
  1112. display: block;
  1113. position: absolute;
  1114. width: 20em;
  1115. height: 20px;
  1116. top: 50%;
  1117. left: 0;
  1118. right: 0;
  1119. margin: 60px auto;
  1120. padding: 0;
  1121. border: none;
  1122. text-align: center;
  1123. text-decoration: none;
  1124. text-shadow: 1px 1px 3px black;
  1125. font-weight: bold;
  1126. color: white;
  1127. }
  1128. .instant-youtube-container span.instant-youtube-link {
  1129. z-index: 8;
  1130. font-weight: normal;
  1131. font-size: 12px;
  1132. }
  1133. .instant-youtube-container .instant-youtube-link:hover {
  1134. text-decoration: underline;
  1135. color: white;
  1136. background: transparent;
  1137. }
  1138. .instant-youtube-container iframe {
  1139. z-index: 10;
  1140. }
  1141. .instant-youtube-container .instant-youtube-title {
  1142. z-index: 9;
  1143. display: block;
  1144. position: absolute;
  1145. width: auto;
  1146. top: 0;
  1147. left: 0;
  1148. right: 0;
  1149. margin: 0;
  1150. padding: 7px;
  1151. border: none;
  1152. text-shadow: 1px 1px 2px black;
  1153. text-align: center;
  1154. text-decoration: none;
  1155. color: white;
  1156. background-color: rgba(0, 0, 0, 0.5);
  1157. }
  1158. .instant-youtube-container .instant-youtube-title strong {
  1159. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1160. }
  1161. .instant-youtube-container .instant-youtube-title strong:after {
  1162. content: " - $tl:'watch on Youtube'";
  1163. font-weight: normal;
  1164. margin-right: 1ex;
  1165. }
  1166. .instant-youtube-container .instant-youtube-title span {
  1167. color: inherit;
  1168. }
  1169. .instant-youtube-container .instant-youtube-title span:before {
  1170. content: "(";
  1171. }
  1172. .instant-youtube-container .instant-youtube-title span:after {
  1173. content: ")";
  1174. }
  1175. @-webkit-keyframes instant-youtube-fadein {
  1176. from { opacity: 0 }
  1177. to { opacity: 1 }
  1178. }
  1179. @-moz-keyframes instant-youtube-fadein {
  1180. from { opacity: 0 }
  1181. to { opacity: 1 }
  1182. }
  1183. @keyframes instant-youtube-fadein {
  1184. from { opacity: 0 }
  1185. to { opacity: 1 }
  1186. }
  1187. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1188. display: none;
  1189. margin: 0;
  1190. }
  1191. .instant-youtube-container .instant-youtube-title:hover {
  1192. text-decoration: underline;
  1193. }
  1194. .instant-youtube-container .instant-youtube-title strong {
  1195. color: white;
  1196. }
  1197. .instant-youtube-container .instant-youtube-options-button {
  1198. opacity: 0.6;
  1199. position: absolute;
  1200. right: 0;
  1201. bottom: 0;
  1202. margin: 0;
  1203. padding: 1.5ex 2ex;
  1204. font-size: 11px;
  1205. text-shadow: 1px 1px 2px black;
  1206. color: white;
  1207. }
  1208. .instant-youtube-container .instant-youtube-options-button:hover {
  1209. opacity: 1;
  1210. background: rgba(0, 0, 0, 0.5);
  1211. }
  1212. .instant-youtube-container .instant-youtube-options {
  1213. display: flex;
  1214. position: absolute;
  1215. right: 0;
  1216. bottom: 0;
  1217. margin: 0;
  1218. padding: 2ex 1ex 2ex 2ex;
  1219. flex-direction: column;
  1220. align-items: flex-start;
  1221. line-height: 1.5;
  1222. text-align: left;
  1223. opacity: 1;
  1224. color: white;
  1225. background: black;
  1226. }
  1227. .instant-youtube-container .instant-youtube-options * {
  1228. width: auto;
  1229. height: auto;
  1230. margin: 0;
  1231. padding: 0;
  1232. font: inherit;
  1233. font-size: 13px;
  1234. vertical-align: middle;
  1235. text-transform: none;
  1236. text-align: left;
  1237. border-radius: 0;
  1238. text-decoration: none;
  1239. color: white;
  1240. background: black;
  1241. }
  1242. .instant-youtube-container .instant-youtube-options > label {
  1243. margin-top: 1ex;
  1244. }
  1245. .instant-youtube-container .instant-youtube-options > label > * {
  1246. display: inline;
  1247. }
  1248. .instant-youtube-container .instant-youtube-options select {
  1249. width: 20ex;
  1250. padding: .5ex .25ex;
  1251. border: 1px solid #444;
  1252. -webkit-appearance: menulist;
  1253. }
  1254. .instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {
  1255. width: 9ex;
  1256. padding: .5ex .5ex .4ex;
  1257. border: 1px solid #666;
  1258. }
  1259. .instant-youtube-container .instant-youtube-options [data-action="buttons"] {
  1260. margin-top: 1em;
  1261. }
  1262. .instant-youtube-container .instant-youtube-options button {
  1263. margin: 0 1ex 0 0;
  1264. padding: .5ex 2ex;
  1265. border: 2px solid gray;
  1266. font-weight: bold;
  1267. }
  1268. .instant-youtube-container .instant-youtube-options button:hover {
  1269. border-color: white;
  1270. }
  1271. .instant-youtube-container .instant-youtube-options > [disabled] {
  1272. opacity: 0.25;
  1273. }
  1274. .instant-youtube-container .instant-youtube-storyboard {
  1275. height: 33%;
  1276. max-height: 90px;
  1277. display: block;
  1278. position: absolute;
  1279. left: 0;
  1280. right: 0;
  1281. bottom: 0;
  1282. overflow: visible;
  1283. overflow-x: visible;
  1284. overflow-y: visible;
  1285. }
  1286. .instant-youtube-container .instant-youtube-storyboard:hover {
  1287. background-color: rgba(0,0,0,0.3);
  1288. }
  1289. .instant-youtube-container .instant-youtube-storyboard[disabled] {
  1290. display:none;
  1291. }
  1292. .instant-youtube-container .instant-youtube-storyboard div {
  1293. display: block;
  1294. position: absolute;
  1295. bottom: 0px;
  1296. pointer-events: none;
  1297. border: 3px solid #888;
  1298. box-shadow: 2px 2px 10px black;
  1299. transition: opacity .25s ease;
  1300. background-color: transparent;
  1301. background-origin: content-box;
  1302. opacity: 0;
  1303. }
  1304. .instant-youtube-container .instant-youtube-storyboard:hover div {
  1305. opacity: 1;
  1306. }
  1307. .instant-youtube-container [pin] {
  1308. display: none;
  1309. position: absolute;
  1310. width: 0;
  1311. height: 0;
  1312. margin: 0;
  1313. padding: 0;
  1314. opacity: 1;
  1315. top: auto; bottom: auto; left: auto; right: auto;
  1316. border-style: solid;
  1317. z-index: 100;
  1318. }
  1319. .instant-youtube-container[playing]:hover [pin] {
  1320. display: block;
  1321. }
  1322. .instant-youtube-container[playing] [pin]:hover {
  1323. cursor: alias;
  1324. }
  1325. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  1326. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  1327. .instant-youtube-container [pin=top-left] {
  1328. top: 0; left: 0;
  1329. border-width: 10px 10px 0 0;
  1330. border-color: red transparent transparent transparent;
  1331. }
  1332. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  1333. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  1334. .instant-youtube-container [pin=top-right] {
  1335. top: 0; right: 0;
  1336. border-width: 0 10px 10px 0;
  1337. border-color: transparent red transparent transparent;
  1338. }
  1339. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  1340. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  1341. .instant-youtube-container [pin=bottom-right] {
  1342. bottom: 0; right: 0;
  1343. border-width: 0 0 10px 10px;
  1344. border-color: transparent transparent red transparent;
  1345. }
  1346. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  1347. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  1348. .instant-youtube-container [pin=bottom-left] {
  1349. bottom: 0; left: 0;
  1350. border-width: 10px 0 0 10px;
  1351. border-color: transparent transparent transparent red;
  1352. }
  1353. */}).replace(/\$tl:'(.+?)'/g, function(m, m1) { return _(m1) })
  1354. );
  1355. }