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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! `ffmpeg` and `ffprobe` in child processes, hardened.
//!
//! Every call is a [`Job`]: one [`Input`] (a file the caller already chose, or bytes it holds, fed
//! on `pipe:0`), the options before and after the input, and an output bound. The [`Runner`] adds
//! the hardening and never goes through a shell:
//!
//! - `-nostdin -hide_banner -loglevel error`, `-protocol_whitelist file,pipe` and a demuxer
//!   allowlist (`-format_whitelist`, [`DEFAULT_FORMATS`]), so a playlist, `concat` list or URL
//!   inside a file can't be followed;
//! - the input only as `file:<absolute path>` (canonicalized, a regular file, under
//!   [`Limits::max_input_bytes`]) or `pipe:0`; URLs, other protocols and extra `-i` options in a job
//!   are refused before anything runs;
//! - output only to `pipe:1` (or `-` with the `null` muxer), read with a size bound
//!   ([`Job::max_output`], capped by [`Limits::max_output`]); the child is killed when it is passed;
//! - a wall-time limit (default 120 s), on Unix an address-space limit (`RLIMIT_AS`, default 1
//!   GiB) and a lower CPU priority, and on Linux a new network namespace when unprivileged user
//!   namespaces allow it;
//! - stderr kept only when the child fails, truncated to 2 KiB; nothing is logged.
//!
//! [`Exec`] is the seam: [`Runner`] runs the real tools, [`FakeRunner`] answers from rules or a
//! [`FakeMedia`] description so tests need no ffmpeg. Both validate jobs the same way.

use std::ffi::{OsStr, OsString};
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::error::{MediaError, Result};

/// Demuxers the runner lets ffmpeg open (`-format_whitelist`): WAV, MP3, FLAC, Ogg, AAC (ADTS),
/// MP4/MOV/M4A, Matroska/WebM and AVI. Never `concat`, playlists, image sequences or `lavfi`.
pub const DEFAULT_FORMATS: &[&str] = &["wav", "mp3", "flac", "ogg", "aac", "mov", "mp4", "m4a", "matroska", "webm", "avi"];

/// Largest stderr kept from a failed child.
pub const STDERR_KEEP: usize = 2048;

/// Where the media comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Input {
    /// A local file. Passed as `file:<canonical path>`.
    File(PathBuf),
    /// Bytes in memory, fed on `pipe:0`. (Containers that need seeking, such as MP4 with its index
    /// at the end, may not open from a pipe; write them to a [`PrivateDir`] first.)
    Bytes(Arc<[u8]>),
}

impl Input {
    /// A local file.
    pub fn file(path: impl Into<PathBuf>) -> Self {
        Input::File(path.into())
    }

    /// Bytes in memory.
    pub fn bytes(bytes: impl Into<Arc<[u8]>>) -> Self {
        Input::Bytes(bytes.into())
    }

    /// The first `n` bytes (fewer when the input is shorter).
    pub fn head(&self, n: usize) -> Result<Vec<u8>> {
        match self {
            Input::Bytes(b) => Ok(b[..n.min(b.len())].to_vec()),
            Input::File(p) => {
                let mut out = Vec::with_capacity(n);
                std::fs::File::open(p)?.take(n as u64).read_to_end(&mut out)?;
                Ok(out)
            }
        }
    }

    /// The input's length in bytes.
    pub fn len(&self) -> Result<u64> {
        match self {
            Input::Bytes(b) => Ok(b.len() as u64),
            Input::File(p) => Ok(std::fs::metadata(p)?.len()),
        }
    }

    /// Whether the input is empty.
    pub fn is_empty(&self) -> Result<bool> {
        Ok(self.len()? == 0)
    }

    /// The whole input in memory.
    pub fn read_all(&self, max: u64) -> Result<Vec<u8>> {
        let len = self.len()?;
        if len > max {
            return Err(MediaError::limit(format!("input is {len} bytes, over the {max}-byte limit")));
        }
        match self {
            Input::Bytes(b) => Ok(b.to_vec()),
            Input::File(p) => Ok(std::fs::read(p)?),
        }
    }
}

/// Which program a job runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tool {
    Ffmpeg,
    Ffprobe,
}

