#!/bin/bash set -euo pipefail set -x # If ffmpeg is not installed, exit with an error message if ! command -v ffmpeg &>/dev/null; then printf "Can't find ffmpeg. Please install it (or check your path).\n" exit 1 fi function makeGIF { local input=$1 local framerate=$2 local width=$3 local basename=$4 local maxColors=$5 # GIFs of 60fps videos have to be 50fps if [[ $framerate == "60" ]]; then framerate=50 fi if [[ $maxColors == "" ]]; then maxColors=256 fi ffmpeg \ -i "$input" \ -framerate "$framerate" \ -vf "fps=$framerate,scale=$width:-1:flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=${maxColors}[p];[s1][p]paletteuse" \ "${basename}.gif" } function makeMP4 { local input=$1 local framerate=$2 local width=$3 local basename=$4 ffmpeg \ -i "$input" \ -framerate "$framerate" \ -vcodec libx264 \ -pix_fmt yuv420p \ -an \ -crf 20 \ -filter:v scale="$width":-1 \ "${basename}.mp4" } function makeWebM { local input=$1 local framerate=$2 local width=$3 local basename=$4 ffmpeg \ -i "$input" \ -framerate "$framerate" \ -pix_fmt yuv420p \ -an \ -crf 30 \ -b:v 0 \ -filter:v scale="$width":-1 \ "${basename}.webm" } function requirePostiveInt { if [[ ! $2 =~ ^[0-9]+$ ]]; then printf "%s must be a positive integer.\n" "$1" exit 1 fi } input="$(gum file --header "Input")" if [[ ! -f "$input" ]]; then printf "Input file '%s' does not exist.\n" "$input" exit 1 fi outputBase="$(gum input --header "Output base name" --value="$(basename "${input%.*}")")" if [[ -z $outputBase ]]; then printf "Output base name cannot be empty.\n" exit 1 fi framerate="$(gum input --header "Framerate" --value="24")" requirePostiveInt "Framerate" "$framerate" width="$(gum input --header "Width" --value="1920")" requirePostiveInt "Width" "$width" type="$(gum choose --header "Output type" "gif" "mp4" "webm")" if [[ -z $type ]]; then printf "No output type selected.\n" exit 1 fi maxColors="" if [[ $type == "gif" ]]; then maxColors="$(gum input --header "Max GIF colors" --value="256")" if [[ ! $maxColors =~ ^[0-9]+$ ]]; then printf "Max GIF colors must be a positive integer.\n" exit 1 fi fi case $type in gif) makeGIF "$input" "$framerate" "$width" "$outputBase" "$maxColors" ;; mp4) makeMP4 "$input" "$framerate" "$width" "$outputBase" ;; webm) makeWebM "$input" "$framerate" "$width" "$outputBase" ;; *) printf "Unknown output type '%s'.\n" "$type" exit 1 ;; esac