broadcast.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. from packet import Packet, CMD, itos
  11. parser = optparse.OptionParser()
  12. 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)')
  13. parser.add_option('--test-delay', dest='test_delay', type='float', help='Time for which to play a test tone')
  14. parser.add_option('-T', '--transpose', dest='transpose', type='int', help='Transpose by a set amount of semitones (positive or negative)')
  15. 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')
  16. parser.add_option('-R', '--random', dest='random', type='float', help='Generate random notes at approximately this period')
  17. parser.add_option('--rand-low', dest='rand_low', type='int', help='Low frequency to randomly sample')
  18. parser.add_option('--rand-high', dest='rand_high', type='int', help='High frequency to randomly sample')
  19. 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')
  20. 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')
  21. parser.add_option('--no-sustain', dest='no_sustain', action='store_true', help='Don\'t use sustain hacks in live mode')
  22. parser.add_option('-q', '--quit', dest='quit', action='store_true', help='Instruct all clients to quit')
  23. 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")')
  24. 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')
  25. parser.add_option('-D', '--duration', dest='duration', type='float', help='How long to play this note for')
  26. parser.add_option('-V', '--volume', dest='volume', type='int', help='Master volume (0-255)')
  27. parser.add_option('-s', '--silence', dest='silence', action='store_true', help='Instruct all clients to stop playing any active tones')
  28. parser.add_option('-S', '--seek', dest='seek', type='float', help='Start time in seconds (scaled by --factor)')
  29. 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)')
  30. parser.add_option('-r', '--route', dest='routes', action='append', help='Add a routing directive (see --route-help)')
  31. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; dump events and actual time (can slow down performance!)')
  32. parser.add_option('-W', '--wait-time', dest='wait_time', type='float', help='How long to wait for clients to initially respond (delays all broadcasts)')
  33. 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)')
  34. parser.add_option('-G', '--gui', dest='gui', default='', help='set a GUI to use')
  35. parser.add_option('--pg-fullscreen', dest='fullscreen', action='store_true', help='Use a full-screen video mode')
  36. parser.add_option('--pg-width', dest='pg_width', type='int', help='Width of the pygame window')
  37. parser.add_option('--pg-height', dest='pg_height', type='int', help='Width of the pygame window')
  38. parser.add_option('--help-routes', dest='help_routes', action='store_true', help='Show help about routing directives')
  39. 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=255, wait_time=0.25, play=[], transpose=0, seek=0.0, bind_addr='', pg_width = 0, pg_height = 0)
  40. options, args = parser.parse_args()
  41. if options.help_routes:
  42. 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.
  43. Routes are fully specified by:
  44. -The attribute to be routed on (either type "T", or UID "U")
  45. -The value of that attribute
  46. -The exclusivity of that route ("+" for inclusive, "-" for exclusive)
  47. -The stream group to be routed there.
  48. The syntax for that specification resembles the following:
  49. broadcast.py -r U:bass=+bass -r U:treble1,U:treble2=+treble -r T:BEEP=-beeps,-trk3,-trk5 -r U:noise=0
  50. 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.'''
  51. exit()
  52. GUIS = {}
  53. def gui_pygame():
  54. print 'Starting pygame GUI...'
  55. import pygame, colorsys
  56. pygame.init()
  57. print 'Pygame init'
  58. dispinfo = pygame.display.Info()
  59. DISP_WIDTH = 640
  60. DISP_HEIGHT = 480
  61. if dispinfo.current_h > 0 and dispinfo.current_w > 0:
  62. DISP_WIDTH = dispinfo.current_w
  63. DISP_HEIGHT = dispinfo.current_h
  64. print 'Pygame info'
  65. WIDTH = DISP_WIDTH
  66. if options.pg_width > 0:
  67. WIDTH = options.pg_width
  68. HEIGHT = DISP_HEIGHT
  69. if options.pg_height > 0:
  70. HEIGHT = options.pg_height
  71. flags = 0
  72. if options.fullscreen:
  73. flags |= pygame.FULLSCREEN
  74. disp = pygame.display.set_mode((WIDTH, HEIGHT), flags)
  75. print 'Disp acquire'
  76. PFAC = HEIGHT / 128.0
  77. clock = pygame.time.Clock()
  78. print 'Pygame GUI initialized, running...'
  79. while True:
  80. disp.scroll(-1, 0)
  81. disp.fill((0, 0, 0), (WIDTH - 1, 0, 1, HEIGHT))
  82. idx = 0
  83. for cli, note in sorted(playing_notes.items(), key = lambda pair: pair[0]):
  84. pitch = note[0]
  85. col = colorsys.hls_to_rgb(float(idx) / len(clients), note[1]/512.0, 1.0)
  86. col = [int(i*255) for i in col]
  87. disp.fill(col, (WIDTH - 1, HEIGHT - pitch * PFAC - PFAC, 1, PFAC))
  88. idx += 1
  89. pygame.display.flip()
  90. for ev in pygame.event.get():
  91. if ev.type == pygame.KEYDOWN:
  92. if ev.key == pygame.K_ESCAPE:
  93. thread.interrupt_main()
  94. pygame.quit()
  95. exit()
  96. clock.tick(60)
  97. GUIS['pygame'] = gui_pygame
  98. PORT = 13676
  99. factor = options.factor
  100. print 'Factor:', factor
  101. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  102. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  103. if options.bind_addr:
  104. addr, _, port = options.bind_addr.partition(':')
  105. if not port:
  106. port = '12074'
  107. s.bind((addr, int(port)))
  108. clients = []
  109. uid_groups = {}
  110. type_groups = {}
  111. s.sendto(str(Packet(CMD.PING)), ('255.255.255.255', PORT))
  112. s.settimeout(options.wait_time)
  113. try:
  114. while True:
  115. data, src = s.recvfrom(4096)
  116. clients.append(src)
  117. except socket.timeout:
  118. pass
  119. playing_notes = {}
  120. for cli in clients:
  121. playing_notes[cli] = (0, 0)
  122. print len(clients), 'detected clients'
  123. print 'Clients:'
  124. for cl in clients:
  125. print cl,
  126. s.sendto(str(Packet(CMD.CAPS)), cl)
  127. data, _ = s.recvfrom(4096)
  128. pkt = Packet.FromStr(data)
  129. print 'ports', pkt.data[0],
  130. tp = itos(pkt.data[1])
  131. print 'type', tp,
  132. uid = ''.join([itos(i) for i in pkt.data[2:]]).rstrip('\x00')
  133. print 'uid', uid
  134. if uid == '':
  135. uid = None
  136. uid_groups.setdefault(uid, []).append(cl)
  137. type_groups.setdefault(tp, []).append(cl)
  138. if options.test:
  139. ts, tms = int(options.test_delay), int(options.test_delay * 1000000) % 1000000
  140. s.sendto(str(Packet(CMD.PLAY, ts, tms, 440, options.volume)), cl)
  141. if not options.sync_test:
  142. time.sleep(options.test_delay)
  143. s.sendto(str(Packet(CMD.PLAY, ts, tms, 880, options.volume)), cl)
  144. if options.quit:
  145. s.sendto(str(Packet(CMD.QUIT)), cl)
  146. if options.silence:
  147. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), cl)
  148. if options.gui:
  149. gui_thr = threading.Thread(target=GUIS[options.gui], args=())
  150. gui_thr.setDaemon(True)
  151. gui_thr.start()
  152. if options.play:
  153. for i, val in enumerate(options.play):
  154. if val.startswith('@'):
  155. options.play[i] = int(val[1:])
  156. else:
  157. options.play[i] = int(440.0 * 2**((int(val) - 69)/12.0))
  158. for i, cl in enumerate(clients):
  159. 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)
  160. if not options.play_async:
  161. time.sleep(options.duration)
  162. exit()
  163. if options.test and options.sync_test:
  164. time.sleep(0.25)
  165. for cl in clients:
  166. s.sendto(str(Packet(CMD.PLAY, 0, 250000, 880, 255)), cl)
  167. if options.test or options.quit or options.silence:
  168. print uid_groups
  169. print type_groups
  170. exit()
  171. if options.random > 0:
  172. while True:
  173. for cl in clients:
  174. 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)
  175. time.sleep(options.random)
  176. if options.live or options.list_live:
  177. if options.gui:
  178. print 'Waiting a second for GUI init...'
  179. time.sleep(3.0)
  180. import midi
  181. from midi import sequencer
  182. S = sequencer.S
  183. if options.list_live:
  184. print sequencer.SequencerHardware()
  185. exit()
  186. seq = sequencer.SequencerRead(sequencer_resolution=120)
  187. client_set = set(clients)
  188. active_set = {} # note (pitch) -> [client]
  189. deferred_set = set() # pitches held due to sustain
  190. sustain_status = False
  191. client, _, port = options.live.partition(',')
  192. if client or port:
  193. seq.subscribe_port(client, port)
  194. seq.start_sequencer()
  195. if not options.gui: # FIXME
  196. seq.set_nonblock(False)
  197. while True:
  198. ev = S.event_input(seq.client)
  199. if ev is None:
  200. time.sleep(0)
  201. event = None
  202. if ev:
  203. if options.verbose:
  204. print 'SEQ:', ev
  205. if ev < 0:
  206. seq._error(ev)
  207. if ev.type == S.SND_SEQ_EVENT_NOTEON:
  208. event = midi.NoteOnEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  209. elif ev.type == S.SND_SEQ_EVENT_NOTEOFF:
  210. event = midi.NoteOffEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  211. elif ev.type == S.SND_SEQ_EVENT_CONTROLLER:
  212. event = midi.ControlChangeEvent(channel = ev.data.control.channel, control = ev.data.control.param, value = ev.data.control.value)
  213. elif ev.type == S.SND_SEQ_EVENT_PGMCHANGE:
  214. event = midi.ProgramChangeEvent(channel = ev.data.control.channel, value = ev.data.control.value)
  215. elif ev.type == S.SND_SEQ_EVENT_PITCHBEND:
  216. event = midi.PitchWheelEvent(channel = ev.data.control.channel, pitch = ev.data.control.value)
  217. elif options.verbose:
  218. print 'WARNING: Unparsed event, type %r'%(ev.type,)
  219. continue
  220. if event is not None:
  221. if isinstance(event, midi.NoteOnEvent) and event.velocity == 0:
  222. event.__class__ = midi.NoteOffEvent
  223. if options.verbose:
  224. print 'EVENT:', event
  225. if isinstance(event, midi.NoteOnEvent):
  226. if event.pitch in active_set:
  227. if sustain_status:
  228. deferred_set.discard(event.pitch)
  229. inactive_set = client_set - set(sum(active_set.values(), []))
  230. if not inactive_set:
  231. print 'WARNING: Out of clients to do note %r; dropped'%(event.pitch,)
  232. continue
  233. cli = sorted(inactive_set)[0]
  234. s.sendto(str(Packet(CMD.PLAY, 65535, 0, int(440.0 * 2**((event.pitch-69)/12.0)), 2*event.velocity)), cli)
  235. active_set.setdefault(event.pitch, []).append(cli)
  236. playing_notes[cli] = (event.pitch, 2*event.velocity)
  237. if options.verbose:
  238. print 'LIVE:', event.pitch, '+ =>', active_set[event.pitch]
  239. elif isinstance(event, midi.NoteOffEvent):
  240. if event.pitch not in active_set or not active_set[event.pitch]:
  241. print 'WARNING: Deactivating inactive note %r'%(event.pitch,)
  242. continue
  243. if sustain_status:
  244. deferred_set.add(event.pitch)
  245. continue
  246. cli = active_set[event.pitch].pop()
  247. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), cli)
  248. playing_notes[cli] = (0, 0)
  249. if options.verbose:
  250. print 'LIVE:', event.pitch, '- =>', active_set[event.pitch]
  251. if sustain_status:
  252. print '...ignored (sustain on)'
  253. elif isinstance(event, midi.ControlChangeEvent):
  254. if event.control == 64 and not options.no_sustain:
  255. sustain_status = (event.value >= 64)
  256. if options.verbose:
  257. print 'LIVE: SUSTAIN', ('+' if sustain_status else '-')
  258. if not sustain_status:
  259. for pitch in deferred_set:
  260. if pitch not in active_set or not active_set[pitch]:
  261. print 'WARNING: Attempted deferred removal of inactive note %r'%(pitch,)
  262. continue
  263. for cli in active_set[pitch]:
  264. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), cli)
  265. playing_notes[cli] = (0, 0)
  266. del active_set[pitch]
  267. deferred_set.clear()
  268. for fname in args:
  269. try:
  270. iv = ET.parse(fname).getroot()
  271. except IOError:
  272. import traceback
  273. traceback.print_exc()
  274. print fname, ': Bad file'
  275. continue
  276. notestreams = iv.findall("./streams/stream[@type='ns']")
  277. groups = set([ns.get('group') for ns in notestreams if 'group' in ns.keys()])
  278. print len(notestreams), 'notestreams'
  279. print len(clients), 'clients'
  280. print len(groups), 'groups'
  281. class Route(object):
  282. def __init__(self, fattr, fvalue, group, excl=False):
  283. if fattr == 'U':
  284. self.map = uid_groups
  285. elif fattr == 'T':
  286. self.map = type_groups
  287. elif fattr == '0':
  288. self.map = {}
  289. else:
  290. raise ValueError('Not a valid attribute specifier: %r'%(fattr,))
  291. self.value = fvalue
  292. if group is not None and group not in groups:
  293. raise ValueError('Not a present group: %r'%(group,))
  294. self.group = group
  295. self.excl = excl
  296. @classmethod
  297. def Parse(cls, s):
  298. fspecs, _, grpspecs = map(lambda x: x.strip(), s.partition('='))
  299. fpairs = []
  300. ret = []
  301. for fspec in [i.strip() for i in fspecs.split(',')]:
  302. fattr, _, fvalue = map(lambda x: x.strip(), fspec.partition(':'))
  303. fpairs.append((fattr, fvalue))
  304. for part in [i.strip() for i in grpspecs.split(',')]:
  305. for fattr, fvalue in fpairs:
  306. if part[0] == '+':
  307. ret.append(Route(fattr, fvalue, part[1:], False))
  308. elif part[0] == '-':
  309. ret.append(Route(fattr, fvalue, part[1:], True))
  310. elif part[0] == '0':
  311. ret.append(Route(fattr, fvalue, None, True))
  312. else:
  313. raise ValueError('Not an exclusivity: %r'%(part[0],))
  314. return ret
  315. def Apply(self, cli):
  316. return cli in self.map.get(self.value, [])
  317. def __repr__(self):
  318. return '<Route of %r to %s:%s>'%(self.group, ('U' if self.map is uid_groups else 'T'), self.value)
  319. class RouteSet(object):
  320. def __init__(self, clis=None):
  321. if clis is None:
  322. clis = clients[:]
  323. self.clients = clis
  324. self.routes = []
  325. def Route(self, stream):
  326. testset = self.clients[:]
  327. grp = stream.get('group', 'ALL')
  328. if options.verbose:
  329. print 'Routing', grp, '...'
  330. excl = False
  331. for route in self.routes:
  332. if route.group == grp:
  333. if options.verbose:
  334. print '\tMatches route', route
  335. excl = excl or route.excl
  336. matches = filter(lambda x, route=route: route.Apply(x), testset)
  337. if matches:
  338. if options.verbose:
  339. print '\tUsing client', matches[0]
  340. self.clients.remove(matches[0])
  341. return matches[0]
  342. if options.verbose:
  343. print '\tNo matches, moving on...'
  344. if route.group is None:
  345. if options.verbose:
  346. print 'Encountered NULL route, removing from search space...'
  347. toremove = []
  348. for cli in testset:
  349. if route.Apply(cli):
  350. toremove.append(cli)
  351. for cli in toremove:
  352. if options.verbose:
  353. print '\tRemoving', cli, '...'
  354. testset.remove(cli)
  355. if excl:
  356. if options.verbose:
  357. print '\tExclusively routed, no route matched.'
  358. return None
  359. if not testset:
  360. if options.verbose:
  361. print '\tOut of clients, no route matched.'
  362. return None
  363. cli = testset[0]
  364. self.clients.remove(cli)
  365. if options.verbose:
  366. print '\tDefault route to', cli
  367. return cli
  368. routeset = RouteSet()
  369. for rspec in options.routes:
  370. try:
  371. routeset.routes.extend(Route.Parse(rspec))
  372. except Exception:
  373. import traceback
  374. traceback.print_exc()
  375. if options.verbose:
  376. print 'All routes:'
  377. for route in routeset.routes:
  378. print route
  379. class NSThread(threading.Thread):
  380. def drop_missed(self):
  381. nsq, cl = self._Thread__args
  382. cnt = 0
  383. while nsq and float(nsq[0].get('time'))*factor < time.time() - BASETIME:
  384. nsq.pop(0)
  385. cnt += 1
  386. if options.verbose:
  387. print self, 'dropped', cnt, 'notes due to miss'
  388. self._Thread__args = (nsq, cl)
  389. def wait_for(self, t):
  390. if t <= 0:
  391. return
  392. time.sleep(t)
  393. def run(self):
  394. nsq, cl = self._Thread__args
  395. for note in nsq:
  396. ttime = float(note.get('time'))
  397. pitch = int(note.get('pitch')) + options.transpose
  398. vel = int(note.get('vel'))
  399. dur = factor*float(note.get('dur'))
  400. while time.time() - BASETIME < factor*ttime:
  401. self.wait_for(factor*ttime - (time.time() - BASETIME))
  402. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), int(vel*2 * options.volume/255.0))), cl)
  403. if options.verbose:
  404. print (time.time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  405. self.wait_for(dur - ((time.time() - BASETIME) - factor*ttime))
  406. class NSThread(threading.Thread):
  407. def drop_missed(self):
  408. nsq, cl = self._Thread__args
  409. cnt = 0
  410. while nsq and float(nsq[0].get('time'))*factor < time.time() - BASETIME:
  411. nsq.pop(0)
  412. cnt += 1
  413. if options.verbose:
  414. print self, 'dropped', cnt, 'notes due to miss'
  415. self._Thread__args = (nsq, cl)
  416. def wait_for(self, t):
  417. if t <= 0:
  418. return
  419. time.sleep(t)
  420. def run(self):
  421. nsq, cl = self._Thread__args
  422. for note in nsq:
  423. ttime = float(note.get('time'))
  424. pitch = int(note.get('pitch')) + options.transpose
  425. vel = int(note.get('vel'))
  426. dur = factor*float(note.get('dur'))
  427. while time.time() - BASETIME < factor*ttime:
  428. self.wait_for(factor*ttime - (time.time() - BASETIME))
  429. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), int(vel*2 * options.volume/255.0))), cl)
  430. if options.verbose:
  431. print (time.time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  432. playing_notes[cl] = (pitch, vel*2)
  433. self.wait_for(dur - ((time.time() - BASETIME) - factor*ttime))
  434. playing_notes[cl] = (0, 0)
  435. if options.verbose:
  436. print '% 6.5f'%(time.time() - BASETIME,), cl, ': DONE'
  437. threads = []
  438. for ns in notestreams:
  439. cli = routeset.Route(ns)
  440. if cli:
  441. nsq = ns.findall('note')
  442. threads.append(NSThread(args=(nsq, cli)))
  443. if options.verbose:
  444. print 'Playback threads:'
  445. for thr in threads:
  446. print thr._Thread__args[1]
  447. BASETIME = time.time() - (options.seek*factor)
  448. if options.seek > 0:
  449. for thr in threads:
  450. thr.drop_missed()
  451. for thr in threads:
  452. thr.start()
  453. for thr in threads:
  454. thr.join()
  455. print fname, ': Done!'