Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Merge origin/main into feat/flac-export

JordyUSA773e1a3c7272
diff --cc Cargo.lock
index 6430d4801,9d1aa3311..b8fe5792f
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -1928,18 -1938,9 +1939,18 @@@ dependencies =
"web-time",
]
+[[package]]
+name = "filmcraft-flac"
- version = "0.5.0"
++version = "0.6.0"
+dependencies = [
+ "filmcraft-bitstream",
+ "filmcraft-testkit",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "filmcraft-format"
- version = "0.5.0"
+ version = "0.6.0"
dependencies = [
"filmcraft-media",
"filmcraft-project",
diff --cc crates/codecs/src/audio.rs
index 0a24e6103,daba8f4cd..a5b05dd4a
--- a/crates/codecs/src/audio.rs
+++ b/crates/codecs/src/audio.rs
@@@ -136,11 -169,10 +169,11 @@@ impl PacketDecoder
use filmcraft_isobmff::CodecConfig as C;
match c {
C::Aac(a) => Self::aac(&a.asc, if rate > 0 { rate } else { a.sample_rate }),
- C::Mp3 => Self::new(CODEC_TYPE_MP3, rate, None),
- C::Ac3 { .. } => Self::ac3(),
+ C::Mp3 => Ok(Self::lazy_mpeg_audio(rate)),
+ C::Ac3 { .. } | C::Eac3 { .. } => Self::ac3(),
C::Alac { cookie } => Self::new(CODEC_TYPE_ALAC, rate, Some(cookie.clone())),
- C::Flac(_) => Self::new(CODEC_TYPE_FLAC, rate, None),
+ // the decoder needs the STREAMINFO body: `dfLa` holds it after the 4-byte block header
+ C::Flac(f) => Self::new(CODEC_TYPE_FLAC, rate, f.metadata_blocks.get(4..38).map(<[u8]>::to_vec)),
C::Opus(o) => Self::opus(filmcraft_opus::OpusHead::from_dops(&o.to_bytes()).map_err(|e| CodecError::Unsupported(format!("Opus: {e}")))?),
other => Err(CodecError::Unsupported(format!("{} audio", other.name()))),
}
diff --cc crates/engine/src/commands.rs
index ab09ccf72,6609afddf..17cfe92e0
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@@ -1180,7 -1285,7 +1285,7 @@@ fn build() -> Vec<CommandSpec>
"Media…",
["File", "Export"],
None,
- r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|hevc|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff|flac"?,"audioCodec":"auto|aac|pcm|flac"?,"flacLevel":0..8=5,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass"?,"hardwareEncoding":"off|auto"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"alpha":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq"?,"dnxProfile":"lb|sq|hq|hqx"?,"apvProfile":"422-10|422-12|444-10|444-12"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,
- r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|hevc|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|jpg|tga|dpx|exr|gif|wav|aiff|aac"?,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass|crf"?,"crf":0..51=23,"hardwareEncoding":"off|auto"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"alpha":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq|4444|4444xq"?,"dnxProfile":"lb|sq|hq|hqx"?,"apvProfile":"422-10|422-12|444-10|444-12"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,
++ r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|hevc|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|jpg|tga|dpx|exr|gif|wav|aiff|aac|flac"?,"audioCodec":"auto|aac|pcm|flac"?,"flacLevel":0..8=5,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass|crf"?,"crf":0..51=23,"hardwareEncoding":"off|auto"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"alpha":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq|4444|4444xq"?,"dnxProfile":"lb|sq|hq|hqx"?,"apvProfile":"422-10|422-12|444-10|444-12"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,
has_seq,
crate::export_tools::export_media
),
diff --cc crates/export/src/lib.rs
index 1ca44f6bd,e9d5b1285..b0559d1e3
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@@ -98,9 -116,10 +116,13 @@@ pub enum Format
Wav,
#[serde(rename = "aiff", alias = "Aiff")]
Aiff,
+ /// AAC Audio: the mix alone, AAC-LC in an MPEG-4 audio file (`.m4a`), or a raw ADTS stream when
+ /// the path ends in `.aac`.
+ #[serde(rename = "aac", alias = "Aac")]
+ Aac,
+ /// FLAC (RFC 9639): lossless compressed audio.
+ #[serde(rename = "flac", alias = "Flac")]
+ Flac,
/// MXF OP1a (SMPTE ST 378): frame-wrapped DNxHR, ProRes or H.264 ([`MxfVideoCodec`]) + PCM.
#[serde(rename = "mxf-op1a", alias = "MxfOp1a")]
MxfOp1a,
@@@ -127,7 -152,7 +155,8 @@@ impl Format
"gif" | "animatedgif" => Format::Gif,
"wav" | "waveform" | "waveformaudio" => Format::Wav,
"aif" | "aiff" | "aifc" => Format::Aiff,
+ "aac" | "aacaudio" | "m4a" | "adts" => Format::Aac,
+ "flac" | "fla" => Format::Flac,
_ => return None,
})
}
@@@ -146,7 -176,7 +180,8 @@@
Format::Gif => "gif",
Format::Wav => "wav",
Format::Aiff => "aiff",
+ Format::Aac => "aac",
+ Format::Flac => "flac",
Format::MxfOp1a => "mxf-op1a",
Format::MxfOpAtom => "mxf-opatom",
}
@@@ -161,7 -195,7 +200,8 @@@
Format::Gif => "gif",
Format::Wav => "wav",
Format::Aiff => "aif",
+ Format::Aac => "m4a",
+ Format::Flac => "flac",
Format::MxfOp1a | Format::MxfOpAtom => "mxf",
}
}
@@@ -179,7 -218,7 +224,8 @@@
Format::Gif => "Animated GIF",
Format::Wav => "Waveform Audio",
Format::Aiff => "AIFF",
+ Format::Aac => "AAC Audio",
+ Format::Flac => "FLAC",
Format::MxfOp1a => "MXF OP1a",
Format::MxfOpAtom => "MXF OP-Atom",
}
@@@ -195,15 -243,28 +250,28 @@@
/// Whether the crate carries an encoder for the format; the others need one registered at runtime
/// ([`register_format_probe`]).
pub fn has_builtin_encoder(self) -> bool {
- self != Format::Hevc
+ !matches!(self, Format::Hevc | Format::Av1)
+ }
- /// Sound without picture: Waveform Audio, AIFF and AAC Audio.
++ /// Sound without picture: Waveform Audio, AIFF, AAC Audio and FLAC.
+ pub fn is_audio_only(self) -> bool {
- matches!(self, Format::Wav | Format::Aiff | Format::Aac)
++ matches!(self, Format::Wav | Format::Aiff | Format::Aac | Format::Flac)
}
/// H.264 or H.265: MPEG-4 (or QuickTime) with AAC audio, set up with the same bitrate controls.
pub fn is_h26x(self) -> bool {
matches!(self, Format::H264 | Format::Hevc)
}
- pub const ALL: [Format; 15] = [
+ /// A bitrate-controlled MPEG-4 video format with AAC audio: H.264, H.265 or AV1 (MPEG-4 only).
+ pub fn is_mp4_video(self) -> bool {
+ matches!(self, Format::H264 | Format::Hevc | Format::Av1)
+ }
+ /// Whether the file is MPEG-4 rather than QuickTime for `mux`.
+ pub fn is_mp4_with(self, mux: Multiplexer) -> bool {
+ self == Format::Av1 || (self.is_h26x() && mux == Multiplexer::Mp4)
+ }
- pub const ALL: [Format; 20] = [
++ pub const ALL: [Format; 21] = [
Format::H264,
Format::Hevc,
+ Format::Av1,
Format::ProRes,
Format::DnxHr,
Format::Apv,
@@@ -214,7 -279,7 +286,8 @@@
Format::Gif,
Format::Wav,
Format::Aiff,
+ Format::Aac,
+ Format::Flac,
Format::MxfOp1a,
Format::MxfOpAtom,
];
@@@ -1647,24 -1753,14 +1825,25 @@@ pub fn export(project: &Arc<Project>, s
let cancelled = || progress.cancel.load(Ordering::Relaxed);
let batch = rayon::current_num_threads().clamp(2, 16) as i64;
let (bytes, nframes) = match settings.format {
+ Format::Aac => aac_out::export(project, seq, settings, range, sources, progress)?,
- Format::Wav | Format::Aiff => {
+ Format::Wav | Format::Aiff | Format::Flac => {
let mut a = audio_out::AudioOut::new(project.clone(), seq, settings, range)?;
let (ch, sr, bits) = (a.channels as u16, a.sr, settings.audio.bits);
- let container = if settings.format == Format::Wav { pcm::PcmContainer::Wav } else { pcm::PcmContainer::Aiff };
let frames = a.remaining();
// the sizes are known up front: refuse an AIFF that cannot hold them before measuring
- let head = pcm::header(container, ch, sr, bits, frames).map_err(ExportError::Unsupported)?;
+ let mut writer = match settings.format {
+ Format::Flac => {
+ let mut cfg = filmcraft_flac::EncoderConfig::new(sr, ch as u8, if bits >= 24 { 24 } else { 16 });
+ cfg.level = settings.audio.flac_level.min(8);
+ AudioWriter::Flac(Box::new(filmcraft_flac::Encoder::new(cfg).map_err(|e| ExportError::Unsupported(format!("FLAC: {e}")))?))
+ }
+ Format::Wav => AudioWriter::Pcm(pcm::PcmContainer::Wav),
+ _ => AudioWriter::Pcm(pcm::PcmContainer::Aiff),
+ };
+ let head = match &writer {
+ AudioWriter::Pcm(c) => pcm::header(*c, ch, sr, bits, frames).map_err(ExportError::Unsupported)?,
+ AudioWriter::Flac(enc) => enc.header(),
+ };
// one second per chunk: memory stays flat however long the range is
let chunk = i64::from(sr.max(1));
if !settings.part_of_batch {
diff --cc crates/export/src/presets.rs
index 12ee53ad6,6e6b9ddd8..58f60d6ef
--- a/crates/export/src/presets.rs
+++ b/crates/export/src/presets.rs
@@@ -153,7 -175,16 +175,17 @@@ pub fn builtin_presets() -> Vec<ExportP
p("Waveform Audio 48 kHz 16-bit", "Audio Only", "WAV, stereo 48 kHz 16-bit PCM", audio_only(Format::Wav, 16)),
p("Waveform Audio 48 kHz 24-bit", "Audio Only", "WAV, stereo 48 kHz 24-bit PCM", audio_only(Format::Wav, 24)),
p("AIFF 48 kHz 16-bit", "Audio Only", "AIFF, stereo 48 kHz 16-bit PCM", audio_only(Format::Aiff, 16)),
+ p(
+ "AAC Audio 48 kHz 320 kbps",
+ "Audio Only",
+ "MPEG-4 audio (.m4a), stereo 48 kHz AAC-LC at 320 kbps",
+ ExportSettings {
+ format: Format::Aac,
- audio: AudioSettings { codec: AudioCodec::Aac, sample_rate: Some(48_000), channels: 2, bitrate_kbps: 320, bits: 16 },
++ audio: AudioSettings { codec: AudioCodec::Aac, sample_rate: Some(48_000), channels: 2, bitrate_kbps: 320, bits: 16, ..Default::default() },
+ ..Default::default()
+ },
+ ),
+ p("FLAC 48 kHz 24-bit", "Audio Only", "FLAC, stereo 48 kHz 24-bit, lossless", audio_only(Format::Flac, 24)),
]
}
diff --cc crates/export/src/settings.rs
index 8ff9eef9c,be8271825..95378d041
--- a/crates/export/src/settings.rs
+++ b/crates/export/src/settings.rs
@@@ -156,8 -160,7 +160,8 @@@ impl MxfVideoCodec
}
}
- /// Audio codec. `Auto` = AAC in MP4, PCM in QuickTime / WAV / AIFF, FLAC in FLAC. MP4 and
- /// QuickTime can also carry FLAC; MXF is always PCM.
-/// Audio codec. `Auto` = AAC in MP4 and AAC Audio, PCM in QuickTime / WAV / AIFF.
++/// Audio codec. `Auto` = AAC in MP4 and AAC Audio, PCM in QuickTime / WAV / AIFF, FLAC in FLAC.
++/// MP4 and QuickTime can also carry FLAC; MXF is always PCM.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AudioCodec {
@@@ -426,12 -431,10 +436,13 @@@ impl ExportSettings
/// The audio codec actually used.
pub fn audio_codec(&self) -> AudioCodec {
match (self.format, self.audio.codec) {
+ (Format::Flac, _) => AudioCodec::Flac,
(Format::Wav | Format::Aiff | Format::MxfOp1a | Format::MxfOpAtom, _) => AudioCodec::Pcm,
+ (Format::Aac, _) => AudioCodec::Aac,
+ // MP4 and QuickTime both carry FLAC (`fLaC` + `dfLa`)
+ (_, AudioCodec::Flac) => AudioCodec::Flac,
- (f, _) if f.is_h26x() && self.multiplexer == Multiplexer::Mp4 => AudioCodec::Aac,
- (_, AudioCodec::Auto) if self.format.is_h26x() => AudioCodec::Aac,
+ (f, _) if f.is_mp4_with(self.multiplexer) => AudioCodec::Aac,
+ (_, AudioCodec::Auto) if self.format.is_mp4_video() => AudioCodec::Aac,
(_, AudioCodec::Auto) => AudioCodec::Pcm,
(_, c) => c,
}
@@@ -480,19 -484,21 +492,24 @@@
};
px * fps * bpp
}
- Format::Mjpeg => px * 8.0 * (0.4 + self.quality as f64 / 100.0 * 2.0) * fps / 8.0,
+ Format::Mjpeg | Format::JpegSequence => px * 8.0 * (0.4 + self.quality as f64 / 100.0 * 2.0) * fps / 8.0,
Format::PngSequence => px * 4.0 * 0.45 * 8.0 * fps,
Format::TiffSequence | Format::BmpSequence => px * if self.format == Format::BmpSequence { 3.0 } else { 4.0 } * 8.0 * fps,
+ Format::TgaSequence => px * if self.keeps_alpha() { 4.0 } else { 3.0 } * 8.0 * fps,
+ // 10-bit RGB in one 32-bit word per pixel
+ Format::DpxSequence => px * 4.0 * 8.0 * fps,
+ // two bytes per half-float channel
+ Format::ExrSequence => px * if self.keeps_alpha() { 8.0 } else { 6.0 } * 8.0 * fps,
Format::Gif => px * 0.6 * 8.0 * fps,
- Format::Wav | Format::Aiff | Format::MxfOp1a | Format::MxfOpAtom => 0.0,
+ Format::Wav | Format::Aiff | Format::Flac | Format::MxfOp1a | Format::MxfOpAtom => 0.0,
};
let audio_bps = if self.has_audio() || self.format.is_audio_only() {
+ let pcm = r.sample_rate as f64 * r.channels as f64 * if self.audio.bits >= 24 { 24.0 } else { 16.0 };
match self.audio_codec() {
AudioCodec::Aac => self.audio.bitrate_kbps as f64 * 1000.0,
- _ => r.sample_rate as f64 * r.channels as f64 * if self.audio.bits >= 24 { 24.0 } else { 16.0 },
+ // typical of music and dialogue; noise compresses less, silence far more
+ AudioCodec::Flac => pcm * 0.6,
+ _ => pcm,
}
} else {
0.0
diff --cc crates/export/src/settings_tests.rs
index 1392535d8,fb68289ec..6dd55a5bd
--- a/crates/export/src/settings_tests.rs
+++ b/crates/export/src/settings_tests.rs
@@@ -167,126 -261,147 +261,267 @@@ fn wav_and_aiff_audio_only()
}
}
+ /// Root-mean-square level of decoded planar audio.
+ fn rms(planes: &[Vec<f32>]) -> f32 {
+ let n = planes.iter().map(Vec::len).sum::<usize>().max(1);
+ (planes.iter().flatten().map(|s| s * s).sum::<f32>() / n as f32).sqrt()
+ }
+
+ #[test]
+ fn aac_audio_writes_m4a_and_adts() {
+ let (p, seq, m) = matte([0.0, 0.0, 0.0, 1.0], 64, 36, Some(-6.0));
+ let dir = Scratch::new("aac-audio");
+ let range = Some(TimeRange::new(Tick::ZERO, Tick(TICKS_PER_SECOND)));
+ // .m4a: one AAC track, no video, the encoder delay in an edit list
+ let m4a = dir.path("a.m4a");
+ let s = ExportSettings { format: Format::Aac, path: m4a.clone(), range, ..Default::default() };
+ assert!(!s.has_video());
+ assert_eq!(s.audio_codec(), AudioCodec::Aac);
+ assert_eq!(s.extension(), "m4a");
+ let r = export(&p, seq, &s, &m, &Progress::default()).unwrap();
+ assert_eq!(r.frames, 48_000, "one second of samples");
+ let bytes = std::fs::read(&m4a).unwrap();
+ let file = filmcraft_isobmff::open(bytes.clone()).unwrap();
+ assert_eq!(file.tracks.len(), 1, "audio only");
+ let t = &file.tracks[0];
+ let filmcraft_isobmff::CodecConfig::Aac(cfg) = &t.entries[0].codec else { panic!("not AAC: {:?}", t.entries[0].codec) };
+ assert_eq!((cfg.object_type, cfg.sample_rate, cfg.channel_config), (2, 48_000, 2));
+ assert!(t.samples.len() >= 48_000 / 1024, "{} access units", t.samples.len());
+ let mut dec = filmcraft_aac::Decoder::new(&cfg.asc).unwrap();
+ let mut pcm: Vec<Vec<f32>> = Vec::new();
+ for i in 0..t.samples.len() {
+ let out = dec.decode(&file.read_sample(&bytes, 0, i).unwrap()).unwrap();
+ pcm.resize(out.len(), Vec::new());
+ pcm.iter_mut().zip(out).for_each(|(a, b)| a.extend(b));
+ }
+ // the -6 dBFS tone (RMS about 0.35) survives the round trip
+ assert!((0.2..0.5).contains(&rms(&pcm)), "rms {}", rms(&pcm));
+ if let Some(j) = ffprobe_json(&["-show_streams", "-show_format"], &m4a) {
+ assert_eq!(j["streams"].as_array().unwrap().len(), 1);
+ let st = &j["streams"][0];
+ assert_eq!(st["codec_name"], "aac");
+ assert_eq!(st["sample_rate"], "48000");
+ assert_eq!(st["channels"], 2);
+ let d: f64 = j["format"]["duration"].as_str().unwrap().parse().unwrap();
+ assert!((d - 1.0).abs() < 0.03, "duration {d}");
+ }
+
+ // .aac: raw ADTS, mono 44.1 kHz at 128 kbps
+ let adts = dir.path("a.aac");
+ let mut s = ExportSettings { format: Format::Aac, path: adts.clone(), range, ..Default::default() };
+ s.audio = AudioSettings { sample_rate: Some(44_100), channels: 1, bitrate_kbps: 128, ..Default::default() };
+ export(&p, seq, &s, &m, &Progress::default()).unwrap();
+ let b = std::fs::read(&adts).unwrap();
+ // AAC-LC 44.1 kHz (index 4) mono: 00010 0100 0001 000
+ let mut dec = filmcraft_aac::Decoder::new(&[0x12, 0x08]).unwrap();
+ let (mut pos, mut units, mut pcm) = (0usize, 0usize, vec![Vec::new()]);
+ while pos < b.len() {
+ let h = &b[pos..pos + 7];
+ assert_eq!((h[0], h[1] & 0xF6), (0xFF, 0xF0), "ADTS sync at {pos}");
+ assert_eq!(h[1] & 0x01, 1, "no CRC");
+ assert_eq!(((h[2] >> 2) & 0x0F, ((h[2] & 1) << 2) | (h[3] >> 6)), (4, 1), "44.1 kHz mono");
+ let len = ((h[3] as usize & 0x03) << 11) | ((h[4] as usize) << 3) | (h[5] as usize >> 5);
+ assert!(len > 7 && pos + len <= b.len(), "frame length {len} at {pos}");
+ pcm[0].extend(dec.decode(&b[pos + 7..pos + len]).unwrap().swap_remove(0));
+ pos += len;
+ units += 1;
+ }
+ assert!(units >= 44_100 / 1024, "{units} frames");
+ assert!((0.2..0.5).contains(&rms(&pcm)), "rms {}", rms(&pcm));
+ if let Some(j) = ffprobe_json(&["-show_streams", "-show_format"], &adts) {
+ assert_eq!(j["format"]["format_name"], "aac");
+ let st = &j["streams"][0];
+ assert_eq!(st["codec_name"], "aac");
+ assert_eq!(st["sample_rate"], "44100");
+ assert_eq!(st["channels"], 1);
+ }
+ if let Some(ffmpeg) = filmcraft_testkit::ffmpeg_or_skip("AAC Audio decode") {
+ for f in [&m4a, &adts] {
+ let out = std::process::Command::new(&ffmpeg).args(["-v", "error", "-xerror", "-i", f, "-f", "null", "-"]).output().unwrap();
+ assert!(out.status.success() && out.stderr.is_empty(), "{f}: {}", String::from_utf8_lossy(&out.stderr));
+ }
+ }
+ }
+
+ #[test]
+ fn aac_audio_settings_and_names() {
+ assert_eq!(Format::from_name("m4a"), Some(Format::Aac));
+ assert_eq!(Format::from_name("AAC Audio"), Some(Format::Aac));
+ assert_eq!(Format::from_name(Format::Aac.id()), Some(Format::Aac));
+ assert!(Format::ALL.contains(&Format::Aac) && Format::Aac.is_audio_only() && !Format::H264.is_audio_only());
+ let s = ExportSettings { format: Format::Aac, include_audio: false, ..Default::default() };
+ let sum = s.summary(1920, 1080, FrameRate::FPS_24, 48_000, Tick(10 * TICKS_PER_SECOND));
+ assert_eq!(sum.video, "No video");
+ assert_eq!(sum.audio, "AAC, 320 kbps, 48000 Hz, Stereo");
+ assert_eq!(sum.estimated_bytes, 400_000, "320 kbps for 10 s, no picture");
+ let preset = presets::find_builtin("AAC Audio 48 kHz 320 kbps").unwrap();
+ assert_eq!(preset.settings.format, Format::Aac);
+ }
+
+ #[test]
+ fn wav_export_honours_explicit_sample_rates() {
+ let (project, sequence, sources) = matte([0.0, 0.0, 0.0, 1.0], 64, 36, Some(-6.0));
+ let dir = Scratch::new("wav-sample-rates");
+ for rate in [1, 4000, 7350, 8000, 48_000, 192_000, 192_001, 200_000, 352_800, 384_000] {
+ let settings = ExportSettings {
+ format: Format::Wav,
+ path: dir.path(&format!("{rate}.wav")),
+ audio: AudioSettings { sample_rate: Some(rate), ..Default::default() },
+ range: Some(TimeRange::new(Tick::ZERO, Tick(TICKS_PER_SECOND / 4))),
+ ..Default::default()
+ };
+ settings.validate().unwrap();
+ let resolved = settings.resolve(64, 36, FrameRate::FPS_24, 48_000);
+ assert_eq!(resolved.sample_rate, rate, "requested {rate} Hz");
+ export(&project, sequence, &settings, &sources, &Progress::default()).unwrap();
+ let bytes = std::fs::read(&settings.path).unwrap();
+ assert_eq!(u32::from_le_bytes(bytes[24..28].try_into().unwrap()), rate);
+ assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), rate / 4 * 4, "quarter-second stereo 16-bit PCM");
+ if let Some(probe) = ffprobe_json(&["-show_streams"], &settings.path) {
+ assert_eq!(probe["streams"][0]["sample_rate"], rate.to_string());
+ }
+ }
+ let settings = ExportSettings { format: Format::Wav, ..Default::default() };
+ assert_eq!(settings.resolve(64, 36, FrameRate::FPS_24, 44_100).sample_rate, 44_100);
+ }
+
+ #[test]
+ fn aac_export_rejects_unsupported_explicit_sample_rates() {
+ let (project, sequence, sources) = matte([0.0, 0.0, 0.0, 1.0], 64, 36, Some(-6.0));
+ let dir = Scratch::new("aac-sample-rates");
+ for rate in [4000, 192_001, 200_000, 384_000] {
+ let settings = ExportSettings {
+ path: dir.path(&format!("{rate}.mp4")),
+ audio: AudioSettings { sample_rate: Some(rate), ..Default::default() },
+ range: Some(TimeRange::new(Tick::ZERO, Tick(TICKS_PER_SECOND / 4))),
+ ..Default::default()
+ };
+ let error = export(&project, sequence, &settings, &sources, &Progress::default()).unwrap_err();
+ assert!(error.to_string().contains("sample rate"), "{error}");
+ assert!(!Path::new(&settings.path).exists(), "an unsupported rate must not produce a substitute file");
+ }
+ }
+
+#[test]
+fn flac_is_lossless_against_wav() {
+ let (p, seq, m) = matte([0.0, 0.0, 0.0, 1.0], 64, 36, Some(-6.0));
+ let dir = Scratch::new("flac");
+ let range = Some(TimeRange::new(Tick::ZERO, Tick(3 * TICKS_PER_SECOND / 2)));
+ let audio = AudioSettings { channels: 2, bits: 24, ..Default::default() };
+ let (wav, flac) = (dir.path("a.wav"), dir.path("a.flac"));
+ let w = ExportSettings { format: Format::Wav, path: wav.clone(), range, audio: audio.clone(), ..Default::default() };
+ export(&p, seq, &w, &m, &Progress::default()).unwrap();
+ let f = ExportSettings { format: Format::Flac, path: flac.clone(), range, audio, ..Default::default() };
+ let prog = Progress::default();
+ let r = export(&p, seq, &f, &m, &prog).unwrap();
+ assert_eq!(r.frames, 72_000, "1.5 s at 48 kHz");
+ // one progress step per second of audio
+ assert_eq!((prog.total.load(Ordering::Relaxed), prog.done.load(Ordering::Relaxed)), (2, 2));
+ let (wb, fb) = (std::fs::read(&wav).unwrap(), std::fs::read(&flac).unwrap());
+ assert_eq!(&fb[..4], b"fLaC");
+ assert!(fb.len() * 2 < wb.len(), "a tone compresses: FLAC {} bytes, WAV {}", fb.len(), wb.len());
+ // STREAMINFO was filled in at the end: total samples
+ let si = &fb[8..42];
+ assert_eq!((u64::from(si[13] & 0x0F) << 32) | u64::from(u32::from_be_bytes(si[14..18].try_into().unwrap())), 72_000);
+
+ // the same samples through FilmCraft's own readers
+ let decode = |name: &str, bytes: Vec<u8>| filmcraft_codecs::open_bytes(name, bytes.into()).unwrap().audio(0, 72_000, 48_000).unwrap();
+ let (a, b) = (decode("a.wav", wb), decode("a.flac", fb));
+ assert_eq!(a.channels.len(), 2);
+ for (ca, cb) in a.channels.iter().zip(&b.channels) {
+ assert_eq!(ca.len(), cb.len());
+ let worst = ca.iter().zip(cb).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
+ assert!(worst < 1e-6, "differs by {worst}");
+ assert!(ca.iter().any(|v| v.abs() > 0.1), "the tone is there");
+ }
+ // and bit for bit through ffmpeg
+ if let Some(ffmpeg) = filmcraft_testkit::ffmpeg_or_skip("flac export") {
+ let raw = |path: &str| {
+ let out = std::process::Command::new(&ffmpeg).args(["-v", "error", "-i", path, "-f", "s32le", "-c:a", "pcm_s32le", "-"]).output().unwrap();
+ assert!(out.status.success() && out.stderr.is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
+ out.stdout
+ };
+ let (a, b) = (raw(&wav), raw(&flac));
+ assert_eq!(a.len(), 72_000 * 2 * 4);
+ assert!(a == b, "FLAC must decode to the WAV's samples exactly");
+ }
+ if let Some(j) = ffprobe_json(&["-show_streams"], &flac) {
+ let st = &j["streams"][0];
+ assert_eq!((st["codec_name"].as_str(), st["sample_rate"].as_str(), st["bits_per_raw_sample"].as_str()), (Some("flac"), Some("48000"), Some("24")));
+ }
+}
+
+#[test]
+fn flac_audio_in_mp4_and_mov() {
+ let (p, seq, m) = matte([0.2, 0.4, 0.6, 1.0], 64, 36, Some(-6.0));
+ let dir = Scratch::new("flac-in");
+ // 1.5 s at 48 kHz: 17 full FLAC frames of 4096 samples and a last one of 2368
+ let range = Some(TimeRange::new(Tick::ZERO, Tick(3 * TICKS_PER_SECOND / 2)));
+ let audio = AudioSettings { codec: AudioCodec::Flac, bits: 24, ..Default::default() };
+ let wav = dir.path("ref.wav");
+ export(&p, seq, &ExportSettings { format: Format::Wav, path: wav.clone(), range, audio: audio.clone(), ..Default::default() }, &m, &Progress::default())
+ .unwrap();
+ for (format, mux, name) in
+ [(Format::H264, Multiplexer::Mp4, "a.mp4"), (Format::H264, Multiplexer::Mov, "b.mov"), (Format::ProRes, Multiplexer::Mp4, "c.mov")]
+ {
+ let path = dir.path(name);
+ let s = ExportSettings { format, multiplexer: mux, path: path.clone(), range, audio: audio.clone(), ..Default::default() };
+ assert_eq!(s.audio_codec(), AudioCodec::Flac, "{name}");
+ assert!(s.summary(64, 36, FrameRate::FPS_24, 48_000, Tick(TICKS_PER_SECOND)).audio.starts_with("FLAC (lossless) 24-bit"), "{name}");
+ export(&p, seq, &s, &m, &Progress::default()).unwrap();
+ let bytes = std::fs::read(&path).unwrap();
+ // `dfLa` was rewritten at the end: STREAMINFO with frame sizes, total samples and the MD5
+ let at = bytes.windows(4).position(|w| w == b"dfLa").unwrap() + 4 + 4 + 4;
+ let si = &bytes[at..at + 34];
+ assert_eq!(bytes[at - 4], 0x80, "{name}: STREAMINFO is the last metadata block");
+ assert!(si[4..10].iter().any(|&b| b != 0), "{name}: frame sizes");
+ assert_eq!(u32::from_be_bytes(si[14..18].try_into().unwrap()), 72_000, "{name}: total samples");
+ assert!(si[18..34].iter().any(|&b| b != 0), "{name}: MD5");
+ // FilmCraft's own importer reads the FLAC track back, sample-accurately long
+ let src = filmcraft_codecs::open_bytes(name, bytes.into()).unwrap();
+ let a = src.audio(0, 72_000, 48_000).unwrap();
+ assert!(a.channels.iter().all(|c| c.len() == 72_000) && a.channels[0].iter().any(|v| v.abs() > 0.1), "{name}");
+ if let Some(j) = ffprobe_json(&["-show_streams", "-count_packets"], &path) {
+ let st = j["streams"].as_array().unwrap().iter().find(|s| s["codec_type"] == "audio").unwrap().clone();
+ assert_eq!((st["codec_name"].as_str(), st["sample_rate"].as_str(), st["channels"].as_u64()), (Some("flac"), Some("48000"), Some(2)), "{name}");
+ assert_eq!(st["nb_read_packets"].as_str(), Some("18"), "{name}: one FLAC frame per packet");
+ assert_eq!(st["duration_ts"].as_u64(), Some(72_000), "{name}: the short last frame is timed exactly");
+ }
+ // the audio decodes to the WAV export's samples bit for bit
+ if let Some(ffmpeg) = filmcraft_testkit::ffmpeg_or_skip("flac in containers") {
+ let raw = |path: &str| {
+ let out = std::process::Command::new(&ffmpeg)
+ .args(["-v", "error", "-i", path, "-map", "0:a", "-f", "s32le", "-c:a", "pcm_s32le", "-"])
+ .output()
+ .unwrap();
+ assert!(out.status.success() && out.stderr.is_empty(), "{name}: {}", String::from_utf8_lossy(&out.stderr));
+ out.stdout
+ };
+ assert!(raw(&path) == raw(&wav), "{name}: FLAC must decode to the WAV's samples exactly");
+ }
+ }
+ // MXF stays PCM whatever is asked for
+ let mxf = ExportSettings { format: Format::MxfOp1a, audio: audio.clone(), ..Default::default() };
+ assert_eq!(mxf.audio_codec(), AudioCodec::Pcm);
+}
+
+#[test]
+fn flac_settings_round_trip_and_summary() {
+ let s: ExportSettings = serde_json::from_value(serde_json::json!({"format": "flac"})).unwrap();
+ assert_eq!((s.format, s.audio_codec(), s.audio.flac_level, s.has_video()), (Format::Flac, AudioCodec::Flac, 5, false));
+ assert_eq!((s.extension(), Format::from_name("FLAC"), Format::Flac.id()), ("flac", Some(Format::Flac), "flac"));
+ // settings saved before FLAC read the default level
+ let old: AudioSettings = serde_json::from_value(serde_json::json!({"bits": 24})).unwrap();
+ assert_eq!(old.flac_level, 5);
+ let sum = ExportSettings { format: Format::Flac, ..Default::default() }.summary(64, 36, FrameRate::FPS_24, 48_000, Tick(TICKS_PER_SECOND));
+ assert!(sum.audio.starts_with("FLAC (lossless) 16-bit, level 5, 48000 Hz"), "{}", sum.audio);
+ assert_eq!(sum.video, "No video");
+ // estimated below PCM
+ let pcm = ExportSettings { format: Format::Wav, ..Default::default() }.estimate_bytes(64, 36, FrameRate::FPS_24, 48_000, Tick(TICKS_PER_SECOND));
+ let flac = ExportSettings { format: Format::Flac, ..Default::default() }.estimate_bytes(64, 36, FrameRate::FPS_24, 48_000, Tick(TICKS_PER_SECOND));
+ assert!(flac < pcm, "{flac} < {pcm}");
+}
+
#[test]
fn invalid_export_allocations_are_rejected_before_rendering() {
let (project, sequence, _) = matte([1.0, 0.0, 0.0, 1.0], 64, 36, None);
@@@ -616,7 -798,7 +918,7 @@@ fn h265_is_a_format_that_needs_a_regist
}
assert_eq!(Format::from_name(Format::Hevc.id()), Some(Format::Hevc));
assert_eq!((Format::Hevc.extension(), Format::Hevc.label()), ("mp4", "H.265 (HEVC)"));
- assert!(Format::ALL.contains(&Format::Hevc) && Format::ALL.len() == 15);
- assert!(Format::ALL.contains(&Format::Hevc) && Format::ALL.len() == 20);
++ assert!(Format::ALL.contains(&Format::Hevc) && Format::ALL.len() == 21);
let s: ExportSettings = serde_json::from_value(serde_json::json!({"format": "hevc"})).unwrap();
assert_eq!(s.format, Format::Hevc);
assert_eq!(serde_json::to_value(&s).unwrap()["format"], "hevc");
diff --cc crates/ui-egui/src/panels/export_mode.rs
index c9bc9461b,30d21268e..8b7bc257a
--- a/crates/ui-egui/src/panels/export_mode.rs
+++ b/crates/ui-egui/src/panels/export_mode.rs
@@@ -758,18 -773,12 +773,18 @@@ fn audio_section(ui: &mut egui::Ui, reg
}
}
row(ui, t, tl!("Audio Format"), |ui| {
- let fixed = s.format.is_mp4_with(s.multiplexer) || audio_only || s.format.is_mxf();
+ let fixed = audio_only || s.format.is_mxf();
let cur = match s.audio_codec() {
AudioCodec::Aac => "AAC",
+ AudioCodec::Flac => tl!("FLAC (lossless)"),
_ => tl!("Uncompressed (PCM)"),
};
- let labels = vec![("AAC".to_string(), !audio_only), (tl!("Uncompressed (PCM)").to_string(), !s.format.is_mp4_with(s.multiplexer))];
+ // MP4 takes AAC or FLAC; QuickTime any of the three
+ let labels = vec![
+ ("AAC".to_string(), !audio_only),
- (tl!("Uncompressed (PCM)").to_string(), !(s.format.is_h26x() && s.multiplexer == Multiplexer::Mp4)),
++ (tl!("Uncompressed (PCM)").to_string(), !s.format.is_mp4_with(s.multiplexer)),
+ (tl!("FLAC (lossless)").to_string(), true),
+ ];
if fixed {
ui.label(cur);
} else if let Some(i) = combo(ui, reg, "export.audio.codec", cur, &labels, 180.0) {