-
Notifications
You must be signed in to change notification settings - Fork 332
/
Copy pathrnbo.py
1591 lines (1377 loc) · 56.4 KB
/
rnbo.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
"""
FAUST Architecture File
Copyright (C) 2023-2025 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
"""
"""
Take the DSP name, the DSP compiled as codebox file and its associated JSON file, possibly the effect
compiled as codebox file and its associated JSON file, and the maxpat output file name.
Addionally, the C++ export path and filename can be specified, and the C++ code
will be exported and compiled if 'compile' is True.
The 'test' option allows to generate a patch with the 'RB_xx' prefixed labels for the parameters,
to be used with the C++ RNBO test application with the rnbo_dsp class.
The 'subpatcher' option allows to generate sub-patch as foo.rnbopat files.
Parsing the JSON file gives:
- the list of parameters (button, checkbox, sliders, nentry) to be added as "set param" objects
- the number of audio inputs/outputs to be added in the subpatch
- the MIDI state to be used in the patch
- the nvoices count to be used in the patch
The maxpat file is generated with the following structure:
- rnbo~ object for DSP
- subpatch
- codebox~ object
- input boxes
- output boxes
- parameter boxes possibly with MIDI control
- lines between boxes
- the subpatch can be generated as flat or as a foo.rnbopat file then loaded as a 'p' subpatcher
- the polyphony control is added if the MIDI state is True and the nvoices count is > 0. Effect is added as a 'p' subpatcher.
- possibly loadbang box and 'compile C++ and export' machinery
- possibly midiin/midiout objects
- dac~ object and possibly adc~ object (if the DSP has inputs)
"""
from py2max.py2max import *
import argparse
import json
import logging
import re
from typing import Dict, List, Tuple, Optional
def get_midi_and_nvoices(json_data: dict) -> Tuple[bool, int]:
"""
Extracts the MIDI state and nvoices count from the given JSON data.
Args:
json_data (dict): The JSON data in dictionary format.
Returns:
Tuple[bool, int]: A tuple containing the MIDI state (True or False) and nvoices count (int).
If the MIDI state or nvoices count is not present in the JSON, the corresponding
value in the tuple will be None.
"""
# Initialize variables to store the MIDI state and nvoices count
midi_state = None
nvoices = None
# Extract the global meta section which is always present
global_meta = json_data["meta"]
for meta_item in global_meta:
# Check for options
if "options" in meta_item:
options = meta_item["options"]
# Extract MIDI state from options
midi_state = "[midi:on]" in options
# Extract nvoices count from options
nvoices_match = re.search(r"\[nvoices:(\d+)\]", options)
if nvoices_match:
nvoices = int(nvoices_match.group(1))
break
return midi_state, nvoices
def extract_items_info(json_data: dict) -> List[dict]:
"""
Extracts information about UI items from the given DSP JSON data.
Args:
json_data (dict): DSP JSON data.
Returns:
List[dict]: A list of dictionaries containing information about each UI item.
"""
def extract_from_ui(ui_items: List) -> List[dict]:
"""
Recursive helper function to extract UI items information.
Args:
ui_items (List): List of UI items.
Returns:
List: A list of dictionaries containing information about each UI item.
"""
info_list = []
for item in ui_items:
shortname = item.get("shortname", "")
item_type = item.get("type", "")
# get MIDI information
midi_info = []
for meta_item in item.get("meta", []):
if "midi" in meta_item:
midi_info.extend(meta_item["midi"].split())
# button and checkbox
if item_type in ["button", "checkbox"]:
info_list.append(
{
"shortname": shortname,
"type": item_type,
"init": 0,
"min": 0,
"max": 1,
"step": 1,
"midi": midi_info, # Include MIDI information as a list
}
)
# bargraph with "min", "max"
elif item_type in ["vbargraph", "hbargraph"]:
info_list.append(
{
"shortname": shortname,
"type": item_type,
"min": item["min"],
"max": item["max"],
"midi": midi_info, # Include MIDI information as a list
}
)
# slider and nentry, and has "min", "max", and "step"
elif all(key in item for key in ["min", "max", "step"]):
info_list.append(
{
"shortname": shortname,
"type": item_type,
"init": item.get("init", 0),
"min": item["min"],
"max": item["max"],
"step": item["step"],
"midi": midi_info, # Include MIDI information as a list
}
)
# possibly recurse
if "items" in item:
info_list.extend(extract_from_ui(item["items"]))
return info_list
# Extracting items info from the "ui" section
if "ui" in json_data:
ui_section = json_data["ui"]
return extract_from_ui(ui_section)
return []
# Creating the proper label for the parameter
def build_label(item_type: str, shortname: str, test: bool) -> str:
if test:
return "RB_" + item_type + "_" + shortname
elif shortname[0].isdigit():
return "cb_" + shortname
else:
return shortname
def add_polyphony_control(
sub_patch: Patcher,
set_param_pitch: Box,
set_param_gain: Box,
set_param_gate: Box,
is_freq: bool,
is_gain: bool,
) -> None:
"""
Adds polyphony control to a sub-patch for MIDI note input.
This function provides the flexibility to control pitch and gain parameters either
by frequency/MIDI key and gain/MIDI velocity. It takes parameters for setting pitch,
gain, and gate parameters, along with flags to specify control methods. The MIDI
notein and relevant processing objects are added to the sub-patch for polyphonic control.
Args:
sub_patch (Patcher): The sub-patch to which the polyphony control elements will be added.
set_param_pitch (Box): The objects for setting the pitch parameter.
set_param_gain (Box): The objects for setting the gain parameter.
set_param_gate (Box): The objects for setting the gate parameter.
is_freq (bool): Flag indicating whether pitch is controlled by frequency or MIDI key.
is_gain (bool): Flag indicating whether gain is controlled by gain or MIDI velocity.
Returns:
None
"""
# Add MIDI notein
note_in = sub_patch.add_textbox("notein")
# Pitch can be controlled by frequency or MIDI key
if is_freq:
# MIDI key to frequency conversion
mtof = sub_patch.add_textbox("mtof")
# freq patching
sub_patch.add_line(note_in, mtof)
sub_patch.add_line(mtof, set_param_pitch)
else:
# MIDI key patching
sub_patch.add_line(note_in, set_param_pitch)
# Gain can be controlled by gain or MIDI velocity
if is_gain:
# MIDI velocity scaled to 0-1
scale_gain = sub_patch.add_textbox("scale 0 127 0 1")
# Velocity/gain patching
sub_patch.add_line(note_in, scale_gain, outlet=1)
sub_patch.add_line(scale_gain, set_param_gain)
else:
# MIDI velocity directly controls gain
sub_patch.add_line(note_in, set_param_gain, outlet=1)
# Velocity/gate patching
gate_op = sub_patch.add_textbox("> 0")
sub_patch.add_line(note_in, gate_op, outlet=1)
sub_patch.add_line(gate_op, set_param_gate)
def add_midi_control(
item: dict,
sub_patch: Patcher,
codebox: Box,
param: Optional[Box] = None,
set_param: Optional[Box] = None,
change: Optional[Box] = None,
) -> bool:
"""
Adds MIDI control to the subpatch.
This function handles the MIDI control for both input and output in the subpatch.
It checks the MIDI control type and prepares the necessary MIDI input and output messages.
The scaling for MIDI input and output messages is also defined based on the control type.
Args:
item (dict): The dictionary containing information about the UI item.
sub_patch (Patcher): The subpatcher object to which MIDI control will be added.
codebox (Box): The codebox~ object in the subpatcher.
param (Optional[Box]): The param object for the input UI items.
set_param (Optional[Box]): The 'set' param object for the input UI items.
change (Optional[Box]): The change object for bargraph UI items.
Returns:
bool: True if MIDI control type is supported and added successfully, possible logs an error and return False otherwise.
"""
# Get the MIDI information from the item dictionary
midi_info = item.get("midi", None)
if not midi_info:
return False
# Define the Faust to RNBO syntax mapping for both MIDI input and output
midi_mapping = {
"ctrl": {"in": "ctlin", "out": "ctlout"},
"chanpress": {"in": "touchin", "out": "touchout"},
"keyon": {"in": "notein", "out": "noteout"},
"keyoff": {"in": "notein", "out": "noteout"},
"key": {"in": "notein", "out": "noteout"},
"pitchwheel": {"in": "bendin @bendmode 2", "out": "bendout @bendmode 2"},
"pgm": {"in": "pgmin", "out": "pgmout"},
}
# Check if the MIDI control type is supported
midi_type = midi_info[0]
if midi_type not in midi_mapping:
logging.error(f"MIDI control type '{midi_type}' not supported")
return False
# Prepare the MIDI input and output messages
midi_type = midi_info[0]
midi_args = " ".join(midi_info[1:])
# Scaling for MIDI input and output messages
# Pitchwheel case using @bendmode 2 (-8192, 8192) mode
if midi_type == "pitchwheel":
scaling_in = f"scale -8192 8192 {item['min']} {item['max']}"
scaling_out = f"scale {item['min']} {item['max']} -8192 8192"
# General case
else:
scaling_in = f"scale 0 127 {item['min']} {item['max']}"
scaling_out = f"scale {item['min']} {item['max']} 0 127"
# Connect the input objects
if set_param:
# Create MIDI object (TODO: handle all channels case: Faust 0 => RNBO -1)
midi_in = sub_patch.add_textbox(f"{midi_mapping[midi_type]['in']} {midi_args}")
midi_out = sub_patch.add_textbox(
f"{midi_mapping[midi_type]['out']} {midi_args}"
)
# Create the scaling box
scaling_in_box = sub_patch.add_textbox(scaling_in)
scaling_out_box = sub_patch.add_textbox(scaling_out)
# Input connections
sub_patch.add_line(midi_in, scaling_in_box)
sub_patch.add_line(scaling_in_box, set_param)
# Output connections
sub_patch.add_line(param, scaling_out_box)
sub_patch.add_line(scaling_out_box, midi_out)
# Connect the output objects
if change:
# Create MIDI object (TODO: handle all channels case: Faust 0 => RNBO -1)
midi_out = sub_patch.add_textbox(
f"{midi_mapping[midi_type]['out']} {midi_args}"
)
# Create the scaling box
scaling_out_box = sub_patch.add_textbox(scaling_out)
# Connections
sub_patch.add_line(change, scaling_out_box)
sub_patch.add_line(scaling_out_box, midi_out)
return True
def generate_io_info(
midi: bool, num_inputs: int, num_outputs: int
) -> Tuple[int, int, dict, dict]:
"""
Generate inlet and outlet information dictionaries based on the number of inputs and outputs.
Args:
midi (bool): A flag indicating whether to include MIDI inlet/outlet.
num_inputs (int): The number of input signals.
num_outputs (int): The number of output signals.
Returns:
Tuple: A tuple containing four elements:
- inlets (int): Total number of inlet ports, including MIDI if applicable.
- outlets (int): Total number of outlet ports, including MIDI if applicable.
- inletInfo (dict): Dictionary containing information about the input ports.
- outletInfo (dict): Dictionary containing information about the output ports.
"""
inletInfo = {"IOInfo": []}
outletInfo = {"IOInfo": []}
if midi:
inlets = max(1, num_inputs) + 1
# First inlets are signals
for i in range(1, num_inputs + 1):
io_entry = {"comment": "", "index": i, "tag": f"in{i}", "type": "signal"}
inletInfo["IOInfo"].append(io_entry)
# Last inlet is MIDI
io_entry = {
"comment": "",
"index": inlets,
"tag": f"in{inlets}",
"type": "midi",
}
inletInfo["IOInfo"].append(io_entry)
# The MIDI outlet is added, then port message and dump outlets are always added
outlets = max(1, num_outputs) + 3
# First outlets are signals
for i in range(1, num_outputs + 1):
io_entry = {"comment": "", "index": i, "tag": f"out{i}", "type": "signal"}
outletInfo["IOInfo"].append(io_entry)
# Next outlet is MIDI
io_entry = {"comment": "", "index": i, "tag": f"out{i}", "type": "midi"}
outletInfo["IOInfo"].append(io_entry)
else:
inlets = max(1, num_inputs)
# All inlets are signals
for i in range(1, num_inputs + 1):
io_entry = {"comment": "", "index": i, "tag": f"in{i}", "type": "signal"}
inletInfo["IOInfo"].append(io_entry)
# Port message and dump outlets are always added
outlets = max(1, num_outputs) + 2
# All outlets are signals
for i in range(1, num_outputs + 1):
io_entry = {"comment": "", "index": i, "tag": f"out{i}", "type": "signal"}
outletInfo["IOInfo"].append(io_entry)
return inlets, outlets, inletInfo, outletInfo
def add_codebox_object(
patcher: Patcher,
sub_patcher: Patcher,
rnbo: Box,
prefix: str,
codebox_code: str,
items_info_list: List[dict],
midi: bool,
nvoices: int,
test: bool,
num_inputs: int,
num_outputs: int,
) -> None:
"""
Add a codebox~ object and parameter controls to a Max/MSP subpatcher.
This function sets up a codebox~ object and associated parameter controls
within a Max/MSP subpatcher. It generates input and output lines, handles
UI elements like buttons, sliders, and MIDI controls, and provides polyphony
control when applicable.
Parameters:
patcher (Patcher): The main Max/MSP patcher.
sub_patcher (Patcher): The subpatcher where the codebox~ will be added.
rnbo (Box): The rnbo object.
prefix (str): The prefix to be added to the label.
codebox_code (str): The code to be added to the codebox~.
items_info_list (list[dict]): List of dictionaries containing UI item information.
midi (bool): Whether MIDI controls should be added.
nvoices (int): Number of voices for polyphony control.
test (bool): Whether the code is for testing purposes.
num_inputs (int): Number of audio inputs.
num_outputs (int): Number of audio outputs.
"""
# Create codebox~ section in the subpatcher
codebox = sub_patcher.add_codebox_tilde(
code=codebox_code, patching_rect=[500.0, 500.0, 400.0, 200.0]
)
# Generating the lines of code for inputs
for i in range(num_inputs):
input_box = sub_patcher.add_textbox(f"in~ {i + 1}")
sub_patcher.add_line(input_box, codebox, inlet=i)
# Generating the lines of code for outputs
for i in range(num_outputs):
output_box = sub_patcher.add_textbox(f"out~ {i + 1}")
sub_patcher.add_line(codebox, output_box, outlet=i)
# Parameter for polyphony handling
set_param_pitch = None
set_param_gain = None
set_param_gate = None
is_freq = False
is_gain = False
# Counter of bargraph to be used to outlet computation
bargraph_count = 0
# Add parameter control for button/checkbox and slider/nentry, annlyse for polyphony
for item in items_info_list:
shortname = item["shortname"]
item_type = item["type"]
label = build_label(item_type, shortname, test)
label_path = prefix + label
# print(label_path)
# button and checkbox use a 'toggle' object
if item_type in ["button", "checkbox"]:
# Add a global 'set' param object
set_param = sub_patcher.add_textbox(f"set {label}")
# Upper level parameter control with a 'toggle' and 'attrui' objects
toggle = patcher.add_textbox("toggle")
# Set the position and size of the toggle button on the canvas
toggle.patching_rect = [
toggle.patching_rect[0],
toggle.patching_rect[1],
24.0,
24.0,
]
param_wrap = patcher.add_textbox(
"attrui",
maxclass="attrui",
attr=label,
parameter_enable=1,
minimum=0,
maximum=1,
saved_attribute_attributes={
"valueof": {
"parameter_initial": [label_path, 0],
"parameter_initial_enable": 1,
}
},
)
patcher.add_line(toggle, param_wrap)
patcher.add_line(param_wrap, rnbo)
param = sub_patcher.add_textbox(
f"param {label} 0 @min 0 @max 1",
)
# Add a line to connect the parameter control to the 'set' param object
sub_patcher.add_line(param, set_param)
# Add a line to connect the 'set' param object to the codebox
sub_patcher.add_line(set_param, codebox)
# Possibly add MIDI input control
if midi:
add_midi_control(
item, sub_patcher, codebox, param=param, set_param=set_param
)
# bargraph with "min", "max"
elif item_type in ["vbargraph", "hbargraph"]:
min_value = item["min"]
max_value = item["max"]
# Upper level parameter control with a 'attrui' object
param_wrap = patcher.add_textbox(
"attrui",
maxclass="attrui",
attr=label,
minimum=min_value,
maximum=max_value,
parameter_enable=1,
saved_attribute_attributes={
"valueof": {
"parameter_initial": [label_path, 0],
"parameter_initial_enable": 1,
}
},
)
patcher.add_line(param_wrap, rnbo)
param = sub_patcher.add_textbox(
f"param {label} 0 @min {min_value} @max {max_value}",
)
# Signal transformed in control
snapshot = sub_patcher.add_textbox("snapshot~ 10")
change = sub_patcher.add_textbox("change")
# Connect codebox outN to snapshot
sub_patcher.add_line(codebox, snapshot, outlet=num_outputs + bargraph_count)
# Connect snapshot to range
sub_patcher.add_line(snapshot, change)
# And finally change to param
sub_patcher.add_line(change, param)
# Possibly add MIDI output control
if midi:
add_midi_control(item, sub_patcher, codebox, change=change)
# Next bargraph
bargraph_count += 1
# slider and nentry use a 'param' object
else:
min_value = item["min"]
max_value = item["max"]
init_value = item["init"]
steps_value = (max_value - min_value) / item["step"]
# Add a global 'set' param object
set_param = sub_patcher.add_textbox(f"set {label}")
# Upper level parameter control with a 'attrui' object
param_wrap = patcher.add_textbox(
"attrui",
maxclass="attrui",
attr=label,
minimum=min_value,
maximum=max_value,
parameter_enable=1,
saved_attribute_attributes={
"valueof": {
"parameter_initial": [label_path, init_value],
"parameter_initial_enable": 1,
}
},
)
patcher.add_line(param_wrap, rnbo)
param = sub_patcher.add_textbox(
# Does not work with @steps, with parameter values slightly different
# f"param {label} {init_value} @min {min_value} @max {max_value} @steps {steps_value} ",
f"param {label} {init_value} @min {min_value} @max {max_value}",
)
# Add a line to connect the parameter control to the 'set' param object
sub_patcher.add_line(param, set_param)
# Add a line to connect the 'set' param object to the codebox
sub_patcher.add_line(set_param, codebox)
# Possibly add MIDI input control
if midi:
add_midi_control(
item, sub_patcher, codebox, param=param, set_param=set_param
)
# Analyze the parameter shortname for polyphony handing
if midi and nvoices > 0:
if shortname.endswith("freq"):
set_param_pitch = set_param
is_freq = True
elif shortname.endswith("key"):
set_param_pitch = set_param
is_freq = False
elif shortname.endswith("gain"):
set_param_gain = set_param
is_gain = True
elif shortname.endswith("velocity"):
set_param_gain = set_param
is_gain = False
elif shortname.endswith("gate"):
set_param_gate = set_param
# After analyzing all UI items to get freq/gain/gate controls, possibly add polyphony control
if midi and nvoices > 0 and set_param_pitch and set_param_gain and set_param_gate:
add_polyphony_control(
sub_patcher,
set_param_pitch,
set_param_gain,
set_param_gate,
is_freq,
is_gain,
)
def create_rnbo_object(
patcher: Patcher,
dsp_name: str,
midi: bool,
nvoices: int,
num_inputs: int,
num_outputs: int,
):
"""
Create and configure the rnbo~ object.
This function creates and configures the rnbo~ object within a Max/MSP patcher.
It sets attributes such as optimization, title, and polyphony (if applicable)
based on the provided parameters.
Parameters:
patcher (Patcher): The Max/MSP patcher where the rnbo~ object will be added.
dsp_name (str): The name of the DSP module.
midi (bool): Whether MIDI controls should be added.
nvoices (int): Number of voices for polyphony control.
num_inputs (int): Number of audio inputs.
num_outputs (int): Number of audio outputs.
Returns:
rnbo (Box): The created rnbo~ object.
"""
# Create the rnbo~ object
rnbo_attributes = {"optimization": "O3", "title": dsp_name, "dumpoutlet": 1}
# Add the polyphony attribute only if midi is True and nvoices > 0
if midi and nvoices > 0:
rnbo_attributes["polyphony"] = nvoices
# Prepare the inlet and outlet information
inlets, outlets, inletInfo, outletInfo = generate_io_info(
midi, num_inputs, num_outputs
)
# Create the rnbo~ object
rnbo = patcher.add_rnbo(
inletInfo=inletInfo,
outletInfo=outletInfo,
title=dsp_name,
numinlets=inlets,
numoutlets=outlets,
saved_object_attributes=rnbo_attributes,
)
# And return it
return rnbo
def add_rnbo_object_flat(
patcher: Patcher,
dsp_name: str,
codebox_code: str,
items_info_list: List[dict],
midi: bool,
nvoices: int,
test: bool,
num_inputs: int,
num_outputs: int,
) -> Box:
"""
Adds DSP elements, routing, and parameter controls for a DSP to the given Patcher object in flat mode.
Parameters:
patcher (Patcher): The Patcher object to which DSP elements and controls will be added.
dsp_name (str): The name of the DSP.
codebox_code (str): The code to be executed by the DSP effect.
items_info_list (List[dict]): A list of dictionaries containing information about UI items.
midi (bool): Indicates whether MIDI control is enabled.
nvoices (int): The number of polyphony voices.
num_inputs (int): The number of audio input channels.
num_outputs (int): The number of audio output channels.
Returns:
Box: The added rnbo~ object representing the DSP.
"""
# Create the rnbo~ object
rnbo = create_rnbo_object(patcher, dsp_name, midi, nvoices, num_inputs, num_outputs)
# Create the codebox subpatcher
sub_patcher = rnbo.subpatcher
add_codebox_object(
patcher,
sub_patcher,
rnbo,
"",
codebox_code,
items_info_list,
midi,
nvoices,
test,
num_inputs,
num_outputs,
)
return rnbo
def add_rnbo_object_subpatcher(
patcher: Patcher,
rnbopat_path: str,
dsp_name: str,
codebox_code: str,
items_info_list: List[dict],
midi: bool,
nvoices: int,
test: bool,
num_inputs: int,
num_outputs: int,
) -> Box:
"""
Adds DSP elements, routing, and parameter controls for a DSP to the given Patcher object in 'p' subpatcher.
Parameters:
patcher (Patcher): The Patcher object to which DSP elements and controls will be added.
rnbopat_path (str): The path to the directory where the maxpat will be saved.
dsp_name (str): The name of the DSP.
codebox_code (str): The code to be executed by the DSP effect.
items_info_list (List[dict]): A list of dictionaries containing information about UI items.
midi (bool): Indicates whether MIDI control is enabled.
nvoices (int): The number of polyphony voices.
num_inputs (int): The number of audio input channels.
num_outputs (int): The number of audio output channels.
Returns:
Box: The added rnbo~ object representing the DSP.
"""
# Create the rnbo~ object
rnbo = create_rnbo_object(patcher, dsp_name, midi, nvoices, num_inputs, num_outputs)
# Create the codebox subpatcher in a rnbopat file
rnbopat = Patcher(rnbopat_path, classnamespace="rnbo")
add_codebox_object(
patcher,
rnbopat,
rnbo,
"poly/" + dsp_name + "/" if nvoices > 0 else dsp_name + "/",
codebox_code,
items_info_list,
midi,
nvoices,
test,
num_inputs,
num_outputs,
)
# Save the rnbopat file
rnbopat.save()
# Get the subpatcher
sub_patcher = rnbo.subpatcher
# Add the DSP subpatcher
if nvoices > 0:
p_dsp_box = sub_patcher.add_textbox(
f"p @title {dsp_name} @file {rnbopat_path} @polyphony {nvoices}"
)
else:
p_dsp_box = sub_patcher.add_textbox(f"p @title {dsp_name} @file {rnbopat_path}")
# Generating the lines of code for inputs
for i in range(num_inputs):
input_box = sub_patcher.add_textbox(f"in~ {i + 1}")
sub_patcher.add_line(input_box, p_dsp_box, inlet=i)
# Generating the lines of code for outputs
for i in range(num_outputs):
output_box = sub_patcher.add_textbox(f"out~ {i + 1}")
sub_patcher.add_line(p_dsp_box, output_box, outlet=i)
# Possibly add MIDI input/output control in the global patcher
# and connect the DSP rnbo~ object to the midiin/midiout objects.
# midi_in/midi_out are only needed in polyphonic mode
if midi and nvoices > 0:
midi_in = sub_patcher.add_textbox("midiin")
midi_out = sub_patcher.add_textbox("midiout")
connect_midi_subpatcher(
sub_patcher, p_dsp_box, midi_in, midi_out, num_inputs, num_outputs
)
return rnbo
def add_rnbo_object_poly_effect(
patcher: Patcher,
dsp_rnbopat_path: str,
effect_rnbopat_path: str,
dsp_name: str,
dsp_codebox_code: str,
effect_codebox_code: str,
dsp_items_info_list: List[dict],
effect_items_info_list: List[dict],
midi: bool,
nvoices: int,
test: bool,
dsp_num_inputs: int,
dsp_num_outputs: int,
effect_num_inputs: int,
effect_num_outputs: int,
) -> Box:
"""
Adds DSP elements, routing, and parameter controls for a DSP to the given Patcher object for DSP and effect.
Parameters:
patcher (Patcher): The Patcher object to which DSP elements and controls will be added.
dsp_rnbopat_path (str): The path to the directory where the DSP maxpat will be saved.
effect_rnbopat_path (str): The path to the directory where the effect maxpat will be saved.
dsp_name (str): The name of the DSP.
dsp_codebox_code (str): The code to be executed by the DSP.
effect_codebox_code (str): The code to be executed by the effect.
dsp_items_info_list (List[dict]): A list of dictionaries containing information about UI items for the DSP.
effect_items_info_list (List[dict]): A list of dictionaries containing information about UI items for the effect.
midi (bool): Indicates whether MIDI control is enabled.
nvoices (int): The number of polyphony voices.
dsp_num_inputs (int): The number of audio input channels.
dsp_num_outputs (int): The number of audio output channels.
effect_num_inputs (int): The number of audio input channels.
effect_num_outputs (int): The number of audio output channels.
Returns:
Box: The added rnbo~ object representing the DSP.
"""
# Create the rnbo~ object
rnbo = create_rnbo_object(
patcher, dsp_name, midi, nvoices, dsp_num_inputs, effect_num_outputs
)
# Create the DSP codebox subpatcher in a dsp_rnbo_pat file
dsp_rnbo_pat = Patcher(dsp_rnbopat_path, classnamespace="rnbo")
add_codebox_object(
patcher,
dsp_rnbo_pat,
rnbo,
"poly/" + dsp_name + "/" if nvoices > 0 else dsp_name + "/",
dsp_codebox_code,
dsp_items_info_list,
midi,
nvoices,
test,
dsp_num_inputs,
dsp_num_outputs,
)
# Save the rnbo_pat file
dsp_rnbo_pat.save()
# Create the effect codebox subpatcher in a rnbo_effect_pat file
effect_rnbo_pat = Patcher(effect_rnbopat_path, classnamespace="rnbo")
add_codebox_object(
patcher,
effect_rnbo_pat,
rnbo,
"poly/" + dsp_name + "[1]/" if nvoices > 0 else dsp_name + "/",
effect_codebox_code,
effect_items_info_list,
midi,
-1,
False,
effect_num_inputs,
effect_num_outputs,
)
# Save the rnbo_effect_pat file
effect_rnbo_pat.save()
# Get the subpatcher
sub_patcher = rnbo.subpatcher
# Add the DSP subpatcher
if nvoices > 0:
p_dsp_box = sub_patcher.add_textbox(
f"p @title {dsp_name} @file {dsp_rnbopat_path} @polyphony {nvoices}"
)
else:
p_dsp_box = sub_patcher.add_textbox(
f"p @title {dsp_name} @file {dsp_rnbopat_path}"
)
# Add the effect subpatcher
p_effect_box = sub_patcher.add_textbox(
f"p @title {dsp_name} @file {effect_rnbopat_path}"
)
# Generating the lines of code for inputs
for i in range(dsp_num_inputs):
input_box = sub_patcher.add_textbox(f"in~ {i + 1}")
sub_patcher.add_line(input_box, p_dsp_box, inlet=i)
# Connect the DSP to the effect
connect_dsp_effect(
sub_patcher,
p_dsp_box,
p_effect_box,
dsp_num_outputs,
effect_num_inputs,
)
# Generating the lines of code for outputs
for i in range(effect_num_outputs):
output_box = sub_patcher.add_textbox(f"out~ {i + 1}")
sub_patcher.add_line(p_effect_box, output_box, outlet=i)
# Possibly add MIDI input/output control in the global patcher
# and connect the DSP rnbo~ object to the midiin/midiout objects
if midi:
midi_in = sub_patcher.add_textbox("midiin")
midi_out = sub_patcher.add_textbox("midiout")
connect_midi_subpatcher(
sub_patcher, p_dsp_box, midi_in, midi_out, dsp_num_inputs, dsp_num_outputs
)
return rnbo
def connect_dsp_effect(
patcher: Patcher,
dsp_box: Box,
effect_box: Box,
dsp_num_outputs: int,
effect_num_inputs: int,
) -> None:
"""
Connects a DSP module to an effect module within a patcher.
Args:
patcher (Patcher): The main patcher where objects will be added.
dsp_box (Box): The rnbo DSP module
effect_box (Box): The rnbo effect module
dsp_num_outputs (int): Number of output channels of the DSP module.
effect_num_inputs (int): Number of input channels of the effect module.
Notes:
This function establishes audio connections between the specified DSP module
and effect module by adding appropriate lines to the patcher.
Implementing this equivalent Faust written logic:
connect(1,1) = _;
connect(2,2) = _,_;
connect(1,2) = _ <: _,_;
connect(2,1) = _,_ :> _;
Returns:
None
"""
# print(f"Connecting DSP to effect: {dsp_num_outputs} -> {effect_num_inputs}")
# Python 3.10 and later
# match (dsp_num_outputs, effect_num_inputs):
# case (1, 1):
# # print("1 -> 1")
# patcher.add_line(dsp_box, effect_box)
# case (1, 2):
# # print("1 -> 2")
# patcher.add_line(dsp_box, effect_box, inlet=0, outlet=0)
# patcher.add_line(dsp_box, effect_box, inlet=1, outlet=0)
# case (2, 1):
# # print("2 -> 1")
# patcher.add_line(dsp_box, effect_box, inlet=0, outlet=0)
# patcher.add_line(dsp_box, effect_box, inlet=0, outlet=1)
# case (2, 2):
# # print("2 -> 2")
# patcher.add_line(dsp_box, effect_box, inlet=0, outlet=0)
# patcher.add_line(dsp_box, effect_box, inlet=1, outlet=1)
if dsp_num_outputs == 1:
if effect_num_inputs == 1: