Skip to content

fix(engine): preserve boosted audio through volume automation - #6612

Open
AksharP5 wants to merge 1 commit into
heygen-com:mainfrom
AksharP5:audio-gain-headroom
Open

AksharP5 wants to merge 1 commit into
heygen-com:mainfrom
AksharP5:audio-gain-headroom

Conversation

@AksharP5

@AksharP5 AksharP5 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What

Adding a unity volume lane can distort a boosted clip even when the group fader turns it back down below full scale. Prepared clips now retain floating-point headroom, so the lane preserves the waveform and level.

Why

The envelope baker multiplies clip gain into prepared PCM before group attenuation. Preparing that PCM as 16-bit saturates peaks above 1 irreversibly. The final mix can remain below its true-peak ceiling while carrying audible harmonic distortion.

Related work

Fixes #6609

#3446 already preserves headroom in group sums; #3174 addresses FX output clipping. This fixes the dry clip before it reaches either path, under the gain-times-lane contract from #6068.

How

Use pcm_f32le for ordinary and looped prepared clips. Explicit -rematrix_maxval 1 retains the previous surround-to-stereo normalization when switching sample formats. Playback-rate ramps also normalize stereo conversion inside their complex filter graph, preserving the mono duplication policy. The existing WAV readers, envelope baker, and FX writer already support float PCM. Regressions compare decoded output with and without a unity lane and preserve static surround levels, covering ordinary and looped extraction.

Tradeoff: prepared PCM scratch data doubles from 2 to 4 bytes per sample (48 kHz stereo: 192,000 to 384,000 bytes per second). No runtime speed improvement is claimed.

Before and after

Baseline 8b1f88b3c06175f43fbdbe1af6e53933847cb195; fixed commit b46b780308a7fcb5a2cea96d01f6221d646bf3ae. Identical generated WAV, clip/group gains, duration and FFmpeg version:

Same input and authored final gain Decoded peak Decoded RMS Third harmonic relative to fundamental
Original: no volume lane 0.6002697348594666 0.4242009125603258 -107.3590058640738 dBc
Original: unity volume lane 0.5006220936775208 0.3912595104564889 -23.75831947097643 dBc
Fixed: no volume lane 0.6002697348594666 0.4242009125603258 -107.3590058640738 dBc
Fixed: unity volume lane 0.6002697348594666 0.4242009125603258 -107.3590058640738 dBc

All four runs report audio present, no true-peak attenuation, and 2.005333333333333 decoded seconds including AAC padding. The two fixed outputs decode to identical first-channel PCM bytes, also identical to the original no-lane control (SHA256 f2448b82be08a653f554562fa779a73fbd8637f42ccfa474e25aed34becee951). The source WAV is identical across baseline and fix (SHA256 537f17a4b9ec89251a955f755d5336ec68a939cbd442001fe6ef31297155a079).

Surround compatibility

The same quiet 5.1 source, unity clip/master gain, and no lane, group, or FX pass through the real Producer audio stage. Measurements use decoded stereo frames 12,000–35,999. Neither run triggers peak attenuation.

Revision Left RMS Right RMS
Merge-base 8b1f88b3 0.09019577 0.06211159
Initial PR 134b80f9 0.21788033 0.14998868
Current fix 0.09019575 0.06211181

Astra HIGH review found the initial float conversion raised this existing mix by 7.66 dB. Explicit rematrix normalization restores the baseline level while retaining float headroom. The new ordinary/looped level tests both fail before this correction by 7.6 dB and pass afterward.

The fixture is a one-second, 48 kHz, 16-bit 5.1 WAV generated with aevalsrc=0.3*sin(2*PI*1000*t)|0.2*sin(2*PI*700*t)|0.1*sin(2*PI*400*t)|0|0|0:c=5.1:s=48000:d=1. The tests compare it with an independently normalized stereo reference made using -ac 2 -c:a pcm_s16le.

Ramped surround compatibility

The same 5.1 fixture with a playback-rate lane from 0.7 at zero seconds to 1.2 at one second passes through the real Producer audio stage at unity gain, without FX or groups. No output triggers peak attenuation.

Revision Left RMS Right RMS
Merge-base 8b1f88b3 0.08900032 0.06075366
Prior head a47a6f36 0.21496591 0.14671012
Current fix 0.08899672 0.06072520

The corrected result is within 0.005 dB of the baseline. The ramped graph applies normalized stereo rematrixing explicitly; an output-only option did not affect that graph. The non-looping ramp regression fails before correction by 7.6 dB, against a 0.2 dB test bound, and passes afterward.

Public reproduction

This runs the real Producer audio stage with a generated 2-second, 48 kHz, 1 kHz sine at peak 0.6. It uses clip gain 2, group gain 0.5, and no effects. The second render adds only a volume lane held at 1. No browser, private media, or mock encoder is needed.

In a checkout of this repository with its Bun dependencies and FFmpeg installed, build the workspace once with bun run build. Save the following as repro-audio.ts in the repository root, then run:

bun repro-audio.ts /tmp/hf-audio-headroom

