-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSourceCode.py
More file actions
1672 lines (1387 loc) · 63.3 KB
/
SourceCode.py
File metadata and controls
1672 lines (1387 loc) · 63.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
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
import time
import json
from pathlib import Path
from tkinter import filedialog
import logging
import threading
import os
from dataclasses import dataclass
import numpy as np
import sounddevice as sd
from scipy import signal
from scipy.io import wavfile
import ttkbootstrap as tb
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import presets
import verification
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
# =============================================================================
# Global Application State
# =============================================================================
osc_merge_var = None
live_status_after_id = None
play_mode = "manual" # "manual" or "ramp"
beat_type_var = None # "binaural", "monaural", or "isochronic"
# Defaults
ramp_carrier_hz = 432.0
ramp_start_beat_hz = 20.0
ramp_end_beat_hz = 3.0
ramp_duration_s = 30.0 * 60.0
manual_left_hz = 432.0
manual_right_hz = 432.0
APP_DIR = Path.home() / ".neuralbeat"
CONFIG_PATH = APP_DIR / "config.json"
# Visualizer state
osc_window = None
visualizer_canvas = None
visualizer_ax = None
line_left = None
line_right = None
OSC_BUFFER_SECONDS = 0.05
osc_plot_buffer_l = None
osc_plot_buffer_r = None
OSC_COLOR_PALETTES = {
"Cyan / Magenta": {
"dark": ("#00FFFF", "#FF00FF"),
"light": ("#008B8B", "#8B008B")
},
"Green / Yellow": {
"dark": ("#00FF00", "#FFFF00"),
"light": ("#006400", "#BDB76B")
},
"Red / Blue": {
"dark": ("#FF4500", "#1E90FF"),
"light": ("#DC143C", "#0000CD")
}
}
waveforms = {
"Sine": np.sin,
"Square": signal.square,
"Sawtooth": signal.sawtooth,
"Triangle": lambda t: signal.sawtooth(t, width=0.5),
}
# =============================================================================
# Noise Generation
# =============================================================================
class NoiseGenerator:
"""
Generates blocks of colored noise with state preservation using digital filters.
"""
def __init__(self):
# Pink noise filter coeffs (-3dB/octave)
self.pink_b = [0.049922035, -0.095993537, 0.050612699, -0.004408786]
self.pink_a = [1, -2.494956002, 2.017265875, -0.522189400]
self.pink_zi = signal.lfilter_zi(self.pink_b, self.pink_a)
# Brown noise filter coeffs (leaky integrator, -6dB/octave)
self.brown_b = [1.0]
self.brown_a = [1.0, -0.999] # Very close to 1 for strong low-pass
self.brown_zi = signal.lfilter_zi(self.brown_b, self.brown_a)
def _normalize(self, noise):
"""Normalize noise to have RMS of 1."""
rms = np.sqrt(np.mean(noise**2))
if rms > 1e-9:
return noise / rms
return noise
def generate(self, noise_type, n_samples):
if noise_type == "White":
return self._normalize(np.random.randn(n_samples))
elif noise_type == "Pink":
white = np.random.randn(n_samples)
noise, self.pink_zi = signal.lfilter(self.pink_b, self.pink_a, white, zi=self.pink_zi)
return self._normalize(noise)
elif noise_type == "Brown":
white = np.random.randn(n_samples)
noise, self.brown_zi = signal.lfilter(self.brown_b, self.brown_a, white, zi=self.brown_zi)
return self._normalize(noise)
return np.zeros(n_samples)
# =============================================================================
# Configuration & Persistence
# =============================================================================
def load_config() -> dict:
"""Loads configuration from the JSON file."""
try:
if CONFIG_PATH.exists():
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
except Exception:
logger.error(f"Error loading config from {CONFIG_PATH}", exc_info=True)
return {}
def save_config(cfg: dict) -> None:
"""Saves the configuration dictionary to the JSON file."""
try:
APP_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
except Exception:
logger.error(f"Error saving config to {CONFIG_PATH}", exc_info=True)
config = load_config()
initial_theme = config.get("theme", "darkly")
def _normalize_category(category: str) -> str:
c = str(category).strip().lower()
if "binaural" in c or "monaural" in c:
return "Binaural"
if "isochronic" in c:
return "Isochronic"
raise ValueError("Category must be 'Binaural Beat / Monaural Beat' or 'Isochronic Tone'")
def get_user_presets() -> dict:
up = config.get("user_presets", {})
return {
"Monaural": list(up.get("Monaural", [])),
"Binaural": list(up.get("Binaural", [])),
"Isochronic": list(up.get("Isochronic", [])),
}
def add_user_preset(category: str, label: str, left_hz: float, right_hz: float) -> None:
category = _normalize_category(category)
try:
preset_obj = {
"label": str(label).strip(),
"left_hz": float(left_hz),
"right_hz": float(right_hz),
}
except ValueError:
raise ValueError("Invalid numeric value for frequencies.")
if not preset_obj["label"]:
raise ValueError("Preset Name Cannot be Empty")
up = get_user_presets()
up[category].append(preset_obj)
config["user_presets"] = up
save_config(config)
def remove_user_preset(category: str, label: str) -> bool:
category = _normalize_category(category)
up = get_user_presets()
label = str(label).strip()
for i, p in enumerate(up[category]):
if str(p.get("label", "")).strip() == label:
up[category].pop(i)
config["user_presets"] = up
save_config(config)
return True
return False
def get_all_presets() -> dict:
up = get_user_presets()
return {
"Monaural": list(presets.MONAURAL_PRESETS) + up["Monaural"],
"Binaural": list(presets.BINAURAL_PRESETS) + up["Binaural"],
"Isochronic": list(presets.ISOCHRONIC_PRESETS) + up["Isochronic"],
}
# =============================================================================
# Audio Engine & DSP
# =============================================================================
def clamp(value, lo, hi):
"""Clamps a value between lo and hi."""
return max(lo, min(hi, value))
def validate_audio_params(freq_l, freq_r, vol_l, vol_r, duration=None):
"""Validates audio parameters (frequencies, volumes, duration)."""
if not (20.0 <= freq_l <= 20000.0):
return "Frequency must be between 20 Hz and 20000 Hz."
if not (20.0 <= freq_r <= 20000.0):
return "Frequency must be between 20 Hz and 20000 Hz."
if not (0.0 <= vol_l <= 100.0):
return "Volume must be between 0% and 100%."
if not (0.0 <= vol_r <= 100.0):
return "Volume must be between 0% and 100%."
if duration is not None and duration <= 0:
return "Duration must be positive."
return None
def _compute_ramped_beat_hz(elapsed_s: float, start_beat_hz: float, end_beat_hz: float, ramp_s: float) -> float:
"""Calculates the current beat frequency based on ramp progress."""
if ramp_s <= 0:
return end_beat_hz
x = clamp(elapsed_s / ramp_s, 0.0, 1.0)
return start_beat_hz + (end_beat_hz - start_beat_hz) * x
@dataclass
class AudioConfig:
sample_rate: int
left_volume: float
right_volume: float
left_waveform: str
right_waveform: str
noise_type: str
noise_volume: float
use_ramp: bool
left_frequency: float
right_frequency: float
carrier_hz: float
start_beat_hz: float
end_beat_hz: float
ramp_duration_s: float
beat_type: str = "binaural"
def get_audio_config_from_ui() -> AudioConfig:
"""Reads values from UI entries and returns an AudioConfig object."""
try:
left_volume_val = float(left_volume_entry.get())
right_volume_val = float(right_volume_entry.get())
noise_volume_val = float(noise_volume_entry.get())
except ValueError:
raise ValueError("Please enter valid numeric values for volume.")
left_volume = clamp(left_volume_val / 100.0, 0.0, 1.0)
right_volume = clamp(right_volume_val / 100.0, 0.0, 1.0)
noise_volume = clamp(noise_volume_val / 100.0, 0.0, 1.0)
left_waveform = left_waveform_var.get()
right_waveform = right_waveform_var.get()
noise_type = noise_type_var.get()
use_ramp = bool(ramp_enabled_var.get())
sample_rate = 44100
beat_type = beat_type_var.get() if beat_type_var else "binaural"
if use_ramp:
try:
r_carrier = float(carrier_entry.get())
r_start = float(start_beat_entry.get())
r_end = float(end_beat_entry.get())
r_min = float(ramp_minutes_entry.get())
except ValueError:
raise ValueError("Please enter valid numeric values for ramp settings.")
if not (20.0 <= r_carrier <= 20000.0):
raise ValueError("Carrier frequency must be between 20 Hz and 20000 Hz.")
if not (0.1 <= r_start <= 100.0):
raise ValueError("Beat frequency must be between 0.1 Hz and 100 Hz.")
if not (0.1 <= r_end <= 100.0):
raise ValueError("Beat frequency must be between 0.1 Hz and 100 Hz.")
ramp_duration_s = max(0.0, r_min * 60.0)
return AudioConfig(
sample_rate=sample_rate,
left_volume=left_volume,
right_volume=right_volume,
left_waveform=left_waveform,
right_waveform=right_waveform,
noise_type=noise_type,
noise_volume=noise_volume,
use_ramp=True,
left_frequency=0.0,
right_frequency=0.0,
carrier_hz=r_carrier,
start_beat_hz=r_start,
end_beat_hz=r_end,
ramp_duration_s=ramp_duration_s,
beat_type=beat_type
)
else:
try:
m_left = float(left_frequency_entry.get())
m_right = float(right_frequency_entry.get())
except ValueError:
raise ValueError("Please enter valid numeric values for frequencies.")
if beat_type == "isochronic":
if not (0.1 <= m_left <= 100.0):
raise ValueError("Beat frequency must be between 0.1 Hz and 100 Hz for isochronic tones.")
if not (20.0 <= m_right <= 20000.0):
raise ValueError("Carrier frequency must be between 20 Hz and 20000 Hz.")
else:
err = validate_audio_params(m_left, m_right, left_volume_val, right_volume_val)
if err:
raise ValueError(err)
carrier_hz = m_right if beat_type == "isochronic" else 0.0
return AudioConfig(
sample_rate=sample_rate,
left_volume=left_volume,
right_volume=right_volume,
left_waveform=left_waveform,
right_waveform=right_waveform,
noise_type=noise_type,
noise_volume=noise_volume,
use_ramp=False,
left_frequency=m_left,
right_frequency=m_right,
carrier_hz=carrier_hz,
start_beat_hz=0.0,
end_beat_hz=0.0,
ramp_duration_s=0.0,
beat_type=beat_type
)
class BinauralGenerator:
"""
Generates binaural or monaural beats based on the provided AudioConfig.
Handles waveform generation, ramping, and soft limiting.
"""
def __init__(self, cfg: AudioConfig):
self.cfg = cfg
self.phase_l = 0.0
self.phase_r = 0.0
self.samples_generated = 0
self.ramp_s = cfg.ramp_duration_s
# Initialize noise generator if needed
if self.cfg.noise_type != "None" and self.cfg.noise_volume > 0:
self.noise_gen = NoiseGenerator()
else:
self.noise_gen = None
# Resolve waveform functions
# Default to Sine if not found to prevent crashes
self.left_wave_func = waveforms.get(cfg.left_waveform, np.sin)
self.right_wave_func = waveforms.get(cfg.right_waveform, np.sin)
self.drive = 2.5
self.tanh_drive = np.tanh(self.drive)
# Fade configuration
self.fade_in_len = int(0.02 * cfg.sample_rate) # 20 ms
self.fade_out_len = int(0.02 * cfg.sample_rate) # 20 ms
self.stopping = False
self.fade_out_counter = 0
self.is_finished = False
def request_stop(self):
"""Signal the generator to start fading out."""
self.stopping = True
def generate_block(self, frames: int) -> np.ndarray:
# Time array for this block (seconds relative to start of stream)
# Using float64 for time accumulation to prevent jitter over long sessions, though inputs are float
current_time = self.samples_generated / self.cfg.sample_rate
# Calculate frequencies per sample
if self.cfg.use_ramp:
# Vectorized ramp calculation
# Create global time array for this block
t_global = current_time + np.arange(frames, dtype=np.float64) / self.cfg.sample_rate
if self.ramp_s <= 0:
beat_hz = np.full(frames, self.cfg.end_beat_hz, dtype=np.float64)
else:
# Linear interpolation with clamping
progress = np.clip(t_global / self.ramp_s, 0.0, 1.0)
beat_hz = self.cfg.start_beat_hz + (self.cfg.end_beat_hz - self.cfg.start_beat_hz) * progress
lf_array = self.cfg.carrier_hz - (beat_hz / 2.0)
rf_array = self.cfg.carrier_hz + (beat_hz / 2.0)
# Enforce positive frequency
lf_array = np.maximum(0.0, lf_array)
rf_array = np.maximum(0.0, rf_array)
# Calculate phase increments: 2 * pi * f / sr
inc_l = (2.0 * np.pi * lf_array / self.cfg.sample_rate)
inc_r = (2.0 * np.pi * rf_array / self.cfg.sample_rate)
# Calculate cumulative phase shift
# We start at self.phase_l. Sample 0 is at self.phase_l.
# Sample n is at self.phase_l + sum(inc[0]...inc[n-1])
# np.cumsum returns [inc0, inc0+inc1, ...]. We shift it.
phase_shift_l = np.concatenate(([0.0], np.cumsum(inc_l)[:-1]))
phase_shift_r = np.concatenate(([0.0], np.cumsum(inc_r)[:-1]))
phase_vec_l = self.phase_l + phase_shift_l
phase_vec_r = self.phase_r + phase_shift_r
# Calculate next block seed phase
# Total change over this block is sum of all increments
self.phase_l = (self.phase_l + np.sum(inc_l)) % (2.0 * np.pi)
self.phase_r = (self.phase_r + np.sum(inc_r)) % (2.0 * np.pi)
else:
# Constant frequency optimization
# Avoid full array allocation and cumsum for constant frequency
freq_l = max(0.0, self.cfg.left_frequency)
freq_r = max(0.0, self.cfg.right_frequency)
# Phase increment per sample
inc_l = (2.0 * np.pi * freq_l / self.cfg.sample_rate)
inc_r = (2.0 * np.pi * freq_r / self.cfg.sample_rate)
# Create time vector for this block (0, 1, ..., frames-1)
t_vec = np.arange(frames, dtype=np.float64)
# phase[n] = phase_start + n * inc
phase_vec_l = self.phase_l + t_vec * inc_l
phase_vec_r = self.phase_r + t_vec * inc_r
# Update phase for next block
self.phase_l = (self.phase_l + frames * inc_l) % (2.0 * np.pi)
self.phase_r = (self.phase_r + frames * inc_r) % (2.0 * np.pi)
# Generate Waveforms
left = self.cfg.left_volume * self.left_wave_func(phase_vec_l)
right = self.cfg.right_volume * self.right_wave_func(phase_vec_r)
stereo = np.column_stack((left, right))
# Generate and mix noise before limiting
if self.noise_gen:
noise = self.noise_gen.generate(self.cfg.noise_type, frames)
# Add mono noise to both channels using broadcasting
stereo += (noise * self.cfg.noise_volume)[:, np.newaxis]
# Stateless soft limiter/saturator
stereo = np.tanh(stereo * self.drive) / self.tanh_drive
stereo = np.clip(stereo, -1.0, 1.0)
# Apply Fade In
start_idx = self.samples_generated
end_idx = start_idx + frames
if start_idx < self.fade_in_len:
# Generate ramp for fade in
ramp_in = np.arange(start_idx, end_idx, dtype=np.float32) / self.fade_in_len
ramp_in = np.clip(ramp_in, 0.0, 1.0)
stereo *= ramp_in[:, np.newaxis]
# Apply Fade Out if stopping
if self.stopping:
# Calculate remaining fade out samples
remaining = self.fade_out_len - self.fade_out_counter
if remaining <= 0:
stereo.fill(0)
self.is_finished = True
self.samples_generated += frames
return stereo
# Generate fade out ramp
t_fade = np.arange(self.fade_out_counter, self.fade_out_counter + frames, dtype=np.float32)
ramp_out = 1.0 - (t_fade / self.fade_out_len)
ramp_out = np.clip(ramp_out, 0.0, 1.0)
stereo *= ramp_out[:, np.newaxis]
self.fade_out_counter += frames
if self.fade_out_counter >= self.fade_out_len:
self.is_finished = True
# Ensure silence after fade
cutoff = int(remaining)
if cutoff < frames:
stereo[cutoff:] = 0
self.samples_generated += frames
return stereo.astype(np.float32, copy=False)
class IsochronicGenerator:
"""
Generates isochronic tones - rhythmic pulses of sound at a specific beat frequency.
The carrier tone pulses on and off at the beat rate with equal intensity on both channels.
"""
def __init__(self, cfg: AudioConfig):
self.cfg = cfg
self.phase = 0.0
self.samples_generated = 0
self.ramp_s = cfg.ramp_duration_s
if self.cfg.noise_type != "None" and self.cfg.noise_volume > 0:
self.noise_gen = NoiseGenerator()
else:
self.noise_gen = None
self.wave_func = waveforms.get(cfg.left_waveform, np.sin)
self.drive = 2.5
self.tanh_drive = np.tanh(self.drive)
self.fade_in_len = int(0.02 * cfg.sample_rate)
self.fade_out_len = int(0.02 * cfg.sample_rate)
self.stopping = False
self.fade_out_counter = 0
self.is_finished = False
def request_stop(self):
self.stopping = True
def generate_block(self, frames: int) -> np.ndarray:
current_time = self.samples_generated / self.cfg.sample_rate
if self.cfg.use_ramp:
t_global = current_time + np.arange(frames, dtype=np.float64) / self.cfg.sample_rate
if self.ramp_s <= 0:
beat_hz = np.full(frames, self.cfg.end_beat_hz, dtype=np.float64)
else:
progress = np.clip(t_global / self.ramp_s, 0.0, 1.0)
beat_hz = self.cfg.start_beat_hz + (self.cfg.end_beat_hz - self.cfg.start_beat_hz) * progress
beat_hz = np.maximum(0.1, beat_hz)
carrier_hz = np.full(frames, self.cfg.carrier_hz, dtype=np.float64)
else:
beat_hz = np.full(frames, max(0.1, self.cfg.left_frequency), dtype=np.float64)
carrier_hz = np.full(frames, max(20.0, self.cfg.carrier_hz), dtype=np.float64)
inc = (2.0 * np.pi * carrier_hz / self.cfg.sample_rate)
phase_shift = np.concatenate(([0.0], np.cumsum(inc)[:-1]))
phase_vec = self.phase + phase_shift
self.phase = (self.phase + np.sum(inc)) % (2.0 * np.pi)
carrier_wave = self.wave_func(phase_vec)
period_samples = self.cfg.sample_rate / beat_hz
pulse = np.mod(np.arange(frames, dtype=np.float64) + self.samples_generated, period_samples) < (period_samples * 0.5)
mono = self.cfg.left_volume * carrier_wave * pulse.astype(np.float64)
stereo = np.column_stack((mono, mono))
if self.noise_gen:
noise = self.noise_gen.generate(self.cfg.noise_type, frames)
stereo += (noise * self.cfg.noise_volume)[:, np.newaxis]
stereo = np.tanh(stereo * self.drive) / self.tanh_drive
stereo = np.clip(stereo, -1.0, 1.0)
start_idx = self.samples_generated
if start_idx < self.fade_in_len:
ramp_in = np.arange(start_idx, start_idx + frames, dtype=np.float32) / self.fade_in_len
ramp_in = np.clip(ramp_in, 0.0, 1.0)
stereo *= ramp_in[:, np.newaxis]
if self.stopping:
remaining = self.fade_out_len - self.fade_out_counter
if remaining <= 0:
stereo.fill(0)
self.is_finished = True
self.samples_generated += frames
return stereo
t_fade = np.arange(self.fade_out_counter, self.fade_out_counter + frames, dtype=np.float32)
ramp_out = 1.0 - (t_fade / self.fade_out_len)
ramp_out = np.clip(ramp_out, 0.0, 1.0)
stereo *= ramp_out[:, np.newaxis]
self.fade_out_counter += frames
if self.fade_out_counter >= self.fade_out_len:
self.is_finished = True
cutoff = int(remaining)
if cutoff < frames:
stereo[cutoff:] = 0
self.samples_generated += frames
return stereo.astype(np.float32, copy=False)
class AudioEngine:
"""
Manages the audio playback stream using sounddevice.
Handles thread safety for starting and stopping playback.
"""
def __init__(self):
self._stream = None
self.generator = None
self._lock = threading.Lock()
self._data_lock = threading.Lock()
self.is_playing = False
self.start_time = 0.0
self.current_config = None
self.last_block = None
def start(self, cfg: AudioConfig):
self.stop()
with self._lock:
try:
if cfg.beat_type == "isochronic":
gen = IsochronicGenerator(cfg)
else:
gen = BinauralGenerator(cfg)
self.generator = gen
self.current_config = cfg
def callback(outdata, frames, time, status):
if status:
logger.warning(f"Audio status: {status}")
try:
# Generate audio using local 'gen' reference
# This avoids race conditions if self.generator is set to None by stop()
data = gen.generate_block(frames)
outdata[:] = data
# Store the last block for visualization
with self._data_lock:
self.last_block = data.copy()
# Check if finished (fade out complete)
if gen.is_finished:
raise sd.CallbackStop
except Exception as e:
if not isinstance(e, sd.CallbackStop):
logger.error("Audio callback error", exc_info=True)
# Silence on error
outdata.fill(0)
self._stream = sd.OutputStream(
samplerate=cfg.sample_rate,
channels=2,
callback=callback,
dtype="float32"
)
self._stream.start()
self.is_playing = True
self.start_time = time.time()
logger.info("Audio started")
except Exception as e:
logger.error("Failed to start audio", exc_info=True)
self.is_playing = False
if self._stream:
try:
self._stream.close()
except Exception: pass
self._stream = None
raise e
def stop(self):
"""Stops audio gracefully with fade out."""
# 1. Signal stop
with self._lock:
if not self.is_playing:
return
if self.generator:
self.generator.request_stop()
# 2. Wait for stream to finish (fade out)
# We wait up to 200ms
for _ in range(20):
with self._lock:
if self.generator and self.generator.is_finished:
break
# Also check if stream is inactive?
# stream.active might be true until callback returns Stop
time.sleep(0.01)
# 3. Force stop
with self._lock:
if self._stream:
try:
self._stream.stop()
self._stream.close()
except Exception:
logger.error("Error closing stream", exc_info=True)
self._stream = None
self.is_playing = False
self.generator = None
with self._data_lock:
self.last_block = None
logger.info("Audio stopped")
def get_elapsed_time(self):
if self.is_playing:
return time.time() - self.start_time
return 0.0
def get_last_block(self):
with self._data_lock:
if self.last_block is not None:
return self.last_block.copy()
return None
audio_engine = AudioEngine()
def stop_audio():
global live_status_after_id
global play_mode
# Stop UI update loop
if live_status_after_id is not None:
try:
root.after_cancel(live_status_after_id)
except Exception:
logger.error("Error cancelling live status update", exc_info=True)
live_status_after_id = None
try:
audio_engine.stop()
except Exception as e:
logger.error(f"Error stopping audio: {e}", exc_info=True)
play_mode = "manual"
# =============================================================================
# UI & Interaction
# =============================================================================
def set_osc_merge_waves():
"""Saves the merge waves setting and updates the live plot's static elements."""
if osc_merge_var is None:
return
is_merged = osc_merge_var.get()
config["osc_merge_waves"] = is_merged
save_config(config)
# If window is open, update its appearance in real-time
if osc_window and visualizer_ax and visualizer_canvas:
try:
# Update horizontal line visibility
if hasattr(visualizer_ax, '_hline'):
visualizer_ax._hline.set_visible(not is_merged)
# Update Y-ticks
if is_merged:
visualizer_ax.set_yticks([-1, 0, 1])
visualizer_ax.tick_params(axis='y', colors=visualizer_ax.yaxis.label.get_color(), length=4)
else:
visualizer_ax.set_yticks([])
visualizer_ax.tick_params(axis='y', length=0)
visualizer_canvas.draw_idle()
except Exception:
pass # Ignore if widgets are being destroyed
def set_osc_colors(palette_name: str):
"""Sets the oscilloscope color palette and saves to config."""
if palette_name not in OSC_COLOR_PALETTES:
return
config["osc_colors"] = palette_name
save_config(config)
# If oscilloscope is open, update its colors in real-time
if osc_window and visualizer_canvas and line_left and line_right:
try:
is_dark = root.style.theme_use() in ["darkly", "superhero"]
theme_mode = "dark" if is_dark else "light"
colors = OSC_COLOR_PALETTES[palette_name][theme_mode]
line_left.set_color(colors[0])
line_right.set_color(colors[1])
visualizer_canvas.draw_idle()
except Exception:
# Ignore errors if window/widgets are in a weird state
pass
def toggle_oscilloscope_window():
"""Opens or closes the real-time oscilloscope window."""
global osc_window, visualizer_canvas, visualizer_ax, line_left, line_right
global osc_plot_buffer_l, osc_plot_buffer_r
# If window exists, destroy it and clear references
if osc_window and osc_window.winfo_exists():
osc_window.destroy()
osc_window = None
visualizer_canvas = None
visualizer_ax = None
line_left = None
line_right = None
osc_plot_buffer_l = None
osc_plot_buffer_r = None
return
# Create new window
osc_window = tb.Toplevel(root)
osc_window.title("Real-time Oscilloscope")
osc_window.geometry("600x300")
def on_osc_close():
"""Callback for when the oscilloscope window is closed by the user."""
global osc_window, visualizer_canvas, visualizer_ax, line_left, line_right
global osc_plot_buffer_l, osc_plot_buffer_r
win_to_destroy = osc_window
# Nullify globals to prevent race conditions with the update loop
osc_window = None
visualizer_canvas = None
visualizer_ax = None
line_left = None
line_right = None
osc_plot_buffer_l = None
osc_plot_buffer_r = None
# Since we overrode the protocol, we are responsible for destroying the window.
if win_to_destroy:
try:
win_to_destroy.destroy()
except tk.TclError:
pass # Window is already being destroyed
osc_window.protocol("WM_DELETE_WINDOW", on_osc_close)
# Initialize plot buffers
sample_rate = 44100 # Match audio engine
buffer_size = int(OSC_BUFFER_SECONDS * sample_rate)
osc_plot_buffer_l = np.zeros(buffer_size, dtype=np.float32)
osc_plot_buffer_r = np.zeros(buffer_size, dtype=np.float32)
fig = Figure(figsize=(5, 2), dpi=100)
visualizer_ax = fig.add_subplot(111)
# Style the plot to match the theme
is_dark = root.style.theme_use() in ["darkly", "superhero"]
theme_mode = "dark" if is_dark else "light"
current_palette_name = config.get("osc_colors", "Cyan / Magenta")
palette = OSC_COLOR_PALETTES.get(current_palette_name, OSC_COLOR_PALETTES["Cyan / Magenta"])
colors = palette[theme_mode]
line_color_l, line_color_r = colors
bg_color = root.style.colors.get("bg")
fg_color = root.style.colors.get("fg")
fig.patch.set_facecolor(bg_color)
visualizer_ax.set_facecolor(bg_color)
visualizer_ax.tick_params(axis='both', colors=fg_color, length=0)
visualizer_ax.spines['bottom'].set_color(fg_color)
visualizer_ax.spines['top'].set_color(fg_color)
visualizer_ax.spines['left'].set_color(fg_color)
visualizer_ax.spines['right'].set_color(fg_color)
visualizer_ax.xaxis.label.set_color(fg_color)
visualizer_ax.yaxis.label.set_color(fg_color)
# Add a horizontal line to separate channels, and store a reference to it
visualizer_ax._hline = visualizer_ax.axhline(0, color=fg_color, lw=0.5, ls='--')
x_data = np.arange(buffer_size)
line_left, = visualizer_ax.plot(x_data, osc_plot_buffer_l, lw=1, color=line_color_l)
line_right, = visualizer_ax.plot(x_data, osc_plot_buffer_r, lw=1, color=line_color_r)
visualizer_ax.set_ylim(-1.1, 1.1)
visualizer_ax.set_xlim(0, buffer_size)
visualizer_ax.set_xticks([])
# Set initial view based on config
is_merged = config.get("osc_merge_waves", False)
visualizer_ax._hline.set_visible(not is_merged)
if is_merged:
visualizer_ax.set_yticks([-1, 0, 1])
visualizer_ax.tick_params(axis='y', colors=fg_color, length=4)
else:
visualizer_ax.set_yticks([])
visualizer_ax.tick_params(axis='y', length=0)
fig.tight_layout()
visualizer_canvas = FigureCanvasTkAgg(fig, master=osc_window)
visualizer_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def _run_export_thread(cfg, filename, duration, progress_win, progress_bar, progress_label, on_success, on_error):
"""Background thread function for exporting audio to a WAV file."""
try:
sample_rate = cfg.sample_rate
total_frames = int(duration * sample_rate)
block_size = 4096
generator = BinauralGenerator(cfg)
frames_written = 0
all_audio = []
while frames_written < total_frames:
# Check for window close (cancellation) via event or shared flag?
# For simplicity, we just check if window exists via main thread callback
chunk_size = min(block_size, total_frames - frames_written)
audio_block = generator.generate_block(chunk_size)
all_audio.append(audio_block)
frames_written += chunk_size
percent = (frames_written / total_frames) * 100
def update_ui(p=percent):
try:
if progress_win.winfo_exists():
progress_bar['value'] = p
progress_label.config(text=f"Generating... {int(p)}%")
except Exception: pass
root.after(0, update_ui)
full_audio = np.concatenate(all_audio)
# Apply fade out to the very end (last 20ms) for clean cut
fade_len = int(0.02 * sample_rate)
if len(full_audio) > fade_len:
ramp = np.linspace(1.0, 0.0, fade_len, dtype=np.float32)
full_audio[-fade_len:] *= ramp[:, np.newaxis]
wavfile.write(filename, sample_rate, full_audio)
root.after(0, lambda: on_success(filename))
except Exception as e:
root.after(0, lambda: on_error(e))
def export_audio_file():
"""Initiates the audio export process with UI dialogs."""
stop_audio()
try:
cfg = get_audio_config_from_ui()
default_duration = cfg.ramp_duration_s if cfg.use_ramp else 300.0
duration_str = simpledialog.askstring("Export Audio", f"Enter duration in seconds:", initialvalue=str(int(default_duration)))
if not duration_str:
return
try:
duration = float(duration_str)
if duration <= 0:
raise ValueError
except ValueError:
messagebox.showerror("Input Error", "Duration must be a positive number.")
return
filename = filedialog.asksaveasfilename(
title="Export WAV",
defaultextension=".wav",
filetypes=[("WAV files", "*.wav")]
)
if not filename:
return
# Progress Window
progress_win = tb.Toplevel(root)
progress_win.title("Exporting...")
progress_win.geometry("300x100")
progress_label = ttk.Label(progress_win, text="Generating audio...")
progress_label.pack(pady=10)
progress_bar = ttk.Progressbar(progress_win, mode='determinate')
progress_bar.pack(fill=tk.X, padx=20, pady=10)
def on_success(fname):
try:
if progress_win.winfo_exists():
progress_win.destroy()
logger.info(f"Exported audio to {fname}")
messagebox.showinfo("Export Complete", f"Saved to {fname}")
except Exception: pass
def on_error(e):
try:
if progress_win.winfo_exists():
progress_win.destroy()
logger.error("Export failed", exc_info=True)
messagebox.showerror("Export Error", f"Export failed: {str(e)}")
except Exception: pass
t = threading.Thread(target=_run_export_thread, args=(cfg, filename, duration, progress_win, progress_bar, progress_label, on_success, on_error))
t.start()