From e496c68ba6ee25573b5148d6b6458f644a276e41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 15:11:55 +0300 Subject: [PATCH] S3: one wrap_delta for the 33-bit clock difference (unwrap33, Clock::feed, PES dts-pts) with identical arithmetic --- crates/ec-mpegts/src/demux.rs | 17 +++++++++-------- crates/ec-mpegts/src/ps.rs | 17 +++-------------- 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/crates/ec-mpegts/src/demux.rs b/crates/ec-mpegts/src/demux.rs index 51cceeb0..480e48fe 100644 --- a/crates/ec-mpegts/src/demux.rs +++ b/crates/ec-mpegts/src/demux.rs @@ -66,18 +66,19 @@ enum Cc { Gap, } +const WRAP33: i64 = 1 << 33; + +/// Signed distance from `b` to `a` on the 33-bit clock, in [-2^32, 2^32). +pub(crate) fn wrap_delta(a: i64, b: i64) -> i64 { + let d = (a - b).rem_euclid(WRAP33); + if d >= WRAP33 / 2 { d - WRAP33 } else { d } +} + pub(crate) fn unwrap33(raw: u64, last: Option) -> i64 { - const M: i64 = 1 << 33; let raw = raw as i64; match last { None => raw, - Some(l) => { - let mut d = (raw - l).rem_euclid(M); - if d >= M / 2 { - d -= M; - } - l + d - } + Some(l) => l + wrap_delta(raw, l), } } diff --git a/crates/ec-mpegts/src/ps.rs b/crates/ec-mpegts/src/ps.rs index 584de33c..3f24f283 100644 --- a/crates/ec-mpegts/src/ps.rs +++ b/crates/ec-mpegts/src/ps.rs @@ -21,7 +21,7 @@ use ec_core::registry::{Demuxer, SeekMode, StreamInfo}; use ec_core::{Error, Packet, Result, Rounding, TimeBase, Timestamp}; use crate::codec::StreamKind; -use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33}; +use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33, wrap_delta}; use crate::psi::{EsEntry, descriptors}; use crate::track::{self, PesIn, Queued, TICKS, Track}; use crate::window::Window; @@ -180,15 +180,11 @@ struct Clock { impl Clock { /// Feeds a pack's SCR. `true` when it stepped back far enough to start a new epoch. fn feed(&mut self, raw: u64) -> bool { - const M: i64 = 1 << 33; let Some(last) = self.last_raw.replace(raw) else { self.cur_u = unwrap33(raw, Some(self.cur_u)); return false; }; - let mut d = (raw as i64 - last as i64).rem_euclid(M); - if d >= M / 2 { - d -= M; - } + let d = wrap_delta(raw as i64, last as i64); if !(-BACK..=FWD).contains(&d) { let last_t = self.cur_u + self.shift; self.cur_u = raw as i64; @@ -578,17 +574,10 @@ impl PsDemuxer { /// Timestamps of a PES header on the presented timeline. fn stamp(&self, pts: Option, dts: Option) -> (Option, Option) { - const M: i64 = 1 << 33; let t = |raw: u64| unwrap33(raw, Some(self.clock.cur_u)) + self.clock.shift; let p = pts.map(t); let d = match (dts, pts, p) { - (Some(d), Some(rp), Some(p)) => { - let mut delta = (d as i64 - rp as i64).rem_euclid(M); - if delta >= M / 2 { - delta -= M; - } - Some(p + delta) - } + (Some(d), Some(rp), Some(p)) => Some(p + wrap_delta(d as i64, rp as i64)), _ => None, }; (p, d)