Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
refactor(editor): drop the audio sync offset, leaving only the parity-safe gain
Etienne Lescotc6e57ffdb2ab
diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rsindex 54432a559..db9b46e13 100644--- a/crates/compositor/src/audio.rs+++ b/crates/compositor/src/audio.rs@@ -27,22 +27,28 @@ const PASSTHROUGH_EPSILON: f64 = 1e-3;pub type PlanarPcm = Vec<Vec<f32>>;-/// Apply the editor's output trim and signed sync offset to the assembled timeline.+/// Apply the editor's output trim to the assembled timeline.///-/// 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.+/// One stage, and keeping it that way takes some resisting. This runs on the assembled+/// timeline — trimmed, speed-adjusted, concatenated — while the editor preview plays the+/// untouched SOURCE file, seeked. A linear gain is the only operation that means the same+/// thing 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.+/// Three things that look like they belong here and do not:+/// - a filter or a compressor, which carries state across cuts here and not in the preview;+/// - a loudness normaliser, whose makeup is a single scalar measured over the whole assembled+/// programme — the preview never holds that programme, and the value moves with every trim;+/// - a sync offset, which shipped here once. It is expressed in TIMELINE seconds at this+/// point in the pipeline, but the preview would apply it in SOURCE seconds, so a 2x speed+/// region halved it; and because the shift is uniform over the assembled programme, near a+/// cut the export pulls audio across the junction while the preview only has the active+/// asset loaded.///-/// 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.+/// Any of them means either rendering the export's audio assembly preview-side, or accepting+/// and documenting a divergence — not a quiet extra stage in this function.+///+/// The bound mirrors `AUDIO_GAIN_DB_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 {@@ -56,28 +62,6 @@ pub fn finish_audio(mut pcm: PlanarPcm, settings: SceneAudio) -> PlanarPcm {for sample in pcm.iter_mut().flatten() {*sample = (*sample * trim).clamp(-1.0, 1.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 {- return pcm;- }- if shift > 0 {- let destination = (shift as usize).min(samples);- let count = samples - destination;- for channel in pcm.iter_mut() {- channel.copy_within(..count, destination);- channel[..destination].fill(0.0);- }- } else {- let source = ((-shift) as usize).min(samples);- let count = samples - source;- for channel in pcm.iter_mut() {- channel.copy_within(source.., 0);- channel[count..].fill(0.0);- }- }pcm}@@ -1119,26 +1103,6 @@ mod tests {assert_eq!(mixed[0], vec![0.5; 8]);}- #[test]- fn signed_audio_offset_is_length_preserving() {- let settings = SceneAudio {- offset_ms: 1000.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64,- gain_db: 0.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(&[0.1, 0.2, 0.3]),- SceneAudio {- offset_ms: -1000.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64,- ..settings- },- );- 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.@@ -1147,10 +1111,7 @@ mod tests {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,- },+ SceneAudio { gain_db },);let expected = (0.25 * 10.0f32.powf(gain_db / 20.0)).clamp(-1.0, 1.0);assert!(@@ -1163,60 +1124,26 @@ mod tests {}#[test]- 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.- //- // The buffer has to outlast the clamp for this to mean anything: on a short input- // every delay past its length produces silence, so the assertion would hold for a- // 500 ms clamp and for no clamp at all. Track a single impulse instead and check- // WHERE it lands.- let limit_samples = AUDIO_OUTPUT_SAMPLE_RATE as usize / 2; // 500 ms- let mut input = vec![0.0f32; limit_samples + 2];- input[0] = 0.5;- let delayed = finish_audio(- planar(&input),- SceneAudio {- offset_ms: 9_999.0,- gain_db: 0.0,- },- );- assert_eq!(- delayed[0][limit_samples], 0.5,- "the impulse must land at 500 ms, not at the requested 9.999 s"- );- assert_eq!(delayed[0][limit_samples - 1], 0.0);- assert_eq!(delayed[0][0], 0.0);-- let advanced = finish_audio(- planar(&input),- SceneAudio {- offset_ms: -9_999.0,- gain_db: 0.0,- },- );- // Advancing by the same clamp drops everything before it; the impulse at sample 0- // is gone and nothing is left behind it.- assert!(advanced[0].iter().all(|sample| *sample == 0.0));-- let quiet = finish_audio(- planar(&[0.5]),- SceneAudio {- offset_ms: 0.0,- gain_db: -99.0,- },- );+ fn out_of_range_gain_is_clamped_to_the_editor_bound() {+ // A hand-edited project, the AI edition agent, or a future UI change must not be+ // able to ask for a gain the slider cannot display.+ let quiet = finish_audio(planar(&[0.5]), SceneAudio { gain_db: -99.0 });let floor = 0.5 * 10.0f32.powf(-12.0 / 20.0);assert!((quiet[0][0] - floor).abs() < 1e-6);- let loud = finish_audio(- planar(&[0.1]),- SceneAudio {- offset_ms: 0.0,- gain_db: 99.0,- },- );+ let loud = finish_audio(planar(&[0.1]), SceneAudio { gain_db: 99.0 });let ceiling = 0.1 * 10.0f32.powf(12.0 / 20.0);assert!((loud[0][0] - ceiling).abs() < 1e-6);}++ #[test]+ fn output_is_clipped_to_full_scale_and_keeps_its_length() {+ // The trim can push a hot signal past full scale; the timeline must come back the+ // same length either way, or video and the following clips drift against it.+ let result = finish_audio(planar(&[0.9, -0.9, 0.1]), SceneAudio { gain_db: 12.0 });+ assert_eq!(result[0].len(), 3);+ assert_eq!(result[0][0], 1.0);+ assert_eq!(result[0][1], -1.0);+ assert!((result[0][2] - 0.1 * 10.0f32.powf(12.0 / 20.0)).abs() < 1e-6);+ }}diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rsindex 538bcb06a..bf9260bef 100644--- a/crates/compositor/src/scene.rs+++ b/crates/compositor/src/scene.rs@@ -395,17 +395,15 @@ pub struct SceneCrop {pub height: f32,}-/// 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.+/// Audio finishing. Deliberately limited to a linear gain — the one operation the editor+/// preview can apply identically to the source file it plays. See `audio::finish_audio`+/// before adding a field here; a sync offset was tried and removed.///-/// 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.+/// The field carries `#[serde(default)]`: a payload from a build that predates it 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,}diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex 6994c7578..c99bd5b4f 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -42,7 +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 { AUDIO_GAIN_DB_LIMIT } from "@/lib/ai-edition/store/editorSettings";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";import {@@ -1743,17 +1743,6 @@ export function AudioPane() {return (<Pane title={ts("audio.title")} icon={<AudioLines size={14} />} helpText={ts("audio.help")}><div className={styles.sliderGrid}>- <SliderCell- label={ts("audio.syncOffset")}- value={settings.audioOffsetMs}- min={-AUDIO_OFFSET_MS_LIMIT}- max={AUDIO_OFFSET_MS_LIMIT}- step={1}- suffix=" ms"- disabled={!hasDocument}- onChange={(value) => setLive({ audioOffsetMs: value })}- onCommit={() => void commit()}- /><SliderCelllabel={ts("audio.outputGain")}value={settings.audioGainDb}@@ -1771,7 +1760,7 @@ export function AudioPane() {type="button"className={styles.secondaryBtn}disabled={!hasDocument}- onClick={() => void set({ audioOffsetMs: 0, audioGainDb: 0 })}+ onClick={() => void set({ audioGainDb: 0 })}>{ts("audio.reset")}</button>diff --git a/src/components/ai-edition/VirtualPreview.audio.test.ts b/src/components/ai-edition/VirtualPreview.audio.test.tsindex a565aebc0..d1425bd79 100644--- a/src/components/ai-edition/VirtualPreview.audio.test.ts+++ b/src/components/ai-edition/VirtualPreview.audio.test.ts@@ -1,27 +1,25 @@import { describe, expect, it } from "vitest";-import { resolveAudioPreviewTime } from "./VirtualPreview";+import { resolveAudioTrackPlayback } from "./VirtualPreview";-describe("resolveAudioPreviewTime", () => {- it("delays audio for a positive offset", () => {- expect(resolveAudioPreviewTime(0.1, 160, 10)).toEqual({ targetTimeSec: 0, shouldPlay: false });- expect(resolveAudioPreviewTime(1, 160, 10)).toEqual({ targetTimeSec: 0.84, shouldPlay: true });+describe("resolveAudioTrackPlayback", () => {+ it("mirrors the video's time", () => {+ expect(resolveAudioTrackPlayback(1, 10)).toEqual({ targetTimeSec: 1, shouldPlay: true });});- it("advances audio for a negative offset", () => {- expect(resolveAudioPreviewTime(1, -160, 10)).toEqual({ targetTimeSec: 1.16, shouldPlay: true });- });-- it("stops instead of seeking past the track", () => {- expect(resolveAudioPreviewTime(9.9, -160, 10)).toEqual({- targetTimeSec: 10,- shouldPlay: false,- });+ it("parks at the end of a track that is shorter than the video", () => {+ // The supplemental track is extracted separately, so it can run out before the+ // video does; seeking past its end leaves the element stuck in `seeking`.+ expect(resolveAudioTrackPlayback(12, 10)).toEqual({ targetTimeSec: 10, shouldPlay: false });});it("plays while the duration is still unknown", () => {- expect(resolveAudioPreviewTime(1, 0, Number.NaN)).toEqual({+ expect(resolveAudioTrackPlayback(1, Number.NaN)).toEqual({targetTimeSec: 1,shouldPlay: true,});});++ it("never seeks to a negative time", () => {+ expect(resolveAudioTrackPlayback(-0.5, 10)).toEqual({ targetTimeSec: 0, shouldPlay: false });+ });});diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 14253bf61..44b47fb80 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -40,16 +40,22 @@ export interface VideoSource {label: string;}-export function resolveAudioPreviewTime(+/**+ * Where an audio element should sit to track the video, and whether it should be playing.+ *+ * The audio elements mirror the video's own time — there is no offset to apply, because the+ * only per-track difference that survives is length: the supplemental track is extracted+ * separately and can end before the video does. Past its end the element is parked at its+ * duration and paused rather than left seeking into nothing.+ */+export function resolveAudioTrackPlayback(videoTimeSec: number,- offsetMs: number,durationSec = Number.POSITIVE_INFINITY,) {- const raw = videoTimeSec - offsetMs / 1000;const finiteDuration = Number.isFinite(durationSec) && durationSec > 0 ? durationSec : Infinity;return {- targetTimeSec: Math.min(Math.max(0, raw), finiteDuration),- shouldPlay: raw >= 0 && raw < finiteDuration,+ targetTimeSec: Math.min(Math.max(0, videoTimeSec), finiteDuration),+ shouldPlay: videoTimeSec >= 0 && videoTimeSec < finiteDuration,};}@@ -160,10 +166,6 @@ export function VirtualPreview({clockRef,}: VirtualPreviewProps) {const { settings } = useEditorSettings();- const audioOffsetMsRef = useRef(settings.audioOffsetMs);- useEffect(() => {- audioOffsetMsRef.current = settings.audioOffsetMs;- }, [settings.audioOffsetMs]);// ponytail: an oversized, offset video inside .videoFrame's overflow:hidden// box — the same "scale + negative-position the full frame, let the// container clip the rest" technique the export renderer uses via a Pixi@@ -438,11 +440,7 @@ export function VirtualPreview({}for (const audio of [primaryAudioRef.current, supplementalAudioRef.current]) {if (!audio) continue;- const target = resolveAudioPreviewTime(- v.currentTime,- audioOffsetMsRef.current,- audio.duration,- );+ const target = resolveAudioTrackPlayback(v.currentTime, audio.duration);if (audio.playbackRate !== v.playbackRate) audio.playbackRate = v.playbackRate;if (Math.abs(audio.currentTime - target.targetTimeSec) > 0.025) {try {diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.jsonindex a0663f78e..664131e1d 100644--- a/src/i18n/locales/ar/settings.json+++ b/src/i18n/locales/ar/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "الصوت",- "syncOffset": "إزاحة المزامنة","outputGain": "ضبط مستوى الإخراج","reset": "إعادة ضبط الصوت",- "help": "اضبط توقيت الصوت ومستوى الإخراج. كلاهما يُطبَّق بالطريقة نفسها في المعاينة وعند التصدير."+ "help": "اضبط مستوى إخراج الصوت. يُطبَّق بالطريقة نفسها في المعاينة وعند التصدير."}}diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.jsonindex f2dedd8f0..e17bcb74c 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 timing and trim the output level. Both apply identically in the preview and the export.",- "syncOffset": "Sync offset",+ "help": "Trim the audio output level. It applies identically in the preview and the export.","outputGain": "Output trim","reset": "Reset audio"},diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.jsonindex 8b61142c0..1386e1e1d 100644--- a/src/i18n/locales/es/settings.json+++ b/src/i18n/locales/es/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Audio",- "syncOffset": "Desfase de sincronización","outputGain": "Ajuste de salida","reset": "Restablecer audio",- "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."+ "help": "Ajusta el nivel de salida del audio. Se aplica 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.jsonindex bf76bdd21..ad3dc0dff 100644--- a/src/i18n/locales/fr/settings.json+++ b/src/i18n/locales/fr/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Audio",- "syncOffset": "Décalage de synchronisation","outputGain": "Niveau de sortie","reset": "Réinitialiser l’audio",- "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."+ "help": "Ajustez le niveau de sortie audio. Il s’applique à l’identique dans l’aperçu et à l’export."}}diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.jsonindex 7e5b160be..206d40bbb 100644--- a/src/i18n/locales/it/settings.json+++ b/src/i18n/locales/it/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Audio",- "syncOffset": "Offset sincronizzazione","outputGain": "Livello di uscita","reset": "Reimposta audio",- "help": "Regola la sincronizzazione dell’audio e il livello di uscita. Entrambi si applicano allo stesso modo nell’anteprima e nell’esportazione."+ "help": "Regola il livello di uscita audio. Si applica 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.jsonindex 8fa1ba767..8d999dc79 100644--- a/src/i18n/locales/ja-JP/settings.json+++ b/src/i18n/locales/ja-JP/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "オーディオ",- "syncOffset": "同期オフセット","outputGain": "出力レベル","reset": "オーディオをリセット",- "help": "音声のタイミングと出力レベルを調整します。どちらもプレビューと書き出しで同じように適用されます。"+ "help": "音声の出力レベルを調整します。プレビューと書き出しで同じように適用されます。"}}diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.jsonindex 71718d49a..cbbc77ada 100644--- a/src/i18n/locales/ko-KR/settings.json+++ b/src/i18n/locales/ko-KR/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "오디오",- "syncOffset": "동기화 오프셋","outputGain": "출력 레벨","reset": "오디오 재설정",- "help": "오디오 타이밍과 출력 레벨을 조정합니다. 둘 다 미리보기와 내보내기에 동일하게 적용됩니다."+ "help": "오디오 출력 레벨을 조정합니다. 미리보기와 내보내기에 동일하게 적용됩니다."}}diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.jsonindex 2171ddf64..68a4112c3 100644--- a/src/i18n/locales/pt-BR/settings.json+++ b/src/i18n/locales/pt-BR/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Áudio",- "syncOffset": "Deslocamento de sincronização","outputGain": "Nível de saída","reset": "Redefinir áudio",- "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."+ "help": "Ajuste o nível de saída do áudio. Ele se aplica 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.jsonindex 4b305f08b..a6798b666 100644--- a/src/i18n/locales/ru/settings.json+++ b/src/i18n/locales/ru/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Аудио",- "syncOffset": "Смещение синхронизации","outputGain": "Уровень выхода","reset": "Сбросить аудио",- "help": "Настройте синхронизацию звука и уровень на выходе. Оба параметра одинаково применяются в предпросмотре и при экспорте."+ "help": "Настройте уровень звука на выходе. Он одинаково применяется в предпросмотре и при экспорте."}}diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.jsonindex f334f8911..c2ab5477a 100644--- a/src/i18n/locales/tr/settings.json+++ b/src/i18n/locales/tr/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Ses",- "syncOffset": "Senkronizasyon kaydırması","outputGain": "Çıkış seviyesi","reset": "Sesi sıfırla",- "help": "Ses zamanlamasını ve çıkış seviyesini ayarlayın. İkisi de önizlemede ve dışa aktarmada aynı şekilde uygulanır."+ "help": "Ses çıkış seviyesini ayarlayın. Önizlemede ve dışa aktarmada aynı şekilde uygulanır."}}diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.jsonindex 21ac6ce1b..d65c801f1 100644--- a/src/i18n/locales/vi/settings.json+++ b/src/i18n/locales/vi/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "Âm thanh",- "syncOffset": "Độ lệch đồng bộ","outputGain": "Mức đầu ra","reset": "Đặt lại âm thanh",- "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."+ "help": "Điều chỉnh mức đầu ra của âm thanh. Nó đượ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.jsonindex f813816d7..3fd503d24 100644--- a/src/i18n/locales/zh-CN/settings.json+++ b/src/i18n/locales/zh-CN/settings.json@@ -306,9 +306,8 @@},"audio": {"title": "音频",- "syncOffset": "同步偏移","outputGain": "输出电平","reset": "重置音频",- "help": "调整音频同步和输出电平。两者在预览和导出中的效果完全一致。"+ "help": "调整音频输出电平。它在预览和导出中的效果完全一致。"}}diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.jsonindex 1c8ada1a3..4a124525d 100644--- a/src/i18n/locales/zh-TW/settings.json+++ b/src/i18n/locales/zh-TW/settings.json@@ -307,9 +307,8 @@},"audio": {"title": "音訊",- "syncOffset": "同步偏移","outputGain": "輸出音量","reset": "重設音訊",- "help": "調整音訊同步與輸出電平。兩者在預覽與匯出中的效果完全一致。"+ "help": "調整音訊輸出電平。它在預覽與匯出中的效果完全一致。"}}diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.tsindex 21a2eb267..b86bf6ba5 100644--- a/src/lib/ai-edition/store/editorSettings.ts+++ b/src/lib/ai-edition/store/editorSettings.ts@@ -38,10 +38,13 @@ 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;+/** Output gain bound, shared by the slider, this store and `finish_audio` (Rust).+ *+ * A linear gain is the one audio setting that behaves identically on the preview's source+ * file and on the export's assembled timeline, which is why it is the only one left. A sync+ * offset was tried and removed: the preview seeks in SOURCE time while the export shifts the+ * stretched, concatenated timeline, so the same value meant different delays under a speed+ * region, and near a cut the export pulls audio across the junction while the preview cannot. */export const AUDIO_GAIN_DB_LIMIT = 12;export interface EditorSettingsSnapshot {@@ -60,8 +63,6 @@ export interface EditorSettingsSnapshot {webcamSizePreset: WebcamSizePreset;webcamPosition: WebcamPosition | null;webcamCropRegion: CropRegion;- /** Positive values move audio later; negative values advance it. */- audioOffsetMs: number;audioGainDb: number;cursor: CursorVisualSettings;cursorShow: boolean;@@ -90,7 +91,6 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettingsSnapshot = {webcamSizePreset: DEFAULT_WEBCAM_SIZE_PRESET,webcamPosition: DEFAULT_WEBCAM_POSITION,webcamCropRegion: DEFAULT_CROP_REGION,- audioOffsetMs: 0,audioGainDb: 0,cursor: {size: DEFAULT_CURSOR_SIZE,@@ -120,7 +120,6 @@ interface LegacyShape {webcamSizePreset?: WebcamSizePreset;webcamPosition?: WebcamPosition | null;webcamCropRegion?: CropRegion;- audioOffsetMs?: number;audioGainDb?: number;cursorSize?: number;cursorSmoothing?: number;@@ -177,13 +176,9 @@ export function getEditorSettings(doc: AxcutDocument | null | undefined): EditorwebcamSizePreset: num(legacy?.webcamSizePreset, DEFAULT_EDITOR_SETTINGS.webcamSizePreset),webcamPosition: normaliseWebcamPosition(legacy?.webcamPosition),webcamCropRegion: normaliseCropRegion(legacy?.webcamCropRegion),- // 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+ // Same bound the slider offers and the native `finish_audio` clamps to. Two+ // different ranges for one value is how a project ends up exporting a gain 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)),@@ -210,7 +205,6 @@ export interface EditorSettingsPatch {webcamSizePreset?: WebcamSizePreset;webcamPosition?: WebcamPosition | null;webcamCropRegion?: CropRegion;- audioOffsetMs?: number;audioGainDb?: number;cursor?: Partial<CursorVisualSettings> & { theme?: string; show?: boolean };autoFocusAll?: boolean;diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex a0c2e8365..fabca4320 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -765,30 +765,32 @@ describe("buildSceneDescription.cropByClip", () => {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 });+ // plays — which is a linear gain, and nothing else. These tests exist so a future+ // stage with state (a filter, a compressor), one measured over the assembled+ // programme (a loudness normaliser), or one expressed in timeline time (a sync+ // offset — this shipped once and was removed) cannot be added here unnoticed.+ it("carries the authored gain through to the native payload", () => {+ const doc = makeDoc({ legacyEditor: { audioGainDb: 4.5 } });+ expect(buildSceneDescription(doc).audio).toEqual({ 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("defaults to a no-op for a project that predates the control", () => {+ expect(buildSceneDescription(makeDoc()).audio).toEqual({ gainDb: 0 });});- it("exposes only offset and gain", () => {+ it("exposes only the 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",- ]);+ expect(Object.keys(buildSceneDescription(makeDoc()).audio)).toEqual(["gainDb"]);});- 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 });+ it("clamps to the range the slider offers, so the UI can always display it", () => {+ expect(buildSceneDescription(makeDoc({ legacyEditor: { audioGainDb: -99 } })).audio).toEqual({+ gainDb: -12,+ });+ expect(buildSceneDescription(makeDoc({ legacyEditor: { audioGainDb: 99 } })).audio).toEqual({+ gainDb: 12,+ });});});diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 3502e8afd..a8081a776 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -372,16 +372,18 @@ export interface SceneDescription {cursor: SceneCursor;/*** 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.+ * One field, and it takes some resisting to keep it that way. The preview plays the+ * untouched SOURCE file, seeked; the export runs on the assembled timeline — trimmed,+ * speed-adjusted, concatenated. A linear gain is the only operation that means the same+ * thing on both. Anything with memory (a filter, a compressor) diverges across cuts;+ * anything measured over the whole programme (a loudness normaliser) cannot be computed+ * preview-side at all; and even a plain delay diverges, because the preview would apply+ * it in source seconds while this applies it in timeline seconds — a 2x speed region+ * halves it, and near a cut the export pulls audio across the junction while the preview+ * only has the active asset. A sync offset shipped here and was removed for exactly that.*/audio: {- offsetMs: number;gainDb: number;};/**@@ -734,7 +736,6 @@ export function buildSceneDescription(theme: settings.cursorTheme,},audio: {- offsetMs: settings.audioOffsetMs,gainDb: settings.audioGainDb,},background: parseWallpaper(settings.wallpaper),