-
Notifications
You must be signed in to change notification settings - Fork 12
/
FoaMatrix.sc
2365 lines (1907 loc) · 55.4 KB
/
FoaMatrix.sc
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
/*
Copyright the ATK Community and Joseph Anderson, 2011-2016
J Anderson j.anderson[at]ambisonictoolkit.net
This file is part of SuperCollider3 version of the Ambisonic Toolkit (ATK).
The SuperCollider3 version of the Ambisonic Toolkit (ATK) 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.
The SuperCollider3 version of the Ambisonic Toolkit (ATK) 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 the
SuperCollider3 version of the Ambisonic Toolkit (ATK). If not, see
<http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------
// The Ambisonic Toolkit (ATK) is a soundfield kernel support library.
//
// Class: FoaSpeakerMatrix
// Class: FoaMatrix
// Class: FoaDecoderMatrix
// Class: FoaEncoderMatrix
// Class: FoaXformerMatrix
// Class: FoaDecoderKernel
// Class: FoaEncoderKernel
//
// The Ambisonic Toolkit (ATK) is intended to bring together a number of tools and
// methods for working with Ambisonic surround sound. The intention is for the toolset
// to be both ergonomic and comprehensive, providing both classic and novel algorithms
// to creatively manipulate and synthesise complex Ambisonic soundfields.
//
// The tools are framed for the user to think in terms of the soundfield kernel. By
// this, it is meant the ATK addresses the holistic problem of creatively controlling a
// complete soundfield, allowing and encouraging the composer to think beyond the placement
// of sounds in a sound-space and instead attend to the impression and image of a soundfield.
// This approach takes advantage of the model the Ambisonic technology presents, and is
// viewed to be the idiomatic mode for working with the Ambisonic technique.
//
//
// We hope you enjoy the ATK!
//
// For more information visit http://ambisonictoolkit.net/ or
// email info[at]ambisonictoolkit.net
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// Third Party Notices
//-----------------------------------------------------------------------
//
//-----------------------------------------------------------------------
// Support for Gerzon's Diametric Decoder Theorem (DDT) decoding
// algorithm is derived from Aaron Heller's Octave code available at:
// http://www.ai.sri.com/ajh/ambisonics/
//
// Benjamin, et al., "Localization in Horizontal-Only Ambisonic Systems"
// Preprint from AES-121, 10/2006, San Francisco
//
// Implementation in the SuperCollider3 version of the ATK is by
// Joseph Anderson <j.anderson[at]ambisonictoolkit.net>
//-----------------------------------------------------------------------
//
//
//-----------------------------------------------------------------------
// Irregular array decoding coefficients (5.0) are kindly provided
// by Bruce Wiggins: http://www.brucewiggins.co.uk/
//
// B. Wiggins, "An Investigation into the Real-time Manipulation and
// Control of Three-dimensional Sound Fields, " PhD Thesis, University of
// Derby, Derby, 2004.
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// matrix decoders
/*
Given HOA, FoaSpeakerMatrix is redundant.
TODO: Replace with updated HOA implementation.
*/
// Heller's DDT (helper function)
FoaSpeakerMatrix {
var <positions, <k, m, n;
*new { |directions, k|
var positions;
switch(directions.rank, // 2D or 3D?
1, { positions = Matrix.with( // 2D
directions.collect({ |item|
Polar.new(1, item).asPoint.asArray
})
)
},
2, { positions = Matrix.with( // 3D
directions.collect({ |item|
Spherical.new(1, item[0], item[1]).asCartesian.asArray
})
)
}
);
^super.newCopyArgs(positions, k).initDiametric;
}
*newPositions { |positions, k|
^super.newCopyArgs(positions, k).initDiametric;
}
initDiametric {
// n = number of output channel (speaker) pairs
// m = number of dimensions,
// 2 = horizontal, 3 = periphonic
m = this.positions.cols;
n = this.positions.rows;
}
dim { ^m }
numChannels { ^n * 2 }
matrix {
var s, directions, pos, dir;
// scatter matrix accumulator
s = Matrix.newClear(m, m);
// output channel (speaker) directions matrix
// NOTE: this isn't the user supplied directions arg
directions = Matrix.newClear(m, n);
n.do({ |i|
// allow entry of positions as
// transpose for convenience
// e.g., output channel (speaker) positions are now in columns
// rather than rows, then
// get the i'th output channel (speaker) position
// e.g., select the i'th column
pos = positions.flop.getCol(i);
// normalize to get direction cosines
dir = pos / pos.squared.sum.sqrt;
// form scatter matrix and accumulate
s = s + Matrix.with(dir * dir.flop);
// form matrix of output channel (speaker) directions
directions.putCol(i, dir)
});
// return resulting matrix
^sqrt(1 / 2) * n * k * (s.inverse * directions);
}
printOn { |stream|
stream << this.class.name << "(" <<* [this.dim, this.numChannels] <<")";
}
}
FoaMatrix : AtkMatrix {
var <>dirChannels; // setter added for matrix-to-file & file-to-matrix support
// most typically called by subclass
*new { |kind|
^super.new(kind).init
}
*newFromMatrix { |matrix, directions|
^super.new(\fromMatrix).initFromMatrix(matrix, directions)
}
initFromMatrix { |aMatrix, argDirections|
var numCoeffs;
var numCoeffsDim, dirChannelsDim;
// set instance matrix
matrix = aMatrix;
// set instance dirChannels
dirChannels = argDirections;
// 1) Check: matrix numChannels == directions.size
if(this.numChannels != this.dirChannels.size, {
Error(
format(
"[%:-initFromMatrix] Matrix number of channels "
"should matches directions. Number of channels = %, number of directions = %",
this.class.asString, this.numChannels, this.dirChannels.size
)
).errorString.postln;
this.halt
});
// 2) Check: matrix numCoeffs == 3 || 4, is it a valid 2D or 3D FOA matrix?
numCoeffs = switch(this.type,
\encoder, { matrix.rows },
\decoder, { matrix.cols },
\xformer, { matrix.rows }
);
if((numCoeffs == 3 or: { numCoeffs == 4 }).not, {
Error(
format(
"[%:-initFromMatrix] Matrix coefficient size invalid for FOA."
"Should be 3 for 2D or 4 for 3D. (detected: %)",
this.class.asString, numCoeffs
)
).errorString.postln;
this.halt
});
// 3) Check: matrix dim against dirChannels dim
numCoeffsDim = numCoeffs - 1;
dirChannelsDim = if(this.type == \xformer, {
this.dim // exception required for \xformer, as dirChannels = nil
}, {
this.dirChannels.rank + 1
});
if(numCoeffsDim != dirChannelsDim, {
Error(
format(
"[%:-initFromMatrix] Detected matrix and specified directions "
"dimensions don't matched. (matrix: %, directions: %)",
this.class.asString, numCoeffsDim, dirChannelsDim
)
).errorString.postln;
this.halt
});
// 4) Check: xformer is square matrix
if((this.type == \xformer and: { matrix.isSquare.not }), {
Error(
format(
"[%:-initFromMatrix] An 'xformer' matrix "
"should be square. rows = %, cols = %",
this.class.asString, matrix.rows, matrix.cols
)
).errorString.postln;
this.halt
})
}
initFromFile { |filePathOrName, mtxType, searchExtensions = false|
var pn, dict;
// first try with path name only
pn = Atk.resolveMtxPath(filePathOrName);
pn ?? {
// partial path reqires set to resolve
pn = Atk.resolveMtxPath(filePathOrName, mtxType, this.set, searchExtensions);
};
// instance var
filePath = pn.fullPath;
case(
{ pn.extension == "txt" }, {
matrix = if(pn.fileName.contains(".mosl"), {
// .mosl.txt file: expected to be matrix only,
// single values on each line, by rows
Matrix.with(this.prParseMOSL(pn));
}, {
// .txt file: expected to be matrix only, cols
// separated by spaces, rows by newlines
Matrix.with(FileReader.read(filePath).asFloat);
});
kind = pn.fileName.asSymbol // kind defaults to filename
},
{ pn.extension == "yml" }, {
dict = filePath.parseYAMLFile;
fileParse = IdentityDictionary(know: true);
// replace String keys with Symbol keys, make "knowable"
dict.keysValuesDo{ |k, v|
fileParse.put(k.asSymbol,
(v == "nil").if({ nil }, { v }) // so .info parsing doesn't see nil as array
)
};
if(fileParse[\type].isNil, {
"Matrix 'type' is undefined in the .yml file: cannot confirm the "
"type matches the loaded object (encoder/decoder/xformer)".warn
}, {
if((fileParse[\type].asSymbol != mtxType.asSymbol), {
Error(
format(
"[%:-initFromFile] Matrix 'type' defined in the .yml file (%) doesn't match "
"the type of matrix you're trying to load (%)",
this.class.asString, fileParse[\type], mtxType
).errorString.postln;
this.halt
)
})
});
matrix = Matrix.with(fileParse.matrix.asFloat);
kind = if(fileParse.kind.notNil, {
fileParse.kind.asSymbol
}, {
pn.fileNameWithoutExtension.asSymbol
})
},
{ // catch all
Error(
"[%:-initFromFile] Unsupported file extension.".format(this.class.asString)
).errorString.postln;
this.halt
}
)
}
// separate YML writer for FOA
prWriteMatrixToYML { |pn, note, attributeDictionary|
var wr, wrAtt, wrAttArr, defaults;
var dirIns, dirOuts;
wr = FileWriter(pn.fullPath);
// write a one-line attribute
wrAtt = { |att, val|
wr.write("% : ".format(att));
wr.write(
(
val ?? { this.tryPerform(att) }
).asCompileString; // allow for large strings
);
wr.write("\n\n")
};
// write a multi-line attribute (2D array)
wrAttArr = { |att, arr|
var vals = arr ?? { this.tryPerform(att) };
if(vals.isNil, {
wr.writeLine(["% : nil".format(att)])
}, {
wr.writeLine(["% : [".format(att)]);
(vals.asArray).do({ |elem, i|
wr.write(elem.asCompileString); // allow for large row strings
wr.write(
(i == (vals.size - 1)).if({ "\n]\n" }, { ",\n" })
)
})
});
wr.write("\n")
};
note !? { wrAtt.(\note, note) };
wrAtt.(\type);
// write default attributes
defaults = if(this.type == \decoder, {
[\kind, \shelfK, \shelfFreq]
}, {
[\kind]
});
if(attributeDictionary.notNil, {
// make sure attribute dict doesn't explicitly set the attribute first
defaults.do({ |att|
attributeDictionary[att] ?? { wrAtt.(att) }
})
}, {
defaults.do({ |att| wrAtt.(att) })
});
attributeDictionary !? {
attributeDictionary.keysValuesDo{ |k, v|
// catch overridden dirIn/Outputs
switch(k,
\dirInputs, { dirIns = v },
\dirOutputs, { dirOuts = v },
{
if(v.isKindOf(Array), {
wrAttArr.(k, v)
}, {
wrAtt.(k, v)
})
}
)
}
};
wrAttArr.(\dirInputs, dirIns);
wrAttArr.(\dirOutputs, dirOuts);
wrAttArr.(\matrix);
wr.close;
}
prParseMOSL { |pn|
var file, numRows, numCols, mtx, row;
file = FileReader.read(pn.fullPath);
numRows = nil;
numCols = nil;
mtx = [];
row = [];
file.do({ |line|
var val = line[0];
switch(val,
"//", { }, // ignore comments: maintain backwards compatability
"#", { }, // ignore comments
";", { }, // ignore comments
"", { }, // ignore blank line
{ // found valid line
case(
{ numRows.isNil }, { numRows = val.asInteger },
{ numCols.isNil }, { numCols = val.asInteger },
{
row = row.add(val.asFloat);
if(row.size == numCols, {
mtx = mtx.add(row);
row = [];
})
}
)
}
)
});
// test matrix dimensions
if((mtx.size == numRows).not, {
Error(
format(
"Mismatch in matrix dimensions: rows specified [%], rows parsed from file [%]",
numRows, mtx.size
)
).throw
});
mtx.do({ |row, i|
if(row.size != numCols, {
Error(
format(
"Mismatch in matrix dimensions: rows % has % columns, but file species %",
i, row.size, numCols
)
).throw
})
});
^mtx
}
// FOA only
loadFromLib { |...args|
var pathStr;
pathStr = this.kind.asString ++ "/";
if(args.size == 0, {
// no args... filename is assumed to be this.kind
pathStr = this.kind.asString
}, {
args.do({ |argParam, i|
pathStr = if(i > 0, {
format("%-%", pathStr, argParam.asString)
}, {
format("%%", pathStr, argParam.asString)
})
})
});
this.initFromFile(pathStr ++ ".yml", this.type, false);
switch(this.type,
\encoder, { this.initEncoderVarsForFiles }, // properly set dirInputs
\decoder, { this.initDecoderVarsForFiles }, // properly set dirOutputs
\xformer, { }
)
}
set { ^\FOA }
// infer from subclass
type { ^this.class.asString.drop(3).drop(-6).toLower.asSymbol }
numChannels {
^switch(this.type,
\encoder, { this.numInputs },
\decoder, { this.numOutputs },
\xformer, { 4 }
)
}
dim {
^switch(this.type,
\encoder, { this.numOutputs - 1 },
\decoder, { this.numInputs - 1 },
\xformer, { 3 } // all transforms are 3D
)
}
dirInputs {
^switch(this.type,
\encoder, { this.dirChannels },
\decoder, { (this.numInputs).collect({ inf }) },
// \xformer, { this.numInputs.collect({ inf }) },
\xformer, { this.dirChannels } // requires set to inf
)
}
dirOutputs {
^switch(this.type,
\encoder, { (this.numOutputs).collect({ inf }) },
\decoder, { this.dirChannels },
// \xformer, { this.numInputs.collect({ inf }) },
\xformer, { this.dirChannels } // requires set to inf
)
}
directions { ^this.dirChannels }
}
FoaDecoderMatrix : FoaMatrix {
var <>shelfFreq, <shelfK;
*newDiametric { |directions = ([pi / 4, 3 * pi / 4]), k = \single|
^super.new(\diametric).initDiametric(directions, k);
}
*newPanto { |numChans = 4, orientation = \flat, k = \single|
^super.new(\panto).initPanto(numChans, orientation, k);
}
*newPeri { |numChanPairs = 4, elevation = 0.61547970867039, orientation = \flat, k = \single|
^super.new(\peri).initPeri(numChanPairs, elevation, orientation, k);
}
*newQuad { |angle = (pi / 4), k = \single|
^super.new(\quad).initQuad(angle, k);
}
*newStereo { |angle = (pi/2), pattern = 0.5|
^super.new(\stereo).initStereo(angle, pattern);
}
*newMono { |theta = 0, phi = 0, pattern = 0|
^super.new(\mono).initMono(theta, phi, pattern);
}
*new5_0 { |irregKind = \focused|
^super.new('5_0').loadFromLib(irregKind);
}
*newBtoA { |orientation = \flu, weight = \dec|
^super.new(\BtoA).loadFromLib(orientation, weight);
}
*newHoa1 { |ordering = \acn, normalisation = \n3d|
^super.new(\hoa1).loadFromLib(ordering, normalisation);
}
*newAmbix1 {
var ordering = \acn, normalisation = \sn3d;
^super.new(\hoa1).loadFromLib(ordering, normalisation);
}
*newFromFile { |filePathOrName|
^super.new.initFromFile(filePathOrName, \decoder, true).initDecoderVarsForFiles;
}
initK2D { |k|
if(k.isNumber, {
^k
}, {
^switch(k,
\velocity, { 1 },
\energy, { 2.reciprocal.sqrt },
\controlled, { 2.reciprocal },
\single, { 2.reciprocal.sqrt },
\dual, {
shelfFreq = 400.0;
shelfK = [(3/2).sqrt, 3.sqrt/2];
1 // return
}
)
})
}
initK3D { |k|
if(k.isNumber, {
^k
}, {
^switch(k,
\velocity, { 1 },
\energy, { 3.reciprocal.sqrt },
\controlled, { 3.reciprocal },
\single, { 3.reciprocal.sqrt },
\dual, {
shelfFreq = 400.0;
shelfK = [2.sqrt, (2 / 3).sqrt];
1 // return
}
)
})
}
initDiametric { |directions, k|
var positions, positions2;
var speakerMatrix, n;
switch(directions.rank, // 2D or 3D?
1, { // 2D
// find positions
positions = Matrix.with(
directions.collect({ |item|
Polar.new(1, item).asPoint.asArray
})
);
// list all of the output channels (speakers)
// i.e., expand to actual pairs
positions2 = positions ++ (positions.neg);
// set output channel (speaker) directions for instance
dirChannels = positions2.asArray.collect({ |item|
item.asPoint.asPolar.angle
});
// initialise k
k = this.initK2D(k)
},
2, { // 3D
// find positions
positions = Matrix.with(
directions.collect({ |item|
Spherical.new(1, item[0], item[1]).asCartesian.asArray
})
);
// list all of the output channels (speakers)
// i.e., expand to actual pairs
positions2 = positions ++ (positions.neg);
// set output channel (speaker) directions for instance
dirChannels = (positions2.asArray).collect({ |item|
item.asCartesian.asSpherical.angles
});
// initialise k
k = this.initK3D(k)
}
);
// get velocity gains
// NOTE: this comment from Heller seems to be slightly
// misleading, in that the gains returned will be
// scaled by k, which may not request a velocity
// gain. I.e., k = 1 isn't necessarily true, as it
// is assigned as an argument to this function.
speakerMatrix = FoaSpeakerMatrix.newPositions(positions2, k).matrix;
// n = number of output channels (speakers)
n = speakerMatrix.cols;
// build decoder matrix
// resulting rows (after flop) are W, X, Y, Z gains
matrix = speakerMatrix.insertRow(0, Array.fill(n, { 1 }));
// return resulting matrix
// ALSO: the below code calls for the complex conjugate
// of decoder_matrix. As we are expecting real vaules,
// we may regard this call as redundant.
// res = sqrt(2) / n * decoder_matrix.conj().transpose()
matrix = 2.sqrt / n * matrix.flop;
}
initPanto { |numChans, orientation, k|
var g0, g1, theta;
g0 = 1.0; // decoder gains
g1 = 2.sqrt; // 0, 1st order
// return theta from output channel (speaker) number
theta = numChans.collect({ |channel|
switch(orientation,
\flat, { ((1.0 + (2.0 * channel)) / numChans) * pi },
\point, { ((2.0 * channel) / numChans) * pi }
)
});
theta = (theta + pi).mod(2pi) - pi;
// set output channel (speaker) directions for instance
dirChannels = theta;
// initialise k
k = this.initK2D(k);
// build decoder matrix
matrix = Matrix.newClear(numChans, 3); // start w/ empty matrix
numChans.do({ |i|
matrix.putRow(i, [
g0,
k * g1 * theta[i].cos,
k * g1 * theta[i].sin
])
});
matrix = 2.sqrt / numChans * matrix
}
initPeri { |numChanPairs, elevation, orientation, k|
var theta, directions, upDirs, downDirs, upMatrix, downMatrix;
// generate output channel (speaker) pair positions
// start with polar positions. . .
theta = [];
numChanPairs.do({ |i|
theta = theta ++ [2 * pi * i / numChanPairs]
});
if(orientation == \flat, {
theta = theta + (pi / numChanPairs) // 'flat' case
});
// collect directions [[theta, phi], ...]
// upper ring only
directions = [
theta,
Array.newClear(numChanPairs).fill(elevation)
].flop;
// prepare output channel (speaker) directions for instance
upDirs = (directions + pi).mod(2pi) - pi;
downDirs = upDirs.collect({ |angles|
Spherical.new(1, angles[0], angles[1]).neg.angles
});
// initialise k
k = this.initK3D(k);
// build decoder matrix
matrix = FoaDecoderMatrix.newDiametric(directions, k).matrix;
// reorder the lower polygon
upMatrix = matrix[..(numChanPairs - 1)];
downMatrix = matrix[(numChanPairs)..];
if(((orientation == \flat) and: { numChanPairs.mod(2) == 1 }), {
// odd, 'flat'
downDirs = downDirs.rotate((numChanPairs / 2 + 1).asInteger);
downMatrix = downMatrix.rotate((numChanPairs / 2 + 1).asInteger)
}, {
// 'flat' case, default
downDirs = downDirs.rotate((numChanPairs / 2).asInteger);
downMatrix = downMatrix.rotate((numChanPairs / 2).asInteger)
});
dirChannels = upDirs ++ downDirs; // set output channel (speaker) directions
matrix = upMatrix ++ downMatrix; // set matrix
}
initQuad { |angle, k|
var g0, g1, g2;
// set output channel (speaker) directions for instance
dirChannels = [angle, pi - angle, (pi - angle).neg, angle.neg];
// initialise k
k = this.initK2D(k);
// calculate g1, g2 (scaled by k)
g0 = 1;
g1 = k / (2.sqrt * angle.cos);
g2 = k / (2.sqrt * angle.sin);
// build decoder matrix
matrix = 2.sqrt / 4 * Matrix.with([
[g0, g1, g2 ],
[g0, g1.neg, g2 ],
[g0, g1.neg, g2.neg ],
[g0, g1, g2.neg ]
])
}
initStereo { |angle, pattern|
var g0, g1, g2;
// set output channel (speaker) directions for instance
dirChannels = [pi/6, (pi/6).neg];
// calculate g0, g1, g2 (scaled by pattern)
g0 = (1.0 - pattern) * 2.sqrt;
g1 = pattern * angle.cos;
g2 = pattern * angle.sin;
// build decoder matrix, and set for instance
matrix = Matrix.with([
[g0, g1, g2 ],
[g0, g1, g2.neg ]
])
}
initMono { |theta, phi, pattern|
// set output channel (speaker) directions for instance
dirChannels = [0];
// build decoder matrix, and set for instance
matrix = Matrix.with([
[
(1.0 - pattern) * 2.sqrt,
pattern * theta.cos * phi.cos,
pattern * theta.sin * phi.cos,
pattern * phi.sin
]
])
}
initDecoderVarsForFiles {
if(fileParse.notNil, {
// TODO: check use of dirOutputs vs. dirChannels here
dirChannels = if(fileParse.dirOutputs.notNil, {
fileParse.dirOutputs.asFloat
}, { // output directions are unspecified in the provided matrix
(this.matrix.rows).collect({ \unspecified })
});
shelfK = fileParse.shelfK !? { fileParse.shelfK.asFloat };
shelfFreq = fileParse.shelfFreq !? { fileParse.shelfFreq.asFloat };
}, { // txt file provided, no fileParse
dirChannels = (this.matrix.rows).collect({ \unspecified });
});
}
}
//-----------------------------------------------------------------------
// martrix encoders
FoaEncoderMatrix : FoaMatrix {
*newAtoB { |orientation = \flu, weight = \dec|
^super.new(\AtoB).loadFromLib(orientation, weight)
}
*newHoa1 { |ordering = \acn, normalisation = \n3d|
^super.new(\hoa1).loadFromLib(ordering, normalisation);
}
*newAmbix1 {
var ordering = \acn, normalisation = \sn3d;
^super.new(\hoa1).loadFromLib(ordering, normalisation);
}
*newZoomH2n {
var ordering = \acn, normalisation = \sn3d;
^super.new(\hoa1).loadFromLib(ordering, normalisation);
}
*newOmni {
^super.new(\omni).loadFromLib;
}
*newDirection { |theta = 0, phi = 0|
^super.new(\dir).initDirection(theta, phi);
}
*newStereo { |angle = 0|
^super.new(\stereo).initStereo(angle);
}
*newQuad {
^super.new(\quad).loadFromLib;
}
*new5_0 {
^super.new('5_0').loadFromLib;
}
*new7_0 {
^super.new('7_0').loadFromLib;
}
*newDirections { |directions, pattern = nil|
^super.new(\dirs).initDirections(directions, pattern);
}
*newPanto { |numChans = 4, orientation = \flat|
^super.new(\panto).initPanto(numChans, orientation);
}
*newPeri { |numChanPairs = 4, elevation = 0.61547970867039, orientation = \flat|
^super.new(\peri).initPeri(numChanPairs, elevation, orientation);
}
*newZoomH2 { |angles = ([pi / 3, 3 / 4 * pi]), pattern = 0.5857, k = 1|
^super.new(\zoomH2).initZoomH2(angles, pattern, k);
}
*newFromFile { |filePathOrName|
^super.new.initFromFile(filePathOrName, \encoder, true).initEncoderVarsForFiles
}
init2D {
var g0 = 2.sqrt.reciprocal;
// build encoder matrix, and set for instance
matrix = Matrix.newClear(3, dirChannels.size); // start w/ empty matrix
dirChannels.do({ |theta, i|
matrix.putCol(i, [
g0,
theta.cos,
theta.sin
])
})
}
init3D {
var g0 = 2.sqrt.reciprocal;
// build encoder matrix, and set for instance
matrix = Matrix.newClear(4, dirChannels.size); // start w/ empty matrix
dirChannels.do({ |thetaPhi, i|
matrix.putCol(i, [
g0,
thetaPhi[1].cos * thetaPhi[0].cos,
thetaPhi[1].cos * thetaPhi[0].sin,
thetaPhi[1].sin
])
})
}
initInv2D { |pattern|
var g0 = 2.sqrt.reciprocal;
// build 'decoder' matrix, and set for instance
matrix = Matrix.newClear(dirChannels.size, 3); // start w/ empty matrix
if(pattern.isArray, {
dirChannels.do({ |theta, i| // mic positions, indivd patterns
matrix.putRow(i, [
(1.0 - pattern[i]),
pattern[i] * theta.cos,
pattern[i] * theta.sin
])
})
}, {
dirChannels.do({ |theta, i| // mic positions
matrix.putRow(i, [
(1.0 - pattern),
pattern * theta.cos,
pattern * theta.sin
])
})
});
// invert to encoder matrix
matrix = matrix.pseudoInverse;
// normalise matrix
matrix = matrix * matrix.getRow(0).sum.reciprocal;
// scale W
matrix = matrix.putRow(0, matrix.getRow(0) * g0);
}
initInv3D { |pattern|
var g0 = 2.sqrt.reciprocal;
// build 'decoder' matrix, and set for instance
matrix = Matrix.newClear(dirChannels.size, 4); // start w/ empty matrix
if(pattern.isArray, {