weirdnet-media 0.2.0

Weirdnet media processing for clients and nodes: WAV probing and PCM in pure Rust, 16 kHz resampling, silence-aware chunking, long-audio transcription plans, long-text speech plans, SRT/VTT, video frame planning, and a hardened ffmpeg runner with a test fake.
Documentation
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
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Video: probing, frame planning (uniform, scene, hybrid, keyframes, fixed intervals), frame,
//! thumbnail and soundtrack extraction, and clips.
//!
//! Decoding is behind [`FrameSource`]: [`FfmpegSource`] uses the hardened [`crate::ffmpeg`]
//! runner (or any [`Exec`], such as [`crate::ffmpeg::FakeRunner`]); platform decoders on phones
//! can implement it too; [`FakeSource`] generates frames for tests. Planning is pure and takes the
//! frame count and size from the caller, who derives them from the model's reported limits: there
//! is no default frame count or frame size here.

use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::audio::{Extract, extract};
use crate::error::{MediaError, Result};
use crate::ffmpeg::{Exec, Input, Job};
use crate::probe::{MediaInfo, ffprobe};

/// Scene changes closer than this to a frame already chosen are the same moment.
pub const DEDUP_MS: u64 = 250;

/// JPEG quality for frames, as ffmpeg's `-q:v` (2 best .. 31 worst); about quality 80.
pub const JPEG_Q: u8 = 4;

/// Video file extensions (the content is still probed; the extension only picks a path).
pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "webm", "mkv", "avi"];

/// Whether `path` names a video by its extension.
pub fn is_video_path(path: &Path) -> bool {
    path.extension().and_then(|e| e.to_str()).is_some_and(|e| VIDEO_EXTENSIONS.iter().any(|v| v.eq_ignore_ascii_case(e)))
}

/// What a video probe found.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct VideoProbe {
    pub duration_ms: u64,
    pub width: u32,
    pub height: u32,
    /// Frames per second, when the container says.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fps: Option<f32>,
    pub has_audio: bool,
}

impl VideoProbe {
    /// The video part of a probe; an error when there is no video stream.
    pub fn from_info(info: &MediaInfo) -> Result<VideoProbe> {
        let v = info.video.as_ref().ok_or_else(|| MediaError::invalid("the file has no video stream"))?;
        Ok(VideoProbe { duration_ms: info.duration_ms.unwrap_or(0), width: v.width, height: v.height, fps: v.fps, has_audio: info.audio.is_some() })
    }
}

/// One encoded frame.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Frame {
    pub mime: String,
    pub bytes: Vec<u8>,
}

/// A frame and when it is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimedFrame {
    pub at_ms: u64,
    pub frame: Frame,
}

/// A decoder.
pub trait FrameSource {
    /// The clip's length, size, frame rate and whether it has sound.
    fn probe(&self) -> Result<VideoProbe>;
    /// The frame at `at_ms`, scaled to `width` x `height`, as JPEG.
    fn frame_at(&self, at_ms: u64, width: u32, height: u32) -> Result<Frame>;
    /// Scene changes above `threshold` (0..1) as `(ms, score)`, in time order.
    fn scenes(&self, threshold: f32) -> Result<Vec<(u64, f32)>>;
    /// Keyframe times, in order. Sources that can't tell return none.
    fn keyframes(&self) -> Result<Vec<u64>> {
        Ok(Vec::new())
    }
    /// The soundtrack from `start_ms` for `len_ms`, as 16 kHz mono 16-bit WAV.
    fn audio(&self, start_ms: u64, len_ms: u64) -> Result<Vec<u8>>;
}

/// How frames are chosen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "mode")]
#[non_exhaustive]
pub enum Mode {
    /// The middle of `n` equal slices.
    #[default]
    Uniform,
    /// The start, then the strongest scene changes, topped up uniformly.
    Scene,
    /// Half uniform, half the strongest scene changes not near them.
    Hybrid,
    /// Keyframes spread over the range, topped up uniformly.
    Keyframes,
    /// One frame every `ms`, at most `n`.
    Every { ms: u64 },
}

/// What the detectors found, for [`plan_frames`].
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Marks {
    /// `(ms, score)` scene changes.
    pub scenes: Vec<(u64, f32)>,
    /// Keyframe times.
    pub keyframes: Vec<u64>,
}

