#!/bin/bash
# test-run.sh: how video resolution changes behave (Koldflux, 2026-11-20). Needs ffmpeg/ffprobe 6.x and python3.
# Sources: two Wikimedia Commons clips (Delaneys Falls, CC0; Vettisfossen, CC BY-SA 3.0) trimmed to 8 s,
# plus code-drawn test cards with a perfect circle (the control: a correct resize keeps it round, roundness 1.00).
set -u; cd "$(dirname "$0")"; mkdir -p src work
UA="KoldfluxResearch/1.0"
[ -s src/delaneys.webm ] || curl -sL -A "$UA" -o src/delaneys.webm https://upload.wikimedia.org/wikipedia/commons/8/8b/Delaneys_Falls.webm
[ -s src/vettis.webm ]   || curl -sL -A "$UA" -o src/vettis.webm   https://upload.wikimedia.org/wikipedia/commons/2/29/Vettisfossenvideo.webm
# 1. inputs: every input is H.264 CRF 18 + AAC in MP4, 8 s, so only the frame shape differs
mk() { ffmpeg -v error -y "$@" -t 8 -c:v libx264 -crf 18 -preset medium -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart; }
[ -s work/in-landscape4k.mp4 ] || mk -ss 5 -i src/delaneys.webm work/in-landscape4k.mp4
[ -s work/in-vertical.mp4 ]    || mk -ss 2 -i src/vettis.webm work/in-vertical.mp4
card() { # card <name> <w> <h> <sar_num> <sar_den>: white frame, black circle that is round on screen
  ffmpeg -v error -y -f lavfi -i "color=white:s=$2x$3:r=30,format=gray,geq=lum='if(lt(hypot((X-W/2)*$4/$5\,Y-H/2)\,min(W*$4/$5\,H)*0.35)\,16\,235)',setsar=$4/$5,format=yuv420p" \
    -f lavfi -i "sine=f=440:r=48000" -t 8 -c:v libx264 -crf 18 -preset medium -c:a aac -b:a 128k -shortest work/in-$1.mp4; }
[ -s work/in-card16x9.mp4 ]  || card card16x9 1920 1080 1 1
[ -s work/in-card9x16.mp4 ]  || card card9x16 1080 1920 1 1
[ -s work/in-card4x3.mp4 ]   || card card4x3 1440 1080 1 1
[ -s work/in-card239.mp4 ]   || card card239 2560 1072 1 1
[ -s work/in-cardanamorphic.mp4 ] || card cardanamorphic 1440 1080 4 3
# a phone-style vertical: stored landscape 1920x1080 with a 90 degree rotation tag
if [ ! -s work/in-cardrotated.mp4 ]; then
  ffmpeg -v error -y -i work/in-card9x16.mp4 -vf transpose=2 -c:v libx264 -crf 18 -preset medium -c:a copy work/tmp-stored.mp4
  ffmpeg -v error -y -display_rotation 90 -i work/tmp-stored.mp4 -c copy work/in-cardrotated.mp4 2>/dev/null || ffmpeg -v error -y -i work/tmp-stored.mp4 -c copy -metadata:s:v:0 rotate=-90 work/in-cardrotated.mp4
fi
# roundness = how round the circle looks in a player that honours SAR; pixel_roundness = in an app that ignores SAR
# 2. methods for a 720p target. BOXFIT: fit a fixed 1280x720 box (a common recipe), TURNED: the box turns with the frame and
#    non-square pixels are squared first (the Koldflux compress tool's filter since 2026-11-20), HEIGHT: -2:720, FORCED: 1280:720
BOXFIT="scale='min(iw,1280)':'min(ih,720)':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1"
TURNED="scale='trunc(iw*sar/2)*2':ih,setsar=1,scale='if(gt(ih,iw),min(iw,720),min(iw,1280))':'if(gt(ih,iw),min(ih,1280),min(ih,720))':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1"
HEIGHT="scale=-2:720"; FORCED="scale=1280:720"
round() { # displayed roundness of the dark circle in one frame: (bbox width * SAR) / bbox height
  local f=$1; IFS=, read w h sar < <(ffprobe -v error -select_streams v:0 -show_entries stream=width,height,sample_aspect_ratio -of csv=p=0 "$f")
  rot=$(ffprobe -v error -select_streams v:0 -show_entries stream_side_data=rotation -of csv=p=0 "$f" | tr -d " -"); case "$rot" in 90|270) t=$w; w=$h; h=$t;; esac
  ffmpeg -v error -ss 1 -i "$f" -frames:v 1 -f rawvideo -pix_fmt gray -y work/frame.gray
  python3 - "$w" "$h" "$sar" <<'PY'
import sys
w,h=int(sys.argv[1]),int(sys.argv[2]); s=sys.argv[3]; n,d=(s.split(':')+['1'])[:2] if ':' in s else ('1','1'); sar=(int(n)/int(d)) if int(n) else 1.0
b=open('work/frame.gray','rb').read(); W,H=w,h
xs=[];ys=[]
for y in range(0,H,2):
  row=b[y*W:(y+1)*W]
  dark=[x for x in range(0,W,2) if row[x]<100]
  if dark: xs+= [dark[0],dark[-1]]; ys.append(y)