impl Tool {
    /// `ffmpeg` or `ffprobe`.
    pub fn name(self) -> &'static str {
        match self {
            Tool::Ffmpeg => "ffmpeg",
            Tool::Ffprobe => "ffprobe",
        }
    }
}

/// One call: the tool, the input, the options around it and the output bound. The hardening
/// options and the input itself are added by the runner.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
    pub tool: Tool,
    pub input: Input,
    /// Input options, placed before the input (`-ss` for a fast seek, `-t`).
    pub before_input: Vec<String>,
    /// Everything after the input. For ffmpeg the last one must be `pipe:1` (or `-` with
    /// `-f null`); for ffprobe the input goes last, so these are its options.
    pub args: Vec<String>,
    /// The most output read before the child is stopped; capped by [`Limits::max_output`].
    pub max_output: Option<u64>,
    /// A shorter time limit than [`Limits::timeout`] for this call.
    pub timeout: Option<Duration>,
}

impl Job {
    /// An ffmpeg job on `input`.
    pub fn ffmpeg(input: Input) -> Self {
        Job { tool: Tool::Ffmpeg, input, before_input: Vec::new(), args: Vec::new(), max_output: None, timeout: None }
    }

    /// An ffprobe job on `input`.
    pub fn ffprobe(input: Input) -> Self {
        Job { tool: Tool::Ffprobe, ..Job::ffmpeg(input) }
    }

    /// Adds input options.
    pub fn before_input<S: Into<String>>(mut self, args: impl IntoIterator<Item = S>) -> Self {
        self.before_input.extend(args.into_iter().map(Into::into));
        self
    }

