YouTube CPU Tamer by AnimationFrame

Reduce Browser's Energy Impact for playing YouTube Video

当前为 2021-09-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube CPU Tamer by AnimationFrame
  3. // @name:en YouTube CPU Tamer by AnimationFrame
  4. // @name:jp 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 2021.09.30
  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:jp YouTubeビデオのエネルギーインパクトを減らす
  13. // @description:zh-tw 減少YouTube影片所致的能源消耗
  14. // @description:zh-cn 减少YouTube影片所致的能源消耗
  15. // @author CY Fung
  16. // @include https://www.youtube.com/*
  17. // @include https://www.youtube.com/embed/*
  18. // @include https://www.youtube-nocookie.com/embed/*
  19. // @include https://www.youtube.com/live_chat*
  20. // @include https://www.youtube.com/live_chat_replay*
  21. // @include 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. (function $$() {
  27. 'use strict';
  28.  
  29. const [window, document] = new Function('return [window, document];')(); // real window & document object
  30.  
  31. const hkey_script = 'nzsxclvflluv';
  32. if (window[hkey_script]) return; // avoid duplicated scripting
  33. window[hkey_script] = true;
  34.  
  35. //if (!document.documentElement) return window.requestAnimationFrame($$); // not required to check documentElement ready or not
  36.  
  37. // copies of native functions
  38. const $$requestAnimationFrame = window.requestAnimationFrame.bind(window); // core looping
  39. const $$setTimeout = window.setTimeout.bind(window); // for race
  40. const $$setInterval = window.setInterval.bind(window); // for background execution
  41. const $$clearTimeout = window.clearTimeout.bind(window); // for native clearTimeout
  42. const $$clearInterval = window.clearInterval.bind(window); // for native clearInterval
  43.  
  44. const $busy = Symbol('$busy');
  45.  
  46. // Number.MAX_SAFE_INTEGER = 9007199254740991
  47.  
  48. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  49. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  50. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  51.  
  52. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  53. const sb = {};
  54. const sFunc = (prop) => {
  55. return (func, ms, ...args) => {
  56. mi++; // start at {INT_INITIAL_VALUE + 1}
  57. if( mi > SAFE_INT_LIMIT ) mi = SAFE_INT_REDUCED; // just in case
  58. let handler = args.length > 0 ? func.bind(null, ...args) : func; // original func if no extra argument
  59. handler[$busy] || ( handler[$busy] = 0 );
  60. sb[mi] = {
  61. handler,
  62. [prop]: ms, // timeout / interval; value can be undefined
  63. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  64. };
  65. return mi;
  66. };
  67. };
  68. const rm = function (jd) {
  69. if (!jd) return; // native setInterval & setTimeout start from 1
  70. let o = sb[jd];
  71. if (typeof o != 'object'){ // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  72. if (jd <= INT_INITIAL_VALUE) this.nativeFn(jd); // only for clearTimeout & clearInterval
  73. return;
  74. }
  75. for (let k in o) o[k] = null;
  76. o = null;
  77. sb[jd] = null;
  78. delete sb[jd];
  79. };
  80. window.setTimeout = sFunc('timeout');
  81. window.setInterval = sFunc('interval');
  82. window.clearTimeout = rm.bind({nativeFn: $$clearTimeout});
  83. window.clearInterval = rm.bind({nativeFn: $$clearInterval});
  84. // window.clearInterval = window.clearTimeout = rm;
  85.  
  86. const delay16ms = ( resolve => $$setTimeout(resolve, 16) );
  87.  
  88. const pf = (
  89. handler => new Promise(resolve => {
  90. // try catch is not required - no further execution on the handler
  91. // 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)
  92. // For function handler with low energy impact, discard or not discard depends on system performance
  93. if (handler[$busy] == 1) handler();
  94. handler[$busy]--;
  95. handler = null; // remove the reference of `handler`
  96. resolve();
  97. resolve = null; // remove the reference of `resolve`
  98. })
  99. );
  100.  
  101. let jf, tf, toResetFuncHandlers = false;
  102. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  103. tf = () => {
  104. if (toResetFuncHandlers) {
  105. toResetFuncHandlers = false;
  106. for (let jb in sb) sb[jb].handler[$busy] = 0; // including the functions with error
  107. }
  108. new Promise(resolveApp1 => {
  109. // microTask #1
  110. let now = Date.now();
  111. bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  112. let promisesF = [];
  113. for (let jb in sb) {
  114. const o = sb[jb];
  115. let {
  116. handler,
  117. // timeout,
  118. interval,
  119. nextAt
  120. } = o;
  121. if (now < nextAt) continue;
  122. handler[$busy]++;
  123. promisesF.push(handler);
  124. if (interval > 0) { // prevent undefined, zero, negative values
  125. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  126. if(o.nextAt + _interval > now) o.nextAt += _interval;
  127. else if(o.nextAt + 2*_interval > now) o.nextAt += 2*_interval;
  128. else if(o.nextAt + 3*_interval > now) o.nextAt += 3*_interval;
  129. else if(o.nextAt + 4*_interval > now) o.nextAt += 4*_interval;
  130. else if(o.nextAt + 5*_interval > now) o.nextAt += 5*_interval;
  131. else o.nextAt = now + _interval;
  132. } else {
  133. // jb in sb must > INT_INITIAL_VALUE
  134. rm(jb); // remove timeout
  135. }
  136. }
  137. resolveApp1(promisesF);
  138. }).then(promisesF => {
  139. // microTask #2
  140. bgExecutionAt = Date.now() + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  141. let hidden = document.hidden; // background running would not call requestAnimationFrame
  142. if (promisesF.length == 0) { // no handler functions
  143. // requestAnimationFrame when the page is active
  144. // execution interval is no less than AnimationFrame
  145. return hidden || jf();
  146. }
  147. if (!hidden) {
  148. let ret2 = new Promise(delay16ms);
  149. let promises = promisesF.map(pf); //microTasks
  150. let ret1 = Promise.all(promises);
  151. let race = Promise.race([ret1, ret2]);
  152. // ensure jf must be called after 16ms to maintain visual changes in high fps.
  153. // >16ms examples: repaint/reflow, change of style/content
  154. race.then(jf);
  155. promises.length = 0;
  156. } else {
  157. promisesF.forEach(pf);
  158. }
  159. promisesF.length = 0;
  160. });
  161. };
  162. (jf = $$requestAnimationFrame.bind(window, tf))();
  163.  
  164. $$setInterval(() => {
  165. // no response of requestAnimationFrame; e.g. running in background
  166. // toResetFuncHandlers = true;
  167. if (Date.now() > bgExecutionAt) {
  168. toResetFuncHandlers = true;
  169. tf();
  170. }
  171. }, 250);
  172. // i.e. 4 times per second for background execution - to keep YouTube application functional
  173. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  174.  
  175. window.addEventListener("yt-navigate-finish", () => {
  176. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  177. }, true); // capturing event - to let it runs before all everything else.
  178.  
  179. // Your code here...
  180. })();