-
Notifications
You must be signed in to change notification settings - Fork 0
/
beats
719 lines (596 loc) · 16.7 KB
/
beats
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#!/usr/bin/env bash
#
# beats - Simple and fast music player.
## Status
# Project restarted: Deadline 10 Sep 2023.
# Disable unicode(Perfomance+).
LC_ALL=C
LANG=C
# version (YY.MM.DD)
BEATS_VERSION=23.08.24
# Must be executed only once the player statrts.
player_start_(){
printf '\e[?1049h' # Use alternative screen buffer.
printf '\e[2J' # Clear the screen.
printf '\e[?25l' # Hide the cursor.
printf '\e[?7l' # Disable line wrapping.
printf '\e[1;%sr' "$LINES" # Limit scrolling.
stty -echo # Hide echoing of user input
# Get termwindow Geometry.
get_term_size_
# Non-Configurable Variables
play_status="STOPPED"
curr_playing_index=-1
}
# Must be executed on the player termination.
player_exit_(){
# Kill Player(background playing not implemented, because its a simple player!)
kill_ffplay_ "$player_pid"
printf '\e[2J' # Clear screen.
printf '\e[?7h' # Enables Line Wrap.
printf '\e[?25h' # Restore cursor.
printf '\e[;r' # Default Scrolling limit.
printf '\e[?1049l' # Return to main screen.
stty echo # Show echoing of user.
exit 0
}
short_(){
# FixIt: you know it!
echo
}
# Get Terminal Size(Lines x Columns).
get_term_size_(){
shopt -s checkwinsize
(:;:) # Sleep for micro seconds.
}
# Get Beats name.
get_beats_name_(){
local Index
unset Beat_Name # Array which stores beats name.
for i in "${!playlist[@]}"; do
for Index in "${playlist[$i]}"*; do
case "$Index" in
# Store beats hvaing following formats.
*'.mp3' | *'.mp4' |\
*'.m4a' | *'.acc' |\
*'.wma' | *'.ogg' |\
*'.wav' | *'.ogg' |\
*'.opus' | *'.flac' |\
*'aiff' )
# Checks if file is realy music file
case "$(file -b --mime-type "$Index")" in
'video/mp4' | 'audio/mpeg') Beat_Name+=("$Index") ;;
esac
esac
done
done
}
# Reads input and exit if idel for sometime
input_parser_(){
local input
# Read one Normal or special key.
read $1 -rs -N 1 input
# Read special escape key.
if [[ "$input" == $'\e' ]]; then
read -t 0.01 -rsn5 input
input='\e'"$input"
fi
# Flush extra input
read -t 0.001 -s
case "$input" in
# Special Keys
$'\n') printf 'ENTER' ;;
' ') printf 'SPACE' ;;
$'\t') printf 'TAB' ;;
$'\177'|$'\b') printf 'BACKSPC';;
'\E'|'\e') printf 'ESCAPE' ;;
# Arrow Keys
'\e[A'|'k'|'\eOA') printf 'UP' ;;
'\e[B'|'j'|'\eOB') printf 'DOWN' ;;
'\e[D'|'h'|'\eOC') printf 'LEFT' ;;
'\e[C'|'l'|'\eOC') printf 'RIGHT' ;;
# Remaining keys
*) echo -n "$input";;
esac
}
# Kill current playing beat.
kill_ffplay_(){
player_pid="${1:-"$player_pid"}" # Just in case if not arg is given
kill "$player_pid" 2>/dev/null
unset $player_pid
play_status='STOPPED'
}
# List available beats.
list_beats_(){
# $1 - Number of beats to show on screen
[[ $1 ]] && ListEnd=$((ListStart + $1)) || ListEnd=$((ListStart+LINES))
# Loop through only the number of beats we want to show
for (( i=$ListStart;i<$ListEnd;i++ )); do
if ! (( $i < 0 || $i > $((Total-1)) )); then
local Temp="${Beat_Name[$i]%.*}"
Temp="${Temp##*/}"
else
Temp=
fi
# Colour selected_index.
if (( $selected_index == $i )); then
echo -en "$color_selected${Temp^^}\e[0m\e[K\n"
# Colour currently_playing.
elif (( $curr_playing_index == $i )); then
echo -en "$color_playing${Temp}\e[0m\e[K\n"
# Remaining beats.
else
echo -en "$Temp\e[K\n"
fi
done
}
# Initialize the player.
initialize_(){
# Duration of current playing beat
if [[ "${play_status^^}" == 'PAUSED' ]]; then
curr_duration=$curr_duration
else
curr_duration="$(cat "$DATA_FILE2" 2>/dev/null)"
fi
# Act upon, when beats end
(( "$curr_duration" == -1 )) && {
# Check if music ended
if (( $curr_duration == -1 )); then
play_status='STOPPED'
curr_duration=0
printf '0' >"$DATA_FILE2"
fi
# Check if a Mode(Shuffle, Repeat, ...) can be applied
if (( ${#Queue_Name[@]} != 0 )); then
case "${play_mode^^}" in
# Shuffle one after another.
'SHUFFLE')
;;
# Repeat a particular beat.
'REPEAT')
queue_index=$((queue_index+1))
## FixIt: some error in 203
if (( $queue_index > $((Total-1)) )); then
queue_index=$((Total-1))
curr_duration=0
fi
ffplay_play_ "${Queue_Name[$queue_index]}"
;;
'REPEATONE')
ffplay_play_ "${Queue_Name[$queue_index]}"
;;
esac
fi
}
}
setup_tui_(){
# Total Beats.
case "$screen" in
"QUEUE")
Total="${#Queue_Name[@]}"
;;
*)
Total="${#Beat_Name[@]}"
;;
esac
# Select the middle of the total beats.
if [[ -z "$selected_index" ]]; then
case "$(( (Total-1)%2 ))" in
'0') select_ "$(( (Total-1)/2 ))" ;; # For event number.
* ) select_ "$(( ( (Total-1)/2 )+1 ))" ;; # For odd number.
esac
fi
initialize_listSE_ "$selected_index"
}
# Initialize selected_index Variable.
select_(){
selected_index=${1:-"$selected_index"}
# Limit selected_index range. It can't be less than zero and
# can't be more than total beats available to select.
if (( $selected_index < 0 )); then
selected_index=0
elif (( $selected_index > $((Total-1)) )); then
selected_index="$((Total-1))"
fi
}
# Initialize ListStart and LinstEnd variables based on current selection.
# This function is made to keep selected beat in center of the list.
initialize_listSE_(){
select_ "${1:-"$selected_index"}"
case "$((LINES%2))" in # If even or odd
'0') local Temp=$(( LINES/2 )) ;; # For even number.
* ) local Temp=$(( (LINES/2) + 1 )) ;; # For odd number.
esac
# (selected_index+1): We need the index of selected_index beat(1 to N)
# rathen than the index of the selected array(0 to N-1).
ListStart=$(( (selected_index+1) - (Temp) ))
}
status_bar_(){
# Show custom text.
if (( $# >= 1 )); then
printf '\r\e[42m%*s' "$COLUMNS"
printf '\r\e[30m%s\e[m' "$1"
# Default status.
else
# Draw colored bar
printf '\e[42m%*s\r\e[30m' "$COLUMNS"
# Align right
#printf "%${COLUMNS}s" "$((total_duration/60))/$((curr_duration/60))s(${PlayPercentage:-'0'}) "
printf "%${COLUMNS}s" "$play_mode "
# Align left
Temp=${currently_playing##*/}
# FixIt: variable names of plst
if [[ ${play_status^^} == 'PLAYING' ]]; then
plst="="
elif [[ ${play_status^^} == 'PAUSED' ]]; then
plst="~"
else
plst=">"
fi
printf '\r%s\e[m' " $plst ${Temp%.*}"
# Align Center
#printf ""
fi
}
# Shows the Progress of currently playing beat.
progress_bar_(){
## Persentage of beat played.
PlayPercentage="$(bc -l <<< "($curr_duration/$total_duration)*100" 2>/dev/null)"
PlayPercentage="$(printf '%.0f' "${PlayPercentage%%.*}")%"
Temp1="(${PlayPercentage:-"0%"}) "
divby="$((COLUMNS-$(echo -n "$Temp1" | wc -c)))"
PlayProgress="$(bc -l <<<"$curr_duration/( $total_duration/$divby )" 2>/dev/null)"
PlayProgress=$(printf '%.0f' "$PlayProgress")
local Temp='\e[K\e[1;31m' # Color Bar
for (( i=0; i++<${PlayProgress:-"0"}; )); do Temp+="─"; done; Temp+='\e[0m'
for (( ;i++<=$divby; )); do Temp+="─"; done
printf '%s' "$(echo -en "$Temp")"
printf "%-$((COLUMNS+4))s\n" "$Temp1"
}
# Play given beat.
ffplay_play_(){
# Kill Previously playing beat, if any.
[[ ! -z $player_pid ]] && kill_ffplay_
# Play the beat and parse the output(continue in background).
ffplay -nodisp -autoexit -loglevel info -hide_banner $2 "$1" 2>&1 | ffplay_parse_ &
# Get PID of ffplay.
player_pid="$!"
play_status='PLAYING'
currently_playing="$1"
# Pause until Done signal is sent from ffplay_parse_ function.
[[ "$(< "$DATA_FILE4")" == 'Done' ]]
source $DATA_FILE
# Update curr_playing_index
# FixIt: fix the name!
# Remove it hardcode it into other functions(like directly assign variable when enter is pressed)
find_indexof_beat_
}
ffplay_parse_(){
# Need to reset curr_duration as soon as possible for, but why?
#echo -en "1" > "$DATA_FILE2"
# One-time parse.
local LINES Words
while read -s LINES; do
Words=($LINES)
# Get beats duration.
if [[ "${Words[0]}" == "Duration:" ]]; then
IFS=: read -a Duration <<< "${Words[1]//,/}"
elif [[ "${Words[0]}" == "Stream" ]]; then
break
fi
done
# If last Word don't match that means there is an error in playing.
[[ "${Words[0]}" == 'Stream' ]] && {
# Update Duration data.
echo "total_dur_h=${Duration[0]}" >$DATA_FILE # Duration Hour.
echo "total_dur_m=${Duration[1]}" >$DATA_FILE # Duration Minute.
echo "total_dur_s=${Duration[2]%%.*}" >$DATA_FILE # Duration Second.
echo "total_dur_ms=${Duration[2]##*.}" >$DATA_FILE # Duration MilliSecond.
echo "total_duration=$(( (${Duration[0]} * 316000) + \
(${Duration[1]} * 3600 ) + \
(${Duration[2]%%.*} * 60) + \
(${Duration[2]##*.} ) ))" >/$DATA_FILE # Total Duration in MilliSecond.
}
# Continue player(send signal to ffplay_play_ function).
echo 'Done' > "$DATA_FILE4"
# Loop Until numbers(Current Duration) appears.
while read -r -d $'\r' Index; do
[[ "${Index%%.*}" == [0-9]* ]] && break
done
# Loop to parse current duration until Music is stops
local durr
while read -r -d $'\r' Index; do
durr="${Index%% *}"
echo -en "$(bc <<< "(${durr%%.*} * 60) + ${durr##*.}" )" > "$DATA_FILE2" # Convert into MilliScond.
done
echo -en "-1" > "$DATA_FILE2" # -1 indicates that music ends
}
create_data_(){
local Temp="/tmp/Beats-$BEATS_VERSION"
mkdir -p "$Temp"
DATA_FILE="$Temp/beatsdata" # Contains variables state.
DATA_FILE2="$Temp/currdur" # Contains current duration.
DATA_FILE3="$Temp/queuelist" # Contains Queue list in sequence.
DATA_FILE4="$Temp/msgfifo" # FIFO file to communicate b/w parallel running functions.
touch "$DATA_FILE" "$DATA_FILE2" "$DATA_FILE3"
mkfifo "$DATA_FILE4" 2>/dev/null
printf '0' > "$DATA_FILE2" # Reset CurrDuration.
}
# Create a queue list
create_queue_(){
# Create a fresh queue list(refrence from available beats).
Temp="${1:-0}"
unset Queue_Name
# Store from [Selected - Total] beats.
for (( i=$Temp; i<$Total; i++ )); do
Queue_Name[$i]="${Beat_Name[$i]}"
done
# Store from [0 - Selected] beats.
(( $Temp != 0 )) && {
for (( i=0; i<$((Temp-1)); i++ )); do
Queue_Name[$i]="${Beat_Name[$i]}"
done
}
# FixIt: what it is? is it required?
#update_data_ QU
}
# Remove a element from queue list.
queue_remove_(){
unset Queue_Name[${1:-0}]
Queue_Name=("${Queue_Name[@]}")
}
# Add a element in the queue list.
queue_add_(){
local Temp=${1:-0}
Queue_Name+=("${Queue_Name[$Temp]}")
}
# Swap the possition of two beats.
queue_swap_(){
(( $# >= 2)) && {
# Don't swap if beats not exist.
[[ -z "${Queue_Name[$1]}" && -z "${Queue_Name[$2]}" ]] || {
local Temp="${Queue_Name[$2]}"
Queue_Name[$2]="${Queue_Name[$1]}"
Queue_Name[$1]="$Temp"
}
}
}
# Refresh the player.
refresh_(){
get_term_size_
# Don't fetch beats name if
[[ "$searched" != 'true' && "$queue_showed" != 'true' ]] && get_beats_name_
setup_tui_
}
# Fetch array-index of last played beat.
find_indexof_beat_(){
for (( i=0; i<$Total;i++ )); do
if [[ "${Beat_Name[$i]}" == "${currently_playing}" ]]; then
curr_playing_index="$i"
break
fi
done
# If not found.
curr_playing_index=${curr_playing_index:-'0'}
}
main_screen_(){
initialize_
# Reset cursor to the top left edge.
printf '\e[0;0H'
list_beats_ "$((LINES - 2))" # -2 for the lines reserved by bars
progress_bar_
# Dont change its position (last module must be not produce newline)
status_bar_
local input="$(input_parser_ '-t 0.9')"
case "$input" in
# Play selected beat.
'ENTER')
ffplay_play_ "${Beat_Name[$selected_index]}"
queue_index="$selected_index" # Set queue index
curr_playing_index=$selected_index
# Quickly reset current duration.
curr_duration=0; printf '0' >"$DATA_FILE2"
;;
# Pause/resume beat
'SPACE')
case "${play_status^^}" in
'PLAYING')
kill_ffplay_ $player_pid 2>/dev/null
play_status='PAUSED'
;;
'PAUSED')
ffplay_play_ "$currently_playing" "-ss $((curr_duration/60))"
;;
'STOPPED')
case "$curr_duration" in
'0'|'-1')
ffplay_play_ "${Beat_Name[$selected_index]}"
queue_index="$selected_index"
curr_playing_index=$selected_index
;;
*)
ffplay_play_ "$currently_playing" "-ss $((curr_duration/60))"
;;
esac
;;
esac
;;
# Move selection up.
'UP')
initialize_listSE_ "$((selected_index-1))"
;;
# Move selection down.
'DOWN')
initialize_listSE_ "$((selected_index+1))"
;;
'LEFT')
curr_playing_index=$((--curr_playing_index))
(( $curr_playing_index < 0 )) && curr_playing_index=0
ffplay_play_ "${Beat_Name[$curr_playing_index]}"
;;
'RIGHT')
curr_playing_index=$((++curr_playing_index))
(( $curr_playing_index > $((Total-1)) )) && curr_playing_index=$((Total-1))
ffplay_play_ "${Beat_Name[$curr_playing_index]}"
;;
# Queue Screen.
'2')
#get_queue_beats_
screen='QUEUE'
setup_tui_
;;
# Add selected song to Queue.
'c') add_queue_ "$selected_index" ;;
# Run commands.
":")
while :; do
status_bar_ ":$output"
read -rs -N 1 input
case "$input" in
$'\n') break ;;
$'\e') output= ; break ;; # exit.
$'\177'|$'\b') output="${output%?}" ;; # Backspace
[[:print:]]) output="$output$input" ;;
esac
done
case "$output" in
'wq'|'wq!'|'q'|'q!'|'quit'|'quitall') exit ;;
esac
[[ "$output" =~ ^[0-9]+$ ]] && initialize_listSE_ "$((output-1))"
unset output input
;;
# Go to Previous Screen
'ESCAPE')
if [[ "$searched" == 'true' ]]; then
get_beats_name_
setup_tui_
else
refresh_
fi
;;
# Seek Backward.
'[')
curr_duration="$((curr_duration - seek_interval))"
# Dont let curr_duration go below 0.
if (( $curr_duration < 0 )); then
curr_duration="0"
fi
printf "$curr_duration" >"$DATA_FILE2"
[[ "${play_status^^}" == 'PLAYING' ]] && ffplay_play_ "$currently_playing" "-ss $((curr_duration/60))"
;;
# Seek Forward
']')
curr_duration="$((curr_duration+seek_interval))"
# Dont let curr_duration go above total_duration.
if (( $curr_duration > ${total_duration:=0} )); then
curr_duration="$total_duration"
fi
printf "$curr_duration" >"$DATA_FILE2"
[[ "${play_status^^}" == 'PLAYING' ]] && ffplay_play_ "$currently_playing" "-ss $((curr_duration/60))"
;;
# Exit
'q') exit ;;
# Refresh
'r') refresh_ ;;
# Stops Music
'x') kill_ffplay_ ;;
# Go to Top
'g') initialize_listSE_ "0" ;;
# Go to Bottom
'G') initialize_listSE_ "$((Total-1))" ;;
# Change Playing Modes
's')
modes_=('SHUFFLE' 'REPEATONE' 'REPEAT')
for i in ${!modes_[@]}; do
if [[ "${modes_[$i]^^}" == "${play_mode^^}" ]]; then
(( $((i+1)) == ${#modes_[@]} )) && i=-1
play_mode="${modes_[$((i+1))]}"
break
fi
done
;;
# Search from listed beats
"/")
while :; do
status_bar_ "$LINES" "/$output"
read -t 1 -rs -N 1 input
case "$input" in
$'\n'|$'\e') output= ; break ;; # Quit
$'\177'|$'\b') output="${output%?}" ;; # Backspace
[[:print:]]) output="$output$input" ;;
esac
done
[[ ! -z "$output" ]] && { find_beats_ "$output"; setup_tui_; }
unset output input
;;
esac
}
list_queue_beats_(){
# $1 - Number of beats to show
[[ $1 ]] && ListEnd=$((ListStart + $1)) || ListEnd=$((ListStart+LINES))
# List limited beats that can fit on screen.
for (( i=$ListStart;i<$ListEnd;i++ )); do
# If exceed the limit then display empty line.
if (( $i < 0 || $i > $((Total-1)) )); then
local Temp="$i"
else
local Temp="${Queue_Name[$i]%.*}"
Temp="${Temp##*/}"
fi
# Colour selected_index.
if [[ $selected_index -eq $i ]]; then
echo -en "$COL2${Temp^^}$COLR\e[K\n"
# Remaining beats.
else
echo -en "$Temp\e[K\n"
fi
done
}
configurations_(){
# Colors
color_selected='\e[32m'
color_playing='\e[33m'
color_barbg='\e[34m'
color_progressbar='\e[35m'
# Seeking interval in milliseconds
seek_interval=300
# Values: Shuffle, LoopShuffle, Repeat, Repeatone, Randomise, None
play_mode=${play_mode:-"REPEATONE"}
# Values: ON, OFF
repeat="ON"
}
main_(){
configurations_
player_start_
# FixIt:
## Create playlist handler screen
## Change BEATDIR name to given_playlist
## Make different funciton for this
if [[ "$BEATS_DIR" ]]; then
playlist=("$BEATS_DIR")
else
playlist=("$HOME/Music/")
#playlist+=("$HOME/Music/Open-Ringtones")
# Append '/' if not available
for i in "${!playlist[@]}"; do
[[ "${playlist[$i]}" != *'/' ]] && playlist[$i]="${playlist[$i]}/"
done
fi
trap 'player_exit_' EXIT # Run once on termination(to reset the TUI).
trap 'refresh_' WINCH # Run every time, there is change in term-window size.
create_data_ # Create required files.
get_beats_name_ # Search for Beats in a given Directory.
setup_tui_
# Create Queue list or use previous list
create_queue_
while :; do
case "${screen^^}" in
'MAIN') main_screen_ ;; # Main Screen(Default)
'QUEUE') queue_screen_ ;; # Queue screen
'NPLAYING') now_playing_screen_;; # Now playing screen
*) screen='MAIN' ;; # Set to Defautl Screen.
esac
done
}
# Main function
main_