univert 0.4.0

Universal file converter (library and CLI)
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
use std::fs;
use std::io::BufReader;
use std::process::Command;

use hound::{SampleFormat, WavSpec, WavWriter};

use crate::converters::scad::which_tool;
use crate::{Error, Job, Result, extension_of};

pub fn midi_to_wav(job: &Job) -> Result<()> {
  use std::sync::Arc;

  use rustysynth::{
    MidiFile, MidiFileSequencer, Synthesizer, SynthesizerSettings,
  };

  let (sound_font, sound_font_path) = load_soundfont()?;
  let sound_font = Arc::new(sound_font);

  let mut mid = fs::File::open(job.input)?;
  let midi_file = Arc::new(
    MidiFile::new(&mut mid)
      .map_err(|e| Error::other(format!("load midi: {e}")))?,
  );

  let sample_rate: i32 = 44_100;
  let channels: u16 = 2;
  let bits_per_sample: u16 = 16;
  eprintln!("SoundFont: {sound_font_path}");
  eprintln!(
    "Output: {sample_rate} Hz, {bits_per_sample}-bit PCM, {channels} channels",
  );
  let settings = SynthesizerSettings::new(sample_rate);
  let synthesizer = Synthesizer::new(&sound_font, &settings)
    .map_err(|e| Error::other(format!("synthesizer: {e}")))?;
  let mut sequencer = MidiFileSequencer::new(synthesizer);
  sequencer.play(&midi_file, false);

  let sample_count =
    (sample_rate as f64 * midi_file.get_length()).ceil() as usize;
  let mut left = vec![0f32; sample_count];
  let mut right = vec![0f32; sample_count];
  sequencer.render(&mut left, &mut right);

  let spec = WavSpec {
    channels,
    sample_rate: sample_rate as u32,
    bits_per_sample,
    sample_format: SampleFormat::Int,
  };
  let mut writer = WavWriter::create(job.output, spec)
    .map_err(|e| Error::other(format!("wav create: {e}")))?;

  for (l, r) in left.iter().zip(right.iter()) {
    writer
      .write_sample(f32_to_i16(*l))
      .map_err(|e| Error::other(format!("wav write: {e}")))?;
    writer
      .write_sample(f32_to_i16(*r))
      .map_err(|e| Error::other(format!("wav write: {e}")))?;
  }

  writer
    .finalize()
    .map_err(|e| Error::other(format!("wav finalize: {e}")))?;
  Ok(())
}

fn f32_to_i16(s: f32) -> i16 {
  (s.clamp(-1.0, 1.0) * 32767.0) as i16
}

