#!/bin/bash


# Where screenshots are saved.
# SC_ROOT/SC_DIR should contain episode screenshot directories
SC_ROOT="model_data/current"
SC_DIR="screenshots"


# Select a temporary working directory
# if false, uses ramdisk.
# set to true if ramdisk overflows.
if false; then
	OUTPUT_DIR="model_data/video_output"

	# This directory will be deleted.
	# Make sure it doesn't already exist.
	if [ -e "$OUTPUT_DIR" ]; then
		echo "$OUTPUT_DIR exists, exiting. Please delete it manually."
		exit 1
	fi
	mkdir -p $OUTPUT_DIR

else
	OUTPUT_DIR=$(mktemp -d)
fi


# Usage:
# render_episode <src_dir> <output_name>
#
# Turns a directory of frame screenshots into a video.
# Applies upscaling. We do it early, because upscaling
# after encoding will exaggerate artifacts.
render_episode () {
	ffmpeg \
		-y \
		-loglevel quiet \
		-framerate 30 \
		-i "$1/hackcel_%003d.png" \
		-c:v libx264 \
		-crf 20 \
		-preset slow \
		-tune animation \
		-vf "scale=1024x1024:flags=neighbor" \
		"$2.mp4"
}



echo "Making episode files..."
for D in "$SC_ROOT/$SC_DIR"/*; do
	if [ -d "${D}" ]; then
		render_episode "$D" "$OUTPUT_DIR/${D##*/}"
	fi
done



echo "Merging..."
for f in "$OUTPUT_DIR"/*.mp4; do
	echo file \'$f\' >> "$OUTPUT_DIR/video_merge_list"
done



# Merge videos
ffmpeg \
	-loglevel error -stats -y \
	-f concat \
	-safe 0 \
	-i "$OUTPUT_DIR/video_merge_list" \
	"$SC_ROOT/1x.mp4"
echo ""
echo "Making accelerated video..."



# Make accelerated video
ffmpeg \
	-loglevel error -stats -y \
	-i "$SC_ROOT/1x.mp4" \
	-framerate 60 \
	-filter:v "setpts=0.125*PTS" \
	"$SC_ROOT/8x.mp4"



echo "Cleaning up...."
rm -dr $OUTPUT_DIR
