#!/usr/bin/env bash

# reference
# https://trac.ffmpeg.org/wiki/Encode/YouTube
# https://ffmpeg.org/ffmpeg-filters.html

# settings
song_path=$1

## metadata
source .metadata || { echo "Couldn't find the .metadata file."; exit 1; };

## other
song_duration=$( soxi -D "$song_path" )
font_title='/usr/share/fonts/serafettin-cartoon/SerafettinCartoonCondensed.ttf'
font_author='/usr/share/fonts/serafettin-cartoon/SerafettinCartoonCondensed.ttf'
font_image_credits='/usr/share/fonts/serafettin-cartoon/SerafettinCartoonCondensed.ttf'

# data cleanup
song_title_clean=$( echo $song_title | sed 's@[[:punct:]]@@g; s@[[:space:]]@_@g' )
video_name="${song_author,,}-${song_title_clean,,}.mp4"


# encode
ffmpeg \
	-y \
	-loop 1 \
	-vaapi_device /dev/dri/renderD128 \
	-i "${image_path}" \
	-i "${song_path}" \
	-c:v libx264 \
		-preset slow \
		-crf 18 \
	-c:a aac \
		-b:a 192k \
	-vf "
		framerate=60,
		format=yuv420p,
		drawbox=y=(ih-h)/2:color=black@0.4:width=iw:height=150:t='$song_duration',
		drawtext=fontfile='${font_title}':text='${song_title}':fontcolor=white@0.9:fontsize=120:x = t * (w / ${song_duration}):y=(h-text_h)/2,
 		drawtext=fontfile='${font_author}':text='${song_author}':fontcolor=white@0.8:fontsize=90:x=(w-text_w)/2:y=(h-text_h)/1.75:box=1:boxcolor=black@0.4:boxborderw=10,
 		drawtext=fontfile='${font_image_credits}':text='${image_credits}':fontcolor=white@0.8:fontsize=45:box=1:boxcolor=black@0.4:boxborderw=10:y=h-line_h
	" \
	-movflags +faststart \
	-shortest \
	-pix_fmt yuv420p \
	"${video_name}"


# play
ffplay "${video_name}"


# delete
echo -n "Delete? (y/n) "
read answer

if [[ "y" == "$answer" ]]; then
	echo "Deleting $video_name..."
	rm -f "${video_name}"
fi

