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
//! Stateful CMAF segmenter — a streaming wrapper over [`build_init_segment`] and
//! [`build_media_segment`].
//!
//! [`build_media_segment`] is a *batch* box
//! builder: hand it the samples for one segment and it emits the `styp`/`moof`/
//! `mdat`. It has no notion of *when* a segment should end. A live remuxer needs
//! that decision: accumulate coded access units, cut a segment on a keyframe once
//! it has reached a target duration, and expose finished segments to the caller.
//!
//! [`Segmenter`] adds exactly that state machine:
//!
//! - [`Segmenter::init_segment`] — the `ftyp`+`moov` init, available immediately.
//! - [`Segmenter::push`] — feed one [`Sample`] for a track, in decode order.
//! - [`Segmenter::take_ready`] — drain media segments finished so far.
//! - [`Segmenter::flush`] — finalize the trailing partial segment at end-of-stream.
//! - [`Segmenter::mark_discontinuity`] — mark the *next* cut as discontinuous
//! (RFC 8216 §4.3.4.3).
//! - [`Segmenter::take_ready_with_meta`] — like `take_ready` but also returns
//! per-segment [`SegmentMeta`] that carries the discontinuity flag for HLS
//! playlist assembly.
//!
//! Segments are cut on the **anchor track** (the first video track, else the
//! first [`is_anchor_capable`] track): when a sync sample arrives *and* the
//! anchor's buffered duration has reached the target, the buffered samples
//! across all tracks are emitted as one media segment and the incoming keyframe
//! starts the next one. So every video segment begins on a random-access point,
//! as CMAF requires, and no sample is dropped or reordered — the concatenation
//! of all segments carries the full input stream with contiguous per-track
//! decode times.
//!
//! # Anchor progress and the un-cut bound
//!
//! "The anchor's buffered duration" is accumulated by [`MediaClock`]: each
//! anchor sample's own `duration` when that is a real, non-zero span, and
//! otherwise the **`dts` delta** from the previous anchor sample. `dts` is
//! absolute (media plane step 2c), so elapsed media time is derivable without
//! `duration` at all — and it must be, because a `duration` of `Some(0)` is
//! routine on live input and would otherwise freeze the accumulator so that no
//! segment is ever cut and the pending buffer grows without bound.
//!
//! A stream that never produces a second sync sample (single-IDR / infinite
//! GOP — legal, and common for screen capture) can still never be cut, because
//! cutting mid-GOP would break CMAF's random-access guarantee. That case is
//! bounded rather than silently mis-cut: past
//! [`MAX_PENDING_SAMPLES_PER_TRACK`] un-cut samples,
//! [`Stage::demand`] reports `saturated` and
//! [`push`](Segmenter::push) returns a named error. These same three
//! primitives are shared verbatim by the other three segmenters.
//!
//! # Discontinuity detection
//!
//! A media-timeline discontinuity (RFC 8216 §4.3.4.3) is signalled in two ways:
//!
//! 1. **Explicit**: call [`Segmenter::mark_discontinuity`] before the next
//! [`Segmenter::push`] call that triggers a segment cut. The *next* segment
//! that is cut will be marked discontinuous.
//!
//! 2. **Auto-detect**: when the init segment bytes change between two consecutive
//! cuts (e.g. because the codec config, `EXT-X-MAP`, or track layout changed),
//! the segmenter automatically marks the later segment as discontinuous.
//!
//! Both mechanisms set the [`SegmentMeta::discontinuous`] flag returned by
//! [`Segmenter::take_ready_with_meta`], which callers can forward directly to
//! [`broadcast_hls::MediaSegment::discontinuous`].
use VecDeque;
use Vec;
use ;
use crate;
use crate;
// ── Shared segmentation primitives (all four segmenters) ────────────────────
//
// [`Segmenter`] (CMAF), [`LlSegmenter`](crate::ll_dash::LlSegmenter)
// (chunked CMAF / LL-DASH), [`LlHlsSegmenter`](crate::ll_hls::LlHlsSegmenter)
// (LL-HLS parts) and [`StreamingTsHlsSegmenter`](crate::ts_hls::StreamingTsHlsSegmenter)
// (classic TS-HLS) all cut on the same rule — "the anchor track's next sync
// sample once the anchor has buffered the target duration" — so anchor
// selection, anchor-clock accounting, and the un-cut buffer bound live here
// once and are shared, rather than re-derived (and drifting) per module.
/// True when `config`'s samples can advance an anchor clock, so the track is
/// eligible to be the segmentation anchor (the keyframe-cut boundary track).
///
/// False only for a section-carried [`CodecConfig::Data`] track
/// ([`DataCarriage::Sections`]): ISO/IEC 13818-1 §2.4.4 PSI/private sections
/// carry no PES timestamp at all, so `TsDemux`/`StreamingTsDemux` never
/// fabricate a `dts` *or* a `duration` for them (media plane step 2c) — every
/// sample is `dts: None, duration: None`, so neither term of
/// [`MediaClock::tick`] can ever advance and the segmenter would buffer
/// forever without cutting. A PES-carried `CodecConfig::Data` track
/// ([`DataCarriage::Pes`], e.g. private PES data) *does* get a real
/// lookahead-derived duration and an absolute dts exactly like audio/video,
/// so it stays anchor-eligible.
///
/// Deliberately narrower than [`CodecConfig::is_muxable_in_bmff`], which
/// excludes every `Data` track (`Pes` or `Sections`) plus `Subtitle`: unlike
/// ISOBMFF, this crate's TS mux path ([`crate::ts_mux`]) *can* and does carry
/// section tracks verbatim (raw on their own PID rather than PES), so a
/// section-carried track must stay in the segmenter's track set to be muxed
/// — it is just never chosen as the anchor.
/// Choose the anchor track index used for segment-cut boundaries: the first
/// video track (any `CodecConfig::is_video` codec — issue #628; that predicate
/// is crate-internal), else the
/// first [`is_anchor_capable`] track.
///
/// Never silently falls back to track 0 when no track qualifies: that would
/// pick a track whose clock can never advance (e.g. a section-only,
/// video-less input carrying only a SCTE-35 splice-info track), and the
/// segmenter would then buffer forever without ever cutting a segment. That
/// case is a construction error instead.
///
/// # Errors
/// [`Error::InvalidInput`] if `configs` is empty, or no track is
/// anchor-capable (every track is a section-carried [`CodecConfig::Data`]
/// track).
/// Per-track elapsed-media accounting: turns a stream of [`Sample`]s into
/// per-sample tick increments in that track's media timescale.
///
/// The increment for a sample is its own `duration` when that is a real,
/// non-zero span; **otherwise the `dts` delta from the previous sample of the
/// same track**. Media plane step 2c made `Sample::dts` an *absolute* tick
/// value, so elapsed media time is derivable without `duration` at all — and
/// it has to be, because `duration` is legitimately `Some(0)` on real inputs:
/// [`StreamingFlvDemux`](crate::flv_stream::StreamingFlvDemux) derives it as
/// the forward delta between consecutive FLV tag timestamps, so the first
/// sample of an RTMP publish, and any two tags sharing a timestamp, yield `0`.
/// Before this fallback existed a `Some(0)`/`None` duration froze every
/// segmenter's anchor accumulator: no segment was ever cut and the pending
/// buffer grew without bound.
///
/// `duration` stays the *primary* term so a stream that carries real
/// durations segments byte-identically to before this fallback existed; the
/// dts delta only fills the gap `duration` leaves. When neither is available
/// the increment is `0` — a track in that state is not
/// [`is_anchor_capable`], and the anchor role is refused at construction.
/// The longest run of un-cut anchor media a segmenter will buffer while
/// waiting for the sync sample it needs to open the next segment on, in
/// seconds. Ten times RFC 8216 §4.3.3.1's recommended 6-second target
/// duration (DASH-IF LL IOP targets 1–4 s), so no conformant configuration
/// can reach it.
const MAX_UNCUT_SECS: usize = 60;
/// Ceiling on an anchor track's sample rate, in samples/second: 120 fps is
/// the top video frame rate in ITU-R BT.2100 / ATSC A/341, and every audio
/// anchor is far slower (48 kHz AAC is 46.9 frames/s at 1024 samples/frame).
const MAX_ANCHOR_RATE_HZ: usize = 120;
/// Hard bound on the number of samples any one track may hold **un-cut**
/// inside a segmenter (issue: single-IDR / infinite-GOP stall).
///
/// A stream with one keyframe at the start and none after — legal, and
/// routine for screen capture and low-motion surveillance — never satisfies
/// the "next sync sample" half of the cut rule, so without a bound every
/// segmenter buffers until memory is exhausted while
/// [`Stage::demand`] still answers "not
/// saturated", inviting a well-behaved driver to keep feeding.
///
/// Cutting mid-GOP is *not* the answer: a CMAF segment (and a classic-HLS
/// `.ts` segment) must begin on a random-access point, so a segment cut on a
/// non-sync sample would be non-conformant. Instead the bound is on data:
/// past it `demand()` reports `saturated` (the load-bearing half — a
/// cooperative driver stops feeding) and `push`/`feed` returns a named error
/// rather than growing further. It is expressed in **samples**, not bytes,
/// because the pathology is "how many access units without a random-access
/// point", which is codec-bitrate-independent; a byte bound would trip at
/// wildly different GOP lengths for a 200 kbit/s and a 200 Mbit/s stream.
/// The bound is deliberately *not* a wall-clock timeout: these types are
/// sans-IO and `no_std`.
///
/// A segmenter that has hit the bound is not wedged: `flush`/`finish` cuts
/// the whole pending buffer (a trailing partial segment is allowed not to
/// start on a keyframe) and the segmenter accepts input again.
pub const MAX_PENDING_SAMPLES_PER_TRACK: usize = MAX_UNCUT_SECS * MAX_ANCHOR_RATE_HZ;
/// The error every segmenter returns when a `push`/`feed` would grow a
/// track's un-cut buffer past [`MAX_PENDING_SAMPLES_PER_TRACK`] — i.e. the
/// anchor track produced that many samples with no sync sample to cut on.
pub
/// Per-segment metadata returned alongside the media segment bytes by
/// [`Segmenter::take_ready_with_meta`].
/// Per-track accumulation state for the segment currently being built.
/// A stateful CMAF segmenter. Build it from the same [`TrackSpec`]s used for the
/// init segment, `push` coded samples in decode order, and pull finished media
/// segments with `take_ready`; `flush` emits the final partial segment.
///
/// ```
/// use transmux::{CodecConfig, Sample, Segmenter, TrackSpec};
/// # use transmux::{AVCConfigurationBox, AVCDecoderConfigurationRecord, AvcPps, AvcSps};
/// # fn spec() -> TrackSpec {
/// # let record = AVCDecoderConfigurationRecord {
/// # configuration_version: 1,
/// # profile_indication: 66,
/// # profile_compatibility: 0,
/// # level_indication: 30,
/// # length_size_minus_one: 3,
/// # sps: vec![AvcSps(vec![0x67, 0x42, 0xc0, 0x1e, 0xd9, 0x00, 0x80, 0x1e, 0x24])],
/// # pps: vec![AvcPps(vec![0x68, 0xce, 0x3c, 0x80])],
/// # chroma_format: None,
/// # bit_depth_luma_minus8: None,
/// # bit_depth_chroma_minus8: None,
/// # sps_ext: vec![],
/// # };
/// # TrackSpec::new(1, 90_000, CodecConfig::Avc {
/// # config: AVCConfigurationBox::new(record),
/// # width: 16,
/// # height: 16,
/// # })
/// # }
/// # fn au(sync: bool) -> Sample {
/// # use std::sync::atomic::{AtomicI64, Ordering};
/// # static NEXT_DTS: AtomicI64 = AtomicI64::new(0);
/// # let dts = NEXT_DTS.fetch_add(1000, Ordering::Relaxed);
/// # Sample::new(vec![0u8; 4], Some(dts), Some(dts), Some(1000), sync)
/// # }
/// let mut seg = Segmenter::new(vec![spec()], 1000, 2.0).unwrap();
/// let init = seg.init_segment().unwrap(); // ftyp + moov
/// assert_eq!(&init[4..8], b"ftyp");
/// seg.push(1, au(true)).unwrap(); // keyframe
/// seg.push(1, au(false)).unwrap();
/// assert!(seg.take_ready().is_empty()); // still buffering: no cut yet
/// seg.flush().unwrap(); // trailing segment
/// assert_eq!(seg.take_ready().len(), 1);
/// ```
/// [`Stage`] adoption (media plane step 2e-2): `In = (u32, Sample)`, the
/// segmenter's real per-call input (a track id plus one coded sample) — not
/// the byte-stream family's `&[u8]`, which would have no honest encoding of a
/// `Sample` (see the `stage` module docs). `Out` is
/// [`take_ready_with_meta`](Self::take_ready_with_meta)'s item type: bytes
/// plus the discontinuity metadata a caller needs for the HLS playlist, not a
/// bare `Vec<u8>` that would silently drop that flag.
///
/// Every inherent method — [`push`](Self::push), [`take_ready`](Self::take_ready),
/// [`take_ready_with_meta`](Self::take_ready_with_meta), [`flush`](Self::flush),
/// [`mark_discontinuity`](Self::mark_discontinuity) — keeps working unchanged;
/// this impl is an additional, uniform way to drive the same engine.
/// [`Stage::poll`] and the inherent drains all read from the *same* `ready`
/// queue (there is no separate staging copy), so a segment is delivered
/// exactly once no matter which API — inherent, `Stage`, or a mix of both on
/// the same instance — the caller uses to retrieve it.