    /// Adds options after the input.
    pub fn args<S: Into<String>>(mut self, args: impl IntoIterator<Item = S>) -> Self {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// Sets the output bound.
    pub fn max_output(mut self, bytes: u64) -> Self {
        self.max_output = Some(bytes);
        self
    }

    /// Sets a time limit for this call.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Whether `needle` is one of the options (before or after the input).
    pub fn has_arg(&self, needle: &str) -> bool {
        self.before_input.iter().chain(&self.args).any(|a| a == needle)
    }

    /// The value after option `name` (the first occurrence, before or after the input).
    pub fn arg_value(&self, name: &str) -> Option<&str> {
        let all: Vec<&String> = self.before_input.iter().chain(&self.args).collect();
        all.windows(2).find(|w| w[0] == name).map(|w| w[1].as_str())
    }

    /// Checks the job against the hardening rules without running anything. [`Runner`] and
    /// [`FakeRunner`] both call it.
    pub fn validate(&self, limits: &Limits) -> Result<()> {
        const OPTIONS_REFUSED: &[&str] = &[
            "-i",
            "-filter_script",
            "-filter_complex_script",
            "-/filter",
            "-attach",
            "-dump_attachment",
            "-report",
            "-protocol_whitelist",
            "-protocol_blacklist",
            "-format_whitelist",
            "-safe",
            "-reconnect",
            "-headers",
            "-user_agent",
            "-stdin",
        ];
        let protocol = |a: &str| {
            let lower = a.to_ascii_lowercase();
            lower.contains("://")
                || [
                    "file:", "pipe:", "fd:", "concat:", "concatf:", "subfile:", "data:", "crypto:", "async:", "cache:", "tee:", "http:", "https:",
                    "ftp:", "tcp:", "udp:", "rtp:", "rtmp", "rtsp:", "srt:", "tls:", "unix:", "gopher:", "sftp:", "smb:", "hls:", "ipfs",
                ]
                .iter()
                .any(|p| lower.starts_with(p))
        };
        let all: Vec<&String> = self.before_input.iter().chain(&self.args).collect();
        for (i, a) in all.iter().enumerate() {
            if OPTIONS_REFUSED.contains(&a.as_str()) {
                return Err(MediaError::refused(format!("option {a} is not allowed in a job")));
            }
            let last_output = self.tool == Tool::Ffmpeg && i + 1 == all.len() && (a.as_str() == "pipe:1" || a.as_str() == "-");
            if !last_output && protocol(a) {
                return Err(MediaError::refused("URLs and protocol prefixes are not allowed in a job"));
            }
        }
        // An input demuxer may be named, but only an allowed one.
        let before: Vec<&String> = self.before_input.iter().collect();
        for w in before.windows(2) {
            if w[0] == "-f" && !limits.formats.iter().any(|f| f == w[1]) {
                return Err(MediaError::refused(format!("input format {} is not allowed", w[1])));
            }
        }
        if self.tool == Tool::Ffmpeg {
            match self.args.last().map(String::as_str) {
                Some("pipe:1") => {}
                Some("-") if self.arg_value("-f") == Some("null") => {}
                _ => return Err(MediaError::refused("ffmpeg output must be pipe:1 (or - with the null muxer)")),
            }
        }
        if let Input::File(p) = &self.input
            && protocol(&p.to_string_lossy())
        {
            return Err(MediaError::refused("the input must be a local file path, not a URL"));
        }
        Ok(())
    }
}

/// Runs jobs. [`Runner`] runs ffmpeg; [`FakeRunner`] answers in tests.
pub trait Exec {
    /// Runs `job` and returns what it wrote to its output.
    fn exec(&self, job: &Job) -> Result<Vec<u8>>;
}

impl<T: Exec + ?Sized> Exec for &T {
    fn exec(&self, job: &Job) -> Result<Vec<u8>> {
        (**self).exec(job)
    }
}

impl<T: Exec + ?Sized> Exec for Arc<T> {
    fn exec(&self, job: &Job) -> Result<Vec<u8>> {
        (**self).exec(job)
    }
}

impl<T: Exec + ?Sized> Exec for Box<T> {
    fn exec(&self, job: &Job) -> Result<Vec<u8>> {
        (**self).exec(job)
    }
}

/// The limits every child runs under.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
    /// Wall time per call (default 120 s).
    pub timeout: Duration,
    /// Address space per child, Unix only (default 1 GiB; `None` leaves it alone).
    pub address_space: Option<u64>,
    /// The most output any call may produce (default 512 MiB). A job's own bound is capped by it.
    pub max_output: u64,
    /// The largest input (default 2 GiB).
    pub max_input_bytes: u64,
    /// The niceness added to children, Unix only (default 10).
    pub nice: Option<i32>,
    /// On Linux, try a new user and network namespace for each child (default on; skipped quietly
    /// where unprivileged user namespaces are off).
    pub isolate_network: bool,
    /// Decoder threads (`-threads`, default 2; `None` lets ffmpeg choose).
    pub threads: Option<u32>,
    /// Allowed demuxers (default [`DEFAULT_FORMATS`]).
    pub formats: Vec<String>,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            timeout: Duration::from_secs(120),
            address_space: Some(1 << 30),
            max_output: 512 << 20,
            max_input_bytes: 2 << 30,
            nice: Some(10),
            isolate_network: true,
            threads: Some(2),
            formats: DEFAULT_FORMATS.iter().map(|s| s.to_string()).collect(),
        }
    }
}

impl Limits {
    /// Sets the wall time per call.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets the address-space limit (`None` for none).
    pub fn with_address_space(mut self, bytes: Option<u64>) -> Self {
        self.address_space = bytes;
        self
    }

    /// Sets the largest output.
    pub fn with_max_output(mut self, bytes: u64) -> Self {
        self.max_output = bytes;
        self
    }

    /// Sets the largest input.
    pub fn with_max_input_bytes(mut self, bytes: u64) -> Self {
        self.max_input_bytes = bytes;
        self
    }

    /// Sets the niceness (`None` for unchanged).
    pub fn with_nice(mut self, nice: Option<i32>) -> Self {
        self.nice = nice;
        self
    }

    /// Turns the Linux network namespace on or off.
    pub fn with_isolate_network(mut self, on: bool) -> Self {
        self.isolate_network = on;
        self
    }

    /// Sets decoder threads.
    pub fn with_threads(mut self, threads: Option<u32>) -> Self {
        self.threads = threads;
        self
    }

    /// Replaces the demuxer allowlist.
    pub fn with_formats<S: Into<String>>(mut self, formats: impl IntoIterator<Item = S>) -> Self {
        self.formats = formats.into_iter().map(Into::into).collect();
        self
    }
}

