A script to process visually and auditory scrambled YouTube videos into a human understandable format, but slightly more optimized. Now also decoding hover previews. Includes an aggressive audio compressor to limit loud noises.
// ==UserScript==
// @name UnsafeYT Decoder
// @author ElectroKnight22
// @namespace unsafe-yt-decoder-namespace
// @version 0.9.4
// @match https://www.youtube.com/*
// @match https://m.youtube.com/*
// @match *://www.youtube-nocookie.com/*
// @exclude *://www.youtube.com/live_chat*
// @require https://update.greasyfork.org/scripts/549881/1688974/YouTube%20Helper%20API.js
// @grant none
// @run-at document-idle
// @inject-into page
// @license MIT
// @description A script to process visually and auditory scrambled YouTube videos into a human understandable format, but slightly more optimized. Now also decoding hover previews. Includes an aggressive audio compressor to limit loud noises.
// ==/UserScript==
/*jshint esversion: 11 */
(function () {
'use strict';
const SHADERS = {
VERT_SHADER: `#version 300 es
in vec2 a_position; in vec2 a_texCoord; out vec2 v_texCoord;
void main() { gl_Position = vec4(a_position, 0.0, 1.0); v_texCoord = a_texCoord; }
`,
FRAG_SHADER: `#version 300 es
precision highp float;
in vec2 v_texCoord; out vec4 fragColor;
uniform sampler2D u_sampler; uniform sampler2D u_shuffle;
const float PI = 3.14159265359;
vec4 getColor( vec2 uv ){
vec2 uv_clamped = clamp(uv, 0.0, 1.0);
vec2 shuffle_sample = texture(u_shuffle, uv_clamped).rg;
vec2 final_sample_pos = uv + shuffle_sample;
vec4 c = texture(u_sampler, final_sample_pos);
return vec4(1.0 - c.rgb, c.a);
}
vec2 getNormal(vec2 uv){vec2 o=vec2(0.0065);vec2 c=round((uv+o)*80.)/80.;return(c-(uv+o))*80.;}
float getAxis(vec2 uv){vec2 n=getNormal(uv);float a=abs(n.x)>0.435?1.:0.;return abs(n.y)>0.4?2.:a;}
float getGrid(vec2 uv){return getAxis(uv)>0.?1.:0.;}
vec4 getGridFix(vec2 uv){vec2 n=getNormal(uv);vec4 b=getColor(uv);vec4 o=getColor(uv+n*0.002);float g=getGrid(uv);return mix(b,o,g);}
vec4 getSmoothed( vec2 uv, float power, float slice ){
vec4 totalColor = vec4(0.0);
float totalWeight = 0.0;
const float sigma = 0.45;
const int sampleCount = 16;
vec2 samples[16]=vec2[](vec2(-.326,-.405),vec2(-.840,-.073),vec2(-.695,.457),vec2(-.203,.620),vec2(.962,-.194),vec2(.473,-.480),vec2(.519,.767),vec2(.185,-.893),vec2(.507,.064),vec2(.896,.412),vec2(-.321,.932),vec2(-.791,-.597),vec2(.089,.290),vec2(.354,-.215),vec2(-.825,.223),vec2(-.913,-.281));
for(int i = 0; i < sampleCount; i++){
vec2 offset = samples[i] * power;
float dist = length(samples[i]);
float weight = exp(-(dist * dist) / (2.0 * sigma * sigma));
totalColor += getGridFix(uv + offset) * weight;
totalWeight += weight;
}
return totalColor / totalWeight;
}
void main() {
vec2 uv=vec2(v_texCoord.x,1.-v_texCoord.y);
float a=getAxis(uv),g=a>0.?1.:0.;
float s[3]=float[3](0.,0.,PI);
vec4 m=getGridFix(uv),o=getSmoothed(uv,0.0008,s[int(a)]);
m=mix(m,o,g);
fragColor = m;
}
`,
};
const initialAppState = Object.freeze({
token: '',
isRendering: false,
canvas: null,
gl: null,
audio: { context: null, sourceNode: null, gainNode: null, compressor: null, outputGainNode: null, notchFilters: [] },
renderFrameId: null,
originalContainerStyle: null,
resizeObserver: null,
listenerController: null,
videoElement: null,
playerContainer: null,
});
let appState = { ...initialAppState };
let isApplyingEffects = false;
const UI_CACHE = {
toggle: null,
manual: null,
tokenIndicator: null,
};
let userscriptHTMLPolicy = null;
function createTrustedHTML(htmlString) {
if (window.trustedTypes && window.trustedTypes.createPolicy) {
if (!userscriptHTMLPolicy) {
userscriptHTMLPolicy = window.trustedTypes.createPolicy('userscript-html-policy', { createHTML: (s) => s });
}
return userscriptHTMLPolicy.createHTML(htmlString);
}
return htmlString;
}
function getDeterministicHash(inputString, prime = 31, modulus = Math.pow(2, 32)) {
let hash = 0;
modulus = Math.floor(modulus);
for (let i = 0; i < inputString.length; i++) {
const charCode = inputString.charCodeAt(i);
hash = (hash * prime + charCode) % modulus;
if (hash < 0) {
hash += modulus;
}
}
return hash / modulus;
}
function _generateUnshuffleOffsetMapFloat32Array(seedToken, width, height) {
if (!seedToken || width <= 0 || height <= 0) {
throw new Error('Invalid params for unshuffle map.');
}
const totalPixels = width * height;
const startHash = getDeterministicHash(seedToken, 31, 2 ** 32 - 1);
const stepHash = getDeterministicHash(seedToken + '_step', 37, 2 ** 32 - 2);
const startAngle = startHash * Math.PI * 2.0;
const angleIncrement = (stepHash * Math.PI) / Math.max(width, height);
const indexedValues = Array.from({ length: totalPixels }, (_, index) => ({
value: Math.sin(startAngle + index * angleIncrement),
index: index,
}));
indexedValues.sort((itemA, itemB) => itemA.value - itemB.value);
const permutationArray = new Array(totalPixels);
for (let index = 0; index < totalPixels; index++) {
permutationArray[indexedValues[index].index] = index;
}
const offsetMapFloats = new Float32Array(totalPixels * 2);
for (let originalY = 0; originalY < height; originalY++) {
for (let originalX = 0; originalX < width; originalX++) {
const originalLinearIndex = originalY * width + originalX;
const shuffledLinearIndex = permutationArray[originalLinearIndex];
const shuffledY = Math.floor(shuffledLinearIndex / width);
const shuffledX = shuffledLinearIndex % width;
const offsetX = (shuffledX - originalX) / width;
const offsetY = (shuffledY - originalY) / height;
const pixelDataIndex = (originalY * width + originalX) * 2;
offsetMapFloats[pixelDataIndex] = offsetX;
offsetMapFloats[pixelDataIndex + 1] = offsetY;
}
}
return offsetMapFloats;
}
function extractTokenFromText(text) {
try {
if (!text) return '';
const trimmed = text.trim();
const firstLine = trimmed.split(/\r?\n/)[0] || '';
const keyMarkers = ['token:', 'key:'];
let key = '';
keyMarkers.forEach((marker) => {
if (firstLine.toLowerCase().startsWith(marker)) {
key = firstLine.substring(marker.length).trim();
return;
}
});
return key;
} catch (error) {
console.error('[UnsafeYT] Token extraction error:', error);
return '';
}
}
function injectStyles() {
if (document.getElementById('unsafeyt-styles')) return;
const STYLES = ` #unsafeyt-controls { display: flex; gap: 8px; align-items: center; margin-left: 12px; } .unsafeyt-button { background: transparent; color: white; padding: 6px 8px; border-radius: 6px; cursor: pointer; font-size: 12px; font-weight: 600; outline: none; transition: box-shadow .2s, border-color .2s; } #unsafeyt-toggle { border: 2px solid rgba(200,0,0,0.95); } #unsafeyt-toggle.active { border-color: rgba(0,200,0,0.95); box-shadow: 0 0 8px rgba(0,200,0,0.25); } #unsafeyt-manual { border: 1px solid rgba(255,255,255,0.2); } #unsafeyt-token-indicator { width: 10px; height: 10px; border-radius: 50%; margin-left: 6px; background: transparent; } #unsafeyt-token-indicator.present { background: limegreen; } `;
const styleSheet = document.createElement('style');
styleSheet.id = 'unsafeyt-styles';
styleSheet.innerHTML = createTrustedHTML(STYLES);
document.head.appendChild(styleSheet);
}
function createControlButtons() {
try {
if (window.location.pathname !== '/watch' || document.querySelector('#unsafeyt-controls')) return;
injectStyles();
const bar = document.querySelector('#top-level-buttons-computed');
if (!bar) throw new Error('Top-level buttons not found.');
const buttonContainer = document.createElement('div');
buttonContainer.id = 'unsafeyt-controls';
const toggleButton = document.createElement('button');
toggleButton.id = 'unsafeyt-toggle';
toggleButton.type = 'button';
toggleButton.className = 'unsafeyt-button';
toggleButton.textContent = 'Toggle Effects';
toggleButton.addEventListener('click', async () => {
appState.isRendering ? await removeEffects() : await applyEffects(appState.token);
});
const manualButton = document.createElement('button');
manualButton.id = 'unsafeyt-manual';
manualButton.type = 'button';
manualButton.className = 'unsafeyt-button';
manualButton.textContent = 'Enter Token';
manualButton.addEventListener('click', async () => {
const userInput = prompt("Enter token (first line of description can also be 'token:...' or 'key:...'):")?.trim();
if (!userInput) return;
appState.token = userInput;
try {
await applyEffects(appState.token);
} catch (error) {
console.error('[UnsafeYT] Manual token apply failed:', error);
}
});
const tokenIndicator = document.createElement('div');
tokenIndicator.id = 'unsafeyt-token-indicator';
buttonContainer.appendChild(toggleButton);
buttonContainer.appendChild(manualButton);
buttonContainer.appendChild(tokenIndicator);
UI_CACHE.toggle = toggleButton;
UI_CACHE.manual = manualButton;
UI_CACHE.tokenIndicator = tokenIndicator;
bar.insertBefore(buttonContainer, bar.firstChild);
updateUIState();
} catch (error) {
console.error('[UnsafeYT] Error creating control buttons:', error);
}
}
function updateUIState() {
if (UI_CACHE.toggle) UI_CACHE.toggle.classList.toggle('active', appState.isRendering);
if (UI_CACHE.tokenIndicator) UI_CACHE.tokenIndicator.classList.toggle('present', !!appState.token);
}
async function removeEffects() {
if (isApplyingEffects) return;
if (!appState.isRendering && !appState.canvas) return;
isApplyingEffects = true;
try {
if (appState.listenerController) appState.listenerController.abort();
appState.isRendering = false;
if (appState.canvas) {
try {
appState.canvas.remove();
} catch (error) {
console.warn('[UnsafeYT] Canvas remove error:', error);
}
}
if (appState.renderFrameId !== null) cancelAnimationFrame(appState.renderFrameId);
if (appState.resizeObserver) appState.resizeObserver.disconnect();
if (appState.gl) {
try {
const webGLContentExtension = appState.gl.getExtension('WEBGL_lose_context');
if (webGLContentExtension) webGLContentExtension.loseContext();
} catch (error) {
console.warn('[UnsafeYT] GL context lose error:', error);
}
}
const container = appState.playerContainer;
if (container && appState.originalContainerStyle) {
try {
Object.assign(container.style, appState.originalContainerStyle);
} catch (error) {
console.warn('[UnsafeYT] Container style reset error:', error);
}
}
if (appState.audio.context) {
Object.values(appState.audio).forEach((node) => {
if (node?.disconnect)
try {
node.disconnect();
} catch (error) {
console.warn('[UnsafeYT] Audio node disconnect error:', error);
}
});
const video = appState.videoElement;
if (video) {
video.style.opacity = '1';
}
}
const preservedAudioContext = appState.audio.context;
const preservedAudioSourceNode = appState.audio.sourceNode;
appState = { ...initialAppState, token: appState.token };
appState.audio.context = preservedAudioContext;
appState.audio.sourceNode = preservedAudioSourceNode;
updateUIState();
console.log('[UnsafeYT] Removed applied effects.');
} finally {
isApplyingEffects = false;
}
}
async function applyEffects(seedToken) {
if (isApplyingEffects) return;
if (typeof seedToken !== 'string' || seedToken.length < 3) return;
const videoElement = appState.videoElement;
const playerContainer = appState.playerContainer;
if (!videoElement || !playerContainer) return;
isApplyingEffects = true;
try {
await removeEffects();
console.log(`[UnsafeYT] Applying effects with token: "${seedToken}"`);
videoElement.style.opacity = '0';
videoElement.crossOrigin = 'anonymous';
appState.token = seedToken;
appState.canvas = document.createElement('canvas');
appState.canvas.id = 'unsafeyt-glcanvas';
Object.assign(appState.canvas.style, {
position: 'absolute',
top: `${window.youtubeHelperApi.page.isMobile ? '50%' : '0%'}`,
left: '50%',
transform: 'translateY(0%) translateX(-50%)',
pointerEvents: 'none',
zIndex: 12,
touchAction: 'none',
});
if (!appState.originalContainerStyle)
appState.originalContainerStyle = {
position: playerContainer.style.position,
height: playerContainer.style.height,
};
Object.assign(playerContainer.style, { position: 'relative', height: '100%' });
playerContainer.appendChild(appState.canvas);
appState.gl = appState.canvas.getContext('webgl2', { alpha: false }) || appState.canvas.getContext('webgl', { alpha: false });
if (!appState.gl) {
await removeEffects();
return;
}
let oesTextureFloatExt = null;
if (appState.gl instanceof WebGLRenderingContext) {
oesTextureFloatExt = appState.gl.getExtension('OES_texture_float');
}
const resizeCallback = () => {
if (!appState.canvas || !videoElement) return;
appState.canvas.width = videoElement.offsetWidth || videoElement.videoWidth || 640;
appState.canvas.height = videoElement.offsetHeight || videoElement.videoHeight || 360;
if (appState.gl) {
try {
appState.gl.viewport(0, 0, appState.gl.drawingBufferWidth, appState.gl.drawingBufferHeight);
} catch (error) {
console.warn('[UnsafeYT] GL viewport error:', error);
}
}
};
appState.resizeObserver = new ResizeObserver(resizeCallback);
appState.resizeObserver.observe(videoElement);
resizeCallback();
function compileShader(type, src) {
try {
if (!appState.gl) return null;
const shader = appState.gl.createShader(type);
if (!shader) throw new Error('Failed to create shader.');
appState.gl.shaderSource(shader, src);
appState.gl.compileShader(shader);
if (!appState.gl.getShaderParameter(shader, appState.gl.COMPILE_STATUS)) {
const infoLog = appState.gl.getShaderInfoLog(shader);
appState.gl.deleteShader(shader);
throw new Error(infoLog);
}
return shader;
} catch (error) {
console.error('[UnsafeYT] Shader compile error:', error);
return null;
}
}
function createProgram(vertexShaderSource, fragmentShaderSource) {
let vertexShader = null;
let fragmentShader = null;
try {
if (!appState.gl) return null;
vertexShader = compileShader(appState.gl.VERTEX_SHADER, vertexShaderSource);
fragmentShader = compileShader(appState.gl.FRAGMENT_SHADER, fragmentShaderSource);
if (!vertexShader || !fragmentShader) throw new Error('Shader creation failed.');
const program = appState.gl.createProgram();
appState.gl.attachShader(program, vertexShader);
appState.gl.attachShader(program, fragmentShader);
appState.gl.linkProgram(program);
if (!appState.gl.getProgramParameter(program, appState.gl.LINK_STATUS)) {
const infoLog = appState.gl.getProgramInfoLog(program);
try {
appState.gl.deleteProgram(program);
} catch (error) {
console.warn('[UnsafeYT] Failed to delete program:', error);
}
throw new Error(`Program link error: ${infoLog}`);
}
appState.gl.useProgram(program);
return program;
} catch (error) {
console.error('[UnsafeYT] Program creation error:', error);
return null;
} finally {
try {
if (vertexShader) appState.gl.deleteShader(vertexShader);
if (fragmentShader) appState.gl.deleteShader(fragmentShader);
} catch (error) {
console.warn('[UnsafeYT] Failed to delete shader post-link:', error);
}
}
}
try {
const program = createProgram(SHADERS.VERT_SHADER, SHADERS.FRAG_SHADER);
if (!program) {
await removeEffects();
return;
}
const positionLocation = appState.gl.getAttribLocation(program, 'a_position');
const texCoordLocation = appState.gl.getAttribLocation(program, 'a_texCoord');
const videoSamplerLocation = appState.gl.getUniformLocation(program, 'u_sampler');
const shuffleSamplerLocation = appState.gl.getUniformLocation(program, 'u_shuffle');
const quadVerts = new Float32Array([-1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, -1, 1, 0, 1, 1, -1, 1, 0, 1, 1, 1, 1]);
const vertexBuffer = appState.gl.createBuffer();
appState.gl.bindBuffer(appState.gl.ARRAY_BUFFER, vertexBuffer);
appState.gl.bufferData(appState.gl.ARRAY_BUFFER, quadVerts, appState.gl.STATIC_DRAW);
appState.gl.enableVertexAttribArray(positionLocation);
appState.gl.vertexAttribPointer(positionLocation, 2, appState.gl.FLOAT, false, 16, 0);
appState.gl.enableVertexAttribArray(texCoordLocation);
appState.gl.vertexAttribPointer(texCoordLocation, 2, appState.gl.FLOAT, false, 16, 8);
const videoTexture = appState.gl.createTexture();
appState.gl.bindTexture(appState.gl.TEXTURE_2D, videoTexture);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_WRAP_S, appState.gl.CLAMP_TO_EDGE);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_WRAP_T, appState.gl.CLAMP_TO_EDGE);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_MIN_FILTER, appState.gl.LINEAR);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_MAG_FILTER, appState.gl.LINEAR);
let unshuffleMapFloats = null;
try {
unshuffleMapFloats = _generateUnshuffleOffsetMapFloat32Array(appState.token, 80, 80);
} catch (error) {
console.error('[UnsafeYT] Failed to generate unshuffle map:', error);
await removeEffects();
return;
}
const shuffleTexture = appState.gl.createTexture();
appState.gl.activeTexture(appState.gl.TEXTURE1);
appState.gl.bindTexture(appState.gl.TEXTURE_2D, shuffleTexture);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_WRAP_S, appState.gl.CLAMP_TO_EDGE);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_WRAP_T, appState.gl.CLAMP_TO_EDGE);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_MIN_FILTER, appState.gl.NEAREST);
appState.gl.texParameteri(appState.gl.TEXTURE_2D, appState.gl.TEXTURE_MAG_FILTER, appState.gl.NEAREST);
if (appState.gl instanceof WebGL2RenderingContext) {
try {
appState.gl.texImage2D(
appState.gl.TEXTURE_2D,
0,
appState.gl.RG32F,
80,
80,
0,
appState.gl.RG,
appState.gl.FLOAT,
unshuffleMapFloats,
);
} catch (error) {
console.warn('[UnsafeYT] WebGL2 RG32F texture failed, falling back to RGBA32F:', error);
try {
const rgbaFloatArray = new Float32Array(80 * 80 * 4);
for (let i = 0; i < unshuffleMapFloats.length / 2; i++) {
rgbaFloatArray[i * 4] = unshuffleMapFloats[i * 2];
rgbaFloatArray[i * 4 + 1] = unshuffleMapFloats[i * 2 + 1];
}
appState.gl.texImage2D(
appState.gl.TEXTURE_2D,
0,
appState.gl.RGBA32F,
80,
80,
0,
appState.gl.RGBA,
appState.gl.FLOAT,
rgbaFloatArray,
);
} catch (error) {
console.error('[UnsafeYT] WebGL2 RGBA32F texture failed:', error);
await removeEffects();
return;
}
}
} else if (oesTextureFloatExt) {
try {
const rgbaFloatArray = new Float32Array(80 * 80 * 4);
for (let i = 0; i < unshuffleMapFloats.length / 2; i++) {
rgbaFloatArray[i * 4] = unshuffleMapFloats[i * 2];
rgbaFloatArray[i * 4 + 1] = unshuffleMapFloats[i * 2 + 1];
}
appState.gl.texImage2D(
appState.gl.TEXTURE_2D,
0,
appState.gl.RGBA,
80,
80,
0,
appState.gl.RGBA,
appState.gl.FLOAT,
rgbaFloatArray,
);
} catch (error) {
console.error('[UnsafeYT] WebGL1 RGBA texture failed:', error);
await removeEffects();
return;
}
} else {
console.error('[UnsafeYT] No float texture support.');
await removeEffects();
return;
}
appState.gl.clearColor(0, 0, 0, 1);
appState.isRendering = true;
const render = () => {
if (!appState.isRendering || !appState.gl || !videoElement || !appState.canvas) return;
try {
if (videoElement.readyState >= videoElement.HAVE_CURRENT_DATA) {
appState.gl.activeTexture(appState.gl.TEXTURE0);
appState.gl.bindTexture(appState.gl.TEXTURE_2D, videoTexture);
try {
appState.gl.texImage2D(
appState.gl.TEXTURE_2D,
0,
appState.gl.RGBA,
appState.gl.RGBA,
appState.gl.UNSIGNED_BYTE,
videoElement,
);
} catch (error) {
try {
// Fallback for tainted canvas
appState.gl.texImage2D(
appState.gl.TEXTURE_2D,
0,
appState.gl.RGBA,
videoElement.videoWidth,
videoElement.videoHeight,
0,
appState.gl.RGBA,
appState.gl.UNSIGNED_BYTE,
null,
);
} catch (error) {
console.warn('[UnsafeYT] Failed to update video texture:', error);
}
}
appState.gl.uniform1i(videoSamplerLocation, 0);
appState.gl.uniform1i(shuffleSamplerLocation, 1);
appState.gl.clear(appState.gl.COLOR_BUFFER_BIT);
appState.gl.drawArrays(appState.gl.TRIANGLES, 0, 6);
}
} catch (error) {
console.error('[UnsafeYT] WebGL render loop failed:', error);
removeEffects().catch((error) =>
console.error('[UnsafeYT] Failed to remove effects after render loop error:', error),
);
return;
}
appState.renderFrameId = requestAnimationFrame(render);
};
render();
} catch (error) {
console.error('[UnsafeYT] WebGL setup failed:', error);
await removeEffects();
return;
}
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (!AudioCtx) return;
if (!appState.audio.context) appState.audio.context = new AudioCtx();
const videoElement = appState.videoElement;
if (videoElement) {
try {
if (!appState.audio.sourceNode)
appState.audio.sourceNode = appState.audio.context.createMediaElementSource(videoElement);
} catch (error) {
console.warn('[UnsafeYT] Could not create media element source:', error);
appState.audio.sourceNode = null;
}
const splitter = appState.audio.context.createChannelSplitter(2),
leftGain = appState.audio.context.createGain(),
rightGain = appState.audio.context.createGain(),
merger = appState.audio.context.createChannelMerger(1);
leftGain.gain.value = 0.25;
rightGain.gain.value = 0.25;
appState.audio.gainNode = appState.audio.context.createGain();
appState.audio.gainNode.gain.value = 1.0;
appState.audio.compressor = appState.audio.context.createDynamicsCompressor();
appState.audio.compressor.threshold.value = -72;
appState.audio.compressor.knee.value = 35;
appState.audio.compressor.ratio.value = 15;
appState.audio.compressor.attack.value = 0.003;
appState.audio.compressor.release.value = 0.25;
appState.audio.outputGainNode = appState.audio.context.createGain();
appState.audio.outputGainNode.gain.value = 4.0;
const filterConfigs = [
{ f: 200, q: 3, g: 1 },
{ f: 440, q: 2, g: 1 },
{ f: 6600, q: 1, g: 0 },
{ f: 15600, q: 1, g: 0 },
{ f: 5000, q: 20, g: 1 },
{ f: 6000, q: 20, g: 1 },
{ f: 6300, q: 5, g: 1 },
{ f: 8000, q: 40, g: 1 },
{ f: 10000, q: 40, g: 1 },
{ f: 12500, q: 40, g: 1 },
{ f: 14000, q: 40, g: 1 },
{ f: 15000, q: 40, g: 1 },
{ f: 15500, q: 1, g: 0 },
{ f: 15900, q: 1, g: 0 },
{ f: 16000, q: 40, g: 1 },
];
appState.audio.notchFilters = filterConfigs.map((config) => {
const filter = appState.audio.context.createBiquadFilter();
filter.type = 'notch';
filter.frequency.value = config.f;
filter.Q.value = config.q * 3.5;
filter.gain.value = config.g;
return filter;
});
if (appState.audio.sourceNode) {
appState.audio.sourceNode.connect(splitter);
splitter.connect(leftGain, 0);
splitter.connect(rightGain, 1);
leftGain.connect(merger, 0, 0);
rightGain.connect(merger, 0, 0);
const audioChain = [
merger,
appState.audio.gainNode,
...appState.audio.notchFilters,
appState.audio.compressor,
appState.audio.outputGainNode,
appState.audio.context.destination,
];
audioChain.reduce((prev, next) => prev.connect(next));
}
appState.listenerController = new AbortController();
const { signal } = appState.listenerController;
const handleAudioState = async () => {
if (!appState.audio.context || appState.audio.context.state === 'closed') return;
if (videoElement.paused) {
if (appState.audio.context.state === 'running')
appState.audio.context
.suspend()
.catch((error) => console.warn('[UnsafeYT] Audio context suspend error:', error));
} else {
if (appState.audio.context.state === 'suspended')
appState.audio.context
.resume()
.catch((error) => console.warn('[UnsafeYT] Audio context resume error:', error));
}
};
videoElement.addEventListener('play', handleAudioState, { signal });
videoElement.addEventListener('pause', handleAudioState, { signal });
if (!videoElement.paused) handleAudioState();
}
} catch (error) {
console.error('[UnsafeYT] Audio graph setup failed:', error);
}
updateUIState();
console.log('[UnsafeYT] Effects applied.');
} finally {
isApplyingEffects = false;
}
}
async function processVideo(event) {
try {
const newToken = extractTokenFromText(event.detail.video.rawDescription);
if (!newToken || (newToken === appState.token && appState.isRendering)) return;
console.log('[UnsafeYT] New video with token detected.');
appState.token = newToken;
appState.token ? await applyEffects(appState.token) : await removeEffects();
updateUIState();
} catch (error) {
console.error('[UnsafeYT] Error in processVideo:', error);
}
}
function _handleApiUpdate(event) {
appState.playerContainer = event.detail.player.playerObject;
appState.videoElement = event.detail.player.videoElement;
createControlButtons();
processVideo(event);
}
console.log('[UnsafeYT] Initializing script.');
window.addEventListener('pageshow', createControlButtons);
window.youtubeHelperApi.eventTarget.addEventListener('yt-helper-api-ready', _handleApiUpdate);
})();