broadcast.py 17 KB

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