t-rec 0.9.0-preview2

Blazingly fast terminal recorder that generates animated gif images for the web written in rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use anyhow::{Context, Result};
use image::save_buffer;
use image::ColorType::Rgba8;
#[cfg(feature = "cli")]
use log::{debug, error};
use std::borrow::Borrow;
use std::ops::{Add, Sub};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tempfile::TempDir;
use tokio::sync::broadcast::error::TryRecvError;
use tokio::sync::broadcast::Receiver;

#[cfg(feature = "cli")]
use super::event_router::LifecycleEvent;
use super::event_router::{CaptureEvent, Event};
#[cfg(feature = "cli")]
use super::screenshot::screenshot_file_name;
#[cfg(feature = "cli")]
use super::screenshot::ScreenshotInfo;
use super::utils::{file_name_for, IMG_EXT};
use super::{ImageOnHeap, PlatformApi, WindowId};

/// Configuration and shared state for the capture thread.
///
/// Groups all parameters needed for frame capture, making the API cleaner
/// and easier to extend with new options.
pub struct CaptureContext {
    /// Window ID to capture
    pub win_id: WindowId,
    /// Shared list to store frame timestamps
    pub time_codes: Arc<Mutex<Vec<u128>>>,
    /// Directory for saving frames
    pub tempdir: Arc<Mutex<TempDir>>,
    /// If true, save all frames without idle detection
    pub natural: bool,
    /// Maximum pause duration to preserve (None = skip all identical frames)
    pub idle_pause: Option<Duration>,
    /// Capture framerate (4-15 fps)
    pub fps: u8,
    /// List of captured screenshots (CLI only)
    #[cfg(feature = "cli")]
    pub screenshots: Option<Arc<Mutex<Vec<ScreenshotInfo>>>>,
}

impl CaptureContext {
    /// Calculate frame interval from fps, this is not used in tests
    pub fn frame_interval(&self) -> Duration {
        if cfg!(test) {
            Duration::from_millis(10) // Fast for testing
        } else {
            Duration::from_millis(1000 / self.fps as u64)
        }
    }
}

