#!/usr/bin/env python3
"""measure.py <file> : per-second payload bitrate of a muxed stream file, from ffprobe packet sizes.
Seconds are bucketed by dts (send order). Prints one line: name avg_video_mbps avg_audio_mbps payload_avg_mbps peak1s_mbps peak_over_avg file_mbps overhead_pct
Mbps = megabits per second, 1 Mbps = 1,000,000 bits/s (decimal, as in encoder settings)."""
import subprocess, sys, os, collections
def mbps(nbytes, secs): return nbytes * 8 / secs / 1e6
f = sys.argv[1]
out = subprocess.run(['ffprobe','-v','error','-show_entries','packet=stream_index,pts_time,size,dts_time','-of','csv=p=0',f],
                     capture_output=True, text=True, check=True).stdout.split('\n')
kinds = subprocess.run(['ffprobe','-v','error','-show_entries','stream=index,codec_type','-of','csv=p=0',f],
                     capture_output=True, text=True, check=True).stdout.split()
kind = {}
for k in kinds:
    i, t = k.split(','); kind[i] = t
sec = collections.defaultdict(int); tot = {'video':0,'audio':0}; t0 = None; t1 = 0
for line in out:
    if not line.strip(): continue
    idx, pts, dts, size = line.split(',')
    t = float(dts if dts not in ('N/A','') else pts)   # dts = the order packets are sent
    size = int(size)
    sec[int(t)] += size; tot[kind[idx]] += size
    t0 = t if t0 is None else min(t0, t); t1 = max(t1, t)
dur = float(subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',f],capture_output=True,text=True).stdout)
n = len(sec)
full = [s for s in sorted(sec) if s < int(dur)]          # whole seconds only (drop the partial last one)
peak = max(sec[s] for s in full) * 8 / 1e6
def window(w):  # busiest run of w whole seconds, sliding by 1 s, as Mbps
    return max(sum(sec[s+k] for k in range(w)) for s in full if s + w - 1 in full) * 8 / w / 1e6
peak2, peak10 = window(2), window(10)
payload = tot['video'] + tot['audio']
fsize = os.path.getsize(f)
print(f"{os.path.basename(f)} dur={dur:.3f}s video={mbps(tot['video'],dur):.3f} audio={mbps(tot['audio'],dur):.3f} payload={mbps(payload,dur):.3f} peak1s={peak:.3f} peak2s={peak2:.3f} peak10s={peak10:.3f} peak/avg={peak/mbps(payload,dur):.3f} file={mbps(fsize,dur):.3f} overhead%={(fsize-payload)/fsize*100:.2f} bytes={fsize}")
