drums.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. from packet import Packet, CMD, stoi, OBLIGATE_POLYPHONE
  11. parser = optparse.OptionParser()
  12. parser.add_option('-t', '--test', dest='test', action='store_true', help='As a test, play all samples then exit')
  13. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose')
  14. 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)')
  15. parser.add_option('-r', '--rate', dest='rate', type='int', default=44100, help='Audio sample rate for output and of input files')
  16. parser.add_option('-u', '--uid', dest='uid', default='', help='User identifier of this client')
  17. parser.add_option('-p', '--port', dest='port', default=13677, type='int', help='UDP port to listen on')
  18. parser.add_option('-c', '--clamp', dest='clamp', action='store_true', help='Clamp over-the-wire amplitudes to 0.0-1.0')
  19. parser.add_option('--amp-exp', dest='amp_exp', default=2.0, type='float', help='Raise floating amplitude to this power before computing raw amplitude')
  20. parser.add_option('--repeat', dest='repeat', action='store_true', help='If a note plays longer than a sample length, keep playing the sample')
  21. parser.add_option('--cut', dest='cut', action='store_true', help='If a note ends within a sample, stop playing that sample immediately')
  22. 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)')
  23. parser.add_option('--pg-low-freq', dest='low_freq', type='int', default=40, help='Low frequency for colored background')
  24. parser.add_option('--pg-high-freq', dest='high_freq', type='int', default=1500, help='High frequency for colored background')
  25. parser.add_option('--pg-log-base', dest='log_base', type='int', default=2, help='Logarithmic base for coloring (0 to make linear)')
  26. 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')
  27. options, args = parser.parse_args()
  28. MAX = 0x7fffffff
  29. MIN = -0x80000000
  30. IDENT = 'DRUM'
  31. if not args:
  32. print 'Need at least one drumpack (.tar.bz2) as an argument!'
  33. parser.print_usage()
  34. exit(1)
  35. def rgb_for_freq_amp(f, a):
  36. pitchval = float(f - options.low_freq) / (options.high_freq - options.low_freq)
  37. a = max((min((a, 1.0)), 0.0))
  38. if options.log_base == 0:
  39. try:
  40. pitchval = math.log(pitchval) / math.log(options.log_base)
  41. except ValueError:
  42. pass
  43. bgcol = colorsys.hls_to_rgb(min((1.0, max((0.0, pitchval)))), 0.5 * (a ** 2), 1.0)
  44. return [int(i*255) for i in bgcol]
  45. DRUMS = {}
  46. for fname in args:
  47. print 'Reading', fname, '...'
  48. tf = tarfile.open(fname, 'r')
  49. names = tf.getnames()
  50. for nm in names:
  51. if not (nm.endswith('.wav') or nm.endswith('.raw')) or len(nm) < 5:
  52. continue
  53. frq = int(nm[:-4])
  54. if options.verbose:
  55. print '\tLoading frq', frq, '...'
  56. fo = tf.extractfile(nm)
  57. if nm.endswith('.wav'):
  58. wf = wave.open(fo)
  59. if wf.getnchannels() != 1:
  60. print '\t\tWARNING: Channel count wrong: got', wf.getnchannels(), 'expecting 1'
  61. if wf.getsampwidth() != 4:
  62. print '\t\tWARNING: Sample width wrong: got', wf.getsampwidth(), 'expecting 4'
  63. if wf.getframerate() != options.rate:
  64. print '\t\tWARNING: Rate wrong: got', wf.getframerate(), 'expecting', options.rate, '(maybe try setting -r?)'
  65. frames = wf.getnframes()
  66. data = ''
  67. while len(data) < wf.getsampwidth() * frames:
  68. data += wf.readframes(frames - len(data) / wf.getsampwidth())
  69. elif nm.endswith('.raw'):
  70. data = fo.read()
  71. frames = len(data) / 4
  72. if options.verbose:
  73. print '\t\tData:', frames, 'samples,', len(data), 'bytes'
  74. if frq in DRUMS:
  75. print '\t\tWARNING: frequency', frq, 'already in map, overwriting...'
  76. DRUMS[frq] = data
  77. if options.verbose:
  78. print len(DRUMS), 'sounds loaded'
  79. PLAYING = []
  80. class SampleReader(object):
  81. def __init__(self, buf, total, amp):
  82. self.buf = buf
  83. self.total = total
  84. self.cur = 0
  85. self.amp = amp
  86. def read(self, bytes):
  87. if self.cur >= self.total:
  88. return ''
  89. res = ''
  90. while self.cur < self.total and len(res) < bytes:
  91. data = self.buf[self.cur % len(self.buf):self.cur % len(self.buf) + bytes - len(res)]
  92. self.cur += len(data)
  93. res += data
  94. arr = array.array('i')
  95. arr.fromstring(res)
  96. for i in range(len(arr)):
  97. arr[i] = int(arr[i] * self.amp)
  98. return arr.tostring()
  99. def __repr__(self):
  100. return '<SR (%d) @%d / %d A:%f>'%(len(self.buf), self.cur, self.total, self.amp)
  101. def gen_data(data, frames, tm, status):
  102. fdata = array.array('l', [0] * frames)
  103. torem = set()
  104. for src in set(PLAYING):
  105. buf = src.read(frames * 4)
  106. if not buf:
  107. torem.add(src)
  108. continue
  109. samps = array.array('i')
  110. samps.fromstring(buf)
  111. if len(samps) < frames:
  112. samps.extend([0] * (frames - len(samps)))
  113. for i in range(frames):
  114. fdata[i] += samps[i]
  115. for src in torem:
  116. PLAYING.remove(src)
  117. for i in range(frames):
  118. fdata[i] = max(MIN, min(MAX, fdata[i]))
  119. fdata = array.array('i', fdata)
  120. return (fdata.tostring(), pyaudio.paContinue)
  121. pa = pyaudio.PyAudio()
  122. stream = pa.open(rate=options.rate, channels=1, format=pyaudio.paInt32, output=True, frames_per_buffer=64, stream_callback=gen_data)
  123. if options.test:
  124. for frq in sorted(DRUMS.keys()):
  125. print 'Current playing:', PLAYING
  126. print 'Playing:', frq
  127. data = DRUMS[frq]
  128. PLAYING.append(SampleReader(data, len(data), options.volume))
  129. time.sleep(len(data) / (4.0 * options.rate))
  130. print 'Done'
  131. exit()
  132. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  133. sock.bind(('', options.port))
  134. #signal.signal(signal.SIGALRM, sigalrm)
  135. counter = 0
  136. while True:
  137. data = ''
  138. while not data:
  139. try:
  140. data, cli = sock.recvfrom(4096)
  141. except socket.error:
  142. pass
  143. pkt = Packet.FromStr(data)
  144. crgb = [int(i*255) for i in colorsys.hls_to_rgb((float(counter) / options.counter_modulus) % 1.0, 0.5, 1.0)]
  145. print '\x1b[38;2;{};{};{}m#'.format(*crgb),
  146. counter += 1
  147. print '\x1b[mFrom', cli, 'command', pkt.cmd,
  148. if pkt.cmd == CMD.KA:
  149. print '\x1b[37mKA'
  150. elif pkt.cmd == CMD.PING:
  151. sock.sendto(data, cli)
  152. print '\x1b[1;33mPING'
  153. elif pkt.cmd == CMD.QUIT:
  154. print '\x1b[1;31mQUIT'
  155. break
  156. elif pkt.cmd == CMD.PLAY:
  157. frq = pkt.data[2]
  158. if frq not in DRUMS:
  159. print 'WARNING: No such instrument', frq, ', ignoring...'
  160. continue
  161. rdata = DRUMS[frq]
  162. rframes = len(rdata) / 4
  163. dur = pkt.data[0]+pkt.data[1]/1000000.0
  164. dframes = int(dur * options.rate)
  165. if not options.repeat:
  166. dframes = max(dframes, rframes)
  167. if not options.cut:
  168. dframes = rframes * ((dframes + rframes - 1) / rframes)
  169. amp = options.volume * pkt.as_float(3)
  170. if options.clamp:
  171. amp = max(min(amp, 1.0), 0.0)
  172. PLAYING.append(SampleReader(rdata, dframes * 4, amp**options.amp_exp))
  173. if options.max_voices >= 0:
  174. while len(PLAYING) > options.max_voices:
  175. PLAYING.pop(0)
  176. frgb = rgb_for_freq_amp(pkt.data[2], pkt.as_float(3))
  177. print '\x1b[1;32mPLAY',
  178. print '\x1b[1;34mVOICE', '{:03}'.format(pkt.data[4]),
  179. print '\x1b[1;38;2;{};{};{}mFREQ'.format(*frgb), '{:04}'.format(pkt.data[2]), 'AMP', '%08.6f'%pkt.as_float(3),
  180. if pkt.data[0] == 0 and pkt.data[1] == 0:
  181. print '\x1b[1;35mSTOP!!!'
  182. else:
  183. print '\x1b[1;36mDUR', '%08.6f'%dur
  184. #signal.setitimer(signal.ITIMER_REAL, dur)
  185. elif pkt.cmd == CMD.CAPS:
  186. data = [0] * 8
  187. data[0] = OBLIGATE_POLYPHONE
  188. data[1] = stoi(IDENT)
  189. for i in xrange(len(options.uid)/4 + 1):
  190. data[i+2] = stoi(options.uid[4*i:4*(i+1)])
  191. sock.sendto(str(Packet(CMD.CAPS, *data)), cli)
  192. print '\x1b[1;34mCAPS'
  193. # elif pkt.cmd == CMD.PCM:
  194. # fdata = data[4:]
  195. # fdata = struct.pack('16i', *[i<<16 for i in struct.unpack('16h', fdata)])
  196. # QUEUED_PCM += fdata
  197. # print 'Now', len(QUEUED_PCM) / 4.0, 'frames queued'
  198. else:
  199. print 'Unknown cmd', pkt.cmd