/// The two programs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binaries {
    pub ffmpeg: PathBuf,
    pub ffprobe: PathBuf,
}

fn exe(name: &str) -> String {
    if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }
}

impl Binaries {
    /// Both programs at the given paths.
    pub fn new(ffmpeg: impl Into<PathBuf>, ffprobe: impl Into<PathBuf>) -> Self {
        Binaries { ffmpeg: ffmpeg.into(), ffprobe: ffprobe.into() }
    }

    /// Finds ffmpeg and ffprobe: the ffmpeg binary named by the environment variable `env` (with
    /// ffprobe beside it), then beside the running executable (and in `../Helpers` for a macOS app
    /// bundle), then on `PATH`.
    pub fn locate(env: Option<&str>) -> Option<Binaries> {
        Self::locate_from(
            env.and_then(std::env::var_os).map(PathBuf::from),
            std::env::current_exe().ok().as_deref(),
            std::env::var_os("PATH").as_deref(),
        )
    }

    /// [`Binaries::locate`] with its inputs given: an override ffmpeg path, the running executable
    /// and `PATH`.
    pub fn locate_from(ffmpeg: Option<PathBuf>, current_exe: Option<&Path>, path: Option<&OsStr>) -> Option<Binaries> {
        let pair = |dir: &Path| {
            let (f, p) = (dir.join(exe("ffmpeg")), dir.join(exe("ffprobe")));
            (f.is_file() && p.is_file()).then_some(Binaries { ffmpeg: f, ffprobe: p })
        };
        if let Some(f) = ffmpeg.filter(|p| p.is_file()) {
            let probe = f.parent().map(|d| d.join(exe("ffprobe"))).filter(|p| p.is_file())?;
            return Some(Binaries { ffmpeg: f, ffprobe: probe });
        }
        if let Some(dir) = current_exe.and_then(Path::parent)
            && let Some(found) = pair(dir).or_else(|| pair(&dir.join("..").join("Helpers")))
        {
            return Some(found);
        }
        std::env::split_paths(path?).find_map(|d| pair(&d))
    }
}

/// The hardened ffmpeg/ffprobe runner. See the [module docs](self).
#[derive(Debug, Clone)]
pub struct Runner {
    bin: Binaries,
    limits: Limits,
}

impl Runner {
    /// A runner for `bin` with the default [`Limits`].
    pub fn new(bin: Binaries) -> Self {
        Runner { bin, limits: Limits::default() }
    }

    /// Finds the programs as [`Binaries::locate`] does; the error names `env` so a user knows what to
    /// set.
    pub fn locate(env: Option<&str>) -> Result<Self> {
        Binaries::locate(env).map(Runner::new).ok_or_else(|| {
            MediaError::Unavailable(match env {
                Some(var) => format!("ffmpeg and ffprobe were not found; install them, or set {var} to an ffmpeg binary with ffprobe beside it"),
                None => "ffmpeg and ffprobe were not found; install them".to_string(),
            })
        })
    }

    /// Replaces the limits.
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// The limits.
    pub fn limits(&self) -> &Limits {
        &self.limits
    }

    /// The programs.
    pub fn binaries(&self) -> &Binaries {
        &self.bin
    }

