-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellmusic.sh
More file actions
executable file
·566 lines (495 loc) · 19.4 KB
/
Copy pathshellmusic.sh
File metadata and controls
executable file
·566 lines (495 loc) · 19.4 KB
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat << 'USAGE'
ShellMusic, a terminal music player built on fzf and mpv
usage
shellmusic [-h|--help]
environment variables
MUSIC_DIR folder to browse, defaults to ~/Music
VOLUME_STEP percent the volume changes per 9/0 press, defaults to 10
MUSIC_ROWS terminal rows requested on start, defaults to 40
MUSIC_COLS terminal columns requested on start, defaults to 110
MUSIC_NO_RESIZE set to 1 to skip the automatic terminal resize
dependencies
fzf, mpv, python3
USAGE
}
if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
usage
exit 0
fi
MUSIC_DIR="${MUSIC_DIR:-$HOME/Music}"
VOLUME_STEP="${VOLUME_STEP:-10}" # how much volume changes per 9/0 press
if ! command -v fzf &>/dev/null; then
echo "fzf is not installed. Install with: sudo apt install fzf"
exit 1
fi
if ! command -v mpv &>/dev/null; then
echo "mpv is not installed. Install with: sudo apt install mpv"
exit 1
fi
if ! command -v python3 &>/dev/null; then
echo "python3 is not installed. Install with: sudo apt install python3"
exit 1
fi
if [ ! -d "$MUSIC_DIR" ]; then
echo "Directory '$MUSIC_DIR' not found."
exit 1
fi
if [ ! -r "$MUSIC_DIR" ]; then
echo "Directory '$MUSIC_DIR' is not readable (check permissions)."
exit 1
fi
WORKDIR=$(mktemp -d /tmp/music_player.XXXXXX)
cleanup() {
rm -rf "$WORKDIR"
printf '\033]0;\007' # reset terminal window title
}
trap cleanup EXIT
# asks the terminal to resize to a roomier size using the standard xterm
# window resize escape sequence, xterm, kitty, alacritty and foot honor it
# while GNOME Terminal and Windows Terminal ignore it on purpose, harmless
# either way and can be skipped with MUSIC_NO_RESIZE=1, MUSIC_ROWS and
# MUSIC_COLS are validated first since this runs under set -e and a non
# numeric value would otherwise abort the whole script
if [ -t 1 ] && [ -z "${MUSIC_NO_RESIZE:-}" ]; then
_resize_rows="${MUSIC_ROWS:-40}"
_resize_cols="${MUSIC_COLS:-110}"
if [[ "$_resize_rows" =~ ^[0-9]+$ ]] && [[ "$_resize_cols" =~ ^[0-9]+$ ]]; then
printf '\033[8;%d;%dt' "$_resize_rows" "$_resize_cols"
sleep 0.1 # give the terminal a moment to actually resize
fi
unset _resize_rows _resize_cols
fi
# this input conf only overrides the volume keys, everything else still
# comes from mpv's own default bindings via input-default-bindings
INPUT_CONF="$WORKDIR/input.conf"
cat > "$INPUT_CONF" << EOF
9 add volume -${VOLUME_STEP}
0 add volume ${VOLUME_STEP}
r playlist-shuffle
u playlist-unshuffle
EOF
# recognized audio extensions, reused in every find call below
AUDIO_MATCH=(-iname "*.mp3" -o -iname "*.flac" -o -iname "*.wav" -o -iname "*.m4a" -o -iname "*.ogg" -o -iname "*.opus")
# colors shared by every screen (browser and now-playing view)
C_TITLE=$'\033[1;97m'
C_SUB=$'\033[38;5;110m'
C_DIM=$'\033[38;5;240m'
C_KEY=$'\033[1;38;5;222m'
C_TXT=$'\033[38;5;245m'
C_ACCENT=$'\033[1;38;5;213m'
C_BORDER=$'\033[38;5;244m'
C_RESET=$'\033[0m'
# off means sequential and on means shuffle, it persists across folders
# and menu redraws and is toggled from inside the listing itself, not a
# separate screen
SHUFFLE_MODE="off"
# the now playing box is sized from the current terminal width every time
# it's drawn, see compute_box below, instead of a fixed width, so it
# doesn't break in narrow terminals or overflow in wide ones
INNER=60
RULE_INNER=""
BOX_TOP=""
BOX_MID=""
BOX_BOTTOM=""
compute_box() {
local cols
cols=$(tput cols 2>/dev/null || echo 68)
INNER=$(( cols - 4 ))
(( INNER < 40 )) && INNER=40
(( INNER > 100 )) && INNER=100
RULE_INNER=$(printf '\342\224\200%.0s' $(seq 1 $INNER))
BOX_TOP=$(printf '%s\342\225\255%s\342\225\256%s' "$C_BORDER" "$RULE_INNER" "$C_RESET")
BOX_MID=$(printf '%s\342\224\234%s\342\224\244%s' "$C_BORDER" "$RULE_INNER" "$C_RESET")
BOX_BOTTOM=$(printf '%s\342\225\260%s\342\225\257%s' "$C_BORDER" "$RULE_INNER" "$C_RESET")
}
print_box_line() {
local content="$1"
local visible
visible=$(printf '%s' "$content" | sed -r 's/\x1b\[[0-9;]*m//g')
local pad=$(( INNER - 2 - ${#visible} ))
(( pad < 0 )) && pad=0
printf "%s\342\224\202%s %s%*s %s\342\224\202%s\n" \
"$C_BORDER" "$C_RESET" "$content" "$pad" "" "$C_BORDER" "$C_RESET"
}
# fzf --ansi shows colored entries but reports the plain, color stripped,
# text back once something is chosen, so lookups must key off this
strip_ansi() {
printf '%s' "$1" | sed -r 's/\x1b\[[0-9;]*m//g'
}
# monitor.py connects to mpv's IPC socket and draws, in a separate process,
# the current track title, a progress bar with remaining time, a VU meter
# driven by the real audio level through the astats filter, and the playlist
# with the current track highlighted, it also updates the terminal window
# title to the playing track, it runs in the background and only writes to
# the terminal, it never reads the keyboard, so it never interferes with
# mpv's own controls, which stay in the foreground
MONITOR_SCRIPT="$WORKDIR/monitor.py"
cat > "$MONITOR_SCRIPT" << 'PYEOF'
import sys, socket, json, time, random, os, shutil
sock_path = sys.argv[1]
BAR_W = 44
MAX_LIST_W = 70
VU_BLOCKS = "▁▂▃▄▅▆▇█"
N_VU_BARS = 14
C_FILL = "\033[38;5;213m"
C_EMPTY = "\033[38;5;238m"
C_TXT = "\033[38;5;245m"
C_KEY = "\033[38;5;222m"
C_VU_LO = "\033[38;5;110m"
C_VU_MID = "\033[38;5;222m"
C_VU_HI = "\033[38;5;203m"
C_ACCENT = "\033[1;38;5;213m"
C_TITLE = "\033[1;97m"
C_DIM = "\033[38;5;240m"
C_DIM2 = "\033[38;5;238m"
C_CUR = "\033[1;38;5;213m"
RESET = "\033[0m"
def query(properties):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(0.5)
try:
s.connect(sock_path)
except OSError:
return None
for i, p in enumerate(properties):
s.sendall((json.dumps({"command": ["get_property", p], "request_id": i}) + "\n").encode())
got, buf = {}, b""
start = time.time()
while len(got) < len(properties) and time.time() - start < 0.4:
try:
data = s.recv(65536)
except socket.timeout:
break
if not data:
break
buf += data
while b"\n" in buf:
line, buf = buf.split(b"\n", 1)
if not line.strip():
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
if "request_id" in obj:
got[obj["request_id"]] = obj.get("data")
s.close()
return [got.get(i) for i in range(len(properties))]
def fmt_time(t):
if t is None:
return "--:--"
t = int(t)
m, s = divmod(t, 60)
h, m = divmod(m, 60)
return f"{h}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
def db_to_frac(db, floor=-45.0, ceil=-2.0):
if db is None or db != db:
db = floor
db = max(floor, min(ceil, db))
return (db - floor) / (ceil - floor)
def track_label(entry):
if not isinstance(entry, dict):
return "?"
title = entry.get("title")
if title:
return title
fn = entry.get("filename", "?")
base = os.path.basename(fn)
return os.path.splitext(base)[0]
def truncate(s, width):
if len(s) <= width:
return s
if width <= 1:
return s[:width]
return s[: width - 1] + "…"
props = ["time-pos", "duration", "time-remaining", "percent-pos", "volume",
"af-metadata/va", "media-title", "playlist", "playlist-pos"]
cols, rows = shutil.get_terminal_size(fallback=(80, 24))
LIST_W = min(cols - 4, MAX_LIST_W)
if LIST_W < 20:
LIST_W = 20
# reserve room for the header/bar/VU meter and use whatever height is left
# for the track list
MAX_VISIBLE = max(5, rows - 16)
prev_title = None
misses = 0
frame = 0
total_lines = None
# two different patience budgets, a long one for the very first connection
# since mpv might be slow to create the socket on a loaded system, a slow
# disk, or a networked home directory, and a short one once we've connected
# at least once, since a string of misses after that means mpv actually
# exited and we want to notice quickly so this process doesn't linger
STARTUP_GRACE = 150 # ~22s @ 0.15s/try
POST_CONNECT_GRACE = 15 # ~2.3s @ 0.15s/try
ever_connected = False
while True:
vals = query(props)
if vals is None:
misses += 1
limit = POST_CONNECT_GRACE if ever_connected else STARTUP_GRACE
if misses > limit:
break
time.sleep(0.15)
continue
ever_connected = True
misses = 0
(time_pos, duration, time_remaining, percent_pos, volume, af,
media_title, playlist, playlist_pos) = vals
percent_pos = percent_pos or 0
if not media_title:
media_title = "Loading…"
if media_title != prev_title:
sys.stdout.write(f"\033]0;{media_title}\007")
prev_title = media_title
filled = max(0, min(BAR_W, int((percent_pos / 100.0) * BAR_W)))
bar = f"{C_FILL}{'█' * filled}{C_EMPTY}{'░' * (BAR_W - filled)}{RESET}"
level_db = None
if isinstance(af, dict):
try:
level_db = float(af.get("lavfi.astats.Overall.RMS_level"))
except (TypeError, ValueError):
level_db = None
intensity = db_to_frac(level_db)
rng = random.Random(frame)
vu_chars = []
for i in range(N_VU_BARS):
jitter = rng.uniform(0.55, 1.0)
h = max(0.0, min(1.0, intensity * jitter))
idx = int(h * (len(VU_BLOCKS) - 1))
color = C_VU_HI if h > 0.75 else (C_VU_MID if h > 0.4 else C_VU_LO)
vu_chars.append(f"{color}{VU_BLOCKS[idx]}{RESET}")
vu_line = " ".join(vu_chars)
now_playing = truncate(media_title, LIST_W)
line_now = f"{C_ACCENT}♫ {C_TITLE}{now_playing}{RESET}"
line_bar = f"{bar} {C_TXT}{fmt_time(time_pos)} / {fmt_time(duration)}{RESET} {C_KEY}-{fmt_time(time_remaining)}{RESET}"
line_vu = f"{vu_line} {C_TXT}vol {int(volume or 0)}%{RESET}"
out_lines = [line_now, line_bar, line_vu, ""]
if isinstance(playlist, list) and playlist:
n = len(playlist)
cur = playlist_pos if isinstance(playlist_pos, int) and playlist_pos >= 0 else 0
digits = len(str(n))
start = max(0, min(cur - MAX_VISIBLE // 2, n - MAX_VISIBLE))
start = max(0, start)
end = min(n, start + MAX_VISIBLE)
header = f"{C_DIM}TRACKLIST{RESET} {C_DIM2}({cur + 1}/{n}){RESET}"
if start > 0:
header += f" {C_DIM2}↑{start} more{RESET}"
out_lines.append(header)
for i in range(start, end):
entry = playlist[i]
label = track_label(entry)
idx_str = str(i + 1).rjust(digits, "0")
is_cur = (i == cur)
avail = LIST_W - digits - 3
label = truncate(label, max(1, avail))
if is_cur:
out_lines.append(f"{C_CUR}▶ {idx_str} {label}{RESET}")
else:
out_lines.append(f"{C_DIM2} {idx_str}{RESET} {C_TXT}{label}{RESET}")
remaining_below = n - end
pad_needed = MAX_VISIBLE - (end - start)
for _ in range(pad_needed):
out_lines.append("")
if remaining_below > 0:
out_lines.append(f"{C_DIM2}↓{remaining_below} more{RESET}")
else:
out_lines.append("")
else:
out_lines.append(f"{C_DIM}TRACKLIST{RESET}")
for _ in range(MAX_VISIBLE):
out_lines.append("")
out_lines.append("")
if total_lines is None:
total_lines = len(out_lines)
sys.stdout.write("\n" * total_lines)
sys.stdout.flush()
# keep the same number of lines on every frame
while len(out_lines) < total_lines:
out_lines.append("")
out_lines = out_lines[:total_lines]
move_up = f"\033[{total_lines}A\r"
body = "\n".join("\033[K" + l for l in out_lines) + "\n"
sys.stdout.write(move_up + body)
sys.stdout.flush()
frame += 1
time.sleep(0.12)
PYEOF
# plays a list of files, can be just one single track or several, meaning
# everything in a folder
play_tracks() {
local label="$1"; shift
local tracks=("$@")
local track_count=${#tracks[@]}
compute_box
local mode_display="sequential"
[ "$SHUFFLE_MODE" = "on" ] && mode_display="shuffle"
local np_date np_time
np_date=$(LC_TIME=en_US.UTF-8 date "+%A, %d %B %Y" 2>/dev/null || date "+%A, %d %B %Y")
np_time=$(date "+%H:%M:%S")
clear
echo "$BOX_TOP"
print_box_line "${C_ACCENT}NOW PLAYING${C_RESET}"
print_box_line "${C_TITLE}${label}${C_RESET} ${C_DIM}· ${track_count} track(s)${C_RESET}"
print_box_line "${C_SUB}${np_date}${C_RESET} ${C_DIM}·${C_RESET} ${C_SUB}${np_time}${C_RESET} ${C_DIM}·${C_RESET} ${C_ACCENT}${mode_display}${C_RESET}"
echo "$BOX_MID"
print_box_line "${C_KEY}space${C_RESET}${C_TXT} play/pause${C_RESET} ${C_KEY}← →${C_RESET}${C_TXT} seek 5s${C_RESET} ${C_KEY}> <${C_RESET}${C_TXT} next/prev${C_RESET}"
print_box_line "${C_KEY}9/0${C_RESET}${C_TXT} volume +/-${VOLUME_STEP}%${C_RESET} ${C_KEY}r${C_RESET}${C_TXT} shuffle${C_RESET} ${C_KEY}u${C_RESET}${C_TXT} unshuffle${C_RESET}"
print_box_line "${C_KEY}q${C_RESET}${C_TXT} back to menu${C_RESET}"
echo "$BOX_BOTTOM"
echo ""
local mpv_socket="$WORKDIR/mpv-$$.sock"
rm -f "$mpv_socket"
# background monitor that only reads the IPC socket and writes to the
# terminal, it never reads the keyboard, so mpv's own controls stay
# unaffected
python3 "$MONITOR_SCRIPT" "$mpv_socket" &
local monitor_pid=$!
local mpv_shuffle="no"
[ "$SHUFFLE_MODE" = "on" ] && mpv_shuffle="yes"
# mpv runs in the foreground, same as always, so it keeps reading keys
# normally
mpv \
--no-video \
--shuffle="$mpv_shuffle" \
--loop-playlist=no \
--input-ipc-server="$mpv_socket" \
--af=@va:astats=metadata=1:length=0.05:reset=1 \
--really-quiet \
--input-conf="$INPUT_CONF" \
--input-default-bindings=yes \
--input-vo-keyboard \
"${tracks[@]}" || true
kill "$monitor_pid" 2>/dev/null || true
wait "$monitor_pid" 2>/dev/null || true
rm -f "$mpv_socket"
printf '\033]0;ShellMusic\007'
}
# browses a given directory, lists its subfolders and its own tracks, plus
# quick actions to go up or play everything here, shuffle versus sequential
# is a keybind, Ctrl-S, shown live in the top bar, so it never takes up a
# row in the list or gets mistaken for a track
#
# the directory listing, meaning find plus per-subfolder counts, is only
# rebuilt when we actually land on a different directory, not on every loop
# iteration, toggling shuffle with Ctrl-S or returning from a subfolder just
# redraws the header and fzf call against the already cached entries,
# instead of re-reading the disk
#
# returns 1 when the user wants to quit the whole program, 0 when they just
# want to go back to the parent folder, using Esc or ..
browse() {
local dir="$1"
local -a subdirs tracks entries
local -A entry_action
local need_scan=1
while true; do
if [ "$need_scan" = "1" ]; then
subdirs=()
tracks=()
entries=()
entry_action=()
# follows symlinks with -L, so albums or playlists symlinked into
# MUSIC_DIR show up like any other folder or track
mapfile -t subdirs < <(find -L "$dir" -mindepth 1 -maxdepth 1 -type d | sort)
mapfile -t tracks < <(find -L "$dir" -mindepth 1 -maxdepth 1 -type f \( "${AUDIO_MATCH[@]}" \) | sort)
if [ ${#subdirs[@]} -eq 0 ] && [ ${#tracks[@]} -eq 0 ]; then
clear
local empty_rel="${dir#$MUSIC_DIR}"
[ -z "$empty_rel" ] && empty_rel="/"
echo -e "${C_DIM}${empty_rel}${C_RESET}"
echo -e "${C_TXT}(empty folder, no subfolders or audio tracks)${C_RESET}"
echo ""
echo -e "${C_DIM}Press any key to go back...${C_RESET}"
read -n 1 -s -r || true
[ "$dir" = "$MUSIC_DIR" ] && return 1
return 0
fi
# actions and folders get their own color + bracket/slash so they
# never look like a track name; tracks stay plain
if [ "$dir" != "$MUSIC_DIR" ]; then
local up_label="${C_ACCENT}[ .. ]${C_RESET}"
entries+=("$up_label")
entry_action["$(strip_ansi "$up_label")"]="UP"
fi
if [ ${#tracks[@]} -gt 0 ]; then
local play_all_label="${C_ACCENT}[ Play all here - ${#tracks[@]} tracks ]${C_RESET}"
entries+=("$play_all_label")
entry_action["$(strip_ansi "$play_all_label")"]="PLAYALL"
fi
local d name count label
for d in "${subdirs[@]}"; do
name=$(basename "$d")
count=$(find -L "$d" -type f \( "${AUDIO_MATCH[@]}" \) | wc -l)
label="${C_SUB}${name}/${C_RESET} ${C_DIM}(${count} tracks)${C_RESET}"
entries+=("$label")
entry_action["$(strip_ansi "$label")"]="DIR:$d"
done
local t base
for t in "${tracks[@]}"; do
base=$(basename "$t")
label="${C_TXT}${base%.*}${C_RESET}"
entries+=("$label")
entry_action["$(strip_ansi "$label")"]="TRACK:$t"
done
need_scan=0
fi
local mode_display="Sequential"
[ "$SHUFFLE_MODE" = "on" ] && mode_display="Shuffle"
local rel="${dir#$MUSIC_DIR}"
[ -z "$rel" ] && rel="/"
local header="${C_TITLE}SHELLMUSIC${C_RESET} ${C_DIM}${rel}${C_RESET} ${C_DIM}·${C_RESET} ${C_ACCENT}${mode_display}${C_RESET}
${C_DIM}Tab / Up Down navigate ${C_RESET}${C_KEY}Enter${C_DIM} choose ${C_RESET}${C_KEY}Ctrl-S${C_DIM} toggle shuffle ${C_RESET}${C_KEY}Esc${C_DIM} back / quit${C_RESET}"
printf '\033]0;ShellMusic\007'
local result key choice
result=$(printf '%s\n' "${entries[@]}" | fzf \
--ansi \
--height=100% \
--layout=reverse \
--border=rounded \
--margin=1,2 \
--prompt=" Search > " \
--header="$header" \
--header-first \
--color="prompt:magenta:bold,pointer:green:bold,marker:yellow,fg+:white:bold,bg+:236,hl:yellow,hl+:yellow:bold,border:blue,info:blue" \
--bind="tab:down,btab:up" \
--expect="ctrl-s" \
--cycle \
--no-multi \
--pointer=">" \
--marker="x" \
--info=inline \
) || result=""
key=$(printf '%s' "$result" | sed -n '1p')
choice=$(printf '%s' "$result" | sed -n '2p')
if [ "$key" = "ctrl-s" ]; then
if [ "$SHUFFLE_MODE" = "on" ]; then SHUFFLE_MODE="off"; else SHUFFLE_MODE="on"; fi
# entries and counts on disk didn't change, just redraw the header
continue
fi
if [ -z "$choice" ]; then
[ "$dir" = "$MUSIC_DIR" ] && return 1
return 0
fi
local action="${entry_action[$choice]:-}"
case "$action" in
UP)
return 0
;;
PLAYALL)
play_tracks "$(basename "$dir")" "${tracks[@]}"
;;
DIR:*)
browse "${action#DIR:}" || return 1
;;
TRACK:*)
local track="${action#TRACK:}"
play_tracks "$(basename "$track")" "$track"
;;
esac
done
}
browse "$MUSIC_DIR" || true