broadcast.py 19 KB

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