YouTube CPU Tamer by AnimationFrame

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

当前为 2022-12-13 提交的版本,查看 最新版本

  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.12.13
  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. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  23. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-cpu-tamper-by-animationframe.webp
  24. // @run-at document-start
  25. // @grant none
  26. // @unwrap
  27. // @allFrames
  28. // @inject-into page
  29. // ==/UserScript==
  30.  
  31. /* jshint esversion:8 */
  32.  
  33. (function () {
  34. 'use strict';
  35.  
  36. const $busy = Symbol('$busy');
  37.  
  38. // Number.MAX_SAFE_INTEGER = 9007199254740991
  39.  
  40. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  41. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  42. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  43.  
  44. let toResetFuncHandlers = false;
  45.  
  46. const [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm] = (()=>{
  47.  
  48. let [window] = new Function('return [window];')(); // real window object
  49.  
  50. const hkey_script = 'nzsxclvflluv';
  51. if (window[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  52. window[hkey_script] = true;
  53.  
  54. // copies of native functions
  55.  
  56. /** @type {requestAnimationFrame} */
  57. const $$requestAnimationFrame = window.requestAnimationFrame.bind(window); // core looping
  58. /** @type {setTimeout} */
  59. const $$setTimeout = window.setTimeout.bind(window); // for race
  60. /** @type {setInterval} */
  61. const $$setInterval = window.setInterval.bind(window); // for background execution
  62. /** @type {clearTimeout} */
  63. const $$clearTimeout = window.clearTimeout.bind(window); // for native clearTimeout
  64. /** @type {clearInterval} */
  65. const $$clearInterval = window.clearInterval.bind(window); // for native clearInterval
  66.  
  67.  
  68. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  69. /** @type { Map<number, object> } */
  70. const sb = new Map();
  71. let sFunc = (prop) => {
  72. return (func, ms, ...args) => {
  73. mi++; // start at {INT_INITIAL_VALUE + 1}
  74. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  75. let handler = args.length > 0 ? func.bind(null, ...args) : func; // original func if no extra argument
  76. handler[$busy] || (handler[$busy] = 0);
  77. sb.set(mi, {
  78. handler,
  79. [prop]: ms, // timeout / interval; value can be undefined
  80. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  81. });
  82. return mi;
  83. };
  84. };
  85. const rm = function (jd) {
  86. if (!jd) return; // native setInterval & setTimeout start from 1
  87. let o = sb.get(jd);
  88. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  89. if (jd <= INT_INITIAL_VALUE) this.nativeFn(jd); // only for clearTimeout & clearInterval
  90. }else{
  91. for (let k in o) o[k] = null;
  92. o = null;
  93. sb.delete(jd);
  94. }
  95. };
  96. window.setTimeout = sFunc('timeout');
  97. window.setInterval = sFunc('interval');
  98. window.clearTimeout = rm.bind({
  99. nativeFn: $$clearTimeout
  100. });
  101. window.clearInterval = rm.bind({
  102. nativeFn: $$clearInterval
  103. });
  104. try {
  105. window.setTimeout.toString = $$setTimeout.toString.bind($$setTimeout)
  106. window.setInterval.toString = $$setInterval.toString.bind($$setInterval)
  107. window.clearTimeout.toString = $$clearTimeout.toString.bind($$clearTimeout)
  108. window.clearInterval.toString = $$clearInterval.toString.bind($$clearInterval)
  109. } catch (e) { console.warn(e) }
  110.  
  111. window.addEventListener("yt-navigate-finish", () => {
  112. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  113. }, true); // capturing event - to let it runs before all everything else.
  114.  
  115. window = null;
  116. sFunc = null;
  117.  
  118. return [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm];
  119.  
  120. })();
  121.  
  122. const delay16ms = (resolve => $$setTimeout(resolve, 16));
  123.  
  124. const pf = (
  125. handler => new Promise(resolve => {
  126. // try catch is not required - no further execution on the handler
  127. // 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)
  128. // For function handler with low energy impact, discard or not discard depends on system performance
  129. if (handler[$busy] === 1) handler();
  130. handler[$busy]--;
  131. handler = null; // remove the reference of `handler`
  132. resolve();
  133. resolve = null; // remove the reference of `resolve`
  134. })
  135. );
  136.  
  137. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  138.  
  139. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  140. /** @type {Function|null} */
  141. let interupter = null;
  142. const infiniteLooper = (resolve) => $$requestAnimationFrame(interupter = resolve); // rAF will not execute if document is hidden
  143.  
  144. const mbx = async () => {
  145.  
  146. // microTask #1
  147. let now = Date.now();
  148. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  149. let promisesF = [];
  150. const lsb = sb;
  151. for (const jb of lsb.keys()) {
  152. const o = lsb.get(jb);
  153. const {
  154. handler,
  155. // timeout,
  156. interval,
  157. nextAt
  158. } = o;
  159. if (now < nextAt) continue;
  160. handler[$busy]++;
  161. promisesF.push(handler);
  162. if (interval > 0) { // prevent undefined, zero, negative values
  163. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  164. if (nextAt + _interval > now) o.nextAt += _interval;
  165. else if (nextAt + 2 * _interval > now) o.nextAt += 2 * _interval;
  166. else if (nextAt + 3 * _interval > now) o.nextAt += 3 * _interval;
  167. else if (nextAt + 4 * _interval > now) o.nextAt += 4 * _interval;
  168. else if (nextAt + 5 * _interval > now) o.nextAt += 5 * _interval;
  169. else o.nextAt = now + _interval;
  170. } else {
  171. // jb in sb must > INT_INITIAL_VALUE
  172. rm(jb); // remove timeout
  173. }
  174. }
  175.  
  176. await Promise.resolve(0); // split microTasks inside async()
  177.  
  178. // microTask #2
  179. // bgExecutionAt = Date.now() + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  180. if (promisesF.length === 0) { // no handler functions
  181. // requestAnimationFrame when the page is active
  182. // execution interval is no less than AnimationFrame
  183. promisesF = null;
  184. } else if (dexActivePage) {
  185. let ret2 = new Promise(delay16ms);
  186. let ret3 = new Promise(resolveK => {
  187. // error would not affect calling the next tick
  188. Promise.all(promisesF.map(pf)).then(resolveK); //microTasks
  189. promisesF.length = 0;
  190. promisesF = null;
  191. })
  192. let race = Promise.race([ret2, ret3]);
  193. // ensure checking function must be called after 16ms to maintain visual changes in high fps.
  194. // >16ms examples: repaint/reflow, change of style/content
  195. await race;
  196. } else {
  197. new Promise(resolveK => {
  198. // error would not affect calling the next tick
  199. promisesF.forEach(pf); //microTasks
  200. promisesF.length = 0;
  201. promisesF = null;
  202. })
  203. }
  204.  
  205. };
  206.  
  207. (async () => {
  208. while (true) {
  209. bgExecutionAt = Date.now() + 160;
  210. await new Promise(infiniteLooper);
  211. if (interupter === null) {
  212. // triggered by setInterval
  213. dexActivePage = false;
  214. } else {
  215. // triggered by rAF
  216. interupter = null;
  217. if (dexActivePage === false) toResetFuncHandlers = true;
  218. dexActivePage = true;
  219. }
  220. if (toResetFuncHandlers) {
  221. // true if page change from hidden to visible OR yt-finish
  222. toResetFuncHandlers = false;
  223. for (let eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  224. }
  225. await mbx();
  226. }
  227. })();
  228.  
  229. $$setInterval(() => {
  230. // no response of requestAnimationFrame; e.g. running in background
  231. let interupter_t = interupter, now;
  232. if (interupter_t && (now = Date.now()) > bgExecutionAt) {
  233. // interupter not triggered by rAF
  234. bgExecutionAt = now + 230;
  235. interupter = null;
  236. interupter_t();
  237. }
  238. }, 250);
  239. // i.e. 4 times per second for background execution - to keep YouTube application functional
  240. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  241.  
  242.  
  243. })();