-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
2187 lines (1791 loc) · 97.2 KB
/
main.py
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
# Test Signal Maker - Loudspeaker testing tool
# Copyright (C) 2024 - Kerem Basaran
# https://github.com/kbasaran
__email__ = "kbasaran@gmail.com"
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# from datetime import date
# today = date.today()
from pathlib import Path
app_definitions = {"app_name": "Test Signal Maker",
"version": "0.2.3",
# "version": "Test build " + today.strftime("%Y.%m.%d"),
"description": "Test Signal Maker - Loudspeaker test signal tool",
"copyright": "Copyright (C) 2024 Kerem Basaran",
"icon_path": str(Path("./logo/icon.ico")),
"author": "Kerem Basaran",
"author_short": "kbasaran",
"email": "kbasaran@gmail.com",
"website": "https://github.com/kbasaran",
}
import sys
import os
import time
# https://doc.qt.io/qtforpython/
from PySide6 import QtWidgets as qtw
from PySide6 import QtCore as qtc
from PySide6 import QtGui as qtg
import sounddevice as sd # https://python-sounddevice.readthedocs.io
import numpy as np
import soundfile as sf # https://python-soundfile.readthedocs.io/
from scipy import signal
import copy
from datetime import datetime
import matplotlib.pyplot as plt # http://matplotlib.org/
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from generictools.signal_tools import TestSignal, make_fade_window_n, calculate_3rd_octave_bands
import generictools.personalized_widgets as pwi
from dataclasses import dataclass, fields
import logging
import multiprocessing
class FileImportDialog(qtw.QDialog):
def __init__(self, main_win_signals):
super().__init__()
# self.setModal(True)
self.setWindowTitle("Import file")
self.setMinimumSize(120, 100)
self.choose_channel_label = qtw.QLabel("Channel to use")
self.choose_channel_combo = qtw.QComboBox(enabled=False)
self.choose_channel_combo.addItem("Channel 1", None)
self.choose_channel_combo.setCurrentIndex(0)
self.sample_rate_label = qtw.QLabel("Sample rate")
self.sample_rate_combo = qtw.QComboBox(enabled=False)
self.buttonBox = qtw.QDialogButtonBox(qtw.QDialogButtonBox.Ok | qtw.QDialogButtonBox.Cancel)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
# Layout
self.layout = qtw.QVBoxLayout()
self.form_layout = qtw.QFormLayout()
self.setLayout(self.layout)
self.layout.addWidget(self.choose_file_button)
self.layout.addLayout(self.form_layout)
self.layout.addWidget(self.buttonBox, alignment=qtc.Qt.AlignHCenter)
self.form_layout.addRow("Channel to use:", self.choose_channel_combo)
self.form_layout.addRow("Sample rate", self.sample_rate_combo)
# Popup window for warnings
class PopupError():
# https://www.techwithtim.net/tutorials/pyqt5-tutorial/messageboxes/
def __init__(self, text, informative_text=None, post_action=None, title="Error"):
msg = qtw.QMessageBox()
msg.setWindowTitle(title)
msg.setText(text)
# msg.setMinimumWidth(200) # doesn't work
msg.setInformativeText(informative_text)
msg.setIcon(qtw.QMessageBox.Warning)
msg.setStandardButtons(qtw.QMessageBox.Ok)
def ok_button_pressed():
if post_action:
post_action()
msg.buttonClicked.connect(ok_button_pressed)
msg.exec()
class SysGainAndLevelsPopup(qtw.QDialog):
global settings
user_changed_sys_params_signal = qtc.Signal()
# channel_count_changed = qtc.Signal(int)
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setWindowTitle("System parameters")
self.setMinimumWidth(400)
self.setMinimumHeight(200)
# Form for gains
sys_gain_form_layout = qtw.QFormLayout()
preferred_device_name = settings.preferred_device
preferred_device_widget = qtw.QComboBox()
for device in sd.query_devices():
hostapi_name = sd.query_hostapis(index=device['hostapi'])['name']
if device["max_output_channels"] > 0 and "WDM" not in hostapi_name and "MME" not in hostapi_name:
device_name = device['name']
data_name = hostapi_name + " - " + device_name
user_friendly_name = f"{data_name} - {device['max_output_channels']} channels"
if device["index"] == sd.default.device[1]:
default_device_user_friendly_name = user_friendly_name
preferred_device_widget.addItem(user_friendly_name, data_name) # data is the pure name from sounddevice. sometimes duplicate.
preferred_device_index = preferred_device_widget.findData(preferred_device_name) # -1 needs not found, and empty selection
if preferred_device_index == -1:
preferred_device_widget.setCurrentText(default_device_user_friendly_name) # does this raise an error if that device name is not in the combobox?
else:
preferred_device_widget.setCurrentIndex(preferred_device_index)
sys_gain_form_layout.addRow("Preferred device", preferred_device_widget)
number_of_channels_widget = qtw.QSpinBox(Minimum=2,
Maximum=int(settings.max_channel_count),
ToolTip="Number of amplifier channels that should become available.",
Value=int(settings.channel_count),
)
sys_gain_form_layout.addRow("Active channels", number_of_channels_widget)
channel_gain_widgets = {}
for cn in range(1, int(settings.max_channel_count) + 1):
channel_gain_widgets[cn] = qtw.QDoubleSpinBox(Minimum=-100,
Maximum=200,
SingleStep=0.1,
Value=float(settings.system_gains[cn-1]),
ToolTip="\n".join(["in dB, Volts per full scale.",
"e.g. setting 26 means a full scale sine wave is creating 20V peaks at amplifier output.",
"1 * 10^(26/20) = 20V"])
)
sys_gain_form_layout.addRow(f"System gain for Ch. {cn}", channel_gain_widgets[cn])
# Peak amp voltage
amp_peak_capability_widget = qtw.QDoubleSpinBox(Minimum=0.0001,
Maximum=999,
Value=settings.amp_peak,
)
# Sweep sample rate
play_sample_rate = qtw.QComboBox()
for val in [44100, 48000, 96000]:
play_sample_rate.addItem(str(val), val)
# check which value is stored in settings
current_val = settings.play_sample_rate
current_val_idx = play_sample_rate.findData(current_val)
if current_val_idx == -1: # if the sapmle rate is not available in current list
play_sample_rate.setCurrentIndex(1)
else:
play_sample_rate.setCurrentIndex(current_val_idx)
# Stream latency
stream_latency = qtw.QComboBox()
stream_latency.addItem("Sound device default: High", "high")
stream_latency.addItem("Sound device default: Low", "low")
stream_latency.addItem("User value: Safe - 25ms", "0.025")
stream_latency.addItem("User value: Very safe - 50ms", "0.05")
current_val = settings.stream_latency # always as str
current_val_idx = stream_latency.findData(current_val)
if current_val_idx == -1:
stream_latency.setCurrentIndex(0)
else:
stream_latency.setCurrentIndex(current_val_idx)
# Rest of the layouts
sys_gain_form_layout.addWidget(qtw.QFrame(FrameShape=qtw.QFrame.HLine, FrameShadow=qtw.QFrame.Sunken))
sys_gain_form_layout.addRow("Amplifier peak capability (V)", amp_peak_capability_widget)
sys_gain_form_layout.addWidget(qtw.QFrame(FrameShape=qtw.QFrame.HLine, FrameShadow=qtw.QFrame.Sunken))
sys_gain_form_layout.addRow("Play sample rate", play_sample_rate)
sys_gain_form_layout.addRow("Stream latency", stream_latency)
# Pushbutton
save_sys_gain_settings = qtw.QPushButton("Save and close")
save_sys_gain_settings.setStyleSheet("padding: 7px;")
# Make layout
gain_and_levels_window_layout = qtw.QVBoxLayout()
self.setLayout(gain_and_levels_window_layout)
gain_and_levels_window_layout.addLayout(sys_gain_form_layout)
gain_and_levels_window_layout.addWidget(save_sys_gain_settings, alignment=qtc.Qt.AlignHCenter)
@qtc.Slot(int)
def disable_inactive_channels_widgets(channel_count):
for i in range(1, int(settings.max_channel_count) + 1):
channel_gain_widgets[i].setEnabled(i <= channel_count)
number_of_channels_widget.valueChanged.connect(disable_inactive_channels_widgets)
# Run once at start_up:
disable_inactive_channels_widgets(number_of_channels_widget.value())
def save_and_close():
settings.update("preferred_device", preferred_device_widget.currentData())
system_gains = list(settings.system_gains)
for cn in channel_gain_widgets.keys():
system_gains[cn-1] = channel_gain_widgets[cn].value()
settings.update("system_gains", tuple(system_gains))
settings.update("amp_peak", amp_peak_capability_widget.value())
settings.update("channel_count", number_of_channels_widget.value())
settings.update("max_channel_count", settings.max_channel_count) # so this stays fixed, no user option to change it yet
settings.update("play_sample_rate", play_sample_rate.currentData())
settings.update("stream_latency", stream_latency.currentData())
self.user_changed_sys_params_signal.emit()
self.done(0)
logger.info("System parameters changed by user.")
save_sys_gain_settings.clicked.connect(save_and_close)
def update_max_channel_count(device_index):
device = sd.query_devices()[device_index]
number_of_channels_widget.setMaximum(max(device["max_output_channels"],
int(settings.max_channel_count),
)
)
preferred_device_widget.currentIndexChanged.connect(update_max_channel_count)
class Generator(qtc.QObject):
"""
Signal generator object.
"""
# signals need to be class variables as you see. don't know why. PyQt thing.
signal_ready = qtc.Signal(TestSignal)
file_import_success = qtc.Signal(TestSignal)
busy = qtc.Signal(str)
exception = qtc.Signal(Exception)
@qtc.Slot(str)
def import_file(self, import_file_path):
logger.debug(f'Importing file...{import_file_path}')
self.busy.emit("Importing file...")
try:
self.imported_signal = TestSignal("Imported",
import_file_path=import_file_path,
import_channel="downmix_all",
)
self.file_import_success.emit(self.imported_signal)
logger.debug("Signal imported and params published.")
except Exception as e:
# Pop-up
logger.error("Import failed" + str(e))
self.exception.emit(e)
@qtc.Slot()
def clear_imported_file(self):
self.imported_signal = None
@qtc.Slot(str, dict)
def process_imported_file(self, sig_type, kwargs):
self.busy.emit("Generating from import...")
try:
if not hasattr(self, "imported_signal") or not self.imported_signal:
raise KeyError("No file imported to process.")
generated_signal = copy.deepcopy(self.imported_signal)
generated_signal.reuse_existing(**kwargs)
self.signal_ready.emit(generated_signal)
logger.debug("Imported signal has been processed and published.")
except Exception as e:
# Pop-up
logger.error(str(e))
self.exception.emit(e)
@qtc.Slot(str, dict)
def generate_ugs(self, sig_type, kwargs):
logger.debug(f'Generate ugs "{sig_type}" initiated')
self.busy.emit(f"Generating {sig_type.lower()}...")
try:
generated_signal = TestSignal(sig_type, **kwargs)
self.signal_ready.emit(generated_signal)
logger.info(f"Signal with type {sig_type} generated.")
except Exception as e:
# Pop-up
logger.error(str(e))
self.exception.emit(e)
class LogView(qtw.QDialog):
def __init__(self, input_dict):
super().__init__()
fig = plt.Figure()
self.canvas = FigureCanvas(fig)
self.toolbar = NavigationToolbar(self.canvas, self)
lay = qtw.QVBoxLayout(self)
lay.addWidget(self.toolbar)
lay.addWidget(self.canvas)
lay.setContentsMargins(0, 0, 0, 0)
self.ax = fig.add_subplot(111)
fig.tight_layout()
self.setLayout(lay)
self.update_plot(input_dict)
@qtc.Slot(list)
def update_plot(self, input_dict):
self.ax.cla()
self.ax.plot(input_dict["time_sig"], ".-")
self.ax.plot(np.array(input_dict["fade_out_window"]) * np.max(input_dict["time_sig"]), "-m")
self.ax.plot(np.array(input_dict["fade_in_window"]) * np.max(input_dict["time_sig"]), "-g")
self.ax.grid(which='minor', axis='x')
self.ax.grid(which='major', axis='y')
# self.ax.legend()
self.canvas.draw()
def clear_plot(self):
self.update_plot(None)
class Player(qtc.QObject):
global settings
play_stopped = qtc.Signal(str)
play_started = qtc.Signal(str)
sweep_generated = qtc.Signal(float, float)
sweep_generator_stopped = qtc.Signal(str)
signal_sound_devices_polled = qtc.Signal(str)
signal_exception = qtc.Signal(str)
publish_log = qtc.Signal(dict)
impossible_voltage_request = qtc.Signal(str)
log_through_thread = qtc.Signal(str)
# which methods should have exception handling in them?
def __init__(self):
super().__init__()
# default setting for sd
sd.default.prime_output_buffers_using_stream_callback = True
# pre-assign state variables for sweep generator
self._theta_last = np.nan
self._omega_last = np.nan
self.play_pos = None
self.is_play_in_loop = False
self.reset_fade_out()
self.output_log = {"time_sig": [],
"fade_out_window": np.array([]),
"fade_in_window": [],
}
self.log_output_signal = False # logs channel 1 and plot it for debugging
# define the sound device based on settings and availability
self.find_right_sound_device()
# Inititate attributes
self._sweep_voltage = 0
self._sweep_channel = 0
# start default stream
self._create_stream()
def _create_stream(self, force_sample_rate=None):
"""Prepare the stream object with provided settings"""
# Close any existing stream
if hasattr(self, "stream"):
self.stop_play_blocking()
self.stream.close()
self._bring_sweep_states_to_zero(settings.channel_count)
sample_rate = force_sample_rate if force_sample_rate else settings.play_sample_rate
try:
stream_latency = float(settings.stream_latency) # for values in s
except ValueError:
stream_latency = str(settings.stream_latency) # for 'high' and 'low'
self.stream = sd.OutputStream(callback=self.callback,
device=self.play_device_idx,
finished_callback=self.announce_callback_is_finished,
samplerate=sample_rate,
channels=settings.channel_count,
latency=stream_latency,
)
self.fade_window_size = int(self.stream.samplerate // 20)
self.ugs_play_stopwatch = -1.
def reset_fade_out(self):
self.fade_out_frames = {"remaining": np.nan,
"total": np.nan,
"stop_after": None,
}
def announce_callback_is_finished(self):
if self.play_pos:
if self.stop_after_seconds:
self.play_stopped.emit(f"Stopped with timer after {self.stop_after_seconds/60:.1f} minutes.")
else:
self.play_stopped.emit("Stopped.")
self.play_pos = None
self.reset_fade_out()
self.user_req_omega, self.user_req_alpha = np.nan, np.nan
self.sweep_generator_stopped.emit("Stopped")
self._bring_sweep_states_to_zero(self.stream.channels)
self.sweep_generated.emit(np.nan, np.nan)
# Debugging
if self.log_output_signal:
# this crashes when a stream is present but no signal has been played yet, e.g. in startup
self.publish_log.emit(self.output_log)
self.output_log = {"time_sig": [],
"fade_out_window": [],
"fade_in_window": [],
}
logger.info("Callback stopped.")
def find_right_sound_device(self):
preferred_device_name = settings.preferred_device
device_name_to_index = {}
for device in sd.query_devices():
hostapi_name = sd.query_hostapis(index=device['hostapi'])['name']
device_name = device['name']
data_name = hostapi_name + " - " + device_name
device_name_to_index[data_name] = device["index"]
self.play_device_idx = device_name_to_index.get(preferred_device_name, sd.default.device[1])
# 0 is the recording device, 1 is playback
# sd.default.device returns (int, int)
@qtc.Slot()
def poll_sound_devices(self):
try:
# this is invoked regularly to update the current sound device in use
# without this, when default device is changed in operating system, there is no detection
# https://github.com/spatialaudio/python-sounddevice/issues/337
# if not self.stream.active: # if stream is not active
# sd._terminate()
# sd._initialize()
self.find_right_sound_device()
play_device_info = sd.query_devices(self.play_device_idx)
# this doesn't update when default sound device is changed in operating system :(
# thus the trick above
play_device_summary = f"""Device name: {play_device_info['name']}
--Host API: {sd.query_hostapis()[play_device_info['hostapi']]["name"]}
--Max. output channels: {play_device_info['max_output_channels']}
--Default samplerate: {int(play_device_info['default_samplerate'])}
--Default data type: {sd.default.dtype[1]}
"""
play_device_summary += f"--Reported latency: {self.stream.latency * 1000:.3g}ms"
except Exception as e:
play_device_summary = f"Exception while detecting sound devices.\n{e}"
self.signal_sound_devices_polled.emit(play_device_summary)
def calculate_digital_signal_rms(self, requested_voltages: dict, signal_CF: float) -> list:
"""
Calculates the digital signal rms that is necessary to get the correct voltage output.
Also checks if this signal level might cause clipping.
"""
if not isinstance(requested_voltages, dict) or not isinstance(signal_CF, (float, int)):
self.signal_exception.emit("Incorrect data type received for voltage to digital signal RMS conversion.")
raise sd.CallbackAbort
amp_peak_voltage_capability = settings.amp_peak
channels = requested_voltages.keys()
rms_for_digital_signals = {cn: requested_voltages[cn] / 10**(settings.system_gains[cn-1] / 20) for cn in channels}
peak_for_digital_signals = {cn: rms * signal_CF for cn, rms in rms_for_digital_signals.items()}
peak_voltages = {cn: requested_voltages[cn] * signal_CF for cn in channels}
if max(peak_for_digital_signals.values()) > 1:
error_text = "Current settings will cause digital clipping at sound card output."
informative_text = ("Increase amplifier gain or reduce target RMS voltage and/or signal crest factor."
+ "\nMake sure system gain is entered correctly."
)
self.stop_play()
self.signal_exception.emit(error_text + "\n" + informative_text)
self.impossible_voltage_request.emit(error_text)
elif max([val for val in peak_voltages.values()]) > amp_peak_voltage_capability: # val is in abs. why?
error_text = f"Required peaks exceed amplifier peak voltage capability of {self._sys_params['amp_peak']} V."
informative_text = ("Reduce target RMS voltage and/or crest factor."
+ "\nMake sure system gain and amplifier peak voltage capability is entered correctly."
)
self.stop_play()
self.signal_exception.emit(error_text + "\n" + informative_text)
self.impossible_voltage_request.emit(error_text)
else:
return rms_for_digital_signals
def _bring_sweep_states_to_zero(self, channel_count):
self._omega_last = 0.
self._theta_last = 0.
self._sweep_level_last = 0.
def calculate_quiet(self, t_array, theta_start, omega_start, omega_end):
"""
Calculate a quiet section
Returns a tuple with,
one channel array of theta, last value of theta, last value of omega
"""
mono_signal_chunk = np.zeros(len(t_array))
theta_last = 0
omega_last = 0
return mono_signal_chunk, theta_last, omega_last
def calculate_lin_sweep(self, t_array, theta_start, omega_start, omega_end):
"""
Calculate a linear sine sweep
Returns a tuple with,
one channel array of theta, last value of theta, last value of omega
"""
T = t_array[-1]
alpha = (omega_end - omega_start) / T
theta_array = (theta_start + omega_start * t_array + alpha * t_array**2 / 2) % (2 * np.pi)
mono_signal_chunk = np.sin(theta_array)
theta_last = theta_array[-1]
omega_last = omega_start + alpha * T
return mono_signal_chunk, theta_last, omega_last
def calculate_exp_sweep(self, t_array, theta_start, omega_start, omega_end):
"""
Calculate an exponential sine sweep
Returns a tuple with,
one channel array of theta, last value of theta, last value of omega
"""
T = t_array[-1]
n = (omega_end / omega_start)**(1 / T)
k = omega_start / np.log(n)
theta_array = (theta_start + k * (np.exp(t_array * np.log(n)) - 1)) % (2 * np.pi)
mono_signal_chunk = np.sin(theta_array)
theta_last = theta_array[-1]
omega_last = omega_end
return mono_signal_chunk, theta_last, omega_last
def calculate_exp_sweep_with_acceleration():
"""
Calculate an exponential sine sweep with user defined acceleration.
Returns a tuple with,
one channel array of theta, last value of theta, last value of omega
"""
pass
def callback_for_ugs(self, frames):
"We are doing a callback for streaming an already generated signal"
stream_needs_to_stop_now = False
try:
# Try to fill the soundcard buffer within this loop
empty_frames = int(frames)
mono_signal_chunk = np.empty(frames)
while empty_frames > 0:
logger.debug("---Fill cycle---")
logger.debug(f"Play pos: {self.play_pos}")
len_user_signal = len(self.user_gen_signal.time_sig)
remaining_in_user_signal = len_user_signal - self.play_pos
if remaining_in_user_signal > 0:
number_of_samples_to_write = min(remaining_in_user_signal, empty_frames)
part_mono_signal_chunk = self.user_gen_signal.time_sig[self.play_pos:self.play_pos + number_of_samples_to_write]
else: # fill it all with empty
number_of_samples_to_write = empty_frames
part_mono_signal_chunk = np.zeros(empty_frames)
# trigger fade_out because end of the signal is coming
if (remaining_in_user_signal <= self.fade_window_size) and np.isnan(self.fade_out_frames["remaining"]):
self.fade_out_frames = {"remaining": remaining_in_user_signal,
"total": remaining_in_user_signal,
"stop_after": False,
}
logger.debug(f"Fade out frames: {self.fade_out_frames}")
# reached end of fade-out and not gonna loop, so stop calling back
if (self.fade_out_frames["remaining"] <= empty_frames) and (not self.is_play_in_loop or self.fade_out_frames["stop_after"]):
stream_needs_to_stop_now = True
# Apply fade-out
if self.fade_out_frames["remaining"] > 0:
fade_start_end_idxs = (self.fade_out_frames["remaining"] - self.fade_out_frames["total"],
self.fade_out_frames["remaining"],
)
fade_out_window = make_fade_window_n(1,
0,
number_of_samples_to_write,
fade_start_end_idxs,
)
part_mono_signal_chunk = part_mono_signal_chunk * fade_out_window
if self.log_output_signal:
self.output_log["fade_out_window"] = np.concatenate([self.output_log["fade_out_window"], fade_out_window])
self.fade_out_frames["remaining"] -= number_of_samples_to_write
else:
if self.log_output_signal:
self.output_log["fade_out_window"] = np.concatenate([self.output_log["fade_out_window"], np.ones(number_of_samples_to_write) * np.nan])
# note: the player tab is not disabled during playing a signal
# Apply fade-in
if self.play_pos < self.fade_window_size:
fade_start_end_idxs = (-self.play_pos,
self.fade_window_size - self.play_pos,
)
fade_in_window = make_fade_window_n(0,
1,
number_of_samples_to_write,
fade_start_end_idxs,
)
part_mono_signal_chunk = part_mono_signal_chunk * fade_in_window
if self.log_output_signal:
window_to_write = list(fade_in_window if self.play_pos < self.fade_window_size else np.ones(number_of_samples_to_write) * np.nan)
self.output_log["fade_in_window"].extend(window_to_write)
# add the data from this while loop to the temporary signal block
start_position = frames - empty_frames
mono_signal_chunk[start_position:(start_position + number_of_samples_to_write)] = part_mono_signal_chunk
empty_frames -= number_of_samples_to_write
self.play_pos += number_of_samples_to_write
if self.is_play_in_loop:
self.play_pos = self.play_pos % len_user_signal
# Reset the fade-out counters when fade-out is over
if (self.fade_out_frames["remaining"] <= 0):
self.reset_fade_out()
# Make a table with correct rms signal levels
initial_rms = self.user_gen_signal.RMS
ugs_play_rms_levels = np.empty(self.stream.channels)
for channel in range(1, self.stream.channels + 1):
ugs_play_rms_levels[channel - 1] = self._ugs_play_signal_rms[channel]
if self.log_output_signal:
logger.debug(f"User generated signal play levels: {ugs_play_rms_levels:.4f}")
if self.ugs_play_stopwatch == -1.:
self.log_through_thread.emit(f"Started with: {self._ugs_play_voltages}Vrms")
self.ugs_play_stopwatch = time.time()
if time.time() > self.ugs_play_stopwatch + 60 * 60: # every hour
self.log_through_thread.emit(f"Ongoing with: {self._ugs_play_voltages}Vrms")
self.ugs_play_stopwatch = time.time()
return mono_signal_chunk, initial_rms, ugs_play_rms_levels, stream_needs_to_stop_now
except Exception as e:
logger.critical(
f"Failed to add {frames} frames during usg callback." +
f"\nPosition: {self.play_pos}/{len(self.user_gen_signal.time_sig)}. Error: {str(e)}")
raise sd.CallbackAbort # why?
def callback_for_sweep(self, frames):
"We are doing a frequency generator callback"
stream_needs_to_stop_now = False
try:
target_omega, alpha = self.user_req_omega, self.user_req_alpha
# Our time array for this callback.
# 0 represents latest value therefore starting from 1
t_array = np.arange(1, frames + 1) / self.stream.samplerate
# if user requests acceleration and not a target omega
# this will translate alpha and change target_omega from nan to a value
if np.isnan(target_omega) and not np.isnan(alpha):
target_omega = min(self.stream.samplerate / 3,
max(0,
self._omega_last * 2**(alpha * frames),
)
)
# Exponential sweep is necessary
if target_omega > 0 and self._omega_last > 0 and (target_omega != self._omega_last):
logger.debug("Callback case exponential")
mono_signal_chunk, self._theta_last, self._omega_last =\
self.calculate_exp_sweep(t_array,
self._theta_last,
self._omega_last,
target_omega,
)
# output should be faded out to zero if target is 0Hz.
# Need to be quiet
elif target_omega == 0 and self._omega_last == 0:
logger.debug("Callback case zero output")
# Otherwise it clicks.
mono_signal_chunk = np.zeros(frames)
# Linear sweep is necessary
else:
logger.debug("Callback case linear")
mono_signal_chunk, self._theta_last, self._omega_last =\
self.calculate_lin_sweep(t_array,
self._theta_last,
self._omega_last,
target_omega,
)
# There was a omega=0 case. Reset the theta and omega values.
if target_omega == 0:
self._bring_sweep_states_to_zero(self.stream.channels)
# set the signals to rms = 1 and also do the smooth crossing between voltages
logger.debug(f"self._sweep_level_last, self._sweep_signal_rms: {self._sweep_level_last}, {self._sweep_signal_rms}")
mono_signal_chunk = mono_signal_chunk / np.exp2(-0.5) * make_fade_window_n(self._sweep_level_last,
self._sweep_signal_rms,
frames,
)
self._sweep_level_last = self._sweep_signal_rms
# If this was the last fade-out callback and calling back needs to stop
if self.fade_out_frames["remaining"] <= frames:
stream_needs_to_stop_now = True
# Apply fade-out
if not np.isnan(self.fade_out_frames["remaining"]):
fade_start_end_idxs = (self.fade_out_frames["remaining"] - self.fade_out_frames["total"],
self.fade_out_frames["remaining"],
)
fade_out_window = make_fade_window_n(1,
0,
frames,
fade_start_end_idxs,
)
mono_signal_chunk = mono_signal_chunk * fade_out_window
logger.debug(f"Remaining/prepared fade out frames: {self.fade_out_frames['remaining']}/{len(fade_out_window)}")
if self.log_output_signal:
self.output_log["fade_out_window"] = np.concatenate([self.output_log["fade_out_window"], fade_out_window])
self.fade_out_frames["remaining"] -= frames
else:
if self.log_output_signal:
self.output_log["fade_out_window"] = np.concatenate([self.output_log["fade_out_window"], np.ones(frames) * np.nan])
# Reset the fade-out counters
if (self.fade_out_frames["remaining"] <= 0):
self.reset_fade_out()
# Make a table with correct rms signal levels
initial_rms = 1 # rms was made 1 above
target_rms_levels = np.zeros(self.stream.channels)
logger.debug(f"_sweep_channel, _sweep_signal_rms: {self._sweep_channel}, {self._sweep_signal_rms}")
target_rms_levels[self._sweep_channel - 1] = 1
# dynamic level adjustment is handled in the fade functions (ramping). therefore here the gain is neutral.
logger.debug(f"Sweep levels: {target_rms_levels}")
# Tell Main window which frequency you are at
if self._sweep_signal_rms == 0 or target_omega == 0:
self.sweep_generated.emit(np.nan, self.stream.latency)
else:
self.sweep_generated.emit(self._omega_last / 2 / np.pi, self.stream.latency)
# doesn't work on initiation # what??
return mono_signal_chunk, initial_rms, target_rms_levels, stream_needs_to_stop_now
except Exception as e:
logger.critical(
f"Failed to add {frames} frames during sweep generator callback. Error: {repr(e)}")
raise sd.CallbackAbort
def callback(self, indata, frames, ctime, status):
"""
Callback function for sounddevice player.
Initiated wheneversound device runs out of buffer.
Avoid placing memory allocation or i/o tasks in here.
"""
logger.debug("")
logger.debug(f"----Callback for DAC time: {ctime.outputBufferDacTime}----")
if logger.level < 20: # 20 is info, 10 is debug
t1_start = time.perf_counter_ns()
if status.output_underflow:
self.log_through_thread.emit("Buffer underflow. Consider increasing latency settings.")
# raise sd.CallbackAbort
# Maybe switch to high latency if this occurs
elif status and not status.priming_output:
error_message = f"Unexpected callback status: {status}"
logger.warning(error_message)
# Nothing to play
if (self.play_pos is None) and (np.isnan(self.user_req_alpha) and np.isnan(self.user_req_omega)):
mono_signal_chunk = np.zeros(frames)
logger.debug("Nothing to play for the callback. Put in zeros.")
# Play a user generated signal
elif self.play_pos is not None:
mono_signal_chunk, initial_rms, target_rms_levels, stream_needs_to_stop_now = self.callback_for_ugs(frames)
# Play a sweep
elif (not np.isnan(self.user_req_alpha)) or (not np.isnan(self.user_req_omega)):
mono_signal_chunk, initial_rms, target_rms_levels, stream_needs_to_stop_now = self.callback_for_sweep(frames)
# Write to sound card
indata[:frames, :self.stream.channels] = mono_signal_chunk\
.repeat(self.stream.channels, axis=0)\
.reshape(frames, self.stream.channels)\
/ initial_rms * np.array(target_rms_levels) # scale for correct voltages
# log the output signal
if self.log_output_signal:
logger.info(f"Adding to log the signal. Remaining fade frames after this: {self.fade_out_frames['remaining']}")
self.output_log["time_sig"].extend([float(i) for i in indata[:, 0]]) # only channel 1 is logged
max_length = int(self.stream.samplerate * 3)
if len(self.output_log["time_sig"]) > max_length:
self.output_log["time_sig"] = self.output_log["time_sig"][-max_length:]
if len(self.output_log["fade_out_window"]) > max_length:
self.output_log["fade_out_window"] = self.output_log["fade_out_window"][-max_length:]
if len(self.output_log["fade_in_window"]) > max_length:
self.output_log["fade_in_window"] = self.output_log["fade_in_window"][-max_length:]
logger.debug(f"Callback current / buffer DAC time: {ctime.currentTime} / {ctime.outputBufferDacTime}")
if logger.level < 20: # 20 is info, 10 is debug
logger.debug(f"Calculation / play time: {(time.perf_counter_ns() - t1_start) / 1e6:.3f} ms / {frames / self.stream.samplerate * 1000:.3f} ms")
# Playing needs to stop
if stream_needs_to_stop_now:
raise sd.CallbackStop()
@qtc.Slot(dict)
def sweep_play(self, **kwargs):
try:
target_omega = kwargs.get("target_freq", np.nan) * 2 * np.pi
alpha = kwargs.get("alpha", np.nan)
if not (np.nan in (target_omega, alpha)):
raise KeyError("Cannot define both frequency and angular acceleration.")
if all([val == np.nan for val in (target_omega, alpha)]):
raise ValueError("What do I play?? You need to define frequency or angular acceleration.")
# define acceleration or frequency. so sweep should happen now.
self.user_req_omega, self.user_req_alpha = target_omega, alpha
# the voltage is being set separetely with a signal and slot "set_sweep_level"
# If no active stream or a ugs stream ongoing
if not self.stream.active or self.play_pos:
self._create_stream()
self.stream.start()
logger.info("Sweep stream started.")
except Exception as e:
self.signal_exception.emit(str(e))
logger.critical(f"Sweep generator failed. {e}")
self.stream.close(ignore_errors=True)
@qtc.Slot(dict, dict)
def ugs_play(self, play_kwargs):
"UGS means 'user generated signal'"
try:
# Make sure stream is stopped first
self.stop_play_blocking()
self.user_gen_signal = play_kwargs["signal_object"]
self.set_ugs_play_levels(play_kwargs["requested_voltages"])
self.is_play_in_loop = play_kwargs["loop"]
self.stop_after_seconds = play_kwargs["stop_after_seconds"]
self.play_pos = 0
status_info_text = "---- Playing ----" if not play_kwargs["loop"] else "---- Playing in loop ----"
now = time.time()
status_info_text += f"\nLocal time at start: {datetime.fromtimestamp(now).strftime('%B %d, %H:%M:%S')}"
stop_after_seconds = play_kwargs.get("stop_after_seconds", 0)
if stop_after_seconds > 0:
stop_time = now + play_kwargs["stop_after_seconds"]
status_info_text += f"\nLocal time to stop: {datetime.fromtimestamp(stop_time).strftime('%B %d, %H:%M:%S')}"
for cn in range(1, self.stream.channels + 1):
channel_rms = self._ugs_play_voltages[cn]
if channel_rms > 0:
status_info_text += (
f"\n\nChannel {cn}:"
f"\nAverage output: {channel_rms:.5g} Vrms"
f"\nPeak output: {channel_rms * self.user_gen_signal.CF:.5g} V"
f"\nSystem gain: {10**(settings.system_gains[cn-1]/20):.5g}x, {settings.system_gains[cn-1]:.4g}dB"
)
else:
status_info_text += (
f"\n\nChannel {cn}:\nMuted."
)
# ---- Stop timer
if self.stop_after_seconds > 0:
self.stop_timer = BasicCountDownTimer(self.stop_after_seconds)
self.stop_timer.signal_finished.connect(self.stop_play)
self.play_stopped.connect(self.stop_timer.stop)
qtw.QApplication.instance().aboutToQuit.connect(self.stop_timer.stop)
self.stop_timer.start()
if play_kwargs["signal_object"].FS == settings.play_sample_rate:
self._create_stream()
else:
self._create_stream(force_sample_rate=play_kwargs["signal_object"].FS)
self.stream.start()
self.play_started.emit(status_info_text)
logger.debug(f"Stream started with block sizes {self.stream.blocksize}.")
except Exception as e:
self.signal_exception.emit(repr(e))
logger.error(f"Play_once failed during start. {e}")
self.stream.close(ignore_errors=True)
@qtc.Slot(str)
def stop_play(self):
if self.stream.active:
if np.isnan(self.fade_out_frames["remaining"]):
self.fade_out_frames = {"remaining": self.fade_window_size,
"total": self.fade_window_size,
"stop_after": True,
}
else:
pass
logger.debug("Stop fadeout initiated.")
else:
logger.debug("Stream was not active when stop was requested.")
def stop_play_blocking(self):
self.stop_play()
# Block until
while self.stream.active:
pass
@qtc.Slot(float)
def set_ugs_play_levels(self, voltage_dict: dict) -> None:
"""Creates a dictionary for rms voltages of user generated signal player.
The keys of dictionary are user friendly channel names, starting from 1.
"""
user_req_voltages = {}
for cn in np.arange(1, settings.channel_count + 1):
if isinstance(voltage_dict, dict) and cn in voltage_dict:
user_req_voltages[cn] = float(voltage_dict[cn])
else:
user_req_voltages[cn] = 0.
self._ugs_play_voltages = user_req_voltages
self._ugs_play_signal_rms = self.calculate_digital_signal_rms(user_req_voltages, self.user_gen_signal.CF)
logger.debug("User generated signal play levels updated in player.")
@qtc.Slot(float)
def set_sweep_level(self, voltage: float) -> None:
"""