Skip to main content

hyprstream_tui/
cast_player.rs

1//! Asciicast v2 parser and timed playback engine.
2//!
3//! Parses asciicast v2 files (JSON header + newline-delimited event tuples)
4//! and provides a `CastPlayer` that drives an `avt::Vt` virtual terminal
5//! with timed event replay, seeking, and pause.
6
7use serde::Deserialize;
8
9/// Strip OSC, DCS, APC, PM sequences from event data.
10///
11/// These have no role in terminal animation playback and could inject
12/// title-sets, clipboard writes, or other side-effects if a cast file
13/// were malicious.
14fn strip_dangerous_sequences(data: String) -> String {
15    // Fast path: vast majority of events contain none of these prefixes.
16    if !data.contains("\x1b]")
17        && !data.contains("\x1bP")
18        && !data.contains("\x1b_")
19        && !data.contains("\x1b^")
20    {
21        return data;
22    }
23    let mut out = String::with_capacity(data.len());
24    let mut chars = data.chars().peekable();
25    while let Some(c) = chars.next() {
26        if c == '\x1b' {
27            match chars.peek().copied() {
28                Some(']') | Some('P') | Some('_') | Some('^') => {
29                    chars.next(); // consume the introducer
30                                  // Skip until BEL or ST (\x1b\\)
31                    let mut prev = '\0';
32                    for ch in chars.by_ref() {
33                        if ch == '\x07' {
34                            break;
35                        }
36                        if prev == '\x1b' && ch == '\\' {
37                            break;
38                        }
39                        prev = ch;
40                    }
41                    // drop the sequence — push nothing
42                }
43                _ => out.push(c),
44            }
45        } else {
46            out.push(c);
47        }
48    }
49    out
50}
51
52/// Asciicast v2 header.
53#[derive(Debug, Deserialize)]
54pub struct CastHeader {
55    pub version: u32,
56    pub width: u32,
57    pub height: u32,
58    #[serde(default)]
59    pub title: Option<String>,
60}
61
62/// A single output event: `[time, "o", data]`.
63#[derive(Debug, Clone)]
64pub struct CastEvent {
65    pub time_ms: u64,
66    pub data: String,
67}
68
69/// Parsed cast file ready for playback.
70#[derive(Debug)]
71pub struct CastFile {
72    pub header: CastHeader,
73    pub events: Vec<CastEvent>,
74    pub duration_ms: u64,
75}
76
77/// Manages timed replay of a cast file.
78pub struct CastPlayer {
79    pub cast: CastFile,
80    pub elapsed_ms: u64,
81    pub event_index: usize,
82    pub paused: bool,
83    vt: avt::Vt,
84}
85
86impl CastFile {
87    /// Parse asciicast v2 content (JSON header + newline-delimited event lines).
88    pub fn parse(content: &str) -> Result<Self, String> {
89        Self::parse_with_idle_limit(content, None)
90    }
91
92    /// Parse with an optional idle time limit (in ms).
93    /// Gaps between consecutive events exceeding the limit are compressed.
94    pub fn parse_with_idle_limit(
95        content: &str,
96        idle_limit_ms: Option<u64>,
97    ) -> Result<Self, String> {
98        let mut lines = content.lines();
99
100        let header_line = lines.next().ok_or("Empty cast file")?;
101        let header: CastHeader =
102            serde_json::from_str(header_line).map_err(|e| format!("Invalid header: {}", e))?;
103
104        if header.version != 2 {
105            return Err(format!("Unsupported version: {}", header.version));
106        }
107
108        let mut events = Vec::new();
109
110        for line in lines {
111            let line = line.trim();
112            if line.is_empty() {
113                continue;
114            }
115
116            let (time_secs, event_type, data): (f64, String, String) =
117                serde_json::from_str(line).map_err(|e| format!("Invalid event: {}", e))?;
118
119            if event_type != "o" {
120                continue;
121            }
122
123            let time_ms = (time_secs * 1000.0) as u64;
124            events.push(CastEvent {
125                time_ms,
126                data: strip_dangerous_sequences(data),
127            });
128        }
129
130        // Apply idle time limit: cap gaps between consecutive events
131        if let Some(limit) = idle_limit_ms {
132            let mut offset: u64 = 0;
133            for i in 1..events.len() {
134                let gap = events[i]
135                    .time_ms
136                    .saturating_sub(events[i - 1].time_ms + offset);
137                if gap > limit {
138                    offset += gap - limit;
139                }
140                events[i].time_ms = events[i].time_ms.saturating_sub(offset);
141            }
142        }
143
144        let duration_ms = events.last().map(|e| e.time_ms).unwrap_or(0);
145
146        Ok(CastFile {
147            header,
148            events,
149            duration_ms,
150        })
151    }
152}
153
154impl CastPlayer {
155    pub fn new(cast: CastFile) -> Self {
156        let vt = avt::Vt::builder()
157            .size(cast.header.width as usize, cast.header.height as usize)
158            .scrollback_limit(0)
159            .build();
160
161        CastPlayer {
162            cast,
163            elapsed_ms: 0,
164            event_index: 0,
165            paused: false,
166            vt,
167        }
168    }
169
170    /// Advance playback by delta_ms. Returns true if new output was produced.
171    pub fn tick(&mut self, delta_ms: u64) -> bool {
172        if self.paused {
173            return false;
174        }
175
176        self.elapsed_ms += delta_ms;
177        let mut produced = false;
178
179        while self.event_index < self.cast.events.len() {
180            let event = &self.cast.events[self.event_index];
181            if event.time_ms <= self.elapsed_ms {
182                self.vt.feed_str(&event.data);
183                self.event_index += 1;
184                produced = true;
185            } else {
186                break;
187            }
188        }
189
190        produced
191    }
192
193    /// Access the virtual terminal for styled rendering.
194    pub fn vt(&self) -> &avt::Vt {
195        &self.vt
196    }
197
198    /// Returns true if all events have been played.
199    pub fn is_finished(&self) -> bool {
200        self.event_index >= self.cast.events.len() && self.elapsed_ms >= self.cast.duration_ms
201    }
202
203    pub fn elapsed_ms(&self) -> u64 {
204        self.elapsed_ms
205    }
206    pub fn duration_ms(&self) -> u64 {
207        self.cast.duration_ms
208    }
209    pub fn event_index(&self) -> usize {
210        self.event_index
211    }
212    pub fn event_count(&self) -> usize {
213        self.cast.events.len()
214    }
215
216    pub fn toggle_pause(&mut self) {
217        self.paused = !self.paused;
218    }
219
220    pub fn seek_forward(&mut self, ms: u64) {
221        if self.paused {
222            self.elapsed_ms += ms;
223            self.replay_to(self.elapsed_ms);
224            self.paused = true;
225        } else {
226            self.elapsed_ms += ms;
227        }
228    }
229
230    pub fn seek_backward(&mut self, ms: u64) {
231        let target = self.elapsed_ms.saturating_sub(ms);
232        self.replay_to(target);
233    }
234
235    /// Seek to an absolute time position, replaying from start.
236    pub fn seek_to(&mut self, target_ms: u64) {
237        self.replay_to(target_ms);
238    }
239
240    /// Replay from the beginning to a target time, rebuilding vt state.
241    fn replay_to(&mut self, target_ms: u64) {
242        let was_paused = self.paused;
243        self.vt = avt::Vt::builder()
244            .size(
245                self.cast.header.width as usize,
246                self.cast.header.height as usize,
247            )
248            .scrollback_limit(0)
249            .build();
250        self.event_index = 0;
251        self.elapsed_ms = 0;
252        self.paused = false;
253        self.tick(target_ms);
254        self.paused = was_paused;
255    }
256
257    pub fn progress(&self) -> f64 {
258        if self.cast.duration_ms == 0 {
259            return 0.0;
260        }
261        (self.elapsed_ms as f64 / self.cast.duration_ms as f64).min(1.0)
262    }
263
264    pub fn elapsed_display(&self) -> String {
265        format_time(self.elapsed_ms)
266    }
267
268    pub fn duration_display(&self) -> String {
269        format_time(self.cast.duration_ms)
270    }
271}
272
273/// Format milliseconds as `MM:SS`.
274pub fn format_time(ms: u64) -> String {
275    let total_secs = ms / 1000;
276    let mins = total_secs / 60;
277    let secs = total_secs % 60;
278    format!("{:02}:{:02}", mins, secs)
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    const SAMPLE_CAST: &str = r#"{"version": 2, "width": 80, "height": 24, "title": "test"}
286[0.0, "o", "Hello "]
287[0.5, "o", "World"]
288[1.0, "o", "\r\nLine 2"]
289[5.0, "o", "\r\nAfter gap"]"#;
290
291    #[test]
292    fn test_parse_basic() {
293        let cast = CastFile::parse(SAMPLE_CAST).unwrap();
294        assert_eq!(cast.header.width, 80);
295        assert_eq!(cast.header.height, 24);
296        assert_eq!(cast.events.len(), 4);
297        assert_eq!(cast.duration_ms, 5000);
298    }
299
300    #[test]
301    fn test_playback() {
302        let cast = CastFile::parse(SAMPLE_CAST).unwrap();
303        let mut player = CastPlayer::new(cast);
304        player.tick(600);
305
306        let text: String = player.vt().text().join("\n");
307        assert!(text.contains("Hello World"));
308    }
309
310    #[test]
311    fn test_idle_limit() {
312        let cast_full = CastFile::parse(SAMPLE_CAST).unwrap();
313        let full_dur = cast_full.duration_ms;
314
315        let cast_limited = CastFile::parse_with_idle_limit(SAMPLE_CAST, Some(500)).unwrap();
316        let limited_dur = cast_limited.duration_ms;
317
318        assert!(limited_dur < full_dur);
319    }
320
321    #[test]
322    fn test_seek() {
323        let cast = CastFile::parse(SAMPLE_CAST).unwrap();
324        let mut player = CastPlayer::new(cast);
325        player.tick(5000);
326        assert!(player.is_finished());
327
328        player.seek_backward(4000);
329        assert!(!player.is_finished());
330    }
331
332    #[test]
333    fn test_strip_dangerous() {
334        let input = "hello\x1b]0;evil title\x07world".to_string();
335        let result = strip_dangerous_sequences(input);
336        assert_eq!(result, "helloworld");
337    }
338}