-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathziggysynth.zig
4262 lines (3457 loc) · 146 KB
/
ziggysynth.zig
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
const std = @import("std");
const math = std.math;
const mem = std.mem;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap;
const ZiggySynthError = error{
InvalidSoundFont,
InvalidMidiFile,
SampleRateIsOutOfRange,
BlockSizeIsOutOfRange,
MaximumPolyphonyIsOutOfRange,
Unexpected,
};
const ArrayMath = struct {
fn multiplyAdd(a: f32, x: []f32, destination: []f32) void {
for (x, destination) |value, *dst| {
dst.* += a * value;
}
}
fn multiplyAddSlope(a: f32, step: f32, x: []f32, destination: []f32) void {
var slope = a;
for (x, destination) |value, *dst| {
dst.* += slope * value;
slope += step;
}
}
};
const BinaryReader = struct {
fn read(comptime T: type, reader: anytype) !T {
var data: [@sizeOf(T)]u8 = undefined;
_ = try reader.readNoEof(&data);
return @bitCast(data);
}
fn readBigEndian(comptime T: type, reader: anytype) !T {
var data: [@sizeOf(T)]u8 = undefined;
_ = try reader.readNoEof(&data);
return @byteSwap(@as(T, @bitCast(data)));
}
fn readIntVariableLength(reader: anytype) !i32 {
var acc: i32 = 0;
var count: i32 = 0;
while (true) {
const value: i32 = @intCast(try BinaryReader.read(u8, reader));
acc = (acc << 7) | (value & 127);
if ((value & 128) == 0) {
break;
}
count += 1;
if (count == 4) {
return ZiggySynthError.Unexpected;
}
}
return acc;
}
};
fn ReadCounter(comptime T: type) type {
return struct {
const Self = @This();
reader: T,
count: usize,
fn init(reader: T) Self {
return Self{
.reader = reader,
.count = 0,
};
}
fn readNoEof(self: *Self, buf: []u8) !void {
try self.reader.readNoEof(buf);
self.count += buf.len;
}
fn skipBytes(self: *Self, num_bytes: u64, options: anytype) !void {
try self.reader.skipBytes(num_bytes, options);
self.count += @intCast(num_bytes);
}
};
}
pub const SoundFont = struct {
const Self = @This();
allocator: Allocator,
wave_data: []i16,
sample_headers: []SampleHeader,
presets: []Preset,
preset_regions: []PresetRegion,
instruments: []Instrument,
instrument_regions: []InstrumentRegion,
pub fn init(allocator: Allocator, reader: anytype) !Self {
var wave_data: ?[]i16 = null;
var sample_headers: ?[]SampleHeader = null;
var presets: ?[]Preset = null;
var preset_regions: ?[]PresetRegion = null;
var instruments: ?[]Instrument = null;
var instrument_regions: ?[]InstrumentRegion = null;
errdefer {
if (wave_data) |value| allocator.free(value);
if (sample_headers) |value| allocator.free(value);
if (presets) |value| allocator.free(value);
if (preset_regions) |value| allocator.free(value);
if (instruments) |value| allocator.free(value);
if (instrument_regions) |value| allocator.free(value);
}
const chunk_id = try BinaryReader.read([4]u8, reader);
if (!mem.eql(u8, &chunk_id, "RIFF")) {
return ZiggySynthError.InvalidSoundFont;
}
_ = try BinaryReader.read(u32, reader);
const form_type = try BinaryReader.read([4]u8, reader);
if (!mem.eql(u8, &form_type, "sfbk")) {
return ZiggySynthError.InvalidSoundFont;
}
try SoundFont.skipInfo(reader);
const sampleData = try SoundFontSampleData.init(allocator, reader);
wave_data = sampleData.wave_data;
const parameters = try SoundFontParameters.init(allocator, reader);
sample_headers = parameters.sample_headers;
presets = parameters.presets;
preset_regions = parameters.preset_regions;
instruments = parameters.instruments;
instrument_regions = parameters.instrument_regions;
return Self{
.allocator = allocator,
.wave_data = wave_data.?,
.sample_headers = sample_headers.?,
.presets = presets.?,
.preset_regions = preset_regions.?,
.instruments = instruments.?,
.instrument_regions = instrument_regions.?,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.wave_data);
self.allocator.free(self.sample_headers);
self.allocator.free(self.presets);
self.allocator.free(self.preset_regions);
self.allocator.free(self.instruments);
self.allocator.free(self.instrument_regions);
}
fn skipInfo(reader: anytype) !void {
const chunk_id = try BinaryReader.read([4]u8, reader);
if (!mem.eql(u8, &chunk_id, "LIST")) {
return ZiggySynthError.InvalidSoundFont;
}
const size = try BinaryReader.read(u32, reader);
try reader.skipBytes(size, .{});
}
};
const SoundFontSampleData = struct {
const Self = @This();
bits_per_sample: i32,
wave_data: []i16,
fn init(allocator: Allocator, reader: anytype) !Self {
var wave_data: ?[]i16 = null;
errdefer {
if (wave_data) |value| allocator.free(value);
}
const chunk_id = try BinaryReader.read([4]u8, reader);
if (!mem.eql(u8, &chunk_id, "LIST")) {
return ZiggySynthError.InvalidSoundFont;
}
const end = try BinaryReader.read(u32, reader);
var rc = ReadCounter(@TypeOf(reader)).init(reader);
const list_type = try BinaryReader.read([4]u8, &rc);
if (!mem.eql(u8, &list_type, "sdta")) {
return ZiggySynthError.InvalidSoundFont;
}
while (rc.count < end) {
const id = try BinaryReader.read([4]u8, &rc);
const size = try BinaryReader.read(u32, &rc);
if (mem.eql(u8, &id, "smpl")) {
wave_data = try allocator.alloc(i16, size / 2);
try rc.readNoEof(@as([*]u8, @ptrCast(wave_data.?.ptr))[0..size]);
} else if (mem.eql(u8, &id, "sm24")) {
try rc.skipBytes(size, .{});
} else {
return ZiggySynthError.InvalidSoundFont;
}
}
_ = wave_data orelse return ZiggySynthError.InvalidSoundFont;
return Self{
.bits_per_sample = 16,
.wave_data = wave_data.?,
};
}
};
const SoundFontParameters = struct {
const Self = @This();
sample_headers: []SampleHeader,
presets: []Preset,
preset_regions: []PresetRegion,
instruments: []Instrument,
instrument_regions: []InstrumentRegion,
fn init(allocator: Allocator, reader: anytype) !Self {
var preset_infos: ?[]PresetInfo = null;
var preset_bag: ?[]ZoneInfo = null;
var preset_generators: ?[]Generator = null;
var instrument_infos: ?[]InstrumentInfo = null;
var instrument_bag: ?[]ZoneInfo = null;
var instrument_generators: ?[]Generator = null;
var sample_headers: ?[]SampleHeader = null;
defer {
if (preset_infos) |value| allocator.free(value);
if (preset_bag) |value| allocator.free(value);
if (preset_generators) |value| allocator.free(value);
if (instrument_infos) |value| allocator.free(value);
if (instrument_bag) |value| allocator.free(value);
if (instrument_generators) |value| allocator.free(value);
}
errdefer {
if (sample_headers) |value| allocator.free(value);
}
const chunk_id = try BinaryReader.read([4]u8, reader);
if (!mem.eql(u8, &chunk_id, "LIST")) {
return ZiggySynthError.InvalidSoundFont;
}
const end = try BinaryReader.read(u32, reader);
var rc = ReadCounter(@TypeOf(reader)).init(reader);
const list_type = try BinaryReader.read([4]u8, &rc);
if (!mem.eql(u8, &list_type, "pdta")) {
return ZiggySynthError.InvalidSoundFont;
}
while (rc.count < end) {
const id = try BinaryReader.read([4]u8, &rc);
const size = try BinaryReader.read(u32, &rc);
if (mem.eql(u8, &id, "phdr")) {
preset_infos = try PresetInfo.readFromChunk(allocator, &rc, size);
} else if (mem.eql(u8, &id, "pbag")) {
preset_bag = try ZoneInfo.readFromChunk(allocator, &rc, size);
} else if (mem.eql(u8, &id, "pmod")) {
try rc.skipBytes(size, .{});
} else if (mem.eql(u8, &id, "pgen")) {
preset_generators = try Generator.readFromChunk(allocator, &rc, size);
} else if (mem.eql(u8, &id, "inst")) {
instrument_infos = try InstrumentInfo.readFromChunk(allocator, &rc, size);
} else if (mem.eql(u8, &id, "ibag")) {
instrument_bag = try ZoneInfo.readFromChunk(allocator, &rc, size);
} else if (mem.eql(u8, &id, "imod")) {
try rc.skipBytes(size, .{});
} else if (mem.eql(u8, &id, "igen")) {
instrument_generators = try Generator.readFromChunk(allocator, &rc, size);
} else if (mem.eql(u8, &id, "shdr")) {
sample_headers = try SampleHeader.readFromChunk(allocator, &rc, size);
} else {
return ZiggySynthError.InvalidSoundFont;
}
}
_ = preset_infos orelse return ZiggySynthError.InvalidSoundFont;
_ = preset_bag orelse return ZiggySynthError.InvalidSoundFont;
_ = preset_generators orelse return ZiggySynthError.InvalidSoundFont;
_ = instrument_infos orelse return ZiggySynthError.InvalidSoundFont;
_ = instrument_bag orelse return ZiggySynthError.InvalidSoundFont;
_ = instrument_generators orelse return ZiggySynthError.InvalidSoundFont;
_ = sample_headers orelse return ZiggySynthError.InvalidSoundFont;
const instrument_zones = try Zone.create(allocator, instrument_bag.?, instrument_generators.?);
defer allocator.free(instrument_zones);
const instrument_regions = try InstrumentRegion.create(allocator, instrument_infos.?, instrument_zones, sample_headers.?);
errdefer allocator.free(instrument_regions);
const instruments = try Instrument.create(allocator, instrument_infos.?, instrument_zones, instrument_regions);
errdefer allocator.free(instruments);
const preset_zones = try Zone.create(allocator, preset_bag.?, preset_generators.?);
defer allocator.free(preset_zones);
const preset_regions = try PresetRegion.create(allocator, preset_infos.?, preset_zones, instruments);
errdefer allocator.free(preset_regions);
const presets = try Preset.create(allocator, preset_infos.?, preset_zones, preset_regions);
errdefer allocator.free(presets);
return Self{
.sample_headers = sample_headers.?,
.presets = presets,
.preset_regions = preset_regions,
.instruments = instruments,
.instrument_regions = instrument_regions,
};
}
};
const SoundFontMath = struct {
const HALF_PI: f32 = math.pi / 2.0;
const NON_AUDIBLE: f32 = 1.0E-3;
const LOG_NON_AUDIBLE: f32 = @log(1.0E-3);
fn clamp(value: f32, min: f32, max: f32) f32 {
if (value < min) {
return min;
} else if (value > max) {
return max;
} else {
return value;
}
}
fn timecentsToSeconds(x: f32) f32 {
return math.pow(f32, 2.0, (1.0 / 1200.0) * x);
}
fn centsToHertz(x: f32) f32 {
return 8.176 * math.pow(f32, 2.0, (1.0 / 1200.0) * x);
}
fn centsToMultiplyingFactor(x: f32) f32 {
return math.pow(f32, 2.0, (1.0 / 1200.0) * x);
}
fn decibelsToLinear(x: f32) f32 {
return math.pow(f32, 10.0, 0.05 * x);
}
fn linearToDecibels(x: f32) f32 {
return 20.0 * @log10(x);
}
fn keyNumberToMultiplyingFactor(cents: i32, key: i32) f32 {
return timecentsToSeconds(@floatFromInt(cents * (60 - key)));
}
fn expCutoff(x: f64) f64 {
if (x < SoundFontMath.LOG_NON_AUDIBLE) {
return 0.0;
} else {
return @exp(x);
}
}
};
const Generator = struct {
const Self = @This();
generator_type: u16,
value: i16,
fn init(reader: anytype) !Self {
const generator_type = try BinaryReader.read(u16, reader);
const value = try BinaryReader.read(i16, reader);
return Self{
.generator_type = generator_type,
.value = value,
};
}
fn readFromChunk(allocator: Allocator, reader: anytype, size: usize) ![]Self {
if (size % 4 != 0) {
return ZiggySynthError.InvalidSoundFont;
}
const count = size / 4 - 1;
var generators = try allocator.alloc(Self, count);
errdefer allocator.free(generators);
for (0..count) |i| {
generators[i] = try Generator.init(reader);
}
// The last one is the terminator.
_ = try Generator.init(reader);
return generators;
}
};
const GeneratorType = struct {
const START_ADDRESS_OFFSET: u16 = 0;
const END_ADDRESS_OFFSET: u16 = 1;
const START_LOOP_ADDRESS_OFFSET: u16 = 2;
const END_LOOP_ADDRESS_OFFSET: u16 = 3;
const START_ADDRESS_COARSE_OFFSET: u16 = 4;
const MODULATION_LFO_TO_PITCH: u16 = 5;
const VIBRATO_LFO_TO_PITCH: u16 = 6;
const MODULATION_ENVELOPE_TO_PITCH: u16 = 7;
const INITIAL_FILTER_CUTOFF_FREQUENCY: u16 = 8;
const INITIAL_FILTER_Q: u16 = 9;
const MODULATION_LFO_TO_FILTER_CUTOFF_FREQUENCY: u16 = 10;
const MODULATION_ENVELOPE_TO_FILTER_CUTOFF_FREQUENCY: u16 = 11;
const END_ADDRESS_COARSE_OFFSET: u16 = 12;
const MODULATION_LFO_TO_VOLUME: u16 = 13;
const UNUSED_1: u16 = 14;
const CHORUS_EFFECTS_SEND: u16 = 15;
const REVERB_EFFECTS_SEND: u16 = 16;
const PAN: u16 = 17;
const UNUSED_2: u16 = 18;
const UNUSED_3: u16 = 19;
const UNUSED_4: u16 = 20;
const DELAY_MODULATION_LFO: u16 = 21;
const FREQUENCY_MODULATION_LFO: u16 = 22;
const DELAY_VIBRATO_LFO: u16 = 23;
const FREQUENCY_VIBRATO_LFO: u16 = 24;
const DELAY_MODULATION_ENVELOPE: u16 = 25;
const ATTACK_MODULATION_ENVELOPE: u16 = 26;
const HOLD_MODULATION_ENVELOPE: u16 = 27;
const DECAY_MODULATION_ENVELOPE: u16 = 28;
const SUSTAIN_MODULATION_ENVELOPE: u16 = 29;
const RELEASE_MODULATION_ENVELOPE: u16 = 30;
const KEY_NUMBER_TO_MODULATION_ENVELOPE_HOLD: u16 = 31;
const KEY_NUMBER_TO_MODULATION_ENVELOPE_DECAY: u16 = 32;
const DELAY_VOLUME_ENVELOPE: u16 = 33;
const ATTACK_VOLUME_ENVELOPE: u16 = 34;
const HOLD_VOLUME_ENVELOPE: u16 = 35;
const DECAY_VOLUME_ENVELOPE: u16 = 36;
const SUSTAIN_VOLUME_ENVELOPE: u16 = 37;
const RELEASE_VOLUME_ENVELOPE: u16 = 38;
const KEY_NUMBER_TO_VOLUME_ENVELOPE_HOLD: u16 = 39;
const KEY_NUMBER_TO_VOLUME_ENVELOPE_DECAY: u16 = 40;
const INSTRUMENT: u16 = 41;
const RESERVED_1: u16 = 42;
const KEY_RANGE: u16 = 43;
const VELOCITY_RANGE: u16 = 44;
const START_LOOP_ADDRESS_COARSE_OFFSET: u16 = 45;
const KEY_NUMBER: u16 = 46;
const VELOCITY: u16 = 47;
const INITIAL_ATTENUATION: u16 = 48;
const RESERVED_2: u16 = 49;
const END_LOOP_ADDRESS_COARSE_OFFSET: u16 = 50;
const COARSE_TUNE: u16 = 51;
const FINE_TUNE: u16 = 52;
const SAMPLE_ID: u16 = 53;
const SAMPLE_MODES: u16 = 54;
const RESERVED_3: u16 = 55;
const SCALE_TUNING: u16 = 56;
const EXCLUSIVE_CLASS: u16 = 57;
const OVERRIDING_ROOT_KEY: u16 = 58;
const UNUSED_5: u16 = 59;
const UNUSED_END: u16 = 60;
const COUNT: usize = 61;
};
const Zone = struct {
const Self = @This();
const empty_generators: [0]Generator = .{};
generators: []Generator,
fn empty() Self {
return Self{
.generators = &empty_generators,
};
}
fn init(info: *ZoneInfo, generators: []Generator) Self {
const start = info.generator_index;
const end = start + info.generator_count;
const segment = generators[start..end];
return Self{
.generators = segment,
};
}
fn create(allocator: Allocator, infos: []ZoneInfo, generators: []Generator) ![]Self {
if (infos.len <= 1) {
return ZiggySynthError.InvalidSoundFont;
}
// The last one is the terminator.
const count = infos.len - 1;
var zones = try allocator.alloc(Self, count);
errdefer allocator.free(zones);
for (0..count) |i| {
zones[i] = Zone.init(&infos[i], generators);
}
return zones;
}
};
const ZoneInfo = struct {
const Self = @This();
generator_index: usize,
modulator_index: usize,
generator_count: usize,
modulator_count: usize,
fn init(reader: anytype) !Self {
const generator_index = try BinaryReader.read(u16, reader);
const modulator_index = try BinaryReader.read(u16, reader);
return Self{
.generator_index = generator_index,
.modulator_index = modulator_index,
.generator_count = 0,
.modulator_count = 0,
};
}
fn readFromChunk(allocator: Allocator, reader: anytype, size: usize) ![]Self {
if (size % 4 != 0) {
return ZiggySynthError.InvalidSoundFont;
}
const count = size / 4;
var zones = try allocator.alloc(Self, count);
errdefer allocator.free(zones);
for (0..count) |i| {
zones[i] = try ZoneInfo.init(reader);
}
for (0..count - 1) |i| {
zones[i].generator_count = zones[i + 1].generator_index - zones[i].generator_index;
zones[i].modulator_count = zones[i + 1].modulator_index - zones[i].modulator_index;
}
return zones;
}
};
pub const Preset = struct {
const Self = @This();
name: [20]u8,
patch_number: i32,
bank_number: i32,
regions: []PresetRegion,
fn init(info: *const PresetInfo, regions: []PresetRegion) Self {
return Self{
.name = info.name,
.patch_number = info.patch_number,
.bank_number = info.bank_number,
.regions = regions,
};
}
fn create(allocator: Allocator, infos: []PresetInfo, all_zones: []Zone, all_regions: []PresetRegion) ![]Self {
// The last one is the terminator.
const preset_count = infos.len - 1;
var presets = try allocator.alloc(Self, preset_count);
errdefer allocator.free(presets);
var region_index: usize = 0;
for (0..preset_count) |preset_index| {
const info = infos[preset_index];
const zones = all_zones[info.zone_start_index..info.zone_end_index];
var region_count: usize = undefined;
// Is the first one the global zone?
if (PresetRegion.containsGlobalZone(zones)) {
// The first one is the global zone.
region_count = zones.len - 1;
} else {
// No global zone.
region_count = zones.len;
}
const region_end = region_index + region_count;
presets[preset_index] = Preset.init(&info, all_regions[region_index..region_end]);
region_index += region_count;
}
if (region_index != all_regions.len) {
return ZiggySynthError.Unexpected;
}
return presets;
}
fn getPatchNumber(self: *const Self) i32 {
return self.patch_number;
}
fn getBankNumber(self: *const Self) i32 {
return self.bank_number;
}
};
pub const PresetRegion = struct {
const Self = @This();
instrument: *Instrument,
gs: [GeneratorType.COUNT]i16,
fn containsGlobalZone(zones: []Zone) bool {
if (zones[0].generators.len == 0) {
return true;
}
if (zones[0].generators[zones[0].generators.len - 1].generator_type != GeneratorType.INSTRUMENT) {
return true;
}
return false;
}
fn countRegions(infos: []PresetInfo, all_zones: []Zone) usize {
// The last one is the terminator.
const preset_count = infos.len - 1;
var sum: usize = 0;
for (0..preset_count) |preset_index| {
const info = infos[preset_index];
const zones = all_zones[info.zone_start_index..info.zone_end_index];
// Is the first one the global zone?
if (PresetRegion.containsGlobalZone(zones)) {
// The first one is the global zone.
sum += zones.len - 1;
} else {
// No global zone.
sum += zones.len;
}
}
return sum;
}
fn setParameter(gs: *[GeneratorType.COUNT]i16, generator: *const Generator) void {
const index = generator.generator_type;
// Unknown generators should be ignored.
if (index < gs.len) {
gs[index] = generator.value;
}
}
fn init(global: *const Zone, local: *const Zone, instruments: []Instrument) !Self {
var gs = mem.zeroes([GeneratorType.COUNT]i16);
gs[GeneratorType.KEY_RANGE] = 0x7F00;
gs[GeneratorType.VELOCITY_RANGE] = 0x7F00;
for (global.generators) |value| {
setParameter(&gs, &value);
}
for (local.generators) |value| {
setParameter(&gs, &value);
}
const id: usize = @intCast(gs[GeneratorType.INSTRUMENT]);
if (id >= instruments.len) {
return ZiggySynthError.InvalidSoundFont;
}
const instrument = &instruments[id];
return Self{
.instrument = instrument,
.gs = gs,
};
}
fn create(allocator: Allocator, infos: []PresetInfo, all_zones: []Zone, instruments: []Instrument) ![]Self {
// The last one is the terminator.
const preset_count = infos.len - 1;
var regions = try allocator.alloc(Self, PresetRegion.countRegions(infos, all_zones));
errdefer allocator.free(regions);
var region_index: usize = 0;
for (0..preset_count) |preset_index| {
const info = infos[preset_index];
const zones = all_zones[info.zone_start_index..info.zone_end_index];
// Is the first one the global zone?
if (PresetRegion.containsGlobalZone(zones)) {
// The first one is the global zone.
for (0..zones.len - 1) |i| {
regions[region_index] = try PresetRegion.init(&zones[0], &zones[i + 1], instruments);
region_index += 1;
}
} else {
// No global zone.
for (0..zones.len) |i| {
regions[region_index] = try PresetRegion.init(&Zone.empty(), &zones[i], instruments);
region_index += 1;
}
}
}
if (region_index != regions.len) {
return ZiggySynthError.Unexpected;
}
return regions;
}
pub fn contains(self: *const Self, key: i32, velocity: i32) bool {
const contains_key = self.getKeyRangeStart() <= key and key <= self.getKeyRangeEnd();
const contains_velocity = self.getVelocityRangeStart() <= velocity and velocity <= self.getVelocityRangeEnd();
return contains_key and contains_velocity;
}
pub fn getModulationLfoToPitch(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.MODULATION_LFO_TO_PITCH]));
}
pub fn getVibratoLfoToPitch(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.VIBRATO_LFO_TO_PITCH]));
}
pub fn getModulationEnvelopeToPitch(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.MODULATION_ENVELOPE_TO_PITCH]));
}
pub fn getInitialFilterCutoffFrequency(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.INITIAL_FILTER_CUTOFF_FREQUENCY])));
}
pub fn getInitialFilterQ(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.INITIAL_FILTER_Q]));
}
pub fn getModulationLfoToFilterCutoffFrequency(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.MODULATION_LFO_TO_FILTER_CUTOFF_FREQUENCY]));
}
pub fn getModulationEnvelopeToFilterCutoffFrequency(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.MODULATION_ENVELOPE_TO_FILTER_CUTOFF_FREQUENCY]));
}
pub fn getModulationLfoToVolume(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.MODULATION_LFO_TO_VOLUME]));
}
pub fn getChorusEffectsSend(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.CHORUS_EFFECTS_SEND]));
}
pub fn getReverbEffectsSend(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.REVERB_EFFECTS_SEND]));
}
pub fn getPan(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.PAN]));
}
pub fn getDelayModulationLfo(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.DELAY_MODULATION_LFO])));
}
pub fn getFrequencyModulationLfo(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.FREQUENCY_MODULATION_LFO])));
}
pub fn getDelayVibratoLfo(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.DELAY_VIBRATO_LFO])));
}
pub fn getFrequencyVibratoLfo(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.FREQUENCY_VIBRATO_LFO])));
}
pub fn getDelayModulationEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.DELAY_MODULATION_ENVELOPE])));
}
pub fn getAttackModulationEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.ATTACK_MODULATION_ENVELOPE])));
}
pub fn getHoldModulationEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.HOLD_MODULATION_ENVELOPE])));
}
pub fn getDecayModulationEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.DECAY_MODULATION_ENVELOPE])));
}
pub fn getSustainModulationEnvelope(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.SUSTAIN_MODULATION_ENVELOPE]));
}
pub fn getReleaseModulationEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.RELEASE_MODULATION_ENVELOPE])));
}
pub fn getKeyNumberToModulationEnvelopeHold(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.KEY_NUMBER_TO_MODULATION_ENVELOPE_HOLD]));
}
pub fn getKeyNumberToModulationEnvelopeDecay(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.KEY_NUMBER_TO_MODULATION_ENVELOPE_DECAY]));
}
pub fn getDelayVolumeEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.DELAY_VOLUME_ENVELOPE])));
}
pub fn getAttackVolumeEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.ATTACK_VOLUME_ENVELOPE])));
}
pub fn getHoldVolumeEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.HOLD_VOLUME_ENVELOPE])));
}
pub fn getDecayVolumeEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.DECAY_VOLUME_ENVELOPE])));
}
pub fn getSustainVolumeEnvelope(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.SUSTAIN_VOLUME_ENVELOPE]));
}
pub fn getReleaseVolumeEnvelope(self: *const Self) f32 {
return SoundFontMath.centsToMultiplyingFactor(@as(f32, @floatFromInt(self.gs[GeneratorType.RELEASE_VOLUME_ENVELOPE])));
}
pub fn getKeyNumberToVolumeEnvelopeHold(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.KEY_NUMBER_TO_VOLUME_ENVELOPE_HOLD]));
}
pub fn getKeyNumberToVolumeEnvelopeDecay(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.KEY_NUMBER_TO_VOLUME_ENVELOPE_DECAY]));
}
pub fn getKeyRangeStart(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.KEY_RANGE])) & 0xFF;
}
pub fn getKeyRangeEnd(self: *const Self) i32 {
return (@as(i32, @intCast(self.gs[GeneratorType.KEY_RANGE])) >> 8) & 0xFF;
}
pub fn getVelocityRangeStart(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.VELOCITY_RANGE])) & 0xFF;
}
pub fn getVelocityRangeEnd(self: *const Self) i32 {
return (@as(i32, @intCast(self.gs[GeneratorType.VELOCITY_RANGE])) >> 8) & 0xFF;
}
pub fn getInitialAttenuation(self: *const Self) f32 {
return 0.1 * @as(f32, @floatFromInt(self.gs[GeneratorType.INITIAL_ATTENUATION]));
}
pub fn getCoarseTune(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.COARSE_TUNE]));
}
pub fn getFineTune(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.FINE_TUNE]));
}
pub fn getScaleTuning(self: *const Self) i32 {
return @as(i32, @intCast(self.gs[GeneratorType.SCALE_TUNING]));
}
};
const PresetInfo = struct {
const Self = @This();
name: [20]u8,
patch_number: i32,
bank_number: i32,
zone_start_index: usize,
zone_end_index: usize,
library: i32,
genre: i32,
morphology: i32,
fn init(reader: anytype) !Self {
const name = try BinaryReader.read([20]u8, reader);
const patch_number = try BinaryReader.read(u16, reader);
const bank_number = try BinaryReader.read(u16, reader);
const zone_start_index = try BinaryReader.read(u16, reader);
const library = try BinaryReader.read(i32, reader);
const genre = try BinaryReader.read(i32, reader);
const morphology = try BinaryReader.read(i32, reader);
return Self{
.name = name,
.patch_number = patch_number,
.bank_number = bank_number,
.zone_start_index = zone_start_index,
.zone_end_index = 0,
.library = library,
.genre = genre,
.morphology = morphology,
};
}
fn readFromChunk(allocator: Allocator, reader: anytype, size: usize) ![]Self {
if (size % 38 != 0) {
return ZiggySynthError.InvalidSoundFont;
}
const count = size / 38;
if (count <= 1) {
return ZiggySynthError.InvalidSoundFont;
}
var presets = try allocator.alloc(Self, count);
errdefer allocator.free(presets);
for (0..count) |i| {
presets[i] = try PresetInfo.init(reader);
}
for (0..count - 1) |i| {
presets[i].zone_end_index = presets[i + 1].zone_start_index;
}
return presets;
}
};
pub const Instrument = struct {
const Self = @This();
name: [20]u8,
regions: []InstrumentRegion,
fn init(name: [20]u8, regions: []InstrumentRegion) Self {
return Self{
.name = name,
.regions = regions,
};
}
fn create(allocator: Allocator, infos: []InstrumentInfo, all_zones: []Zone, all_regions: []InstrumentRegion) ![]Self {
// The last one is the terminator.
const instrument_count = infos.len - 1;
var instruments = try allocator.alloc(Self, instrument_count);
errdefer allocator.free(instruments);
var region_index: usize = 0;
for (0..instrument_count) |instrument_index| {
const info = infos[instrument_index];
const zones = all_zones[info.zone_start_index..info.zone_end_index];
var region_count: usize = undefined;
// Is the first one the global zone?
if (InstrumentRegion.containsGlobalZone(zones)) {
// The first one is the global zone.
region_count = zones.len - 1;
} else {
// No global zone.
region_count = zones.len;
}
const region_end = region_index + region_count;
instruments[instrument_index] = Instrument.init(info.name, all_regions[region_index..region_end]);
region_index += region_count;
}
if (region_index != all_regions.len) {
return ZiggySynthError.Unexpected;
}