broadcast.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 ev < 0:
  128. seq._error(ev)
  129. if ev.type == S.SND_SEQ_EVENT_NOTEON:
  130. event = midi.NoteOnEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  131. elif ev.type == S.SND_SEQ_EVENT_NOTEOFF:
  132. event = midi.NoteOffEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  133. elif ev.type == S.SND_SEQ_EVENT_CONTROLLER:
  134. event = midi.ControlChangeEvent(channel = ev.data.control.channel, control = ev.data.control.param, value = ev.data.control.value)
  135. elif ev.type == S.SND_SEQ_EVENT_PGMCHANGE:
  136. event = midi.ProgramChangeEvent(channel = ev.data.control.channel, pitch = ev.data.control.value)
  137. elif ev.type == S.SND_SEQ_EVENT_PITCHBEND:
  138. event = midi.PitchWheelEvent(channel = ev.data.control.channel, pitch = ev.data.control.value)
  139. elif options.verbose:
  140. print 'WARNING: Unparsed event, type %r'%(ev.type,)
  141. continue
  142. if event is not None:
  143. if isinstance(event, midi.NoteOnEvent) and event.velocity == 0:
  144. ev.__class__ = midi.NoteOffEvent
  145. if options.verbose:
  146. print 'EVENT:', event
  147. if isinstance(event, midi.NoteOnEvent):
  148. if event.pitch in active_set:
  149. if sustain_status:
  150. deferred_set.discard(event.pitch)
  151. else:
  152. print 'WARNING: Note already activated: %r'%(event.pitch,),
  153. continue
  154. inactive_set = client_set - set(active_set.values())
  155. if not inactive_set:
  156. print 'WARNING: Out of clients to do note %r; dropped'%(event.pitch,)
  157. continue
  158. cli = random.choice(list(inactive_set))
  159. s.sendto(str(Packet(CMD.PLAY, 65535, 0, int(440.0 * 2**((event.pitch-69)/12.0)), 2*event.velocity)), cli)
  160. active_set[event.pitch] = cli
  161. elif isinstance(event, midi.NoteOffEvent):
  162. if event.pitch not in active_set:
  163. print 'WARNING: Deactivating inactive note %r'%(event.pitch,)
  164. continue
  165. if sustain_status:
  166. deferred_set.add(event.pitch)
  167. continue
  168. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), active_set[event.pitch])
  169. del active_set[event.pitch]
  170. elif isinstance(event, midi.ControlChangeEvent):
  171. if event.control == 64:
  172. sustain_status = (event.value >= 64)
  173. if not sustain_status:
  174. for pitch in deferred_set:
  175. if pitch not in active_set:
  176. print 'WARNING: Attempted deferred removal of inactive note %r'%(pitch,)
  177. continue
  178. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), active_set[pitch])
  179. del active_set[pitch]
  180. deferred_set.clear()
  181. try:
  182. iv = ET.parse(args[0]).getroot()
  183. except IOError:
  184. import traceback
  185. traceback.print_exc()
  186. print 'Bad file'
  187. exit()
  188. notestreams = iv.findall("./streams/stream[@type='ns']")
  189. groups = set([ns.get('group') for ns in notestreams if 'group' in ns.keys()])
  190. print len(notestreams), 'notestreams'
  191. print len(clients), 'clients'
  192. print len(groups), 'groups'
  193. class Route(object):
  194. def __init__(self, fattr, fvalue, group, excl=False):
  195. if fattr == 'U':
  196. self.map = uid_groups
  197. elif fattr == 'T':
  198. self.map = type_groups
  199. else:
  200. raise ValueError('Not a valid attribute specifier: %r'%(fattr,))
  201. self.value = fvalue
  202. if group is not None and group not in groups:
  203. raise ValueError('Not a present group: %r'%(group,))
  204. self.group = group
  205. self.excl = excl
  206. @classmethod
  207. def Parse(cls, s):
  208. fspecs, _, grpspecs = map(lambda x: x.strip(), s.partition('='))
  209. fpairs = []
  210. ret = []
  211. for fspec in [i.strip() for i in fspecs.split(',')]:
  212. fattr, _, fvalue = map(lambda x: x.strip(), fspec.partition(':'))
  213. fpairs.append((fattr, fvalue))
  214. for part in [i.strip() for i in grpspecs.split(',')]:
  215. for fattr, fvalue in fpairs:
  216. if part[0] == '+':
  217. ret.append(Route(fattr, fvalue, part[1:], False))
  218. elif part[0] == '-':
  219. ret.append(Route(fattr, fvalue, part[1:], True))
  220. elif part[0] == '0':
  221. ret.append(Route(fattr, fvalue, None, True))
  222. else:
  223. raise ValueError('Not an exclusivity: %r'%(part[0],))
  224. return ret
  225. def Apply(self, cli):
  226. return cli in self.map.get(self.value, [])
  227. def __repr__(self):
  228. return '<Route of %r to %s:%s>'%(self.group, ('U' if self.map is uid_groups else 'T'), self.value)
  229. class RouteSet(object):
  230. def __init__(self, clis=None):
  231. if clis is None:
  232. clis = clients[:]
  233. self.clients = clis
  234. self.routes = []
  235. def Route(self, stream):
  236. testset = self.clients[:]
  237. grp = stream.get('group', 'ALL')
  238. if options.verbose:
  239. print 'Routing', grp, '...'
  240. excl = False
  241. for route in self.routes:
  242. if route.group == grp:
  243. if options.verbose:
  244. print '\tMatches route', route
  245. excl = excl or route.excl
  246. matches = filter(lambda x, route=route: route.Apply(x), testset)
  247. if matches:
  248. if options.verbose:
  249. print '\tUsing client', matches[0]
  250. self.clients.remove(matches[0])
  251. return matches[0]
  252. if options.verbose:
  253. print '\tNo matches, moving on...'
  254. if route.group is None:
  255. if options.verbose:
  256. print 'Encountered NULL route, removing from search space...'
  257. toremove = []
  258. for cli in testset:
  259. if route.Apply(cli):
  260. toremove.append(cli)
  261. for cli in toremove:
  262. if options.verbose:
  263. print '\tRemoving', cli, '...'
  264. testset.remove(cli)
  265. if excl:
  266. if options.verbose:
  267. print '\tExclusively routed, no route matched.'
  268. return None
  269. if not testset:
  270. if options.verbose:
  271. print '\tOut of clients, no route matched.'
  272. return None
  273. cli = testset[0]
  274. self.clients.remove(cli)
  275. if options.verbose:
  276. print '\tDefault route to', cli
  277. return cli
  278. routeset = RouteSet()
  279. for rspec in options.routes:
  280. try:
  281. routeset.routes.extend(Route.Parse(rspec))
  282. except Exception:
  283. import traceback
  284. traceback.print_exc()
  285. if options.verbose:
  286. print 'All routes:'
  287. for route in routeset.routes:
  288. print route
  289. class NSThread(threading.Thread):
  290. def wait_for(self, t):
  291. if t <= 0:
  292. return
  293. time.sleep(t)
  294. def run(self):
  295. nsq, cl = self._Thread__args
  296. for note in nsq:
  297. ttime = float(note.get('time'))
  298. pitch = int(note.get('pitch')) + options.transpose
  299. vel = int(note.get('vel'))
  300. dur = factor*float(note.get('dur'))
  301. while time.time() - BASETIME < factor*ttime:
  302. self.wait_for(factor*ttime - (time.time() - BASETIME))
  303. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), vel*2)), cl)
  304. if options.verbose:
  305. print (time.time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  306. self.wait_for(dur - ((time.time() - BASETIME) - factor*ttime))
  307. if options.verbose:
  308. print '% 6.5f'%(time.time() - BASETIME,), cl, ': DONE'
  309. threads = []
  310. for ns in notestreams:
  311. cli = routeset.Route(ns)
  312. if cli:
  313. nsq = ns.findall('note')
  314. threads.append(NSThread(args=(nsq, cli)))
  315. if options.verbose:
  316. print 'Playback threads:'
  317. for thr in threads:
  318. print thr._Thread__args[1]
  319. BASETIME = time.time()
  320. for thr in threads:
  321. thr.start()
  322. for thr in threads:
  323. thr.join()