#!/bin/bash
# to-limit.sh <video> <limit_MB> [out.mp4] [height]: two-pass H.264 encode aimed a little under a size limit (1 MB = 1,000,000 bytes).
# Uses 97% of the limit as the target and 128 kbps AAC audio: draft settings, not a platform figure.
set -euo pipefail
in=${1:-}; limit=${2:-}; out=${3:-to-limit-out.mp4}; height=${4:-}
[ -s "$in" ] || { echo "input missing or empty: $in" >&2; exit 1; }
case $limit in ""|*[!0-9.]*) echo "limit must be a number of MB, for example 25" >&2; exit 1;; esac
secs=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$in" | tr -d "\r")
case $secs in ""|*[!0-9.]*) echo "no duration in the file: remux it first, for example ffmpeg -i in.webm -c copy fixed.mkv" >&2; exit 1;; esac
awk -v s="$secs" 'BEGIN{exit !(s>0)}' || { echo "no duration in the file: remux it first, for example ffmpeg -i in.webm -c copy fixed.mkv" >&2; exit 1; }
if [ "$(wc -c < "$in")" -le "$(awk -v l="$limit" 'BEGIN{printf "%d", l*1000000}')" ]; then echo "the file is already under $limit MB: send the original, re-encoding would only enlarge it" >&2; exit 0; fi
vk=$(awk -v l="$limit" -v s="$secs" 'BEGIN{printf "%d", l*1000000*8*0.97/s/1000-128}')
[ "$vk" -ge 50 ] || { echo "limit too small for $secs s: video bitrate would be $vk kbps" >&2; exit 1; }
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
vf=(); [ -z "$height" ] || vf=(-vf "scale=-2:$height")
ffmpeg -y -v error -i "$in" ${vf[@]+"${vf[@]}"} -c:v libx264 -b:v "${vk}k" -pass 1 -passlogfile "$tmp/p" -an -f null /dev/null
ffmpeg -y -v error -i "$in" ${vf[@]+"${vf[@]}"} -c:v libx264 -b:v "${vk}k" -pass 2 -passlogfile "$tmp/p" -c:a aac -b:a 128k -movflags +faststart "$out"
echo "video bitrate ${vk} kbps, output $(wc -c < "$out") bytes"
