YouTube CPU Tamer by AnimationFrame

Reduce Browser's Energy Impact for playing YouTube Video

当前为 2022-07-24 提交的版本,查看 最新版本

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