YouTube CPU Tamer by AnimationFrame

减少YouTube影片所致的能源消耗

当前为 2023-07-20 提交的版本,查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2021-2023 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 CPU Tamer by AnimationFrame
  28. // @name:ja YouTube CPU Tamer by AnimationFrame
  29. // @name:zh-TW YouTube CPU Tamer by AnimationFrame
  30. // @namespace http://tampermonkey.net/
  31. // @version 2023.07.20.4
  32. // @license MIT License
  33. // @author CY Fung
  34. // @match https://www.youtube.com/*
  35. // @match https://www.youtube.com/embed/*
  36. // @match https://www.youtube-nocookie.com/embed/*
  37. // @match https://www.youtube.com/live_chat*
  38. // @match https://www.youtube.com/live_chat_replay*
  39. // @match https://music.youtube.com/*
  40. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  41. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-cpu-tamper-by-animationframe.webp
  42. // @supportURL https://github.com/cyfung1031/userscript-supports
  43. // @run-at document-start
  44. // @grant none
  45. // @unwrap
  46. // @allFrames true
  47. // @inject-into page
  48.  
  49. // @description Reduce Browser's Energy Impact for playing YouTube Video
  50. // @description:en Reduce Browser's Energy Impact for playing YouTube Video
  51. // @description:ja YouTubeビデオのエネルギーインパクトを減らす
  52. // @description:zh-TW 減少YouTube影片所致的能源消耗
  53. // @description:zh-CN 减少YouTube影片所致的能源消耗
  54.  
  55. // @description:ko YouTube 비디오 재생 시 브라우저의 에너지 영향을 줄입니다.
  56. // @description:ru Снижает энергетическое воздействие браузера при воспроизведении видео на YouTube.
  57. // @description:af Verminder die energie-impak van die blaaier vir YouTube-video speel
  58. // @description:az YouTube videolarını oynamaq üçün Brauzer enerji təsirini azaldır
  59. // @description:id Kurangi Dampak Energi Browser untuk memutar Video YouTube
  60. // @description:ms Kurangkan Impak Tenaga Pelayar untuk memainkan Video YouTube
  61. // @description:bs Smanji energetski uticaj preglednika za reprodukciju YouTube videa
  62. // @description:ca Redueix l'impacte energètic del navegador per reproduir vídeos de YouTube
  63. // @description:cs Snížit energetický dopad prohlížeče při přehrávání videí na YouTube
  64. // @description:da Reducer browserens energipåvirkning for at afspille YouTube-video
  65. // @description:de Reduzieren Sie die Energieauswirkungen des Browsers für die Wiedergabe von YouTube-Videos
  66. // @description:et Vähendage YouTube'i video esitamiseks brauseri energiamõju
  67. // @description:es Reduzca el impacto energético del navegador al reproducir videos de YouTube
  68. // @description:eu Gutxitu nabigatzeko energiaren eragina YouTube bideoak erreproduzitzeko
  69. // @description:fr Réduire l'impact énergétique du navigateur lors de la lecture de vidéos YouTube
  70. // @description:gl Reduzca o impacto enerxético do navegador para reproducir vídeos de YouTube
  71. // @description:hr Smanjite energetski utjecaj preglednika za reprodukciju YouTube videa
  72. // @description:zu Qaqalitsha Umbono We-Energy we-Browser ukuze udlale i-Video ye-YouTube
  73. // @description:is Minkaðu orkuáhrif vafra til að spila YouTube myndband
  74. // @description:it Riduci l'impatto energetico del browser per la riproduzione di video di YouTube
  75. // @description:sw Punguza Athari ya Nishati ya Kivinjari kwa kucheza Video za YouTube
  76. // @description:lv Samaziniet pārlūkprogrammas enerģijas ietekmi YouTube video atskaņošanai
  77. // @description:lt Sumažinkite naršyklės energijos poveikį žaidžiant „YouTube“ vaizdo įrašus
  78. // @description:hu Csökkentse a böngésző energiaterhelését a YouTube videó lejátszásához
  79. // @description:nl Verminder de energie-impact van de browser bij het afspelen van YouTube-video's
  80. // @description:uz YouTube videoni tinglash uchun brauzer energiyasi ta'sirini kamaytirish
  81. // @description:pl Zmniejsz zużycie energii przeglądarki podczas odtwarzania filmów na YouTube
  82. // @description:pt Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  83. // @description:pt-BR Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  84. // @description:ro Reduceți impactul energetic al browser-ului pentru redarea videoclipurilor YouTube
  85. // @description:sq Zvogëlo ndikimin e energjisë të shfletuesit për luajtjen e video YouTube
  86. // @description:sk Znížte energetický dopad prehliadača pri prehrávaní videí na YouTube
  87. // @description:sl Zmanjšajte energijski vpliv brskalnika pri predvajanju videoposnetkov YouTube
  88. // @description:sr Smanjite energetski uticaj pregledača za reprodukciju YouTube videa
  89. // @description:fi Vähennä selaimen energiankulutusta YouTube-videoiden toistossa
  90. // @description:sv Minska webbläsarens energipåverkan för att spela YouTube-video
  91. // @description:vi Giảm tác động năng lượng của trình duyệt khi phát Video YouTube
  92. // @description:tr YouTube Videolarını Oynatırken Tarayıcının Enerji Etkisini Azaltın
  93. // @description:be Змяншыце энергетычны ўплыў браўзара на прайграванне YouTube-відэа
  94. // @description:bg Намалете енергийния влияние на браузъра при възпроизвеждане на видео в YouTube
  95. // @description:ky YouTube видеонун ойнотуусунан башкаруу үчүн браузердеги энергиялык турмуштарды көмүштөштүрүү
  96. // @description:kk YouTube-дың браузерде көрсету мүмкіндігін көмеге қысқартыңыз
  97. // @description:mk Намалете ја енергетската присутност на пребарувачот за репродукција на YouTube видео
  98. // @description:mn YouTube видеогийг тоглуулж буй хөтөчийн энерги хүчинг буурах
  99. // @description:uk Зменште енергетичний вплив браузера на відтворення відео на YouTube
  100. // @description:el Μειώστε την ενεργειακή επίδραση του προγράμματος περιήγησης για την αναπαραγωγή βίντεο στο YouTube
  101. // @description:hy Փոքրանալիքայինը դանդարեցրեք բրաուզերի էներգիայի ազդեցությունը YouTube վիդեոների ներածման դեպքում
  102. // @description:ur یوٹیوب ویڈیو کھیلنے کے لئے براؤزر کی توانائی پر اثر کم کریں
  103. // @description:ar تقليل تأثير استهلاك الطاقة لمتصفح تشغيل مقاطع فيديو يوتيوب
  104. // @description:fa کاهش تأثیر انرژی مرورگر برای پخش ویدئوی یوتیوب
  105. // @description:ne युट्युब भिडियो खेल्नका लागि ब्राउजरको ऊर्जा प्रभाव कम गर्नुहोस्
  106. // @description:mr YouTube व्हिडिओ चालवण्यासाठी ब्राउझरचे ऊर्जाचे प्रभाव कमी करा
  107. // @description:hi यूट्यूब वीडियो चलाने के लिए ब्राउज़र की ऊर्जा प्रभाव को कम करें
  108. // @description:as YouTube ভিডিঅ' প্ৰশ্ন কৰা ব্ৰাউজাৰৰ শক্তিৰ প্ৰভাৱ কমিয়া দিব
  109. // @description:bn YouTube ভিডিও চালাতে ব্রাউজারের শক্তি প্রভাব কমান
  110. // @description:pa YouTube ਵਿਡੀਓ ਚਲਾਉਣ ਲਈ ਬਰਾਉਜ਼ਰ ਦੀ ਊਰਜਾ ਪ੍ਰਭਾਵ ਘਟਾਓ
  111. // @description:gu YouTube વિડિઓ ચલાવવા માટે બ્રાઉઝરનું ઊર્જા પ્રભાવ ઘટાડો
  112. // @description:or YouTube ଭିଡିଓ ଚାଲାନ୍ତୁ ପାଇଁ ବ୍ରାଉଜରର ଶକ୍ତି ପ୍ରଭାବ କମାନ୍ତୁ
  113. // @description:ta யூடியூப் வீடியோவை இயக்குவதற்கான உலாவியின் மிக்க விளைவுகளை குறைக்கவும்
  114. // @description:te YouTube వీడియోను ప్రసారం చేయడానికి బ్రౌజర్ యొక్క శక్తి ప్రభావాన్ని తగ్గించుకోండి
  115. // @description:kn YouTube ವೀಡಿಯೊಗಳನ್ನು ಪ್ರದರ್ಶಿಸಲು ಬ್ರೌಸರ್ ಯನ್ನು ಉಪಯೋಗಿಸುವಾಗ ಶಕ್ತಿ ಪ್ರಭಾವವನ್ನು ಕಡಿಮೆಗೊಳಿಸಿ
  116. // @description:ml YouTube വീഡിയോ പ്രവർത്തിപ്പിക്കുവാൻ ബ്രൗസർയുടെ പ്രഭാവം കുറയ്ക്കുക
  117. // @description:si YouTube වීඩියෝ චාරිකා කිරීම සඳහා බ්‍රවුසරයේ ඊම්ජි බලන්න
  118. // @description:th ลดผลกระทบทางพลังงานของเบราว์เซอร์ในการเล่นวิดีโอ YouTube
  119. // @description:lo ບຣາຣິໂຄດລາວເອີ້ນໃນການເພີ່ມເວັບວຽກຂອງ YouTube ສຳ ລັບການຂະໜາດໃນການເພີ່ມເວັບວຽກ
  120. // @description:my YouTube ဗီဒီယိုများကို ဖွင့်ရန် Browser အတွက် Energy Impact ကိုအနိုင်ရန်
  121. // @description:ka YouTube ვიდეოების დაკვრებისას ბრაუზერის ენერგიის შეცვლა
  122. // @description:am YouTube ቪዲዮዎችን ለመቀነስ የባህሪውን አርእስት ግንኙነት ማድረግ
  123. // @description:km បង្កើតការធ្វើបរិមាណលំអិតរបស់ការកំណត់ការដាក់នៅលើសម្ពាធរបស់ប្រព័ន្ធបញ្ចូលបន្ទាត់ YouTube
  124. // ==/UserScript==
  125.  
  126. /* jshint esversion:8 */
  127.  
  128. /**
  129. *
  130. * This script does not support the following syntax intentionally.
  131. *
  132. * - string parameter as TimerHandler
  133. * e.g. setTimeout("console.log('300ms')", 300)
  134. * - no delay for `setInterval`
  135. * e.g. setInterval(f)
  136. *
  137. */
  138.  
  139. /**
  140. @typedef TimerObject
  141. @type {Object}
  142. @property {Function} handler
  143. @property {number?} timeout
  144. @property {number?} interval
  145. @property {number} nextAt
  146.  
  147. */
  148.  
  149. (function (__CONTEXT__) {
  150. 'use strict';
  151.  
  152. const UNDERCLOCK = +localStorage.cpuTamerUnderclock || 10; // default 10ms; increase to make the timer less responsive.
  153.  
  154. // "UNDERCLOCK" is set at 10ms by default. You can increase it to avoid unnecessary timer callbacks.
  155. // Suggested values: 10ms, 16ms, 24ms, 32ms, 48ms, 64ms.
  156. // Note: The script is not designed to operate with values higher 200ms. Please be careful of changing UNDERCLOCK value.
  157.  
  158. const win = this || window;
  159.  
  160. // Create a unique key for the script and check if it is already running
  161. const hkey_script = 'nzsxclvflluv';
  162. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  163. win[hkey_script] = true;
  164.  
  165. /** @type {globalThis.PromiseConstructor} */
  166. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  167. const cleanContext = async (win) => {
  168. const waitFn = requestAnimationFrame; // shall have been binded to window
  169. try {
  170. const mx = 16; // MAX TRIAL
  171. const frame = document.createElement('iframe');
  172. frame.sandbox = 'allow-same-origin';
  173. const n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  174. n.appendChild(frame);
  175. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  176. const root = document.documentElement;
  177. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  178. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  179. const fc = frame.contentWindow;
  180. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  181. const { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout } = fc;
  182. const res = { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout };
  183. for (let k in res) res[k] = res[k].bind(win); // necessary
  184. n.remove();
  185. return res;
  186. } catch (e) {
  187. console.warn(e);
  188. return null;
  189. }
  190. };
  191.  
  192. let videoIsPaused = 0; // for video is fetching data
  193. let isAllMediaPaused = false; // only when there is any video is fetching data
  194.  
  195. cleanContext(win).then(__CONTEXT__ => {
  196. if (!__CONTEXT__) return null;
  197.  
  198.  
  199. // Create a symbol to represent the busy state of a handler function
  200. const $busy = Symbol('$busy');
  201.  
  202. // Define some constants for the initial value and the safe limits of the timer ID
  203. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  204. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  205. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  206. // Note: Number.MAX_SAFE_INTEGER = 9007199254740991
  207.  
  208. // Define a flag to indicate whether the function handlers need to be reset
  209. let toResetFuncHandlers = false;
  210.  
  211. // Assign the Promise constructor to a local variable
  212. const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = __CONTEXT__;
  213.  
  214. const onPromiseErrorFn = (e) => { Promise.resolve(e).then(e => console.error(e)); }; // Promise will be resolved for Promise.all
  215.  
  216. const pq = new Map();
  217. const [sb, rm] = (() => {
  218.  
  219. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  220.  
  221. /** @type { Map<number, TimerObject> } */
  222. const sb = new Map(); // map of timer objects
  223.  
  224. /**
  225. * Define a helper function to create a timer object with a handler, a delay and a next execution time
  226. * @param {string} prop timeout / interval
  227. * @returns
  228. */
  229. const sFunc = (prop) => {
  230. /**
  231. * @param {Function} func TimerHandler
  232. * @param {number?} ms TimerHandler
  233. * @param {any[]} args
  234. */
  235. return (func, ms, ...args) => {
  236. mi++; // start at {INT_INITIAL_VALUE + 1}
  237. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  238. if (ms > SAFE_INT_LIMIT) return mi;
  239. if (typeof func === 'function') { // ignore all non-function parameter (e.g. string)
  240.  
  241. const hasArgs = args.length > 0;
  242. if (videoIsPaused > 0 && !hasArgs && prop === 'timeout') { // no exceptional case for hasArgs can be found
  243.  
  244. // 0, 10
  245. // 20 (rare)
  246. // 100
  247. // 250, 1000, 10000, 20000
  248. if (ms < 16 && !isAllMediaPaused) {
  249. // typical example for ms: 0, 10 [no undefined was found]
  250.  
  251. const jd = mi;
  252. const cid = setTimeout(() => {
  253. func();
  254. Promise.resolve().then(() => pq.delete(jd));
  255. }, ms);
  256. pq.set(mi, cid);
  257. return mi;
  258.  
  259. } else if (ms < 200) {
  260. // 20ms, TBC
  261. // 100ms
  262. ms = 200;
  263.  
  264. } else if (ms < 800) {
  265. // 250ms
  266. // no modification
  267. // for video resume by user
  268. } else {
  269. // 1000ms, 10000ms, 20000ms
  270. if (isAllMediaPaused) {
  271. if (ms < 8000) ms = 32000;
  272. else if (ms < 80000) ms = 320000;
  273. else ms = ms + 380000;
  274. }
  275. }
  276.  
  277. }
  278.  
  279. let handler = hasArgs ? func.bind(null, ...args) : func; // original func if no extra argument
  280. handler[$busy] || (handler[$busy] = 0);
  281. sb.set(mi, {
  282. handler,
  283. [prop]: ms, // timeout / interval; value can be undefined
  284. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  285. });
  286. }
  287. return mi;
  288. };
  289. };
  290.  
  291. /**
  292. * Define a helper function to remove a timer object from the map or call the native method if not found
  293. * @param {number} jd timeoutID / intervalID
  294. * @returns
  295. */
  296. const rm = function (jd) {
  297. if (!jd) return; // native setInterval & setTimeout start from 1
  298. if (typeof jd === 'string') jd = +jd;
  299. const o = sb.get(jd);
  300. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  301. let action = jd <= INT_INITIAL_VALUE;
  302. if (!action) {
  303. const cid = pq.get(jd);
  304. if (cid > 0) {
  305. action = true;
  306. pq.delete(jd);
  307. jd = cid;
  308. }
  309. }
  310. if (action) {
  311. const nativeFn = this.nativeFn; // de::this
  312. nativeFn(jd); // only for clearTimeout & clearInterval
  313. }
  314. } else {
  315. for (const k in o) o[k] = null;
  316. sb.delete(jd);
  317. }
  318. };
  319.  
  320. // Override the window methods for setTimeout and setInterval with custom functions that use the helper function sFunc
  321. win.setTimeout = sFunc('timeout');
  322. win.setInterval = sFunc('interval');
  323.  
  324. // Override the window methods for clearTimeout and clearInterval with custom functions that use the helper function rm
  325. win.clearTimeout = rm.bind({
  326. nativeFn: clearTimeout
  327. });
  328. win.clearInterval = rm.bind({
  329. nativeFn: clearInterval
  330. });
  331.  
  332. // Try to override the toString methods of the window methods with the native ones
  333. try {
  334. win.setTimeout.toString = setTimeout.toString.bind(setTimeout)
  335. win.setInterval.toString = setInterval.toString.bind(setInterval)
  336. win.clearTimeout.toString = clearTimeout.toString.bind(clearTimeout)
  337. win.clearInterval.toString = clearInterval.toString.bind(clearInterval)
  338. } catch (e) { console.warn(e) }
  339.  
  340. // Add an event listener for when YouTube finishes navigating to a new page and set the flag to reset the function handlers
  341. win.addEventListener("yt-navigate-finish", () => {
  342. videoIsPaused = 0; // reset; no weaker tamer after navigation until video is paused afterwards.
  343. isAllMediaPaused = false; // reset first
  344. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  345. Promise.resolve().then(executeNow);
  346. }, true); // capturing event - to let it runs before all everything else.
  347.  
  348. return [sb, rm];
  349.  
  350. })();
  351.  
  352. /** @type {Function|null} */
  353. let nonResponsiveResolve = null;
  354. /** @type {(resolve: () => void)} */
  355. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  356.  
  357. /** @param {Function} handler */
  358. const pfMicroFn = (handler) => {
  359. // For function handler with high energy impact, discard 1st, 2nd, ... (n-1)th calling: (a,b,c,a,b,d,e,f) => (c,a,b,d,e,f)
  360. // For function handler with low energy impact, discard or not discard depends on system performance
  361. if (handler[$busy] === 1) handler();
  362. // error in handler would stop the following code execution and jump out to the Promise.all considered as "resolved" due to ignorePromiseErrorFn
  363. handler[$busy]--;
  364. };
  365.  
  366. /**
  367. *
  368. * @param {Function} handler
  369. */
  370. const pf = (
  371. handler => Promise.resolve(handler).then(pfMicroFn).catch(onPromiseErrorFn) // catch here to avoid no resolve to the race promise & avoid immediate end of the promise.all
  372. );
  373.  
  374. // Define a variable to store the next background execution time
  375. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  376.  
  377. // Define a variable to store the active page state
  378. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  379.  
  380. /** @type {Function|null} */
  381. let afInterupter = null;
  382.  
  383. /** @type {(resolve: () => void)} */
  384. const infiniteLooper = (resolve) => requestAnimationFrame(afInterupter = resolve); // rAF will not execute if document is hidden
  385. const infiniteLooperForNoPlaying = (resolve) => (afInterupter = resolve); // rAF will not execute if document is hidden
  386.  
  387. /** @type {(aHandlers: Function[])} */
  388. const microTaskExecutionActivePage = (aHandlers) => Promise.all(aHandlers.map(pf));
  389.  
  390. /** @type {(aHandlers: Function[])} */
  391. const microTaskExecutionBackgroundPage = (aHandlers) => {
  392. // error would not affect calling the next tick
  393. aHandlers.forEach(pf); // microTasks
  394. aHandlers.length = 0;
  395. };
  396.  
  397. const nextTickExecutionMT1 = async () => { // microTask #1
  398. const now = Date.now();
  399. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  400. /** @type {Function[]} */
  401. const sHandlers = []; // an array of handlers being executed in this tick
  402. const lsb = sb; // vairable scope < global to local > for better performance
  403. lsb.forEach((sV, sK) => {
  404. const {
  405. handler,
  406. // timeout,
  407. interval,
  408. nextAt
  409. } = sV;
  410. if (now < nextAt) return;
  411. handler[$busy]++;
  412. sHandlers.push(handler);
  413. if (interval > 0) { // prevent undefined, zero, negative values
  414. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  415. if (nextAt + _interval > now) sV.nextAt += _interval;
  416. else if (nextAt + 2 * _interval > now) sV.nextAt += 2 * _interval;
  417. else if (nextAt + 3 * _interval > now) sV.nextAt += 3 * _interval;
  418. else if (nextAt + 4 * _interval > now) sV.nextAt += 4 * _interval;
  419. else if (nextAt + 5 * _interval > now) sV.nextAt += 5 * _interval;
  420. else sV.nextAt = now + _interval;
  421. } else {
  422. // sK in sb must > INT_INITIAL_VALUE
  423. rm(sK); // remove timeout
  424. }
  425. });
  426. await Promise.resolve();
  427. return sHandlers;
  428. }
  429.  
  430. /**
  431. *
  432. * @param {Function[]} sHandlers
  433. */
  434. const nextTickExecutionMT2 = async (sHandlers) => { // microTask #2
  435. if (sHandlers.length === 0) { // no handler functions
  436. // requestAnimationFrame when the page is active
  437. // execution interval is no less than AnimationFrame
  438. } else if (dexActivePage) {
  439.  
  440. // retFP: looping for all functions. First error leads resolve non-reachable;
  441. // the particular [$busy] will not reset to 0 normally
  442. const retFP = Promise.resolve(sHandlers).then(microTaskExecutionActivePage);
  443. // inside Promise (async function), error would not affect calling the next tick
  444.  
  445. const retNR = new Promise(delayNonResponsive);
  446. // for every 125ms, retNR probably resolve eariler than retFP
  447. // however it still be controlled by rAF (or 250ms) in the next looping
  448.  
  449. await Promise.race([retFP, retNR]); // continue either 125ms time limit reached or all working functions have been done
  450. sHandlers.length = 0;
  451. nonResponsiveResolve = null;
  452. } else {
  453. Promise.resolve(sHandlers).then(microTaskExecutionBackgroundPage);
  454. }
  455. };
  456.  
  457. let intervalTimerResolve = null;
  458. setInterval(() => {
  459. if (intervalTimerResolve !== null) {
  460. intervalTimerResolve();
  461. intervalTimerResolve = null;
  462. }
  463. }, UNDERCLOCK);
  464. const pTimerFn = resolve => { intervalTimerResolve = resolve };
  465.  
  466. (async () => {
  467. while (true) {
  468. bgExecutionAt = Date.now() + 160;
  469. if (isAllMediaPaused) {
  470. await new Promise(infiniteLooperForNoPlaying);
  471. afInterupter = null;
  472. toResetFuncHandlers = false;
  473. dexActivePage = false;
  474. } else {
  475. const pTimer = new Promise(pTimerFn);
  476. await new Promise(infiniteLooper); // resolve by rAF or timer@250ms
  477. await pTimer; // resolve by timer@10ms
  478. if (afInterupter === null) {
  479. // triggered by setInterval
  480. dexActivePage = false;
  481. } else {
  482. // triggered by rAF
  483. afInterupter = null;
  484. if (dexActivePage === false) toResetFuncHandlers = true;
  485. dexActivePage = true;
  486. }
  487. if (toResetFuncHandlers) {
  488. // true if page change from hidden to visible OR yt-finish
  489. toResetFuncHandlers = false;
  490. for (const eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  491. }
  492. }
  493. const sHandlers = await nextTickExecutionMT1();
  494. await nextTickExecutionMT2(sHandlers);
  495. }
  496. })();
  497.  
  498. setInterval(() => {
  499. if (videoIsPaused > 0) {
  500. // videoIsPaused = 2 => 125ms
  501. // videoIsPaused = 3 => 250ms ...
  502. if (videoIsPaused < 16) {
  503. videoIsPaused++;
  504. if (videoIsPaused === 8) { // 875ms
  505. Promise.resolve().then(() => {
  506. if (videoIsPaused > 0) {
  507. /** @type {NodeListOf<HTMLMediaElement | HTMLVideoElement >} */
  508. let medias = document.querySelectorAll('video[src], audio[src]');
  509. let mp = true;
  510. for (const media of medias) {
  511. if (media.paused !== true) {
  512. mp = false;
  513. break;
  514. }
  515. }
  516. if (mp) {
  517. // check spinner as well
  518. for (const spinner of document.querySelectorAll('.ytp-spinner')) {
  519. const rect = spinner.getBoundingClientRect();
  520. if (rect.width * rect.height > 4) {
  521. mp = false;
  522. break;
  523. }
  524. }
  525. }
  526. if (!mp) {
  527. videoIsPaused = false;
  528. isAllMediaPaused = false;
  529. Promise.resolve().then(executeNow);
  530. } else {
  531. isAllMediaPaused = true;
  532. }
  533. }
  534. })
  535. }
  536. }
  537. }
  538. if (nonResponsiveResolve !== null) {
  539. nonResponsiveResolve();
  540. return;
  541. }
  542. // no response of requestAnimationFrame; e.g. running in background
  543. const dInterupter = afInterupter;
  544. let now;
  545. if (dInterupter !== null && (now = Date.now()) > bgExecutionAt) {
  546. // interupter not triggered by rAF
  547. afInterupter = null;
  548. bgExecutionAt = now + 230;
  549. dInterupter();
  550. }
  551. }, 125);
  552. // --- 2022.12.14 ---
  553. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  554. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  555. // ---------------------
  556. // 4 times per second for background execution - to keep YouTube application functional
  557. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  558.  
  559.  
  560. const passiveCapture = typeof IntersectionObserver === 'function' ? { capture: true, passive: true } : true;
  561.  
  562.  
  563. function executeNow() {
  564. // in order to immediate fire setTimeout(..., 0) when livestream is paused (laggy)
  565.  
  566. if (nonResponsiveResolve !== null) {
  567. nonResponsiveResolve();
  568. }
  569.  
  570. if (intervalTimerResolve !== null) {
  571. intervalTimerResolve();
  572. intervalTimerResolve = null;
  573. }
  574.  
  575. const dInterupter = afInterupter;
  576. if (dInterupter !== null) {
  577. afInterupter = null;
  578. bgExecutionAt = Date.now() + 230;
  579. dInterupter();
  580. }
  581.  
  582. }
  583.  
  584. document.addEventListener('pause', function (evt) {
  585.  
  586. const target = (evt || 0).target;
  587. if (target instanceof HTMLVideoElement && target.networkState === 2) {
  588. // the video paused might not be the main video; i.e. weaker tamer will apply to non-watch page (like home page)
  589. // networkState will be useful to filter out no source or fully loaded video
  590. // weaker tamer focuses on the video is loading (fetching from the server)
  591. // execute whatever videoIsPaused is.
  592. videoIsPaused = 1;
  593. Promise.resolve().then(executeNow);
  594. }
  595.  
  596. }, passiveCapture);
  597.  
  598.  
  599. document.addEventListener('play', function (evt) {
  600.  
  601. const target = (evt || 0).target;
  602. if (target instanceof HTMLVideoElement && ((target.networkState % 3) >= 1)) {
  603. // reset even it is ads or hover element
  604. // execute whatever videoIsPaused is.
  605. videoIsPaused = 0;
  606. isAllMediaPaused = false;
  607. Promise.resolve().then(executeNow);
  608. }
  609.  
  610. }, passiveCapture);
  611.  
  612. })
  613.  
  614.  
  615. })(null);