/// Photographer actor: captures frames periodically, handles idle detection.
pub fn capture_thread(
    mut rx: Receiver<Event>,
    api: impl PlatformApi,
    ctx: CaptureContext,
) -> Result<()> {
    // Wait for Start event before beginning capture
    #[cfg(feature = "cli")]
    loop {
        match rx.blocking_recv() {
            Ok(Event::Capture(CaptureEvent::Start)) => break,
            Ok(Event::Capture(CaptureEvent::Stop))
            | Ok(Event::Lifecycle(LifecycleEvent::Shutdown)) => return Ok(()),
            Ok(_) => continue, // Ignore Flash events and Screenshot in wait-for-start phase
            Err(_) => return Ok(()),
        }
    }
    #[cfg(not(feature = "cli"))]
    match rx.blocking_recv() {
        Ok(Event::Capture(CaptureEvent::Start)) => {}
        Ok(Event::Capture(CaptureEvent::Stop)) | Err(_) => return Ok(()),
    }

    let duration = ctx.frame_interval();
    let start = Instant::now();

    // Total idle time skipped (subtracted from timestamps to prevent gaps)
    let mut idle_duration = Duration::from_millis(0);

    // How long current identical frames have lasted
    let mut current_idle_period = Duration::from_millis(0);

    let mut last_frame: Option<ImageOnHeap> = None;
    let mut last_now = Instant::now();
    loop {
        // Wait for remaining time to hit target frame interval
        let elapsed = last_now.elapsed();
        if let Some(remaining) = duration.checked_sub(elapsed) {
            std::thread::sleep(remaining);
        }

        #[cfg(feature = "cli")]
        let screenshot_event_tc = match rx.try_recv() {
            Ok(Event::Capture(CaptureEvent::Stop))
            | Ok(Event::Lifecycle(LifecycleEvent::Shutdown)) => break,
            Ok(Event::Capture(CaptureEvent::Start)) => continue,
            Ok(Event::Capture(CaptureEvent::Screenshot { timecode_ms })) => {
                debug!("Received Screenshot event with timecode {}", timecode_ms);
                Some(timecode_ms)
            }
            Ok(_) => None, // Ignore Flash events
            Err(TryRecvError::Closed) => break,
            Err(TryRecvError::Empty) => None,
            Err(_) => None,
        };
        #[cfg(not(feature = "cli"))]
        let screenshot_event_tc: Option<u128> = match rx.try_recv() {
            Ok(Event::Capture(CaptureEvent::Stop)) => break,
            Ok(Event::Capture(CaptureEvent::Start)) => continue,
            Err(TryRecvError::Closed) => break,
            Err(TryRecvError::Empty) => None,
            Err(_) => None,
        };
        let now = Instant::now();

        // Calculate timestamp with skipped idle time removed
        let effective_now = now.sub(idle_duration);
        let tc = effective_now.saturating_duration_since(start).as_millis();

        let image = api.capture_window_screenshot(ctx.win_id)?;
        let frame_duration = now.duration_since(last_now);

        // Handle screenshot if triggered by event (CLI only)
        #[cfg(feature = "cli")]
        if let Some(screenshot_tc) = screenshot_event_tc {
            debug!("Taking screenshot at tc={}", screenshot_tc);
            if let Err(e) = save_screenshot(&image, screenshot_tc, &ctx) {
                error!("Failed to save screenshot: {}", e);
            } else {
                debug!("Screenshot saved successfully to tempdir");
            }
        }
        // Suppress unused variable warning for lib builds
        #[cfg(not(feature = "cli"))]
        let _ = screenshot_event_tc;

        // Check if frame is identical to previous (skip check in natural mode)
        let frame_unchanged = !ctx.natural
            && last_frame
                .as_ref()
                .map(|last| image.samples.as_slice() == last.samples.as_slice())
                .unwrap_or(false);

        // Track duration of identical frames
        if frame_unchanged {
            current_idle_period = current_idle_period.add(frame_duration);
        } else {
            current_idle_period = Duration::from_millis(0);
        }

        // Decide whether to save this frame
        let should_save_frame = if frame_unchanged {
            let should_skip_for_compression = if let Some(threshold) = ctx.idle_pause {
                // Skip if idle exceeds threshold
                current_idle_period >= threshold
            } else {
                // No threshold: skip all identical frames
                true
            };

            if should_skip_for_compression {
                // Add skipped time to idle_duration for timestamp adjustment
                idle_duration = idle_duration.add(frame_duration);
                false
            } else {
                // Save frame (idle within threshold)
                true
            }
        } else {
            // Frame changed: reset idle tracking and save
            current_idle_period = Duration::from_millis(0);
            true
        };

        if should_save_frame {
            // Save frame and update state
            if let Err(e) = save_frame(
                &image,
                tc,
                ctx.tempdir.lock().unwrap().borrow(),
                file_name_for,
            ) {
                eprintln!("{}", &e);
                return Err(e);
            }
            ctx.time_codes.lock().unwrap().push(tc);

            // Store frame for next comparison
            last_frame = Some(image);
        }
        last_now = now;
    }

    Ok(())
}

/// Saves a screenshot to the temp directory (CLI only).
#[cfg(feature = "cli")]
fn save_screenshot(image: &ImageOnHeap, timecode_ms: u128, ctx: &CaptureContext) -> Result<()> {
    let tempdir = ctx.tempdir.lock().unwrap();
    let path = tempdir
        .path()
        .join(screenshot_file_name(timecode_ms, IMG_EXT));

    save_buffer(
        &path,
        &image.samples,
        image.layout.width,
        image.layout.height,
        image.color_hint.unwrap_or(Rgba8),
    )
    .context("Cannot save screenshot")?;

    debug!("Screenshot saved at timecode {timecode_ms}");

    // Record screenshot info
    if let Some(ref screenshots) = ctx.screenshots {
        screenshots.try_lock().unwrap().push(ScreenshotInfo {
            timecode_ms,
            temp_path: path.clone(),
        });
        debug!("ScreenshotInfo collected for timecode {timecode_ms}");
    } else {
        debug!("ScreenshotInfo collection skipped (no storage) for timecode {timecode_ms}");
    }

    Ok(())
}

/// Saves a frame as a BMP file.
pub fn save_frame(
    image: &ImageOnHeap,
    time_code: u128,
    tempdir: &TempDir,
    file_name_for: fn(&u128, &str) -> String,
) -> Result<()> {
    save_buffer(
        tempdir.path().join(file_name_for(&time_code, IMG_EXT)),
        &image.samples,
        image.layout.width,
        image.layout.height,
        image.color_hint.unwrap_or(Rgba8),
    )
    .context("Cannot save frame")
}

