drums.py 8.3 KB

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