broadcast.py 18 KB

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