#!/usr/bin/env bash

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

if [[ $1 == "" ]]; then
    printf "${BOLD}${RED}Usage: $0 <use-gpu (1|0)> <filename> <optional output name>${NORMAL}\n"
    exit 1
fi

use_gpu=$1

filename=$(basename -- "$2")
extension="${filename##*.}"
filename="${filename%.*}"

output_name="$3"

use_crf=25 # Found the following to work best with vids containing text (e.g. programming vid): 25 for CPU encoding and 27 for GPU.
if [[ $use_gpu -eq 1 ]]; then
    use_crf=27
fi

function encode() {
    crf=$1
    if [[ $output_name == "" ]]; then
        output="${filename}_COMPRESSED_CRF-${crf}.$extension"
    else
        output="${output_name}.$extension"
    fi

    printf "\n${YELLOW}${BOLD}Encoding '$filename.$extension' | GPU: $use_gpu | CRF $crf | output: $output${NORMAL}\n"

    if [[ $use_gpu -eq 1 ]]; then
        # File will be slightly larger than CPU encoding, but it's much faster to transcode and doesn't max out the CPU cores.
        ffmpeg -y -vsync 0 -hwaccel cuvid -c:v h264_cuvid -i "$filename.$extension" -c:a copy -c:v h264_nvenc -profile:v high -rc:v vbr_hq -cq:v $crf -b:v 5M -maxrate 5M -max_muxing_queue_size 9999 "$output"
    else
        ffmpeg -i "$filename.$extension" -c:v libx264 -crf $crf -preset veryfast -profile:v baseline -level 3.0 -strict -2 "$output"
    fi
    printf "\n${GREEN}${BOLD}Done encoding '$filename.$extension' (CRF $crf) | output name '$output'${NORMAL}\n\n"
}

encode $use_crf

#printf "\n${YELLOW}${BOLD}Encoding using a range of CRF values.${NORMAL}\n"
## Bigger crf values == bigger compression.
#for crf in {25..28}
#do
#    encode $crf
#done