-
Notifications
You must be signed in to change notification settings - Fork 21
/
beatsaber-cli
executable file
·437 lines (361 loc) · 10.9 KB
/
beatsaber-cli
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python3
#
# beatsaber-cli, by Shawn Presser. July 2021.
#
# requirements:
#
# pip3 install ansi-styles ansi-escapes python-vlc
#
# example usage:
#
# beatsaber-cli ~/Downloads/beatsaber/dna/ExpertPlusStandard.dat
#
# get songs from https://bsaber.com/
#==============================================================================
# Functionality
#==============================================================================
import pdb
import sys
import os
import re
# utility funcs, classes, etc go here.
def asserting(cond):
if not cond:
pdb.set_trace()
assert(cond)
def has_stdin():
return not sys.stdin.isatty()
def reg(pat, flags=0):
return re.compile(pat, re.VERBOSE | flags)
#==============================================================================
# Cmdline
#==============================================================================
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description="""
TODO
""")
parser.add_argument('-v', '--verbose',
action="store_true",
help="verbose output" )
args = None
#==============================================================================
# Main
#==============================================================================
import json
from collections import namedtuple
from ansi_styles import ansiStyles as styles
class Renderer:
def __init__(self):
self.cmds = []
self(ansiEscapes.clearScreen)
self(ansiEscapes.cursorHide)
def __call__(self, msg):
self.cmds.append(msg)
def to(self, x, y):
self(ansiEscapes.cursorTo(x, y))
def flush(self):
print(''.join(self.cmds), end='', flush=True)
self.cmds.clear()
def viewport(self, w, h):
for line in range(h):
self(ansiEscapes.cursorTo(w, line) + ansiEscapes.eraseStartLine)
self(ansiEscapes.cursorTo(0, 0))
#arrows = "↑↓←→◜◝◟◞∎"
arrows = "↑↓←→↖↗↙↘∎"
class Note(namedtuple('Note', 'index time lineIndex lineLayer type cutDirection'.split())):
@property
def insignia(self):
return arrows[self.cutDirection]
@property
def upwards(self):
return "1↓←→11↙↘∎"[self.cutDirection] == "1"
@property
def downwards(self):
return "↑1←→↖↗11∎"[self.cutDirection] == "1"
@property
def leftwards(self):
return "↑↓1→1↗1↘∎"[self.cutDirection] == "1"
@property
def rightwards(self):
return "↑↓←1↖1↙1∎"[self.cutDirection] == "1"
@property
def left(self):
return "↑↓1→↖↗↙↘∎"[self.cutDirection] == "1"
@property
def right(self):
return "↑↓←1↖↗↙↘∎"[self.cutDirection] == "1"
@property
def up(self):
return "1↓←→↖↗↙↘∎"[self.cutDirection] == "1"
@property
def down(self):
return "↑1←→↖↗↙↘∎"[self.cutDirection] == "1"
def color(self, opacity=1.0):
if self.type == 0:
return (1.0, 0, 0, opacity)
elif self.type == 1:
return (0, 0, 1.0, opacity)
else:
return (96/255, 100/255, 105/255, opacity)
@property
def w(self):
return 3
@property
def h(self):
return 1
def secs(self, bpm):
return self.time / bpm * 60
@property
def x(self):
return self.lineIndex
@property
def y(self):
return 2 - self.lineLayer
class BeatsaberMap:
def __init__(self, info='info.dat'):
if isinstance(info, str):
with open(info) as f:
info = json.load(f)
self.info = info
def parse(self, file):
if isinstance(file, str):
with open(file) as f:
file = json.load(f)
notes = file['_notes']
#notes = [list(sorted(x.items())) for x in notes]
#notes = [[y[1] for y in x] for x in notes]
notes = [Note(index=i, **{k.lstrip('_'): v for k, v in x.items()}) for i, x in enumerate(notes)]
#return Track([(n.type, n.c, n.time / self.bpm * 60000, n.x, n.y) for n in notes])
return Song(self.info, notes)
from ansi_escapes import ansiEscapes
import subprocess
import vlc
def dovlc(cmd):
cmd = cmd.replace('\n', '\n ')
return subprocess.check_output(['osascript', '-e', f"""
tell application "VLC"
{cmd}
end tell
""".strip()])
def lerp(a, b, t):
return (b - a) * t + a
def lerprgb(a, b, t):
return tuple([lerp(x, y, t) for x, y in zip(a, b)])
def wherebetween(lo, hi, t):
return (t - lo) / (hi - lo)
def clamp(lo, hi, t):
if t < lo:
return lo
if t > hi:
return hi
return t
def blend(src, dst=(0.0, 0.0, 0.0, 1.0)):
sr, sg, sb, sa = src
dr, dg, db, da = dst
sr *= sa
sg *= sa
sb *= sa
dr *= (1 - sa)
dg *= (1 - sa)
db *= (1 - sa)
dr += sr * sa
dg += sg * sa
db += sb * sa
return (
clamp(0, 255, int(255*dr)),
clamp(0, 255, int(255*dg)),
clamp(0, 255, int(255*db))
)
from glob import glob
class Song:
def __init__(self, info, notes):
self.info = info
self.tracks = tuple(list(Track(self.bpm, tuple(note for note in notes if note.type == i)) for i in range(4)))
self.viewport_offset = (5, 5)
self.reset_viewport_offset()
@property
def bpm(self):
return self.info['_beatsPerMinute']
@property
def song_path(self):
return self.info['_songFilename']
def reset_viewport_offset(self):
size = os.get_terminal_size()
prev_offset = self.viewport_offset
self.viewport_offset = (
size.columns // 2 - 3*2,
size.lines // 2 - 2)
return prev_offset != self.viewport_offset
def resync(self, start):
elapsed_vlc = self.player.get_time()
while True:
time.sleep(0.001)
now = time.time()
now_vlc = self.player.get_time()
if elapsed_vlc != now_vlc:
return start - (now - start) + (now_vlc / 1000)
def resync_incremental(self, now, start, elapsed_vlc):
now_vlc = self.player.get_time()
if now_vlc != elapsed_vlc:
start += (now - start) - (now_vlc / 1000)
if self.reset_viewport_offset():
self.renderer(ansiEscapes.clearScreen)
self.renderer(ansiEscapes.cursorHide)
return now, start, now_vlc
def play(self):
self.player = vlc.MediaPlayer(self.song_path)
self.player.play()
try:
self.renderer = Renderer()
self.renderer.flush()
start = self.resync(time.time())
elapsed_vlc = self.player.get_time()
while self.player.is_playing():
#time.sleep(0.005)
now, start, elapsed_vlc = self.resync_incremental(time.time(), start, elapsed_vlc)
elapsed = (now - start)
notes = self.gather_notes(elapsed)
self.render_notes(self.renderer, notes, elapsed)
finally:
self.player.stop()
def last_note(self):
won = None
for kind, track in enumerate(self.tracks):
for note in track.notes:
if not won or note.time > won.time:
won = note
return won
def gather_notes(self, elapsed):
notes = []
for kind, track in enumerate(self.tracks):
notes.extend(track.at(elapsed))
return notes
def render_note(self, r, note, elapsed):
til = note.secs(self.bpm) - elapsed
before = 0.5 # notes show up this many seconds in advance
linger = -0.05 # notes hang around this many seconds after dying
if linger <= til <= before:
nx = 0+note.w*note.x+self.viewport_offset[0]
ny = 0+note.h*note.y+self.viewport_offset[1]
c = note.insignia
if til < 0:
t = clamp(0.0, 1.0, wherebetween(0, linger, til))
else:
t = clamp(0.0, 1.0, wherebetween(0, before, til))
# opacity = lerp(1.5, 0.5, 1 - (1 - t)**8) # good
opacity = lerp(1.5, 0.5, 1 - (1 - t)**10)
# opacity = 1.0
rgb = note.color(opacity=opacity)
bgColor = blend(rgb)
# fgBlend = (1.0, 1.0, 1.0, opacity)
fgBlend = (rgb[0] + 0.4, rgb[1] + 0.4, rgb[2] + 0.4, opacity)
fgColor = blend(fgBlend, rgb)
#fgColor = blend((1.0,1.0,1.0,opacity), (0.5,0.0,-0.5,1.0))
bg, bge = styles.bgColor.ansi16m(*bgColor), styles.bgColor.close
fg, fge = styles.color.ansi16m(*fgColor), styles.color.close
e = '\033[0m'
m = ''
nx += 1
if til > 0.0:
# m += '\033[1m'
m += '\033[3m' # italics
# if note.upwards:
# m += '\033[4m' # underline
r.to(nx, ny)
r(f'{fg}{bg}{m}{c}{e}{fge}{bge}')
elif til > 0:
# m += '\033[1m'
#m += '\033[3m' # italics
if note.upwards:
m += '\033[4m'
r.to(nx, ny)
r(f'{bg}{fg}{m}{c}{e}{bg}{fge}{bge}')
else:
if not note.downwards and not note.upwards:
m += '\033[9m'
# m += '\033[3m' # italics
dx = 0
dy = 0
if note.left:
dx -= 1
elif note.right:
dx += 1
elif note.up:
dy -= 1
elif note.down:
dy += 1
else:
if note.rightwards:
dx += 1
if note.leftwards:
dx -= 1
if note.upwards:
dy -= 1
dx *= 2
if note.downwards:
dy += 1
dx *= 2
if not note.upwards and not note.downwards and not note.leftwards and not note.rightwards:
dx += 1
r.to(nx + dx, ny + dy)
r(f'{m}{fg}{c}{fge}{e}')
def render_notes(self, r, notes, elapsed):
r.viewport(16 + self.viewport_offset[0], 8 + self.viewport_offset[1])
songname = ellipsize(os.path.basename(os.path.dirname(os.path.realpath(self.song_path))))
r(f'{songname}\n{int(elapsed/60.0):02d}m{int(elapsed%60.0):02d}s')
for note in sorted(notes, key=lambda x: x.time):
self.render_note(r, note, elapsed)
r.flush()
def ellipsize(s, n=30):
if len(s) > n:
return s[:(n-3)] + '...'
return s
import time
class Track:
def __init__(self, bpm, notes):
self.bpm = bpm
self.notes = notes
# def before(self, now):
# return tuple(n for n in self.notes if n.secs(self.bpm) <= now)
def at(self, now):
r = []
for i, note in enumerate(self.notes):
t = note.secs(self.bpm)
if abs(now - t) < 2.0:
r.append(note)
return r
def run():
if args.verbose:
print(args)
files = [os.path.realpath(file) for file in args.args]
while True:
# shuffle?
for file in files:
try:
os.chdir(os.path.dirname(file) or '.')
file = os.path.basename(file)
bs = BeatsaberMap()
song = bs.parse(file)
song.play()
except KeyboardInterrupt:
time.sleep(1.0)
def main():
try:
global args
if not args:
args, leftovers = parser.parse_known_args()
args.args = leftovers
return run()
except IOError:
# http://stackoverflow.com/questions/15793886/how-to-avoid-a-broken-pipe-error-when-printing-a-large-amount-of-formatted-data
try:
sys.stdout.close()
except IOError:
pass
try:
sys.stderr.close()
except IOError:
pass
if __name__ == "__main__":
main()