Skip to main content

rtflow_hls/segmenter/
mod.rs

1use bytes::Bytes;
2use std::{collections::HashMap, time::Duration};
3use tokio::sync::broadcast;
4
5use rtflow_media::{AccessUnit, Codec, MediaDescription, MediaKind};
6
7mod entries;
8mod init;
9mod media;
10mod sps;
11mod ts;
12pub use self::ts::track_spec;
13pub(crate) mod util;
14
15use self::init::build_init_segment;
16use self::media::build_media_segment;
17use self::ts::TsPipeline;
18use self::util::{annex_b_to_length_prefixed, codec_config_from_annex_b, codec_config_from_fmtp};
19
20/// Hard safety bound for a segment whose timestamps never advance.
21const MAX_SAMPLES_PER_SEGMENT: usize = 10_000;
22
23/// Un-cut hold bounds for the live segmenters. A stream whose encoder never
24/// produces the sync sample a segment must open on is refused (the error is
25/// logged and the mount stops producing) instead of buffering without limit;
26/// 7200 samples is 4 minutes at 30 fps, 32 MiB bounds the coded bytes.
27pub(crate) fn pending_limits() -> transmux::segmenter::PendingLimits {
28    transmux::segmenter::PendingLimits {
29        max_samples: std::num::NonZeroUsize::new(7_200).expect("non-zero pending sample bound"),
30        max_bytes: std::num::NonZeroUsize::new(32 * 1024 * 1024)
31            .expect("non-zero pending byte bound"),
32    }
33}
34
35/// Configuration for the fMP4 segmenter.
36#[derive(Clone, Debug)]
37pub struct SegmenterConfig {
38    /// Target segment duration.
39    pub segment_duration: Duration,
40    /// Maximum number of segments to keep in the ring buffer.
41    pub lookback_count: usize,
42}
43
44impl Default for SegmenterConfig {
45    fn default() -> Self {
46        Self {
47            segment_duration: Duration::from_secs(2),
48            // Embedded budget (docs/audits/embedded-resource.md P1-6):
49            // lookback segments are retained in RAM after finalization,
50            // so 2s×bitrate×lookback caps the HLS writer peak (5→3 saves
51            // ~2×segment bytes, e.g. 2MB at 1080p 4Mbps).
52            lookback_count: 3,
53        }
54    }
55}
56
57/// Container written for a completed segment.
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59pub enum SegmentFormat {
60    /// fMP4 (init + moof/mdat), used by VOD and static HLS.
61    Fmp4,
62    /// MPEG-TS (PAT/PMT/PES), used by live HLS.
63    MpegTs,
64}
65
66/// A completed HLS segment.
67#[derive(Clone, Debug)]
68pub struct Segment {
69    /// Sequence number (monotonically increasing).
70    pub sequence: u64,
71    /// Actual duration of this segment.
72    pub duration: Duration,
73    /// Init segment data (ftyp + moov).
74    pub init: Bytes,
75    /// Media segment data (moof + mdat).
76    pub data: Bytes,
77    /// Whether this segment starts with a keyframe.
78    pub starts_with_keyframe: bool,
79    /// Whether a decoder discontinuity precedes this segment.
80    pub discontinuity: bool,
81    /// Global discontinuity sequence number of this segment (Some when
82    /// `discontinuity`), for EXT-X-DISCONTINUITY-SEQUENCE alignment.
83    pub discontinuity_sequence: Option<u32>,
84    /// Timestamp of the first sample in the segment.
85    pub timestamp: Duration,
86    /// Container format of `data`.
87    pub format: SegmentFormat,
88}
89
90struct TrackState {
91    kind: MediaKind,
92    timescale: u32,
93    samples: Vec<SampleEntry>,
94    last_dts: Option<Duration>,
95    /// Last PTS pushed for this track, for reset detection against the
96    /// track's own timeline (audio and video clocks are independent; a
97    /// global comparison would mistake their long-term baseline drift
98    /// for a stream reset).
99    last_pts: Option<Duration>,
100    codec_config: Option<Bytes>,
101}
102
103struct SampleEntry {
104    data: Bytes,
105    pts: Duration,
106    dts: Duration,
107    is_keyframe: bool,
108    duration: Duration,
109}
110
111pub struct Segmenter {
112    config: SegmenterConfig,
113    description: MediaDescription,
114    tracks: Vec<TrackState>,
115    track_indices: HashMap<u8, usize>,
116    current_segment_pts: Option<Duration>,
117    sequence: u64,
118    tx: broadcast::Sender<Segment>,
119    init_segment: Option<Bytes>,
120    next_discontinuity: bool,
121    /// Monotonic counter of discontinuities ever generated.
122    discontinuity_counter: u32,
123    ts_pipeline: Option<TsPipeline>,
124    mpeg_ts: bool,
125}
126
127impl Segmenter {
128    pub fn new(config: SegmenterConfig, description: &MediaDescription) -> Self {
129        let (tx, _) = broadcast::channel(config.lookback_count.max(2));
130        let track_indices = description
131            .tracks
132            .iter()
133            .enumerate()
134            .map(|(index, track)| (track.id, index))
135            .collect();
136        let tracks = description
137            .tracks
138            .iter()
139            .map(|t| TrackState {
140                kind: t.kind,
141                timescale: t.clock_rate,
142                samples: Vec::new(),
143                last_dts: None,
144                last_pts: None,
145                codec_config: None,
146            })
147            .collect();
148
149        Self {
150            config,
151            description: description.clone(),
152            tracks,
153            track_indices,
154            current_segment_pts: None,
155            sequence: 0,
156            tx,
157            init_segment: None,
158            next_discontinuity: false,
159            discontinuity_counter: 0,
160            ts_pipeline: None,
161            mpeg_ts: false,
162        }
163    }
164
165    /// Create a live segmenter that emits MPEG-TS segments via the
166    /// `transmux` streaming TS-HLS segmenter. Falls back to fMP4 when the
167    /// description lacks a usable AVC/AAC configuration.
168    pub fn new_mpegts(config: SegmenterConfig, description: &MediaDescription) -> Self {
169        let ts_pipeline = TsPipeline::new(description, &config);
170        let mut segmenter = Self::new(config, description);
171        segmenter.mpeg_ts = ts_pipeline.is_some();
172        segmenter.ts_pipeline = ts_pipeline;
173        segmenter
174    }
175
176    /// Subscribe to completed segments.
177    pub fn subscribe(&self) -> broadcast::Receiver<Segment> {
178        self.tx.subscribe()
179    }
180
181    /// Update track fmtp parameters (e.g., from a late ANNOUNCE SDP).
182    ///
183    /// If a track's `codec_config` has not yet been extracted from the stream,
184    /// this also attempts to initialize it from `sprop-parameter-sets` in the fmtp.
185    pub fn update_fmtp(&mut self, fmtp_map: &HashMap<u8, std::sync::Arc<str>>) {
186        for track_desc in &mut self.description.tracks {
187            if let Some(fmtp) = fmtp_map.get(&track_desc.id) {
188                track_desc.fmtp = Some(fmtp.clone());
189            }
190        }
191        // Try to initialize codec_config from fmtp for tracks that don't have it yet
192        for (i, track_desc) in self.description.tracks.iter().enumerate() {
193            if let Some(state) = self.tracks.get_mut(i)
194                && state.codec_config.is_none()
195            {
196                state.codec_config = codec_config_from_fmtp(track_desc);
197                tracing::debug!(
198                    track_id = track_desc.id,
199                    codec_config_len = state.codec_config.as_ref().map(|c| c.len()).unwrap_or(0),
200                    "Segmenter update_fmtp codec_config"
201                );
202            }
203        }
204    }
205
206    /// Push an AccessUnit into the segmenter. Segments are cut immediately before
207    /// the first keyframe at or after the target duration, so every new video
208    /// segment begins at a random access point.
209    /// Set the next sequence number before the first push. Used when a
210    /// segmenter is recreated for a long-lived live mount: the playlist's
211    /// EXT-X-MEDIA-SEQUENCE must never go backwards.
212    pub fn set_sequence(&mut self, sequence: u64) {
213        self.sequence = sequence;
214        if let Some(pipeline) = &mut self.ts_pipeline {
215            pipeline.set_sequence(sequence);
216        }
217    }
218
219    pub fn push(&mut self, unit: AccessUnit) {
220        if self.mpeg_ts
221            && let Some(pipeline) = &mut self.ts_pipeline
222        {
223            for segment in pipeline.push(unit) {
224                let _ = self.tx.send(segment);
225            }
226            return;
227        }
228        let Some(&track_index) = self.track_indices.get(&unit.track_id) else {
229            return;
230        };
231        let pts = unit.pts;
232        let has_video = self
233            .tracks
234            .iter()
235            .any(|track| track.kind == MediaKind::Video);
236        // Timestamps can stall (broken encoder/ingest). A pure PTS-based cut
237        // then never fires and `samples` grows without bound; force a cut at
238        // the hard sample cap for audio-only streams. Video must never be cut
239        // mid-GOP: a segment that does not start at an IDR is undecodable.
240        if self.tracks[track_index].samples.len() >= MAX_SAMPLES_PER_SEGMENT && !has_video {
241            self.finalize_segment(pts);
242        }
243        // A reset of this track's own timeline (timestamp wrap / source
244        // restart) is detected against the track's last PTS. A global
245        // comparison against the segment start would mistake independent
246        // audio/video clock baselines for a reset once they drift >30 s
247        // apart — which produced a discontinuity storm and 0-length
248        // segments on long-running multi-track streams.
249        let track_reset = self.tracks[track_index]
250            .last_pts
251            .is_some_and(|last| last.saturating_sub(pts) > Duration::from_secs(30));
252        // The reset flag must land on the segment *after* the cut (the one
253        // starting at the restart frame), not on the finalized pre-reset
254        // segment: players reset their decoder where they see the flag.
255        let mut delayed_discontinuity = false;
256        let starts_new_segment = if track_reset {
257            delayed_discontinuity = true;
258            true
259        } else {
260            self.current_segment_pts.is_some_and(|start| {
261                if pts < start {
262                    // A small backward delta is just the difference
263                    // between track start baselines (audio vs video) and
264                    // must not cut a segment.
265                    return false;
266                }
267                let elapsed = pts.saturating_sub(start);
268                if elapsed < self.config.segment_duration {
269                    return false;
270                }
271                let hard_limit = self
272                    .config
273                    .segment_duration
274                    .saturating_mul(2)
275                    .max(Duration::from_millis(1));
276                if elapsed >= hard_limit && !has_video {
277                    // Hard time-based cut is only valid for audio-only
278                    // streams. Cutting a video segment before an IDR makes
279                    // every following segment undecodable (HLS.js black
280                    // screen, ffprobe "missing reference picture").
281                    return true;
282                }
283                // Regular cut: align with a video random-access point.
284                unit.is_keyframe && matches!(unit.codec, Codec::H264 | Codec::H265)
285            })
286        };
287        if unit.is_keyframe && matches!(unit.codec, Codec::H264 | Codec::H265) {
288            tracing::debug!(?pts, ?self.current_segment_pts, "HLS video random-access point");
289        }
290        // Learn the codec configuration *before* a possible cut: the first
291        // keyframe of a recording that started mid-GOP both carries the
292        // SPS/PPS and triggers finalization of the previous segment. Building
293        // the init segment first would cache an empty avcC/hvcC.
294        if self.tracks[track_index].codec_config.is_none() {
295            self.tracks[track_index].codec_config =
296                codec_config_from_annex_b(unit.codec, &unit.data);
297        }
298        if starts_new_segment {
299            self.finalize_segment(pts);
300        }
301        // Apply a pending reset flag to the *new* segment only.
302        if delayed_discontinuity {
303            self.next_discontinuity = true;
304        }
305        if self.current_segment_pts.is_none() {
306            self.current_segment_pts = Some(pts);
307        }
308
309        let track = &mut self.tracks[track_index];
310        track.last_pts = Some(pts);
311        let dts = unit.dts.unwrap_or(pts);
312        let sample_duration = track
313            .last_dts
314            .map(|last| dts.saturating_sub(last))
315            .filter(|duration| !duration.is_zero())
316            .unwrap_or_else(|| Duration::from_millis(40));
317        track.last_dts = Some(dts);
318        let data = match unit.codec {
319            Codec::H264 | Codec::H265 => annex_b_to_length_prefixed(unit.codec, &unit.data),
320            _ => unit.data,
321        };
322        track.samples.push(SampleEntry {
323            data,
324            pts,
325            dts,
326            is_keyframe: unit.is_keyframe,
327            duration: sample_duration,
328        });
329    }
330
331    fn finalize_segment(&mut self, end_pts: Duration) {
332        // Check if we have any samples
333        let has_samples = self.tracks.iter().any(|t| !t.samples.is_empty());
334        if !has_samples {
335            return;
336        }
337
338        // Build init segment if not cached
339        if self.init_segment.is_none() {
340            self.init_segment = Some(build_init_segment(&self.description, &self.tracks));
341        }
342
343        // Build media segment
344        let segment_data = build_media_segment(&mut self.tracks, self.sequence);
345        let segment_pts = self.current_segment_pts.unwrap_or(end_pts);
346        let segment_duration = end_pts.saturating_sub(segment_pts);
347
348        let starts_with_keyframe = self.tracks.iter().any(|track| {
349            track.kind == MediaKind::Video
350                && track
351                    .samples
352                    .first()
353                    .is_some_and(|sample| sample.is_keyframe)
354        });
355
356        let discontinuity_flag = std::mem::take(&mut self.next_discontinuity);
357        let segment_discontinuity_sequence = if discontinuity_flag {
358            self.discontinuity_counter += 1;
359            Some(self.discontinuity_counter)
360        } else {
361            None
362        };
363        let segment = Segment {
364            sequence: self.sequence,
365            duration: segment_duration,
366            init: self.init_segment.clone().unwrap_or_default(),
367            data: segment_data,
368            starts_with_keyframe,
369            discontinuity: discontinuity_flag,
370            discontinuity_sequence: segment_discontinuity_sequence,
371            timestamp: segment_pts,
372            format: SegmentFormat::Fmp4,
373        };
374
375        tracing::debug!(sequence = segment.sequence, ?segment.duration, "HLS segment finalized");
376        let _ = self.tx.send(segment);
377        self.sequence += 1;
378        self.current_segment_pts = Some(end_pts);
379
380        // Clear samples for next segment
381        for track in &mut self.tracks {
382            track.samples.clear();
383        }
384    }
385
386    /// Finalize the current segment at the last sample's end.
387    ///
388    /// DASH uses this to reap an audio segment when its video counterpart is
389    /// cut, keeping the two tracks' segment boundaries close without changing
390    /// the HLS segmenter's own keyframe-driven cuts.
391    pub fn cut_current(&mut self) {
392        if self.mpeg_ts {
393            return;
394        }
395        let end = self
396            .tracks
397            .iter()
398            .flat_map(|track| track.samples.iter())
399            .map(|sample| sample.pts.saturating_add(sample.duration))
400            .max();
401        if let Some(end) = end {
402            self.finalize_segment(end);
403        }
404    }
405
406    /// Drop incomplete samples after a transport gap and mark the next segment.
407    pub fn reset_after_discontinuity(&mut self) {
408        if let Some(pipeline) = &mut self.ts_pipeline {
409            pipeline.mark_discontinuity();
410        }
411        for track in &mut self.tracks {
412            track.samples.clear();
413            track.last_dts = None;
414            track.last_pts = None;
415            track.codec_config = None;
416        }
417        self.current_segment_pts = None;
418        self.init_segment = None;
419        self.next_discontinuity = true;
420    }
421
422    /// Flush any remaining samples as a final segment.
423    pub fn flush(&mut self) {
424        if self.mpeg_ts
425            && let Some(pipeline) = &mut self.ts_pipeline
426        {
427            for segment in pipeline.flush() {
428                let _ = self.tx.send(segment);
429            }
430            return;
431        }
432        let has_samples = self.tracks.iter().any(|t| !t.samples.is_empty());
433        if !has_samples {
434            return;
435        }
436
437        if self.init_segment.is_none() {
438            self.init_segment = Some(build_init_segment(&self.description, &self.tracks));
439        }
440
441        let segment_data = build_media_segment(&mut self.tracks, self.sequence);
442        let segment_pts = self.current_segment_pts.unwrap_or_default();
443
444        let end_pts = self
445            .tracks
446            .iter()
447            .flat_map(|track| track.samples.iter())
448            .map(|sample| sample.pts.saturating_add(sample.duration))
449            .max()
450            .unwrap_or(segment_pts);
451        let discontinuity_flag = std::mem::take(&mut self.next_discontinuity);
452        let segment_discontinuity_sequence = if discontinuity_flag {
453            self.discontinuity_counter += 1;
454            Some(self.discontinuity_counter)
455        } else {
456            None
457        };
458        let segment = Segment {
459            sequence: self.sequence,
460            duration: end_pts.saturating_sub(segment_pts),
461            init: self.init_segment.clone().unwrap_or_default(),
462            data: segment_data,
463            starts_with_keyframe: self.tracks.iter().any(|track| {
464                track.kind == MediaKind::Video
465                    && track
466                        .samples
467                        .first()
468                        .is_some_and(|sample| sample.is_keyframe)
469            }),
470            discontinuity: discontinuity_flag,
471            discontinuity_sequence: segment_discontinuity_sequence,
472            timestamp: segment_pts,
473            format: SegmentFormat::Fmp4,
474        };
475
476        let _ = self.tx.send(segment);
477        self.sequence += 1;
478
479        for track in &mut self.tracks {
480            track.samples.clear();
481        }
482    }
483}