broadcast.py 31 KB

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