1use rtflow_core::{
2 error::{Error, Result},
3 identity::StreamEpoch,
4};
5use rtflow_media::{AccessUnit, MediaDescription, MediaKind, TrackDescription};
6use std::{
7 collections::{HashMap, VecDeque},
8 sync::Arc,
9 time::Duration,
10};
11
12#[derive(Clone, Copy, Debug)]
13pub struct ContinuityPolicy {
14 pub preserve_rtp_timestamps: bool,
15 pub preserve_presentation_time: bool,
16 pub maximum_gap: Duration,
17}
18
19impl Default for ContinuityPolicy {
20 fn default() -> Self {
21 Self {
22 preserve_rtp_timestamps: true,
23 preserve_presentation_time: true,
24 maximum_gap: Duration::from_millis(500),
25 }
26 }
27}
28
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub struct TimelineSnapshot {
31 pub epoch: StreamEpoch,
32 pub tracks: usize,
33}
34
35struct TrackTimeline {
36 clock_rate: u32,
37 new_epoch: bool,
38 timestamp_offset: u32,
39 time_offset_ns: i128,
40 previous_input_timestamp: Option<u32>,
41 last_output_timestamp: Option<u32>,
42 last_output_pts: Option<Duration>,
43 estimated_step: Option<u32>,
44}
45
46pub struct TimelineNormalizer {
47 policy: ContinuityPolicy,
48 epoch: StreamEpoch,
49 tracks: HashMap<u8, TrackTimeline>,
50}
51
52impl TimelineNormalizer {
53 pub fn new(description: &MediaDescription, policy: ContinuityPolicy) -> Result<Self> {
54 if policy.maximum_gap == Duration::ZERO {
55 return Err(Error::Limit("proxy timeline maximum gap"));
56 }
57 let mut tracks = HashMap::with_capacity(description.tracks.len());
58 for track in &description.tracks {
59 if track.clock_rate == 0 {
60 return Err(Error::Media("proxy track clock rate is zero".into()));
61 }
62 tracks.insert(
63 track.id,
64 TrackTimeline {
65 clock_rate: track.clock_rate,
66 new_epoch: true,
67 timestamp_offset: 0,
68 time_offset_ns: 0,
69 previous_input_timestamp: None,
70 last_output_timestamp: None,
71 last_output_pts: None,
72 estimated_step: None,
73 },
74 );
75 }
76 Ok(Self {
77 policy,
78 epoch: StreamEpoch::new(0),
79 tracks,
80 })
81 }
82
83 pub fn begin_epoch(&mut self) -> StreamEpoch {
84 self.epoch = StreamEpoch::new(self.epoch.get().saturating_add(1));
85 for track in self.tracks.values_mut() {
86 track.new_epoch = true;
87 track.previous_input_timestamp = None;
88 }
89 self.epoch
90 }
91
92 pub fn normalize(&mut self, frame: &mut AccessUnit) -> Result<()> {
93 let track = self.tracks.get_mut(&frame.track_id).ok_or_else(|| {
94 Error::Media(format!("proxy timeline has no track {}", frame.track_id))
95 })?;
96 let input_timestamp = frame.rtp_timestamp;
97 if track.new_epoch {
98 if let Some(last_timestamp) = track.last_output_timestamp {
99 let maximum_step = duration_to_ticks(self.policy.maximum_gap, track.clock_rate);
100 let step = track
101 .estimated_step
102 .unwrap_or(1)
103 .clamp(1, maximum_step.max(1));
104 let next_timestamp = last_timestamp.wrapping_add(step);
105 track.timestamp_offset = next_timestamp.wrapping_sub(input_timestamp);
106 if let Some(last_pts) = track.last_output_pts {
107 let desired =
108 last_pts.saturating_add(ticks_to_duration(step, track.clock_rate));
109 track.time_offset_ns = duration_ns(desired) - duration_ns(frame.pts);
110 }
111 } else {
112 track.timestamp_offset = 0;
113 track.time_offset_ns = 0;
114 }
115 track.new_epoch = false;
116 } else if let Some(previous) = track.previous_input_timestamp {
117 let step = input_timestamp.wrapping_sub(previous);
118 let maximum_step = duration_to_ticks(self.policy.maximum_gap, track.clock_rate);
119 if step > 0 && step <= maximum_step {
120 track.estimated_step = Some(match track.estimated_step {
121 Some(estimate) => ((u64::from(estimate) * 7 + u64::from(step)) / 8) as u32,
122 None => step,
123 });
124 }
125 }
126
127 if self.policy.preserve_rtp_timestamps {
128 frame.rtp_timestamp = input_timestamp.wrapping_add(track.timestamp_offset);
129 }
130 if self.policy.preserve_presentation_time {
131 frame.pts = apply_time_offset(frame.pts, track.time_offset_ns);
132 frame.dts = frame
133 .dts
134 .map(|value| apply_time_offset(value, track.time_offset_ns));
135 }
136 track.previous_input_timestamp = Some(input_timestamp);
137 track.last_output_timestamp = Some(frame.rtp_timestamp);
138 track.last_output_pts = Some(frame.pts);
139 Ok(())
140 }
141
142 pub fn snapshot(&self) -> TimelineSnapshot {
143 TimelineSnapshot {
144 epoch: self.epoch,
145 tracks: self.tracks.len(),
146 }
147 }
148}
149
150#[derive(Clone, Copy, Debug)]
151pub struct StartupCacheConfig {
152 pub enabled: bool,
153 pub max_bytes: usize,
155 pub max_bytes_total: usize,
157 pub max_frames_per_track: usize,
158}
159
160impl Default for StartupCacheConfig {
161 fn default() -> Self {
162 Self {
163 enabled: true,
164 max_bytes: crate::DEFAULT_MAX_QUEUED_BYTES_PER_SESSION,
165 max_bytes_total: crate::DEFAULT_MAX_QUEUED_BYTES_PER_SESSION.saturating_mul(4),
166 max_frames_per_track: 256,
167 }
168 }
169}
170
171struct TrackCache {
172 kind: MediaKind,
173 frames: VecDeque<Arc<AccessUnit>>,
174 bytes: usize,
175 starts_with_keyframe: bool,
176}
177
178pub struct KeyframeCache {
179 config: StartupCacheConfig,
180 tracks: HashMap<u8, TrackCache>,
181}
182
183impl KeyframeCache {
184 pub fn new(description: &MediaDescription, config: StartupCacheConfig) -> Result<Self> {
185 if config.enabled
186 && (config.max_bytes == 0
187 || config.max_bytes_total == 0
188 || config.max_frames_per_track == 0)
189 {
190 return Err(Error::Limit("proxy startup cache"));
191 }
192 Ok(Self {
193 config,
194 tracks: description
195 .tracks
196 .iter()
197 .map(|track| {
198 (
199 track.id,
200 TrackCache {
201 kind: track.kind,
202 frames: VecDeque::new(),
203 bytes: 0,
204 starts_with_keyframe: false,
205 },
206 )
207 })
208 .collect(),
209 })
210 }
211
212 pub fn push(&mut self, frame: Arc<AccessUnit>) {
213 if !self.config.enabled {
214 return;
215 }
216 let Some(track) = self.tracks.get_mut(&frame.track_id) else {
217 return;
218 };
219 if track.kind == MediaKind::Video && frame.is_keyframe {
220 track.frames.clear();
221 track.bytes = 0;
222 track.starts_with_keyframe = true;
223 }
224 if track.kind == MediaKind::Video && !track.starts_with_keyframe {
225 return;
226 }
227 track.bytes = track.bytes.saturating_add(frame.data.len());
228 track.frames.push_back(frame);
229 while track.frames.len() > self.config.max_frames_per_track {
230 pop_front(track);
231 }
232 if track.bytes > self.config.max_bytes {
233 while track.bytes > self.config.max_bytes && !track.frames.is_empty() {
237 pop_front(track);
238 }
239 if track.kind == MediaKind::Video {
242 while track.frames.front().is_some_and(|frame| !frame.is_keyframe) {
243 pop_front(track);
244 }
245 }
246 if track.frames.is_empty() {
247 track.starts_with_keyframe = false;
248 }
249 }
250 self.enforce_total_budget();
251 }
252
253 fn enforce_total_budget(&mut self) {
255 if !self.config.enabled {
256 return;
257 }
258 let mut total: usize = self.tracks.values().map(|track| track.bytes).sum();
259 while total > self.config.max_bytes_total {
260 let Some(id) = self
261 .tracks
262 .iter()
263 .filter(|(_, track)| !track.frames.is_empty())
264 .max_by_key(|(_, track)| track.bytes)
265 .map(|(id, _)| *id)
266 else {
267 break;
268 };
269 let Some(track) = self.tracks.get_mut(&id) else {
270 break;
271 };
272 if let Some(frame) = track.frames.pop_front() {
273 track.bytes = track.bytes.saturating_sub(frame.data.len());
274 total = total.saturating_sub(frame.data.len());
275 }
276 if track.kind == MediaKind::Video {
277 while track.frames.front().is_some_and(|frame| !frame.is_keyframe) {
278 if let Some(frame) = track.frames.pop_front() {
279 track.bytes = track.bytes.saturating_sub(frame.data.len());
280 total = total.saturating_sub(frame.data.len());
281 }
282 }
283 }
284 if track.frames.is_empty() {
285 track.starts_with_keyframe = false;
286 }
287 }
288 }
289
290 pub fn snapshot(&self, track_id: u8) -> Vec<Arc<AccessUnit>> {
291 self.tracks
292 .get(&track_id)
293 .map(|track| track.frames.iter().cloned().collect())
294 .unwrap_or_default()
295 }
296
297 pub fn snapshot_all(&self) -> Vec<Arc<AccessUnit>> {
298 let mut frames = self
299 .tracks
300 .values()
301 .flat_map(|track| track.frames.iter().cloned())
302 .collect::<Vec<_>>();
303 frames.sort_by_key(|frame| (frame.pts, frame.track_id));
304 frames
305 }
306
307 pub fn clear(&mut self) {
308 for track in self.tracks.values_mut() {
309 track.frames.clear();
310 track.bytes = 0;
311 track.starts_with_keyframe = false;
312 }
313 }
314
315 pub fn usage(&self) -> (usize, usize) {
316 self.tracks.values().fold((0, 0), |(frames, bytes), track| {
317 (frames + track.frames.len(), bytes + track.bytes)
318 })
319 }
320}
321
322#[derive(Clone, Debug, Default, Eq, PartialEq)]
323pub struct TrackCompatibility {
324 pub compatible: bool,
325 pub differences: Vec<String>,
326}
327
328impl TrackCompatibility {
329 pub fn compare(expected: &MediaDescription, candidate: &MediaDescription) -> Self {
330 let mut differences = Vec::new();
331 if expected.tracks.len() != candidate.tracks.len() {
332 differences.push(format!(
333 "track count changed from {} to {}",
334 expected.tracks.len(),
335 candidate.tracks.len()
336 ));
337 }
338 for expected_track in &expected.tracks {
339 match candidate.track(expected_track.id) {
340 Some(candidate_track) => {
341 compare_track(expected_track, candidate_track, &mut differences)
342 }
343 None => differences.push(format!("track {} is missing", expected_track.id)),
344 }
345 }
346 Self {
347 compatible: differences.is_empty(),
348 differences,
349 }
350 }
351}
352
353fn compare_track(expected: &TrackDescription, candidate: &TrackDescription, out: &mut Vec<String>) {
354 if expected.codec != candidate.codec {
355 out.push(format!("track {} codec changed", expected.id));
356 }
357 if expected.clock_rate != candidate.clock_rate {
358 out.push(format!("track {} clock rate changed", expected.id));
359 }
360 if expected.channels != candidate.channels {
361 out.push(format!("track {} channel count changed", expected.id));
362 }
363}
364
365fn pop_front(track: &mut TrackCache) {
366 if let Some(frame) = track.frames.pop_front() {
367 track.bytes = track.bytes.saturating_sub(frame.data.len());
368 }
369}
370
371fn duration_to_ticks(duration: Duration, clock_rate: u32) -> u32 {
372 rtflow_media::clock::duration_to_ticks(duration, clock_rate).clamp(1, u64::from(u32::MAX))
373 as u32
374}
375
376fn ticks_to_duration(ticks: u32, clock_rate: u32) -> Duration {
377 rtflow_media::clock::ticks_to_duration(u64::from(ticks), clock_rate)
378}
379
380fn duration_ns(value: Duration) -> i128 {
381 value.as_nanos().min(i128::MAX as u128) as i128
382}
383
384fn apply_time_offset(value: Duration, offset_ns: i128) -> Duration {
385 let adjusted = duration_ns(value).saturating_add(offset_ns).max(0) as u128;
386 Duration::from_nanos(adjusted.min(u128::from(u64::MAX)) as u64)
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392 use bytes::Bytes;
393 use rtflow_media::{Codec, MediaKind, TrackDescription};
394 use std::sync::Arc;
395
396 fn description(codec: Codec) -> MediaDescription {
397 MediaDescription {
398 session_name: Arc::from("proxy"),
399 tracks: vec![TrackDescription {
400 id: 0,
401 kind: MediaKind::Video,
402 codec,
403 clock_rate: rtflow_media::clock::VIDEO_CLOCK_RATE,
404 channels: None,
405 payload_type: 96,
406 fmtp: None,
407 control: Arc::from("trackID=0"),
408 width: None,
409 height: None,
410 frame_rate: None,
411 crypto: None,
412 direction: None,
413 ptime: None,
414 rtcp: None,
415 bandwidth_as: None,
416 rtx: None,
417 }],
418 connection: None,
419 }
420 }
421
422 fn frame(timestamp: u32, pts_ms: u64, keyframe: bool, data: Bytes) -> AccessUnit {
423 AccessUnit {
424 nal_offsets: None,
425 track_id: 0,
426 codec: Codec::H264,
427 pts: Duration::from_millis(pts_ms),
428 dts: None,
429 rtp_timestamp: timestamp,
430 is_keyframe: keyframe,
431 data,
432 }
433 }
434
435 #[test]
436 fn reconnect_keeps_timestamp_and_pts_monotonic() {
437 let media = description(Codec::H264);
438 let mut timeline = TimelineNormalizer::new(&media, ContinuityPolicy::default()).unwrap();
439 timeline.begin_epoch();
440 let mut first = frame(9_000, 100, true, Bytes::from_static(b"a"));
441 let mut second = frame(12_000, 133, false, Bytes::from_static(b"b"));
442 timeline.normalize(&mut first).unwrap();
443 timeline.normalize(&mut second).unwrap();
444 assert_eq!((first.rtp_timestamp, second.rtp_timestamp), (9_000, 12_000));
445
446 timeline.begin_epoch();
447 let mut restarted = frame(0, 0, true, Bytes::from_static(b"c"));
448 timeline.normalize(&mut restarted).unwrap();
449 assert_eq!(restarted.rtp_timestamp, 15_000);
450 assert!(restarted.pts > second.pts);
451 assert_eq!(timeline.snapshot().epoch, StreamEpoch::new(2));
452 }
453
454 #[test]
455 fn cache_starts_at_keyframe_and_shares_payload_storage() {
456 let media = description(Codec::H264);
457 let mut cache = KeyframeCache::new(&media, StartupCacheConfig::default()).unwrap();
458 cache.push(std::sync::Arc::new(frame(
459 1,
460 0,
461 false,
462 Bytes::from_static(b"ignored"),
463 )));
464 assert!(cache.snapshot(0).is_empty());
465
466 let key_data = Bytes::from_static(b"key");
467 let pointer = key_data.as_ptr();
468 cache.push(std::sync::Arc::new(frame(2, 33, true, key_data)));
469 cache.push(std::sync::Arc::new(frame(
470 3,
471 66,
472 false,
473 Bytes::from_static(b"delta"),
474 )));
475 let snapshot = cache.snapshot(0);
476 assert_eq!(snapshot.len(), 2);
477 assert!(snapshot[0].is_keyframe);
478 assert_eq!(snapshot[0].data.as_ptr(), pointer);
479 }
480
481 #[test]
482 fn incompatible_codec_is_reported_before_failover() {
483 let expected = description(Codec::H264);
484 let candidate = description(Codec::H265);
485 let result = TrackCompatibility::compare(&expected, &candidate);
486 assert!(!result.compatible);
487 assert_eq!(result.differences, vec!["track 0 codec changed"]);
488 }
489}