diff --git a/crates/engine/src/cmd/clip_split.rs b/crates/engine/src/cmd/clip_split.rs new file mode 100644 index 00000000..e2064031 --- /dev/null +++ b/crates/engine/src/cmd/clip_split.rs @@ -0,0 +1,206 @@ +//! Split to Mono Tracks (`clip.split_to_mono`): each channel of the selected stereo or wider audio +//! clips on a new mono track below its track, the originals muted, in one undo step: two +//! microphones recorded onto one stereo track come apart this way. The clips of one track share +//! its new tracks. An in-memory source splits in memory (each channel is written to `Audio Files` +//! on save, as a recording is); a source played from its file (ADR 0035) gets one mono WAV per +//! channel written beside that file, played from disk in turn. + +use super::*; +use crate::cmd; +use serde_json::json; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; +use transit_audio_io::{AudioBuffer, FileFormat}; +use transit_model::disk::DiskSource; +use transit_model::{ChannelFormat, ClipContent, ClipId, SourceAudio, SourceId, TrackId, TrackKind}; + +const ID: &str = "clip.split_to_mono"; + +pub fn specs() -> Vec { + vec![cmd!( + "clip.split_to_mono", + "Split to Mono Tracks", + ["Clip"], + None, + "{clips?} — each channel of the stereo or wider audio clips on a new mono track below its track; the originals are muted", + has_selection, + split_to_mono + )] +} + +/// The most channels a clip splits into, one track each, so a hostile file's channel count never +/// becomes tens of thousands of tracks: a MADI-sized recording (64) fits, a wider one is refused. +const MAX_CHANNELS: usize = 64; + +/// Channel `ch` of `n` in a split's names: `L` and `R` for stereo, else its number from 1 (a +/// file's channels carry no layout here; an eight-track field recording is not 7.1). +fn split_label(n: usize, ch: usize) -> String { + match (n, ch) { + (2, 0) => "L".into(), + (2, 1) => "R".into(), + _ => (ch + 1).to_string(), + } +} + +/// A channel's audio, ready to become a source. +enum Mono { + Memory(SourceAudio), + /// The file written for it, and its audio played from that file. + Disk(PathBuf, Arc), +} + +/// One source's split: its id, its BWF time stamp, and each channel's name and audio. +type Split = (SourceId, u64, Vec<(String, Mono)>); + +fn split_to_mono(e: &mut Engine, p: &Value) -> Result { + let mut ids = clip_ids_param(e, p); + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); + let s = e.session(); + // The clips to split on each track, in track order, with their sources' channel counts. + let mut by_track: BTreeMap)> = BTreeMap::new(); + for id in &ids { + let (t, c) = s.find_clip(*id).ok_or_else(|| bad(ID, format!("unknown clip {}", id.0)))?; + let ClipContent::Audio { source, .. } = c.content else { continue }; + let n = s.pool.get(source).map_or(0, |a| a.buffer.num_channels()); + if n > MAX_CHANNELS { + return Err(bad(ID, format!("{} has {n} channels: a clip splits into at most {MAX_CHANNELS} tracks", c.name))); + } + if let (true, Some(i)) = (n > 1, s.track_index(t)) { + by_track.entry(i).or_insert((t, Vec::new())).1.push((*id, source, n)); + } + } + if by_track.is_empty() { + return Err(bad(ID, "no stereo or wider audio clip is selected")); + } + // Muting the originals edits their tracks: refused before any file is written. + if let Some(tr) = by_track.values().filter_map(|(t, _)| s.track(*t)).find(|t| t.freeze.is_some()) { + return Err(bad(ID, format!("{} is frozen: unfreeze it to split its clips", tr.name))); + } + // Every channel's audio before the session changes, so a refusal leaves it as it was and no + // file written for it behind. + let mut written = Vec::new(); + let split = match prepare(s, &by_track, &mut written) { + Ok(split) => split, + Err(err) => { + crate::io::split_files::remove(&written); + return Err(err); + } + }; + let s = e.session_mut(); + let mut sources: BTreeMap<(SourceId, usize), SourceId> = BTreeMap::new(); + for (src, stamp, monos) in split { + for (ch, (name, mono)) in monos.into_iter().enumerate() { + let id = match mono { + // The extension keeps the label: a source is named after its file's stem. + Mono::Memory(audio) => crate::io::add_source_audio(s, &format!("{name}.wav"), Arc::new(audio), None, FileFormat::Wav), + // The path written, absolute as a recording's is: a save brings it into the session folder. + Mono::Disk(path, audio) => crate::io::add_disk_source(s, &format!("{name}.wav"), audio, &path.to_string_lossy()), + }; + if let Some(sx) = s.sources.last_mut() { + sx.time_reference = stamp; + } + sources.insert((src, ch), id); + } + } + let (mut new_tracks, mut new_clips) = (Vec::new(), Vec::new()); + for (t, clips) in by_track.into_values() { + let Some(tr) = s.track(t).cloned() else { continue }; + let n = clips.iter().map(|c| c.2).max().unwrap_or(0); + let mut lanes = Vec::with_capacity(n); + for ch in 0..n { + let nt = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{} {}", tr.name, split_label(n, ch)))); + // Taken out before `t` is found: a new track goes in before a Master, which may sit above `t`. + if let Some(from) = s.track_index(nt) { + let moved = s.tracks.remove(from); + let at = s.track_index(t).map_or(s.tracks.len(), |at| at + 1 + ch); + s.tracks.insert(at.min(s.tracks.len()), moved); + } + if let Some(m) = s.track_mut(nt) { + m.folder = tr.folder; + m.mixer.volume_db = tr.mixer.volume_db; + m.mixer.output = tr.mixer.output.clone(); + m.mixer.sends = tr.mixer.sends.clone(); + } + lanes.push(nt); + new_tracks.push(nt); + } + for (cid, src, channels) in clips { + let Some(orig) = s.find_clip(cid).map(|(_, c)| c.clone()) else { continue }; + let ClipContent::Audio { offset, .. } = orig.content else { continue }; + for (ch, &lane) in lanes.iter().enumerate().take(channels) { + let Some(&mono) = sources.get(&(src, ch)) else { continue }; + let mut c = orig.clone(); + c.id = s.new_clip_id(); + c.name = format!("{}.{}", orig.name, split_label(channels, ch)); + c.content = ClipContent::Audio { source: mono, offset }; + c.group = None; + new_clips.push(c.id); + // Pushed as they are: the original's layering on its track stays as it was. + if let Some(pl) = s.track_mut(lane).and_then(|l| l.playlist_mut()) { + pl.clips.push(c); + pl.sort(); + } + } + if let Some(c) = s.find_clip_mut(cid) { + c.muted = true; + } + } + } + Ok(json!({"tracks": new_tracks, "clips": new_clips})) +} + +/// Channel `ch` of in-memory `audio` as mono audio, its peaks kept (rebuilt when there are none). +fn mono_audio(audio: &SourceAudio, ch: usize) -> SourceAudio { + let buffer = AudioBuffer { sample_rate: audio.buffer.sample_rate, channels: audio.buffer.channels.get(ch).cloned().into_iter().collect() }; + match audio.peaks.get(ch) { + Some(p) => SourceAudio { buffer, peaks: vec![p.clone()], disk: None }, + None => SourceAudio::new(buffer), + } +} + +/// Each source's channels, in memory or as one mono WAV per channel written beside its file (a +/// number added while a name is taken). The files are opened to play from disk only once every +/// one is complete; each path created is in `written`, for the caller to remove on a failure. +fn prepare( + s: &transit_model::Session, + by_track: &BTreeMap)>, + written: &mut Vec, +) -> Result> { + let mut out: Vec<(SourceId, u64, Vec<(String, Option)>, Option>)> = Vec::new(); + for (_, clips) in by_track.values() { + for &(_, src, n) in clips { + if out.iter().any(|o| o.0 == src) { + continue; + } + let (Some(meta), Some(audio)) = (s.source(src), s.pool.get(src)) else { continue }; + let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, split_label(n, ch))).collect(); + let channels = match &audio.disk { + Some(disk) => { + crate::io::split_files::write(disk, &names, written)?; + names.into_iter().map(|name| (name, None)).collect() + } + None => names.into_iter().enumerate().map(|(ch, name)| (name, Some(mono_audio(audio, ch)))).collect(), + }; + out.push((src, meta.time_reference, channels, audio.disk.clone())); + } + } + let mut files = written.iter(); + out.into_iter() + .map(|(src, stamp, channels, disk)| { + let monos = channels + .into_iter() + .map(|(name, mem)| match (mem, &disk) { + (Some(audio), _) => Ok((name, Mono::Memory(audio))), + (None, Some(disk)) => { + let p = files.next().ok_or_else(|| EngineError::Io(format!("{name}: its file was not written")))?; + Ok((name, Mono::Disk(p.clone(), crate::io::split_files::open(p, disk.rate())?))) + } + (None, None) => Err(EngineError::Io(format!("{name}: no audio"))), + }) + .collect::>>()?; + Ok((src, stamp, monos)) + }) + .collect() +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index cb2ce606..7341ae74 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -361,6 +361,10 @@ fn commit_import(e: &mut Engine, p: &Value) -> Result { /// audio track or errors when none is selected. fn import_audio_target(e: &Engine, p: &Value) -> Result> { if let Some(t) = track_param(e, "file.import_audio", p, "track")? { + // As `file.commit_import`: audio never lands on a MIDI, instrument or other track. + if let Some(tr) = e.session().track(t).filter(|tr| tr.kind != TrackKind::Audio) { + return Err(bad("file.import_audio", format!("{} is not an audio track", tr.name))); + } return Ok(Some(t)); } if bool_or(p, "new_tracks", true) { diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index da60fdd9..3e92cbeb 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -13,6 +13,7 @@ mod clip; pub(crate) mod clip_bounce; mod clip_list; mod clip_more; +mod clip_split; mod device_pages; mod edit; mod edit_more; @@ -188,6 +189,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(track_more::specs()); v.extend(clip_more::specs()); v.extend(clip_bounce::specs()); + v.extend(clip_split::specs()); v.extend(clip_list::specs()); v.extend(event_more::specs()); v.extend(setup_more::specs()); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 67500e58..bf0a6727 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -818,6 +818,7 @@ pub(crate) use session::{DecodedFiles, decode_file_streamed, file_key, open_sess use session::{replace_with, write_synced}; pub(crate) mod disk; +pub(crate) mod split_files; pub use disk::{add_disk_source, copy_path}; mod disk_reads; pub use disk_reads::{DiskReads, unreadable_line}; diff --git a/crates/engine/src/io/split_files.rs b/crates/engine/src/io/split_files.rs new file mode 100644 index 00000000..498867cb --- /dev/null +++ b/crates/engine/src/io/split_files.rs @@ -0,0 +1,83 @@ +//! The files of Split to Mono Tracks (`clip.split_to_mono`) for a take played from its file (ADR +//! 0035): one mono float WAV per channel written beside it, opened to play from disk, and removed +//! again when the split fails. + +use super::*; +use std::io::Write; +use transit_audio_io::{BitDepth, FileEncoder}; +use transit_model::disk::DiskSource; + +/// The file `path`, written by [`write`], as a source played from disk at `rate`. +pub(crate) fn open(path: &Path, rate: u32) -> Result> { + let len = std::fs::metadata(path).map_err(|err| EngineError::Io(format!("{}: {err}", path.display())))?.len(); + disk::open_disk_audio(path, len, rate).map_err(EngineError::Io) +} + +/// Removes the files a failed split wrote, and any peaks sidecar begun beside one. +pub(crate) fn remove(paths: &[PathBuf]) { + for p in paths { + let _ = std::fs::remove_file(p); + let _ = std::fs::remove_file(transit_model::disk::sidecar_path(p)); + } +} + +/// One mono float WAV per channel of `disk`'s file, beside it, named `names` (`.wav`, or +/// `-2.wav` and on while that is taken), in one pass over the file. Each path is pushed to +/// `written` as soon as it is created. +pub(crate) fn write(disk: &DiskSource, names: &[String], written: &mut Vec) -> Result<()> { + let io = |p: &Path, err: &dyn std::fmt::Display| EngineError::Io(format!("{}: {err}", p.display())); + // A reader that failed once reads nothing more: opened anew, as before an offline render, so a + // take whose file is back splits again. + disk.check().map_err(|why| io(&disk.path(), &why))?; + let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None, bitrate_kbps: None, title: None }; + let mut encoders = Vec::with_capacity(names.len()); + for name in names { + let stem = crate::io::sanitize_name(name); + let mut found = None; + for i in 1..1000 { + let p = dir.join(if i == 1 { format!("{stem}.wav") } else { format!("{stem}-{i}.wav") }); + crate::file_access::check_write(&p).map_err(EngineError::Io)?; + match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { + Ok(f) => { + found = Some((p, f)); + break; + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(err) => return Err(io(&p, &err)), + } + } + let (path, file) = found.ok_or_else(|| EngineError::Io(format!("{}: no file name free for {stem}.wav", dir.display())))?; + written.push(path.clone()); + let enc = FileEncoder::new(std::io::BufWriter::new(file), &opts, 1, disk.rate(), None).map_err(|err| io(&path, &err))?; + enc.check_room(disk.frames()).map_err(|err| io(&path, &err))?; + encoders.push((path, enc)); + } + const BLOCK: usize = 64 * 1024; + let frames = usize::try_from(disk.frames()).unwrap_or(usize::MAX); + let mut block = vec![vec![0.0f32; BLOCK]; encoders.len()]; + let unread = || EngineError::Io(format!("{}: the file could not be read", disk.path().display())); + disk.with_sync(|read| { + let mut at = 0; + while at < frames { + let len = BLOCK.min(frames - at); + // Frame by frame across the channels, so the reader passes over the file once. + for i in 0..len { + for (ch, out) in block.iter_mut().enumerate() { + out[i] = read(ch, at + i).ok_or_else(unread)?; + } + } + for ((path, enc), out) in encoders.iter_mut().zip(&block) { + enc.write(std::slice::from_ref(out), len).map_err(|err| io(path, &err))?; + } + at += len; + } + Ok::<(), EngineError>(()) + })?; + for (path, enc) in encoders { + let mut w = enc.finish().map_err(|err| io(&path, &err))?; + w.flush().map_err(|err| io(&path, &err))?; + w.into_inner().map_err(|err| io(&path, &err.error()))?.sync_all().map_err(|err| io(&path, &err))?; + } + Ok(()) +} diff --git a/crates/engine/tests/split_to_mono.rs b/crates/engine/tests/split_to_mono.rs new file mode 100644 index 00000000..88d6c9af --- /dev/null +++ b/crates/engine/tests/split_to_mono.rs @@ -0,0 +1,195 @@ +//! Split to Mono Tracks (`clip.split_to_mono`): each channel of a stereo or wider clip on a new mono +//! track below its track, in one undo step. Import itself keeps a file's channels as they are. + +use serde_json::json; +use transit_engine::Engine; +use transit_engine::model::TrackId; + +/// A 16-bit stereo PCM WAV: every left sample is `l`, every right one `r`. +fn stereo_wav(frames: u32, l: i16, r: i16) -> Vec { + let data = frames * 4; + let mut b = Vec::new(); + b.extend_from_slice(b"RIFF"); + b.extend_from_slice(&(36 + data).to_le_bytes()); + b.extend_from_slice(b"WAVEfmt "); + for v in [16u32, 0x0002_0001, 48_000, 48_000 * 4, 0x0010_0004] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(b"data"); + b.extend_from_slice(&data.to_le_bytes()); + for _ in 0..frames { + b.extend_from_slice(&l.to_le_bytes()); + b.extend_from_slice(&r.to_le_bytes()); + } + b +} + +fn track(e: &mut Engine, format: &str) -> u64 { + e.execute("track.new", &json!({"kind": "audio", "format": format})).unwrap()["tracks"][0].as_u64().unwrap() +} + +/// Each clip on `t`: its start, length, name, its source's channel count and first sample. +fn clips(e: &Engine, t: u64) -> Vec<(i64, i64, String, usize, f32)> { + let s = e.session(); + let tr = s.track(TrackId(t)).unwrap(); + tr.clips() + .iter() + .map(|c| { + let transit_engine::model::ClipContent::Audio { source, .. } = c.content else { panic!("an audio clip") }; + let buf = &s.pool.get(source).unwrap().buffer; + (c.start, c.length, c.name.clone(), buf.num_channels(), buf.channels[0][0]) + }) + .collect() +} + +#[test] +fn import_keeps_a_stereo_file_whole_even_on_a_mono_track_with_a_free_mono_track_below() { + let d = transit_test_support::TestDir::new("import-stays-whole"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let (a, b) = (track(&mut e, "mono"), track(&mut e, "mono")); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a})).unwrap(); + assert_eq!(clips(&e, a), vec![(0, 480, "LAV-2".to_string(), 2, 0.5)], "one stereo clip: a split is asked for, never done on import"); + assert!(clips(&e, b).is_empty()); +} + +#[test] +fn split_to_mono_tracks_puts_each_channel_of_a_stereo_clip_on_a_new_mono_track_below() { + let d = transit_test_support::TestDir::new("split-to-mono"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(4_800, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let mics = e.execute("track.new", &json!({"kind": "audio", "format": "stereo", "name": "Mics"})).unwrap()["tracks"][0].as_u64().unwrap(); + track(&mut e, "mono"); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": mics, "at": 960})).unwrap(); + let cid = e.session().track(TrackId(mics)).unwrap().clips()[0].id.0; + let undo = e.undo_history().len(); + let r = e.execute("clip.split_to_mono", &json!({"clips": [cid]})).unwrap(); + let names: Vec = e.session().tracks.iter().map(|t| t.name.clone()).collect(); + assert_eq!(names[..3], ["Mics", "Mics L", "Mics R"], "the new tracks sit right below: {names:?}"); + let (l, r) = (r["tracks"][0].as_u64().unwrap(), r["tracks"][1].as_u64().unwrap()); + assert_eq!(clips(&e, l), vec![(960, 4_800, "LAV-2.L".to_string(), 1, 0.5)]); + assert_eq!(clips(&e, r), vec![(960, 4_800, "LAV-2.R".to_string(), 1, -0.25)]); + assert!(e.session().find_clip(transit_engine::model::ClipId(cid)).unwrap().1.muted, "the original is muted"); + assert_eq!(e.undo_history().len(), undo + 1, "one undo step"); + + let file = d.join("split.transit"); + e.execute("session.save", &json!({"path": file.to_string_lossy()})).unwrap(); + let mut f = Engine::default(); + f.execute("session.open", &json!({"path": file.to_string_lossy()})).unwrap(); + let paths: Vec<&str> = f.session().sources.iter().map(|s| s.path.as_str()).collect(); + assert!(paths.contains(&"Audio Files/LAV-2.L.wav") && paths.contains(&"Audio Files/LAV-2.R.wav"), "{paths:?}"); + assert_eq!((clips(&f, l), clips(&f, r)), (clips(&e, l), clips(&e, r)), "the split reopens from its two mono files"); + + e.undo(); + assert_eq!(e.session().tracks.len(), 2, "one undo takes the tracks back"); + assert!(!e.session().find_clip(transit_engine::model::ClipId(cid)).unwrap().1.muted); +} + +#[test] +fn split_to_mono_tracks_writes_a_mono_file_per_channel_for_a_take_played_from_disk() { + let d = transit_test_support::TestDir::new("split-to-mono-disk"); + std::fs::create_dir_all(&*d).unwrap(); + let take = d.join("Take.wav"); + std::fs::write(&take, stereo_wav(4_800, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + // A take longer than this plays from its file (ADR 0035): 0.001 minutes is 2880 frames. + e.session_mut().edit.values.insert(transit_model::disk::STREAM_MINUTES_KEY.into(), 0.001); + let mics = track(&mut e, "stereo"); + let ids = transit_engine::io::add_recording_take(&mut e, &transit_engine::io::Recording::new(0), vec![(TrackId(mics), take)], false); + assert!(e.session().sources.last().is_some_and(|s| s.disk), "the take plays from disk"); + let r = e.execute("clip.split_to_mono", &json!({"clips": [ids[0].0]})).unwrap(); + for (i, (side, want)) in [("L", 0.5), ("R", -0.25)].into_iter().enumerate() { + let t = r["tracks"][i].as_u64().unwrap(); + let s = e.session(); + let c = &s.track(TrackId(t)).unwrap().clips()[0]; + let transit_engine::model::ClipContent::Audio { source, .. } = c.content else { panic!("an audio clip") }; + let src = s.source(source).unwrap(); + assert!(src.disk && src.channels == 1 && src.path.ends_with(&format!("Take.{side}.wav")), "{src:?}"); + let disk = s.pool.get(source).unwrap().disk.clone().unwrap(); + assert_eq!((disk.frames(), disk.with_sync(|read| read(0, 4_799))), (4_800, Some(want)), "Take.{side}.wav holds that channel"); + } +} + +#[test] +fn a_split_that_fails_on_a_later_take_leaves_no_file_of_an_earlier_one() { + let d = transit_test_support::TestDir::new("split-to-mono-cleanup"); + std::fs::create_dir_all(&*d).unwrap(); + let mut e = Engine::default(); + e.session_mut().edit.values.insert(transit_model::disk::STREAM_MINUTES_KEY.into(), 0.001); + let mut clips = Vec::new(); + for name in ["One", "Two"] { + let take = d.join(format!("{name}.wav")); + std::fs::write(&take, stereo_wav(4_800, 16_384, -8_192)).unwrap(); + let t = track(&mut e, "stereo"); + clips.extend(transit_engine::io::add_recording_take(&mut e, &transit_engine::io::Recording::new(0), vec![(TrackId(t), take)], false)); + } + // Two.wav loses its audio after it was placed: reading it fails partway through the split. + std::fs::OpenOptions::new().write(true).open(d.join("Two.wav")).unwrap().set_len(44).unwrap(); + let tracks = e.session().tracks.len(); + let r = e.execute("clip.split_to_mono", &json!({"clips": clips.iter().map(|c| c.0).collect::>()})); + assert!(r.is_err(), "{r:?}"); + // The takes' own peaks sidecars are built in the background; only split files are counted. + let left: Vec = std::fs::read_dir(&*d).unwrap().map(|f| f.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert!(left.iter().all(|f| !f.contains(".L") && !f.contains(".R")), "no split file stays behind: {left:?}"); + assert_eq!(e.session().tracks.len(), tracks, "the session is as it was"); +} + +#[test] +fn the_new_tracks_sit_right_below_the_clips_track_with_a_master_above_it() { + let d = transit_test_support::TestDir::new("split-to-mono-master"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let mics = e.execute("track.new", &json!({"kind": "audio", "format": "stereo", "name": "Mics"})).unwrap()["tracks"][0].as_u64().unwrap(); + e.execute("track.new", &json!({"kind": "audio", "format": "mono", "name": "Other"})).unwrap(); + let master = e.session_mut().add_track(transit_model::TrackKind::Master, transit_model::ChannelFormat::Stereo, Some("Master")); + let s = e.session_mut(); + let m = s.tracks.iter().position(|t| t.id == master).unwrap(); + let moved = s.tracks.remove(m); + s.tracks.insert(0, moved); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": mics})).unwrap(); + let cid = e.session().track(TrackId(mics)).unwrap().clips()[0].id.0; + e.execute("clip.split_to_mono", &json!({"clips": [cid, cid]})).unwrap(); + let names: Vec = e.session().tracks.iter().map(|t| t.name.clone()).collect(); + assert_eq!(names, ["Master 1", "Mics", "Mics L", "Mics R", "Other"]); + let per_track: Vec = e.session().tracks[2..4].iter().map(|t| t.clips().len()).collect(); + assert_eq!(per_track, [1, 1], "a clip named twice splits once"); +} + +#[test] +fn audio_is_never_imported_onto_a_midi_track() { + let d = transit_test_support::TestDir::new("import-onto-midi"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("Kick.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let midi = e.execute("track.new", &json!({"kind": "midi", "name": "Synth"})).unwrap()["tracks"][0].as_u64().unwrap(); + let r = e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": midi})); + assert!(r.as_ref().is_err_and(|err| err.to_string().contains("Synth is not an audio track")), "{r:?}"); + assert!(e.session().track(TrackId(midi)).unwrap().clips().is_empty() && e.session().sources.is_empty()); +} + +#[test] +fn a_take_whose_file_is_back_after_a_failed_read_splits_again() { + let d = transit_test_support::TestDir::new("split-to-mono-reopen"); + std::fs::create_dir_all(&*d).unwrap(); + let take = d.join("Take.wav"); + let bytes = stereo_wav(4_800, 16_384, -8_192); + std::fs::write(&take, &bytes).unwrap(); + let mut e = Engine::default(); + e.session_mut().edit.values.insert(transit_model::disk::STREAM_MINUTES_KEY.into(), 0.001); + let mics = track(&mut e, "stereo"); + let ids = transit_engine::io::add_recording_take(&mut e, &transit_engine::io::Recording::new(0), vec![(TrackId(mics), take.clone())], false); + // The file loses its audio (a drive unplugged): the split's read fails and its reader with it. + std::fs::OpenOptions::new().write(true).open(&take).unwrap().set_len(44).unwrap(); + assert!(e.execute("clip.split_to_mono", &json!({"clips": [ids[0].0]})).is_err()); + // The file is back: the split opens the take anew, as an offline render does. + std::fs::write(&take, &bytes).unwrap(); + let r = e.execute("clip.split_to_mono", &json!({"clips": [ids[0].0]})); + assert!(r.as_ref().is_ok_and(|r| r["tracks"].as_array().map(Vec::len) == Some(2)), "{r:?}"); +} diff --git a/crates/ui-studio/src/arrange.rs b/crates/ui-studio/src/arrange.rs index 7d2aa05e..b6617867 100644 --- a/crates/ui-studio/src/arrange.rs +++ b/crates/ui-studio/src/arrange.rs @@ -855,6 +855,11 @@ fn timeline_input(app: &mut StudioApp, ui: &mut Ui, s: &Session, map: Map, tl: R let item = crate::bounce_in_place::clip_menu_item(app, ui); app.arrange.menu.retain(|m| m.label != item.label); app.arrange.menu.push(item); + // Each channel of the selected stereo or wider clips on a new mono track below. + if on_clip && ui.add(crate::chrome::MenuRow::new("Split to Mono Tracks")).clicked() { + let _ = app.run("clip.split_to_mono", json!({})); + ui.close(); + } ui.separator(); crate::edit_tools::context_menu_items(app, ui); }); diff --git a/crates/ui-studio/src/browser.rs b/crates/ui-studio/src/browser.rs index a28fbd3d..86b1ed3f 100644 --- a/crates/ui-studio/src/browser.rs +++ b/crates/ui-studio/src/browser.rs @@ -630,8 +630,10 @@ impl StudioApp { /// Import audio files at `at`: onto `track` (an audio track), or onto a new track when /// `track` is `None`. Several files go one after another on the same track. The files are /// prepared in the background and committed in order, one undo step each (see `import`). + /// Maschine/Kontakt files are left out here; whether any other file is audio is the engine's + /// call (it reads a file by its contents), and a refusal gives its reason. pub fn import_files(&mut self, files: &[PathBuf], track: Option, at: Samples) -> Result<(), String> { - let (ok, closed): (Vec<&PathBuf>, Vec<&PathBuf>) = files.iter().partition(|p| kind_of(&p.to_string_lossy(), false) == Some(Kind::Audio)); + let (ok, closed): (Vec<&PathBuf>, Vec<&PathBuf>) = files.iter().partition(|p| kind_of(&p.to_string_lossy(), false) != Some(Kind::Closed)); if ok.is_empty() { let what = closed.first().map_or("Nothing to import".to_string(), |p| refusal(p)); self.status = what.clone(); @@ -639,7 +641,10 @@ impl StudioApp { } if let Some(t) = track { let s = self.engine.session(); - let Some(tr) = s.track(t) else { return Err("no such track".into()) }; + let Some(tr) = s.track(t) else { + self.status = "The track was deleted: drop the files again".into(); + return Err(self.status.clone()); + }; if tr.kind != TrackKind::Audio { self.status = format!("{} is not an audio track: drop audio files on an audio track or below the tracks", tr.name); return Err(self.status.clone()); @@ -666,13 +671,15 @@ impl StudioApp { /// device layouts. An editor window on top at `pos` comes first and takes the drop whole: /// `audio` (the payload holds an audio file) lands on a Sampler pad or an empty Sampler view's /// well, anything else over a window is no target (nothing behind a window is reached). - fn drop_target(&self, ctx: &egui::Context, pos: Pos2, snap: bool, audio: bool) -> Option<(Target, R4)> { + pub(crate) fn drop_target(&self, ctx: &egui::Context, pos: Pos2, snap: bool, audio: bool) -> Option<(Target, R4)> { if let Some(key) = self.editor_window_at(ctx, pos) { return if audio { self.editor_target(key, pos) } else { None }; } let m = &self.mixer.layout; if m.visible { - for s in m.strips.iter().chain(m.master.iter()) { + // The Main strip of a session with no Master track is the main bus, no track (its + // `track` is 0, an id no track has): no target, as the mixer's empty area. + for s in m.strips.iter().chain(m.master.iter()).filter(|s| s.track != 0) { if rect(s.rect).contains(pos) { return Some((Target::Track { track: TrackId(s.track), at: None }, s.rect)); } diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index 233049b4..761181b8 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -8,10 +8,12 @@ //! frame or a later one). A `PointerGone` does not route it blind: the drop stays held, and only //! after [`GONE_GRACE_FRAMES`] frames with no position does it go to the arrangement. Then the //! editor window on top at that position (egui's own layer order) claims it, or the arrangement -//! imports it. Exactly one claimant takes a drop; a held drop never vanishes (a second drop while -//! one is held routes with it). +//! imports it by the browser drag's rules: on the track under the pointer or below the tracks, else +//! at the cursor, with the reason on the status line when it can't. Exactly one claimant takes a +//! drop; a held drop never vanishes (a second drop while one is held routes with it). use crate::StudioApp; +use crate::browser::Target; use std::path::PathBuf; use transit_model::TrackId; @@ -123,9 +125,60 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) r.offer = Some((key, offer)); return; } - for p in &offer.paths { + // A drop holding a session opens it and nothing else: its other files would land in whichever + // document is open when their turn came, the closing one or the new one by a pointer or a + // cursor that still names the closing one's tracks. + if let Some(session) = offer.paths.iter().find(|p| opens_session(&p.to_string_lossy())) { + let left = offer.paths.len() - 1; + if left > 0 { + // Said first, so a session that fails to open replaces it with its own reason. + let name = session.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + app.status = format!( + "{left} file{} dropped with {name} {} not imported; drop {} on the session once it is open", + if left == 1 { "" } else { "s" }, + if left == 1 { "was" } else { "were" }, + if left == 1 { "it" } else { "them" } + ); + } + open_path(app, &session.to_string_lossy()); + return; + } + let (midi, audio): (Vec, Vec) = offer.paths.iter().cloned().partition(|p| is_midi(&p.to_string_lossy())); + for p in midi { open_path(app, &p.to_string_lossy()); } + if audio.is_empty() { + return; + } + // The rest lands as a browser drag's files do (`import_files`): on the track under the pointer + // (at the pointer's time on its lane) or on a new track below the tracks, one after another; + // anywhere else at the cursor (on the cursor's track, as before). A track that takes no audio, + // or a file that is not audio, is refused with the reason on the status line. + let snap = !ctx.input(|i| i.modifiers.shift); + let cursor = app.cursor(); + let _ = match offer.pos.and_then(|p| app.drop_target(ctx, p, snap, true)).map(|(t, _)| t) { + Some(Target::Track { track, at }) => app.import_files(&audio, Some(track), at.unwrap_or(cursor)), + Some(Target::Below { at }) => app.import_files(&audio, None, at.unwrap_or(cursor)), + _ => app.import_files(&audio, cursor_audio_track(app), cursor), + }; +} + +/// The cursor's track when it is an audio track: where audio lands at the cursor (none: a new +/// track). +fn cursor_audio_track(app: &StudioApp) -> Option { + app.cursor_track().filter(|t| app.engine.session().track(*t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio)) +} + +/// Whether dropping `p` opens it as the session. +fn opens_session(p: &str) -> bool { + let lower = p.to_ascii_lowercase(); + lower.ends_with(".transit") || lower.ends_with(".dawproject") +} + +/// Whether `p` imports as MIDI. +fn is_midi(p: &str) -> bool { + let lower = p.to_ascii_lowercase(); + lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") } /// Offers `path` to the editor window `key` in the next frame, as a file dropped on it at `pos` (a @@ -140,21 +193,21 @@ pub(crate) fn take(app: &mut StudioApp, key: (TrackId, usize)) -> Option Open does), a MIDI file imports, any other file imports +/// as audio at the cursor (on the cursor's track when it is an audio track, else on a new one). +/// Used for files named on the command line; a failure's reason goes to the status line. pub fn open_path(app: &mut StudioApp, p: &str) { - let lower = p.to_ascii_lowercase(); - if lower.ends_with(".transit") || lower.ends_with(".dawproject") { + if opens_session(p) { app.run_or_ask("session.open", serde_json::json!({"path": p})); return; } - let r = if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { + let r = if is_midi(p) { app.run("file.import_midi", serde_json::json!({"path": p})) } else { let at = app.cursor(); let mut params = serde_json::json!({"path": p, "at": at}); - if let Some(t) = app.cursor_track() { + if let Some(t) = cursor_audio_track(app) { params["track"] = serde_json::json!(t.0); } app.run("file.import_audio", params) diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index 94c4bc1d..18cf26bc 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -280,7 +280,22 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { app.drop_item(0, msg); } "failed" => { - let msg = format!("Couldn't import {}: {}", front.name, front.error.clone().unwrap_or_default()); + let (name, why, batch) = (front.name.clone(), front.error.clone().unwrap_or_default(), front.batch); + let mut msg = format!("Couldn't import {name}: {why}"); + // Kept for the drop's last line, so a later file's commit keeps the reason. When + // this is the drop's last file, its own line goes on with the files left out up + // front and the drop's earlier failures, never a track (it may be gone by now). + let last = !app.imports.items.iter().skip(1).any(|i| i.batch == batch); + if let Some(b) = app.imports.batches.get_mut(&batch) { + if last && b.closed > 0 { + let s = if b.closed == 1 { "" } else { "s" }; + msg.push_str(&format!("; {} Maschine/Kontakt file{s} skipped: not supported", b.closed)); + } + if last && !b.refused.is_empty() { + msg.push_str(&format!("; {}", not_prepared(&b.refused, b.asked))); + } + b.refused.push((name, why)); + } app.drop_item(0, msg); } _ => break, diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index 3096261a..0e31793e 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -5,12 +5,17 @@ use super::test_rig::{T, mid}; use transit_model::TrackId; -/// A point on the arrangement's timeline that no editor window covers. +/// A point on the menu bar: no track, nor the space below the tracks, so a drop there lands at the +/// cursor. +const MENU_BAR: (f32, f32) = (300.0, 12.0); + +/// A point on the arrangement's timeline that no editor window covers, below the tracks (a drop +/// there lands on a new track; the Sampler's own instrument track takes no audio). fn arrangement_point(t: &T, tr: TrackId) -> (f32, f32) { let tl = t.app.arrange.layout.timeline; let w = t.window(tr).rect; let inside = |p: (f32, f32)| p.0 >= w[0] && p.0 <= w[2] && p.1 >= w[1] && p.1 <= w[3]; - let candidates = [(tl[0] + 40.0, tl[1] + 12.0), (tl[2] - 40.0, tl[1] + 12.0), (tl[0] + 40.0, tl[3] - 12.0), (tl[2] - 40.0, tl[3] - 12.0)]; + let candidates = [(tl[0] + 40.0, tl[3] - 12.0), (tl[2] - 40.0, tl[3] - 12.0)]; *candidates.iter().find(|p| !inside(**p) && tl[3] - tl[1] > 24.0).expect("a visible stretch of timeline outside the editor window") } @@ -110,8 +115,9 @@ fn a_drop_with_the_pointer_gone_then_a_position_on_the_arrangement_imports_a_cli let snare = t.sample("Snare.wav", 2400); let clips = t.clip_count(); t.drop_gone(&snare); - assert_eq!(t.clip_count(), clips, "held"); + assert!(t.clip_count() == clips && !t.app.imports.active(), "held"); t.point(arrangement_point(&t, tr)); + t.settle_imports(); assert_eq!(t.clip_count(), clips + 1, "one clip imported"); assert!(t.patch(tr).zones.is_empty(), "no pad bound"); } @@ -124,8 +130,10 @@ fn a_drop_held_after_the_pointer_left_goes_to_the_arrangement_after_the_grace_fr // The drop frame counts as the first held frame; the last held frame is the grace count. t.drop_gone(&snare); t.frames(crate::drops::GONE_GRACE_FRAMES as usize - 1); - assert_eq!(t.clip_count(), clips, "still held on the last grace frame"); + assert!(t.clip_count() == clips && !t.app.imports.active(), "still held on the last grace frame"); t.frames(1); + assert!(t.app.imports.active() || t.clip_count() == clips + 1, "routed on the next frame"); + t.settle_imports(); assert_eq!(t.clip_count(), clips + 1, "then imported to the arrangement: the drop never vanishes"); assert!(t.patch(tr).zones.is_empty()); } @@ -157,3 +165,291 @@ fn the_gone_rule_holds_where_the_old_rule_imported() { assert_eq!(placement(None, false, &mut count), Placement::Hold); } } + +/// A file-manager drop lands where it is let go, as a browser drag does: on the track under the +/// pointer, at the pointer's time on its lane, rather than at the cursor (on a new track when the +/// cursor has none). A stereo file keeps its channels there: a split is asked for, never done on +/// import, even with a free mono track below. +#[test] +fn a_stereo_file_dropped_on_a_mono_lane_lands_whole_on_that_track_at_the_pointer() { + let mut t = T::new(); + let mono = |t: &mut T| t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let (a, b) = (mono(&mut t), mono(&mut t)); + t.frames(3); + let mut wav = Vec::new(); + for v in [0x4646_4952u32, 36 + 4_800 * 4, 0x4556_4157, 0x2074_6d66, 16, 0x0002_0001, 48_000, 48_000 * 4, 0x0010_0004, 0x6174_6164, 4_800 * 4] { + wav.extend(v.to_le_bytes()); + } + for _ in 0..4_800 { + wav.extend([0x00, 0x40, 0x00, 0xe0]); // 0.5 left, -0.25 right + } + let path = t.dir.join("Mics.wav"); + std::fs::write(&path, wav).unwrap(); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + let at = (lane[0] + (lane[2] - lane[0]) * 0.75, (lane[1] + lane[3]) / 2.0); + let Some((crate::browser::Target::Track { at: Some(want), .. }, _)) = t.app.drop_target(&t.ctx, egui::pos2(at.0, at.1), true, true) else { + panic!("the lane is a drop target") + }; + assert!(want > 0 && t.app.cursor() == 0, "the pointer's time ({want}) is not the cursor's"); + t.drop_file(&path, at); + let s = t.app.engine.session(); + let on = |id: u64| s.track(TrackId(id)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect::>(); + assert_eq!(s.tracks.len(), 2, "no new track"); + assert_eq!((on(a), on(b)), (vec![("Mics".to_string(), want)], vec![]), "whole, on A, at the pointer"); + assert_eq!(s.sources.iter().map(|x| x.channels).collect::>(), [2], "one stereo source"); +} + +/// Several files dropped on a lane follow each other on its track, as a browser drag's do: each +/// lands where the one before ends, so none erases another. +#[test] +fn files_dropped_together_on_a_lane_follow_each_other_on_its_track() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 4_800)); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_files(vec![one, two], mid(lane)); + let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); + assert_eq!(clips.len(), 2, "both files are on the track: {clips:?}"); + assert_eq!(clips[1].1 - clips[0].1, 4_800, "Two starts where One ends: {clips:?}"); +} + +/// A drop holding a session opens it and imports nothing else: its other files would land by a +/// pointer or a cursor that still names the closing session's tracks (here the cursor is on the +/// track with the id of the new session's MIDI track). +#[test] +fn a_drop_that_opens_a_session_opens_it_and_imports_nothing_else() { + let mut t = T::new(); + let mut other = transit_engine::Engine::default(); + other.execute("track.new", &serde_json::json!({"kind": "audio", "name": "Drums"})).unwrap(); + let synth = other.execute("track.new", &serde_json::json!({"kind": "midi", "name": "Synth"})).unwrap()["tracks"][0].as_u64().unwrap(); + let b = t.dir.join("B.transit"); + other.execute("session.save", &serde_json::json!({"path": b.to_string_lossy()})).unwrap(); + for _ in 0..2 { + t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap(); + } + t.app.run("session.save", serde_json::json!({"path": t.dir.join("A.transit").to_string_lossy()})).unwrap(); + t.app.set_cursor(96_000, Some(TrackId(synth))); + t.frames(3); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == synth).expect("A has a track of Synth's id").lane; + let (one, two) = (t.sample("One.wav", 2_400), t.sample("Two.wav", 2_400)); + t.drop_files(vec![b, one, two], mid(lane)); + let s = t.app.engine.session(); + assert!(s.tracks.iter().any(|tr| tr.name == "Synth"), "B is open"); + assert!(s.tracks.iter().all(|tr| tr.clips().is_empty()), "nothing else is imported"); + assert!(t.app.status.contains("2 files dropped with B.transit were not imported"), "{}", t.app.status); +} + +/// Files dropped where no track or the space below them is (here the menu bar) land at the cursor +/// on the cursor's track, and follow each other there, rather than each erasing the last. +#[test] +fn files_dropped_at_the_cursor_follow_each_other_on_its_track() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.run("track.new", serde_json::json!({"kind": "midi"})).unwrap(); + t.app.set_cursor(48_000, Some(TrackId(a))); + t.frames(3); + let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 2_400)); + t.drop_files(vec![one, two], MENU_BAR); + let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); + assert_eq!(clips, [("One".to_string(), 48_000), ("Two".to_string(), 52_800)]); +} + +/// Audio dropped on a track that takes none (a MIDI track's lane) is refused with the reason on +/// the status line, as a browser drag's is, rather than landing somewhere else unannounced. +#[test] +fn audio_dropped_on_a_midi_lane_is_refused_with_the_reason() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let m = t.app.run("track.new", serde_json::json!({"kind": "midi", "name": "Synth"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.set_cursor(0, Some(TrackId(a))); + t.frames(3); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == m).unwrap().lane; + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, mid(lane)); + assert!(t.app.status.starts_with("Synth is not an audio track"), "{}", t.app.status); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); +} + +/// A dropped session goes through the save question File > Open asks: with unsaved changes it +/// opens only once the question is answered, and nothing else of the drop is imported. +#[test] +fn a_dropped_session_asks_to_save_unsaved_changes_first() { + let mut t = T::new(); + let b = t.dir.join("B.transit"); + let mut other = transit_engine::Engine::default(); + other.execute("track.new", &serde_json::json!({"kind": "midi", "name": "Synth"})).unwrap(); + other.execute("session.save", &serde_json::json!({"path": b.to_string_lossy()})).unwrap(); + t.app.run("track.new", serde_json::json!({"kind": "audio", "name": "Unsaved"})).unwrap(); + t.frames(3); + assert!(t.app.unsaved_changes()); + let one = t.sample("One.wav", 2_400); + t.drop_files(vec![b, one], MENU_BAR); + assert!(matches!(t.app.dialog, Some(crate::Dialog::SaveChanges { .. })), "the save question is up"); + let s = t.app.engine.session(); + assert!(s.tracks.iter().any(|tr| tr.name == "Unsaved") && s.tracks.iter().all(|tr| tr.clips().is_empty()), "nothing opened or imported yet"); +} + +/// With the cursor before bar 1 (a count-in session's pre-count zone), files dropped at the cursor +/// still follow each other: the first lands at 0, where the engine puts it, and the next after it. +#[test] +fn files_dropped_at_a_cursor_before_bar_one_follow_each_other_from_zero() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let m = t.app.run("track.new", serde_json::json!({"kind": "midi"})).unwrap()["tracks"][0].as_u64().unwrap(); + // A pickup clip at -96 000 opens the pre-count zone (ADR 0052), so the cursor can sit before 0. + let s = t.app.engine.session_mut(); + let id = s.new_clip_id(); + let pickup = transit_model::Clip::midi(id, "Pickup", -96_000, 48_000, Default::default()); + s.track_mut(TrackId(m)).unwrap().playlist_mut().unwrap().clips.push(pickup); + t.frames(3); + t.app.ui.cursor = -48_000; + t.app.ui.cursor_track = Some(TrackId(a)); + assert_eq!(t.app.cursor(), -48_000, "the cursor is before bar 1"); + let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 4_800)); + t.drop_files(vec![one, two], MENU_BAR); + let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); + assert_eq!(clips, [("One".to_string(), 0), ("Two".to_string(), 4_800)]); +} + +/// A dropped session that fails to open keeps its own reason on the status line: the line about +/// the files left out comes first, so the open's refusal replaces it. +#[test] +fn a_dropped_session_that_fails_to_open_shows_why() { + let mut t = T::new(); + let bad = t.dir.join("B.transit"); + std::fs::write(&bad, b"not a session").unwrap(); + let (one, two) = (t.sample("One.wav", 2_400), t.sample("Two.wav", 2_400)); + let tl = t.app.arrange.layout.timeline; + t.drop_files(vec![bad, one, two], (tl[0] + 40.0, tl[1] + 12.0)); + assert!(t.app.status.starts_with("Could not open"), "{}", t.app.status); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); +} + +/// Whether a dropped file is audio is the engine's call, as it was for every file-manager drop: +/// WAV data named `.rf64`, or with no extension at all, imports, though the browser lists neither. +#[test] +fn audio_the_engine_reads_imports_whatever_its_file_is_named() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let (rf64, bare) = (t.sample("Kick.rf64", 2_400), t.sample("Snare", 2_400)); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_files(vec![rf64, bare], mid(lane)); + let names: Vec = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| c.name.clone()).collect(); + assert_eq!(names, ["Kick", "Snare"], "{}", t.app.status); +} + +/// A file that is not audio, dropped with one that is, is named on the drop's last line with the +/// engine's reason (never as a Maschine/Kontakt file), though the audio after it commits later. +#[test] +fn a_file_that_is_not_audio_in_a_drop_is_named_with_its_reason() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let notes = t.dir.join("notes.txt"); + std::fs::write(¬es, b"not audio").unwrap(); + let kick = t.sample("Kick.wav", 2_400); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_files(vec![notes, kick], mid(lane)); + assert_eq!(t.app.engine.session().track(TrackId(a)).unwrap().clips().len(), 1, "Kick lands"); + let status = &t.app.status; + assert!(status.contains("notes.txt (") && !status.contains("Maschine"), "{status}"); +} + +/// A drop at the cursor lands on the cursor's track, as it did before drops followed the pointer, +/// even when an earlier import left the focus on another audio track. +#[test] +fn a_drop_at_the_cursor_lands_on_the_cursors_track_not_the_focused_one() { + let mut t = T::new(); + let new = |t: &mut T| t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let (a, b) = (new(&mut t), new(&mut t)); + t.app.set_cursor(48_000, Some(TrackId(a))); + t.app.ui.focus_track = Some(TrackId(b)); + t.frames(3); + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, MENU_BAR); + let on = |id: u64| t.app.engine.session().track(TrackId(id)).unwrap().clips().iter().map(|c| c.start).collect::>(); + assert_eq!((on(a), on(b)), (vec![48_000], vec![]), "{}", t.app.status); +} + +/// When the last file of a drop fails too, the drop's last line gives that failure's own reason, +/// then the Maschine/Kontakt files left out, then the drop's earlier failures with the first +/// reason, each its own part; a lone failure keeps its own line. +#[test] +fn a_drop_whose_last_file_fails_names_every_failure() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let lane = mid(t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane); + let text = |t: &T, name: &str| { + let p = t.dir.join(name); + std::fs::write(&p, b"not audio").unwrap(); + p + }; + let (x, y) = (text(&t, "a.txt"), text(&t, "b.txt")); + t.drop_files(vec![x, y], lane); + let why = "unsupported audio"; + let status = t.app.status.clone(); + assert!( + status.starts_with("Couldn't import b.txt: b.txt: unsupported audio") + && status.contains("; 1 of 2 could not be prepared: a.txt (a.txt: unsupported audio"), + "{status}" + ); + let (bad, kick, notes, kit) = (text(&t, "Bad.wav"), t.sample("Kick.wav", 2_400), text(&t, "notes.txt"), text(&t, "Kit.nki")); + t.drop_files(vec![bad, kick, notes, kit], lane); + let status = &t.app.status; + let parts: Vec<&str> = status.split("; ").collect(); + assert!(parts.len() == 3 && parts[0].starts_with("Couldn't import notes.txt: ") && parts[0].contains(why), "{status}"); + assert_eq!(parts[1], "1 Maschine/Kontakt file skipped: not supported", "{status}"); + assert!(parts[2].starts_with("1 of 3 could not be prepared: Bad.wav (") && parts[2].contains(why), "{status}"); + let lone = text(&t, "c.txt"); + t.drop_files(vec![lone], lane); + assert!(t.app.status.starts_with("Couldn't import c.txt: "), "{}", t.app.status); +} + +/// A drop on a track deleted since the frame it was seen in says so, rather than importing nothing +/// unannounced. +#[test] +fn a_drop_on_a_deleted_track_says_so() { + let mut t = T::new(); + let one = t.sample("One.wav", 2_400); + let r = t.app.import_files(&[one], Some(TrackId(9_999)), 0); + assert!(r.is_err() && t.app.status == "The track was deleted: drop the files again", "{}", t.app.status); + assert!(!t.app.imports.active()); +} + +/// The mixer's Main strip with no Master track is the main bus, no track: a file dropped there +/// lands at the cursor, as anywhere else no track is, never refused as a deleted track. +#[test] +fn a_drop_on_the_main_strip_with_no_master_track_lands_at_the_cursor() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.set_cursor(48_000, Some(TrackId(a))); + t.app.ui.show_mixer = true; + t.frames(3); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.kind != transit_model::TrackKind::Master)); + let main = t.app.mixer.layout.master.clone().expect("the Main strip is drawn"); + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, mid(main.rect)); + let starts: Vec = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| c.start).collect(); + assert_eq!(starts, [48_000], "{}", t.app.status); +} + +/// A real Master track's strip is still a drop target, refused for audio with the reason (only the +/// main bus with no Master track is no target). +#[test] +fn audio_dropped_on_a_master_tracks_strip_is_refused_with_the_reason() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.run("track.new", serde_json::json!({"kind": "master"})).unwrap(); + t.app.set_cursor(0, Some(TrackId(a))); + t.app.ui.show_mixer = true; + t.frames(3); + let master = t.app.mixer.layout.master.clone().expect("the Master strip is drawn"); + assert_ne!(master.track, 0, "a Master track's own strip"); + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, mid(master.rect)); + assert!(t.app.status.contains("is not an audio track"), "{}", t.app.status); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); +} diff --git a/crates/ui-studio/src/sampler_panel/test_rig.rs b/crates/ui-studio/src/sampler_panel/test_rig.rs index 918c3b30..2c0f6f2b 100644 --- a/crates/ui-studio/src/sampler_panel/test_rig.rs +++ b/crates/ui-studio/src/sampler_panel/test_rig.rs @@ -161,8 +161,25 @@ impl T { /// Drops `path` at `at` (the next frame sees it), then runs a few frames. pub fn drop_file(&mut self, path: &Path, at: (f32, f32)) { - self.drop = Some((vec![path.to_path_buf()], Some(egui::pos2(at.0, at.1)))); + self.drop_files(vec![path.to_path_buf()], at); + } + + /// Drops `paths` together at `at`, as [`T::drop_file`] drops one, then lets the arrangement's + /// queued imports land. + pub fn drop_files(&mut self, paths: Vec, at: (f32, f32)) { + self.drop = Some((paths, Some(egui::pos2(at.0, at.1)))); self.frames(3); + self.settle_imports(); + } + + /// Runs frames until the arrangement's queued imports are committed (or 10 s). + pub fn settle_imports(&mut self) { + let t0 = std::time::Instant::now(); + while self.app.imports.active() && t0.elapsed().as_secs() < 10 { + self.frames(6); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(!self.app.imports.active(), "imports never finished: {}", self.app.status); } /// Drops `path` with no pointer motion in the drop's frame (egui's pointer stays where it last diff --git a/docs/known-issues/README.md b/docs/known-issues/README.md index e349d4da..dbc3a2c7 100644 --- a/docs/known-issues/README.md +++ b/docs/known-issues/README.md @@ -101,7 +101,7 @@ existed keep their K numbers and their historical order. | K110 | The Sampler's core path (#269, C2) holds every zone's audio in memory: a sample longer than 30 s or 32 MiB of decoded audio, or one over the session's streaming threshold, is refused for a zone, and a patch holds at most 128 MiB of distinct audio. Its zone controls (`zone001_level`, ...) are not automatable yet. | Open, by design until #271 | Long samples stream from disk in #271 (ADR 0041); slot automation needs the lanes to learn the 28,928 slot ids. | | K111 | On Windows a device that only the old cpal WASAPI path could open no longer opens: since ADR 0046 Windows opens audio through native WASAPI or native ASIO only, and a device that does not open stays closed with the reason. None is known: cpal's Windows host was WASAPI alone, and the slice 2 test found the native backend lists the same endpoints. | Open, none observed | On a report: paste the "did not open" status and the report from Copy diagnostics, and reopen ADR 0046 (its Reopen when). A v0.6.x release still has the cpal path for comparison. | | K112 | Opus export is mono and stereo only (#238): a surround main mix, bus or output path exported as Opus is refused with "transit writes mono and stereo Opus only; fold the export down to stereo, or export WAV or FLAC". Surround Opus needs channel mapping family 1 (Vorbis channel order) and libopus's multistream encoder; the import side reads mono and stereo Opus files and refuses other mapping families the same way. | Open, by design for #238 | Fold down to stereo (`fold_down: "stereo"` on `file.bounce_mix` and `file.bounce_stems`) or export WAV/FLAC. Family 1 for 3 to 8 channels is Rust only: the multistream and projection encoders are already compiled in `crates/opus`, so the follow-up is the OpusHead mapping table, the SMPTE-to-Vorbis reorder and a multistream handle in `ffi.rs` (ADR 0048 decision 3). | -| K113 | A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). | Open, dependency | Use the drop's own position once winit's drag events carry one (`DragDropped { position }` in winit's next release) and egui-winit forwards it. | +| K113 | A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). That position also picks where an arrangement drop lands (the track under the pointer, at its time, as a browser drag), so a pointer moved before its next report imports the file onto the track it reached, or is refused there when that track takes no audio. | Open, dependency | Use the drop's own position once winit's drag events carry one (`DragDropped { position }` in winit's next release) and egui-winit forwards it. | | K114 | Upgrading to v0.7.0 rescans every plug-in once: the plug-in scan cache now lives only in transit's own settings folder, and the cache in the inherited app's `SoundCraft` folder under the user's config root (`%APPDATA%\SoundCraft`, `~/Library/Application Support/SoundCraft`, `~/.config/soundcraft`) is no longer read or written. | Open, by design (alpha) | None in code. That folder can be deleted by hand once no other program uses it. | | K115 | Clip group files tagged `soundcraft.clipgroup` and track presets tagged `soundcraft-track-preset` (written before v0.7.0) read in v0.7.x only. v0.7.x reads them, tells the caller once per read (the status line and the command result's `note`: ": saved before transit 0.7.0; ... to keep it opening in 0.8.0 and later"), and writes `transit.clipgroup` (`.tclips`) and `transit-track-preset` (`.tpreset`); from the **v0.8.0 tag** they are refused with "This file was saved by a version before transit 0.7.0. Open and save it in transit 0.7.0 first: https://github.com/transit-audio/transit/releases/tag/v0.7.0" ([ADR 0049](../adr/0049-inherited-file-identifiers-retire.md)). Files written by v0.7.0 do not open in v0.6.x. On Linux the session MIME type is now `application/x-transit-session`, so a hand-set per-user default app for `.transit` files is set once more. | Open, by design (alpha); the old tags are refused from the v0.8.0 tag | Convert in any 0.7 release: import each clip group and export the clips again (`file.export_clip_groups`); load each preset and save it again (`track.save_preset`). The v0.8.0 release moves the old tags from the readers' accept checks to the refusal; a version-gated test in `transit-engine` fails a 0.8 version bump that skips it. K114 comes from #374; renumber at landing if the order changes. | | K116 | macOS: a CLAP editor opens in the same `NSWindow` the VST3 host uses, and that window has no header strip (presets, Save, Bypass, the menu and MIDI Learn: use the device card and the mixer), is not user-resizable, and follows the plug-in's own resize requests only (as on Linux, K94). | Open, macOS CLAP editors have no header strip | A macOS header strip needs AppKit drawing in `transit-rt`. `crates/clap-host/tests/editor_main_thread.rs` expects the embedded editor on macOS. | diff --git a/docs/known-issues/entries/K113.md b/docs/known-issues/entries/K113.md index a8890443..d2d02a2f 100644 --- a/docs/known-issues/entries/K113.md +++ b/docs/known-issues/entries/K113.md @@ -4,4 +4,4 @@ follow-up: Use the drop's own position once winit's drag events carry one (`Drag order: 119 --> -A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). +A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). That position also picks where an arrangement drop lands (the track under the pointer, at its time, as a browser drag), so a pointer moved before its next report imports the file onto the track it reached, or is refused there when that track takes no audio. diff --git a/docs/user-guide.md b/docs/user-guide.md index 87ca2883..527698c1 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -920,10 +920,23 @@ slot), in one undo step, with the dashed well outlined while you hold it there; view has content it takes no drag. On an Instrument key map with zones, a file dragged over keys no zone plays shows, dashed, the keys it will cover, and letting go makes a zone there (see below). A file or plug-in dropped elsewhere on a device window is ignored; the window takes the drop, so nothing behind it is reached. Anywhere else, a browser drag lands on the track lane, -header, mixer strip or device chain where you let go, and a file from the file manager is imported -into the arrangement at the cursor (a `.transit` or `.dawproject` file opens as the session, a MIDI -file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other -platforms it lands as soon as the pointer moves after you let go (see the known issues). +header, mixer strip or device chain where you let go. A file from the file manager lands the same +way: on the track under the pointer (at the pointer's time on its lane) or below the tracks on a +new track, several files one after another, and anywhere else at the cursor (a MIDI file imports +as MIDI). A track that takes no audio, or a file that is not audio transit imports, is refused +with the reason on the status line. A file keeps its channels: a stereo file dropped on a mono +track lands there as one stereo clip. A `.transit` or `.dawproject` file opens as the session, +asking first to save unsaved changes as File > Open does; dropped with other files, it opens alone +and the status line says how many were left out. On Windows a file manager drop lands where the pointer +is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see +the known issues). + +To split a stereo or wider clip into mono tracks, such as two microphones recorded onto one stereo +track, right-click it and choose **Split to Mono Tracks**: each channel goes to a new mono track +below the clip's track (` L` and ` R`, numbered past stereo), with the clip's +timing, fades and gain, the original clip is muted, and the whole split is one undo step. Each +channel becomes its own mono file, saved to `Audio Files`; a take played from its file gets one +mono WAV per channel beside it. Right-click a pad and choose **Clear pad** to empty it and reset its name, choke group, mute, and solo. Delete or Backspace does the same for the selected pad while the Sampler window has