-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2822 lines (2385 loc) · 143 KB
/
Copy pathapp.py
File metadata and controls
2822 lines (2385 loc) · 143 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
import numpy as np
import requests
import scipy.signal as signal
import scipy.io.wavfile as wavfile
import scipy.fft as fft
from scipy.optimize import minimize_scalar
import json
import base64
import sys
import os
import time
import traceback
from flask import Flask, request, jsonify, render_template
import webbrowser
import threading
app = Flask(__name__)
# Default Globals (Can be overridden by the web UI)
REW_API_URL = "http://localhost:4735"
TARGET_SAMPLE_RATE = 48000
FILTER_TAPS = 65536
APP_STATE = {}
# ==============================================================================
# DSP & REW API FUNCTIONS
# ==============================================================================
def log_smoothed_fast(data, freqs, fraction=3, variable=False):
smoothed = np.empty_like(data)
smoothed[0] = data[0]
df = freqs[1] - freqs[0]
cumsum = np.concatenate(([0.0], np.cumsum(data, dtype=np.float64)))
for i in range(1, len(freqs)):
f = freqs[i]
if f == 0: continue
if variable:
if f <= 100.0: current_fraction = 48.0
elif f >= 10000.0: current_fraction = 3.0
else:
t = (np.log10(f) - 2.0) / 2.0
current_fraction = 48.0 - t * 45.0
else:
current_fraction = fraction
w = f * (2**(1.0/(2.0*current_fraction)) - 2**(-1.0/(2.0*current_fraction)))
bin_w = int(max(1, round(w / df)))
if bin_w <= 1:
smoothed[i] = data[i]
continue
start = max(0, i - bin_w // 2)
end = min(len(data), i + (bin_w // 2) + 1)
smoothed[i] = (cumsum[end] - cumsum[start]) / (end - start)
return smoothed
def erb_smoothed_fast(data, freqs):
"""Applies Equivalent Rectangular Bandwidth (ERB) smoothing to magnitude data."""
smoothed = np.empty_like(data)
smoothed[0] = data[0]
df = freqs[1] - freqs[0]
if df <= 0: return smoothed
cumsum = np.concatenate(([0.0], np.cumsum(data, dtype=np.float64)))
for i in range(1, len(freqs)):
f = freqs[i]
if f <= 0:
smoothed[i] = data[i]
continue
# Moore and Glasberg (1983) ERB formula
erb_bw = 24.7 * ((4.37 * f / 1000.0) + 1.0)
bin_w = int(max(1, round(erb_bw / df)))
if bin_w <= 1:
smoothed[i] = data[i]
continue
start = max(0, i - bin_w // 2)
end = min(len(data), i + (bin_w // 2) + 1)
smoothed[i] = (cumsum[end] - cumsum[start]) / (end - start)
return smoothed
def detect_room_modes(freqs, mag_raw, min_freq=20.0, max_freq=120.0, max_modes=3):
mag_smoothed = log_smoothed_fast(mag_raw, freqs, fraction=24, variable=False)
mag_db = 20 * np.log10(np.maximum(mag_smoothed, 1e-12))
df = freqs[1] - freqs[0]
if df <= 0: return[]
# Lower prominence to 2.5dB to catch fundamentals that might be suppressed at mic position
dist_bins = max(1, int(5.0 / df))
peaks, properties = signal.find_peaks(mag_db, prominence=2.5, distance=dist_bins)
valid_peaks =[]
for i, p in enumerate(peaks):
if min_freq <= freqs[p] <= max_freq:
valid_peaks.append((freqs[p], properties['prominences'][i]))
# Sort by frequency to find fundamentals (Length > Width > Height)
valid_peaks.sort(key=lambda x: x[0])
# Return the first max_modes that sit at the lowest frequencies
return valid_peaks[:max_modes]
def get_rew_measurements():
try:
response = requests.get(f"{REW_API_URL}/measurements")
response.raise_for_status()
meas_ids = response.json()
detailed_measurements = {}
for m_id in meas_ids:
m_id = str(m_id)
info_response = requests.get(f"{REW_API_URL}/measurements/{m_id}")
if info_response.status_code == 200:
detailed_measurements[m_id] = info_response.json()
else:
detailed_measurements[m_id] = {'title': "Unknown Title"}
return detailed_measurements
except requests.exceptions.ConnectionError:
raise ConnectionError(f"[!] Could not connect to REW at {REW_API_URL}. Is the API Server enabled?")
def fetch_ir_data(meas_id):
endpoints =[f"{REW_API_URL}/measurements/{meas_id}/impulse-response", f"{REW_API_URL}/measurements/{meas_id}"]
data = None
for ep in endpoints:
res = requests.get(ep)
if res.status_code == 200:
data = res.json()
break
if data is None: raise ValueError(f"API returned 404 for ID {meas_id}.")
if isinstance(data, list): return np.array(data, dtype=np.float32)
b64_str = None
if isinstance(data, str): b64_str = data
elif isinstance(data, dict):
for key in['impulseResponse', 'ir', 'data', 'samples', 'y']:
if key in data and isinstance(data[key], str):
b64_str = data[key]
break
if not b64_str:
for v in data.values():
if isinstance(v, str) and len(v) > 1000:
b64_str = v
break
try:
return np.frombuffer(base64.b64decode(b64_str), dtype='>f4').astype(np.float32)
except Exception as e:
raise ValueError(f"Failed to decode Base64: {e}")
def fetch_fr_data(meas_id):
"""
Fetches frequency response data from the REW API.
Supports linear and log spacing, Base64 or JSON lists, and multiple key variants.
"""
res = requests.get(f"{REW_API_URL}/measurements/{meas_id}/frequency-response")
if res.status_code != 200:
raise ValueError(f"API returned {res.status_code} fetching Frequency Response for ID {meas_id}")
data = res.json()
# --- Format 1: Implicit Frequencies (startFreq + step/ppo) ---
# This matches the core REW API 'FrequencyResponse' object structure.
# We make it robust by checking for common key variants (singular, plural, smoothed).
if isinstance(data, dict) and 'startFreq' in data:
mag_key = next((k for k in ['magnitude', 'magnitudes', 'smoothedMagnitude'] if k in data), None)
if mag_key:
start_freq = float(data['startFreq'])
# Use pointsPerOctave (log) or freqStep (linear)
if 'freqStep' in data:
freq_step = float(data['freqStep'])
is_log = 1.0 < freq_step < 1.1
elif 'pointsPerOctave' in data or 'ppo' in data:
ppo_key = 'pointsPerOctave' if 'pointsPerOctave' in data else 'ppo'
freq_step = 2.0**(1.0 / float(data[ppo_key]))
is_log = True
else:
# Default fallback (unlikely, but prevents crash)
freq_step = 1.0
is_log = False
mag_val = data[mag_key]
if isinstance(mag_val, str):
mags = np.frombuffer(base64.b64decode(mag_val), dtype='>f4').astype(np.float32)
else:
mags = np.array(mag_val, dtype=np.float32)
if is_log:
freqs = start_freq * (freq_step ** np.arange(len(mags)))
else:
freqs = start_freq + np.arange(len(mags)) * freq_step
return freqs.astype(np.float32), mags
# --- Format 2: Explicit Frequencies & Magnitudes in a Dictionary ---
# e.g. {"frequencies": [...], "magnitudes": [...]} or {"f": "Base64", "m": "Base64"}
if isinstance(data, dict):
freq_key = next((k for k in data.keys() if k.lower() in ['freq', 'frequencies', 'freqs', 'f', 'frequency']), None)
mag_key = next((k for k in data.keys() if k.lower() in ['mag', 'magnitudes', 'mags', 'm', 'magnitude', 'spl', 'smoothedmagnitude']), None)
if freq_key and mag_key:
f_val = data[freq_key]
m_val = data[mag_key]
# Handle Base64-encoded arrays inside the keys
if isinstance(f_val, str):
freqs = np.frombuffer(base64.b64decode(f_val), dtype='>f4').astype(np.float32)
else:
freqs = np.array(f_val, dtype=np.float32)
if isinstance(m_val, str):
mags = np.frombuffer(base64.b64decode(m_val), dtype='>f4').astype(np.float32)
else:
mags = np.array(m_val, dtype=np.float32)
return freqs, mags
# --- Format 3: List of Point Dictionaries ---
# e.g. [{"f": 20, "m": 75}, {"f": 21, "m": 76}, ...]
if isinstance(data, list) and len(data) > 0 and isinstance(data[0], dict):
freq_key = next((k for k in data[0].keys() if k.lower() in ['freq', 'frequency', 'f']), None)
mag_key = next((k for k in data[0].keys() if k.lower() in ['mag', 'magnitude', 'm', 'spl']), None)
if freq_key and mag_key:
return np.array([pt[freq_key] for pt in data], dtype=np.float32), np.array([pt[mag_key] for pt in data], dtype=np.float32)
# --- Format 4: List of Lists ---
# e.g. [[20, 75], [21, 76], ...]
if isinstance(data, list) and len(data) > 0 and isinstance(data[0], list) and len(data[0]) >= 2:
return np.array([pt[0] for pt in data], dtype=np.float32), np.array([pt[1] for pt in data], dtype=np.float32)
# If we reached here, parsing failed. Log keys for debugging.
keys = list(data.keys()) if isinstance(data, dict) else f"List (len={len(data)})"
raise ValueError(f"Unrecognized frequency response format from REW API for ID {meas_id}. Data keys: {keys}")
def parse_rew_house_curve(b64_str, target_freqs):
"""
Parses a base64 encoded REW-style house curve (.txt) and interpolates it to match target_freqs.
Returns: A magnitude array (linear, not real dB) representing the house curve shape.
"""
try:
content = base64.b64decode(b64_str).decode('utf-8')
freqs_list = []
db_list = []
for line in content.split('\n'):
line = line.strip()
# Ignore comments and empty lines
if not line or line.startswith('*') or line.startswith('//') or line.startswith('#'):
continue
# Extract numbers (handles standard space or tab separation)
parts = line.split()
if len(parts) >= 2:
try:
f = float(parts[0])
db = float(parts[1])
freqs_list.append(f)
db_list.append(db)
except ValueError:
continue
if not freqs_list:
return None
freqs_arr = np.array(freqs_list)
db_arr = np.array(db_list)
# Sort to ensure monotonic increasing frequencies for numpy.interp
sort_idx = np.argsort(freqs_arr)
freqs_arr = freqs_arr[sort_idx]
db_arr = db_arr[sort_idx]
# Interpolate onto our high-resolution frequency grid
# Extrapolate flat ends beyond the defined points of the custom curve
db_interp = np.interp(target_freqs, freqs_arr, db_arr)
# Convert from dB to linear magnitude multiplier
# Normalize curve so 0 is unity gain anchor
db_interp = db_interp - np.max(db_interp)
linear_mag_curve = 10 ** (db_interp / 20.0)
return linear_mag_curve
except Exception as e:
print(f"Error parsing custom house curve: {e}")
return None
def generate_crossover(freqs, fc, btype, crossover_type='lr4', phase_type='linear'):
"""
Generates a crossover filter (minimum or linear phase).
btype: 'highpass' or 'lowpass'
crossover_type: e.g., 'lr4', 'bw2', 'bw4', 'none'
phase_type: 'linear' or 'minimum'
"""
if crossover_type.lower() == 'none' or crossover_type.lower() == 'bypass':
return np.ones_like(freqs, dtype=np.complex128)
nyq = TARGET_SAMPLE_RATE / 2.0
norm_fc = max(min(fc / nyq, 0.99), 1e-5)
# Parse crossover type and order
if len(crossover_type) < 3:
ctype = 'lr'
order = 4
else:
ctype = crossover_type[:2].lower()
try:
order = int(crossover_type[2:])
except ValueError:
order = 4
# Generate the complex response h based on type
if ctype == 'bw':
b, a = signal.butter(order, norm_fc, btype=btype, analog=False)
w, h = signal.freqz(b, a, worN=freqs, fs=TARGET_SAMPLE_RATE)
elif ctype == 'bs':
b, a = signal.bessel(order, norm_fc, btype=btype, analog=False, norm='phase')
w, h = signal.freqz(b, a, worN=freqs, fs=TARGET_SAMPLE_RATE)
else: # Linkwitz-Riley (Default)
bw_order = max(1, order // 2)
b, a = signal.butter(bw_order, norm_fc, btype=btype, analog=False)
w, h = signal.freqz(b, a, worN=freqs, fs=TARGET_SAMPLE_RATE)
h = h * h # Square Butterworth for LR
if phase_type.lower() == 'minimum':
return h # Return the complex response with its native minimum phase
else:
return np.abs(h) + 0j # Zero phase / Linear phase
def get_centered_ir(ir, is_lfe=False):
peak_idx = np.argmax(np.abs(ir))
N = FILTER_TAPS
pre_samples = int(0.100 * TARGET_SAMPLE_RATE) if is_lfe else int(0.005 * TARGET_SAMPLE_RATE)
post_samples = int(0.500 * TARGET_SAMPLE_RATE) if is_lfe else int(0.015 * TARGET_SAMPLE_RATE)
# Ensure pre+post doesn't exceed FILTER_TAPS (avoids crash at 192kHz/high sample rates)
total_requested = pre_samples + post_samples
if total_requested > N:
ratio = (N - 1) / total_requested
pre_samples = int(pre_samples * ratio)
post_samples = int(post_samples * ratio)
# Final safety check for integer rounding
if pre_samples + post_samples >= N:
post_samples = N - pre_samples - 1
ir_padded = np.pad(ir, (pre_samples, post_samples), mode='constant')
new_peak = peak_idx + pre_samples
sliced = ir_padded[new_peak - pre_samples:new_peak + post_samples]
window = signal.windows.tukey(len(sliced), alpha=0.1 if is_lfe else 0.5)
sliced = sliced * window
padded = np.zeros(N)
# Correctly handle potential indexing for pre/post windows
padded[-pre_samples:] = sliced[:pre_samples]
padded[:post_samples] = sliced[pre_samples:]
return padded
def get_fdw_spectrum(ir_centered, freqs, cycles=5.0, fs=48000):
N = len(ir_centered)
H_fdw = np.zeros_like(freqs, dtype=np.complex128)
H_standard = np.fft.rfft(ir_centered)
for k, f in enumerate(freqs):
if f < 20.0:
H_fdw[k] = H_standard[k]
continue
win_len_s = cycles / f
half_win_samples = int((win_len_s / 2.0) * fs)
if half_win_samples * 2 >= N:
H_fdw[k] = H_standard[k]
continue
t_pos = np.arange(half_win_samples) / fs
t_neg = np.arange(-half_win_samples, 0) / fs
t_valid = np.concatenate((t_neg, t_pos))
ir_valid = np.concatenate((ir_centered[-half_win_samples:], ir_centered[:half_win_samples]))
# Tukey window (alpha=0.5) matches REW's default behavior better than Hann
win = signal.windows.tukey(len(t_valid), alpha=0.5)
phasor = np.exp(-1j * 2 * np.pi * f * t_valid)
H_fdw[k] = np.sum(ir_valid * win * phasor)
return H_fdw
def generate_final_fir(H_complex, freqs, delay_s, log_func=print, is_lin_phase=True):
if is_lin_phase and delay_s < 0.05:
log_func(f"⚠️ Warning: Final FIR delay ({delay_s*1000:.1f} ms) might be too short to safely house sub-bass linear phase pre-ringing!")
total_samples = delay_s * TARGET_SAMPLE_RATE
int_shift = int(np.floor(total_samples))
frac_shift_s = (total_samples - int_shift) / TARGET_SAMPLE_RATE
H_shifted = H_complex * np.exp(1j * -2.0 * np.pi * freqs * frac_shift_s)
h_time = fft.irfft(H_shifted, n=FILTER_TAPS)
# Safety guard against circular wrap-around of pre-ringing energy
if is_lin_phase and int_shift > 0:
safety_start = FILTER_TAPS // 2
safety_end = FILTER_TAPS - int_shift
if safety_end > safety_start:
fade_len = int(TARGET_SAMPLE_RATE * 0.050) # 50ms fade
if safety_end - safety_start > fade_len * 2:
win_fade = np.ones_like(h_time)
t_fade = np.linspace(0, 1, fade_len)
win_fade[safety_start:safety_start+fade_len] = 0.5 * (1 + np.cos(np.pi * t_fade))
win_fade[safety_start+fade_len:safety_end-fade_len] = 0.0
win_fade[safety_end-fade_len:safety_end] = 0.5 * (1 - np.cos(np.pi * t_fade))
h_time *= win_fade
h_causal = np.roll(h_time, max(0, min(int_shift, FILTER_TAPS-1)))
asym_win = np.ones(FILTER_TAPS)
# Only apply fade-in if we have non-zero padding AND we are in linear phase mode
if is_lin_phase and int_shift > 0:
fade_in = max(2, int(int_shift * 0.1))
asym_win[:fade_in] = 0.5 * (1 - np.cos(np.pi * np.linspace(0, 1, fade_in)))
fade_out = int(TARGET_SAMPLE_RATE * 0.010)
asym_win[-fade_out:] = 0.5 * (1 + np.cos(np.pi * np.linspace(0, 1, fade_out)))
return h_causal * asym_win
def get_exact_fractional_peak(H_complex, N):
h_coarse = fft.irfft(H_complex, n=N)
h_shifted = np.roll(h_coarse, N // 2)
peak_idx = np.argmax(np.abs(h_shifted))
k_mid = np.arange(1, len(H_complex) - 1)
H_mid = H_complex[1:-1]
H_0 = np.real(H_complex[0])
H_Nyq = np.real(H_complex[-1])
def idft_val(t_shifted):
t = t_shifted - (N // 2)
phase = np.exp(1j * 2 * np.pi * k_mid * t / N)
val = H_0 + 2 * np.real(np.dot(H_mid, phase)) + H_Nyq * np.cos(np.pi * t)
return -np.abs(val)
res = minimize_scalar(idft_val, bounds=(peak_idx - 1.0, peak_idx + 1.0), method='bounded')
return res.x - (N // 2)
def kirkeby_regularized_inverse(H_mag, freqs, target_mag, beta_db=12.0):
"""
Kirkeby regularized spectral inversion with psychoacoustically-shaped
frequency-dependent regularization.
Instead of hard-clipping eq = target/measured, uses:
eq = (target * H) / (H^2 + beta(f)^2)
beta(f) is shaped to match human hearing sensitivity:
- Below 20 Hz: maximum beta (inaudible, don't correct)
- 20-200 Hz: moderate beta (room modes are audible)
- 200-5000 Hz: minimum beta (peak hearing sensitivity, correct aggressively)
- 5000-10000 Hz: gently rising beta
- Above 10000 Hz: rising beta (diminishing returns, distortion risk)
- Above 20000 Hz: maximum beta (inaudible)
H_mag: measured magnitude spectrum (linear, positive)
freqs: frequency array (Hz)
target_mag: desired target magnitude spectrum (linear, positive)
beta_db: controls overall regularization strength (dB). Default 12.
Returns: EQ magnitude curve (linear, positive)
"""
beta_base = 10 ** (-beta_db / 20.0) # Convert dB to linear floor
# --- Normalize H and target so beta is meaningful ---
# Without normalization, H_mag (linear SPL) is ~10-1000+, making
# beta (~0.25) negligible and the regularization a no-op.
# Using median gives moderate regularization; max would be too aggressive.
scale = np.median(H_mag[H_mag > 1e-12])
if scale < 1e-12:
scale = 1.0
H_norm = H_mag / scale
T_norm = target_mag / scale
# --- Build frequency-dependent regularization weight W(f) ---
# W(f) = 1.0 means full regularization (gentle), W(f) ≈ 0 means minimal (aggressive)
W = np.ones_like(freqs, dtype=np.float64)
for i, f in enumerate(freqs):
if f <= 0:
W[i] = 1.0 # DC: full regularization
elif f < 20:
# Ramp from full reg down to moderate over sub-audible range
W[i] = 1.0 - 0.7 * (f / 20.0)
elif f < 200:
# Moderate regularization in bass (room modes are audible but tricky)
W[i] = 0.3
elif f < 5000:
# Minimum regularization: peak hearing sensitivity, correct hard
t = (f - 200) / (5000 - 200)
W[i] = 0.3 - 0.25 * t # 0.3 → 0.05
elif f < 10000:
# Rising gently: HF sensitivity decreasing
t = (f - 5000) / (10000 - 5000)
W[i] = 0.05 + 0.25 * t # 0.05 → 0.30
elif f < 20000:
# Continues rising
t = (f - 10000) / (20000 - 10000)
W[i] = 0.30 + 0.40 * t # 0.30 → 0.70
else:
W[i] = 1.0 # Above audibility: full regularization
# Compute the frequency-dependent beta
beta_f = beta_base * W
# Kirkeby regularized inverse on normalized values:
# eq_norm = (T_norm * H_norm) / (H_norm^2 + beta^2)
H2 = H_norm ** 2
beta2 = beta_f ** 2
eq_mag = (T_norm * H_norm) / (H2 + beta2)
return np.maximum(eq_mag, 1e-12)
def mixed_phase_decompose(H_eq_mag, excess_phase, freqs, crossover_hz=500.0):
"""
True mixed-phase filter design for correction filters.
Below crossover_hz: minimum-phase EQ (no pre-ringing, causal)
Above crossover_hz: linear-phase EQ (preserves transient accuracy)
Transition: 1-octave Hann crossfade centered at crossover_hz
H_eq_mag: magnitude of the EQ correction (linear, from kirkeby or clip)
excess_phase: the unwrapped excess phase to linearize (radians)
freqs: frequency array (Hz)
crossover_hz: mixed-phase transition frequency (default 500.0)
Returns: complex H_correction filter (magnitude + mixed phase)
"""
N = (len(freqs) - 1) * 2 # Reconstruct FILTER_TAPS from rfft length
# --- Crossfade window: 0 = min-phase region, 1 = linear-phase region ---
# One-octave transition centered at crossover_hz
f_low = crossover_hz / np.sqrt(2.0) # ~0.707 * crossover
f_high = crossover_hz * np.sqrt(2.0) # ~1.414 * crossover
W_linear = np.zeros_like(freqs)
W_linear[freqs >= f_high] = 1.0
idx_trans = (freqs > f_low) & (freqs < f_high)
if np.any(idx_trans):
W_linear[idx_trans] = 0.5 * (1 - np.cos(np.pi * (freqs[idx_trans] - f_low) / (f_high - f_low)))
# --- Minimum-phase component (via cepstral liftering) ---
lifter = np.zeros(N)
lifter[0] = 1
lifter[1:N//2] = 2
if N % 2 == 0:
lifter[N//2] = 1
cepstrum = fft.irfft(np.log(np.maximum(H_eq_mag, 1e-12)), n=N)
min_phase_spectrum = np.exp(fft.rfft(cepstrum * lifter))
# min_phase_spectrum has magnitude ≈ H_eq_mag and minimum-phase angle
# --- Linear-phase component (zero phase = magnitude only + excess phase correction) ---
# negative excess phase = correction that linearizes the speaker
lin_phase_correction = -excess_phase
H_linear = H_eq_mag * np.exp(1j * lin_phase_correction)
# --- Blend: min-phase in bass, linear-phase in treble ---
H_mixed = min_phase_spectrum * (1.0 - W_linear) + H_linear * W_linear
return H_mixed
def detect_speaker_rolloff(mag_raw, freqs, threshold_db=-10.0, ref_low=200.0, ref_high=2000.0):
"""
Detects the natural low-end and high-end rolloff frequencies of a speaker
by finding where the 1/3-octave-smoothed magnitude drops below threshold_db
relative to the midband (ref_low–ref_high Hz) average.
Returns (low_rolloff_hz, high_rolloff_hz).
"""
# Use 1/3-octave smoothing to avoid mistaking dips for rolloff
mag_smoothed = log_smoothed_fast(mag_raw, freqs, fraction=3, variable=False)
mag_db = 20 * np.log10(np.maximum(mag_smoothed, 1e-12))
# Selection of reference band: default 200–2000 Hz, or custom for subs
idx_mid_low = np.argmin(np.abs(freqs - ref_low))
idx_mid_high = np.argmin(np.abs(freqs - ref_high))
if idx_mid_high <= idx_mid_low:
idx_mid_high = idx_mid_low + 1
midband_level_db = np.mean(mag_db[idx_mid_low:idx_mid_high])
threshold = midband_level_db + threshold_db # threshold_db is negative
# Low-end rolloff: scan downward from midband
low_rolloff_hz = freqs[1] if len(freqs) > 1 else 20.0
for i in range(idx_mid_low, 0, -1):
if mag_db[i] < threshold:
low_rolloff_hz = freqs[i]
break
# High-end rolloff: scan upward from midband
high_rolloff_hz = 20000.0
for i in range(idx_mid_high, len(freqs)):
if mag_db[i] < threshold:
high_rolloff_hz = freqs[i]
break
return float(low_rolloff_hz), float(high_rolloff_hz)
def compute_spatial_variance_weight(position_ids, freqs, fdw_cycles, fs, threshold_db=3.0):
"""
Compute a frequency-dependent weight W(f) in [0,1] based on cross-seat variance.
W=1.0 at frequencies where all seats agree, W->0 where variance is high.
position_ids: list of REW measurement IDs (one per listening position)
threshold_db: std deviation (dB) at which W drops to 0.5
"""
if len(position_ids) < 2:
return np.ones_like(freqs)
mags_db = []
for pid in position_ids:
try:
ir = fetch_ir_data(int(pid))
ir_long = get_centered_ir(ir, is_lfe=False)
H = get_fdw_spectrum(ir_long, freqs, cycles=fdw_cycles, fs=fs)
mag_db = 20 * np.log10(np.maximum(np.abs(H), 1e-12))
mag_smooth = log_smoothed_fast(mag_db, freqs, fraction=3)
mags_db.append(mag_smooth)
except Exception:
continue
if len(mags_db) < 2:
return np.ones_like(freqs)
std_db = np.std(mags_db, axis=0)
W = 1.0 / (1.0 + (std_db / threshold_db) ** 2)
return W
def get_crossover_threshold_db(crossover_type):
"""
Returns the dB point at which a speaker's rolloff should be detected
for optimal crossover placement with the given crossover type.
Linkwitz-Riley: -6 dB (HPF + LPF each at -6dB sum to unity)
Butterworth: -3 dB (each filter is -3dB at fc)
Bessel: -3 dB (with norm='phase')
"""
ctype = crossover_type[:2].lower() if len(crossover_type) >= 2 else 'lr'
if ctype == 'lr':
return -6.0
else: # bw, bs
return -3.0
def detect_reflection_gap(ir, fs, threshold_ratio=0.15):
"""
Detects the time gap between the direct sound peak and the first strong
early reflection in an impulse response, using the Hilbert envelope.
ir: raw impulse response array
fs: sample rate
threshold_ratio: fraction of peak envelope amplitude that counts as a
'strong' reflection (default 0.15 = 15% of peak)
Returns: gap_seconds (float). Clamped to [0.5ms, 20ms].
"""
from scipy.signal import hilbert as hilbert_transform
# Compute analytic signal envelope
analytic = hilbert_transform(ir)
envelope = np.abs(analytic)
# Smooth the envelope to avoid false peaks from noise
smooth_samples = max(1, int(0.0005 * fs)) # 0.5ms smoothing kernel
kernel = np.ones(smooth_samples) / smooth_samples
envelope_smooth = np.convolve(envelope, kernel, mode='same')
# Find the direct sound peak
peak_idx = np.argmax(envelope_smooth)
peak_val = envelope_smooth[peak_idx]
if peak_val < 1e-12:
return 0.005 # fallback: 5ms
# Search forward from peak for the first dip below threshold, then the
# next rise above threshold (= first reflection)
threshold = peak_val * threshold_ratio
# First, find where envelope drops below threshold after the peak
found_dip = False
dip_idx = peak_idx
for i in range(peak_idx + 1, min(len(envelope_smooth), peak_idx + int(0.030 * fs))):
if envelope_smooth[i] < threshold:
found_dip = True
dip_idx = i
break
if not found_dip:
return 0.005 # No clear dip found, fallback
# Then find where envelope rises back above threshold (= reflection arrival)
reflection_idx = dip_idx
for i in range(dip_idx, min(len(envelope_smooth), peak_idx + int(0.030 * fs))):
if envelope_smooth[i] > threshold:
reflection_idx = i
break
gap_s = (reflection_idx - peak_idx) / fs
# Clamp to sensible range
return float(np.clip(gap_s, 0.0005, 0.020))
def ir_gap_to_fdw_cycles(gap_s, reference_freq=500.0):
"""
Converts a direct-to-reflection time gap into an optimal FDW cycle count.
The FDW window at a given frequency f has a half-length of:
t_half = cycles / (2 * f)
We want the full window (2 * t_half = cycles / f) to fit within the gap,
so: cycles = gap_s * f
We use a reference frequency in the midband where FDW behavior matters most.
Result is clamped to [3.0, 10.0].
"""
cycles = gap_s * reference_freq
return float(np.clip(cycles, 3.0, 10.0))
def detect_auto_house_curve(H_mains_mags, H_sub_mag, freqs, fc, fs):
"""
Analyzes the average in-room steady-state magnitude to derive psychoacoustically
appropriate house curve parameters by measuring the natural room gain slope.
H_mains_mags: list of linear magnitude arrays from each main speaker
H_sub_mag: linear magnitude array from the subwoofer (or None)
freqs: frequency array (Hz)
fc: crossover frequency (Hz)
Returns: (house_boost_db, house_start_hz, house_end_hz)
"""
# Build combined in-room magnitude: RMS average of all channels
all_mags = list(H_mains_mags)
if H_sub_mag is not None:
all_mags.append(H_sub_mag)
combined_mag = np.sqrt(np.mean(np.array(all_mags)**2, axis=0))
combined_mag = np.maximum(combined_mag, 1e-12)
# Smooth with 1/3 octave to get the trend, not individual modes
combined_db = 20 * np.log10(combined_mag)
combined_db_smooth = log_smoothed_fast(combined_db, freqs, fraction=3, variable=False)
# Reference level: average in the midband (500-2000 Hz)
idx_mid_low = np.argmin(np.abs(freqs - 500.0))
idx_mid_high = np.argmin(np.abs(freqs - 2000.0))
if idx_mid_high <= idx_mid_low:
idx_mid_high = idx_mid_low + 1
mid_level_db = np.mean(combined_db_smooth[idx_mid_low:idx_mid_high])
# Measure how much louder (or quieter) the bass is relative to midband
# Use the 30-80 Hz region as the "deep bass" reference
idx_bass_low = np.argmin(np.abs(freqs - 30.0))
idx_bass_high = np.argmin(np.abs(freqs - 80.0))
if idx_bass_high <= idx_bass_low:
idx_bass_high = idx_bass_low + 1
bass_level_db = np.mean(combined_db_smooth[idx_bass_low:idx_bass_high])
# Natural room gain = how much louder bass is vs. mids
natural_room_gain = bass_level_db - mid_level_db
# The house curve should follow a psychoacoustically pleasant bass shelf.
# Research (Harman, Toole) suggests +3 to +6 dB is optimal for music,
# +6 to +10 dB for cinema. We use the measured room gain as a guide
# and target a boost that's close to 60-80% of the existing room gain
# (the room is already doing some of the work).
# If room gain is already high (>8dB), we target less boost (room does the work).
# If room gain is low (<3dB), we target more boost (room isn't helping).
if natural_room_gain > 8.0:
target_boost = max(3.0, natural_room_gain * 0.5)
elif natural_room_gain > 4.0:
target_boost = max(4.0, natural_room_gain * 0.7)
else:
target_boost = max(4.0, min(8.0, 6.0 + (3.0 - natural_room_gain) * 0.5))
# Clamp to sensible bounds
house_boost = float(np.clip(target_boost, 2.0, 12.0))
# Find where the room gain slope begins by scanning upward from bass
# to find where the level crosses the midband reference
slope_start_hz = 120.0 # default
for i in range(idx_bass_high, idx_mid_low):
if combined_db_smooth[i] <= mid_level_db + 1.0:
slope_start_hz = float(freqs[i])
break
slope_start_hz = float(np.clip(slope_start_hz, 80.0, 300.0))
# The slope end (where maximum boost is reached) should be well into the bass
# Typically around half the crossover frequency or where bass levels off
slope_end_hz = float(np.clip(fc * 0.8, 20.0, 120.0))
return house_boost, slope_start_hz, slope_end_hz
def detect_schroeder_statistical(mag_raw, freqs, fs=48000, min_f=80.0, max_f=600.0, window_oct=0.25, min_anchor=None):
"""
Detects the Schroeder frequency by analyzing the statistical variance
of the magnitude response. Improved version with bandwidth checks,
tighter thresholds for smooth rooms, and physical geometric anchoring.
"""
# 1. Bandwidth Pre-Check: If this is a subwoofer-only sweep, variance above 300Hz is pure noise.
idx_bass = (freqs >= 40.0) & (freqs <= 80.0)
idx_mid = (freqs >= 300.0) & (freqs <= 600.0)
if np.any(idx_bass) and np.any(idx_mid):
med_bass = np.median(20 * np.log10(np.maximum(mag_raw[idx_bass], 1e-12)))
med_mid = np.median(20 * np.log10(np.maximum(mag_raw[idx_mid], 1e-12)))
# If the midrange is >25dB below the bass, it's a dedicated subwoofer sweep.
if med_bass - med_mid > 25.0:
return 200.0
mag_db = 20 * np.log10(np.maximum(mag_raw, 1e-12))
variances = []
test_freqs = []
curr_f = min_f
while curr_f < max_f:
f_low = curr_f / (2**(window_oct/2))
f_high = curr_f * (2**(window_oct/2))
idx = (freqs >= f_low) & (freqs <= f_high)
if np.any(idx) and np.sum(idx) > 3:
variances.append(np.std(mag_db[idx]))
test_freqs.append(curr_f)
curr_f *= 1.03
if not variances:
return 200.0
variances = np.array(variances)
test_freqs = np.array(test_freqs)
v_smooth = log_smoothed_fast(variances, test_freqs, fraction=4)
# Clean Baseline: Use the region > 500Hz to establish a truly stochastic reference.
high_freq_idx = test_freqs > 500.0
if np.any(high_freq_idx):
baseline_v = np.percentile(v_smooth[high_freq_idx], 20)
v_spread = np.std(v_smooth[high_freq_idx])
else:
baseline_v = np.min(v_smooth)
v_spread = 1.0
# Tighter Threshold Logic: max(0.4, v_spread * 1.3)
# Refined for even better sensitivity in smooth (low channel count) rooms.
threshold = baseline_v + max(0.4, v_spread * 1.3)
fc_detected = 250.0
trend_count = 0
required_trend = 3
for i in range(len(v_smooth)-1, 0, -1):
if v_smooth[i] > threshold:
trend_count += 1
else:
trend_count = 0
if trend_count >= required_trend:
detected_idx = min(i + required_trend, len(v_smooth)-1)
fc_detected = test_freqs[detected_idx]
break
# Physical Anchor Floor: If dimensions say the room is 300Hz, don't let
# smooth high-frequency comb-filtering dupe us into a 145Hz fallback.
if min_anchor is not None:
fc_detected = max(fc_detected, min_anchor)
if fc_detected <= min_f + 5.0:
fc_detected = 200.0
return float(np.clip(fc_detected, min_f, 450.0))
def detect_auto_prc_frequency(H_eq_flat, freqs, smoothed_excess_phase, fs, delay_s,
min_freq=100.0, max_freq=5000.0, step=100.0):
"""
Iteratively tests PRC cutoff frequencies from TOP DOWN to find the
LEAST CONSERVATIVE safe value (highest frequency) that keeps
pre-ringing artifacts below psychoacoustic audibility thresholds.
H_eq_flat: complex EQ spectrum (magnitude + min phase)
freqs: frequency array
smoothed_excess_phase: the windowed excess phase to correct
fs: sample rate
delay_s: the FIR delay used for generating test FIRs
min_freq: lowest PRC freq (Hz)
max_freq: highest PRC freq to start searching from (Hz)
step: frequency step between candidates (Hz)
Returns: (best_prc_hz, peak_ratio_db)
"""
def get_audibility_threshold_db(f):
# Human ear is less sensitive to slow ringing at low frequencies
# and extremely sensitive to high frequency pre-echo.
if f <= 200:
return -20.0 # 10% peak ratio
elif f >= 2000:
return -45.0 # 0.5% peak ratio
else:
# Linear interpolation in dB between 200Hz and 2000Hz
# 200 -> -20, 2000 -> -45
alpha = (f - 200) / (2000 - 200)
return -20.0 + alpha * (-45.0 - (-20.0))
best_prc_hz = 1000.0 # Safe default if search fails
best_db = 0.0
# Search from highest frequency DOWNWARDS (least conservative first)
candidates = np.arange(max_freq, min_freq - step, -step)
for prc_hz in candidates:
# Build PRC window
W_prc = np.ones_like(freqs)
fade_start = prc_hz
fade_end = prc_hz * 2.0
W_prc[freqs >= fade_end] = 0.0
idx_prc = (freqs > fade_start) & (freqs < fade_end)
if np.any(idx_prc):
W_prc[idx_prc] = 0.5 * (1 + np.cos(np.pi * (freqs[idx_prc] - fade_start) / (fade_end - fade_start)))
target_phase = -smoothed_excess_phase
# Normalize phase at fade start to prevent wrapping clicks
idx_fs = np.argmin(np.abs(freqs - fade_start))
phase_shift = np.round(target_phase[idx_fs] / (2 * np.pi)) * (2 * np.pi)
target_phase_prc = (target_phase - phase_shift) * W_prc
H_lin = np.exp(1j * target_phase_prc)
H_candidate = H_eq_flat * H_lin
# Generate test FIR
test_fir = generate_final_fir(H_candidate, freqs, delay_s, log_func=lambda x: None)
# Evaluate peak-based pre-ringing ratio
abs_fir = np.abs(test_fir)
peak_idx = np.argmax(abs_fir)
main_peak = abs_fir[peak_idx]
if main_peak < 1e-12:
continue
# Analysis window: more than 2ms before the peak
pre_margin = int(0.002 * fs)
pre_window = abs_fir[:max(0, peak_idx - pre_margin)]
if len(pre_window) == 0:
max_pre_peak = 0.0
else:
max_pre_peak = np.max(pre_window)
ratio = max_pre_peak / main_peak
db = 20 * np.log10(ratio) if ratio > 1e-10 else -100.0
threshold_db = get_audibility_threshold_db(prc_hz)
if db <= threshold_db:
# Found the highest frequency that is safe
return float(prc_hz), float(db)
# Track best relative to its frequency threshold
margin = db - threshold_db
if 'min_margin' not in locals() or margin < min_margin:
min_margin = margin
best_prc_hz = prc_hz
best_db = db
return float(best_prc_hz), float(best_db)
# ==============================================================================
# FLASK ROUTES
# ==============================================================================
@app.route('/')
def index():
return render_template('index.html')
@app.route('/docs')
def docs():
return render_template('docs.html')
@app.route('/api/run_phase1', methods=['POST'])
def run_phase1():
global APP_STATE, REW_API_URL, TARGET_SAMPLE_RATE, FILTER_TAPS
console_log = []
def clog(msg):
console_log.append(msg)
print(msg)
try:
config = request.json
mains_ids = config.get('mains_ids', [])
lfe_id = config.get('lfe_id', '')
fc = float(config.get('fc', 80.0))
delay_ms = float(config.get('delay_ms', 75.0))
house_boost = float(config.get('house_boost', 6.0))
house_start = float(config.get('house_start', 120.0))
house_end = float(config.get('house_end', 80.0))
# Override Globals with Advanced Configs
TARGET_SAMPLE_RATE = int(config.get('sample_rate', 48000))
FILTER_TAPS = int(config.get('filter_taps', 65536))
REW_API_URL = config.get('rew_api_url', "http://localhost:4735").rstrip('/')
# Load other Advanced Configs
fdw_cycles = float(config.get('fdw_cycles', 5.0))
trans_start = float(config.get('trans_start', 200.0))
trans_end = float(config.get('trans_end', 300.0))
max_boost_low = float(config.get('max_boost_low', 6.0))
max_boost_high = float(config.get('max_boost_high', 6.0))
global_max_boost = float(config.get('global_max_boost', 0.0))
sub_percentile = float(config.get('sub_percentile', 15.0))
global_smoothing = config.get('global_smoothing', '6')
vol_match_low = float(config.get('vol_match_low', 500.0))
vol_match_high = float(config.get('vol_match_high', 2000.0))
mains_eq_enabled = config.get('mains_eq_enabled', True)
mains_phase_lin_enabled = config.get('mains_phase_lin_enabled', True)
vol_align_enabled = config.get('vol_align_enabled', True)
direct_sound_vol_align = config.get('direct_sound_vol_align', False)