    /// The program and arguments `job` would run with, after validation (nothing runs).
    pub fn command_line(&self, job: &Job) -> Result<(PathBuf, Vec<OsString>)> {
        job.validate(&self.limits)?;
        let input: OsString = match &job.input {
            Input::Bytes(b) => {
                if b.len() as u64 > self.limits.max_input_bytes {
                    return Err(MediaError::limit(format!("input is {} bytes, over the {}-byte limit", b.len(), self.limits.max_input_bytes)));
                }
                "pipe:0".into()
            }
            Input::File(p) => {
                let meta = std::fs::metadata(p)?;
                if !meta.is_file() {
                    return Err(MediaError::refused("the input is not a regular file"));
                }
                if meta.len() > self.limits.max_input_bytes {
                    return Err(MediaError::limit(format!("input is {} bytes, over the {}-byte limit", meta.len(), self.limits.max_input_bytes)));
                }
                let canon = plain_path(std::fs::canonicalize(p)?);
                let mut s = OsString::from("file:");
                s.push(canon.as_os_str());
                s
            }
        };
        let formats = self.limits.formats.join(",");
        let mut args: Vec<OsString> = Vec::new();
        let mut push = |a: &str| args.push(a.into());
        match job.tool {
            Tool::Ffmpeg => {
                for a in ["-nostdin", "-hide_banner", "-loglevel", "error"] {
                    push(a);
                }
            }
            Tool::Ffprobe => {
                for a in ["-hide_banner", "-loglevel", "error"] {
                    push(a);
                }
            }
        }
        for a in ["-protocol_whitelist", "file,pipe", "-format_whitelist", &formats] {
            push(a);
        }
        if job.tool == Tool::Ffmpeg
            && let Some(t) = self.limits.threads
        {
            push("-threads");
            push(&t.to_string());
        }
        for a in &job.before_input {
            push(a);
        }
        match job.tool {
            Tool::Ffmpeg => {
                args.push("-i".into());
                args.push(input);
                args.extend(job.args.iter().map(OsString::from));
            }
            Tool::Ffprobe => {
                args.extend(job.args.iter().map(OsString::from));
                args.push(input);
            }
        }
        let program = match job.tool {
            Tool::Ffmpeg => self.bin.ffmpeg.clone(),
            Tool::Ffprobe => self.bin.ffprobe.clone(),
        };
        Ok((program, args))
    }
}

/// Drops Windows' `\\?\` prefix from a canonical drive path so ffmpeg can open it.
fn plain_path(p: PathBuf) -> PathBuf {
    if cfg!(windows) {
        let s = p.to_string_lossy();
        if let Some(rest) = s.strip_prefix(r"\\?\")
            && rest.as_bytes().get(1) == Some(&b':')
        {
            return PathBuf::from(rest.to_string());
        }
    }
    p
}

fn truncate(text: &str, max: usize) -> String {
    if text.len() <= max {
        return text.trim().to_string();
    }
    let mut end = max;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}…", text[..end].trim())
}

