#!/bin/sh
# split-mp4-audio encodes each audio track of a video file as an Ogg Opus
# file for whip-loop(1), named after the video file and the language of
# the track: talk.mp4 becomes talk-deu.opus, talk-eng.opus, ...
#
# All files are as long as the video, rounded up to 20 ms; tracks that
# start late, have gaps or end early are padded with silence, so that
# whip-loop plays them in sync.  Needs ffmpeg and ffprobe.
set -eu

usage() {
    echo "usage: split-mp4-audio [-b bitrate] [-o output-dir] file.mp4" >&2
    exit 2
}

bitrate=64k
outdir=
while getopts b:o: opt; do
    case $opt in
    b) bitrate=$OPTARG ;;
    o) outdir=$OPTARG ;;
    *) usage ;;
    esac
done
shift $((OPTIND - 1))
[ $# -eq 1 ] || usage
in=$1
base=$(basename "$in")
base=${base%.*}
outdir=${outdir:-$(dirname "$in")}

duration=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$in")
duration=$(awk -v d="$duration" \
    'BEGIN { n = int(d * 50); if (n < d * 50) n++; printf "%.2f", n / 50 }')
# One line per audio track: its index and language, if it has one.
tracks=$(ffprobe -v error -select_streams a \
    -show_entries stream=index:stream_tags=language -of csv=p=0 "$in")
if [ -z "$tracks" ]; then
    echo "$in: no audio tracks" >&2
    exit 1
fi

# Build the ffmpeg command line, one output per track.
set -- -hide_banner -loglevel warning -stats -i "$in"
n=0
names=" "
files=
for track in $tracks; do
    lang=$(echo "$track" | awk -F, '{ print $2 }')
    case $lang in
    "" | und) lang=track$n ;;
    esac
    case $names in
    *" $lang "*) lang=$lang-$n ;;
    esac
    names="$names$lang "
    out=$outdir/$base-$lang.opus
    files="$files$out
"
    set -- "$@" -map "0:a:$n" -af aresample=async=1:first_pts=0,apad \
        -t "$duration" -c:a libopus -b:a "$bitrate" -ar 48000 "$out"
    n=$((n + 1))
done

ffmpeg "$@"
printf '%s' "$files"
