broadcast.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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('-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)')
  26. parser.add_option('-r', '--route', dest='routes', action='append', help='Add a routing directive (see --route-help)')
  27. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; dump events and actual time (can slow down performance!)')
  28. parser.add_option('-W', '--wait-time', dest='wait_time', type='float', help='How long to wait for clients to initially respond (delays all broadcasts)')
  29. parser.add_option('--help-routes', dest='help_routes', action='store_true', help='Show help about routing directives')
  30. 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)
  31. options, args = parser.parse_args()
  32. if options.help_routes:
  33. 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.
  34. Routes are fully specified by:
  35. -The attribute to be routed on (either type "T", or UID "U")
  36. -The value of that attribute
  37. -The exclusivity of that route ("+" for inclusive, "-" for exclusive)
  38. -The stream group to be routed there.
  39. The syntax for that specification resembles the following:
  40. broadcast.py -r U:bass=+bass -r U:treble1,U:treble2=+treble -r T:BEEP=-beeps,-trk3,-trk5 -r U:noise=0
  41. 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.'''
  42. exit()
  43. PORT = 13676
  44. factor = options.factor
  45. print 'Factor:', factor
  46. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  47. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  48. clients = []
  49. uid_groups = {}
  50. type_groups = {}
  51. s.sendto(str(Packet(CMD.PING)), ('255.255.255.255', PORT))
  52. s.settimeout(options.wait_time)
  53. try:
  54. while True:
  55. data, src = s.recvfrom(4096)
  56. clients.append(src)
  57. except socket.timeout:
  58. pass
  59. print 'Clients:'
  60. for cl in clients:
  61. print cl,
  62. s.sendto(str(Packet(CMD.CAPS)), cl)
  63. data, _ = s.recvfrom(4096)
  64. pkt = Packet.FromStr(data)
  65. print 'ports', pkt.data[0],
  66. tp = itos(pkt.data[1])
  67. print 'type', tp,
  68. uid = ''.join([itos(i) for i in pkt.data[2:]]).rstrip('\x00')
  69. print 'uid', uid
  70. if uid == '':
  71. uid = None
  72. uid_groups.setdefault(uid, []).append(cl)
  73. type_groups.setdefault(tp, []).append(cl)
  74. if options.test:
  75. s.sendto(str(Packet(CMD.PLAY, 0, 250000, 440, 255)), cl)
  76. if not options.sync_test:
  77. time.sleep(0.25)
  78. s.sendto(str(Packet(CMD.PLAY, 0, 250000, 880, 255)), cl)
  79. if options.quit:
  80. s.sendto(str(Packet(CMD.QUIT)), cl)
  81. if options.silence:
  82. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), cl)
  83. if options.play:
  84. for i, val in enumerate(options.play):
  85. if val.startswith('@'):
  86. options.play[i] = int(val[1:])
  87. else:
  88. options.play[i] = int(440.0 * 2**((int(val) - 69)/12.0))
  89. for i, cl in enumerate(clients):
  90. 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)
  91. if not options.play_async:
  92. time.sleep(options.duration)
  93. exit()
  94. if options.test and options.sync_test:
  95. time.sleep(0.25)
  96. for cl in clients:
  97. s.sendto(str(Packet(CMD.PLAY, 0, 250000, 880, 255)), cl)
  98. if options.test or options.quit or options.silence:
  99. print uid_groups
  100. print type_groups
  101. exit()
  102. if options.random > 0:
  103. while True:
  104. for cl in clients:
  105. 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)
  106. time.sleep(options.random)
  107. if options.live or options.list_live:
  108. import midi
  109. from midi import sequencer
  110. S = sequencer.S
  111. if options.list_live:
  112. print sequencer.SequencerHardware()
  113. exit()
  114. seq = sequencer.SequencerRead(sequencer_resolution=120)
  115. client_set = set(clients)
  116. active_set = {} # note (pitch) -> client
  117. deferred_set = set() # pitches held due to sustain
  118. sustain_status = False
  119. client, _, port = options.live.partition(',')
  120. if client or port:
  121. seq.subscribe_port(client, port)
  122. seq.start_sequencer()
  123. while True:
  124. ev = S.event_input(seq.client)
  125. event = None
  126. if ev:
  127. if options.verbose:
  128. print 'SEQ:', 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, pitch = 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. event.__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. else:
  154. print 'WARNING: Note already activated: %r'%(event.pitch,),
  155. continue
  156. inactive_set = client_set - set(active_set.values())
  157. if not inactive_set:
  158. print 'WARNING: Out of clients to do note %r; dropped'%(event.pitch,)
  159. continue
  160. cli = random.choice(list(inactive_set))
  161. s.sendto(str(Packet(CMD.PLAY, 65535, 0, int(440.0 * 2**((event.pitch-69)/12.0)), 2*event.velocity)), cli)
  162. active_set[event.pitch] = cli
  163. elif isinstance(event, midi.NoteOffEvent):
  164. if event.pitch not in active_set:
  165. print 'WARNING: Deactivating inactive note %r'%(event.pitch,)
  166. continue
  167. if sustain_status:
  168. deferred_set.add(event.pitch)
  169. continue
  170. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), active_set[event.pitch])
  171. del active_set[event.pitch]
  172. elif isinstance(event, midi.ControlChangeEvent):
  173. if event.control == 64:
  174. sustain_status = (event.value >= 64)
  175. if not sustain_status:
  176. for pitch in deferred_set:
  177. if pitch not in active_set:
  178. print 'WARNING: Attempted deferred removal of inactive note %r'%(pitch,)
  179. continue
  180. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), active_set[pitch])
  181. del active_set[pitch]
  182. deferred_set.clear()
  183. for fname in args:
  184. try:
  185. iv = ET.parse(fname).getroot()
  186. except IOError:
  187. import traceback
  188. traceback.print_exc()
  189. print fname, ': Bad file'
  190. continue
  191. notestreams = iv.findall("./streams/stream[@type='ns']")
  192. groups = set([ns.get('group') for ns in notestreams if 'group' in ns.keys()])
  193. print len(notestreams), 'notestreams'
  194. print len(clients), 'clients'
  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 wait_for(self, t):
  294. if t <= 0:
  295. return
  296. time.sleep(t)
  297. def run(self):
  298. nsq, cl = self._Thread__args
  299. for note in nsq:
  300. ttime = float(note.get('time'))
  301. pitch = int(note.get('pitch')) + options.transpose
  302. vel = int(note.get('vel'))
  303. dur = factor*float(note.get('dur'))
  304. while time.time() - BASETIME < factor*ttime:
  305. self.wait_for(factor*ttime - (time.time() - BASETIME))
  306. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), vel*2)), cl)
  307. if options.verbose:
  308. print (time.time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  309. self.wait_for(dur - ((time.time() - BASETIME) - factor*ttime))
  310. if options.verbose:
  311. print '% 6.5f'%(time.time() - BASETIME,), cl, ': DONE'
  312. threads = []
  313. for ns in notestreams:
  314. cli = routeset.Route(ns)
  315. if cli:
  316. nsq = ns.findall('note')
  317. threads.append(NSThread(args=(nsq, cli)))
  318. if options.verbose:
  319. print 'Playback threads:'
  320. for thr in threads:
  321. print thr._Thread__args[1]
  322. BASETIME = time.time()
  323. for thr in threads:
  324. thr.start()
  325. for thr in threads:
  326. thr.join()
  327. print fname, ': Done!'