#!/bin/bash
# Koldflux noise re-test for "Why is my TikTok video blurry" (2026-11-18). Replaces the old part D, which put a CRF 23 file next to a 4 Mbps file.
# Like with like: the clean and the noisy picture go through the SAME encoder settings, once at CRF 23 and once at 4 Mbps.
# Made-up ffmpeg testsrc2 pattern (8 s, 1080x1920, 30 fps), no people, no TikTok account. Writes noise-results.txt next to this script.
set -e
D=$(cd "$(dirname "$0")" && pwd); W=$(mktemp -d /tmp/rt_ttnoise.XXXXXX); cd "$W"
LOG="$D/noise-results.txt"; : > "$LOG"
say(){ echo "$*" | tee -a "$LOG"; }
ssim(){ ffmpeg -hide_banner -v info -i "$1" -i "$2" -lavfi "[0:v][1:v]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | tail -1 | cut -d: -f2; }
say "## Koldflux noise re-test, $(date -u +%F) UTC, $(ffmpeg -version | head -1 | cut -c1-40)"
ffmpeg -hide_banner -v error -f lavfi -i testsrc2=s=1080x1920:r=30:d=8 -c:v ffv1 clean.mkv
ffmpeg -hide_banner -v error -y -i clean.mkv -vf "noise=alls=24:allf=t+u" -c:v ffv1 noisy.mkv
say "clean source against itself: SSIM $(ssim clean.mkv clean.mkv)  (control, must be 1.000000)"
say "noisy source against the clean source: SSIM $(ssim noisy.mkv clean.mkv)"
enc(){ # name source mode-args
  ffmpeg -hide_banner -v error -y -i "$2" -c:v libx264 -preset medium $3 -pix_fmt yuv420p -an "$1.mp4"
  ffmpeg -hide_banner -v error -y -i "$1.mp4" -c:v ffv1 "$1.mkv"
}
say ""
say "## A. SAME SETTINGS, CRF 23 for both (quality-targeted): file size"
enc a_clean clean.mkv "-crf 23"; enc a_noisy noisy.mkv "-crf 23"
SC=$(stat -c %s a_clean.mp4); SN=$(stat -c %s a_noisy.mp4)
say "clean at CRF 23: $SC bytes"; say "noisy at CRF 23: $SN bytes"
say "ratio noisy / clean at the same CRF 23: $(python3 -c "print('%.1f'%($SN/$SC))") times"
say "SSIM clean -> clean encoded: $(ssim a_clean.mkv clean.mkv)"
say "SSIM noisy -> noisy encoded (against its own source): $(ssim a_noisy.mkv noisy.mkv)"
say "SSIM clean -> noisy encoded: $(ssim a_noisy.mkv clean.mkv)"
say ""
say "## B. SAME SETTINGS, 4 Mbps for both (fixed bitrate): quality"
enc b_clean clean.mkv "-b:v 4M -maxrate 4M -bufsize 8M"; enc b_noisy noisy.mkv "-b:v 4M -maxrate 4M -bufsize 8M"
say "clean at 4 Mbps: $(stat -c %s b_clean.mp4) bytes"; say "noisy at 4 Mbps: $(stat -c %s b_noisy.mp4) bytes"
say "SSIM clean -> clean encoded: $(ssim b_clean.mkv clean.mkv)"
say "SSIM noisy -> noisy encoded (against its own source): $(ssim b_noisy.mkv noisy.mkv)"
say "SSIM clean -> noisy encoded: $(ssim b_noisy.mkv clean.mkv)"
say ""
say "## C. CONTROL: the same clean source encoded twice with the same settings gives the same size"
enc c_clean clean.mkv "-crf 23"
[ "$(stat -c %s c_clean.mp4)" = "$SC" ] && say "CONTROL repeat encode identical size: PASS" || { say "CONTROL repeat encode differs: FAIL"; exit 1; }
say "ALL CONTROLS PASS"
rm -rf "$W"
