YouTube CPU Tamer by AnimationFrame

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

当前为 2022-08-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube CPU Tamer by AnimationFrame
  3. // @name:en YouTube CPU Tamer by AnimationFrame
  4. // @name:ja YouTube CPU Tamer by AnimationFrame
  5. // @name:zh-TW YouTube CPU Tamer by AnimationFrame
  6. // @name:zh-CN YouTube CPU Tamer by AnimationFrame
  7. // @namespace http://tampermonkey.net/
  8. // @version 2022.08.18.1
  9. // @license MIT License
  10. // @description Reduce Browser's Energy Impact for playing YouTube Video
  11. // @description:en Reduce Browser's Energy Impact for playing YouTube Video
  12. // @description:ja YouTubeビデオのエネルギーインパクトを減らす
  13. // @description:zh-TW 減少YouTube影片所致的能源消耗
  14. // @description:zh-CN 减少YouTube影片所致的能源消耗
  15. // @author CY Fung
  16. // @match https://www.youtube.com/*
  17. // @match https://www.youtube.com/embed/*
  18. // @match https://www.youtube-nocookie.com/embed/*
  19. // @match https://www.youtube.com/live_chat*
  20. // @match https://www.youtube.com/live_chat_replay*
  21. // @match https://music.youtube.com/*
  22. // @icon https://www.google.com/s2/favicons?domain=youtube.com
  23. // @run-at document-start
  24. // @grant none
  25. // ==/UserScript==
  26.  
  27. /* jshint esversion:8 */
  28.  
  29. (function () {
  30. 'use strict';
  31.  
  32. const $busy = Symbol('$busy');
  33. // Number.MAX_SAFE_INTEGER = 9007199254740991
  34. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  35. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  36. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  37.  
  38. let toResetFuncHandlers = false;
  39.  
  40. const [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm] = (()=>{
  41. let [window] = new Function('return [window];')(); // real window object
  42. const hkey_script = 'nzsxclvflluv';
  43. if (window[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  44. window[hkey_script] = true;
  45. // copies of native functions
  46.  
  47. /** @type {requestAnimationFrame} */
  48. const $$requestAnimationFrame = window.requestAnimationFrame.bind(window); // core looping
  49. /** @type {setTimeout} */
  50. const $$setTimeout = window.setTimeout.bind(window); // for race
  51. /** @type {setInterval} */
  52. const $$setInterval = window.setInterval.bind(window); // for background execution
  53. /** @type {clearTimeout} */
  54. const $$clearTimeout = window.clearTimeout.bind(window); // for native clearTimeout
  55. /** @type {clearInterval} */
  56. const $$clearInterval = window.clearInterval.bind(window); // for native clearInterval
  57. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  58. const sb = {};
  59. let sFunc = (prop) => {
  60. return (func, ms, ...args) => {
  61. mi++; // start at {INT_INITIAL_VALUE + 1}
  62. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  63. let handler = args.length > 0 ? func.bind(null, ...args) : func; // original func if no extra argument
  64. handler[$busy] || (handler[$busy] = 0);
  65. sb[mi] = {
  66. handler,
  67. [prop]: ms, // timeout / interval; value can be undefined
  68. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  69. };
  70. return mi;
  71. };
  72. };
  73. const rm = function (jd) {
  74. if (!jd) return; // native setInterval & setTimeout start from 1
  75. let o = sb[jd];
  76. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  77. if (jd <= INT_INITIAL_VALUE) this.nativeFn(jd); // only for clearTimeout & clearInterval
  78. return;
  79. }
  80. for (let k in o) o[k] = null;
  81. o = null;
  82. sb[jd] = null;
  83. delete sb[jd];
  84. };
  85. window.setTimeout = sFunc('timeout');
  86. window.setInterval = sFunc('interval');
  87. window.clearTimeout = rm.bind({
  88. nativeFn: $$clearTimeout
  89. });
  90. window.clearInterval = rm.bind({
  91. nativeFn: $$clearInterval
  92. });
  93. // window.clearInterval = window.clearTimeout = rm;
  94.  
  95. window.addEventListener("yt-navigate-finish", () => {
  96. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  97. }, true); // capturing event - to let it runs before all everything else.
  98.  
  99. window = null;
  100. sFunc = null;
  101.  
  102. return [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm];
  103.  
  104. })();
  105. const delay16ms = (resolve => $$setTimeout(resolve, 16));
  106. const pf = (
  107. handler => new Promise(resolve => {
  108. // try catch is not required - no further execution on the handler
  109. // 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)
  110. // For function handler with low energy impact, discard or not discard depends on system performance
  111. if (handler[$busy] === 1) handler();
  112. handler[$busy]--;
  113. handler = null; // remove the reference of `handler`
  114. resolve();
  115. resolve = null; // remove the reference of `resolve`
  116. })
  117. );
  118. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  119. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  120. /** @type {Function|null} */
  121. let interupter = null;
  122. const infiniteLooper = (resolve) => $$requestAnimationFrame(interupter = resolve); // rAF will not execute if document is hidden
  123. const mbx1 = async () => {
  124. // microTask #1
  125. let now = Date.now();
  126. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  127. let promisesF = [];
  128. for (let jb in sb) {
  129. const o = sb[jb];
  130. let {
  131. handler,
  132. // timeout,
  133. interval,
  134. nextAt
  135. } = o;
  136. if (now < nextAt) continue;
  137. handler[$busy]++;
  138. promisesF.push(handler);
  139. if (interval > 0) { // prevent undefined, zero, negative values
  140. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  141. if (o.nextAt + _interval > now) o.nextAt += _interval;
  142. else if (o.nextAt + 2 * _interval > now) o.nextAt += 2 * _interval;
  143. else if (o.nextAt + 3 * _interval > now) o.nextAt += 3 * _interval;
  144. else if (o.nextAt + 4 * _interval > now) o.nextAt += 4 * _interval;
  145. else if (o.nextAt + 5 * _interval > now) o.nextAt += 5 * _interval;
  146. else o.nextAt = now + _interval;
  147. } else {
  148. // jb in sb must > INT_INITIAL_VALUE
  149. rm(jb); // remove timeout
  150. }
  151. }
  152. return promisesF;
  153. };
  154. const mbx2 = async (promisesF) => {
  155. // microTask #2
  156. // bgExecutionAt = Date.now() + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  157. if (promisesF.length === 0) { // no handler functions
  158. // requestAnimationFrame when the page is active
  159. // execution interval is no less than AnimationFrame
  160. } else if (dexActivePage) {
  161. let ret2 = new Promise(delay16ms);
  162. let ret3 = new Promise(resolveK => {
  163. // error would not affect calling the next tick
  164. Promise.all(promisesF.map(pf)).then(resolveK); //microTasks
  165. promisesF.length = 0;
  166. })
  167. let race = Promise.race([ret2, ret3]);
  168. // ensure checking function must be called after 16ms to maintain visual changes in high fps.
  169. // >16ms examples: repaint/reflow, change of style/content
  170. await race;
  171. } else {
  172. new Promise(resolveK => {
  173. // error would not affect calling the next tick
  174. promisesF.forEach(pf); //microTasks
  175. promisesF.length = 0;
  176. })
  177. }
  178. };
  179. (async () => {
  180. while (true) {
  181. bgExecutionAt = Date.now() + 160;
  182. await new Promise(infiniteLooper);
  183. if (!interupter) {
  184. // triggered by setInterval
  185. dexActivePage = false;
  186. } else {
  187. // triggered by rAF
  188. interupter = null;
  189. if (dexActivePage === false) toResetFuncHandlers = true;
  190. dexActivePage = true;
  191. }
  192. if (toResetFuncHandlers) {
  193. // true if page change from hidden to visible OR yt-finish
  194. toResetFuncHandlers = false;
  195. for (let jb in sb) sb[jb].handler[$busy] = 0; // including the functions with error
  196. }
  197. let promisesF = await mbx1();
  198. await mbx2(promisesF);
  199. interupter = null; // just ensure no interupter after mbx1 and mbx2
  200. }
  201. })();
  202. $$setInterval(() => {
  203. // no response of requestAnimationFrame; e.g. running in background
  204. let interupter_t = interupter, now;
  205. if (interupter_t && (now = Date.now()) > bgExecutionAt) {
  206. // interupter not triggered by rAF
  207. bgExecutionAt = now + 230;
  208. interupter = null;
  209. interupter_t();
  210. }
  211. }, 250);
  212. // i.e. 4 times per second for background execution - to keep YouTube application functional
  213. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  214. })();