//! Splits a service stream into HLS (MPEG-TS) segments on keyframe boundaries. use super::filter::ServiceFilter; use crate::ts::packet; use crate::ts::pes; use bytes::Bytes; use std::time::Instant; #[derive(Clone, Debug)] pub struct Segment { pub seq: u64, pub duration: f64, pub data: Bytes, /// Segment end time (for bitrate measurement). pub created: Instant, } pub struct Segmenter { pub filter: ServiceFilter, target_90k: u64, max_90k: u64, buf: Vec, start_pts: Option, last_pts: Option, wall_start: Instant, started: bool, next_seq: u64, scratch: Vec, } impl Segmenter { pub fn new(filter: ServiceFilter, target_secs: f64, first_seq: u64) -> Self { let target_90k = (target_secs * 90_000.0) as u64; Self { filter, target_90k, max_90k: target_90k * 6 + 90_000 * 4, buf: Vec::with_capacity(2 * 1024 * 1024), start_pts: None, last_pts: None, wall_start: Instant::now(), started: false, next_seq: first_seq, scratch: Vec::with_capacity(188 * 64), } } /// Processes a multiplex packet, returns a finished segment (if any). pub fn push(&mut self, pkt: &[u8]) -> Option { self.scratch.clear(); let mut scratch = std::mem::take(&mut self.scratch); self.filter.push(pkt, &mut scratch); let mut result = None; for p in scratch.chunks_exact(packet::TS_SIZE) { if let Some(seg) = self.push_filtered(p) { result = Some(seg); } } self.scratch = scratch; result } fn push_filtered(&mut self, p: &[u8]) -> Option { let pid = packet::pid(p); let primary = self.filter.primary(); let mut out = None; if let Some((ppid, kind)) = primary { if pid == ppid && packet::pusi(p) { if let Some(pl) = packet::payload(p) { let pts = pes::pts(pl); let key = if kind.is_video() { packet::random_access(p) || pes::is_keyframe(kind, pl) } else { true }; if let Some(pts) = pts { self.last_pts = Some(pts); } if key { if !self.started { self.started = true; self.begin(pts); } else { let elapsed = match (self.start_pts, pts) { (Some(s), Some(e)) => pes::pts_diff(s, e).max(0) as u64, _ => (self.wall_start.elapsed().as_secs_f64() * 90_000.0) as u64, }; if elapsed >= self.target_90k { out = self.finish(elapsed); self.begin(pts); } } } else if self.started { // guard against very long GOPs / missing flags if let (Some(s), Some(e)) = (self.start_pts, pts) { let el = pes::pts_diff(s, e).max(0) as u64; if el > self.max_90k { out = self.finish(el); self.begin(Some(e)); } } } } } } if self.started { self.buf.extend_from_slice(p); } out } fn begin(&mut self, pts: Option) { self.buf.clear(); self.filter.write_psi(&mut self.buf); self.start_pts = pts; self.wall_start = Instant::now(); } fn finish(&mut self, elapsed_90k: u64) -> Option { if self.buf.is_empty() { return None; } let data = Bytes::from(std::mem::replace( &mut self.buf, Vec::with_capacity(2 * 1024 * 1024), )); let seq = self.next_seq; self.next_seq += 1; Some(Segment { seq, duration: elapsed_90k as f64 / 90_000.0, data, created: Instant::now(), }) } /// Closes the current segment (e.g. at the end of a recording). pub fn flush(&mut self) -> Option { if !self.started || self.buf.is_empty() { return None; } let el = match (self.start_pts, self.last_pts) { (Some(s), Some(e)) => pes::pts_diff(s, e).max(0) as u64, _ => (self.wall_start.elapsed().as_secs_f64() * 90_000.0) as u64, }; let seg = self.finish(el.max(1)); self.started = false; seg } } #[cfg(test)] mod tests { use super::*; use crate::ts::testgen::GenMux; fn run(hevc_index: usize, target: f64) -> Vec { let mux = GenMux::sample(1, 0x10, &["A", "B"], 1_700_000_000); let ts = mux.generate(9); let s = &mux.services[hevc_index]; let mut seg = Segmenter::new(ServiceFilter::new(Some(s.sid), Some(s.pmt_pid)), target, 0); let mut out = Vec::new(); for p in ts.chunks(188) { if let Some(x) = seg.push(p) { out.push(x); } } out.extend(seg.flush()); out } #[test] fn segments_on_keyframes_h264_and_hevc() { for idx in [0, 1] { let segs = run(idx, 2.0); assert!(segs.len() >= 3, "{}", segs.len()); for (i, s) in segs.iter().enumerate() { assert_eq!(s.seq, i as u64); assert_eq!(s.data.len() % 188, 0); // every segment starts with a PAT assert_eq!(packet::pid(&s.data[..188]), 0); if i + 1 < segs.len() { assert!((s.duration - 2.0).abs() < 0.05, "dur {}", s.duration); } } } } #[test] fn segment_is_valid_standalone_ts() { let segs = run(0, 1.0); let mut si = crate::ts::si::SiCollector::new(false); for p in segs[1].data.chunks(188) { si.push(p); } assert!(si.pmts_complete()); } }