// ==UserScript== // @name YouTube Video Enhancer 1.1-alpha // @namespace https://github.com/PorkSandwitch // @version 1.1-alpha // @description Lightweight YouTube picture enhancer (contrast, brightness, saturation, optional sharpening) built for low-end PCs // @author PorkSandwitch // @license MIT // @homepageURL https://github.com/PorkSandwitch/YouTube-Video-Enhancer // @supportURL https://github.com/PorkSandwitch/YouTube-Video-Enhancer/issues // @downloadURL https://github.com/PorkSandwitch/YouTube-Video-Enhancer/blob/main/youtube-video-enhancer-1.1-alpha.user.js // @updateURL https://github.com/PorkSandwitch/YouTube-Video-Enhancer/blob/main/youtube-video-enhancer-1.1-alpha.user.js // @match https://www.youtube.com/* // @match https://m.youtube.com/* // @run-at document-idle // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM.getValue // @grant GM.setValue // @grant GM.deleteValue // @noframes // ==/UserScript== (() => { 'use strict'; const PANEL_ID = 'yt-video-enhancer-panel'; const STYLE_ID = 'yt-video-enhancer-styles'; const SVG_ID = 'yt-video-enhancer-svg'; const FILTER_ID = 'yt-video-enhancer-sharpen'; const CANVAS_ID = 'yt-video-enhancer-canvas'; const COLLAPSED = 46; const EXPANDED_W = 300; const EXPANDED_H_FALLBACK = 226; const EDGE_GAP = 18; const DEFAULT_STRENGTH = 25; const AUTO_BASE = 25; const PRESETS = { natural: 18, clear: 32, strong: 48 }; const PRESET_NAMES = ['custom', 'natural', 'clear', 'strong']; const SHARPEN_MAX_P = 1080; const SHARPEN_AMOUNT = 0.35; const TIERS = [ [144, 1.8, '144P'], [240, 1.7, '240P'], [360, 1.5, '360P'], [480, 1.35, '480P'], [720, 1.15, '720P'], [1080, 1.0, '1080P'], [1440, 0.9, '1440P'], [Infinity, 0.8, '4K+'] ]; const STORE_KEYS = [ 'ytSharpness', 'ytEnhancerStrength', 'ytEnhancerPreset', 'ytEnhancerAuto', 'ytEnhancerEnabled', 'ytEnhancerSharpen', 'ytEnhancerPosition' ]; const hasGM = typeof GM_getValue === 'function' && typeof GM_setValue === 'function'; const hasGM4 = !hasGM && typeof GM === 'object' && GM !== null && typeof GM.getValue === 'function' && typeof GM.setValue === 'function'; const LS_PREFIX = 'ytEnhancer:'; const gm4Cache = {}; function preloadStore() { return Promise.all( STORE_KEYS.map(key => Promise.resolve(GM.getValue(key)) .then(value => { if (value !== undefined) gm4Cache[key] = value; }) .catch(() => {}) ) ); } const store = { get(key, fallback) { try { if (hasGM) return GM_getValue(key, fallback); if (hasGM4) return key in gm4Cache ? gm4Cache[key] : fallback; const raw = localStorage.getItem(LS_PREFIX + key); return raw === null ? fallback : JSON.parse(raw); } catch (_) { return fallback; } }, set(key, value) { try { if (hasGM) { GM_setValue(key, value); } else if (hasGM4) { gm4Cache[key] = value; Promise.resolve(GM.setValue(key, value)).catch(() => {}); } else { localStorage.setItem(LS_PREFIX + key, JSON.stringify(value)); } } catch (_) {} }, remove(key) { try { if (hasGM) { if (typeof GM_deleteValue === 'function') GM_deleteValue(key); } else if (hasGM4) { delete gm4Cache[key]; if (typeof GM.deleteValue === 'function') { Promise.resolve(GM.deleteValue(key)).catch(() => {}); } } else { localStorage.removeItem(LS_PREFIX + key); } } catch (_) {} } }; const state = { strength: DEFAULT_STRENGTH, preset: 'custom', auto: false, enabled: true, sharpen: false, video: null, width: 0, height: 0, position: null, hoverOrigin: null, expandedH: EXPANDED_H_FALLBACK }; const ui = {}; const sharp = { canvas: null, gl: null, uPx: null, uK: null, video: null, ro: null, running: false, useVfc: false, handle: 0, layout: '', colorKey: '', dirty: true, failed: false }; let drag = null; let restoreTimer = null; let toastTimer = null; let rescanTimer = null; let collapseTimer = null; let watchedPlayer = null; let playerClassObserver = null; let playerChildObserver = null; function clamp(value, min, max) { return Math.min(Math.max(value, min), max); } function el(tag, props = {}, children = []) { const node = document.createElement(tag); Object.assign(node, props); node.append(...children.filter(Boolean)); return node; } function loadSettings() { const legacy = store.get('ytSharpness', undefined); if (legacy !== undefined) { if (store.get('ytEnhancerStrength', undefined) === undefined) { store.set('ytEnhancerStrength', legacy); } store.remove('ytSharpness'); } const saved = Number(store.get('ytEnhancerStrength', DEFAULT_STRENGTH)); state.strength = clamp( Number.isFinite(saved) ? Math.round(saved) : DEFAULT_STRENGTH, 0, 100 ); const preset = store.get('ytEnhancerPreset', 'custom'); state.preset = PRESET_NAMES.includes(preset) ? preset : 'custom'; if (state.preset !== 'custom') { state.strength = PRESETS[state.preset]; } state.auto = store.get('ytEnhancerAuto', false) === true; state.enabled = store.get('ytEnhancerEnabled', true) !== false; state.sharpen = store.get('ytEnhancerSharpen', false) === true; } function getVideo() { return ( document.querySelector('video.html5-main-video') || document.querySelector('video') ); } function getPlayer() { return document.querySelector('.html5-video-player'); } function isAdShowing() { const player = getPlayer(); return !!player && player.classList.contains('ad-showing'); } function getResolution(video) { if (!video) return null; const w = video.videoWidth || 0; const h = video.videoHeight || 0; return w && h ? { w, h } : null; } function getP(video) { const r = getResolution(video); return r ? Math.min(r.w, r.h) : 0; } function getTier(video) { const p = getP(video); return p ? TIERS.find(([max]) => p <= max) : null; } function getEffectiveStrength() { if (!state.auto) return state.strength; const tier = getTier(state.video); const multiplier = tier ? tier[1] : 1; return clamp(Math.round(AUTO_BASE * multiplier), 0, 100); } function isSharpening(video) { const p = getP(video); return ( state.enabled && state.sharpen && !isAdShowing() && p > 0 && p <= SHARPEN_MAX_P ); } function isWorking() { const video = state.video; return ( state.enabled && !isAdShowing() && !!video && video.isConnected && !!getResolution(video) && (getEffectiveStrength() > 0 || isSharpening(video)) ); } function getColorParams(amount) { const n = amount / 100; return { contrast: 1 + n * 0.3, brightness: 1 - n * 0.012, saturate: 1 + n * 0.035 }; } function createSvgFilter() { if (document.getElementById(SVG_ID)) return; const NS = 'http://www.w3.org/2000/svg'; const svg = document.createElementNS(NS, 'svg'); svg.id = SVG_ID; svg.setAttribute('width', '0'); svg.setAttribute('height', '0'); svg.setAttribute('aria-hidden', 'true'); svg.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;'; const filter = document.createElementNS(NS, 'filter'); filter.id = FILTER_ID; filter.setAttribute('color-interpolation-filters', 'sRGB'); filter.setAttribute('x', '0'); filter.setAttribute('y', '0'); filter.setAttribute('width', '1'); filter.setAttribute('height', '1'); const a = SHARPEN_AMOUNT; const center = (1 + 4 * a).toFixed(2); const convolve = document.createElementNS(NS, 'feConvolveMatrix'); convolve.setAttribute('order', '3'); convolve.setAttribute('preserveAlpha', 'true'); convolve.setAttribute( 'kernelMatrix', `0 ${-a} 0 ${-a} ${center} ${-a} 0 ${-a} 0` ); filter.appendChild(convolve); svg.appendChild(filter); document.body.appendChild(svg); } function buildFilterValue(video, useSvgSharpen = true) { if (!state.enabled || isAdShowing()) return ''; const amount = getEffectiveStrength(); const parts = []; if (useSvgSharpen && isSharpening(video)) { parts.push(`url(#${FILTER_ID})`); } if (amount > 0) { const c = getColorParams(amount); parts.push( `contrast(${c.contrast.toFixed(3)}) ` + `brightness(${c.brightness.toFixed(3)}) ` + `saturate(${c.saturate.toFixed(3)})` ); } return parts.join(' '); } const SHARP_VS = 'attribute vec2 p;varying vec2 v;' + 'void main(){v=p*.5+.5;gl_Position=vec4(p,0.,1.);}'; const SHARP_FS = 'precision mediump float;' + 'uniform sampler2D t;uniform vec2 px;uniform float a;uniform vec3 k;' + 'varying vec2 v;' + 'void main(){' + 'vec3 c=texture2D(t,v).rgb;' + 'vec3 s=texture2D(t,v+vec2(px.x,0.)).rgb+texture2D(t,v-vec2(px.x,0.)).rgb' + '+texture2D(t,v+vec2(0.,px.y)).rgb+texture2D(t,v-vec2(0.,px.y)).rgb;' + 'c=clamp(c*(1.+4.*a)-a*s,0.,1.);' + 'c=clamp((c-.5)*k.x+.5,0.,1.);' + 'c=clamp(c*k.y,0.,1.);' + 'float l=dot(c,vec3(.2126,.7152,.0722));' + 'c=clamp(mix(vec3(l),c,k.z),0.,1.);' + 'gl_FragColor=vec4(c,1.);}'; function initSharpGL() { if (sharp.gl) return true; if (sharp.failed) return false; try { const canvas = document.createElement('canvas'); canvas.id = CANVAS_ID; canvas.style.cssText = 'position:absolute;pointer-events:none;display:none;z-index:1;'; const gl = canvas.getContext('webgl', { alpha: false, antialias: false, depth: false, stencil: false, powerPreference: 'low-power' }); if (!gl) throw new Error('WebGL unavailable'); const compile = (type, src) => { const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { throw new Error(gl.getShaderInfoLog(shader)); } return shader; }; const program = gl.createProgram(); gl.attachShader(program, compile(gl.VERTEX_SHADER, SHARP_VS)); gl.attachShader(program, compile(gl.FRAGMENT_SHADER, SHARP_FS)); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error('Shader link failed'); } gl.useProgram(program); gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW ); const loc = gl.getAttribLocation(program, 'p'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); gl.bindTexture(gl.TEXTURE_2D, gl.createTexture()); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.uniform1i(gl.getUniformLocation(program, 't'), 0); gl.uniform1f(gl.getUniformLocation(program, 'a'), SHARPEN_AMOUNT); sharp.uK = gl.getUniformLocation(program, 'k'); gl.uniform3f(sharp.uK, 1, 1, 1); sharp.colorKey = ''; sharp.uPx = gl.getUniformLocation(program, 'px'); sharp.canvas = canvas; sharp.gl = gl; canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); failSharpGL(); }); return true; } catch (_) { sharp.failed = true; sharp.gl = null; return false; } } function failSharpGL() { sharp.failed = true; sharp.gl = null; stopSharpGL(); applyEnhancement(); } function stopSharpLoop() { if (sharp.running && sharp.handle) { try { if (sharp.useVfc && sharp.video) { sharp.video.cancelVideoFrameCallback(sharp.handle); } else { cancelAnimationFrame(sharp.handle); } } catch (_) {} } sharp.running = false; sharp.handle = 0; } function hideSharpCanvas() { if (sharp.canvas) sharp.canvas.style.display = 'none'; } function stopSharpGL() { stopSharpLoop(); sharp.video = null; if (sharp.ro) sharp.ro.disconnect(); hideSharpCanvas(); } function watchSharpResize(video) { if (typeof ResizeObserver !== 'function') return; if (!sharp.ro) { sharp.ro = new ResizeObserver(() => { sharp.dirty = true; if (sharp.video) syncSharpLayout(sharp.video); }); } sharp.ro.disconnect(); sharp.ro.observe(video); } function syncSharpLayout(video, force) { const canvas = sharp.canvas; const parent = video.parentNode; if (!canvas || !parent) return; if (canvas.parentNode !== parent) { parent.insertBefore(canvas, video.nextSibling); force = true; } if (!force && !sharp.dirty) return; sharp.dirty = false; const cs = getComputedStyle(video); const layout = [ cs.width, cs.height, cs.left, cs.top, cs.transform, cs.transformOrigin, cs.objectFit ].join('|'); if (layout === sharp.layout) return; sharp.layout = layout; const c = canvas.style; c.width = cs.width; c.height = cs.height; c.left = cs.left; c.top = cs.top; c.transform = cs.transform === 'none' ? '' : cs.transform; c.transformOrigin = cs.transformOrigin; c.objectFit = cs.objectFit; } function redrawSharp(video) { if (sharp.running && sharp.video === video) drawSharp(video); } function updateSharpColor(video) { if (!sharp.gl) return; const c = getColorParams(getEffectiveStrength()); const key = `${c.contrast}|${c.brightness}|${c.saturate}`; if (key === sharp.colorKey) return; sharp.colorKey = key; sharp.gl.uniform3f(sharp.uK, c.contrast, c.brightness, c.saturate); redrawSharp(video); } function startSharpGL(video) { if (!initSharpGL()) return false; if (sharp.running && sharp.video === video) return true; stopSharpLoop(); sharp.video = video; sharp.running = true; sharp.layout = ''; sharp.dirty = true; hideSharpCanvas(); watchSharpResize(video); scheduleSharpFrame(); return true; } function scheduleSharpFrame() { const video = sharp.video; if (!sharp.running || !video) return; const tick = () => { if (!sharp.running) return; drawSharp(video); scheduleSharpFrame(); }; if (typeof video.requestVideoFrameCallback === 'function') { sharp.useVfc = true; sharp.handle = video.requestVideoFrameCallback(tick); } else { sharp.useVfc = false; sharp.handle = requestAnimationFrame(tick); } } function drawSharp(video) { const { gl, canvas } = sharp; if (!gl || video.readyState < 2 || !video.videoWidth) return; if (!video.parentNode) return; syncSharpLayout(video); const w = video.videoWidth; const h = video.videoHeight; if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; gl.viewport(0, 0, w, h); gl.uniform2f(sharp.uPx, 1 / w, 1 / h); } try { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video); } catch (_) { failSharpGL(); return; } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); if (canvas.style.display) canvas.style.display = ''; } function applyEnhancement(video = getVideo()) { if (video) { state.video = video; const sharpOn = isSharpening(video); const useGL = sharpOn ? startSharpGL(video) : (stopSharpGL(), false); if (useGL) updateSharpColor(video); const value = useGL ? '' : buildFilterValue(video); if (value) { video.style.setProperty('filter', value, 'important'); } else { video.style.removeProperty('filter'); } video._ytEnhApplied = video.style.getPropertyValue('filter'); } updateUI(); } function watchVideoStyle(video) { if (video._ytEnhStyleObs) return; video._ytEnhStyleObs = new MutationObserver(() => { if (video !== state.video) return; if (sharp.running && sharp.video === video) { sharp.dirty = true; syncSharpLayout(video); } const current = video.style.getPropertyValue('filter'); if (current !== (video._ytEnhApplied || '')) { applyEnhancement(video); } }); video._ytEnhStyleObs.observe(video, { attributes: true, attributeFilter: ['style'] }); } function setEnabled(on) { state.enabled = on; store.set('ytEnhancerEnabled', on); applyEnhancement(); } function setAuto(on) { state.auto = on; store.set('ytEnhancerAuto', on); if (on && !state.enabled) { state.enabled = true; store.set('ytEnhancerEnabled', true); } applyEnhancement(); } function setSharpen(on) { state.sharpen = on; store.set('ytEnhancerSharpen', on); if (on) showToast('Sharpen uses more hardware and may lag on very old PCs'); applyEnhancement(); } function setPreset(preset) { if (state.auto) return; state.preset = preset; if (preset !== 'custom') { state.strength = PRESETS[preset]; } store.set('ytEnhancerPreset', state.preset); store.set('ytEnhancerStrength', state.strength); applyEnhancement(); } function setStrength(value, persist = true) { if (state.auto) return; state.strength = clamp(Math.round(Number(value) || 0), 0, 100); state.preset = 'custom'; if (persist) { store.set('ytEnhancerStrength', state.strength); store.set('ytEnhancerPreset', 'custom'); } applyEnhancement(); } function resetStrength() { if (state.auto) return; setStrength(DEFAULT_STRENGTH, true); showToast(`Enhancer reset to ${DEFAULT_STRENGTH}%`); } function buildStatus(effective) { const res = getResolution(state.video); const tier = getTier(state.video); const parts = []; parts.push(!state.enabled ? 'OFF' : state.auto ? 'AUTO' : 'MANUAL'); if (!res) { parts.push('NO VIDEO'); } else { parts.push(state.auto && tier ? tier[2] : `${res.w}×${res.h}`); } if (state.enabled) { parts.push(isAdShowing() ? 'AD (paused)' : `${effective}%`); } if (state.sharpen && state.enabled && !isAdShowing()) { parts.push(isSharpening(state.video) ? 'SHARP' : 'SHARP N/A'); } return parts.join(' • '); } function updateUI() { if (!ui.panel) return; const effective = getEffectiveStrength(); const set = (node, prop, value) => { if (node[prop] !== value) node[prop] = value; }; set(ui.slider, 'value', String(state.auto ? effective : state.strength)); set(ui.slider, 'disabled', state.auto); set(ui.preset, 'value', state.preset); set(ui.preset, 'disabled', state.auto); set(ui.enabled, 'checked', state.enabled); set(ui.auto, 'checked', state.auto); set(ui.sharpen, 'checked', state.sharpen); set( ui.value, 'textContent', !state.enabled ? 'OFF' : state.auto ? `AUTO ${effective}%` : `${state.strength}%` ); set(ui.status, 'textContent', buildStatus(effective)); const working = isWorking(); ui.panel.classList.toggle('active', working); set( ui.handle, 'title', working ? 'Enhancer active • drag to move • Alt+E toggle, Alt+↑/↓ strength' : 'Enhancer off • drag to move • Alt+E toggle, Alt+↑/↓ strength' ); } function showToast(text) { const host = document.fullscreenElement || document.body; if (!ui.toast) { ui.toast = el('div', { className: 'yt-enhancer-toast' }); } ui.toast.textContent = text; if (ui.toast.parentNode !== host) { host.appendChild(ui.toast); } ui.toast.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => { ui.toast.classList.remove('show'); }, 1800); } function setPanelPosition(left, top) { ui.panel.style.transform = `translate3d(${Math.round(left)}px, ${Math.round(top)}px, 0)`; } function getPanelPosition() { if (!ui.panel) return null; if (state.hoverOrigin) { return { left: Math.round(state.hoverOrigin.left), top: Math.round(state.hoverOrigin.top) }; } const rect = ui.panel.getBoundingClientRect(); if (!rect.width) return null; return { left: Math.round(rect.left), top: Math.round(rect.top) }; } function saveNormalPosition() { if (!ui.panel || document.fullscreenElement) return; const position = getPanelPosition(); if (!position) return; state.position = position; store.set('ytEnhancerPosition', position); } function loadPosition() { const saved = store.get('ytEnhancerPosition', null); if ( saved && Number.isFinite(saved.left) && Number.isFinite(saved.top) ) { state.position = { left: saved.left, top: saved.top }; } } function keepInsideScreen() { if (!ui.panel || document.fullscreenElement || state.hoverOrigin) return; const rect = ui.panel.getBoundingClientRect(); if (!rect.width) return; const left = clamp(rect.left, 0, Math.max(0, window.innerWidth - COLLAPSED)); const top = clamp(rect.top, 0, Math.max(0, window.innerHeight - COLLAPSED)); if (Math.round(rect.left) !== Math.round(left) || Math.round(rect.top) !== Math.round(top)) { setPanelPosition(left, top); } } function restoreNormalPosition() { if (!ui.panel || document.fullscreenElement || drag || state.hoverOrigin) return; if (!state.position) loadPosition(); if (state.position) { setPanelPosition(state.position.left, state.position.top); } else { setPanelPosition( window.innerWidth - EDGE_GAP - COLLAPSED, window.innerHeight - EDGE_GAP - COLLAPSED ); } requestAnimationFrame(keepInsideScreen); } function expandIntoView() { if (!ui.panel || drag || state.hoverOrigin || document.fullscreenElement) return; const rect = ui.panel.getBoundingClientRect(); if (!rect.width) return; const origin = { left: rect.left, top: rect.top }; const left = clamp(origin.left, 0, Math.max(0, window.innerWidth - EXPANDED_W)); const top = clamp(origin.top, 0, Math.max(0, window.innerHeight - state.expandedH)); if (left !== origin.left || top !== origin.top) { state.hoverOrigin = origin; setPanelPosition(left, top); } } function collapseBack() { if (!state.hoverOrigin) return; const origin = state.hoverOrigin; state.hoverOrigin = null; setPanelPosition(origin.left, origin.top); } function toggleOpen() { const open = ui.panel.classList.toggle('open'); if (open) expandIntoView(); else collapseBack(); } function closePanel() { if (!ui.panel) return; ui.panel.classList.remove('open'); if (!ui.panel.matches(':hover')) collapseBack(); } function measureExpandedHeight() { if (!ui.content || !ui.panel) return; const h = ui.content.offsetHeight; if (!h) return; state.expandedH = h; ui.panel.style.setProperty('--exp-h', `${h}px`); } function createStyles() { if (document.getElementById(STYLE_ID)) return; const P = `#${PANEL_ID}`; const style = document.createElement('style'); style.id = STYLE_ID; style.textContent = ` ${P} { position: fixed; top: 0; left: 0; z-index: 2147483647; width: ${COLLAPSED}px; height: ${COLLAPSED}px; box-sizing: border-box; --exp-h: ${EXPANDED_H_FALLBACK}px; --drop: 0 4px 14px rgba(0, 0, 0, 0.40); --glow: 0 0 0 0 transparent; background: rgba(15, 15, 18, 0.96); border: 1px solid rgba(255, 255, 255, 0.10); border-radius: 14px; box-shadow: var(--glow), var(--drop); color: #f4f4f5; overflow: hidden; will-change: transform; font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif; user-select: none; -webkit-user-select: none; cursor: default; transition: width 0.16s ease, height 0.16s ease, transform 0.16s ease, box-shadow 0.16s ease, border-color 0.16s ease; } ${P} * { user-select: none !important; -webkit-user-select: none !important; } ${P}:hover, ${P}.open { width: ${EXPANDED_W}px; height: var(--exp-h); --drop: 0 8px 24px rgba(0, 0, 0, 0.45); } ${P}.active { --glow: 0 0 10px rgba(74, 222, 128, 0.55); border-color: rgba(74, 222, 128, 0.70); } ${P}.dragging { width: ${COLLAPSED}px; height: ${COLLAPSED}px; --drop: 0 0 0 0 transparent; transition: none; } ${P} .yt-enhancer-drag-handle { position: absolute; top: 0; left: 0; width: ${COLLAPSED}px; height: ${COLLAPSED}px; display: flex; align-items: center; justify-content: center; box-sizing: border-box; color: #ffffff; font-size: 21px; font-weight: 500; cursor: grab; opacity: 0.92; z-index: 10; touch-action: none; transition: color 0.16s ease, text-shadow 0.16s ease; } ${P}.active .yt-enhancer-drag-handle { color: #86efac; text-shadow: 0 0 8px rgba(74, 222, 128, 0.90); } ${P} .yt-enhancer-drag-handle:hover { opacity: 0.65; } ${P} .yt-enhancer-drag-handle:active { cursor: grabbing; } ${P} .yt-enhancer-drag-handle:focus-visible, ${P} .yt-enhancer-preset:focus-visible { outline: 2px solid rgba(255, 255, 255, 0.7); outline-offset: -3px; } ${P} .yt-enhancer-content { position: absolute; top: 0; left: ${COLLAPSED}px; width: ${EXPANDED_W - COLLAPSED}px; padding: 13px 14px 12px 10px; box-sizing: border-box; opacity: 0; visibility: hidden; pointer-events: none; transition: opacity 0.10s ease, visibility 0.10s ease; } ${P}:hover .yt-enhancer-content, ${P}.open .yt-enhancer-content { opacity: 1; visibility: visible; pointer-events: auto; } ${P}.dragging .yt-enhancer-content { opacity: 0; visibility: hidden; pointer-events: none; } ${P} .yt-enhancer-header { display: flex; align-items: center; justify-content: space-between; height: 27px; margin-bottom: 8px; } ${P} .yt-enhancer-title-wrap { display: flex; align-items: center; gap: 7px; min-width: 0; } ${P} .yt-enhancer-dot { flex: 0 0 7px; width: 7px; height: 7px; border-radius: 50%; background: rgba(255, 255, 255, 0.22); transition: background 0.16s ease, box-shadow 0.16s ease; } ${P}.active .yt-enhancer-dot { background: #4ade80; box-shadow: 0 0 8px rgba(74, 222, 128, 0.90); } ${P} .yt-enhancer-title { font-size: 14px; font-weight: 650; letter-spacing: 0.1px; white-space: nowrap; } ${P} .yt-enhancer-preset { width: 100%; height: 30px; box-sizing: border-box; margin-bottom: 9px; padding: 0 9px; border: 1px solid rgba(255, 255, 255, 0.10); border-radius: 8px; outline: none; background: #202024; color: #f2f2f2; font-size: 11px; cursor: pointer; appearance: auto; transition: opacity 0.12s ease; } ${P} .yt-enhancer-preset:hover:not(:disabled) { background: #28282d; } ${P} .yt-enhancer-preset:focus { border-color: rgba(255, 255, 255, 0.22); } ${P} .yt-enhancer-preset:disabled { opacity: 0.38; cursor: not-allowed; } ${P} .yt-enhancer-slider-row { display: flex; align-items: center; gap: 8px; margin-bottom: 5px; } ${P} .yt-enhancer-value { flex: 0 0 auto; min-width: 58px; text-align: right; white-space: nowrap; font-size: 11px; font-weight: 600; color: rgba(255, 255, 255, 0.70); } ${P} .yt-enhancer-slider { flex: 1 1 auto; min-width: 0; height: 18px; margin: 0; padding: 0; appearance: none; -webkit-appearance: none; background: transparent; cursor: pointer; transition: opacity 0.12s ease; } ${P} .yt-enhancer-slider:disabled { opacity: 0.30; cursor: not-allowed; } ${P} .yt-enhancer-slider::-webkit-slider-runnable-track { height: 4px; border-radius: 999px; background: rgba(255, 255, 255, 0.16); } ${P} .yt-enhancer-slider::-webkit-slider-thumb { appearance: none; -webkit-appearance: none; width: 13px; height: 13px; margin-top: -4.5px; border: 0; border-radius: 50%; background: #ffffff; box-shadow: 0 1px 5px rgba(0, 0, 0, 0.45); } ${P} .yt-enhancer-slider::-moz-range-track { height: 4px; border-radius: 999px; background: rgba(255, 255, 255, 0.16); } ${P} .yt-enhancer-slider::-moz-range-thumb { width: 13px; height: 13px; border: 0; border-radius: 50%; background: #ffffff; box-shadow: 0 1px 5px rgba(0, 0, 0, 0.45); } ${P} .yt-enhancer-row { display: flex; align-items: center; justify-content: space-between; min-height: 28px; padding: 0 1px; } ${P} .yt-enhancer-row-title { position: relative; display: flex; align-items: center; gap: 6px; font-size: 11px; font-weight: 600; color: rgba(255, 255, 255, 0.92); } ${P} .yt-enhancer-info { position: relative; display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; flex: 0 0 16px; box-sizing: border-box; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 50%; background: rgba(255, 255, 255, 0.10); color: rgba(255, 255, 255, 0.90); font-size: 10px; font-weight: 700; line-height: 14px; cursor: help; } ${P} .yt-enhancer-info:hover { background: rgba(255, 255, 255, 0.18); } ${P} .yt-enhancer-tooltip { position: absolute; left: -50px; bottom: 23px; width: 190px; padding: 7px 8px; box-sizing: border-box; background: rgba(20, 20, 23, 0.99); border: 1px solid rgba(255, 255, 255, 0.14); border-radius: 7px; color: rgba(255, 255, 255, 0.85); font-size: 10px; font-weight: 400; line-height: 13px; white-space: normal; text-align: left; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.48); opacity: 0; visibility: hidden; pointer-events: none; transform: translateY(3px); transition: opacity 0.10s ease, visibility 0.10s ease, transform 0.10s ease; z-index: 100; } ${P} .yt-enhancer-info:hover .yt-enhancer-tooltip { opacity: 1; visibility: visible; transform: translateY(0); } ${P} .yt-enhancer-warning { margin: 0 0 2px 1px; font-size: 10px; line-height: 13px; font-weight: 500; color: #fbbf24; white-space: normal; } ${P} .yt-enhancer-switch { position: relative; flex: 0 0 auto; width: 34px; height: 19px; margin-left: 8px; } ${P} .yt-enhancer-switch input { position: absolute; opacity: 0; width: 0; height: 0; } ${P} .yt-enhancer-switch-track { position: absolute; inset: 0; border-radius: 999px; background: rgba(255, 255, 255, 0.14); cursor: pointer; transition: background 0.12s ease; } ${P} .yt-enhancer-switch-track::after { content: ""; position: absolute; top: 3px; left: 3px; width: 13px; height: 13px; border-radius: 50%; background: rgba(255, 255, 255, 0.78); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35); transition: transform 0.12s ease; } ${P} .yt-enhancer-switch input:checked + .yt-enhancer-switch-track { background: rgba(255, 255, 255, 0.34); } ${P} .yt-enhancer-switch input:checked + .yt-enhancer-switch-track::after { transform: translateX(15px); background: #ffffff; } ${P} .yt-enhancer-switch input:focus-visible + .yt-enhancer-switch-track { outline: 2px solid rgba(255, 255, 255, 0.7); outline-offset: 2px; } ${P} .yt-enhancer-status { margin-top: 3px; font-size: 10px; line-height: 13px; color: rgba(255, 255, 255, 0.45); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: 0.1px; } .yt-enhancer-toast { position: fixed; top: 84px; left: 50%; z-index: 2147483647; padding: 7px 12px; border-radius: 8px; background: rgba(15, 15, 18, 0.92); color: #ffffff; font: 600 13px Inter, -apple-system, "Segoe UI", Roboto, Arial, sans-serif; pointer-events: none; opacity: 0; transform: translateX(-50%); transition: opacity 0.15s ease; } .yt-enhancer-toast.show { opacity: 1; } @media (prefers-reduced-motion: reduce) { ${P}, ${P} .yt-enhancer-content, ${P} .yt-enhancer-drag-handle, ${P} .yt-enhancer-dot, ${P} .yt-enhancer-tooltip, ${P} .yt-enhancer-switch-track, ${P} .yt-enhancer-switch-track::after, .yt-enhancer-toast { transition: none !important; } } `; document.head.appendChild(style); } function createSwitch(ariaLabel) { const input = el('input', { type: 'checkbox' }); input.setAttribute('aria-label', ariaLabel); const toggle = el('label', { className: 'yt-enhancer-switch' }, [ input, el('span', { className: 'yt-enhancer-switch-track' }) ]); return { input, toggle }; } function createSwitchRow(label, tip) { const { input, toggle } = createSwitch(label); const title = el('div', { className: 'yt-enhancer-row-title' }, [label]); if (tip) { title.append( el('span', { className: 'yt-enhancer-info', textContent: '?' }, [ el('span', { className: 'yt-enhancer-tooltip', textContent: tip }) ]) ); } return { input, row: el('div', { className: 'yt-enhancer-row' }, [title, toggle]) }; } function setupDragging(handle) { const flushPending = () => { if (!drag) return; drag.raf = 0; if (drag.pending) { setPanelPosition(drag.pending.left, drag.pending.top); drag.pending = null; } }; const finishDrag = event => { if (!drag) return; const { moved, pointerId, raf, pending, origin } = drag; if (raf) cancelAnimationFrame(raf); if (pending) setPanelPosition(pending.left, pending.top); drag = null; try { handle.releasePointerCapture?.(pointerId); } catch (_) {} ui.panel.classList.remove('dragging'); if (!moved && origin && !state.hoverOrigin) { state.hoverOrigin = origin; } if (moved) { ui.panel.classList.remove('open'); keepInsideScreen(); saveNormalPosition(); } else if ( event && event.type === 'pointerup' && event.pointerType !== 'mouse' ) { toggleOpen(); return; } if (ui.panel.matches(':hover')) expandIntoView(); }; handle.addEventListener('pointerdown', event => { if (event.button !== 0 || document.fullscreenElement) return; if (drag) finishDrag(null); event.preventDefault(); const iconRect = ui.handle.getBoundingClientRect(); const origin = state.hoverOrigin; state.hoverOrigin = null; clearTimeout(collapseTimer); ui.panel.classList.add('dragging'); const rect = { left: iconRect.left, top: iconRect.top }; drag = { origin, pointerId: event.pointerId, offsetX: event.clientX - rect.left, offsetY: event.clientY - rect.top, startX: event.clientX, startY: event.clientY, moved: false, pending: null, raf: 0 }; try { handle.setPointerCapture?.(event.pointerId); } catch (_) {} setPanelPosition(rect.left, rect.top); }); handle.addEventListener('pointermove', event => { if (!drag || event.pointerId !== drag.pointerId) return; if (event.pointerType === 'mouse' && event.buttons === 0) { finishDrag(event); return; } event.preventDefault(); if ( Math.abs(event.clientX - drag.startX) > 4 || Math.abs(event.clientY - drag.startY) > 4 ) { drag.moved = true; } drag.pending = { left: clamp( event.clientX - drag.offsetX, 0, Math.max(0, window.innerWidth - COLLAPSED) ), top: clamp( event.clientY - drag.offsetY, 0, Math.max(0, window.innerHeight - COLLAPSED) ) }; if (!drag.raf) drag.raf = requestAnimationFrame(flushPending); }); handle.addEventListener('pointerup', finishDrag); handle.addEventListener('pointercancel', finishDrag); handle.addEventListener('lostpointercapture', finishDrag); handle.addEventListener('dragstart', event => event.preventDefault()); handle.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggleOpen(); } }); window.addEventListener('blur', () => finishDrag(null)); } function createPanel() { if (document.getElementById(PANEL_ID)) return; createStyles(); createSvgFilter(); loadPosition(); ui.handle = el('div', { className: 'yt-enhancer-drag-handle', textContent: '⟡', title: 'Drag to move' }); ui.handle.setAttribute('role', 'button'); ui.handle.setAttribute('tabindex', '0'); ui.handle.setAttribute('aria-label', 'Video Enhancer (drag to move, Enter to open)'); ui.dot = el('span', { className: 'yt-enhancer-dot' }); const enabledSwitch = createSwitch('Enabled'); enabledSwitch.toggle.title = 'Turn the enhancer on or off (Alt+E)'; ui.enabled = enabledSwitch.input; const header = el('div', { className: 'yt-enhancer-header' }, [ el('div', { className: 'yt-enhancer-title-wrap' }, [ ui.dot, el('div', { className: 'yt-enhancer-title', textContent: 'Video Enhancer' }) ]), enabledSwitch.toggle ]); ui.preset = el( 'select', { className: 'yt-enhancer-preset' }, [ ['custom', 'Custom'], ['natural', 'Natural'], ['clear', 'Clear'], ['strong', 'Strong'] ].map(([value, text]) => el('option', { value, textContent: text })) ); ui.preset.setAttribute('aria-label', 'Preset'); ui.slider = el('input', { className: 'yt-enhancer-slider', type: 'range', min: '0', max: '100', step: '1', title: `Double-click to reset to ${DEFAULT_STRENGTH}% • Alt+↑/↓ adjusts by 5` }); ui.slider.setAttribute('aria-label', 'Enhancement strength'); ui.value = el('div', { className: 'yt-enhancer-value' }); const sliderRow = el('div', { className: 'yt-enhancer-slider-row' }, [ ui.slider, ui.value ]); const autoRow = createSwitchRow( 'Auto Enhance', 'Picks the strength from the video resolution. Lower quality gets more.' ); const sharpenRow = createSwitchRow( 'Sharpen', 'Sharpens the picture. Works at 1080p and below.' ); const warning = el('div', { className: 'yt-enhancer-warning', textContent: '⚠ Uses more hardware. May lag on old PCs.' }); ui.auto = autoRow.input; ui.sharpen = sharpenRow.input; ui.status = el('div', { className: 'yt-enhancer-status' }); ui.content = el('div', { className: 'yt-enhancer-content' }, [ header, ui.preset, sliderRow, autoRow.row, sharpenRow.row, warning, ui.status ]); ui.panel = el('div', { id: PANEL_ID }, [ui.handle, ui.content]); document.body.appendChild(ui.panel); updateUI(); measureExpandedHeight(); requestAnimationFrame(measureExpandedHeight); ui.slider.addEventListener('input', () => { setStrength(ui.slider.value, false); }); ui.slider.addEventListener('change', () => { setStrength(ui.slider.value, true); }); ui.slider.addEventListener('dblclick', resetStrength); ui.preset.addEventListener('change', () => setPreset(ui.preset.value)); ui.enabled.addEventListener('change', () => setEnabled(ui.enabled.checked)); ui.auto.addEventListener('change', () => setAuto(ui.auto.checked)); ui.sharpen.addEventListener('change', () => setSharpen(ui.sharpen.checked)); ui.panel.addEventListener('pointerenter', () => { clearTimeout(collapseTimer); expandIntoView(); }); ui.panel.addEventListener('pointerleave', () => { clearTimeout(collapseTimer); collapseTimer = setTimeout(() => { if (!drag && !ui.panel.classList.contains('open')) collapseBack(); }, 120); }); ui.panel.addEventListener('focusin', event => { if (event.target.matches(':focus-visible')) { ui.panel.classList.add('open'); expandIntoView(); } }); ui.panel.addEventListener('focusout', event => { if (ui.panel.contains(event.relatedTarget)) return; closePanel(); }); ui.panel.addEventListener('keydown', event => { if (event.key === 'Escape') { closePanel(); if (document.activeElement) document.activeElement.blur(); } }); document.addEventListener( 'pointerdown', event => { if ( ui.panel.classList.contains('open') && !ui.panel.contains(event.target) ) { closePanel(); } }, true ); setupDragging(ui.handle); restoreNormalPosition(); } function syncVideo(video) { const r = getResolution(video); const changed = video !== state.video || (r && (r.w !== state.width || r.h !== state.height)); if (changed) { state.video = video; state.width = r ? r.w : 0; state.height = r ? r.h : 0; applyEnhancement(video); } else { updateUI(); } } function setupVideoEvents(video) { if (video.dataset.ytEnhancerEvents === '1') return; video.dataset.ytEnhancerEvents = '1'; video.addEventListener('loadedmetadata', () => syncVideo(video)); video.addEventListener('resize', () => syncVideo(video)); const redraw = () => redrawSharp(video); video.addEventListener('seeked', redraw); video.addEventListener('loadeddata', redraw); video.addEventListener('canplay', redraw); video.addEventListener('emptied', () => { if (sharp.video === video) hideSharpCanvas(); }); watchVideoStyle(video); } function watchPlayer() { const player = getPlayer(); if (!player || player === watchedPlayer) return; if (playerClassObserver) playerClassObserver.disconnect(); if (playerChildObserver) playerChildObserver.disconnect(); watchedPlayer = player; playerClassObserver = new MutationObserver(() => { sharp.dirty = true; applyEnhancement(); }); playerClassObserver.observe(player, { attributes: true, attributeFilter: ['class'] }); const container = player.querySelector('.html5-video-container') || player; playerChildObserver = new MutationObserver(() => { clearTimeout(rescanTimer); rescanTimer = setTimeout(scanVideo, 250); }); playerChildObserver.observe(container, { childList: true }); } function scanVideo() { watchPlayer(); const video = getVideo(); if (!video) return; setupVideoEvents(video); syncVideo(video); } function setupYouTubeNavigation() { document.addEventListener('yt-navigate-finish', () => { setTimeout(() => { scanVideo(); restoreNormalPosition(); }, 100); }); document.addEventListener('yt-player-updated', scanVideo); } function handleFullscreenChange() { sharp.dirty = true; if (!ui.panel) return; if (document.fullscreenElement) { if (ui.panel.style.display !== 'none') saveNormalPosition(); ui.panel.style.display = 'none'; return; } ui.panel.style.display = ''; if (ui.toast && ui.toast.parentNode && ui.toast.parentNode !== document.body) { document.body.appendChild(ui.toast); } clearTimeout(restoreTimer); restoreTimer = setTimeout(() => { restoreTimer = null; restoreNormalPosition(); }, 80); } function handleHotkey(event) { if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; const target = event.target; if ( target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) ) { return; } switch (event.code) { case 'KeyE': setEnabled(!state.enabled); showToast(state.enabled ? 'Enhancer ON' : 'Enhancer OFF'); break; case 'ArrowUp': case 'ArrowDown': { if (state.auto) { showToast('Auto is on: turn it off to adjust strength'); break; } if (!state.enabled) setEnabled(true); setStrength(state.strength + (event.code === 'ArrowUp' ? 5 : -5)); showToast(`Enhancer: ${state.strength}%`); break; } default: return; } event.preventDefault(); } function initialize() { loadSettings(); createPanel(); document.addEventListener('fullscreenchange', handleFullscreenChange); document.addEventListener('keydown', handleHotkey, true); window.addEventListener( 'resize', () => { sharp.dirty = true; keepInsideScreen(); }, { passive: true } ); setupYouTubeNavigation(); scanVideo(); [500, 1500, 3000].forEach(ms => setTimeout(scanVideo, ms)); } function start() { (hasGM4 ? preloadStore() : Promise.resolve()).then(initialize); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', start, { once: true }); } else { start(); } })();