/// Try each candidate SoundFont in priority order and return the first one
/// that `rustysynth` can actually parse. Existence alone isn't enough: some
/// bundled .sf2 files (e.g. Homebrew fluid-synth's VintageDreamsWaves) use
/// features rustysynth rejects, so we skip past those rather than failing.
fn load_soundfont() -> Result<(rustysynth::SoundFont, String)> {
  let mut candidates: Vec<String> = Vec::new();
  let mut env_override = false;
  if let Ok(p) = std::env::var("UNIVERT_SOUNDFONT") {
    env_override = true;
    if !std::path::Path::new(&p).is_file() {
      return Err(Error::other(format!(
        "UNIVERT_SOUNDFONT points to {p}, which does not exist"
      )));
    }
    candidates.push(p);
  } else {
    // Prefer full General MIDI banks (FluidR3_GM etc.) when present, then
    // fall back to smaller banks that ship with fluid-synth or Csound.
    for p in [
      // Debian/Ubuntu: fluid-soundfont-gm
      "/usr/share/sounds/sf2/FluidR3_GM.sf2",
      // Debian/Ubuntu: fluid-soundfont-gs
      "/usr/share/sounds/sf2/FluidR3_GS.sf2",
      // Debian/Ubuntu: timgm6mb-soundfont (small GM bank)
      "/usr/share/sounds/sf2/TimGM6mb.sf2",
      // Arch: soundfont-fluid
      "/usr/share/soundfonts/FluidR3_GM.sf2",
      // Generic fallback some distros set up
      "/usr/share/soundfonts/default.sf2",
      // Occasionally packaged as fluid-soundfont
      "/opt/homebrew/share/fluid-soundfont/FluidR3_GM.sf2",
      "/usr/local/share/fluid-soundfont/FluidR3_GM.sf2",
      // Homebrew `fluid-synth` (no separate soundfont formula exists)
      "/opt/homebrew/share/fluid-synth/sf2/VintageDreamsWaves-v2.sf2",
      "/usr/local/share/fluid-synth/sf2/VintageDreamsWaves-v2.sf2",
      // Csound examples (macOS framework)
      "/Library/Frameworks/CsoundLib64.framework/Resources/Manual/examples/sf_GMbank.sf2",
    ] {
      if std::path::Path::new(p).is_file() {
        candidates.push(p.to_string());
      }
    }
  }

  if candidates.is_empty() {
    return Err(Error::other(
      "No SoundFont found. Set UNIVERT_SOUNDFONT to a .sf2 file, or install \
       one (macOS: `brew install fluid-synth`; Debian/Ubuntu: \
       `apt install fluid-soundfont-gm`).",
    ));
  }

  let mut last_err: Option<String> = None;
  for path in &candidates {
    match fs::File::open(path)
      .map_err(|e| format!("open {path}: {e}"))
      .and_then(|mut f| {
        rustysynth::SoundFont::new(&mut f)
          .map_err(|e| format!("load {path}: {e}"))
      }) {
      Ok(sf) => return Ok((sf, path.clone())),
      Err(e) => last_err = Some(e),
    }
  }

  // Env-var override means the user picked a specific file; surface the
  // underlying parse error so they can tell something's wrong with it.
  if env_override {
    return Err(Error::other(format!(
      "could not load UNIVERT_SOUNDFONT: {}",
      last_err.unwrap_or_else(|| "unknown error".to_string())
    )));
  }
  Err(Error::other(format!(
    "No usable SoundFont found ({} candidate(s) rejected by rustysynth). \
     Last error: {}. Set UNIVERT_SOUNDFONT to a different .sf2 file, or \
     install one (macOS: `brew install fluid-synth`; Debian/Ubuntu: \
     `apt install fluid-soundfont-gm`).",
    candidates.len(),
    last_err.unwrap_or_else(|| "unknown error".to_string()),
  )))
}

pub fn wav_to_aac(job: &Job) -> Result<()> {
  // Use ffmpeg when present; it is cross-platform, unlike macOS afconvert.
  if which_tool("ffmpeg") {
    let status = Command::new("ffmpeg")
      .args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
      .arg(job.input)
      .args(["-c:a", "aac", "-f", "adts"])
      .arg(job.output)
      .status()
      .map_err(|e| Error::ToolFailed {
        tool: "ffmpeg",
        message: e.to_string(),
      })?;
    if !status.success() {
      return Err(Error::ToolFailed {
        tool: "ffmpeg",
        message: format!("ffmpeg exited with status {status}"),
      });
    }
    return Ok(());
  }
  Err(Error::MissingTool {
    from: extension_of(job.input).unwrap_or_default(),
    to: extension_of(job.output).unwrap_or_default(),
    tool: "ffmpeg",
  })
}

pub fn wav_to_ogg(job: &Job) -> Result<()> {
  if which_tool("ffmpeg") {
    let status = Command::new("ffmpeg")
      .args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
      .arg(job.input)
      .args(["-c:a", "libvorbis"])
      .arg(job.output)
      .status()
      .map_err(|e| Error::ToolFailed {
        tool: "ffmpeg",
        message: e.to_string(),
      })?;
    if !status.success() {
      return Err(Error::ToolFailed {
        tool: "ffmpeg",
        message: format!("ffmpeg exited with status {status}"),
      });
    }
    return Ok(());
  }
  Err(Error::MissingTool {
    from: extension_of(job.input).unwrap_or_default(),
    to: extension_of(job.output).unwrap_or_default(),
    tool: "ffmpeg",
  })
}

pub fn wav_to_mp3(job: &Job) -> Result<()> {
  if which_tool("ffmpeg") {
    let status = Command::new("ffmpeg")
      .args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
      .arg(job.input)
      .args(["-c:a", "libmp3lame"])
      .arg(job.output)
      .status()
      .map_err(|e| Error::ToolFailed {
        tool: "ffmpeg",
        message: e.to_string(),
      })?;
    if !status.success() {
      return Err(Error::ToolFailed {
        tool: "ffmpeg",
        message: format!("ffmpeg exited with status {status}"),
      });
    }
    return Ok(());
  }
  Err(Error::MissingTool {
    from: extension_of(job.input).unwrap_or_default(),
    to: extension_of(job.output).unwrap_or_default(),
    tool: "ffmpeg",
  })
}

