From 929bba911819a4e3ef12f3b52bed5b7d0793d7e2 Mon Sep 17 00:00:00 2001 From: iMyth Date: Wed, 19 Aug 2026 10:15:21 +0300 Subject: [PATCH 1/4] fix: prevent audio tail truncation during video export Two issues caused audio to be cut off at the end: 1. loudnorm filter without linear=true uses internal buffering that can drop trailing samples. Adding linear=true makes it apply a fixed gain without altering duration. 2. -shortest flag in merge_video_with_audio truncates the output to the shorter stream. When video is slightly shorter than audio (due to frame duration rounding), audio gets clipped. Replaced with -t using the actual audio duration from ffprobe, making audio the authoritative length source. Fixes both normal mode and sleep mode export paths. --- .../audio/hyperframes/ffmpeg_utils.rs | 59 +++++++++++++++---- .../audio/hyperframes/section_audio.rs | 2 +- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs b/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs index d3b9e1d..7fc31f0 100644 --- a/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs +++ b/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs @@ -28,16 +28,50 @@ use crate::core::error::AppError; /// This is a single source of truth for the sleep mode filter chain, /// used by section_audio.rs, video_merger.rs, and render.rs. pub fn build_sleep_mode_audio_filter() -> &'static str { - "bass=g=3:f=150,lowpass=f=8000:p=1,loudnorm=I=-20:TP=-2:LRA=7" + "bass=g=3:f=150,lowpass=f=8000:p=1,loudnorm=I=-20:TP=-2:LRA=7:linear=true" +} + +/// Probe the duration of a media file in seconds using ffprobe. +fn probe_duration_secs(file_path: &str) -> Result { + let ffmpeg_path = find_ffmpeg(); + let ffprobe_path = ffmpeg_path.replace("ffmpeg", "ffprobe"); + + let output = std::process::Command::new(&ffprobe_path) + .args([ + "-v", + "quiet", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + file_path, + ]) + .output() + .map_err(|e| AppError::FFmpeg(format!("Failed to run ffprobe for duration: {}", e)))?; + + if !output.status.success() { + return Err(AppError::FFmpeg(format!( + "ffprobe duration query failed for '{}'", + file_path + ))); + } + + let stdout = String::from_utf8_lossy(&output.stdout); + stdout + .trim() + .parse::() + .map_err(|_| AppError::FFmpeg(format!("Failed to parse duration from ffprobe for '{}'", file_path))) } /// Merge a silent video with an audio file using FFmpeg. /// /// - Video is copied without re-encoding (`-c:v copy`) /// - Audio is encoded to AAC (`-c:a aac`) -/// - Uses `-shortest` to truncate output to the shorter stream (audio). -/// This prevents oversized videos (from LLM rendering bugs) from polluting -/// the final multi-section merge with trailing blank frames. +/// - Uses audio duration as the authoritative length via `-t` from ffprobe. +/// This prevents audio truncation that occurred with `-shortest` when the +/// video stream was slightly shorter than the audio stream (due to frame +/// rounding). If the video is shorter, the last frame holds; if longer, +/// it gets trimmed to audio duration — preventing trailing blank frames. /// /// Returns Ok(()) on success, Err on failure. No longer silently falls back /// to a silent video — callers should handle the error explicitly. @@ -53,12 +87,14 @@ pub async fn merge_video_with_audio( silent_video_path, audio_path, output_path ); - // Use audio as the duration reference: - // -map 0:v -map 1:a ensures we take video from first input, audio from second. - // -shortest: truncate to the shorter stream. This is critical because if the - // video renderer produced a longer-than-expected video (due to incorrect duration - // in the HTML), we don't want trailing blank frames polluting the output and - // breaking the final multi-section merge. + // Probe audio duration to use as the authoritative output length. + // Previously we used -shortest which would truncate audio if the video stream + // ended slightly earlier (due to frame duration rounding). Now we explicitly + // set the output duration to match audio, ensuring no audio is lost. + let audio_duration_secs = probe_duration_secs(audio_path)?; + + let duration_str = format!("{:.6}", audio_duration_secs); + let result = Command::new(&ffmpeg_bin) .args([ "-y", @@ -76,7 +112,8 @@ pub async fn merge_video_with_audio( "aac", "-b:a", "192k", - "-shortest", + "-t", + &duration_str, output_path, ]) .stdout(Stdio::null()) diff --git a/src-tauri/src/commands/audio/hyperframes/section_audio.rs b/src-tauri/src/commands/audio/hyperframes/section_audio.rs index e5f540a..52858a6 100644 --- a/src-tauri/src/commands/audio/hyperframes/section_audio.rs +++ b/src-tauri/src/commands/audio/hyperframes/section_audio.rs @@ -210,7 +210,7 @@ pub async fn merge_section_audio( } else { // Normal mode: concat → single loudnorm pass filter.push_str(&format!( - "concat=n={}:v=0:a=1[raw];[raw]loudnorm=I=-16:TP=-1.5:LRA=11[out]", + "concat=n={}:v=0:a=1[raw];[raw]loudnorm=I=-16:TP=-1.5:LRA=11:linear=true[out]", n )); } From 9fb3209a7cd6a1d127d5af2b6abf0bf1cf38eba7 Mon Sep 17 00:00:00 2001 From: iMyth Date: Wed, 19 Aug 2026 10:19:29 +0300 Subject: [PATCH 2/4] style(audio): fix rustfmt formatting in probe_duration_secs --- .../src/commands/audio/hyperframes/ffmpeg_utils.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs b/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs index 7fc31f0..823bce2 100644 --- a/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs +++ b/src-tauri/src/commands/audio/hyperframes/ffmpeg_utils.rs @@ -57,10 +57,12 @@ fn probe_duration_secs(file_path: &str) -> Result { } let stdout = String::from_utf8_lossy(&output.stdout); - stdout - .trim() - .parse::() - .map_err(|_| AppError::FFmpeg(format!("Failed to parse duration from ffprobe for '{}'", file_path))) + stdout.trim().parse::().map_err(|_| { + AppError::FFmpeg(format!( + "Failed to parse duration from ffprobe for '{}'", + file_path + )) + }) } /// Merge a silent video with an audio file using FFmpeg. From 72b9bdbb917e68b9cb7d72aa4c25cbd4625fd789 Mon Sep 17 00:00:00 2001 From: iMyth Date: Tue, 22 Sep 2026 15:07:37 +0300 Subject: [PATCH 3/4] fix(audio): stabilize video export and balance sleep narration --- src-tauri/src/commands/audio/export.rs | 38 ++- src-tauri/src/commands/audio/ffmpeg.rs | 80 ++--- .../src/commands/audio/hyperframes/agent.rs | 121 ++++--- .../src/commands/audio/hyperframes/extract.rs | 39 ++- .../audio/hyperframes/ffmpeg_utils.rs | 147 +++++++-- .../commands/audio/hyperframes/html_fix.rs | 23 +- .../src/commands/audio/hyperframes/render.rs | 191 ++++++++--- .../audio/hyperframes/section_audio.rs | 40 +-- .../audio/hyperframes/section_video.rs | 103 ++---- .../audio/hyperframes/video_merger.rs | 229 ++----------- src-tauri/src/commands/audio/loudness.rs | 312 ++++++++++++++++++ src-tauri/src/commands/audio/mod.rs | 1 + src/i18n/en.json | 2 +- src/i18n/zh.json | 2 +- 14 files changed, 818 insertions(+), 510 deletions(-) create mode 100644 src-tauri/src/commands/audio/loudness.rs diff --git a/src-tauri/src/commands/audio/export.rs b/src-tauri/src/commands/audio/export.rs index 92c9487..1fcf7c1 100644 --- a/src-tauri/src/commands/audio/export.rs +++ b/src-tauri/src/commands/audio/export.rs @@ -100,14 +100,36 @@ pub async fn export_audio_mix( }, ); + let sleep_enabled = sleep_mode.unwrap_or(false); + let gains = if sleep_enabled { + let _ = app.emit( + "mix-progress", + MixProgress { + percent: 15.0, + stage: "正在测量逐句响度".into(), + }, + ); + super::loudness::clip_gains(&audio_paths).await? + } else { + Vec::new() + }; + let intermediate = + super::loudness::TemporaryMedia::beside(std::path::Path::new(&output_path), "wav"); + let mix_path = if sleep_enabled { + intermediate.0.to_string_lossy().into_owned() + } else { + output_path.clone() + }; + // Build FFmpeg command let ffmpeg_args = build_ffmpeg_args( &audio_paths, bgm_path.as_deref(), bgm_volume, &gaps_ms, - &output_path, - sleep_mode.unwrap_or(false), + &mix_path, + sleep_enabled, + &gains, ); let _ = app.emit( @@ -150,6 +172,18 @@ pub async fn export_audio_mix( ))); } + if sleep_enabled { + let _ = app.emit( + "mix-progress", + MixProgress { + percent: 75.0, + stage: "正在平衡睡眠音轨响度".into(), + }, + ); + super::loudness::master_sleep(&intermediate.0, std::path::Path::new(&output_path), false) + .await?; + } + let _ = app.emit( "mix-progress", MixProgress { diff --git a/src-tauri/src/commands/audio/ffmpeg.rs b/src-tauri/src/commands/audio/ffmpeg.rs index 31e98dc..5208492 100644 --- a/src-tauri/src/commands/audio/ffmpeg.rs +++ b/src-tauri/src/commands/audio/ffmpeg.rs @@ -7,9 +7,8 @@ /// Each voice clip is normalized to -16 LUFS (EBU R128) using the `loudnorm` filter /// to ensure consistent volume across TTS fragments before concatenation. /// -/// When `sleep_mode` is true, additional audio processing is applied to create a -/// soothing, sleep-friendly sound: slight pitch reduction, warmth boost (bass EQ), -/// gentle high-frequency rolloff, and reduced overall loudness target (-20 LUFS). +/// When `sleep_mode` is true, level speech using measured fixed gains. The caller masters the complete mix +/// (including BGM) with the shared two-pass sleep processor. pub fn build_ffmpeg_args( audio_paths: &[String], bgm_path: Option<&str>, @@ -17,6 +16,7 @@ pub fn build_ffmpeg_args( gaps_ms: &[i32], output_path: &str, sleep_mode: bool, + gains_db: &[f64], ) -> Vec { let n = audio_paths.len(); let mut args = Vec::new(); @@ -32,44 +32,14 @@ pub fn build_ffmpeg_args( args.push(bgm.to_string()); } - // Single file without BGM or gaps: still normalize for consistency - if n == 1 && bgm_path.is_none() && (gaps_ms.is_empty() || gaps_ms[0] == 0) { - let mut filter = "[0:a]loudnorm=I=-16:TP=-1.5:LRA=11[voice]".to_string(); - if sleep_mode { - // Sleep mode: warm tone + gentle rolloff + quieter target - filter.push_str( - ";[voice]equalizer=f=200:t=q:w=0.8:g=3,\ - equalizer=f=3000:t=q:w=1.0:g=-2,\ - lowpass=f=8000:p=1,\ - loudnorm=I=-20:TP=-2:LRA=7[out]", - ); - args.push("-filter_complex".to_string()); - args.push(filter); - args.push("-map".to_string()); - args.push("[out]".to_string()); - } else { - args.push("-filter_complex".to_string()); - args.push(filter); - args.push("-map".to_string()); - args.push("[voice]".to_string()); - } - args.push(output_path.to_string()); - return args; - } - let mut filter = String::new(); - - // Step 1: Normalize each voice clip to -16 LUFS (EBU R128) - // This ensures consistent volume across TTS fragments without distortion. - // loudnorm parameters: - // I=-16 target integrated loudness (LUFS) - // TP=-1.5 true peak limit (dBTP) — prevents clipping - // LRA=11 loudness range target (LU) — preserves natural dynamics for i in 0..n { - filter.push_str(&format!( - "[{i}:a]loudnorm=I=-16:TP=-1.5:LRA=11[norm{i}];", - i = i - )); + let leveling = if sleep_mode { + format!("volume={:.4}dB", gains_db.get(i).copied().unwrap_or(0.0)) + } else { + "loudnorm=I=-16:TP=-1.5:LRA=11".to_string() + }; + filter.push_str(&format!("[{i}:a]{leveling},aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[norm{i}];")); } // Check if any gap > 0 exists between clips @@ -83,7 +53,7 @@ pub fn build_ffmpeg_args( if gap > 0 { let gap_sec = gap as f64 / 1000.0; filter.push_str(&format!( - "anullsrc=r=44100:cl=stereo[sil{s}];[sil{s}]atrim=0:{dur}[gap{s}];", + "anullsrc=r=48000:cl=stereo[sil{s}];[sil{s}]atrim=0:{dur}[gap{s}];", s = i, dur = gap_sec )); @@ -113,28 +83,18 @@ pub fn build_ffmpeg_args( } } - // Sleep mode: apply soothing audio processing to the concatenated voice - // - equalizer f=200 g=3: gentle bass warmth (adds body/comfort to voice) - // - equalizer f=3000 g=-2: slight upper-mid reduction (less harsh/bright) - // - lowpass f=8000: roll off high frequencies (removes sibilance/sharpness) - // - loudnorm I=-20: quieter target loudness (sleep-appropriate level) - let voice_label = if sleep_mode { - filter.push_str( - ";[voice]equalizer=f=200:t=q:w=0.8:g=3,\ - equalizer=f=3000:t=q:w=1.0:g=-2,\ - lowpass=f=8000:p=1,\ - loudnorm=I=-20:TP=-2:LRA=7[sleepvoice]", - ); - "[sleepvoice]" - } else { - "[voice]" - }; + let voice_label = "[voice]"; if bgm_path.is_some() { let bgm_idx = n; + let mixing = if sleep_mode { + "dropout_transition=0:normalize=0" + } else { + "dropout_transition=2" + }; filter.push_str(&format!( - ";[{}:a]volume={}[bgm];{}[bgm]amix=inputs=2:duration=first:dropout_transition=2[out]", - bgm_idx, bgm_volume, voice_label + ";[{}:a]volume={}[bgm];{}[bgm]amix=inputs=2:duration=first:{}[out]", + bgm_idx, bgm_volume, voice_label, mixing )); args.push("-filter_complex".to_string()); args.push(filter); @@ -147,6 +107,10 @@ pub fn build_ffmpeg_args( args.push(voice_label.to_string()); } + if sleep_mode { + // Floating-point intermediate avoids clipping before final mastering. + args.extend(["-c:a".to_string(), "pcm_f32le".to_string()]); + } args.push(output_path.to_string()); args } diff --git a/src-tauri/src/commands/audio/hyperframes/agent.rs b/src-tauri/src/commands/audio/hyperframes/agent.rs index 7188424..934d72a 100644 --- a/src-tauri/src/commands/audio/hyperframes/agent.rs +++ b/src-tauri/src/commands/audio/hyperframes/agent.rs @@ -104,83 +104,76 @@ pub async fn generate_with_agent( report("agent_generating"); - // Retry up to 2 times on extraction failure (LLM may return malformed output). - let max_attempts = 2; - let mut last_error: Option = None; - let mut html = String::new(); - - for attempt in 1..=max_attempts { - let start = std::time::Instant::now(); - info!( - "[Agent] Sending prompt to LLM (model: {}, attempt {}/{})...", - config.model, attempt, max_attempts - ); - + // Retry the entire extraction / post-processing / validation pipeline. + // A failed validation must never be published as a successful composition. + let mut last_error = String::new(); + for attempt in 1..=2 { + let prompt = if attempt == 1 { + user_prompt.clone() + } else { + report("retrying"); + format!("{user_prompt}\n\nThe previous attempt failed: {last_error}\nGenerate the entire corrected HTML document, including and . Simplify the visuals if needed to fit the output limit. Return HTML only.") + }; + info!("[Agent] Generating composition, attempt {}", attempt); let response = agent - .prompt(&user_prompt) + .prompt(&prompt) .max_turns(1) .await .map_err(|e| format!("Agent execution failed: {e}"))?; - info!("[Agent] LLM response received in {:?}", start.elapsed()); report("extracting_html"); - - // Log the response for debugging — use char boundary safe truncation - info!("[Agent] Response length: {} chars", response.len()); - let preview_end = response - .char_indices() - .take_while(|(i, _)| *i < 200) - .last() - .map(|(i, c)| i + c.len_utf8()) - .unwrap_or(0); - info!("[Agent] Response preview: {}", &response[..preview_end]); - - match extract_html(&response) { - Ok(extracted) => { - html = extracted; - last_error = None; - break; + match prepare_composition(&response, entries, total_duration) { + Ok(html) => { + report("agent_done"); + return Ok(html); } - Err(e) => { - info!( - "[Agent] HTML extraction failed on attempt {}: {}", - attempt, e - ); - last_error = Some(e); - if attempt < max_attempts { - info!("[Agent] Retrying LLM generation..."); - report("retrying"); - } + Err(error) => { + info!("[Agent] Attempt {} rejected: {}", attempt, error); + last_error = error; } } } + Err(format!( + "Composition generation failed after 2 attempts: {last_error}" + )) +} - if let Some(err) = last_error { - return Err(err); - } - - // Post-process: apply safety-net fixes in dependency order +fn prepare_composition( + response: &str, + entries: &[TimelineEntry], + duration: f64, +) -> Result { + let mut html = extract_html(response)?; html = fix_css_font_variables(&html); html = sanitize_unsupported_fonts(&html); - html = ensure_hyperframes_interfaces(&html, total_duration); - html = ensure_root_duration(&html, total_duration); + html = ensure_hyperframes_interfaces(&html, duration); + html = ensure_root_duration(&html, duration); html = ensure_clip_timing(&html, entries); - html = clamp_overflow_clips(&html, total_duration); - - // Final validation - match validate_composition(&html) { - Ok(()) => { - info!("[Agent] Generation complete, validation passed"); - report("agent_done"); - Ok(html) - } - Err(errors) => { - info!( - "[Agent] Generation complete with {} validation warnings", - errors.len() - ); - report("agent_done_with_warnings"); - Ok(html) - } + html = clamp_overflow_clips(&html, duration); + validate_composition(&html).map_err(|errors| errors.join("\n"))?; + Ok(html) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_complete_document_without_composition() { + assert!(prepare_composition( + "hello", + &[], + 5.0 + ) + .is_err()); + } + + #[test] + fn rejects_truncation_before_injecting_safety_net() { + assert!( + prepare_composition("