#!/bin/bash

set -e

# This script allows me to take mp4 files and clip+slow them down for interesting slow mo clips :^)
# Magic is at the bottom the rest is just interfacing


if [ -z "$3" ]; then
        cat <<- EOF
        Usage: slow-mo.sh /path/to/file.mp4 HH:MM:SS[.ms] HH:MM:SS[.ms]
        Note:
            .ms (miliseconds) optional as they are not required to make this script work but
            ffmpeg does understand the field

        Alternative flags( environment variables ):
            REMOVE_AUDIO
                    When this is set the audio output is disabled
                SLOW_RATE
                    2.0 => Half speed
            3.0 => 3x slower
            Formula is 1 / RATE => OutputRate
        EOF
        exit 0
fi

# If this gets set then we do not create the first clip with audio
case "$REMOVE_AUDIO" in
        true)
                echo "Audio: DISABLED"
                FFMPEG_COPY="-c copy -an"
                ;;
        *)
                echo "Audio: ENABLED"
                FFMPEG_COPY="-c:v copy"
                ;;
esac

# Aliasing input variables
input="$1"
starttime="$2"
endtime="$3"

SLOW_RATE=2.0
# Make ffmpeg be quiet
LOG="-loglevel error"

clip="$input-clip.mp4"

echo "Cutting desired section from $2 to $3..."
ffmpeg $LOG -y -i "$input" -ss "$starttime" -to "$endtime" $FFMPEG_COPY "$clip"

echo "Slowing down video now"
ffmpeg $LOG -y -i "$clip" -vf "setpts=$SLOW_RATE*PTS" "$input.slow.mp4"

