-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrt-page.js
More file actions
2048 lines (1709 loc) · 72.8 KB
/
rt-page.js
File metadata and controls
2048 lines (1709 loc) · 72.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Default Configuration
let config = {
masterSwitch: true,
opacity: 100,
blur: 20,
saturation: 100,
brightness: 75,
contrast: 100,
sepia: 0,
invert: 0,
hueLoop: false,
sharpness: 0,
highlights: 100,
shadows: 100,
sensitivity: 50,
audioEnabled: true,
cameraShake: false,
cameraIntensity: 50,
framerate: 30, // Time in ms between checks
smoothness: 60, // 0-100, controls the fade factor
resolution: 100, // Pixel width of the internal canvas
pointerActive: false, // Inverted pointer follow
visualizerActive: false, // Dynamic visualizer
visualizerType: 'bars', // Visualizer style: bars, soundwave, ocean
ambientMode: false, // Smart Ambient Mode
ambientScale: 110, // Scale %
musicOnly: true, // Only activate audio reactivity on music videos
cropCanvas: true, // Auto-crop black bars from canvas reflection
cropVideo: false // Auto-crop black bars from video element
};
// ----------------------------------------------------------------------
// SETTINGS & INIT
// ----------------------------------------------------------------------
// Load settings
if (chrome.storage && chrome.storage.sync) {
chrome.storage.sync.get(['rt_config'], (result) => {
if (result.rt_config) {
config = { ...config, ...result.rt_config };
// Migration
if (result.rt_config.quality && !result.rt_config.framerate) {
config.framerate = result.rt_config.quality;
}
}
init();
});
}
// Listen for updates
// Listener moved to end of file to ensure ModernEngine is initialized
// ----------------------------------------------------------------------
// MUSIC VIDEO DETECTION
// ----------------------------------------------------------------------
function isMusicVideo() {
// 1. YouTube Music domain — always music
if (location.hostname.includes('music.youtube.com')) return true;
// 2. Check ytmusic-player element (YTM embedded)
if (document.querySelector('ytmusic-player')) return true;
// 3. Check LD+JSON microformat (updates on SPA navigation, unlike meta tags)
try {
const microformatScript = document.querySelector('#microformat script[type="application/ld+json"]');
if (microformatScript) {
const data = JSON.parse(microformatScript.textContent);
if (data.genre && data.genre.toLowerCase().includes('music')) return true;
}
} catch (e) { /* JSON parse error, skip */ }
// 4. Check ytInitialPlayerResponse (fallback for genre detection)
try {
const playerResponse = window.ytInitialPlayerResponse;
if (playerResponse?.microformat?.playerMicroformatRenderer?.category) {
const category = playerResponse.microformat.playerMicroformatRenderer.category.toLowerCase();
if (category.includes('music')) return true;
}
} catch (e) { /* skip */ }
// 5. Check for YouTube music badge in the player
if (document.querySelector('span.ytp-music-badge')) return true;
// 6. Check for "Music" in the video category info
const categoryEl = document.querySelector('#info-rows yt-formatted-string a[href*="/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ"]');
if (categoryEl) return true; // Links to YouTube Music category channel
return false;
}
// Returns true if audio effects should be active right now
// Combines audioEnabled toggle + musicOnly filter (evaluated per-frame for instant response)
function isAudioActive() {
if (!config.audioEnabled) return false;
if (config.musicOnly && !isMusicVideo()) return false;
return true;
}
function applyGlobalStyles() {
const root = document.documentElement;
const container = document.getElementById('rt-container');
if (container) {
if (config.cameraShake) {
container.classList.add('camhand');
} else {
container.classList.remove('camhand');
}
}
// CSS Variables
root.style.setProperty('--rt_opacity', config.opacity + '%');
root.style.setProperty('--rt_blur', config.blur + 'px');
root.style.setProperty('--rt_saturate', config.saturation + '%');
root.style.setProperty('--rt_brightness', (config.brightness || 100) + '%');
root.style.setProperty('--rt_contrast', (config.contrast || 100) + '%');
root.style.setProperty('--rt_sepia', (config.sepia || 0) + '%');
root.style.setProperty('--rt_invert', (config.invert || 0) + '%');
// New filter variables
root.style.setProperty('--rt_sharpness', (config.sharpness || 0));
root.style.setProperty('--rt_highlights', (config.highlights || 100) + '%');
root.style.setProperty('--rt_shadows', (config.shadows || 100) + '%');
if (!config.hueLoop) {
root.style.setProperty('--rt_hue-rotate', '0deg');
}
// Camera Intensity
const factor = config.cameraIntensity / 50;
root.style.setProperty('--fuerza', factor.toFixed(2));
// Apply SVG filters to container based on sharpness/highlights/shadows
if (container) {
updateContainerFilters(container);
}
// Effect Update
EffectManager.updateState();
}
function updateContainerFilters(container) {
// Build filter string with SVG filter references when applicable
let filters = [];
// Base CSS filters
filters.push(`blur(var(--rt_blur))`);
filters.push(`contrast(var(--rt_contrast))`);
filters.push(`grayscale(var(--rt_grayscale))`);
filters.push(`hue-rotate(var(--rt_hue-rotate))`);
filters.push(`invert(var(--rt_invert))`);
filters.push(`opacity(var(--rt_opacity))`);
filters.push(`saturate(var(--rt_saturate))`);
filters.push(`sepia(var(--rt_sepia))`);
filters.push(`brightness(var(--rt_brightness))`);
// Add sharpen if sharpness > 0
if (config.sharpness > 0) {
filters.push(`url(#sharpen-${Math.round(config.sharpness)})`);
}
// Add color adjustment if highlights or shadows differ from 100
if (config.highlights !== 100 || config.shadows !== 100) {
updateColorAdjustFilter(); // Update the filter values dynamically
filters.push(`url(#color-adjust)`);
}
container.style.filter = filters.join(' ');
}
function init() {
applyGlobalStyles();
injectVideoQualityFilters(); // Inject SVG filters for video enhancement
PointerManager.init();
VisualizerManager.init();
disableNativeAmbientMode();
restartEngine();
}
function disableNativeAmbientMode() {
// Only on YouTube, not YouTube Music
if (location.hostname.includes('music.youtube.com')) return;
// Only detect once per page load to avoid spamming the DOM
if (window.rtNativeAmbientDisabled) return;
const findAndDisable = () => {
const regularCanvases = document.querySelectorAll('#cinematics canvas');
const shortsCanvases = document.querySelectorAll('#shorts-cinematic-container canvas');
let found = false;
regularCanvases.forEach(c => {
c.remove();
found = true;
});
shortsCanvases.forEach(c => {
c.remove();
found = true;
});
if (found) {
window.rtNativeAmbientDisabled = true;
// Check storage to ensure the alert is only shown once EVER
chrome.storage.local.get(['ambientAlertShown'], (res) => {
if (!res.ambientAlertShown) {
alert(chrome.i18n.getMessage("native_ambient_mode_disabled"));
chrome.storage.local.set({ ambientAlertShown: true });
}
});
return true;
}
return false;
};
if (findAndDisable()) return;
// If not found yet (because of lazy loading or SPA navigation), wait for it
const observer = new MutationObserver((mutations, obs) => {
if (findAndDisable()) {
obs.disconnect(); // Stop observing once found
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
// ----------------------------------------------------------------------
// VIDEO QUALITY SVG FILTERS
// ----------------------------------------------------------------------
function injectVideoQualityFilters() {
if (document.getElementById('vq-svg-filters')) return; // Already injected
// Generate sharpness filters for different intensity levels (0-100 in steps of 10)
let sharpenFilters = '';
for (let i = 10; i <= 100; i += 10) {
// kernelMatrix intensity scales with sharpness value
const intensity = 0.1 + (i / 100) * 0.9; // 0.1 to 1.0
const center = 1 + (intensity * 3); // 1 to 4
const edge = -intensity; // 0 to -1
sharpenFilters += `
<filter id="sharpen-${i}">
<feConvolveMatrix order="3" preserveAlpha="true"
kernelMatrix="0 ${edge.toFixed(2)} 0
${edge.toFixed(2)} ${center.toFixed(2)} ${edge.toFixed(2)}
0 ${edge.toFixed(2)} 0"/>
</filter>`;
}
const svgContainer = document.createElement('div');
svgContainer.id = 'vq-svg-filters';
svgContainer.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;width:0;height:0;overflow:hidden;">
<defs>
${sharpenFilters}
<!-- Color Adjustment Filter: Dynamic Highlights/Shadows -->
<filter id="color-adjust">
<feComponentTransfer>
<feFuncR type="gamma" amplitude="1" exponent="1" offset="0"/>
<feFuncG type="gamma" amplitude="1" exponent="1" offset="0"/>
<feFuncB type="gamma" amplitude="1" exponent="1" offset="0"/>
</feComponentTransfer>
</filter>
</defs>
</svg>
`;
document.body.insertAdjacentElement('afterbegin', svgContainer);
}
// Update the color-adjust filter dynamically based on highlights/shadows
function updateColorAdjustFilter() {
const filter = document.getElementById('color-adjust');
if (!filter) return;
// Convert 50-150 range to amplitude/exponent adjustments
// highlights > 100 = brighter highlights, shadows > 100 = brighter shadows
const highlightsVal = (config.highlights || 100) / 100; // 0.5 to 1.5
const shadowsVal = (config.shadows || 100) / 100;
// Gamma exponent: < 1 brightens shadows, > 1 darkens shadows
// Amplitude affects overall brightness
const exponent = 1 / highlightsVal; // Inverse for highlights control
const amplitude = shadowsVal;
filter.innerHTML = `
<feComponentTransfer>
<feFuncR type="gamma" amplitude="${amplitude.toFixed(3)}" exponent="${exponent.toFixed(3)}" offset="0"/>
<feFuncG type="gamma" amplitude="${amplitude.toFixed(3)}" exponent="${exponent.toFixed(3)}" offset="0"/>
<feFuncB type="gamma" amplitude="${amplitude.toFixed(3)}" exponent="${exponent.toFixed(3)}" offset="0"/>
</feComponentTransfer>
`;
}
function restartEngine() {
// Teardown
ModernEngine.stop();
AmbientEngine.stop();
if (typeof WebGLEngine !== 'undefined') WebGLEngine.stop();
// Clear Container (Global Projector)
let container = document.getElementById('rt-container');
if (container) {
container.innerHTML = '';
container.remove();
}
// Start appropriate engine
if (config.ambientMode) {
AmbientEngine.start();
} else if (config.webglActive && typeof WebGLEngine !== 'undefined') {
WebGLEngine.init();
} else {
ModernEngine.start();
}
// Ensure visualizer is recreated if needed
if (config.visualizerActive) VisualizerManager.create();
}
// ----------------------------------------------------------------------
// POINTER MANAGER (Inverted Follow)
// ----------------------------------------------------------------------
const PointerManager = (() => {
let active = false;
function init() {
document.addEventListener('mousemove', (e) => {
if (!active || !config.pointerActive || !config.masterSwitch) return;
const container = document.getElementById('rt-container');
if (container) {
// Calculate inverted from center
const cx = window.innerWidth / 2;
const cy = window.innerHeight / 2;
// Invert factor
const dx = (cx - e.clientX) / 50;
const dy = (cy - e.clientY) / 50;
container.style.transform = `translate(${dx}px, ${dy}px)`;
}
});
updateState();
}
function updateState() {
active = config.pointerActive;
const container = document.getElementById('rt-container');
if (!active && container) {
container.style.transform = 'none'; // Reset
}
}
return { init, updateState };
})();
// ----------------------------------------------------------------------
// AUDIO MANAGER (Shared Context)
// ----------------------------------------------------------------------
const AudioManager = (() => {
let context = null;
let analyser = null;
let sources = new WeakMap();
let isInitialized = false;
function init() {
if (!isInitialized) {
try {
const AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0.85;
analyser.fftSize = 512;
analyser.connect(context.destination);
isInitialized = true;
// Auto-resume on user interaction
const resumeHandler = () => {
if (context && context.state === 'suspended') {
context.resume().then(() => {
// Remove listeners once resumed?
// Keep them just in case browser suspends it again (unlikely but possible)
});
}
};
document.addEventListener('click', resumeHandler);
document.addEventListener('keydown', resumeHandler);
} catch (e) {
console.error("Reflectube Audio Init Error:", e);
}
}
}
function resume() {
if (context && context.state === 'suspended') {
context.resume();
}
}
function connect(videoElement) {
if (!videoElement) return;
init();
// Try to resume immediately
resume();
if (sources.has(videoElement)) return; // Already connected
try {
// Check if there's already a source (some other extensions might mess with this, but we try ours)
// Note: createMediaElementSource can only be called once per element.
// If it throws, it means it's already connected.
const source = context.createMediaElementSource(videoElement);
source.connect(analyser);
sources.set(videoElement, source);
} catch (e) {
// Already connected or error
// If already connected by us, WeakMap catches it.
// If connected by external, we might not get audio unless we can hook into it, but usually this throws.
// We ignore to prevent crash.
}
}
function getAnalyser() {
return analyser;
}
function getAudioData(dataArray) {
if (analyser) {
analyser.getByteFrequencyData(dataArray);
}
}
return { init, connect, resume, getAnalyser, getAudioData };
})();
// ----------------------------------------------------------------------
// VISUALIZER MANAGER (Canvas Logic)
// ----------------------------------------------------------------------
const VisualizerManager = (() => {
let active = false;
let canvas = null;
let ctx = null;
let lastColorCheck = 0;
// Smooth color transition
let targetColor = { r: 255, g: 255, b: 255 };
let currentColorRGB = { r: 255, g: 255, b: 255 };
const colorLerpSpeed = 0.05; // Slower = smoother transitions
// For Ocean wave effect
let waveOffset = 0;
// For Bubbles effect
let bubbles = [];
function init() {
updateState();
}
function create() {
if (document.getElementById('rt_visualizer_canvas')) return;
canvas = document.createElement("canvas");
canvas.id = "rt_visualizer_canvas";
canvas.style.cssText = "position: fixed; bottom: 0; left: 0; width: 100%; height: 120px; opacity: 0.85; pointer-events: none; z-index: 99;";
// Logical resolution for crisp rendering
canvas.width = window.innerWidth;
canvas.height = 120;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d', { alpha: true });
// Handle resize
window.addEventListener('resize', () => {
if (canvas) canvas.width = window.innerWidth;
});
if (!active) canvas.style.display = 'none';
applyStyles();
}
function applyStyles() {
if (canvas) {
canvas.style.display = (active && config.masterSwitch) ? 'block' : 'none';
}
}
function updateState() {
active = config.visualizerActive;
const v = document.getElementById('rt_visualizer_canvas');
if (active && !v) create();
else applyStyles();
}
// Smooth color interpolation
function lerpColor() {
currentColorRGB.r += (targetColor.r - currentColorRGB.r) * colorLerpSpeed;
currentColorRGB.g += (targetColor.g - currentColorRGB.g) * colorLerpSpeed;
currentColorRGB.b += (targetColor.b - currentColorRGB.b) * colorLerpSpeed;
}
function getCurrentColor() {
return `rgb(${Math.round(currentColorRGB.r)},${Math.round(currentColorRGB.g)},${Math.round(currentColorRGB.b)})`;
}
// Called by Engines - Main render dispatcher
function updateBars(dataArray, bufferLength) {
if (!active || !config.masterSwitch || !ctx || !canvas) return;
// Smooth color transition each frame
lerpColor();
const type = config.visualizerType || 'bars';
switch (type) {
case 'soundwave':
renderSoundwave(dataArray, bufferLength);
break;
case 'ocean':
renderOcean(dataArray, bufferLength);
break;
case 'bubbles':
renderBubbles(dataArray, bufferLength);
break;
case 'bars':
default:
renderBars(dataArray, bufferLength);
break;
}
}
// ========== BARS VISUALIZER ==========
function renderBars(dataArray, bufferLength) {
const width = canvas.width;
const height = canvas.height;
const barCount = 64;
const barWidth = width / barCount;
const step = Math.floor(bufferLength / barCount);
ctx.clearRect(0, 0, width, height);
const color = getCurrentColor();
ctx.fillStyle = color;
ctx.shadowBlur = 15;
ctx.shadowColor = color;
let x = 0;
for (let i = 0; i < barCount; i++) {
const val = dataArray[i * step] || 0;
const barHeight = (val / 255) * height * 0.85;
if (barHeight > 2) {
// Gradient bar from bottom to top
const gradient = ctx.createLinearGradient(x, height, x, height - barHeight);
gradient.addColorStop(0, color);
gradient.addColorStop(1, `rgba(${Math.round(currentColorRGB.r)},${Math.round(currentColorRGB.g)},${Math.round(currentColorRGB.b)},0.3)`);
ctx.fillStyle = gradient;
// Rounded bars
const radius = Math.min(barWidth / 4, 3);
ctx.beginPath();
ctx.roundRect(x + 1, height - barHeight, barWidth - 3, barHeight, [radius, radius, 0, 0]);
ctx.fill();
}
x += barWidth;
}
}
// ========== SOUNDWAVE VISUALIZER ==========
function renderSoundwave(dataArray, bufferLength) {
const width = canvas.width;
const height = canvas.height;
const centerY = height / 2;
ctx.clearRect(0, 0, width, height);
const color = getCurrentColor();
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.shadowBlur = 20;
ctx.shadowColor = color;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// Main wave
ctx.beginPath();
const sliceWidth = width / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const val = dataArray[i] / 255;
const y = centerY + (val - 0.12) * height * 0.8;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
if (dataArray.every(val => val === 0)) {
ctx.strokeStyle = "rgba(255, 255, 255, 0)";
}
ctx.stroke();
// Mirror wave (reflected, more transparent)
ctx.globalAlpha = 1;
ctx.beginPath();
x = 0;
for (let i = 0; i < bufferLength; i++) {
const val = dataArray[i] / 255;
const y = centerY - (val - 0.82) * height * 0.6;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.stroke();
ctx.globalAlpha = 0.3;
}
// ========== OCEAN WAVE VISUALIZER ==========
function renderOcean(dataArray, bufferLength) {
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
const color = getCurrentColor();
// Calculate average amplitude for wave intensity
let avgAmplitude = 0;
for (let i = 0; i < bufferLength; i++) {
avgAmplitude += dataArray[i];
}
avgAmplitude = (avgAmplitude / bufferLength) / 255;
// Animate wave offset - faster when louder
waveOffset += 0.02 + avgAmplitude * 0.08;
// Dynamic base Y position - waves stay at bottom when quiet, rise when loud
const baseY = height * (0.7 + (1 - avgAmplitude) * 0.25); // 70% to 95% from top
// Draw multiple layered waves
for (let layer = 0; layer < 3; layer++) {
const layerAlpha = (0.4 + avgAmplitude * 0.3) - layer * 0.1;
// Amplitude scales dramatically with audio
const layerAmplitude = (5 + avgAmplitude * 35) * (1 - layer * 0.25);
const layerFrequency = 0.006 + layer * 0.002;
const layerOffset = waveOffset * (1 + layer * 0.4);
const layerY = baseY + layer * 8;
ctx.beginPath();
ctx.moveTo(0, height);
for (let x = 0; x <= width; x += 2) {
// Combine multiple sine waves for organic look
const y = layerY +
Math.sin(x * layerFrequency + layerOffset) * layerAmplitude +
Math.sin(x * layerFrequency * 2.5 + layerOffset * 1.3) * (layerAmplitude * 0.5) +
Math.sin(x * layerFrequency * 0.7 + layerOffset * 0.6) * (layerAmplitude * 0.3);
ctx.lineTo(x, y);
}
ctx.lineTo(width, height);
ctx.closePath();
// Gradient fill
const gradient = ctx.createLinearGradient(0, layerY - layerAmplitude, 0, height);
gradient.addColorStop(0, `rgba(${Math.round(currentColorRGB.r)},${Math.round(currentColorRGB.g)},${Math.round(currentColorRGB.b)},${layerAlpha})`);
gradient.addColorStop(1, `rgba(${Math.round(currentColorRGB.r)},${Math.round(currentColorRGB.g)},${Math.round(currentColorRGB.b)},0.05)`);
ctx.fillStyle = gradient;
ctx.shadowBlur = 8;
ctx.shadowColor = color;
ctx.fill();
}
}
// ========== BUBBLES VISUALIZER ==========
function renderBubbles(dataArray, bufferLength) {
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
const color = getCurrentColor();
// Calculate average amplitude
let avgAmplitude = 0;
for (let i = 0; i < bufferLength; i++) {
avgAmplitude += dataArray[i];
}
avgAmplitude = (avgAmplitude / bufferLength) / 255;
// Spawn new bubbles based on audio intensity
const spawnRate = Math.floor(avgAmplitude * 5) + 1; // 1-6 bubbles per frame
for (let i = 0; i < spawnRate; i++) {
if (bubbles.length < 100 && Math.random() < avgAmplitude + 0.1) {
bubbles.push({
x: Math.random() * width,
y: height + 20,
baseSize: 3 + Math.random() * 12,
speed: 0.5 + Math.random() * 2 + avgAmplitude * 2,
wobble: Math.random() * Math.PI * 2,
wobbleSpeed: 0.02 + Math.random() * 0.03,
opacity: 0.6 + Math.random() * 0.4
});
}
}
// Update and draw bubbles
ctx.shadowBlur = 15;
ctx.shadowColor = color;
for (let i = bubbles.length - 1; i >= 0; i--) {
const b = bubbles[i];
// Move upward
b.y -= b.speed;
b.wobble += b.wobbleSpeed;
// Horizontal wobble
const wobbleX = Math.sin(b.wobble) * 2;
// Fade out as it rises
b.opacity -= 0.003;
// Size reacts to current audio
const sizeMultiplier = 0.6 + avgAmplitude * 1.2;
const currentSize = b.baseSize * sizeMultiplier;
// Remove if off screen or faded
if (b.y < -currentSize || b.opacity <= 0) {
bubbles.splice(i, 1);
continue;
}
// Draw bubble
ctx.beginPath();
ctx.arc(b.x + wobbleX, b.y, currentSize, 0, Math.PI * 2);
// Gradient for 3D effect
const gradient = ctx.createRadialGradient(
b.x + wobbleX - currentSize * 0.3, b.y - currentSize * 0.3, 0,
b.x + wobbleX, b.y, currentSize
);
gradient.addColorStop(0, `rgba(255,255,255,${b.opacity * 0.5})`);
gradient.addColorStop(0.4, `rgba(${Math.round(currentColorRGB.r)},${Math.round(currentColorRGB.g)},${Math.round(currentColorRGB.b)},${b.opacity * 0.7})`);
gradient.addColorStop(1, `rgba(${Math.round(currentColorRGB.r)},${Math.round(currentColorRGB.g)},${Math.round(currentColorRGB.b)},${b.opacity * 0.2})`);
ctx.fillStyle = gradient;
ctx.fill();
// Bubble outline
ctx.strokeStyle = `rgba(255,255,255,${b.opacity * 0.3})`;
ctx.lineWidth = 1;
ctx.stroke();
}
}
function updateColor(ctxSource, width, height) {
if (!active || !config.masterSwitch) return;
const now = Date.now();
if (now - lastColorCheck < 300) return; // Throttle 300ms
lastColorCheck = now;
// Sample center 50% of the screen
const sx = Math.floor(width * 0.25);
const sy = Math.floor(height * 0.25);
const sw = Math.floor(width * 0.5);
const sh = Math.floor(height * 0.5);
if (sw < 1 || sh < 1) return;
try {
const data = ctxSource.getImageData(sx, sy, sw, sh).data;
let totalScore = 0;
let totalR = 0;
let totalG = 0;
let totalB = 0;
// Optimization: Skip pixels (step 20 = examine ~5% of pixels)
const step = 4 * 20;
for (let i = 0; i < data.length; i += step) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const range = max - min;
const score = (range * range) * max;
if (score > 1000) {
totalR += r * score;
totalG += g * score;
totalB += b * score;
totalScore += score;
}
}
if (totalScore > 0) {
let finalR = Math.floor(totalR / totalScore);
let finalG = Math.floor(totalG / totalScore);
let finalB = Math.floor(totalB / totalScore);
const boost = 1.2;
finalR = Math.min(255, finalR * boost);
finalG = Math.min(255, finalG * boost);
finalB = Math.min(255, finalB * boost);
// Set target color for smooth interpolation
targetColor = { r: finalR, g: finalG, b: finalB };
} else {
targetColor = { r: 200, g: 200, b: 200 };
}
} catch (e) { }
}
return { init, updateState, create, updateBars, updateColor };
})();
// ----------------------------------------------------------------------
// EFFECT MANAGER (Hue Loop)
// ----------------------------------------------------------------------
const EffectManager = (() => {
let loopId = null;
let hue = 0;
let lastTime = 0;
function updateState() {
if (config.hueLoop && config.masterSwitch) {
if (!loopId) loopId = requestAnimationFrame(loop);
} else {
if (loopId) cancelAnimationFrame(loopId);
loopId = null;
document.documentElement.style.setProperty('--rt_hue-rotate', '0deg');
}
}
function loop(timestamp) {
if (!loopId) return;
loopId = requestAnimationFrame(loop);
if (document.hidden) return;
if (timestamp - lastTime < 50) return; // 20fps for color cycle is enough
lastTime = timestamp;
hue = (hue + 1) % 360;
document.documentElement.style.setProperty('--rt_hue-rotate', hue + 'deg');
}
return { updateState };
})();
// ----------------------------------------------------------------------
// VIDEO MANAGER (Optimization)
// ----------------------------------------------------------------------
const VideoManager = (() => {
let videos = new Set();
let observer = null;
function init() {
updateList();
if (!observer) {
observer = new MutationObserver((mutations) => {
// Optimization: Debounce or just check type?
updateList();
});
observer.observe(document.body, { childList: true, subtree: true });
}
}
function updateList() {
const nodelist = document.querySelectorAll('video');
videos = new Set(nodelist);
}
function findActive() {
// Efficient search through cached Set
for (let v of videos) {
// Check src to avoid empty video placeholders
if (!v.paused && v.style.display !== 'none' && v.readyState > 2 && v.src && v.src !== '') {
// Prioritize Shorts/Main
if (v.closest('ytd-reel-video-renderer')) return v;
if (!v.closest('ytd-miniplayer')) return v; // Main player preference
return v; // Fallback
}
}
return null; // No valid active video found
}
return { init, findActive };
})();
// ----------------------------------------------------------------------
// THUMBNAIL MANAGER (Fallback for Audio Mode)
// ----------------------------------------------------------------------
const ThumbnailManager = (() => {
let currentId = null;
let currentImage = null;
let isLoading = false;
function getVideoId() {
// Try URL param first (most reliable for YT/YTM)
const urlParams = new URLSearchParams(window.location.search);
const v = urlParams.get('v');
if (v) return v;
return null;
}
function getThumbnail(id) {
if (!id) return null;
if (currentId === id) {
return currentImage; // Return image only if loaded
}
// New ID, fetch
currentId = id;
currentImage = null; // Reset
isLoading = true;
loadBestThumbnail(id).then(img => {
if (currentId === id) {
currentImage = img;
isLoading = false;
}
});
return null; // Not ready yet
}
async function loadBestThumbnail(id) {
// Try qualities in order
const qualities = [
`https://i.ytimg.com/vi/${id}/maxresdefault.jpg`,
`https://i.ytimg.com/vi/${id}/hq720.jpg`,
`https://i.ytimg.com/vi/${id}/sddefault.jpg`,
`https://i.ytimg.com/vi/${id}/hqdefault.jpg`
];
for (let src of qualities) {
try {
const img = await loadImage(src);
return img;
} catch (e) {
// Try next
continue;
}
}
return null;
}
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "Anonymous"; // Crucial for canvas
img.onload = () => {
if (img.width <= 120) {
reject('Too small');
} else {
resolve(img);
}
};
img.onerror = reject;
img.src = src;
});
}
return { getThumbnail, getVideoId };
})();
// ----------------------------------------------------------------------
// WEBGL ENGINE (GPU)
// ----------------------------------------------------------------------
const WebGLEngine = (() => {
let canvas, gl, program;
let texture;
let animationId;
let startTime = 0;
// SHADERS (Liquid Distortion + Chromatic Aberration)
const vsSource = `
attribute vec2 a_position;