r=(max(xs)-min(xs)+2)/(max(ys)-min(ys)+2) if xs else 0
print("%.3f pixel_roundness(SAR ignored)=%.3f"%(r*sar,r) if xs else "na")
PY
}
probe() { ffprobe -v error -select_streams v:0 -show_entries stream=width,height,sample_aspect_ratio,display_aspect_ratio:stream_side_data=rotation -of compact=p=0:nk=0 "$1" | tr '\n' ' ' | sed 's/side_data_type=Display Matrix|//'; }
echo "== ffmpeg: $(ffmpeg -version | head -1 | cut -d' ' -f3)  date: $(date -u +%F)"
echo "== inputs"
for i in work/in-*.mp4; do n=$(basename $i .mp4); n=${n#in-}; printf "%-16s %s size=%s" $n "$(probe $i)" $(stat -c%s $i); case $n in card*) printf " roundness=%s" "$(round $i)";; esac; echo; done
echo "== 720p target: method | input | output | roundness"
for m in BOXFIT TURNED HEIGHT FORCED; do
  for i in work/in-*.mp4; do n=$(basename $i .mp4); n=${n#in-}; o=work/out-$m-$n.mp4
    [ -s $o ] || ffmpeg -v error -y -i $i -vf "${!m}" -c:v libx264 -pix_fmt yuv420p -crf 28 -preset veryfast -c:a aac -b:a 128k $o
    printf "%-6s %-16s %s size=%s" $m $n "$(probe $o)" $(stat -c%s $o); case $n in card*) printf " roundness=%s" "$(round $o)";; esac; echo
  done
done
echo "== file size by target height (tool settings: libx264 CRF 28 veryfast, AAC 128k; TURNED filter with 854x480 / 1280x720 / 1920x1080 boxes)"
for i in work/in-landscape4k.mp4 work/in-vertical.mp4; do n=$(basename $i .mp4)
  for b in "854 480" "1280 720" "1920 1080"; do set -- $b
    F="scale='trunc(iw*sar/2)*2':ih,setsar=1,scale='if(gt(ih,iw),min(iw,$2),min(iw,$1))':'if(gt(ih,iw),min(ih,$1),min(ih,$2))':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1"
    o=work/size-$n-$2.mp4; [ -s $o ] || ffmpeg -v error -y -i $i -vf "$F" -c:v libx264 -pix_fmt yuv420p -crf 28 -preset veryfast -c:a aac -b:a 128k $o
    printf "%-16s box=%sx%s %s size=%s\n" ${n#in-} $1 $2 "$(probe $o)" $(stat -c%s $o)
  done
  o=work/size-$n-same.mp4; [ -s $o ] || ffmpeg -v error -y -i $i -c:v libx264 -pix_fmt yuv420p -crf 28 -preset veryfast -c:a aac -b:a 128k $o
  printf "%-16s box=none(control, same CRF, no resize) %s size=%s\n" ${n#in-} "$(probe $o)" $(stat -c%s $o)
done
echo "== upscale check: 720p file back to 3840x2160 vs the 4K input (SSIM measures similarity to the input, not how good it looks)"
[ -s work/up-2160.mp4 ] || ffmpeg -v error -y -i work/size-in-landscape4k-720.mp4 -vf scale=3840:2160:flags=lanczos -c:v libx264 -pix_fmt yuv420p -crf 28 -preset veryfast -c:a copy work/up-2160.mp4
s720=$(ffmpeg -i work/size-in-landscape4k-720.mp4 -i work/in-landscape4k.mp4 -lavfi "[0:v]scale=3840:2160:flags=lanczos[a];[a][1:v]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*')
sup=$(ffmpeg -i work/up-2160.mp4 -i work/in-landscape4k.mp4 -lavfi "[0:v][1:v]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*')
echo "720p file      size=$(stat -c%s work/size-in-landscape4k-720.mp4) ssim_vs_input(after display scaling)=$s720"
echo "upscaled 2160p size=$(stat -c%s work/up-2160.mp4) $(probe work/up-2160.mp4) ssim_vs_input=$sup"
echo "== Koldflux compress tool in a browser (ffmpeg.wasm), 720p and 480p presets, driven by compresstool.cjs"
if [ -n "${TOOL_URL:-}" ]; then
  mkdir -p tool; for job in 720p:work/in-vertical.mp4 720p:work/in-cardanamorphic.mp4 480p:work/in-vertical.mp4; do
    pr=${job%%:*}; i=${job#*:}
    node compresstool.cjs "$TOOL_URL" tool $pr $i | python3 -c "import sys,json; r=json.loads(sys.stdin.read()); print(r['preset'], r['file'], 'in', r['in_bytes'], 'out', r.get('out_bytes'), 'seconds', r.get('secs'), r.get('error',''))"
    n=$(basename $i .mp4); o=$(ls tool/$n-*-$pr.mp4 | head -1); printf "  %s" "$(probe $o)"; case $n in *card*) printf " roundness=%s" "$(round $o)";; esac; printf " audio=%s\n" "$(ffprobe -v error -select_streams a -show_entries stream=codec_name -of csv=p=0 $o)"
  done
else echo "skipped (set TOOL_URL)"; fi
