Skip to content

Instantly share code, notes, and snippets.

@hr3lxphr6j
Created July 24, 2021 04:12
Show Gist options
  • Save hr3lxphr6j/2ec988570728808183c1c87519d3332c to your computer and use it in GitHub Desktop.
Save hr3lxphr6j/2ec988570728808183c1c87519d3332c to your computer and use it in GitHub Desktop.
convert2alac.sh
#!/usr/bin/env bash
set -ueo pipefail
get_cover_index() {
input_file="${1}"
ffprobe -i "${input_file}" \
-loglevel -8 \
-show_streams \
-of json | jq '.streams[] | select(.disposition.attached_pic==1) | .index'
}
get_cover_file() {
input_dir="${1}"
fd -1 '^(?:[cC][oO][vV][eE][rR]|[fF][lL][oO][dD][eE][rR])\d*\.(?:[jJ][pP][eE]?|[pP][nN])[gG]$' "${input_dir}"
}
convert() {
input_file="$1"
out_dir="$2"
echo "[INFO] Input: ${input_file}"
input_file_dir=$(dirname "${input_file}")
input_file_name=$(basename "${input_file}")
command="ffmpeg -loglevel error -hide_banner -y -i \"${input_file}\" "
cover_idx=$(get_cover_index "${input_file}")
cover_file=$(get_cover_file "${input_file_dir}")
if [[ -n ${cover_idx} ]]; then
echo "[INFO] Cover from input file[idx:${cover_idx}]"
command+=" -map 0:${cover_idx} -c:v copy "
elif [[ -f "${cover_file}" ]]; then
echo "[INFO] Cover from image file: ${cover_file}"
command+=" -i \"${cover_file}\" -map 1 -c:v copy"
else
echo "[WARN] Cover not found"
fi
command+=" -disposition:v:0 attached_pic "
command+=" -map 0:a -map_metadata 0 -c:a alac "
command+=" \"${out_dir}/${input_file_dir}/${input_file_name%.*}.m4a\" "
if [[ ${DRY_RUN:-} == "1" ]]; then
echo "$command"
else
echo "[INFO] Result: ${out_dir}/${input_file_dir}/${input_file_name%.*}.m4a"
mkdir -p "${out_dir}/${input_file_dir}"
eval "$command"
fi
}
help() {
printf "%s: -h\n\tShow help.\n" "$0"
printf "%s: -o\n\tOutput dir.\n" "$0"
printf "%s: -i\n\tInput dir.\n" "$0"
printf "%s: -d\n\Dry run.\n" "$0"
}
main() {
while getopts "hdi:o:" OPT; do
case ${OPT} in
h) help && exit 0 ;;
i) input="${OPTARG}" ;;
d) export DRY_RUN=1 ;;
o) output="${OPTARG}" ;;
?) help && exit 1 ;;
esac
done
if [[ ! -d "${output:-}" ]]; then
echo "[Error] Output dir not spec or not exist." 1>&2 && exit 1
fi
if [[ -f "${input:-}" ]]; then
convert "${input}" ${output}
elif [[ -d "${input:-}" ]]; then
bash -c "cd \"${input}\"; fd -e flac -x $0 -i \"{}\" -o \"${output}\""
else
echo "[Error] Input not spec or not exist." 1>&2 && exit 1
fi
unset DRY_RUN
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment