-
Notifications
You must be signed in to change notification settings - Fork 0
/
m4b2opus
executable file
·476 lines (394 loc) · 18.1 KB
/
m4b2opus
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
#!/bin/bash
#depends opustags, ffmpeg, indexopus, opus.book.4, mplayer, mediaduration
#need to address existing m4a files in the convert directory prior to the m4b to m4a split.
#trap pause DEBUG
shopt -s nullglob
threads=4
scriptpath="$(realpath "$0")"
scriptname="${scriptpath##*\/}"
ulon=$(tput smul) #underline on
uloff=$(tput rmul) #underline off
bold="$(tput bold)" #bold on
tput0="$(tput sgr0)" #clear tput
red="$(tput setaf 9)" #red fg
white="$(tput setaf 15)" #white fg
relipsis="$red..."
stamp="$(date +%s)"
screened='false'
##definitions#################################################################################
## load functions #############################################################################
## printline()
## pause()
## checkdur()
. "$HOME/bin/gits/indexopus/indexopus.lib"
fnrmr(){
local red relipsis="${red}..."
[[ "$1" = "-r" ]] && red="${tput setaf 7}"
fn_rmfile(){
printf '%s\n%s is a file:\n%s' "$relipsis" "$bold" "$1" "$white"
ls -ltr "$1"
printf '%s\nrmr: remove this file? (y/n) %s' "$red" "$tput0"
old_stty_cfg=$(stty -g) # https://stackoverflow.com/questions/226703/how-do-i-prompt-for-yes-no-cancel-input-in-a-linux-shell-script
stty raw -echo
answer=$(head -c 1)
stty "$old_stty_cfg" # Careful playing with stty
if [ "$answer" != "${answer#[Yy]}" ]
then
rm "$1"
printf "\n\n"
if [ ! -e "$1" ]
then
printf '\n%sDone! File \"%s\" removed.\n\n%s' "$relipsis" "$1" "$tput0"
else
printf "\n\n%s%s%s not removed, check permissions:\n\n%s" "$relipsis" "$bold" "$1" "$tput0"
ls -ltr "$1"
fi
else
printf '\n\n%sFiles remain:\n%s \n%s\n' "$relipsis" "$(ls -ltr "$1")" "$tput0"
fi
# There isn't really anything wrong with this code, but the above method removes the CR
# There're other ways to do this https://stackoverflow.com/questions/226703/how-do-i-prompt-for-yes-no-cancel-input-in-a-linux-shell-script
}
##--> fn_rmfile() <--###############################################################################
for path in "$@"
do
if [[ -d "$path" ]]; then
printf '%s%s\n' "$red" "$bold"
if rmdir "$path" 2>/dev/null; then
printf 'Removing %s... \n\n$ ls %s/ \n\n' "$path" "$path"
else
printf '\n%s' "$tput0"
find "$path"
printf '%s' "$bold"
rm -rI "$path"
printf '%s' "$tput0"
fi
if [ ! -e "$path" ]; then
printf '%s\nDone!\n' "$relipsis"
else
printf '\n\n%s%sRemoval Failed!%s\n\n%s is still present check ownership and permissions:\n' "$relipsis" "$bold" "$tput0" "$path"
ls -lad --color=always "$path"
fi
elif [[ -f "$path" ]]; then
fn_rmfile "$path"
else
printf '\n\n No such directory or file found!\n\n'
fi
done
}
##--> fnrmr() <--###################################################################################
editscript(){
local script path; script="${scriptname##*/}"; path="${scriptname%/*}"; swp="$path/.$script.swp"
if [[ ! -e "$swp" ]]; then printf "\n\n%s\n\n" "$swp"; (/usr/bin/nano "$scriptname"); exit
else printf "\n%s is already being edited.\n%s exists; try fg or look in another window.\n" "$scriptname" "$swp"; exit;
fi; }
##--> editscript() <--##############################################################################
filecheck(){
clifilename="$1" #if a filename is passed via the cli. this doesn't work anymore now with -t??
[[ -d "$clifilename" ]] && clidir="${clifilename%/*}" && cd "$clidir" && unset clifilename
[[ -f "$clifilename" ]] && clidir="${clifilename%/*}" && cd "$clidir" && clifilename="${clifilename##*/}"
if [[ -n "$clifilename" ]] && [[ "$clifilename" != *\ --\ Audiobook.m4b ]]
then
printf 'The file specified: %s\nis not in the correct format of\n* -- Audiobook.m4b, checking directory for an m4b file...' "$clifilename"
elif [[ "$clifilename" == *\ --\ Audiobook.m4b ]] && [[ -f "$1" ]]
then
m4bin="$1"
else
files=(*m4b)
if [[ "${#files[@]}" == 1 ]]; then
if [[ "${files[@]}" == *\ --\ Audiobook.m4b ]]; then
m4bin="$files"
elif [[ "${files[@]}" == *m4b ]]; then
m4bin="${files/.m4b/ -- Audiobook.m4b}"
mvoutput="$(mv "$files" "$m4bin" 2>&1)"
mvec="$?"
if (( mvec > 0 )); then
if [[ "$mvoutput" = "mv: cannot move "*\ to\ *": Permission denied" ]]; then
own && mv "$files" "$m4bin" || { printf 'Unable to gain write permission for %s. exit 1\n\n' "${files[@]}"; exit 1; }
else
printf 'Unknown error renaming %s. exit 1\n\n' "${files[@]}"
exit 1
fi
fi
fi
else
echo "No single & appropriate input file found or specified, please check and retry..."
ls
exit 1
fi
fi; }
##--> filecheck() <--#################################################################################
calctime(){
duration=$(find -type f -name "$1" -print0 |
xargs -0 mplayer -vo dummy -ao dummy -identify 2>/dev/null |
perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d:%02d:%02d\n",$t/3600,$t/60%60,$t%60' |
tail -n 1)
hours=$(find -type f -name "$1" -print0 |
xargs -0 mplayer -vo dummy -ao dummy -identify 2>/dev/null |
perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d\n",$t/3600' |
tail -n 1)
minutes=$(find -type f -name "$1" -print0 |
xargs -0 mplayer -vo dummy -ao dummy -identify 2>/dev/null |
perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d\n",$t/60%60' |
tail -n 1)
seconds=$(find -type f -name "*$1" -print0 |
xargs -0 mplayer -vo dummy -ao dummy -identify 2>/dev/null |
perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d\n",$t%60' |
tail -n 1)
[[ "$hours" =~ "0*(.*)" ]] && hours=${BASH_REMATCH[1]}
[[ "$minutes" =~ "0*(.*)" ]] && minutes=${BASH_REMATCH[1]}
[[ "$seconds" =~ "0*(.*)" ]] && seconds=${BASH_REMATCH[1]}
#BASH_REMATCH is an array variable in Bash that contains the results of the most recent pattern match operation performed using the =~ operator with the [[ ... ]] conditional expression.
#
#When you use =~ to match a pattern against a string, Bash populates the BASH_REMATCH array with the text that matches the pattern. The first element (BASH_REMATCH[0]) contains the portion of the string that matches the entire regular expression, while subsequent elements (BASH_REMATCH[1], BASH_REMATCH[2], etc.) contain the portions of the string that match the corresponding capture groups in the regular expression.
#
#Here's a breakdown of how BASH_REMATCH is populated:
#
#BASH_REMATCH[0]: Contains the portion of the string that matches the entire regular expression.
#BASH_REMATCH[1]: Contains the portion of the string that matches the first capture group ( ... ).
#BASH_REMATCH[2]: Contains the portion of the string that matches the second capture group ( ... ), if present.
#and so on...
#In the script provided earlier, we used BASH_REMATCH[1] to extract the content inside double quotes. If the pattern \"(.*)\" matches successfully, the content inside the double quotes is captured and stored in BASH_REMATCH[1].
# printf "Duration %s\n" "$duration"
hours="${hours#0}"
hourmin=$(( hours*60 ))
##echo "hourmin $hourmin"
minutes="${minutes#0}"
secmin=$((hourmin+minutes))
secmin=$((secmin*60))
seconds="${seconds#0}"
##echo "secmin $secmin"
##echo "seconds $seconds"
totalsec=$(( "$seconds" + "$secmin" ))
##echo "totalsec $totalsec"
divsec=$(python3 -c "print($totalsec/4)")
##echo "divsec $divsec"
}
##--> calctime{} <--#############################################################################
m4bsplit(){
# Original code from: http://crunchbang.org/forums/viewtopic.php?id=38748#p414992
# m4bronto
# Chapter #0:0: start 0.000000, end 1290.013333
# first _ _ start _ end
local bpath outputdur START first start end partnum n
outputdir="$2"
START=1
bpath="$(basename "$PWD")"
#while [ "$#" -gt 0 ]; do
ffmpeg -i "$1" 2> ".tmp$stamp"
n="$START"
while read -r first _ _ start _ end
do
if [[ "$first" = Chapter ]]
then
read # discard line with Metadata:
read _ _ chapter
[[ "$chapter" = Chapter\ ?\:\ * ]] && chapter="${chapter/Chapter /Chapter 0}"
# at some point i'd like to make a menu for what to do here, but for now this works.
# [[ "$chapter" =~ \ \/\ ]] && chapter="${chapter// \/ /: }"
[[ "$chapter" =~ \/ ]] && chapter="${chapter//\//\\}"
# read -rp "$title" </dev/tty
[[ "$n" -lt 10 ]] && partnum="0$n" || partnum="$n"
printf '%sCreating %s -- Part %s: %s.m4a%s\n' "$relipsis" "$title" "$partnum" "$chapter" "$tput0"
readarray -t ffoutput < <(ffmpeg -n -nostdin -hide_banner -stats -v error -vsync 2 -ss "${start%?}" -to "$end" -i "$1" -vn -codec copy "$outputdir/$title -- Part $partnum: $chapter.m4a" 2>&1)
((n++))
fi
done <".tmp$stamp"
rm ".tmp$stamp"
#shift
#done
}
##--> m4bsplit() <--##################################################################################
rmyn(){
local quiet
[[ "$1" = '-q' ]] && quiet=true && shift
while true
read -rp "$1" rmyn
do
case "$rmyn" in
[yY] ) #"${@:3}"; break;;
if [[ $quiet ]]; then
"${@:3}" >/dev/null
else
"${@:3}"
fi
break;;
[nN] ) printf '%s\n' "$2"; break;;
* ) printf "Invalid response...\n";;
esac
done
}
##--> rmyn() <--######################################################################################
noindexsplit(){
local i n partno m4bin="$1" convertdir="$2"
printf '%s%sNo index found in %s!\n...%s%sThe item will be spiit into %s parts for efficient ffmpeg conversion.\n...Reindex later with chapter information pulled from the web.\n\n' "$relipsis" "$bold" "$m4bin" "$tput0" "$red" "$partno"
partno=1
calctime "$m4bin" #why? i think this is the only call to calctime? there's no need for it here...
#oh contrare! this is what provides $divsec and the script fails without that line!
for ((partno=1; partno < $(( threads + 1)); partno++ )); do
printf '%s%s: %s' "$relipsis" "$partno" "$tput0"
ffmpeg -n -nostdin -hide_banner -stats -v error -ss $(python3 -c "print(($partno-1)*$divsec)") -to $(python3 -c "print($partno*$divsec)") -i "$m4bin" -vn -acodec copy "$convertdir/${m4bin%% -- *} -- Part 0$partno.m4a"
printf '%s' "$tput0"
done
cd "$convertdir"
#for i in First Second Third Fourth
for ((i=1; i<=parts; i++)); do
printf -v i '%02d\n' "$i"
((n++))
for f in *\ --\ Part\ 0"$n".*; do
mv "$f" "${f/./: Part $i.}"
done
done
}
##--> Main Code <--################################################################################
##--> m4b2opus <--####################################################################################
echo
[[ "$1" = @(edit|e|nano) ]] && editscript
[[ "$1" = "-y" ]] && shift && rmmatch=true
[[ "$1" = "--stats" ]] && shift && stats=true
[[ "$1" = @(--screen|-s) ]] && shift && screened=true
[[ "$1" = @(-ys|-yes) ]] && shift && rmmatch=true && screened=true
#[[ "$1" ]] && clifile "$1"
if "$screened"; then
printline "$bold Calling m4b2opus in GNU screen $tput0"
printf \\n\\n
allm4s=(*.m4[ab])
screenname="m4b2opus-${allm4s[0]}"
screen -dmS "${screenname:0:16}" m4b2opus -y #should this be a -y here? probably.
screen -ls
printf \\n\\n
exit
fi
#if "$screened"; then
# printline "$bold Calling m4b2opus in GNU screen $tput0"
# printf \\n\\n
# allm4s=(*.m4[ab])
# #read -rp "${allm4s[0]}"
## exec bash -c "TERM=screen-256color COLORTERM=1 screen -dmS m4b2opus-\"${allm4s[0]}\" m4b2opus -y; screen -ls; printf \\n\\n"
## exec bash -c "screen -dmS test bash -c \"echo $TERM; \sleep 60m\"; m4b2opus-\"${allm4s[0]}\" m4b2opus -y; screen -ls; printf \\n\\n"
# exec bash -c "screen -dmS m4b2opus-\"${allm4s[0]}\" m4b2opus -y; screen -ls; printf \\n\\n"
#fi
[[ "$TERM"=screen ]] && TERM=screen.xterm-256color
printline "${bold} Welcome to ${white}$script ${tput0}"
filecheck "$1" && [[ ! "$?" = 0 ]] && exit
allm4s=(*.m4[ab])
printf '\n%s/*.m4[ab]: \n' "$PWD"
printf ' %s%s%s\n' "$red" "${allm4s[@]}" "$white"
[[ "$stats" = true ]] && mediainfo "$m4bin"
m4bindur="$(checkdur m4b)"
printf '\n%sStarting .m4b file:%s' "$bold" "$tput0"
printf ' %s%s%s%s\n' "$bold" "$red" "$m4bin" "$tput0"
printf '%sStarting duration :%s' "$bold" "$tput0"
printf ' %s%s%s\n' "$red" "$bold" "$m4bindur" "$tput0"
title="${m4bin% -- *}"
swd="$PWD"
convertdir="$CACHE/m4b2opus-$title"
[[ "$convertdir" == *\'* ]] && convertdir="${convertdir//\'}" #check $convertdir for \'s and remove them
[[ ! -d "$convertdir" ]] && mkdir "$convertdir"
[[ ! -d "$convertdir" ]] && echo "Could not create $convertdir. Please investigate. (exit 1)" && exit 1
if [[ ! $(mediainfo "$m4bin"|grep Menu) =~ ^Menu ]]; then #process unindexed m4b files
noindexsplit "$m4bin" "$convertdir"
else
m4bsplit "$m4bin" "$convertdir"
cd "$convertdir"
(( $(ls *m4a|wc -l) > 99 )) && for i in *\ --\ Part\ ??\:\ *.m4a; do mv "$i" "${i/Part /Part 0}"; done
regexexp='.*\ --\ Part\ [[:digit:]]{2}:\ Chapter\ [[:digit:]][\ |\.]'
for m4afile in *m4a
do
[[ "$m4afile" =~ .*\ --\ Part\ [[:digit:]]{2}:\ Chapter\ [[:digit:]][\.\ ] ]] &&
mv "$m4afile" "${m4afile/Chapter /Chapter 0}"
done
fi
cd "$convertdir"
echo
[[ "$rmmatch" != true ]] && pause "${bold}${red}Control-Z to suspend and adjust chapter names in $convertdir? $tput0"
#opus.book.4##################################################################################
echo
printline "${bold} Calling external dependency:${red} opus.book.4 ${tput0}"
opus.book.4 --stats -d "${m4bindur#*: }" #this is a dependency; needs to be made a function?
if (( "$?" > 0 )); then
printf '%s\n\nopus.book.4 failed; exit 1\n\n%s' "$bold" "$tput0"
printline " Leaving $scriptname: Error! "
exit 1
fi
printline "${bold} Returning from external dependency: ${red} opus.book.4 ${tput0}"
#opus.book.4##################################################################################
clear -x
#need to renable rmyn below if these are uncommented
#[[ ! -d "$convertdir/m4a" ]] && mkdir "$convertdir/m4a"
#mv *.m4a ./m4a
opuspartdur="$(checkdur opus)"
m4bindur="${m4bindur#*: }"
printf '%sDuration of the original m4b file: %s%s%s\n' "$bold" "$red" "$m4bindur" "$tput0"
printf '%sDuration of the .opus part files: %s%s%s\n' "$bold" "$red" "$opuspartdur" "$tput0"
##indexopus##################################################################################
echo
printline "${bold} Calling external dependency:${red} indexopus ${tput0}"
if [[ "$rmmatch" = true ]]
then
indexopus -y -t "$title" -m "$convertdir" -s "$stamp" -d "$opuspartdur"
else
indexopus -t "$title" -m "$convertdir" -s "$stamp" -d "$opuspartdur"
fi
ec4io="$?" # error code 4 indexopus
if (( ec4io == 2 )); then
iorm=true
elif (( ec4io == 1 )); then
printf 'How the hell did you manage to get here?!'
if ! [[ -f "$convertdir/$title -- Audiobook.opus" ]]; then
pause "\$convertdir/\$title -- Audiobook.opus: $convertdir/$title -- Audiobook.opus"
exit
fi
elif (( ec4io == 130 )); then
printf '%sindexopus was aborted by user, exit (130). Investigate...\n%s\n%s\n\n' "$bold" "$tput0" "$(printline " ${bold}Leaving ${scriptname}: ${red}indexopus aborted, exit (1)${tput0} ")"
exit
fi
printline "${bold} Returning from external dependency:${red} indexopus ${tput0}"
##indexopus##################################################################################
tmp="/tmp/indexopus-$stamp" #this probably doesn't exist...
titleopus="$title -- Audiobook.opus"
[[ ! -f "$titleopus" ]] &&
printf '%s%sError: Where the fuck is %s?! Exiting (1)\n%s' "$bold" "$red" "$titleopus" "$tput0" &&
printline "$scriptname" &&
exit 1
mv "$titleopus" "$swd"
opusparts=( *opus )
cd "$swd"
[[ ! "$rmmatch"=true ]] && pause "Need to check to see if $tmp is being created... when indexopus isn't run with -y"
checkdur # probably do something different here since you have m4bindur and have to calc opusdur...
# yeah, this is a terrible idea. do this by heand instead of relying on something no
# indended for this
#echo "Duration(s):"
#echo "${red}${bold}${tput0}$(m4bindur) the $m4bin" #this threw an error saying m4bindur could not be found: not a function?
#echo "${red}${bold}${tput0}$m4bindur $m4bin" #removed the () from above.
#echo "${red}${bold}${tput0}$(checkdur opus) $titleopus"
opusdursec="$(sex2sec "$(checkdur opus)")"
m4bindursec="$(sex2sec $m4bindur)"
if [[ "$rmmatch" = true ]] && (( opusdursec > 0 )); then
verifydur=$(bc <<< "scale=4; ($m4bindursec - $opusdursec) / $opusdursec " )
verifydur="${verifydur/#-}"
if [[ $(bc <<< "scale=4; $verifydur < 0.001") ]]; then
rm -r *m4b "$convertdir"
[[ "$m4bindursec" != "$opusdursec" ]] &&
printf '\n%sDurations don'\''t %sexactly%s match but fuckin'\'' close '\''nuff!%s\n' "$relipsis" "$(tput sitm)" "$(tput ritm)" "$tput0" ||
printf '%sDurations match!%s\n' "$relipsis" "$tput0"
printf '\n%sDone.\n\nPlease see %s/%s%s\n\n' "$relipsis" "$PWD" "$ioutput" "$tput0"
exit
elif [[ "$rmmatch" = true ]] && [[ "$(checkdur m4b)" != "$(checkdur opus)" ]]; then
printf '%s%sThe m4b and opus audiobook durations do not match!\n' "$bold" "$red"
printf '%s%sm4b2opus will not automatically delete starting and temporary files!\n' "$white" "$tput0"
printf '\n\n'
printf '%s-y/-f specified, but the durations do not match!\n%s' "$bold" "$tput0"
fi
fi
printf '\n%sCleaning up remaining files:%s\n\n' "$red" "$tput0"
# ls "$tmp" "$convertdir" 2>/dev/null
printf '\n\n'
# the 2>/dev/null does not work for rmyn -- rewrite!!
# rmyn -q "${red}${bold}Remove the conversion ./m4a directory? ${tput0}" "${red}...Leaving ./m4a.${tput0}" rm -r "$convertdir/m4a"
[[ ! "$iorm" ]] && [[ "$opusparts" ]] && rmyn -q "${red}${bold}Remove $ititle -- Part *.opus files? ${tput0}" "${red}...Leaving $ititle -- Part *.opus files...${tput0}" rm "$convertdir/$title"\ --\ Part\ ??:*.opus
rmyn "${red}${bold}Remove the starting $m4bin? " "${red}Leaving starting $m4bin${tput0}" rm "$m4bin"
for i in "$convertdir" .tmp* "$tmp"; do [[ -a "$i" ]] && fnrmr "$i"; done
printf '\n\n...Done.\n\nPlease see %s/%s\n\n' "$PWD" "$ioutput"
printline "${bold} Exiting (0) ${white}m4b2opus ${tput0}"
exit 0