Python synthesizer stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

373 lines
10KB

  1. """
  2. Python audio synthesis framework.
  3. """
  4. from pymod import _ysynth_init, _ysynth_init, _ysynth_set_callback
  5. from math import cos, sin, pi, modf
  6. from itertools import izip
  7. import numpy as np
  8. from scipy.signal import lfilter
  9. __all__ = ['YSynth', 'Sin', 'Cos', 'Saw', 'RevSaw', 'Square', 'Pulse']
  10. class YSynth(object):
  11. """
  12. YSynth synthesis and audio context.
  13. """
  14. def __init__(self, samplerate=44100, channels=2):
  15. """
  16. Setup a simple synthesizer.
  17. samplerate: Samples/second
  18. channels: Number of output channels.
  19. e.g. 1 for mono, 2 for stereo
  20. """
  21. self.context = _ysynth_init(samplerate, channels)
  22. self.samples = 0
  23. self.volume = 0.75
  24. # XXX need to fetch 'acquired' values from ysynth context
  25. self.samplerate = samplerate
  26. self.channels = channels
  27. self.graph = None
  28. self.set_callback(self.default_callback)
  29. def deinit(self):
  30. """
  31. Shutdown synthesizer, afterwards this object becomes useless.
  32. """
  33. if self.context:
  34. _ysynth_shutdown(self.context)
  35. self.context = None
  36. def default_callback(self, *channels):
  37. """
  38. Default synthesis callback.
  39. """
  40. # Outputs silence if no graph available
  41. if not self.graph:
  42. return
  43. # Process audio graph
  44. buf_len = len(channels[0])
  45. self.chunk_size = buf_len
  46. next_chunk = next(self.graph)
  47. for j in xrange(len(channels)):
  48. for i in xrange(buf_len):
  49. channels[j][i] = next_chunk[i]
  50. # Advance sampleclock
  51. self.samples += buf_len
  52. def set_graph(self, graph):
  53. graph.set_synth(self)
  54. self.graph = iter(graph)
  55. def get_graph(self):
  56. return self.graph
  57. def __del__(self):
  58. """
  59. Deinitialise synth before being removed from mem
  60. """
  61. print "Deinitialising"
  62. self.deinit()
  63. def set_callback(self, func):
  64. """
  65. Set audio output function.
  66. Without any callback the synthesizer will simply output silence.
  67. The callback should adhere the following signature:
  68. def callback(channels):
  69. channels shall contain a list of lists and each list
  70. contains a large block of 0.0 floats describing the next set of samples.
  71. Those floats should be set to the chunk of audio.
  72. """
  73. _ysynth_set_callback(self.context, func)
  74. def get_callback(self):
  75. return _ysynth_get_callback(self.context)
  76. class YConstant(object):
  77. """
  78. Unchanging signal output.
  79. """
  80. def __init__(self, const):
  81. self.const = float(const)
  82. def __iter__(self):
  83. return iter(self())
  84. def __call__(self):
  85. while True:
  86. yield self.const
  87. def set_synth(self, synth):
  88. pass
  89. class YAudioGraphNode(object):
  90. """
  91. Base audio graph node
  92. This base class provides YSynth's DSL behaviours such as
  93. adding, substracting and the sample iteration protocol.
  94. """
  95. def __init__(self, *inputs):
  96. self.inputs = []
  97. lens = 0
  98. for stream in inputs:
  99. if not isinstance(stream, YAudioGraphNode):
  100. stream = YConstant(stream)
  101. self.inputs.append(stream)
  102. self.inputs = tuple(self.inputs)
  103. #for stream in inputs:
  104. # if isinstance(stream, YAudioGraphNode):
  105. # pass
  106. # # Make sure all multi-channels share the same size
  107. # if len(stream) != 1:
  108. # if not lens:
  109. # lens = len
  110. # elif lens != len(stream):
  111. # # TODO: Expand error info to contain sizes
  112. # raise ValueError("Cannot combine different sized "
  113. # "multi-channel streams")
  114. #self.channels = lens
  115. def __iter__(self):
  116. """
  117. Initialise graph for synthesis, link to sampleclock.
  118. """
  119. # XXX This function is not graph cycle safe
  120. # FIXME: I need to unpack the channels from the input streams
  121. # multiplex any mono-streams if there are multi-channel streams
  122. # available, and then initialise every set of streams' component
  123. # generator function by calling self with the correct arguments.
  124. # Setup input streams
  125. for stream in self.inputs:
  126. stream.set_synth(self.synth)
  127. # Setup self
  128. # The self.samples variable is used for protecting against
  129. # multiple next() calls, next will only evaluate the next
  130. # set of input samples if the synth's sampleclock has changed
  131. self.samples = self.synth.samples - 1
  132. # XXX self.last_sample is currently not initialised on purpose
  133. # maybe this must be changed at a later time.
  134. # Connect the actual generator components
  135. sample_iter = iter(self(izip(*self.inputs)))
  136. # Build the sample protection function
  137. def sample_func():
  138. """
  139. Make sure multiple next() calls during the same
  140. clock cycle yield the same sample value.
  141. """
  142. while True:
  143. if self.samples != self.synth.samples:
  144. self.last_sample = next(sample_iter)
  145. self.samples = self.synth.samples
  146. yield self.last_sample
  147. return sample_func()
  148. def set_synth(self, synth):
  149. """
  150. Set this component's synthesizer.
  151. This is mainly useful for reading the synth's sampleclock. However every
  152. active component requires a valid synthesizer.
  153. """
  154. self.synth = synth
  155. def get_synth(self, synth):
  156. """
  157. Return this component's synthesizer.
  158. """
  159. return self.synth
  160. def __add__(self, other):
  161. return Adder(self, other)
  162. def __radd__(self, other):
  163. return Adder(other, self)
  164. def __sub__(self, other):
  165. return Subtractor(self, other)
  166. def __rsub__(self, other):
  167. return Subtractor(other, self)
  168. def __mul__(self, other):
  169. return Multiplier(self, other)
  170. def __rmul__(self, other):
  171. return Multiplier(other, self)
  172. def __div__(self, other):
  173. return Divisor(self, other)
  174. def __rdiv__(self, other):
  175. return Divisor(other, self)
  176. def __getitem__(self, delay):
  177. """
  178. Return a delayed version of the output signal.
  179. """
  180. return Delay(self, delay)
  181. def __next__(self):
  182. """
  183. Process next sample.
  184. """
  185. def __call__(self):
  186. raise NotImplementedError("You need to inherit this class")
  187. def process(self, *streams):
  188. raise NotImplementedError("You need to inherit this class")
  189. # Basic signal arithmetic
  190. class Adder(YAudioGraphNode):
  191. def __call__(self, l):
  192. for a, b in l:
  193. yield a + b
  194. class Subtractor(YAudioGraphNode):
  195. def __call__(self, l):
  196. for a, b in l:
  197. yield a - b
  198. class Multiplier(YAudioGraphNode):
  199. def __call__(self, l):
  200. for a, b in l:
  201. yield a * b
  202. class Divisor(YAudioGraphNode):
  203. def __call__(self, l):
  204. for a, b in l:
  205. yield a / b
  206. # Sample delay
  207. class Delay(YAudioGraphNode):
  208. def __call__(self, l):
  209. buf = [0.0] * 4096
  210. samples = 0
  211. for sig, delay in l:
  212. buf[samples] = sig
  213. yield buf[(samples - delay) % 4096]
  214. samples = (samples + 1) % 4096
  215. # Base oscillator class
  216. class YOscillator(YAudioGraphNode):
  217. def __call__(self, l):
  218. def cycle_gen():
  219. """
  220. This function generates the oscillation cycle
  221. upon which all basic decoupled oscillators base their output
  222. signal.
  223. A decoupled oscillator is an oscillator
  224. with its own cycle generator. These oscillators respond well to
  225. incoming frequency changes, but due to the limitations of floating
  226. point are at risk of drifting out of phase, coupled oscillators
  227. are always in phase with each other.
  228. The generated cycle ranges from 0.0 to 1.0 exclusive.
  229. """
  230. last_cycle = [0.0]
  231. for freq, in l:
  232. # The last_cycle will only be a list during the initial
  233. # iteration, perfect for a 'once' statement, we want
  234. # to force the first cycle value to 0.
  235. if isinstance(last_cycle, list):
  236. if isinstance(freq, np.ndarray):
  237. ifreq = freq[0]
  238. else:
  239. ifreq = freq
  240. last_cycle = [-(ifreq / float(self.synth.samplerate))]
  241. # Compute cycle using IIR filter and np.fmod
  242. cycle, last_cycle = lfilter([1], [1, -1], freq /
  243. float(self.synth.samplerate) *
  244. np.ones(self.synth.chunk_size), zi=last_cycle)
  245. yield np.fmod(cycle, 1.0)
  246. last_cycle = np.fmod(last_cycle, 1.0)
  247. return self.oscillate(cycle_gen())
  248. def oscillate(self, l):
  249. raise NotImplementedError("Inherit this class")
  250. # Basic oscillators
  251. class Sin(YOscillator):
  252. """
  253. Sine wave oscillator
  254. """
  255. def oscillate(self, l):
  256. for pos in l:
  257. yield np.sin(2 * pi * pos)
  258. class Cos(YOscillator):
  259. """
  260. Cosine wave oscillator
  261. """
  262. def oscillate(self, l):
  263. for pos in l:
  264. yield np.cos(2 * pi * pos)
  265. class Saw(YOscillator):
  266. """
  267. Saw wave oscillator
  268. """
  269. def oscillate(self, l):
  270. for pos in l:
  271. yield pos * 2.0 - 1.0
  272. class RevSaw(YOscillator):
  273. """
  274. Reverse Saw wave oscillator
  275. """
  276. def oscillate(self, l):
  277. for pos in l:
  278. yield -(pos * 2.0 - 1.0)
  279. class Square(YOscillator):
  280. """
  281. Square wave oscillator
  282. """
  283. def oscillate(self, l):
  284. for pos in l:
  285. #yield 1.0 if pos < 0.5 else -1.0
  286. pos = pos - 0.5
  287. yield -(np.abs(pos) / pos)
  288. class Pulse(YOscillator):
  289. """
  290. Pulse oscillator
  291. """
  292. def oscillate(self, l):
  293. zi = [1.0]
  294. for pos in l:
  295. pos, zi = lfilter([-1, 1], [1], pos, zi=zi)
  296. yield np.array(pos > 0, dtype=float)