diff --git a/Cargo.lock b/Cargo.lock index faf1dee1..89a66063 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1140,6 +1140,7 @@ dependencies = [ "dstudio-core", "dstudio-engine", "flate2", + "mp3lame-encoder", "objc2 0.6.5", "objc2-foundation 0.3.2", "png", @@ -2792,6 +2793,24 @@ dependencies = [ "pxfm", ] +[[package]] +name = "mp3lame-encoder" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a768064bbfe7e0853bda4d0fd9c2ee65e4642f9a4d085265a2a12702a8d30f78" +dependencies = [ + "mp3lame-sys", +] + +[[package]] +name = "mp3lame-sys" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a01c8bcc75d256a40b8e3c8dfefbbebe704eef1615cab5025bf362ba2a55f0c0" +dependencies = [ + "cc", +] + [[package]] name = "muda" version = "0.19.3" diff --git a/PROGRESS.md b/PROGRESS.md index dbcdb436..4c15d6f6 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -591,3 +591,14 @@ The source texture and exact generation prompt live in `docs/art/textures/`; the uses it at lower strength behind feature and architecture cards. App source, screenshots, installation identities and settings are unchanged. The website uses compressed versions of the same material in its own repository. + +### 2026-11-14: export to MP3 + +- The Export dialog's Format segments now pick WAV or MP3 for Mixdown and Stems. With MP3 the second segments pick the + bitrate (192 or 320 kbps, 320 by default) in place of the bit depth; the sample rate and range choices work as for + WAV, the Name field ends in ".mp3", and the size estimate follows the bitrate. A Project export (Live set) stays WAV. +- `src/mp3.rs`: constant-bitrate joint stereo through LAME (`mp3lame-encoder` 0.3.0, LAME built from source by + `mp3lame-sys`, LGPL), quality setting 2, with LAME's Info tag in the first frame so decoders trim the encoder delay + and padding and the file has exactly the rendered length. +- Tests: `mp3::tests` encodes one second of a sine at both bitrates and reads it back through the engine's MP3 + decoder (same frame count, peak within 0.05 of the source, size within 5 % of the estimate). diff --git a/README.md b/README.md index fe693d74..540cedda 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,8 @@ wgpu. power switch and choose Automate. Draw lanes with points, curves or freehand, or record your moves with touch-write. Lanes read in the parameter's own units (Hz, dB, ms, choice names, On/Off), and mute, mono and device on/off lanes switch exactly on their points. -- **Export.** Mix down the arrangement, or export each track as its own stem, as 16- or 24-bit WAV at 44.1 or 48 kHz - (converted from the engine's rate), over the whole project or just the loop region (an exact-length file that loops +- **Export.** Mix down the arrangement, or export each track as its own stem, as 16- or 24-bit WAV or 192 or 320 kbps + MP3 at 44.1 or 48 kHz (converted from the engine's rate), over the whole project or just the loop region (an exact-length file that loops seamlessly), or export the project as an Ableton Live set that keeps its return tracks and sends. - **Undo for everything.** Every edit is a validated, invertible command, so undo and redo cover the whole project. - **Assistant.** An optional side panel that can explain the app (Teach) or make edits for you (Assist), each turn as @@ -163,7 +163,7 @@ decisions behind rendering, recording, plugins, delay compensation and automatio | Mixer | ✅ | | | Automation | ✅ | | | Delay compensation | ✅ | | -| Export | 🚧 | MP3 | +| Export | ✅ | | | Assistant | 🚧 | Tested only with a fixture provider, not yet against the live API | | Windows and Linux audio | 🚧 | Linux streams run in CI on a headless PipeWire server; neither has run on a physical sound card; no ASIO | | Releases and branding | 🚧 | Packages are built (unsigned); code signing, original icons, a first tagged release | @@ -293,6 +293,7 @@ network, you must offer them the modified source too. Third-party code keeps its own license. The engine's dependencies, the VST3 SDK, CLAP headers and Signalsmith libraries (MIT), dr_libs (public domain or MIT-0) and stb_vorbis (public domain or MIT), are fetched at build time and listed in -[engine/third_party_licenses.md](engine/third_party_licenses.md). The app uses Slint under its +[engine/third_party_licenses.md](engine/third_party_licenses.md). MP3 export uses the LAME encoder (LGPL), built from +source by the `mp3lame-sys` crate and listed there too. The app uses Slint under its [GPL-3.0 licence](https://github.com/slint-ui/slint/blob/master/LICENSE.md) (compatible with the AGPL), and the bundled Inter font is under the SIL Open Font License. diff --git a/crates/dstudio-app/Cargo.toml b/crates/dstudio-app/Cargo.toml index 6d7fced0..3bff7dd5 100644 --- a/crates/dstudio-app/Cargo.toml +++ b/crates/dstudio-app/Cargo.toml @@ -35,6 +35,8 @@ flate2 = "1.1" # Already in the tree; local date and time for Edit › Undo History. chrono = { version = "0.4.45", default-features = false, features = ["clock"] } roxmltree = "0.21" +# MP3 export: LAME (LGPL), built from source; see engine/third_party_licenses.md. +mp3lame-encoder = "=0.3.0" serde_json.workspace = true serde.workspace = true diff --git a/crates/dstudio-app/src/clip_render.rs b/crates/dstudio-app/src/clip_render.rs index dcd56953..2998ee99 100644 --- a/crates/dstudio-app/src/clip_render.rs +++ b/crates/dstudio-app/src/clip_render.rs @@ -165,7 +165,7 @@ fn write_render( let (path, target, bits) = match out { Output::New { dir, stem } => { std::fs::create_dir_all(dir).map_err(|e| failed(dir, e.to_string()))?; - let (path, _) = create_free_file(dir, stem).map_err(|e| failed(dir, e))?; + let (path, _) = create_free_file(dir, stem, "wav").map_err(|e| failed(dir, e))?; (path.clone(), path, 24) } Output::Export { path, bits } => { diff --git a/crates/dstudio-app/src/dialogs.rs b/crates/dstudio-app/src/dialogs.rs index a181f1a8..9e6b3c11 100644 --- a/crates/dstudio-app/src/dialogs.rs +++ b/crates/dstudio-app/src/dialogs.rs @@ -1,4 +1,4 @@ -//! Export dialog (mixdown or stems to WAV) and the unsaved-changes prompt shown before +//! Export dialog (mixdown or stems to WAV or MP3) and the unsaved-changes prompt shown before //! File › New Project. DStudio renders with the engine's offline //! render at the engine sample rate. A stem is one track played alone: DStudio has no //! returns, groups or master devices, so that is the post-effects track @@ -63,10 +63,13 @@ pub struct ExportUi { pub range: ExportRange, pub range_menu: bool, pub bits24: bool, + /// Mixdown and Stems write MP3 (at `kbps`) instead of WAV. + pub mp3: bool, + pub kbps: u32, /// The file's sample rate as picked in the dialog (44.1 or 48 kHz); None until then, which /// means the one nearest the engine's. pub rate: Option, - /// The Name field: ".wav" when one file is written, the stems folder base otherwise. + /// The Name field: ".wav" (or ".mp3") when one file is written, the stems folder base otherwise. pub name: String, pub dir: PathBuf, /// The name the dialog filled in; while the field still holds it, picking one track @@ -86,6 +89,8 @@ impl Default for ExportUi { range: ExportRange::Project, range_menu: false, bits24: true, + mp3: false, + kbps: crate::mp3::BITRATES[1], rate: None, name: "Untitled.wav".into(), dir: home.join("Music").join("DStudio Exports"), @@ -101,18 +106,64 @@ impl ExportUi { self.recipe == Recipe::Stems && !matches!(self.stems, StemsPick::Track(_)) } - /// The Name field without a ".wav" ending, trimmed, with characters a file name can't hold - /// replaced. + /// What Mixdown and Stems write. + pub fn format(&self) -> FileFormat { + if self.mp3 { FileFormat::Mp3 { kbps: self.kbps } } else { FileFormat::Wav { bits: if self.bits24 { 24 } else { 16 } } } + } + + /// The Name field without a ".wav" or ".mp3" ending, trimmed, with characters a file name + /// can't hold replaced. pub fn base_name(&self) -> String { let n = self.name.trim(); - let n = if n.to_lowercase().ends_with(".wav") { &n[..n.len() - 4] } else { n }; + let lower = n.to_lowercase(); + let n = if lower.ends_with(".wav") || lower.ends_with(".mp3") { &n[..n.len() - 4] } else { n }; file_safe(n, usize::MAX) } fn normalize_name(&mut self) { let base = self.base_name(); if !base.is_empty() { - self.name = if self.writes_folder() || self.recipe == Recipe::Project { base } else { format!("{base}.wav") }; + self.name = + if self.writes_folder() || self.recipe == Recipe::Project { base } else { format!("{base}.{}", self.format().ext()) }; + } + } +} + +/// The file type and its one setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileFormat { + Wav { bits: u16 }, + Mp3 { kbps: u32 }, +} + +impl FileFormat { + pub fn ext(self) -> &'static str { + match self { + FileFormat::Wav { .. } => "wav", + FileFormat::Mp3 { .. } => "mp3", + } + } + + /// "WAV 24-bit", "MP3 320 kbps". + pub fn label(self) -> String { + match self { + FileFormat::Wav { bits } => format!("WAV {bits}-bit"), + FileFormat::Mp3 { kbps } => format!("MP3 {kbps} kbps"), + } + } + + /// Bytes of one stereo file of `frames` at `rate` Hz. + pub fn bytes(self, frames: u64, rate: f64) -> f64 { + match self { + FileFormat::Wav { bits } => frames as f64 * 2.0 * (bits / 8) as f64, + FileFormat::Mp3 { kbps } => crate::mp3::estimate_bytes(frames, rate, kbps), + } + } + + fn write(self, file: std::fs::File, rate: u32, samples: &[f32]) -> std::io::Result<()> { + match self { + FileFormat::Wav { bits } => wavgen::encode_wav_pcm(file, rate, 2, bits, samples), + FileFormat::Mp3 { kbps } => crate::mp3::encode_mp3(file, rate, kbps, samples), } } } @@ -203,16 +254,22 @@ pub(crate) fn stem_snapshot(mix: &dstudio_core::snapshot::SessionSnapshot, id: T /// "3.7 MB • 0:14" for "files" stereo PCM files of "frames" each at "bits". pub fn estimate_text(frames: u64, rate: f64, bits: u32, files: usize) -> String { - let mb = files as f64 * frames as f64 * 2.0 * (bits / 8) as f64 / 1e6; + format_estimate_text(frames, rate, FileFormat::Wav { bits: bits as u16 }, files) +} + +/// "3.7 MB • 0:14" for "files" stereo files of "frames" each in `format`. +pub fn format_estimate_text(frames: u64, rate: f64, format: FileFormat, files: usize) -> String { + let mb = files as f64 * format.bytes(frames, rate) / 1e6; let secs = (frames as f64 / rate).round() as u64; format!("{mb:.1} MB • {}:{:02}", secs / 60, secs % 60) } -/// Opens "dir/.wav", or " 2.wav", " 3.wav", … when taken; never an existing file. -pub(crate) fn create_free_file(dir: &Path, stem: &str) -> Result<(PathBuf, std::fs::File), String> { +/// Opens "dir/.", or " 2.", " 3.", … when taken; never an +/// existing file. +pub(crate) fn create_free_file(dir: &Path, stem: &str, ext: &str) -> Result<(PathBuf, std::fs::File), String> { (1..1000) .find_map(|n| { - let path = dir.join(if n == 1 { format!("{stem}.wav") } else { format!("{stem} {n}.wav") }); + let path = dir.join(if n == 1 { format!("{stem}.{ext}") } else { format!("{stem} {n}.{ext}") }); match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) { Ok(f) => Some(Ok((path, f))), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => None, @@ -429,6 +486,19 @@ impl Controller { self.ui_dirty = true; } + /// The Format segments: WAV or MP3 (the Name field's ending follows). + pub fn export_set_mp3(&mut self, mp3: bool) { + self.export.mp3 = mp3; + self.export.normalize_name(); + self.ui_dirty = true; + } + + /// The bitrate segments shown for MP3: the higher (320 kbps) or the lower (192 kbps). + pub fn export_set_kbps(&mut self, high: bool) { + self.export.kbps = crate::mp3::BITRATES[usize::from(high)]; + self.ui_dirty = true; + } + pub fn export_set_name(&mut self, name: &str) { self.export.name = name.to_string(); self.ui_dirty = true; @@ -446,7 +516,7 @@ impl Controller { let base = self.export.base_name(); let base = if base.is_empty() { "Untitled".to_string() } else { base }; let result = match self.export.recipe { - Recipe::Mixdown => self.export_plan(&self.export.dir.clone(), &[(None, base)], self.export_rate()), + Recipe::Mixdown => self.export_plan(&self.export.dir.clone(), &[(None, base)], self.export_rate(), self.export.format()), Recipe::Stems => { let tracks = self.export_stem_tracks(); if tracks.is_empty() { @@ -466,9 +536,9 @@ impl Controller { }) .collect(); free_folder(&self.export.dir, &format!("{base} Stems")) - .and_then(|dir| self.export_plan(&dir, &names, self.export_rate())) + .and_then(|dir| self.export_plan(&dir, &names, self.export_rate(), self.export.format())) } else { - self.export_plan(&self.export.dir.clone(), &[(Some(tracks[0]), base)], self.export_rate()) + self.export_plan(&self.export.dir.clone(), &[(Some(tracks[0]), base)], self.export_rate(), self.export.format()) } } Recipe::Project => self.export_project(&base), @@ -532,7 +602,8 @@ impl Controller { rendered.iter().map(|(id, f)| (Some(*id), f.trim_end_matches(".wav").to_string())).collect(); // The set records the renders' length and rate as the engine made them. let rate = self.engine.sample_rate().round() as u32; - self.export_plan(&folder.join(RENDERS), &files, rate)?.1 + let bits = if self.export.bits24 { 24 } else { 16 }; + self.export_plan(&folder.join(RENDERS), &files, rate, FileFormat::Wav { bits })?.1 }; let p = self.project(); let rate = self.engine.sample_rate(); @@ -737,19 +808,22 @@ impl Controller { dir: &Path, files: &[(Option, String)], rate: u32, + format: FileFormat, ) -> Result<(Vec, Result<(), String>), String> { let (start, frames) = self.export_span(); let frames = frames as usize; let engine_rate = self.engine.sample_rate().round() as u32; let resampler = Resampler::new(engine_rate, rate).ok_or_else(|| format!("can't convert {engine_rate} Hz to {rate} Hz"))?; // WAV sizes are 32-bit: refuse before rendering rather than after. - if resampler.out_frames(frames) as u64 * 2 * if self.export.bits24 { 3 } else { 2 } > (u32::MAX - 36) as u64 { + if let FileFormat::Wav { bits } = format + && resampler.out_frames(frames) as u64 * 2 * (bits / 8) as u64 > (u32::MAX - 36) as u64 + { return Err("too long for a WAV file (4 GB limit)".into()); } std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; let mut passes = Vec::with_capacity(files.len()); for (track, stem) in files { - match create_free_file(dir, stem) { + match create_free_file(dir, stem, format.ext()) { Ok((path, file)) => passes.push(Pass { track: *track, path, file }), Err(e) => { for p in &passes { @@ -760,7 +834,7 @@ impl Controller { } } let paths: Vec = passes.iter().map(|p| p.path.clone()).collect(); - let (written, restarted) = self.render_passes(passes, start, frames, rate, &resampler); + let (written, restarted) = self.render_passes(passes, start, frames, rate, &resampler, format); match (written, restarted) { (Ok(()), restarted) => Ok((paths, restarted)), (Err(e), restarted) => { @@ -776,7 +850,7 @@ impl Controller { } /// Plays `frames` of the arrangement from engine frame `start` once per pass (no loop, no - /// click) and writes it as stereo PCM at `out_rate` Hz, converted by `resampler` when the + /// click) and writes it as a stereo `format` file at `out_rate` Hz, converted by `resampler` when the /// engine runs at another rate. The audio device is paused for the renders; transport, mutes /// and the device are restored afterwards. fn render_passes( @@ -786,9 +860,9 @@ impl Controller { frames: usize, out_rate: u32, resampler: &Resampler, + format: FileFormat, ) -> (Result<(), String>, Result<(), String>) { let rate = self.engine.sample_rate(); - let bits = if self.export.bits24 { 24 } else { 16 }; let restore = self.project().ticks_to_frames(self.playhead_ticks(), rate); let solo_passes = passes.iter().any(|p| p.track.is_some()); let e = self.engine.clone(); @@ -816,7 +890,7 @@ impl Controller { } e.stop().map_err(|e| e.to_string())?; let converted = resampler.process(&out, 2); - wavgen::encode_wav_pcm(pass.file, out_rate, 2, bits, &converted).map_err(|e| e.to_string())?; + format.write(pass.file, out_rate, &converted).map_err(|e| e.to_string())?; } Ok::<(), String>(()) })(); @@ -936,8 +1010,12 @@ impl Controller { if !self.export.open { return; } - let bits = if self.export.bits24 { 24 } else { 16 }; - // Project renders stay at the engine rate; Mixdown and Stems use the picked one. + // Project renders stay at the engine rate and WAV; Mixdown and Stems use the picked ones. + let format = if self.export.recipe == Recipe::Project { + FileFormat::Wav { bits: if self.export.bits24 { 24 } else { 16 } } + } else { + self.export.format() + }; let (frames, rate) = if self.export.recipe == Recipe::Project { (self.export_frames(), self.engine.sample_rate()) } else { @@ -953,9 +1031,12 @@ impl Controller { }); s.set_export_bits24(self.export.bits24); s.set_export_rate48(self.export_rate() == 48_000); - s.set_export_recipe_text(format!("WAV {bits}-bit").into()); + s.set_export_mp3(self.export.mp3); + s.set_export_kbps_high(self.export.kbps == crate::mp3::BITRATES[1]); + s.set_export_recipe_text(self.export.format().label().into()); let plural = if files == 1 { "file" } else { "files" }; - s.set_export_stems_text(format!("{files} WAV {plural}").into()); + let kind = if self.export.mp3 { "MP3" } else { "WAV" }; + s.set_export_stems_text(format!("{files} {kind} {plural}").into()); s.set_export_files_text(format!("{files} {plural}").into()); let range = self.export_range(); s.set_export_bars_text(range_bars_text(p, range).into()); @@ -984,7 +1065,7 @@ impl Controller { s.set_export_name(self.export.name.clone().into()); s.set_export_name_label(if self.export.writes_folder() { "Folder" } else { "Name" }.into()); s.set_export_dir(self.export.dir.display().to_string().into()); - s.set_export_estimate(estimate_text(frames, rate, bits, if stems { files } else { 1 }).into()); + s.set_export_estimate(format_estimate_text(frames, rate, format, if stems { files } else { 1 }).into()); let tracks_label = match self.export.stems { StemsPick::AllTracks => "All individual tracks".to_string(), StemsPick::Selected => "Selected tracks only".to_string(), @@ -1092,6 +1173,32 @@ mod tests { assert_eq!(c.export_rate(), 48_000); } + #[test] + fn a_mixdown_exports_as_mp3_with_the_picked_rate_and_length() { + let engine = std::sync::Arc::new(dstudio_engine::Engine::new(dstudio_engine::Config::default()).unwrap()); + let mut c = Controller::new(engine, Project::default()); + let dir = std::env::temp_dir().join(format!("dstudio-mp3-export-{}", std::process::id())); + c.export_open(); + c.export_set_dir(dir.clone()); + c.export_set_mp3(true); + assert_eq!((c.export.name.as_str(), c.export.format()), ("Untitled.mp3", FileFormat::Mp3 { kbps: 320 })); + c.export_set_kbps(false); + assert_eq!(c.export.format().label(), "MP3 192 kbps"); + c.export_set_rate(false); + let frames = c.export_out_frames(); + c.export_run(); + let path = dir.join("Untitled.mp3"); + let info = c.engine.load_file(&path); + let _ = std::fs::remove_dir_all(&dir); + let info = info.unwrap_or_else(|e| panic!("{e:?}; status {:?}", c.status_message())); + assert_eq!(info.source_sample_rate.round() as u32, 44_100); + // Loaded at the engine rate: the 44.1 kHz frames converted back. + let back = (info.frames as f64 * 44_100.0 / c.engine.sample_rate()).round() as u64; + assert!(back.abs_diff(frames) <= 1, "{back} frames back, {frames} written"); + c.export_set_mp3(false); + assert_eq!(c.export.name, "Untitled.wav", "the ending follows the format"); + } + #[test] fn overlapping_midi_clips_get_their_own_lanes() { use dstudio_core::MidiClip; diff --git a/crates/dstudio-app/src/main.rs b/crates/dstudio-app/src/main.rs index 6ff4d2c3..b5eaa3d1 100644 --- a/crates/dstudio-app/src/main.rs +++ b/crates/dstudio-app/src/main.rs @@ -57,6 +57,7 @@ mod live_set; mod midi_in; mod minimap; mod mixer; +mod mp3; mod panel_fields; mod panel_graph; mod panel_multiband; @@ -426,6 +427,10 @@ fn parse_args() -> Result { a.reference_default = true; a.dialog_state = 9; } + "review-export-mp3" => { + a.reference_default = true; + a.dialog_state = 10; + } "review-undo-history" => { a.reference_default = true; a.dialog_state = 7; @@ -2173,6 +2178,8 @@ fn run() -> Result<(), Box> { on!(on_export_run, |c| c.export_run()); on!(on_export_bits, |c, b: bool| c.export_set_bits(b)); on!(on_export_rate, |c, b: bool| c.export_set_rate(b)); + on!(on_export_format, |c, b: bool| c.export_set_mp3(b)); + on!(on_export_kbps, |c, b: bool| c.export_set_kbps(b)); on!(on_export_pick_recipe, |c, i: i32| c.export_pick_recipe(i)); on!(on_export_toggle_tracks, |c| c.export_toggle_tracks_menu()); on!(on_export_toggle_range, |c| c.export_toggle_range_menu()); @@ -2985,6 +2992,9 @@ fn run() -> Result<(), Box> { if state == 8 { c.export_set_rate(false); } + if state == 10 { + c.export_set_mp3(true); + } if state == 9 { let tpb = c.project().ticks_per_bar(); let _ = c.doc.execute( diff --git a/crates/dstudio-app/src/mp3.rs b/crates/dstudio-app/src/mp3.rs new file mode 100644 index 00000000..3b1a91b7 --- /dev/null +++ b/crates/dstudio-app/src/mp3.rs @@ -0,0 +1,114 @@ +//! MP3 writer for Export (Mixdown and Stems): constant bitrate stereo, encoded with LAME +//! (libmp3lame, LGPL; built from source by the `mp3lame-sys` crate). The first frame is LAME's +//! "Info" tag, which records the encoder delay and padding so players and decoders give back +//! exactly the frames that were rendered (gapless). + +use mp3lame_encoder::{Bitrate, Builder, FlushGap, InterleavedPcm, Mode, Quality}; +use std::io::Write; + +/// The bitrates the Export dialog offers, in kbps. +pub const BITRATES: [u32; 2] = [192, 320]; +/// Frames handed to LAME per call (a multiple of the 1152-frame MP3 frame). +const CHUNK: usize = 1152 * 32; + +fn bitrate(kbps: u32) -> Option { + Some(match kbps { + 128 => Bitrate::Kbps128, + 160 => Bitrate::Kbps160, + 192 => Bitrate::Kbps192, + 224 => Bitrate::Kbps224, + 256 => Bitrate::Kbps256, + 320 => Bitrate::Kbps320, + _ => return None, + }) +} + +fn err(what: &str, e: impl std::fmt::Debug) -> std::io::Error { + std::io::Error::other(format!("MP3 encoder: {what} ({e:?})")) +} + +/// Interleaved stereo `samples` at `rate` Hz as a CBR MP3 at `kbps`, into an opened file. +pub fn encode_mp3(file: std::fs::File, rate: u32, kbps: u32, samples: &[f32]) -> std::io::Result<()> { + let brate = bitrate(kbps).ok_or_else(|| err("unsupported bitrate", kbps))?; + let mut b = Builder::new().ok_or_else(|| err("can't start", ()))?; + b.set_num_channels(2).map_err(|e| err("channels", e))?; + b.set_sample_rate(rate).map_err(|e| err("sample rate", e))?; + b.set_brate(brate).map_err(|e| err("bitrate", e))?; + b.set_mode(Mode::JointStereo).map_err(|e| err("mode", e))?; + // LAME's "-q 2": its recommended high-quality setting (0 is much slower for no audible gain). + b.set_quality(Quality::NearBest).map_err(|e| err("quality", e))?; + b.set_to_write_vbr_tag(true).map_err(|e| err("info tag", e))?; + let mut enc = b.build().map_err(|e| err("settings", e))?; + let frames = samples.len() / 2; + let mut out = Vec::with_capacity(mp3lame_encoder::max_required_buffer_size(frames) + 7200); + // LAME wants -1..1; louder samples would wrap, so clip them like the WAV writer does. + let mut buf = Vec::with_capacity(CHUNK * 2); + for chunk in samples[..frames * 2].chunks(CHUNK * 2) { + buf.clear(); + buf.extend(chunk.iter().map(|s| s.clamp(-1.0, 1.0))); + out.reserve(mp3lame_encoder::max_required_buffer_size(chunk.len() / 2)); + enc.encode_to_vec(InterleavedPcm(buf.as_slice()), &mut out).map_err(|e| err("encode", e))?; + } + out.reserve(7200); + enc.flush_to_vec::(&mut out).map_err(|e| err("flush", e))?; + // The Info tag goes in the (empty) first frame LAME left for it. + let mut tag = Vec::with_capacity(enc.lame_tag_size()); + if enc.lame_tag_encode_to_vec(&mut tag).is_some() && tag.len() <= out.len() { + out[..tag.len()].copy_from_slice(&tag); + } + let mut f = std::io::BufWriter::new(file); + f.write_all(&out)?; + f.flush() +} + +/// Bytes an MP3 of `frames` at `rate` Hz and `kbps` takes (the audio; the tag frame is small). +pub fn estimate_bytes(frames: u64, rate: f64, kbps: u32) -> f64 { + frames as f64 / rate * kbps as f64 * 1000.0 / 8.0 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// One second of a 440 Hz sine at -6 dB, encoded and read back through the engine's decoder + /// (the one used for importing MP3s): same length, same level. + #[test] + fn an_mp3_reads_back_with_its_length_and_level() { + let engine = dstudio_engine::Engine::new(dstudio_engine::Config::default()).unwrap(); + let rate = engine.sample_rate().round() as u32; + let frames = rate as usize; + let samples: Vec = (0..frames) + .flat_map(|i| { + let s = 0.5 * (std::f32::consts::TAU * 440.0 * i as f32 / rate as f32).sin(); + [s, s] + }) + .collect(); + for kbps in BITRATES { + let path = std::env::temp_dir().join(format!("dstudio-mp3-{}-{kbps}.mp3", std::process::id())); + encode_mp3(std::fs::File::create(&path).unwrap(), rate, kbps, &samples).unwrap(); + let size = std::fs::metadata(&path).unwrap().len() as f64; + let info = engine.load_file(&path); + let _ = std::fs::remove_file(&path); + let info = info.unwrap(); + assert_eq!((info.channels, info.source_sample_rate.round() as u32), (2, rate)); + assert_eq!(info.frames, frames as u64, "{kbps} kbps: the Info tag trims the encoder delay and padding"); + let expect = estimate_bytes(frames as u64, rate as f64, kbps); + // Off by the Info tag frame and the delay and padding frames at most. + let frame_bytes = 144.0 * kbps as f64 * 1000.0 / rate as f64; + assert!((size - expect).abs() < 4.0 * frame_bytes, "{kbps} kbps: {size} bytes, estimate {expect}"); + // Peak of the middle of the file (away from the fade-in LAME's filters may add). + let peaks = engine.peaks(info.asset_id, frames as u64 / 4, (frames / 2) as u32, 1).unwrap(); + let peak = peaks[0][1].max(-peaks[0][0]); + assert!((peak - 0.5).abs() < 0.05, "{kbps} kbps: peak {peak}"); + let _ = engine.release_asset(info.asset_id); + } + } + + #[test] + fn only_standard_bitrates_are_accepted() { + let path = std::env::temp_dir().join(format!("dstudio-mp3-bad-{}.mp3", std::process::id())); + let r = encode_mp3(std::fs::File::create(&path).unwrap(), 48_000, 100, &[0.0; 8]); + let _ = std::fs::remove_file(&path); + assert!(r.is_err()); + } +} diff --git a/crates/dstudio-app/ui/dialogs.slint b/crates/dstudio-app/ui/dialogs.slint index 59015494..7464cd97 100644 --- a/crates/dstudio-app/ui/dialogs.slint +++ b/crates/dstudio-app/ui/dialogs.slint @@ -52,7 +52,8 @@ component RowLabel inherits Text { // Export (File › Export…, ⇧⌘E). Mixdown and Stems render to WAV, Project writes an Ableton // Live set (Open in + Effects rows in place of Range + Format; Effects is always Render, Convert -// is a PLACEHOLDER). MP3 is a PLACEHOLDER (status line); 44.1 / 48 kHz sets the file's rate +// is a PLACEHOLDER). WAV or MP3 (the second segments are the bit depth for WAV, the bitrate +// for MP3); 44.1 / 48 kHz sets the file's rate // (converted from the engine's). Range is the full project (plus a tail) or the loop region // (exactly, so the file loops). Stems adds // the Tracks row above Range (one form row, 30.6px: 24 pt rows 12 pt apart); the @@ -121,8 +122,11 @@ export component ExportModal inherits Rectangle { Text { x: parent.width + 8.5px; height: 20.4px; text: Studio.export-bars-text; color: DialogTokens.label; font-size: 10.2px; font-weight: 600; letter-spacing: -0.4px; vertical-alignment: center; } } if Studio.export-recipe != 2: RowLabel { x: 17px; y: 136px + root.dy; text: "Format"; } - if Studio.export-recipe != 2: Segments { x: 71.4px; y: 136.85px + root.dy; width: 85.9px; a: "WAV"; b: "MP3"; a-w: 40px; index: 0; picked(i) => { if (i == 1) { Studio.chat-placeholder("MP3 export"); } } } - if Studio.export-recipe != 2: Segments { x: 71.4px + 91.8px; y: 136.85px + root.dy; width: 97.3px; a: "16-bit"; b: "24-bit"; a-w: 48.4px; index: Studio.export-bits24 ? 1 : 0; picked(i) => { Studio.export-bits(i == 1); } } + if Studio.export-recipe != 2: Segments { x: 71.4px; y: 136.85px + root.dy; width: 85.9px; a: "WAV"; b: "MP3"; a-w: 40px; index: Studio.export-mp3 ? 1 : 0; picked(i) => { Studio.export-format(i == 1); } } + if Studio.export-recipe != 2: Segments { x: 71.4px + 91.8px; y: 136.85px + root.dy; width: 97.3px; a: Studio.export-mp3 ? "192k" : "16-bit"; b: Studio.export-mp3 ? "320k" : "24-bit"; a-w: 48.4px; + index: (Studio.export-mp3 ? Studio.export-kbps-high : Studio.export-bits24) ? 1 : 0; + picked(i) => { if (Studio.export-mp3) { Studio.export-kbps(i == 1); } else { Studio.export-bits(i == 1); } } + } if Studio.export-recipe != 2: Segments { x: 71.4px + 197.7px; y: 136.85px + root.dy; width: 117.3px; a: "44.1 kHz"; b: "48 kHz"; a-w: 56.3px; index: Studio.export-rate48 ? 1 : 0; picked(i) => { Studio.export-rate(i == 1); } diff --git a/crates/dstudio-app/ui/studio.slint b/crates/dstudio-app/ui/studio.slint index fcfd2021..73fec922 100644 --- a/crates/dstudio-app/ui/studio.slint +++ b/crates/dstudio-app/ui/studio.slint @@ -868,6 +868,8 @@ export global Studio { in property export-open; in property export-bits24: true; in property export-rate48: true; // the file's rate: 48 kHz (true) or 44.1 kHz + in property export-mp3; // Format: MP3 (true) or WAV + in property export-kbps-high: true; // MP3 bitrate: 320 kbps (true) or 192 kbps in property export-recipe-text: "WAV 24-bit"; in property export-bars-text: "Bars 1–1"; in property export-name: "Untitled.wav"; @@ -895,6 +897,8 @@ export global Studio { callback export-choose-dir(); callback export-bits(bool); // true = 24-bit callback export-rate(bool); // true = 48 kHz, false = 44.1 kHz + callback export-format(bool); // true = MP3, false = WAV + callback export-kbps(bool); // true = 320 kbps, false = 192 kbps callback export-name-edited(string); in property unsaved-open; // Settings › General (src/settings.rs general_toggle): Always load last session, Auto-show diff --git a/engine/third_party_licenses.md b/engine/third_party_licenses.md index cadeb00c..3978f623 100644 --- a/engine/third_party_licenses.md +++ b/engine/third_party_licenses.md @@ -188,3 +188,21 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + +## App: LAME (MP3 export) + +The app (not the engine) links LAME for MP3 export, through the Rust crates +`mp3lame-encoder` 0.3.0 and `mp3lame-sys` 0.2.0 (crates.io), which compile +LAME's `libmp3lame` from the sources shipped in the `mp3lame-sys` crate +(`lame-4.0`) into the app binary. Used in `crates/dstudio-app/src/mp3.rs`. + +| Component | Source | Version | License | +|---|---|---|---| +| LAME (`libmp3lame`) | https://lame.sourceforge.io/ via https://github.com/DoumanAsh/mp3lame-sys | as bundled in `mp3lame-sys` 0.2.0 | GNU Library (Lesser) General Public License, version 2 or later | +| `mp3lame-sys`, `mp3lame-encoder` (Rust bindings) | https://github.com/DoumanAsh/mp3lame-encoder | 0.2.0, 0.3.0 | LGPL-3.0 | + +The LGPL asks that people receiving the app can relink it against a +modified LAME. Device's complete source (AGPL-3.0-or-later) is public, so a +modified LAME can be built into it with `cargo` (for example with a +`[patch.crates-io]` entry for `mp3lame-sys`). The license texts ship in the +crates (`COPYING` in `lame-4.0`, `LICENSE` in each crate).