diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 3a315b8..aa7e33c 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -4,7 +4,6 @@ on: push: branches: [main] pull_request: - branches: [main] jobs: check: @@ -20,6 +19,7 @@ jobs: targets: '' runs-on: ${{ matrix.platform }} + timeout-minutes: 45 steps: - name: Checkout repository @@ -27,15 +27,8 @@ jobs: - name: Install Linux dependencies if: matrix.platform == 'ubuntu-22.04' - run: | - sudo apt-get update - sudo apt-get install -y \ - libasound2-dev \ - libwebkit2gtk-4.1-dev \ - libappindicator3-dev \ - librsvg2-dev \ - libssl-dev \ - pkg-config + timeout-minutes: 15 + run: bash scripts/install-linux-deps.sh - name: Install Rust stable uses: dtolnay/rust-toolchain@master diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4612c80..fe628d5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -55,16 +55,8 @@ jobs: - name: Install Linux dependencies if: matrix.platform == 'ubuntu-22.04' - run: | - sudo apt-get update - sudo apt-get install -y \ - libasound2-dev \ - libwebkit2gtk-4.1-dev \ - libappindicator3-dev \ - librsvg2-dev \ - patchelf \ - libssl-dev \ - pkg-config + timeout-minutes: 15 + run: bash scripts/install-linux-deps.sh patchelf - name: Add macOS targets if: matrix.platform == 'macos-latest' diff --git a/scripts/install-linux-deps.sh b/scripts/install-linux-deps.sh new file mode 100644 index 0000000..d95880a --- /dev/null +++ b/scripts/install-linux-deps.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +# The hosted Jammy runner's Azure mirror can stall for hours. Replace only that +# Ubuntu endpoint, including entries in the runner's mirror list and deb822 files. +shopt -s nullglob +sources=(/etc/apt/sources.list /etc/apt/apt-mirrors.txt /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources) +for source in "${sources[@]}"; do + if [[ -f "$source" ]]; then + sudo sed -i \ + -e 's|http://azure.archive.ubuntu.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' \ + -e 's|https://azure.archive.ubuntu.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' \ + "$source" + fi +done + +apt_options=( + -o Acquire::Retries=3 + -o Acquire::http::Timeout=30 + -o Acquire::https::Timeout=30 +) +# Fail on incomplete index downloads instead of proceeding with stale indexes. +sudo apt-get "${apt_options[@]}" -o APT::Update::Error-Mode=any update +sudo apt-get "${apt_options[@]}" install -y --no-install-recommends \ + libasound2-dev \ + libwebkit2gtk-4.1-dev \ + libappindicator3-dev \ + librsvg2-dev \ + libssl-dev \ + pkg-config \ + "$@" 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("