Last active
March 13, 2025 10:49
Reencoding mpvs to upload as discord clips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# A script that reencodes mkvs to a target filetype for uploading to discord | |
current_datetime=$(date +%Y-%m-%d_%H-%M-%S) | |
output_dir="discord-sized/$current_datetime" | |
if [[ ! -d "$output_dir" ]]; then | |
mkdir -p "$output_dir" | |
fi | |
reencoded_files=() | |
for file in *.mkv; do | |
# Check if the file exists | |
if [[ ! -f "$file" ]]; then | |
echo "Error: File $file not found. Skipping." | |
continue | |
fi | |
filename=$(basename "$file") | |
filename="${filename%.*}" | |
output_file="$output_dir/${filename}.mp4" | |
target_mb=$((9 * 1024 * 1024)) | |
audio_bytes=$(ffprobe -v error -select_streams a:0 -show_entries packet=size -of default=nokey=1:noprint_wrappers=1 "$file" | awk '{s+=$1} END {print s}' ) | |
duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file") | |
video_kbps=$(echo "scale=0; (($target_mb - $audio_bytes) * 8 / $duration / 1024)" | bc) | |
# Prevent video bitrate from being negative if audio is too large | |
if ((video_kbps < 0)); then | |
video_kbps=100 | |
fi | |
# Perform two-pass encoding | |
ffmpeg -y -i "$file" -c:v libx264 -b:v "${video_kbps}k" -pass 1 -an -f null /dev/null && \ | |
ffmpeg -y -i "$file" -c:v libx264 -b:v "${video_kbps}k" -pass 2 -c:a copy "$output_file" | |
echo "Re-encoded: $file to $output_file" | |
reencoded_files+=("$output_file") | |
done | |
echo "Finished processing all files, output:" | |
for encoded_file in "${reencoded_files[@]}"; do | |
echo "$output_dir/$encoded_file" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment