YouTube CPU Tamer by AnimationFrame

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

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

  1. /*
  2.  
  3. Copyright 2021 CY Fung
  4.  
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  6.  
  7. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  8.  
  9. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  10.  
  11. */
  12. // ==UserScript==
  13. // @name YouTube CPU Tamer by AnimationFrame
  14. // @name:en YouTube CPU Tamer by AnimationFrame
  15. // @name:ja YouTube CPU Tamer by AnimationFrame
  16. // @name:zh-TW YouTube CPU Tamer by AnimationFrame
  17. // @name:zh-CN YouTube CPU Tamer by AnimationFrame
  18. // @namespace http://tampermonkey.net/
  19. // @version 2022.12.28
  20. // @license MIT License
  21. // @description Reduce Browser's Energy Impact for playing YouTube Video
  22. // @description:en Reduce Browser's Energy Impact for playing YouTube Video
  23. // @description:ja YouTubeビデオのエネルギーインパクトを減らす
  24. // @description:zh-TW 減少YouTube影片所致的能源消耗
  25. // @description:zh-CN 减少YouTube影片所致的能源消耗
  26. // @author CY Fung
  27. // @match https://www.youtube.com/*
  28. // @match https://www.youtube.com/embed/*
  29. // @match https://www.youtube-nocookie.com/embed/*
  30. // @match https://www.youtube.com/live_chat*
  31. // @match https://www.youtube.com/live_chat_replay*
  32. // @match https://music.youtube.com/*
  33. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  34. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-cpu-tamper-by-animationframe.webp
  35. // @supportURL https://github.com/cyfung1031/userscript-supports
  36. // @run-at document-start
  37. // @grant none
  38. // @unwrap
  39. // @allFrames
  40. // @inject-into page
  41. // ==/UserScript==
  42.  
  43. /* jshint esversion:8 */
  44.  
  45. (function () {
  46. 'use strict';
  47.  
  48. const $busy = Symbol('$busy');
  49.  
  50. // Number.MAX_SAFE_INTEGER = 9007199254740991
  51.  
  52. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  53. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  54. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  55.  
  56. let toResetFuncHandlers = false;
  57.  
  58. const [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm] = (() => {
  59.  
  60. let [window] = new Function('return [window];')(); // real window object
  61.  
  62. const hkey_script = 'nzsxclvflluv';
  63. if (window[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  64. window[hkey_script] = true;
  65.  
  66. // copies of native functions
  67.  
  68. /** @type {requestAnimationFrame} */
  69. const $$requestAnimationFrame = window.requestAnimationFrame.bind(window); // core looping
  70. /** @type {setTimeout} */
  71. const $$setTimeout = window.setTimeout.bind(window); // for race
  72. /** @type {setInterval} */
  73. const $$setInterval = window.setInterval.bind(window); // for background execution
  74. /** @type {clearTimeout} */
  75. const $$clearTimeout = window.clearTimeout.bind(window); // for native clearTimeout
  76. /** @type {clearInterval} */
  77. const $$clearInterval = window.clearInterval.bind(window); // for native clearInterval
  78.  
  79.  
  80. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  81. /** @type { Map<number, object> } */
  82. const sb = new Map();
  83. let sFunc = (prop) => {
  84. return (func, ms, ...args) => {
  85. mi++; // start at {INT_INITIAL_VALUE + 1}
  86. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  87. if (ms > SAFE_INT_LIMIT) return mi
  88. let handler = args.length > 0 ? func.bind(null, ...args) : func; // original func if no extra argument
  89. handler[$busy] || (handler[$busy] = 0);
  90. sb.set(mi, {
  91. handler,
  92. [prop]: ms, // timeout / interval; value can be undefined
  93. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  94. });
  95. return mi;
  96. };
  97. };
  98. const rm = function (jd) {
  99. if (!jd) return; // native setInterval & setTimeout start from 1
  100. let o = sb.get(jd);
  101. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  102. if (jd <= INT_INITIAL_VALUE) this.nativeFn(jd); // only for clearTimeout & clearInterval
  103. } else {
  104. for (let k in o) o[k] = null;
  105. o = null;
  106. sb.delete(jd);
  107. }
  108. };
  109. window.setTimeout = sFunc('timeout');
  110. window.setInterval = sFunc('interval');
  111. window.clearTimeout = rm.bind({
  112. nativeFn: $$clearTimeout
  113. });
  114. window.clearInterval = rm.bind({
  115. nativeFn: $$clearInterval
  116. });
  117. try {
  118. window.setTimeout.toString = $$setTimeout.toString.bind($$setTimeout)
  119. window.setInterval.toString = $$setInterval.toString.bind($$setInterval)
  120. window.clearTimeout.toString = $$clearTimeout.toString.bind($$clearTimeout)
  121. window.clearInterval.toString = $$clearInterval.toString.bind($$clearInterval)
  122. } catch (e) { console.warn(e) }
  123.  
  124. window.addEventListener("yt-navigate-finish", () => {
  125. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  126. }, true); // capturing event - to let it runs before all everything else.
  127.  
  128. window = null;
  129. sFunc = null;
  130.  
  131. return [$$requestAnimationFrame, $$setTimeout, $$setInterval, $$clearTimeout, $$clearInterval, sb, rm];
  132.  
  133. })();
  134.  
  135. let nonResponsiveResolve = null
  136. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  137.  
  138. const pf = (
  139. handler => new Promise(resolve => {
  140. // try catch is not required - no further execution on the handler
  141. // 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)
  142. // For function handler with low energy impact, discard or not discard depends on system performance
  143. if (handler[$busy] === 1) handler();
  144. handler[$busy]--;
  145. handler = null; // remove the reference of `handler`
  146. resolve();
  147. resolve = null; // remove the reference of `resolve`
  148. })
  149. );
  150.  
  151. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  152.  
  153. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  154. /** @type {Function|null} */
  155. let interupter = null;
  156. const infiniteLooper = (resolve) => $$requestAnimationFrame(interupter = resolve); // rAF will not execute if document is hidden
  157.  
  158. const mbx = async () => {
  159.  
  160. // microTask #1
  161. let now = Date.now();
  162. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  163. let promisesF = [];
  164. const lsb = sb;
  165. for (const jb of lsb.keys()) {
  166. const o = lsb.get(jb);
  167. const {
  168. handler,
  169. // timeout,
  170. interval,
  171. nextAt
  172. } = o;
  173. if (now < nextAt) continue;
  174. handler[$busy]++;
  175. promisesF.push(handler);
  176. if (interval > 0) { // prevent undefined, zero, negative values
  177. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  178. if (nextAt + _interval > now) o.nextAt += _interval;
  179. else if (nextAt + 2 * _interval > now) o.nextAt += 2 * _interval;
  180. else if (nextAt + 3 * _interval > now) o.nextAt += 3 * _interval;
  181. else if (nextAt + 4 * _interval > now) o.nextAt += 4 * _interval;
  182. else if (nextAt + 5 * _interval > now) o.nextAt += 5 * _interval;
  183. else o.nextAt = now + _interval;
  184. } else {
  185. // jb in sb must > INT_INITIAL_VALUE
  186. rm(jb); // remove timeout
  187. }
  188. }
  189.  
  190. await Promise.resolve(0); // split microTasks inside async()
  191.  
  192. // microTask #2
  193. // bgExecutionAt = Date.now() + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  194. if (promisesF.length === 0) { // no handler functions
  195. // requestAnimationFrame when the page is active
  196. // execution interval is no less than AnimationFrame
  197. promisesF = null;
  198. } else if (dexActivePage) {
  199. // ret3: looping for all functions. First error leads resolve non-reachable;
  200. // the particular [$busy] will not reset to 0 normally
  201. let ret3 = new Promise(resolveK => {
  202. // error would not affect calling the next tick
  203. Promise.all(promisesF.map(pf)).then(resolveK); //microTasks
  204. promisesF.length = 0;
  205. promisesF = null;
  206. })
  207. let ret2 = new Promise(delayNonResponsive);
  208. // for every 125ms, ret2 probably resolve eariler than ret3
  209. // however it still be controlled by rAF (or 250ms) in the next looping
  210. let race = Promise.race([ret2, ret3]);
  211. // continue either 125ms time limit reached or all working functions have been done
  212. await race;
  213. nonResponsiveResolve = null;
  214. } else {
  215. new Promise(resolveK => {
  216. // error would not affect calling the next tick
  217. promisesF.forEach(pf); //microTasks
  218. promisesF.length = 0;
  219. promisesF = null;
  220. })
  221. }
  222.  
  223. };
  224.  
  225. (async () => {
  226. while (true) {
  227. bgExecutionAt = Date.now() + 160;
  228. await new Promise(infiniteLooper);
  229. if (interupter === null) {
  230. // triggered by setInterval
  231. dexActivePage = false;
  232. } else {
  233. // triggered by rAF
  234. interupter = null;
  235. if (dexActivePage === false) toResetFuncHandlers = true;
  236. dexActivePage = true;
  237. }
  238. if (toResetFuncHandlers) {
  239. // true if page change from hidden to visible OR yt-finish
  240. toResetFuncHandlers = false;
  241. for (let eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  242. }
  243. await mbx();
  244. }
  245. })();
  246.  
  247. $$setInterval(() => {
  248. if (nonResponsiveResolve !== null) {
  249. nonResponsiveResolve();
  250. return;
  251. }
  252. // no response of requestAnimationFrame; e.g. running in background
  253. let interupter_t = interupter, now;
  254. if (interupter_t !== null && (now = Date.now()) > bgExecutionAt) {
  255. // interupter not triggered by rAF
  256. bgExecutionAt = now + 230;
  257. interupter = null;
  258. interupter_t();
  259. }
  260. }, 125);
  261. // --- 2022.12.14 ---
  262. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  263. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  264. // ---------------------
  265. // 4 times per second for background execution - to keep YouTube application functional
  266. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  267.  
  268.  
  269. })();