drums.py 8.3 KB

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