/// Evenly spread times inside `[start, end)`: the middle of each of `n` equal slices.
pub fn uniform(start: u64, end: u64, n: u32) -> Vec<u64> {
    let len = end.saturating_sub(start);
    if n == 0 || len == 0 {
        return if n == 0 { Vec::new() } else { vec![start] };
    }
    let n = u64::from(n).min(len);
    (0..n).map(|i| start + (2 * i + 1) * len / (2 * n)).collect()
}

/// One time every `every_ms` from `start` inside `[start, end)`, at most `n`.
pub fn every(start: u64, end: u64, every_ms: u64, n: u32) -> Vec<u64> {
    if n == 0 || every_ms == 0 {
        return Vec::new();
    }
    (0..u64::from(n)).map(|i| start + i * every_ms).take_while(|t| *t < end.max(start + 1)).collect()
}

fn tidy(mut times: Vec<u64>, start: u64, end: u64) -> Vec<u64> {
    times.retain(|t| *t >= start && *t < end.max(start + 1));
    times.sort_unstable();
    times.dedup();
    times
}

fn top_up(mut times: Vec<u64>, start: u64, end: u64, n: u32) -> Vec<u64> {
    let mut k = n;
    while (times.len() as u32) < n && k <= n.saturating_mul(4).max(4) {
        for t in uniform(start, end, k) {
            if times.len() as u32 >= n {
                break;
            }
            if !times.iter().any(|c| c.abs_diff(t) < DEDUP_MS) {
                times.push(t);
            }
        }
        k += 1;
    }
    tidy(times, start, end)
}

/// The frame times for `range` with at most `n` frames. Always sorted, unique and inside the
/// range.
pub fn plan_frames(mode: Mode, range: (u64, u64), n: u32, marks: &Marks) -> Vec<u64> {
    let (start, end) = range;
    if n == 0 {
        return Vec::new();
    }
    let strongest = |k: usize, near: &[u64]| -> Vec<u64> {
        let mut hits: Vec<(u64, f32)> = marks.scenes.iter().copied().filter(|(t, _)| *t > start && *t < end).collect();
        hits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
        let mut out: Vec<u64> = Vec::new();
        for (t, _) in hits {
            if out.len() >= k {
                break;
            }
            if !out.iter().chain(near).any(|c| c.abs_diff(t) < DEDUP_MS) {
                out.push(t);
            }
        }
        out
    };
    let times = match mode {
        Mode::Uniform => uniform(start, end, n),
        Mode::Scene => {
            let mut t = vec![start];
            t.extend(strongest(n as usize - 1, &[start]));
            top_up(t, start, end, n)
        }
        Mode::Hybrid => {
            let backbone = uniform(start, end, n.div_ceil(2));
            let mut t = backbone.clone();
            t.extend(strongest((n as usize).saturating_sub(backbone.len()), &backbone));
            top_up(t, start, end, n)
        }
        Mode::Keyframes => {
            let keys = tidy(marks.keyframes.clone(), start, end);
            let picked: Vec<u64> = if keys.len() as u32 <= n {
                keys
            } else {
                // The keyframe nearest each uniform slot.
                uniform(start, end, n).into_iter().filter_map(|slot| keys.iter().copied().min_by_key(|k| (k.abs_diff(slot), *k))).collect()
            };
            top_up(tidy(picked, start, end), start, end, n)
        }
        Mode::Every { ms } => every(start, end, ms, n),
    };
    let mut times = tidy(times, start, end);
    times.truncate(n as usize);
    times
}

/// `w` x `h` scaled to fit `edge` on its longer side (even sizes, as encoders want); unchanged
/// (but even) when it fits already or there is no edge.
pub fn fit(w: u32, h: u32, edge: Option<u32>) -> (u32, u32) {
    let even = |x: u32| (x.max(2) / 2) * 2;
    match edge {
        Some(e) if w.max(h) > e && e > 0 => {
            let (w, h, e) = (u64::from(w), u64::from(h), u64::from(e));
            if w >= h { (even(e as u32), even((h * e / w).max(2) as u32)) } else { (even((w * e / h).max(2) as u32), even(e as u32)) }
        }
        _ => (even(w), even(h)),
    }
}

/// A timestamp label, `[00:07.5]` (`[61:02.0]` past an hour).
pub fn label(ms: u64) -> String {
    let s = ms / 1000;
    format!("[{:02}:{:02}.{}]", s / 60, s % 60, (ms % 1000) / 100)
}

