client.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. # A simple client that generates sine waves via python-pyaudio
  2. import signal
  3. import pyaudio
  4. import sys
  5. import socket
  6. import time
  7. import math
  8. import struct
  9. import socket
  10. import optparse
  11. import array
  12. import random
  13. import threading
  14. import thread
  15. import colorsys
  16. import mmap
  17. import os
  18. import atexit
  19. from packet import Packet, CMD, PLF, stoi, OBLIGATE_POLYPHONE
  20. parser = optparse.OptionParser()
  21. parser.add_option('-t', '--test', dest='test', action='store_true', help='Play a test sequence (440,<rest>,880,440), then exit')
  22. parser.add_option('-g', '--generator', dest='generator', default='math.sin', help='Set the generator (to a Python expression)')
  23. parser.add_option('--generators', dest='generators', action='store_true', help='Show the list of generators, then exit')
  24. parser.add_option('-u', '--uid', dest='uid', default='', help='Set the UID (identifier) of this client in the network')
  25. parser.add_option('-p', '--port', dest='port', type='int', default=13676, help='Set the port to listen on')
  26. parser.add_option('-r', '--rate', dest='rate', type='int', default=44100, help='Set the sample rate of the audio device')
  27. parser.add_option('-V', '--volume', dest='volume', type='float', default=1.0, help='Set the volume factor (>1 distorts, <1 attenuates)')
  28. parser.add_option('-n', '--streams', dest='streams', type='int', default=1, help='Set the number of streams this client will play back')
  29. parser.add_option('-N', '--numpy', dest='numpy', action='store_true', help='Use numpy acceleration')
  30. parser.add_option('-G', '--gui', dest='gui', default='', help='set a GUI to use')
  31. parser.add_option('-c', '--clamp', dest='clamp', action='store_true', help='Clamp over-the-wire amplitudes to 0.0-1.0')
  32. parser.add_option('-C', '--chorus', dest='chorus', default=0.0, type='float', help='Apply uniform random offsets (in MIDI pitch space)')
  33. parser.add_option('-B', '--bind', dest='bind_addr', default='', help='Bind to this address')
  34. parser.add_option('--amp-exp', dest='amp_exp', default=2.0, type='float', help='Raise floating amplitude to this power before computing raw amplitude')
  35. parser.add_option('--vibrato', dest='vibrato', default=0.0, type='float', help='Apply periodic perturbances in pitch space by this amplitude (in MIDI pitches)')
  36. parser.add_option('--vibrato-freq', dest='vibrato_freq', default=6.0, type='float', help='Frequency of the vibrato perturbances in Hz')
  37. parser.add_option('--fmul', dest='fmul', default=1.0, type='float', help='Multiply requested frequencies by this amount')
  38. parser.add_option('--narts', dest='narts', default=64, type='int', help='Store this many articulation parameters for generator use (global is GARTS, voice-local is LARTS)')
  39. parser.add_option('--pg-fullscreen', dest='fullscreen', action='store_true', help='Use a full-screen video mode')
  40. parser.add_option('--pg-samp-width', dest='samp_width', type='int', help='Set the width of the sample pane (by default display width / 2)')
  41. parser.add_option('--pg-bgr-width', dest='bgr_width', type='int', help='Set the width of the bargraph pane (by default display width / 2)')
  42. parser.add_option('--pg-height', dest='height', type='int', help='Set the height of the window or full-screen video mode')
  43. parser.add_option('--pg-no-colback', dest='no_colback', action='store_true', help='Don\'t render a colored background')
  44. parser.add_option('--pg-low-freq', dest='low_freq', type='int', default=40, help='Low frequency for colored background')
  45. parser.add_option('--pg-high-freq', dest='high_freq', type='int', default=1500, help='High frequency for colored background')
  46. parser.add_option('--pg-log-base', dest='log_base', type='int', default=2, help='Logarithmic base for coloring (0 to make linear)')
  47. parser.add_option('--map-file', dest='map_file', default='client_map', help='File mapped by -G mapped (contains u32 frequency, f32 amplitude pairs for each voice)')
  48. parser.add_option('--map-interval', dest='map_interval', type='float', default=0.02, help='Period in seconds between refreshes of the map')
  49. parser.add_option('--map-samples', dest='map_samples', type='int', default=4096, help='Number of samples in the map file (MUST agree with renderer)')
  50. parser.add_option('--counter-modulus', dest='counter_modulus', type='int', default=16, help='Number of packet events in period of the terminal color scroll on the left margin')
  51. parser.add_option('--pcm-corr-rate', dest='pcm_corr_rate', type='float', default=0.05, help='Amount of time to correct buffer drift, measured as percentage of the current sync rate')
  52. options, args = parser.parse_args()
  53. if options.numpy:
  54. import numpy
  55. PORT = options.port
  56. STREAMS = options.streams
  57. IDENT = 'TONE'
  58. UID = options.uid
  59. LAST_SAMPS = [0] * STREAMS
  60. LAST_SAMPLES = []
  61. FREQS = [0] * STREAMS
  62. REAL_FREQS = [0] * STREAMS
  63. PHASES = [0] * STREAMS
  64. RATE = options.rate
  65. FPB = 64
  66. Z_SAMP = '\x00\x00\x00\x00'
  67. MAX = 0x7fffffff
  68. AMPS = [MAX] * STREAMS
  69. MIN = -0x80000000
  70. EXPIRATIONS = [0] * STREAMS
  71. QUEUED_PCM = ''
  72. DRIFT_FACTOR = 1.0
  73. DRIFT_ERROR = 0.0
  74. LAST_SYN = None
  75. CUR_PERIODS = [0] * STREAMS
  76. CUR_PERIOD = 0.0
  77. GARTS = [0.0] * options.narts
  78. VLARTS = [[0.0] * options.narts for i in xrange(STREAMS)]
  79. LARTS = None
  80. def lin_interp(frm, to, p):
  81. return p*to + (1-p)*frm
  82. def rgb_for_freq_amp(f, a):
  83. a = max((min((a, 1.0)), 0.0))
  84. pitchval = float(f - options.low_freq) / (options.high_freq - options.low_freq)
  85. if options.log_base == 0:
  86. try:
  87. pitchval = math.log(pitchval) / math.log(options.log_base)
  88. except ValueError:
  89. pass
  90. bgcol = colorsys.hls_to_rgb(min((1.0, max((0.0, pitchval)))), 0.5 * (a ** 2), 1.0)
  91. return [int(i*255) for i in bgcol]
  92. # GUIs
  93. GUIs = {}
  94. def GUI(f):
  95. GUIs[f.__name__] = f
  96. return f
  97. @GUI
  98. def pygame_notes():
  99. import pygame
  100. import pygame.gfxdraw
  101. pygame.init()
  102. dispinfo = pygame.display.Info()
  103. DISP_WIDTH = 640
  104. DISP_HEIGHT = 480
  105. if dispinfo.current_h > 0 and dispinfo.current_w > 0:
  106. DISP_WIDTH = dispinfo.current_w
  107. DISP_HEIGHT = dispinfo.current_h
  108. SAMP_WIDTH = DISP_WIDTH / 2
  109. if options.samp_width > 0:
  110. SAMP_WIDTH = options.samp_width
  111. BGR_WIDTH = DISP_WIDTH / 2
  112. if options.bgr_width > 0:
  113. BGR_WIDTH = options.bgr_width
  114. HEIGHT = DISP_HEIGHT
  115. if options.height > 0:
  116. HEIGHT = options.height
  117. flags = 0
  118. if options.fullscreen:
  119. flags |= pygame.FULLSCREEN
  120. disp = pygame.display.set_mode((SAMP_WIDTH + BGR_WIDTH, HEIGHT), flags)
  121. WIDTH, HEIGHT = disp.get_size()
  122. SAMP_WIDTH = WIDTH / 2
  123. BGR_WIDTH = WIDTH - SAMP_WIDTH
  124. PFAC = HEIGHT / 128.0
  125. sampwin = pygame.Surface((SAMP_WIDTH, HEIGHT))
  126. sampwin.set_colorkey((0, 0, 0))
  127. lastsy = HEIGHT / 2
  128. bgrwin = pygame.Surface((BGR_WIDTH, HEIGHT))
  129. bgrwin.set_colorkey((0, 0, 0))
  130. clock = pygame.time.Clock()
  131. font = pygame.font.SysFont(pygame.font.get_default_font(), 24)
  132. while True:
  133. if options.no_colback:
  134. disp.fill((0, 0, 0), (0, 0, WIDTH, HEIGHT))
  135. else:
  136. gap = WIDTH / STREAMS
  137. for i in xrange(STREAMS):
  138. FREQ = REAL_FREQS[i]
  139. AMP = AMPS[i]
  140. if FREQ > 0:
  141. bgcol = rgb_for_freq_amp(FREQ, float(AMP) / MAX)
  142. else:
  143. bgcol = (0, 0, 0)
  144. #print i, ':', pitchval
  145. disp.fill(bgcol, (i*gap, 0, gap, HEIGHT))
  146. bgrwin.scroll(-1, 0)
  147. bgrwin.fill((0, 0, 0), (BGR_WIDTH - 1, 0, 1, HEIGHT))
  148. for i in xrange(STREAMS):
  149. FREQ = REAL_FREQS[i]
  150. AMP = AMPS[i]
  151. if FREQ > 0:
  152. try:
  153. pitch = 12 * math.log(FREQ / 440.0, 2) + 69
  154. except ValueError:
  155. pitch = 0
  156. else:
  157. pitch = 0
  158. col = [min(max(int((AMP / MAX) * 255), 0), 255)] * 3
  159. bgrwin.fill(col, (BGR_WIDTH - 1, HEIGHT - pitch * PFAC - PFAC, 1, PFAC))
  160. sampwin.scroll(-len(LAST_SAMPLES), 0)
  161. x = max(0, SAMP_WIDTH - len(LAST_SAMPLES))
  162. sampwin.fill((0, 0, 0), (x, 0, SAMP_WIDTH - x, HEIGHT))
  163. for i in LAST_SAMPLES:
  164. sy = int((float(i) / MAX) * (HEIGHT / 2) + (HEIGHT / 2))
  165. pygame.gfxdraw.line(sampwin, x - 1, lastsy, x, sy, (0, 255, 0))
  166. x += 1
  167. lastsy = sy
  168. del LAST_SAMPLES[:]
  169. #w, h = SAMP_WIDTH, HEIGHT
  170. #pts = [(BGR_WIDTH, HEIGHT / 2), (w + BGR_WIDTH, HEIGHT / 2)]
  171. #x = w + BGR_WIDTH
  172. #for i in reversed(LAST_SAMPLES):
  173. # pts.insert(1, (x, int((h / 2) + (float(i) / MAX) * (h / 2))))
  174. # x -= 1
  175. # if x < BGR_WIDTH:
  176. # break
  177. #if len(pts) > 2:
  178. # pygame.gfxdraw.aapolygon(disp, pts, [0, 255, 0])
  179. disp.blit(bgrwin, (0, 0))
  180. disp.blit(sampwin, (BGR_WIDTH, 0))
  181. if QUEUED_PCM:
  182. tsurf = font.render('%+011.6g'%(DRIFT_FACTOR - 1,), True, (255, 255, 255), (0, 0, 0))
  183. disp.fill((0, 0, 0), tsurf.get_rect())
  184. disp.blit(tsurf, (0, 0))
  185. pygame.display.flip()
  186. for ev in pygame.event.get():
  187. if ev.type == pygame.KEYDOWN:
  188. if ev.key == pygame.K_ESCAPE:
  189. thread.interrupt_main()
  190. pygame.quit()
  191. exit()
  192. elif ev.type == pygame.QUIT:
  193. thread.interrupt_main()
  194. pygame.quit()
  195. exit()
  196. clock.tick(60)
  197. @GUI
  198. def mapped():
  199. if os.path.exists(options.map_file):
  200. raise ValueError('Refusing to map file--already exists!')
  201. ms = options.map_samples
  202. stm = options.map_interval
  203. fixfmt = '>f'
  204. fixfmtsz = struct.calcsize(fixfmt)
  205. sigfmt = '>' + 'f' * ms
  206. sigfmtsz = struct.calcsize(sigfmt)
  207. strfmt = '>' + 'Lf' * STREAMS
  208. strfmtsz = struct.calcsize(strfmt)
  209. sz = sum((fixfmtsz, sigfmtsz, strfmtsz))
  210. print 'Reserving', sz, 'in map file'
  211. print 'Size triple:', fixfmtsz, sigfmtsz, strfmtsz
  212. f = open(options.map_file, 'w+')
  213. f.seek(sz - 1)
  214. f.write('\0')
  215. f.flush()
  216. mapping = mmap.mmap(f.fileno(), sz, access=mmap.ACCESS_WRITE)
  217. f.close()
  218. atexit.register(os.unlink, options.map_file)
  219. def unzip2(i):
  220. for a, b in i:
  221. yield a
  222. yield b
  223. while True:
  224. mapping[:fixfmtsz] = struct.pack(fixfmt, (DRIFT_FACTOR - 1.0) if QUEUED_PCM else 0.0)
  225. del LAST_SAMPLES[:-ms]
  226. mapping[fixfmtsz:fixfmtsz+sigfmtsz] = struct.pack(sigfmt, *(float(LAST_SAMPLES[i])/MAX if i < len(LAST_SAMPLES) else 0.0 for i in xrange(ms)))
  227. mapping[fixfmtsz+sigfmtsz:] = struct.pack(strfmt, *unzip2((FREQS[i], float(AMPS[i])/MAX) for i in xrange(STREAMS)))
  228. time.sleep(stm)
  229. # Generator functions--should be cyclic within [0, 2*math.pi) and return [-1, 1]
  230. GENERATORS = [{'name': 'math.sin', 'args': None, 'desc': 'Sine function'},
  231. {'name':'math.cos', 'args': None, 'desc': 'Cosine function'}]
  232. def generator(desc=None, args=None):
  233. def inner(f, desc=desc, args=args):
  234. if desc is None:
  235. desc = f.__doc__
  236. GENERATORS.append({'name': f.__name__, 'desc': desc, 'args': args})
  237. return f
  238. return inner
  239. @generator('Simple triangle wave (peaks/troughs at pi/2, 3pi/2)')
  240. def tri_wave(theta):
  241. if theta < math.pi/2:
  242. return lin_interp(0, 1, theta/(math.pi/2))
  243. elif theta < 3*math.pi/2:
  244. return lin_interp(1, -1, (theta-math.pi/2)/math.pi)
  245. else:
  246. return lin_interp(-1, 0, (theta-3*math.pi/2)/(math.pi/2))
  247. @generator('Saw wave (line from (0, 1) to (2pi, -1))')
  248. def saw_wave(theta):
  249. return lin_interp(1, -1, theta/(math.pi * 2))
  250. @generator('Simple square wave (piecewise 1 at x<pi, 0 else)')
  251. def square_wave(theta):
  252. if theta < math.pi:
  253. return 1
  254. else:
  255. return -1
  256. @generator('Random (noise) generator')
  257. def noise(theta):
  258. return random.random() * 2 - 1
  259. @generator('Square generator with polynomial falloff')
  260. class sq_cub(object):
  261. def __init__(self, mina, degree=1.0/3):
  262. self.mina = mina
  263. self.degree = degree
  264. def __call__(self, theta):
  265. if theta < math.pi:
  266. return 1 - (1 - self.mina) * ((theta / math.pi) ** self.degree)
  267. else:
  268. return -1 + (1 - self.mina) * (((theta - math.pi) / math.pi) ** self.degree)
  269. @generator('Impulse-like square')
  270. class impulse(object):
  271. def __init__(self, dc=0.01):
  272. self.dc = dc
  273. def __call__(self, theta):
  274. if theta < self.dc * math.pi:
  275. return 1
  276. elif theta < math.pi:
  277. return 0
  278. elif theta < (1+self.dc) * math.pi:
  279. return -1
  280. else:
  281. return 0
  282. @generator('File generator', '(<file>[, <bits=8>[, <signed=True>[, <0=linear interp (default), 1=nearest>[, <swapbytes=False>[, <loop=(fraction to loop, 0.0 is all, 1.0 is end, or False to not loop)>[, <loopend=1.0>[, periods=1 (periods in wave file)/freq=None (base frequency)/pitch=None (base MIDI pitch)]]]]]]])')
  283. class file_samp(object):
  284. LINEAR = 0
  285. NEAREST = 1
  286. TYPES = {8: 'B', 16: 'H', 32: 'L'}
  287. def __init__(self, fname, bits=8, signed=True, samp=LINEAR, swab=False, loop=0.0, loopend=1.0, periods=1.0, freq=None, pitch=None):
  288. tp = self.TYPES[bits]
  289. if signed:
  290. tp = tp.lower()
  291. self.max = float((2 << bits) - 1)
  292. if signed:
  293. self.max /= 2.0
  294. self.buffer = array.array(tp)
  295. self.buffer.fromstring(open(fname, 'rb').read())
  296. if swab:
  297. self.buffer.byteswap()
  298. self.samp = samp
  299. self.loop = loop
  300. self.loopend = loopend
  301. self.periods = periods
  302. if pitch is not None:
  303. freq = 440.0 * 2 ** ((pitch - 69) / 12.0)
  304. if freq is not None:
  305. self.periods = freq * len(self.buffer) / RATE
  306. print 'file_samp periods:', self.periods, 'freq:', freq, 'pitch:', pitch
  307. def __call__(self, theta):
  308. full_norm = CUR_PERIOD / (2*self.periods*math.pi)
  309. if full_norm > 1.0:
  310. if self.loop is False:
  311. return self.buffer[0]
  312. else:
  313. norm = (full_norm - 1.0) / (self.loopend - self.loop) % 1.0 * (self.loopend - self.loop) + self.loop
  314. else:
  315. norm = full_norm
  316. norm %= 1.0
  317. if self.samp == self.LINEAR:
  318. v = norm*len(self.buffer)
  319. l = int(math.floor(v))
  320. h = int(math.ceil(v))
  321. if l == h:
  322. return self.buffer[l]/self.max
  323. if h >= len(self.buffer):
  324. h = 0
  325. return lin_interp(self.buffer[l], self.buffer[h], v-l)/self.max
  326. elif self.samp == self.NEAREST:
  327. return self.buffer[int(math.ceil(norm*len(self.buffer) - 0.5))]/self.max
  328. @generator('Harmonics generator (adds overtones at f, 2f, 3f, 4f, etc.)', '(<generator>, <amplitude of f>, <amp 2f>, <amp 3f>, ...)')
  329. class harmonic(object):
  330. def __init__(self, gen, *spectrum):
  331. self.gen = gen
  332. self.spectrum = spectrum
  333. def __call__(self, theta):
  334. return max(-1, min(1, sum([amp*self.gen((i+1)*theta % (2*math.pi)) for i, amp in enumerate(self.spectrum)])))
  335. @generator('General harmonics generator (adds arbitrary overtones)', '(<generator>, <factor of f>, <amplitude>, <factor>, <amplitude>, ...)')
  336. class genharmonic(object):
  337. def __init__(self, gen, *harmonics):
  338. self.gen = gen
  339. self.harmonics = zip(harmonics[::2], harmonics[1::2])
  340. def __call__(self, theta):
  341. return max(-1, min(1, sum([amp * self.gen(i * theta % (2*math.pi)) for i, amp in self.harmonics])))
  342. @generator('Mix generator', '(<generator>[, <amp>], [<generator>[, <amp>], [...]])')
  343. class mixer(object):
  344. def __init__(self, *specs):
  345. self.pairs = []
  346. i = 0
  347. while i < len(specs):
  348. if i+1 < len(specs) and isinstance(specs[i+1], (float, int)):
  349. pair = (specs[i], specs[i+1])
  350. i += 2
  351. else:
  352. pair = (specs[i], None)
  353. i += 1
  354. self.pairs.append(pair)
  355. tamp = 1 - min(1, sum([amp for gen, amp in self.pairs if amp is not None]))
  356. parts = float(len([None for gen, amp in self.pairs if amp is None]))
  357. for idx, pair in enumerate(self.pairs):
  358. if pair[1] is None:
  359. self.pairs[idx] = (pair[0], tamp / parts)
  360. def __call__(self, theta):
  361. return max(-1, min(1, sum([amp*gen(theta) for gen, amp in self.pairs])))
  362. @generator('Phase offset generator (in radians; use math.pi)', '(<generator>, <offset>)')
  363. class phase_off(object):
  364. def __init__(self, gen, offset):
  365. self.gen = gen
  366. self.offset = offset
  367. def __call__(self, theta):
  368. return self.gen((theta + self.offset) % (2*math.pi))
  369. @generator('Normally distributed random-inversion square waves (chorus effect)', '(<sigma>)')
  370. class nd_square_wave(object):
  371. def __init__(self, sig):
  372. self.sig = sig
  373. self.invt = 0
  374. self.lastp = 2*math.pi
  375. def __call__(self, theta):
  376. if theta < self.lastp:
  377. self.invt = random.normalvariate(math.pi, self.sig)
  378. self.lastp = theta
  379. return -1 if theta < self.invt else 1
  380. @generator('Normally distributed random-point triangle waves (chorus effect)', '(<sigma>)')
  381. class nd_tri_wave(object):
  382. def __init__(self, sig):
  383. self.sig = sig
  384. self.p1 = 0.5*math.pi
  385. self.p2 = 1.5*math.pi
  386. self.lastp = 2*math.pi
  387. def __call__(self, theta):
  388. if theta < self.lastp:
  389. self.p1 = random.normalvariate(0.5*math.pi, self.sig)
  390. self.p2 = random.normalvariate(1.5*math.pi, self.sig)
  391. self.lastp = theta
  392. if theta < self.p1:
  393. return lin_interp(0, 1, theta / self.p1)
  394. elif theta < self.p2:
  395. return lin_interp(1, -1, (theta - self.p1) / (self.p2 - self.p1))
  396. else:
  397. return lin_interp(-1, 0, (theta - self.p2) / (2*math.pi - self.p2))
  398. @generator('Random phase offset', '(<generator>, <noise factor>)')
  399. class rand_phase_off(object):
  400. def __init__(self, gen, fac):
  401. self.gen = gen
  402. self.fac = fac
  403. def __call__(self, theta):
  404. return self.gen((theta + self.fac * random.random()) % (2*math.pi))
  405. @generator('Infinite Impulse Response low pass filter', '(<generator>, <RC normalized to dt=1 sample>)')
  406. class lowpass(object):
  407. def __init__(self, gen, rc):
  408. self.gen = gen
  409. self.alpha = 1.0 / (rc + 1)
  410. self.last = 0
  411. def __call__(self, theta):
  412. self.last += self.alpha * (self.gen(theta) - self.last)
  413. return self.last
  414. @generator('Infinite Impulse Response high pass filter', '(<generator>, <RC normalized to dt=1 sample>)')
  415. class highpass(object):
  416. def __init__(self, gen, rc):
  417. self.gen = gen
  418. self.alpha = rc / (rc + 1.0)
  419. self.last = 0
  420. self.lastx = 0
  421. def __call__(self, theta):
  422. x = self.gen(theta)
  423. self.last = self.alpha * (self.last + x - self.lastx)
  424. self.lastx = x
  425. return self.last
  426. @generator('Applies a function to itself repeatedly; often used with filters', '(<times>, <func>, <inner>, <extra arg 1>, <extra arg 2>, ...)')
  427. def order(n, f, i, *args):
  428. cur = f(i, *args)
  429. while n > 0:
  430. cur = f(cur, *args)
  431. n -= 1
  432. return cur
  433. if options.generators:
  434. for item in GENERATORS:
  435. print item['name'],
  436. if item['args'] is not None:
  437. print item['args'],
  438. print '--', item['desc']
  439. exit()
  440. #generator = math.sin
  441. #generator = tri_wave
  442. #generator = square_wave
  443. generator = eval(options.generator)
  444. #def sigalrm(sig, frm):
  445. # global FREQ
  446. # FREQ = 0
  447. if options.numpy:
  448. def lin_seq(frm, to, cnt):
  449. return numpy.linspace(frm, to, cnt, dtype=numpy.int32)
  450. def samps(freq, amp, phase, cnt):
  451. global CUR_PERIOD
  452. samps = numpy.ndarray((cnt,), numpy.int32)
  453. pvel = 2 * math.pi * freq / RATE
  454. fac = options.volume * amp / float(STREAMS)
  455. for i in xrange(cnt):
  456. samps[i] = fac * max(-1, min(1, generator((phase + i * pvel) % (2*math.pi))))
  457. CUR_PERIOD += pvel
  458. return samps, phase + pvel * cnt
  459. def to_data(samps):
  460. return samps.tobytes()
  461. def mix(a, b):
  462. return a + b
  463. def resample(samps, amt):
  464. samps = numpy.frombuffer(samps, numpy.int32)
  465. return numpy.interp(numpy.linspace(0, samps.shape[0], amt, False), numpy.linspace(0, samps.shape[0], samps.shape[0], False), samps).astype(numpy.int32).tobytes()
  466. else:
  467. def lin_seq(frm, to, cnt):
  468. step = (to-frm)/float(cnt)
  469. samps = [0]*cnt
  470. for i in xrange(cnt):
  471. p = i / float(cnt-1)
  472. samps[i] = int(lin_interp(frm, to, p))
  473. return samps
  474. def samps(freq, amp, phase, cnt):
  475. global RATE, CUR_PERIOD
  476. samps = [0]*cnt
  477. for i in xrange(cnt):
  478. samps[i] = int(amp / float(STREAMS) * max(-1, min(1, options.volume*generator((phase + 2 * math.pi * freq * i / RATE) % (2*math.pi)))))
  479. CUR_PERIOD += 2 * math.pi * freq / RATE
  480. next_phase = (phase + 2 * math.pi * freq * cnt / RATE)
  481. return samps, next_phase
  482. def to_data(samps):
  483. return struct.pack('i'*len(samps), *samps)
  484. def mix(a, b):
  485. return [min(MAX, max(MIN, i + j)) for i, j in zip(a, b)]
  486. def resample(samps, amt):
  487. isl = len(samps) / 4
  488. if isl == amt:
  489. return samps
  490. arr = struct.unpack(str(isl)+'i', samps)
  491. out = []
  492. for i in range(amt):
  493. effidx = i * (isl / amt)
  494. ieffidx = int(effidx)
  495. if ieffidx == effidx:
  496. out.append(arr[ieffidx])
  497. else:
  498. frac = effidx - ieffidx
  499. out.append(arr[ieffidx] * (1-frac) + arr[ieffidx+1] * frac)
  500. return struct.pack(str(amt)+'i', *out)
  501. def gen_data(data, frames, tm, status):
  502. global FREQS, PHASE, Z_SAMP, LAST_SAMP, LAST_SAMPLES, QUEUED_PCM, DRIFT_FACTOR, DRIFT_ERROR, CUR_PERIOD, LARTS
  503. if len(QUEUED_PCM) >= frames*4:
  504. desired_frames = DRIFT_FACTOR * frames
  505. err_frames = desired_frames - int(desired_frames)
  506. desired_frames = int(desired_frames)
  507. DRIFT_ERROR += err_frames
  508. if DRIFT_ERROR >= 1.0:
  509. desired_frames += 1
  510. DRIFT_ERROR -= 1.0
  511. fdata = QUEUED_PCM[:desired_frames*4]
  512. QUEUED_PCM = QUEUED_PCM[desired_frames*4:]
  513. if options.gui:
  514. LAST_SAMPLES.extend(struct.unpack(str(desired_frames)+'i', fdata))
  515. return resample(fdata, frames), pyaudio.paContinue
  516. if options.numpy:
  517. fdata = numpy.zeros((frames,), numpy.int32)
  518. else:
  519. fdata = [0] * frames
  520. for i in range(STREAMS):
  521. FREQ = FREQS[i]
  522. if options.vibrato > 0 and FREQ > 0:
  523. midi = 12 * math.log(FREQ / 440.0, 2) + 69
  524. midi += options.vibrato * math.sin(time.time() * 2 * math.pi * options.vibrato_freq + i * 2 * math.pi / STREAMS)
  525. FREQ = 440.0 * 2 ** ((midi - 69) / 12)
  526. REAL_FREQS[i] = FREQ
  527. LAST_SAMP = LAST_SAMPS[i]
  528. AMP = AMPS[i]
  529. EXPIRATION = EXPIRATIONS[i]
  530. PHASE = PHASES[i]
  531. CUR_PERIOD = CUR_PERIODS[i]
  532. LARTS = VLARTS[i]
  533. if FREQ != 0:
  534. if time.time() > EXPIRATION:
  535. FREQ = 0
  536. FREQS[i] = 0
  537. if FREQ == 0:
  538. if LAST_SAMP != 0:
  539. vdata = lin_seq(LAST_SAMP, 0, frames)
  540. fdata = mix(fdata, vdata)
  541. LAST_SAMPS[i] = vdata[-1]
  542. else:
  543. vdata, CUR_PERIOD = samps(FREQ, AMP, CUR_PERIOD, frames)
  544. PHASE = (PHASE + CUR_PERIOD) % (2 * math.pi)
  545. fdata = mix(fdata, vdata)
  546. PHASES[i] = PHASE
  547. CUR_PERIODS[i] = CUR_PERIOD
  548. LAST_SAMPS[i] = vdata[-1]
  549. if options.gui:
  550. LAST_SAMPLES.extend(fdata)
  551. return (to_data(fdata), pyaudio.paContinue)
  552. pa = pyaudio.PyAudio()
  553. stream = pa.open(rate=RATE, channels=1, format=pyaudio.paInt32, output=True, frames_per_buffer=FPB, stream_callback=gen_data)
  554. if options.gui:
  555. guithread = threading.Thread(target=GUIs[options.gui])
  556. guithread.setDaemon(True)
  557. guithread.start()
  558. if options.test:
  559. FREQS[0] = 440
  560. EXPIRATIONS[0] = time.time() + 1
  561. CUR_PERIODS[0] = 0.0
  562. time.sleep(1)
  563. FREQS[0] = 0
  564. time.sleep(1)
  565. FREQS[0] = 880
  566. EXPIRATIONS[0] = time.time() + 1
  567. CUR_PERIODS[0] = 0.0
  568. time.sleep(1)
  569. FREQS[0] = 440
  570. EXPIRATIONS[0] = time.time() + 2
  571. CUR_PERIODS[0] = 0.0
  572. time.sleep(2)
  573. exit()
  574. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  575. sock.bind((options.bind_addr, PORT))
  576. #signal.signal(signal.SIGALRM, sigalrm)
  577. counter = 0
  578. while True:
  579. data = ''
  580. while not data:
  581. try:
  582. data, cli = sock.recvfrom(4096)
  583. except socket.error:
  584. pass
  585. pkt = Packet.FromStr(data)
  586. inds = [' ' if f == 0 else '\x1b[1;38;2;{};{};{}m|'.format(*rgb_for_freq_amp(f, a / MAX)) for f, a in zip(FREQS, AMPS)]
  587. if pkt.cmd != CMD.PCM:
  588. crgb = [int(i*255) for i in colorsys.hls_to_rgb((float(counter) / options.counter_modulus) % 1.0, 0.5, 1.0)]
  589. print '\x1b[38;2;{};{};{}m#'.format(*crgb),
  590. counter += 1
  591. print '\x1b[m', cli, pkt.cmd,
  592. if pkt.cmd == CMD.KA:
  593. print '\x1b[37mKA', ' '.join(inds)
  594. elif pkt.cmd == CMD.PING:
  595. sock.sendto(data, cli)
  596. print '\x1b[1;33mPING', ' '.join(inds)
  597. elif pkt.cmd == CMD.QUIT:
  598. print '\x1b[1;31mQUIT', ' '.join(inds)
  599. break
  600. elif pkt.cmd == CMD.PLAY:
  601. voice = pkt.data[4]
  602. dur = pkt.data[0]+pkt.data[1]/1000000.0
  603. freq = pkt.data[2] * options.fmul
  604. if options.chorus > 0:
  605. midi = 12 * math.log(freq / 440.0, 2) + 69
  606. midi += (random.random() * 2 - 1) * options.chorus
  607. freq = 440.0 * 2 ** ((midi - 69) / 12)
  608. FREQS[voice] = freq
  609. amp = pkt.as_float(3)
  610. if options.clamp:
  611. amp = max(min(amp, 1.0), 0.0)
  612. AMPS[voice] = MAX * amp**options.amp_exp
  613. EXPIRATIONS[voice] = time.time() + dur
  614. if not (pkt.data[5] & PLF.SAMEPHASE):
  615. CUR_PERIODS[voice] = 0.0
  616. PHASES[voice] = 0.0
  617. vrgb = [int(i*255) for i in colorsys.hls_to_rgb(float(voice) / STREAMS * 2.0 / 3.0, 0.5, 1.0)]
  618. frgb = rgb_for_freq_amp(pkt.data[2], pkt.as_float(3))
  619. print '\x1b[1;32mPLAY',
  620. print '\x1b[1;38;2;{};{};{}mVOICE'.format(*vrgb), '{:03}'.format(voice),
  621. print '\x1b[1;38;2;{};{};{}mFREQ'.format(*frgb), '{:04}'.format(pkt.data[2]), 'AMP', '%08.6f'%pkt.as_float(3),
  622. inds[voice] = '\x1b[1;38;2;{};{};{}m-'.format(*frgb)
  623. print ' '.join(inds),
  624. if pkt.data[5] & PLF.SAMEPHASE:
  625. print '\x1b[1;37mSAMEPHASE',
  626. if pkt.data[0] == 0 and pkt.data[1] == 0:
  627. print '\x1b[1;31mSTOP!!!'
  628. else:
  629. print '\x1b[1;36mDUR', '%08.6f'%dur
  630. #signal.setitimer(signal.ITIMER_REAL, dur)
  631. elif pkt.cmd == CMD.CAPS:
  632. data = [0] * 8
  633. data[0] = STREAMS
  634. data[1] = stoi(IDENT)
  635. for i in xrange(len(UID)/4 + 1):
  636. data[i+2] = stoi(UID[4*i:4*(i+1)])
  637. sock.sendto(str(Packet(CMD.CAPS, *data)), cli)
  638. print '\x1b[1;34mCAPS', ' '.join(inds)
  639. elif pkt.cmd == CMD.PCM:
  640. fdata = data[4:]
  641. fdata = struct.pack('16i', *[i<<16 for i in struct.unpack('16h', fdata)])
  642. QUEUED_PCM += fdata
  643. #print 'Now', len(QUEUED_PCM) / 4.0, 'frames queued'
  644. elif pkt.cmd == CMD.PCMSYN:
  645. print '\x1b[1;37mPCMSYN',
  646. bufamt = pkt.data[0]
  647. print '\x1b[0m DESBUF={}'.format(bufamt),
  648. if LAST_SYN is None:
  649. LAST_SYN = time.time()
  650. else:
  651. dt = time.time() - LAST_SYN
  652. dfr = dt * RATE
  653. bufnow = len(QUEUED_PCM) / 4
  654. print '\x1b[35m CURBUF={}'.format(bufnow),
  655. if bufnow != 0:
  656. DRIFT_FACTOR = 1.0 + float(bufnow - bufamt) / (bufamt * dfr * options.pcm_corr_rate)
  657. print '\x1b[37m (DRIFT_FACTOR=%08.6f)'%(DRIFT_FACTOR,),
  658. print
  659. elif pkt.cmd == CMD.ARTP:
  660. print '\x1b[1;36mARTP',
  661. if pkt.data[0] == OBLIGATE_POLYPHONE:
  662. print '\x1b[1;31mGLOBAL',
  663. else:
  664. vrgb = [int(i*255) for i in colorsys.hls_to_rgb(float(pkt.data[0]) / STREAMS * 2.0 / 3.0, 0.5, 1.0)]
  665. print '\x1b[1;38;2;{};{};{}mVOICE'.format(*vrgb), '{:03}'.format(pkt.data[0]),
  666. print '\x1b[1;36mINDEX', pkt.data[1], '\x1b[1;37mVALUE', '%08.6f'%pkt.as_float(2),
  667. if pkt.data[1] >= options.narts:
  668. print '\x1b[1;31mOOB!!!',
  669. else:
  670. if pkt.data[0] == OBLIGATE_POLYPHONE:
  671. GARTS[pkt.data[1]] = pkt.as_float(2)
  672. else:
  673. VLARTS[pkt.data[0]][pkt.data[1]] = pkt.as_float(2)
  674. print
  675. else:
  676. print '\x1b[1;31mUnknown cmd', pkt.cmd