drums.py 8.5 KB

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