impl Exec for Runner {
    fn exec(&self, job: &Job) -> Result<Vec<u8>> {
        let (program, args) = self.command_line(job)?;
        let tool = job.tool.name();
        let cap = job.max_output.unwrap_or(self.limits.max_output).min(self.limits.max_output);
        let timeout = job.timeout.unwrap_or(self.limits.timeout).min(self.limits.timeout);
        let mut cmd = Command::new(&program);
        cmd.args(&args);
        cmd.env("MALLOC_ARENA_MAX", "2");
        cmd.stdin(if matches!(job.input, Input::Bytes(_)) { Stdio::piped() } else { Stdio::null() });
        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt as _;
            let nice = self.limits.nice;
            let space = self.limits.address_space;
            let isolate = self.limits.isolate_network;
            // SAFETY: only async-signal-safe system calls run between fork and exec, and their
            // failures are ignored (each limit is best effort on top of the others).
            unsafe {
                cmd.pre_exec(move || {
                    if let Some(n) = nice {
                        libc::nice(n);
                    }
                    if let Some(bytes) = space {
                        let r = libc::rlimit { rlim_cur: bytes as libc::rlim_t, rlim_max: bytes as libc::rlim_t };
                        libc::setrlimit(libc::RLIMIT_AS, &r);
                    }
                    #[cfg(target_os = "linux")]
                    if isolate {
                        libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNET);
                    }
                    #[cfg(not(target_os = "linux"))]
                    let _ = isolate;
                    Ok(())
                });
            }
        }
        let mut child = cmd.spawn().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                MediaError::Unavailable(format!("{tool} is not installed where it was expected"))
            } else {
                MediaError::Unavailable(format!("couldn't start {tool}: {e}"))
            }
        })?;
        let writer = match (&job.input, child.stdin.take()) {
            (Input::Bytes(bytes), Some(mut stdin)) => {
                let bytes = Arc::clone(bytes);
                Some(std::thread::spawn(move || {
                    let _ = stdin.write_all(&bytes);
                }))
            }
            _ => None,
        };
        let mut out = child.stdout.take().ok_or_else(|| MediaError::Unavailable(format!("{tool} gave no output pipe")))?;
        let mut err = child.stderr.take().ok_or_else(|| MediaError::Unavailable(format!("{tool} gave no error pipe")))?;
        let over = Arc::new(AtomicBool::new(false));
        let over_r = Arc::clone(&over);
        let reader = std::thread::spawn(move || {
            let mut buf = Vec::new();
            let mut chunk = [0u8; 64 * 1024];
            loop {
                match out.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        if buf.len() as u64 + n as u64 > cap {
                            over_r.store(true, Ordering::SeqCst);
                            break;
                        }
                        buf.extend_from_slice(&chunk[..n]);
                    }
                }
            }
            buf
        });
        let err_reader = std::thread::spawn(move || {
            let mut b = Vec::new();
            let _ = (&mut err).take(64 * 1024).read_to_end(&mut b);
            // Keep draining so the child never blocks on a full stderr pipe.
            let _ = std::io::copy(&mut err, &mut std::io::sink());
            b
        });
        let deadline = Instant::now() + timeout;
        let status = loop {
            match child.try_wait() {
                Ok(Some(s)) => break s,
                Ok(None) if over.load(Ordering::SeqCst) => {
                    let _ = child.kill();
                    let _ = child.wait();
                    let _ = reader.join();
                    let _ = err_reader.join();
                    return Err(MediaError::limit(format!("{tool} output passed the {cap}-byte bound and was stopped")));
                }
                Ok(None) if Instant::now() >= deadline => {
                    let _ = child.kill();
                    let _ = child.wait();
                    let _ = reader.join();
                    let _ = err_reader.join();
                    return Err(MediaError::Timeout { seconds: timeout.as_secs() });
                }
                Ok(None) => std::thread::sleep(Duration::from_millis(10)),
                Err(e) => return Err(MediaError::Unavailable(format!("{tool}: {e}"))),
            }
        };
        if let Some(w) = writer {
            let _ = w.join();
        }
        let stdout = reader.join().unwrap_or_default();
        let stderr = err_reader.join().unwrap_or_default();
        if over.load(Ordering::SeqCst) {
            return Err(MediaError::limit(format!("{tool} output passed the {cap}-byte bound and was stopped")));
        }
        if !status.success() {
            return Err(MediaError::Failed { tool, status: status.to_string(), stderr: truncate(&String::from_utf8_lossy(&stderr), STDERR_KEEP) });
        }
        Ok(stdout)
    }
}

/// A private temporary directory (mode 0700 on Unix), removed with everything in it on drop, so
/// also on early return, panic unwinding and cancellation.
#[derive(Debug)]
pub struct PrivateDir {
    path: PathBuf,
}

impl PrivateDir {
    /// A new directory under the system temp dir.
    pub fn new() -> Result<Self> {
        Self::new_in(&std::env::temp_dir())
    }

    /// A new directory under `parent`.
    pub fn new_in(parent: &Path) -> Result<Self> {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
        for _ in 0..16 {
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let path = parent.join(format!("weirdnet-media-{}-{nanos:x}-{n}", std::process::id()));
            #[cfg(unix)]
            let builder = {
                use std::os::unix::fs::DirBuilderExt as _;
                let mut b = std::fs::DirBuilder::new();
                b.mode(0o700);
                b
            };
            #[cfg(not(unix))]
            let builder = std::fs::DirBuilder::new();
            match builder.create(&path) {
                Ok(()) => return Ok(PrivateDir { path }),
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Err(MediaError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "couldn't create a private temp dir")))
    }

    /// The directory.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Writes `bytes` to `name` inside the directory and returns its path. `name` must be a plain
    /// file name.
    pub fn write(&self, name: &str, bytes: &[u8]) -> Result<PathBuf> {
        if name.is_empty() || name.contains(['/', '\\']) || name == "." || name == ".." {
            return Err(MediaError::refused("a private file name must be a plain name"));
        }
        let path = self.path.join(name);
        std::fs::write(&path, bytes)?;
        Ok(path)
    }
}

impl Drop for PrivateDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

type Matcher = Box<dyn Fn(&Job) -> bool + Send + Sync>;
type Responder = Box<dyn Fn(&Job) -> Result<Vec<u8>> + Send + Sync>;

