ferraus-core 0.1.2

Core types for ferraus: audio buffers, unit parsing, operation specs, pipelines, provenance
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
//! The execution context handed to every op: global flags, input/output helpers, and
//! the collectors for warnings, metrics, models, and resolved parameter notes.

use crate::buffer::AudioBuffer;
use crate::error::{Error, ErrorKind, Result};
use serde::Serialize;
use serde_json::{Map, Value};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Information about a decoded source.
#[derive(Clone, Debug, Default, Serialize)]
pub struct SourceInfo {
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub codec: Option<String>,
    pub duration_s: f64,
    pub sample_rate: u32,
    pub channels: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bit_depth: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bitrate: Option<u32>,
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub tags: std::collections::BTreeMap<String, String>,
}

/// Encoding options for an output.
#[derive(Clone, Debug, Default, Serialize)]
pub struct EncodeOptions {
    /// Container/codec name (`wav`, `flac`, `mp3`, `ogg`, `opus`, `m4a`, `aiff`). Inferred
    /// from the path extension when `None`.
    pub format: Option<String>,
    pub bit_depth: Option<u16>,
    /// Write 32-bit float WAV.
    pub float: bool,
    pub bitrate: Option<u32>,
    pub vbr: bool,
    /// `triangular` (default when reducing bit depth), `shaped`, `none`.
    pub dither: Option<String>,
    pub seed: u64,
    pub tags: std::collections::BTreeMap<String, String>,
}

/// Decoding and encoding, implemented by `ferraus-codec` and injected by the CLI.
pub trait AudioIo: Send + Sync {
    fn read(&self, path: &Path) -> Result<(AudioBuffer, SourceInfo)>;
    /// Read from bytes (stdin) with a format hint.
    fn read_bytes(&self, bytes: &[u8], format_hint: Option<&str>) -> Result<(AudioBuffer, SourceInfo)>;
    fn probe(&self, path: &Path) -> Result<SourceInfo>;
    fn write(&self, path: &Path, buf: &AudioBuffer, opts: &EncodeOptions) -> Result<()>;
    fn write_bytes(&self, buf: &AudioBuffer, opts: &EncodeOptions) -> Result<Vec<u8>>;
    /// Extensions this build can encode.
    fn can_encode(&self, ext: &str) -> bool;
    /// Open `path` for streaming decode, or `None` when it can only be read whole (callers then
    /// use [`AudioIo::read`]). The chunks concatenate to exactly the samples `read` returns.
    fn open_reader(&self, _path: &Path) -> Result<Option<Box<dyn AudioReader>>> {
        Ok(None)
    }
    /// Open `path` for streaming encode of `frames` frames, or `None` when the format needs the
    /// whole buffer (resampling, an external encoder). The file's bytes equal what
    /// [`AudioIo::write`] writes for the same samples.
    fn open_writer(
        &self,
        _path: &Path,
        _sample_rate: u32,
        _channels: usize,
        _frames: u64,
        _opts: &EncodeOptions,
    ) -> Result<Option<Box<dyn AudioWriter>>> {
        Ok(None)
    }
}

/// A streaming decoder (see [`AudioIo::open_reader`]): planar chunks in file order, every
/// chunk with the channel count of the first.
pub trait AudioReader {
    /// What the container declares (sample rate, channels, duration).
    fn info(&self) -> &SourceInfo;
    /// Frames the container declares, if it does.
    fn frames_hint(&self) -> Option<u64>;
    fn next_chunk(&mut self) -> Result<Option<AudioBuffer>>;
}

/// A streaming encoder for one file (see [`AudioIo::open_writer`]).
pub trait AudioWriter {
    /// Encode one planar block (every channel the same length).
    fn write(&mut self, planes: &[&[f32]]) -> Result<()>;
    /// Finish the file (sizes in headers, tags).
    fn finish(self: Box<Self>) -> Result<()>;
}

/// Progress sink (stderr bar, NDJSON events, or nothing).
pub trait Progress: Send + Sync {
    fn stage(&self, _stage: &str, _index: usize, _of: usize) {}
    fn progress(&self, _stage: &str, _fraction: f64) {}
    fn output(&self, _path: &str, _role: Option<&str>) {}
    fn warning(&self, _code: &str, _message: &str) {}
    fn log(&self, _message: &str) {}
}

