YouTube CPU Tamer by AnimationFrame

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

当前为 2023-06-24 提交的版本,查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2021 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:en YouTube CPU Tamer by AnimationFrame
  29. // @name:ja YouTube CPU Tamer by AnimationFrame
  30. // @name:zh-TW YouTube CPU Tamer by AnimationFrame
  31. // @name:zh-CN YouTube CPU Tamer by AnimationFrame
  32. // @namespace http://tampermonkey.net/
  33. // @version 2023.06.24.2
  34. // @license MIT License
  35. // @description Reduce Browser's Energy Impact for playing YouTube Video
  36. // @description:en Reduce Browser's Energy Impact for playing YouTube Video
  37. // @description:ja YouTubeビデオのエネルギーインパクトを減らす
  38. // @description:zh-TW 減少YouTube影片所致的能源消耗
  39. // @description:zh-CN 减少YouTube影片所致的能源消耗
  40.  
  41. // @description:ko YouTube 비디오 재생 시 브라우저의 에너지 영향을 줄입니다.
  42. // @description:ru Снижает энергетическое воздействие браузера при воспроизведении видео на YouTube.
  43. // @description:af Verminder die energie-impak van die blaaier vir YouTube-video speel
  44. // @description:az YouTube videolarını oynamaq üçün Brauzer enerji təsirini azaldır
  45. // @description:id Kurangi Dampak Energi Browser untuk memutar Video YouTube
  46. // @description:ms Kurangkan Impak Tenaga Pelayar untuk memainkan Video YouTube
  47. // @description:bs Smanji energetski uticaj preglednika za reprodukciju YouTube videa
  48. // @description:ca Redueix l'impacte energètic del navegador per reproduir vídeos de YouTube
  49. // @description:cs Snížit energetický dopad prohlížeče při přehrávání videí na YouTube
  50. // @description:da Reducer browserens energipåvirkning for at afspille YouTube-video
  51. // @description:de Reduzieren Sie die Energieauswirkungen des Browsers für die Wiedergabe von YouTube-Videos
  52. // @description:et Vähendage YouTube'i video esitamiseks brauseri energiamõju
  53. // @description:es Reduzca el impacto energético del navegador al reproducir videos de YouTube
  54. // @description:eu Gutxitu nabigatzeko energiaren eragina YouTube bideoak erreproduzitzeko
  55. // @description:fr Réduire l'impact énergétique du navigateur lors de la lecture de vidéos YouTube
  56. // @description:gl Reduzca o impacto enerxético do navegador para reproducir vídeos de YouTube
  57. // @description:hr Smanjite energetski utjecaj preglednika za reprodukciju YouTube videa
  58. // @description:zu Qaqalitsha Umbono We-Energy we-Browser ukuze udlale i-Video ye-YouTube
  59. // @description:is Minkaðu orkuáhrif vafra til að spila YouTube myndband
  60. // @description:it Riduci l'impatto energetico del browser per la riproduzione di video di YouTube
  61. // @description:sw Punguza Athari ya Nishati ya Kivinjari kwa kucheza Video za YouTube
  62. // @description:lv Samaziniet pārlūkprogrammas enerģijas ietekmi YouTube video atskaņošanai
  63. // @description:lt Sumažinkite naršyklės energijos poveikį žaidžiant „YouTube“ vaizdo įrašus
  64. // @description:hu Csökkentse a böngésző energiaterhelését a YouTube videó lejátszásához
  65. // @description:nl Verminder de energie-impact van de browser bij het afspelen van YouTube-video's
  66. // @description:uz YouTube videoni tinglash uchun brauzer energiyasi ta'sirini kamaytirish
  67. // @description:pl Zmniejsz zużycie energii przeglądarki podczas odtwarzania filmów na YouTube
  68. // @description:pt Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  69. // @description:pt-BR Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  70. // @description:ro Reduceți impactul energetic al browser-ului pentru redarea videoclipurilor YouTube
  71. // @description:sq Zvogëlo ndikimin e energjisë të shfletuesit për luajtjen e video YouTube
  72. // @description:sk Znížte energetický dopad prehliadača pri prehrávaní videí na YouTube
  73. // @description:sl Zmanjšajte energijski vpliv brskalnika pri predvajanju videoposnetkov YouTube
  74. // @description:sr Smanjite energetski uticaj pregledača za reprodukciju YouTube videa
  75. // @description:fi Vähennä selaimen energiankulutusta YouTube-videoiden toistossa
  76. // @description:sv Minska webbläsarens energipåverkan för att spela YouTube-video
  77. // @description:vi Giảm tác động năng lượng của trình duyệt khi phát Video YouTube
  78. // @description:tr YouTube Videolarını Oynatırken Tarayıcının Enerji Etkisini Azaltın
  79. // @description:be Змяншыце энергетычны ўплыў браўзара на прайграванне YouTube-відэа
  80. // @description:bg Намалете енергийния влияние на браузъра при възпроизвеждане на видео в YouTube
  81. // @description:ky YouTube видеонун ойнотуусунан башкаруу үчүн браузердеги энергиялык турмуштарды көмүштөштүрүү
  82. // @description:kk YouTube-дың браузерде көрсету мүмкіндігін көмеге қысқартыңыз
  83. // @description:mk Намалете ја енергетската присутност на пребарувачот за репродукција на YouTube видео
  84. // @description:mn YouTube видеогийг тоглуулж буй хөтөчийн энерги хүчинг буурах
  85. // @description:uk Зменште енергетичний вплив браузера на відтворення відео на YouTube
  86. // @description:el Μειώστε την ενεργειακή επίδραση του προγράμματος περιήγησης για την αναπαραγωγή βίντεο στο YouTube
  87. // @description:hy Փոքրանալիքայինը դանդարեցրեք բրաուզերի էներգիայի ազդեցությունը YouTube վիդեոների ներածման դեպքում
  88. // @description:ur یوٹیوب ویڈیو کھیلنے کے لئے براؤزر کی توانائی پر اثر کم کریں
  89. // @description:ar تقليل تأثير استهلاك الطاقة لمتصفح تشغيل مقاطع فيديو يوتيوب
  90. // @description:fa کاهش تأثیر انرژی مرورگر برای پخش ویدئوی یوتیوب
  91. // @description:ne युट्युब भिडियो खेल्नका लागि ब्राउजरको ऊर्जा प्रभाव कम गर्नुहोस्
  92. // @description:mr YouTube व्हिडिओ चालवण्यासाठी ब्राउझरचे ऊर्जाचे प्रभाव कमी करा
  93. // @description:hi यूट्यूब वीडियो चलाने के लिए ब्राउज़र की ऊर्जा प्रभाव को कम करें
  94. // @description:as YouTube ভিডিঅ' প্ৰশ্ন কৰা ব্ৰাউজাৰৰ শক্তিৰ প্ৰভাৱ কমিয়া দিব
  95. // @description:bn YouTube ভিডিও চালাতে ব্রাউজারের শক্তি প্রভাব কমান
  96. // @description:pa YouTube ਵਿਡੀਓ ਚਲਾਉਣ ਲਈ ਬਰਾਉਜ਼ਰ ਦੀ ਊਰਜਾ ਪ੍ਰਭਾਵ ਘਟਾਓ
  97. // @description:gu YouTube વિડિઓ ચલાવવા માટે બ્રાઉઝરનું ઊર્જા પ્રભાવ ઘટાડો
  98. // @description:or YouTube ଭିଡିଓ ଚାଲାନ୍ତୁ ପାଇଁ ବ୍ରାଉଜରର ଶକ୍ତି ପ୍ରଭାବ କମାନ୍ତୁ
  99. // @description:ta யூடியூப் வீடியோவை இயக்குவதற்கான உலாவியின் மிக்க விளைவுகளை குறைக்கவும்
  100. // @description:te YouTube వీడియోను ప్రసారం చేయడానికి బ్రౌజర్ యొక్క శక్తి ప్రభావాన్ని తగ్గించుకోండి
  101. // @description:kn YouTube ವೀಡಿಯೊಗಳನ್ನು ಪ್ರದರ್ಶಿಸಲು ಬ್ರೌಸರ್ ಯನ್ನು ಉಪಯೋಗಿಸುವಾಗ ಶಕ್ತಿ ಪ್ರಭಾವವನ್ನು ಕಡಿಮೆಗೊಳಿಸಿ
  102. // @description:ml YouTube വീഡിയോ പ്രവർത്തിപ്പിക്കുവാൻ ബ്രൗസർയുടെ പ്രഭാവം കുറയ്ക്കുക
  103. // @description:si YouTube වීඩියෝ චාරිකා කිරීම සඳහා බ්‍රවුසරයේ ඊම්ජි බලන්න
  104. // @description:th ลดผลกระทบทางพลังงานของเบราว์เซอร์ในการเล่นวิดีโอ YouTube
  105. // @description:lo ບຣາຣິໂຄດລາວເອີ້ນໃນການເພີ່ມເວັບວຽກຂອງ YouTube ສຳ ລັບການຂະໜາດໃນການເພີ່ມເວັບວຽກ
  106. // @description:my YouTube ဗီဒီယိုများကို ဖွင့်ရန် Browser အတွက် Energy Impact ကိုအနိုင်ရန်
  107. // @description:ka YouTube ვიდეოების დაკვრებისას ბრაუზერის ენერგიის შეცვლა
  108. // @description:am YouTube ቪዲዮዎችን ለመቀነስ የባህሪውን አርእስት ግንኙነት ማድረግ
  109. // @description:km បង្កើតការធ្វើបរិមាណលំអិតរបស់ការកំណត់ការដាក់នៅលើសម្ពាធរបស់ប្រព័ន្ធបញ្ចូលបន្ទាត់ YouTube
  110.  
  111. // @author CY Fung
  112. // @match https://www.youtube.com/*
  113. // @match https://www.youtube.com/embed/*
  114. // @match https://www.youtube-nocookie.com/embed/*
  115. // @match https://www.youtube.com/live_chat*
  116. // @match https://www.youtube.com/live_chat_replay*
  117. // @match https://music.youtube.com/*
  118. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  119. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-cpu-tamper-by-animationframe.webp
  120. // @supportURL https://github.com/cyfung1031/userscript-supports
  121. // @run-at document-start
  122. // @grant none
  123. // @unwrap
  124. // @allFrames true
  125. // @inject-into page
  126. // ==/UserScript==
  127.  
  128. /* jshint esversion:8 */
  129.  
  130. (function (__Promise__) {
  131. 'use strict';
  132.  
  133. // Create a symbol to represent the busy state of a handler function
  134. const $busy = Symbol('$busy');
  135.  
  136. // Define some constants for the initial value and the safe limits of the timer ID
  137. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  138. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  139. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  140. // Note: Number.MAX_SAFE_INTEGER = 9007199254740991
  141.  
  142. // Define a flag to indicate whether the function handlers need to be reset
  143. let toResetFuncHandlers = false;
  144.  
  145. // Assign the Promise constructor to a local variable
  146. const Promise = __Promise__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  147.  
  148. const ignorePromiseErrorFn = () => { };
  149.  
  150. const [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm] = (() => {
  151.  
  152. // Get the window object from the global scope
  153. let [window] = new Function('return [window];')(); // real window object
  154.  
  155. // Create a unique key for the script and check if it is already running
  156. const hkey_script = 'nzsxclvflluv';
  157. if (window[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  158. window[hkey_script] = true;
  159.  
  160.  
  161. // copies of native functions
  162. // Bind the native window methods to local variables
  163.  
  164. /** @type {requestAnimationFrame} */
  165. const $$requestAnimationFrame = window.requestAnimationFrame.bind(window); // core looping
  166. /** @type {setTimeout} */
  167. const $$setTimeout = window.setTimeout.bind(window); // for race
  168. /** @type {setInterval} */
  169. const $$setInterval = window.setInterval.bind(window); // for background execution
  170. /** @type {clearTimeout} */
  171. const $$clearTimeout = window.clearTimeout.bind(window); // for native clearTimeout
  172. /** @type {clearInterval} */
  173. const $$clearInterval = window.clearInterval.bind(window); // for native clearInterval
  174.  
  175. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  176.  
  177. /** @type { Map<number, object> } */
  178. const sb = new Map(); // map of timer objects
  179.  
  180. // Define a helper function to create a timer object with a handler, a delay and a next execution time
  181. let sFunc = (prop) => {
  182. return (func, ms, ...args) => {
  183. mi++; // start at {INT_INITIAL_VALUE + 1}
  184. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  185. if (ms > SAFE_INT_LIMIT) return mi;
  186. if (typeof func === 'function') { // ignore all non-function parameter
  187. let handler = args.length > 0 ? func.bind(null, ...args) : func; // original func if no extra argument
  188. handler[$busy] || (handler[$busy] = 0);
  189. sb.set(mi, {
  190. handler,
  191. [prop]: ms, // timeout / interval; value can be undefined
  192. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  193. });
  194. }
  195. return mi;
  196. };
  197. };
  198.  
  199. // Define a helper function to remove a timer object from the map or call the native method if not found
  200. const rm = function (jd) {
  201. if (!jd) return; // native setInterval & setTimeout start from 1
  202. let o = sb.get(jd);
  203. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  204. if (jd <= INT_INITIAL_VALUE) this.nativeFn(jd); // only for clearTimeout & clearInterval
  205. } else {
  206. for (let k in o) o[k] = null;
  207. o = null;
  208. sb.delete(jd);
  209. }
  210. };
  211.  
  212. // Override the window methods for setTimeout and setInterval with custom functions that use the helper function sFunc
  213. window.setTimeout = sFunc('timeout');
  214. window.setInterval = sFunc('interval');
  215.  
  216. // Override the window methods for clearTimeout and clearInterval with custom functions that use the helper function rm
  217. window.clearTimeout = rm.bind({
  218. nativeFn: $$clearTimeout
  219. });
  220. window.clearInterval = rm.bind({
  221. nativeFn: $$clearInterval
  222. });
  223.  
  224. // Try to override the toString methods of the window methods with the native ones
  225. try {
  226. window.setTimeout.toString = $$setTimeout.toString.bind($$setTimeout)
  227. window.setInterval.toString = $$setInterval.toString.bind($$setInterval)
  228. window.clearTimeout.toString = $$clearTimeout.toString.bind($$clearTimeout)
  229. window.clearInterval.toString = $$clearInterval.toString.bind($$clearInterval)
  230. } catch (e) { console.warn(e) }
  231.  
  232. // Add an event listener for when YouTube finishes navigating to a new page and set the flag to reset the function handlers
  233. window.addEventListener("yt-navigate-finish", () => {
  234. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  235. }, true); // capturing event - to let it runs before all everything else.
  236.  
  237. // Clear the reference to the window object and the helper function sFunc
  238. window = null;
  239. sFunc = null;
  240.  
  241. return [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm];
  242.  
  243. })();
  244.  
  245. let nonResponsiveResolve = null;
  246. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  247.  
  248. const pfMicroFn = (handler) => {
  249. // try catch is not required - no further execution on the handler
  250. // 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)
  251. // For function handler with low energy impact, discard or not discard depends on system performance
  252. if (handler[$busy] === 1) handler();
  253. handler[$busy]--;
  254. };
  255.  
  256. const pf = (
  257. handler => Promise.resolve(handler).then(pfMicroFn).catch(ignorePromiseErrorFn) // catch here to avoid no resolve to the race promise & avoid immediate end of the promise.all
  258. );
  259.  
  260. // Define a variable to store the next background execution time
  261. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  262.  
  263. // Define a variable to store the active page state
  264. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  265.  
  266. /** @type {Function|null} */
  267. let interupter = null;
  268.  
  269. const infiniteLooper = (resolve) => $$requestAnimationFrame(interupter = resolve); // rAF will not execute if document is hidden
  270.  
  271. // Define a helper function to execute the timer handlers in the map
  272. const mbx = async () => {
  273.  
  274. // microTask #1
  275. let now = Date.now();
  276. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  277. let promisesF = [];
  278. const lsb = sb;
  279. for (const jb of lsb.keys()) {
  280. const o = lsb.get(jb);
  281. const {
  282. handler,
  283. // timeout,
  284. interval,
  285. nextAt
  286. } = o;
  287. if (now < nextAt) continue;
  288. handler[$busy]++;
  289. promisesF.push(handler);
  290. if (interval > 0) { // prevent undefined, zero, negative values
  291. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  292. if (nextAt + _interval > now) o.nextAt += _interval;
  293. else if (nextAt + 2 * _interval > now) o.nextAt += 2 * _interval;
  294. else if (nextAt + 3 * _interval > now) o.nextAt += 3 * _interval;
  295. else if (nextAt + 4 * _interval > now) o.nextAt += 4 * _interval;
  296. else if (nextAt + 5 * _interval > now) o.nextAt += 5 * _interval;
  297. else o.nextAt = now + _interval;
  298. } else {
  299. // jb in sb must > INT_INITIAL_VALUE
  300. rm(jb); // remove timeout
  301. }
  302. }
  303.  
  304. await Promise.resolve(); // split microTasks inside async()
  305.  
  306. // microTask #2
  307. // bgExecutionAt = Date.now() + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  308. if (promisesF.length === 0) { // no handler functions
  309. // requestAnimationFrame when the page is active
  310. // execution interval is no less than AnimationFrame
  311. promisesF = null;
  312. } else if (dexActivePage) {
  313.  
  314. // retFP: looping for all functions. First error leads resolve non-reachable;
  315. // the particular [$busy] will not reset to 0 normally
  316. let retFP = Promise.resolve(promisesF).then(promisesF => Promise.all(promisesF.map(pf)));
  317. // inside Promise (async function), error would not affect calling the next tick
  318.  
  319. let retNR = new Promise(delayNonResponsive);
  320. // for every 125ms, ret2 probably resolve eariler than retFP
  321. // however it still be controlled by rAF (or 250ms) in the next looping
  322.  
  323. await Promise.race([retFP, retNR]); // continue either 125ms time limit reached or all working functions have been done
  324. promisesF.length = 0;
  325. promisesF = null;
  326. nonResponsiveResolve = null;
  327. } else {
  328. Promise.resolve(promisesF).then(promisesF => {
  329. // error would not affect calling the next tick
  330. promisesF.forEach(pf); // microTasks
  331. promisesF.length = 0;
  332. });
  333. promisesF = null;
  334. }
  335.  
  336. };
  337.  
  338. (async () => {
  339. while (true) {
  340. bgExecutionAt = Date.now() + 160;
  341. await new Promise(infiniteLooper);
  342. if (interupter === null) {
  343. // triggered by setInterval
  344. dexActivePage = false;
  345. } else {
  346. // triggered by rAF
  347. interupter = null;
  348. if (dexActivePage === false) toResetFuncHandlers = true;
  349. dexActivePage = true;
  350. }
  351. if (toResetFuncHandlers) {
  352. // true if page change from hidden to visible OR yt-finish
  353. toResetFuncHandlers = false;
  354. for (let eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  355. }
  356. await mbx();
  357. }
  358. })();
  359.  
  360. $$setInterval(() => {
  361. if (nonResponsiveResolve !== null) {
  362. nonResponsiveResolve();
  363. return;
  364. }
  365. // no response of requestAnimationFrame; e.g. running in background
  366. let interupter_t = interupter, now;
  367. if (interupter_t !== null && (now = Date.now()) > bgExecutionAt) {
  368. // interupter not triggered by rAF
  369. bgExecutionAt = now + 230;
  370. interupter = null;
  371. interupter_t();
  372. }
  373. }, 125);
  374. // --- 2022.12.14 ---
  375. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  376. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  377. // ---------------------
  378. // 4 times per second for background execution - to keep YouTube application functional
  379. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  380.  
  381.  
  382. })(Promise);