broadcast.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. import socket
  2. import sys
  3. import struct
  4. import time
  5. import xml.etree.ElementTree as ET
  6. import threading
  7. import thread
  8. import optparse
  9. import random
  10. import itertools
  11. import re
  12. import os
  13. from packet import Packet, CMD, PLF, itos, OBLIGATE_POLYPHONE
  14. parser = optparse.OptionParser()
  15. 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)')
  16. parser.add_option('-T', '--transpose', dest='transpose', type='int', help='Transpose by a set amount of semitones (positive or negative)')
  17. 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')
  18. parser.add_option('--wait-test', dest='wait_test', action='store_true', help='Wait for user input before moving to the next client tested')
  19. parser.add_option('-R', '--random', dest='random', type='float', help='Generate random notes at approximately this period')
  20. parser.add_option('--rand-low', dest='rand_low', type='int', help='Low frequency to randomly sample')
  21. parser.add_option('--rand-high', dest='rand_high', type='int', help='High frequency to randomly sample')
  22. 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')
  23. 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')
  24. parser.add_option('--no-sustain', dest='no_sustain', action='store_true', help='Don\'t use sustain hacks in live mode')
  25. parser.add_option('-q', '--quit', dest='quit', action='store_true', help='Instruct all clients to quit')
  26. 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")')
  27. 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')
  28. parser.add_option('-D', '--duration', dest='duration', type='float', help='How long to play this note for')
  29. parser.add_option('-V', '--volume', dest='volume', type='float', help='Master volume [0.0, 1.0]')
  30. parser.add_option('-s', '--silence', dest='silence', action='store_true', help='Instruct all clients to stop playing any active tones')
  31. parser.add_option('-S', '--seek', dest='seek', type='float', help='Start time in seconds (scaled by --factor)')
  32. 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)')
  33. parser.add_option('-c', '--clamp', dest='clamp', action='store_true', help='Clamp over-the-wire amplitudes to 0.0-1.0')
  34. parser.add_option('-r', '--route', dest='routes', action='append', help='Add a routing directive (see --route-help)')
  35. parser.add_option('--clear-routes', dest='routes', action='store_const', const=[], help='Clear routes previously specified (including the default)')
  36. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; dump events and actual time (can slow down performance!)')
  37. parser.add_option('-W', '--wait-time', dest='wait_time', type='float', help='How long to wait between pings for clients to initially respond (delays all broadcasts)')
  38. parser.add_option('--tries', dest='tries', type='int', help='Number of ping packets to send')
  39. parser.add_option('-B', '--bind-addr', dest='bind_addr', help='The IP address (or IP:port) to bind to (influences the network to send to)')
  40. parser.add_option('--to', dest='to', action='append', help='IP:port pairs to send to (skips discovery)')
  41. parser.add_option('--port', dest='ports', action='append', type='int', help='Add a port to find clients on')
  42. parser.add_option('--clear-ports', dest='ports', action='store_const', const=[], help='Clear ports previously specified (including the default)')
  43. parser.add_option('--repeat', dest='repeat', action='store_true', help='Repeat the file playlist indefinitely')
  44. parser.add_option('-n', '--number', dest='number', type='int', help='Number of clients to use; if negative (default -1), use the product of stream count and the absolute value of this parameter')
  45. parser.add_option('--dry', dest='dry', action='store_true', help='Dry run--don\'t actually search for or play to clients, but pretend they exist (useful with -G)')
  46. parser.add_option('--pcm', dest='pcm', action='store_true', help='Use experimental PCM rendering')
  47. parser.add_option('--pcm-lead', dest='pcmlead', type='float', help='Seconds of leading PCM data to send')
  48. parser.add_option('--pcm-sync-every', dest='pcm_sync_every', type='int', help='How many PCM packets to wait before sending a SYNC event with buffer amounts')
  49. parser.add_option('--spin', dest='spin', action='store_true', help='Ignore delta times in the queue (busy loop the CPU) for higher accuracy')
  50. parser.add_option('--tapper', dest='tapper', type='float', help='When the main loop would wait this many seconds, wait instead for a keypress')
  51. parser.add_option('-G', '--gui', dest='gui', default='', help='set a GUI to use')
  52. parser.add_option('--pg-fullscreen', dest='fullscreen', action='store_true', help='Use a full-screen video mode')
  53. parser.add_option('--pg-width', dest='pg_width', type='int', help='Width of the pygame window')
  54. parser.add_option('--pg-height', dest='pg_height', type='int', help='Width of the pygame window')
  55. parser.add_option('--help-routes', dest='help_routes', action='store_true', help='Show help about routing directives')
  56. parser.set_defaults(routes=['T:DRUM=!perc,0'], random=0.0, rand_low=80, rand_high=2000, live=None, factor=1.0, duration=0.25, volume=1.0, wait_time=0.1, tries=5, play=[], transpose=0, seek=0.0, bind_addr='', to=[], ports=[13676, 13677], tapper=None, pg_width = 0, pg_height = 0, number=-1, pcmlead=0.1, pcm_sync_every=4096)
  57. options, args = parser.parse_args()
  58. tap_func = None
  59. play_time = time.time
  60. if options.tapper is not None:
  61. tap_play_time = 0.0
  62. play_time = lambda: tap_play_time
  63. if sys.platform.startswith('win'):
  64. import msvcrt
  65. tap_func = msvcrt.getch
  66. else:
  67. import termios, tty
  68. # https://stackoverflow.com/questions/1052107/reading-a-single-character-getch-style-in-python-is-not-working-in-unix
  69. def unix_tap_func():
  70. fd = sys.stdin.fileno() # 0?
  71. prev_settings = termios.tcgetattr(fd)
  72. try:
  73. mode = prev_settings[:]
  74. mode[tty.LFLAG] &= ~(termios.ECHO | termios.ICANON)
  75. termios.tcsetattr(fd, termios.TCSAFLUSH, mode)
  76. return sys.stdin.read(1)
  77. finally:
  78. termios.tcsetattr(fd, termios.TCSADRAIN, prev_settings)
  79. tap_func = unix_tap_func
  80. if options.help_routes:
  81. 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.
  82. Routes are fully specified by:
  83. -The attribute to be routed on (either type "T", or UID "U")
  84. -The value of that attribute
  85. -The exclusivity of that route ("+" for inclusive, "-" for exclusive, "!" for complete)
  86. -The stream group to be routed there, or 0 to null route.
  87. The first two may be replaced by a single '0' to null route a stream--effective only when used with an exclusive route.
  88. "Complete" exclusivity is valid only for obligate polyphones, and indicates that *all* matches are to receive the stream. In other cases, this will have the undesirable effect of routing only one stream.
  89. The special group ALL matches all streams. Regular expressions may be used to specify groups. Note that the first character is *not* part of the regular expression.
  90. The syntax for that specification resembles the following:
  91. broadcast.py -r U:bass=+bass -r U:treble1,U:treble2=+treble -r T:BEEP=-beeps,-trk3,-trk5 -r U:noise=0
  92. 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.'''
  93. exit()
  94. GUIS = {}
  95. BASETIME = play_time() # XXX fixes a race with the GUI
  96. factor = options.factor
  97. def gui_pygame():
  98. # XXX Racy, do this fast
  99. global tap_func, BASETIME, factor
  100. key_cond = threading.Condition()
  101. if options.tapper is not None:
  102. def pygame_tap_func():
  103. with key_cond:
  104. key_cond.wait()
  105. tap_func = pygame_tap_func
  106. print 'Starting pygame GUI...'
  107. import pygame, colorsys
  108. pygame.init()
  109. print 'Pygame init'
  110. dispinfo = pygame.display.Info()
  111. DISP_WIDTH = 640
  112. DISP_HEIGHT = 480
  113. if dispinfo.current_h > 0 and dispinfo.current_w > 0:
  114. DISP_WIDTH = dispinfo.current_w
  115. DISP_HEIGHT = dispinfo.current_h
  116. print 'Pygame info'
  117. WIDTH = DISP_WIDTH
  118. if options.pg_width > 0:
  119. WIDTH = options.pg_width
  120. HEIGHT = DISP_HEIGHT
  121. if options.pg_height > 0:
  122. HEIGHT = options.pg_height
  123. flags = 0
  124. if options.fullscreen:
  125. flags |= pygame.FULLSCREEN
  126. disp = pygame.display.set_mode((WIDTH, HEIGHT), flags)
  127. print 'Disp acquire'
  128. PFAC = HEIGHT / 128.0
  129. clock = pygame.time.Clock()
  130. font = pygame.font.SysFont(pygame.font.get_default_font(), 24)
  131. status = ('', 0.0)
  132. DISP_TIME = 4.0
  133. print 'Pygame GUI initialized, running...'
  134. while True:
  135. disp.scroll(-1, 0)
  136. disp.fill((0, 0, 0), (WIDTH - 1, 0, 1, HEIGHT))
  137. idx = 0
  138. for cli, note in sorted(playing_notes.items(), key = lambda pair: pair[0]):
  139. pitch = note[0]
  140. col = colorsys.hls_to_rgb(float(idx) / len(targets), note[1]/2.0, 1.0)
  141. col = [min(max(int(i*255), 0), 255) for i in col]
  142. disp.fill(col, (WIDTH - 1, HEIGHT - pitch * PFAC - PFAC, 1, PFAC))
  143. idx += 1
  144. tsurf = font.render('%0.3f' % ((play_time() - BASETIME) / factor,), True, (255, 255, 255), (0, 0, 0))
  145. disp.fill((0, 0, 0), tsurf.get_rect())
  146. disp.blit(tsurf, (0, 0))
  147. if time.time() - DISP_TIME < status[1]:
  148. ssurf = font.render(status[0], True, (0, 255, 0), (0, 0, 0))
  149. disp.blit(ssurf, (0, tsurf.get_height()))
  150. pygame.display.flip()
  151. for ev in pygame.event.get():
  152. if ev.type == pygame.KEYDOWN:
  153. with key_cond:
  154. key_cond.notify()
  155. if ev.key == pygame.K_ESCAPE:
  156. thread.interrupt_main()
  157. pygame.quit()
  158. exit()
  159. elif ev.key == pygame.K_LEFT:
  160. BASETIME += 5
  161. elif ev.key == pygame.K_RIGHT:
  162. BASETIME -= 5
  163. elif ev.key in (pygame.K_LEFTBRACKET, pygame.K_RIGHTBRACKET):
  164. pt = play_time()
  165. rtime = (pt - BASETIME) / factor
  166. if ev.key == pygame.K_LEFTBRACKET:
  167. factor /= 1.1
  168. elif ev.key == pygame.K_RIGHTBRACKET:
  169. factor *= 1.1
  170. BASETIME = pt - rtime * factor
  171. status = ('factor: ' + str(factor), time.time())
  172. clock.tick(60)
  173. GUIS['pygame'] = gui_pygame
  174. print 'Factor:', factor
  175. try:
  176. rows, columns = map(int, os.popen('stty size', 'r').read().split())
  177. except Exception:
  178. import traceback
  179. traceback.print_exc()
  180. rows, columns = 25, 80
  181. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  182. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  183. if options.bind_addr:
  184. addr, _, port = options.bind_addr.partition(':')
  185. if not port:
  186. port = '12074'
  187. s.bind((addr, int(port)))
  188. clients = set()
  189. targets = set()
  190. uid_groups = {}
  191. type_groups = {}
  192. ports = {}
  193. s.settimeout(options.wait_time)
  194. if options.to:
  195. for dst in options.to:
  196. host, _, port = dst.partition(':')
  197. clients.add((host, int(port)))
  198. else:
  199. if not options.dry:
  200. for PORT in options.ports:
  201. for num in xrange(options.tries):
  202. s.sendto(str(Packet(CMD.PING)), ('255.255.255.255', PORT))
  203. try:
  204. while True:
  205. data, src = s.recvfrom(4096)
  206. clients.add(src)
  207. except socket.timeout:
  208. pass
  209. print len(clients), 'detected clients'
  210. for num in xrange(options.tries):
  211. print 'Try', num
  212. for cl in clients:
  213. print cl,
  214. s.sendto(str(Packet(CMD.CAPS)), cl)
  215. data, _ = s.recvfrom(4096)
  216. pkt = Packet.FromStr(data)
  217. print 'ports', pkt.data[0],
  218. ports[cl] = pkt.data[0]
  219. tp = itos(pkt.data[1])
  220. print 'type', tp,
  221. uid = ''.join([itos(i) for i in pkt.data[2:]]).rstrip('\x00')
  222. print 'uid', uid
  223. if uid == '':
  224. uid = None
  225. uid_groups.setdefault(uid, set()).add(cl)
  226. type_groups.setdefault(tp, set()).add(cl)
  227. if options.test:
  228. ts, tms = int(options.duration), int(options.duration * 1000000) % 1000000
  229. if options.wait_test:
  230. s.sendto(str(Packet(CMD.PLAY, 65535, 0, 440, options.volume)), cl)
  231. raw_input('%r: Press enter to test next client...' %(cl,))
  232. s.sendto(str(Packet(CMD.PLAY, ts, tms, 880, options.volume)), cl)
  233. else:
  234. s.sendto(str(Packet(CMD.PLAY, ts, tms, 440, options.volume)), cl)
  235. if not options.sync_test:
  236. time.sleep(options.duration)
  237. s.sendto(str(Packet(CMD.PLAY, ts, tms, 880, options.volume)), cl)
  238. if options.quit:
  239. s.sendto(str(Packet(CMD.QUIT)), cl)
  240. if options.silence:
  241. for i in xrange(pkt.data[0]):
  242. s.sendto(str(Packet(CMD.PLAY, 0, 0, 0, 0.0, i)), cl)
  243. if pkt.data[0] == OBLIGATE_POLYPHONE:
  244. pkt.data[0] = 1
  245. for i in xrange(pkt.data[0]):
  246. targets.add(cl+(i,))
  247. playing_notes = {}
  248. for tg in targets:
  249. playing_notes[tg] = (0, 0)
  250. if options.gui:
  251. gui_thr = threading.Thread(target=GUIS[options.gui], args=())
  252. gui_thr.setDaemon(True)
  253. gui_thr.start()
  254. if options.play:
  255. for i, val in enumerate(options.play):
  256. if val.startswith('@'):
  257. options.play[i] = int(val[1:])
  258. else:
  259. options.play[i] = int(440.0 * 2**((int(val) - 69)/12.0))
  260. for i, cl in enumerate(targets):
  261. 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[2])), cl[:2])
  262. if not options.play_async:
  263. time.sleep(options.duration)
  264. exit()
  265. if options.test and options.sync_test:
  266. time.sleep(0.25)
  267. for cl in targets:
  268. s.sendto(str(Packet(CMD.PLAY, 0, 250000, 880, options.volume, cl[2])), cl[:2])
  269. if options.test or options.quit or options.silence:
  270. print uid_groups
  271. print type_groups
  272. exit()
  273. if options.random > 0:
  274. while True:
  275. for cl in targets:
  276. s.sendto(str(Packet(CMD.PLAY, int(options.random), int(1000000*(options.random-int(options.random))), random.randint(options.rand_low, options.rand_high), options.volume, cl[2])), cl[:2])
  277. time.sleep(options.random)
  278. if options.live or options.list_live:
  279. if options.gui:
  280. print 'Waiting a second for GUI init...'
  281. time.sleep(3.0)
  282. import midi
  283. from midi import sequencer
  284. S = sequencer.S
  285. if options.list_live:
  286. print sequencer.SequencerHardware()
  287. exit()
  288. seq = sequencer.SequencerRead(sequencer_resolution=120)
  289. client_set = set(targets)
  290. active_set = {} # note (pitch) -> [client]
  291. deferred_set = set() # pitches held due to sustain
  292. sustain_status = False
  293. client, _, port = options.live.partition(',')
  294. if client or port:
  295. seq.subscribe_port(client, port)
  296. seq.start_sequencer()
  297. if not options.gui: # FIXME
  298. seq.set_nonblock(False)
  299. while True:
  300. ev = S.event_input(seq.client)
  301. if ev is None:
  302. time.sleep(0)
  303. event = None
  304. if ev:
  305. if options.verbose:
  306. print 'SEQ:', ev
  307. if ev < 0:
  308. seq._error(ev)
  309. if ev.type == S.SND_SEQ_EVENT_NOTEON:
  310. event = midi.NoteOnEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  311. elif ev.type == S.SND_SEQ_EVENT_NOTEOFF:
  312. event = midi.NoteOffEvent(channel = ev.data.note.channel, pitch = ev.data.note.note, velocity = ev.data.note.velocity)
  313. elif ev.type == S.SND_SEQ_EVENT_CONTROLLER:
  314. event = midi.ControlChangeEvent(channel = ev.data.control.channel, control = ev.data.control.param, value = ev.data.control.value)
  315. elif ev.type == S.SND_SEQ_EVENT_PGMCHANGE:
  316. event = midi.ProgramChangeEvent(channel = ev.data.control.channel, value = ev.data.control.value)
  317. elif ev.type == S.SND_SEQ_EVENT_PITCHBEND:
  318. event = midi.PitchWheelEvent(channel = ev.data.control.channel, pitch = ev.data.control.value)
  319. elif options.verbose:
  320. print 'WARNING: Unparsed event, type %r'%(ev.type,)
  321. continue
  322. if event is not None:
  323. if isinstance(event, midi.NoteOnEvent) and event.velocity == 0:
  324. event.__class__ = midi.NoteOffEvent
  325. if options.verbose:
  326. print 'EVENT:', event
  327. if isinstance(event, midi.NoteOnEvent):
  328. if event.pitch in active_set:
  329. if sustain_status:
  330. deferred_set.discard(event.pitch)
  331. inactive_set = client_set - set(sum(active_set.values(), []))
  332. if not inactive_set:
  333. print 'WARNING: Out of clients to do note %r; dropped'%(event.pitch,)
  334. continue
  335. cli = sorted(inactive_set)[0]
  336. s.sendto(str(Packet(CMD.PLAY, 65535, 0, int(440.0 * 2**((event.pitch-69)/12.0)), event.velocity / 127.0, cli[2])), cli[:2])
  337. active_set.setdefault(event.pitch, []).append(cli)
  338. playing_notes[cli] = (event.pitch, event.velocity / 127.0)
  339. if options.verbose:
  340. print 'LIVE:', event.pitch, '+ =>', active_set[event.pitch]
  341. elif isinstance(event, midi.NoteOffEvent):
  342. if event.pitch not in active_set or not active_set[event.pitch]:
  343. print 'WARNING: Deactivating inactive note %r'%(event.pitch,)
  344. continue
  345. if sustain_status:
  346. deferred_set.add(event.pitch)
  347. continue
  348. cli = active_set[event.pitch].pop()
  349. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0, cli[2])), cli[:2])
  350. playing_notes[cli] = (0, 0)
  351. if options.verbose:
  352. print 'LIVE:', event.pitch, '- =>', active_set[event.pitch]
  353. if sustain_status:
  354. print '...ignored (sustain on)'
  355. elif isinstance(event, midi.ControlChangeEvent):
  356. if event.control == 64 and not options.no_sustain:
  357. sustain_status = (event.value >= 64)
  358. if options.verbose:
  359. print 'LIVE: SUSTAIN', ('+' if sustain_status else '-')
  360. if not sustain_status:
  361. for pitch in deferred_set:
  362. if pitch not in active_set or not active_set[pitch]:
  363. print 'WARNING: Attempted deferred removal of inactive note %r'%(pitch,)
  364. continue
  365. for cli in active_set[pitch]:
  366. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0, cli[2])), cli[:2])
  367. playing_notes[cli] = (0, 0)
  368. del active_set[pitch]
  369. deferred_set.clear()
  370. if options.repeat:
  371. args = itertools.cycle(args)
  372. for fname in args:
  373. if options.pcm and not fname.endswith('.iv'):
  374. print 'PCM: play', fname
  375. if fname == '-':
  376. import wave
  377. pcr = wave.open(sys.stdin)
  378. samprate = pcr.getframerate()
  379. pcr.read = pcr.readframes
  380. else:
  381. try:
  382. import audiotools
  383. pcr = audiotools.open(fname).to_pcm()
  384. assert pcr.channels == 1 and pcr.bits_per_sample == 16 and pcr.sample_rate == 44100
  385. samprate = pcr.sample_rate
  386. except ImportError:
  387. import wave
  388. pcr = wave.open(fname, 'r')
  389. assert pcr.getnchannels() == 1 and pcr.getsampwidth() == 2 and pcr.getframerate() == 44100
  390. samprate = pcr.getframerate()
  391. pcr.read = pcr.readframes
  392. def read_all(fn, n):
  393. buf = ''
  394. while len(buf) < n:
  395. nbuf = fn.read(n - len(buf))
  396. if not isinstance(nbuf, str):
  397. nbuf = nbuf.to_bytes(False, True)
  398. buf += nbuf
  399. return buf
  400. BASETIME = play_time() - options.pcmlead
  401. sampcnt = 0
  402. buf = read_all(pcr, 32)
  403. pcnt = 0
  404. print 'PCM: pcr', pcr, 'BASETIME', BASETIME, 'buf', len(buf)
  405. while len(buf) >= 32:
  406. frag = buf[:32]
  407. buf = buf[32:]
  408. for cl in clients:
  409. s.sendto(struct.pack('>L', CMD.PCM) + frag, cl)
  410. pcnt += 1
  411. if pcnt >= options.pcm_sync_every:
  412. for cl in clients:
  413. s.sendto(str(Packet(CMD.PCMSYN, int(options.pcmlead * samprate))), cl)
  414. print 'PCMSYN'
  415. pcnt = 0
  416. sampcnt += len(frag) / 2
  417. delay = max(0, BASETIME + (sampcnt / float(samprate)) - play_time())
  418. #print sampcnt, delay
  419. if delay > 0:
  420. time.sleep(delay)
  421. if len(buf) < 32:
  422. buf += read_all(pcr, 32 - len(buf))
  423. print 'PCM: exit'
  424. continue
  425. try:
  426. if fname.endswith('.ivz'):
  427. import gzip
  428. ivf = gzip.open(fname, 'rb')
  429. elif fname.endswith('.ivb'):
  430. import bz2
  431. ivf = bz2.BZ2File(fname, 'r')
  432. else:
  433. ivf = open(fname, 'rb')
  434. iv = ET.parse(ivf).getroot()
  435. except IOError:
  436. import traceback
  437. traceback.print_exc()
  438. print fname, ': Bad file'
  439. continue
  440. notestreams = iv.findall("./streams/stream[@type='ns']")
  441. groups = set([ns.get('group') for ns in notestreams if 'group' in ns.keys()])
  442. number = (len(notestreams) * abs(options.number) if options.number < 0 else options.number)
  443. print len(notestreams), 'notestreams'
  444. print len(clients), 'clients'
  445. print len(targets), 'targets'
  446. print len(groups), 'groups'
  447. print number, 'clients used (number)'
  448. class Route(object):
  449. def __init__(self, fattr, fvalue, group, excl=False, complete=False):
  450. if fattr == 'U':
  451. self.map = uid_groups
  452. elif fattr == 'T':
  453. self.map = type_groups
  454. elif fattr == '0':
  455. self.map = {}
  456. else:
  457. raise ValueError('Not a valid attribute specifier: %r'%(fattr,))
  458. self.value = fvalue
  459. self.group = group
  460. self.excl = excl
  461. self.complete = complete
  462. @classmethod
  463. def Parse(cls, s):
  464. fspecs, _, grpspecs = map(lambda x: x.strip(), s.partition('='))
  465. fpairs = []
  466. ret = []
  467. for fspec in [i.strip() for i in fspecs.split(',')]:
  468. fattr, _, fvalue = map(lambda x: x.strip(), fspec.partition(':'))
  469. fpairs.append((fattr, fvalue))
  470. for part in [i.strip() for i in grpspecs.split(',')]:
  471. for fattr, fvalue in fpairs:
  472. if part[0] == '+':
  473. ret.append(Route(fattr, fvalue, part[1:], False))
  474. elif part[0] == '-':
  475. ret.append(Route(fattr, fvalue, part[1:], True))
  476. elif part[0] == '!':
  477. ret.append(Route(fattr, fvalue, part[1:], True, True))
  478. elif part[0] == '0':
  479. ret.append(Route(fattr, fvalue, None, True))
  480. else:
  481. raise ValueError('Not an exclusivity: %r'%(part[0],))
  482. return ret
  483. def Apply(self, cli):
  484. return cli[:2] in self.map.get(self.value, [])
  485. def __repr__(self):
  486. return '<Route of %r to %s:%s>'%(self.group, ('U' if self.map is uid_groups else 'T'), self.value)
  487. class RouteSet(object):
  488. def __init__(self, clis=None):
  489. if clis is None:
  490. clis = set(targets)
  491. self.clients = list(clis)
  492. self.routes = []
  493. def Route(self, stream):
  494. testset = self.clients
  495. grp = stream.get('group', 'ALL')
  496. if options.verbose:
  497. print 'Routing', grp, '...'
  498. excl = False
  499. for route in self.routes:
  500. if route.group is not None and re.match(route.group, grp) is not None:
  501. if options.verbose:
  502. print '\tMatches route', route
  503. excl = excl or route.excl
  504. matches = filter(lambda x, route=route: route.Apply(x), testset)
  505. if matches:
  506. if route.complete:
  507. if options.verbose:
  508. print '\tUsing ALL clients:', matches
  509. for cl in matches:
  510. self.clients.remove(matches[0])
  511. if ports.get(matches[0][:2]) == OBLIGATE_POLYPHONE:
  512. self.clients.append(matches[0])
  513. return matches
  514. if options.verbose:
  515. print '\tUsing client', matches[0]
  516. self.clients.remove(matches[0])
  517. if ports.get(matches[0][:2]) == OBLIGATE_POLYPHONE:
  518. self.clients.append(matches[0])
  519. return [matches[0]]
  520. if options.verbose:
  521. print '\tNo matches, moving on...'
  522. if route.group is None:
  523. if options.verbose:
  524. print 'Encountered NULL route, removing from search space...'
  525. toremove = []
  526. for cli in testset:
  527. if route.Apply(cli):
  528. toremove.append(cli)
  529. for cli in toremove:
  530. if options.verbose:
  531. print '\tRemoving', cli, '...'
  532. testset.remove(cli)
  533. if excl:
  534. if options.verbose:
  535. print '\tExclusively routed, no route matched.'
  536. return []
  537. if not testset:
  538. if options.verbose:
  539. print '\tOut of clients, no route matched.'
  540. return []
  541. cli = list(testset)[0]
  542. self.clients.remove(cli)
  543. if ports.get(cli[:2]) == OBLIGATE_POLYPHONE:
  544. self.clients.append(cli)
  545. if options.verbose:
  546. print '\tDefault route to', cli
  547. return [cli]
  548. routeset = RouteSet()
  549. for rspec in options.routes:
  550. try:
  551. routeset.routes.extend(Route.Parse(rspec))
  552. except Exception:
  553. import traceback
  554. traceback.print_exc()
  555. if options.verbose:
  556. print 'All routes:'
  557. for route in routeset.routes:
  558. print route
  559. class NSThread(threading.Thread):
  560. def __init__(self, *args, **kwargs):
  561. threading.Thread.__init__(self, *args, **kwargs)
  562. self.done = False
  563. self.cur_offt = None
  564. self.next_t = None
  565. def actuate_missed(self):
  566. nsq, cls = self._Thread__args
  567. dur = None
  568. i = 0
  569. while nsq and float(nsq[0].get('time'))*factor <= play_time() - BASETIME:
  570. i += 1
  571. note = nsq.pop(0)
  572. ttime = float(note.get('time'))
  573. if note.tag == 'art':
  574. val = float(note.get('value'))
  575. idx = int(note.get('index'))
  576. global_ = note.get('global') is not None
  577. if not options.dry:
  578. for cl in cls:
  579. s.sendto(str(Packet(CMD.ARTP, OBLIGATE_POLYPHONE if global_ else cl[2], idx, val)), cl[:2])
  580. if options.verbose:
  581. print (play_time() - BASETIME), cl, ': ARTP', cl[2], idx, val
  582. continue
  583. pitch = float(note.get('pitch')) + options.transpose
  584. ampl = float(note.get('ampl', float(note.get('vel', 127.0)) / 127.0))
  585. dur = factor*float(note.get('dur'))
  586. pl_dur = dur if options.tapper is None else 65535
  587. if options.verbose:
  588. print (play_time() - BASETIME) / options.factor, ': PLAY', pitch, dur, ampl
  589. if options.dry:
  590. playing_notes[self.nsid] = (pitch, ampl)
  591. else:
  592. amp = ampl * options.volume
  593. if options.clamp:
  594. amp = max(min(amp, 1.0), 0.0)
  595. flags = 0
  596. if note.get('par', None):
  597. flags |= PLF.SAMEPHASE
  598. for cl in cls:
  599. s.sendto(str(Packet(CMD.PLAY, int(pl_dur), int((pl_dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), amp, cl[2], flags)), cl[:2])
  600. playing_notes[cl] = (pitch, ampl)
  601. if i > 0 and dur is not None:
  602. self.cur_offt = ttime + dur / options.factor
  603. else:
  604. if self.cur_offt:
  605. if factor * self.cur_offt <= play_time() - BASETIME:
  606. if options.verbose:
  607. print '% 6.5f'%((play_time() - BASETIME) / factor,), ': DONE'
  608. if options.tapper is not None:
  609. for cl in cls:
  610. s.sendto(str(Packet(CMD.PLAY, 0, 1, 1, 0.0, cl[2])), cl[:2])
  611. self.cur_offt = None
  612. if options.dry:
  613. playing_notes[self.nsid] = (0, 0)
  614. else:
  615. for cl in cls:
  616. playing_notes[cl] = (0, 0)
  617. next_act = None
  618. if nsq:
  619. next_act = float(nsq[0].get('time'))
  620. if options.verbose:
  621. print 'NEXT_ACT:', next_act, 'CUR_OFFT:', self.cur_offt
  622. self.next_t = min((next_act or float('inf'), self.cur_offt or float('inf')))
  623. self.done = not (nsq or self.cur_offt)
  624. def drop_missed(self):
  625. nsq, cl = self._Thread__args
  626. cnt = 0
  627. while nsq and float(nsq[0].get('time'))*factor < play_time() - BASETIME:
  628. nsq.pop(0)
  629. cnt += 1
  630. if options.verbose:
  631. print self, 'dropped', cnt, 'notes due to miss'
  632. def wait_for(self, t):
  633. if t <= 0:
  634. return
  635. time.sleep(t)
  636. def run(self):
  637. nsq, cls = self._Thread__args
  638. for note in nsq:
  639. ttime = float(note.get('time'))
  640. if note.tag == 'art':
  641. val = float(note.get('value'))
  642. idx = int(note.get('index'))
  643. global_ = note.get('global') is not None
  644. if not options.dry:
  645. for cl in cls:
  646. s.sendto(str(Packet(CMD.ARTP, OBLIGATE_POLYPHONE if global_ else cl[2], idx, val)), cl[:2])
  647. if options.verbose:
  648. print (play_time() - BASETIME), cl, ': ARTP', cl[2], idx, val
  649. continue
  650. pitch = float(note.get('pitch')) + options.transpose
  651. ampl = float(note.get('ampl', float(note.get('vel', 127.0)) / 127.0))
  652. dur = factor*float(note.get('dur'))
  653. while play_time() - BASETIME < factor*ttime:
  654. self.wait_for(factor*ttime - (play_time() - BASETIME))
  655. if options.dry:
  656. cl = self.nsid # XXX hack
  657. else:
  658. for cl in cls:
  659. s.sendto(str(Packet(CMD.PLAY, int(dur), int((dur*1000000)%1000000), int(440.0 * 2**((pitch-69)/12.0)), ampl * options.volume, cl[2])), cl[:2])
  660. if options.verbose:
  661. print (play_time() - BASETIME), cl, ': PLAY', pitch, dur, vel
  662. playing_notes[cl] = (pitch, ampl)
  663. self.wait_for(dur - ((play_time() - BASETIME) - factor*ttime))
  664. playing_notes[cl] = (0, 0)
  665. if options.verbose:
  666. print '% 6.5f'%(play_time() - BASETIME,), cl, ': DONE'
  667. threads = {}
  668. if options.dry:
  669. for nsid, ns in enumerate(notestreams):
  670. nsq = ns.findall('note')
  671. nsq.sort(key=lambda x: float(x.get('time')))
  672. threads[ns] = NSThread(args=(nsq, set()))
  673. threads[ns].nsid = nsid
  674. targets = threads.values() # XXX hack
  675. else:
  676. nscycle = itertools.cycle(notestreams)
  677. for idx, ns in zip(xrange(number), nscycle):
  678. clis = routeset.Route(ns)
  679. for cli in clis:
  680. nsq = ns.findall('*')
  681. nsq.sort(key=lambda x: float(x.get('time')))
  682. if ns in threads:
  683. threads[ns]._Thread__args[1].add(cli)
  684. else:
  685. threads[ns] = NSThread(args=(nsq, set([cli])))
  686. if options.verbose:
  687. print 'Playback threads:'
  688. for thr in threads.values():
  689. print thr._Thread__args[1]
  690. BASETIME = play_time() - (options.seek*factor)
  691. ENDTIME = max(max(float(n.get('time', 0.0)) + float(n.get('dur', 0.0)) for n in thr._Thread__args[0]) for thr in threads.values())
  692. print 'Playtime is', ENDTIME
  693. if options.seek > 0:
  694. for thr in threads.values():
  695. thr.drop_missed()
  696. spin_phase = 0
  697. SPINNERS = ['-', '\\', '|', '/']
  698. while not all(thr.done for thr in threads.values()):
  699. for thr in threads.values():
  700. if thr.next_t is None or factor * thr.next_t <= play_time() - BASETIME:
  701. thr.actuate_missed()
  702. delta = factor * min(thr.next_t for thr in threads.values() if thr.next_t is not None) + BASETIME - play_time()
  703. if delta == float('inf'):
  704. print 'WARNING: Infinite postponement detected! Did all notestreams finish?'
  705. break
  706. if options.verbose:
  707. print 'TICK DELTA:', delta
  708. else:
  709. sys.stdout.write('\x1b[G\x1b[K[%s]' % (
  710. ('#' * int((play_time() - BASETIME) * (columns - 2) / (ENDTIME * factor)) + SPINNERS[spin_phase]).ljust(columns - 2),
  711. ))
  712. fmtime = '% 8.3f' % ((play_time() - BASETIME) / factor,)
  713. sys.stdout.write('\x1b[%dG%s' % (
  714. 2 if play_time() - BASETIME > factor * ENDTIME / 2 else columns - len(fmtime) - 1,
  715. fmtime,
  716. ))
  717. sys.stdout.flush()
  718. spin_phase += 1
  719. if spin_phase >= len(SPINNERS):
  720. spin_phase = 0
  721. if delta >= 0 and not options.spin:
  722. if tap_func is not None:
  723. try:
  724. delta_on = factor * min(thr.next_t for thr in threads.values() if thr.next_t is not None and thr.next_t != thr.cur_offt)
  725. except ValueError:
  726. delta_on = float('inf')
  727. if delta_on >= options.tapper:
  728. if options.verbose:
  729. print 'TAP'
  730. tap_func()
  731. else:
  732. time.sleep(delta)
  733. tap_play_time += delta
  734. else:
  735. time.sleep(delta)
  736. print fname, ': Done!'