/// What a [`FakeRunner`] pretends the input is.
#[derive(Debug, Clone, PartialEq)]
pub struct FakeMedia {
    /// The demuxer name it reports (`mov,mp4,m4a,3gp,3g2,mj2` by default).
    pub format: String,
    pub duration_ms: u64,
    /// `(width, height, fps)` for a video stream; `None` for audio only.
    pub video: Option<(u32, u32, f32)>,
    /// Whether there is an audio stream.
    pub audio: bool,
    /// Scene changes `(ms, score)` the scene detector reports.
    pub scenes: Vec<(u64, f32)>,
    /// Keyframe times.
    pub keyframes: Vec<u64>,
}

impl FakeMedia {
    /// A 1920x1080, 30 fps MP4 of `duration_ms`, keyframes every 2 s.
    pub fn video(duration_ms: u64, audio: bool) -> Self {
        FakeMedia {
            format: "mov,mp4,m4a,3gp,3g2,mj2".into(),
            duration_ms,
            video: Some((1920, 1080, 30.0)),
            audio,
            scenes: Vec::new(),
            keyframes: (0..duration_ms).step_by(2000).collect(),
        }
    }

    /// An audio-only file in container `format` (`mp3`, `ogg`, ...).
    pub fn audio(format: &str, duration_ms: u64) -> Self {
        FakeMedia { format: format.into(), duration_ms, video: None, audio: true, scenes: Vec::new(), keyframes: Vec::new() }
    }

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

    /// The ffprobe JSON this media would produce.
    pub fn ffprobe_json(&self) -> String {
        let mut streams = Vec::new();
        if let Some((w, h, fps)) = self.video {
            streams.push(serde_json::json!({
                "codec_type": "video", "codec_name": "h264", "width": w, "height": h,
                "avg_frame_rate": format!("{}/1000", (fps * 1000.0).round() as u64),
                "disposition": {"attached_pic": 0}
            }));
        }
        if self.audio {
            streams.push(serde_json::json!({"codec_type": "audio", "codec_name": "aac", "sample_rate": "48000", "channels": 2}));
        }
        serde_json::json!({
            "format": {"format_name": self.format, "duration": format!("{:.3}", self.duration_ms as f64 / 1000.0)},
            "streams": streams
        })
        .to_string()
    }

    fn respond(&self, job: &Job) -> Result<Vec<u8>> {
        let secs = |v: Option<&str>| v.and_then(|s| s.parse::<f64>().ok()).map(|s| (s * 1000.0).round() as u64);
        match job.tool {
            Tool::Ffprobe if job.has_arg("-show_entries") => {
                let mut out = String::new();
                for k in &self.keyframes {
                    out.push_str(&format!("{:.6},K__\n", *k as f64 / 1000.0));
                }
                Ok(out.into_bytes())
            }
            Tool::Ffprobe => Ok(self.ffprobe_json().into_bytes()),
            Tool::Ffmpeg => {
                let start = secs(job.arg_value("-ss")).unwrap_or(0);
                let fmt = job.args.windows(2).rev().find(|w| w[0] == "-f").map(|w| w[1].as_str()).unwrap_or("");
                match fmt {
                    "image2pipe" => {
                        if self.video.is_none() {
                            return Err(MediaError::Failed { tool: "ffmpeg", status: "exit status: 1".into(), stderr: "no video stream".into() });
                        }
                        let scale = job.arg_value("-vf").unwrap_or("");
                        let mut b = vec![0xFF, 0xD8, 0xFF];
                        b.extend(format!("{start}@{scale}").into_bytes());
                        Ok(b)
                    }
                    "wav" => {
                        if !self.audio {
                            return Err(MediaError::Failed { tool: "ffmpeg", status: "exit status: 1".into(), stderr: "no audio stream".into() });
                        }
                        let rate: u32 = job.arg_value("-ar").and_then(|r| r.parse().ok()).unwrap_or(16_000);
                        let channels: u16 = job.arg_value("-ac").and_then(|r| r.parse().ok()).unwrap_or(1);
                        let len =
                            secs(job.arg_value("-t")).unwrap_or(self.duration_ms.saturating_sub(start)).min(self.duration_ms.saturating_sub(start));
                        let frames = (u64::from(rate) * len / 1000) as usize;
                        let pcm = crate::pcm::Pcm::new(rate, channels, vec![0; frames * channels as usize]);
                        Ok(crate::pcm::encode_wav(&pcm))
                    }
                    "null" => {
                        let mut out = String::new();
                        let threshold = job
                            .arg_value("-vf")
                            .and_then(|vf| vf.split("gt(scene,").nth(1))
                            .and_then(|r| r.split(')').next())
                            .and_then(|t| t.parse::<f32>().ok())
                            .unwrap_or(0.0);
                        for (i, (t, s)) in self.scenes.iter().enumerate().filter(|(_, (_, s))| *s > threshold) {
                            out.push_str(&format!("frame:{i} pts:{t} pts_time:{:.3}\nlavfi.scene_score={s:.6}\n", *t as f64 / 1000.0));
                        }
                        Ok(out.into_bytes())
                    }
                    other => {
                        let len = secs(job.arg_value("-t")).unwrap_or(0);
                        let input = job.input.len().unwrap_or(0);
                        Ok(format!("FAKE {other} ss={start} t={len} in={input}").into_bytes())
                    }
                }
            }
        }
    }
}

