#!/usr/bin/env bash
# Podcast file size per hour: encode one 60:00 speech master at 64/96/128/192 kbps,
# mono and stereo, and compare the bytes on disk with size = kbps x 1000 x seconds / 8.
# Input: LibriVox "A Summer in a Canyon" (dramatic reading), chapters 1 and 2,
# Public Domain Mark 1.0, https://archive.org/details/summercanyon_1907_librivox
# Usage: bash test-run.sh <workdir>   (expects <workdir>/in/ch01.mp3 and ch02.mp3)
set -euo pipefail
W="${1:?usage: test-run.sh <workdir>}"
cd "$W"
[ -s in/ch01.mp3 ] && [ -s in/ch02.mp3 ] || { echo "missing in/ch01.mp3 or in/ch02.mp3"; exit 1; }
mkdir -p out
SEC=3600
echo "# podcast-file-size-per-hour test run $(date -u +%FT%TZ)"
ffmpeg -version | head -1
echo "lame: $(ffmpeg -hide_banner -h encoder=libmp3lame 2>/dev/null | head -1)"

# 1. Master: join chapters 1+2 (67:10 total), cut to exactly 3600 s, 16-bit 44.1 kHz stereo WAV.
ffmpeg -v error -y -i in/ch01.mp3 -i in/ch02.mp3 \
  -filter_complex "[0:a][1:a]concat=n=2:v=0:a=1[a]" -map "[a]" -t $SEC -ar 44100 -ac 2 -c:a pcm_s16le out/master-stereo.wav
ffmpeg -v error -y -i out/master-stereo.wav -ac 1 -c:a pcm_s16le out/master-mono.wav

bytes() { stat -c %s "$1"; }
dur() { ffprobe -v error -show_entries format=duration -of csv=p=0 "$1"; }

# 2. Control with a known answer: PCM WAV, 44,100 x 2 ch x 2 bytes x 3600 s = 635,040,000 data bytes (+ header).
echo "## control: WAV sizes (expected data bytes: stereo 635040000, mono 317520000)"
for m in stereo mono; do
  f=out/master-$m.wav
  echo "control wav-$m bytes=$(bytes $f) duration=$(dur $f)"
done

# 3. CBR MP3, ffmpeg defaults (ID3v2 tag with encoder name + Xing/LAME info frame).
echo "## cbr mp3: label | kbps | ch | bytes | formula_bytes | diff_bytes | diff_pct | duration"
for ch in 1 2; do
  for k in 64 96 128 192; do
    f=out/cbr-${k}k-${ch}ch.mp3
    ffmpeg -v error -y -i out/master-stereo.wav -ac $ch -c:a libmp3lame -b:a ${k}k "$f"
    b=$(bytes "$f"); fb=$(( k * 1000 * SEC / 8 ))
    python3 -c "import sys; b,fb=int(sys.argv[1]),int(sys.argv[2]); print(f'cbr | {sys.argv[3]} | {sys.argv[4]} | {b} | {fb} | {b-fb} | {(b-fb)/fb*100:.3f} | {sys.argv[5]}')" "$b" "$fb" "$k" "$ch" "$(dur "$f")"
  done
done

# 4. Where the extra bytes come from: the same 64 kbps mono encode with no ID3v2 tag and no Xing frame.
echo "## overhead split, 64 kbps mono"
ffmpeg -v error -y -i out/master-stereo.wav -ac 1 -c:a libmp3lame -b:a 64k -id3v2_version 0 -write_xing 0 out/bare-64k-1ch.mp3
python3 - out/cbr-64k-1ch.mp3 out/bare-64k-1ch.mp3 <<'PY'
import sys, struct
def id3_size(p):
    h = open(p, 'rb').read(10)
    if h[:3] != b'ID3': return 0
    s = h[6:10]; return 10 + ((s[0] << 21) | (s[1] << 14) | (s[2] << 7) | s[3])
