#!/bin/bash
if [ "$1" = "-f" ]
then
	force=1
	shift
fi

for inf in "$@"
do
	level=`ffprobe -show_streams "$inf" 2> /dev/null | grep level= | head -1 | cut -f2 -d=`
	if [ -z "$force" ] && [ -n "$level" ] &&
			[ ! "$level" -gt 41 ] &&
			ffprobe -show_streams "$inf" 2> /dev/null | grep -q codec_name=h264
	then
		echo
		echo `basename "$inf"` "is already in H.264 format, <= High@L4.1!"
		if mediainfo "$inf" | grep -iq ': Quicktime$'
		then
			echo "...but it will have to be remuxed to MP4"

			movf="${inf%.*}".mov
			if [ "$inf" != "$movf" ]
			then
				mv "$inf" "$movf"
			fi
			inf=

			if mediainfo "$mmvf" | grep -iq 'Format.* : AAC$'
			then
				remuxer=remux-mp4
			else
				remuxer=remux-mp4-aac
				echo "...and its audio must be transcoded to AAC"
			fi
			echo

			movbn=$(basename "$movf")
			( cd "$(dirname "$movf")" ;
			  $remuxer "$movbn" &&
			  rmtrash "$movbn"
			)

			inf="${movf%.*}".mp4
		fi

		if [ -n "$inf" ]
		then
			echo
			open "$inf"     # send video to Subler for [re]tagging
		fi
		# else, we landed in the remux case above and it failed, so
		# don't open the problem file with Subler
	elif [ -e "$inf" ]
	then
		actual=$(mediainfo "$inf" | grep "Format profile.*@" | cut -f2 -d:)
		echo `basename "$inf"` "was encoded at $actual; transcoding..."

		# Extract existing artwork first.  Yes, -E goes at end.  :rolleyes:
		cover=$(atomicparsley "$inf" -E)
		if [ -n "$cover" ]
		then
			cover=$(echo "$cover" | cut -f5- -d' ')
			echo No cover art in \"$inf\".
		fi

		# Do the transcode
		tmpf="$inf".tmp
		if ffmpeg -i "$inf" -pix_fmt yuv420p \
				-c:v libx264 -profile:v main -level 4.1 -crf 18 -coder 0 \
				-c:a aac -ab 128k \
				-f mp4 "$tmpf"
		then
			# Overwrite original with transcode.  Don't bother trying to
			# put the cover art back.  It doesn't seem to work right,
			# and this process already requires an Subler pass to
			# restore other things.  We'll use the saved art then.
			#
			# The mv target syntax ensures that if the input file name
			# wasn't *.mp4 that it gets renamed.  Yes, this means we
			# break any references to *.m4v, but that's the wrong
			# extension to use for an MPEG-4 systems file.
			outf="${inf%.*}.mp4"
			mv "$tmpf" "$outf"
			open "$outf"
		else
			rmtrash "$tmpf"
		fi
	fi
done
