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.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램을 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==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();
})();