1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! `ServedEgress`, `PushEgress`, `SegmentEgress` — the three egress shapes
//! that read from a [`crate::Trunk`] (plan step 3d;
//! `docs/superpowers/specs/2026-07-26-media-plane-architecture.md` §1/§3).
//!
//! `#[cfg(feature = "std")]`: like [`crate::trunk`]/[`crate::ingress`], this
//! module's types are handed [`transmux::TrackSpec`]s and
//! [`crate::trunk::SampleCursorItem`]/[`crate::trunk::SegmentCursorItem`]
//! values, and every real consumer is `std`+`tokio` per the architecture.
//!
//! # Why three shapes, not one
//!
//! Rev 1 of the architecture treated egress as a single reader class; the
//! architecture-audit finding that corrected it (G6, spec §3) is that the
//! three egress consumers this workspace actually has are structurally
//! different operations, not three configurations of the same one:
//!
//! - [`ServedEgress`] **resolves a request**: given "does part 3.2 of segment
//! 9 exist" (LL-HLS), "here is the current MPD" (DASH), or "give me segment
//! N from an hour ago" (catch-up), it answers *now*, from whatever window
//! state it already holds. It never initiates I/O and it never iterates a
//! stream — a request comes in, an answer goes out (or, for the one
//! protocol that legitimately blocks on a not-yet-existing byte range,
//! [`EgressResponse::Await`] goes out — see below).
//! - [`PushEgress`] **streams samples that already exist** at whoever is
//! listening (WHEP, RTMP-out, SRT-out, a loudness tap): there is no
//! "request" — it drains one [`crate::trunk::SampleCursor`] forever, in
//! publish order, until the stream ends.
//! - [`SegmentEgress`] **consumes finished segments** (DVR, MABR, ATSC ROUTE,
//! Smooth-push): the unit of work is not a sample, and answering "have you
//! seen segment N" is not the shape of the operation — draining one
//! [`crate::trunk::SegmentCursor`] to completion, and reacting correctly to
//! [`crate::trunk::ArchiveOverrun`]'s three-way loss/stall/drop trade, is.
//!
//! Collapsing these into one trait (a single `fn feed(&mut self, item)` that
//! every one of the nine-plus real outputs implements) was tried in spec rev
//! 1 and rejected: a request/response protocol has no "next item" to feed —
//! it has to be able to say "not yet, ask again", which a push/consume
//! interface has no way to express (there is no caller waiting for a
//! return value); conversely a request-answering interface has no method a
//! streaming push side could call once, unprompted, to hand over a sample. A
//! trait that tried to serve both would need every implementor to leave half
//! the interface an unreachable `unimplemented!()`, which is exactly the
//! "no variant you cannot correctly produce" violation this crate's
//! [`crate::byte_merge`] module already rejected once (`Hitless2022_7`).
//! **If a future refactor is tempted to merge these three back into one
//! trait, re-read this section first** — the three shapes above are not an
//! accident of the current call sites, they are the actual difference
//! between resolve/stream/consume, and merging them just moves the
//! unreachable-branch problem into whichever one trait was chosen as the
//! "real" shape.
//!
//! # `ServedEgress::resolve` does not take `&Trunk` — a correction found
//! before Step 4, the same way ingress's `dial()` was
//!
//! The architecture spec's own pseudocode (§3) sketches
//! `fn resolve(req, &Trunk) -> EgressResponse`. Reading
//! `hls-runtime/src/server/` (the engine this trait exists to receive,
//! per the implementation plan's Step 4) before writing this trait surfaced
//! the same class of problem that reading `rtsp-runtime` before writing
//! [`crate::ingress::Dialer::dial`] surfaced: the pseudocode names a
//! parameter that the actual data structure cannot make good on.
//!
//! **What `&Trunk` can answer today, `&self`-shaped, no cursor required:**
//! [`crate::Trunk::events_between`]/[`crate::Trunk::events_in_segment`] (the
//! event log's snapshot queries) and the four `*_len()` diagnostics. That is
//! genuinely a "resolve a request against shared state" shape, and a
//! `ServedEgress` implementation is free to call them.
//!
//! **What it cannot answer:** "does segment 9 exist", "what bytes are
//! part 3.2", or anything else a `ServedEgress` implementing LL-HLS/DASH/
//! catch-up actually needs to resolve most requests. The segment log has
//! exactly one reader shape — [`crate::trunk::SegmentCursor`], a **moving**,
//! **stateful**, single-consumer position — with no companion snapshot query
//! the way the event log has `events_between`. So a `resolve()` that took
//! `&Trunk` would, for every real implementation, immediately have to ignore
//! it and consult a second, self-maintained cache instead — which is exactly
//! what `hls_runtime::server::MediaStore` already does in production: it
//! is fed by `add_segment`/`add_part`/`set_init` (called by whatever drains
//! the segmenter) and *separately* answers `resolve_playlist`/
//! `resolve_resource` from that already-synced state. `MediaStore` is
//! two-sided — a write side and a read side — and no version of `&Trunk`
//! passed into `resolve()` changes that; it would just be a parameter every
//! real implementation quietly declines to use for the one thing it is
//! there for.
//!
//! So this trait states the honest shape: **`resolve` takes no `Trunk` at
//! all.** A `ServedEgress` implementation is constructed with (or otherwise
//! obtains) whatever [`crate::trunk::SegmentCursor`]/[`crate::trunk::SampleCursor`]
//! it needs, keeps its own resolvable window in sync by draining them
//! (Step 4/5's job, not this trait's), and `resolve` only ever reads that
//! already-synced state. This is not a smaller trait than the spec sketched —
//! it is the same trait with a parameter removed that no implementation
//! could have honestly used.
//!
//! **A second gap in the same area, recorded rather than solved:**
//! `MediaStore::listen()` gives its adapter a wakeup future
//! (`event_listener`) so a blocked LL-HLS request does not have to
//! busy-poll — [`Trunk`](crate::Trunk) has no reader-side notify primitive at
//! all today (every cursor is a synchronous, non-blocking `poll()`; the only
//! `Condvar` in `trunk.rs` wakes a **writer** parked on
//! [`crate::trunk::ArchiveOverrun::StallIngest`], not a reader waiting on new
//! data). An adapter built on this trait must therefore poll-with-backoff,
//! bounded by [`AwaitPolicy`], rather than truly sleeping on a wake channel —
//! acceptable (bounded, correct, just less efficient than `event_listener`),
//! but Step 4 should decide deliberately whether to add a `Trunk`-level
//! notify primitive or accept the poll loop, rather than discovering the gap
//! mid-port.
//!
//! # `EgressResponse::Await` is bounded, by construction, not by convention
//!
//! LL-HLS blocking reload (RFC 8216bis §6.2.5.2) is precisely "hold this
//! request open until a part exists" — and precisely that is also a
//! textbook way for a hostile client to park a request forever: ask for a
//! part that will never arrive, and if the origin waits unconditionally,
//! one connection now costs the origin an open handle indefinitely. This
//! project has already shipped four unbounded-allocation vectors, every one
//! in code handling remote input, which is why this is treated as a hard
//! requirement rather than a documented-only convention:
//! [`EgressResponse::Await`] MUST NOT be returned once the caller's own
//! patience ([`AwaitPolicy::deadline`]) has passed. [`AwaitPolicy::expired`]
//! and [`EgressResponse::pending`] are the one correct path through this
//! check — real code in this crate, not merely documented advice — so an
//! implementor gets the bound for free by calling `EgressResponse::pending`
//! rather than hand-rolling the comparison per protocol. The mutation-tested
//! proof is in this module's tests: `EgressResponse::pending` mutated to
//! never expire is exactly the bug this section exists to prevent, and the
//! test below catches it.
//!
//! Once expired, `pending` answers [`EgressResponse::NotFound`] — literally
//! true ("nothing was found within the time I was willing to wait") — not a
//! fabricated [`EgressResponse::Ready`]. An implementation that *can*
//! produce an honest best-effort `Ready` once its patience runs out (e.g.
//! LL-HLS answering with whatever playlist state currently exists, per RFC
//! 8216bis's own "SHOULD respond in a reasonable time" guidance) is free to
//! do that instead of calling `pending` at all — the contract is "never
//! `Await` past the deadline", not "must be `NotFound` specifically".
//!
//! # `PushEgress`: one cursor, `send` takes one item, `poll_transmit` reused
//! from `IngestSession`
//!
//! [`crate::Trunk::subscribe`]'s own docs are the load-bearing citation here:
//! writer cost is **O(N) in cursor count** (`spikes/trunk-bench`), so a
//! `PushEgress` serving many peers (WHEP, any future RTP multicast/SSM
//! egress) must take **exactly one** [`crate::trunk::SampleCursor`] and fan
//! out to its peers itself, at the layer that already holds per-peer state
//! (SRTP context, congestion window, pacing epoch) anyway — never one cursor
//! per peer. This trait does not (and structurally cannot) enforce that by
//! itself, any more than `Trunk::subscribe` enforces "call me only a
//! single-digit number of times" — it is a documented contract a driver
//! (Step 5) must honour, exactly like that method's own docs.
//!
//! `send` takes `&`[`crate::trunk::SampleCursorItem`] — the exact type
//! [`crate::trunk::SampleCursor::poll`] already produces — rather than the
//! architecture spec's sketched `&TrackBatch`. No `TrackBatch` type exists
//! anywhere in this workspace, and inventing one here would be pure
//! speculation: every real drive loop in this crate (`Stage::poll`,
//! `IngestSession`/`SessionEvent`, `SampleCursor::poll`) already hands back
//! **one item per call**, not a batch, and `SampleCursorItem` already
//! carries the `Lagged`/`Degraded` loss reports a push output needs to see
//! in-band, cannot-skip-past, exactly like every other cursor in this crate.
//! Reusing it is the module's established "reuse, don't duplicate" pattern
//! (see `crate::trunk::SegmentEntry`'s own module doc for the same
//! reasoning), not a smaller feature than the spec sketched.
//!
//! [`PushEgress::poll_transmit`] mirrors
//! [`crate::ingress::IngestSession::poll_transmit`] exactly, for the same
//! reason: a WHEP/RTP push output has real outbound bytes to hand a
//! transport (SRTCP receiver reports, an RTP/RTCP control loop), but most
//! `PushEgress` implementations (a loudness tap, an RTMP-out session that
//! only writes what it is fed) never transmit anything of their own accord,
//! so this is a `None`-returning default a real transmitting output
//! overrides, not a method every implementor must stub out.
//!
//! # `renegotiate` and issue #781: a track addition must be expressible, and
//! a refusal must be truthful
//!
//! Issue #781 is the reason `renegotiate` exists at all, restated precisely
//! since this crate does not fix it (Step 5 does): `multimux`'s
//! `SampleSource::track_specs()` is a one-shot, connect-time snapshot, so
//! when `transmux` (issue #774) correctly detects a mid-stream PMT track
//! *addition* and reports it, there is today no call a source can make to
//! tell a running segmenter/output about it — the new track's samples have
//! nowhere to go. [`PushEgress::negotiate`] is the connect-time call;
//! [`PushEgress::renegotiate`] is what #781 needs: a second, later call with
//! the **current** `&[TrackSpec]` (which may add, remove, or update tracks
//! relative to whatever was last negotiated — driven by
//! `SessionEvent::NewProgram`'s updated track list or a future
//! `Trunk`-level track-set-changed signal), so an addition has a real call
//! site to land on instead of only a log line.
//!
//! **The deliberate design decision this step was asked to make, not
//! default on:** what does an output do when it genuinely cannot accept the
//! new track set — a WHEP peer that already answered an SDP offer, a DASH
//! manifest that already published a `Period` with a fixed
//! `AdaptationSet` list? [`NegotiationOutcome::Refused`] is the answer: a
//! truthful "I understand the change and cannot apply it, and here is why"
//! (`reason: &'static str`), distinct from [`NegotiationOutcome::Accepted`]
//! *and* from [`NegotiationOutcome::Error`] (a malformed/unsatisfiable
//! offer, not a refusal of an otherwise-valid one). The alternative —
//! silently keeping the old [`TrackSelection`] and returning `Accepted`
//! anyway, or simply dropping the new track with no return value at all —
//! was rejected: both look identical to "nothing changed" from the caller's
//! side, which is exactly the silent-drop failure mode #781 already
//! demonstrates for the *ingest* side (a warning logged where nobody reads
//! logs as a control-flow signal). `Refused` is in-band, exactly like every
//! other loss/refusal signal in this crate
//! ([`crate::trunk::SampleCursorItem::Lagged`],
//! [`crate::trunk::SegmentCursorItem::Gap`],
//! [`crate::ingress::HealthState::HandshakeTimedOut`]) — the caller (Step 5's
//! driver reacting to #781) can log it, surface it as a metric, or decide to
//! cut a discontinuity and restart the output; what it cannot do is confuse
//! it with success. After a `Refused`, the output continues running on
//! whichever [`TrackSelection`] it last had `Accepted` (or, if `Refused` was
//! the answer to the very first `negotiate`, it never started at all — the
//! driver's job, not this trait's).
//!
//! # `SegmentEgress` reuses `SegmentCursorItem` verbatim — and does not add
//! `on_manifest`
//!
//! [`SegmentEgress::on_segment`] takes `&`[`crate::trunk::SegmentCursorItem`]
//! — the exact type [`crate::trunk::SegmentCursor::poll`] already produces,
//! including [`crate::trunk::SegmentCursorItem::Gap`]/`Terminated` — so a DVR
//! writer sees the same [`crate::trunk::ArchiveOverrun`] loss/stall/drop
//! signal every other segment reader does, and this step reuses rather than
//! reimplements 3b-ii's pinning: nothing here re-derives when a segment is
//! evicted or a pin releases; that logic stays exactly where it was tested.
//!
//! The architecture spec's §3 pseudocode also sketches
//! `async fn on_manifest(&mut self, m: &ManifestSnapshot)`. `ManifestSnapshot`
//! does not exist anywhere in this workspace, and the spec's own §3 admits
//! why a single type would be wrong here: DVR's "manifest" is a recording
//! index, MABR's is a service/session list, and "a FLUTE/ROUTE sender
//! additionally needs a carousel repeat schedule with per-object deadlines,
//! TOI allocation and FDT expiry — none of which is a `TrackBatch`". Typing
//! one `ManifestSnapshot` now, before any of those four real shapes has a
//! concrete producer, would be exactly the kind of field/variant this
//! crate's own precedent (`crate::byte_merge`'s `Hitless2022_7` note) argues
//! against: don't add a method whose payload nothing can correctly produce
//! yet. `on_segment` alone is what this step can honestly ship;
//! `on_manifest` (or four protocol-specific equivalents) is Step 5's problem,
//! once a real FLUTE/MABR/DVR-index writer exists to shape it.
use Timestamp;
use Bytes;
use TrackSpec;
use crate;
/// `Cache-Control` policy an adapter should apply to a resolved
/// [`EgressResponse::Ready`] body — playlists/manifests are always
/// re-fetched for liveness, while a produced init/segment/part byte range
/// never changes once produced. Mirrors
/// `hls_runtime::server::CachePolicy` in spirit (this crate cannot depend
/// on that crate — the dependency runs the other way, per the migration
/// order in `docs/superpowers/plans/2026-07-26-media-plane-implementation.md`
/// Step 4) so it is redefined here rather than borrowed.
impl_spec_display!;
/// Bounds how long [`ServedEgress::resolve`] may keep answering
/// [`EgressResponse::Await`] for **one logical request** — the same
/// absolute-deadline shape as
/// [`crate::ingress::HandshakePolicy::establish_by`], for the same reason:
/// the failure mode is wall-clock ("the awaited part never arrives"), not an
/// attempt/iteration count, and a fixed [`Timestamp`] costs no new clock
/// concept since [`Timestamp`] is already threaded through this crate.
///
/// A caller constructs one `AwaitPolicy` when a request first arrives (e.g.
/// LL-HLS's RFC 8216bis §6.2.5.2 hold, or a caller-chosen HTTP timeout) and
/// passes the **same** value to every re-resolve of that request as `now`
/// advances — never a fresh, later deadline for the same logical request,
/// which would defeat the bound entirely.
/// What [`ServedEgress::resolve`] hands back: the resolved body, a bounded
/// "not yet", or a reason resolution stops immediately.
///
/// `#[non_exhaustive]`: the growth point for a later, protocol-specific
/// outcome (e.g. a redirect) without a breaking change to every match arm in
/// the workspace.
/// Pull egress: answers a **request** against whatever window state an
/// implementation keeps in sync (LL-HLS, DASH, catch-up) — see
/// [the module docs](self#why-three-shapes-not-one) for why this is not a
/// stream/consume interface, and
/// [why `resolve` takes no `&Trunk`](self#servedegressresolve-does-not-take-trunk--a-correction-found-before-step-4-the-same-way-ingresss-dial-was)
/// for why the signature below differs from the architecture spec's rough
/// pseudocode.
///
/// No `axum`, no `tokio`, no HTTP type appears here on purpose — `multimux`
/// supplies the HTTP adapter (Step 5); this trait is what that adapter maps
/// a wire request onto and renders a wire response from.
/// Which of the currently-known tracks a [`PushEgress`] selected.
///
/// `#[non_exhaustive]`: constructed via [`TrackSelection::new`] — a later
/// step may need per-track selection metadata (e.g. a chosen bitrate ladder
/// rung) alongside the id list.
/// The result of [`PushEgress::negotiate`]/[`PushEgress::renegotiate`] — see
/// [the module docs](self#renegotiate-and-issue-781-a-track-addition-must-be-expressible-and-a-refusal-must-be-truthful)
/// for why `Refused` is a distinct, truthful outcome rather than a silent
/// fallback to the previous selection.
///
/// `#[non_exhaustive]`: the growth point for a later outcome (e.g. "accepted,
/// but only after the next discontinuity") without breaking every match arm.
/// Sample push egress: streams samples that already exist at whoever is
/// listening (WHEP, RTMP-out, SRT-out, a loudness tap) — see
/// [the module docs](self#pushegress-one-cursor-send-takes-one-item-poll_transmit-reused-from-ingestsession).
///
/// # One cursor, never one per peer
///
/// A conforming implementation owns **exactly one**
/// [`crate::trunk::SampleCursor`] (obtained via [`crate::Trunk::subscribe`])
/// regardless of how many peers it serves — see that method's own docs for
/// the O(N)-in-cursor-count writer cost this exists to avoid. This trait
/// does not take a cursor as a parameter (a driver, not this trait, owns and
/// drains it — see [`crate::trunk::SampleCursor::poll`]'s own docs), so
/// nothing here can *enforce* the rule; it is exactly as documented-only as
/// `Trunk::subscribe`'s own guidance.
/// Segment/object push egress: consumes finished segments (DVR, DVB-MABR,
/// ATSC ROUTE, Smooth-push) via one [`crate::trunk::SegmentCursor`] — see
/// [the module docs](self#segmentegress-reuses-segmentcursoritem-verbatim--and-does-not-add-on_manifest).
///
/// Exactly like [`PushEgress`], a conforming implementation owns **one**
/// cursor (ordinary, from [`crate::Trunk::subscribe_segments`], or pinning,
/// from [`crate::Trunk::pin_segments`], for a consumer that must not miss a
/// segment) — the same single-digit-reader, one-cursor-per-consumer rule as
/// every other `Trunk` reader.