YouTube Performance Booster HYPER

Maximum low-level optimizations: tames ytcfg experiment flags, bypasses useless logging, pauses hover/transitions during scroll for flawless FPS, throttles ambient glow, and safely mitigates memory leaks. Zero UI changes.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

You will need to install an extension such as Tampermonkey to install this script.

Tendrás que instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Tendrás que instalar una extensión como Tampermonkey antes de poder instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name         YouTube Performance Booster HYPER
// @name:ru      Гипер-оптимизатор YouTube (Без изменения интерфейса)
// @namespace    http://tampermonkey.net/
// @version      4.0
// @description  Maximum low-level optimizations: tames ytcfg experiment flags, bypasses useless logging, pauses hover/transitions during scroll for flawless FPS, throttles ambient glow, and safely mitigates memory leaks. Zero UI changes.
// @description:ru Низкоуровневые оптимизации: перехватывает конфигурацию ytcfg, отключает фоновое логирование, замораживает hover-эффекты при скролле для максимального FPS, оптимизирует память и эмбиент. Без изменений интерфейса.
// @author       torch
// @match        https://*.youtube.com/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // --- 1. ПЕРЕХВАТ И ОПТИМИЗАЦИЯ YTCFG (EXPERIMENT FLAGS) ---
    // На лету перехватывает конфигурацию YouTube и отключает ресурсоемкое фоновое логирование.
    function optimizeConfig(cfg) {
        if (!cfg) return;
        if (cfg.EXPERIMENT_FLAGS) {
            cfg.EXPERIMENT_FLAGS.web_attention_logging_scroll_throttle = 1500; // Реже трекать внимание при прокрутке
            cfg.EXPERIMENT_FLAGS.log_window_onerror_fraction = 0.0;            // Отключить отправку логов ошибок на сервер
        }
        if (cfg.web_attention_logging_scroll_throttle !== undefined) cfg.web_attention_logging_scroll_throttle = 1500;
        if (cfg.log_window_onerror_fraction !== undefined) cfg.log_window_onerror_fraction = 0.0;
        if (cfg.polymer_property_access_logging_percent !== undefined) cfg.polymer_property_access_logging_percent = 0.0;
    }

    let ytcfgVal = window.ytcfg;
    Object.defineProperty(window, 'ytcfg', {
        get() { return ytcfgVal; },
        set(newVal) {
            ytcfgVal = newVal;
            if (ytcfgVal && typeof ytcfgVal.set === 'function' && !ytcfgVal.set.isPatched) {
                const originalSet = ytcfgVal.set;
                ytcfgVal.set = function(key, val) {
                    if (typeof key === 'object') {
                        optimizeConfig(key);
                    } else if (key === 'EXPERIMENT_FLAGS' && val) {
                        optimizeConfig({ EXPERIMENT_FLAGS: val });
                    }
                    return originalSet.apply(this, arguments);
                };
                ytcfgVal.set.isPatched = true;
            }
        },
        configurable: true
    });

    if (window.ytcfg && typeof window.ytcfg.set === 'function') {
        optimizeConfig(window.ytcfg);
    }

    // --- 2. УСТРАНЕНИЕ ЛАГОВ ПРИ СКРОЛЛИНГЕ (TRANSITION SUSPENDER) ---
    // Отключает hover-эффекты и анимации строго на время прокрутки. Поднимает FPS до стабильных 60/120/144 Гц.
    const disableHoverStyles = document.createElement('style');
    disableHoverStyles.id = 'yt-scroll-hover-disable';
    disableHoverStyles.textContent = `
        body.is-scrolling * {
            pointer-events: none !important;
            transition: none !important;
            animation-play-state: paused !important;
        }
    `;
    document.documentElement.appendChild(disableHoverStyles);

    let isScrollingTimeout;
    window.addEventListener('scroll', () => {
        window.clearTimeout(isScrollingTimeout);
        if (!document.body.classList.contains('is-scrolling')) {
            document.body.classList.add('is-scrolling');
        }
        isScrollingTimeout = setTimeout(() => {
            document.body.classList.remove('is-scrolling');
        }, 150);
    }, { passive: true });

    // --- 3. ОЧИСТКА ПАМЯТИ ПРИ НАВИГАЦИИ (SPA GC ASSIST) ---
    // Предотвращает утечки ОЗУ при переходе от одного видео к другому.
    window.addEventListener('yt-navigate-start', () => {
        // Очищаем кэшированные браузером изображения и тяжелые неактивные элементы
        window.clearTimeout(isScrollingTimeout);
        if (typeof window.gc === 'function') {
            try { window.gc(); } catch(e) {}
        }
    }, { passive: true });

    // --- 4. ОГРАНИЧЕНИЕ ЭМБИЕНТ-СВЕЧЕНИЯ ПЛЕЕРА ---
    const originalGetContext = HTMLCanvasElement.prototype.getContext;
    HTMLCanvasElement.prototype.getContext = function(type, attributes) {
        const context = originalGetContext.call(this, type, attributes);
        if (type === '2d' && (this.id === 'cinematic' || this.classList.contains('ytp-glow-canvas') || this.closest('#cinematic-container'))) {
            const originalDrawImage = context.drawImage;
            let lastDrawTime = 0;
            context.drawImage = function(...args) {
                const now = performance.now();
                if (now - lastDrawTime < 50) return; // Лимит 20 FPS для размытого свечения
                lastDrawTime = now;
                return originalDrawImage.apply(this, args);
            };
        }
        return context;
    };

    // --- 5. ОГРАНИЧЕНИЕ ЧАСТОТЫ LAYOUT OBSERVERS ---
    const OriginalResizeObserver = window.ResizeObserver;
    window.ResizeObserver = class ThrottledResizeObserver extends OriginalResizeObserver {
        constructor(callback) {
            let timeout;
            const throttledCallback = (entries, observer) => {
                if (timeout) return;
                timeout = setTimeout(() => {
                    callback(entries, observer);
                    timeout = null;
                }, 30);
            };
            super(throttledCallback);
        }
    };

    // --- 6. КОРРЕКТИРОВКА ЧАСТОТЫ ФОНОВЫХ ТАЙМЕРОВ ---
    const originalSetInterval = window.setInterval;
    window.setInterval = function(fn, delay, ...args) {
        if (delay > 0 && delay < 100) {
            delay = 100;
        }
        return originalSetInterval.call(window, fn, delay, ...args);
    };

    // --- 7. БЛОКИРОВКА ИЗБЫТОЧНОЙ СЕТЕВОЙ ТЕЛЕМЕТРИИ ---
    const originalSendBeacon = Navigator.prototype.sendBeacon;
    Navigator.prototype.sendBeacon = function(url, data) {
        if (url.includes('/csi_204') || url.includes('/error_204') || url.includes('/api/stats/qoe')) {
            if (Math.random() > 0.2) return true;
        }
        return originalSendBeacon.call(this, url, data);
    };

    // --- 8. ОГРАНИЧЕНИЕ МЫШИ НА PROGRESS BAR ---
    let lastMoveTime = 0;
    document.addEventListener('mousemove', (e) => {
        const now = performance.now();
        if (e.target.closest && e.target.closest('.ytp-progress-bar')) {
            if (now - lastMoveTime < 16.6) {
                e.stopPropagation();
            } else {
                lastMoveTime = now;
            }
        }
    }, { passive: true, capture: true });

    // --- 9. ПАССИВНЫЕ ОБРАБОТЧИКИ СОБЫТИЙ ДЛЯ СКРОЛЛА ---
    const originalAddEventListener = EventTarget.prototype.addEventListener;
    EventTarget.prototype.addEventListener = function(type, listener, options) {
        if (['touchstart', 'touchmove', 'wheel', 'mousewheel'].includes(type)) {
            if (typeof options === 'boolean') {
                options = { passive: true, capture: options };
            } else if (typeof options === 'object') {
                options.passive = options.passive !== undefined ? options.passive : true;
            } else {
                options = { passive: true };
            }
        }
        return originalAddEventListener.call(this, type, listener, options);
    };

    // --- 10. АСИНХРОННОЕ ДЕКОДИРОВАНИЕ ИЗОБРАЖЕНИЙ ---
    const originalCreateElement = Document.prototype.createElement;
    Document.prototype.createElement = function(tagName, options) {
        const element = originalCreateElement.call(this, tagName, options);
        if (tagName.toLowerCase() === 'img') {
            element.setAttribute('decoding', 'async');
        }
        return element;
    };

    // --- 11. ОПТИМАЛЬНЫЕ CSS-ПРАВИЛА Отрисовки ---
    const injectOptimizeStyles = () => {
        if (document.head) {
            const style = document.createElement('style');
            style.id = 'yt-perf-optimizer-hyper-styles';
            style.textContent = `
                ytd-rich-grid-renderer,
                ytd-rich-item-renderer,
                ytd-video-renderer,
                ytd-compact-video-renderer,
                ytd-comment-thread-renderer,
                #player-container,
                .html5-video-container,
                #columns {
                    will-change: transform;
                    transform: translateZ(0);
                    backface-visibility: hidden;
                    perspective: 1000px;
                }

                ytd-rich-item-renderer,
                ytd-comment-thread-renderer,
                ytd-compact-video-renderer {
                    content-visibility: auto;
                    contain-intrinsic-size: auto 320px;
                }

                img {
                    content-visibility: auto;
                }
            `;
            document.head.appendChild(style);
        } else {
            setTimeout(injectOptimizeStyles, 10);
        }
    };

    injectOptimizeStyles();
})();