mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-02 20:22:27 -05:00
Merge branch 'main' into fix/sec-packaging
This commit is contained in:
28 files changed
+802
-61
No files matched your search
@@ -168,7 +168,8 @@ pub fn import(e: &mut Engine, path: &str, first: Option<TrackId>, at: Samples) -
|
||||
.unwrap_or(2);
|
||||
let kind = if audio_lane { soundcraft_model::TrackKind::Audio } else { soundcraft_model::TrackKind::Midi };
|
||||
let fmt = if channels == 1 { soundcraft_model::ChannelFormat::Mono } else { soundcraft_model::ChannelFormat::Stereo };
|
||||
s.add_track(kind, fmt, Some("Clip Group"))
|
||||
let t = s.add_track(kind, fmt, Some("Clip Group"));
|
||||
crate::no_input::assign_first_input(s, t)
|
||||
}
|
||||
};
|
||||
let mut prepared = Vec::new();
|
||||
|
||||
@@ -21,14 +21,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// How many times longer than its input a process's output can be.
|
||||
fn growth(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> f64 {
|
||||
match name {
|
||||
"time_stretch" => ratio,
|
||||
"pitch_shift" => 2f64.powf(f64::from(semitones) / 12.0),
|
||||
"varispeed" => f64::from(to) / sr,
|
||||
"speed_ramp" if selection == SpeedRampSelection::Extend => 1.5,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The most frames a process can take in: these processes cut their output at MAX_OFFLINE_SAMPLES frames.
|
||||
fn frame_limit(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> usize {
|
||||
let longest = |grows: f64| (soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / grows) as usize;
|
||||
match name {
|
||||
"time_stretch" => longest(ratio),
|
||||
"pitch_shift" => longest(2f64.powf(f64::from(semitones) / 12.0)),
|
||||
"varispeed" => longest(f64::from(to) / sr),
|
||||
"speed_ramp" => longest(if selection == SpeedRampSelection::Extend { 1.5 } else { 1.0 }),
|
||||
"time_stretch" | "pitch_shift" | "varispeed" | "speed_ramp" => {
|
||||
(soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / growth(name, ratio, semitones, sr, to, selection)) as usize
|
||||
}
|
||||
_ => usize::MAX,
|
||||
}
|
||||
}
|
||||
@@ -80,14 +89,33 @@ fn process(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let selection = if get("selection", 0.0) >= 0.5 { SpeedRampSelection::Extend } else { SpeedRampSelection::FitTo };
|
||||
let fades = get("fades", 1.0) >= 0.5;
|
||||
let most = frame_limit(&name, ratio, semitones, sr.as_f64(), to, selection);
|
||||
// Each clip once: a clip listed again would otherwise process the result of its first pass
|
||||
// (an expanding process compounding its length every time).
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let ids: Vec<_> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
// Refuse before processing anything. Every result is kept as a new source for the life of
|
||||
// the command (and undo holds it), so cap the total output across clips, not just each one.
|
||||
// (pitch_shift resamples its stretched result back to the input length)
|
||||
let grows = if name == "pitch_shift" { 1.0 } else { growth(&name, ratio, semitones, sr.as_f64(), to, selection).max(1.0) };
|
||||
let mut budget = soundcraft_mix::MAX_RENDER_SAMPLES;
|
||||
for id in &ids {
|
||||
let Some((track, clip)) = e.session().find_clip(*id) else { continue };
|
||||
if !clip.is_audio() {
|
||||
continue;
|
||||
}
|
||||
let channels = e.session().track(track).map_or(1, |t| t.channels()).max(1);
|
||||
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
|
||||
let frames = (clip.length.max(0) as f64 * grows).ceil() as usize;
|
||||
budget = budget
|
||||
.checked_sub(frames.saturating_mul(channels))
|
||||
.ok_or_else(|| bad("audiosuite.process", "too much audio to process in one command"))?;
|
||||
}
|
||||
let mut done = 0;
|
||||
for id in ids {
|
||||
let Some((track, clip)) = e.session().find_clip(id).map(|(t, c)| (t, c.clone())) else { continue };
|
||||
if !clip.is_audio() {
|
||||
continue;
|
||||
}
|
||||
let channels = e.session().track(track).map_or(1, |t| t.channels());
|
||||
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
|
||||
let mut audio = soundcraft_mix::render_clips(e.session(), track, clip.range());
|
||||
// Render without the clip's own fades: re-render a copy without fades so they stay editable.
|
||||
let mut tmp = e.session().clone();
|
||||
@@ -362,6 +390,40 @@ mod tests {
|
||||
assert_eq!(e.session().tracks[0].clips().len(), 1, "one clip, not one per duplicate listing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_listed_twice_is_processed_once() {
|
||||
let (mut e, id) = gained_clip();
|
||||
let out =
|
||||
e.execute("audiosuite.process", &json!({"process": "time_stretch", "params": {"ratio": 4.0}, "clips": [id.0, id.0, id.0]})).unwrap();
|
||||
assert_eq!(out["processed"], 1);
|
||||
let c = e.session().tracks[0].clips()[0].clone();
|
||||
assert!(c.length <= 64 * 4 + 64, "stretched once, not compounded: {}", c.length);
|
||||
assert_eq!(e.session().sources.len(), 2, "one new source, not one per listing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_refuses_a_total_budget_across_clips() {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Tone"));
|
||||
let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.5; 64]] };
|
||||
let src = crate::io::add_source(&mut s, "tone", buf, None, FileFormat::Wav);
|
||||
// Three clips each within the per-clip limit whose results together exceed the budget.
|
||||
let len = (soundcraft_mix::MAX_RENDER_SAMPLES / 3 + 1) as i64;
|
||||
let ids: Vec<u64> = (0..3)
|
||||
.map(|k| {
|
||||
let id = s.new_clip_id();
|
||||
crate::edit::place_clip(&mut s, t, Clip::audio(id, "tone", src, 0, k * len, len));
|
||||
id.0
|
||||
})
|
||||
.collect();
|
||||
let mut e = crate::Engine::new(s);
|
||||
let before = serde_json::to_value(e.session()).unwrap();
|
||||
let out = e.execute("audiosuite.process", &json!({"process": "reverse", "clips": ids}));
|
||||
let ok = matches!(out, Err(crate::EngineError::BadParams(_, ref m)) if m.contains("too much audio"));
|
||||
assert!(ok, "three clips over budget, but got: {out:?}");
|
||||
assert_eq!(serde_json::to_value(e.session()).unwrap(), before, "refused before processing anything");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_refuses_a_total_budget_across_tracks() {
|
||||
let mut e = Engine::new(Session::default());
|
||||
|
||||
@@ -162,7 +162,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let t = match track {
|
||||
Some(t) if s.track(t).is_some_and(|x| x.kind == soundcraft_model::TrackKind::Audio) => t,
|
||||
Some(_) => return Err(bad("clip.place_source", "audio files go on audio tracks")),
|
||||
None => s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name)),
|
||||
None => {
|
||||
let t =
|
||||
s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name));
|
||||
crate::no_input::assign_first_input(s, t)
|
||||
}
|
||||
};
|
||||
let (sh, len) = (s.edit.edit_mode == soundcraft_model::EditMode::Shuffle, frames.max(1));
|
||||
let at = if sh { crate::edit::shuffle_slot(s, t, at, &[]) } else { at };
|
||||
|
||||
@@ -476,7 +476,8 @@ fn import_session_data(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "file.import_session_data";
|
||||
let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad(id, "`path` required"))?.to_string();
|
||||
let text_v = crate::io::read_session_text(&path)?;
|
||||
let other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
|
||||
let mut other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
|
||||
crate::no_input::upgrade_legacy_inputs(&mut other);
|
||||
let names: Option<Vec<String>> =
|
||||
p.get("tracks").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
|
||||
let picked: Vec<soundcraft_model::Track> = match &names {
|
||||
|
||||
@@ -300,6 +300,7 @@ fn new_track_row(e: &mut Engine, p: &Value) -> Result<Vec<TrackId>> {
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..count {
|
||||
let id = s.add_track(kind, format, name.as_deref());
|
||||
crate::no_input::assign_first_input(s, id);
|
||||
if let Some(t) = s.track_mut(id) {
|
||||
if let Some(tb) = ticks {
|
||||
t.ticks_timebase = tb;
|
||||
@@ -474,6 +475,7 @@ fn split_mono(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
_ => format!("{}", ch + 1),
|
||||
};
|
||||
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{}.{suffix}", src.name)));
|
||||
crate::no_input::assign_first_input(s, id);
|
||||
let mut clips = src.clips().to_vec();
|
||||
for c in &mut clips {
|
||||
c.id = s.new_clip_id();
|
||||
|
||||
@@ -1097,7 +1097,8 @@ fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::colle
|
||||
}
|
||||
|
||||
/// The record-enabled audio tracks, each with the input channels it records (those its input
|
||||
/// route names, "In 3" → 2, wrapped to the device's `input_channels`) and a new take file
|
||||
/// route names, "In 3" → 2, wrapped to the device's `input_channels`; with no input,
|
||||
/// [`NO_INPUT_CHANNEL`](crate::no_input::NO_INPUT_CHANNEL), which records silence) and a new take file
|
||||
/// `<track>_<NN>.wav` in the `Audio Files` of the session's folder (`unsaved_dir` until it is saved).
|
||||
pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<(TrackId, Vec<usize>, PathBuf)> {
|
||||
let dir = e.path.as_deref().and_then(|p| Path::new(p).parent()).unwrap_or(unsaved_dir);
|
||||
@@ -1113,7 +1114,11 @@ pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let inputs = (0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect();
|
||||
let inputs = if t.mixer.input == soundcraft_model::Route::None {
|
||||
vec![crate::no_input::NO_INPUT_CHANNEL; t.channels()]
|
||||
} else {
|
||||
(0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect()
|
||||
};
|
||||
let file = |n: usize| dir.join("Audio Files").join(format!("{}_{n:02}.wav", sanitize_name(&t.name)));
|
||||
let path = (take_no..take_no + 1_000).map(file).find(|p| !p.exists()).unwrap_or_else(|| file(take_no));
|
||||
(t.id, inputs, path)
|
||||
|
||||
@@ -192,7 +192,8 @@ fn place_import(
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let stem = Path::new(name).file_stem().and_then(OsStr::to_str).unwrap_or("Audio").to_string();
|
||||
s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem))
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem));
|
||||
crate::no_input::assign_first_input(s, t)
|
||||
}
|
||||
};
|
||||
let cid = s.new_clip_id();
|
||||
|
||||
@@ -87,7 +87,7 @@ fn lost_covers(lost: u8, device: u8) -> bool {
|
||||
}
|
||||
|
||||
/// What `track` recorded of `events` over `range`, in ticks from the start of the range. A key
|
||||
/// already down when the range starts is left out; one still down at its end ends there, and one
|
||||
/// already down when the range starts sounds from its start, as long as it is held; one still down at its end ends there, and one
|
||||
/// whose device lost input ends where that happened. Keys are told apart by device, channel and
|
||||
/// pitch: the same pitch held on two devices gives two notes. A key held while loop recording
|
||||
/// goes round ([`MidiTakeEvent::WRAP`]) is two notes: to the end of the loop, and from its start;
|
||||
@@ -108,9 +108,10 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
// The round of the loop being played: it goes up at every `WRAP`.
|
||||
let mut round = 0u32;
|
||||
// Keys down: (device, channel, pitch) -> (start tick, velocity, round, the sample the key was
|
||||
// pressed at). Whether the loop went round between a press and its release is judged by
|
||||
// their samples: two positions a few samples apart may share a tick, and a press in the
|
||||
// last samples of the range starts its note a tick earlier so that it plays.
|
||||
// pressed at, which is before the range only for a key held into it). Whether the loop went
|
||||
// round between a press and its release is judged by their samples: two positions a few
|
||||
// samples apart may share a tick, and a press in the last samples of the range starts its
|
||||
// note a tick earlier so that it plays.
|
||||
let mut down: HashMap<(u8, u8, u8), (i64, u8, u32, Samples)> = HashMap::new();
|
||||
let close = |seq: &mut Sequence,
|
||||
(_, channel, pitch): (u8, u8, u8),
|
||||
@@ -152,7 +153,16 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
round = round.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
if e.at < range.start || e.at >= range.end {
|
||||
if e.at < range.start {
|
||||
// Before the range (the pre-roll, or before the punch-in): a key pressed there and
|
||||
// still down when the range starts is recorded from the start of the range, "the
|
||||
// start of the note is quantized to the punch-in point" (Reference Guide p.822).
|
||||
// An entry there that ends a note pressed in the range is a late callback, as below.
|
||||
if round > 0 || held_into_range(s, input, devices, e, &mut down, range.start) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if e.at >= range.end {
|
||||
continue;
|
||||
}
|
||||
let at = tick(e.at);
|
||||
@@ -175,7 +185,7 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
match e.status & 0xF0 {
|
||||
0x90 if d2 > 0 => {
|
||||
// The same key again without a release: the first note ends here.
|
||||
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at)) {
|
||||
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at.max(range.start))) {
|
||||
close(&mut seq, key, open, at, 64, round, e.at);
|
||||
}
|
||||
}
|
||||
@@ -209,6 +219,45 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
seq
|
||||
}
|
||||
|
||||
/// Follow the keys pressed and released before a record range starts, in `down` (as the take
|
||||
/// builder keeps them: start tick, velocity, round, the sample the key was pressed at, which for
|
||||
/// these keys alone is before `start`). A key still down when the range starts goes on from its
|
||||
/// first tick; one released before it, or whose device lost input, leaves nothing. Returns
|
||||
/// false when `e` is left to the range: a lost-input entry (for the keys pressed in the range),
|
||||
/// or an entry for a key pressed in the range, stamped early by a late audio callback.
|
||||
fn held_into_range(
|
||||
s: &Session,
|
||||
input: &MidiInput<'_>,
|
||||
devices: &[String],
|
||||
e: &MidiTakeEvent,
|
||||
down: &mut HashMap<(u8, u8, u8), (i64, u8, u32, Samples)>,
|
||||
start: Samples,
|
||||
) -> bool {
|
||||
if e.status == MidiTakeEvent::LOST {
|
||||
down.retain(|k, open| open.3 >= start || !lost_covers(e.device, k.0));
|
||||
return false;
|
||||
}
|
||||
let channel = e.status & 0x0F;
|
||||
if midi_filtered(s, e.status) || !input.accepts(devices.get(usize::from(e.device)).map(String::as_str), channel) {
|
||||
return true;
|
||||
}
|
||||
let key = (e.device, channel, e.data1 & 0x7F);
|
||||
let note = matches!(e.status & 0xF0, 0x80 | 0x90);
|
||||
if note && down.get(&key).is_some_and(|open| open.3 >= start) {
|
||||
return false;
|
||||
}
|
||||
match e.status & 0xF0 {
|
||||
0x90 if e.data2 & 0x7F > 0 => {
|
||||
down.insert(key, (0, e.data2 & 0x7F, 0, e.at));
|
||||
}
|
||||
0x80 | 0x90 => {
|
||||
down.remove(&key);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Most events of one MIDI record pass that are kept.
|
||||
pub const MAX_MIDI_TAKE_EVENTS: usize = 1 << 20;
|
||||
|
||||
@@ -310,7 +359,7 @@ mod tests {
|
||||
assert_eq!(e.session().busses.len(), 0, "a MIDI input is not a bus name");
|
||||
assert!(records_midi(&e));
|
||||
let events = [
|
||||
ev(40_000, 0, 0x90, 59, 80), // before the pass: left out, and so is its release
|
||||
ev(40_000, 0, 0x90, 59, 80), // before the pass, released inside it: from the pass start
|
||||
ev(48_000, 0, 0x90, 60, 100), // one beat at 120 bpm, 48 kHz: 24 000 samples = 960 ticks
|
||||
ev(50_000, 0, 0x80, 59, 0),
|
||||
ev(60_000, 1, 0x99, 36, 127),
|
||||
@@ -328,7 +377,7 @@ mod tests {
|
||||
assert_eq!((before, take.clips.len(), take.gaps), (0, 2, 0), "the track whose device was silent gets no clip");
|
||||
let keys = sequence(&e, all, range);
|
||||
let notes: Vec<(u8, u8, i64, i64, u8)> = keys.notes.iter().map(|n| (n.channel, n.pitch, n.start, n.length, n.release_velocity)).collect();
|
||||
assert_eq!(notes, [(0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
|
||||
assert_eq!(notes, [(0, 59, 0, 80, 0), (0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
|
||||
assert_eq!(
|
||||
keys.ctrls.iter().map(|c| (c.tick, c.kind, c.value)).collect::<Vec<_>>(),
|
||||
[(960, CtrlKind::PitchBend, 4096), (1680, CtrlKind::Cc(64), 127)]
|
||||
@@ -345,6 +394,28 @@ mod tests {
|
||||
assert!(add_midi_recording(&mut e, Range::new(5, 5), &events, &devices, false).clips.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_held_into_the_punch_in_is_recorded_from_the_punch_in() {
|
||||
// Reference Guide p.822: played before the punch-in point, released after it.
|
||||
let s = Session::default();
|
||||
let range = Range::new(48_000, 144_000);
|
||||
let events = [
|
||||
ev(24_000, 0, 0x90, 60, 100), // held into the range
|
||||
ev(30_000, 0, 0x90, 62, 100), // pressed and released before it: nothing
|
||||
ev(36_000, 0, 0x80, 62, 0),
|
||||
ev(40_000, 0, 0x90, 64, 90), // another one released before it
|
||||
ev(44_000, 0, 0x80, 64, 0),
|
||||
ev(72_000, 0, 0x80, 60, 30), // the held key, released one quarter into the range
|
||||
ev(96_000, 0, 0x90, 67, 100),
|
||||
ev(120_000, 0, 0x80, 67, 0),
|
||||
];
|
||||
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events, &[]));
|
||||
assert_eq!(got, [(0, 60, 0, 960, 100, 30), (0, 67, 1920, 960, 100, 0)]);
|
||||
// A key still down at the end of the range covers all of it.
|
||||
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events[..1], &[]));
|
||||
assert_eq!(got, [(0, 60, 0, 3840, 100, 64)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_pitch_on_two_devices_is_two_notes_and_lost_input_ends_only_its_device() {
|
||||
let mut e = Engine::default();
|
||||
@@ -550,6 +621,21 @@ mod tests {
|
||||
let marked = [ev(24_000, 0, 0x90, 60, 100), ev(96_000, u8::MAX, MidiTakeEvent::WRAP, 0, 0), ev(48_000, 0, 0x80, 60, 0)];
|
||||
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &marked, &[]));
|
||||
assert_eq!(got.iter().map(|n| (n.2, n.3)).collect::<Vec<_>>(), [(960, 960)]);
|
||||
// A punch range: a key pressed in it whose release is stamped before its start is one
|
||||
// short note at the press too, and a key pressed and released before it stays out.
|
||||
let punch = Range::new(48_000, 144_000);
|
||||
let events = [
|
||||
ev(30_000, 0, 0x90, 62, 100),
|
||||
ev(36_000, 0, 0x80, 62, 0),
|
||||
ev(49_000, 0, 0x90, 60, 100),
|
||||
ev(47_000, 0, 0x80, 60, 40),
|
||||
ev(72_000, 0, 0x90, 64, 100),
|
||||
ev(47_400, 0, 0xB0, 64, 127), // a controller stamped there is still left out
|
||||
ev(47_500, u8::MAX, MidiTakeEvent::LOST, 0, 0),
|
||||
];
|
||||
let seq = midi_take_sequence(&s, &MidiInput::default(), punch, MidiPass::Linear, &events, &[]);
|
||||
assert_eq!(notes_of(&seq), [(0, 60, 40, 1, 100, 40), (0, 64, 960, 1, 100, 64)]);
|
||||
assert!(seq.ctrls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod feature_names;
|
||||
pub mod file_access;
|
||||
pub mod inspect;
|
||||
pub mod io;
|
||||
pub mod no_input;
|
||||
pub mod score;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -220,8 +221,9 @@ impl Default for Engine {
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(session: Session) -> Self {
|
||||
pub fn new(mut session: Session) -> Self {
|
||||
install_panic_hook();
|
||||
no_input::upgrade_legacy_inputs(&mut session);
|
||||
let doc = Arc::new(session);
|
||||
Engine {
|
||||
saved: Arc::clone(&doc),
|
||||
@@ -296,8 +298,10 @@ impl Engine {
|
||||
&mut Arc::make_mut(&mut self.doc).edit.zoom
|
||||
}
|
||||
|
||||
/// Replace the whole document (open / new); clears history.
|
||||
pub fn replace_session(&mut self, s: Session) {
|
||||
/// Replace the whole document (open / new); clears history. A session saved before "no
|
||||
/// input" existed is upgraded ([`no_input::upgrade_legacy_inputs`]).
|
||||
pub fn replace_session(&mut self, mut s: Session) {
|
||||
no_input::upgrade_legacy_inputs(&mut s);
|
||||
self.transport = TransportStatus { position: s.edit.selection.start.max(0), ..TransportStatus::default() };
|
||||
self.transport_requests.clear();
|
||||
self.transport_requests.push(TransportRequest::ResetSession);
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! "no input" on an audio track (`Route::None`): the track records and monitors nothing, as
|
||||
//! Pro Tools' No Input does. A new audio track gets its first input path explicitly instead.
|
||||
//!
|
||||
//! Sessions saved before this rule used `Route::None` for an audio track that recorded and
|
||||
//! monitored hardware input 1 (the selector showed "In 1"). [`upgrade_legacy_inputs`] turns
|
||||
//! those into the explicit first input when such a session is opened, so it keeps sounding and
|
||||
//! recording as before. Sessions held by the engine carry [`NO_INPUT_MARKER`], so a "no input"
|
||||
//! saved by this build stays "no input" when it is opened again.
|
||||
|
||||
use soundcraft_model::{ChannelFormat, Route, Session, TrackKind};
|
||||
|
||||
/// Set in `edit.flags` of every session the engine holds: its `Route::None` audio inputs mean
|
||||
/// "no input". A session without it was saved before that, when they meant hardware input 1.
|
||||
pub const NO_INPUT_MARKER: &str = "io.none_is_no_input";
|
||||
|
||||
/// The input channel an audio track with no input records: no device has it, so the take is
|
||||
/// digital silence.
|
||||
pub const NO_INPUT_CHANNEL: usize = usize::MAX;
|
||||
|
||||
/// The first hardware input path of a track of `format`: "In 1", "In 1-2", "In 1-6"…
|
||||
pub fn first_input(format: ChannelFormat) -> Route {
|
||||
match format.channels() {
|
||||
0 | 1 => Route::Hardware("In 1".into()),
|
||||
n => Route::Hardware(format!("In 1-{n}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the new track `id`, if it is an audio track, its first input path (Pro Tools assigns
|
||||
/// new tracks an input path), and return `id`.
|
||||
pub(crate) fn assign_first_input(s: &mut Session, id: soundcraft_model::TrackId) -> soundcraft_model::TrackId {
|
||||
if let Some(t) = s.track_mut(id)
|
||||
&& t.kind == TrackKind::Audio
|
||||
&& t.mixer.input == Route::None
|
||||
{
|
||||
t.mixer.input = first_input(t.format);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// A session saved before [`NO_INPUT_MARKER`]: each audio track whose input is `Route::None`
|
||||
/// recorded and monitored hardware input 1, so it gets that input explicitly. Then the session
|
||||
/// is marked, and running this again changes nothing.
|
||||
pub fn upgrade_legacy_inputs(s: &mut Session) {
|
||||
if s.edit.flag(NO_INPUT_MARKER) {
|
||||
return;
|
||||
}
|
||||
for t in &mut s.tracks {
|
||||
if t.kind == TrackKind::Audio && t.mixer.input == Route::None {
|
||||
t.mixer.input = first_input(t.format);
|
||||
}
|
||||
}
|
||||
s.edit.set_flag(NO_INPUT_MARKER, true);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Engine;
|
||||
use serde_json::json;
|
||||
use soundcraft_model::TrackId;
|
||||
|
||||
fn new_track(e: &mut Engine, format: &str) -> TrackId {
|
||||
TrackId(e.execute("track.new", &json!({"format": format})).unwrap()["tracks"][0].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn input(e: &Engine, t: TrackId) -> Route {
|
||||
e.session().track(t).unwrap().mixer.input.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_audio_track_gets_its_first_input_path() {
|
||||
let mut e = Engine::default();
|
||||
let mono = new_track(&mut e, "mono");
|
||||
let stereo = new_track(&mut e, "stereo");
|
||||
assert_eq!(input(&e, mono), Route::Hardware("In 1".into()));
|
||||
assert_eq!(input(&e, stereo), Route::Hardware("In 1-2".into()));
|
||||
let aux = TrackId(e.execute("track.new", &json!({"kind": "aux"})).unwrap()["tracks"][0].as_u64().unwrap());
|
||||
assert_eq!(input(&e, aux), Route::None, "only audio tracks take a hardware input by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_track_with_no_input_records_no_device_channel() {
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-no-input-{}", std::process::id()));
|
||||
let mut e = Engine::default();
|
||||
let vox = new_track(&mut e, "mono");
|
||||
let gtr = new_track(&mut e, "stereo");
|
||||
e.execute("track.input", &json!({"tracks": [vox.0, gtr.0], "input": "none"})).unwrap();
|
||||
e.execute("mix.record_arm", &json!({"tracks": [vox.0, gtr.0], "value": true})).unwrap();
|
||||
let plan = crate::io::plan_takes(&e, &dir, 30);
|
||||
assert_eq!(
|
||||
plan.iter().map(|(t, inputs, _)| (*t, inputs.clone())).collect::<Vec<_>>(),
|
||||
vec![(vox, vec![NO_INPUT_CHANNEL]), (gtr, vec![NO_INPUT_CHANNEL; 2])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_saved_before_no_input_existed_keeps_recording_input_1() {
|
||||
let mut old = Session::default();
|
||||
let vox = old.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Vox"));
|
||||
let gtr = old.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Gtr"));
|
||||
let keys = old.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys"));
|
||||
let text = old.to_json().unwrap();
|
||||
assert!(!text.contains(NO_INPUT_MARKER));
|
||||
let mut e = Engine::default();
|
||||
e.replace_session(Session::from_json(&text).unwrap());
|
||||
assert_eq!(input(&e, vox), Route::Hardware("In 1".into()));
|
||||
assert_eq!(input(&e, gtr), Route::Hardware("In 1-2".into()));
|
||||
assert_eq!(input(&e, keys), Route::None, "a MIDI input is left alone");
|
||||
assert!(!e.is_dirty(), "opening an old session does not modify it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_input_survives_save_and_reopen() {
|
||||
let mut e = Engine::default();
|
||||
let vox = new_track(&mut e, "mono");
|
||||
e.execute("track.input", &json!({"tracks": [vox.0], "input": "no input"})).unwrap();
|
||||
let text = e.session().to_json().unwrap();
|
||||
let mut reopened = Engine::default();
|
||||
reopened.replace_session(Session::from_json(&text).unwrap());
|
||||
assert_eq!(input(&reopened, vox), Route::None);
|
||||
}
|
||||
}
|
||||
@@ -68,8 +68,8 @@ fn insertion_trims_still_trim_unlocked_clips_beside_both_lock_kinds() {
|
||||
for clip in &mut session.track_mut(track).unwrap().playlist_mut().unwrap().clips {
|
||||
clip.start = 0;
|
||||
}
|
||||
let before = session.clone();
|
||||
let mut engine = Engine::new(session);
|
||||
let before = engine.session().clone();
|
||||
let result = engine.execute(command, &json!({"tracks": [track.0], "at": 50})).unwrap();
|
||||
assert_eq!(result["trimmed"], json!(1), "{command}");
|
||||
let clips = engine.session().track(track).unwrap().clips();
|
||||
|
||||
@@ -238,9 +238,11 @@ fn zero_buf(buf: &mut [Vec<f32>], frames: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Input monitoring: the track hears its hardware input instead of its clips.
|
||||
/// Input monitoring: the track hears its hardware input instead of its clips. With no input
|
||||
/// (`Route::None`) it hears nothing.
|
||||
fn monitor_input(t: &Track, strip: &mut Strip, live: &LiveInput<'_>, frames: usize) {
|
||||
let first = match &t.mixer.input {
|
||||
Route::None => return,
|
||||
Route::Hardware(h) => {
|
||||
h.trim_start_matches("In ").split(['-', ' ']).next().and_then(|n| n.parse::<usize>().ok()).map_or(0, |n| n.saturating_sub(1))
|
||||
}
|
||||
|
||||
@@ -1143,6 +1143,7 @@ fn a_hosted_instruments_latency_is_compensated() {
|
||||
#[test]
|
||||
fn input_monitoring_replaces_clips() {
|
||||
let (mut s, t) = session_with_dc(0.5, 4800);
|
||||
s.track_mut(t).unwrap().mixer.input = Route::Hardware("In 1".into());
|
||||
let mut eng = MixEngine::new(48_000.0, 512);
|
||||
eng.input = vec![vec![0.25; 512]];
|
||||
let mut out = vec![vec![0.0; 512]; 2];
|
||||
@@ -1161,6 +1162,23 @@ fn input_monitoring_replaces_clips() {
|
||||
assert!(out[0][100].abs() < 1e-6, "stopped, unmonitored: silence");
|
||||
}
|
||||
|
||||
/// A track whose input is "no input" (`Route::None`) hears nothing, not hardware input 1.
|
||||
#[test]
|
||||
fn a_track_with_no_input_monitors_nothing() {
|
||||
let (mut s, t) = session_with_dc(0.0, 4800);
|
||||
let mut eng = MixEngine::new(48_000.0, 512);
|
||||
eng.input = vec![vec![0.25; 512], vec![0.5; 512]];
|
||||
eng.monitor_only = true;
|
||||
let mut out = vec![vec![0.0; 512]; 2];
|
||||
s.track_mut(t).unwrap().mixer.input_monitor = true;
|
||||
s.track_mut(t).unwrap().mixer.input = Route::None;
|
||||
eng.render(&s, 0, 512, &mut out);
|
||||
assert!(out.iter().all(|c| c.iter().all(|x| *x == 0.0)), "no input: silence, not In 1");
|
||||
s.track_mut(t).unwrap().mixer.input = Route::Hardware("In 2".into());
|
||||
eng.render(&s, 512, 512, &mut out);
|
||||
assert!((out[0][100] - 0.5 * std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3, "In 2 is heard: {}", out[0][100]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_session_is_silent() {
|
||||
let s = Session::default();
|
||||
|
||||
@@ -175,6 +175,62 @@ pub(crate) fn device(host: &cpal::Host, name: Option<&str>, output: bool) -> Opt
|
||||
if output { host.default_output_device() } else { host.default_input_device() }
|
||||
}
|
||||
|
||||
/// Why the device does not run at the chosen buffer size, when it does not. `running` is the
|
||||
/// size the open stream reports it runs at, when it reports one.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BufferNote {
|
||||
/// The size is outside the range the driver reports; the device runs at its default buffer.
|
||||
/// A range of one size (a shared-mode WASAPI device reports only its period) means the device
|
||||
/// runs only at that size.
|
||||
OutsideRange { min: u32, max: u32, running: Option<u32> },
|
||||
/// The driver refused the size although it reports no range, or one that holds the size; the
|
||||
/// device runs at its default buffer.
|
||||
Refused { want: u32, running: Option<u32> },
|
||||
/// The device took the size, but the open stream runs at another one (a host may round a
|
||||
/// fixed size to one the hardware supports).
|
||||
Rounded { want: u32, running: u32 },
|
||||
}
|
||||
|
||||
impl BufferNote {
|
||||
/// The note in English (the reply's `buffer_note`, and the key of the window's translation).
|
||||
pub fn english(&self) -> String {
|
||||
match *self {
|
||||
BufferNote::OutsideRange { min, max, .. } if min == max => format!("The device runs only at {min} samples."),
|
||||
BufferNote::OutsideRange { min, max, running: Some(n) } => {
|
||||
format!("The device allows {min}–{max} samples; it runs at its default buffer, {n} samples.")
|
||||
}
|
||||
BufferNote::OutsideRange { min, max, running: None } => format!("The device allows {min}–{max} samples; it runs at its default buffer."),
|
||||
BufferNote::Refused { want, running: Some(n) } => {
|
||||
format!("The device did not take {want} samples; it runs at its default buffer, {n} samples.")
|
||||
}
|
||||
BufferNote::Refused { want, running: None } => format!("The device did not take {want} samples; it runs at its default buffer."),
|
||||
BufferNote::Rounded { want, running } => format!("The device runs at {running} samples, not {want}."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The note for a chosen buffer (`want`) the device did not take (`used`, `None` for its
|
||||
/// default), or took but runs at another size, given the range its driver reports and the size
|
||||
/// the open stream runs at.
|
||||
pub fn buffer_note(want: Option<u32>, used: Option<u32>, range: Option<(u32, u32)>, running: Option<u32>) -> Option<BufferNote> {
|
||||
let want = want?;
|
||||
if used == Some(want) {
|
||||
return running.filter(|&n| n != want).map(|running| BufferNote::Rounded { want, running });
|
||||
}
|
||||
Some(match range {
|
||||
Some((min, max)) if !(min..=max).contains(&want) => BufferNote::OutsideRange { min, max, running },
|
||||
_ => BufferNote::Refused { want, running },
|
||||
})
|
||||
}
|
||||
|
||||
/// The range a driver reports, if it reports one.
|
||||
pub(crate) fn buffer_range(supported: &cpal::SupportedBufferSize) -> Option<(u32, u32)> {
|
||||
match supported {
|
||||
cpal::SupportedBufferSize::Range { min, max } => Some((*min, *max)),
|
||||
cpal::SupportedBufferSize::Unknown => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer to request: the chosen size when the device's range allows it, else the default.
|
||||
pub(crate) fn buffer_size(want: Option<u32>, supported: &cpal::SupportedBufferSize) -> cpal::BufferSize {
|
||||
match (want, supported) {
|
||||
@@ -190,6 +246,55 @@ pub(crate) fn buffer_size(want: Option<u32>, supported: &cpal::SupportedBufferSi
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A buffer the driver does not take is said, not silently replaced (#1757).
|
||||
#[test]
|
||||
fn a_buffer_the_device_did_not_take_gets_a_note() {
|
||||
// The RME UFX on Core Audio allows 15..=3072 frames (measured); 4096 opens at its default.
|
||||
assert_eq!(buffer_note(Some(4096), None, Some((15, 3072)), None), Some(BufferNote::OutsideRange { min: 15, max: 3072, running: None }));
|
||||
assert_eq!(
|
||||
BufferNote::OutsideRange { min: 15, max: 3072, running: None }.english(),
|
||||
"The device allows 15–3072 samples; it runs at its default buffer."
|
||||
);
|
||||
// The driver gave no range and refused the size.
|
||||
assert_eq!(buffer_note(Some(100), None, None, None), Some(BufferNote::Refused { want: 100, running: None }));
|
||||
// A size within the reported range that still failed is refused, not outside the range.
|
||||
assert_eq!(buffer_note(Some(256), None, Some((15, 3072)), None), Some(BufferNote::Refused { want: 256, running: None }));
|
||||
// Taken as asked, or nothing asked: no note.
|
||||
assert_eq!(buffer_note(Some(256), Some(256), Some((15, 3072)), Some(256)), None);
|
||||
assert_eq!(buffer_note(None, None, Some((15, 3072)), Some(512)), None);
|
||||
}
|
||||
|
||||
/// The note says the size the device runs at, when the stream reports it.
|
||||
#[test]
|
||||
fn the_note_says_the_buffer_the_device_runs_at() {
|
||||
let note = buffer_note(Some(4096), None, Some((15, 3072)), Some(512)).unwrap();
|
||||
assert_eq!(note, BufferNote::OutsideRange { min: 15, max: 3072, running: Some(512) });
|
||||
assert_eq!(note.english(), "The device allows 15–3072 samples; it runs at its default buffer, 512 samples.");
|
||||
let refused = buffer_note(Some(100), None, None, Some(480)).unwrap();
|
||||
assert_eq!(refused.english(), "The device did not take 100 samples; it runs at its default buffer, 480 samples.");
|
||||
}
|
||||
|
||||
/// A fixed size the device opened with can still run at another size (cpal: "the host may
|
||||
/// round to hardware-supported values"); the note names the size it runs at.
|
||||
#[test]
|
||||
fn a_size_the_device_took_but_runs_differently_gets_a_note() {
|
||||
let note = buffer_note(Some(100), Some(100), Some((15, 3072)), Some(128)).unwrap();
|
||||
assert_eq!(note, BufferNote::Rounded { want: 100, running: 128 });
|
||||
assert_eq!(note.english(), "The device runs at 128 samples, not 100.");
|
||||
assert_eq!(buffer_note(Some(100), Some(100), Some((15, 3072)), Some(100)), None, "runs as asked");
|
||||
assert_eq!(buffer_note(Some(100), Some(100), Some((15, 3072)), None), None, "no running size reported");
|
||||
}
|
||||
|
||||
/// A shared-mode WASAPI device reports one size (its period, 480 frames at 48 kHz on the
|
||||
/// Windows test machine), so the range has a single value.
|
||||
#[test]
|
||||
fn a_device_with_one_buffer_size_is_said_to_run_only_at_it() {
|
||||
let note = buffer_note(Some(256), None, Some((480, 480)), Some(480)).unwrap();
|
||||
assert_eq!(note, BufferNote::OutsideRange { min: 480, max: 480, running: Some(480) });
|
||||
assert_eq!(note.english(), "The device runs only at 480 samples.");
|
||||
assert_eq!(buffer_note(Some(256), None, Some((480, 480)), None).unwrap().english(), "The device runs only at 480 samples.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_round_trips_and_tolerates_missing_fields() {
|
||||
let c = AudioConfig {
|
||||
|
||||
@@ -62,7 +62,7 @@ use callback::{STALL, copy_meter_snapshot};
|
||||
use callback::{guarded_block, stalled};
|
||||
#[cfg(test)]
|
||||
use stream::pick_output_config;
|
||||
use stream::{Opened, build_output, first_started, open_device, start_stream};
|
||||
use stream::{Opened, build_output, first_started, open_device, running_buffer, start_stream};
|
||||
|
||||
/// Meter values for the UI: the highest peak (and gain reduction) of every block rendered since
|
||||
/// the UI last took them with [`Player::take_meters`]. The audio thread renders blocks faster than
|
||||
@@ -178,6 +178,10 @@ pub struct Player {
|
||||
pub device_channels: u16,
|
||||
/// The device buffer in frames when one was chosen (`None`: the device default).
|
||||
pub device_buffer: Option<u32>,
|
||||
/// The buffer range the output device's driver reports, when it reports one.
|
||||
pub device_buffer_range: Option<(u32, u32)>,
|
||||
/// The buffer the open output stream reports it runs at (`None` when it reports none).
|
||||
pub device_buffer_running: Option<u32>,
|
||||
/// True when no audio device could be opened (silent clock).
|
||||
pub silent: bool,
|
||||
}
|
||||
@@ -234,7 +238,7 @@ impl Player {
|
||||
Mutex::new(side)
|
||||
};
|
||||
match open_device(want, want_ch, cfg) {
|
||||
Ok((device, config, format, name)) => {
|
||||
Ok((device, config, format, name, buffer_range)) => {
|
||||
// The chosen buffer size first; if the device refuses it, its default.
|
||||
let mut attempts = vec![config];
|
||||
if config.buffer_size != cpal::BufferSize::Default {
|
||||
@@ -266,9 +270,11 @@ impl Player {
|
||||
cpal::BufferSize::Fixed(n) => Some(n),
|
||||
cpal::BufferSize::Default => None,
|
||||
};
|
||||
let running = running_buffer(&stream);
|
||||
log::info!(
|
||||
"audio device: {name} @ {rate} Hz, {channels} ch, {format}, buffer {}",
|
||||
buffer.map_or("default".to_string(), |n| n.to_string())
|
||||
"audio device: {name} @ {rate} Hz, {channels} ch, {format}, buffer {}{}",
|
||||
buffer.map_or("default".to_string(), |n| n.to_string()),
|
||||
running.map_or(String::new(), |n| format!(" (runs at {n})"))
|
||||
);
|
||||
Player {
|
||||
shared,
|
||||
@@ -282,6 +288,8 @@ impl Player {
|
||||
device_rate: rate,
|
||||
device_channels: config.channels,
|
||||
device_buffer: buffer,
|
||||
device_buffer_range: buffer_range,
|
||||
device_buffer_running: running,
|
||||
silent: false,
|
||||
}
|
||||
}
|
||||
@@ -359,6 +367,8 @@ impl Player {
|
||||
device_rate: rate,
|
||||
device_channels: 0,
|
||||
device_buffer: None,
|
||||
device_buffer_range: None,
|
||||
device_buffer_running: None,
|
||||
silent: true,
|
||||
}
|
||||
}
|
||||
@@ -382,6 +392,8 @@ impl Player {
|
||||
device_rate: session.sample_rate.hz(),
|
||||
device_channels: 0,
|
||||
device_buffer: None,
|
||||
device_buffer_range: None,
|
||||
device_buffer_running: None,
|
||||
silent: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,6 +669,18 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_the_device_does_not_have_is_recorded_as_digital_silence() {
|
||||
// A track with no input records `usize::MAX`, a channel no device has.
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-silent-take-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut take = TakeWriter::create(TrackId(1), vec![usize::MAX, 0], dir.join("Vox_01.wav"), 48_000, ONE_FILE).unwrap();
|
||||
take.write(&[0.25; 200], 2);
|
||||
take.write_header();
|
||||
assert_eq!(decode(&dir.join("Vox_01.wav")), vec![vec![0.0; 100], vec![0.25; 100]]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Files of 100 stereo or 200 mono frames: blocks that straddle a file's end are split there.
|
||||
#[test]
|
||||
fn a_take_that_fills_its_file_goes_on_in_the_next() {
|
||||
|
||||
@@ -13,6 +13,12 @@ pub(crate) fn start_stream(stream: &impl cpal::traits::StreamTrait) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer a started stream reports it runs at: Core Audio's device buffer, WASAPI's period.
|
||||
/// `None` when the backend cannot say (or says 0).
|
||||
pub(crate) fn running_buffer(stream: &impl cpal::traits::StreamTrait) -> Option<u32> {
|
||||
stream.buffer_size().ok().filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
/// A built output stream and the channels and fault flag its callback shares with the player.
|
||||
pub(crate) struct Opened {
|
||||
pub(crate) stream: cpal::Stream,
|
||||
@@ -94,7 +100,7 @@ pub(crate) fn open_device(
|
||||
want_rate: u32,
|
||||
want_ch: u16,
|
||||
cfg: &AudioConfig,
|
||||
) -> Result<(cpal::Device, cpal::StreamConfig, cpal::SampleFormat, String), String> {
|
||||
) -> Result<(cpal::Device, cpal::StreamConfig, cpal::SampleFormat, String, Option<(u32, u32)>), String> {
|
||||
use cpal::traits::DeviceTrait;
|
||||
let host = devices::host(cfg);
|
||||
let device = devices::device(&host, cfg.output.as_deref(), true).ok_or_else(|| "no output device".to_string())?;
|
||||
@@ -103,10 +109,10 @@ pub(crate) fn open_device(
|
||||
let want_ch = want_ch.max(2);
|
||||
let rates: Vec<u32> = cfg.sample_rate.into_iter().chain(Some(want_rate)).collect();
|
||||
let configs: Vec<cpal::SupportedStreamConfigRange> = device.supported_output_configs().map(|configs| configs.collect()).unwrap_or_default();
|
||||
let (config, format) = match pick_output_config(&configs, &rates, want_ch) {
|
||||
let (config, format, range) = match pick_output_config(&configs, &rates, want_ch) {
|
||||
Some((mut c, buffers, format)) => {
|
||||
c.buffer_size = devices::buffer_size(cfg.buffer_size, &buffers);
|
||||
(c, format)
|
||||
(c, format, devices::buffer_range(&buffers))
|
||||
}
|
||||
None => {
|
||||
let d = device.default_output_config().map_err(|e| e.to_string())?;
|
||||
@@ -126,10 +132,10 @@ pub(crate) fn open_device(
|
||||
};
|
||||
let mut stream_config = c.config();
|
||||
stream_config.buffer_size = devices::buffer_size(cfg.buffer_size, c.buffer_size());
|
||||
(stream_config, c.sample_format())
|
||||
(stream_config, c.sample_format(), devices::buffer_range(c.buffer_size()))
|
||||
}
|
||||
};
|
||||
Ok((device, config, format, name))
|
||||
Ok((device, config, format, name, range))
|
||||
}
|
||||
|
||||
/// Pick the output configuration for the first requested rate the device offers (the configured
|
||||
|
||||
@@ -15,7 +15,8 @@ impl cpal::traits::StreamTrait for Fake {
|
||||
fn pause(&self) -> Result<(), cpal::Error> {
|
||||
Ok(())
|
||||
}
|
||||
/// The fake stream has no clock and no fixed buffer; neither is used by these tests.
|
||||
/// The fake stream reports 0 frames, which says nothing about a buffer (see
|
||||
/// `a_stream_that_reports_no_buffer_size_has_no_running_buffer`).
|
||||
fn buffer_size(&self) -> Result<cpal::FrameCount, cpal::Error> {
|
||||
Ok(0)
|
||||
}
|
||||
@@ -25,6 +26,12 @@ impl cpal::traits::StreamTrait for Fake {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_that_reports_no_buffer_size_has_no_running_buffer() {
|
||||
// The fake reports 0 frames, which says nothing about the device.
|
||||
assert_eq!(stream::running_buffer(&Fake { starts: true }), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_that_will_not_start_is_reported_as_failed() {
|
||||
assert!(!start_stream(&Fake { starts: false }));
|
||||
@@ -696,6 +703,7 @@ fn armed_tracks_are_heard_and_metered_after_playback_stops() {
|
||||
let mut s = soundcraft_model::Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
s.track_mut(t).unwrap().mixer.record_arm = true;
|
||||
s.track_mut(t).unwrap().mixer.input = soundcraft_model::Route::Hardware("In 1".into());
|
||||
let shared = Arc::new(Shared {
|
||||
position: AtomicI64::new(0),
|
||||
playing: AtomicBool::new(false),
|
||||
|
||||
@@ -325,6 +325,20 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
}
|
||||
"No engine" => "Sem mecanismo de áudio",
|
||||
"default buffer" => "buffer padrão",
|
||||
"The device allows {}–{} samples; it runs at its default buffer." => {
|
||||
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão."
|
||||
}
|
||||
"The device did not take {} samples; it runs at its default buffer." => {
|
||||
"O dispositivo não aceitou {} amostras; ele funciona com o buffer padrão."
|
||||
}
|
||||
"The device runs only at {} samples." => "O dispositivo funciona apenas com {} amostras.",
|
||||
"The device runs at {} samples, not {}." => "O dispositivo funciona com {} amostras, não {}.",
|
||||
"The device allows {}–{} samples; it runs at its default buffer, {} samples." => {
|
||||
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão, {} amostras."
|
||||
}
|
||||
"The device did not take {} samples; it runs at its default buffer, {} samples." => {
|
||||
"O dispositivo não aceitou {} amostras; ele funciona com o buffer padrão, {} amostras."
|
||||
}
|
||||
"Bus name: {name}" => "Nome do bus: {name}",
|
||||
"Model" => "Modelo",
|
||||
"Version" => "Versão",
|
||||
|
||||
@@ -27,7 +27,7 @@ impl SoundApp {
|
||||
// The input reopens on the next record or monitor with the new choice.
|
||||
self.recorder = None;
|
||||
self.recorder_failed = false;
|
||||
let player = soundcraft_playback::Player::with_config(self.engine.session_arc(), &self.ui.audio);
|
||||
let player = reopen(&mut self.player, &self.ui.audio, || soundcraft_playback::Player::with_config(self.engine.session_arc(), &self.ui.audio));
|
||||
self.attach_midi(&player);
|
||||
player.locate(at);
|
||||
self.player = Some(player);
|
||||
@@ -127,12 +127,34 @@ impl SoundApp {
|
||||
}
|
||||
self.recorder = None;
|
||||
self.recorder_failed = false;
|
||||
let player = Player::with_config(self.engine.session_arc(), &self.ui.audio);
|
||||
let player = reopen(&mut self.player, &self.ui.audio, || Player::with_config(self.engine.session_arc(), &self.ui.audio));
|
||||
self.attach_midi(&player);
|
||||
self.player = Some(player);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the new device of `cfg` with `open` in place of the one in `slot`, and return it; the caller
|
||||
/// stores it, which closes the old one if it is still there.
|
||||
///
|
||||
/// On ASIO the old device closes first: in cpal 0.18.2 a process holds one ASIO driver, and while
|
||||
/// the old stream keeps it loaded the device list stops at the first other driver, so the new device
|
||||
/// (even the same driver again) is often not found and the player falls back to the silent clock
|
||||
/// (#1864). Elsewhere (Core Audio, WASAPI, ALSA, JACK) a device opens whatever else is open, and the
|
||||
/// old one stays open until the new one is there, as before: closing first there would only make the
|
||||
/// new device start cold, which on Core Audio holds Apply on the UI thread for about half a second.
|
||||
fn reopen<T>(slot: &mut Option<T>, cfg: &soundcraft_playback::AudioConfig, open: impl FnOnce() -> T) -> T {
|
||||
if one_driver_per_process(cfg) {
|
||||
drop(slot.take());
|
||||
}
|
||||
open()
|
||||
}
|
||||
|
||||
/// Whether `cfg`'s audio system opens one driver per process (ASIO in cpal 0.18.2), so the device in
|
||||
/// use must close before another (or the same one again) can be found.
|
||||
fn one_driver_per_process(cfg: &soundcraft_playback::AudioConfig) -> bool {
|
||||
cfg.system.as_deref().is_some_and(|s| s.eq_ignore_ascii_case("ASIO"))
|
||||
}
|
||||
|
||||
pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], gr: f32, dt: f32) {
|
||||
// Instant attack, ~26 dB/s release, 2 s peak hold.
|
||||
let fall = 10f32.powf(-26.0 * dt / 20.0);
|
||||
@@ -167,6 +189,84 @@ pub(super) fn wants_audio_input(s: &soundcraft_model::Session) -> bool {
|
||||
s.tracks.iter().any(|t| !t.kind.is_midi() && (t.mixer.input_monitor || t.mixer.record_arm))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reopen_tests {
|
||||
use super::reopen;
|
||||
use soundcraft_playback::AudioConfig;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// A fake audio system. `one_driver` models ASIO in cpal 0.18.2: while a stream holds the
|
||||
/// driver, looking a device up by name finds nothing. Without it, any device opens.
|
||||
#[derive(Default)]
|
||||
struct FakeHost {
|
||||
one_driver: bool,
|
||||
open_streams: Rc<Cell<u32>>,
|
||||
opened_while_another_was_open: Cell<u32>,
|
||||
}
|
||||
|
||||
/// An open stream; dropping it closes it (and releases an ASIO driver).
|
||||
struct Stream(Rc<Cell<u32>>);
|
||||
|
||||
impl Drop for Stream {
|
||||
fn drop(&mut self) {
|
||||
self.0.set(self.0.get() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// A player: its stream when the device was found, else the silent clock (no stream).
|
||||
struct FakePlayer {
|
||||
stream: Option<Stream>,
|
||||
}
|
||||
|
||||
impl FakeHost {
|
||||
fn open(&self) -> FakePlayer {
|
||||
if self.open_streams.get() > 0 {
|
||||
self.opened_while_another_was_open.set(self.opened_while_another_was_open.get() + 1);
|
||||
if self.one_driver {
|
||||
return FakePlayer { stream: None };
|
||||
}
|
||||
}
|
||||
self.open_streams.set(self.open_streams.get() + 1);
|
||||
FakePlayer { stream: Some(Stream(Rc::clone(&self.open_streams))) }
|
||||
}
|
||||
}
|
||||
|
||||
fn config(system: &str) -> AudioConfig {
|
||||
AudioConfig { system: Some(system.into()), output: Some("ASIO4ALL v2".into()), ..AudioConfig::default() }
|
||||
}
|
||||
|
||||
/// Apply, Apply, Reconnect: each step opens the device of `cfg` in place of the open one, as
|
||||
/// `apply_audio_config` and `reconnect_audio` do. Returns whether each step found the device.
|
||||
fn apply_apply_reconnect(host: &FakeHost, cfg: &AudioConfig) -> Vec<bool> {
|
||||
let mut player = Some(host.open());
|
||||
assert!(player.as_ref().is_some_and(|p| p.stream.is_some()), "the first open finds the device");
|
||||
let mut found = Vec::new();
|
||||
for _ in ["first Apply", "second Apply", "Reconnect"] {
|
||||
let new = reopen(&mut player, cfg, || host.open());
|
||||
found.push(new.stream.is_some());
|
||||
player = Some(new);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_asio_every_apply_and_reconnect_finds_the_device() {
|
||||
let host = FakeHost { one_driver: true, ..FakeHost::default() };
|
||||
assert_eq!(apply_apply_reconnect(&host, &config("ASIO")), [true, true, true], "no step falls back to the silent clock");
|
||||
assert_eq!(host.opened_while_another_was_open.get(), 0, "the old stream released the driver before each lookup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elsewhere_the_old_device_stays_open_until_the_new_one_is_there() {
|
||||
for system in ["CoreAudio", "WASAPI"] {
|
||||
let host = FakeHost::default();
|
||||
assert_eq!(apply_apply_reconnect(&host, &config(system)), [true, true, true]);
|
||||
assert_eq!(host.opened_while_another_was_open.get(), 3, "{system}: each new device opened before the old one closed, as before");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod audio_input_tests {
|
||||
use super::wants_audio_input;
|
||||
|
||||
@@ -71,9 +71,8 @@ pub(crate) fn midi_input_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
|
||||
pub(crate) fn input_name(app: &SoundApp, track: &Track) -> String {
|
||||
if track.kind.is_midi() {
|
||||
midi_input_name(track)
|
||||
} else if track.kind.has_playlist() && track.mixer.input == Route::None {
|
||||
let channels = track.format.channels();
|
||||
if channels == 1 { crate::localized_format!("In {}", 1) } else { crate::localized_format!("In 1-{}", channels) }
|
||||
} else if track.mixer.input == Route::None {
|
||||
crate::localization::text("no input").to_string()
|
||||
} else {
|
||||
route_name(app, &track.mixer.input)
|
||||
}
|
||||
@@ -180,3 +179,22 @@ mod midi_input_tests {
|
||||
assert_eq!(shown(&app, audio), "In 1", "an audio track still shows its audio input");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod no_input_tests {
|
||||
use super::input_name;
|
||||
use crate::{Services, SoundApp};
|
||||
use serde_json::json;
|
||||
|
||||
/// An audio or aux track set to no input says so (it showed "In 1", or "no output" on an aux).
|
||||
#[test]
|
||||
fn no_input_reads_no_input_on_the_selector() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
app.run("track.new", json!({"format": "mono"})).unwrap();
|
||||
app.run("track.new", json!({"kind": "aux"})).unwrap();
|
||||
app.run("track.input", json!({"tracks": [app.engine.session().tracks[0].id.0], "input": "none"})).unwrap();
|
||||
for track in &app.engine.session().tracks {
|
||||
assert_eq!(input_name(&app, track), "no input", "{}", track.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -672,6 +672,11 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
}));
|
||||
ui.end_row();
|
||||
if let Some(note) = buffer_note(app) {
|
||||
ui.label("");
|
||||
ui.label(egui::RichText::new(buffer_note_text(note)).color(ui.visuals().warn_fg_color));
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label(crate::localization::text("Input"));
|
||||
ui.label(app.recorder.as_ref().map_or(crate::localization::text("opened on first record or monitor").to_string(), |r| {
|
||||
crate::localized_format!("{} · {} Hz · {} ch", r.device_name, r.sample_rate, r.channels)
|
||||
@@ -722,7 +727,9 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
|
||||
/// `ui.audio_device`: `{list?: bool}` returns the audio systems and their devices;
|
||||
/// `{system?, output?, input?, sample_rate?, buffer_size?}` (a `null` value means "default") sets
|
||||
/// the choice and reopens the devices. Always returns the choice and the open device.
|
||||
/// the choice and reopens the devices. Always returns the choice, the open device (with the
|
||||
/// driver's `buffer_range`, null when it reports none, and `buffer_running`, the size the stream
|
||||
/// reports it runs at) and a `buffer_note` when the device does not run at the chosen buffer size.
|
||||
pub fn audio_device_command(app: &mut SoundApp, p: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
use serde_json::Value;
|
||||
let mut changed = false;
|
||||
@@ -746,21 +753,55 @@ pub fn audio_device_command(app: &mut SoundApp, p: &serde_json::Value) -> Result
|
||||
app.apply_audio_config(cfg)?;
|
||||
}
|
||||
let device = app.player.as_ref().map(|pl| {
|
||||
json!({"name": pl.device_name, "sample_rate": pl.device_rate, "channels": pl.device_channels, "buffer_size": pl.device_buffer, "silent": pl.silent})
|
||||
let range = pl.device_buffer_range.map(|(min, max)| json!({"min": min, "max": max}));
|
||||
json!({"name": pl.device_name, "sample_rate": pl.device_rate, "channels": pl.device_channels, "buffer_size": pl.device_buffer, "buffer_range": range, "buffer_running": pl.device_buffer_running, "silent": pl.silent})
|
||||
});
|
||||
let mut out = json!({"config": app.ui.audio, "device": device});
|
||||
let mut out = json!({"config": app.ui.audio, "device": device, "buffer_note": buffer_note(app).map(|n| n.english())});
|
||||
if p.get("list").and_then(Value::as_bool).unwrap_or(false) {
|
||||
out["systems"] = json!(soundcraft_playback::devices::audio_systems());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Why the open output does not run at the chosen buffer, when it does not (#1757).
|
||||
fn buffer_note(app: &SoundApp) -> Option<soundcraft_playback::devices::BufferNote> {
|
||||
let player = app.player.as_ref().filter(|p| !p.silent)?;
|
||||
soundcraft_playback::devices::buffer_note(
|
||||
app.ui.audio.buffer_size,
|
||||
player.device_buffer,
|
||||
player.device_buffer_range,
|
||||
player.device_buffer_running,
|
||||
)
|
||||
}
|
||||
|
||||
/// The window's wording of a [`soundcraft_playback::devices::BufferNote`].
|
||||
fn buffer_note_text(note: soundcraft_playback::devices::BufferNote) -> String {
|
||||
use soundcraft_playback::devices::BufferNote;
|
||||
match note {
|
||||
BufferNote::OutsideRange { min, max, .. } if min == max => crate::localized_format!("The device runs only at {} samples.", min),
|
||||
BufferNote::OutsideRange { min, max, running: Some(n) } => {
|
||||
crate::localized_format!("The device allows {}–{} samples; it runs at its default buffer, {} samples.", min, max, n)
|
||||
}
|
||||
BufferNote::OutsideRange { min, max, running: None } => {
|
||||
crate::localized_format!("The device allows {}–{} samples; it runs at its default buffer.", min, max)
|
||||
}
|
||||
BufferNote::Refused { want, running: Some(n) } => {
|
||||
crate::localized_format!("The device did not take {} samples; it runs at its default buffer, {} samples.", want, n)
|
||||
}
|
||||
BufferNote::Refused { want, running: None } => {
|
||||
crate::localized_format!("The device did not take {} samples; it runs at its default buffer.", want)
|
||||
}
|
||||
BufferNote::Rounded { want, running } => crate::localized_format!("The device runs at {} samples, not {}.", running, want),
|
||||
}
|
||||
}
|
||||
|
||||
/// Programmatic `setup.playback_engine` / `setup.hardware`. `device` is the output name and
|
||||
/// `buffer_size` is any integer 16..=8192 or null (not rounded to the window's power-of-two list);
|
||||
/// both go through [`audio_device_command`]. Delay compensation still goes through the engine
|
||||
/// command, and only after the device change has been accepted. The result is the open device:
|
||||
/// its name, the buffer actually in use (`device_buffer`, null for the device default), its sample
|
||||
/// rate, and delay compensation. `applied` is true only when an audio device is open.
|
||||
/// its name, the buffer actually in use (`buffer_size`, null for the device default), a
|
||||
/// `buffer_note` when that is not the chosen size, its sample rate, and delay compensation.
|
||||
/// `applied` is true only when an audio device is open.
|
||||
pub fn setup_audio_command(app: &mut SoundApp, id: &str, p: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
use serde_json::Value;
|
||||
let mut audio = serde_json::Map::new();
|
||||
@@ -796,6 +837,7 @@ pub fn setup_audio_command(app: &mut SoundApp, id: &str, p: &serde_json::Value)
|
||||
"applied": applied,
|
||||
"device": device,
|
||||
"buffer_size": buffer_size,
|
||||
"buffer_note": buffer_note(app).map(|n| n.english()),
|
||||
"sample_rate": sample_rate,
|
||||
"bit_depth": app.engine.session().bit_depth,
|
||||
"delay_compensation": app.engine.session().edit.delay_compensation,
|
||||
|
||||
@@ -83,19 +83,21 @@ pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
// an event's `repeat` flag from the physical key state, which says nothing about whether that
|
||||
// particular event was injected.
|
||||
let scripted = app.scripted_key_press_indices();
|
||||
let events: Vec<(Key, Modifiers, bool)> = ctx.input(|i| {
|
||||
let events: Vec<(Key, Option<Key>, Modifiers, bool)> = ctx.input(|i| {
|
||||
i.events
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, e)| match e {
|
||||
egui::Event::Key { key, pressed: true, repeat, modifiers, .. } => Some((*key, *modifiers, *repeat && !scripted.contains(&index))),
|
||||
egui::Event::Key { key, physical_key, pressed: true, repeat, modifiers } => {
|
||||
Some((*key, *physical_key, *modifiers, *repeat && !scripted.contains(&index)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
// Cmd and Ctrl are separate keys only on macOS (asked at runtime so the web build in a Mac browser agrees).
|
||||
let mac = ctx.os() == egui::os::OperatingSystem::Mac;
|
||||
for (key, mods, repeat) in events {
|
||||
for (key, physical, mods, repeat) in events {
|
||||
if repeat {
|
||||
if let Some((id, params)) = repeating_command(key, mods, mac) {
|
||||
let _ = app.run(id, params);
|
||||
@@ -105,19 +107,57 @@ pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if fixed(app, key, mods, mac) {
|
||||
continue;
|
||||
}
|
||||
if let Some(id) = command_for(key, mods, mac) {
|
||||
if crate::menus::invoke_shortcut_dialog(app, id) {
|
||||
continue;
|
||||
}
|
||||
let _ = app.run(id, json!({}));
|
||||
} else if let Some(c) =
|
||||
crate::menus::UI_COMMANDS.iter().find(|c| c.3.and_then(parse).is_some_and(|(m, k)| k == key && mods_match(m, mods, mac)))
|
||||
if !registered(app, key, mods, mac)
|
||||
&& let Some(base) = shifted_symbol_base(key, physical, mods)
|
||||
{
|
||||
let _ = app.run(c.0, json!({}));
|
||||
registered(app, base, mods, mac);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the registry or UI command whose shortcut is this chord. Returns whether one matched.
|
||||
fn registered(app: &mut SoundApp, key: Key, mods: Modifiers, mac: bool) -> bool {
|
||||
if let Some(id) = command_for(key, mods, mac) {
|
||||
if !crate::menus::invoke_shortcut_dialog(app, id) {
|
||||
let _ = app.run(id, json!({}));
|
||||
}
|
||||
true
|
||||
} else if let Some(c) = crate::menus::UI_COMMANDS.iter().find(|c| c.3.and_then(parse).is_some_and(|(m, k)| k == key && mods_match(m, mods, mac)))
|
||||
{
|
||||
let _ = app.run(c.0, json!({}));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The key a shortcut names for a Shift chord the layout reports by its shifted character. With
|
||||
/// Shift held the platform reports the `/` key as `?` (and `\` as `|`, `[` as `{`, ...), so
|
||||
/// "Shift+/" never matched a real press, only a scripted one built from the shortcut string. The key's
|
||||
/// position (`physical_key`, named after the US layout) gives the key back. Only punctuation: a letter
|
||||
/// or digit position must not stand in for a symbol another layout types there.
|
||||
fn shifted_symbol_base(key: Key, physical: Option<Key>, mods: Modifiers) -> Option<Key> {
|
||||
let shifted = matches!(key, Key::Questionmark | Key::Pipe | Key::OpenCurlyBracket | Key::CloseCurlyBracket | Key::Colon | Key::Plus);
|
||||
physical.filter(|p| {
|
||||
mods.shift
|
||||
&& shifted
|
||||
&& matches!(
|
||||
p,
|
||||
Key::Slash
|
||||
| Key::Backslash
|
||||
| Key::OpenBracket
|
||||
| Key::CloseBracket
|
||||
| Key::Semicolon
|
||||
| Key::Equals
|
||||
| Key::Comma
|
||||
| Key::Period
|
||||
| Key::Quote
|
||||
| Key::Minus
|
||||
| Key::Backtick
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The command a host auto-repeat of this chord runs, if it is one of [`REPEATING`]. A repeat
|
||||
/// resolves its chord the way a press falls through to these zooms ([`zoom_key`], then the
|
||||
/// registry) without the earlier [`fixed`] / [`fixed_more`] arms, so an arm added there for one of
|
||||
|
||||
@@ -30,6 +30,16 @@ fn new_app() -> SoundApp {
|
||||
SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reply_says_when_the_device_does_not_run_at_the_chosen_buffer() {
|
||||
// Nothing open: there is no device buffer to explain, so the note is null, never a guess (#1757).
|
||||
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
|
||||
for command in ["ui.audio_device", "setup.playback_engine"] {
|
||||
let r = app.run(command, json!({})).unwrap();
|
||||
assert!(r.get("buffer_note").is_some_and(serde_json::Value::is_null), "{command}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playback_engine_refuses_an_invalid_or_untimely_device_choice_without_side_effects() {
|
||||
let mut app = new_app();
|
||||
|
||||
@@ -317,3 +317,57 @@ fn cmd_6_and_7_choose_the_pencil_and_the_smart_tool() {
|
||||
assert_eq!(app.engine.session().edit.tool.id(), "smart", "{os:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What egui-winit sends for a real press of the `key` key with Shift and Cmd (Ctrl off macOS) held: the
|
||||
/// modifier keys first, each with its own `ModifiersChanged`, then the key by the name the layout gives
|
||||
/// it, with its US-layout position as `physical_key`, and no `Text` while Cmd or Ctrl is down.
|
||||
fn host_chord(os: OperatingSystem, cmd: Modifiers, logical: Key, physical: Key) -> Vec<Event> {
|
||||
let command_key = if os == OperatingSystem::Mac { Key::SuperLeft } else { Key::ControlLeft };
|
||||
let shift_held = Modifiers { shift: true, ..cmd };
|
||||
let key = |key, physical_key, pressed, modifiers| Event::Key { key, physical_key, pressed, repeat: false, modifiers };
|
||||
vec![
|
||||
key(command_key, Some(command_key), true, Modifiers::NONE),
|
||||
Event::ModifiersChanged(cmd),
|
||||
key(Key::ShiftLeft, Some(Key::ShiftLeft), true, cmd),
|
||||
Event::ModifiersChanged(shift_held),
|
||||
key(logical, Some(physical), true, shift_held),
|
||||
key(logical, Some(physical), false, shift_held),
|
||||
]
|
||||
}
|
||||
|
||||
fn host_pass(ctx: &egui::Context, app: &mut SoundApp, events: Vec<Event>) {
|
||||
ctx.run_ui(RawInput { events, ..Default::default() }, |ui| shortcuts::handle(app, ui.ctx())).textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Cmd+Shift+. is All MIDI Notes Off (Pro Tools p.1061), also under Commands Keyboard Focus, where a
|
||||
/// bare `.` nudges. macOS reports the key from the layout's Cmd table as `.`; Windows and Linux report
|
||||
/// `>`, which egui has no key for, so the key arrives by its position.
|
||||
#[test]
|
||||
fn a_host_cmd_shift_period_turns_all_notes_off_and_does_not_nudge() {
|
||||
for (os, cmd) in OSES {
|
||||
let (ctx, mut app) = rig(os);
|
||||
app.run("options.keyboard_focus", json!({"focus": "commands"})).unwrap();
|
||||
app.run("edit.select", json!({"tracks": ["Kick"], "start": 48_000, "end": 96_000})).unwrap();
|
||||
app.engine.transport_requests.clear();
|
||||
host_pass(&ctx, &mut app, host_chord(os, cmd, Key::Period, Key::Period));
|
||||
assert_eq!(app.engine.transport_requests, [TransportRequest::AllNotesOff], "{os:?}");
|
||||
assert_eq!(start(&app), 48_000, "{os:?}: the chord nudged the selection");
|
||||
}
|
||||
}
|
||||
|
||||
/// Shift+/ is Link Timeline and Edit Selection. Every platform reports that press as `?`.
|
||||
#[test]
|
||||
fn a_host_shift_slash_toggles_link_timeline_and_edit_selection() {
|
||||
for (os, _) in OSES {
|
||||
let (ctx, mut app) = rig(os);
|
||||
let linked = app.engine.session().edit.link_timeline_edit;
|
||||
let shift = Modifiers::SHIFT;
|
||||
let key = |key, physical_key, pressed| Event::Key { key, physical_key, pressed, repeat: false, modifiers: shift };
|
||||
host_pass(
|
||||
&ctx,
|
||||
&mut app,
|
||||
vec![Event::ModifiersChanged(shift), key(Key::Questionmark, Some(Key::Slash), true), key(Key::Questionmark, Some(Key::Slash), false)],
|
||||
);
|
||||
assert_ne!(app.engine.session().edit.link_timeline_edit, linked, "{os:?}");
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -1,6 +1,6 @@
|
||||
# Where SoundCraft falls short of Pro Tools
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-23 · **Change:** trivial (G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-25 · **Change:** minor (G-01: a buffer size the driver does not take is reported; previously trivial: G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing
|
||||
real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker**
|
||||
@@ -52,6 +52,14 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t
|
||||
not rounded onto the window's power-of-two list. Headless (CLI, no app) still stores the request
|
||||
and returns `applied: false`, with `buffer_size` null when unset; playback does not read those
|
||||
session values.
|
||||
- **Done (2026-11-25):** a buffer size the driver does not take is reported: `ui.audio_device`,
|
||||
`setup.playback_engine` and `setup.hardware` return a `buffer_note`, `ui.audio_device` also
|
||||
returns the driver's range as `device.buffer_range`, and the Playback Engine shows the note under
|
||||
Output (#1757). On macOS an RME UFX's driver allows 15–3072 frames; 4096 opens at its default
|
||||
buffer. The note says the size the device runs at (`device.buffer_running`, from the open
|
||||
stream), and a device that reports one size (shared-mode WASAPI reports its period, 480 frames at
|
||||
48 kHz) is said to run only at that size. A size the driver takes while the stream runs at
|
||||
another (a host may round it) is said too.
|
||||
- **Missing:** routing to physical channels (I/O Setup), one duplex stream on one clock (input and
|
||||
output are still separate cpal streams), latency reporting and record-offset compensation, ASIO
|
||||
in official builds (owner decision: Steinberg's SDK is proprietary or GPLv3), JACK, and
|
||||
@@ -252,6 +260,7 @@ missing. Out of scope unless the owner decides otherwise.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-25 | minor | G-01: a buffer size the driver does not take is reported, with the driver's range (#1757); estimates unchanged |
|
||||
| 2026-11-23 | trivial | G-04: Clip Looping Number of Loops accepts up to 1,000; crossfade remains open; estimates unchanged |
|
||||
| 2026-11-14 | minor | G-03: strict external-WAV AAF import with bounded property caching; AAF/OMF export, OMF import and `.ptx` remain; estimates unchanged |
|
||||
| 2026-11-13 | trivial | G-09: the pt-BR catalog now covers tooltips localized inside buttons and toggles, the Edit-window status bar, the remove-session question, the send help text and engine errors shown in the status line; estimates unchanged |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Hardware parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (record to disk: done, #84 and #888, previously trivial: bounces of a bus fed by an aux compensate its latency, #246; previously minor: MIDI input devices, live play-through with controllers, and MIDI recording) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (buffer sizes verified on Core Audio; one the driver does not take is reported; previously minor: record to disk: done, #84 and #888, previously trivial: bounces of a bus fed by an aux compensate its latency, #246; previously minor: MIDI input devices, live play-through with controllers, and MIDI recording) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
A DAW is judged by how it drives audio interfaces, MIDI gear, control surfaces and sync. This is
|
||||
SoundCraft's weakest dimension. Ours is measured from `crates/playback` (cpal) and the absence of
|
||||
@@ -18,7 +18,7 @@ Legend: ✅ works · 🟡 partial · ❌ missing.
|
||||
| Driver API | Core Audio / ASIO | 🟡 Core Audio via cpal | 🟡 WASAPI shared via cpal; ASIO with the opt-in `asio` build feature (verified with an SSL 2+) | 🟡 ALSA/Pulse via cpal; no JACK | 🟡 cpal (ALSA layer) | 🟡 Web Audio |
|
||||
| Choose playback device | ✅ Playback Engine | 🟡 Setup › Playback Engine (not yet verified on macOS) | ✅ Setup › Playback Engine (WASAPI, ASIO) | 🟡 (not yet verified) | 🟡 (not yet verified) | ❌ |
|
||||
| Choose input device | ✅ | 🟡 Setup › Playback Engine (not yet verified on macOS) | ✅ (WASAPI, ASIO) | 🟡 (not yet verified) | ❌ no recording | ❌ |
|
||||
| Buffer size (32–2048) | ✅ | 🟡 device buffer when the driver allows it (not yet verified); mix in 512-sample blocks | 🟡 device buffer 16–8192 (verified 128 on ASIO, 256 on WASAPI); mix in 512-sample blocks | 🟡 (not yet verified) | 🟡 | ❌ |
|
||||
| Buffer size (32–2048) | ✅ | 🟡 device buffer when the driver allows it (16–2048 verified on an RME UFX, whose driver allows 15–3072); outside the driver's range the default buffer, and the Playback Engine says so; mix in 512-sample blocks | 🟡 device buffer 16–8192 (verified 128 on ASIO, 256 on WASAPI); mix in 512-sample blocks | 🟡 (not yet verified) | 🟡 | ❌ |
|
||||
| Duplex stream on one clock | ✅ | ❌ separate input/output streams | ❌ | ❌ | ❌ | ❌ |
|
||||
| Hardware I/O mapping (I/O Setup to physical channels) | ✅ | 🟡 multichannel output in order; no per-channel map | 🟡 | 🟡 | 🟡 | ❌ |
|
||||
| Low-latency monitoring | ✅ | ❌ (`options.low_latency_monitoring` is a stored flag) | ❌ | ❌ | ❌ | ❌ |
|
||||
@@ -72,6 +72,7 @@ Legend: ✅ works · 🟡 partial · ❌ missing.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-25 | minor | Buffer sizes 16–2048 verified on Core Audio; a size the driver does not take is reported with its range (#1757) |
|
||||
| 2026-11-18 | minor | MIDI input devices (`midir`): live play-through to record-enabled MIDI and instrument tracks (notes, pedal, controllers, pitch bend, aftertouch), MIDI recording into clips, per-track device and channel, device switches in Playback Engine; guide in `midi-input.md` |
|
||||
| 2026-10-30 | minor | Record to disk: takes are written to disk as they record (#84) and long takes continue in a new file (#888) |
|
||||
| 2026-10-13 | trivial | bounces of a bus fed by an aux compensate its latency (#246) |
|
||||
|
||||
+3
-1
@@ -75,7 +75,9 @@ When the pass stops, each track that was record-enabled and active when it start
|
||||
clip with what its input received: notes with their velocities, controllers, pitch bend, aftertouch and
|
||||
program changes. What a pass records is settled when it starts: a track put in record while it
|
||||
runs is recorded from the next pass, and one taken out of record keeps what it recorded. A track
|
||||
that received nothing gets no clip. The clip covers the pass, the punch range, or the loop.
|
||||
that received nothing gets no clip. The clip covers the pass, the punch range, or the loop. A key
|
||||
pressed before a punch range (during the pre-roll) and still held when it starts is recorded
|
||||
from the start of the range.
|
||||
One **Undo** removes the take.
|
||||
|
||||
**Setup › MIDI › MIDI Input Filter…** keeps kinds of messages (for example aftertouch) out of
|
||||
|
||||
Reference in new issue
Block a user