#!/bin/bash -e

#####################################################
#
# Youtube: https://trac.ffmpeg.org/wiki/Encode/YouTube
# Vimeo:   https://vimeo.zendesk.com/hc/en-us/articles/360056550451-Video-and-audio-compression-guidelines
#
# Usage: bash ffmpeg/basic/social.sh <input video>
#
#####################################################

INPUT=`realpath "${1}"`
FILENAME=`basename "${INPUT}"`
FILE="${FILENAME%.*}"
INPUTDIR=`dirname "${INPUT}"`

if [ "${INPUT}" == "" ]; then
	echo "Please provide an input video as your first argument"
	exit 1
fi

YOUTUBE="${INPUTDIR}/${FILE}-youtube.mkv"
VIMEO="${INPUTDIR}/${FILE}-vimeo.mkv"
TWITTER="${INPUTDIR}/${FILE}-twitter.mp4"
INSTAGRAM="${INPUTDIR}/${FILE}-instagram.mp4"

# Encode a video for YouTube
ffmpeg -i "${INPUT}" \
	-vcodec libx264 \
	-preset slow \
	-vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" \
	-pix_fmt yuv420p \
	-crf 12 \
	-c:a aac \
	-b:a 192k \
	 "${YOUTUBE}"

# Encode a video for Vimeo using the
# recommended settings for 720p video
ffmpeg -i "${INPUT}" \
	-vcodec libx264 \
	-preset slow \
	-pix_fmt yuv420p \
	-profile:v main \
	-b:v 7500k \
	-minrate 5000k \
	-maxrate 10000k \
	-c:a aac \
	-ar 48000 \
	"${VIMEO}"

# Encode video for Twitter
ffmpeg -i "${INPUT}" \
	-pix_fmt yuv420p \
	-vcodec libx264 \
	-acodec aac \
	-vb 2048k\
	-minrate 1024k \
	-maxrate 4096k \
	-bufsize 1024k \
	-ar 44100  \
	-ac 2  \
	-strict experimental \
	"${TWITTER}"

# Crop and encode for Instagram
ffmpeg -i "${INPUT}" \
	-vf "crop=w='min(iw\,ih)':h='min(iw\,ih)',setsar=1" \
	-framerate 30 \
	-vcodec mpeg4 \
	-vb 8000k \
	-strict experimental \
	-q:v 0 \
	"${INSTAGRAM}"