/// The range to sample: `range` checked against the clip, or the whole clip.
pub fn clip_range(probe: &VideoProbe, range: Option<(u64, u64)>) -> Result<(u64, u64)> {
    let len = probe.duration_ms;
    match range {
        None => Ok((0, len.max(1))),
        Some((a, b)) if a < b && a < len.max(1) => Ok((a, b.min(len.max(1)))),
        Some((a, b)) => Err(MediaError::invalid(format!("range {}..{} is outside the clip ({} ms)", label(a), label(b), len))),
    }
}

/// Scene hits from ffmpeg's `metadata=print:file=-` output (`pts_time:` then
/// `lavfi.scene_score=`).
pub fn parse_scenes(text: &str) -> Vec<(u64, f32)> {
    let mut out = Vec::new();
    let mut at: Option<u64> = None;
    for line in text.lines() {
        if let Some(t) = line.split_whitespace().find_map(|w| w.strip_prefix("pts_time:")).and_then(|t| t.parse::<f64>().ok()) {
            at = Some((t * 1000.0).round().max(0.0) as u64);
        } else if let (Some(t), Some(score)) = (at, line.trim().strip_prefix("lavfi.scene_score=").and_then(|s| s.parse::<f32>().ok())) {
            out.push((t, score));
            at = None;
        }
    }
    out
}

/// Keyframe times from `ffprobe -select_streams v:0 -show_entries packet=pts_time,flags -of
/// csv=p=0` output (`0.000000,K__` lines).
pub fn parse_keyframes(text: &str) -> Vec<u64> {
    let mut out: Vec<u64> = text
        .lines()
        .filter_map(|l| {
            let (t, flags) = l.trim().split_once(',')?;
            flags.contains('K').then_some(())?;
            t.parse::<f64>().ok().filter(|t| t.is_finite() && *t >= 0.0).map(|t| (t * 1000.0).round() as u64)
        })
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

fn secs(ms: u64) -> String {
    format!("{}.{:03}", ms / 1000, ms % 1000)
}

/// A [`FrameSource`] over ffmpeg through any [`Exec`].
#[derive(Debug, Clone)]
pub struct FfmpegSource<E: Exec> {
    exec: E,
    input: Input,
    /// The largest single frame (default 4 MiB).
    pub max_frame_bytes: u64,
    /// The longest soundtrack read at once (default 10 minutes).
    pub max_audio_ms: u64,
}

impl<E: Exec> FfmpegSource<E> {
    /// A source for `input`.
    pub fn new(exec: E, input: Input) -> Self {
        FfmpegSource { exec, input, max_frame_bytes: 4 << 20, max_audio_ms: 10 * 60 * 1000 }
    }

    /// The input.
    pub fn input(&self) -> &Input {
        &self.input
    }

    /// The runner.
    pub fn exec(&self) -> &E {
        &self.exec
    }

    /// The full probe (container, streams).
    pub fn info(&self) -> Result<MediaInfo> {
        ffprobe(&self.exec, &self.input)
    }
}

impl<E: Exec> FrameSource for FfmpegSource<E> {
    fn probe(&self) -> Result<VideoProbe> {
        VideoProbe::from_info(&self.info()?)
    }

    fn frame_at(&self, at_ms: u64, width: u32, height: u32) -> Result<Frame> {
        let job = Job::ffmpeg(self.input.clone())
            .before_input(["-ss".to_string(), secs(at_ms)])
            .args(["-an", "-sn", "-dn", "-map_metadata", "-1", "-frames:v", "1"])
            .args(["-vf".to_string(), format!("scale={width}:{height}")])
            .args(["-c:v".to_string(), "mjpeg".into(), "-q:v".into(), JPEG_Q.to_string(), "-f".into(), "image2pipe".into(), "pipe:1".into()])
            .max_output(self.max_frame_bytes);
        let bytes = self.exec.exec(&job)?;
        if !bytes.starts_with(&[0xFF, 0xD8]) {
            return Err(MediaError::invalid(format!("no frame at {}", label(at_ms))));
        }
        Ok(Frame { mime: "image/jpeg".into(), bytes })
    }

    fn scenes(&self, threshold: f32) -> Result<Vec<(u64, f32)>> {
        let threshold = threshold.clamp(0.0, 1.0);
        let job = Job::ffmpeg(self.input.clone())
            .args(["-an", "-sn", "-dn", "-vf"])
            .args([format!("select='gt(scene,{threshold})',metadata=print:file=-")])
            .args(["-f", "null", "-"])
            .max_output(16 << 20);
        Ok(parse_scenes(&String::from_utf8_lossy(&self.exec.exec(&job)?)))
    }

    fn keyframes(&self) -> Result<Vec<u64>> {
        let job = Job::ffprobe(self.input.clone())
            .args(["-select_streams", "v:0", "-show_entries", "packet=pts_time,flags", "-of", "csv=p=0"])
            .max_output(64 << 20);
        Ok(parse_keyframes(&String::from_utf8_lossy(&self.exec.exec(&job)?)))
    }

    fn audio(&self, start_ms: u64, len_ms: u64) -> Result<Vec<u8>> {
        extract(&self.exec, &self.input, &Extract::transcribe(self.max_audio_ms).range(start_ms, len_ms.min(self.max_audio_ms)))
    }
}

/// What to take from a clip.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FrameRequest {
    /// How many frames, at most (from the model's limits; there is no default).
    pub count: u32,
    /// The longest edge, from the model's preferred image edge or the user.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_edge: Option<u32>,
    pub mode: Mode,
    /// Scene-change threshold, 0..1 (for `Scene` and `Hybrid`).
    pub scene_threshold: f32,
    /// Only this part of the clip, in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub range: Option<(u64, u64)>,
    /// The most bytes all frames together may take (default 32 MiB).
    pub max_total_bytes: u64,
}

