YouTube CPU Tamer by AnimationFrame

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

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

  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.22.1
  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. const $busy = Symbol('$busy');
  134.  
  135. // Number.MAX_SAFE_INTEGER = 9007199254740991
  136.  
  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.  
  141. let toResetFuncHandlers = false;
  142.  
  143. const Promise = __Promise__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  144.  
  145. const [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm] = (() => {
  146.  
  147. let [window] = new Function('return [window];')(); // real window object
  148.  
  149. const hkey_script = 'nzsxclvflluv';
  150. if (window[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  151. window[hkey_script] = true;
  152.  
  153. // copies of native functions
  154.  
  155. /** @type {requestAnimationFrame} */
  156. const $$requestAnimationFrame = window.requestAnimationFrame.bind(window); // core looping
  157. /** @type {setTimeout} */
  158. const $$setTimeout = window.setTimeout.bind(window); // for race
  159. /** @type {setInterval} */
  160. const $$setInterval = window.setInterval.bind(window); // for background execution
  161. /** @type {clearTimeout} */
  162. const $$clearTimeout = window.clearTimeout.bind(window); // for native clearTimeout
  163. /** @type {clearInterval} */
  164. const $$clearInterval = window.clearInterval.bind(window); // for native clearInterval
  165.  
  166.  
  167. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  168. /** @type { Map<number, object> } */
  169. const sb = new Map();
  170. let sFunc = (prop) => {
  171. return (func, ms, ...args) => {
  172. mi++; // start at {INT_INITIAL_VALUE + 1}
  173. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  174. if (ms > SAFE_INT_LIMIT) return mi
  175. if (typeof func === 'function') { // ignore all non-function parameter
  176. let handler = args.length > 0 ? func.bind(null, ...args) : func; // original func if no extra argument
  177. handler[$busy] || (handler[$busy] = 0);
  178. sb.set(mi, {
  179. handler,
  180. [prop]: ms, // timeout / interval; value can be undefined
  181. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  182. });
  183. }
  184. return mi;
  185. };
  186. };
  187. const rm = function (jd) {
  188. if (!jd) return; // native setInterval & setTimeout start from 1
  189. let o = sb.get(jd);
  190. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  191. if (jd <= INT_INITIAL_VALUE) this.nativeFn(jd); // only for clearTimeout & clearInterval
  192. } else {
  193. for (let k in o) o[k] = null;
  194. o = null;
  195. sb.delete(jd);
  196. }
  197. };
  198. window.setTimeout = sFunc('timeout');
  199. window.setInterval = sFunc('interval');
  200. window.clearTimeout = rm.bind({
  201. nativeFn: $$clearTimeout
  202. });
  203. window.clearInterval = rm.bind({
  204. nativeFn: $$clearInterval
  205. });
  206. try {
  207. window.setTimeout.toString = $$setTimeout.toString.bind($$setTimeout)
  208. window.setInterval.toString = $$setInterval.toString.bind($$setInterval)
  209. window.clearTimeout.toString = $$clearTimeout.toString.bind($$clearTimeout)
  210. window.clearInterval.toString = $$clearInterval.toString.bind($$clearInterval)
  211. } catch (e) { console.warn(e) }
  212.  
  213. window.addEventListener("yt-navigate-finish", () => {
  214. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  215. }, true); // capturing event - to let it runs before all everything else.
  216.  
  217. window = null;
  218. sFunc = null;
  219.  
  220. return [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm];
  221.  
  222. })();
  223.  
  224. let nonResponsiveResolve = null
  225. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  226.  
  227. const pf = (
  228. handler => new Promise(resolve => {
  229. // try catch is not required - no further execution on the handler
  230. // 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)
  231. // For function handler with low energy impact, discard or not discard depends on system performance
  232. if (handler[$busy] === 1) handler();
  233. handler[$busy]--;
  234. handler = null; // remove the reference of `handler`
  235. resolve();
  236. resolve = null; // remove the reference of `resolve`
  237. })
  238. );
  239.  
  240. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  241.  
  242. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  243. /** @type {Function|null} */
  244. let interupter = null;
  245. const infiniteLooper = (resolve) => $$requestAnimationFrame(interupter = resolve); // rAF will not execute if document is hidden
  246.  
  247. const mbx = async () => {
  248.  
  249. // microTask #1
  250. let now = Date.now();
  251. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  252. let promisesF = [];
  253. const lsb = sb;
  254. for (const jb of lsb.keys()) {
  255. const o = lsb.get(jb);
  256. const {
  257. handler,
  258. // timeout,
  259. interval,
  260. nextAt
  261. } = o;
  262. if (now < nextAt) continue;
  263. handler[$busy]++;
  264. promisesF.push(handler);
  265. if (interval > 0) { // prevent undefined, zero, negative values
  266. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  267. if (nextAt + _interval > now) o.nextAt += _interval;
  268. else if (nextAt + 2 * _interval > now) o.nextAt += 2 * _interval;
  269. else if (nextAt + 3 * _interval > now) o.nextAt += 3 * _interval;
  270. else if (nextAt + 4 * _interval > now) o.nextAt += 4 * _interval;
  271. else if (nextAt + 5 * _interval > now) o.nextAt += 5 * _interval;
  272. else o.nextAt = now + _interval;
  273. } else {
  274. // jb in sb must > INT_INITIAL_VALUE
  275. rm(jb); // remove timeout
  276. }
  277. }
  278.  
  279. await Promise.resolve(0); // split microTasks inside async()
  280.  
  281. // microTask #2
  282. // bgExecutionAt = Date.now() + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  283. if (promisesF.length === 0) { // no handler functions
  284. // requestAnimationFrame when the page is active
  285. // execution interval is no less than AnimationFrame
  286. promisesF = null;
  287. } else if (dexActivePage) {
  288. // ret3: looping for all functions. First error leads resolve non-reachable;
  289. // the particular [$busy] will not reset to 0 normally
  290. let ret3 = new Promise(resolveK => {
  291. // error would not affect calling the next tick
  292. Promise.all(promisesF.map(pf)).then(resolveK); //microTasks
  293. promisesF.length = 0;
  294. promisesF = null;
  295. })
  296. let ret2 = new Promise(delayNonResponsive);
  297. // for every 125ms, ret2 probably resolve eariler than ret3
  298. // however it still be controlled by rAF (or 250ms) in the next looping
  299. let race = Promise.race([ret2, ret3]);
  300. // continue either 125ms time limit reached or all working functions have been done
  301. await race;
  302. nonResponsiveResolve = null;
  303. } else {
  304. new Promise(resolveK => {
  305. // error would not affect calling the next tick
  306. promisesF.forEach(pf); //microTasks
  307. promisesF.length = 0;
  308. promisesF = null;
  309. })
  310. }
  311.  
  312. };
  313.  
  314. (async () => {
  315. while (true) {
  316. bgExecutionAt = Date.now() + 160;
  317. await new Promise(infiniteLooper);
  318. if (interupter === null) {
  319. // triggered by setInterval
  320. dexActivePage = false;
  321. } else {
  322. // triggered by rAF
  323. interupter = null;
  324. if (dexActivePage === false) toResetFuncHandlers = true;
  325. dexActivePage = true;
  326. }
  327. if (toResetFuncHandlers) {
  328. // true if page change from hidden to visible OR yt-finish
  329. toResetFuncHandlers = false;
  330. for (let eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  331. }
  332. await mbx();
  333. }
  334. })();
  335.  
  336. $$setInterval(() => {
  337. if (nonResponsiveResolve !== null) {
  338. nonResponsiveResolve();
  339. return;
  340. }
  341. // no response of requestAnimationFrame; e.g. running in background
  342. let interupter_t = interupter, now;
  343. if (interupter_t !== null && (now = Date.now()) > bgExecutionAt) {
  344. // interupter not triggered by rAF
  345. bgExecutionAt = now + 230;
  346. interupter = null;
  347. interupter_t();
  348. }
  349. }, 125);
  350. // --- 2022.12.14 ---
  351. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  352. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  353. // ---------------------
  354. // 4 times per second for background execution - to keep YouTube application functional
  355. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  356.  
  357.  
  358. })(Promise);