pub struct NoProgress;
impl Progress for NoProgress {}

/// Flags accepted by every command.
#[derive(Clone, Debug, Serialize)]
pub struct Globals {
    pub output: Option<String>,
    pub outdir: Option<PathBuf>,
    pub format: Option<String>,
    pub input_format: Option<String>,
    pub overwrite: bool,
    pub in_place: bool,
    pub sidecar: bool,
    pub dry_run: bool,
    pub explain: bool,
    pub force: bool,
    pub sample_rate: Option<u32>,
    pub bit_depth: Option<u16>,
    pub channels: Option<usize>,
    pub bitrate: Option<u32>,
    pub seed: u64,
    pub threads: usize,
    pub device: String,
    pub deterministic: bool,
    pub offline: bool,
    pub yes: bool,
    pub bpm: Option<f64>,
    pub sound_paths: Vec<PathBuf>,
    pub max_memory: u64,
    /// When set, every read and write must stay inside one of these directories (MCP sandbox).
    pub allow: Vec<PathBuf>,
    pub config_path: Option<PathBuf>,
}

impl Default for Globals {
    fn default() -> Self {
        Globals {
            output: None,
            outdir: None,
            format: None,
            input_format: None,
            overwrite: false,
            in_place: false,
            sidecar: true,
            dry_run: false,
            explain: false,
            force: false,
            sample_rate: None,
            bit_depth: None,
            channels: None,
            bitrate: None,
            seed: 0,
            threads: 0,
            device: "auto".into(),
            deterministic: false,
            offline: false,
            yes: false,
            bpm: None,
            sound_paths: Vec::new(),
            max_memory: 2 * 1024 * 1024 * 1024,
            allow: Vec::new(),
            config_path: None,
        }
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct OutputRecord {
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_s: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sample_rate: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channels: Option<usize>,
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub extra: Map<String, Value>,
}

#[derive(Clone, Debug, Serialize)]
pub struct WarningRecord {
    pub code: String,
    pub message: String,
}

#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct ModelRecord {
    pub name: String,
    pub version: String,
    pub sha256: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct InputRecord {
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_s: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sample_rate: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channels: Option<usize>,
}

/// Cancellation flag shared with signal handlers and job runners.
#[derive(Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);

impl CancelToken {
    pub fn cancel(&self) {
        self.0.store(true, Ordering::SeqCst)
    }
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::SeqCst)
    }
    pub fn check(&self) -> Result<()> {
        if self.is_cancelled() {
            Err(Error::cancelled("cancelled"))
        } else {
            Ok(())
        }
    }
}

/// Context for one op invocation.
pub struct OpCtx<'a> {
    /// The command path being run (e.g. `separate`).
    pub command: String,
    pub inputs: Vec<PathBuf>,
    pub globals: Globals,
    pub io: &'a dyn AudioIo,
    pub progress: &'a dyn Progress,
    pub cancel: CancelToken,
    /// Registry of every op, for ops that compose others (master, enhance, hum...).
    pub registry: Option<&'a crate::registry::Registry>,
    pub outputs: Vec<OutputRecord>,
    pub input_records: Vec<InputRecord>,
    pub warnings: Vec<WarningRecord>,
    pub metrics: Map<String, Value>,
    /// Parameter values resolved at run time (detected key, chosen noise region...).
    pub notes: Map<String, Value>,
    pub models: Vec<ModelRecord>,
    pub plugins: Vec<Value>,
    /// False when a stage may be nondeterministic (plugins with internal randomness).
    pub deterministic: Option<bool>,
    /// Stdin bytes (when an input is `-`).
    pub stdin: Option<Vec<u8>>,
    /// Bytes to write to stdout when `-o -`.
    pub stdout: Option<Vec<u8>>,
    /// Index of this item in a batch (for `{index}` in output templates).
    pub index: usize,
    /// Files created by this op that must be removed if the op fails.
    pub temp_files: Vec<PathBuf>,
    /// Result value set by a Transform op (custom ops return theirs directly).
    pub result: Option<Value>,
}