pub fn flac_to_wav(job: &Job) -> Result<()> {
  let mut reader = claxon::FlacReader::open(job.input)
    .map_err(|e| Error::other(format!("flac open: {e}")))?;
  let info = reader.streaminfo();
  let spec = WavSpec {
    channels: info.channels as u16,
    sample_rate: info.sample_rate,
    bits_per_sample: info.bits_per_sample as u16,
    sample_format: SampleFormat::Int,
  };
  let mut writer = WavWriter::create(job.output, spec)
    .map_err(|e| Error::other(format!("wav create: {e}")))?;

  for sample in reader.samples() {
    let s = sample.map_err(|e| Error::other(format!("flac decode: {e}")))?;
    writer
      .write_sample(s)
      .map_err(|e| Error::other(format!("wav write: {e}")))?;
  }

  writer
    .finalize()
    .map_err(|e| Error::other(format!("wav finalize: {e}")))?;
  Ok(())
}

pub fn wav_to_flac(job: &Job) -> Result<()> {
  // claxon is decode-only; shell out to ffmpeg when available.
  if which_tool("ffmpeg") {
    let status = Command::new("ffmpeg")
      .args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
      .arg(job.input)
      .args(["-c:a", "flac"])
      .arg(job.output)
      .status()
      .map_err(|e| Error::ToolFailed {
        tool: "ffmpeg",
        message: e.to_string(),
      })?;
    if !status.success() {
      return Err(Error::ToolFailed {
        tool: "ffmpeg",
        message: format!("ffmpeg exited with status {status}"),
      });
    }
    return Ok(());
  }
  Err(Error::MissingTool {
    from: extension_of(job.input).unwrap_or_default(),
    to: extension_of(job.output).unwrap_or_default(),
    tool: "ffmpeg",
  })
}

pub fn ogg_to_wav(job: &Job) -> Result<()> {
  let file = fs::File::open(job.input)?;
  let mut reader =
    lewton::inside_ogg::OggStreamReader::new(BufReader::new(file))
      .map_err(|e| Error::other(format!("ogg open: {e}")))?;

  let spec = WavSpec {
    channels: reader.ident_hdr.audio_channels as u16,
    sample_rate: reader.ident_hdr.audio_sample_rate,
    bits_per_sample: 16,
    sample_format: SampleFormat::Int,
  };
  let channels = spec.channels as usize;
  let mut writer = WavWriter::create(job.output, spec)
    .map_err(|e| Error::other(format!("wav create: {e}")))?;

  while let Some(packet) = reader
    .read_dec_packet()
    .map_err(|e| Error::other(format!("ogg decode: {e}")))?
  {
    if packet.is_empty() {
      continue;
    }
    let frames = packet[0].len();
    for frame in 0..frames {
      for (ch, samples) in packet.iter().enumerate().take(channels) {
        let sample = *samples.get(frame).unwrap_or(&0);
        writer
          .write_sample(sample)
          .map_err(|e| Error::other(format!("wav write: {e}")))?;
        let _ = ch;
      }
    }
  }

  writer
    .finalize()
    .map_err(|e| Error::other(format!("wav finalize: {e}")))?;
  Ok(())
}

pub fn opus_to_wav(job: &Job) -> Result<()> {
  // No mature pure-Rust Opus decoder exists (symphonia lacks one), so shell
  // out to ffmpeg like the other lossy encoders.
  if which_tool("ffmpeg") {
    let status = Command::new("ffmpeg")
      .args(["-y", "-hide_banner", "-loglevel", "error", "-i"])
      .arg(job.input)
      .arg(job.output)
      .status()
      .map_err(|e| Error::ToolFailed {
        tool: "ffmpeg",
        message: e.to_string(),
      })?;
    if !status.success() {
      return Err(Error::ToolFailed {
        tool: "ffmpeg",
        message: format!("ffmpeg exited with status {status}"),
      });
    }
    return Ok(());
  }
  Err(Error::MissingTool {
    from: extension_of(job.input).unwrap_or_default(),
    to: extension_of(job.output).unwrap_or_default(),
    tool: "ffmpeg",
  })
}