impl FrameRequest {
    /// `count` uniform frames at the clip's own size.
    pub fn new(count: u32) -> Self {
        FrameRequest { count, max_edge: None, mode: Mode::Uniform, scene_threshold: 0.3, range: None, max_total_bytes: 32 << 20 }
    }

    /// Sets the longest edge.
    pub fn max_edge(mut self, edge: u32) -> Self {
        self.max_edge = Some(edge);
        self
    }

    /// Sets the mode.
    pub fn mode(mut self, mode: Mode) -> Self {
        self.mode = mode;
        self
    }

    /// Sets the scene threshold.
    pub fn scene_threshold(mut self, t: f32) -> Self {
        self.scene_threshold = t;
        self
    }

    /// Only `[start_ms, end_ms)`.
    pub fn range(mut self, start_ms: u64, end_ms: u64) -> Self {
        self.range = Some((start_ms, end_ms));
        self
    }

    /// Sets the byte bound for all frames.
    pub fn max_total_bytes(mut self, bytes: u64) -> Self {
        self.max_total_bytes = bytes;
        self
    }
}

/// Probes the clip, plans the frame times and extracts them.
pub fn extract_frames(source: &dyn FrameSource, req: &FrameRequest) -> Result<(VideoProbe, Vec<TimedFrame>)> {
    let probe = source.probe()?;
    let range = clip_range(&probe, req.range)?;
    let marks = match req.mode {
        Mode::Scene | Mode::Hybrid => Marks { scenes: source.scenes(req.scene_threshold)?, keyframes: Vec::new() },
        Mode::Keyframes => Marks { scenes: Vec::new(), keyframes: source.keyframes()? },
        _ => Marks::default(),
    };
    let (w, h) = fit(probe.width, probe.height, req.max_edge);
    let mut frames = Vec::new();
    let mut total = 0u64;
    for t in plan_frames(req.mode, range, req.count, &marks) {
        let frame = source.frame_at(t, w, h)?;
        total += frame.bytes.len() as u64;
        if total > req.max_total_bytes {
            return Err(MediaError::limit(format!("the frames come to over {} bytes; ask for fewer frames or a smaller edge", req.max_total_bytes)));
        }
        frames.push(TimedFrame { at_ms: t, frame });
    }
    Ok((probe, frames))
}

/// One frame for a preview: at `at_ms`, or a tenth of the way in (at most 10 s), fit to `max_edge`.
pub fn thumbnail(source: &dyn FrameSource, at_ms: Option<u64>, max_edge: Option<u32>) -> Result<TimedFrame> {
    let probe = source.probe()?;
    let at = at_ms.unwrap_or((probe.duration_ms / 10).min(10_000)).min(probe.duration_ms.saturating_sub(1));
    let (w, h) = fit(probe.width, probe.height, max_edge);
    Ok(TimedFrame { at_ms: at, frame: source.frame_at(at, w, h)? })
}

/// The soundtrack of the whole clip or `range`, as 16 kHz mono WAV; `None` when it has no sound.
pub fn soundtrack(source: &dyn FrameSource, range: Option<(u64, u64)>) -> Result<Option<Vec<u8>>> {
    let probe = source.probe()?;
    if !probe.has_audio {
        return Ok(None);
    }
    let (a, b) = clip_range(&probe, range)?;
    source.audio(a, b - a).map(Some)
}

