Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
fix(audio): keep the duck envelope aligned and handle opposite-phase …
…stereo

- Carry the incomplete 10 ms window across iter_chunks() chunks and pad only
  the final remainder. Padding each chunk drifted the envelope (about 0.4 s
  per minute at 24 kHz), so ducking started and ended late on long narration.
- Measure energy per channel instead of the mean waveform, so channels in
  opposite phase no longer cancel to silence and disable ducking.

Adds a 120 s / 24 kHz regression (envelope length and speech boundaries) and
an opposite-phase stereo regression.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
  • Loading branch information
simply-Rahul8 and claude committed Nov 18, 2026
commit ab240dba05764c04de669a92d8d80a6d71bcbfac
16 changes: 13 additions & 3 deletions app/services/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,11 +925,21 @@ def _narration_duck_gain(voice_clip) -> np.ndarray:
"""Return one music gain per 10 ms: 1.0 in pauses, lower under speech."""
step = max(int(voice_clip.fps * _DUCK_STEP_SECONDS), 1)
levels = []
carry = np.empty(0, dtype=np.float32)
# Chunked so a long narration is never decoded into memory at once.
for chunk in voice_clip.iter_chunks(chunksize=step * 100):
mono = np.asarray(chunk, dtype=np.float32).reshape(len(chunk), -1).mean(axis=1)
mono = np.pad(mono, (0, -len(mono) % step))
levels.append(np.sqrt((mono.reshape(-1, step) ** 2).mean(axis=1)))
samples = np.asarray(chunk, dtype=np.float32).reshape(len(chunk), -1)
# Energy per channel, not the mean waveform: opposite-phase channels
# would cancel to silence. Chunk sizes are not multiples of the step,
# so the incomplete window rolls into the next chunk.
energy = np.concatenate([carry, (samples**2).mean(axis=1)])
whole = len(energy) // step * step
levels.append(np.sqrt(energy[:whole].reshape(-1, step).mean(axis=1)))
carry = energy[whole:]
if len(carry):
tail = np.pad(carry, (0, step - len(carry)))
levels.append(np.sqrt(tail.mean(keepdims=True)))
levels = [part for part in levels if len(part)]
if not levels:
return np.ones(1)
level = np.concatenate(levels)
Expand Down
29 changes: 29 additions & 0 deletions test/services/test_bgm_duck.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,35 @@ def test_silent_narration_leaves_music_untouched():
assert np.all(video._narration_duck_gain(silent) == 1.0)


def test_long_narration_keeps_one_gain_per_10_ms():
# 24 kHz makes moviepy's chunks non-multiples of the 10 ms window.
fps, seconds = 24000, 120
t = np.arange(seconds * fps) / fps
speech = (t.astype(int) % 2 == 0) * 0.5 * np.sin(2 * np.pi * 220 * t)
clip = AudioArrayClip(np.stack([speech] * 2, axis=1), fps=fps)

gain = video._narration_duck_gain(clip)

assert len(gain) == seconds * 100
# Speech starts at every even second: the music must be down by its end
# and back up by the end of the following pause, even 110 s in.
assert _gain_at(gain, 110.9) == pytest.approx(video._DUCK_SPEECH_GAIN, abs=0.05)
assert _gain_at(gain, 111.9) > 0.95
assert _gain_at(gain, 54.9) == pytest.approx(video._DUCK_SPEECH_GAIN, abs=0.05)


def test_opposite_phase_stereo_still_ducks():
wave = _tone(2, 0.5, channels=1)[:, 0]
pause = np.zeros(2 * FPS)
left = np.concatenate([wave, pause])
clip = AudioArrayClip(np.stack([left, -left], axis=1), fps=FPS)

gain = video._narration_duck_gain(clip)

assert _gain_at(gain, 1.5) == pytest.approx(video._DUCK_SPEECH_GAIN, abs=0.05)
assert _gain_at(gain, 3.8) > 0.95


@pytest.mark.parametrize("channels", [1, 2])
def test_ducked_music_follows_the_envelope(channels):
music = AudioArrayClip(_tone(8, 0.4, channels), fps=FPS)
Expand Down
Loading