/// An [`Exec`] for tests: no child processes. Jobs are validated as [`Runner`] validates them,
/// recorded, and answered by the first matching rule, else by the [`FakeMedia`] if one is set.
pub struct FakeRunner {
    rules: Vec<(Matcher, Responder)>,
    media: Option<FakeMedia>,
    limits: Limits,
    calls: Mutex<Vec<Job>>,
}

impl std::fmt::Debug for FakeRunner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FakeRunner").field("rules", &self.rules.len()).field("media", &self.media).finish()
    }
}

impl Default for FakeRunner {
    fn default() -> Self {
        Self::new()
    }
}

impl FakeRunner {
    /// A fake that answers nothing until given rules or media.
    pub fn new() -> Self {
        FakeRunner { rules: Vec::new(), media: None, limits: Limits::default(), calls: Mutex::new(Vec::new()) }
    }

    /// A fake whose input is `media` for every job.
    pub fn with_media(media: FakeMedia) -> Self {
        FakeRunner { media: Some(media), ..Self::new() }
    }

    /// Adds a rule: jobs for which `matches` is true get `respond`'s answer.
    pub fn on(
        mut self,
        matches: impl Fn(&Job) -> bool + Send + Sync + 'static,
        respond: impl Fn(&Job) -> Result<Vec<u8>> + Send + Sync + 'static,
    ) -> Self {
        self.rules.push((Box::new(matches), Box::new(respond)));
        self
    }

    /// Every ffprobe job answers `output`.
    pub fn on_ffprobe(self, output: impl Into<Vec<u8>>) -> Self {
        let output = output.into();
        self.on(|j| j.tool == Tool::Ffprobe, move |_| Ok(output.clone()))
    }

    /// Every ffmpeg job that has `arg` among its options answers `output`.
    pub fn on_arg(self, arg: &str, output: impl Into<Vec<u8>>) -> Self {
        let (arg, output) = (arg.to_string(), output.into());
        self.on(move |j| j.tool == Tool::Ffmpeg && j.has_arg(&arg), move |_| Ok(output.clone()))
    }

    /// Validates with these limits instead of the defaults.
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// The jobs run so far, in order.
    pub fn calls(&self) -> Vec<Job> {
        self.calls.lock().map(|c| c.clone()).unwrap_or_default()
    }
}

impl Exec for FakeRunner {
    fn exec(&self, job: &Job) -> Result<Vec<u8>> {
        job.validate(&self.limits)?;
        if let Ok(mut c) = self.calls.lock() {
            c.push(job.clone());
        }
        if let Some((_, respond)) = self.rules.iter().find(|(m, _)| m(job)) {
            return respond(job);
        }
        match &self.media {
            Some(media) => media.respond(job),
            None => Err(MediaError::Unavailable(format!("FakeRunner has no rule for this {} job", job.tool.name()))),
        }
    }
}