Commit b17ad529 by ale

Parallelize MP3 encoding

1 parent c800399f
Showing with 54 additions and 34 deletions
#!/bin/bash
#
# Synchronize FLAC files to removable media.
# It can convert output files to MP3 (in parallel).
#
if [ $# -lt 2 ]; then
echo "Usage: $0 [--mp3] <MEDIA_DIR> <FLAC>..." >&2
exit 1
echo "Usage: $0 [--mp3] <MEDIA_DIR> <FLAC>..." >&2
exit 1
fi
convert_to_mp3=0
case "$1" in
--mp3)
convert_to_mp3=1
shift
;;
--mp3)
convert_to_mp3=1
shift
;;
esac
# Automatically detect ffmpeg/avconv.
if [ ${convert_to_mp3} -eq 1 ]; then
ffmpeg=$(which ffmpeg)
[ -n "${ffmpeg}" ] || ffmpeg=$(which avconv)
if [ -z "${ffmpeg}" ]; then
echo "ERROR: could not find ffmpeg or avconv executable" >&2
exit 1
fi
fi
media_root="$1"
shift
cleanup() {
sed s,/,-,g | sed s,:,,g
tr / - | tr -d :
}
for f in "$@"; do
artist=$(metaflac "$f" --show-tag=ARTIST | sed s/^.*=//g | cleanup)
album=$(metaflac "$f" --show-tag=ALBUM | sed s/^.*=//g | cleanup)
if [ -z "${artist}" -a -z "${album}" ]; then
echo "ERROR: could not read metadata for $f" >&2
continue
fi
dst="${media_root}"
if [ -n "${artist}" ]; then
dst="${dst}/${artist}"
fi
if [ -n "${album}" ]; then
dst="${dst}/${album}"
fi
mkdir -p "${dst}"
if [ ${convert_to_mp3} -eq 1 ]; then
dst="${dst}/$(basename "${f}" .flac).mp3"
avconv -i "$f" -f mp3 -b:a 320k "${dst}"
else
cp -v "$f" "$dst"
fi
done
# Select command to run (copy, or conversion).
if [ ${convert_to_mp3} -eq 1 ]; then
cmd="${ffmpeg} -i {1} -codec:a libmp3lame -b:a 320k {2}"
concurrency=$(grep ^proc /proc/cpuinfo | wc -l)
else
cmd="cp -v {1} {2}"
concurrency=1
fi
# Emit source / destination pairs, one per line, and feed them to
# GNU parallel.
(for f in "$@"; do
artist=$(metaflac "$f" --show-tag=ARTIST | sed s/^.*=//g | cleanup)
album=$(metaflac "$f" --show-tag=ALBUM | sed s/^.*=//g | cleanup)
if [ -z "${artist}" -a -z "${album}" ]; then
echo "ERROR: could not read metadata for $f" >&2
continue
fi
dst="${media_root}"
if [ -n "${artist}" ]; then
dst="${dst}/${artist}"
fi
if [ -n "${album}" ]; then
dst="${dst}/${album}"
fi
mkdir -p "${dst}"
if [ ${convert_to_mp3} -eq 1 ]; then
dst="${dst}/$(basename "${f}" .flac).mp3"
fi
echo -e "${f}\t${dst}"
done) \
| parallel --colsep '\t' -j ${concurrency} ${cmd}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!