').replace('min(uv, vec2f(u.maxX, u.maxY))', 'uv')
.replaceAll('vec2f(u.cropX, u.cropY)', 'vec2f(1.0)').replace('vec2f(u.offX, u.offY)', 'vec2f(0.0)'),
});
const flatLayout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {} },
{ binding: 2, visibility: GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX, buffer: { type: 'uniform' } },
],
});
const pipeline = (mod, entryPoint, target, pipelineLayout) => device.createRenderPipeline({
layout: pipelineLayout,
vertex: { module: mod, entryPoint: 'vs_main' },
fragment: { module: mod, entryPoint, targets: [{ format: target }] },
primitive: { topology: 'triangle-list' },
});
const flatPipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [flatLayout] });
const timed = device.features.has('timestamp-query');
return {
querySet: timed ? device.createQuerySet({ type: 'timestamp', count: 2 }) : null,
resolveBuffer: timed ? device.createBuffer({ size: 16, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC }) : null,
readBuffer: timed ? device.createBuffer({ size: 16, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }) : null,
layout,
sampler: device.createSampler({ magFilter: 'linear', minFilter: 'linear' }),
pipeline: pipeline(module, 'fs_main', format, filterLayout),
midPipeline: pipeline(module, 'fs_main', 'rgb10a2unorm', filterLayout),
downPipeline: pipeline(module, 'fs_down', 'rgb10a2unorm', filterLayout),
flatPipeline: pipeline(flatModule, 'fs_main', format, flatPipelineLayout),
flatLayout,
down: null, downView: null, flatGroup: null,
// Copy path: the frame is first copied to an ordinary texture (see gpuCheckImport)
flatMidPipeline: pipeline(flatModule, 'fs_main', 'rgb10a2unorm', flatPipelineLayout),
flatDownPipeline: pipeline(flatModule, 'fs_down', 'rgb10a2unorm', flatPipelineLayout),
checkPipeline: pipeline(module, 'fs_down', 'rgba8unorm', filterLayout),
src: null, srcGroup: null,
easuPipeline: pipeline(upscaleModule, 'fs_easu', 'rgb10a2unorm', 'auto'),
rcasPipeline: pipeline(upscaleModule, 'fs_rcas', format, 'auto'),
uniformBuffer: device.createBuffer({ size: 112, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }),
dirty: true,
mid: null, midView: null, easuGroup: null,
up: null, upView: null, rcasGroup: null,
last: 0, interval: 16.7, tick: 0, slow: 0, gpuMs: 0, upscaleOff: false,
};
}
// Canvas buffer size = on-screen size in device pixels, so the shader does the scaling
// (both ways) instead of the compositor. fill: stretch mode, each axis scales on its own.
function gpuTargetSize(srcW, srcH, boxW, boxH, allowUp, fill) {
if (!boxW || !boxH) return [srcW, srcH];
let sx = Math.min(boxW / srcW, 4096 / srcW), sy = Math.min(boxH / srcH, 4096 / srcH);
if (!fill) sx = sy = Math.min(sx, sy);
const up = Math.max(sx, sy) > 1.02;
if (up && !allowUp) return [srcW, srcH];
// Within 2% of the box: no scaling. The canvas takes the part of the frame that
// fits, so the 1920x1082 Boosteroid sends for a 1080-line screen is shown pixel for
// pixel instead of being squeezed by two lines.
if (!up && Math.min(sx, sy) > 0.98) return [Math.min(srcW, boxW), Math.min(srcH, boxH)];
// The canvas is centred in its box: an odd leftover would put it on a half pixel
// and the browser would blur the whole image to draw it there.
const fit = (size, box) => {
const t = Math.round(size);
return t < box && (box - t) % 2 ? t + (t < size ? 1 : -1) : t;
};
return [fit(srcW * sx, boxW), fit(srcH * sy, boxH)];
}
// Boosteroid sends some sizes with two extra rows below the picture (1920x1082 for 1080
// lines, 3200x1802 for 1800). They hold no image and decode as a green band. known: the
// sizes the server streams, as a Set of 'WxH'. Returns the size of the real picture,
// which starts at the top left of the frame.
function gpuVisibleSize(w, h, known) {
if (known.has(w + 'x' + h)) return [w, h];
for (const [dw, dh] of [[0, 2], [2, 0], [2, 2]]) {
if (known.has((w - dw) + 'x' + (h - dh))) return [w - dw, h - dh];
}
return [w, h];
}
// Chrome hands some video frames to WebGPU with the colour plane out of place: on the
// 1920x1082 Boosteroid stream, importExternalTexture returns colours 12 rows too low and
// a green band at the top, while the video element and a 2D canvas show the same frame
// correctly. This draws a 64x32 strip from the top of the frame both ways and returns
// their mean difference per channel (0 to 255): about 1 when the import is right.
async function gpuCheckImport(device, g, frame, srcW, srcH) {
const W = 64, H = 32, x0 = Math.max(0, (srcW >> 1) - 32);
const ref = new OffscreenCanvas(W, H).getContext('2d', { willReadFrequently: true });
ref.drawImage(frame, x0, 0, W, H, 0, 0, W, H);
const a = ref.getImageData(0, 0, W, H).data;
const u = new Float32Array(28);
u[20] = W / srcW; u[21] = H / srcH; u[22] = 1; u[23] = 1; u[24] = x0 / srcW;
const uniformBuffer = device.createBuffer({ size: 112, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
device.queue.writeBuffer(uniformBuffer, 0, u);
const texture = device.createTexture({ size: [W, H], format: 'rgba8unorm', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC });
const out = device.createBuffer({ size: W * H * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{ view: texture.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 1 } }],
});
pass.setPipeline(g.checkPipeline);
pass.setBindGroup(0, device.createBindGroup({
layout: g.layout,
entries: [
{ binding: 0, resource: g.sampler },
{ binding: 1, resource: device.importExternalTexture({ source: frame }) },
{ binding: 2, resource: { buffer: uniformBuffer } },
],
}));
pass.draw(6);
pass.end();
encoder.copyTextureToBuffer({ texture }, { buffer: out, bytesPerRow: W * 4 }, [W, H]);
device.queue.submit([encoder.finish()]);
await out.mapAsync(GPUMapMode.READ);
const b = new Uint8Array(out.getMappedRange());
let sum = 0;
for (let i = 0; i < a.length; i += 4) sum += Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]);
out.unmap();
texture.destroy();
uniformBuffer.destroy();
out.destroy();
return sum / (W * H * 3);
}
// source: HTMLVideoElement or VideoFrame (srcW x srcH). The filters always read an image
// at the size they output, so they look the same at every stream resolution:
// canvas = source: filter. canvas larger: filter -> EASU -> RCAS.
// canvas smaller: downscale -> filter.
// canvas within 2% of the source: filter, cropped to the canvas (no scaling at all).
// visW x visH: the picture inside the frame (see gpuVisibleSize); sizes are compared to it.
// copy: read the frame through copyExternalImageToTexture instead of importing it (see
// gpuCheckImport). One more GPU copy per frame, and the passes read an ordinary texture.
// Owns uniform slots 0, 1 (the resolution the filter pass works at), 14 and 18 to 25.
function gpuDrawFrame(device, context, g, source, srcW, srcH, uniforms, visW = srcW, visH = srcH, copy = false) {
const target = context.getCurrentTexture();
const near = Math.abs(target.width - visW) <= visW * 0.02 && Math.abs(target.height - visH) <= visH * 0.02;
const upscale = !near && (target.width > visW || target.height > visH);
const minify = !near && !upscale && (target.width < visW || target.height < visH);
const resW = upscale ? visW : target.width, resH = upscale ? visH : target.height;
// The part of the texture shown, in UV: the whole picture, or when it is cropped
// rather than scaled, a canvas-sized window in its middle. Slots 20, 21: its size.
// Slots 24, 25: its top left corner. Slots 22, 23: the last picture pixel, which
// no tap may pass.
const shownW = near ? Math.min(visW, target.width) : visW, shownH = near ? Math.min(visH, target.height) : visH;
const cropX = Math.fround(shownW / srcW), cropY = Math.fround(shownH / srcH);
const offX = Math.fround((visW - shownW) / 2 / srcW), offY = Math.fround((visH - shownH) / 2 / srcH);
const maxX = Math.fround((visW - 0.5) / srcW), maxY = Math.fround((visH - 0.5) / srcH);
g.path = upscale ? 'upscale' : minify ? 'downscale' : (shownW < visW || shownH < visH ? 'crop' : 'direct');
if (visW !== srcW || visH !== srcH) g.path += ' -pad';
if (copy) g.path += ' copy';
// Slot 14: 1 = upscaling (RCAS sharpens). Slots 18, 19: tap offset of the downscale
// pass in UV. In source pixels: ratio - 1 up to 0.5, which removes one-pixel
// patterns (moire) from a ratio of 1.5, then a quarter of the ratio past 2. Wider
// would remove them at every ratio but blur: at 1.33 it keeps 44% of the finest
// detail instead of 60%.
const mode = upscale ? 1 : 0;
const tap = (vis, dst, src) => {
if (!minify || dst >= vis) return 0;
const r = vis / dst;
return Math.fround((r < 2 ? Math.min(0.5, r - 1) : r / 4) / src);
};
// The copied texture holds only the shown part, so its width is the picture's
const tapX = tap(visW, target.width, copy ? shownW : srcW), tapY = tap(visH, target.height, copy ? shownH : srcH);
if (g.dirty || uniforms[0] !== resW || uniforms[1] !== resH || uniforms[14] !== mode || uniforms[18] !== tapX || uniforms[19] !== tapY ||
uniforms[20] !== cropX || uniforms[21] !== cropY || uniforms[22] !== maxX || uniforms[23] !== maxY ||
uniforms[24] !== offX || uniforms[25] !== offY) {
uniforms[0] = resW;
uniforms[1] = resH;
uniforms[14] = mode;
uniforms[18] = tapX;
uniforms[19] = tapY;
uniforms[20] = cropX;
uniforms[21] = cropY;
uniforms[22] = maxX;
uniforms[23] = maxY;
uniforms[24] = offX;
uniforms[25] = offY;
device.queue.writeBuffer(g.uniformBuffer, 0, uniforms);
g.dirty = false;
}
const sized = (texture, w, h, format = 'rgb10a2unorm', usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING) => {
if (texture && texture.width === w && texture.height === h) return texture;
if (texture) texture.destroy();
return device.createTexture({ size: [w, h], format, usage });
};
let bindGroup;
if (copy) {
const src = sized(g.src, shownW, shownH, 'rgba8unorm', GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING);
if (src !== g.src) {
g.src = src;
g.srcGroup = device.createBindGroup({
layout: g.flatLayout,
entries: [
{ binding: 0, resource: g.sampler },
{ binding: 1, resource: src.createView() },
{ binding: 2, resource: { buffer: g.uniformBuffer } },
],
});
}
// copyExternalImageToTexture straight from the frame has the same colour offset
// (seen in a real session), so the frame goes through a 2D canvas, which the
// check found correct, and the canvas is copied.
if (!g.c2d || g.c2d.canvas.width !== shownW || g.c2d.canvas.height !== shownH) {
g.c2d = new OffscreenCanvas(shownW, shownH).getContext('2d', { alpha: false });
}
g.c2d.drawImage(source, Math.round((visW - shownW) / 2), Math.round((visH - shownH) / 2), shownW, shownH, 0, 0, shownW, shownH);
device.queue.copyExternalImageToTexture({ source: g.c2d.canvas }, { texture: src }, [shownW, shownH]);
bindGroup = g.srcGroup;
} else {
// An external texture expires after use: this bind group is rebuilt every frame
bindGroup = device.createBindGroup({
layout: g.layout,
entries: [
{ binding: 0, resource: g.sampler },
{ binding: 1, resource: device.importExternalTexture({ source }) },
{ binding: 2, resource: { buffer: g.uniformBuffer } },
],
});
}
if (upscale) {
const mid = sized(g.mid, visW, visH);
if (mid !== g.mid) {
g.mid = mid;
g.midView = mid.createView();
g.easuGroup = device.createBindGroup({
layout: g.easuPipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: g.midView }],
});
}
const up = sized(g.up, target.width, target.height);
if (up !== g.up) {
g.up = up;
g.upView = up.createView();
g.rcasGroup = device.createBindGroup({
layout: g.rcasPipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: g.upView }, { binding: 1, resource: { buffer: g.uniformBuffer } }],
});
}
}
if (minify) {
const down = sized(g.down, target.width, target.height);
if (down !== g.down) {
g.down = down;
g.downView = down.createView();
g.flatGroup = device.createBindGroup({
layout: g.flatLayout,
entries: [
{ binding: 0, resource: g.sampler },
{ binding: 1, resource: g.downView },
{ binding: 2, resource: { buffer: g.uniformBuffer } },
],
});
}
}
// Every 30th upscaled frame is timed on the GPU itself
const timed = upscale && g.querySet && ++g.tick % 30 === 0 && g.readBuffer.mapState === 'unmapped';
const encoder = device.createCommandEncoder();
const run = (view, pipeline, group, timestampWrites) => {
const pass = encoder.beginRenderPass({
colorAttachments: [{ view, loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 1 } }],
timestampWrites,
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, group);
pass.draw(6);
pass.end();
};
if (upscale) {
run(g.midView, copy ? g.flatMidPipeline : g.midPipeline, bindGroup, timed ? { querySet: g.querySet, beginningOfPassWriteIndex: 0 } : undefined);
run(g.upView, g.easuPipeline, g.easuGroup);
run(target.createView(), g.rcasPipeline, g.rcasGroup, timed ? { querySet: g.querySet, endOfPassWriteIndex: 1 } : undefined);
} else if (minify) {
run(g.downView, copy ? g.flatDownPipeline : g.downPipeline, bindGroup);
run(target.createView(), g.flatPipeline, g.flatGroup);
} else {
run(target.createView(), copy ? g.flatPipeline : g.pipeline, bindGroup);
}
if (timed) {
encoder.resolveQuerySet(g.querySet, 0, 2, g.resolveBuffer, 0);
encoder.copyBufferToBuffer(g.resolveBuffer, 0, g.readBuffer, 0, 16);
}
device.queue.submit([encoder.finish()]);
const now = performance.now();
if (g.last) g.interval += (Math.min(now - g.last, 50) - g.interval) * 0.1;
g.last = now;
// Guard: the three passes eating over half the frame interval, ten samples in a row,
// stops upscaling for the session. One-way.
if (timed) {
g.readBuffer.mapAsync(GPUMapMode.READ).then(() => {
const t = new BigInt64Array(g.readBuffer.getMappedRange());
const ms = Number(t[1] - t[0]) / 1e6;
g.readBuffer.unmap();
if (ms < 0 || ms > 1000) return;
g.gpuMs = ms;
g.slow = ms > g.interval * 0.5 ? g.slow + 1 : 0;
if (g.slow >= 10) g.upscaleOff = true;
}).catch(() => {});
}
}
// Fills the settings slots of the uniform block.
function packUniforms(config, data) {
const e = config.enhancer;
const f = config.filters;
data[2] = e.contrast || 1.0;
data[3] = e.saturation || 1.0;
data[4] = e.brightness || 1.0;
data[5] = f.gamma?.enabled ? f.gamma.value : 1.0;
data[6] = f.exposure?.enabled ? f.exposure.value : 0.0;
data[7] = f.vibrance?.enabled ? f.vibrance.amount : 0.0;
// Sharpness: combine enhancer base slider + CAS/USM advanced filters additively
const casUsm = f.enabled ? ((f.cas?.enabled ? f.cas.sharpness : 0) + (f.usm?.enabled ? f.usm.amount : 0)) : 0;
const baseSharp = e.enabled ? (e.sharpness || 0) : 0;
// Clamp to [0,1]: used as a mix() factor, >1 overshoots into halos
data[8] = Math.min(1.0, casUsm + baseSharp);
data[9] = f.denoise?.enabled ? f.denoise.strength : 0.0;
data[10] = f.clarity?.enabled ? f.clarity.amount : 0.0;
data[11] = f.deband?.enabled ? (f.deband.strength || 0.3) : 0.0;
data[12] = e.enabled ? 1.0 : 0.0;
data[13] = f.enabled ? 1.0 : 0.0;
data[15] = 0.0; // time (unused by the shader)
data[16] = ENV_PROFILE.isHighEnd ? 1.0 : 0.0; // qualityMode
data[17] = f.performanceMode ? 1.0 : 0.0; // performanceMode
}
// Worker renderer — WebGPU off the main thread.
// Frames go decoder -> MediaStreamTrackProcessor -> worker -> OffscreenCanvas, so
// frame pacing no longer depends on the page's main thread (which is busy with
// input events during mouse play). Chrome/Edge only; anything else, or any
// failure, falls back to the main-thread renderers below.
// Kill switch: localStorage.setItem('optimizer_worker', '0') + reload.
const WORKER_RENDERER = (() => {
try { return localStorage.getItem('optimizer_worker') !== '0'; } catch (e) { return true; }
})();
const KNOWN_STREAM_SIZES = new Set(SmartResolutionDetector.SUPPORTED_RESOLUTIONS.map(([w, h]) => w + 'x' + h));
function workerRendererMain() {
let device, context, gpu, canvas, format;
let active = false, generation = 0, frames = 0, maxGap = 0, lastDraw = 0, boxW = 0, boxH = 0, warned = false, statsAt = 0, allowUp = false, fill = false, frameColor = null, frameFormat = null, pending = 0, hitches = 0;
const uniforms = new Float32Array(28);
const fail = (e) => postMessage({ type: 'fail', message: String((e && e.message) || e) });
const configure = () => context.configure({ device, format, colorSpace: 'srgb', alphaMode: 'opaque' });
// Dev build only: brightness of the first and last four rows of a frame and how much
// each differs from the next one. Shows whether the two extra rows Boosteroid sends
// (1082 for 1080) are picture or padding.
let dev = false, probedW = 0, probedH = 0, known = new Set();
// 'WxH' -> true when importExternalTexture shows that frame size wrong
const copySizes = new Map();
async function checkImport(f, key) {
try {
const diff = await gpuCheckImport(device, gpu, f, f.displayWidth, f.displayHeight);
copySizes.set(key, diff > 8);
const v = f.visibleRect;
postMessage({ type: 'import-check', text: `${key} ${f.format} coded ${f.codedWidth}x${f.codedHeight} visible ${v.width}x${v.height}@${v.x},${v.y}: import differs from 2D canvas by ${diff.toFixed(1)} -> ${diff > 8 ? 'copy path' : 'direct import'}` });
} catch (e) {
postMessage({ type: 'import-check', text: key + ' check failed: ' + e.message });
} finally {
f.close();
}
}
async function probeEdges(f) {
try {
const w = f.displayWidth, h = f.displayHeight;
if (f.format !== 'NV12' && f.format !== 'I420') { postMessage({ type: 'edges', text: `${w}x${h} format ${f.format}` }); return; }
const rows = async (y) => {
const rect = { x: 0, y, width: w, height: 4 };
const buf = new Uint8Array(f.allocationSize({ rect }));
const layout = await f.copyTo(buf, { rect });
const { offset, stride } = layout[0];
const out = [];
for (let r = 0; r < 4; r++) {
let sum = 0, diff = 0;
for (let x = 0; x < w; x++) {
const v = buf[offset + r * stride + x];
sum += v;
if (r < 3) diff += Math.abs(v - buf[offset + (r + 1) * stride + x]);
}
out.push(`${(sum / w).toFixed(0)}${r < 3 ? '~' + (diff / w).toFixed(1) : ''}`);
}
return out.join(' ');
};
postMessage({ type: 'edges', text: `${w}x${h} top rows ${await rows(0)} | bottom rows ${await rows((h - 4) & ~1)}` });
} catch (e) {
postMessage({ type: 'edges', text: 'probe failed: ' + e.message });
} finally {
f.close();
}
}
function draw(frame) {
const w = frame.displayWidth, h = frame.displayHeight;
const [visW, visH] = gpuVisibleSize(w, h, known);
const key = w + 'x' + h;
if (!copySizes.has(key)) {
// Copy path until the check clears the direct import: no green frame meanwhile
copySizes.set(key, true);
checkImport(frame.clone(), key);
}
if (dev && (w !== probedW || h !== probedH)) {
probedW = w;
probedH = h;
probeEdges(frame.clone());
}
const off = gpu.upscaleOff;
const [targetW, targetH] = gpuTargetSize(visW, visH, boxW, boxH, allowUp && !off, fill);
if (canvas.width !== targetW || canvas.height !== targetH) {
canvas.width = targetW;
canvas.height = targetH;
configure();
}
gpuDrawFrame(device, context, gpu, frame, w, h, uniforms, visW, visH, copySizes.get(key));
if (frames % 64 === 0) {
frameColor = frame.colorSpace;
frameFormat = frame.format;
}
if (off && !warned) {
warned = true;
postMessage({ type: 'upscale-off' });
}
}
async function pump(readable, mine) {
const reader = readable.getReader();
let errors = 0, first = true;
try {
for (;;) {
const { value: frame, done } = await reader.read();
if (done) break;
let error = null, drawn = false;
if (active && mine === generation) {
try {
draw(frame);
drawn = true;
const now = performance.now();
if (lastDraw) {
maxGap = Math.max(maxGap, now - lastDraw);
// A frame shown more than 1.6 frame intervals after the previous one
if (now - lastDraw > gpu.interval * 1.6) hitches++;
}
lastDraw = now;
frames++;
errors = 0;
if (first) { first = false; postMessage({ type: 'frame' }); }
} catch (e) { error = e; }
}
// The decoder reuses a frame's surface as soon as the frame is closed, so a drawn
// frame stays open until the GPU has read it: closing early shows up as green
// garbage. Never more than 4 held, or the decoder's frame pool would stall.
if (drawn && pending < 4) {
pending++;
const release = () => { pending--; frame.close(); };
device.queue.onSubmittedWorkDone().then(release, release);
} else {
frame.close();
}
if (mine !== generation) { reader.cancel().catch(() => {}); return; }
// Transient GPU errors skip a frame; ~90 in a row is a dead pipeline
if (error && ++errors >= 90) throw error;
}
if (mine === generation) postMessage({ type: 'ended' });
} catch (e) { fail(e); }
}
onmessage = async ({ data: m }) => {
try {
if (m.type === 'init') {
canvas = m.canvas;
allowUp = m.upscale;
dev = m.dev;
known = new Set(m.sizes);
const adapter = await navigator.gpu.requestAdapter(m.adapterOptions);
if (!adapter) throw new Error('no WebGPU adapter');
device = await adapter.requestDevice({ requiredFeatures: adapter.features.has('timestamp-query') ? ['timestamp-query'] : [] });
device.lost.then((info) => fail('device lost: ' + info.message));
context = canvas.getContext('webgpu');
format = navigator.gpu.getPreferredCanvasFormat();
configure();
gpu = gpuCreatePipeline(device, m.shader, format, m.upscaleShader);
postMessage({ type: 'ready' });
} else if (m.type === 'uniforms') {
uniforms.set(m.data);
gpu.dirty = true;
active = m.active;
if (!active) lastDraw = 0;
} else if (m.type === 'box') {
boxW = m.w;
boxH = m.h;
fill = m.fill;
} else if (m.type === 'stream') {
pump(m.readable, ++generation);
} else if (m.type === 'stats') {
const now = performance.now();
postMessage({ type: 'stats', frames, maxGap, gpuMs: gpu.gpuMs, ms: now - statsAt, upscaleOff: gpu.upscaleOff, path: gpu.path, hitches,
color: frameColor ? [frameColor.primaries, frameColor.transfer, frameColor.matrix, frameColor.fullRange ? 'full' : 'limited', frameFormat].join('/') : '?' });
statsAt = now;
frames = 0;
maxGap = 0;
hitches = 0;
}
} catch (e) { fail(e); }
};
}
class WorkerVideoRenderer {
constructor() {
this.canvas = null;
this.videoElement = null;
this.worker = null;
this.isActive = false;
this.onFail = null;
this._running = false;
this._hasFrame = false;
this._track = null;
this._data = new Float32Array(28);
this._rebind = () => { try { this._bind(); } catch (e) { this._fail(e.message); } };
}
static supported(video) {
return WORKER_RENDERER && !!navigator.gpu &&
typeof MediaStreamTrackProcessor === 'function' &&
typeof HTMLCanvasElement.prototype.transferControlToOffscreen === 'function' &&
!!video.srcObject?.getVideoTracks?.()[0];
}
// Resolves true once the worker owns a working GPU pipeline and the stream.
init(videoElement) {
return new Promise((resolve) => {
let settled = false;
const done = (ok) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (!ok) this.destroy();
resolve(ok);
};
const timer = setTimeout(() => done(false), 4000);
try {
this.videoElement = videoElement;
const source = `${gpuCreatePipeline}\n${gpuTargetSize}\n${gpuVisibleSize}\n${gpuCheckImport}\n${gpuDrawFrame}\n(${workerRendererMain})()`;
const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
this.worker = new Worker(url);
URL.revokeObjectURL(url);
this.worker.onerror = (e) => (settled ? this._fail(e.message) : done(false));
this.worker.onmessage = ({ data: m }) => {
if (m.type === 'ready') {
try { this._bind(); done(true); } catch (e) { done(false); }
} else if (m.type === 'frame') {
this._hasFrame = true;
this._sync();
} else if (m.type === 'ended') {
// Track ended: show the raw video until a new track is bound
this._track = null;
this._hasFrame = false;
this._sync();
this._rebind();
} else if (m.type === 'stats') {
this._stats = m;
} else if (m.type === 'import-check') {
console.log('[Optimizer+] [Render] ' + m.text);
} else if (m.type === 'edges') {
report('[Optimizer+] [Render] edge rows (brightness~difference to next row): ' + m.text);
} else if (m.type === 'upscale-off') {
showNotification(t('upscaleOffNotif'));
} else if (m.type === 'fail') {
if (settled) this._fail(m.message); else done(false);
}
};
this.canvas = document.createElement('canvas');
this.canvas.id = 'optimizer-webgpu-canvas';
this.canvas.style.cssText = `
position: absolute; top: 0; left: 0;
width: 100%; height: 100%;
pointer-events: none;
object-fit: contain;
will-change: transform;
contain: strict;
display: none;
`;
const parent = videoElement.parentElement;
if (parent) {
parent.style.position = parent.style.position || 'relative';
parent.insertBefore(this.canvas, videoElement.nextSibling);
}
const offscreen = this.canvas.transferControlToOffscreen();
this.worker.postMessage({
type: 'init',
canvas: offscreen,
shader: WGSL_SHADER,
upscaleShader: WGSL_UPSCALE,
upscale: UPSCALE,
dev: DEV_BUILD,
sizes: [...KNOWN_STREAM_SIZES],
// Chrome on Windows ignores powerPreference and logs a warning (crbug.com/369219127)
adapterOptions: /Win/i.test(navigator.platform) ? {} : { powerPreference: 'high-performance' },
}, [offscreen]);
// A new srcObject (reconnect, 60<->120 FPS switch) carries a new track
videoElement.addEventListener('loadedmetadata', this._rebind);
this._boxObserver = observeDeviceBox(this.canvas, (w, h) => {
this._boxW = w;
this._boxH = h;
this.refreshBox();
});
} catch (e) {
done(false);
}
});
}
_bind() {
const track = this.videoElement?.srcObject?.getVideoTracks?.()[0];
if (!this.worker || !track || track === this._track || track.readyState !== 'live') return;
this._track = track;
this._hasFrame = false;
this._sync();
// maxBufferSize 1: a late worker gets the newest frame, never a backlog
const { readable } = new MediaStreamTrackProcessor({ track, maxBufferSize: 1 });
this.worker.postMessage({ type: 'stream', readable }, [readable]);
}
refreshBox() {
if (this.worker) this.worker.postMessage({ type: 'box', w: this._boxW || 0, h: this._boxH || 0, fill: CONFIG.display.stretchMode });
}
// Returns the last sample and requests the next one
poll() {
const s = this._stats;
if (this.worker) this.worker.postMessage({ type: 'stats' });
if (!s) return 'starting';
return `${Math.round(s.frames * 1000 / s.ms)} fps, max gap ${Math.round(s.maxGap)}ms, late frames ${s.hitches}, gpu ${s.gpuMs.toFixed(1)}ms${s.upscaleOff ? ', upscale stopped' : ''}, path ${s.path}, color ${s.color}`;
}
_fail(message) {
console.warn('[Optimizer+] Worker renderer failed, falling back to main thread:', message);
const onFail = this.onFail;
this.destroy();
if (onFail) onFail();
}
// The canvas replaces the video only while it actually has frames to show
_sync() {
if (!this.canvas || !this.videoElement) return;
const show = this.isActive && this._running && this._hasFrame;
const display = show ? 'block' : 'none';
const opacity = show ? '0.01' : '1';
if (this.canvas.style.display !== display) this.canvas.style.display = display;
if (this.videoElement.style.opacity !== opacity) this.videoElement.style.opacity = opacity;
}
_post() {
if (this.worker) this.worker.postMessage({ type: 'uniforms', data: this._data, active: this.isActive && this._running });
this._sync();
}
updateUniforms(config) {
this.isActive = config.enhancer.enabled || config.filters.enabled;
packUniforms(config, this._data);
this._post();
}
startRenderLoop() {
this._running = true;
this._post();
}
stopRenderLoop() {
this._running = false;
this._post();
}
destroy() {
if (this.videoElement) {
this.videoElement.removeEventListener('loadedmetadata', this._rebind);
this.videoElement.style.opacity = '1';
}
if (this._boxObserver) this._boxObserver.disconnect();
if (this.worker) this.worker.terminate();
if (this.canvas && this.canvas.parentElement) this.canvas.parentElement.removeChild(this.canvas);
this.worker = null;
this.canvas = null;
this.videoElement = null;
this._track = null;
this.onFail = null;
}
}
// WebGPUVideoRenderer — main-thread WebGPU (fallback when the worker path is unavailable)
class WebGPUVideoRenderer {
constructor() {
this.device = null;
this.context = null;
this.videoElement = null;
this.canvas = null;
this.animationId = null;
this.isActive = false;
this._attached = false;
this._lastConfig = null;
this._canvasFormat = null;
this._useRVFC = typeof HTMLVideoElement !== 'undefined' &&
'requestVideoFrameCallback' in HTMLVideoElement.prototype;
this._lastVideoTime = 0;
// True once GPU rendering has failed continuously; the raw video is shown instead
this._failOpen = false;
// Pre-allocated to avoid GC pressure in the render loop
this._uniformData = new Float32Array(28); // 112 bytes (WGSL-aligned struct)
}
async init(videoElement) {
if (!videoElement || this._attached) return false;
if (!navigator.gpu) {
console.error('[Optimizer+] WebGPU not available — Chrome 113+ / Edge 113+ required');
return false;
}
this.videoElement = videoElement;
try {
// Chrome on Windows ignores powerPreference and logs a warning (crbug.com/369219127)
const adapter = await navigator.gpu.requestAdapter(/Win/i.test(navigator.platform)
? {} : { powerPreference: 'high-performance' });
if (!adapter) {
console.error('[Optimizer+] No WebGPU adapter found');
return false;
}
this.device = await adapter.requestDevice({ requiredFeatures: adapter.features.has('timestamp-query') ? ['timestamp-query'] : [] });
this.device.lost.then((info) => {
console.warn('[Optimizer+] WebGPU device lost:', info.message);
this.stopRenderLoop();
if (this.videoElement) this.videoElement.style.opacity = '1';
if (this.canvas) this.canvas.style.display = 'none';
this._attached = false;
});
this.canvas = document.createElement('canvas');
this.canvas.id = 'optimizer-webgpu-canvas';
this.canvas.style.cssText = `
position: absolute; top: 0; left: 0;
width: 100%; height: 100%;
pointer-events: none;
object-fit: contain;
will-change: transform;
contain: strict;
`;
// Set initial size to match the streaming video to prevent low-resolution swap chain
const initialW = videoElement.videoWidth || 1920;
const initialH = videoElement.videoHeight || 1080;
this.canvas.width = initialW;
this.canvas.height = initialH;
const parent = videoElement.parentElement;
if (parent) {
parent.style.position = parent.style.position || 'relative';
parent.insertBefore(this.canvas, videoElement.nextSibling);
}
this.context = this.canvas.getContext('webgpu');
this._canvasFormat = navigator.gpu.getPreferredCanvasFormat();
this.context.configure({
device: this.device,
format: this._canvasFormat,
colorSpace: 'srgb',
alphaMode: 'opaque',
});
this._gpu = gpuCreatePipeline(this.device, WGSL_SHADER, this._canvasFormat, WGSL_UPSCALE);
this._boxObserver = observeDeviceBox(this.canvas, (w, h) => { this._boxW = w; this._boxH = h; });
this._attached = true;
console.log('[Optimizer+] WebGPU pipeline initialized (true zero-copy mode)');
return true;
} catch (e) {
console.error('[Optimizer+] WebGPU initialization failed, falling back to WebGL2:', e);
this.destroy();
return false;
}
}
updateUniforms(config) {
this._lastConfig = config;
if (!this.device) return;
const e = config.enhancer;
const f = config.filters;
const wasActive = this.isActive;
this.isActive = e.enabled || f.enabled;
// Guard style writes to avoid needless style recalculation
if (this.canvas) {
const targetDisplay = this.isActive ? 'block' : 'none';
if (this.canvas.style.display !== targetDisplay) {
this.canvas.style.display = targetDisplay;
}
}
if (!this.isActive && this.videoElement && this.videoElement.style.opacity !== '1') {
this.videoElement.style.opacity = '1';
}
if (this.isActive && !wasActive && !this.animationId) {
this.startRenderLoop();
}
const data = this._uniformData;
packUniforms(config, data);
if (this._gpu) this._gpu.dirty = true;
}
render() {
if (!this.isActive) return;
const video = this.videoElement;
if (!video || video.readyState < 2) return;
if (!this._useRVFC) {
if (video.currentTime === this._lastVideoTime) return;
this._lastVideoTime = video.currentTime;
}
const texW = video.videoWidth || 1920;
const texH = video.videoHeight || 1080;
if (!texW || !texH) return;
try {
const off = this._gpu.upscaleOff;
const [visW, visH] = gpuVisibleSize(texW, texH, KNOWN_STREAM_SIZES);
const [targetW, targetH] = gpuTargetSize(visW, visH, this._boxW, this._boxH, UPSCALE && !off, CONFIG.display.stretchMode);
if (this.canvas.width !== targetW || this.canvas.height !== targetH) {
this.canvas.width = targetW;
this.canvas.height = targetH;
this.context.configure({
device: this.device,
format: this._canvasFormat,
colorSpace: 'srgb',
alphaMode: 'opaque'
});
}
// Same import check as the worker renderer: copy path until cleared
const key = texW + 'x' + texH;
this._copySizes = this._copySizes || new Map();
if (!this._copySizes.has(key)) {
this._copySizes.set(key, true);
gpuCheckImport(this.device, this._gpu, video, texW, texH)
.then((diff) => {
this._copySizes.set(key, diff > 8);
console.log(`[Optimizer+] [Render] ${key} main-thread import differs from 2D canvas by ${diff.toFixed(1)}`);
})
.catch(() => {});
}
gpuDrawFrame(this.device, this.context, this._gpu, video, texW, texH, this._uniformData, visW, visH, this._copySizes.get(key));
if (off && !this._upscaleWarned) {
this._upscaleWarned = true;
showNotification(t('upscaleOffNotif'));
}
this._failStreak = 0;
if (video.style.opacity !== '0.01') {
video.style.opacity = '0.01';
}
} catch (e) {
// Skip frame on error — don't kill the loop
if (!this._errorLogged) {
console.warn('[Optimizer+] WebGPU render frame skipped:', e.message);
this._errorLogged = true;
setTimeout(() => { this._errorLogged = false; }, 5000);
}
// Fail-open: if rendering keeps failing (~90 frames) the canvas would freeze on the last
// frame while the hidden video keeps playing. Show the raw video, hide the canvas
// and stop the loop.
this._failStreak = (this._failStreak || 0) + 1;
if (this._failStreak >= 90) {
console.warn('[Optimizer+] WebGPU fail-open: rendu défaillant ~1.5s → vidéo brute affichée (filtres désactivés)');
this._failOpen = true;
this.stopRenderLoop();
if (this.videoElement) this.videoElement.style.opacity = '1';
if (this.canvas) this.canvas.style.display = 'none';
this._attached = false;
}
}
}
startRenderLoop() {
if (this.animationId) return;
// Never restart the loop after fail-open
if (this._failOpen) return;
const loop = () => {
this.render();
if (!this.isActive) {
this.animationId = null;
return;
}
if (this._useRVFC && this.videoElement) {
this.animationId = this.videoElement.requestVideoFrameCallback(loop);
} else {
this.animationId = requestAnimationFrame(loop);
}
};
if (this._useRVFC && this.videoElement) {
this.animationId = this.videoElement.requestVideoFrameCallback(loop);
} else {
this.animationId = requestAnimationFrame(loop);
}
console.log('[Optimizer+] WebGPU render loop started' +
(this._useRVFC ? ' (requestVideoFrameCallback sync)' : ' (VSync-aligned rAF)'));
}
stopRenderLoop() {
if (this.animationId) {
if (this._useRVFC && this.videoElement) {
this.videoElement.cancelVideoFrameCallback(this.animationId);
} else {
cancelAnimationFrame(this.animationId);
}
this.animationId = null;
}
}
destroy() {
this.stopRenderLoop();
if (this.videoElement) {
this.videoElement.style.opacity = '1';
}
if (this.canvas && this.canvas.parentElement) {
this.canvas.parentElement.removeChild(this.canvas);
}
if (this._boxObserver) this._boxObserver.disconnect();
if (this.device) {
this.device.destroy();
}
this._attached = false;
this.device = null;
this.context = null;
this.canvas = null;
this.videoElement = null;
}
}
// VideoEnhancer — picks and drives the active renderer
class VideoEnhancer {
constructor() {
this.enabled = CONFIG.enhancer.enabled;
this.filtersEnabled = CONFIG.filters.enabled;
this.videoElement = null;
// Renderer order: worker WebGPU, main-thread WebGPU, WebGL2
this._workerRenderer = null;
this._workerFailed = false;
this._gpuRenderer = new WebGPUVideoRenderer();
this._glRenderer = new WebGLVideoRenderer();
this._webgpuActive = false;
this._webglActive = false;
this._initInProgress = null; // Guards against a concurrent WebGPU init (async)
}
refreshBox() {
if (this._workerRenderer) this._workerRenderer.refreshBox();
}
describe() {
const r = this._getActiveRenderer();
if (!r) return 'render none';
const size = r.canvas ? `canvas ${r.canvas.width}x${r.canvas.height}` : 'no canvas';
if (r === this._workerRenderer) return `render worker ${r.poll()}, ${size}`;
return `render ${r === this._gpuRenderer ? 'webgpu-main' : 'webgl2'}, ${size}`;
}
_getActiveRenderer() {
if (this._workerRenderer) return this._workerRenderer;
if (this._webgpuActive) return this._gpuRenderer;
if (this._webglActive) return this._glRenderer;
return null;
}
applyToVideo(videoElement) {
if (!videoElement) return;
this.videoElement = videoElement;
const activeRenderer = this._getActiveRenderer();
// Handle video element replacement (e.g., stream reconnect)
if (activeRenderer && activeRenderer.videoElement !== videoElement) {
console.log('[Optimizer+] Video element changed. Rebinding renderer...');
activeRenderer.destroy();
this._workerRenderer = null;
this._webgpuActive = false;
this._webglActive = false;
}
if (this._getActiveRenderer()) {
this._getActiveRenderer().updateUniforms(CONFIG);
this._getActiveRenderer().startRenderLoop();
return;
}
// The video observer can call applyToVideo twice before the async WebGPU init
// resolves: a second init would leak a canvas and a GPU device
if (this._initInProgress === videoElement) return;
if (!this._workerFailed && WorkerVideoRenderer.supported(videoElement)) {
this._initInProgress = videoElement;
const renderer = new WorkerVideoRenderer();
const fallBack = () => {
this._workerRenderer = null;
this._workerFailed = true;
this.applyToVideo(videoElement);
};
renderer.onFail = fallBack;
renderer.init(videoElement).then((ok) => {
this._initInProgress = null;
if (!ok) return fallBack();
this._workerRenderer = renderer;
renderer.updateUniforms(CONFIG);
renderer.startRenderLoop();
console.log('[Optimizer+] Worker renderer active (off-main-thread WebGPU)');
});
return;
}
if (navigator.gpu) {
this._initInProgress = videoElement;
this._gpuRenderer.init(videoElement)
.then((success) => {
this._initInProgress = null;
if (success) {
this._webgpuActive = true;
this._gpuRenderer.updateUniforms(CONFIG);
this._gpuRenderer.startRenderLoop();
console.log('[Optimizer+] WebGPU shaders active (true zero-copy)');
} else {
this._tryWebGL2Fallback(videoElement);
}
})
.catch((err) => {
this._initInProgress = null;
console.error('[Optimizer+] WebGPU init promise rejected, falling back to WebGL2:', err);
this._tryWebGL2Fallback(videoElement);
});
} else {
this._tryWebGL2Fallback(videoElement);
}
}
_tryWebGL2Fallback(videoElement) {
const ok = this._glRenderer.init(videoElement);
if (ok) {
this._webglActive = true;
this._glRenderer.updateUniforms(CONFIG);
this._glRenderer.startRenderLoop();
console.log('[Optimizer+] WebGL2 fallback active');
} else {
console.warn('[Optimizer+] No GPU renderer available — filters disabled');
}
}
updateFilterString() {
const r = this._getActiveRenderer();
if (r) r.updateUniforms(CONFIG);
}
applyFiltersToAllVideos() {
const r = this._getActiveRenderer();
if (r) r.updateUniforms(CONFIG);
}
removeFiltersFromAllVideos() {
const r = this._getActiveRenderer();
if (r) {
r.stopRenderLoop();
if (r.videoElement) r.videoElement.style.opacity = '1';
if (r.canvas) r.canvas.style.display = 'none';
}
}
// After a tab switch: restart the loop. The renderer decides what is shown; a renderer
// that gave up (fail-open, lost context) or filters the user turned off keep the raw video.
ensureActive() {
const r = this._getActiveRenderer();
if (!r || !r.canvas || !r.videoElement || r._failOpen) return;
if (r.gl && r.gl.isContextLost()) return;
r.updateUniforms(CONFIG);
r.startRenderLoop();
}
updateSettings(settings) {
Object.assign(CONFIG.enhancer, settings);
this.updateFilterString();
saveConfig(true);
}
updateFilterSettings(filterName, settings) {
if (CONFIG.filters[filterName]) {
Object.assign(CONFIG.filters[filterName], settings);
// Moving a filter slider enables that filter; otherwise the slider appears to do nothing
if (!CONFIG.filters[filterName].enabled) {
CONFIG.filters[filterName].enabled = true;
const cb = document.querySelector(`.optimizer-filter-checkbox[data-filter="${filterName}"]`);
if (cb) cb.checked = true;
}
this.updateFilterString();
saveConfig(true);
}
}
applyPreset(presetName) {
const preset = FILTER_PRESETS[presetName];
if (!preset) return;
CONFIG.filters.preset = presetName;
// Automatically turn on advanced filters when a preset is applied
if (presetName !== 'custom') {
CONFIG.filters.enabled = true;
this.filtersEnabled = true;
}
if (preset.enhancer) Object.assign(CONFIG.enhancer, preset.enhancer);
if (preset.filters) {
Object.keys(preset.filters).forEach(key => {
if (CONFIG.filters[key]) Object.assign(CONFIG.filters[key], preset.filters[key]);
});
}
this.updateFilterString();
saveConfig(true);
console.log('[Optimizer+] Preset "' + (preset.name || presetName) + '" applied');
}
toggle(enabled) {
this.enabled = enabled;
CONFIG.enhancer.enabled = enabled;
this.updateFilterString();
saveConfig(true);
}
toggleFilters(enabled) {
this.filtersEnabled = enabled;
CONFIG.filters.enabled = enabled;
this.updateFilterString();
saveConfig(true);
}
toggleFilter(filterName, enabled) {
if (CONFIG.filters[filterName]) {
CONFIG.filters[filterName].enabled = enabled;
this.updateFilterString();
saveConfig(true);
}
}
}
const videoEnhancer = new VideoEnhancer();
// UI INJECTION - Adds the panel to the Boosteroid menu
// Hide Boosteroid's own "Brighter image" option: it conflicts with the script's filters
function hideBoosteroidBrighterOption() {
// Only rows that hold a toggle, not the stats panels
const switchBlocks = document.querySelectorAll('.menu_switch_block');
switchBlocks.forEach(block => {
const hasToggle = block.querySelector('input[type="checkbox"], .switch, .toggle');
if (!hasToggle) return;
if (block.closest('.optimizer-injected')) return;
const text = block.textContent?.toLowerCase() || '';
// Label of the "Brighter image" option in each language
const brighterKeywords = [
'brighter image', 'image plus lumineuse', 'helleres bild',
'imagen m\u00E1s brillante', 'immagine pi\u00F9 luminosa', 'imagem mais brilhante',
'\u044F\u0440\u0447\u0435 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435', 'ja\u015Bniejszy obraz', '\u044F\u0441\u043A\u0440\u0430\u0432\u0456\u0448\u0435 \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F',
'daha parlak', 'sv\u011Btlej\u0161\u00ED obraz', 'f\u00E9nyesebb k\u00E9p', 'imagine mai luminoas\u0103'
];
const isBrighterOption = brighterKeywords.some(kw => text.includes(kw.toLowerCase()));
if (isBrighterOption) {
block.style.display = 'none';
block.style.visibility = 'hidden';
block.style.pointerEvents = 'none';
}
});
}
function findInsertionPoint(menu) {
const menuBlocks = menu.querySelectorAll('.menu_block');
if (menuBlocks.length > 0) {
return menuBlocks[menuBlocks.length - 1];
}
const menuTitles = menu.querySelectorAll('.menu_title');
if (menuTitles.length > 0) {
return menuTitles[menuTitles.length - 1];
}
return null;
}
// GAME SESSION DETECTION
function isDashboardPage() {
const path = window.location.pathname.toLowerCase();
if (path.includes('streaming.html') || path.includes('/streaming/')) {
return false;
}
const dashboardPatterns = [
'/dashboard',
'/library',
'/store',
'/settings',
'/profile',
'/subscription',
'/support'
];
if (path === '/' || path === '') {
return true;
}
return dashboardPatterns.some(pattern => path.includes(pattern));
}
function isStreamingPage() {
const path = window.location.pathname.toLowerCase();
const href = window.location.href.toLowerCase();
if (path.includes('streaming.html') || href.includes('sessionid=')) {
return true;
}
const gamePatterns = ['/play/', '/game/', '/stream/', '/session/', '/run/'];
return gamePatterns.some(pattern => path.includes(pattern));
}
// Returns the open Boosteroid options menu, or null. Desktop: #menu.menu_desktop, mobile: .m_lan_wrapper, both shown with display:block
function findOpenOptionsMenu() {
const mobileMenus = document.querySelectorAll('.m_lan_wrapper');
for (const mobileMenu of mobileMenus) {
const style = window.getComputedStyle(mobileMenu);
if (style.display !== 'none' && mobileMenu.offsetParent !== null) {
return mobileMenu;
}
}
const boosteroidMenu = document.querySelector('#menu.menu_desktop');
if (boosteroidMenu) {
const style = window.getComputedStyle(boosteroidMenu);
if (style.display !== 'none' && boosteroidMenu.offsetParent !== null) {
return boosteroidMenu;
}
}
const menuById = document.getElementById('menu');
if (menuById && menuById.classList.contains('menu_desktop')) {
const style = window.getComputedStyle(menuById);
if (style.display !== 'none') {
return menuById;
}
}
// Fallback: search by structure (menu_title inside a menu container)
const menuTitles = document.querySelectorAll('.menu_title');
for (const title of menuTitles) {
let parent = title.parentElement;
while (parent && parent !== document.body) {
if (parent.id === 'menu' || parent.classList.contains('menu_desktop') ||
parent.classList.contains('m_lan_wrapper')) {
const style = window.getComputedStyle(parent);
if (style.display !== 'none' && parent.offsetParent !== null) {
return parent;
}
}
parent = parent.parentElement;
}
}
return null;
}
function cleanupUI() {
const elementsToRemove = [
'.optimizer-injected',
'#optimizer-notification',
'#optimizer-dashboard-widget',
'.optimizer-overlay',
'#opt-notification-style'
];
elementsToRemove.forEach(selector => {
const elements = document.querySelectorAll(selector);
elements.forEach(el => el.remove());
});
// Also detach the dashboard widget's document handlers
if (typeof detachWidgetEvents === 'function') {
try { detachWidgetEvents(); } catch (_) { }
}
// WebGPU: stop render loop when leaving game
if (!SessionState.isGameActive && typeof videoEnhancer !== 'undefined') {
videoEnhancer.removeFiltersFromAllVideos();
}
SessionState.isUIInjected = false;
console.log('[Optimizer+] UI nettoy\u00E9e');
}
// Injects the UI only during a game session and while the options menu is open
function injectUI() {
// INITIAL CHECK
const onStreaming = isStreamingPage();
console.log('[Optimizer+] Page de streaming:', onStreaming);
console.log('[Optimizer+] URL:', window.location.href);
if (isDashboardPage() && !onStreaming) {
console.log('[Optimizer+] Dashboard détecté - UI désactivée');
return;
}
// MAIN OBSERVER - Tracks game and menu state
let lastUrl = window.location.href;
let isInjecting = false; // Mutex against double injection
let _lastCheckTime = 0; // Throttle: keeps this off the main thread during play
let throttleTimer = null;
// Style/class changes are observed on the menu containers only, so in-game DOM
// churn (cursor, overlays) never reaches a script callback.
const watchedMenus = new WeakSet();
const menuObserver = new MutationObserver(() => setTimeout(checkAndInject, 50));
const watchMenus = () => {
document.querySelectorAll('#menu, .m_lan_wrapper').forEach((el) => {
if (watchedMenus.has(el)) return;
watchedMenus.add(el);
menuObserver.observe(el, { attributes: true, attributeFilter: ['style', 'class'] });
});
};
const checkAndInject = () => {
const now = Date.now();
const timeSinceLast = now - _lastCheckTime;
if (timeSinceLast < 500) {
// Throttled: schedule one check at the end of the window
if (throttleTimer) clearTimeout(throttleTimer);
throttleTimer = setTimeout(() => {
throttleTimer = null;
checkAndInject();
}, 500 - timeSinceLast);
return;
}
_lastCheckTime = now;
if (throttleTimer) {
clearTimeout(throttleTimer);
throttleTimer = null;
}
watchMenus();
if (isInjecting) return;
isInjecting = true;
try {
SessionState.selfHeal();
const onStreaming = isStreamingPage();
if (!onStreaming && isDashboardPage()) {
if (SessionState.isUIInjected) {
cleanupUI();
}
return;
}
// Streaming enhancements start with the streaming page, before the menu exists
if (onStreaming && !StreamingEnhancements.active) {
StreamingEnhancements.enable();
}
const menu = findOpenOptionsMenu();
if (menu && !SessionState.isUIInjected) {
if (!isUIFullyInjected(menu)) {
if (document.querySelector('.optimizer-injected')) {
cleanupUI();
}
createOptimizerUI(menu);
hideBoosteroidBrighterOption();
SessionState.isUIInjected = true;
SessionState.isMenuOpen = true;
SessionState.isGameActive = true;
SessionState.retryCount = 0;
console.log('[Optimizer+] [OK] UI injectée dans le menu Boosteroid');
}
} else if (menu && SessionState.isUIInjected) {
// Boosteroid may have partially destroyed the UI
if (!isUIFullyInjected(menu)) {
console.log('[Optimizer+] UI partiellement détruite détectée lors du check, réinjection...');
cleanupUI();
createOptimizerUI(menu);
}
hideBoosteroidBrighterOption();
SessionState.isUIInjected = true;
SessionState.isMenuOpen = true;
SessionState.retryCount = 0;
} else if (!menu && SessionState.isUIInjected) {
// Menu closed: clean up to avoid orphans
cleanupUI();
SessionState.isMenuOpen = false;
}
} finally {
isInjecting = false;
}
};
const handleUrlChange = () => {
if (window.location.href !== lastUrl) {
lastUrl = window.location.href;
console.log('[Optimizer+] Navigation d\u00E9tect\u00E9e:', window.location.pathname);
if (SessionState.hasSessionChanged()) {
console.log('[Optimizer+] Nouveau jeu d\u00E9tect\u00E9 - r\u00E9initialisation');
SessionState.forceReinject();
setTimeout(checkAndInject, 500);
return;
}
if (isDashboardPage()) {
cleanupUI();
SessionState.reset();
} else {
setTimeout(checkAndInject, 500);
}
}
};
// OBSERVERS
const domObserver = new MutationObserver((mutations) => {
handleUrlChange();
let shouldCheck = false;
const len = mutations.length;
for (let i = 0; i < len; i++) {
const mutation = mutations[i];
if (mutation.type === 'childList') {
const added = mutation.addedNodes;
const addedLen = added.length;
for (let j = 0; j < addedLen; j++) {
const node = added[j];
if (node.nodeType === 1) { // Node.ELEMENT_NODE
const id = node.id;
const classList = node.classList;
const name = node.nodeName;
if (id === 'menu' ||
name === 'VIDEO' ||
(classList && (
classList.contains('menu_desktop') ||
classList.contains('menu_block') ||
classList.contains('m_lan_wrapper') ||
classList.contains('menu_title') ||
classList.contains('menu_switch_block')
))) {
shouldCheck = true;
break;
}
}
}
if (shouldCheck) break;
}
}
if (shouldCheck) {
// Let the DOM settle
setTimeout(checkAndInject, 50);
}
});
domObserver.observe(document.body, {
childList: true,
subtree: true
});
// Clicks and taps may open the menu
const clickHandler = () => {
if (document.pointerLockElement) return; // in-game click: the menu cannot open
setTimeout(checkAndInject, 300);
};
document.addEventListener('click', clickHandler, { passive: true });
document.addEventListener('touchend', clickHandler, { passive: true });
const keyHandler = (e) => {
if (e.key === 'Escape') {
setTimeout(checkAndInject, 100);
}
};
document.addEventListener('keydown', keyHandler);
const popstateHandler = () => {
setTimeout(() => {
handleUrlChange();
checkAndInject();
}, 100);
};
window.addEventListener('popstate', popstateHandler);
// Tab visible again (alt-tab): make sure the renderer is running
const visibilityHandler = () => {
if (document.visibilityState === 'visible' && isStreamingPage()) {
console.log('[Optimizer+] Onglet redevenu visible - réactivation et vérification des filtres');
if (typeof videoEnhancer !== 'undefined' && videoEnhancer.ensureActive) {
videoEnhancer.ensureActive();
}
setTimeout(() => {
SessionState.selfHeal();
checkAndInject();
}, 300);
}
};
document.addEventListener('visibilitychange', visibilityHandler);
const focusHandler = () => {
if (isStreamingPage()) {
if (typeof videoEnhancer !== 'undefined' && videoEnhancer.ensureActive) {
videoEnhancer.ensureActive();
}
setTimeout(checkAndInject, 200);
}
};
window.addEventListener('focus', focusHandler);
const fullscreenHandler = () => {
console.log('[Optimizer+] Changement de plein écran détecté');
setTimeout(checkAndInject, 200);
setTimeout(checkAndInject, 800);
};
document.addEventListener('fullscreenchange', fullscreenHandler);
const resizeHandler = () => {
setTimeout(checkAndInject, 200);
setTimeout(checkAndInject, 800);
};
window.addEventListener('resize', resizeHandler);
// isStreamingPage() is re-read every iteration: it changes on dashboard/game navigation
// Poll rarely once the UI is injected: the observers handle detection
const scheduleNextCheck = () => {
const streamingNow = isStreamingPage();
const delay = streamingNow
? (SessionState.isUIInjected ? 10000 : 5000)
: 5000;
setTimeout(() => {
if (isStreamingPage()) checkAndInject();
scheduleNextCheck();
}, delay);
};
scheduleNextCheck();
// These observers and listeners intentionally live for the whole page lifetime
if (onStreaming) {
console.log('[Optimizer+] Page streaming d\u00E9tect\u00E9e - activation imm\u00E9diate');
[100, 500, 1000, 2000].forEach(delay => setTimeout(checkAndInject, delay));
} else {
setTimeout(checkAndInject, 500);
}
console.log('[Optimizer+] Syst\u00E8me d\'injection intelligent activ\u00E9');
}
function showNotification(message, type = 'info') {
const existing = document.getElementById('optimizer-notification');
if (existing) existing.remove();
const notification = document.createElement('div');
notification.id = 'optimizer-notification';
const icons = {
success: ICONS.check,
error: ICONS.x,
info: ICONS.activity
};
const colors = {
success: '#22c55e',
error: '#ef4444',
info: '#00a3ff'
};
// message goes into a text node, never innerHTML (XSS)
const iconSpan = document.createElement('span');
iconSpan.style.cssText = `display: flex; align-items: center; color: ${colors[type] || colors.info};`;
iconSpan.innerHTML = icons[type] || icons.info; // hard-coded SVG, safe
const textSpan = document.createElement('span');
textSpan.textContent = message;
notification.appendChild(iconSpan);
notification.appendChild(textSpan);
notification.style.cssText = `
position: fixed;
bottom: 80px;
left: 50%;
transform: translateX(-50%);
background: rgba(15, 15, 25, 0.95);
border: 1px solid ${colors[type]}40;
border-radius: 12px;
padding: 12px 20px;
display: flex;
align-items: center;
gap: 10px;
color: #fff;
font-size: 13px;
z-index: 9999999;
backdrop-filter: blur(10px);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
animation: opt-slide-up 0.3s ease;
`;
if (!document.getElementById('opt-notification-style')) {
const style = document.createElement('style');
style.id = 'opt-notification-style';
style.textContent = `
@keyframes opt-slide-up {
from { opacity: 0; transform: translateX(-50%) translateY(20px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
`;
document.head.appendChild(style);
}
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateX(-50%) translateY(20px)';
notification.style.transition = 'all 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
function isUIFullyInjected(menuElement) {
const root = menuElement || document;
return root.querySelector('#optimizer-reset') !== null &&
root.querySelector('#optimizer-res-select') !== null &&
root.querySelector('#optimizer-enhancer') !== null &&
root.querySelector('#optimizer-filters-toggle') !== null;
}
function createOptimizerUI(menuElement) {
if (isUIFullyInjected(menuElement)) {
console.log('[Optimizer+] UI déjà présente et complète');
return;
}
if (document.querySelector('.optimizer-injected')) {
console.log('[Optimizer+] UI incomplète détectée, nettoyage avant réinjection');
cleanupUI();
}
if (!StreamingEnhancements.active) {
StreamingEnhancements.enable();
}
const insertAfter = findInsertionPoint(menuElement);
const sectionScreenAnalysis = SmartResolutionDetector.getScreenAnalysis();
const temp = document.createElement('div');
temp.innerHTML = `
`;
const children = Array.from(temp.children);
if (insertAfter && insertAfter.parentNode) {
let current = insertAfter;
children.forEach(child => {
current.parentNode.insertBefore(child, current.nextSibling);
current = child;
});
console.log('[Optimizer+] UI injectée directement après la section Streaming');
} else {
children.forEach(child => {
menuElement.appendChild(child);
});
console.log('[Optimizer+] UI ajoutée à la fin du menu');
}
attachUIEvents();
initSliderStyles();
console.log('[Optimizer+] Interface injectée avec succès');
}
function createCustomSlider(inputElement) {
const wrapper = document.createElement('div');
wrapper.className = 'optimizer-slider';
const track = document.createElement('div');
track.className = 'optimizer-slider-track';
const fill = document.createElement('div');
fill.className = 'optimizer-slider-fill';
const thumb = document.createElement('div');
thumb.className = 'optimizer-slider-thumb';
wrapper.appendChild(track);
wrapper.appendChild(fill);
wrapper.appendChild(thumb);
inputElement.parentNode.insertBefore(wrapper, inputElement);
wrapper.appendChild(inputElement);
const updateVisual = () => {
const min = parseFloat(inputElement.min) || 0;
const max = parseFloat(inputElement.max) || 100;
const value = parseFloat(inputElement.value) || 0;
const percentage = ((value - min) / (max - min)) * 100;
fill.style.width = `${percentage}%`;
thumb.style.left = `${percentage}%`;
};
updateVisual();
inputElement.addEventListener('input', updateVisual);
return wrapper;
}
function initSliderStyles() {
const sliders = document.querySelectorAll('.optimizer-injected input[type="range"]');
sliders.forEach(slider => {
if (!slider.parentElement.classList.contains('optimizer-slider')) {
createCustomSlider(slider);
}
});
}
function attachUIEvents() {
const autoSave = () => {
saveConfig(true);
};
const resSelect = document.getElementById('optimizer-res-select');
if (resSelect) {
resSelect.addEventListener('change', (e) => {
const value = e.target.value;
let width, height;
let isAutoMode = false;
if (value === 'auto') {
isAutoMode = true;
width = _realScreen.width;
height = _realScreen.height;
} else {
[width, height] = value.split('x').map(Number);
}
CONFIG.resolution.width = width;
CONFIG.resolution.height = height;
CONFIG.resolution.isAuto = isAutoMode;
const resDisplay = document.getElementById('optimizer-resolution');
if (resDisplay) {
resDisplay.textContent = isAutoMode ? `Auto: ${width}x${height}` : `${width}x${height}`;
}
hookResolution();
// Make Boosteroid recompute the video size (avoids the zoomed-corner bug)
setTimeout(() => {
window.dispatchEvent(new Event('resize'));
const video = document.querySelector('video');
if (video && !CONFIG.display.stretchMode) {
video.style.transform = '';
}
}, 100);
// aspectRatio must be a number (toFixed returns a string)
const aspectRatio = width / height;
let ratioName = '16:9';
if (aspectRatio >= 3.4) ratioName = '32:9';
else if (aspectRatio >= 2.2) ratioName = '21:9';
else if (aspectRatio >= 1.75) ratioName = '16:9';
else if (aspectRatio >= 1.55) ratioName = '16:10';
const modeText = isAutoMode ? 'Auto' : '';
showNotification(`${modeText} Resolution: ${width}x${height} (${ratioName})`);
// Saved now, not debounced: users reload right after picking a resolution
saveConfig(false);
confirmResolution(width, height);
});
}
const enhancerToggle = document.getElementById('optimizer-enhancer');
if (enhancerToggle) {
enhancerToggle.addEventListener('change', (e) => {
videoEnhancer.toggle(e.target.checked);
autoSave();
});
}
const filtersToggle = document.getElementById('optimizer-filters-toggle');
if (filtersToggle) {
filtersToggle.addEventListener('change', (e) => {
videoEnhancer.toggleFilters(e.target.checked);
const detailsSection = document.getElementById('optimizer-filters-details');
if (detailsSection) {
detailsSection.style.display = e.target.checked ? 'block' : 'none';
}
if (!e.target.checked) {
CONFIG.filters.preset = null;
document.querySelectorAll('.optimizer-preset-btn').forEach(btn => btn.classList.remove('active'));
}
autoSave();
});
}
// Performance mode: lighter shader path, the user's filter config is untouched
const filtersPerfToggle = document.getElementById('optimizer-filters-performance-toggle');
if (filtersPerfToggle) {
filtersPerfToggle.addEventListener('change', (e) => {
CONFIG.filters.performanceMode = e.target.checked;
console.log(`[Optimizer+] Performance Mode: ${e.target.checked ? 'ON (filtres légers)' : 'OFF (qualité max)'}`);
videoEnhancer.updateFilterString();
videoEnhancer.applyFiltersToAllVideos();
if (typeof showNotification === 'function') {
showNotification(e.target.checked
? t('perfModeNotifOn' ) || 'Mode Performance: FPS maximisés'
: t('perfModeNotifOff') || 'Mode Performance désactivé (qualité max)');
}
autoSave();
});
}
const stretchModeToggle = document.getElementById('optimizer-stretch-mode');
if (stretchModeToggle) {
stretchModeToggle.addEventListener('change', (e) => {
CONFIG.display.stretchMode = e.target.checked;
// No autoSave(): stretch does not persist across sessions
if (e.target.checked) {
document.documentElement.classList.add('optimizer-stretch-mode');
// WebGPU: stretch the canvas too
const glCanvas = document.getElementById('optimizer-webgpu-canvas') || document.getElementById('optimizer-webgl-canvas');
if (glCanvas) glCanvas.style.objectFit = 'fill';
showNotification('Stretch Mode ON (Borders Removed)');
} else {
document.documentElement.classList.remove('optimizer-stretch-mode');
const glCanvas = document.getElementById('optimizer-webgpu-canvas') || document.getElementById('optimizer-webgl-canvas');
if (glCanvas) glCanvas.style.objectFit = 'contain';
showNotification('Stretch Mode OFF');
}
videoEnhancer.refreshBox();
});
}
const sharpSlider = document.getElementById('optimizer-sharpness');
if (sharpSlider) {
sharpSlider.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('optimizer-sharp-value').textContent = `${e.target.value}%`;
videoEnhancer.updateSettings({ sharpness: value });
autoSave();
});
}
const contrastSlider = document.getElementById('optimizer-contrast');
if (contrastSlider) {
contrastSlider.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('optimizer-contrast-value').textContent = `${e.target.value}%`;
videoEnhancer.updateSettings({ contrast: value });
autoSave();
});
}
const satSlider = document.getElementById('optimizer-saturation');
if (satSlider) {
satSlider.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('optimizer-sat-value').textContent = `${e.target.value}%`;
videoEnhancer.updateSettings({ saturation: value });
autoSave();
});
}
const resetBtn = document.getElementById('optimizer-reset');
if (resetBtn) {
resetBtn.addEventListener('click', () => {
// Reset turns every image effect off, so Boosteroid's own picture is shown. The
// chosen resolution and the slider defaults are kept for when effects come back.
CONFIG.enhancer = { ...DEFAULT_CONFIG.enhancer, enabled: false };
CONFIG.filters = JSON.parse(JSON.stringify(DEFAULT_CONFIG.filters));
CONFIG.language = DEFAULT_CONFIG.language;
if (CONFIG.display) CONFIG.display.stretchMode = false;
document.documentElement.classList.remove('optimizer-stretch-mode');
const glCanvas = document.getElementById('optimizer-webgpu-canvas') || document.getElementById('optimizer-webgl-canvas');
if (glCanvas) glCanvas.style.objectFit = 'contain';
localStorage.removeItem('optimizer_config');
saveConfig(false);
videoEnhancer.enabled = CONFIG.enhancer.enabled;
videoEnhancer.filtersEnabled = CONFIG.filters.enabled;
videoEnhancer.updateFilterString();
videoEnhancer.applyFiltersToAllVideos();
updateAllUIValues();
showNotification('[OK] ' + t('settingsReset').replace('[<<] ', ''));
console.log('[Optimizer+] Reset effectu\u00E9 - valeurs par d\u00E9faut restaur\u00E9es');
});
}
const langSelect = document.getElementById('optimizer-lang-select');
if (langSelect) {
langSelect.addEventListener('change', (e) => {
const newLang = e.target.value;
CONFIG.language = newLang;
if (newLang === 'auto') {
const browserLang = (navigator.language || navigator.userLanguage || 'en').substring(0, 2).toLowerCase();
currentLang = I18N.translations[browserLang] ? browserLang : 'en';
} else {
currentLang = newLang;
}
autoSave();
showNotification(`${t('language')}: ${e.target.options[e.target.selectedIndex].text}`);
// Rebuild the UI in the new language
setTimeout(() => {
const injectedElements = document.querySelectorAll('.optimizer-injected');
if (injectedElements.length > 0) {
injectedElements.forEach(el => el.remove());
SessionState.isUIInjected = false;
const menu = findOpenOptionsMenu();
if (menu) {
createOptimizerUI(menu);
SessionState.isUIInjected = true;
}
}
}, 500);
});
}
// === ADVANCED FILTERS ===
const presetBtns = document.querySelectorAll('.optimizer-preset-btn');
presetBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
const preset = e.currentTarget.dataset.preset;
videoEnhancer.applyPreset(preset);
presetBtns.forEach(b => b.classList.remove('active'));
e.currentTarget.classList.add('active');
// Defer DOM updates to next frame to avoid reflow shake
requestAnimationFrame(() => updateFiltersUI());
autoSave();
showNotification(t('presetApplied', { name: FILTER_PRESETS[preset]?.name || preset }));
});
});
document.querySelectorAll('.optimizer-filter-checkbox').forEach(toggle => {
toggle.addEventListener('change', (e) => {
const filterName = e.target.dataset.filter;
const isActive = e.target.checked;
videoEnhancer.toggleFilter(filterName, isActive);
setPresetToCustom();
autoSave();
});
});
const usmAmount = document.getElementById('usm-amount');
if (usmAmount) {
usmAmount.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('usm-title').textContent = `${e.target.value}%`;
videoEnhancer.updateFilterSettings('usm', { amount: value });
setPresetToCustom();
autoSave();
});
}
const casSharpness = document.getElementById('cas-sharpness');
if (casSharpness) {
casSharpness.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('cas-title').textContent = `${e.target.value}%`;
videoEnhancer.updateFilterSettings('cas', { sharpness: value });
setPresetToCustom();
autoSave();
});
}
const clarityAmount = document.getElementById('clarity-amount');
if (clarityAmount) {
clarityAmount.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('clarity-title').textContent = `${e.target.value}%`;
videoEnhancer.updateFilterSettings('clarity', { amount: value });
setPresetToCustom();
autoSave();
});
}
const denoiseStrength = document.getElementById('denoise-strength');
if (denoiseStrength) {
denoiseStrength.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('denoise-title').textContent = `${e.target.value}%`;
videoEnhancer.updateFilterSettings('denoise', { strength: value });
setPresetToCustom();
autoSave();
});
}
const vibranceAmount = document.getElementById('vibrance-amount');
if (vibranceAmount) {
vibranceAmount.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('vibrance-title').textContent = `${e.target.value}%`;
videoEnhancer.updateFilterSettings('vibrance', { amount: value });
setPresetToCustom();
autoSave();
});
}
const debandStrength = document.getElementById('deband-strength');
if (debandStrength) {
debandStrength.addEventListener('input', (e) => {
const value = parseInt(e.target.value) / 100;
document.getElementById('deband-title').textContent = `${e.target.value}%`;
videoEnhancer.updateFilterSettings('deband', { strength: value });
setPresetToCustom();
autoSave();
});
}
}
// Refresh the whole UI from CONFIG
function updateAllUIValues() {
const resSelect = document.getElementById('optimizer-res-select');
if (resSelect) {
resSelect.value = CONFIG.resolution.isAuto ? 'auto' : `${CONFIG.resolution.width}x${CONFIG.resolution.height}`;
}
const resDisplay = document.getElementById('optimizer-resolution');
if (resDisplay) {
resDisplay.textContent = (CONFIG.resolution.isAuto ? 'Auto: ' : '') + `${CONFIG.resolution.width}x${CONFIG.resolution.height}`;
}
const enhancerToggle = document.getElementById('optimizer-enhancer');
if (enhancerToggle) {
enhancerToggle.checked = CONFIG.enhancer.enabled;
}
const filtersToggle = document.getElementById('optimizer-filters-toggle');
if (filtersToggle) {
filtersToggle.checked = CONFIG.filters.enabled;
}
const stretchModeToggle = document.getElementById('optimizer-stretch-mode');
if (stretchModeToggle && CONFIG.display) {
stretchModeToggle.checked = CONFIG.display.stretchMode;
}
const filtersPerfToggle = document.getElementById('optimizer-filters-performance-toggle');
if (filtersPerfToggle) {
filtersPerfToggle.checked = CONFIG.filters.performanceMode;
}
const presetBtns = document.querySelectorAll('.optimizer-preset-btn');
presetBtns.forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.preset === CONFIG.filters.preset) {
btn.classList.add('active');
}
});
const langSelect = document.getElementById('optimizer-lang-select');
if (langSelect) {
langSelect.value = CONFIG.language;
}
updateFiltersUI();
}
function updateFiltersUI() {
// Sync advanced filters details drawer visibility
const detailsSection = document.getElementById('optimizer-filters-details');
if (detailsSection) {
detailsSection.style.display = CONFIG.filters.enabled ? 'block' : 'none';
}
// Performance mode changes the shader, not the config: sliders always stay enabled
const sharpSlider = document.getElementById('optimizer-sharpness');
if (sharpSlider) {
sharpSlider.value = CONFIG.enhancer.sharpness * 100;
document.getElementById('optimizer-sharp-value').textContent = `${Math.round(CONFIG.enhancer.sharpness * 100)}%`;
}
const contrastSlider = document.getElementById('optimizer-contrast');
if (contrastSlider) {
contrastSlider.value = CONFIG.enhancer.contrast * 100;
document.getElementById('optimizer-contrast-value').textContent = `${Math.round(CONFIG.enhancer.contrast * 100)}%`;
}
const satSlider = document.getElementById('optimizer-saturation');
if (satSlider) {
satSlider.value = CONFIG.enhancer.saturation * 100;
document.getElementById('optimizer-sat-value').textContent = `${Math.round(CONFIG.enhancer.saturation * 100)}%`;
}
const filters = CONFIG.filters;
const usmAmountEl = document.getElementById('usm-amount');
if (usmAmountEl) {
usmAmountEl.value = filters.usm.amount * 100;
usmAmountEl.disabled = false;
document.getElementById('usm-title').textContent = `${Math.round(filters.usm.amount * 100)}%`;
}
const casSharpnessEl = document.getElementById('cas-sharpness');
if (casSharpnessEl) {
casSharpnessEl.value = filters.cas.sharpness * 100;
casSharpnessEl.disabled = false;
document.getElementById('cas-title').textContent = `${Math.round(filters.cas.sharpness * 100)}%`;
}
const clarityAmountEl = document.getElementById('clarity-amount');
if (clarityAmountEl) {
clarityAmountEl.value = filters.clarity.amount * 100;
clarityAmountEl.disabled = false;
document.getElementById('clarity-title').textContent = `${Math.round(filters.clarity.amount * 100)}%`;
}
const denoiseStrengthEl = document.getElementById('denoise-strength');
if (denoiseStrengthEl) {
denoiseStrengthEl.value = filters.denoise.strength * 100;
denoiseStrengthEl.disabled = false;
document.getElementById('denoise-title').textContent = `${Math.round(filters.denoise.strength * 100)}%`;
}
const vibranceAmountEl = document.getElementById('vibrance-amount');
if (vibranceAmountEl) {
vibranceAmountEl.value = filters.vibrance.amount * 100;
vibranceAmountEl.disabled = false;
document.getElementById('vibrance-title').textContent = `${Math.round(filters.vibrance.amount * 100)}%`;
}
const debandStrengthEl = document.getElementById('deband-strength');
if (debandStrengthEl) {
debandStrengthEl.value = filters.deband.strength * 100;
debandStrengthEl.disabled = false;
document.getElementById('deband-title').textContent = `${Math.round(filters.deband.strength * 100)}%`;
}
['usm', 'cas', 'clarity', 'denoise', 'vibrance', 'deband'].forEach(filterName => {
const checkbox = document.querySelector(`.optimizer-filter-checkbox[data-filter="${filterName}"]`);
if (checkbox) {
checkbox.checked = filters[filterName].enabled;
checkbox.disabled = false;
}
});
const sliders = document.querySelectorAll('.optimizer-injected input[type="range"]');
sliders.forEach(slider => updateSliderStyle(slider));
}
// Updates a custom slider's fill and thumb position
function updateSliderStyle(slider) {
if (!slider || !slider.parentElement) return;
const wrapper = slider.closest('.optimizer-slider');
if (!wrapper) return; // not wrapped yet
const fill = wrapper.querySelector('.optimizer-slider-fill');
const thumb = wrapper.querySelector('.optimizer-slider-thumb');
if (!fill || !thumb) return;
const min = parseFloat(slider.min) || 0;
const max = parseFloat(slider.max) || 100;
const value = parseFloat(slider.value) || 0;
const percentage = Math.max(0, Math.min(100, ((value - min) / (max - min)) * 100));
fill.style.width = `${percentage}%`;
thumb.style.left = `${percentage}%`;
}
// Manual edits switch the preset to custom
function setPresetToCustom() {
CONFIG.filters.preset = 'custom';
document.querySelectorAll('.optimizer-preset-btn').forEach(btn => {
btn.classList.remove('active');
});
}
// VIDEO OBSERVER
function setupVideoObserver() {
const observer = new MutationObserver((mutations) => {
const mutationsLen = mutations.length;
for (let i = 0; i < mutationsLen; i++) {
const added = mutations[i].addedNodes;
const addedLen = added.length;
for (let j = 0; j < addedLen; j++) {
const node = added[j];
if (node.nodeName === 'VIDEO') {
handleVideoElement(node);
} else if (node.querySelectorAll) {
const videos = node.querySelectorAll('video');
const videosLen = videos.length;
for (let k = 0; k < videosLen; k++) {
handleVideoElement(videos[k]);
}
}
}
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
document.querySelectorAll('video').forEach(handleVideoElement);
}
function handleVideoElement(video) {
console.log('[Optimizer+] Vid\u00E9o d\u00E9tect\u00E9e');
// Bind the renderer to the WebRTC stream only (srcObject). Videos with src= (dashboard
// trailers) would otherwise steal the canvas from the stream.
if (video.srcObject) {
videoEnhancer.applyToVideo(video);
} else {
video.addEventListener('loadedmetadata', () => {
if (video.srcObject) videoEnhancer.applyToVideo(video);
}, { once: true });
}
video.setAttribute('playsinline', '');
}
// DASHBOARD FLOATING WIDGET - Sets the resolution before launching a game
function createDashboardWidget() {
if (document.getElementById('optimizer-dashboard-widget')) {
return;
}
const injectWidget = () => {
const widget = document.createElement('div');
widget.id = 'optimizer-dashboard-widget';
// Inline style avoids a white flash on load
widget.style.cssText = 'position:fixed;right:20px;bottom:40px;z-index:9999999 !important;background:transparent;opacity:0;visibility:hidden;pointer-events:none;transition:opacity 0.25s ease 0.05s;';
const screenAnalysis = SmartResolutionDetector.getScreenAnalysis();
const resolutionOptions = SmartResolutionDetector.generateResolutionOptionsHTML(
CONFIG.resolution.width,
CONFIG.resolution.height,
CONFIG.resolution.isAuto
);
const currentResText = CONFIG.resolution.isAuto
? `Auto: ${CONFIG.resolution.width}x${CONFIG.resolution.height}`
: `${CONFIG.resolution.width}x${CONFIG.resolution.height}`;
const safeCurrentResText = escapeHtml(currentResText);
const safeScreenWidth = escapeHtml(screenAnalysis.screen.width);
const safeScreenHeight = escapeHtml(screenAnalysis.screen.height);
const safeScreenRatioType = escapeHtml(screenAnalysis.screen.ratioType);
const safeScreenRatioName = escapeHtml(screenAnalysis.screen.ratioName);
const hardwareTier = ENV_PROFILE.isHighEnd ? 'High-End' : (ENV_PROFILE.isMidRange ? 'Mid-Range' : 'Low-End');
widget.innerHTML = `
`;
document.body.appendChild(widget);
// Reveal the widget only once styled (no white flash)
const revealWidget = () => {
widget.style.opacity = '1';
widget.style.visibility = 'visible';
widget.style.pointerEvents = 'auto';
widget.style.zIndex = '9999999';
};
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => requestAnimationFrame(revealWidget));
} else {
setTimeout(revealWidget, 50);
}
console.log('[Optimizer+] [OK] Dashboard widget inject\u00E9 dans le DOM');
const attachWithRetry = (attempt = 1) => {
const btn = document.getElementById('opt-widget-toggle');
if (btn) {
attachWidgetEvents();
console.log('[Optimizer+] [OK] \u00C9v\u00E9nements attach\u00E9s (tentative ' + attempt + ')');
} else if (attempt < 5) {
console.log('[Optimizer+] Bouton non trouv\u00E9, nouvelle tentative dans 100ms...');
setTimeout(() => attachWithRetry(attempt + 1), 100);
} else {
console.error('[Optimizer+] [X] Impossible de trouver le bouton apr\u00E8s 5 tentatives');
}
};
setTimeout(() => attachWithRetry(), 50);
console.log('[Optimizer+] [OK] Dashboard widget cr\u00E9\u00E9');
};
setTimeout(() => {
injectWidget();
}, 800);
}
// Document-level handlers are stored so they can be removed (leak on SPA navigation otherwise)
let _widgetDocHandlers = null;
function detachWidgetEvents() {
if (!_widgetDocHandlers) return;
document.removeEventListener('click', _widgetDocHandlers.click);
document.removeEventListener('keydown', _widgetDocHandlers.keydown);
_widgetDocHandlers = null;
}
function attachWidgetEvents() {
// Rebinding: remove the previous handlers first
detachWidgetEvents();
const widget = document.getElementById('optimizer-dashboard-widget');
const toggleBtn = document.getElementById('opt-widget-toggle');
const panel = document.getElementById('opt-widget-panel');
const resSelect = document.getElementById('opt-widget-resolution');
const applyBtn = document.getElementById('opt-widget-apply');
const statusText = document.getElementById('opt-widget-status-text');
console.log('[Optimizer+] Attaching widget events...', {
widget: !!widget,
toggleBtn: !!toggleBtn,
panel: !!panel,
resSelect: !!resSelect
});
if (!widget) {
console.error('[Optimizer+] Widget container not found!');
return;
}
const handleToggle = (e) => {
if (e) {
e.preventDefault();
e.stopPropagation();
}
if (panel) {
const isOpen = panel.classList.contains('open');
if (isOpen) {
panel.classList.remove('open');
panel.style.opacity = '0';
panel.style.visibility = 'hidden';
panel.style.transform = 'translateY(10px) scale(0.95)';
} else {
panel.classList.add('open');
panel.style.opacity = '1';
panel.style.visibility = 'visible';
panel.style.transform = 'translateY(0) scale(1)';
}
console.log('[Optimizer+] Panel state:', panel.classList.contains('open') ? 'OPEN' : 'CLOSED');
}
};
if (toggleBtn) {
toggleBtn.style.pointerEvents = 'auto';
toggleBtn.addEventListener('click', handleToggle);
}
widget.addEventListener('click', (e) => {
const target = e.target;
if (!target) return;
const element = target.nodeType === 1 ? target : target.parentElement;
if (!element || !element.closest) return;
if (element.id === 'opt-widget-toggle' || element.closest('#opt-widget-toggle')) {
handleToggle(e);
return;
}
if (target.id === 'opt-widget-reload' || target.closest('#opt-widget-reload')) {
e.preventDefault();
console.log('[Optimizer+] Reload button clicked');
location.reload();
return;
}
if (target.id === 'opt-widget-apply' || target.closest('#opt-widget-apply')) {
e.preventDefault();
console.log('[Optimizer+] Apply button clicked');
saveConfig(false);
hookResolution();
if (applyBtn) {
applyBtn.innerHTML = `
${escapeHtml(t('apply'))} \u2713
`;
applyBtn.style.background = '#22c55e';
setTimeout(() => {
applyBtn.innerHTML = `
${escapeHtml(t('apply'))}
`;
applyBtn.style.background = '';
if (panel) {
panel.classList.remove('open');
panel.style.opacity = '0';
panel.style.visibility = 'hidden';
panel.style.transform = 'translateY(10px) scale(0.95)';
}
}, 1500);
}
console.log('[Optimizer+] [OK] Configuration sauvegard\u00E9e');
return;
}
});
if (resSelect) {
resSelect.addEventListener('change', (e) => {
const value = e.target.value;
let width, height, displayText;
let isAutoMode = false;
if (value === 'auto') {
isAutoMode = true;
width = _realScreen.width;
height = _realScreen.height;
displayText = `Auto: ${width}x${height}`;
} else {
[width, height] = value.split('x').map(Number);
displayText = `${width}x${height}`;
}
CONFIG.resolution.width = width;
CONFIG.resolution.height = height;
CONFIG.resolution.isAuto = isAutoMode;
if (statusText) {
statusText.textContent = displayText;
}
const statusDot = document.querySelector('#optimizer-dashboard-widget .opt-status-dot');
if (statusDot) {
statusDot.title = `${t('active')}: ${displayText}`;
}
const screenValue = document.querySelector('.opt-screen-value');
if (screenValue && value === 'auto') {
screenValue.classList.add('auto-active');
} else if (screenValue) {
screenValue.classList.remove('auto-active');
}
saveConfig(false);
hookResolution();
console.log(`[Optimizer+] R\u00E9solution chang\u00E9e: ${displayText}`);
});
}
const docClickHandler = (e) => {
if (panel && widget && !widget.contains(e.target)) {
panel.classList.remove('open');
panel.style.opacity = '0';
panel.style.visibility = 'hidden';
panel.style.transform = 'translateY(10px) scale(0.95)';
}
};
const docKeyHandler = (e) => {
if (e.key === 'Escape' && panel) {
panel.classList.remove('open');
panel.style.opacity = '0';
panel.style.visibility = 'hidden';
panel.style.transform = 'translateY(10px) scale(0.95)';
}
};
document.addEventListener('click', docClickHandler);
document.addEventListener('keydown', docKeyHandler);
_widgetDocHandlers = { click: docClickHandler, keydown: docKeyHandler };
console.log('[Optimizer+] [OK] All widget events attached successfully');
}
// Dev build only: shows where the Boosteroid client sends the stream resolution and
// which API paths it calls. Prints key names and resolution-like values, never whole
// bodies (they can carry tokens).
function devCaptureRequests() {
const RES = /width|height|resol|screen|\b\d{3,4}\s*[x*]\s*\d{3,4}\b/i;
let left = 60;
const seenPaths = new Set();
const short = (u) => { try { const x = new URL(u, location.href); return x.host + x.pathname; } catch (e) { return '?'; } };
const describe = (txt) => {
const out = [];
const keep = (k, v) => { if (out.length < 12 && RES.test(k + '=' + v)) out.push(`${k}=${String(v).slice(0, 24)}`); };
try {
const walk = (o, path) => {
if (!o || typeof o !== 'object') return;
for (const [k, v] of Object.entries(o)) {
const p = path ? `${path}.${k}` : k;
if (v && typeof v === 'object') walk(v, p); else keep(p, v);
}
};
walk(JSON.parse(txt), '');
} catch (e) {
new URLSearchParams(txt).forEach((v, k) => keep(k, v));
if (!out.length) { const m = txt.match(RES); if (m) out.push('raw: ' + txt.slice(m.index, m.index + 40).replace(/\s+/g, ' ')); }
}
return out.join(' ');
};
const note = (via, where, body) => {
if (left <= 0 || typeof body !== 'string' || body.length > 20000 || !RES.test(body)) return;
const d = describe(body);
if (d) { left--; report(`[Optimizer+] [Capture] ${via} ${where} | ${d}`); }
};
const seen = (via, url) => {
const p = short(url);
if (seenPaths.size < 40 && !seenPaths.has(p) && /boosteroid/i.test(p)) { seenPaths.add(p); report(`[Optimizer+] [Capture] ${via} ${p}`); }
try { note(via + ' query', p, new URL(url, location.href).search.slice(1)); } catch (e) {}
};
note('page', location.pathname, location.search.slice(1));
const origFetch = windowCtx.fetch;
windowCtx.fetch = function (input, init) {
try {
const url = typeof input === 'string' ? input : input && input.url;
seen('fetch', url);
note('fetch body', short(url), init && init.body);
} catch (e) {}
return origFetch.apply(this, arguments);
};
const xhrOpen = XMLHttpRequest.prototype.open;
const xhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url) { this._optUrl = url; return xhrOpen.apply(this, arguments); };
XMLHttpRequest.prototype.send = function (body) {
try { seen('xhr', this._optUrl); note('xhr body', short(this._optUrl), body); } catch (e) {}
return xhrSend.apply(this, arguments);
};
const OrigWS = windowCtx.WebSocket;
if (typeof OrigWS === 'function') {
windowCtx.WebSocket = new Proxy(OrigWS, {
construct(Target, args) {
const ws = new Target(...args);
const send = ws.send.bind(ws);
let n = 0;
report(`[Optimizer+] [Capture] ws open ${short(args[0])}`);
// Only the first messages are inspected: later traffic costs one counter increment
ws.send = (data) => {
if (n++ < 40) note('ws send', short(args[0]), data);
return send(data);
};
return ws;
}
});
}
}
// INITIALISATION
function init() {
console.log('[Optimizer+] =======================================');
console.log(`[Optimizer+] Boosteroid Optimizer Plus v${SCRIPT_VERSION} by Derfog`);
console.log('[Optimizer+] Device:', ENV_PROFILE.summary());
console.log('[Optimizer+] Resolution:', `${CONFIG.resolution.width}x${CONFIG.resolution.height}`);
console.log('[Optimizer+] Bitrate:', `${Math.round(CONFIG.streaming.maxBitrate / 1000000)}Mbps`);
console.log('[Optimizer+] Low Latency:', CONFIG.performance.lowLatencyMode ? 'ON' : 'OFF');
console.log('[Optimizer+] =======================================');
// Technical hooks apply everywhere (dashboard included): they prepare the browser for streaming
hookResolution();
hookCodecs();
hookPerformance();
hookBitrate();
SmartCodecSelector.probe();
if (DEV_BUILD) devCaptureRequests();
console.log(`[Optimizer+] v${SCRIPT_VERSION} \u2014 WebGPU zero-copy mode active`);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', onDOMReady);
} else {
onDOMReady();
}
}
function onDOMReady() {
ensureOptimizerTypography();
const onStreaming = isStreamingPage();
const onDashboard = isDashboardPage();
console.log('[Optimizer+] Type de page - Streaming:', onStreaming, '| Dashboard:', onDashboard);
// Dashboard: show the floating widget only
if (onDashboard && !onStreaming) {
console.log('[Optimizer+] Dashboard d\u00E9tect\u00E9 - Widget flottant activ\u00E9');
console.log('[Optimizer+] L\'UI compl\u00E8te s\'activera automatiquement quand vous lancerez un jeu');
createDashboardWidget();
return;
}
injectUI();
setupVideoObserver();
}
init();
})();