#[cfg(all(test, feature = "cli"))]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use tokio::sync::broadcast;

    /// Mock PlatformApi that returns predefined 1x1 pixel frames.
    /// Sends a Stop event after all frames have been consumed, making tests deterministic.
    struct TestApi {
        frames: Vec<Vec<u8>>,
        index: std::cell::Cell<usize>,
        stop_sender: tokio::sync::broadcast::Sender<Event>,
    }

    impl crate::PlatformApi for TestApi {
        fn capture_window_screenshot(
            &self,
            _: crate::WindowId,
        ) -> crate::Result<crate::ImageOnHeap> {
            let i = self.index.get();
            self.index.set(i + 1);
            let num_channels = 4;
            let pixel_width = 1;
            let pixel_height = 1;
            let frame_index = if i >= self.frames.len() {
                self.frames.len() - 1
            } else {
                // Send stop after returning the last frame
                if i == self.frames.len() - 1 {
                    let _ = self.stop_sender.send(Event::Capture(CaptureEvent::Stop));
                }
                i
            };
            Ok(Box::new(image::FlatSamples {
                samples: self.frames[frame_index].clone(),
                layout: image::flat::SampleLayout::row_major_packed(
                    num_channels,
                    pixel_width,
                    pixel_height,
                ),
                color_hint: Some(image::ColorType::Rgba8),
            }))
        }
        fn calibrate(&mut self, _: crate::WindowId) -> crate::Result<()> {
            Ok(())
        }
        fn window_list(&self) -> crate::Result<crate::WindowList> {
            Ok(vec![])
        }
        fn get_active_window(&self) -> crate::Result<crate::WindowId> {
            Ok(0)
        }
    }

    /// Convert a byte sequence into RGBA pixel frames (each byte becomes one 1x1 frame).
    fn frames<T: AsRef<[u8]>>(sequence: T) -> Vec<Vec<u8>> {
        sequence
            .as_ref()
            .iter()
            .map(|&value| vec![value; 4])
            .collect()
    }

    /// Run a capture test with the given frames and settings, returning captured timestamps.
    /// The test stops deterministically after all frames are consumed, not based on timing.
    fn run_capture_test(
        test_frames: Vec<Vec<u8>>,
        natural_mode: bool,
        idle_threshold: Option<Duration>,
    ) -> crate::Result<Vec<u128>> {
        let captured_timestamps = Arc::new(Mutex::new(Vec::new()));
        let temp_directory = Arc::new(Mutex::new(TempDir::new()?));
        let (tx, rx) = broadcast::channel::<Event>(10);

        let test_api = TestApi {
            frames: test_frames.clone(),
            index: Default::default(),
            stop_sender: tx.clone(),
        };

        // Send start event
        tx.send(Event::Capture(CaptureEvent::Start)).unwrap();

        let ctx = CaptureContext {
            win_id: 0,
            time_codes: captured_timestamps.clone(),
            tempdir: temp_directory,
            natural: natural_mode,
            idle_pause: idle_threshold,
            fps: 4,
            screenshots: None,
        };
        capture_thread(rx, test_api, ctx)?;
        let result = captured_timestamps.lock().unwrap().clone();
        Ok(result)
    }

    #[test]
    fn test_all_unique_frames_are_captured() {
        // Each frame is different, all should be saved
        let test_frames = frames([1, 2, 3, 4, 5]);
        let timestamps = run_capture_test(test_frames, false, None).unwrap();

        assert_eq!(timestamps.len(), 5, "All unique frames should be captured");
    }

    #[test]
    fn test_identical_frames_are_skipped_by_default() {
        // Frames: A, A, A, B, B, C (3 unique values)
        let test_frames = frames([1, 1, 1, 2, 2, 3]);
        let timestamps = run_capture_test(test_frames, false, None).unwrap();

        // Only first occurrence of each unique frame should be saved
        assert_eq!(
            timestamps.len(),
            3,
            "Identical consecutive frames should be skipped"
        );
    }

    #[test]
    fn test_natural_mode_preserves_all_frames() {
        // Same sequence but natural mode keeps everything
        let test_frames = frames([1, 1, 1, 2, 2, 3]);
        let timestamps = run_capture_test(test_frames, true, None).unwrap();

        assert_eq!(timestamps.len(), 6, "Natural mode should keep all frames");
    }

    #[test]
    fn test_idle_threshold_preserves_short_pauses() {
        // With a very generous threshold, identical frames should be preserved
        // Frame interval is 10ms in test mode, so 500ms threshold easily covers a few frames
        // Using a large threshold to avoid flakiness on CI where timing can vary
        let test_frames = frames([1, 1, 1, 2]); // 3 identical then change
        let timestamps =
            run_capture_test(test_frames, false, Some(Duration::from_millis(500))).unwrap();

        // With such a large threshold, at minimum the first unique frame and
        // the changed frame should be captured (2 frames minimum)
        // In practice all 4 should be captured since idle never exceeds threshold
        assert!(
            timestamps.len() >= 2,
            "Frames within idle threshold should be preserved, got {} frames",
            timestamps.len()
        );
    }

    #[test]
    fn test_idle_threshold_skips_long_pauses() {
        // With a short threshold, long identical sequences get truncated
        let test_frames = frames([1, 1, 1, 1, 1, 1, 1, 1, 2]); // 8 identical then change
        let timestamps =
            run_capture_test(test_frames, false, Some(Duration::from_millis(25))).unwrap();

        // Should have fewer than 9 frames (some idle skipped)
        assert!(
            timestamps.len() < 9,
            "Long idle periods beyond threshold should be skipped"
        );
        // But should still have the unique frames
        assert!(
            timestamps.len() >= 2,
            "Unique frames should still be captured"
        );
    }

    #[test]
    fn test_alternating_frames_all_captured() {
        // Rapidly changing content: A, B, A, B, A
        let test_frames = frames([1, 2, 1, 2, 1]);
        let timestamps = run_capture_test(test_frames, false, None).unwrap();

        assert_eq!(
            timestamps.len(),
            5,
            "Alternating frames should all be captured"
        );
    }

    #[test]
    fn test_timestamps_are_monotonically_increasing() {
        let test_frames = frames([1, 2, 3, 4, 5]);
        let timestamps = run_capture_test(test_frames, false, None).unwrap();

        for window in timestamps.windows(2) {
            assert!(
                window[1] > window[0],
                "Timestamps should be strictly increasing"
            );
        }
    }

    #[test]
    fn test_stop_event_terminates_capture() {
        let captured_timestamps = Arc::new(Mutex::new(Vec::new()));
        let temp_directory = Arc::new(Mutex::new(TempDir::new().unwrap()));
        let (tx, rx) = broadcast::channel::<Event>(10);

        let test_api = TestApi {
            frames: frames([1, 2, 3]),
            index: Default::default(),
            stop_sender: tx.clone(),
        };

        // Send start then immediate stop
        tx.send(Event::Capture(CaptureEvent::Start)).unwrap();
        tx.send(Event::Capture(CaptureEvent::Stop)).unwrap();

        let ctx = CaptureContext {
            win_id: 0,
            time_codes: captured_timestamps.clone(),
            tempdir: temp_directory,
            natural: false,
            idle_pause: None,
            fps: 4,
            screenshots: None,
        };

        capture_thread(rx, test_api, ctx).unwrap();
        // Should terminate quickly without error
    }

    #[test]
    fn test_shutdown_event_terminates_capture() {
        let captured_timestamps = Arc::new(Mutex::new(Vec::new()));
        let temp_directory = Arc::new(Mutex::new(TempDir::new().unwrap()));
        let (tx, rx) = broadcast::channel::<Event>(10);

        let test_api = TestApi {
            frames: frames([1, 2, 3]),
            index: Default::default(),
            stop_sender: tx.clone(),
        };

        // Shutdown before start should exit cleanly
        tx.send(Event::Lifecycle(LifecycleEvent::Shutdown)).unwrap();

        let ctx = CaptureContext {
            win_id: 0,
            time_codes: captured_timestamps.clone(),
            tempdir: temp_directory,
            natural: false,
            idle_pause: None,
            fps: 4,
            screenshots: None,
        };

        capture_thread(rx, test_api, ctx).unwrap();
    }

    #[test]
    fn test_frames_saved_to_tempdir() {
        let test_frames = frames([1, 2, 3]);
        let captured_timestamps = Arc::new(Mutex::new(Vec::new()));
        let temp_directory = Arc::new(Mutex::new(TempDir::new().unwrap()));
        let (tx, rx) = broadcast::channel::<Event>(10);

        // Clone the Arc to keep tempdir alive for file check
        let temp_directory_check = temp_directory.clone();

        let test_api = TestApi {
            frames: test_frames,
            index: Default::default(),
            stop_sender: tx.clone(),
        };

        tx.send(Event::Capture(CaptureEvent::Start)).unwrap();

        let ctx = CaptureContext {
            win_id: 0,
            time_codes: captured_timestamps.clone(),
            tempdir: temp_directory,
            natural: false,
            idle_pause: None,
            fps: 4,
            screenshots: None,
        };

        capture_thread(rx, test_api, ctx).unwrap();

        // Check that files were actually created (tempdir still alive via temp_directory_check)
        let temp_guard = temp_directory_check.lock().unwrap();
        let files: Vec<_> = std::fs::read_dir(temp_guard.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();

        let num_timestamps = captured_timestamps.lock().unwrap().len();
        assert_eq!(
            files.len(),
            num_timestamps,
            "Number of saved files should match timestamps"
        );
    }
}