YouTube CPU Tamer by AnimationFrame

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

目前为 2023-07-27 提交的版本,查看 最新版本

  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.23.0
  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. ((__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 instanceof Window ? 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. let mx = 16; // MAX TRIAL
  171. const frameId = 'vanillajs-iframe-v1'
  172. let frame = document.getElementById(frameId);
  173. let removeIframeFn = null;
  174. if (!frame) {
  175. frame = document.createElement('iframe');
  176. frame.id = 'vanillajs-iframe-v1';
  177. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  178. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  179. n.appendChild(frame);
  180. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  181. const root = document.documentElement;
  182. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  183. removeIframeFn = (setTimeout) => {
  184. const removeIframeOnDocumentReady = (e) => {
  185. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  186. win = null;
  187. setTimeout(() => {
  188. n.remove();
  189. n = null;
  190. }, 200);
  191. }
  192. if (document.readyState !== 'loading') {
  193. removeIframeOnDocumentReady();
  194. } else {
  195. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  196. }
  197. }
  198. }
  199. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  200. const fc = frame.contentWindow;
  201. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  202. const { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout } = fc;
  203. const res = { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout };
  204. for (let k in res) res[k] = res[k].bind(win); // necessary
  205. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  206. return res;
  207. } catch (e) {
  208. console.warn(e);
  209. return null;
  210. }
  211. };
  212.  
  213. cleanContext(win).then(__CONTEXT__ => {
  214. if (!__CONTEXT__) return null;
  215.  
  216. // Create a symbol to represent the busy state of a handler function
  217. const $busy = Symbol('$busy');
  218.  
  219. // Define some constants for the initial value and the safe limits of the timer ID
  220. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  221. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  222. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  223. // Note: Number.MAX_SAFE_INTEGER = 9007199254740991
  224.  
  225. // Assign the Promise constructor to a local variable
  226. const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = __CONTEXT__;
  227.  
  228. const onPromiseErrorFn = (e) => { Promise.resolve(e).then(e => console.error(e)); }; // Promise will be resolved for Promise.all
  229.  
  230. let isAnyVideoJustStartedWaiting = 0;
  231. let countAnyVideoJustPaused = 0; // for video is fetching data
  232. let noActiveMediaForAWhile = false; // only when there is any video is fetching data
  233.  
  234. // Define a flag to indicate whether the function handlers need to be reset
  235. let toResetFuncHandlers = false;
  236. let intervalTimerResolve = null;
  237.  
  238. const pq = new Map();
  239. const [sb, rm] = (() => {
  240.  
  241. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  242.  
  243. /** @type { Map<number, TimerObject> } */
  244. const sb = new Map(); // map of timer objects
  245.  
  246. /**
  247. * Define a helper function to create a timer object with a handler, a delay and a next execution time
  248. * @param {string} prop timeout / interval
  249. * @returns
  250. */
  251. const sFunc = (prop) => {
  252. /**
  253. * @param {Function} func TimerHandler
  254. * @param {number?} ms TimerHandler
  255. * @param {any[]} args
  256. */
  257. return (func, ms, ...args) => {
  258. mi++; // start at {INT_INITIAL_VALUE + 1}
  259. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  260. if (ms > SAFE_INT_LIMIT) return mi;
  261. if (typeof func === 'function') { // ignore all non-function parameter (e.g. string)
  262.  
  263. const hasArgs = args.length > 0;
  264. let doNativeFn = false;
  265. if (isAnyVideoJustStartedWaiting > 0 && !hasArgs && prop === 'timeout') {
  266. if (ms < 16) {
  267. doNativeFn = true;
  268. }
  269. } else if (countAnyVideoJustPaused > 0 && !hasArgs && prop === 'timeout') { // no exceptional case for hasArgs can be found
  270.  
  271. // 0, 10
  272. // 20 (rare)
  273. // 100
  274. // 250, 1000, 10000, 20000
  275. if (ms <= 16 && !noActiveMediaForAWhile) {
  276. // typical example for ms: 0, 10 [no undefined was found]
  277. doNativeFn = true;
  278.  
  279. } else if (ms <= 20) {
  280. // 20ms, TBC
  281. ms = 20;
  282.  
  283. } else if (ms <= 40) {
  284. // TBC
  285. ms = 40;
  286.  
  287. } else if (ms <= 80) {
  288. // TBC
  289. ms = 80;
  290.  
  291. } else if (ms <= 200) {
  292. // 100ms
  293. ms = 200;
  294.  
  295. } else if (ms < 800) {
  296. // 250ms
  297. // no modification
  298. // for video resume by user
  299. } else {
  300. // 1000ms, 10000ms, 20000ms
  301. if (noActiveMediaForAWhile) {
  302. if (ms < 8000) ms = 32000;
  303. else if (ms < 80000) ms = 320000;
  304. else ms = ms + 380000;
  305. }
  306. }
  307.  
  308. }
  309. if (doNativeFn) {
  310. const jd = mi;
  311. const cid = setTimeout(() => {
  312. func();
  313. Promise.resolve().then(() => pq.delete(jd));
  314. }, ms);
  315. pq.set(mi, cid);
  316. return mi;
  317. }
  318.  
  319. let handler = hasArgs ? func.bind(null, ...args) : func; // original func if no extra argument
  320. handler[$busy] || (handler[$busy] = 0);
  321. sb.set(mi, {
  322. handler,
  323. [prop]: ms, // timeout / interval; value can be undefined
  324. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  325. });
  326. }
  327. return mi;
  328. };
  329. };
  330.  
  331. /**
  332. * Define a helper function to remove a timer object from the map or call the native method if not found
  333. * @param {number} jd timeoutID / intervalID
  334. * @returns
  335. */
  336. const rm = function (jd) {
  337. if (!jd) return; // native setInterval & setTimeout start from 1
  338. if (typeof jd === 'string') jd = +jd;
  339. const o = sb.get(jd);
  340. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  341. let action = jd <= INT_INITIAL_VALUE;
  342. if (!action) {
  343. const cid = pq.get(jd);
  344. if (cid > 0) {
  345. action = true;
  346. pq.delete(jd);
  347. jd = cid;
  348. }
  349. }
  350. if (action) {
  351. const nativeFn = this.nativeFn; // de::this
  352. nativeFn(jd); // only for clearTimeout & clearInterval
  353. }
  354. } else {
  355. for (const k in o) o[k] = null;
  356. sb.delete(jd);
  357. }
  358. };
  359.  
  360. // Override the window methods for setTimeout and setInterval with custom functions that use the helper function sFunc
  361. win.setTimeout = sFunc('timeout');
  362. win.setInterval = sFunc('interval');
  363.  
  364. // Override the window methods for clearTimeout and clearInterval with custom functions that use the helper function rm
  365. win.clearTimeout = rm.bind({
  366. nativeFn: clearTimeout
  367. });
  368. win.clearInterval = rm.bind({
  369. nativeFn: clearInterval
  370. });
  371.  
  372. // Try to override the toString methods of the window methods with the native ones
  373. try {
  374. win.setTimeout.toString = setTimeout.toString.bind(setTimeout)
  375. win.setInterval.toString = setInterval.toString.bind(setInterval)
  376. win.clearTimeout.toString = clearTimeout.toString.bind(clearTimeout)
  377. win.clearInterval.toString = clearInterval.toString.bind(clearInterval)
  378. } catch (e) { console.warn(e) }
  379.  
  380. return [sb, rm];
  381.  
  382. })();
  383.  
  384. /** @type {Function|null} */
  385. let nonResponsiveResolve = null;
  386. /** @type {(resolve: () => void)} */
  387. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  388.  
  389. /** @param {Function} handler */
  390. const pfMicroFn = (handler) => {
  391. // 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)
  392. // For function handler with low energy impact, discard or not discard depends on system performance
  393. if (handler[$busy] === 1) handler();
  394. // error in handler would stop the following code execution and jump out to the Promise.all considered as "resolved" due to ignorePromiseErrorFn
  395. handler[$busy]--;
  396. };
  397.  
  398. /**
  399. *
  400. * @param {Function} handler
  401. */
  402. const pf = (
  403. 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
  404. );
  405.  
  406. // Define a variable to store the next background execution time
  407. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  408.  
  409. // Define a variable to store the active page state
  410. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  411.  
  412. /** @type {Function|null} */
  413. let afInterupter = null;
  414.  
  415. function executeNow() {
  416. // in order to immediate fire setTimeout(..., 0) when livestream is paused (laggy)
  417.  
  418. if (nonResponsiveResolve !== null) {
  419. nonResponsiveResolve();
  420. }
  421.  
  422. if (intervalTimerResolve !== null) {
  423. intervalTimerResolve();
  424. intervalTimerResolve = null;
  425. }
  426.  
  427. const dInterupter = afInterupter;
  428. if (dInterupter !== null) {
  429. afInterupter = null;
  430. bgExecutionAt = Date.now() + 230;
  431. dInterupter();
  432. }
  433.  
  434. }
  435.  
  436. /** @type {(resolve: () => void)} */
  437. const infiniteLooper = (resolve) => requestAnimationFrame(afInterupter = resolve); // rAF will not execute if document is hidden
  438.  
  439. /** @type {(aHandlers: Function[])} */
  440. const microTaskExecutionActivePage = (aHandlers) => Promise.all(aHandlers.map(pf));
  441.  
  442. /** @type {(aHandlers: Function[])} */
  443. const microTaskExecutionBackgroundPage = (aHandlers) => {
  444. // error would not affect calling the next tick
  445. aHandlers.forEach(pf); // microTasks
  446. aHandlers.length = 0;
  447. };
  448.  
  449. const nextTickExecutionMT1 = async () => { // microTask #1
  450. const now = Date.now();
  451. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  452. /** @type {Function[]} */
  453. const sHandlers = []; // an array of handlers being executed in this tick
  454. const lsb = sb; // vairable scope < global to local > for better performance
  455. lsb.forEach((sV, sK) => {
  456. const {
  457. handler,
  458. // timeout,
  459. interval,
  460. nextAt
  461. } = sV;
  462. if (now < nextAt) return;
  463. handler[$busy]++;
  464. sHandlers.push(handler);
  465. if (interval > 0) { // prevent undefined, zero, negative values
  466. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  467. if (nextAt + _interval > now) sV.nextAt += _interval;
  468. else if (nextAt + 2 * _interval > now) sV.nextAt += 2 * _interval;
  469. else if (nextAt + 3 * _interval > now) sV.nextAt += 3 * _interval;
  470. else if (nextAt + 4 * _interval > now) sV.nextAt += 4 * _interval;
  471. else if (nextAt + 5 * _interval > now) sV.nextAt += 5 * _interval;
  472. else sV.nextAt = now + _interval;
  473. } else {
  474. // sK in sb must > INT_INITIAL_VALUE
  475. rm(sK); // remove timeout
  476. }
  477. });
  478. await Promise.resolve();
  479. return sHandlers;
  480. }
  481.  
  482. /**
  483. *
  484. * @param {Function[]} sHandlers
  485. */
  486. const nextTickExecutionMT2 = async (sHandlers) => { // microTask #2
  487. if (sHandlers.length === 0) { // no handler functions
  488. // requestAnimationFrame when the page is active
  489. // execution interval is no less than AnimationFrame
  490. } else if (dexActivePage) {
  491.  
  492. // retFP: looping for all functions. First error leads resolve non-reachable;
  493. // the particular [$busy] will not reset to 0 normally
  494. const retFP = Promise.resolve(sHandlers).then(microTaskExecutionActivePage);
  495. // inside Promise (async function), error would not affect calling the next tick
  496.  
  497. const retNR = new Promise(delayNonResponsive);
  498. // for every 125ms, retNR probably resolve eariler than retFP
  499. // however it still be controlled by rAF (or 250ms) in the next looping
  500.  
  501. await Promise.race([retFP, retNR]); // continue either 125ms time limit reached or all working functions have been done
  502. sHandlers.length = 0;
  503. nonResponsiveResolve = null;
  504. } else {
  505. Promise.resolve(sHandlers).then(microTaskExecutionBackgroundPage);
  506. }
  507. };
  508.  
  509. // Add an event listener for when YouTube finishes navigating to a new page and set the flag to reset the function handlers
  510. document.addEventListener("yt-navigate-finish", () => {
  511. isAnyVideoJustStartedWaiting = 0; // reset
  512. countAnyVideoJustPaused = 0; // reset; no weaker tamer after navigation until video is paused afterwards.
  513. noActiveMediaForAWhile = false; // reset first
  514. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  515. Promise.resolve().then(executeNow);
  516. }, true); // capturing event - to let it runs before all everything else.
  517.  
  518. setInterval(() => {
  519. if (intervalTimerResolve !== null) {
  520. intervalTimerResolve();
  521. intervalTimerResolve = null;
  522. }
  523. }, UNDERCLOCK);
  524. const pTimerFn = resolve => { intervalTimerResolve = resolve };
  525.  
  526. (async () => {
  527. while (true) {
  528. bgExecutionAt = Date.now() + 160;
  529. if (noActiveMediaForAWhile) {
  530. await new Promise(pTimerFn); // CPU
  531. afInterupter = null;
  532. toResetFuncHandlers = false;
  533. dexActivePage = false;
  534. } else {
  535. const pTimer = new Promise(pTimerFn); // CPU
  536. if (!isAnyVideoJustStartedWaiting) await new Promise(infiniteLooper); // resolve by rAF or timer@250ms
  537. await pTimer; // resolve by timer@10ms
  538. if (afInterupter === null) {
  539. // triggered by setInterval
  540. dexActivePage = false;
  541. } else {
  542. // triggered by rAF
  543. afInterupter = null;
  544. if (dexActivePage === false) toResetFuncHandlers = true;
  545. dexActivePage = true;
  546. }
  547. if (toResetFuncHandlers) {
  548. // true if page change from hidden to visible OR yt-finish
  549. toResetFuncHandlers = false;
  550. for (const eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  551. }
  552. }
  553. const sHandlers = await nextTickExecutionMT1();
  554. await nextTickExecutionMT2(sHandlers);
  555. }
  556. })();
  557.  
  558. setInterval(() => {
  559. if (countAnyVideoJustPaused > 0) {
  560. // videoIsPaused = 2 => 125ms
  561. // videoIsPaused = 3 => 250ms ...
  562. if (countAnyVideoJustPaused < 16) {
  563. countAnyVideoJustPaused++;
  564. if (countAnyVideoJustPaused === 8 && !isAnyVideoJustStartedWaiting) { // 875ms
  565. Promise.resolve().then(() => {
  566. if (countAnyVideoJustPaused > 0) {
  567. /** @type {NodeListOf<HTMLMediaElement | HTMLVideoElement >} */
  568. let medias = document.querySelectorAll('video[src], audio[src]');
  569. let mp = true;
  570. for (const media of medias) {
  571. if (media.paused !== true && media.readyState >= 3) {
  572. mp = false;
  573. break;
  574. }
  575. }
  576. if (!mp) {
  577. countAnyVideoJustPaused = 0;
  578. noActiveMediaForAWhile = false;
  579. Promise.resolve().then(executeNow);
  580. } else {
  581. noActiveMediaForAWhile = true;
  582. }
  583. }
  584. })
  585. }
  586. }
  587. }
  588. if (nonResponsiveResolve !== null) {
  589. nonResponsiveResolve();
  590. return;
  591. }
  592. // no response of requestAnimationFrame; e.g. running in background
  593. const dInterupter = afInterupter;
  594. let now;
  595. if (dInterupter !== null && (now = Date.now()) > bgExecutionAt) {
  596. // interupter not triggered by rAF
  597. afInterupter = null;
  598. bgExecutionAt = now + 230;
  599. dInterupter();
  600. }
  601. }, 125);
  602. // --- 2022.12.14 ---
  603. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  604. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  605. // ---------------------
  606. // 4 times per second for background execution - to keep YouTube application functional
  607. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  608.  
  609.  
  610. const passiveCapture = typeof IntersectionObserver === 'function' ? { capture: true, passive: true } : true;
  611.  
  612. document.addEventListener('pause', function (evt) {
  613. // for changing quality, 'abort' + 'emptied' will be triggered instead.
  614. // quality change: 'abort' 'emptied' 'play' 'waiting' 'loadeddata'
  615. const target = (evt || 0).target;
  616. if (target instanceof HTMLVideoElement) {
  617. // the video paused might not be the main video; i.e. weaker tamer will apply to non-watch page (like home page)
  618. // networkState will be useful to filter out no source or fully loaded video
  619. // weaker tamer focuses on the video is loading (fetching from the server)
  620. // execute whatever videoIsPaused is.
  621. countAnyVideoJustPaused = 1;
  622. noActiveMediaForAWhile = false; // as there is user action to trigger pause
  623. executeNow();
  624. }
  625. }, passiveCapture);
  626.  
  627. document.addEventListener('abort', function (evt) {
  628. const target = (evt || 0).target;
  629. if (target instanceof HTMLVideoElement) {
  630. countAnyVideoJustPaused = 1;
  631. noActiveMediaForAWhile = false; // as there is user action to trigger abort
  632. executeNow();
  633. }
  634. }, passiveCapture);
  635.  
  636. document.addEventListener('emptied', function (evt) {
  637. const target = (evt || 0).target;
  638. if (target instanceof HTMLVideoElement) {
  639. countAnyVideoJustPaused = 1;
  640. noActiveMediaForAWhile = false; // as there is user action to trigger emptied
  641. executeNow();
  642. }
  643. }, passiveCapture);
  644.  
  645. document.addEventListener('play', function (evt) {
  646. const target = (evt || 0).target;
  647. if (target instanceof HTMLVideoElement) {
  648. if (countAnyVideoJustPaused > 0) countAnyVideoJustPaused = 1;
  649. noActiveMediaForAWhile = false; // videoIsPaused remains unchanged
  650. executeNow();
  651. }
  652. }, passiveCapture);
  653.  
  654. document.addEventListener('waiting', function (evt) {
  655. const target = (evt || 0).target;
  656. if (target instanceof HTMLVideoElement && target.readyState <= 2) {
  657. isAnyVideoJustStartedWaiting = 1;
  658. executeNow();
  659. }
  660. }, passiveCapture);
  661.  
  662. document.addEventListener('loadedmetadata', function (evt) {
  663. const target = (evt || 0).target;
  664. if (target instanceof HTMLVideoElement) {
  665. if (countAnyVideoJustPaused > 0) countAnyVideoJustPaused = 1;
  666. noActiveMediaForAWhile = false;
  667. executeNow();
  668. }
  669. }, passiveCapture);
  670.  
  671. document.addEventListener('loadeddata', function (evt) {
  672. const target = (evt || 0).target;
  673. if (target instanceof HTMLVideoElement) {
  674. if (countAnyVideoJustPaused > 0) countAnyVideoJustPaused = 1;
  675. noActiveMediaForAWhile = false;
  676. executeNow();
  677. }
  678. }, passiveCapture);
  679.  
  680. document.addEventListener('playing', function (evt) {
  681. const target = (evt || 0).target;
  682. if (target instanceof HTMLVideoElement && target.readyState >= 3) {
  683. isAnyVideoJustStartedWaiting = 0;
  684. countAnyVideoJustPaused = 0;
  685. noActiveMediaForAWhile = false;
  686. executeNow();
  687. }
  688. }, passiveCapture);
  689.  
  690. })
  691.  
  692.  
  693. })(null);