YouTube CPU Tamer by AnimationFrame

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

当前为 2023-01-25 提交的版本,查看 最新版本

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