YouTube CPU Tamer by AnimationFrame

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

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

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