diff --git a/crates/ec-mpegts/src/demux.rs b/crates/ec-mpegts/src/demux.rs index 4e2f1af0..be5130f8 100644 --- a/crates/ec-mpegts/src/demux.rs +++ b/crates/ec-mpegts/src/demux.rs @@ -4,11 +4,11 @@ use std::collections::{HashMap, VecDeque}; use std::io::{Read, Seek}; use ec_core::registry::{Demuxer, SeekMode, StreamInfo}; -use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp}; +use ec_core::{Error, Packet, Result, Rounding, TimeBase, Timestamp}; -use crate::codec::{StreamKind, annexb_to_length_prefixed}; +use crate::codec::StreamKind; use crate::psi::{self, EsEntry, PatEntry, Pmt, SectionBuf}; -use crate::track::{MAX_PES, PesIn, Queued, TICKS, Track}; +use crate::track::{self, MAX_PES, PesIn, Queued, TICKS, Track}; use crate::ts::{self, Layout, SYNC, TS_LEN}; use crate::window::Window; @@ -66,18 +66,18 @@ enum Cc { Gap, } +const WRAP33: i64 = 1 << 33; + +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), } } @@ -698,7 +698,7 @@ impl TsDemuxer { for t in &mut self.tracks { t.start_time = t.min_pts; } - self.assign_streams(); + track::assign_streams(&mut self.tracks, &mut self.streams); self.frozen = true; let tail = self.scan_tail(); self.frozen = false; @@ -707,31 +707,6 @@ impl TsDemuxer { Ok(()) } - fn assign_streams(&mut self) { - for ti in 0..self.tracks.len() { - self.make_stream(ti); - } - } - - /// Gives track `ti` a stream index when it can be described. Returns it. - fn make_stream(&mut self, ti: usize) -> Option { - if let Some(s) = self.tracks[ti].stream { - return Some(s); - } - let index = self.streams.len() as u32; - let mut info = self.tracks[ti].stream_info(index)?; - if !self - .streams - .iter() - .any(|s| s.params.codec.media_type() == info.params.codec.media_type() && s.default) - { - info.default = true; - } - self.tracks[ti].stream = Some(index); - self.streams.push(info); - Some(index) - } - fn scan_tail(&mut self) -> Result<()> { let size = self.layout.size as u64; let mut win: u64 = 4 << 20; @@ -796,36 +771,6 @@ impl TsDemuxer { } } - fn make_packet(&mut self, q: Queued) -> Option { - let ti = q.track; - let stream = match self.tracks[ti].stream { - Some(s) => s, - None => { - if self.tracks[ti].start_time.is_none() { - self.tracks[ti].start_time = self.tracks[ti].min_pts; - } - self.make_stream(ti)? - } - }; - let kind = &self.tracks[ti].kind; - let data = if self.framing == VideoFraming::LengthPrefixed && kind.is_annexb_video() { - annexb_to_length_prefixed(&q.data, 4) - } else { - q.data - }; - let mut p = Packet::new(stream, self.time_base(), data); - p.pts = q.pts; - p.dts = q.dts; - p.duration = q.dur; - p.flags = PacketFlags { - keyframe: q.key, - corrupt: q.corrupt, - ..PacketFlags::default() - }; - self.last_off = q.off; - Some(p) - } - // ----- seeking ---------------------------------------------------------------- fn align(&self, off: u64) -> u64 { @@ -906,7 +851,11 @@ impl Demuxer for TsDemuxer { let Some(q) = self.pump()? else { return Err(Error::Eof); }; - if let Some(p) = self.make_packet(q) { + let off = q.off; + if let Some(p) = + track::make_packet(&mut self.tracks, &mut self.streams, self.framing, q) + { + self.last_off = off; return Ok(p); } } diff --git a/crates/ec-mpegts/src/ps.rs b/crates/ec-mpegts/src/ps.rs index c1595d68..8c71fc6f 100644 --- a/crates/ec-mpegts/src/ps.rs +++ b/crates/ec-mpegts/src/ps.rs @@ -18,14 +18,22 @@ use std::collections::{HashMap, VecDeque}; use std::io::{Read, Seek}; use ec_core::registry::{Demuxer, SeekMode, StreamInfo}; -use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp}; +use ec_core::{Error, Packet, Result, Rounding, TimeBase, Timestamp}; -use crate::codec::{StreamKind, annexb_to_length_prefixed}; -use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33}; +use crate::codec::StreamKind; +use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33, wrap_delta}; use crate::psi::{EsEntry, descriptors}; -use crate::track::{PesIn, Queued, TICKS, Track}; +use crate::track::{self, PesIn, Queued, TICKS, Track}; use crate::window::Window; +mod clock; +mod epochs; +mod es_index; + +use clock::Clock; +use epochs::Epoch; +use es_index::{EsIndex, Pic}; + const MAX_TRACKS: usize = 128; const PROBE_BYTES: u64 = 32 << 20; /// Files up to this size are walked completely at open to find SCR discontinuities. @@ -168,70 +176,6 @@ fn es_start(head: &[u8]) -> Option { /// A PSM entry: stream type and its descriptors (tag, body). type PsmEntry = (u8, Vec<(u8, Vec)>); -/// The pack clock unwrapped into a continuous `u` (33-bit wraps removed) and the shift -/// that keeps the presented timeline monotonic over SCR resets: `T = u + shift`. -#[derive(Debug, Clone, Copy)] -struct Clock { - last_raw: Option, - cur_u: i64, - shift: i64, -} - -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; - } - if !(-BACK..=FWD).contains(&d) { - let last_t = self.cur_u + self.shift; - self.cur_u = raw as i64; - self.shift = last_t - self.cur_u; - true - } else { - self.cur_u += d; - false - } - } -} - -/// A stretch of the file with one SCR timeline. -#[derive(Debug, Clone, Copy)] -struct Epoch { - off: u64, - shift: i64, - /// `u` of the first pack. - base: i64, -} - -// --------------------------------------------------------------------------- -// Raw video elementary streams: the picture index -// --------------------------------------------------------------------------- - -struct Pic { - off: u64, - key: bool, - pts: i64, - dts: i64, -} - -/// Every picture of a raw stream with timestamps made from the frame rate: pictures are -/// grouped (a GOP or sequence header, or an anchor whose temporal reference does not -/// advance, starts a group), the display index is the group's frame count so far plus -/// the temporal reference, `pts` is that index and `dts` the decode index less the -/// reordering depth, both in frame durations. -struct EsIndex { - pics: Vec, - start: i64, - end: i64, -} - // --------------------------------------------------------------------------- // The demuxer // --------------------------------------------------------------------------- @@ -578,17 +522,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) @@ -959,7 +896,7 @@ impl PsDemuxer { for t in &mut self.tracks { t.start_time = t.min_pts; } - self.assign_streams(); + track::assign_streams(&mut self.tracks, &mut self.streams); self.frozen = true; let tail = self.scan_tail(); self.frozen = false; @@ -968,30 +905,6 @@ impl PsDemuxer { Ok(()) } - fn assign_streams(&mut self) { - for ti in 0..self.tracks.len() { - self.make_stream(ti); - } - } - - fn make_stream(&mut self, ti: usize) -> Option { - if let Some(s) = self.tracks[ti].stream { - return Some(s); - } - let index = self.streams.len() as u32; - let mut info = self.tracks[ti].stream_info(index)?; - if !self - .streams - .iter() - .any(|s| s.params.codec.media_type() == info.params.codec.media_type() && s.default) - { - info.default = true; - } - self.tracks[ti].stream = Some(index); - self.streams.push(info); - Some(index) - } - fn scan_tail(&mut self) -> Result<()> { let mut win: u64 = 4 << 20; loop { @@ -1078,36 +991,6 @@ impl PsDemuxer { } } - fn make_packet(&mut self, q: Queued) -> Option { - let ti = q.track; - let stream = match self.tracks[ti].stream { - Some(s) => s, - None => { - if self.tracks[ti].start_time.is_none() { - self.tracks[ti].start_time = self.tracks[ti].min_pts; - } - self.make_stream(ti)? - } - }; - let kind = &self.tracks[ti].kind; - let data = if self.framing == VideoFraming::LengthPrefixed && kind.is_annexb_video() { - annexb_to_length_prefixed(&q.data, 4) - } else { - q.data - }; - let mut p = Packet::new(stream, self.time_base(), data); - p.pts = q.pts; - p.dts = q.dts; - p.duration = q.dur; - p.flags = PacketFlags { - keyframe: q.key, - corrupt: q.corrupt, - ..PacketFlags::default() - }; - self.last_off = q.off; - Some(p) - } - // ----- seeking ------------------------------------------------------------------------------ fn time_at(&mut self, off: u64, ti: usize) -> Result> { @@ -1291,7 +1174,7 @@ impl PsDemuxer { self.tracks[0].start_time = Some(ix.start); self.duration = Some(ix.end - ix.start); self.es = Some(ix); - self.assign_streams(); + track::assign_streams(&mut self.tracks, &mut self.streams); if let Some(s) = self.streams.first_mut() { s.duration = self.duration; } @@ -1533,7 +1416,11 @@ impl Demuxer for PsDemuxer { let Some(q) = self.pump()? else { return Err(Error::Eof); }; - if let Some(p) = self.make_packet(q) { + let off = q.off; + if let Some(p) = + track::make_packet(&mut self.tracks, &mut self.streams, self.framing, q) + { + self.last_off = off; return Ok(p); } } diff --git a/crates/ec-mpegts/src/ps/clock.rs b/crates/ec-mpegts/src/ps/clock.rs new file mode 100644 index 00000000..16dac7bd --- /dev/null +++ b/crates/ec-mpegts/src/ps/clock.rs @@ -0,0 +1,31 @@ +use super::{BACK, FWD}; +use crate::demux::{unwrap33, wrap_delta}; + +/// The pack clock unwrapped into a continuous `u` (33-bit wraps removed) and the shift +/// that keeps the presented timeline monotonic over SCR resets: `T = u + shift`. +#[derive(Debug, Clone, Copy)] +pub(super) struct Clock { + pub(super) last_raw: Option, + pub(super) cur_u: i64, + pub(super) shift: i64, +} + +impl Clock { + /// Feeds a pack's SCR. `true` when it stepped back far enough to start a new epoch. + pub(super) fn feed(&mut self, raw: u64) -> bool { + let Some(last) = self.last_raw.replace(raw) else { + self.cur_u = unwrap33(raw, Some(self.cur_u)); + return false; + }; + 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; + self.shift = last_t - self.cur_u; + true + } else { + self.cur_u += d; + false + } + } +} diff --git a/crates/ec-mpegts/src/ps/epochs.rs b/crates/ec-mpegts/src/ps/epochs.rs new file mode 100644 index 00000000..b2aaad87 --- /dev/null +++ b/crates/ec-mpegts/src/ps/epochs.rs @@ -0,0 +1,8 @@ +/// A stretch of the file with one SCR timeline. +#[derive(Debug, Clone, Copy)] +pub(super) struct Epoch { + pub(super) off: u64, + pub(super) shift: i64, + /// `u` of the first pack. + pub(super) base: i64, +} diff --git a/crates/ec-mpegts/src/ps/es_index.rs b/crates/ec-mpegts/src/ps/es_index.rs new file mode 100644 index 00000000..2aa7fd52 --- /dev/null +++ b/crates/ec-mpegts/src/ps/es_index.rs @@ -0,0 +1,17 @@ +pub(super) struct Pic { + pub(super) off: u64, + pub(super) key: bool, + pub(super) pts: i64, + pub(super) dts: i64, +} + +/// Every picture of a raw stream with timestamps made from the frame rate: pictures are +/// grouped (a GOP or sequence header, or an anchor whose temporal reference does not +/// advance, starts a group), the display index is the group's frame count so far plus +/// the temporal reference, `pts` is that index and `dts` the decode index less the +/// reordering depth, both in frame durations. +pub(super) struct EsIndex { + pub(super) pics: Vec, + pub(super) start: i64, + pub(super) end: i64, +} diff --git a/crates/ec-mpegts/src/track.rs b/crates/ec-mpegts/src/track.rs index fc6f59e9..63718203 100644 --- a/crates/ec-mpegts/src/track.rs +++ b/crates/ec-mpegts/src/track.rs @@ -4,14 +4,15 @@ use std::collections::VecDeque; use ec_core::{ - AudioParameters, ChannelLayout, CodecId, CodecParameters, MediaParameters, PixelFormat, - SampleFormat, StreamInfo, TimeBase, registry::VideoParameters, + AudioParameters, ChannelLayout, CodecId, CodecParameters, MediaParameters, Packet, PacketFlags, + PixelFormat, SampleFormat, StreamInfo, TimeBase, registry::VideoParameters, }; use crate::codec::{ - self, FrameHdr, Framing, LpcmHeader, StreamKind, build_avcc, build_hvcc, frame_header, - header_lookahead, scan_au, + self, FrameHdr, Framing, LpcmHeader, StreamKind, annexb_to_length_prefixed, build_avcc, + build_hvcc, frame_header, header_lookahead, scan_au, }; +use crate::demux::VideoFraming; use crate::psi::EsEntry; use ec_truehd::{AccessUnitHeader, frame_length}; @@ -972,3 +973,65 @@ fn pixel_format(chroma: u8, depth: u8) -> Option { _ => None, } } + +pub(crate) fn assign_streams(tracks: &mut [Track], streams: &mut Vec) { + for ti in 0..tracks.len() { + make_stream(tracks, streams, ti); + } +} + +/// Gives track `ti` a stream index when it can be described. Returns it. +pub(crate) fn make_stream( + tracks: &mut [Track], + streams: &mut Vec, + ti: usize, +) -> Option { + if let Some(s) = tracks[ti].stream { + return Some(s); + } + let index = streams.len() as u32; + let mut info = tracks[ti].stream_info(index)?; + if !streams + .iter() + .any(|s| s.params.codec.media_type() == info.params.codec.media_type() && s.default) + { + info.default = true; + } + tracks[ti].stream = Some(index); + streams.push(info); + Some(index) +} + +pub(crate) fn make_packet( + tracks: &mut [Track], + streams: &mut Vec, + framing: VideoFraming, + q: Queued, +) -> Option { + let ti = q.track; + let stream = match tracks[ti].stream { + Some(s) => s, + None => { + if tracks[ti].start_time.is_none() { + tracks[ti].start_time = tracks[ti].min_pts; + } + make_stream(tracks, streams, ti)? + } + }; + let kind = &tracks[ti].kind; + let data = if framing == VideoFraming::LengthPrefixed && kind.is_annexb_video() { + annexb_to_length_prefixed(&q.data, 4) + } else { + q.data + }; + let mut p = Packet::new(stream, TimeBase::new(1, TICKS), data); + p.pts = q.pts; + p.dts = q.dts; + p.duration = q.dur; + p.flags = PacketFlags { + keyframe: q.key, + corrupt: q.corrupt, + ..PacketFlags::default() + }; + Some(p) +}