drums.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import pyaudio
  2. import socket
  3. import optparse
  4. import tarfile
  5. import wave
  6. import cStringIO as StringIO
  7. import array
  8. import time
  9. import colorsys
  10. import struct
  11. import mmap
  12. import threading
  13. import os
  14. import atexit
  15. from packet import Packet, CMD, stoi, OBLIGATE_POLYPHONE
  16. parser = optparse.OptionParser()
  17. parser.add_option('-t', '--test', dest='test', action='store_true', help='As a test, play all samples then exit')
  18. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose')
  19. parser.add_option('-V', '--volume', dest='volume', type='float', default=1.0, help='Set the volume factor (nominally [0.0, 1.0], but >1.0 can be used to amplify with possible distortion)')
  20. parser.add_option('-r', '--rate', dest='rate', type='int', default=44100, help='Audio sample rate for output and of input files')
  21. parser.add_option('-u', '--uid', dest='uid', default='', help='User identifier of this client')
  22. parser.add_option('-p', '--port', dest='port', default=13677, type='int', help='UDP port to listen on')
  23. parser.add_option('-c', '--clamp', dest='clamp', action='store_true', help='Clamp over-the-wire amplitudes to 0.0-1.0')
  24. parser.add_option('-B', '--bind', dest='bind_addr', default='', help='Bind to this address')
  25. parser.add_option('-G', '--gui', dest='gui', help='Use a GUI')
  26. parser.add_option('--amp-exp', dest='amp_exp', default=2.0, type='float', help='Raise floating amplitude to this power before computing raw amplitude')
  27. parser.add_option('--repeat', dest='repeat', action='store_true', help='If a note plays longer than a sample length, keep playing the sample')
  28. parser.add_option('--cut', dest='cut', action='store_true', help='If a note ends within a sample, stop playing that sample immediately')
  29. parser.add_option('-n', '--max-voices', dest='max_voices', default=-1, type='int', help='Only support this many notes playing simultaneously (earlier ones get dropped)')
  30. parser.add_option('--pg-low-freq', dest='low_freq', type='int', default=40, help='Low frequency for colored background')
  31. parser.add_option('--pg-high-freq', dest='high_freq', type='int', default=1500, help='High frequency for colored background')
  32. parser.add_option('--pg-log-base', dest='log_base', type='int', default=2, help='Logarithmic base for coloring (0 to make linear)')
  33. 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)')
  34. parser.add_option('--map-interval', dest='map_interval', type='float', default=0.02, help='Period in seconds between refreshes of the map')
  35. parser.add_option('--map-samples', dest='map_samples', type='int', default=4096, help='Number of samples in the map file (MUST agree with renderer)')
  36. 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')
  37. options, args = parser.parse_args()
  38. MAX = 0x7fffffff
  39. MIN = -0x80000000
  40. IDENT = 'DRUM'
  41. LAST_SAMPLES = []
  42. FREQS = [0]
  43. AMPS = [0]
  44. STREAMS = 1
  45. if not args:
  46. print 'Need at least one drumpack (.tar.bz2) as an argument!'
  47. parser.print_usage()
  48. exit(1)
  49. def rgb_for_freq_amp(f, a):
  50. pitchval = float(f - options.low_freq) / (options.high_freq - options.low_freq)
  51. a = max((min((a, 1.0)), 0.0))
  52. if options.log_base == 0:
  53. try:
  54. pitchval = math.log(pitchval) / math.log(options.log_base)
  55. except ValueError:
  56. pass
  57. bgcol = colorsys.hls_to_rgb(min((1.0, max((0.0, pitchval)))), 0.5 * (a ** 2), 1.0)
  58. return [int(i*255) for i in bgcol]
  59. # GUIs
  60. GUIs = {}
  61. def GUI(f):
  62. GUIs[f.__name__] = f
  63. return f
  64. @GUI
  65. def mapped():
  66. if os.path.exists(options.map_file):
  67. raise ValueError('Refusing to map file--already exists!')
  68. ms = options.map_samples
  69. stm = options.map_interval
  70. fixfmt = '>f'
  71. fixfmtsz = struct.calcsize(fixfmt)
  72. sigfmt = '>' + 'f' * ms
  73. sigfmtsz = struct.calcsize(sigfmt)
  74. strfmt = '>' + 'Lf' * STREAMS
  75. strfmtsz = struct.calcsize(strfmt)
  76. sz = sum((fixfmtsz, sigfmtsz, strfmtsz))
  77. print 'Reserving', sz, 'in map file'
  78. print 'Size triple:', fixfmtsz, sigfmtsz, strfmtsz
  79. f = open(options.map_file, 'w+')
  80. f.seek(sz - 1)
  81. f.write('\0')
  82. f.flush()
  83. mapping = mmap.mmap(f.fileno(), sz, access=mmap.ACCESS_WRITE)
  84. f.close()
  85. atexit.register(os.unlink, options.map_file)
  86. def unzip2(i):
  87. for a, b in i:
  88. yield a
  89. yield b
  90. while True:
  91. mapping[:fixfmtsz] = struct.pack(fixfmt, 0.0)
  92. 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)))
  93. mapping[fixfmtsz+sigfmtsz:] = struct.pack(strfmt, *unzip2((FREQS[i], AMPS[i]) for i in xrange(STREAMS)))
  94. del LAST_SAMPLES[:]
  95. time.sleep(stm)
  96. if options.gui:
  97. guithread = threading.Thread(target=GUIs[options.gui])
  98. guithread.setDaemon(True)
  99. guithread.start()
  100. DRUMS = {}
  101. for fname in args:
  102. print 'Reading', fname, '...'
  103. tf = tarfile.open(fname, 'r')
  104. names = tf.getnames()
  105. for nm in names:
  106. if not (nm.endswith('.wav') or nm.endswith('.raw')) or len(nm) < 5:
  107. continue
  108. frq = int(nm[:-4])
  109. if options.verbose:
  110. print '\tLoading frq', frq, '...'
  111. fo = tf.extractfile(nm)
  112. if nm.endswith('.wav'):
  113. wf = wave.open(fo)
  114. if wf.getnchannels() != 1:
  115. print '\t\tWARNING: Channel count wrong: got', wf.getnchannels(), 'expecting 1'
  116. if wf.getsampwidth() != 4:
  117. print '\t\tWARNING: Sample width wrong: got', wf.getsampwidth(), 'expecting 4'
  118. if wf.getframerate() != options.rate:
  119. print '\t\tWARNING: Rate wrong: got', wf.getframerate(), 'expecting', options.rate, '(maybe try setting -r?)'
  120. frames = wf.getnframes()
  121. data = ''
  122. while len(data) < wf.getsampwidth() * frames:
  123. data += wf.readframes(frames - len(data) / wf.getsampwidth())
  124. elif nm.endswith('.raw'):
  125. data = fo.read()
  126. frames = len(data) / 4
  127. if options.verbose:
  128. print '\t\tData:', frames, 'samples,', len(data), 'bytes'
  129. if frq in DRUMS:
  130. print '\t\tWARNING: frequency', frq, 'already in map, overwriting...'
  131. DRUMS[frq] = data
  132. if options.verbose:
  133. print len(DRUMS), 'sounds loaded'
  134. PLAYING = []
  135. class SampleReader(object):
  136. def __init__(self, buf, total, amp):
  137. self.buf = buf
  138. self.total = total
  139. self.cur = 0
  140. self.amp = amp
  141. def read(self, bytes):
  142. if self.cur >= self.total:
  143. return ''
  144. res = ''
  145. while self.cur < self.total and len(res) < bytes:
  146. data = self.buf[self.cur % len(self.buf):self.cur % len(self.buf) + bytes - len(res)]
  147. self.cur += len(data)
  148. res += data
  149. arr = array.array('i')
  150. arr.fromstring(res)
  151. for i in range(len(arr)):
  152. arr[i] = int(arr[i] * self.amp)
  153. return arr.tostring()
  154. def __repr__(self):
  155. return '<SR (%d) @%d / %d A:%f>'%(len(self.buf), self.cur, self.total, self.amp)
  156. def gen_data(data, frames, tm, status):
  157. fdata = array.array('l', [0] * frames)
  158. torem = set()
  159. for src in set(PLAYING):
  160. buf = src.read(frames * 4)
  161. if not buf:
  162. torem.add(src)
  163. continue
  164. samps = array.array('i')
  165. samps.fromstring(buf)
  166. if len(samps) < frames:
  167. samps.extend([0] * (frames - len(samps)))
  168. for i in range(frames):
  169. fdata[i] += samps[i]
  170. for src in torem:
  171. PLAYING.remove(src)
  172. for i in range(frames):
  173. fdata[i] = max(MIN, min(MAX, fdata[i]))
  174. fdata = array.array('i', fdata)
  175. AMPS[0] = (float(sum(abs(i) for i in fdata)) / (len(fdata) * MAX))**0.25
  176. LAST_SAMPLES.extend(fdata)
  177. return (fdata.tostring(), pyaudio.paContinue)
  178. pa = pyaudio.PyAudio()
  179. stream = pa.open(rate=options.rate, channels=1, format=pyaudio.paInt32, output=True, frames_per_buffer=64, stream_callback=gen_data)
  180. if options.test:
  181. for frq in sorted(DRUMS.keys()):
  182. print 'Current playing:', PLAYING
  183. print 'Playing:', frq
  184. data = DRUMS[frq]
  185. FREQS[0] = frq
  186. AMPS[0] = 1.0
  187. PLAYING.append(SampleReader(data, len(data), options.volume))
  188. time.sleep(len(data) / (4.0 * options.rate))
  189. print 'Done'
  190. exit()
  191. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  192. sock.bind((options.bind_addr, options.port))
  193. #signal.signal(signal.SIGALRM, sigalrm)
  194. counter = 0
  195. while True:
  196. data = ''
  197. while not data:
  198. try:
  199. data, cli = sock.recvfrom(4096)
  200. except socket.error:
  201. pass
  202. pkt = Packet.FromStr(data)
  203. crgb = [int(i*255) for i in colorsys.hls_to_rgb((float(counter) / options.counter_modulus) % 1.0, 0.5, 1.0)]
  204. print '\x1b[38;2;{};{};{}m#'.format(*crgb),
  205. counter += 1
  206. print '\x1b[mFrom', cli, 'command', pkt.cmd,
  207. if pkt.cmd == CMD.KA:
  208. print '\x1b[37mKA'
  209. elif pkt.cmd == CMD.PING:
  210. sock.sendto(data, cli)
  211. print '\x1b[1;33mPING'
  212. elif pkt.cmd == CMD.QUIT:
  213. print '\x1b[1;31mQUIT'
  214. break
  215. elif pkt.cmd == CMD.PLAY:
  216. frq = pkt.data[2]
  217. if frq not in DRUMS:
  218. print 'WARNING: No such instrument', frq, ', ignoring...'
  219. continue
  220. rdata = DRUMS[frq]
  221. rframes = len(rdata) / 4
  222. dur = pkt.data[0]+pkt.data[1]/1000000.0
  223. dframes = int(dur * options.rate)
  224. if not options.repeat:
  225. dframes = max(dframes, rframes)
  226. if not options.cut:
  227. dframes = rframes * ((dframes + rframes - 1) / rframes)
  228. amp = options.volume * pkt.as_float(3)
  229. if options.clamp:
  230. amp = max(min(amp, 1.0), 0.0)
  231. FREQS[0] = frq
  232. AMPS[0] = amp
  233. PLAYING.append(SampleReader(rdata, dframes * 4, amp**options.amp_exp))
  234. if options.max_voices >= 0:
  235. while len(PLAYING) > options.max_voices:
  236. PLAYING.pop(0)
  237. frgb = rgb_for_freq_amp(pkt.data[2], pkt.as_float(3))
  238. print '\x1b[1;32mPLAY',
  239. print '\x1b[1;34mVOICE', '{:03}'.format(pkt.data[4]),
  240. print '\x1b[1;38;2;{};{};{}mFREQ'.format(*frgb), '{:04}'.format(pkt.data[2]), 'AMP', '%08.6f'%pkt.as_float(3),
  241. if pkt.data[0] == 0 and pkt.data[1] == 0:
  242. print '\x1b[1;35mSTOP!!!'
  243. else:
  244. print '\x1b[1;36mDUR', '%08.6f'%dur
  245. #signal.setitimer(signal.ITIMER_REAL, dur)
  246. elif pkt.cmd == CMD.CAPS:
  247. data = [0] * 8
  248. data[0] = OBLIGATE_POLYPHONE
  249. data[1] = stoi(IDENT)
  250. for i in xrange(len(options.uid)/4 + 1):
  251. data[i+2] = stoi(options.uid[4*i:4*(i+1)])
  252. sock.sendto(str(Packet(CMD.CAPS, *data)), cli)
  253. print '\x1b[1;34mCAPS'
  254. # elif pkt.cmd == CMD.PCM:
  255. # fdata = data[4:]
  256. # fdata = struct.pack('16i', *[i<<16 for i in struct.unpack('16h', fdata)])
  257. # QUEUED_PCM += fdata
  258. # print 'Now', len(QUEUED_PCM) / 4.0, 'frames queued'
  259. else:
  260. print 'Unknown cmd', pkt.cmd