/// The container for [`clip`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ClipFormat {
    /// Fragmented MP4 (streamable to a pipe).
    Mp4,
    /// Matroska.
    Matroska,
    /// WebM (VP8/VP9/AV1 with Vorbis/Opus sources only).
    Webm,
}

impl ClipFormat {
    /// The MIME type.
    pub fn mime(self) -> &'static str {
        match self {
            ClipFormat::Mp4 => "video/mp4",
            ClipFormat::Matroska => "video/x-matroska",
            ClipFormat::Webm => "video/webm",
        }
    }
}

/// What to cut.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ClipRequest {
    pub start_ms: u64,
    pub len_ms: u64,
    pub format: ClipFormat,
    /// Keep the first audio stream.
    pub audio: bool,
    /// The largest output.
    pub max_bytes: u64,
}

impl ClipRequest {
    /// `[start_ms, start_ms + len_ms)` as fragmented MP4 with sound, at most `max_bytes`.
    pub fn new(start_ms: u64, len_ms: u64, max_bytes: u64) -> Self {
        ClipRequest { start_ms, len_ms, format: ClipFormat::Mp4, audio: true, max_bytes }
    }

    /// Sets the container.
    pub fn format(mut self, format: ClipFormat) -> Self {
        self.format = format;
        self
    }

    /// Drops the sound.
    pub fn without_audio(mut self) -> Self {
        self.audio = false;
        self
    }
}

/// A part of a clip, stream-copied (no re-encode, so cuts land on keyframes), for models that
/// read video natively.
pub fn clip(exec: &dyn Exec, input: &Input, req: &ClipRequest) -> Result<Vec<u8>> {
    if req.len_ms == 0 {
        return Err(MediaError::invalid("a clip needs a length"));
    }
    let mut job = Job::ffmpeg(input.clone()).before_input(["-ss".to_string(), secs(req.start_ms), "-t".to_string(), secs(req.len_ms)]);
    job = job.args(["-map", "0:v:0"]);
    if req.audio {
        job = job.args(["-map", "0:a:0?"]);
    }
    job = job.args(["-sn", "-dn", "-map_metadata", "-1", "-c", "copy"]);
    job = match req.format {
        ClipFormat::Mp4 => job.args(["-movflags", "frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "pipe:1"]),
        ClipFormat::Matroska => job.args(["-f", "matroska", "pipe:1"]),
        ClipFormat::Webm => job.args(["-f", "webm", "pipe:1"]),
    };
    exec.exec(&job.max_output(req.max_bytes))
}

/// A source with generated frames, for tests: no ffmpeg.
#[derive(Debug, Clone, PartialEq)]
pub struct FakeSource {
    pub probe: VideoProbe,
    pub scenes: Vec<(u64, f32)>,
    pub keyframes: Vec<u64>,
}

impl FakeSource {
    /// A 1920x1080, 30 fps clip of `duration_ms`, keyframes every 2 s.
    pub fn new(duration_ms: u64, has_audio: bool) -> Self {
        FakeSource {
            probe: VideoProbe { duration_ms, width: 1920, height: 1080, fps: Some(30.0), has_audio },
            scenes: Vec::new(),
            keyframes: (0..duration_ms).step_by(2000).collect(),
        }
    }

    /// With these scene changes.
    pub fn with_scenes(mut self, scenes: Vec<(u64, f32)>) -> Self {
        self.scenes = scenes;
        self
    }
}

impl FrameSource for FakeSource {
    fn probe(&self) -> Result<VideoProbe> {
        Ok(self.probe)
    }

    fn frame_at(&self, at_ms: u64, width: u32, height: u32) -> Result<Frame> {
        let mut bytes = vec![0xFF, 0xD8, 0xFF];
        bytes.extend(format!("{at_ms}@{width}x{height}").into_bytes());
        Ok(Frame { mime: "image/jpeg".into(), bytes })
    }

    fn scenes(&self, threshold: f32) -> Result<Vec<(u64, f32)>> {
        Ok(self.scenes.iter().copied().filter(|(_, s)| *s > threshold).collect())
    }

    fn keyframes(&self) -> Result<Vec<u64>> {
        Ok(self.keyframes.clone())
    }

    fn audio(&self, _start_ms: u64, len_ms: u64) -> Result<Vec<u8>> {
        Ok(crate::pcm::encode_wav(&crate::pcm::Pcm::silence(crate::pcm::TRANSCRIBE_RATE, 1, len_ms)))
    }
}