#!/usr/bin/env bash
# h264-declared-level-violation   ·   run: bash h264-declared-level-violation.sh
# Needs ffmpeg. ffmpeg will stamp a level the stream violates, and exit 0.
set -u; cd "$(mktemp -d)"
W=1080; H=1920; FPS=30; LVL=3.1; MAXFS=3600; MAXMBPS=108000
ffmpeg -v error -y -f lavfi -i "testsrc=size=${W}x${H}:rate=${FPS}:duration=1" \
  -c:v libx264 -preset ultrafast -level $LVL -pix_fmt yuv420p liar.mp4
echo "ffmpeg exit code: $?   <- the ceremony's entire evidence"
read -r w h lvl <<<"$(ffprobe -v error -select_streams v:0 \
  -show_entries stream=width,height,level -of csv=p=0 liar.mp4 | tr ',' ' ')"
mbw=$(( (w + 15) / 16 )); mbh=$(( (h + 15) / 16 ))    # CEIL, not floor
mbs=$(( mbw * mbh )); rate=$(( mbs * FPS ))
echo
echo "CEREMONY  ffprobe says level=$lvl                          : PASS"
echo "ORACLE    derive it from the picture's own dimensions"
echo "          ${w}x${h} -> ${mbw}x${mbh} = ${mbs} macroblocks @ ${FPS}fps = ${rate} MB/s"
echo "          L${LVL} ceilings: MaxFS=${MAXFS}  MaxMBPS=${MAXMBPS}"
ffmpeg -v error -i liar.mp4 -f null - 2>/dev/null && echo "          software decode: OK  <- why this ships"
if [ "$mbs" -gt "$MAXFS" ] || [ "$rate" -gt "$MAXMBPS" ]; then
  echo "                                                          : FAIL"
  echo
  echo "The file declares L${LVL} and breaks it on BOTH ceilings."
  echo "Android's MediaCodec sizes hardware buffers from the declaration."
  echo "Desktop software decoders ignore it entirely -- which is why it"
  echo "plays on every machine you own and fails on your visitors' phones."
  echo
  echo "Note: floor(1080/16)=67 and ceil(1080/16)=68. Coded frames pad up to"
  echo "whole macroblocks. floor and ceil AGREE at 720, 1280, 1920 and 640 --"
  echo "so a floor-based checker looks correct until it meets 1080 or 360."
  echo "The cure: do not pass -level at all. Let the encoder write the truth."
else
  echo "                                                          : PASS"
fi
