-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvu_spectrum.html
More file actions
1185 lines (1012 loc) · 43.3 KB
/
vu_spectrum.html
File metadata and controls
1185 lines (1012 loc) · 43.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio Analysis Console</title>
<style>
:root {
/* --- THEME DEFINITIONS --- */
/* DARK (Default) */
--bg-color: #1a1a1a;
--panel-bg: #252525;
--text-color: #e0e0e0;
--accent-color: #333;
--border-color: #444;
--highlight-color: #4a90e2;
/* Analog Meter Specifics */
--meter-face-1: #2a2a2a;
--meter-face-2: #111;
--meter-bezel: #444;
--meter-text: #ddd;
--meter-needle: #ff3333;
--meter-shadow: rgba(0,0,0,0.5);
/* LED Meter Specifics */
--led-off: #222;
/* Spectrum Analyzer Specifics */
--grid-color: #333;
--bar-top: #ff3333;
--bar-mid: #ffff00;
--bar-bot: #00ff00;
--peak-color: #ffffff;
--font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
[data-theme="light"] {
--bg-color: #f0f2f5;
--panel-bg: #ffffff;
--text-color: #333;
--accent-color: #e0e0e0;
--border-color: #ccc;
--highlight-color: #4a90e2;
--meter-face-1: #fffbf0;
--meter-face-2: #f0e6d2;
--meter-bezel: #aaa;
--meter-text: #333;
--meter-needle: #cc0000;
--meter-shadow: rgba(0,0,0,0.2);
--led-off: #e0e0e0;
--grid-color: #e0e0e0;
--bar-top: #d32f2f;
--bar-mid: #fbc02d;
--bar-bot: #388e3c;
--peak-color: #000;
}
[data-theme="blue"] {
--bg-color: #021019;
--panel-bg: #051e30;
--text-color: #4fc3f7;
--accent-color: #082840;
--border-color: #0d47a1;
--highlight-color: #00e5ff;
--meter-face-1: #052030;
--meter-face-2: #021019;
--meter-bezel: #0d47a1;
--meter-text: #00e5ff;
--meter-needle: #00e5ff;
--meter-shadow: rgba(0,229,255,0.2);
--led-off: #062233;
--grid-color: #132f4c;
--bar-top: #00e5ff;
--bar-mid: #2979ff;
--bar-bot: #1565c0;
--peak-color: #00e5ff;
}
[data-theme="green"] {
--bg-color: #051405;
--panel-bg: #0c260c;
--text-color: #4caf50;
--accent-color: #1b5e20;
--border-color: #2e7d32;
--highlight-color: #00ff00;
--meter-face-1: #0c260c;
--meter-face-2: #000;
--meter-bezel: #33691e;
--meter-text: #66bb6a;
--meter-needle: #00ff00;
--meter-shadow: rgba(0,255,0,0.1);
--led-off: #122b12;
--grid-color: #0f330f;
--bar-top: #ccff90;
--bar-mid: #69f0ae;
--bar-bot: #00c853;
--peak-color: #00ff00;
}
* {
box-sizing: border-box;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: var(--font-family);
margin: 0;
display: flex;
flex-direction: column;
height: 100vh;
transition: all 0.3s ease;
overflow: hidden;
}
/* Header */
.app-header {
background-color: var(--panel-bg);
padding: 12px 20px;
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
}
.app-title {
font-size: 1.5rem;
font-weight: 700;
letter-spacing: 1px;
color: var(--highlight-color);
}
/* Main Toolbar */
.toolbar {
background-color: var(--panel-bg);
padding: 12px 20px;
border-bottom: 1px solid var(--border-color);
display: flex;
gap: 15px;
flex-wrap: wrap;
align-items: center;
justify-content: center;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
z-index: 100;
}
.control-group {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 12px;
border-radius: 6px;
background: rgba(0,0,0,0.1);
}
label {
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 1px;
opacity: 0.8;
}
select, input[type="text"] {
background: var(--bg-color);
color: var(--text-color);
border: 1px solid var(--border-color);
padding: 6px 10px;
border-radius: 4px;
font-family: inherit;
font-size: 0.9rem;
outline: none;
transition: border-color 0.2s;
}
select:hover, input:hover { border-color: var(--highlight-color); }
input[type="text"] { width: 120px; text-align: center; }
/* Checkbox Styling */
input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
accent-color: var(--highlight-color);
}
button {
background: var(--accent-color);
color: var(--text-color);
border: 1px solid var(--border-color);
padding: 6px 20px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
font-size: 0.85rem;
transition: all 0.2s;
}
button:hover {
filter: brightness(1.2);
transform: translateY(-1px);
border-color: var(--highlight-color);
}
button:active { transform: translateY(0); }
/* Status Dot */
.status-light {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #444;
margin-left: 10px;
box-shadow: inset 0 1px 2px rgba(0,0,0,0.5);
transition: all 0.3s;
}
.status-light.connected { background-color: #00e676; box-shadow: 0 0 8px #00e676; }
.status-light.error { background-color: #ff1744; box-shadow: 0 0 8px #ff1744; }
/* Mode Selector */
.mode-selector {
display: flex;
background: var(--accent-color);
border-radius: 6px;
overflow: hidden;
border: 1px solid var(--border-color);
}
.mode-button {
padding: 8px 16px;
background: transparent;
border: none;
cursor: pointer;
font-weight: 600;
transition: all 0.2s;
}
.mode-button.active {
background: var(--highlight-color);
color: white;
}
/* Canvas Area */
.meter-stage {
flex: 1;
position: relative;
width: 100%;
height: 100%;
background: radial-gradient(circle at center, var(--bg-color), #000);
}
.spectrum-stage {
flex: 1;
position: relative;
width: 100%;
height: 100%;
background: radial-gradient(circle at center, var(--panel-bg), var(--bg-color));
}
canvas {
display: block;
width: 100%;
height: 100%;
}
.overlay-fps {
position: absolute;
bottom: 10px;
right: 10px;
font-family: monospace;
font-size: 0.7rem;
opacity: 0.3;
pointer-events: none;
}
/* Hide/Show sections based on mode */
.vu-section { display: block; }
.spectrum-section { display: none; }
.mode-vu .vu-section { display: block; }
.mode-vu .spectrum-section { display: none; }
.mode-spectrum .vu-section { display: none; }
.mode-spectrum .spectrum-section { display: block; }
</style>
</head>
<body class="mode-vu">
<div class="app-header">
<div class="app-title">AUDIO ANALYSIS CONSOLE</div>
<div class="mode-selector">
<button class="mode-button active" onclick="switchMode('vu')">VU METERS</button>
<button class="mode-button" onclick="switchMode('spectrum')">SPECTRUM ANALYZER</button>
</div>
</div>
<div class="toolbar">
<!-- Connection Controls -->
<div class="control-group">
<label>IP Address</label>
<input type="text" id="ipAddress" placeholder="192.168.1.X">
<button onclick="toggleConnection()" id="connectBtn">CONNECT</button>
<div class="status-light" id="statusIndicator"></div>
</div>
<!-- VU Meter Controls -->
<div class="control-group vu-section">
<label>Display</label>
<select id="meterStyle" onchange="requestDraw()">
<option value="analog" selected>Analog Pro</option>
<option value="led">Digital LED</option>
</select>
</div>
<div class="control-group vu-section">
<label>Gain</label>
<select id="gain">
<option value="0.5">0.5x</option>
<option value="1.0">1.0x</option>
<option value="2.0">2.0x</option>
<option value="4.0" selected>4.0x</option>
<option value="8.0">8.0x</option>
<option value="12.0">12.0x</option>
</select>
</div>
<div class="control-group vu-section">
<label>Decay</label>
<select id="decay">
<option value="15.0">Fast</option>
<option value="8.0" selected>Normal</option>
<option value="4.0">Slow</option>
<option value="2.0">Fluid</option>
</select>
</div>
<div class="control-group vu-section">
<label title="Add random variation to channels">Stereo Sim</label>
<input type="checkbox" id="stereoSim">
<select id="noiseAmt">
<option value="0.10">10%</option>
<option value="0.20" selected>20%</option>
<option value="0.30">30%</option>
<option value="0.40">40%</option>
</select>
</div>
<!-- Spectrum Analyzer Controls -->
<div class="control-group spectrum-section">
<label>Mode</label>
<select id="vizMode">
<option value="bars">Bars</option>
<option value="line">Line</option>
<option value="mirror">Mirror</option>
</select>
</div>
<div class="control-group spectrum-section">
<label>Gain</label>
<select id="specGain">
<option value="1.0">1x</option>
<option value="2.0">2x</option>
<option value="4.0" selected>4x</option>
<option value="8.0">8x</option>
<option value="12.0">12x</option>
</select>
</div>
<div class="control-group spectrum-section">
<label>Decay</label>
<select id="specSmooth">
<option value="0.6">Fast</option>
<option value="0.8" selected>Normal</option>
<option value="0.9">Slow</option>
<option value="0.95">Fluid</option>
</select>
</div>
<!-- Theme Selector -->
<div class="control-group">
<label>Theme</label>
<select id="themeSelector">
<option value="dark">Studio Dark</option>
<option value="light">Vintage Light</option>
<option value="blue">Cyber Blue</option>
<option value="green">Matrix Green</option>
</select>
</div>
</div>
<!-- VU Meter Display -->
<div class="meter-stage vu-section" id="vuStage">
<canvas id="vuCanvas"></canvas>
<div class="overlay-fps">RENDER: GPU // FPS: <span id="vuFps">--</span></div>
</div>
<!-- Spectrum Analyzer Display -->
<div class="spectrum-stage spectrum-section" id="specStage">
<canvas id="specCanvas"></canvas>
<div class="overlay-fps">FFT: 64 BANDS // FPS: <span id="specFps">--</span></div>
</div>
<script>
// --- SYSTEM CONFIG ---
// Canvas elements and contexts for both VU meters and spectrum analyzer
const vuCanvas = document.getElementById('vuCanvas');
const vuCtx = vuCanvas.getContext('2d', { alpha: false });
const specCanvas = document.getElementById('specCanvas');
const specCtx = specCanvas.getContext('2d', { alpha: false });
// UI control elements
const ipInput = document.getElementById('ipAddress');
const connectBtn = document.getElementById('connectBtn');
const statusLight = document.getElementById('statusIndicator');
const themeSelector = document.getElementById('themeSelector');
const stereoSimCheck = document.getElementById('stereoSim');
const noiseAmtSelect = document.getElementById('noiseAmt');
// Detect if running on device
const isLocal = window.location.protocol === 'file:';
if (!isLocal) {
// Auto-populate IP with current host when running on network
ipInput.value = window.location.hostname;
// AUTO CONNECT ON LOAD IF ON NETWORK
window.onload = connect;
} else {
// Default IP for local testing
ipInput.value = "192.168.1.57";
}
// --- APP STATE ---
// Connection and animation state
let isConnected = false;
let pollInterval = null;
let animFrame = null;
let lastTime = 0;
// Frame rate tracking
let vuFrameCount = 0;
let specFrameCount = 0;
let lastVuFpsTime = 0;
let lastSpecFpsTime = 0;
// VU Meter State - track current and target volumes for both channels
let volL = 0;
let volR = 0;
let targetVolL = 0;
let targetVolR = 0;
// Spectrum Analyzer State
const numBars = 64; // Number of frequency bands to display
const BASE_SENSITIVITY = 2000; // Base sensitivity for FFT calculation
const PADDING_TOP = 20; // Top padding for spectrum display
const PADDING_BOTTOM = 10; // Bottom padding for spectrum display
// Arrays to store current bar values, peak values, and peak hold times
let barValues = new Array(numBars).fill(0);
let peakValues = new Array(numBars).fill(0);
let peakHoldTime = new Array(numBars).fill(0);
// --- MODE SWITCHING ---
// Function to switch between VU meter and spectrum analyzer modes
function switchMode(mode) {
// Update active button state
document.querySelectorAll('.mode-button').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`.mode-button[onclick="switchMode('${mode}')"]`).classList.add('active');
// Update body class to show/hide appropriate sections
document.body.className = `mode-${mode}`;
// Resize the appropriate canvas
if (mode === 'vu') {
resizeVuCanvas();
} else {
resizeSpecCanvas();
}
// Request a redraw
requestDraw();
}
// --- EVENTS ---
// Theme change handler
themeSelector.addEventListener('change', (e) => {
document.documentElement.setAttribute('data-theme', e.target.value);
requestDraw();
});
// Window resize handler
window.addEventListener('resize', () => {
if (document.body.classList.contains('mode-vu')) {
resizeVuCanvas();
} else {
resizeSpecCanvas();
}
});
// --- INITIALIZATION ---
// Function to resize VU meter canvas to fit its container
function resizeVuCanvas() {
const stage = document.getElementById('vuStage');
const dpr = window.devicePixelRatio || 1;
vuCanvas.width = stage.clientWidth * dpr;
vuCanvas.height = stage.clientHeight * dpr;
vuCtx.scale(dpr, dpr);
requestDraw();
}
// Function to resize spectrum analyzer canvas to fit its container
function resizeSpecCanvas() {
const stage = document.getElementById('specStage');
const dpr = window.devicePixelRatio || 1;
specCanvas.width = stage.clientWidth * dpr;
specCanvas.height = stage.clientHeight * dpr;
specCtx.scale(dpr, dpr);
}
// --- NETWORK LOGIC ---
// Toggle connection between connected and disconnected states
function toggleConnection() {
if (isConnected) disconnect();
else connect();
}
// Establish connection to audio data source
function connect() {
let ip = ipInput.value.trim();
if(!ip) ip = window.location.hostname;
// Update UI for connected state
connectBtn.innerText = "DISCONNECT";
isConnected = true;
statusLight.className = "status-light connected";
// Use relative path if IP matches current host (avoids CORS)
let url = (ip === window.location.hostname && !isLocal) ? '/data' : `http://${ip}/data`;
// Set up polling interval to fetch audio data
pollInterval = setInterval(() => {
fetch(url)
.then(r => r.json())
.then(json => {
// Process data for both VU meters and spectrum analyzer
processVUData(json.data);
processSpectrumData(json.data);
})
.catch(e => {
console.error(e);
statusLight.className = "status-light error";
});
}, 40); // Poll every 40ms (~25fps)
// Start animation loop
loop(0);
}
// Disconnect from audio data source
function disconnect() {
// Clean up intervals and animation frames
clearInterval(pollInterval);
cancelAnimationFrame(animFrame);
// Update UI for disconnected state
isConnected = false;
connectBtn.innerText = "CONNECT";
statusLight.className = "status-light";
// Reset audio data
volL = 0; volR = 0; targetVolL = 0; targetVolR = 0;
barValues.fill(0);
// Request final draw to show reset state
requestDraw();
}
// Process audio data for VU meters
function processVUData(data) {
// Find maximum absolute value in the audio data
let maxVal = 0;
for (let v of data) {
if (Math.abs(v) > maxVal) maxVal = Math.abs(v);
}
// Apply gain to the volume
const gain = parseFloat(document.getElementById('gain').value);
let baseVol = (maxVal * gain) / 18000;
// --- STEREO SIMULATION LOGIC ---
// Add random variation to channels if stereo simulation is enabled
if (stereoSimCheck.checked) {
const noise = parseFloat(noiseAmtSelect.value);
const jitterL = (Math.random() - 0.5) * 2.0 * noise;
const jitterR = (Math.random() - 0.5) * 2.0 * noise;
targetVolL = baseVol + (baseVol * jitterL);
targetVolR = baseVol + (baseVol * jitterR);
} else {
// Use same volume for both channels
targetVolL = baseVol;
targetVolR = baseVol;
}
// Clamp volume values to valid range
if (targetVolL > 1.2) targetVolL = 1.2;
if (targetVolR > 1.2) targetVolR = 1.2;
if (targetVolL < 0) targetVolL = 0;
if (targetVolR < 0) targetVolR = 0;
// Update connection status
statusLight.className = "status-light connected";
}
// Process audio data for spectrum analyzer using FFT
function processSpectrumData(waveform) {
const N = waveform.length; // Number of samples
const gain = parseFloat(document.getElementById('specGain').value);
// Calculate FFT for each frequency band
for (let k = 0; k < numBars; k++) {
let real = 0;
let imag = 0;
// Calculate frequency index for this bar
let freqIndex = Math.floor((k + 1) * 1.5);
// Perform DFT calculation for this frequency
for (let n = 0; n < N; n++) {
// Apply Hann window to reduce spectral leakage
const window = 0.5 * (1 - Math.cos((2 * Math.PI * n) / (N - 1)));
const sample = waveform[n] * window;
const angle = (2 * Math.PI * freqIndex * n) / N;
real += sample * Math.cos(angle);
imag += sample * Math.sin(angle);
}
// Calculate magnitude and normalize
let mag = Math.sqrt(real * real + imag * imag);
let val = ((mag / N) * gain) / BASE_SENSITIVITY;
// Clamp value and update bar if this is a new peak
if (val > 1.0) val = 1.0;
if (val > barValues[k]) {
barValues[k] = val;
}
}
// Update connection status
statusLight.className = "status-light connected";
}
// --- PHYSICS LOOP ---
// Main animation loop that updates and renders both VU meters and spectrum analyzer
function loop(timestamp) {
if (!isConnected) return;
// Calculate time delta for frame-independent animation
const dt = (timestamp - lastTime) / 1000;
lastTime = timestamp;
// FPS calculation and display
vuFrameCount++;
specFrameCount++;
if (timestamp - lastVuFpsTime >= 1000) {
document.getElementById('vuFps').innerText = vuFrameCount;
vuFrameCount = 0;
lastVuFpsTime = timestamp;
}
if (timestamp - lastSpecFpsTime >= 1000) {
document.getElementById('specFps').innerText = specFrameCount;
specFrameCount = 0;
lastSpecFpsTime = timestamp;
}
// VU Meter Physics - smooth volume changes with attack/decay
const speed = parseFloat(document.getElementById('decay').value);
// --- LEFT CHANNEL PHYSICS ---
if (targetVolL > volL) {
// Attack phase - faster response when volume is increasing
volL += (targetVolL - volL) * speed * dt;
} else {
// Decay phase - slower response when volume is decreasing
volL += (targetVolL - volL) * (speed * 0.6) * dt;
}
if (volL < 0.005) volL = 0;
// --- RIGHT CHANNEL PHYSICS ---
if (targetVolR > volR) {
volR += (targetVolR - volR) * speed * dt;
} else {
volR += (targetVolR - volR) * (speed * 0.6) * dt;
}
if (volR < 0.005) volR = 0;
// Spectrum Analyzer Physics - smooth bar decay and peak hold
const decayRate = parseFloat(document.getElementById('specSmooth').value);
const gravity = 0.5 * dt; // Gravity effect for peak decay
for (let i = 0; i < numBars; i++) {
// Apply decay to current bar value
barValues[i] *= decayRate;
if (barValues[i] < 0.01) barValues[i] = 0;
// Update peak values with hold time
if (barValues[i] > peakValues[i]) {
peakValues[i] = barValues[i];
peakHoldTime[i] = 0.5; // Reset hold time when new peak is set
} else {
if (peakHoldTime[i] > 0) {
// Decrease hold time if still in hold period
peakHoldTime[i] -= dt;
} else {
// Apply gravity to peak after hold time expires
peakValues[i] -= gravity;
}
}
// Ensure peak doesn't go below zero
if (peakValues[i] < 0) peakValues[i] = 0;
}
// Render the current display
draw();
// Request next animation frame
animFrame = requestAnimationFrame(loop);
}
// Request a redraw (used when not connected to show static state)
function requestDraw() {
if (!isConnected) draw();
}
// --- RENDERER ---
// Main draw function that delegates to appropriate renderer based on mode
function draw() {
if (document.body.classList.contains('mode-vu')) {
drawVUMeter();
} else {
drawSpectrum();
}
}
// Render VU meters based on selected style (analog or LED)
function drawVUMeter() {
const stage = document.getElementById('vuStage');
const w = stage.clientWidth;
const h = stage.clientHeight;
const style = document.getElementById('meterStyle').value;
// Clear canvas
vuCtx.clearRect(0, 0, w, h);
if (style === 'led') {
// For LED style: split height for vertical stacking (one on top of the other)
const splitH = h / 2;
drawLedMeter(0, 0, w, splitH, volL, "LEFT CHANNEL");
drawLedMeter(0, splitH, w, splitH, volR, "RIGHT CHANNEL");
} else {
// For analog style: split width for horizontal placement
const splitW = w / 2;
drawFancyAnalog(0, 0, splitW, h, volL, "LEFT");
drawFancyAnalog(splitW, 0, splitW, h, volR, "RIGHT");
}
}
// Render spectrum analyzer based on selected visualization mode
function drawSpectrum() {
const stage = document.getElementById('specStage');
const w = stage.clientWidth;
const h = stage.clientHeight;
const mode = document.getElementById('vizMode').value;
// Clear canvas and draw grid
specCtx.clearRect(0, 0, w, h);
drawGrid(w, h);
// Draw the selected visualization mode
if (mode === 'mirror') {
drawBars(w, h, true);
} else if (mode === 'line') {
drawLine(w, h);
} else {
drawBars(w, h, false);
}
}
// --- COMPONENT: FANCY ANALOG METER ---
// Draw a professional-looking analog VU meter
function drawFancyAnalog(x, y, w, h, val, label) {
const targetAspect = 1.8; // Aspect ratio for the meter
const margin = 20; // Margin around the meter
// Skip if area is too small
if (w <= margin * 2 || h <= margin * 2) return;
// Calculate meter dimensions maintaining aspect ratio
let meterW = w - (margin * 2);
let meterH = meterW / targetAspect;
// Adjust if height is the limiting factor
if (meterH > h - (margin * 2)) {
meterH = h - (margin * 2);
meterW = meterH * targetAspect;
}
// Center the meter in the available space
const mx = x + (w - meterW) / 2;
const my = y + (h - meterH) / 2;
// Get theme colors
const styles = getComputedStyle(document.body);
const colFace1 = styles.getPropertyValue('--meter-face-1').trim();
const colFace2 = styles.getPropertyValue('--meter-face-2').trim();
const colBezel = styles.getPropertyValue('--meter-bezel').trim();
const colText = styles.getPropertyValue('--meter-text').trim();
const colNeedle = styles.getPropertyValue('--meter-needle').trim();
vuCtx.save();
// 1. BEZEL - outer frame of the meter
roundedRect(vuCtx, mx, my, meterW, meterH, 12);
let gradBezel = vuCtx.createLinearGradient(mx, my, mx, my + meterH);
gradBezel.addColorStop(0, colBezel);
gradBezel.addColorStop(0.5, "#666");
gradBezel.addColorStop(1, colBezel);
vuCtx.fillStyle = gradBezel;
vuCtx.fill();
// 2. FACE - inner area of the meter
const border = 6;
roundedRect(vuCtx, mx + border, my + border, meterW - (border*2), meterH - (border*2), 8);
let gradFace = vuCtx.createRadialGradient(
mx + meterW/2, my + meterH, 10,
mx + meterW/2, my + meterH/1.5, meterW
);
gradFace.addColorStop(0, colFace1);
gradFace.addColorStop(1, colFace2);
vuCtx.fillStyle = gradFace;
vuCtx.fill();
vuCtx.strokeStyle = "rgba(0,0,0,0.3)";
vuCtx.lineWidth = 2;
vuCtx.stroke();
// 3. SCALE - arc for the meter scale
const pivotX = mx + meterW / 2;
const pivotY = my + meterH * 0.85;
const radius = meterH * 0.75;
const startAngle = Math.PI * 1.2; // Start angle (240 degrees)
const endAngle = Math.PI * 1.8; // End angle (300 degrees)
const totalAngle = endAngle - startAngle;
// 4. TICKS - markings on the scale
vuCtx.strokeStyle = colText;
vuCtx.fillStyle = colText;
vuCtx.textAlign = "center";
vuCtx.textBaseline = "middle";
vuCtx.font = `bold ${meterW * 0.035}px sans-serif`;
const ticks = 10;
for (let i = 0; i <= ticks; i++) {
const pct = i / ticks;
const theta = startAngle + (pct * totalAngle);
// Determine if this is a major or minor tick
const isMajor = (i % 5 === 0);
const tickLen = isMajor ? meterH * 0.1 : meterH * 0.05;
// Calculate tick endpoints
const x1 = pivotX + Math.cos(theta) * (radius - tickLen);
const y1 = pivotY + Math.sin(theta) * (radius - tickLen);
const x2 = pivotX + Math.cos(theta) * radius;
const y2 = pivotY + Math.sin(theta) * radius;
// Change color to red for high levels
if (pct > 0.7) vuCtx.strokeStyle = "#ff3333";
else vuCtx.strokeStyle = colText;
// Draw the tick
vuCtx.lineWidth = isMajor ? 3 : 1.5;
vuCtx.beginPath();
vuCtx.moveTo(x1, y1);
vuCtx.lineTo(x2, y2);
vuCtx.stroke();
// Add labels for major ticks
if (isMajor) {
const labelDist = radius - tickLen - 15;
const lx = pivotX + Math.cos(theta) * labelDist;
const ly = pivotY + Math.sin(theta) * labelDist;
// Set label text based on position
let txt = "";
if (i===0) txt = "-20";
if (i===5) txt = "0";
if (i===10) txt = "+3";
// Set label color (red for high levels)
vuCtx.fillStyle = (pct > 0.7) ? "#ff3333" : colText;
vuCtx.fillText(txt, lx, ly);
}
}
// 5. LABEL - meter title and channel label
vuCtx.fillStyle = colText;
vuCtx.font = `bold ${meterW * 0.05}px sans-serif`;
vuCtx.fillText("VU", pivotX, my + meterH * 0.35);
vuCtx.font = `${meterW * 0.03}px sans-serif`;
vuCtx.fillStyle = "#888";
vuCtx.fillText(label, pivotX, my + meterH * 0.5);
// 6. NEEDLE - the moving indicator
let safeVal = Math.min(Math.max(val, 0), 1.2);
let needlePct = safeVal;
// Non-linear mapping for the upper range
if (needlePct > 1) needlePct = 1 + (safeVal-1)*0.5;
// Calculate needle angle based on value
const needleAngle = startAngle + (needlePct * totalAngle);
// Draw needle shadow
vuCtx.save();
vuCtx.translate(5, 5);
drawNeedleShape(vuCtx, pivotX, pivotY, radius * 0.95, needleAngle, "rgba(0,0,0,0.3)");
vuCtx.restore();
// Draw main needle
drawNeedleShape(vuCtx, pivotX, pivotY, radius * 0.95, needleAngle, colNeedle);
// Draw needle pivot
vuCtx.beginPath();
vuCtx.arc(pivotX, pivotY, meterW * 0.03, 0, Math.PI*2);
let gradCap = vuCtx.createLinearGradient(pivotX, pivotY-10, pivotX, pivotY+10);
gradCap.addColorStop(0, "#666");
gradCap.addColorStop(1, "#111");
vuCtx.fillStyle = gradCap;
vuCtx.fill();
// 7. GLASS - reflective effect on the meter face
vuCtx.globalCompositeOperation = "source-over";
let gradGlass = vuCtx.createLinearGradient(mx, my, mx, my + meterH * 0.6);
gradGlass.addColorStop(0, "rgba(255,255,255,0.1)");
gradGlass.addColorStop(1, "rgba(255,255,255,0)");
roundedRect(vuCtx, mx+border, my+border, meterW-(border*2), meterH*0.5, 6);
vuCtx.fillStyle = gradGlass;
vuCtx.fill();
vuCtx.restore();
}
// Draw a needle shape at the specified position and angle
function drawNeedleShape(ctx, x, y, len, theta, color) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(0, -2);
ctx.lineTo(len, 0);
ctx.lineTo(0, 2);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
// Draw a rectangle with rounded corners
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
// --- COMPONENT: LED METER ---
// Draw a horizontal LED VU meter (vertical stacking handled by parent function)
function drawLedMeter(x, y, w, h, val, label) {
const styles = getComputedStyle(document.body);
const colLedOff = styles.getPropertyValue('--led-off').trim();