forked from b-fuze/batch-encoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.sh
2380 lines (2049 loc) · 81.6 KB
/
encoder.sh
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# vim:set shiftwidth=4 tabstop=4:
BATCH_ENCODER_VERSION=0.2.8
# Author: Mike32
#
# Print usage: encoder.sh -h
#
# This works in any *nix environment with at least Bash v4
# and `ffmpeg` and `ffprobe` are in your PATH
#
# It also works on Windows via WSL as long as both `ffmpeg.exe` and
# `ffprobe.exe` are in your PATH
# [1] TODO: Cache FFprobes output somewhere
# [2] TODO: Validate stream options
# [3] TODO: Batch video resolution (e.g 1080,720,360)
# [4] TODO: Show titles of Streams
shopt -s extglob
shopt -u nocaseglob
# Utility functions
# Bold formatting
b() {
echo -en "\e[1m$1\e[0m"
}
# Output miscellaneous information
misc_info() {
local msg=$1
echo -e '\e[90m'"$msg"'\e[0m'
}
# Confirmation prompt
confirm() {
echo -n "$1 (y/n) [$2]: "
read _response
_response=${_response,,*}
if [[ ${_response:0:1} == y ]]; then
return 0
fi
return 1
}
# Get key value from detail string structure
get_detail() {
local key="$1"
local details="$2"
echo "$details" | grep -E "^$key:" | sed -Ee 's/^[^:]+:(.*)$/\1/'
}
# Convert paths for external Windows programs
HAS_CYGPATH=false
HAS_WSLPATH=false
path() {
local __cur_path="$1"
if [[ $IS_WINDOWS == true ]]; then
if [[ $HAS_WSLPATH == true ]]; then
wslpath -m "$__cur_path"
elif [[ $HAS_CYGPATH == true ]]; then
cypath.exe -w "$__cur_path"
fi
else
echo -n "$__cur_path"
fi
}
# Convert windows paths to nix
nix_path() {
local __cur_path="$1"
if [[ $IS_WINDOWS == true ]]; then
if [[ $HAS_WSLPATH == true ]]; then
wslpath -u "$__cur_path"
elif [[ $HAS_CYGPATH == true ]]; then
cypath.exe -u "$__cur_path"
fi
else
echo -n "$__cur_path"
fi
}
# Check for Windows paths (and convert them to *nix paths)
check_windows_path() {
local path="$1"
# Match against absolute paths on Windows
if [[ $path =~ ^[A-Z]:\\ || $path =~ ^\\\\?wsl$\\ ]]; then
nix_path "$path"
else
echo -n "$path"
fi
}
# Hide temporary files on Windows
hide_tmp_file_windows() {
local path=$1
if [[ $IS_WINDOWS == true ]]; then
# TODO: Maybe hide all files and not just ones in the Windows' drives
if [[ $path =~ ^/mnt/ && -n $windows_attrib_executable ]]; then
attrib.exe +s +h "$( path "$path" )" &> /dev/null
fi
fi
}
# Update encoder
update_encoder() {
if ! which git &> /dev/null; then
echo "Error: can't update without $( b git ). Install $( b git ) and try again" 1>&2
return 1
fi
cd "$data_dir"
if git rev-parse HEAD &> /dev/null; then
local branch=$( git branch --show-current )
local remote_name=$( git remote | head -n1 )
local cur_commit=$( git rev-parse --short HEAD )
echo -n "Loading latest version information..."
git fetch "$remote_name" "$branch" -q
local new_commit=$( git rev-parse --short "$remote_name/$branch" )
# Clear line
echo -ne '\e[?25h\e[2K\r'
if [[ $cur_commit = $new_commit ]]; then
echo "Already up to date"
echo "Version $( b "$BATCH_ENCODER_VERSION" )-$cur_commit"
else
git checkout HEAD . -q
git merge "$remote_name"/"$branch" -q
local new_version=$( grep BATCH_ENCODER_VERSION -m 1 encoder.sh | sed -E 's/^.+=(.+)$/\1/' )
echo "Updated to latest version"
echo "From version $( b "$BATCH_ENCODER_VERSION" )-$cur_commit $( b $'\e[32m''->' ) $( b "$new_version" )-$new_commit"
fi
else
echo "Error: can't update, not installed with Git" 1>&2
fi
}
# Check for and load config
load_config() {
local config=~/.config/batch-encoder-cfg.sh
local parser=$data_dir/config/parser.sh
if [[ -f $config && -f $parser ]]; then
. "$parser"
bep_cur_file=~/.config/batch-encoder-cfg.sh
# Sync the relevant variables with the parser
bep_sync default_sources
bep_sync defaults
bep_sync ffmpeg_input_args
bep_sync ffmpeg_output_args
# Finally, parse the config file
bep_parse < "$config"
misc_info "Loaded config file"
fi
}
# Print config when using --debug-config
print_config() {
echo -e '\e[1m'"CONFIG:\e[0m"
local IFS=$'\n'
local keys=($( sort <<< "${!defaults[*]}" ))
local longest_key=
for key in "${keys[@]}"; do
if (( ${#key} > ${#longest_key} )); then
longest_key=$key
fi
done
# Convert to whitespace
local longest_key=$( tr -c '' ' ' <<< "$longest_key" )
for key in "${keys[@]}"; do
local key_length=${#key}
echo -en '\e[32m'" $key\e[0m:${longest_key:$key_length}"
echo -en "\e[95m'\e[37m"
# Print default value with escaped single quotes
echo -n "${defaults[$key]//\'/\'\\\'\'}"
echo -e "\e[95m'\e[0m"
done
# TODO: DRY
# Calculate padding
local longest_arg=
for arg in "${ffmpeg_input_args[@]}"; do
if [[ ${arg:0:1} = - && ${#arg} -gt ${#longest_arg} ]]; then
longest_arg=$arg
fi
done
# Convert to whitespace
local longest_arg=$( tr -c '' ' ' <<< "$longest_arg" )
echo -en '\n\e[1m'"FFMPEG INPUT ARGS:\e[0m"
local initial_newline=$'\n '
for arg in "${ffmpeg_input_args[@]}"; do
local tail=
case ${arg:0:1} in
'-' )
local arg_length=${#arg}
local tail=${longest_arg:$arg_length}
echo -en "\n \e[95m'\e[37m"
;;
* )
echo -en "$initial_newline\e[95m'\e[37m"
;;
esac
# Print arg with escaped single quotes
echo -n "${arg//\'/\'\\\'\'}"
echo -en "\e[95m'\e[0m$tail"
local initial_newline=
done
# Calculate padding
local longest_arg=
for arg in "${ffmpeg_output_args[@]}"; do
if [[ ${arg:0:1} = - && ${#arg} -gt ${#longest_arg} ]]; then
longest_arg=$arg
fi
done
# Convert to whitespace
local longest_arg=$( tr -c '' ' ' <<< "$longest_arg" )
echo -en '\n\n\e[1m'"FFMPEG OUTPUT ARGS:\e[0m"
local initial_newline=$'\n '
for arg in "${ffmpeg_output_args[@]}"; do
local tail=
case ${arg:0:1} in
'-' )
local arg_length=${#arg}
local tail=${longest_arg:$arg_length}
echo -en "\n \e[95m'\e[37m"
;;
* )
echo -en "$initial_newline\e[95m'\e[37m"
;;
esac
# Print arg with escaped single quotes
echo -n "${arg//\'/\'\\\'\'}"
echo -en "\e[95m'\e[0m$tail"
local initial_newline=
done
if [[ ${#dir_sources[@]} -gt 0 ]]; then
echo -en '\n\n\e[1m'"SOURCE FOLDERS:\e[0m"
for arg in "${dir_sources[@]}"; do
# Print arg with escaped single quotes
printf "\n \e[95m'\e[37m%s\e[95m'\e[37m\e[0m" "${arg//\'/\'\\\'\'}"
done
fi
if [[ ${#vid_sources[@]} -gt 0 ]]; then
echo -en '\n\n\e[1m'"SOURCE VIDEOS:\e[0m"
for arg in "${vid_sources[@]}"; do
# Print arg with escaped single quotes
printf "\n \e[95m'\e[37m%s\e[95m'\e[37m\e[0m" "${arg//\'/\'\\\'\'}"
done
fi
echo
}
# Print CLI args used
print_ffmpeg_args() {
local ffmpeg_cmd=$1
shift
local args=("$@")
echo -en '\e[90m'
echo -n "$ffmpeg_cmd"
echo -en '\e[0m '
local next_arg=
for arg in "${args[@]}"; do
echo -n "$next_arg"
if [[ ${arg:0:1} = - ]]; then
next_arg=$'\e[35m'"$arg"$'\e[0m'
else
# Print $arg with any single quotes
# escaped to allow easy copy pasting
# reproducible FFmpeg commands
next_arg=\'"${arg//\'/\'\\\'\'}"\'
fi
next_arg+=' '
done
next_arg=${next_arg% }
echo "$next_arg"
}
# Human readable duration
human_duration() {
local seconds="$1"
local output=""
# Hours
if [[ $seconds -gt "60 * 60" ]]; then
local hours=$(( seconds / 60 / 60 ))
local output="${hours}h "
fi
# Minutes
if [[ $seconds -gt 60 ]]; then
local minutes=$(( (seconds / 60) % 60 ))
local output="${output}${minutes}m "
fi
# Seconds
local seconds=$(( seconds % 60 ))
local output="${output}${seconds}s"
echo "$output"
}
# Get first stream ID of a specific stream type
get_first_stream_id() {
local type=$1
local streams=$2
grep -E "^ +Stream.+$type" -m 1 <<< "$streams" | sed -Ee 's/^.+Stream #0:([0-9]+).*$/\1/'
}
# Get video stream frame count
get_stream_framecount() {
local cur_stream_details="$1"
local duration="$( echo -n "$cur_stream_details" | grep -Eo 'Duration: [^,]+' | awk '{ print $2 }' )"
local duration_secs=0
local size=($((60 * 60)) 60 1)
# Convert HH:MM:SS to just seconds
local IFS=':'
for dur in $duration; do
local secs=$( bc <<< "scale=8; $dur * ${size[0]}" )
local duration_secs=$( bc <<< "scale=8; $duration_secs + $secs" )
local size=("${size[@]:1}")
done
# Get fps to get total frames
local fps=$( grep -oP '\d+(.\d+)? fps' <<< "$cur_stream_details" | awk '{ print $1 }' )
# Check if the user specified an alternate framerate
if [[ $framerate != original ]]; then
local fps=$framerate
fi
local total_frames=$( bc <<< "scale=8; $fps * $duration_secs" )
local total_frames=$( printf "%.f" "$total_frames" )
# Stream identifier
local stream_id="$( grep -oP 'Stream #\d+:\d+' <<< "$cur_stream_details" | awk '{ print $2 }' )"
# stream_id,frame_count,dur_secs
echo "${stream_id#*:},$total_frames,$duration_secs"
}
# Run ffmpeg and print progress
run_ffmpeg() {
local vid_details="$1"
local vid_frames="$( get_detail "VSTREAM_FRAMES" "$vid_details" )"
local vid_dir_out="$( dirname "$( get_detail "VIDEO_OUT" "$vid_details" )" )"
local vid_file_out="$( basename "$( get_detail "VIDEO_OUT" "$vid_details" )" )"
# Create temporary file to store FFmpeg errors
local tmp_vid_ffmpeg_errors_filename=$( tr -sc '[:alnum:]' '-' <<< "$vid_file_out" | sed -Ee 's/^-+//;s/-+$//' )
local tmp_vid_ffmpeg_errors=$( dirname "$tmp_vid_enc_list" )/.batch-enc-ffmpeg-errors-${tmp_encoder_id:0:7}-$tmp_vid_ffmpeg_errors_filename
encoder_tmp_files+=("$tmp_vid_ffmpeg_errors")
touch "$tmp_vid_ffmpeg_errors"
hide_tmp_file_windows "$tmp_vid_ffmpeg_errors"
echo -n "" > "$tmp_vid_ffmpeg_errors"
shift
local ffmpeg_cmd=("${@}")
# Mapping of stream id's to video stream frame counts and duration
# TODO: Cleanup. This is probably over-engineered and useless
local IFS=':'
declare -A vid_stream_frames
for vid_s_frames in $vid_frames; do
local vid_stream_info_acts=(stream_id frames duration)
local stream_id=
local cur_vid_stream_frames=
local cur_vid_stream_duration=
local IFS=','
for part in $vid_s_frames; do
case ${vid_stream_info_acts[0]} in
stream_id )
local stream_id="$part" ;;
frames )
local cur_vid_stream_frames="$part" ;;
duration )
local cur_vid_stream_duration="$part"
vid_stream_frames[$stream_id]="$cur_vid_stream_frames,$cur_vid_stream_duration"
esac
vid_stream_info_acts=("${vid_stream_info_acts[@]:1}")
done
done
declare -A cur_progress
# Hide cursor
echo -en "\e[?25l"
# Start FFmpeg
"${ffmpeg_cmd[@]}" 2> "$tmp_vid_ffmpeg_errors" |
while read -r line; do
local key="${line%=*}"
local value="${line#*=}"
if [[ $key == progress ]]; then
# Prepare data for calculating progress
local enc_stream_info="${vid_stream_frames[${stream_id}]}"
local enc_frame_count="${enc_stream_info%,*}"
local enc_duration="${enc_stream_info#*,}"
local enc_duration_final="$enc_duration"
[[ $debug_run == true ]] && local enc_duration_final="$debug_run_dur"
local enc_frame_count="$( printf "%.f" "$( bc <<< "scale=8; ($enc_duration_final / $enc_duration) * $enc_frame_count")" )"
# Calculate progress' percentage
local enc_pct_n="$( printf "%.f" "$( bc <<< "scale=8; (${cur_progress[frame]} / $enc_frame_count) * 100" )" )"
local enc_pct_padding=" "
local enc_pct="${enc_pct_padding:0:-${#enc_pct_n}}${enc_pct_n}%"
if [[ "$( printf "%.f" "${cur_progress[fps]}" )" -gt 0 ]]; then
local eta_secs="$( printf "%.f" "$( bc <<< "scale=8; ($enc_frame_count - ${cur_progress[frame]}) / ${cur_progress[fps]}" )" )"
else
local eta_secs=0
fi
# Clear line. Print progress, FPS, and ETA (with some pretty formatting)
echo -en '\e[2K'"Progress \e[92m$( b "$enc_pct" ) FPS $( b "${cur_progress[fps]}" ) ETA $( b "$( human_duration "$eta_secs" )" )"
# Reset cursor position to the beginning of the line
echo -en "\r"
else
local cur_progress[$key]="$value"
fi
done
local ffmpeg_status=${PIPESTATUS[0]}
# Show cursor
echo -en "\e[?25h"
# Remove temporary FFmpeg error file or
# print it to the user in case of error
read -r -d '' ffmpeg_last_error_log < <( sed -Ee '/^\s*$/d' < "$tmp_vid_ffmpeg_errors" )
rm "$tmp_vid_ffmpeg_errors"
# Remove FFmpeg error log from list of temp files
unset encoder_tmp_files[-1]
# Return FFmpeg's exit status
return $ffmpeg_status
}
# Utility for checking and adding either source
# video files or directories
add_source() {
local source=$( check_windows_path "$1" )
if [[ -e $source ]]; then
if [[ -f $source ]]; then
vid_sources+=("$source")
elif [[ -d $source ]]; then
dir_sources+=("$source")
fi
else
echo "Error: '$source': no such file or directory" 1>&2
fi
}
# Main script logic
usage_section() {
local section=$1
local usage=$2
local cur_section=${defaults[help_section]}
if [[ $section == $cur_section || $cur_section == all ]]; then
echo -n "$usage"
fi
}
# Print usage/help
usage() {
echo -n "
USAGE
encoder.sh [sub | dub] [-r RES] [-a] [-s SOURCE] [-d DEST] [-R]
[--burn-subs] [--watermark FILE] [--clean] [--force]
[-w] [--watch-rescan] [--verbose-streams] [--fatal]
[--debug-run [DUR]] [--version]
encoder.sh update
encoder.sh -h | --help
DESCRIPTION
Encode all MKV and AVI and MP4 videos in the current
directory (or subdirectories) to MP4 videos.
Options are either set via optional arguments
listed below or interactive prompts in the
absence of such arguments. Arguments that accept
values can be in the form --arg=value.
OPTIONS" | sed -Ee '1d'
usage_section all "
sub, dub
Whether to encode subbed or dubbed.
Defaults to subbed. Implies --auto.
"
usage_section advanced "
--target-lang LANG
Target language that videos will be
encoded to. Defaults to $( b en ).
--origin-lang LANG
Original language that videos are currently
encoded in. Defaults to $( b jp ).
"
usage_section basic "
-r, --resolution RES
RES can be one of $( b 240 ), $( b 360 ), $( b 480 ), $( b 640 ), $( b 720 ),
$( b 1080 ), $( b 2160 ), or $( b original ). Original by default.
-a, --auto, --no-auto
Automatically determine appropriate audio
and video streams. Implies --burn-subs
in the absence of --no-burn-subs. Prompts
by default.
--burn-subs, --no-burn-subs
Burn subtitles. Prompts by default.
--recolor-subs
Recolor PGS/VOB subtitles to neutral
colors.
"
usage_section advanced "
--watermark FILE, --no-watermark
Use a watermark .ass FILE. Defaults to
AU watermark if it exists.
"
usage_section basic "
-s, --source DIR
Source file or directory to encode. Can be
used multiple times. Defaults to current
directory if omitted.
-d, --destination DIR
Destination directory for all encodes.
Will create the directory it it doesn't
already exist. Defaults to source
directory.
"
usage_section advanced "
-R, --recursive, --no-recursive
Whether to recursively search subdirs for
videos to encode. Won't by default.
--keep-default-sources
If sources are specified don't omit the
default sources specified in the config
file. Omits them by default if any
sources are specified.
--out-suffix[=SUFFIX]
Add a suffix to output video filenames.
e.g. $( b '--out-suffix=-encoded' ) would encode
foo.mkv into foo-encoded.mp4 instead
of foo.mp4. Defaults to -out when SUFFIX
is omitted.
--clean
Remove original videos after encoding.
--force
Overwrite existing videos. Won't by default.
"
usage_section basic "
-w, --watch
Watch source directory recursively for new
videos.
"
usage_section advanced "
--watch-rescan
Rescan the source directory on every file
change event; don't trust inotify's
information. Default on WSL.
--watch-validate
Validate files after detecting them while
watching. Won't by default as it's optimistic
and assumes the video is valid.
--framerate NUM
Set framerate for the video. Defaults to
the original framerate.
"
usage_section debug "
--debug-run [DURATION]
Test encoder by only encoding (optional)
DURATION in seconds of videos. When
DURATION is omitted it defaults to 5
seconds.
--debug-ffmpeg-args
Display the FFmpeg command used
--debug-ffmpeg-errors
Display FFmpeg error log even after successful
encodes.
--debug-config
Print the resulting configuration.
"
usage_section advanced "
--fatal
Consider FFmpeg errors fatal and stop encoding
all videos.
--verbose-streams
Print all streams and don't exclusively filter
video, audio, and subtitle streams.
--prompt-all
Prompt for all videos even if they have identical
stream tracks. Defaults to using the configuration
of an earlier video with the same stream/track
structure without prompting.
edit-config
Edit config file in a file editor. Use --editor
to choose an editor, e.g. $( b vim ) for Linux or
$( b notepad.exe ) for Windows, which are also the
defaults.
load-config CONFIG_URL
Download a new config file from CONFIG_URL and
change the current to the new config.
reset-config
Removes the config file and resets all
configuration to the defaults.
"
echo -n "
--version
Print version.
update
Update encoder.sh to its latest version.
-h, --help
Show simplfied help.
--help-advanced, --help-debug, --help-all
Show help from advanced sections.
"
}
# Data dir with watermark (same as script folder)
data_dir="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))"
IS_WINDOWS=false
# Check if is on Windows
if which ffmpeg.exe &> /dev/null; then
IS_WINDOWS=true
# Check for either wslpath or cygpath
if which wslpath &> /dev/null; then
HAS_WSLPATH=true
elif which cygpath &> /dev/null; then
HAS_CYGPATH=true
else
echo "On Windows either 'wslpath' or 'cygpath.exe' is required."
exit 1
fi
fi
# Some defaults
declare -A defaults
declare -A arg_mapping
# Arrays of sources to encode
vid_sources=()
dir_sources=()
# Default sources that will be included if no sources
# are specified or keep_default_sources is true
default_sources=()
defaults[res]=prompt # Default resolution (same as source)
defaults[auto]=null # Automatically determine streams
defaults[keep_default_sources]=false # If sources are specified don't omit the default sources
defaults[out_dir]="" # Output directory
defaults[recursive]=null # Recursively encode subdirs
defaults[out_suffix]=false # Append a suffix to output filename
defaults[out_suffix_name]="" # Output filename suffix
defaults[force]=false # Overwrites existing encodes
defaults[watch]=false # Watch source directory for new videos
defaults[watch_rescan]=false # Rescan the source dir for every inotify event
defaults[watch_validate]=false # Validate last 10 seconds of files after detecting them from watch mode
defaults[clean]=false # Removes original video after encoding
defaults[burn_subs]=null # Burns subtitles into videos
defaults[recolor_subs]=false # Recolor subtitles to a neutral color
defaults[watermark]="$data_dir/au.ass" # Watermark video (with AU watermark by default)
defaults[locale]=null # Subbed or dubbed
defaults[target_lang]=en # Target language to encode videos to
defaults[origin_lang]=jp # Original language videos (or streams of interest thereof) were encoded in
defaults[framerate]=original # Output framerate
defaults[debug_run]=false # Only encode short durations of the video for testing
defaults[debug_run_dur]=5 # Debug run duration
defaults[debug_ffmpeg_errors]=false # Don't remove FFmpeg error logs
defaults[debug_ffmpeg_args]=false # Print FFmpeg cli args
defaults[fatal]=false # Fail on FFmpeg errors
defaults[verbose_streams]=false # Don't filter video, audio, and subs streams, also print e.g attachment streams
defaults[prompt_all]=false # Prompt for all videos, even ones with identical stream structures
defaults[edit_config]=false # Whether to edit the config file or not
defaults[edit_config_editor]="" # Default editor for edit-config command. If omitted is Vim on *nix and Notepad on Windows
defaults[download_config_url]="" # URL to download a new config from
defaults[help_section]="" # Help section to choose from: basic, advanced, debug, all
arg_mapping[-r]=--resolution
arg_mapping[-a]=--auto
arg_mapping[-d]=--destination
arg_mapping[-s]=--source
arg_mapping[-R]=--recursive
arg_mapping[-w]=--watch
arg_mapping[-h]=--help
# FFmpeg argument defaults
ffmpeg_input_args=(
-hide_banner
-loglevel warning
-strict -2 # In case old version of FFmpeg to enable experimental AAC encoder
)
ffmpeg_output_args=(
-y # Overwrite existing files without prompting, we check instead
-c:v libx264
-preset veryslow
-tune ssim,fastdecode,zerolatency
-trellis 2
-subq 11
-me_method umh
-crf 19
-vsync 2
-g 30
-x264-params ref=6:deblock=1,1:bframes=8:psy-rd=1.5:aq-mode=3:aq-strength=1:psy-rd=1.50,0.60
-profile:v high
-profile:v high
-level 4.1
-b_strategy 1
-bf 16
-color_primaries bt709
-color_trc bt709
-colorspace bt709
-pix_fmt yuv420p
-c:a aac
-ac 2
-b:a 192k
-sn
-map_metadata -1
-map_chapters -1
-movflags +faststart # Web optimization
)
# Check for and load config
load_config
# Load default_sources
for src in "${default_sources[@]}"; do
add_source "$src"
done
cur_arg="$1"
consume_next=false
consume_optional=false
consume_next_arg=
invalid_args=()
has_initial_source_arg=false
# Argument parsing stuff
while true; do
# Check this argument isn't empty
if [[ -n $cur_arg ]]; then
# Check if this is parameter of a previous argument
if [[ $consume_next == true ]]; then
# If argument parmeter is optional and next arg is another argument, then skip to next argument
if [[ $consume_optional == true ]] && [[ ${cur_arg:0:1} == "-" ]]; then
consume_optional=false
consume_next=false
# Move on to next arg
continue
fi
# Special handling for --source/-s values.
if [[ $consume_next_arg = source ]]; then
add_source "$cur_arg"
else
defaults[$consume_next_arg]="$cur_arg"
fi
consume_next=false
consume_optional=false
# Current arg isn't another arg's parameter
else
cur_base_arg=("$cur_arg")
cur_base_arg_index=0
while [[ -n ${cur_base_arg[$cur_base_arg_index]} ]]; do
cur_arg_name=${cur_base_arg[$cur_base_arg_index]}
cur_arg_param=
if [[ $cur_arg_name =~ = ]]; then
cur_arg_param=${cur_arg_name#*=}
cur_arg_name=${cur_arg_name%%=*}
fi
case $cur_arg_name in
# Match all (listed) single char arguments either combined
# (e.g -aRs) or separate (e.g -a -R -s)
-+([adhsRrw]) )
opts=${cur_arg:1}
opt_length=${#opts}
# Remap single char arg to its full counterpart pushing it to $cur_base_arg
# to reprocess it
for (( i=0; i<opt_length; i++ )); do
arg_char=${opts:$i:1}
cur_base_arg+=("${arg_mapping[-$arg_char]}")
done
(( cur_base_arg_index++ ))
continue
;;
# Match all full arguments
--resolution )
# Resolution is supplied as next arg
consume_next=true
consume_next_arg=res
;;
--auto )
defaults[auto]=true
;;
--no-auto )
defaults[auto]=false
;;
--burn-subs )
defaults[burn_subs]=true
;;
--no-burn-subs )
defaults[burn_subs]=false
;;
--recolor-subs )
defaults[recolor_subs]=true
;;
--watermark )
# Watermark .ass file supplied as next arg
consume_next=true
consume_next_arg=watermark
;;
--no-watermark )
defaults[watermark]=
;;
--destination )
# Directory is supplied as next arg
consume_next=true
consume_next_arg=out_dir
;;
--source )
if [[ $has_initial_source_arg = false ]]; then
has_initial_source_arg=true
# Empty sources provided by default_sources from
# config file if keep_default_sources isn't set
if [[ ${defaults[keep_default_sources]} = false ]]; then
dir_sources=()
vid_sources=()
fi
fi
# Directory is supplied as next arg
consume_next=true
consume_next_arg=source
;;
--keep-default-sources )
defaults[keep_default_sources]=true
;;
--recursive )
defaults[recursive]=true
;;
--no-recursive )
defaults[recursive]=false
;;
--out-suffix )
defaults[out_suffix]=true
defaults[out_suffix_name]=-out
# out-suffix's name is (optionally) supplied as next arg
consume_next=true
consume_optional=true
consume_next_arg=out_suffix_name
;;
--force )
defaults[force]=true
;;
--watch )
defaults[watch]=true
;;
--watch-rescan )
defaults[watch_rescan]=true
;;
--watch-validate )
defaults[watch_validate]=true
;;
--clean )
defaults[clean]=true
;;
--framerate )
consume_next=true
consume_next_arg=framerate
;;
--debug-run )
defaults[debug_run]=true
# Debug run's duration is (optionally) supplied as next arg
consume_next=true
consume_optional=true
consume_next_arg=debug_run_dur
;;
--debug-ffmpeg-errors )
defaults[debug_ffmpeg_errors]=true
;;
--debug-ffmpeg-args )
defaults[debug_ffmpeg_args]=true
;;
--debug-config )
print_config
exit 0
;;
--fatal )
defaults[fatal]=true
;;
--prompt-all )
defaults[prompt_all]=true
;;
--verbose-streams )
defaults[verbose_streams]=true
;;
--help-advanced )
# Print help and quit
defaults[help_section]=advanced
;;
--help-debug )
# Print help and quit
defaults[help_section]=debug
;;
--help-all )
# Print help and quit
defaults[help_section]=all
;;
--help )
# Print help and quit
defaults[help_section]=basic
;;
--origin-lang )
# Directory is supplied as next arg
consume_next=true
consume_next_arg=origin_lang
;;
--target-lang )
# Directory is supplied as next arg
consume_next=true
consume_next_arg=target_lang
;;
# Sub/dub
sub )
defaults[locale]=sub
# Implies --auto
defaults[auto]=true
;;