import os
a, b = sys.argv[1], sys.argv[2]
print(f"default bytes={os.path.getsize(a)} id3v2_bytes={id3_size(a)}")
print(f"bare bytes={os.path.getsize(b)} id3v2_bytes={id3_size(b)}")
print(f"tag_plus_xing_bytes={os.path.getsize(a)-os.path.getsize(b)}")
fb = 64 * 1000 * 3600 // 8
print(f"bare_minus_formula_bytes={os.path.getsize(b)-fb}")
# MPEG-1 Layer III at 44.1 kHz: 1152 samples per frame; frames needed for 3600 s plus encoder delay/padding
frames_audio = 3600 * 44100 / 1152
print(f"frames_for_3600s={frames_audio:.2f} (frame = 1152 samples = {1152/44100*1000:.3f} ms)")
PY

# 5. Cover art inside the MP3 (embedded artwork adds its own bytes, Spotify asks to keep it small).
echo "## cover art"
ffmpeg -v error -y -f lavfi -i "mandelbrot=s=3000x3000:end_pts=1" -frames:v 1 -q:v 3 out/cover-3000.jpg
ffmpeg -v error -y -i out/cbr-64k-1ch.mp3 -i out/cover-3000.jpg -map 0:a -map 1:v -c copy -id3v2_version 3 \
  -metadata:s:v title="Album cover" -metadata:s:v comment="Cover (front)" out/cbr-64k-1ch-cover.mp3
echo "cover jpg bytes=$(bytes out/cover-3000.jpg)"
echo "mp3 without cover bytes=$(bytes out/cbr-64k-1ch.mp3) with cover bytes=$(bytes out/cbr-64k-1ch-cover.mp3) added=$(( $(bytes out/cbr-64k-1ch-cover.mp3) - $(bytes out/cbr-64k-1ch.mp3) ))"

# 6. VBR MP3 (size follows the content, not a formula) and AAC-LC in M4A (Apple prefers AAC for RSS feeds).
echo "## vbr mp3 and aac: label | setting | ch | bytes | avg_kbps | duration"
for ch in 1 2; do
  for q in 4 6; do
    f=out/vbr-V${q}-${ch}ch.mp3
    ffmpeg -v error -y -i out/master-stereo.wav -ac $ch -c:a libmp3lame -q:a $q "$f"
    b=$(bytes "$f"); d=$(dur "$f")
    python3 -c "import sys; b,d=int(sys.argv[1]),float(sys.argv[2]); print(f'vbr | V{sys.argv[3]} | {sys.argv[4]} | {b} | {b*8/d/1000:.1f} | {d}')" "$b" "$d" "$q" "$ch"
  done
done
for spec in "64 1" "128 2"; do
  set -- $spec
  f=out/aac-${1}k-${2}ch.m4a
  ffmpeg -v error -y -i out/master-stereo.wav -ac $2 -c:a aac -b:a ${1}k -movflags +faststart "$f"
  b=$(bytes "$f"); fb=$(( $1 * 1000 * SEC / 8 ))
  python3 -c "import sys; b,fb=int(sys.argv[1]),int(sys.argv[2]); print(f'aac | {sys.argv[3]}k | {sys.argv[4]} | {b} | formula {fb} | diff_pct {(b-fb)/fb*100:.3f} | {sys.argv[5]}')" "$b" "$fb" "$1" "$2" "$(dur "$f")"
done

# 7. Units: the same byte counts in MB (1,000,000 bytes) and MiB (1,048,576 bytes).
echo "## units for the formula sizes"
for k in 32 64 96 128 192 256 320; do
  python3 -c "import sys; k=int(sys.argv[1]); b=k*1000*3600/8; print(f'{k} kbps 1 h: {b:.0f} bytes = {b/1e6:.1f} MB = {b/1048576:.1f} MiB; per minute {b/60/1e6:.2f} MB')" "$k"
done
python3 -c "b=320*1000*12*3600/8; print(f'320 kbps 12 h: {b:.0f} bytes = {b/1e9:.3f} GB = {b/1024**3:.3f} GiB')"
echo "DONE"
