#!/usr/bin/env python3
"""figs.py <flv> <out.html> : draws the per-second payload rate of a stream file as an inline SVG (1200x720), from ffprobe packet sizes (dts buckets, whole seconds)."""
import subprocess, sys, collections
f, out = sys.argv[1:3]
rows = subprocess.run(['ffprobe','-v','error','-show_entries','packet=dts_time,size','-of','csv=p=0',f],capture_output=True,text=True,check=True).stdout.split('\n')
s = collections.defaultdict(int)
for r in rows:
    if ',' in r:
        t, z = r.split(',')
        if t != 'N/A': s[int(float(t))] += int(z)
n = max(s)                                  # whole seconds only
v = [s[i]*8/1e6 for i in range(n)]
avg = sum(v)/n; mx = max(v)
X0, X1, Y0, Y1, TOP = 110, 1160, 150, 590, 12.0
bw = (X1-X0)/n
def y(m): return Y1 - (Y1-Y0)*m/TOP
bars = ''.join(f'<rect x="{X0+i*bw+1:.1f}" y="{y(m):.1f}" width="{bw-2:.1f}" height="{Y1-y(m):.1f}" fill="{"#c2570c" if m > 7.0 else "#3b6ea5"}"/>' for i, m in enumerate(v))
grid = ''.join(f'<line x1="{X0}" x2="{X1}" y1="{y(m):.1f}" y2="{y(m):.1f}" stroke="#ddd" stroke-width="1"/><text x="{X0-12}" y="{y(m)+10:.1f}" text-anchor="end" font-size="28" fill="#333">{m}</text>' for m in (0, 4, 8, 12))
lines = (f'<line x1="{X0}" x2="{X1}" y1="{y(5.6):.1f}" y2="{y(5.6):.1f}" stroke="#b3261e" stroke-width="4"/>'
         f'<line x1="{X0}" x2="{X1}" y1="{y(7.0):.1f}" y2="{y(7.0):.1f}" stroke="#1b7f3b" stroke-width="4"/>'
         f'<line x1="{X0}" x2="{X1}" y1="{y(avg):.1f}" y2="{y(avg):.1f}" stroke="#222" stroke-width="3" stroke-dasharray="14 8"/>')
html = f'''<!doctype html><meta charset="utf-8"><body style="margin:0;background:#fff;font-family:Inter,Arial,sans-serif">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 720" width="1200" height="720">
<rect width="1200" height="720" fill="#fff"/>
<text x="30" y="40" font-size="30" font-weight="700" fill="#111">1080p60 stream, CBR 6000 kbps: Mbps in each second</text>
<text x="30" y="82" font-size="28" fill="#c2570c">orange: above 7.0 Mbps</text>
<text x="560" y="82" font-size="28" fill="#222">average {avg:.2f}</text>
<text x="30" y="122" font-size="28" fill="#1b7f3b">green line: 10 Mbps upload x 0.7 = 7.0</text>
<text x="700" y="122" font-size="28" fill="#b3261e">red: 8 x 0.7 = 5.6</text>
{grid}{bars}{lines}
<text x="{X0}" y="640" font-size="28" fill="#333">second 1</text>
<text x="{X1}" y="640" font-size="28" text-anchor="end" fill="#333">second {n}</text>
<text x="30" y="690" font-size="28" fill="#333">Busiest second {mx:.1f} Mbps; Mbps on the vertical axis</text>
</svg></body>'''
open(out,'w').write(html)
print(f'seconds={n} avg={avg:.3f} max={mx:.3f} over7.0={sum(1 for m in v if m>7.0)} under5.6={sum(1 for m in v if m<5.6)}')
