"""Summarize one local frame-interval stream using frametime-v1.""" import argparse import json import math import os from pathlib import Path import stat import sys MAX_BYTES = 2 * 1024 * 1024 MAX_ROWS = 60_000 FRAME_KINDS = {"application", "generated", "unknown"} INTERVAL_KINDS = {"cpu-start", "present", "displayed"} def reciprocal(value): if value > 0: rate = 1000 / value if math.isfinite(rate) and rate > 0: return rate return None def summarize(samples, target): ordered = sorted(value for value in samples if reciprocal(value) is not None) count = len(ordered) budget = reciprocal(target) result = {"invalid": len(samples) - count, "budget": budget, "summary": None} total = ordinary_sum(ordered) average = reciprocal(total / count) if count else None if average is None: return result tail_count = (count + 99) // 100 over = [value for value in ordered if value > budget] if budget is not None else None result["summary"] = { "count": count, "total": total, "average": average, **{f"p{p}": ordered[(p * count + 99) // 100 - 1] for p in (50, 95, 99)}, "max": ordered[-1], "tailCount": tail_count, "low": reciprocal(ordinary_sum(value / tail_count for value in ordered[-tail_count:])), "overCount": len(over) if over is not None else None, "overTimeShare": ordinary_sum(over) / total if over is not None else None, } return result def ordinary_sum(values): # Match the website's left-to-right binary64 addition, including on Python 3.12+. total = 0.0 for value in values: total += value return total def unique_fields(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("Duplicate JSON field.") result[key] = value return result def reject_constant(_): raise ValueError("Use null for missing or nonfinite intervals.") def read_intervals(path): if not stat.S_ISREG(path.stat().st_mode): raise ValueError("Choose a readable regular file.") fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)) with os.fdopen(fd, "rb") as stream: if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): raise ValueError("Choose a readable regular file.") data = stream.read(MAX_BYTES + 1) if len(data) > MAX_BYTES: raise ValueError("Input exceeds 2 MiB.") capture = json.loads(data.decode("utf-8-sig"), parse_int=float, parse_constant=reject_constant, object_pairs_hook=unique_fields) if type(capture) is not dict or set(capture) != { "format", "unit", "intervalKind", "frameKind", "evidence", "intervals", }: raise ValueError("Expected a frame-intervals-v1 object with documented fields.") kind, frame, evidence = capture["intervalKind"], capture["frameKind"], capture["evidence"] if (capture["format"] != "frame-intervals-v1" or capture["unit"] != "ms" or type(kind) is not str or kind not in INTERVAL_KINDS or type(frame) is not str or frame not in FRAME_KINDS or evidence not in ("synthetic", "provided")): raise ValueError("Unsupported format, unit or stream semantics.") samples = capture["intervals"] if type(samples) is not list or len(samples) > MAX_ROWS: raise ValueError("Expected at most 60,000 ordered intervals.") if any(value is not None and type(value) is not float for value in samples): raise ValueError("Intervals must be numbers or null.") return kind, frame, evidence, [float("nan") if value is None else value for value in samples] def human(report): lines = [ f'Evidence: {report["evidence"]}', f'{report["method"]} | {report["intervalKind"]} intervals (ms) | {report["frameKind"]} frames', f'Valid intervals: {report["valid"]} | Invalid intervals: {report["invalid"]}', ] metrics = report["summary"] if metrics is None: return "\n".join([*lines, "Frame metrics unavailable."]) lines.extend([ f'Valid interval sum: {metrics["total"]:.3f} ms | Average: {metrics["average"]:.3f} FPS', f'p50 / p95 / p99 / max: {metrics["p50"]:.3f} / {metrics["p95"]:.3f} / ' f'{metrics["p99"]:.3f} / {metrics["max"]:.3f} ms', f'Exact-count 1% low: {metrics["low"]:.3f} FPS ({metrics["tailCount"]} intervals)', ]) if metrics["tailCount"] < 10: lines.append("Few intervals contribute to this 1% low.") if report["budget"] is not None: lines.append(f'{metrics["overCount"]} of {metrics["count"]} intervals above ' f'{report["budget"]:.3f} ms ({metrics["overTimeShare"]:.2%} of valid interval time)') return "\n".join(lines) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("inspect", "summarize")) parser.add_argument("file", type=Path) parser.add_argument("--target-fps", type=float) parser.add_argument("--json", action="store_true", help="Write structured output to stdout.") args = parser.parse_args(argv) if args.target_fps is not None and reciprocal(args.target_fps) is None: parser.error("target FPS must have a positive finite budget") try: kind, frame, evidence, samples = read_intervals(args.file) except (OSError, UnicodeError, ValueError, RecursionError) as exc: reason = str(exc) if type(exc) is ValueError else "Unreadable file or malformed UTF-8 JSON." print(f"Frame analysis: {reason}", file=sys.stderr) return 2 report = { "method": "frametime-v1", "format": "frame-intervals-v1", "unit": "ms", "intervalKind": kind, "frameKind": frame, "evidence": evidence, "rows": len(samples), } if args.action == "inspect": invalid = sum(reciprocal(value) is None for value in samples) report.update(invalid=invalid, valid=len(samples) - invalid) print(json.dumps(report, allow_nan=False) if args.json else f'{evidence}: {kind} intervals (ms), {frame} frames. {report["valid"]} valid, {invalid} invalid.') else: report.update(summarize(samples, args.target_fps if args.target_fps is not None else math.nan)) report["valid"] = len(samples) - report["invalid"] print(json.dumps(report, allow_nan=False) if args.json else human(report)) return 0 if __name__ == "__main__": raise SystemExit(main())