set -e

INFILE="$1"
# additional params can be input to the extraction
# for time or seek
shift

mkdir -p temp

ffmpeg \
    -i "$INFILE" \
    -r 60000/1001 \
    -vf 'scale=256:-2' \
    -an \
    "$@" \
    -y "temp/$INFILE-%04d.png"

ffmpeg \
    -i "$INFILE" \
    -vn \
    -ac 1 \
    -ar 15734 \
    -acodec pcm_u8 \
    "$@" \
    -y "temp/$INFILE-audio.wav" || echo no audio

for frame in "temp/$INFILE-"[0-9][0-9][0-9][0-9].png
do
    n="${frame#temp/$INFILE-}"
    n="${n%.png}"
    out="temp/$INFILE-dither-${n}"
    last="${n:0-1}"
    node ../dither-image.js "$frame" "$out" &
    if (( last == 9 ))
    then
        echo "frame $n"
        wait
    fi
done
wait

if [ -f "temp/$INFILE-audio.wav" ]
then
    ffmpeg \
        -r 60000/1001 \
        -i "temp/$INFILE-dither-%04d.png" \
        -i "temp/$INFILE-audio.wav" \
        -ac 2 \
        -ar 48000 \
        -vf 'pad=w=534' \
        -pix_fmt yuv420p \
        -movflags +faststart \
        -y "$INFILE-dither.mp4"
else
    ffmpeg \
        -r 60000/1001 \
        -i "temp/$INFILE-dither-%04d.png" \
        -vf 'pad=w=534' \
        -pix_fmt yuv420p \
        -movflags +faststart \
        -y "$INFILE-dither.mp4"
fi
