Debian Codegraph @

tests/SF2.py

raw
1 #!/usr/bin/python
2 #
3 # Project: lib Instrument Patch Python testing suite
4 # File: SF2.py
5 # Descr: SoundFont tests
6 # Author: Element Green <[email protected]>
7 # Date: 2016-07-01
8 # License: Public Domain
9 #
10 import Test
11 import gi
12 import ctypes
13 import math
14 import sys
15 import os
16
17 from gi.repository import GObject
18
19 gi.require_version ('Ipatch', '1.1')
20 from gi.repository import Ipatch
21
22 # Sample audio format (native SoundFont 16 bit mono signed little endian byte order audio)
23 SAMPLE_FORMAT = Ipatch.SampleWidth.BIT16 | Ipatch.SampleChannel.MONO | Ipatch.SampleSign.SIGNED | Ipatch.SampleEndian.LENDIAN
24
25 # Format used for writing sample data (converted from this format)
26 ACCESS_FORMAT = Ipatch.SampleWidth.FLOAT | Ipatch.SampleChannel.MONO | Ipatch.SampleSign.SIGNED
27 SAMPLE_RATE = 48000 # Sample rate
28 SAMPLE_LOOP_PADDING = 4 # Number of samples before and after the sample loop
29 TEST_SF2_FILENAME = os.path.join (Test.TEST_DATA_PATH, 'test.sf2')
30
31 # Set sample access format endian byte order depending on host system
32 ACCESS_FORMAT |= Ipatch.SampleEndian.BENDIAN if sys.byteorder == 'big' else Ipatch.SampleEndian.LENDIAN
33
34 def SineWave (periodPos):
35 """Sine waveform generation function"""
36 return math.sin (periodPos * 2 * math.pi)
37
38 def SawWave (periodPos):
39 """Triangle waveform generation function"""
40 if (periodPos <= 0.25): return periodPos / 0.25
41 elif (periodPos <= 0.75): return (0.75 - periodPos) * 4.0 - 1.0
42 else: return (1.0 - periodPos) * -4.0
43
44 def SquareWave (periodPos):
45 """Square waveform generation function"""
46 return 1.0 if periodPos <= 0.5 else 0.0
47
48 def sampleDataGen (freq, mathfunc):
49 """Raw sample data generator"""
50
51 period = float (SAMPLE_RATE) / freq
52
53 start = int (math.floor (period - SAMPLE_LOOP_PADDING))
54 end = int (math.ceil (2 * period + SAMPLE_LOOP_PADDING))
55 size = end - start
56
57 buf = (ctypes.c_float * size)()
58
59 # Generate a single period of the waveform, including loop padding
60 for i in xrange (0, size):
61 periodPos = math.fmod (start + i, period) / period
62 buf[i] = mathfunc (periodPos)
63
64 return bytearray (buf)
65
66 def createSF2Sample (floatData):
67 """Generate sample data object"""
68
69 sampleSize = len (floatData) / 4
70
71 # Create RAM sample store then set format, rate, and size
72 store = Ipatch.SampleStoreRam ()
73 store.set_properties (sample_format=SAMPLE_FORMAT, sample_rate=SAMPLE_RATE, sample_size=sampleSize)
74
75 # Open a handle to the sample store and write the waveform floating point data to it
76 retval, handle = store.handle_open ('w', ACCESS_FORMAT, 0)
77 handle.write (0, floatData) # 0 is the position to write to (start of sample)
78 handle.close ()
79
80 # Create sample data object and add sample store to it
81 sampleData = Ipatch.SampleData ()
82 sampleData.add (store)
83
84 # Create SF2Sample and add sample data to it
85 sf2Sample = Ipatch.SF2Sample ()
86 sf2Sample.set_data (sampleData)
87
88 loopStart = SAMPLE_LOOP_PADDING
89 loopEnd = sampleSize - SAMPLE_LOOP_PADDING - 1
90
91 # Calculate root note and fine tune based on loop length for a single waveform
92 notecents = Ipatch.unit_hertz_to_cents (float (SAMPLE_RATE) / (loopEnd - loopStart))
93 cents = math.fmod (notecents, 100.0)
94
95 # Fine tune offset corrects for inaccuracy of a single digital waveform
96 if cents <= 50.0:
97 rootNote = int (notecents / 100.0)
98 fineTune = -int (round (cents))
99 else:
100 rootNote = int (notecents / 100.0) + 1
101 fineTune = int (round (100.0 - cents))
102
103 sf2Sample.set_properties (sample_rate=SAMPLE_RATE, loop_start=loopStart, loop_end=loopEnd,
104 root_note=rootNote, fine_tune=fineTune)
105 return sf2Sample
106
107 def addSF2Preset (sf2, name, midiProgram, sampleMathFunc):
108 """Create a SoundFont preset, with an instrument, and containing several generated samples"""
109
110 # Create a SF2 preset object, set its MIDI bank and program numbers (MIDI locale), and add it to the SF2 object
111 preset = Ipatch.SF2Preset ()
112 preset.set_name (name)
113 preset.set_midi_locale (0, midiProgram)
114 sf2.add (preset)
115
116 # Create a SF2 instrument object and add it to the SF2 object
117 inst = Ipatch.SF2Inst ()
118 inst.set_name (name)
119 sf2.add (inst)
120 preset.new_zone (inst) # Create new preset zone and add instrument to it
121
122 # Create 2 modulators to disable the default pitch modulation control and modulate the filter cutoff instead
123 mod = Ipatch.SF2Mod ()
124 mod.src = 1 | Ipatch.SF2ModControlPalette.MIDI | Ipatch.SF2ModDirection.POSITIVE \
125 | Ipatch.SF2ModPolarity.UNIPOLAR | Ipatch.SF2ModType.LINEAR
126 mod.dest = Ipatch.SF2GenType.VIB_LFO_TO_PITCH
127 mod.amount = 0
128 mod.amtsrc = 0
129 mod.trans = Ipatch.SF2ModTransform.LINEAR
130
131 modlist = [mod] # Create modulator list
132
133 mod = Ipatch.SF2Mod ()
134 mod.src = 1 | Ipatch.SF2ModControlPalette.MIDI | Ipatch.SF2ModDirection.POSITIVE \
135 | Ipatch.SF2ModPolarity.UNIPOLAR | Ipatch.SF2ModType.LINEAR
136 mod.dest = Ipatch.SF2GenType.MOD_LFO_TO_FILTER_CUTOFF
137 mod.amount = 2400
138 mod.amtsrc = 0
139 mod.trans = Ipatch.SF2ModTransform.LINEAR
140
141 modlist.append (mod) # Append 2nd modulator to list
142
143 # Set instrument global modulators to modulator list
144 inst.set_mods (modlist)
145
146 # Create A note samples for octaves A0 through A6 (7 octaves) and add to instrument zones
147 for octave in xrange (0, 7):
148 note = 33 + octave * 12 # MIDI note 33 is A0
149 sample = createSF2Sample (sampleDataGen (Ipatch.unit_cents_to_hertz (note * 100), sampleMathFunc))
150 sample.set_name ('%s A%d' % (name, octave))
151 sf2.append (sample) # Add sample to SF2 base object
152
153 # Create instrument zone
154 izone = Ipatch.SF2IZone ()
155 inst.add (izone)
156
157 izone.set_sample (sample) # Assign the sample to the zone
158
159 # Calculate optimal note ranges for samples
160 start = note - 5 if octave > 0 else 0
161 end = note + 6 if octave < 6 else 127
162
163 izone.set_properties (loop_type=Ipatch.SampleLoopType.STANDARD, # Enable looping
164 note_range=Ipatch.Range.new (start, end)) # Create range and assign to note range
165
166 def createSF2 ():
167 """Create SoundFont object"""
168
169 # Create SoundFont object, a file object, and assign it
170 sf2 = Ipatch.SF2 ()
171 sf2.props.name = "Test SoundFont"
172 sf2.props.author = "Robo Python 3000+"
173 sf2.props.comment = """This is a test SoundFont generated by the Instrument Patch library Python binding.
174 One should find 3 different presets for Sine, Saw, and Square waves with 7 samples each.
175 Enjoy!"""
176
177 sf2File = Ipatch.SF2File ()
178 sf2File.set_name (TEST_SF2_FILENAME)
179 sf2.set_file (sf2File)
180
181 # Add presets for sine, saw, and square waves
182 addSF2Preset (sf2, "Sine", 0, SineWave)
183 addSF2Preset (sf2, "Saw", 1, SawWave)
184 addSF2Preset (sf2, "Square", 2, SquareWave)
185
186 return sf2
187
188
189 # Main
190 if __name__ == "__main__":
191 parser = Test.createArgParser ('libInstPatch SoundFont tests')
192 parser.add_argument ('-n', '--nodelete', action='store_true', help="Don't delete created test SoundFont (%s)" % TEST_SF2_FILENAME)
193 args = Test.parseArgs (parser)
194
195 Ipatch.init ()
196
197 Test.msg ("Creating SoundFont")
198 sf2 = createSF2 ()
199
200 Test.msg ("Saving SoundFont")
201 sf2.save ()
202
203 Test.msg ("Loading SoundFont")
204 sf2file = Ipatch.SF2File ()
205 sf2file.set_property ('file-name', TEST_SF2_FILENAME)
206 cmpsf2 = Ipatch.convert_object_to_type (sf2file, Ipatch.SF2)
207
208 blacklistProps = {
209 (Ipatch.SF2, "software"), # SF2 software will include the loaded software version appended
210 (Ipatch.SF2File, "sample-size") # Sample size is the total sample data in the SoundFont file which will differ
211 }
212
213 # Clear changed and saved flags so they don't trigger a value mismatch
214 sf2.clear_flags (Ipatch.BaseFlags.CHANGED | Ipatch.BaseFlags.SAVED)
215 cmpsf2.clear_flags (Ipatch.BaseFlags.CHANGED | Ipatch.BaseFlags.SAVED)
216
217 Test.msg ("Verifying SoundFont")
218 Test.compareItems (sf2, cmpsf2, blackList=blacklistProps)
219
220 if not args.nodelete:
221 os.unlink (TEST_SF2_FILENAME)
222
223 Test.exit ()
224