impl<'a> OpCtx<'a> {
    pub fn new(
        command: &str,
        inputs: Vec<PathBuf>,
        globals: Globals,
        io: &'a dyn AudioIo,
        progress: &'a dyn Progress,
    ) -> Self {
        OpCtx {
            command: command.to_string(),
            inputs,
            globals,
            io,
            progress,
            cancel: CancelToken::default(),
            registry: None,
            outputs: Vec::new(),
            input_records: Vec::new(),
            warnings: Vec::new(),
            metrics: Map::new(),
            notes: Map::new(),
            models: Vec::new(),
            plugins: Vec::new(),
            deterministic: None,
            stdin: None,
            stdout: None,
            index: 0,
            temp_files: Vec::new(),
            result: None,
        }
    }

    /// A child context for running a nested op (shares io, progress, globals, registry).
    pub fn child(&self, command: &str, inputs: Vec<PathBuf>) -> OpCtx<'a> {
        let mut c = OpCtx::new(command, inputs, self.globals.clone(), self.io, self.progress);
        c.cancel = self.cancel.clone();
        c.registry = self.registry;
        c
    }

    /// Merge a child's records into this context.
    pub fn absorb(&mut self, child: OpCtx<'a>) {
        self.warnings.extend(child.warnings);
        for m in child.models {
            if !self.models.contains(&m) {
                self.models.push(m);
            }
        }
        self.plugins.extend(child.plugins);
        if child.deterministic == Some(false) {
            self.deterministic = Some(false);
        }
    }

    pub fn bpm(&self) -> Option<f64> {
        self.globals.bpm
    }

    pub fn seed(&self) -> u64 {
        self.globals.seed
    }

    pub fn input(&self, i: usize) -> Result<&Path> {
        self.inputs
            .get(i)
            .map(|p| p.as_path())
            .ok_or_else(|| Error::usage(format!("'{}' needs at least {} input(s)", self.command, i + 1)))
    }

    /// Check that a path is inside the sandbox (when one is set).
    pub fn check_allowed(&self, path: &Path) -> Result<()> {
        if self.globals.allow.is_empty() {
            return Ok(());
        }
        let abs = absolutize(path);
        if self.globals.allow.iter().any(|a| abs.starts_with(absolutize(a))) {
            Ok(())
        } else {
            Err(Error::new(
                ErrorKind::Usage,
                "path_not_allowed",
                format!("{} is outside the allowed directories", path.display()),
            )
            .with_hint("serve with --allow <dir> to permit it"))
        }
    }

    /// Decode input `i` (or stdin for `-`), applying `--channels`/`--sample-rate` only at write time.
    pub fn read_audio(&mut self, i: usize) -> Result<AudioBuffer> {
        let path = self.input(i)?.to_path_buf();
        self.read_audio_path(&path)
    }

    pub fn read_audio_path(&mut self, path: &Path) -> Result<AudioBuffer> {
        let (buf, info) = if path.as_os_str() == "-" {
            let bytes = self.stdin.take().ok_or_else(|| Error::input("stdin was already consumed or is empty"))?;
            let r = self.io.read_bytes(&bytes, self.globals.input_format.as_deref())?;
            self.stdin = Some(bytes);
            r
        } else {
            self.check_allowed(path)?;
            if !path.exists() {
                return Err(Error::new(
                    ErrorKind::InputMissing,
                    "input_not_found",
                    format!("input not found: {}", path.display()),
                ));
            }
            self.io.read(path)?
        };
        self.input_records.push(InputRecord {
            path: info.path.clone(),
            duration_s: Some(info.duration_s),
            sample_rate: Some(info.sample_rate),
            channels: Some(info.channels),
        });
        Ok(buf)
    }

    /// Input `i` as a stream of chunks when the IO layer can stream it; `Ok(None)` means use
    /// [`OpCtx::read_audio`]. Call [`OpCtx::record_stream_input`] once the stream is consumed.
    pub fn open_audio_stream(&mut self, i: usize) -> Result<Option<Box<dyn AudioReader>>> {
        let path = self.input(i)?.to_path_buf();
        if path.as_os_str() == "-" {
            return Ok(None);
        }
        self.check_allowed(&path)?;
        if !path.exists() {
            return Err(Error::new(
                ErrorKind::InputMissing,
                "input_not_found",
                format!("input not found: {}", path.display()),
            ));
        }
        self.io.open_reader(&path)
    }

    /// Record a streamed input as [`OpCtx::read_audio`] would (`frames` = what was decoded).
    pub fn record_stream_input(&mut self, info: &SourceInfo, sample_rate: u32, channels: usize, frames: u64) {
        self.input_records.push(InputRecord {
            path: info.path.clone(),
            duration_s: Some(frames as f64 / sample_rate.max(1) as f64),
            sample_rate: Some(sample_rate),
            channels: Some(channels),
        });
    }

    /// Record a non-audio input (MIDI, score, profile...).
    pub fn note_input(&mut self, path: &Path) {
        self.input_records.push(InputRecord {
            path: path.display().to_string(),
            duration_s: None,
            sample_rate: None,
            channels: None,
        });
    }

    /// Resolve the output path for this op.
    ///
    /// * `role` — e.g. `vocals` for a stem (fills `{stem}`); `None` for the main output.
    /// * `ext` — default extension when the user gave no `-o`.
    ///
    /// Honours `-o` templates (`{name}`, `{stem}`, `{index}`, `{ext}`, `{command}`), `--outdir`,
    /// `--in-place`, and the default `<input>.<command>[.<role>].<ext>` beside the input.
    pub fn output_path(&self, role: Option<&str>, ext: &str) -> Result<PathBuf> {
        let input = self.inputs.first().filter(|p| p.as_os_str() != "-");
        let name = input
            .and_then(|p| p.file_stem())
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "ferraus".to_string());
        let in_ext = input.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase());
        let cmd = self.command.replace(' ', "-");
        let ext = if ext.is_empty() { in_ext.clone().unwrap_or_else(|| "wav".into()) } else { ext.to_string() };

        if self.globals.in_place && role.is_none() {
            if let Some(p) = input {
                return Ok(p.clone());
            }
        }
        let p = if let Some(o) = &self.globals.output {
            if o == "-" {
                return Ok(PathBuf::from("-"));
            }
            // Several outputs from one -o (stems, split parts) must get distinct names: {stem}
            // takes the role; without {stem}, {index} takes it; otherwise the role is inserted
            // before the extension.
            let has_stem = o.contains("{stem}");
            let index_takes_role = role.is_some() && !has_stem && o.contains("{index}");
            let index = if index_takes_role { role.unwrap_or_default().to_string() } else { self.index.to_string() };
            let mut s =
                o.replace("{name}", &name).replace("{index}", &index).replace("{command}", &cmd).replace("{ext}", &ext);
            s = s.replace("{stem}", role.unwrap_or("out"));
            let mut p = PathBuf::from(s);
            if let (Some(role), false, false) = (role, has_stem, index_takes_role) {
                let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
                let e = p.extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_else(|| ext.clone());
                p.set_file_name(format!("{stem}.{role}.{e}"));
            }
            if let Some(dir) = &self.globals.outdir {
                if p.is_relative() {
                    p = dir.join(p);
                }
            }
            p
        } else {
            let file = match role {
                Some(r) => format!("{name}.{r}.{ext}"),
                None => format!("{name}.{cmd}.{ext}"),
            };
            match (&self.globals.outdir, input.and_then(|p| p.parent())) {
                (Some(dir), _) => dir.join(file),
                (None, Some(parent)) => parent.join(file),
                (None, None) => PathBuf::from(file),
            }
        };
        Ok(p)
    }

    /// Check overwrite policy and sandbox for an output path, creating its directory.
    pub fn prepare_output(&self, path: &Path) -> Result<()> {
        if path.as_os_str() == "-" {
            return Ok(());
        }
        self.check_allowed(path)?;
        let is_input = self.inputs.iter().any(|i| i == path);
        if path.exists() && !self.globals.overwrite && !self.globals.force && !(self.globals.in_place && is_input) {
            return Err(Error::new(ErrorKind::Usage, "output_exists", format!("{} already exists", path.display()))
                .with_hint("pass --overwrite (or --force) to replace it, or choose another -o path"));
        }
        if is_input && !self.globals.in_place {
            return Err(Error::usage(format!("output {} is the same as an input; use --in-place", path.display())));
        }
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() && !self.globals.dry_run {
                std::fs::create_dir_all(parent)?;
            }
        }
        Ok(())
    }

    /// Encoding options from global flags for a given output path.
    pub fn encode_options(&self, path: &Path) -> EncodeOptions {
        let format = if path.as_os_str() == "-" {
            Some(self.globals.format.clone().unwrap_or_else(|| "wav".into()))
        } else {
            self.globals.format.clone().or_else(|| path.extension().map(|e| e.to_string_lossy().to_lowercase()))
        };
        EncodeOptions {
            format,
            bit_depth: self.globals.bit_depth,
            float: false,
            bitrate: self.globals.bitrate,
            vbr: true,
            dither: None,
            seed: self.globals.seed,
            tags: Default::default(),
        }
    }

    /// Write an audio output, applying `--sample-rate` and `--channels` conversions is the
    /// caller's job (the executor does it for transforms). Records the output.
    pub fn write_audio(&mut self, path: &Path, buf: &AudioBuffer, role: Option<&str>) -> Result<()> {
        let opts = self.encode_options(path);
        self.write_audio_with(path, buf, role, &opts)
    }

    pub fn write_audio_with(
        &mut self,
        path: &Path,
        buf: &AudioBuffer,
        role: Option<&str>,
        opts: &EncodeOptions,
    ) -> Result<()> {
        self.prepare_output(path)?;
        if !self.globals.dry_run {
            if path.as_os_str() == "-" {
                let bytes = self.io.write_bytes(buf, opts)?;
                self.stdout.get_or_insert_with(Vec::new).extend(bytes);
            } else {
                if self.globals.in_place && path.exists() {
                    let bak = PathBuf::from(format!("{}.bak", path.display()));
                    std::fs::copy(path, &bak)?;
                }
                // write to a temp file then rename, so a failed encode never leaves a partial file
                let tmp = tmp_path(path);
                self.io.write(&tmp, buf, opts).inspect_err(|_| {
                    let _ = std::fs::remove_file(&tmp);
                })?;
                std::fs::rename(&tmp, path)?;
            }
        }
        self.outputs.push(OutputRecord {
            path: path.display().to_string(),
            role: role.map(|r| r.to_string()),
            duration_s: Some(buf.duration_s()),
            sample_rate: Some(buf.sample_rate),
            channels: Some(buf.channels()),
            extra: Map::new(),
        });
        self.progress.output(&path.display().to_string(), role);
        Ok(())
    }

    /// Write an audio output block by block: `produce(sink)` hands `sink` consecutive planar
    /// blocks covering exactly `frames` frames. The output streams to the encoder when the IO
    /// layer can (memory independent of the length); otherwise the blocks are collected and
    /// written with [`OpCtx::write_audio_with`]. The file's bytes are the same either way.
    #[allow(clippy::too_many_arguments)]
    pub fn write_audio_blocks(
        &mut self,
        path: &Path,
        role: Option<&str>,
        opts: &EncodeOptions,
        sample_rate: u32,
        channels: usize,
        frames: usize,
        produce: &mut dyn FnMut(&mut dyn FnMut(&[&[f32]]) -> Result<()>) -> Result<()>,
    ) -> Result<()> {
        if path.as_os_str() != "-" && !self.globals.dry_run && !(self.globals.in_place && path.exists()) {
            self.prepare_output(path)?;
            let tmp = tmp_path(path);
            if let Some(mut w) = self.io.open_writer(&tmp, sample_rate, channels, frames as u64, opts)? {
                let mut written = 0usize;
                let mut sink = |p: &[&[f32]]| {
                    if p.len() != channels {
                        return Err(Error::internal("audio block with the wrong channel count"));
                    }
                    written += p.first().map(|c| c.len()).unwrap_or(0);
                    w.write(p)
                };
                let mut r = produce(&mut sink);
                if r.is_ok() && written != frames {
                    r = Err(Error::internal(format!("streamed {written} frames of {frames}")));
                }
                let r = r.and_then(|_| w.finish()).and_then(|_| std::fs::rename(&tmp, path).map_err(Error::from));
                if let Err(e) = r {
                    let _ = std::fs::remove_file(&tmp);
                    return Err(e);
                }
                self.outputs.push(OutputRecord {
                    path: path.display().to_string(),
                    role: role.map(|r| r.to_string()),
                    duration_s: Some(frames as f64 / sample_rate.max(1) as f64),
                    sample_rate: Some(sample_rate),
                    channels: Some(channels),
                    extra: Map::new(),
                });
                self.progress.output(&path.display().to_string(), role);
                return Ok(());
            }
        }
        let mut data: Vec<Vec<f32>> = (0..channels).map(|_| Vec::with_capacity(frames)).collect();
        produce(&mut |p: &[&[f32]]| {
            for (d, s) in data.iter_mut().zip(p) {
                d.extend_from_slice(s);
            }
            Ok(())
        })?;
        self.write_audio_with(path, &AudioBuffer { sample_rate, data }, role, opts)
    }

    /// Write a non-audio file (JSON, MIDI, text...) and record it.
    pub fn write_file(&mut self, path: &Path, bytes: &[u8], role: Option<&str>) -> Result<()> {
        self.prepare_output(path)?;
        if !self.globals.dry_run {
            if path.as_os_str() == "-" {
                self.stdout.get_or_insert_with(Vec::new).extend_from_slice(bytes);
            } else {
                let tmp = tmp_path(path);
                std::fs::write(&tmp, bytes)?;
                std::fs::rename(&tmp, path)?;
            }
        }
        self.record_output(path, role);
        Ok(())
    }

    /// Record an output that was written by other means (e.g. a helper process).
    pub fn record_output(&mut self, path: &Path, role: Option<&str>) {
        self.outputs.push(OutputRecord {
            path: path.display().to_string(),
            role: role.map(|r| r.to_string()),
            duration_s: None,
            sample_rate: None,
            channels: None,
            extra: Map::new(),
        });
        self.progress.output(&path.display().to_string(), role);
    }

    /// Set the envelope `result` from a Transform op.
    pub fn set_result(&mut self, value: impl Serialize) {
        self.result = Some(serde_json::to_value(value).unwrap_or(Value::Null));
    }

    pub fn warn(&mut self, code: &str, message: impl Into<String>) {
        let message = message.into();
        self.progress.warning(code, &message);
        self.warnings.push(WarningRecord { code: code.to_string(), message });
    }

    pub fn metric(&mut self, key: &str, value: impl Serialize) {
        self.metrics.insert(key.to_string(), serde_json::to_value(value).unwrap_or(Value::Null));
    }

    /// Record a parameter resolved at run time (shown in params and the sidecar).
    pub fn note(&mut self, key: &str, value: impl Serialize) {
        self.notes.insert(key.to_string(), serde_json::to_value(value).unwrap_or(Value::Null));
    }

    pub fn model_used(&mut self, name: &str, version: &str, sha256: &str) {
        let r = ModelRecord { name: name.into(), version: version.into(), sha256: sha256.into() };
        if !self.models.contains(&r) {
            self.models.push(r);
        }
    }

    pub fn set_progress(&self, fraction: f64) {
        self.progress.progress(&self.command, fraction.clamp(0.0, 1.0));
    }

    pub fn check_cancel(&self) -> Result<()> {
        self.cancel.check()
    }

    /// Thread count to use (0 = all cores).
    pub fn threads(&self) -> usize {
        if self.globals.threads == 0 {
            std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1)
        } else {
            self.globals.threads
        }
    }
}

pub fn tmp_path(path: &Path) -> PathBuf {
    let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
    let ext = path.extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default();
    // keep the real extension last so encoders that infer format still work
    path.with_file_name(format!(".{name}.{}.part.{ext}", std::process::id()))
}

pub fn absolutize(p: &Path) -> PathBuf {
    let expanded = if let Ok(s) = p.strip_prefix("~") {
        std::env::var_os("HOME").map(|h| PathBuf::from(h).join(s)).unwrap_or_else(|| p.to_path_buf())
    } else {
        p.to_path_buf()
    };
    let abs =
        if expanded.is_absolute() { expanded } else { std::env::current_dir().unwrap_or_default().join(expanded) };
    // lexical normalization (no symlink resolution so non-existent outputs work)
    let mut out = PathBuf::new();
    for c in abs.components() {
        match c {
            std::path::Component::ParentDir => {
                out.pop();
            }
            std::path::Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}