broadcast.py 32 KB

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