YouTube Video Resize Fix

This Userscript can fix the video sizing issue. Please use it with other Userstyles / Userscripts.

Nainstalovat skript?
Skript doporučený autorem

Mohlo by se vám také líbit YouTube Live Borderless.

Nainstalovat jako uživatelský styl
  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2022 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name YouTube Video Resize Fix
  28. // @name:ja YouTube Video Resize Fix
  29. // @name:zh-TW YouTube Video Resize Fix
  30. // @name:zh-CN YouTube Video Resize Fix
  31. // @version 0.4.10
  32. // @description This Userscript can fix the video sizing issue. Please use it with other Userstyles / Userscripts.
  33. // @description:ja この Userscript は、動画のサイズ変更の問題を修正できます。 他のユーザースタイル・ユーザースクリプトと合わせてご利用ください。
  34. // @description:zh-TW 此 Userscript 可以解決影片大小變形問題。 請將它與其他Userstyles / Userscripts一起使用。
  35. // @description:zh-CN 此 Userscript 可以解决视频大小变形问题。请将它与其他Userstyles / Userscripts一起使用。
  36. // @namespace http://tampermonkey.net/
  37. // @author CY Fung
  38. // @license MIT License
  39. // @supportURL https://github.com/cyfung1031/userscript-supports
  40. // @run-at document-start
  41. // @match https://www.youtube.com/*
  42. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-video-resize-fix.png?v1
  43. // @grant none
  44. // @unwrap
  45. // @allFrames true
  46. // @inject-into page
  47. // ==/UserScript==
  48.  
  49. /* jshint esversion:8 */
  50.  
  51. ((__CONTEXT01__) => {
  52. 'use strict';
  53.  
  54.  
  55. const win = this instanceof Window ? this : window;
  56.  
  57. // Create a unique key for the script and check if it is already running
  58. const hkey_script = 'ahceihvpbosz';
  59. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  60. win[hkey_script] = true;
  61.  
  62. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  63. const indr = o => insp(o).$ || o.$ || 0;
  64.  
  65. /** @type {globalThis.PromiseConstructor} */
  66. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  67. const cleanContext = async (win) => {
  68. const waitFn = requestAnimationFrame; // shall have been binded to window
  69. try {
  70. let mx = 16; // MAX TRIAL
  71. const frameId = 'vanillajs-iframe-v1'
  72. let frame = document.getElementById(frameId);
  73. let removeIframeFn = null;
  74. if (!frame) {
  75. frame = document.createElement('iframe');
  76. frame.id = frameId;
  77. const blobURL = typeof webkitCancelAnimationFrame === 'function' && typeof kagi === 'undefined' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  78. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  79. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  80. n.appendChild(frame);
  81. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  82. const root = document.documentElement;
  83. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  84. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  85.  
  86. removeIframeFn = (setTimeout) => {
  87. const removeIframeOnDocumentReady = (e) => {
  88. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  89. e = n;
  90. n = win = removeIframeFn = 0;
  91. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  92. }
  93. if (!setTimeout || document.readyState !== 'loading') {
  94. removeIframeOnDocumentReady();
  95. } else {
  96. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  97. }
  98. }
  99. }
  100. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  101. const fc = frame.contentWindow;
  102. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  103. try {
  104. const { requestAnimationFrame, setTimeout, clearTimeout } = fc;
  105. const res = { requestAnimationFrame, setTimeout, clearTimeout };
  106. for (let k in res) res[k] = res[k].bind(win); // necessary
  107. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  108. return res;
  109. } catch (e) {
  110. if (removeIframeFn) removeIframeFn();
  111. return null;
  112. }
  113. } catch (e) {
  114. console.warn(e);
  115. return null;
  116. }
  117. };
  118. const isWatchPageURL = (url) => {
  119. url = url || location;
  120. return location.pathname === '/watch' || location.pathname.startsWith('/live/')
  121. };
  122.  
  123. cleanContext(win).then(__CONTEXT02__ => {
  124. if (!__CONTEXT02__) return null;
  125.  
  126. const { ResizeObserver } = __CONTEXT01__;
  127. const { requestAnimationFrame, setTimeout, clearTimeout } = __CONTEXT02__;
  128. const elements = {};
  129. let rid1 = 0;
  130. let rid2 = 0;
  131. /** @type {MutationObserver | null} */
  132. let attrObserver = null;
  133. /** @type {ResizeObserver | null} */
  134. let resizeObserver = null;
  135. let isHTMLAttrApplied = false;
  136. const core = {
  137. begin() {
  138. document.addEventListener('yt-player-updated', core.hanlder, true);
  139. document.addEventListener('ytd-navigate-finish', core.hanlder, true);
  140. },
  141. hanlder: () => {
  142. rid1++;
  143. if (rid1 > 1e9) rid1 = 9;
  144. const tid = rid1;
  145. requestAnimationFrame(() => {
  146. if (tid !== rid1) return;
  147. core.runner();
  148. })
  149. },
  150. async runner() {
  151. if (!location.href.startsWith('https://www.youtube.com/')) return;
  152. if (!isWatchPageURL()) return;
  153.  
  154. elements.ytdFlexy = document.querySelector('ytd-watch-flexy');
  155. elements.video = document.querySelector('ytd-watch-flexy #movie_player video, ytd-watch-flexy #movie_player audio.video-stream.html5-main-video');
  156. if (elements.ytdFlexy && elements.video) { } else return;
  157. elements.moviePlayer = elements.video.closest('#movie_player');
  158. if (!elements.moviePlayer) return;
  159.  
  160. // resize Video
  161. let { ytdFlexy } = elements;
  162. if (!ytdFlexy.ElYTL) {
  163. ytdFlexy.ElYTL = 1;
  164. const ytdFlexyCnt = insp(ytdFlexy);
  165. if (typeof ytdFlexyCnt.calculateNormalPlayerSize_ === 'function') {
  166. ytdFlexyCnt.calculateNormalPlayerSize_ = core.resizeFunc(ytdFlexyCnt.calculateNormalPlayerSize_, 1);
  167. } else {
  168. console.warn('ytdFlexyCnt.calculateNormalPlayerSize_ is not a function.')
  169. }
  170. if (typeof ytdFlexyCnt.calculateCurrentPlayerSize_ === 'function') {
  171. ytdFlexyCnt.calculateCurrentPlayerSize_ = core.resizeFunc(ytdFlexyCnt.calculateCurrentPlayerSize_, 0);
  172. } else {
  173. console.warn('ytdFlexyCnt.calculateCurrentPlayerSize_ is not a function.')
  174. }
  175. }
  176. ytdFlexy = null;
  177.  
  178. // when video is fetched
  179. elements.video.removeEventListener('canplay', core.triggerResizeDelayed, false);
  180. elements.video.addEventListener('canplay', core.triggerResizeDelayed, false);
  181.  
  182. // when video is resized
  183. if (resizeObserver) {
  184. resizeObserver.disconnect();
  185. resizeObserver = null;
  186. }
  187. if (typeof ResizeObserver === 'function') {
  188. resizeObserver = new ResizeObserver(core.triggerResizeDelayed);
  189. resizeObserver.observe(elements.moviePlayer);
  190. }
  191.  
  192. // MutationObserver:[collapsed] @ ytd-live-chat-frame#chat
  193. if (attrObserver) {
  194. attrObserver.takeRecords();
  195. attrObserver.disconnect();
  196. attrObserver = null;
  197. }
  198. let chat = document.querySelector('ytd-watch-flexy ytd-live-chat-frame#chat');
  199. if (chat) {
  200. // resize due to DOM update
  201. attrObserver = new MutationObserver(core.triggerResizeDelayed);
  202. attrObserver.observe(chat, { attributes: true, attributeFilter: ["collapsed"] });
  203. chat = null;
  204. }
  205.  
  206. // resize on idle
  207. Promise.resolve().then(core.triggerResizeDelayed);
  208. },
  209. resizeFunc(originalFunc, kb) {
  210. return function () {
  211. rid2++;
  212. if (!isHTMLAttrApplied) {
  213. isHTMLAttrApplied = true;
  214. Promise.resolve(0).then(() => {
  215. document.documentElement.classList.add('youtube-video-resize-fix');
  216. }).catch(console.warn);
  217. }
  218. if (document.fullscreenElement === null) {
  219.  
  220. // calculateCurrentPlayerSize_ shall be always return NaN to make correct positioning of toolbars
  221. if (!kb) return { width: NaN, height: NaN };
  222.  
  223. let ret = core.calculateSize();
  224. if (ret.height > 0 && ret.width > 0) {
  225. return ret;
  226. }
  227. }
  228. return originalFunc.apply(this, arguments);
  229. }
  230. },
  231. calculateSize_() {
  232. const { moviePlayer, video } = elements;
  233. const rect1 = { width: video.videoWidth, height: video.videoHeight }; // native values independent of css rules
  234. if (rect1.width > 0 && rect1.height > 0) {
  235. const rect2 = moviePlayer.getBoundingClientRect();
  236. const aspectRatio = rect1.width / rect1.height;
  237. let h2 = rect2.width / aspectRatio;
  238. let w2 = rect2.height * aspectRatio;
  239. return { rect2, h2, w2 };
  240. }
  241. return null;
  242. },
  243. calculateSize() {
  244. let rs = core.calculateSize_();
  245. if (!rs) return { width: NaN, height: NaN };
  246. const { rect2, h2, w2 } = rs;
  247. if (h2 > rect2.height) {
  248. return { width: w2, height: rect2.height };
  249. } else {
  250. return { width: rect2.width, height: h2 };
  251. }
  252. },
  253. triggerResizeDelayed: () => {
  254. rid2++;
  255. if (rid2 > 1e9) rid2 = 9;
  256. const tid = rid2;
  257. requestAnimationFrame(() => {
  258. if (tid !== rid2) return;
  259. const { ytdFlexy } = elements;
  260. let r = false;
  261. const ytdFlexyCnt = insp(ytdFlexy);
  262. const windowSize_ = ytdFlexyCnt.windowSize_;
  263. if (windowSize_ && typeof ytdFlexyCnt.onWindowResized_ === 'function') {
  264. try {
  265. ytdFlexyCnt.onWindowResized_(windowSize_);
  266. r = true;
  267. } catch (e) { }
  268. }
  269. if (!r) window.dispatchEvent(new Event('resize'));
  270. })
  271. }
  272. };
  273. core.begin();
  274.  
  275.  
  276.  
  277.  
  278.  
  279.  
  280.  
  281. // YouTube Watch Page Reflect (WPR)
  282.  
  283.  
  284.  
  285. // This script enhances the functionality of YouTube pages by reflecting changes in the page state.
  286.  
  287. (async function youTubeWPR() {
  288.  
  289. let checkPageVisibilityChanged = false;
  290.  
  291. // A WeakSet to keep track of elements being monitored for mutations.
  292. const monitorWeakSet = new WeakSet();
  293.  
  294. /** @type {globalThis.PromiseConstructor} */
  295. const Promise = (async () => { })().constructor;
  296.  
  297. // Function to reflect the current state of the YouTube page.
  298. async function _reflect() {
  299. await Promise.resolve();
  300.  
  301. const youtubeWpr = document.documentElement.getAttribute("youtube-wpr");
  302. let s = '';
  303.  
  304. // Check if the current page is the video watch page.
  305. if (isWatchPageURL()) {
  306. let watch = document.querySelector("ytd-watch-flexy");
  307. let chat = document.querySelector("ytd-live-chat-frame#chat");
  308.  
  309. if (watch) {
  310. // Determine the state of the chat and video player on the watch page and generate a state string.
  311. s += !chat ? 'h0' : (chat.hasAttribute('collapsed') || !document.querySelector('iframe#chatframe')) ? 'h1' : 'h2';
  312. s += watch.hasAttribute('is-two-columns_') ? 's' : 'S';
  313. s += watch.hasAttribute('fullscreen') ? 'F' : 'f';
  314. s += watch.hasAttribute('theater') ? 'T' : 't';
  315. }
  316. }
  317.  
  318. // Update the reflected state if it has changed.
  319. if (s !== youtubeWpr) {
  320. document.documentElement.setAttribute("youtube-wpr", s);
  321. }
  322.  
  323. }
  324.  
  325. // Function to reflect changes in specific attributes of monitored elements.
  326. async function reflect(nodeName, attrNames, forced) {
  327. await Promise.resolve();
  328.  
  329. if (!forced) {
  330. let skip = true;
  331. for (const attrName of attrNames) {
  332. if (nodeName === 'ytd-live-chat-frame') {
  333. if (attrName === 'collapsed') skip = false;
  334. } else if (nodeName === 'ytd-watch-flexy') {
  335. if (attrName === 'is-two-columns_') skip = false;
  336. else if (attrName === 'fullscreen') skip = false;
  337. else if (attrName === 'theater') skip = false;
  338. }
  339. }
  340. if (skip) return;
  341. }
  342.  
  343. // Log the mutated element and its attributes.
  344. // console.log(nodeName, attrNames);
  345.  
  346. // Call _reflect() to update the reflected state.
  347. _reflect();
  348. }
  349.  
  350. // Callback function for the MutationObserver that tracks mutations in monitored elements.
  351. function callback(mutationsList) {
  352. const attrNames = new Set();
  353. let nodeName = null;
  354. for (const mutation of mutationsList) {
  355. if (nodeName === null && mutation.target) nodeName = mutation.target.nodeName.toLowerCase();
  356. attrNames.add(mutation.attributeName);
  357. }
  358. reflect(nodeName, attrNames, false);
  359. }
  360.  
  361. function getParent(element) {
  362. return element.__shady_native_parentNode || element.__shady_parentNode || element.parentNode;
  363. }
  364.  
  365. let lastPageTypeChanged = 0;
  366. function chatContainerMutationHandler() {
  367. if (Date.now() - lastPageTypeChanged < 800) _reflect();
  368. }
  369.  
  370. // Function to start monitoring an element for mutations.
  371. function monitor(element) {
  372. if (!element) return;
  373. if (monitorWeakSet.has(element)) {
  374. return;
  375. }
  376.  
  377. monitorWeakSet.add(element);
  378.  
  379. const observer = new MutationObserver(callback);
  380. observer.observe(element, { attributes: true });
  381.  
  382. if (element.id === 'chat') {
  383. const parentNode = getParent(element);
  384. if (parentNode instanceof Element && parentNode.id === 'chat-container' && !monitorWeakSet.has(parentNode)) {
  385. monitorWeakSet.add(parentNode);
  386. const observer = new MutationObserver(chatContainerMutationHandler);
  387. observer.observe(parentNode, { childList: true, subtree: false });
  388. }
  389. }
  390.  
  391. return 1;
  392. }
  393.  
  394. let timeout = 0;
  395.  
  396. // Function to monitor relevant elements and update the reflected state.
  397. let g = async (forced) => {
  398. await Promise.resolve();
  399. let b = 0;
  400. b = b | monitor(document.querySelector("ytd-watch-flexy"));
  401. b = b | monitor(document.querySelector("ytd-live-chat-frame#chat"));
  402. if (b || forced) {
  403. _reflect();
  404. }
  405. }
  406. // let renderId = 0;
  407. // Event handler function that triggers when the page finishes navigation or page data updates.
  408. let eventHandlerFunc = async (evt) => {
  409. checkPageVisibilityChanged = true;
  410. timeout = Date.now() + 800;
  411. g(1);
  412. if (evt.type === 'yt-navigate-finish') {
  413. // delay required when page type is changed for #chat (home -> watch).
  414. setTimeout(() => {
  415. g(1);
  416. }, 80);
  417. } else if (evt.type === 'yt-page-type-changed') {
  418. lastPageTypeChanged = Date.now();
  419. // setTimeout(() => {
  420. // if (renderId > 1e9) renderId = 9;
  421. // const t = ++renderId;
  422. // requestAnimationFrame(() => {
  423. // if (t !== renderId) return;
  424. // g(1);
  425. // });
  426. // }, 180);
  427. if (typeof requestIdleCallback === 'function') {
  428. requestIdleCallback(() => {
  429. g(1);
  430. });
  431. }
  432. }
  433. }
  434.  
  435. let loadState = 0;
  436.  
  437. // Function to initialize the script and start monitoring the page.
  438. async function actor() {
  439. if (loadState === 0) {
  440. if (!document.documentElement.hasAttribute("youtube-wpr")) {
  441. loadState = 1;
  442. document.documentElement.setAttribute("youtube-wpr", "");
  443. document.addEventListener("yt-navigate-finish", eventHandlerFunc, false);
  444. document.addEventListener("yt-page-data-updated", eventHandlerFunc, false);
  445. document.addEventListener("yt-page-type-changed", eventHandlerFunc, false);
  446. } else {
  447. loadState = -1;
  448. document.removeEventListener("yt-page-data-fetched", actor, false);
  449. return;
  450. }
  451. }
  452. if (loadState === 1) {
  453. timeout = Date.now() + 800;
  454. // Function to continuously monitor elements and update the reflected state.
  455. let pf = () => {
  456. g(0);
  457. if (Date.now() < timeout) requestAnimationFrame(pf);
  458. };
  459. pf();
  460. }
  461. }
  462.  
  463. // Event listener that triggers when page data is fetched.
  464. document.addEventListener("yt-page-data-fetched", actor, false);
  465.  
  466. // Update after visibility changed (looks like there are bugs due to inactive tab)
  467. document.addEventListener('visibilitychange', () => {
  468. if (document.visibilityState !== 'visible') return;
  469. if (checkPageVisibilityChanged) {
  470. checkPageVisibilityChanged = false;
  471. setTimeout(() => {
  472. g(1);
  473. }, 100);
  474. requestAnimationFrame(() => {
  475. g(1);
  476. });
  477. }
  478. }, false);
  479.  
  480.  
  481. })();
  482.  
  483. });
  484.  
  485. })({ ResizeObserver });