forge
Explore
Log in

Don't you dare go Hollow

EC_AV1_TIMELINE -- per-frame decode timeline + critical-path report

Browse files at this commit

9cdd364d1cfb2bbc423b13ab1cb0bac21759717fAhmet Kaan GümüşParent: c604fcd
  • feat
    • EC_AV1_TIMELINE -- per-frame decode timeline + critical-path report
Show full message
feat(av1): EC_AV1_TIMELINE -- per-frame decode timeline + critical-path report

Two lanes pipelined the loop filters per superblock row and recovered 2.3%
wall although the filters were 19% of frame-thread time; nobody had measured
the actual critical path. `EC_AV1_TIMELINE=1` records ~10 timestamps per
coded frame on one monotonic clock -- submit, worker start, each reference
slot wait (with the producing frame, so the DAG has real edges), header
setup, tile parse, wavefront drain, filters, slot publish, grain, output --
plus every block of the dispatcher at the in-flight bound, and dumps them as
TSV at stream end. `scripts/av1-timeline-report.py` reports phase medians,
the reference waits, the work-weighted critical path through the DAG,
concurrency at 10 ms ticks (in-flight vs actually RUNNING) and the cap waits.

Measured at (16,4,2) on the 4K segment, 3 runs: wall 5.44 s, of which the
measured dependency chain is 4.96 s = 91%, and 90.8% of that chain is parse.
Only 2.9 frames are runnable at any instant while 18 are in flight, so the
dispatcher cap is never the bound (48 threads on the 1080p cut: 4.0 running,
no wall gain). The filters are 5.0% of the chain -- which is exactly the
2.3% the pipelining lanes could recover.

