client.py 26 KB

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