-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_measure.py
More file actions
1436 lines (1194 loc) · 43.6 KB
/
Copy pathtest_measure.py
File metadata and controls
1436 lines (1194 loc) · 43.6 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
from __future__ import annotations
import builtins
import csv
import json
import sys
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pytest
import soundfile as sf
from hypothesis import given
from hypothesis import strategies as st
from matchpatch.devices import get_device_profile
from matchpatch.devices.base import (
AudioProcessingMode,
AudioRouting,
AudioTransportCapabilities,
AudioTransportContext,
DeviceProfile,
MeasurementBackendCapabilities,
OfflineAudioProcessingRequest,
PatchFileHandler,
SteeringOptions,
)
from matchpatch.measure import (
HardwareBackend,
LoopbackBackend,
SimulatedHardwareBackend,
check_hardware,
collect_hardware_diagnostics,
collect_hardware_preflight,
csv_fields,
list_devices,
load_reference_audio,
main,
measure,
measure_presets,
optimize_measurement_timing,
parse_args,
parse_channel_mapping,
parse_int_list,
parse_snapshot_plan,
resolve_audio_config,
resolve_steering_options,
)
from matchpatch.measurement_optimizer import TIMING_PARAMETERS, ParameterOptimizationResult
def test_loopback_backend_writes_compatible_csv(tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
csv_path = tmp_path / "lufs_analysis.csv"
measure_presets(
get_device_profile("helix"),
[1, 6],
csv_path,
reference,
sample_rate,
LoopbackBackend(),
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
rows = list(csv.DictReader(csv_file))
assert [row["DevicePatch"] for row in rows] == ["01A", "02B"]
assert rows[0]["LUFS1"] == rows[0]["LUFS4"]
assert rows[0]["CrestFactor1"] == rows[0]["CrestFactor4"]
def test_measure_presets_emits_structured_progress(tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
events = []
measure_presets(
get_device_profile("helix"),
[1],
tmp_path / "events.csv",
reference,
sample_rate,
LoopbackBackend(),
snapshot_count=2,
on_progress=events.append,
log_output=False,
)
assert [event.kind for event in events] == [
"measurement_preparation",
"reference_loudness",
"preset_started",
"snapshot_started",
"snapshot_completed",
"snapshot_started",
"snapshot_completed",
"preset_completed",
"measurement_completed",
]
assert events[0].message == "Analyzing reference DI loudness..."
assert events[1].reference_lufs is not None
assert events[2].device_patch == "01A"
assert events[4].snapshot == 1
assert events[4].reference_lufs == events[1].reference_lufs
assert events[4].lufs is not None
def test_measure_presets_can_save_and_play_recorded_snapshots(monkeypatch, tmp_path) -> None:
sample_rate = 48000
reference = np.ones((sample_rate * 4, 2), dtype=np.float32) * 0.1
played = []
events = []
monkeypatch.setattr(
"matchpatch.measure._play_audio", lambda audio, rate: played.append((audio, rate))
)
measure_presets(
get_device_profile("helix"),
[1],
tmp_path / "recorded.csv",
reference,
sample_rate,
LoopbackBackend(),
snapshot_count=1,
on_progress=events.append,
log_output=False,
play_recorded_output=True,
recorded_output_dir=tmp_path / "recordings",
)
recorded_path = tmp_path / "recordings" / "01A_snapshot_1.wav"
assert recorded_path.is_file()
assert [event.kind for event in events if event.kind == "snapshot_recorded"] == [
"snapshot_recorded"
]
assert events[4].path == str(recorded_path)
assert len(played) == 1
assert played[0][0] == pytest.approx(reference)
assert played[0][1] == sample_rate
class FakePatchFileHandler(PatchFileHandler):
def validate_input(self, input_path: Path) -> None:
return None
def validate_output(self, input_path: Path, output_path: Path) -> None:
return None
def list_assignments(self, input_path: Path) -> list:
return []
def parse_patch_set(self, value: str) -> list[int]:
return []
def select_preset_ids(
self, input_path: Path, assignments: list, requested_ids: list[int] | None
) -> list[int]:
return []
def format_patch_id(self, preset_id: int) -> str:
return f"patch-{preset_id}"
def create_measurement_file(self, input_path: Path, output_path: Path) -> None:
return None
def apply_analysis_csv(
self,
input_path: Path,
output_path: Path,
csv_path: Path,
ignore_bad_lufs: bool,
target_lufs: float,
) -> None:
return None
def automation_output_path(self, input_path: Path, postfix: str) -> Path:
return input_path
class FakeDeviceProfile(DeviceProfile):
name = "fake"
display_name = "Fake Processor"
def create_patch_file_handler(self, project_dir: Path) -> PatchFileHandler:
return FakePatchFileHandler()
def default_audio_routing(self) -> AudioRouting:
raise AssertionError("Loopback must not resolve USB routing")
def default_steering_options(self) -> SteeringOptions:
raise AssertionError("Loopback must not resolve steering")
def create_controller(self, options: SteeringOptions):
raise AssertionError("Loopback must not create a controller")
class RecordingTransport:
def __init__(self) -> None:
self.calls: list[tuple[str, int] | tuple[str, tuple[int, ...]] | tuple[str]] = []
def __enter__(self):
self.calls.append(("enter",))
return self
def __exit__(self, *args) -> None:
self.calls.append(("exit",))
def activate_target(self, target: int) -> None:
self.calls.append(("target", target))
def activate_subdivision(self, subdivision: int) -> None:
self.calls.append(("subdivision", subdivision))
def process(self, reference_audio: np.ndarray) -> np.ndarray:
self.calls.append(("process", reference_audio.shape))
return reference_audio.copy()
class RecordingTransportFactory:
capabilities = AudioTransportCapabilities(mode="loopback")
def __init__(self) -> None:
self.transport = RecordingTransport()
self.contexts: list[AudioTransportContext] = []
def supports(self, mode: AudioProcessingMode, settings) -> bool:
return mode == "loopback" and settings["sample_rate"] == 48000
def create(self, context: AudioTransportContext) -> RecordingTransport:
self.contexts.append(context)
return self.transport
class OfflineRecordingTransport:
def __init__(self) -> None:
self.calls: list[tuple[str, int] | tuple[str, tuple[int, ...]] | tuple[str]] = []
self.requests: list[OfflineAudioProcessingRequest] = []
def __enter__(self):
self.calls.append(("enter",))
return self
def __exit__(self, *args) -> None:
self.calls.append(("exit",))
def activate_target(self, target: int) -> None:
self.calls.append(("target", target))
def activate_subdivision(self, subdivision: int) -> None:
self.calls.append(("subdivision", subdivision))
def process_offline(self, request: OfflineAudioProcessingRequest) -> np.ndarray:
self.calls.append(("offline", request.reference_audio.shape))
self.requests.append(request)
return request.reference_audio * 0.5
class OfflineRecordingTransportFactory:
capabilities = AudioTransportCapabilities(mode="offline", real_time=False, offline=True)
def __init__(self) -> None:
self.transport = OfflineRecordingTransport()
self.contexts: list[AudioTransportContext] = []
def supports(self, mode: AudioProcessingMode, settings) -> bool:
return mode == "offline" and settings["sample_rate"] == 48000
def create(self, context: AudioTransportContext) -> OfflineRecordingTransport:
self.contexts.append(context)
return self.transport
class TransportDeviceProfile(DeviceProfile):
name = "transport"
display_name = "Transport Processor"
snapshot_count = 1
def __init__(self, factory: RecordingTransportFactory) -> None:
self.factory = factory
def create_patch_file_handler(self, project_dir: Path) -> PatchFileHandler:
return FakePatchFileHandler()
def measurement_backends(self) -> tuple[str, ...]:
return MeasurementBackendCapabilities(hardware=False, simulated=False).names()
def audio_transport_factories(self):
return (self.factory,)
def default_audio_routing(self) -> AudioRouting:
return AudioRouting(None, 48000, (1, 2), (1, 2))
def default_steering_options(self) -> SteeringOptions:
return SteeringOptions(None, 1, 0.0, 0.0, 0.0)
def create_controller(self, options: SteeringOptions):
raise AssertionError("Custom loopback transport must not create a controller")
class OfflineTransportDeviceProfile(TransportDeviceProfile):
name = "offline-transport"
display_name = "Offline Transport Processor"
def __init__(self, factory: OfflineRecordingTransportFactory) -> None:
self.factory = factory
def measurement_backends(self) -> tuple[str, ...]:
return MeasurementBackendCapabilities(
hardware=False,
loopback=False,
simulated=False,
offline=True,
).names()
def audio_transport_factories(self):
return (self.factory,)
def test_loopback_is_device_independent(tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
csv_path = tmp_path / "generic.csv"
measure_presets(
FakeDeviceProfile(),
[7],
csv_path,
reference,
sample_rate,
LoopbackBackend(),
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
row = next(csv.DictReader(csv_file))
assert row["DevicePatch"] == "patch-7"
assert "HelixPreset" not in row
def test_simulated_backend_tracks_state_and_modifies_audio() -> None:
routing = AudioRouting("processor", 48000, (1, 2), (3, 4))
backend = SimulatedHardwareBackend(routing, snapshot_count=4)
reference = np.array([[0.1, -0.2], [0.3, -0.4]])
backend.activate_preset(1)
backend.reapply_snapshot(1)
first = backend.record(reference)
backend.reapply_snapshot(2)
second = backend.record(reference)
assert backend.steering_events == [
("preset", 1),
("snapshot", 1),
("snapshot", 2),
]
assert first == pytest.approx(reference * 10.0 ** (-4.0 / 20.0))
assert second == pytest.approx(np.tanh(reference * 10.0 ** (-3.0 / 20.0) * 2.0) / 2.0)
@pytest.mark.parametrize(
("input_mapping", "output_mapping", "message"),
[
((7, 8), None, "input mapping"),
(None, (7, 8), "output mapping"),
],
)
def test_simulated_backend_validates_routing(input_mapping, output_mapping, message) -> None:
routing = AudioRouting("processor", 48000, (1, 2), (3, 4))
with pytest.raises(ValueError, match=message):
SimulatedHardwareBackend(routing, 4, input_mapping, output_mapping)
def test_simulated_backend_validates_state_and_injected_failures() -> None:
backend = SimulatedHardwareBackend(
AudioRouting("processor", 48000, (1, 2), (3, 4)),
snapshot_count=1,
failing_preset_ids=frozenset({6}),
)
reference = np.ones((2, 2))
with pytest.raises(RuntimeError, match="must be active"):
backend.record(reference)
with pytest.raises(RuntimeError, match="preset is not active"):
backend.reapply_snapshot(1)
with pytest.raises(ValueError, match="preset ID"):
backend.activate_preset(0)
with pytest.raises(RuntimeError, match="failure"):
backend.activate_preset(6)
backend.activate_preset(1)
with pytest.raises(RuntimeError, match="must be active"):
backend.record(reference)
with pytest.raises(ValueError, match="snapshot"):
backend.reapply_snapshot(0)
with pytest.raises(ValueError, match="snapshot"):
backend.reapply_snapshot(2)
backend.reapply_snapshot(1)
assert backend.steering_events == [("preset", 1), ("snapshot", 1)]
def test_parse_worker_lists_and_channels() -> None:
assert parse_int_list("1, 2,,3") == [1, 2, 3]
assert parse_channel_mapping("3,4") == (3, 4)
assert csv_fields(2) == [
"Preset",
"DevicePatch",
"LUFS1",
"LUFS2",
"CrestFactor1",
"CrestFactor2",
]
for invalid in ("1", "0,2", "1,2,3"):
with pytest.raises(Exception, match="two positive"):
parse_channel_mapping(invalid)
@given(
first=st.integers(min_value=1, max_value=128),
second=st.integers(min_value=1, max_value=128),
)
def test_channel_mapping_round_trips_positive_channel_ids(first: int, second: int) -> None:
assert parse_channel_mapping(f" {first}, {second} ") == (first, second)
@given(
first=st.integers(min_value=-128, max_value=0),
second=st.integers(min_value=-128, max_value=0),
)
def test_channel_mapping_rejects_non_positive_channel_ids(first: int, second: int) -> None:
with pytest.raises(Exception, match="two positive"):
parse_channel_mapping(f"{first},{second}")
def test_load_reference_audio_repeats_mono_and_trims_extra_channels(tmp_path) -> None:
mono_path = tmp_path / "mono.wav"
stereo_path = tmp_path / "stereo.wav"
wide_path = tmp_path / "wide.wav"
sf.write(mono_path, np.ones((20, 1)), 48000)
sf.write(stereo_path, np.ones((20, 2)), 48000)
sf.write(wide_path, np.ones((20, 3)), 48000)
assert load_reference_audio(mono_path, 48000).shape == (20, 2)
assert load_reference_audio(stereo_path, 48000).shape == (20, 2)
assert load_reference_audio(wide_path, 48000).shape == (20, 2)
with pytest.raises(ValueError, match="sample rate"):
load_reference_audio(mono_path, 44100)
class FailingBackend(LoopbackBackend):
def activate_preset(self, preset_id: int) -> None:
raise RuntimeError("processor unavailable")
class PartlySilentBackend(LoopbackBackend):
def __init__(self) -> None:
self.snapshot = 0
def reapply_snapshot(self, snapshot: int) -> None:
self.snapshot = snapshot
def record(self, reference: np.ndarray) -> np.ndarray:
if self.snapshot == 2:
return np.zeros_like(reference)
return reference
class RecordingBackend(LoopbackBackend):
def __init__(self) -> None:
self.snapshots: list[int] = []
def reapply_snapshot(self, snapshot: int) -> None:
self.snapshots.append(snapshot)
def test_measure_presets_writes_error_row_when_backend_fails(tmp_path) -> None:
csv_path = tmp_path / "errors.csv"
measure_presets(
get_device_profile("helix"),
[1],
csv_path,
np.ones((400, 2)),
100,
FailingBackend(),
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
row = next(csv.DictReader(csv_file))
assert row["DevicePatch"] == "01A"
assert row["LUFS1"] == "ERROR"
assert row["CrestFactor4"] == "ERROR"
def test_measure_presets_retains_good_snapshots_when_one_snapshot_fails(tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
events = []
csv_path = tmp_path / "partial.csv"
measure_presets(
get_device_profile("helix"),
[1],
csv_path,
reference,
sample_rate,
PartlySilentBackend(),
snapshot_count=2,
on_progress=events.append,
log_output=False,
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
row = next(csv.DictReader(csv_file))
assert row["DevicePatch"] == "01A"
assert row["LUFS1"] != "ERROR"
assert row["CrestFactor1"] != "ERROR"
assert row["LUFS2"] == "ERROR"
assert row["CrestFactor2"] == "ERROR"
assert [event.kind for event in events if event.kind.startswith("snapshot_")] == [
"snapshot_started",
"snapshot_completed",
"snapshot_started",
"snapshot_failed",
]
def test_measure_presets_skips_snapshots_outside_plan(tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
backend = RecordingBackend()
events = []
csv_path = tmp_path / "planned.csv"
measure_presets(
get_device_profile("helix"),
[1],
csv_path,
reference,
sample_rate,
backend,
snapshot_count=3,
on_progress=events.append,
log_output=False,
snapshot_plan={"01A": (1, 3)},
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
row = next(csv.DictReader(csv_file))
assert backend.snapshots == [1, 3]
assert row["LUFS1"] != ""
assert row["CrestFactor1"] != ""
assert row["LUFS2"] == "SKIP"
assert row["CrestFactor2"] == "SKIP"
assert row["LUFS3"] != ""
assert row["CrestFactor3"] != ""
assert [event.snapshot for event in events if event.kind == "snapshot_started"] == [1, 3]
def test_parse_snapshot_plan_normalizes_patch_ids() -> None:
assert parse_snapshot_plan("01a=1,3;02B=2") == {"01A": (1, 3), "02B": (2,)}
def test_hardware_backend_delegates_and_waits(monkeypatch) -> None:
events = []
controller = SimpleNamespace(
activate_preset=lambda preset: events.append(("preset", preset)),
reapply_snapshot=lambda snapshot: events.append(("snapshot", snapshot)),
)
audio = SimpleNamespace(
record_processed_audio=lambda reference, config: (
events.append(("record", reference, config)) or reference
)
)
monkeypatch.setitem(sys.modules, "matchpatch.audio", audio)
monkeypatch.setattr(
"matchpatch.measure.time.sleep", lambda delay: events.append(("sleep", delay))
)
backend = HardwareBackend("config", controller, 0.25)
reference = np.ones((4, 2))
backend.activate_preset(6)
backend.reapply_snapshot(2)
assert backend.record(reference) is reference
assert events == [
("preset", 6),
("snapshot", 2),
("sleep", 0.25),
("record", reference, "config"),
]
def test_resolve_steering_options_uses_defaults_and_overrides() -> None:
args = SimpleNamespace(
steering_output=None,
steering_channel=4,
preset_wait=None,
snapshot_wait=0.2,
measurement_wait=None,
)
options = resolve_steering_options(args, get_device_profile("helix"))
assert options.output == "Helix"
assert options.channel == 4
assert options.preset_wait_seconds == 0.5
assert options.snapshot_wait_seconds == 0.2
assert options.measurement_wait_seconds == 0.1
def test_resolve_audio_config_uses_defaults_and_overrides(monkeypatch) -> None:
class AudioConfig:
def __init__(self, **kwargs) -> None:
self.__dict__.update(kwargs)
monkeypatch.setitem(sys.modules, "matchpatch.audio", SimpleNamespace(AudioConfig=AudioConfig))
args = SimpleNamespace(
audio_device=None,
sample_rate=44100,
input_mapping=None,
output_mapping=(7, 8),
blocksize=128,
)
config = resolve_audio_config(args, get_device_profile("helix"))
assert config.device == "Helix"
assert config.sample_rate == 44100
assert config.input_mapping == (1, 2)
assert config.output_mapping == (7, 8)
assert config.blocksize == 128
assert config.pre_roll_seconds == 0.2
assert config.post_roll_seconds == 0.1
assert config.round_trip_latency_seconds == 0.02
def worker_args(**overrides):
values = {
"device": "helix",
"backend": "loopback",
"preset_ids": [1],
"csv": "results.csv",
"reference_di": "reference.wav",
"audio_device": None,
"steering_output": None,
"steering_channel": None,
"sample_rate": None,
"input_mapping": None,
"output_mapping": None,
"blocksize": 0,
"preset_wait": None,
"snapshot_wait": None,
"measurement_wait": None,
"pre_roll": 0.2,
"post_roll": 0.1,
"round_trip_latency": 0.02,
"simulate_fail_presets": [],
"snapshot_plan": None,
}
values.update(overrides)
return SimpleNamespace(**values)
def test_measure_dispatches_loopback_without_audio_module(monkeypatch) -> None:
calls = []
monkeypatch.setattr("matchpatch.measure.load_reference_audio", lambda path, rate: "reference")
monkeypatch.setattr(
"matchpatch.measure.measure_presets", lambda *args, **kwargs: calls.append(args)
)
measure(worker_args())
assert isinstance(calls[0][-1].transport.backend, LoopbackBackend)
assert calls[0][4] == 48000
def test_measure_dispatches_stateful_simulator_without_audio_module(monkeypatch) -> None:
calls = []
monkeypatch.setattr("matchpatch.measure.load_reference_audio", lambda path, rate: "reference")
monkeypatch.setattr(
"matchpatch.measure.measure_presets", lambda *args, **kwargs: calls.append(args)
)
measure(
worker_args(
backend="simulated",
input_mapping=(1, 2),
output_mapping=(3, 4),
simulate_fail_presets=[6],
)
)
backend = calls[0][-1]
assert isinstance(backend.transport.backend, SimulatedHardwareBackend)
assert backend.transport.backend.failing_preset_ids == frozenset({6})
def test_measure_configures_hardware_backend(monkeypatch) -> None:
calls = []
events = []
controller = SimpleNamespace(__enter__=lambda self: self, __exit__=lambda *args: None)
class ContextController:
def __enter__(self):
return controller
def __exit__(self, *args):
return None
profile = get_device_profile("helix")
monkeypatch.setattr("matchpatch.measure.get_device_profile", lambda device: profile)
monkeypatch.setattr("matchpatch.measure.load_reference_audio", lambda path, rate: "reference")
monkeypatch.setattr(
"matchpatch.measure.measure_presets", lambda *args, **kwargs: calls.append(args)
)
monkeypatch.setattr(profile, "create_controller", lambda options: ContextController())
monkeypatch.setitem(
sys.modules,
"matchpatch.audio",
SimpleNamespace(
AudioConfig=lambda **kwargs: SimpleNamespace(**kwargs),
prepare_audio_config=lambda config: calls.append(("prepared", config.device)) or config,
),
)
measure(
worker_args(
backend="hardware",
audio_device="processor",
sample_rate=44100,
on_progress=events.append,
)
)
assert calls[0] == ("prepared", "processor")
assert isinstance(calls[1][-1].transport.backend, HardwareBackend)
assert [event.message for event in events] == [
"Loading reference DI audio...",
"Resolving and validating audio device...",
"Opening processor MIDI output...",
]
def test_measure_uses_profile_audio_transport_factory(monkeypatch, tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
factory = RecordingTransportFactory()
profile = TransportDeviceProfile(factory)
csv_path = tmp_path / "transport.csv"
monkeypatch.setattr("matchpatch.measure.get_device_profile", lambda device: profile)
monkeypatch.setattr("matchpatch.measure.load_reference_audio", lambda path, rate: reference)
measure(
worker_args(
device="transport",
backend="loopback",
csv=str(csv_path),
reference_di="reference.wav",
)
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
row = next(csv.DictReader(csv_file))
assert row["DevicePatch"] == "patch-1"
assert factory.contexts[0].mode == "loopback"
assert factory.transport.calls == [
("enter",),
("target", 1),
("subdivision", 1),
("process", reference.shape),
("exit",),
]
def test_measure_uses_profile_offline_audio_transport_factory(monkeypatch, tmp_path) -> None:
sample_rate = 48000
times = np.arange(sample_rate * 4) / sample_rate
reference = np.sin(2 * np.pi * 1000 * times)[:, np.newaxis]
factory = OfflineRecordingTransportFactory()
profile = OfflineTransportDeviceProfile(factory)
csv_path = tmp_path / "offline.csv"
monkeypatch.setattr("matchpatch.measure.get_device_profile", lambda device: profile)
monkeypatch.setattr("matchpatch.measure.load_reference_audio", lambda path, rate: reference)
measure(
worker_args(
device="offline-transport",
backend="offline",
csv=str(csv_path),
reference_di="reference.wav",
)
)
with csv_path.open(newline="", encoding="utf-8") as csv_file:
row = next(csv.DictReader(csv_file))
request = factory.transport.requests[0]
assert row["DevicePatch"] == "patch-1"
assert factory.contexts[0].mode == "offline"
assert request.sample_rate == sample_rate
assert request.target_id == 1
assert request.subdivision_id == 1
assert request.target_metadata == {"preset_id": 1}
assert request.subdivision_metadata == {"snapshot": 1}
assert factory.transport.calls == [
("enter",),
("target", 1),
("subdivision", 1),
("offline", reference.shape),
("exit",),
]
def test_check_hardware_validates_audio_and_midi_presence(monkeypatch) -> None:
calls = []
profile = get_device_profile("helix")
monkeypatch.setattr("matchpatch.measure.get_device_profile", lambda device: profile)
monkeypatch.setitem(
sys.modules,
"matchpatch.audio",
SimpleNamespace(
AudioConfig=lambda **kwargs: SimpleNamespace(**kwargs),
validate_audio_device_available=lambda config: (
calls.append(("validated", config.device)) or config
),
),
)
monkeypatch.setitem(
sys.modules,
"mido",
SimpleNamespace(get_output_names=lambda: calls.append("midi_listed") or ["Helix MIDI"]),
)
check_hardware(worker_args(backend="hardware", audio_device="processor"))
assert calls == [("validated", "processor"), "midi_listed"]
def test_check_hardware_reports_missing_midi_backend(monkeypatch) -> None:
profile = get_device_profile("helix")
monkeypatch.setattr("matchpatch.measure.get_device_profile", lambda device: profile)
monkeypatch.setitem(
sys.modules,
"matchpatch.audio",
SimpleNamespace(
AudioConfig=lambda **kwargs: SimpleNamespace(**kwargs),
validate_audio_device_available=lambda config: config,
),
)
monkeypatch.setitem(
sys.modules,
"mido",
SimpleNamespace(
get_output_names=lambda: (_ for _ in ()).throw(
ModuleNotFoundError(
"No module named 'mido.backends.rtmidi'",
name="mido.backends.rtmidi",
)
)
),
)
with pytest.raises(ValueError, match="MIDI output backend is unavailable") as exc:
check_hardware(worker_args(backend="hardware", audio_device="processor"))
assert "mido.backends.rtmidi" not in str(exc.value)
def fake_sounddevice():
apis = [{"name": "ASIO"}]
devices = [
{
"name": "Processor",
"hostapi": 0,
"max_input_channels": 2,
"max_output_channels": 4,
}
]
return SimpleNamespace(
query_hostapis=lambda index=None: apis if index is None else apis[index],
query_devices=lambda: devices,
)
def test_optimize_measurement_timing_pins_parameters(monkeypatch, capsys) -> None:
calls = []
monkeypatch.setattr("matchpatch.measure.load_reference_audio", lambda path, rate: "reference")
def fake_optimize(*args, **kwargs):
calls.append(kwargs["parameters"])
parameter = next(item for item in TIMING_PARAMETERS if item.name == "measurement_wait")
return (ParameterOptimizationResult(parameter, 0.08, True, 2),)
monkeypatch.setattr("matchpatch.measure.optimize_timing_parameters", fake_optimize)
optimize_measurement_timing(
SimpleNamespace(
device="helix",
backend="loopback",
preset_id=1,
alternate_preset_id=None,
reference_di="reference.wav",
sample_rate=None,
input_mapping=None,
output_mapping=None,
simulate_fail_presets=[],
stability_runs=3,
termination_tolerance=10.0,
stability_tolerance=2.0,
pinned_parameter=["pre_roll", "preset_wait"],
pre_roll=0.3,
post_roll=0.1,
round_trip_latency=0.02,
preset_wait=0.6,
snapshot_wait=0.2,
measurement_wait=0.1,
analysis_options=SimpleNamespace(
window_seconds=3.0,
interval_seconds=0.1,
minimum_valid_lufs=-100.0,
),
)
)
output = capsys.readouterr().out
optimized_names = {parameter.name for parameter in calls[0]}
assert "pre_roll" not in optimized_names
assert "preset_wait" not in optimized_names
assert "pre_roll_seconds = 0.3" in output
assert "preset_wait_seconds = 0.6" in output
assert "measurement_wait_seconds = 0.08" in output
def test_list_devices_prints_audio_and_midi(monkeypatch, capsys) -> None:
monkeypatch.setitem(sys.modules, "matchpatch.audio", SimpleNamespace(sd=fake_sounddevice()))
monkeypatch.setitem(
sys.modules, "mido", SimpleNamespace(get_output_names=lambda: ["Processor MIDI"])
)
list_devices()
output = capsys.readouterr().out
assert "helix: Line 6 Helix" in output
assert "[0] Processor | ASIO | in=2 out=4" in output
assert "Processor MIDI" in output
def test_list_devices_reports_missing_mido(monkeypatch, capsys) -> None:
original_import = builtins.__import__
def fail_mido(name, *args, **kwargs):
if name == "mido":
raise ImportError("missing")
return original_import(name, *args, **kwargs)
monkeypatch.setitem(sys.modules, "matchpatch.audio", SimpleNamespace(sd=fake_sounddevice()))
monkeypatch.delitem(sys.modules, "mido", raising=False)
monkeypatch.setattr(builtins, "__import__", fail_mido)
list_devices()
assert "unavailable: MIDI output backend is unavailable" in capsys.readouterr().out
def test_worker_parse_args_supports_hardware_aliases(monkeypatch) -> None:
monkeypatch.setattr(
sys,
"argv",
[
"measure",
"measure",
"--device",
"helix",
"--preset-ids",
"1,6",
"--csv",
"results.csv",
"--reference-di",
"reference.wav",
"--midi-output",
"port",