#!/bin/bash
# Copyright © 2024 DiffieHellman
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# Return invalid usage if there aren't at least 2 args
[ "$#" -gt 0 ] || exit 2

# $video is each video after argv[0]
for video ; do
	# Probe the audio format
	audioformat=$(ffprobe -loglevel error -select_streams a:0 -show_entries stream=codec_name -of default=nw=1:nk=1 "${video}")
	# Remux if already in a free format, otherwise rencode to opus
	if [ "$audioformat" = "opus" ]; then
		ffmpeg -i "${video}" -map_metadata 0 -c:a copy -vn -sn "${video%.*}.opus"
	elif [ "$audioformat" = "vorbis" ]; then
		#hack to turn first frame of video into 300x200 thumbnail and embed it into ogg as ffmpeg doesn't yet support embedding thumbnails in ogg in the standard way
	ffmpeg -i "${video}" -map_metadata 0 -map 0:v -vf trim=1:2,thumbnail,scale=300:200 -map 0:a -disposition:v attached_pic -c:a copy  "${video%.*}.ogg"
	elif [ "$audioformat" = "flac" ]; then
		#ditto
		ffmpeg -i "${video}" -map_metadata 0 -map 0:v -vf trim=1:2,thumbnail,scale=300:200 -map 0:a -disposition:v attached_pic -c:a copy "${video%.*}.flac"
	else
		ffmpeg -i "${video}" -map_metadata 0 -c:a libopus -vn -sn "${video%.*}.opus"
	fi
done
