broadcast.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. import socket
  2. import sys
  3. import struct
  4. import time
  5. import xml.etree.ElementTree as ET
  6. import threading
  7. import thread
  8. import optparse
  9. import random
  10. import itertools
  11. import re
  12. import os
  13. from packet import Packet, CMD, itos, OBLIGATE_POLYPHONE
  14. parser = optparse.OptionParser()
  15. parser.add_option('-t', '--test', dest='test', action='store_true', help='Play a test tone (440, 880) on all clients in sequence (the last overlaps with the first of the next)')
  16. parser.add_option('-T', '--transpose', dest='transpose', type='int', help='Transpose by a set amount of semitones (positive or negative)')
  17. parser.add_option('--sync-test', dest='sync_test', action='store_true', help='Don\'t wait for clients to play tones properly--have them all test tone at the same time')
  18. parser.add_option('--wait-test', dest='wait_test', action='store_true', help='Wait for user input before moving to the next client tested')
  19. parser.add_option('-R', '--random', dest='random', type='float', help='Generate random notes at approximately this period')
  20. parser.add_option('--rand-low', dest='rand_low', type='int', help='Low frequency to randomly sample')
  21. parser.add_option('--rand-high', dest='rand_high', type='int', help='High frequency to randomly sample')
  22. parser.add_option('-l', '--live', dest='live', help='Enter live mode (play from a controller in real time), specifying the port to connect to as "client,port"; use just "," to manually subscribe later')
  23. parser.add_option('-L', '--list-live', dest='list_live', action='store_true', help='List all the clients and ports that can be connected to for live performance')
  24. parser.add_option('--no-sustain', dest='no_sustain', action='store_true', help='Don\'t use sustain hacks in live mode')
  25. parser.add_option('-q', '--quit', dest='quit', action='store_true', help='Instruct all clients to quit')
  26. parser.add_option('-p', '--play', dest='play', action='append', help='Play a single tone or chord (specified multiple times) on all listening clients (either "midi pitch" or "@frequency")')
  27. parser.add_option('-P', '--play-async', dest='play_async', action='store_true', help='Don\'t wait for the tone to finish using the local clock')
  28. parser.add_option('-D', '--duration', dest='duration', type='float', help='How long to play this note for')
  29. parser.add_option('-V', '--volume', dest='volume', type='float', help='Master volume [0.0, 1.0]')
  30. parser.add_option('-s', '--silence', dest='silence', action='store_true', help='Instruct all clients to stop playing any active tones')
  31. parser.add_option('-S', '--seek', dest='seek', type='float', help='Start time in seconds (scaled by --factor)')
  32. parser.add_option('-f', '--factor', dest='factor', type='float', help='Rescale time by this factor (0<f<1 are faster; 0.5 is twice the speed, 2 is half)')
  33. parser.add_option('-r', '--route', dest='routes', action='append', help='Add a routing directive (see --route-help)')
  34. parser.add_option('--clear-routes', dest='routes', action='store_const', const=[], help='Clear routes previously specified (including the default)')
  35. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; dump events and actual time (can slow down performance!)')
  36. parser.add_option('-W', '--wait-time', dest='wait_time', type='float', help='How long to wait between pings for clients to initially respond (delays all broadcasts)')
  37. parser.add_option('--tries', dest='tries', type='int', help='Number of ping packets to send')
  38. parser.add_option('-B', '--bind-addr', dest='bind_addr', help='The IP address (or IP:port) to bind to (influences the network to send to)')
  39. parser.add_option('--port', dest='ports', action='append', type='int', help='Add a port to find clients on')
  40. parser.add_option('--clear-ports', dest='ports', action='store_const', const=[], help='Clear ports previously specified (including the default)')
  41. parser.add_option('--repeat', dest='repeat', action='store_true', help='Repeat the file playlist indefinitely')
  42. parser.add_option('-n', '--number', dest='number', type='int', help='Number of clients to use; if negative (default -1), use the product of stream count and the absolute value of this parameter')
  43. parser.add_option('--dry', dest='dry', action='store_true', help='Dry run--don\'t actually search for or play to clients, but pretend they exist (useful with -G)')
  44. parser.add_option('--pcm', dest='pcm', action='store_true', help='Use experimental PCM rendering')
  45. parser.add_option('--pcm-lead', dest='pcmlead', type='float', help='Seconds of leading PCM data to send')
  46. parser.add_option('--spin', dest='spin', action='store_true', help='Ignore delta times in the queue (busy loop the CPU) for higher accuracy')
  47. parser.add_option('-G', '--gui', dest='gui', default='', help='set a GUI to use')
  48. parser.add_option('--pg-fullscreen', dest='fullscreen', action='store_true', help='Use a full-screen video mode')
  49. parser.add_option('--pg-width', dest='pg_width', type='int', help='Width of the pygame window')
  50. parser.add_option('--pg-height', dest='pg_height', type='int', help='Width of the pygame window')
  51. parser.add_option('--help-routes', dest='help_routes', action='store_true', help='Show help about routing directives')
  52. parser.set_defaults(routes=['T:DRUM=!perc,0'], random=0.0, rand_low=80, rand_high=2000, live=None, factor=1.0, duration=0.25, volume=1.0, wait_time=0.1, tries=5, play=[], transpose=0, seek=0.0, bind_addr='', ports=[13676, 13677], pg_width = 0, pg_height = 0, number=-1, pcmlead=0.1)
  53. options, args = parser.parse_args()
  54. if options.help_routes:
  55. print '''Routes are a way of either exclusively or mutually binding certain streams to certain playback clients. They are especially fitting in heterogenous environments where some clients will outperform others in certain pitches or with certain parts.
  56. Routes are fully specified by:
  57. -The attribute to be routed on (either type "T", or UID "U")
  58. -The value of that attribute
  59. -The exclusivity of that route ("+" for inclusive, "-" for exclusive, "!" for complete)
  60. -The stream group to be routed there, or 0 to null route.
  61. The first two may be replaced by a single '0' to null route a stream--effective only when used with an exclusive route.
  62. "Complete" exclusivity is valid only for obligate polyphones, and indicates that *all* matches are to receive the stream. In other cases, this will have the undesirable effect of routing only one stream.
  63. The special group ALL matches all streams. Regular expressions may be used to specify groups. Note that the first character is *not* part of the regular expression.
  64. The syntax for that specification resembles the following:
  65. broadcast.py -r U:bass=+bass -r U:treble1,U:treble2=+treble -r T:BEEP=-beeps,-trk3,-trk5 -r U:noise=0
  66. The specifier consists of a comma-separated list of attribute-colon-value pairs, followed by an equal sign. After this is a comma-separated list of exclusivities paired with the name of a stream group as specified in the file. The above example shows that stream groups "bass", "treble", and "beeps" will be routed to clients with UID "bass", "treble", and TYPE "BEEP" respectively. Additionally, TYPE "BEEP" will receive tracks 4 and 6 (indices 3 and 5) of the MIDI file (presumably split with -T), and that these three groups are exclusively to be routed to TYPE "BEEP" clients only (the broadcaster will drop the stream if no more are available), as opposed to the preference of the bass and treble groups, which may be routed onto other stream clients if they are available. Finally, the last route says that all "noise" UID clients should not proceed any further (receiving "null" streams) instead. Order is important; if a "noise" client already received a stream (such as "+beeps"), then it would receive that route with priority.'''
  67. exit()
  68. GUIS = {}
  69. BASETIME = time.time() # XXX fixes a race with the GUI
  70. def gui_pygame():
  71. print 'Starting pygame GUI...'
  72. import pygame, colorsys
  73. pygame.init()
  74. print 'Pygame init'
  75. dispinfo = pygame.display.Info()
  76. DISP_WIDTH = 640
  77. DISP_HEIGHT = 480
  78. if dispinfo.current_h > 0 and dispinfo.current_w > 0:
  79. DISP_WIDTH = dispinfo.current_w
  80. DISP_HEIGHT = dispinfo.current_h
  81. print 'Pygame info'
  82. WIDTH = DISP_WIDTH
  83. if options.pg_width > 0:
  84. WIDTH = options.pg_width
  85. HEIGHT = DISP_HEIGHT
  86. if options.pg_height > 0:
  87. HEIGHT = options.pg_height
  88. flags = 0
  89. if options.fullscreen:
  90. flags |= pygame.FULLSCREEN
  91. disp = pygame.display.set_mode((WIDTH, HEIGHT), flags)
  92. print 'Disp acquire'
  93. PFAC = HEIGHT / 128.0
  94. clock = pygame.time.Clock()
  95. font = pygame.font.SysFont(pygame.font.get_default_font(), 24)
  96. print 'Pygame GUI initialized, running...'
  97. while True:
  98. disp.scroll(-1, 0)
  99. disp.fill((0, 0, 0), (WIDTH - 1, 0, 1, HEIGHT))
  100. idx = 0
  101. for cli, note in sorted(playing_notes.items(), key = lambda pair: pair[0]):
  102. pitch = note[0]
  103. col = colorsys.hls_to_rgb(float(idx) / len(targets), note[1]/2.0, 1.0)
  104. col = [int(i*255) for i in col]
  105. disp.fill(col, (WIDTH - 1, HEIGHT - pitch * PFAC - PFAC, 1, PFAC))
  106. idx += 1
  107. tsurf = font.render('%0.3f' % ((time.time() - BASETIME) / factor,), True, (255, 255, 255), (0, 0, 0))
  108. disp.fill((0, 0, 0), tsurf.get_rect())
  109. disp.blit(tsurf, (0, 0))
  110. pygame.display.flip()
  111. for ev in pygame.event.get():
  112. if ev.type == pygame.KEYDOWN:
  113. if ev.key == pygame.K_ESCAPE:
  114. thread.interrupt_main()
  115. pygame.quit()
  116. exit()
  117. clock.tick(60)
  118. GUIS['pygame'] = gui_pygame
  119. factor = options.factor
  120. print 'Factor:', factor
  121. try:
  122. rows, columns = map(int, os.popen('stty size', 'r').read().split())
  123. except Exception:
  124. import traceback
  125. traceback.print_exc()
  126. rows, columns = 25, 80
  127. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  128. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  129. if options.bind_addr:
  130. addr, _, port = options.bind_addr.partition(':')
  131. if not port:
  132. port = '12074'
  133. s.bind((addr, int(port)))
  134. clients = set()
  135. targets = set()
  136. uid_groups = {}
  137. type_groups = {}
  138. ports = {}
  139. if not options.dry:
  140. s.settimeout(options.wait_time)
  141. for PORT in options.ports:
  142. for num in xrange(options.tries):
  143. s.sendto(str(Packet(CMD.PING)), ('255.255.255.255', PORT))
  144. try:
  145. while True:
  146. data, src = s.recvfrom(4096)
  147. clients.add(src)
  148. except socket.timeout:
  149. pass
  150. print len(clients), 'detected clients'
  151. for num in xrange(options.tries):
  152. print 'Try', num
  153. for cl in clients:
  154. print cl,
  155. s.sendto(str(Packet(CMD.CAPS)), cl)
  156. data, _ = s.recvfrom(4096)
  157. pkt = Packet.FromStr(data)
  158. print 'ports', pkt.data[0],
  159. ports[cl] = pkt.data[0]
  160. tp = itos(pkt.data[1])
  161. print 'type', tp,
  162. uid = ''.join([itos(i) for i in pkt.data[2:]]).rstrip('\x00')
  163. print 'uid', uid
  164. if uid == '':
  165. uid = None
  166. uid_groups.setdefault(uid, set()).add(cl)
  167. type_groups.setdefault(tp, set()).add(cl)
  168. if options.test:
  169. ts, tms = int(options.duration), int(options.duration * 1000000) % 1000000
  170. if options.wait_test:
  171. s.sendto(str(Packet(CMD.PLAY, 65535, 0, 440, options.volume)), cl)
  172. raw_input('%r: Press enter to test next client...' %(cl,))
  173. s.sendto(str(Packet(CMD.PLAY, ts, tms, 880, options.volume)), cl)
  174. else:
  175. s.sendto(str(Packet(CMD.PLAY, ts, tms, 440, options.volume)), cl)
  176. if not options.sync_test:
  177. time.sleep(options.duration)
  178. s.sendto(str(Packet(CMD.PLAY, ts, tms, 880, options.volume)), cl)
  179. if options.quit:
  180. s.sendto(str(Packet(CMD.QUIT)), cl)
  181. if options.silence:
  182. for i in xrange(pkt.data[0]):
  183. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0.0, i)), cl)
  184. if pkt.data[0] == OBLIGATE_POLYPHONE:
  185. pkt.data[0] = 1
  186. for i in xrange(pkt.data[0]):
  187. targets.add(cl+(i,))
  188. playing_notes = {}
  189. for tg in targets:
  190. playing_notes[tg] = (0, 0)
  191. if options.gui:
  192. gui_thr = threading.Thread(target=GUIS[options.gui], args=())
  193. gui_thr.setDaemon(True)
  194. gui_thr.start()
  195. if options.play:
  196. for i, val in enumerate(options.play):
  197. if val.startswith('@'):
  198. options.play[i] = int(val[1:])
  199. else:
  200. options.play[i] = int(440.0 * 2**((int(val) - 69)/12.0))
  201. for i, cl in enumerate(targets):
  202. s.sendto(str(Packet(CMD.PLAY, int(options.duration), int(1000000*(options.duration-int(options.duration))), options.play[i%len(options.play)], options.volume, cl[2])), cl[:2])
  203. if not options.play_async:
  204. time.sleep(options.duration)
  205. exit()
  206. if options.test and options.sync_test:
  207. time.sleep(0.25)
  208. for cl in targets:
  209. s.sendto(str(Packet(CMD.PLAY, 0, 250000, 880, options.volume, cl[2])), cl[:2])
  210. if options.test or options.quit or options.silence:
  211. print uid_groups
  212. print type_groups
  213. exit()
  214. if options.random > 0:
  215. while True:
  216. for cl in targets:
  217. s.sendto(str(Packet(CMD.PLAY, int(options.random), int(1000000*(options.random-int(options.random))), random.randint(options.rand_low, options.rand_high), options.volume, cl[2])), cl[:2])
  218. time.sleep(options.random)
  219. if options.live or options.list_live:
  220. if options.gui:
  221. print 'Waiting a second for GUI init...'
  222. time.sleep(3.0)
  223. import midi
  224. from midi import sequencer
  225. S = sequencer.S
  226. if options.list_live:
  227. print sequencer.SequencerHardware()
  228. exit()
  229. seq = sequencer.SequencerRead(sequencer_resolution=120)
  230. client_set = set(targets)
  231. active_set = {} # note (pitch) -> [client]
  232. deferred_set = set() # pitches held due to sustain
  233. sustain_status = False
  234. client, _, port = options.live.partition(',')
  235. if client or port:
  236. seq.subscribe_port(client, port)
  237. seq.start_sequencer()
  238. if not options.gui: # FIXME
  239. seq.set_nonblock(False)
  240. while True:
  241. ev = S.event_input(seq.client)
  242. if ev is None:
  243. time.sleep(0)
  244. event = None
  245. if ev:
  246. if options.verbose:
  247. print 'SEQ:', ev
  248. if ev < 0:
  249. seq._error(ev)
  250. if ev.type == S.SND_SEQ_EVENT_NOTEON:
  251. event = midi.NoteOnEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  252. elif ev.type == S.SND_SEQ_EVENT_NOTEOFF:
  253. event = midi.NoteOffEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  254. elif ev.type == S.SND_SEQ_EVENT_CONTROLLER:
  255. event = midi.ControlChangeEvent(channel = ev.data.control.channel, control = ev.data.control.param, value = ev.data.control.value)
  256. elif ev.type == S.SND_SEQ_EVENT_PGMCHANGE:
  257. event = midi.ProgramChangeEvent(channel = ev.data.control.channel, value = ev.data.control.value)
  258. elif ev.type == S.SND_SEQ_EVENT_PITCHBEND:
  259. event = midi.PitchWheelEvent(channel = ev.data.control.channel, pitch = ev.data.control.value)
  260. elif options.verbose:
  261. print 'WARNING: Unparsed event, type %r'%(ev.type,)
  262. continue
  263. if event is not None:
  264. if isinstance(event, midi.NoteOnEvent) and event.velocity == 0:
  265. event.__class__ = midi.NoteOffEvent
  266. if options.verbose:
  267. print 'EVENT:', event
  268. if isinstance(event, midi.NoteOnEvent):
  269. if event.pitch in active_set:
  270. if sustain_status:
  271. deferred_set.discard(event.pitch)
  272. inactive_set = client_set - set(sum(active_set.values(), []))
  273. if not inactive_set:
  274. print 'WARNING: Out of clients to do note %r; dropped'%(event.pitch,)
  275. continue
  276. cli = sorted(inactive_set)[0]
  277. s.sendto(str(Packet(CMD.PLAY, 65535, 0, int(440.0 * 2**((event.pitch-69)/12.0)), event.velocity / 127.0, cli[2])), cli[:2])
  278. active_set.setdefault(event.pitch, []).append(cli)
  279. playing_notes[cli] = (event.pitch, event.velocity / 127.0)
  280. if options.verbose:
  281. print 'LIVE:', event.pitch, '+ =>', active_set[event.pitch]
  282. elif isinstance(event, midi.NoteOffEvent):
  283. if event.pitch not in active_set or not active_set[event.pitch]:
  284. print 'WARNING: Deactivating inactive note %r'%(event.pitch,)
  285. continue
  286. if sustain_status:
  287. deferred_set.add(event.pitch)
  288. continue
  289. cli = active_set[event.pitch].pop()
  290. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0, cli[2])), cli[:2])
  291. playing_notes[cli] = (0, 0)
  292. if options.verbose:
  293. print 'LIVE:', event.pitch, '- =>', active_set[event.pitch]
  294. if sustain_status:
  295. print '...ignored (sustain on)'
  296. elif isinstance(event, midi.ControlChangeEvent):
  297. if event.control == 64 and not options.no_sustain:
  298. sustain_status = (event.value >= 64)
  299. if options.verbose:
  300. print 'LIVE: SUSTAIN', ('+' if sustain_status else '-')
  301. if not sustain_status:
  302. for pitch in deferred_set:
  303. if pitch not in active_set or not active_set[pitch]:
  304. print 'WARNING: Attempted deferred removal of inactive note %r'%(pitch,)
  305. continue
  306. for cli in active_set[pitch]:
  307. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0, cli[2])), cli[:2])
  308. playing_notes[cli] = (0, 0)
  309. del active_set[pitch]
  310. deferred_set.clear()
  311. if options.repeat:
  312. args = itertools.cycle(args)
  313. for fname in args:
  314. if options.pcm and not fname.endswith('.iv'):
  315. print 'PCM: play', fname
  316. if fname == '-':
  317. import wave
  318. pcr = wave.open(sys.stdin)
  319. samprate = pcr.getframerate()
  320. pcr.read = pcr.readframes
  321. else:
  322. try:
  323. import audiotools
  324. pcr = audiotools.open(fname).to_pcm()
  325. assert pcr.channels == 1 and pcr.bits_per_sample == 16 and pcr.sample_rate == 44100
  326. samprate = pcr.sample_rate
  327. except ImportError:
  328. import wave
  329. pcr = wave.open(fname, 'r')
  330. assert pcr.getnchannels() == 1 and pcr.getsampwidth() == 2 and pcr.getframerate() == 44100
  331. samprate = pcr.getframerate()
  332. pcr.read = pcr.readframes
  333. def read_all(fn, n):
  334. buf = ''
  335. while len(buf) < n:
  336. nbuf = fn.read(n - len(buf))
  337. if not isinstance(nbuf, str):
  338. nbuf = nbuf.to_bytes(False, True)
  339. buf += nbuf
  340. return buf
  341. BASETIME = time.time() - options.pcmlead
  342. sampcnt = 0
  343. buf = read_all(pcr, 32)
  344. print 'PCM: pcr', pcr, 'BASETIME', BASETIME, 'buf', len(buf)
  345. while len(buf) >= 32:
  346. frag = buf[:32]
  347. buf = buf[32:]
  348. for cl in clients:
  349. s.sendto(struct.pack('>L', CMD.PCM) + frag, cl)
  350. sampcnt += len(frag) / 2
  351. delay = max(0, BASETIME + (sampcnt / float(samprate)) - time.time())
  352. #print sampcnt, delay
  353. if delay > 0:
  354. time.sleep(delay)
  355. if len(buf) < 32:
  356. buf += read_all(pcr, 32 - len(buf))
  357. print 'PCM: exit'
  358. continue
  359. try:
  360. iv = ET.parse(fname).getroot()
  361. except IOError:
  362. import traceback
  363. traceback.print_exc()
  364. print fname, ': Bad file'
  365. continue
  366. notestreams = iv.findall("./streams/stream[@type='ns']")
  367. groups = set([ns.get('group') for ns in notestreams if 'group' in ns.keys()])
  368. number = (len(notestreams) * abs(options.number) if options.number < 0 else options.number)
  369. print len(notestreams), 'notestreams'
  370. print len(clients), 'clients'
  371. print len(targets), 'targets'
  372. print len(groups), 'groups'
  373. print number, 'clients used (number)'
  374. class Route(object):
  375. def __init__(self, fattr, fvalue, group, excl=False, complete=False):
  376. if fattr == 'U':
  377. self.map = uid_groups
  378. elif fattr == 'T':
  379. self.map = type_groups
  380. elif fattr == '0':
  381. self.map = {}
  382. else:
  383. raise ValueError('Not a valid attribute specifier: %r'%(fattr,))
  384. self.value = fvalue
  385. self.group = group
  386. self.excl = excl
  387. self.complete = complete
  388. @classmethod
  389. def Parse(cls, s):
  390. fspecs, _, grpspecs = map(lambda x: x.strip(), s.partition('='))
  391. fpairs = []
  392. ret = []
  393. for fspec in [i.strip() for i in fspecs.split(',')]:
  394. fattr, _, fvalue = map(lambda x: x.strip(), fspec.partition(':'))
  395. fpairs.append((fattr, fvalue))
  396. for part in [i.strip() for i in grpspecs.split(',')]:
  397. for fattr, fvalue in fpairs:
  398. if part[0] == '+':
  399. ret.append(Route(fattr, fvalue, part[1:], False))
  400. elif part[0] == '-':
  401. ret.append(Route(fattr, fvalue, part[1:], True))
  402. elif part[0] == '!':
  403. ret.append(Route(fattr, fvalue, part[1:], True, True))
  404. elif part[0] == '0':
  405. ret.append(Route(fattr, fvalue, None, True))
  406. else:
  407. raise ValueError('Not an exclusivity: %r'%(part[0],))
  408. return ret
  409. def Apply(self, cli):
  410. return cli[:2] in self.map.get(self.value, [])
  411. def __repr__(self):
  412. return '<Route of %r to %s:%s>'%(self.group, ('U' if self.map is uid_groups else 'T'), self.value)
  413. class RouteSet(object):
  414. def __init__(self, clis=None):
  415. if clis is None:
  416. clis = set(targets)
  417. self.clients = list(clis)
  418. self.routes = []
  419. def Route(self, stream):
  420. testset = self.clients
  421. grp = stream.get('group', 'ALL')
  422. if options.verbose:
  423. print 'Routing', grp, '...'
  424. excl = False
  425. for route in self.routes:
  426. if route.group is not None and re.match(route.group, grp) is not None:
  427. if options.verbose:
  428. print '\tMatches route', route
  429. excl = excl or route.excl
  430. matches = filter(lambda x, route=route: route.Apply(x), testset)
  431. if matches:
  432. if route.complete:
  433. if options.verbose:
  434. print '\tUsing ALL clients:', matches
  435. for cl in matches:
  436. self.clients.remove(matches[0])
  437. if ports.get(matches[0][:2]) == OBLIGATE_POLYPHONE:
  438. self.clients.append(matches[0])
  439. return matches
  440. if options.verbose:
  441. print '\tUsing client', matches[0]
  442. self.clients.remove(matches[0])
  443. if ports.get(matches[0][:2]) == OBLIGATE_POLYPHONE:
  444. self.clients.append(matches[0])
  445. return [matches[0]]
  446. if options.verbose:
  447. print '\tNo matches, moving on...'
  448. if route.group is None:
  449. if options.verbose:
  450. print 'Encountered NULL route, removing from search space...'
  451. toremove = []
  452. for cli in testset:
  453. if route.Apply(cli):
  454. toremove.append(cli)
  455. for cli in toremove:
  456. if options.verbose:
  457. print '\tRemoving', cli, '...'
  458. testset.remove(cli)
  459. if excl:
  460. if options.verbose:
  461. print '\tExclusively routed, no route matched.'
  462. return []
  463. if not testset:
  464. if options.verbose:
  465. print '\tOut of clients, no route matched.'
  466. return []
  467. cli = list(testset)[0]
  468. self.clients.remove(cli)
  469. if ports.get(cli[:2]) == OBLIGATE_POLYPHONE:
  470. self.clients.append(cli)
  471. if options.verbose:
  472. print '\tDefault route to', cli
  473. return [cli]
  474. routeset = RouteSet()
  475. for rspec in options.routes:
  476. try:
  477. routeset.routes.extend(Route.Parse(rspec))
  478. except Exception:
  479. import traceback
  480. traceback.print_exc()
  481. if options.verbose:
  482. print 'All routes:'
  483. for route in routeset.routes:
  484. print route
  485. class NSThread(threading.Thread):
  486. def __init__(self, *args, **kwargs):
  487. threading.Thread.__init__(self, *args, **kwargs)
  488. self.done = False
  489. self.cur_offt = None
  490. self.next_t = None
  491. def actuate_missed(self):
  492. nsq, cls = self._Thread__args
  493. dur = None
  494. i = 0
  495. while nsq and float(nsq[0].get('time'))*factor <= time.time() - BASETIME:
  496. i += 1
  497. note = nsq.pop(0)
  498. ttime = float(note.get('time'))
  499. pitch = float(note.get('pitch')) + options.transpose
  500. ampl = float(note.get('ampl', float(note.get('vel', 127.0)) / 127.0))
  501. dur = factor*float(note.get('dur'))
  502. if options.verbose:
  503. print (time.time() - BASETIME) / options.factor, ': PLAY', pitch, dur, ampl
  504. if options.dry:
  505. playing_notes[self.nsid] = (pitch, ampl)
  506. else:
  507. for cl in cls:
  508. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), ampl * options.volume, cl[2])), cl[:2])
  509. playing_notes[cl] = (pitch, ampl)
  510. if i > 0 and dur is not None:
  511. self.cur_offt = ttime + dur / options.factor
  512. else:
  513. if self.cur_offt:
  514. if factor * self.cur_offt <= time.time() - BASETIME:
  515. if options.verbose:
  516. print '% 6.5f'%((time.time() - BASETIME) / factor,), ': DONE'
  517. self.cur_offt = None
  518. if options.dry:
  519. playing_notes[self.nsid] = (0, 0)
  520. else:
  521. for cl in cls:
  522. playing_notes[cl] = (0, 0)
  523. next_act = None
  524. if nsq:
  525. next_act = float(nsq[0].get('time'))
  526. if options.verbose:
  527. print 'NEXT_ACT:', next_act, 'CUR_OFFT:', self.cur_offt
  528. self.next_t = min((next_act or float('inf'), self.cur_offt or float('inf')))
  529. self.done = not (nsq or self.cur_offt)
  530. def drop_missed(self):
  531. nsq, cl = self._Thread__args
  532. cnt = 0
  533. while nsq and float(nsq[0].get('time'))*factor < time.time() - BASETIME:
  534. nsq.pop(0)
  535. cnt += 1
  536. if options.verbose:
  537. print self, 'dropped', cnt, 'notes due to miss'
  538. def wait_for(self, t):
  539. if t <= 0:
  540. return
  541. time.sleep(t)
  542. def run(self):
  543. nsq, cls = self._Thread__args
  544. for note in nsq:
  545. ttime = float(note.get('time'))
  546. pitch = float(note.get('pitch')) + options.transpose
  547. ampl = float(note.get('ampl', float(note.get('vel', 127.0)) / 127.0))
  548. dur = factor*float(note.get('dur'))
  549. while time.time() - BASETIME < factor*ttime:
  550. self.wait_for(factor*ttime - (time.time() - BASETIME))
  551. if options.dry:
  552. cl = self.nsid # XXX hack
  553. else:
  554. for cl in cls:
  555. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), ampl * options.volume, cl[2])), cl[:2])
  556. if options.verbose:
  557. print (time.time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  558. playing_notes[cl] = (pitch, ampl)
  559. self.wait_for(dur - ((time.time() - BASETIME) - factor*ttime))
  560. playing_notes[cl] = (0, 0)
  561. if options.verbose:
  562. print '% 6.5f'%(time.time() - BASETIME,), cl, ': DONE'
  563. threads = {}
  564. if options.dry:
  565. for nsid, ns in enumerate(notestreams):
  566. nsq = ns.findall('note')
  567. nsq.sort(key=lambda x: float(x.get('time')))
  568. threads[ns] = NSThread(args=(nsq, set()))
  569. threads[ns].nsid = nsid
  570. targets = threads.values() # XXX hack
  571. else:
  572. nscycle = itertools.cycle(notestreams)
  573. for idx, ns in zip(xrange(number), nscycle):
  574. clis = routeset.Route(ns)
  575. for cli in clis:
  576. nsq = ns.findall('note')
  577. nsq.sort(key=lambda x: float(x.get('time')))
  578. if ns in threads:
  579. threads[ns]._Thread__args[1].add(cli)
  580. else:
  581. threads[ns] = NSThread(args=(nsq, set([cli])))
  582. if options.verbose:
  583. print 'Playback threads:'
  584. for thr in threads.values():
  585. print thr._Thread__args[1]
  586. BASETIME = time.time() - (options.seek*factor)
  587. ENDTIME = max(max(float(n.get('time')) + float(n.get('dur')) for n in thr._Thread__args[0]) for thr in threads.values())
  588. print 'Playtime is', ENDTIME
  589. if options.seek > 0:
  590. for thr in threads.values():
  591. thr.drop_missed()
  592. spin_phase = 0
  593. SPINNERS = ['-', '\\', '|', '/']
  594. while not all(thr.done for thr in threads.values()):
  595. for thr in threads.values():
  596. if thr.next_t is None or factor * thr.next_t <= time.time() - BASETIME:
  597. thr.actuate_missed()
  598. delta = factor * min(thr.next_t for thr in threads.values() if thr.next_t is not None) + BASETIME - time.time()
  599. if delta == float('inf'):
  600. print 'WARNING: Infinite postponement detected! Did all notestreams finish?'
  601. break
  602. if options.verbose:
  603. print 'TICK DELTA:', delta
  604. else:
  605. sys.stdout.write('\x1b[G\x1b[K[%s]' % (
  606. ('#' * int((time.time() - BASETIME) * (columns - 2) / (ENDTIME * factor)) + SPINNERS[spin_phase]).ljust(columns - 2),
  607. ))
  608. sys.stdout.flush()
  609. spin_phase += 1
  610. if spin_phase >= len(SPINNERS):
  611. spin_phase = 0
  612. if delta >= 0 and not options.spin:
  613. time.sleep(delta)
  614. print fname, ': Done!'