
A post-render AI video validation pipeline catches -4.2 LUFS loudness blowouts, +1.6 dBTP AAC inter-sample clipping, lingering tail silence, and subtitle cue end-of-file overruns before a batch of generated MP4 files hits an upload queue. Running one ffprobe metadata probe alongside FFmpeg's ebur128=peak=true and silencedetect filters isolates all four defects in a single decode pass.
When I wired up my first check script for short vertical clips, ffmpeg -v error -i clip.mp4 -f null - returned exit code 0 on every file and fooled me into shipping broken audio. Every stream decoded cleanly at the container level, yet one export crackled on phone speakers during loud bass hits and another hung its closing caption past playback end. Ignore everything below if you only export silent four-second B-roll cuts without dialogue or sidecar captions. Once timed speech and WebVTT subtitles run in automated batches, exit code 0 doesn't tell you whether a file is publishable.
Where a basic AI video validation pipeline lets broken renders slip through
Standard upload checks verify file size, codec headers, and packet decoding, leaving an AI video validation pipeline blind to integrated loudness, true-peak headroom, dead air, and subtle container rounding drift. Batch exports from generation APIs or preset tools like Sheru Bhai Maker commonly land in 5s, 8s, and 10s brackets across 480p, 720p, and 1080p MP4 files. Small shifts in AAC encoder priming and integer video frame counts regularly push real container durations away from the nominal length you asked the model for.
Four post-render assertions catch those defects right after muxing:
| Validation gate | Tool / FFmpeg filter | Automated pass rule | Failure mode prevented |
|---|
| Integrated loudness window | ffmpeg -af ebur128=peak=true | -18.0 <= I <= -12.0 LUFS | Whisper-quiet clips or aggressive platform gain reduction |
| True-peak headroom ceiling | ebur128=peak=true (Peak) | true_peak_db <= -1.0 dBTP | Inter-sample distortion after lossy AAC compression |
| Trailing dead-air tail | silencedetect=noise=-35dB:d=0.30 | tail_silence_s <= 0.65 s | Awkward silent hold after dialogue finishes |
| Subtitle EOF cue overrun | ffprobe duration vs SRT/VTT | (cue_end_s - actual_dur_s) * 1000 <= 0.0 ms | Final caption truncated or stuck on frame close |
Keeping these gates downstream saves compute compared to blindly re-encoding every file. Running two-pass normalization on clean exports wastes CPU cycles and re-quantizes already compressed AAC audio.
Catching +1.6 dBTP clipping and -28.8 LUFS outliers with ebur128
Digital sample peaks look harmless right up until lossy AAC reconstruction pushes inter-sample waveforms past 0.0 dBFS. Checking raw PCM sample amplitude misses that overshoot, whereas running FFmpeg's ebur128 filter with peak=true enables 4x oversampled true-peak metering across the decoded waveform. That extra check catches brief bass or vocal transients that overload mobile speakers.
I built four synthetic 24.0 fps H.264/AAC MP4 fixtures locally under Python 3.13.3 with ffmpeg 9.0.2 and ffprobe 9.0.2 to isolate how these boundary failures behave under real filter output.

Integrated loudness and true-peak dBTP headroom measured by ffmpeg 9.0.2 ebur128=peak=true across four batch MP4 fixtures.
On clip_01_balanced_5s (720x1280, target 5.0s), integrated loudness lands at -14.6 LUFS and true peak sits at -8.9 dBTP. Both checks pass. Switch to clip_02_clipped_5s (720x1280, target 4.92s), and integrated loudness surges to -4.2 LUFS while true peak jumps +1.6 dBTP past the -1.0 dBTP ceiling, pushing audible distortion into mobile speakers even though ffprobe sees a valid AAC stream with zero decode errors.
Quiet outliers break differently. On clip_04_quiet_10s (1280x720, target 10.0s), true peak sits safely at -24.3 dBTP, yet integrated loudness falls to -28.8 LUFS. Boosting a -28.8 LUFS file by 14.8 dB drags background encoding noise up behind the voice. Meanwhile, clip_03_tailsil_8s (720x1280, target 7.88s) clears both acoustic limits at -15.0 LUFS and -9.0 dBTP, showing why loudness checks alone still pass broken timing downstream.
Auditing GOP rounding drift, cue overruns, and tail silence in Python
Asking an MP4 encoder for a 4.92s or 7.88s clip at 24.0 fps rarely yields that exact duration on disk. Video codecs emit integer frame counts: 4.92 * 24 rounds up to 119 frames (4.958s), while 7.88 * 24 rounds up to 190 frames (7.917s). Meanwhile, audio packets flush on 1024-sample AAC boundaries independently of the last video PTS, so subtitle sidecar timestamps generated from nominal target lengths easily drift out of alignment with actual container EOF.

