Moved everything into funcitons for scoping; push optimized videos to an "optimized" subfolder

This commit is contained in:
Alex Paarfus
2023-06-27 15:06:13 -04:00
parent 20d208d9a0
commit 88cd942e90

View File

@@ -1,64 +1,81 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -e
FOLDER_ORIGIN="$2"
EXTENSIONS_TO_WATCH=("mkv" "mp4" "avi" "mov")
MESSAGE_WAITING="optimizing_please_wait"
usage() { usage() {
[[ -n "${*}" ]] && printf '%s\n' "Error: ${*}" >&2
cat << EOF cat << EOF
USAGE: ${0##*/} [OPTION] --folder PATH USAGE: ${0##*/} [OPTION] PATH
Watches when new videos are added to a folder and optimizes them. Watches when new videos are added to a folder and optimizes them.
OPTIONS: OPTIONS:
--help Display this usage message and exit --help Display this usage message and exit
--folder PATH Folder path where new video will be monitored and optimized
EOF EOF
exit 1
} }
start() { optimize() {
inotifywait -m -e create,moved_to --format '%f' "$FOLDER_ORIGIN" | while read -r filename; do touch -a "${2}"
extension="${filename##*.}" ffmpeg \
for ext in "${EXTENSIONS_TO_WATCH[@]}"; do -i "${1}" \
if [[ "$ext" = "$extension" ]]; then -c:v "libx264" \
if [[ "$filename" != optimized* ]]; then -tune stillimage \
filename_output="optimized_${filename%.*}.mp4" -c:a "aac" \
touch "$FOLDER_ORIGIN/$MESSAGE_WAITING" -b:a "192k" \
ffmpeg -i "$FOLDER_ORIGIN/$filename" -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -nostdin -shortest "/tmp/$filename_output" -pix_fmt "yuv420p" \
mv "/tmp/$filename_output" "$FOLDER_ORIGIN/$filename_output" -nostdin \
rm "$FOLDER_ORIGIN/$MESSAGE_WAITING" -shortest \
fi "${2}"
fi
done
done
} }
isArg="" run() {
local file extension optimized
optimized="${1}/optimized"
while [[ $# -gt 0 ]]; do set -e
case "$1" in
--help) mkdir --parents "${optimized}"
while read -r file; do
extension="${file##*.}"
[[ "${extension,,}" =~ foo ]] || continue
printf '%s\n' "Optimizing file '${file}'..."
if ! optimize "${file}" "${optimized}/${file%.*}.mp4"; then
printf '%s\n' "Failed to optimize file: '${file}'" >&2
fi
done < <(inotifywait --monitor --event "create" --event "moved_to" --format '%f' "${1}")
}
main() {
local opts
opts="$(getopt \
--options h \
--longoptions help \
--name "${0##*/}" \
-- "${@}" \
)"
eval set -- "${opts}"
while true; do
case "${1}" in
-h | --help ) usage; return 0;;
-- ) shift; break;;
* )
printf '%s\n' "Unknown option: '${1}'" >&2
usage usage
return 1
;; ;;
--folder)
isArg="1"
if [ $# -eq 2 ]; then
start
else
usage "You need to specify the path of the folder to watch."
fi
;;
*)
esac esac
shift shift
done done
if [[ -z "${isArg}" ]]; then if [[ -z "${1}" ]]; then
usage "Not enough arguments" printf '%s\n' "No folder specified" >&2
fi return 1
fi
mkdir --parents "${1}"
run "${1}"
}
main "${@}"