pub fn mp3_to_wav(job: &Job) -> Result<()> {
  use symphonia::core::codecs::DecoderOptions;
  use symphonia::core::errors::Error as SymError;
  use symphonia::core::formats::FormatOptions;
  use symphonia::core::io::MediaSourceStream;
  use symphonia::core::meta::MetadataOptions;
  use symphonia::core::probe::Hint;

  let src = fs::File::open(job.input)?;
  let mss = MediaSourceStream::new(Box::new(src), Default::default());
  let mut hint = Hint::new();
  hint.with_extension("mp3");

  let probed = symphonia::default::get_probe()
    .format(
      &hint,
      mss,
      &FormatOptions::default(),
      &MetadataOptions::default(),
    )
    .map_err(|e| Error::other(format!("mp3 probe: {e}")))?;

  let mut format = probed.format;
  let track = format
    .default_track()
    .ok_or_else(|| Error::other("mp3: no default track"))?;
  let track_id = track.id;
  let params = track.codec_params.clone();

  let mut decoder = symphonia::default::get_codecs()
    .make(&params, &DecoderOptions::default())
    .map_err(|e| Error::other(format!("mp3 decoder: {e}")))?;

  let sample_rate = params
    .sample_rate
    .ok_or_else(|| Error::other("mp3: unknown sample rate"))?;
  let channels = params
    .channels
    .ok_or_else(|| Error::other("mp3: unknown channel layout"))?
    .count() as u16;

  let spec = WavSpec {
    channels,
    sample_rate,
    bits_per_sample: 16,
    sample_format: SampleFormat::Int,
  };
  let mut writer = WavWriter::create(job.output, spec)
    .map_err(|e| Error::other(format!("wav create: {e}")))?;

  loop {
    let packet = match format.next_packet() {
      Ok(p) => p,
      Err(SymError::IoError(e))
        if e.kind() == std::io::ErrorKind::UnexpectedEof =>
      {
        break;
      }
      Err(SymError::ResetRequired) => break,
      Err(e) => return Err(Error::other(format!("mp3 read: {e}"))),
    };

    if packet.track_id() != track_id {
      continue;
    }

    let decoded = match decoder.decode(&packet) {
      Ok(d) => d,
      Err(SymError::IoError(_)) | Err(SymError::DecodeError(_)) => continue,
      Err(e) => return Err(Error::other(format!("mp3 decode: {e}"))),
    };

    write_audio_buffer(&decoded, &mut writer, channels as usize)?;
  }

  writer
    .finalize()
    .map_err(|e| Error::other(format!("wav finalize: {e}")))?;
  Ok(())
}

fn write_audio_buffer<W: std::io::Write + std::io::Seek>(
  buf: &symphonia::core::audio::AudioBufferRef<'_>,
  writer: &mut WavWriter<std::io::BufWriter<W>>,
  channels: usize,
) -> Result<()> {
  use symphonia::core::audio::{AudioBufferRef, Signal};
  use symphonia::core::conv::IntoSample;

  macro_rules! write_samples {
    ($buf:expr, $ty:ty) => {{
      let frames = $buf.frames();
      for f in 0..frames {
        for ch in 0..channels {
          let s = $buf.chan(ch)[f];
          let i16_sample: i16 = <$ty as IntoSample<i16>>::into_sample(s);
          writer
            .write_sample(i16_sample)
            .map_err(|e| Error::other(format!("wav write: {e}")))?;
        }
      }
    }};
  }

  match buf {
    AudioBufferRef::U8(b) => write_samples!(b, u8),
    AudioBufferRef::U16(b) => write_samples!(b, u16),
    AudioBufferRef::U24(b) => write_samples!(b, symphonia::core::sample::u24),
    AudioBufferRef::U32(b) => write_samples!(b, u32),
    AudioBufferRef::S8(b) => write_samples!(b, i8),
    AudioBufferRef::S16(b) => write_samples!(b, i16),
    AudioBufferRef::S24(b) => write_samples!(b, symphonia::core::sample::i24),
    AudioBufferRef::S32(b) => write_samples!(b, i32),
    AudioBufferRef::F32(b) => write_samples!(b, f32),
    AudioBufferRef::F64(b) => write_samples!(b, f64),
  }
  Ok(())
}