Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

refactor(editor): drop auto-mastering so preview and export match

Etienne Lescot28d8f2f7fedd
diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rs
index adfeb0906..fb6e3da21 100644
--- a/crates/compositor/src/audio.rs
+++ b/crates/compositor/src/audio.rs
@@ -27,12 +27,22 @@ const PASSTHROUGH_EPSILON: f64 = 1e-3;
pub type PlanarPcm = Vec<Vec<f32>>;
-/// Apply the editor's signed sync offset and fast voice-oriented mastering.
+/// Apply the editor's output trim and signed sync offset to the assembled timeline.
///
-/// The automatic path is deliberately deterministic and dependency-free: an 80 Hz high-pass
-/// removes desk/room rumble, a linked-stereo 3:1 compressor controls speech peaks, and a final
-/// RMS/peak pass raises intelligibility without clipping. Linking the envelope preserves the
-/// stereo image. The result stays the same length so video and following clips cannot drift.
+/// Both stages are stateless on purpose. The editor preview plays the untouched source file
+/// (seeked), while this runs on the assembled timeline — trimmed, speed-adjusted, concatenated
+/// — so the two see different signals. A linear gain and a whole-sample delay are the only
+/// operations that land identically on both, which is what lets the editor claim that what you
+/// hear is what you export.
+///
+/// That rules out the obvious next feature. A filter or a compressor carries state across
+/// cuts here and not in the preview; a loudness normaliser is worse still, because its makeup
+/// is a single scalar measured over the whole assembled programme, which the preview never
+/// holds and which changes with every trim. Adding either back means either an offline preview
+/// render or an accepted, documented divergence — not a quiet extra stage in this function.
+///
+/// Bounds mirror `AUDIO_GAIN_DB_LIMIT` / `AUDIO_OFFSET_MS_LIMIT` in editorSettings.ts. The
+/// result stays the same length so video and following clips cannot drift.
pub fn finish_audio(mut pcm: PlanarPcm, settings: SceneAudio) -> PlanarPcm {
let samples = pcm.first().map(Vec::len).unwrap_or(0);
if samples == 0 {
@@ -42,76 +52,12 @@ pub fn finish_audio(mut pcm: PlanarPcm, settings: SceneAudio) -> PlanarPcm {
channel.resize(samples, 0.0);
}
- if settings.auto_master {
- let cutoff_hz = 80.0f32;
- let dt = 1.0 / AUDIO_OUTPUT_SAMPLE_RATE as f32;
- let rc = 1.0 / (2.0 * PI * cutoff_hz);
- let alpha = rc / (rc + dt);
- for channel in pcm.iter_mut() {
- let mut previous_input = 0.0f32;
- let mut previous_output = 0.0f32;
- for sample in channel.iter_mut() {
- let input = *sample;
- let output = alpha * (previous_output + input - previous_input);
- *sample = output;
- previous_input = input;
- previous_output = output;
- }
- }
-
- let threshold_db = -18.0f32;
- let ratio = 3.0f32;
- let attack = (-1.0 / (0.010 * AUDIO_OUTPUT_SAMPLE_RATE as f32)).exp();
- let release = (-1.0 / (0.120 * AUDIO_OUTPUT_SAMPLE_RATE as f32)).exp();
- let mut envelope = 0.0f32;
- for index in 0..samples {
- let peak = pcm
- .iter()
- .map(|channel| channel[index].abs())
- .fold(0.0f32, f32::max);
- let coefficient = if peak > envelope { attack } else { release };
- envelope = coefficient * envelope + (1.0 - coefficient) * peak;
- let level_db = 20.0 * envelope.max(1e-9).log10();
- let reduction_db = if level_db > threshold_db {
- (level_db - threshold_db) * (1.0 - 1.0 / ratio)
- } else {
- 0.0
- };
- let reduction = 10.0f32.powf(-reduction_db / 20.0);
- for channel in pcm.iter_mut() {
- channel[index] *= reduction;
- }
- }
-
- let mut sum_squares = 0.0f64;
- let mut count = 0usize;
- let mut peak = 0.0f32;
- for &sample in pcm.iter().flatten() {
- peak = peak.max(sample.abs());
- if sample.abs() > 1e-5 {
- sum_squares += (sample as f64) * (sample as f64);
- count += 1;
- }
- }
- if count > 0 && peak > 0.0 {
- let rms = (sum_squares / count as f64).sqrt() as f32;
- let target_rms = 10.0f32.powf(-16.0 / 20.0);
- let peak_ceiling = 10.0f32.powf(-1.0 / 20.0);
- let makeup = (target_rms / rms.max(1e-9))
- .min(peak_ceiling / peak)
- .clamp(0.1, 4.0);
- for sample in pcm.iter_mut().flatten() {
- *sample *= makeup;
- }
- }
- }
-
- let trim = 10.0f32.powf(settings.gain_db.clamp(-24.0, 18.0) / 20.0);
+ let trim = 10.0f32.powf(settings.gain_db.clamp(-12.0, 12.0) / 20.0);
for sample in pcm.iter_mut().flatten() {
*sample = (*sample * trim).clamp(-1.0, 1.0);
}
- let shift = ((settings.offset_ms.clamp(-2_000.0, 2_000.0) / 1_000.0)
+ let shift = ((settings.offset_ms.clamp(-500.0, 500.0) / 1_000.0)
* AUDIO_OUTPUT_SAMPLE_RATE as f64)
.round() as i64;
if shift == 0 {
@@ -1178,59 +1124,65 @@ mod tests {
let settings = SceneAudio {
offset_ms: 1000.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64,
gain_db: 0.0,
- auto_master: false,
};
- let delayed = finish_audio(planar(&[1.0, 2.0, 3.0]), settings);
- assert_eq!(delayed[0], vec![0.0, 1.0, 1.0]);
+ // Values stay inside [-1, 1] so this asserts the shift, not the output clamp.
+ let delayed = finish_audio(planar(&[0.1, 0.2, 0.3]), settings);
+ assert_eq!(delayed[0], vec![0.0, 0.1, 0.2]);
let advanced = finish_audio(
- planar(&[1.0, 0.5, 0.25]),
+ planar(&[0.1, 0.2, 0.3]),
SceneAudio {
offset_ms: -1000.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64,
..settings
},
);
- assert_eq!(advanced[0], vec![0.5, 0.25, 0.0]);
+ assert_eq!(advanced[0], vec![0.2, 0.3, 0.0]);
+ }
+
+ /// The gain must be the SAME scalar the editor preview feeds its GainNode
+ /// (`10 ** (dB / 20)`), because that identity is the whole parity guarantee: nothing
+ /// else stands between what the editor plays and what this writes.
+ #[test]
+ fn output_trim_is_the_same_scalar_the_preview_applies() {
+ for gain_db in [-12.0f32, -6.0206, 0.0, 6.0206, 12.0] {
+ let result = finish_audio(
+ planar(&[0.25, -0.25]),
+ SceneAudio {
+ offset_ms: 0.0,
+ gain_db,
+ },
+ );
+ let expected = (0.25 * 10.0f32.powf(gain_db / 20.0)).clamp(-1.0, 1.0);
+ assert!(
+ (result[0][0] - expected).abs() < 1e-6,
+ "gain {gain_db} dB: got {}, want {expected}",
+ result[0][0]
+ );
+ assert!((result[0][1] + expected).abs() < 1e-6);
+ }
}
#[test]
- fn manual_gain_is_applied_when_auto_master_is_off() {
+ fn out_of_range_settings_are_clamped_to_the_editor_bounds() {
+ // A hand-edited project (or a future UI change) must not be able to ask for an
+ // offset or a gain the sliders cannot display.
let result = finish_audio(
- planar(&[0.25, -0.25]),
+ planar(&[0.5, 0.5]),
SceneAudio {
- offset_ms: 0.0,
- gain_db: 6.0206,
- auto_master: false,
+ offset_ms: 9_999.0,
+ gain_db: 99.0,
},
);
- assert!((result[0][0] - 0.5).abs() < 1e-4);
- assert!((result[0][1] + 0.5).abs() < 1e-4);
- }
+ assert_eq!(result[0], vec![0.0, 0.0], "offset clamps to 500 ms, not 10 s");
- #[test]
- fn auto_master_removes_dc_and_respects_peak_ceiling() {
- let mut input = vec![0.2f32; AUDIO_OUTPUT_SAMPLE_RATE as usize / 2];
- for index in (0..input.len()).step_by(400) {
- input[index] = 1.0;
- }
- let result = finish_audio(
- planar(&input),
+ let quiet = finish_audio(
+ planar(&[0.5]),
SceneAudio {
offset_ms: 0.0,
- gain_db: 0.0,
- auto_master: true,
+ gain_db: -99.0,
},
);
- let peak = result
- .iter()
- .flatten()
- .fold(0.0f32, |value, sample| value.max(sample.abs()));
- let tail_mean = result[0][result[0].len() / 2..]
- .iter()
- .copied()
- .sum::<f32>()
- / (result[0].len() / 2) as f32;
- assert!(peak <= 10.0f32.powf(-1.0 / 20.0) + 1e-5);
- assert!(tail_mean.abs() < 0.01);
+ let floor = 0.5 * 10.0f32.powf(-12.0 / 20.0);
+ assert!((quiet[0][0] - floor).abs() < 1e-6);
}
}
diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs
index 34209c286..538bcb06a 100644
--- a/crates/compositor/src/scene.rs
+++ b/crates/compositor/src/scene.rs
@@ -395,22 +395,19 @@ pub struct SceneCrop {
pub height: f32,
}
-#[derive(Debug, Clone, Copy, Deserialize)]
+/// Audio finishing. Deliberately limited to a linear gain and a signed delay — the two
+/// operations the editor preview can apply identically to the source file it plays. See
+/// `audio::finish_audio` before adding a field here.
+///
+/// Every field carries `#[serde(default)]`: a payload from a build that predates one of them
+/// must degrade to "that stage is neutral", not fail the whole scene.
+#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SceneAudio {
+ #[serde(default)]
pub offset_ms: f64,
+ #[serde(default)]
pub gain_db: f32,
- pub auto_master: bool,
-}
-
-impl Default for SceneAudio {
- fn default() -> Self {
- Self {
- offset_ms: 0.0,
- gain_db: 0.0,
- auto_master: false,
- }
- }
}
#[derive(Debug, Clone, Copy, Deserialize)]
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 81e9d57f8..6994c7578 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -42,6 +42,7 @@ import type {
AxcutTrimRange,
AxcutWord,
} from "@/lib/ai-edition/schema";
+import { AUDIO_GAIN_DB_LIMIT, AUDIO_OFFSET_MS_LIMIT } from "@/lib/ai-edition/store/editorSettings";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import {
@@ -1741,20 +1742,12 @@ export function AudioPane() {
const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
return (
<Pane title={ts("audio.title")} icon={<AudioLines size={14} />} helpText={ts("audio.help")}>
- <div className={styles.paneRow}>
- <span className="label">{ts("audio.autoMaster")}</span>
- <Toggle
- checked={settings.audioAutoMaster}
- disabled={!hasDocument}
- onChange={(value) => void set({ audioAutoMaster: value })}
- />
- </div>
<div className={styles.sliderGrid}>
<SliderCell
label={ts("audio.syncOffset")}
value={settings.audioOffsetMs}
- min={-500}
- max={500}
+ min={-AUDIO_OFFSET_MS_LIMIT}
+ max={AUDIO_OFFSET_MS_LIMIT}
step={1}
suffix=" ms"
disabled={!hasDocument}
@@ -1764,8 +1757,8 @@ export function AudioPane() {
<SliderCell
label={ts("audio.outputGain")}
value={settings.audioGainDb}
- min={-12}
- max={12}
+ min={-AUDIO_GAIN_DB_LIMIT}
+ max={AUDIO_GAIN_DB_LIMIT}
step={0.5}
decimals={1}
suffix=" dB"
@@ -1778,7 +1771,7 @@ export function AudioPane() {
type="button"
className={styles.secondaryBtn}
disabled={!hasDocument}
- onClick={() => void set({ audioOffsetMs: 0, audioGainDb: 0, audioAutoMaster: true })}
+ onClick={() => void set({ audioOffsetMs: 0, audioGainDb: 0 })}
>
{ts("audio.reset")}
</button>
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 0f3691959..14253bf61 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -55,15 +55,23 @@ export function resolveAudioPreviewTime(
interface PreviewAudioGraph {
context: AudioContext;
- highpasses: BiquadFilterNode[];
- compressor: DynamicsCompressorNode;
gain: GainNode;
}
+/**
+ * The preview's ONLY audio processing is the output trim, and that is deliberate: it is
+ * the same `10 ** (dB / 20)` scalar `finish_audio` applies natively, so what the editor
+ * plays is what the export writes.
+ *
+ * Nothing with state belongs here. The export runs on the assembled timeline (trimmed,
+ * speed-adjusted, concatenated); the preview runs on the untouched source file, seeked.
+ * A filter or a compressor would see a different signal on each side and drift — and an
+ * offline stage measured over the whole programme (a loudness normaliser) cannot exist
+ * here at all, because the preview never holds that programme.
+ */
function applyPreviewAudioSettings(
graph: PreviewAudioGraph | null,
elements: Array<HTMLAudioElement | null>,
- autoMaster: boolean,
gainDb: number,
): void {
const outputGain = 10 ** (gainDb / 20);
@@ -73,15 +81,6 @@ function applyPreviewAudioSettings(
}
return;
}
- for (const filter of graph.highpasses) {
- filter.frequency.value = autoMaster ? 80 : 20;
- filter.Q.value = 0.707;
- }
- graph.compressor.threshold.value = autoMaster ? -18 : 0;
- graph.compressor.knee.value = autoMaster ? 12 : 0;
- graph.compressor.ratio.value = autoMaster ? 3 : 1;
- graph.compressor.attack.value = 0.01;
- graph.compressor.release.value = 0.12;
graph.gain.gain.value = outputGain;
}
@@ -192,16 +191,10 @@ export function VirtualPreview({
const [supplementalAudioEl, setSupplementalAudioEl] = useState<HTMLAudioElement | null>(null);
const [supplementalAudioSrc, setSupplementalAudioSrc] = useState<string | null>(null);
const [audioProbeComplete, setAudioProbeComplete] = useState(false);
- const audioSettingsRef = useRef({
- autoMaster: settings.audioAutoMaster,
- gainDb: settings.audioGainDb,
- });
+ const audioGainDbRef = useRef(settings.audioGainDb);
useEffect(() => {
- audioSettingsRef.current = {
- autoMaster: settings.audioAutoMaster,
- gainDb: settings.audioGainDb,
- };
- }, [settings.audioAutoMaster, settings.audioGainDb]);
+ audioGainDbRef.current = settings.audioGainDb;
+ }, [settings.audioGainDb]);
const audioContextRef = useRef<AudioContext | null>(null);
const audioContextCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const audioSourceNodesRef = useRef(new WeakMap<HTMLAudioElement, MediaElementAudioSourceNode>());
@@ -271,69 +264,62 @@ export function VirtualPreview({
};
}, [activeSource?.filePath]);
- // Route preview audio through the same fast voice-oriented controls the native export uses.
- // The primary media element carries track 1; on macOS the existing IPC helper extracts track 2
- // (normally the microphone) so both are audible instead of Chromium silently choosing one.
+ // Sum the audio elements into one gain node so the output trim can boost past 0 dB,
+ // which `element.volume` cannot do. The primary media element carries track 1; on macOS
+ // the existing IPC helper extracts track 2 (normally the microphone) so both are audible
+ // instead of Chromium silently choosing one.
useEffect(() => {
if (!primaryAudioEl || !audioProbeComplete) return;
if (supplementalAudioSrc && !supplementalAudioEl) return;
- const connectedSources: MediaElementAudioSourceNode[] = [];
- const highpasses: BiquadFilterNode[] = [];
- let compressor: DynamicsCompressorNode | null = null;
- let gain: GainNode | null = null;
- try {
- let context = audioContextRef.current;
- if (!context || context.state === "closed") {
- context = new AudioContext();
- audioContextRef.current = context;
- audioSourceNodesRef.current = new WeakMap();
+ const elements = [primaryAudioEl, supplementalAudioEl].filter(
+ (value): value is HTMLAudioElement => Boolean(value),
+ );
+ const graph = ((): PreviewAudioGraph | null => {
+ try {
+ let context = audioContextRef.current;
+ if (!context || context.state === "closed") {
+ context = new AudioContext();
+ audioContextRef.current = context;
+ audioSourceNodesRef.current = new WeakMap();
+ }
+ const gain = context.createGain();
+ gain.connect(context.destination);
+ return { context, gain };
+ } catch {
+ return null;
}
- compressor = context.createDynamicsCompressor();
- gain = context.createGain();
- compressor.connect(gain).connect(context.destination);
- for (const element of [primaryAudioEl, supplementalAudioEl].filter(
- (value): value is HTMLAudioElement => Boolean(value),
- )) {
+ })();
+ if (!graph) {
+ // WebAudio can be unavailable in unit tests or under a denied audio policy. No source
+ // node was created, so `volume` still reaches the output — capped at 0 dB.
+ applyPreviewAudioSettings(null, elements, audioGainDbRef.current);
+ return;
+ }
+
+ const connectedSources: MediaElementAudioSourceNode[] = [];
+ for (const element of elements) {
+ try {
let source = audioSourceNodesRef.current.get(element);
if (!source) {
- source = context.createMediaElementSource(element);
+ source = graph.context.createMediaElementSource(element);
audioSourceNodesRef.current.set(element, source);
}
source.disconnect();
- const highpass = context.createBiquadFilter();
- highpass.type = "highpass";
- source.connect(highpass).connect(compressor);
+ source.connect(graph.gain);
connectedSources.push(source);
- highpasses.push(highpass);
+ } catch {
+ // Routing THIS element failed; leave the others alone. Once
+ // createMediaElementSource has run for an element its audio no longer reaches
+ // the default output, so tearing the whole graph down here would mute the
+ // preview outright rather than degrade it.
}
- const graph = { context, highpasses, compressor, gain };
- audioGraphRef.current = graph;
- applyPreviewAudioSettings(
- graph,
- [primaryAudioEl, supplementalAudioEl],
- audioSettingsRef.current.autoMaster,
- audioSettingsRef.current.gainDb,
- );
- } catch {
- // WebAudio can be unavailable in unit tests or under a denied audio policy. The media
- // elements remain usable; the sync loop below still applies offset and playback state.
- for (const source of connectedSources) source.disconnect();
- for (const highpass of highpasses) highpass.disconnect();
- compressor?.disconnect();
- gain?.disconnect();
- applyPreviewAudioSettings(
- null,
- [primaryAudioEl, supplementalAudioEl],
- audioSettingsRef.current.autoMaster,
- audioSettingsRef.current.gainDb,
- );
}
+ audioGraphRef.current = graph;
+ applyPreviewAudioSettings(graph, elements, audioGainDbRef.current);
return () => {
audioGraphRef.current = null;
for (const source of connectedSources) source.disconnect();
- for (const highpass of highpasses) highpass.disconnect();
- compressor?.disconnect();
- gain?.disconnect();
+ graph.gain.disconnect();
};
}, [primaryAudioEl, supplementalAudioEl, supplementalAudioSrc, audioProbeComplete]);
@@ -361,10 +347,9 @@ export function VirtualPreview({
applyPreviewAudioSettings(
audioGraphRef.current,
[primaryAudioRef.current, supplementalAudioRef.current],
- settings.audioAutoMaster,
settings.audioGainDb,
);
- }, [settings.audioAutoMaster, settings.audioGainDb]);
+ }, [settings.audioGainDb]);
const setPrimaryAudioElement = useCallback((element: HTMLAudioElement | null) => {
primaryAudioRef.current = element;
diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json
index 34969e119..a0663f78e 100644
--- a/src/i18n/locales/ar/settings.json
+++ b/src/i18n/locales/ar/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "الصوت",
- "autoMaster": "تحسين الصوت تلقائيًا",
"syncOffset": "إزاحة المزامنة",
"outputGain": "ضبط مستوى الإخراج",
"reset": "إعادة ضبط الصوت",
- "help": "نظّف ووازن صوت الكلام تلقائيًا، ثم اضبط التوقيت والمستوى بدقة."
+ "help": "اضبط توقيت الصوت ومستوى الإخراج. كلاهما يُطبَّق بالطريقة نفسها في المعاينة وعند التصدير."
}
}
diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json
index dc10fa46e..f2dedd8f0 100644
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@ -67,8 +67,7 @@
},
"audio": {
"title": "Audio",
- "help": "Nudge audio into sync, adjust output trim, and apply automatic speech-focused EQ, compression, and loudness finishing.",
- "autoMaster": "Auto master voice",
+ "help": "Nudge audio timing and trim the output level. Both apply identically in the preview and the export.",
"syncOffset": "Sync offset",
"outputGain": "Output trim",
"reset": "Reset audio"
diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json
index 83a37016f..8b61142c0 100644
--- a/src/i18n/locales/es/settings.json
+++ b/src/i18n/locales/es/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Audio",
- "autoMaster": "Mejora automática de voz",
"syncOffset": "Desfase de sincronización",
"outputGain": "Ajuste de salida",
"reset": "Restablecer audio",
- "help": "Limpia y equilibra la voz automáticamente y luego ajusta con precisión el tiempo y el nivel."
+ "help": "Ajusta la sincronización del audio y el nivel de salida. Ambos se aplican igual en la vista previa y en la exportación."
}
}
diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json
index 7079cc5a5..bf76bdd21 100644
--- a/src/i18n/locales/fr/settings.json
+++ b/src/i18n/locales/fr/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Audio",
- "autoMaster": "Mastering vocal automatique",
"syncOffset": "Décalage de synchronisation",
"outputGain": "Niveau de sortie",
"reset": "Réinitialiser l’audio",
- "help": "Nettoyez et équilibrez automatiquement la voix, puis ajustez précisément la synchronisation et le niveau."
+ "help": "Ajustez le calage de l’audio et le niveau de sortie. Les deux s’appliquent à l’identique dans l’aperçu et à l’export."
}
}
diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json
index 969262eb3..7e5b160be 100644
--- a/src/i18n/locales/it/settings.json
+++ b/src/i18n/locales/it/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Audio",
- "autoMaster": "Mastering vocale automatico",
"syncOffset": "Offset sincronizzazione",
"outputGain": "Livello di uscita",
"reset": "Reimposta audio",
- "help": "Pulisci e bilancia automaticamente la voce, quindi regola con precisione sincronizzazione e livello."
+ "help": "Regola la sincronizzazione dell’audio e il livello di uscita. Entrambi si applicano allo stesso modo nell’anteprima e nell’esportazione."
}
}
diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json
index cb77c87e6..8fa1ba767 100644
--- a/src/i18n/locales/ja-JP/settings.json
+++ b/src/i18n/locales/ja-JP/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "オーディオ",
- "autoMaster": "音声を自動マスタリング",
"syncOffset": "同期オフセット",
"outputGain": "出力レベル",
"reset": "オーディオをリセット",
- "help": "音声を自動的に整えてバランスを調整し、タイミングと音量を細かく仕上げます。"
+ "help": "音声のタイミングと出力レベルを調整します。どちらもプレビューと書き出しで同じように適用されます。"
}
}
diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json
index 0b6c7eaa6..71718d49a 100644
--- a/src/i18n/locales/ko-KR/settings.json
+++ b/src/i18n/locales/ko-KR/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "오디오",
- "autoMaster": "음성 자동 마스터링",
"syncOffset": "동기화 오프셋",
"outputGain": "출력 레벨",
"reset": "오디오 재설정",
- "help": "음성을 자동으로 정리하고 균형을 맞춘 뒤 타이밍과 레벨을 세밀하게 조정합니다."
+ "help": "오디오 타이밍과 출력 레벨을 조정합니다. 둘 다 미리보기와 내보내기에 동일하게 적용됩니다."
}
}
diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json
index 21e28eed2..2171ddf64 100644
--- a/src/i18n/locales/pt-BR/settings.json
+++ b/src/i18n/locales/pt-BR/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Áudio",
- "autoMaster": "Masterização automática de voz",
"syncOffset": "Deslocamento de sincronização",
"outputGain": "Nível de saída",
"reset": "Redefinir áudio",
- "help": "Limpe e equilibre a voz automaticamente e depois ajuste com precisão o tempo e o nível."
+ "help": "Ajuste a sincronização do áudio e o nível de saída. Ambos se aplicam da mesma forma na prévia e na exportação."
}
}
diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json
index 6d11ad9be..4b305f08b 100644
--- a/src/i18n/locales/ru/settings.json
+++ b/src/i18n/locales/ru/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Аудио",
- "autoMaster": "Автоматический мастеринг голоса",
"syncOffset": "Смещение синхронизации",
"outputGain": "Уровень выхода",
"reset": "Сбросить аудио",
- "help": "Автоматически очистите и сбалансируйте голос, затем точно настройте синхронизацию и уровень."
+ "help": "Настройте синхронизацию звука и уровень на выходе. Оба параметра одинаково применяются в предпросмотре и при экспорте."
}
}
diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json
index d6994dfcb..f334f8911 100644
--- a/src/i18n/locales/tr/settings.json
+++ b/src/i18n/locales/tr/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Ses",
- "autoMaster": "Otomatik ses mastering",
"syncOffset": "Senkronizasyon kaydırması",
"outputGain": "Çıkış seviyesi",
"reset": "Sesi sıfırla",
- "help": "Konuşma sesini otomatik olarak temizleyip dengeleyin, ardından zamanlama ve seviyeyi hassas biçimde ayarlayın."
+ "help": "Ses zamanlamasını ve çıkış seviyesini ayarlayın. İkisi de önizlemede ve dışa aktarmada aynı şekilde uygulanır."
}
}
diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json
index 66a32b75c..21ac6ce1b 100644
--- a/src/i18n/locales/vi/settings.json
+++ b/src/i18n/locales/vi/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "Âm thanh",
- "autoMaster": "Tự động hoàn thiện giọng nói",
"syncOffset": "Độ lệch đồng bộ",
"outputGain": "Mức đầu ra",
"reset": "Đặt lại âm thanh",
- "help": "Tự động làm sạch và cân bằng giọng nói, sau đó tinh chỉnh thời gian và mức âm lượng."
+ "help": "Điều chỉnh thời điểm âm thanh và mức đầu ra. Cả hai được áp dụng giống hệt nhau trong bản xem trước và khi xuất."
}
}
diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json
index 518091e5e..f813816d7 100644
--- a/src/i18n/locales/zh-CN/settings.json
+++ b/src/i18n/locales/zh-CN/settings.json
@@ -306,10 +306,9 @@
},
"audio": {
"title": "音频",
- "autoMaster": "自动优化人声",
"syncOffset": "同步偏移",
"outputGain": "输出电平",
"reset": "重置音频",
- "help": "自动清理并平衡人声,然后精细调整时间和音量。"
+ "help": "调整音频同步和输出电平。两者在预览和导出中的效果完全一致。"
}
}
diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json
index 4596c4204..1c8ada1a3 100644
--- a/src/i18n/locales/zh-TW/settings.json
+++ b/src/i18n/locales/zh-TW/settings.json
@@ -307,10 +307,9 @@
},
"audio": {
"title": "音訊",
- "autoMaster": "自動優化人聲",
"syncOffset": "同步偏移",
"outputGain": "輸出音量",
"reset": "重設音訊",
- "help": "自動清理並平衡人聲,再精細調整時間與音量。"
+ "help": "調整音訊同步與輸出電平。兩者在預覽與匯出中的效果完全一致。"
}
}
diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.ts
index 3d4f77d0d..21a2eb267 100644
--- a/src/lib/ai-edition/store/editorSettings.ts
+++ b/src/lib/ai-edition/store/editorSettings.ts
@@ -38,6 +38,12 @@ import type { AxcutDocument } from "../schema";
// for the same reason (their canonical types live in lib/wallpaper and
// lib/cursor/cursorThemes as the source of truth).
+/** Audio finishing bounds, shared by the sliders, this store and `finish_audio` (Rust).
+ * Both settings are deliberately parity-safe: a pure delay and a linear gain behave
+ * identically on the preview's source file and on the export's assembled timeline. */
+export const AUDIO_OFFSET_MS_LIMIT = 500;
+export const AUDIO_GAIN_DB_LIMIT = 12;
+
export interface EditorSettingsSnapshot {
wallpaper: string;
aspectRatio: AspectRatio;
@@ -57,7 +63,6 @@ export interface EditorSettingsSnapshot {
/** Positive values move audio later; negative values advance it. */
audioOffsetMs: number;
audioGainDb: number;
- audioAutoMaster: boolean;
cursor: CursorVisualSettings;
cursorShow: boolean;
cursorTheme: string;
@@ -87,7 +92,6 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettingsSnapshot = {
webcamCropRegion: DEFAULT_CROP_REGION,
audioOffsetMs: 0,
audioGainDb: 0,
- audioAutoMaster: true,
cursor: {
size: DEFAULT_CURSOR_SIZE,
smoothing: DEFAULT_CURSOR_SMOOTHING,
@@ -118,7 +122,6 @@ interface LegacyShape {
webcamCropRegion?: CropRegion;
audioOffsetMs?: number;
audioGainDb?: number;
- audioAutoMaster?: boolean;
cursorSize?: number;
cursorSmoothing?: number;
cursorMotionBlur?: number;
@@ -174,9 +177,17 @@ export function getEditorSettings(doc: AxcutDocument | null | undefined): Editor
webcamSizePreset: num(legacy?.webcamSizePreset, DEFAULT_EDITOR_SETTINGS.webcamSizePreset),
webcamPosition: normaliseWebcamPosition(legacy?.webcamPosition),
webcamCropRegion: normaliseCropRegion(legacy?.webcamCropRegion),
- audioOffsetMs: Math.min(2_000, Math.max(-2_000, num(legacy?.audioOffsetMs, 0))),
- audioGainDb: Math.min(18, Math.max(-24, num(legacy?.audioGainDb, 0))),
- audioAutoMaster: bool(legacy?.audioAutoMaster, true),
+ // Same bounds the sliders offer and the native `finish_audio` clamps to. Three
+ // different ranges for one value is how a project ends up exporting an offset the
+ // UI cannot display.
+ audioOffsetMs: Math.min(
+ AUDIO_OFFSET_MS_LIMIT,
+ Math.max(-AUDIO_OFFSET_MS_LIMIT, num(legacy?.audioOffsetMs, 0)),
+ ),
+ audioGainDb: Math.min(
+ AUDIO_GAIN_DB_LIMIT,
+ Math.max(-AUDIO_GAIN_DB_LIMIT, num(legacy?.audioGainDb, 0)),
+ ),
cursor,
cursorShow: bool(legacy?.cursorShow, DEFAULT_EDITOR_SETTINGS.cursorShow),
cursorTheme: str(legacy?.cursorTheme, DEFAULT_EDITOR_SETTINGS.cursorTheme),
@@ -201,7 +212,6 @@ export interface EditorSettingsPatch {
webcamCropRegion?: CropRegion;
audioOffsetMs?: number;
audioGainDb?: number;
- audioAutoMaster?: boolean;
cursor?: Partial<CursorVisualSettings> & { theme?: string; show?: boolean };
autoFocusAll?: boolean;
}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index fe5631804..a0c2e8365 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -760,6 +760,38 @@ describe("buildSceneDescription.cropByClip", () => {
});
});
+// --- audio -----------------------------------------------------------------
+
+describe("buildSceneDescription.audio", () => {
+ // The editor claims "what you hear is what you export". That only holds while this
+ // payload carries nothing the preview cannot reproduce on the raw source file it
+ // plays: a linear gain and a whole-sample delay, and nothing else. These tests exist
+ // so a future stage with state (a filter, a compressor) or one measured over the
+ // assembled programme (a loudness normaliser) cannot be added here unnoticed.
+ it("carries the authored offset and gain through to the native payload", () => {
+ const doc = makeDoc({ legacyEditor: { audioOffsetMs: -120, audioGainDb: 4.5 } });
+ expect(buildSceneDescription(doc).audio).toEqual({ offsetMs: -120, gainDb: 4.5 });
+ });
+
+ it("defaults to a no-op for a project that predates the controls", () => {
+ expect(buildSceneDescription(makeDoc()).audio).toEqual({ offsetMs: 0, gainDb: 0 });
+ });
+
+ it("exposes only offset and gain", () => {
+ // Guards the parity contract itself, not a value: an extra key here means the
+ // export applies something the preview does not.
+ expect(Object.keys(buildSceneDescription(makeDoc()).audio).sort()).toEqual([
+ "gainDb",
+ "offsetMs",
+ ]);
+ });
+
+ it("clamps to the range the sliders offer, so the UI can always display it", () => {
+ const doc = makeDoc({ legacyEditor: { audioOffsetMs: 9_999, audioGainDb: -99 } });
+ expect(buildSceneDescription(doc).audio).toEqual({ offsetMs: 500, gainDb: -12 });
+ });
+});
+
// --- settings mapping ------------------------------------------------------
describe("buildSceneDescription.settings mapping", () => {
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index fe95ac43f..3502e8afd 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -370,12 +370,19 @@ export interface SceneDescription {
*/
speedRegions: SceneSpeedRegion[];
cursor: SceneCursor;
- /** Voice-oriented finishing applied to preview/export audio. Offset is signed:
- * positive delays audio, negative advances it. */
+ /**
+ * Audio finishing, applied identically by the preview and by `finish_audio` (Rust).
+ * Offset is signed: positive delays audio, negative advances it.
+ *
+ * Both fields are deliberately stateless — a pure delay and a linear gain. The preview
+ * plays the untouched source file while the export runs on the assembled timeline, so
+ * anything with memory (a filter, a compressor) or anything measured over the whole
+ * programme (a loudness normaliser) would sound different on the two sides. Keep this
+ * shape parity-safe; see the AudioPane comment before adding a field.
+ */
audio: {
offsetMs: number;
gainDb: number;
- autoMaster: boolean;
};
/**
* Per-clip screen crop (fractions of the frame), or null for the identity
@@ -729,7 +736,6 @@ export function buildSceneDescription(
audio: {
offsetMs: settings.audioOffsetMs,
gainDb: settings.audioGainDb,
- autoMaster: settings.audioAutoMaster,
},
background: parseWallpaper(settings.wallpaper),
zoomRegions: projectedZoomRegions.map((region) => ({