For the original result, use commit 8b1f88b3c06175f43fbdbe1af6e53933847cb195 (0.8.210). For the fixed result, use this fix's branch and rebuild the engine with bun run --cwd packages/engine build before running the same script. The script generates its own asset and prints measurements from the decoded M4A's middle second; it also saves both M4A files and observations.json in the supplied output directory.

import { spawnSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve, join } from "node:path";
import { pathToFileURL } from "node:url";

const repo = process.cwd();
const { runAudioStage } = await import(
  pathToFileURL(join(repo, "packages/producer/src/services/render/stages/audioStage.ts")).href
);
const { parseAudioElements } = await import(
  pathToFileURL(join(repo, "packages/engine/src/services/audioMixer.ts")).href
);
const out = resolve(process.argv[2]);
mkdirSync(out, { recursive: true });
function ffmpeg(args: string[]) {
  const result = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args], {
    maxBuffer: 8 * 1024 * 1024,
  });
  if (result.status !== 0) throw new Error(result.stderr.toString());
  return result.stdout;
}
ffmpeg([
  "-f",
  "lavfi",
  "-i",
  "aevalsrc=0.6*sin(2*PI*1000*t):s=48000:d=2",
  "-c:a",
  "pcm_s16le",
  join(out, "tone.wav"),
]);
const lane = JSON.stringify({
  version: 1,
  lanes: [
    {
      target: "volume",
      points: [
        { t: 0, v: 1 },
        { t: 2, v: 1 },
      ],
    },
  ],
});
const results = [];
for (const automated of [false, true]) {
  const name = automated ? "unity-lane" : "static";
  const work = join(out, name);
  mkdirSync(work, { recursive: true });
  const html = `<hf-audio-group id="bus" data-volume="0.5"></hf-audio-group><audio id="tone" src="tone.wav" data-audio-group="bus" data-start="0" data-duration="2" data-volume="2" ${automated ? `data-automation='${lane}'` : ""}></audio>`;
  const result = await runAudioStage({
    projectDir: out,
    workDir: work,
    compiledDir: out,
    totalFrames: 60,
    fps: { num: 30, den: 1 },
    ffmpegProcessTimeout: 30000,
    audioGain: 1,
    audios: parseAudioElements(html),
    abortSignal: undefined,
    assertNotAborted: () => {},
  });
  if (!result.hasAudio) throw new Error(JSON.stringify(result));
  const pcm = ffmpeg([
    "-i",
    result.audioOutputPath,
    "-af",
    "pan=mono|c0=c0",
    "-ar",
    "48000",
    "-f",
    "f32le",
    "-",
  ]);
  let energy = 0,
    peak = 0;
  const harmonics = [1, 3, 5].map((h) => {
    let re = 0,
      im = 0;
    for (let i = 24000; i < 72000; i++) {
      const v = pcm.readFloatLE(i * 4);
      re += v * Math.cos((2 * Math.PI * 1000 * h * i) / 48000);
      im += v * Math.sin((2 * Math.PI * 1000 * h * i) / 48000);
    }
    return (2 * Math.hypot(re, im)) / 48000;
  });
  for (let i = 24000; i < 72000; i++) {
    const v = pcm.readFloatLE(i * 4);
    energy += v * v;
    peak = Math.max(peak, Math.abs(v));
  }
  results.push({
    name,
    hasAudio: result.hasAudio,
    loweredDb: result.audioLoweredDb ?? 0,
    seconds: pcm.length / 4 / 48000,
    rms: Math.sqrt(energy / 48000),
    peak,
    harmonics,
    thirdHarmonicDb: 20 * Math.log10(harmonics[1] / harmonics[0]),
  });
}
console.log(JSON.stringify(results, null, 2));
writeFileSync(join(out, "observations.json"), JSON.stringify(results, null, 2) + "\n");

Test plan

fails without the fix: packages/engine/src/services/audioMixer.level.test.ts, preserves the normalized surround mix level (loop=false, ramped=true). At a47a6f36 it differs from the normalized stereo reference by 7.6 dB; the current fix is within the 0.2 dB bound.

  • New regressions fail on the baseline: both normal and looped waveform comparisons fail at about 10.5% relative RMS error, against a 0.5% bound. Both pass with the fix.
  • Real Producer stage reproduction and decoded PCM measurements above; no mocked test used as the impact proof.
  • Full workspace build before tests, then rebuilt the changed engine before dependent Producer checks. Engine and Producer typechecks pass.
  • Documentation and affected format comments updated.
  • Oxlint, oxfmt, comment citation/ratchet checks and normal pre-commit/commit-msg hooks.

Validation before this refresh: 119 focused Engine tests passed. Eighteen real FFmpeg scenarios cover mono/stereo/surround, ordinary and looped playback, nonconstant rate ramps, clip/group FX, master attenuation, and video audio. Every lane/no-lane pair decodes byte-identically. Only the previously incorrect non-looping surround-ramp scenario changes from the prior head; all other scenario outputs retain identical decoded bytes. The real Producer ramp reproduction matches baseline levels within 0.005 dB. Changed Engine build, typechecks, lint/format, Fallow, comment gates, and normal hooks pass.

