-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
2037 lines (1676 loc) · 91.3 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) 2023 - Kerem Basaran
# https://github.com/kbasaran
__email__ = "[email protected]"
# 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.0",
# "version": "Test build " + today.strftime("%Y.%m.%d"),
"description": "Test Signal Maker - Loudspeaker test signal tool",
"copyright": "Copyright (C) 2023 Kerem Basaran",
"icon_path": str(Path("./logo/icon.ico")),
"author": "Kerem Basaran",
"author_short": "kbasaran",
"email": "[email protected]",
"website": "https://github.com/kbasaran",
}
import sys
import os
import time as pyt_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 acoustics as ac # https://github.com/timmahrt/pyAcoustics
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
from dataclasses import dataclass, fields
import logging
home_folder = os.path.expanduser("~")
logging.basicConfig(level=logging.INFO,
filename=os.path.join(home_folder, 'tsm.log'),
# encoding='utf-8',
format='%(asctime)s %(levelname)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
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"
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_index = sd.default.device[1]
preferred_device_widget.setCurrentIndex(preferred_device_index) # does this raise an error if that device name is not in the combobox?
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
sweep_sample_rate = qtw.QComboBox()
for val in [44100, 48000, 96000]:
sweep_sample_rate.addItem(str(val), val)
# check which value is stored in settings
current_val = settings.sweep_sample_rate
current_val_idx = sweep_sample_rate.findData(current_val)
if current_val_idx == -1: # if the sapmle rate is not available in current list
sweep_sample_rate.setCurrentIndex(0)
else:
sweep_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 - 50ms", 0.05)
stream_latency.addItem("User value: Very safe - 100ms", 0.1)
current_val = settings.stream_latency
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("Sweep sample rate", sweep_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_attr("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_attr("system_gains", tuple(system_gains))
settings.update_attr("amp_peak", amp_peak_capability_widget.value())
settings.update_attr("channel_count", number_of_channels_widget.value())
settings.update_attr("max_channel_count", settings.max_channel_count) # so this stays fixed, no user option to change it yet
settings.update_attr("sweep_sample_rate", sweep_sample_rate.currentData())
settings.update_attr("stream_latency", stream_latency.currentData())
self.user_changed_sys_params_signal.emit()
self.done(0)
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):
logging.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)
logging.debug("Signal imported and params published.")
except Exception as e:
# Pop-up
logging.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)
logging.debug("Imported signal has been processed and published.")
except Exception as e:
# Pop-up
logging.error(str(e))
self.exception.emit(e)
@qtc.Slot(str, dict)
def generate_ugs(self, sig_type, kwargs):
logging.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)
logging.info(f"Signal with type {sig_type} generated.")
except Exception as e:
# Pop-up
logging.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 # only logs channel 1 currently
# define the sound device based on settings and availability
self.find_right_sound_device()
# Inititate attributes
self._sweep_voltage = 0
self._sweep_channel = 0
def reset_fade_out(self):
self.fade_out_frames = {"remaining": np.nan,
"total": np.nan,
"stop_after": None,
}
def announce_callback_is_finished(self):
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.play_stopped.emit("Stopped.")
self._theta_last = np.nan
self._omega_last = np.nan
self._bring_wave_states_to_zero(self.stream.channels)
self.sweep_generated.emit(np.nan, np.nan)
self.fade_out_frames = {"remaining": np.nan, "total": np.nan}
if self.log_output_signal:
self.publish_log.emit(self.output_log)
self.output_log = {"time_sig": [],
"fade_out_window": [],
"fade_in_window": [],
}
logging.info("Audio stream stopped.")
return None
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 hasattr(self, "stream") and 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]}
"""
if hasattr(self, "stream"):
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 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 _initiate_stream(self, stream_settings):
"""Prepare the stream object with provided settings"""
self.stop_play()
# Check if anything is new - (doesn't work properly due to .latency receiving str but returning float)
new_settings = {}
running_stream = None if not hasattr(self, "stream") else self.stream
for setting, value in stream_settings.items():
if getattr(running_stream, setting, None) != value: # this returns None if there is no such key
new_settings.update({setting: value})
# Logging
if new_settings:
logging.debug(f"New stream settings: {new_settings}")
# If anything is new or there was no stream in the first place
if new_settings:
if hasattr(self, "stream"):
while self.stream.active: # maybe it is still doing callbacks, so wait a bit
pass
self.stream.close()
self._bring_wave_states_to_zero(stream_settings["channels"])
self.stream = sd.OutputStream(callback=self.callback,
device=self.play_device_idx,
finished_callback=self.announce_callback_is_finished,
**stream_settings,
)
self.fade_window_size = int(self.stream.samplerate // 10)
self.ugs_play_elapsed_time = -1.
def _bring_wave_states_to_zero(self, channel_count):
self._omega_last = 0.
self._theta_last = 0.
self._sweep_level_last = {channel: 0. for channel in range(1, channel_count + 1)}
@qtc.Slot()
def is_active(self):
return hasattr(self, "stream") and self.stream.active
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 ------------------
do_callback_stop = 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:
logging.debug("---Fill cycle---")
logging.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,
}
logging.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"]):
do_callback_stop = True
# Apply fade-out
if self.fade_out_frames["remaining"] > 0:
fade_start_end_idx = (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_idx,
)
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_idx = (-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_idx,
)
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 = [None] * 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:
logging.debug(f"User generated signal play levels: {ugs_play_rms_levels:.4f}")
if self.ugs_play_elapsed_time == -1.:
self.log_through_thread.emit(f"Started with: {self._ugs_play_voltages}Vrms")
self.ugs_play_elapsed_time += self.stream.latency
if self.ugs_play_elapsed_time > 60 * 60 * 6: # 6 is a correction factor. latency value from sound card is incorrect
self.log_through_thread.emit(f"Ongoing with: {self._ugs_play_voltages}Vrms")
self.ugs_play_elapsed_time = 0.
return mono_signal_chunk, initial_rms, ugs_play_rms_levels, do_callback_stop
except Exception as e:
logging.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 --------------------
do_callback_stop = 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):
logging.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:
logging.debug("Callback case zero output")
# Otherwise it clicks.
mono_signal_chunk = np.zeros(frames)
# Linear sweep is necessary
else:
logging.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_wave_states_to_zero(self.stream.channels)
# set the signals to rms = 1 and also do the smooth crossing between voltages
logging.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_channel],
self._sweep_signal_rms[self._sweep_channel],
frames,
)
self._sweep_level_last[self._sweep_channel] = self._sweep_signal_rms[self._sweep_channel]
# If this was the last fade-out callback and calling back needs to stop
if self.fade_out_frames["remaining"] <= frames:
do_callback_stop = True
# Apply fade-out
if not np.isnan(self.fade_out_frames["remaining"]):
fade_start_end_idx = (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_idx,
)
mono_signal_chunk = mono_signal_chunk * fade_out_window
logging.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)
logging.debug(f"_sweep_channel, _sweep_signal_rms: {self._sweep_channel}, {self._sweep_signal_rms}")
target_rms_levels[self._sweep_channel - 1] = 1
logging.debug(f"Sweep levels: {target_rms_levels}")
# Tell Main window which frequency you are at
if self._sweep_signal_rms[self._sweep_channel] == 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, do_callback_stop
except Exception as e:
logging.critical(
f"Failed to add {frames} frames during sweep generator callback. Error: {repr(e)}")
raise sd.CallbackAbort
def callback(self, indata, frames, time, status):
"""
Callback function for sounddevice player.
Initiated wheneversound device runs out of buffer.
Avoid placing memory allocation or i/o tasks in here.
"""
logging.debug("")
logging.debug(f"----Callback for DAC time: {time.outputBufferDacTime}----")
t1_start = pyt_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}"
logging.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)
logging.debug("Nothing to play for the callback. Put in zeros.")
elif self.play_pos is not None:
mono_signal_chunk, initial_rms, target_rms_levels, do_callback_stop = self.callback_for_ugs(frames)
elif (not np.isnan(self.user_req_alpha)) or (not np.isnan(self.user_req_omega)):
mono_signal_chunk, initial_rms, target_rms_levels, do_callback_stop = 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 voltage
# log the output signal
if self.log_output_signal:
logging.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:]
logging.debug(f"Callback current / buffer DAC time: {time.currentTime} / {time.outputBufferDacTime}")
logging.debug(f"Calculation / play time: {(pyt_time.perf_counter_ns() - t1_start) / 1e6:.3f} ms / {frames / self.stream.samplerate * 1000:.3f} ms")
# Playing needs to stop
if do_callback_stop:
raise sd.CallbackStop
@qtc.Slot(dict)
def generate_sweep(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 there is no sweep stream ongoing currently
if (not hasattr(self, "stream")) or (not self.stream.active) or self.play_pos:
stream_settings = {"samplerate": settings.sweep_sample_rate,
"channels": settings.channel_count,
"latency": settings.stream_latency,
}
self._initiate_stream(stream_settings)
logging.info("Sweep stream started.")
self.stream.start()
except Exception as e:
self.signal_exception.emit(str(e))
logging.critical(f"Sweep generator failed. {e}")
self.stream.close(ignore_errors=True)
@qtc.Slot(dict, dict)
def ugs_play(self, stream_settings, play_kwargs):
"UGS means 'user generated signal'"
try:
if hasattr(self, "stream"):
# Already doing a usg play
self.stop_play()
while self.stream.active:
pass
self._initiate_stream(stream_settings)
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.play_pos = 0
status_info_text = "---- Playing ----" if not play_kwargs["loop"] else "---- Playing in loop ----"
now = datetime.now()
status_info_text += f"\nLocal time at start: {now.strftime('%B %d, %H:%M:%S')}"
for cn in range(1, stream_settings["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."
)
self.stream.start()
self.play_started.emit(status_info_text)
logging.debug(f"Stream started with block sizes {self.stream.blocksize}.")
except Exception as e:
self.signal_exception.emit(repr(e))
logging.error(f"Play_once failed during start. {e}")
self.stream.close(ignore_errors=True)
@qtc.Slot()
def stop_play(self):
# This is a blocking function due to the while loop below
if hasattr(self, "stream") and 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
logging.debug("Stop fadeout initiated.")
else:
self.play_stopped.emit("Stopped.")
logging.debug("Stream was not active when stop was requested.")
@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)
logging.debug("User generated signal play levels updated in player.")
@qtc.Slot(float)
def set_sweep_level(self, voltage: float) -> None:
"""
Receive requested voltage output and set the correct gain in a dictionary attribute.
"""
rms_required = self.calculate_digital_signal_rms({self._sweep_channel: voltage}, np.exp2(0.5))[self._sweep_channel]
self._sweep_voltage = float(voltage)
if not hasattr(self, "_sweep_signal_rms"):
self._sweep_signal_rms = {}
self._sweep_signal_rms[self._sweep_channel] = rms_required
logging.debug("Sweep level updated in player.")
# not handling exceptions within this function. risky.