Off, this is one `LazyLock<bool>` load per event at frame granularity: eight
gate hashes byte-identical at 1 and 16 threads, instructions:u +0.056%
(gate 0.05%, wall -0.5%).
crates/ec-av1/src/decode.rsmodified+11 -0
@@ -22459,12 +22459,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2245922459 if waving {
2246022460 wave_submit(fctx, wave_job.0, wave_job.1);
2246122461 }
22462+ // lane-timeline: this tile's last symbol is read here; its wavefront
22463+ // workers are drained by `_wave`'s drop at the end of the iteration.
22464+ crate::timeline::tile_done();
2246222465 flush_recon(fctx, &mut y, &mut u, &mut v);
2246322466
2246422467 if tile_num == tile_info.context_update_tile_id {
2246522468 result_cdfs = cdfs;
2246622469 }
2246722470 }
22471+ crate::timeline::recon_done();
2246822472
2246922473 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
2247022474 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
@@ -22596,6 +22600,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2259622600 scratch_return(db_u.data.into_owned());
2259722601 scratch_return(db_y.data.into_owned());
2259822602 }
22603+ crate::timeline::filters_done();
2259922604
2260022605 let (fw, fh) = (lr_w, frame_height as usize);
2260122606 // An upscaled frame is already at its final size with no mi-aligned
@@ -34751,12 +34756,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3475134756 if waving {
3475234757 wave_submit(fctx, wave_job.0, wave_job.1);
3475334758 }
34759+ // lane-timeline: this tile's last symbol is read here; its wavefront
34760+ // workers are drained by `_wave`'s drop at the end of the iteration.
34761+ crate::timeline::tile_done();
3475434762 flush_recon(fctx, &mut y, &mut u, &mut v);
3475534763
3475634764 if tile_num == tile_info.context_update_tile_id {
3475734765 result_cdfs = cdfs;
3475834766 }
3475934767 }
34768+ crate::timeline::recon_done();
3476034769
3476134770 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
3476234771 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
@@ -34790,6 +34799,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3479034799 // out; from here the picture is deblocked and CDEF-filtered exactly as
3479134800 // the whole-frame path leaves it.
3479234801 let pipelined = pipe.is_some();
34802+ crate::timeline::note_pipe(pipelined);
3479334803 if let Some(p) = &mut pipe {
3479434804 p.finish();
3479534805 }
@@ -34901,6 +34911,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3490134911 scratch_return(db_y.data.into_owned());
3490234912 }
3490334913
34914+ crate::timeline::filters_done();
3490434915 let motion_field = build_motion_field(
3490534916 &grid,
3490634917 mi_cols as usize,
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -48,6 +48,7 @@ mod restoration;
4848 pub mod sequence;
4949 mod superres;
5050 pub mod stream;
51+mod timeline;
5152 pub mod tile;
5253 pub mod transform;
5354 mod warp;
crates/ec-av1/src/stream.rsmodified+44 -0
@@ -317,6 +317,7 @@ impl Reorder {
317317 while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) {
318318 self.next += 1;
319319 sink(&picture, decode_idx, shown)?;
320+ crate::timeline::output(decode_idx);
320321 }
321322 Ok(())
322323 }
@@ -552,6 +553,10 @@ pub fn decode_stream_with_threads(
552553 // keeps every counter-reading gate meaningful).
553554 let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
554555 std::array::from_fn(|_| None);
556+ // lane-timeline: which decoded frame installed each slot's promise, so
557+ // the timeline records a dependency EDGE (frame -> producing frame) and
558+ // not just a slot number. `usize::MAX` = nobody yet.
559+ let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];
555560
556561 let mut pos = 0usize;
557562 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
@@ -612,8 +617,11 @@ pub fn decode_stream_with_threads(
612617 for i in 0..NUM_REF_FRAMES {
613618 if header.refresh_frame_flags & (1 << i) != 0 {
614619 slot_promises[i] = Some(promise.clone());
620+ slot_owner[i] = slot_owner[slot];
615621 }
616622 }
623+ let cap_t0 = crate::timeline::now();
624+ let capped = in_flight_shows >= in_flight_cap;
617625 while in_flight_shows >= in_flight_cap {
618626 collect_one(
619627 &rx,
@@ -623,6 +631,9 @@ pub fn decode_stream_with_threads(
623631 &mut sink,
624632 )?;
625633 }
634+ if capped {
635+ crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
636+ }
626637 let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
627638 emit_seq += 1;
628639 pictures_shown += 1;
@@ -813,6 +824,8 @@ pub fn decode_stream_with_threads(
813824 // deadlock argument). A key frame stays inline: it resets the whole
814825 // bank and reads nothing, so there is nothing to gain.
815826 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
827+ let cap_t0 = crate::timeline::now();
828+ let capped = in_flight_decodes >= in_flight_cap;
816829 while in_flight_decodes >= in_flight_cap {
817830 collect_one(
818831 &rx,
@@ -822,6 +835,9 @@ pub fn decode_stream_with_threads(
822835 &mut sink,
823836 )?;
824837 }
838+ if capped {
839+ crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
840+ }
825841 // Exactly the slots this frame reads: `ref_frame_idx` names its
826842 // references, and its `primary_ref_frame` CDFs/segment map, its
827843 // reference order hints and every field `setup_motion_field`
@@ -833,11 +849,13 @@ pub fn decode_stream_with_threads(
833849 let slot = header.ref_frame_idx[i] as usize;
834850 deps[slot] = slot_promises[slot].clone();
835851 }
852+ let dep_owner = slot_owner;
836853 let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
837854 if let Some(promise) = &produces {
838855 for i in 0..NUM_REF_FRAMES {
839856 if header.refresh_frame_flags & (1 << i) != 0 {
840857 slot_promises[i] = Some(promise.clone());
858+ slot_owner[i] = pictures_decoded;
841859 }
842860 }
843861 }
@@ -850,18 +868,28 @@ pub fn decode_stream_with_threads(
850868 }
851869 let tx = tx.clone();
852870 let dump = final_dump.clone();
871+ crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
853872 jobs.submit(move || {
854873 let promise = produces;
855874 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
875+ crate::timeline::start(decode_idx);
856876 // The wait happens HERE, off the parsing thread, and only
857877 // for this frame's own references.
858878 let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
859879 std::array::from_fn(|_| None);
860880 for (slot, dep) in deps.iter().enumerate() {
861881 if let Some(dep) = dep {
882+ let t0 = crate::timeline::now();
862883 resolved[slot] = Some(dep.wait()?);
884+ crate::timeline::ref_wait(
885+ decode_idx,
886+ slot,
887+ dep_owner[slot],
888+ crate::timeline::now().saturating_sub(t0),
889+ );
863890 }
864891 }
892+ crate::timeline::refs_ready();
865893 // Fresh per-thread state: every field this path reads is
866894 // written from this frame's own header before it is read.
867895 let fctx = crate::decode::FrameCtx::new();
@@ -903,6 +931,7 @@ pub fn decode_stream_with_threads(
903931 seg_map: out.seg_map,
904932 order_hint: header.order_hint,
905933 }));
934+ crate::timeline::slot_fulfil();
906935 }
907936 // Grain is synthesised for OUTPUT only: a hidden frame is
908937 // reported to the sink clean, exactly as the inline path
@@ -918,6 +947,7 @@ pub fn decode_stream_with_threads(
918947 } else {
919948 picture
920949 };
950+ crate::timeline::grain_done();
921951 Ok((output, decode_idx, shown))
922952 }))
923953 .unwrap_or_else(|_| {
@@ -993,6 +1023,7 @@ pub fn decode_stream_with_threads(
9931023 for i in 0..NUM_REF_FRAMES {
9941024 if header.refresh_frame_flags & (1 << i) != 0 {
9951025 slot_promises[i] = Some(promise.clone());
1026+ slot_owner[i] = pictures_decoded - 1;
9961027 }
9971028 }
9981029 }
@@ -1055,6 +1086,7 @@ pub fn decode_stream_with_threads(
10551086 )?;
10561087 }
10571088 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
1089+ crate::timeline::dump();
10581090 Ok(())
10591091 }
10601092
@@ -1482,6 +1514,18 @@ fn decode_frame(
14821514 // reads temporal candidates.
14831515 let ref_order_hints = snap.ref_order_hints;
14841516
1517+ crate::timeline::bind(
1518+ decode_idx,
1519+ if header.frame_type == FrameType::Key {
1520+ 'K'
1521+ } else if header.show_frame {
1522+ 'P'
1523+ } else {
1524+ 'A'
1525+ },
1526+ header.show_frame,
1527+ );
1528+ crate::timeline::hdr_done();
14851529 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
14861530 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
14871531 &tile_bufs,
crates/ec-av1/src/timeline.rsadded+262 -0
@@ -0,0 +1,262 @@
1+//! lane-timeline: `EC_AV1_TIMELINE=1` frame-granularity decode timeline.
2+//!
3+//! The threaded decoder (`stream.rs`) is bounded by *something* -- reference
4+//! latency, the dispatcher's in-flight cap, the filter tail or the output
5+//! path -- and no instrument could tell which: `EC_AV1_WAVE_STATS` counts
6+//! superblocks, `perf` counts instructions, neither sees the dependency
7+//! graph. This records ~10 timestamps per coded frame (submit, worker start,
8+//! reference waits, parse, recon, filters, slot publish, grain, output) on
9+//! one monotonic clock and dumps them as TSV at stream end;
10+//! `scripts/av1-timeline-report.py` reads that and walks the critical path.
11+//!
12+//! Cost when off: one relaxed atomic load ([`env_flag!`]'s `LazyLock<bool>`)
13+//! per event, at frame granularity -- ~10 loads per frame, nothing per block.
14+
15+use std::sync::Mutex;
16+use std::time::Instant;
17+
18+/// Process start, the zero of every timestamp below.
19+static START: std::sync::LazyLock<Instant> = std::sync::LazyLock::new(Instant::now);
20+
21+/// `EC_AV1_TIMELINE` -- one atomic load per call site after the first.
22+pub(crate) fn on() -> bool {
23+ crate::envflags::env_flag!("EC_AV1_TIMELINE")
24+}
25+
26+fn now_us() -> u64 {
27+ START.elapsed().as_micros() as u64
28+}
29+
30+/// One coded frame's timestamps, in microseconds since [`START`]; 0 = never
31+/// reached (a key frame decodes inline, so it has no submit/start/publish).
32+#[derive(Clone, Default)]
33+struct Rec {
34+ used: bool,
35+ ftype: char,
36+ show: bool,
37+ submit: u64,
38+ start: u64,
39+ refs_ready: u64,
40+ hdr_done: u64,
41+ tile_done: u64,
42+ recon_done: u64,
43+ filters_done: u64,
44+ slot_fulfil: u64,
45+ grain_done: u64,
46+ output: u64,
47+ /// Slot this frame blocked on longest, which frame produced it, and
48+ /// for how long.
49+ wait_slot: i32,
50+ wait_owner: i64,
51+ wait_us: u64,
52+ /// The producing frame of every slot it waited on, for the DAG.
53+ deps: Vec<usize>,
54+ pipe: bool,
55+}
56+
57+#[derive(Default)]
58+struct Log {
59+ frames: Vec<Rec>,
60+ /// Dispatcher blocks at the in-flight bound: (kind, begin, end).
61+ caps: Vec<(&'static str, u64, u64)>,
62+}
63+
64+static LOG: Mutex<Option<Log>> = Mutex::new(None);
65+
66+fn with<F: FnOnce(&mut Log)>(f: F) {
67+ let mut g = LOG.lock().expect("timeline");
68+ f(g.get_or_insert_with(Log::default));
69+}
70+
71+fn rec<F: FnOnce(&mut Rec)>(idx: usize, f: F) {
72+ with(|log| {
73+ if log.frames.len() <= idx {
74+ log.frames.resize(idx + 1, Rec { wait_slot: -1, wait_owner: -1, ..Rec::default() });
75+ }
76+ let r = &mut log.frames[idx];
77+ r.used = true;
78+ f(r);
79+ });
80+}
81+
82+// The frame this thread is decoding, so `decode.rs`'s phase marks need no
83+// new parameter threaded through the tile decoders.
84+thread_local! {
85+ static CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
86+}
87+
88+/// Dispatch (parsing thread), before the job is queued.
89+#[cold]
90+pub(crate) fn submit(idx: usize, ftype: char, show: bool) {
91+ if !on() {
92+ return;
93+ }
94+ let t = now_us();
95+ rec(idx, |r| {
96+ r.ftype = ftype;
97+ r.show = show;
98+ r.submit = t;
99+ });
100+}
101+
102+/// A worker picked the job up. Also binds this thread to `idx`.
103+#[cold]
104+pub(crate) fn start(idx: usize) {
105+ if !on() {
106+ return;
107+ }
108+ CUR.with(|c| c.set(idx));
109+ let t = now_us();
110+ rec(idx, |r| r.start = t);
111+}
112+
113+/// Binds a thread to `idx` without a start timestamp (the inline key-frame
114+/// path, which is dispatched by nobody).
115+#[cold]
116+pub(crate) fn bind(idx: usize, ftype: char, show: bool) {
117+ if !on() {
118+ return;
119+ }
120+ CUR.with(|c| c.set(idx));
121+ rec(idx, |r| {
122+ r.ftype = ftype;
123+ r.show = show;
124+ });
125+}
126+
127+/// One resolved `SlotPromise::wait`, with the slot and how long it blocked.
128+#[cold]
129+pub(crate) fn ref_wait(idx: usize, slot: usize, owner: usize, waited_us: u64) {
130+ if !on() {
131+ return;
132+ }
133+ rec(idx, |r| {
134+ if owner != usize::MAX && !r.deps.contains(&owner) {
135+ r.deps.push(owner);
136+ }
137+ if waited_us > r.wait_us {
138+ r.wait_us = waited_us;
139+ r.wait_slot = slot as i32;
140+ r.wait_owner = if owner == usize::MAX { -1 } else { owner as i64 };
141+ }
142+ });
143+}
144+
145+macro_rules! stamp {
146+ ($name:ident, $field:ident) => {
147+ #[doc = concat!("Marks `", stringify!($field), "` for the frame this thread is decoding.")]
148+ #[cold]
149+ pub(crate) fn $name() {
150+ if !on() {
151+ return;
152+ }
153+ let (idx, t) = (CUR.with(std::cell::Cell::get), now_us());
154+ if idx != usize::MAX {
155+ rec(idx, |r| r.$field = t);
156+ }
157+ }
158+ };
159+}
160+stamp!(refs_ready, refs_ready);
161+stamp!(hdr_done, hdr_done);
162+stamp!(tile_done, tile_done);
163+stamp!(recon_done, recon_done);
164+stamp!(filters_done, filters_done);
165+stamp!(slot_fulfil, slot_fulfil);
166+stamp!(grain_done, grain_done);
167+
168+/// Whether this frame's filters ran pipelined per superblock row.
169+#[cold]
170+pub(crate) fn note_pipe(pipe: bool) {
171+ if !on() {
172+ return;
173+ }
174+ let idx = CUR.with(std::cell::Cell::get);
175+ if idx != usize::MAX {
176+ rec(idx, |r| r.pipe = pipe);
177+ }
178+}
179+
180+/// The picture reached the sink. Only a frame that finished on a worker
181+/// (`grain_done`) and has not been emitted yet takes the stamp -- a
182+/// `show_existing_frame` re-output reports a decode index that is not its
183+/// own, and must not overwrite another frame's row.
184+#[cold]
185+pub(crate) fn output(idx: usize) {
186+ if !on() {
187+ return;
188+ }
189+ let t = now_us();
190+ with(|log| {
191+ if let Some(r) = log.frames.get_mut(idx)
192+ && r.output == 0
193+ // A frame that finished on a worker, or the inline key frame
194+ // (never submitted) that has passed its filters.
195+ && (r.grain_done != 0 || (r.submit == 0 && r.filters_done != 0))
196+ {
197+ r.output = t;
198+ }
199+ });
200+}
201+
202+/// The parsing thread blocked at the in-flight bound.
203+#[cold]
204+pub(crate) fn cap_wait(kind: &'static str, begin: u64, end: u64) {
205+ if !on() {
206+ return;
207+ }
208+ with(|log| log.caps.push((kind, begin, end)));
209+}
210+
211+/// `now_us` for the two call sites that need a begin timestamp of their own.
212+pub(crate) fn now() -> u64 {
213+ if !on() {
214+ return 0;
215+ }
216+ now_us()
217+}
218+
219+/// Writes every row to stderr as TSV and clears the log.
220+#[cold]
221+pub(crate) fn dump() {
222+ if !on() {
223+ return;
224+ }
225+ let taken = LOG.lock().expect("timeline").take();
226+ let Some(log) = taken else { return };
227+ let mut out = String::new();
228+ out.push_str(
229+ "TL_HDR\tidx\ttype\tshow\tsubmit\tstart\trefs_ready\thdr_done\ttile_done\trecon_done\tfilters_done\tslot_fulfil\tgrain_done\toutput\twait_slot\twait_owner\twait_us\tpipe\tdeps\n",
230+ );
231+ for (idx, r) in log.frames.iter().enumerate() {
232+ if !r.used {
233+ continue;
234+ }
235+ let deps: Vec<String> = r.deps.iter().map(std::string::ToString::to_string).collect();
236+ out.push_str(&format!(
237+ "TL\t{idx}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
238+ r.ftype,
239+ u8::from(r.show),
240+ r.submit,
241+ r.start,
242+ r.refs_ready,
243+ r.hdr_done,
244+ r.tile_done,
245+ r.recon_done,
246+ r.filters_done,
247+ r.slot_fulfil,
248+ r.grain_done,
249+ r.output,
250+ r.wait_slot,
251+ r.wait_owner,
252+ r.wait_us,
253+ u8::from(r.pipe),
254+ if deps.is_empty() { "-".to_string() } else { deps.join(",") },
255+ ));
256+ }
257+ for (kind, b, e) in &log.caps {
258+ out.push_str(&format!("TL_CAP\t{kind}\t{b}\t{e}\n"));
259+ }
260+ out.push_str(&format!("TL_END\t{}\n", now_us()));
261+ eprint!("{out}");
262+}
scripts/av1-timeline-report.pyadded+225 -0
@@ -0,0 +1,225 @@
1+#!/usr/bin/env python3
2+"""Reads `EC_AV1_TIMELINE=1` TSV (stderr of decode_probe) and reports what
3+bounds the wall: per-phase durations, reference waits, the critical path
4+through the reference DAG, concurrency over time, and dispatcher cap waits.
5+
6+Usage: EC_AV1_TIMELINE=1 decode_probe f.obu 2>tl.tsv; av1-timeline-report.py tl.tsv
7+"""
8+import sys
9+from statistics import median
10+
11+COLS = ("idx type show submit start refs_ready hdr_done tile_done recon_done "
12+ "filters_done slot_fulfil grain_done output wait_slot wait_owner wait_us "
13+ "pipe deps").split()
14+INT = set(COLS) - {"type", "deps"}
15+
16+# (label, from, to) -- the phases of one frame, in order.
17+PHASES = [
18+ ("queue submit->start", "submit", "start"),
19+ ("refwait start->refs", "start", "refs_ready"),
20+ ("setup refs->hdr", "refs_ready", "hdr_done"),
21+ ("parse hdr->tile", "hdr_done", "tile_done"),
22+ ("recontail tile->recon", "tile_done", "recon_done"),
23+ ("filters recon->filt", "recon_done", "filters_done"),
24+ ("publish filt->fulfil", "filters_done", "slot_fulfil"),
25+ ("grain fulfil->grain", "slot_fulfil", "grain_done"),
26+ ("outwait grain->output", "grain_done", "output"),
27+]
28+# Which phase a chain segment's time is charged to (same order).
29+CHAIN_KEYS = [p[0].split()[0] for p in PHASES]
30+
31+
32+def load(path):
33+ frames, caps, end = [], [], 0
34+ with (open(path) if path != "-" else sys.stdin) as fh:
35+ for line in fh:
36+ f = line.rstrip("\n").split("\t")
37+ if f[0] == "TL":
38+ r = dict(zip(COLS, f[1:]))
39+ for k in INT:
40+ r[k] = int(r[k])
41+ r["deps"] = [] if r["deps"] == "-" else [int(x) for x in r["deps"].split(",")]
42+ frames.append(r)
43+ elif f[0] == "TL_CAP":
44+ caps.append((f[1], int(f[2]), int(f[3])))
45+ elif f[0] == "TL_END":
46+ end = int(f[1])
47+ return {f["idx"]: f for f in frames}, caps, end
48+
49+
50+def ms(us):
51+ return us / 1000.0
52+
53+
54+def stats(vals):
55+ vals = sorted(v for v in vals if v is not None)
56+ if not vals:
57+ return None
58+ p90 = vals[min(len(vals) - 1, int(round(0.9 * (len(vals) - 1))))]
59+ return median(vals), p90, vals[-1], sum(vals), len(vals)
60+
61+
62+def dur(r, a, b):
63+ """Duration of one phase, or None when either end was never reached."""
64+ if r[a] == 0 or r[b] == 0 or r[b] < r[a]:
65+ return None
66+ return r[b] - r[a]
67+
68+
69+def main():
70+ path = sys.argv[1] if len(sys.argv) > 1 else "-"
71+ fr, caps, end = load(path)
72+ if not fr:
73+ sys.exit("no TL rows")
74+ t0 = min(min(v for k, v in r.items() if k in INT and k not in
75+ ("idx", "show", "wait_slot", "wait_owner", "wait_us", "pipe") and v > 0)
76+ for r in fr.values())
77+ wall = end - t0
78+ n = len(fr)
79+ npipe = sum(r["pipe"] for r in fr.values())
80+ print(f"frames={n} (key={sum(1 for r in fr.values() if r['type']=='K')} "
81+ f"shown={sum(r['show'] for r in fr.values())} pipelined_filters={npipe}/{n}) "
82+ f"wall={ms(wall):.1f} ms (first event {ms(t0):.1f} ms, end {ms(end):.1f} ms)")
83+
84+ print("\n(a) per-frame phase durations, ms")
85+ print(f"{'phase':24} {'n':>4} {'median':>8} {'p90':>8} {'max':>8} {'sum':>9} {'sum/wall':>8}")
86+ for label, a, b in PHASES:
87+ s = stats([dur(r, a, b) for r in fr.values()])
88+ if not s:
89+ print(f"{label:24} -")
90+ continue
91+ med, p90, mx, tot, cnt = s
92+ print(f"{label:24} {cnt:>4} {ms(med):>8.2f} {ms(p90):>8.2f} {ms(mx):>8.2f} "
93+ f"{ms(tot):>9.1f} {tot/wall:>8.2f}")
94+ s = stats([dur(r, "start", "grain_done") for r in fr.values()])
95+ if s:
96+ print(f"{'TOTAL start->grain':24} {s[4]:>4} {ms(s[0]):>8.2f} {ms(s[1]):>8.2f} "
97+ f"{ms(s[2]):>8.2f} {ms(s[3]):>9.1f} {s[3]/wall:>8.2f}")
98+
99+ print("\n(b) reference wait (start -> refs_ready), ms")
100+ waits = [(dur(r, "start", "refs_ready") or 0, r) for r in fr.values() if r["start"]]
101+ s = stats([w for w, _ in waits])
102+ print(f" n={s[4]} median={ms(s[0]):.2f} p90={ms(s[1]):.2f} max={ms(s[2]):.2f} "
103+ f"sum={ms(s[3]):.1f} ({s[3]/wall:.2f}x wall)")
104+ zero = sum(1 for w, _ in waits if w < 1000)
105+ print(f" frames waiting <1 ms: {zero}/{len(waits)}")
106+ print(" top waiters (frame -> longest-blocking producer):")
107+ for w, r in sorted(waits, key=lambda x: -x[0])[:10]:
108+ print(f" f{r['idx']:<4}{r['type']} waited {ms(w):8.2f} on slot {r['wait_slot']} "
109+ f"produced by f{r['wait_owner']} (deps {r['deps']})")
110+
111+ # (c) critical path. A frame's critical predecessor is the dependency
112+ # whose slot publish is the LAST one -- the edge that actually released
113+ # this frame's refs_ready.
114+ def pred(r):
115+ best, bt = None, -1
116+ for d in r["deps"]:
117+ p = fr.get(d)
118+ if p is None:
119+ continue
120+ t = own_w[d]
121+ if t > bt:
122+ best, bt = p, t
123+ return best
124+
125+ # Walk back from the frame on the longest WORK-WEIGHTED chain (the frame
126+ # that finishes last is often in a short last-GOP chain: a key frame
127+ # resets the DAG, so wall-clock-last is not dependency-deepest).
128+ own_w = {}
129+ for i in sorted(fr):
130+ r = fr[i]
131+ own_w[i] = max([own_w.get(d, 0) for d in r["deps"]] + [0]) + sum(
132+ dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7])
133+ tail = fr[max(own_w, key=lambda k: own_w[k])]
134+ chain, cur = [], tail
135+ while cur is not None:
136+ chain.append(cur)
137+ cur = pred(cur)
138+ chain.reverse()
139+ head = chain[0]
140+ span_a = head["hdr_done"] or head["start"] or t0
141+ span_b = max(tail["output"], tail["grain_done"])
142+ print(f"\n(c) critical path: {len(chain)} frames "
143+ f"({chain[0]['idx']} -> {chain[-1]['idx']}), "
144+ f"{ms(span_b - span_a):.1f} ms = {(span_b-span_a)/wall*100:.1f}% of wall")
145+ charge = dict.fromkeys(CHAIN_KEYS, 0)
146+ slack = 0
147+ for i, r in enumerate(chain):
148+ for (label, a, b) in PHASES:
149+ d = dur(r, a, b)
150+ if d is None:
151+ continue
152+ k = label.split()[0]
153+ if i == 0 and k in ("queue", "refwait"):
154+ continue
155+ # A frame's own wait is charged only for the part after its
156+ # predecessor published -- before that the predecessor's own
157+ # phases already account for the time.
158+ if k == "refwait":
159+ p = chain[i - 1]
160+ d = max(0, r["refs_ready"] - max(r["start"], p["slot_fulfil"] or p["filters_done"]))
161+ if k == "outwait" and r is not tail:
162+ continue
163+ charge[k] += d
164+ if i:
165+ p = chain[i - 1]
166+ pt = p["slot_fulfil"] or p["filters_done"]
167+ if r["start"] and r["start"] > pt:
168+ slack += r["start"] - pt
169+ print(f" {'segment':12} {'ms':>9} {'% of chain':>11}")
170+ tot = span_b - span_a
171+ for k in CHAIN_KEYS:
172+ if charge[k]:
173+ print(f" {k:12} {ms(charge[k]):>9.1f} {charge[k]/tot*100:>10.1f}%")
174+ print(f" {'(late start)':12} {ms(slack):>9.1f} {slack/tot*100:>10.1f}% "
175+ "producer published before the consumer's worker even started")
176+ print(f" chain frames: {[r['idx'] for r in chain][:40]}"
177+ f"{' ...' if len(chain) > 40 else ''}")
178+
179+ # Infinite-core lower bound: earliest finish of every frame if a core
180+ # were always free -- own work only, no queueing.
181+ own = {}
182+ for i in sorted(fr):
183+ r = fr[i]
184+ w = sum(dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7])
185+ own[i] = max([own.get(d, 0) for d in r["deps"]] + [0]) + w
186+ crit = max(own, key=lambda k: own[k])
187+ print(f" infinite-core bound (longest work-weighted chain, ends at f{crit}): "
188+ f"{ms(own[crit]):.1f} ms = {own[crit]/wall*100:.1f}% of wall")
189+ work = sum(sum(dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7]) for r in fr.values())
190+ print(f" frame-thread work total {ms(work):.1f} ms = {work/wall:.2f} cores' worth; "
191+ f"work/bound = {work/own[crit]:.2f} (the parallelism the DAG would need)")
192+
193+ print("\n(d) concurrency (frames between start and slot publish), 10 ms ticks")
194+ def tick(live, label):
195+ counts = []
196+ t = t0
197+ while t < end:
198+ counts.append(sum(1 for a, b in live if a <= t < b))
199+ t += 10000
200+ counts.sort()
201+ lt2 = sum(1 for c in counts if c < 2)
202+ print(f" {label:9} median={counts[len(counts)//2]:3} "
203+ f"p90={counts[int(0.9*(len(counts)-1))]:3} max={counts[-1]:3} "
204+ f"mean={sum(counts)/len(counts):5.2f} <2 for {lt2/len(counts)*100:5.1f}% of wall"
205+ f" (<1: {sum(1 for c in counts if c<1)/len(counts)*100:.1f}%)")
206+
207+ end_of = lambda r: r["slot_fulfil"] or r["grain_done"] or r["filters_done"]
208+ # in flight = dispatched and not yet published (includes frames blocked on
209+ # a reference); running = past its reference waits, i.e. actually runnable.
210+ tick([(r["start"], end_of(r)) for r in fr.values() if r["start"]], "in-flight")
211+ tick([(r["refs_ready"], end_of(r)) for r in fr.values() if r["refs_ready"]], "running")
212+ tick([(r["hdr_done"], r["tile_done"]) for r in fr.values() if r["hdr_done"] and r["tile_done"]],
213+ "parsing")
214+
215+ print("\n(e) dispatcher in-flight cap waits")
216+ for kind in ("decode", "show"):
217+ k = [(b, e) for t_, b, e in caps if t_ == kind]
218+ tot = sum(e - b for b, e in k)
219+ mx = max((e - b for b, e in k), default=0)
220+ print(f" {kind:7} blocks={len(k):5} total={ms(tot):9.1f} ms "
221+ f"({tot/wall*100:5.1f}% of wall) max={ms(mx):.2f} ms")
222+
223+
224+if __name__ == "__main__":
225+ main()