Initial validation: 179 selected Engine tests and 20 Producer tests passed across focused runs and targeted retries. Two group-FX tests initially failed because Chromium could not launch/access host /tmp; all 60 grouping/FX cases pass with installed Chromium 156 and a Snap-visible TMPDIR. Two existing Producer integration tests exceeded the default 5-second limit and passed with --testTimeout 60000; their timeout cause was not established. No production change was made for those failures.

Linux aarch64; Bun 1.4.4; Node 24.22.1; FFmpeg/FFprobe 7.0.2-static; Hyperframes source 0.8.210. The reproduction calls the real Producer audio stage and decodes its delivered M4A. It does not capture video or audition through a physical output device.

Mintlify checks could not run: mint validate and mint broken-links both report mint: command not found. Mintlify was not installed.

GPT-6 Astra high independently re-reviewed exact current head 30dc79f274f2c999227038177f33e3d12620bb01 on 2026-11-03 and found no blocking findings. Fresh verification passed 121 focused Engine tests, 14 Producer stage tests, two duration-format tests, and a real Producer/FFmpeg reproduction. Static gain and unity automation produced identical peak, RMS and harmonic measurements. The prior ramp-specific downmix finding remains resolved; all six changed-file hashes matched the reviewed commit and the checkout remained clean. This review did not repeat the full workspace build, all media-probe fixtures, native Windows or physical audition. Maintainer approval remains pending.

Refresh onto main

Updated onto main 47fe68562f39d91b4d9280dff41ae43d67805fae at verified signed head 30dc79f274f2c999227038177f33e3d12620bb01. The extraction-argument conflict is resolved with float PCM plus main's corrected seek timestamps and decimal duration formatting from #6664 and #6893. Upstream fetch-isolation changes in audioMixer.test.ts are retained.

  • Full workspace build passed after a frozen dependency install with browser downloads disabled.
  • 131 focused audio/loop/read/envelope/WAV tests passed, plus all 124 media-probe tests and 14 Producer audio-stage tests.
  • The first probe run hit four failures because the HDR PNG was an unpopulated Git LFS pointer. All 124 passed with its checksum-verified public 3,026-byte fixture; the original pointer was restored. No fixture change is included in this commit.
  • All 18 real FFmpeg scenarios retain byte-identical decoded output to b46b780; every unity-lane/static pair also remains identical. The real Producer surround-rate-ramp metrics are unchanged from that head.
  • Normal hooks, typechecks, lint/format, Fallow, commitlint and comment gates passed. The GitHub-verified signed commit's full tree matches the tested snapshot; the checkout is clean.

GitHub reports the branch conflict-free. All 12 required checks pass on 30dc79f, with no failed or pending checks. Maintainer review remains pending. No new native Windows or physical-audition verification; local Mintlify remains unavailable.

@mintlify

mintlify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 30dc79f.

Approve preview

@AksharP5

AksharP5 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Refreshed #6612 onto main 47fe68562f39d91b4d9280dff41ae43d67805fae at verified signed head 30dc79f274f2c999227038177f33e3d12620bb01.

The extraction-argument conflict now retains both this PR's float PCM and main's seek-timestamp/decimal-duration corrections. Both surround-normalization paths remain intact. Upstream fetch-isolation tests are retained.

Full workspace build, 131 focused Engine audio tests, 124 media-probe tests, and 14 Producer audio-stage tests pass. All 18 real FFmpeg cases decode identically to prior head b46b780, including unity-lane/static pairs. The Producer surround-rate-ramp metrics are unchanged, preserving the earlier Astra finding's correction.

Four initial probe failures came from an unpopulated Git LFS HDR PNG. The probe suite passes with the checksum-verified public fixture; the original pointer was restored and no fixture change is included. Normal hooks, lint/format, typechecks, Fallow and comment gates pass. GitHub verifies the signed commit and its complete tree matches the tested snapshot.

The branch is conflict-free. All 12 required checks pass on 30dc79f, with no failed or pending checks. Maintainer review is pending. No merge performed. Linux arm64; no new native Windows, physical audition or local Mintlify validation. The independent reviewer has not reviewed this refresh.

@github-actions

Copy link
Copy Markdown
Contributor

This PR has had no activity for 14 days, so it is marked stale and will close in 7 days. Push a commit or leave a comment to keep it open. A maintainer can add keep-open to exempt it.

@github-actions github-actions Bot added the stale label Nov 18, 2026
@AksharP5

Copy link
Copy Markdown
Contributor Author

Could a maintainer review 30dc79f27? The PR still applies cleanly to main, and GitHub shows no failing or pending checks. The before/after FFmpeg evidence in the PR shows the original issue: the volume lane clipped boosted audio before the group fader could bring it below full scale. The fix keeps that headroom through automation.

@github-actions github-actions Bot removed the stale label Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Volume automation clips boosted audio before the group fader

1 participant