Subtitle cue overrun in milliseconds alongside trailing silence duration below -35 dB detected by silencedetect=noise=-35dB:d=0.30.
Running silencedetect=noise=-35dB:d=0.30 alongside ffprobe exposes both trailing dead air and subtitle bleed immediately. Why drop d to 0.30 instead of keeping FFmpeg's default 2.0 seconds? A two-second silence floor misses most trailing pauses inside five-second or eight-second clips. Setting 0.30 ignores brief 250 ms breath gaps (0.000s flagged on clip_01_balanced_5s and clip_02_clipped_5s) while catching genuine dead air. On clip_03_tailsil_8s, speech cuts out early and leaves 1.111s of dead air past -35 dB. That breaches the 0.650s publish cap, whereas clip_04_quiet_10s lands at 0.592s and passes the tail check even while failing loudness at -28.8 LUFS.
Under the W3C WebVTT specification, cue ranges use mm:ss.ttt --> mm:ss.ttt or hh:mm:ss.ttt --> hh:mm:ss.ttt with dot millisecond separators rather than SRT commas. Both clip_01_balanced_5s (cue_end_s = 4.65s against 5.000s, -350.0 ms margin) and clip_04_quiet_10s (cue_end_s = 9.35s against 10.000s, -650.0 ms margin) close captions well before container end. On clip_02_clipped_5s (cue_end_s = 5.10s vs 4.958s actual) and clip_03_tailsil_8s (cue_end_s = 8.20s vs 7.917s actual), the final cues overrun container EOF by +141.7 ms and +283.3 ms.
The first Python function below parses both SRT and WebVTT final cue timestamps and compares them against unrounded ffprobe container duration using subprocess.run with capture_output=True. Keep raw_dur_s unrounded in memory for arithmetic before rounding display values, because rounding 7.9167 up to 7.917 prematurely shifts millisecond tail math by 1 ms.
import json
import re
import subprocess
from pathlib import Path
def parse_last_cue_end_s(subtitle_path: str) -> float:
"""Return the final cue end timestamp in seconds from an SRT or WebVTT file."""
text = Path(subtitle_path).read_text(encoding="utf-8")
long_re = re.compile(
r"^\s*\d{2}:\d{2}:\d{2}[.,]\d{3}\s*-->\s*(\d{2}):(\d{2}):(\d{2})[.,](\d{3})"
)
short_re = re.compile(
r"^\s*\d{2}:\d{2}[.,]\d{3}\s*-->\s*(\d{2}):(\d{2})[.,](\d{3})"
)
end_times = []
for line in text.splitlines():
if m_long := long_re.match(line):
eh, em, es, ems = map(int, m_long.groups())
end_times.append(eh * 3600 + em * 60 + es + ems / 1000.0)
elif m_short := short_re.match(line):
em, es, ems = map(int, m_short.groups())
end_times.append(em * 60 + es + ems / 1000.0)
if not end_times:
raise ValueError(f"No valid SRT/VTT timestamps in {subtitle_path}")
return max(end_times)
def probe_container_and_cues(mp4_path: str, subtitle_path: str) -> dict:
"""Probe MP4 streams via ffprobe and compute subtitle EOF overrun in milliseconds."""
cmd = [
"ffprobe", "-v", "quiet",
"-print_format", "json",
"-show_format", "-show_streams",
mp4_path,
]
proc = subprocess.run(cmd, capture_output=True, text=True, check=True)
probe = json.loads(proc.stdout)
streams = probe.get("streams", [])
vstream = next((s for s in streams if s.get("codec_type") == "video"), None)
astream = next((s for s in streams if s.get("codec_type") == "audio"), None)
if not vstream or not astream:
raise RuntimeError(f"Missing video or audio stream in {mp4_path}")
raw_dur_s = float(probe["format"]["duration"])
num, den = map(int, vstream["r_frame_rate"].split("/"))
cue_end_s = parse_last_cue_end_s(subtitle_path)
return {
"width": int(vstream["width"]),
"height": int(vstream["height"]),
"fps": round(num / den, 2),
"raw_dur_s": raw_dur_s,
"actual_dur_s": round(raw_dur_s, 3),
"cue_end_s": cue_end_s,
"cue_overrun_ms": round((cue_end_s - raw_dur_s) * 1000.0, 1),
}
Watch out for an ebur128 stderr parsing trap I tripped over while writing the audio filter wrapper. FFmpeg prints I: and LRA: progress updates every 100 ms across the whole decode stream before writing the final Summary: block at the bottom. Matching re.search against the full stderr buffer grabs t: 0.1s startup numbers (LRA: 0.0 LU) instead of end-of-file measurements. Splitting err.split("Summary:")[-1] isolates the footer cleanly, and checking silence_end against raw_dur_s - 0.15 prevents mid-clip pauses from masquerading as trailing dead air.
def validate_audio_and_gate(
mp4_path: str,
raw_dur_s: float,
cue_overrun_ms: float,
) -> dict:
"""Measure integrated LUFS, true peak dBTP, and trailing silence in one FFmpeg pass."""
cmd = [
"ffmpeg", "-hide_banner", "-nostats",
"-i", mp4_path,
"-af", "ebur128=peak=true,silencedetect=noise=-35dB:d=0.30",
"-f", "null", "-",
]
proc = subprocess.run(cmd, capture_output=True, text=True, check=True)
err = proc.stderr
summary = err.split("Summary:")[-1]
lufs_match = re.search(r"I:\s*([-\d.]+)\s*LUFS", summary)
tp_match = re.search(r"Peak:\s*([-\d.]+)\s*dBFS", summary)
if not (lufs_match and tp_match):
raise RuntimeError(f"Incomplete EBU R128 summary for {mp4_path}")
integrated_lufs = float(lufs_match.group(1))
true_peak_db = float(tp_match.group(1))
sil_starts = [float(x) for x in re.findall(r"silence_start:\s*([\d.]+)", err)]
sil_ends = [float(x) for x in re.findall(r"silence_end:\s*([\d.]+)", err)]
is_tail_silence = bool(
sil_starts
and sil_starts[-1] > 1.0
and (len(sil_ends) < len(sil_starts) or sil_ends[-1] >= raw_dur_s - 0.15)
)
tail_silence_s = round(max(0.0, raw_dur_s - sil_starts[-1]), 3) if is_tail_silence else 0.0
failures = []
if not (-18.0 <= integrated_lufs <= -12.0):
failures.append(f"loudness {integrated_lufs} LUFS outside [-18.0, -12.0]")
if true_peak_db > -1.0:
failures.append(f"true peak {true_peak_db:+.1f} dBTP > -1.0 ceiling")
if tail_silence_s > 0.65:
failures.append(f"tail silence {tail_silence_s:.3f}s > 0.650s")
if cue_overrun_ms > 0.0:
failures.append(f"cue overrun {cue_overrun_ms:+.1f} ms past EOF")
return {
"integrated_lufs": integrated_lufs,
"true_peak_db": true_peak_db,
"tail_silence_s": tail_silence_s,
"qc_pass": not failures,
"failures": failures,
}
Running both functions verbatim against clip_01_balanced_5s.mp4 and its 4.65s WebVTT sidecar under Python 3.13.3 and ffmpeg 9.0.2 returned {'width': 720, 'height': 1280, 'fps': 24.0, 'actual_dur_s': 5.0, 'cue_end_s': 4.65, 'cue_overrun_ms': -350.0, 'integrated_lufs': -14.6, 'true_peak_db': -8.9, 'tail_silence_s': 0.0, 'qc_pass': True, 'failures': []}. On clip_02_clipped_5s.mp4, the failure list caught -4.2 LUFS loudness, +1.6 dBTP true peak, and a +141.7 ms cue overrun. On clip_03_tailsil_8s.mp4, it flagged 1.111s tail silence alongside +283.3 ms cue overrun, while clip_04_quiet_10s.mp4 tripped -28.8 LUFS without firing a false silence error on its 0.592s tail.
Locking wide vs vertical stream tags and YouTube disclosure flags
Acoustic and cue checks still need stream-geometry verification so a 1280x720 landscape export never slips into a 720x1280 vertical Reels slot. Reading width, height, and r_frame_rate inside probe_container_and_cues() lets your batch router verify that vertical exports (clip_01 through clip_03, 720x1280 at 24.0 fps) and horizontal widescreen exports (clip_04_quiet_10s, 1280x720 at 24.0 fps) stay separated before queuing uploads.

Wide horizontal sample frame contrasting 16:9 widescreen framing checks against 9:16 vertical exports before subtitle burn-in and upload tagging.
Frames built for wide 16:9 exports, like the sunset yacht helipad layout above, rely on that dimension check before you place captions or set upload flags. If an exported MP4 carries realistic altered visuals or synthetic voices, verify your platform disclosure toggle in metadata alongside the audio check rather than patching it manually after publish. Under YouTube's altered or synthetic content guidelines, clearly unrealistic animations don't require mandatory disclosure, while realistic synthetic voices or faces mean checking the upload box and keeping C2PA credentials intact. Fail any clip outside -18.0 to -12.0 LUFS, above -1.0 dBTP, over 0.650s trailing silence, or past 0.0 ms cue EOF before it ever reaches the scheduler.
Join the conversation! Your thoughts help the community grow.