#!/usr/bin/env bash

# Extracts audio from a video. It expects you to know what audio codecs the video container has, e.g.
# it's an mp4 video with aac and m4a audio. Just set the format to the appropriate extension.
# If you want to convert to a different format or you want to change the bit rate, channels, trim the audio, etc.
# then use extract-audio-from-video-and-transcode

if which tput >/dev/null 2>&1; then
    ncolors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
    RED="$(tput setaf 1)"
    GREEN="$(tput setaf 2)"
    YELLOW="$(tput setaf 3)"
    BLUE="$(tput setaf 4)"
    MAGENTA="$(tput setaf 5)"
    CYAN="$(tput setaf 6)"
    BOLD="$(tput bold)"
    NORMAL="$(tput sgr0)"
else
    RED=""
    GREEN=""
    YELLOW=""
    BLUE=""
    MAGENTA=""
    CYAN=""
    BOLD=""
    NORMAL=""
fi

filename=$(basename -- "$1")
format="$2"
start_time="$3"
end_time="$4"

if [[ $1 == "" || $2 == "" ]]; then
    printf "${BOLD}${RED}Usage: extract-audio-from-video <filename> <format (mp3, m4a, aac, etc)> <optional: start time HH:MM:SS, use empty string or 0 for start> <optional: end time HH:MM:SS, use empty string or 0 for no value>${NORMAL}\n"
    exit 1
fi

extension="${filename##*.}"
filename="${filename%.*}"
output_name="$filename.$format"

timing_args=""
if [[ $start_time != "" ]]; then
    timing_args="-ss $start_time "
fi
if [[ $end_time != "" ]]; then
    if [[ $start_time == "0" && $end_time == "0" ]]; then
        # We treat a start and end with 0 values as no op.
        timing_args=""
    elif [[ $end_time != "0" ]]; then
        # Handle having a start time but end time is set to 0, can just ignore it and it'll use the remainder of the video.
        timing_args+="-to $end_time"
    fi
fi

printf "\n${YELLOW}${BOLD}Extracting audio from $filename.$extension | output: $output_name | start: $start_time | end: $end_time${NORMAL}\n"

ffmpeg -y -stats -loglevel level+error $timing_args -i "$filename.$extension" -vn -acodec copy "$output_name"

printf "\n${GREEN}${BOLD}Done extracting audio from $filename.$extension | output name '$output_name'${NORMAL}\n\n"