broadcast.py 29 KB

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