piano.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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', '--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')
  13. parser.add_option('-R', '--random', dest='random', type='float', help='Generate random notes at approximately this period')
  14. parser.add_option('--rand-low', dest='rand_low', type='int', help='Low frequency to randomly sample')
  15. parser.add_option('--rand-high', dest='rand_high', type='int', help='High frequency to randomly sample')
  16. 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')
  17. 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')
  18. parser.add_option('-q', '--quit', dest='quit', action='store_true', help='Instruct all clients to quit')
  19. 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")')
  20. 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')
  21. parser.add_option('-D', '--duration', dest='duration', type='float', help='How long to play this note for')
  22. parser.add_option('-V', '--volume', dest='volume', type='int', help='How loud to play this note (0-255)')
  23. parser.add_option('-s', '--silence', dest='silence', action='store_true', help='Instruct all clients to stop playing any active tones')
  24. 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)')
  25. parser.add_option('-r', '--route', dest='routes', action='append', help='Add a routing directive (see --route-help)')
  26. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; dump events and actual time (can slow down performance!)')
  27. parser.add_option('-W', '--wait-time', dest='wait_time', type='float', help='How long to wait for clients to initially respond (delays all broadcasts)')
  28. parser.add_option('-k', '--keyboard', dest='keyboard', action='store_true', help='Play using the keyboard')
  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=[])
  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. if options.keyboard:
  184. import pygame
  185. import midi
  186. from pygame import *
  187. pygame.init()
  188. size = width , height = 640,360
  189. screen = pygame.display.set_mode(size)
  190. #picture = pygame.image.load("aaaa.png")
  191. #surface = pygame.display.get_surface()
  192. pitch = 60
  193. velocity = 127
  194. client_set = set(clients)
  195. active_set = {} # note (pitch) -> client
  196. sustain_status = False
  197. sharp = 0
  198. while True:
  199. #surface.blit(picture,(0,0))
  200. #pygame.display.update()
  201. for event in pygame.event.get():
  202. if event.type == pygame.QUIT:
  203. pygame.quit()
  204. sys.exit()
  205. elif event.type == pygame.KEYDOWN:
  206. if event.key == K_a:
  207. pitch = 60
  208. if event.key == K_s:
  209. pitch = 62
  210. if event.key == K_d:
  211. pitch = 64
  212. if event.key == K_f:
  213. pitch = 65
  214. if event.key == K_g:
  215. pitch = 67
  216. if event.key == K_h:
  217. pitch = 69
  218. if event.key == K_j:
  219. pitch = 71
  220. if event.key == K_k:
  221. pitch = 72
  222. if event.key == K_l:
  223. pitch = 74
  224. if event.key == K_z:
  225. pitch = 48
  226. if event.key == K_x:
  227. pitch = 50
  228. if event.key == K_c:
  229. pitch = 52
  230. if event.key == K_v:
  231. pitch = 53
  232. if event.key == K_b:
  233. pitch = 55
  234. if event.key == K_n:
  235. pitch = 57
  236. if event.key == K_m:
  237. pitch = 59
  238. if event.key == K_q:
  239. pitch = 76
  240. if event.key == K_w:
  241. pitch = 77
  242. if event.key == K_e:
  243. pitch = 79
  244. if event.key == K_r:
  245. pitch = 81
  246. if event.key == K_t:
  247. pitch = 83
  248. if event.key == K_y:
  249. pitch = 84
  250. if event.key == K_u:
  251. pitch = 86
  252. if event.key == K_i:
  253. pitch = 88
  254. if event.key == K_o:
  255. pitch = 89
  256. if event.key == K_p:
  257. pitch = 91
  258. if event.key == K_LSHIFT:
  259. sharp = 1
  260. continue
  261. pitch = pitch + sharp
  262. mevent = midi.NoteOnEvent(channel = 0, pitch = pitch, velocity = velocity)
  263. if mevent.pitch in active_set:
  264. if sustain_status:
  265. deferred_set.discard(mevent.pitch)
  266. else:
  267. print 'WARNING: Note already activated: %r \n'%(mevent.pitch,),
  268. continue
  269. inactive_set = client_set - set(active_set.values())
  270. if not inactive_set:
  271. print 'WARNING: Out of clients to do note %r; dropped'%(mevent.pitch,)
  272. continue
  273. cli = random.choice(list(inactive_set))
  274. s.sendto(str(Packet(CMD.PLAY, 65535, 0, int(440.0 * 2**((mevent.pitch-69)/12.0)), 2*mevent.velocity)), cli)
  275. active_set[mevent.pitch] = cli
  276. elif event.type == pygame.KEYUP:
  277. if event.key == K_a:
  278. pitch = 60
  279. if event.key == K_s:
  280. pitch = 62
  281. if event.key == K_d:
  282. pitch = 64
  283. if event.key == K_f:
  284. pitch = 65
  285. if event.key == K_g:
  286. pitch = 67
  287. if event.key == K_h:
  288. pitch = 69
  289. if event.key == K_j:
  290. pitch = 71
  291. if event.key == K_k:
  292. pitch = 72
  293. if event.key == K_l:
  294. pitch = 74
  295. if event.key == K_z:
  296. pitch = 48
  297. if event.key == K_x:
  298. pitch = 50
  299. if event.key == K_c:
  300. pitch = 52
  301. if event.key == K_v:
  302. pitch = 53
  303. if event.key == K_b:
  304. pitch = 55
  305. if event.key == K_n:
  306. pitch = 57
  307. if event.key == K_m:
  308. pitch = 59
  309. if event.key == K_q:
  310. pitch = 76
  311. if event.key == K_w:
  312. pitch = 77
  313. if event.key == K_e:
  314. pitch = 79
  315. if event.key == K_r:
  316. pitch = 81
  317. if event.key == K_t:
  318. pitch = 83
  319. if event.key == K_y:
  320. pitch = 84
  321. if event.key == K_u:
  322. pitch = 86
  323. if event.key == K_i:
  324. pitch = 88
  325. if event.key == K_o:
  326. pitch = 89
  327. if event.key == K_p:
  328. pitch = 91
  329. if event.key == K_LSHIFT:
  330. sharp = 0
  331. continue
  332. mevent = midi.NoteOffEvent(channel = 0, pitch = pitch, velocity = velocity)
  333. if mevent.pitch not in active_set:
  334. print 'WARNING: Deactivating inactive note %r'%(mevent.pitch,)
  335. continue
  336. if sustain_status:
  337. deferred_set.add(mevent.pitch)
  338. continue
  339. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), active_set[mevent.pitch])
  340. del active_set[mevent.pitch]
  341. mevent = midi.NoteOffEvent(channel = 0, pitch = pitch + 1, velocity = velocity)
  342. if mevent.pitch not in active_set:
  343. print 'WARNING: Deactivating inactive note %r'%(mevent.pitch,)
  344. continue
  345. if sustain_status:
  346. deferred_set.add(mevent.pitch)
  347. continue
  348. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0)), active_set[mevent.pitch])
  349. del active_set[mevent.pitch]
  350. for fname in args:
  351. try:
  352. iv = ET.parse(fname).getroot()
  353. except IOError:
  354. import traceback
  355. traceback.print_exc()
  356. print fname, ': Bad file'
  357. continue
  358. notestreams = iv.findall("./streams/stream[@type='ns']")
  359. groups = set([ns.get('group') for ns in notestreams if 'group' in ns.keys()])
  360. print len(notestreams), 'notestreams'
  361. print len(clients), 'clients'
  362. print len(groups), 'groups'
  363. class Route(object):
  364. def __init__(self, fattr, fvalue, group, excl=False):
  365. if fattr == 'U':
  366. self.map = uid_groups
  367. elif fattr == 'T':
  368. self.map = type_groups
  369. else:
  370. raise ValueError('Not a valid attribute specifier: %r'%(fattr,))
  371. self.value = fvalue
  372. if group is not None and group not in groups:
  373. raise ValueError('Not a present group: %r'%(group,))
  374. self.group = group
  375. self.excl = excl
  376. @classmethod
  377. def Parse(cls, s):
  378. fspecs, _, grpspecs = map(lambda x: x.strip(), s.partition('='))
  379. fpairs = []
  380. ret = []
  381. for fspec in [i.strip() for i in fspecs.split(',')]:
  382. fattr, _, fvalue = map(lambda x: x.strip(), fspec.partition(':'))
  383. fpairs.append((fattr, fvalue))
  384. for part in [i.strip() for i in grpspecs.split(',')]:
  385. for fattr, fvalue in fpairs:
  386. if part[0] == '+':
  387. ret.append(Route(fattr, fvalue, part[1:], False))
  388. elif part[0] == '-':
  389. ret.append(Route(fattr, fvalue, part[1:], True))
  390. elif part[0] == '0':
  391. ret.append(Route(fattr, fvalue, None, True))
  392. else:
  393. raise ValueError('Not an exclusivity: %r'%(part[0],))
  394. return ret
  395. def Apply(self, cli):
  396. return cli in self.map.get(self.value, [])
  397. def __repr__(self):
  398. return '<Route of %r to %s:%s>'%(self.group, ('U' if self.map is uid_groups else 'T'), self.value)
  399. class RouteSet(object):
  400. def __init__(self, clis=None):
  401. if clis is None:
  402. clis = clients[:]
  403. self.clients = clis
  404. self.routes = []
  405. def Route(self, stream):
  406. testset = self.clients[:]
  407. grp = stream.get('group', 'ALL')
  408. if options.verbose:
  409. print 'Routing', grp, '...'
  410. excl = False
  411. for route in self.routes:
  412. if route.group == grp:
  413. if options.verbose:
  414. print '\tMatches route', route
  415. excl = excl or route.excl
  416. matches = filter(lambda x, route=route: route.Apply(x), testset)
  417. if matches:
  418. if options.verbose:
  419. print '\tUsing client', matches[0]
  420. self.clients.remove(matches[0])
  421. return matches[0]
  422. if options.verbose:
  423. print '\tNo matches, moving on...'
  424. if route.group is None:
  425. if options.verbose:
  426. print 'Encountered NULL route, removing from search space...'
  427. toremove = []
  428. for cli in testset:
  429. if route.Apply(cli):
  430. toremove.append(cli)
  431. for cli in toremove:
  432. if options.verbose:
  433. print '\tRemoving', cli, '...'
  434. testset.remove(cli)
  435. if excl:
  436. if options.verbose:
  437. print '\tExclusively routed, no route matched.'
  438. return None
  439. if not testset:
  440. if options.verbose:
  441. print '\tOut of clients, no route matched.'
  442. return None
  443. cli = testset[0]
  444. self.clients.remove(cli)
  445. if options.verbose:
  446. print '\tDefault route to', cli
  447. return cli
  448. routeset = RouteSet()
  449. for rspec in options.routes:
  450. try:
  451. routeset.routes.extend(Route.Parse(rspec))
  452. except Exception:
  453. import traceback
  454. traceback.print_exc()
  455. if options.verbose:
  456. print 'All routes:'
  457. for route in routeset.routes:
  458. print route
  459. class NSThread(threading.Thread):
  460. def wait_for(self, t):
  461. if t <= 0:
  462. return
  463. time.sleep(t)
  464. def run(self):
  465. nsq, cl = self._Thread__args
  466. for note in nsq:
  467. ttime = float(note.get('time'))
  468. pitch = int(note.get('pitch'))
  469. vel = int(note.get('vel'))
  470. dur = factor*float(note.get('dur'))
  471. while time.time() - BASETIME < factor*ttime:
  472. self.wait_for(factor*ttime - (time.time() - BASETIME))
  473. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), vel*2)), cl)
  474. if options.verbose:
  475. print (time.time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  476. self.wait_for(dur - ((time.time() - BASETIME) - factor*ttime))
  477. if options.verbose:
  478. print '% 6.5f'%(time.time() - BASETIME,), cl, ': DONE'
  479. threads = []
  480. for ns in notestreams:
  481. cli = routeset.Route(ns)
  482. if cli:
  483. nsq = ns.findall('note')
  484. threads.append(NSThread(args=(nsq, cli)))
  485. if options.verbose:
  486. print 'Playback threads:'
  487. for thr in threads:
  488. print thr._Thread__args[1]
  489. BASETIME = time.time()
  490. for thr in threads:
  491. thr.start()
  492. for thr in threads:
  493. thr.join()
  494. print fname, ': Done!'