# `helix vehicle audio-import` — a car's sounds from its sim mod, never synthesised

Vehicle audio is **never generated or synthesised** — not resynthesis, not a text-to-audio take, not the runtime's
built-in synthesised engine. Every slot is a real recording, in this order of preference:

1. the most accurate BeamNG mod of that exact car;
2. another BeamNG mod of the same engine or car family, or BeamNG's stock FMOD banks for generic sounds (doors,
   horns, tyres, impacts) when no car-specific recording exists;
3. another sim's mod or official car (Assetto Corsa / ACC ...);
4. real recordings of the car.

A slot with none of these stays **empty with a reason**; `vehicle audio-check` and `vehicle publish` then fail the car
until it is sourced (or the part is genuinely not fitted — see below).

## Command

```sh
helix vehicle audio-import <mod dir | mod .zip | Assetto Corsa car dir | .bank> --out <dir> \
  [--sim beamng|ac|auto] [--vehicle <beamng vehicle id>] [--config <file.pc>] [--map <slot-map.json>] \
  [--beamng-root <BeamNG.drive install>] [--cylinders N] [--prefer exterior|interior] [--ac-native-rungs] \
  [--mod-url <url>] [--base-package <vehicle-package.json | dir | audio.json>] [--json]
```

- `--beamng-root` (or `HELIX_BEAMNG_ROOT`): the BeamNG.drive install. Its `content/art_sound.zip` FMOD banks resolve
  every stock event a mod names (`event:>Engine>Starter>v8flat_1986_eng`), its `content/vehicles/common.zip` resolves
  the common parts a vehicle selects (the soundscape horn), its stock engine blends fill a mod that uses a stock engine
  sound, and slots no part names get what the game itself plays (table below). For a non-BeamNG car (Assetto Corsa) it
  fills the slots that car lacks with BeamNG's generic stock recordings.
- The audio block always carries the five mix fields the runtime reads: `engineGainDb`, `exhaustGainDb`, `minLoadMix`,
  `maxLoadMix`, `muffling`. Each comes from, in order: the `--map` top level; `--base-package` (an existing package's
  audio block, so re-importing a published car keeps its mix); the BeamNG mod's selected `soundConfig` (`mainGain`,
  `minLoadMix`, `maxLoadMix`, `intakeMuffling`) and `soundConfigExhaust.mainGain` — the ladder source first, then the
  main source; else the engine's own BeamNG-blend defaults (-8 dB, -5 dB, 0.15, 1, 0.25). `audio-import.json` and the
  printed summary say where each came from (`mix`).
- `--cylinders`: the RECORDED engine's cylinder count (the ladder pitch model). Derived from the BeamNG engine part when
  it says; required for an Assetto Corsa car.
- FMOD decoding uses `vgmstream-cli` (`HELIX_VGMSTREAM` or PATH, release r2117 measured); without it PCM banks are
  decoded byte for byte and Vorbis banks via `pip install fsb5`; anything else is refused with an install message.
  `ffmpeg` (`HELIX_FFMPEG`) transcodes OGG/FLAC and re-pitches FMOD auto-pitched rungs.

Output:

- `<out>/audio/*.wav` — 16-bit PCM. The only byte changes ever made are recorded as `provenance.transforms`:
  `wav-header-repair` (a malformed header rebuilt around the untouched sample data — the mmbng 993 mod's PSH ladder
  declares 2 channels with the byteRate/blockAlign of mono, so decoders that trust blockAlign play it an octave low at
  half speed), `decode` (OGG/FLAC/FMOD codec to PCM) and `fmod-autopitch-varispeed` (below).
- `<out>/audio.json` — the package `audio` block, ready to drop into `vehicle-package.json` (copy `audio/` beside it):
  `bankId`, `sampleCylinderCount`, `strokes`, `engineBlend`, `exhaustBlend?`, `bank { blends, assets }`, and all 26
  live `slots`. The tyre squeal, scrub, wheelspin, skid and brake squeal slots are retired (the engine has no tyre squeal): they are never generated.
- `<out>/audio-import.json` — the full report: every slot's decision, source, alternatives and reason; unmapped source
  sounds; the stock events extracted.

`vehicle audio-check <out>/audio.json` checks the block on its own (fitment is cross-checked only against a full
package's physics).

## Provenance

Every consumed slot, every bank sample and every blend carries:

```json
"provenance": {
  "kind": "sim-mod" | "sim-official" | "recording",
  "sim": "beamng" | "assetto-corsa",
  "mod": "mmbng",                                  // the mod / car folder ("BeamNG.drive" for stock banks)
  "modUrl": "https://...",                         // when --mod-url / map modUrl is given
  "sourceFile": "art/sound/engine/PSH/1768.wav",   // or "content/art_sound.zip:art/sound/fmod/desktop/vehicle.assets.bank"
  "sourceSha256": "<sha256 of that source file>",
  "event": "event:/Engine/Starter/v8flat_1986_eng",
  "sample": "<FMOD subsound name>", "subsong": 1234,
  "extractor": "helix beamng_stock_events + vgmstream-cli r2117",
  "transforms": [{ "kind": "wav-header-repair", "detail": "..." }],
  "jbeam": "Porsh_engine.starterSample",            // the field that named it (BeamNG)
  "baseGameDefault": "lua/vehicle/... default"      // when the game's own default filled the slot
}
```

It lives inline: `audio.slots[i].provenance`, `audio.slots[i].assets[j].provenance`, `audio.bank.assets[k].provenance`,
`audio.bank.blends[name].provenance` (`audio-check` also reads a top-level `audio.provenance[slot]` map). The engine's
package validator ignores unknown keys, and the backend's `pinVehiclePackage` (helix-backend-api
`src/universal-items/vehicle-package-wire.ts`) seals a `structuredClone` of the submitted package, so the keys survive
publication (the live 993's slot `note` keys are the existing proof that extra slot keys round-trip).

## Gates (`vehicle audio-check`; `vehicle publish` refuses the same)

| code | level | when |
|---|---|---|
| `AUDIO_SYNTHESISED` | error | a provenance `kind`/`transform` that is generated or synthesised, or a slot `reason`/`note` that says so (negated clauses like "rather than synthesised" are fine) |
| `AUDIO_ENGINE_UNSOURCED` | error | no recorded engine ladder (`audio.bank`/`engineBlend`): the runtime would play its synthesised fallback engine. Replaces the old `AUDIO_FALLBACK_ENGINE` warning. Electric cars are exempt |
| `AUDIO_MIX_FIELDS_MISSING` | error | the audio block lacks a finite `engineGainDb` / `exhaustGainDb`, or a `minLoadMix` / `maxLoadMix` / `muffling` in 0..1. The runtime feeds them to Web Audio; a NaN gain throws in the frame loop, so the car boards but never moves or sounds (R34 1.0.9) |
| `AUDIO_SLOT_UNSOURCED` | error | one of the 26 live slots is missing, has no recording, or only names a platform buffer (the runtime's default pack) |
| `AUDIO_PROVENANCE_MISSING` | error | a recording (slot asset or ladder rung) that says nothing about where it came from |
| `AUDIO_SLOT_FITMENT_MISMATCH` | error | `absent: "not-fitted"` on a car that has the part (a turbo car's turboSpool, a manual's clutch), or turbo sounds on a car with no `physics.induction` |
| `AUDIO_SLOT_RETIRED` | warn | the package still carries `tyreSqueal`, `tyreScrub`, `tyreSpin`, `skid` or `brakeSqueal`. The engine plays none of them, so the slot is ignored: no recording is demanded and its wav gets no sample, provenance or near-duplicate judgement. Remove the slot |
| `AUDIO_ENGINE_EXHAUST_SHARED_RECORDING` | warn | engine and exhaust blends play the same **sourced** recording (an unsourced shared blend stays `AUDIO_ENGINE_EXHAUST_SAME_BLEND`, error) |

The only legitimately empty slots (`consumed: false`, `buffers: []`, a `reason`):

```json
{ "slot": "turboSpool", "buffers": [], "consumed": false, "absent": "not-fitted", "reason": "naturally aspirated ..." }
{ "slot": "exhaustLadder", "buffers": [], "consumed": false, "absent": "combined-with-engine", "reason": "..." }
```

- `not-fitted`: `turboSpool` / `blowOff` without a turbocharger (`physics.induction` absent or not `turbo`),
  `reverseBeep` (fitted equipment), `clutch` on an automatic or CVT; every combustion slot on an electric car.
- `combined-with-engine`: `exhaustLadder` only, with a sourced engine ladder.

**Combined engine+exhaust recordings.** Some mods record one set for both (the mmbng 993 sets the exhaust
`sampleName` to `"0"`). `audio-import` omits `exhaustBlend` and declares the exhaust slot `combined-with-engine`; the
recording plays once, on the engine layer, exactly as BeamNG plays it (`importBeamngBank` takes the exhaust blend as
optional). A package that instead points both blends at the same sourced recording is a warning, not an error: it is a
real recording, just doubled.

## Load rows

`bank.blends[name].samples` is `[row 0, row 1]` = **row 0 off-throttle / low load, row 1 on-throttle / high load**.
Verified against the engine: helix-web-engine-new `systems/engine-core/src/audio/vehicle/beamngBlend.ts`
`importBeamngBlend` (`loadAxisOrder ?? 'offLoad-first'`: `offIndex = 0`, `onIndex = 1`), which `packageBank.ts`
`resolvePackageBank` calls without overriding the order. A BeamNG blend's rows are kept as authored; a one-row blend
serves both rows.

## Sources

### BeamNG mods

| what the mod names | slot |
|---|---|
| `soundConfig.sampleName` → `art/sound/blends/<name>.sfxBlend2D.json` (else the stock blend in `art_sound.zip` + FLAC ladder in `audio.zip`) | `engineLadder` |
| `soundConfigExhaust.sampleName` (`"0"` = combined) | `exhaustLadder` |
| `starterSample` / `starterSampleExhaust` | `startup` |
| `shutOffSampleEngine` / `shutOffSampleExhaust` | `shutdown` |
| `instantAfterFireSound` / `sustainedAfterFireSound` / `shiftAfterFireSound` | `backfire` |
| `turbocharger.whineLoopEvent` | `turboSpool` |
| `bovSoundFileName` | `blowOff` |
| `gearWhineInputEvent` / `gearWhineOutputEvent` | `transmissionWhine` |
| `shiftSoundEventSequentialGearUp` / `...GearDown`, `shiftSoundEventHPatternGearIn` / `...GearOut`, `shiftSoundEventSingleAxisLever` | `shiftUp` / `shiftDown` |
| coupler `detachSoundEvent` / `attachSoundEvent` naming `Latches>Door` | `doorOpen` / `doorClose` (bonnet/boot latches: no HELIX slot) |
| `beepLoopName` | `reverseBeep` |
| beam `soundFile` naming a suspension event | `suspension` |
| `soundscape` rows: `horn`, `indLoop1` / `indicatorStart`, `handbrakeEngaging` | `horn`, `indicatorTick`, `handbrake` |
| `art/sound/**`, `vehicles/*/sounds/**` files no field names | by file name (`horn`, `door_open`, `gearup`, `blowoff`, `limiter` ...; a skid or brake file is dropped, those slots are retired) |
| `hissLoopEvent`, supercharger `whineLoopEvent`, light switches, bonnet/boot latches | reported as unmapped (no HELIX slot) |

What BeamNG plays when no selected part names a sound (filled with `--beamng-root`; the evidence is the game's own Lua):

| slot | stock event (sample choice) | evidence |
|---|---|---|
| `startup` | `Engine/Starter/Old_V2` (the start take) | `combustionEngine.lua` starterSample default |
| `backfire` | `Vehicle/Afterfire/01_Single_EQ1` | `combustionEngineThermals.lua` |
| `transmissionWhine` | `Vehicle/Transmission/helical_01/twine_in` | `manualGearbox.lua` |
| `shiftUp` / `shiftDown` | `Vehicle/Interior/Gearshift/manual_modern_01_in` / `_out` | `hPattern.lua` |
| `tyreRollSlow` / `tyreRollFast` | `Surfaces/roll_rigid_v2` (asphalt slow / fast) | `sounds.lua` rigidRoll |
| `impactLight` / `impactMedium` / `impactHeavy` | `Destruction/Vehicle/vehicle_part_impact` (sml / med / lrg) | `sounds.lua` impactGenericEvent |
| `suspension` | `Vehicle/Suspension/car_modn_med_01/spring_compress_01` | common beamSounds |
| `doorOpen` / `doorClose` | `Vehicle/Latches/Door/modern_03_open` / `_close` | common door couplers |
| `handbrake` | `Vehicle/Interior/Handbrake_Ratchet/Ratchet_01_Ratchet` | common soundscape |
| `indicatorTick` | `Vehicle/Interior/Indicator/AU3_Click` | common `soundscape_indicator1` |
| `turboSpool` / `blowOff` (turbo cars only) | `Vehicle/Forced_Induction/Turbo_01/turbo_spin` / `turbo_bov` | turbocharger defaults |

`shutdown`, `clutch`, `intake` and `revLimiter` have no base-game default: BeamNG plays nothing for them unless a part
names one, so they stay empty until a `--map` source provides them.

`tyreSqueal`, `tyreScrub`, `tyreSpin`, `skid` and `brakeSqueal` are retired (engine-core 0.1.51 deleted every tyre and brake squeal): `audio-import` never emits them, and a `--map` entry naming one is ignored with a warning. `idle` names the lowest off-throttle
engine rung, unconsumed (the runtime idles on the ladder). Two consumed slots that resolve to the same recording keep
it once; the second is unconsumed with the reason. A cross-role match between rows that cite the same sourced take
(same source file, sha256, take and transforms) is the sim's own choice to play one recording for both roles, so
audio-check does not call it `AUDIO_NEAR_DUPLICATE_SOUNDS`; unsourced reuse still fails it.

`vehicle publish` uploads, provisions and seals the assets of every slot, consumed or not: they are all in the
Package's runtime closure, which the engine validator requires to be complete. `vehicle preview` serves them from
disk the same way (a url-less one stops the car being presented), and `audio-check` verifies each one loads — a
local file or a url that answers 200 with the declared digest and size, decoding as a WAV — without judging it as a
played sound (`AUDIO_SOURCE_MISSING`, `AUDIO_ROW_NOT_LOADABLE`, `AUDIO_URL_NOT_FOUND`, `AUDIO_CHECKSUM_MISMATCH`,
`AUDIO_NOT_WAV`, `AUDIO_NOT_IN_CLOSURE` apply; the loudness/pitch/duplicate gates do not).

### Assetto Corsa / ACC

`content/cars/<car>/sfx/<car>.bank` (FMOD Studio 1.x, FMT `0x50`; metadata and FSB5 samples in one file) and
`content/sfx/GUIDs.txt` (event paths; Kunos variants such as `ferrari_f40_s3` share GUIDs, the bank's own car wins).

| event | slots |
|---|---|
| `engine_ext` (preferred) / `engine_int` | `engineLadder` (exhaust layer: `combined-with-engine`) |
| `backfire_ext` / `_int` | `backfire` |
| `door` | `doorOpen`, `doorClose` (by sample name) |
| `gear_ext` / `_int` | `shiftUp`, `shiftDown` |
| `horn`, `limiter` | `horn`, `revLimiter` |
| `skid_ext` / `_int` | unmapped (retired) |
| `transmission` | `transmissionWhine` |
| `turbo` | `turboSpool`, `blowOff` |
| `wheel` | `tyreRollSlow` |
| `gear_grind`, `bodywork`, `wind`, `tractioncontrol_*` | unmapped |

The engine ladder comes from the event's `rpms` parameter sheet. Each instrument has an **auto-pitch reference** (the
rpm it was recorded at; INST float at +69, measured against the samples' spectra: the F40's exterior on-throttle set is
four takes recorded at 4,600 rpm) and volume fades on `rpms` (CTRL property 4 + CURV points) that make it the dominant
voice over a plateau. Kunos spreads several takes recorded at one rpm across the rev range by auto-pitch; a HELIX rung
is one recording per rpm, so each instrument becomes:

- reference rpm inside its plateau → the recording itself at its reference rpm;
- otherwise → the recording as FMOD plays it at the plateau's anchor (centre, or its open edge), i.e. a varispeed by
  anchor/reference (`fmod-autopitch-varispeed`, ratio recorded). `--ac-native-rungs` keeps only unchanged rungs.

Rows: `_off_` samples → row 0, `_on_` → row 1; an idle take with neither joins both.

## `--map`: one car from several sources

```json
{
  "sources": {
    "ac":   { "path": "/mnt/d/SteamLibrary/steamapps/common/assettocorsa/content/cars/ferrari_f40", "sim": "ac" },
    "euan": { "path": "../mods/euan-f40-0.38.zip", "sim": "beamng", "vehicle": "gabryf40", "config": "LM (EU).pc", "modUrl": "https://..." },
    "bng":  { "path": "/mnt/d/SteamLibrary/steamapps/common/BeamNG.drive", "sim": "beamng-base" },
    "rec":  { "path": "../reference-sound", "sim": "recording", "mod": "993 cold start, field recording", "modUrl": "https://youtu.be/..." }
  },
  "slots": {
    "engineLadder": { "source": "euan", "blend": "art/sound/blends/f40engine.sfxBlend2D.json" },
    "exhaustLadder": { "source": "euan", "blend": "f40exhaust" },
    "startup":   { "source": "euan", "sample": "F40_LM_Start" },
    "blowOff":   { "source": "euan", "sample": "bovf40", "trim": { "startS": 0, "endS": 0.9 } },
    "doorClose": { "source": "ac", "sample": "door_close" },
    "shutdown":  { "event": "event:>Engine>Shutoff>v8flat_1986_eng", "sample": "Auto_Maserati_Exterior_Start_Idle_Engine_01_SHUTOFF_right" },
    "intake":    { "source": "rec", "file": "intake-1.mp3" },
    "horn": { "concat": [
      { "event": "event:>Vehicle>Electrics>Horns>BM1_V1", "sample": "<start take>" },
      { "event": "event:>Vehicle>Electrics>Horns>BM1_V1", "sample": "<loop take>", "repeat": 9 },
      { "event": "event:>Vehicle>Electrics>Horns>BM1_V1", "sample": "<end take>" } ] },
    "reverseBeep": { "absent": "not-fitted", "reason": "the Ferrari F40 has no reverse beeper" }
  },
  "ladder": { "rpm": { "F40_ex_on_mid": 5700 }, "prefer": "exterior", "nativeRungs": false },
  "cylinders": 8, "strokes": 4, "crankLayout": "flat-plane", "bankId": "ferrari-f40", "modUrl": "https://..."
}
```

- The positional source is `main`; slots the map does not name come from `main` (then, with `--beamng-root`, the
  base game's default). Paths are relative to the map file.
- A pick on a BeamNG mod (`sample` / `field`) is a jbeam field, the value it names, or a recording the mod ships
  (path, or a bare stem such as `F40_LM_Start` / `bovf40` — extension-less jbeam references resolve the same way). On an
  Assetto Corsa source `sample` is the FMOD subsound name (`event` narrows to one event).
- `event` names a BeamNG stock FMOD event (`event:>A>B>C`, `event:/A/B/C`, or `A/B/C`); `sample` then picks one take of
  it exactly. A stock event without a `source` is resolved in the `--beamng-root` install.
- `blend` (on `engineLadder` / `exhaustLadder`, or `ladder.blend` / `ladder.engineBlend` / `ladder.exhaustBlend`) picks a
  blend the mod ships that no selected part names (an Automation export whose jbeam names a stale `sampleName`).
- `trim: { startS, endS }` keeps a window of a longer real recording; `concat` plays several pieces in order (`repeat`
  per piece), e.g. a stock horn's start + loop + end. Both are recorded in `provenance.transforms`
  (`{ kind: "trim", startS, endS }`, `{ kind: "concat", detail }`) and the pieces in `provenance.pieces`; nothing is
  mixed, filtered or generated.
- `sim: "recording"` sources take real recordings of the car (`file`); they carry `provenance.kind: "recording"`.
- `notFitted: "<reason>"` or `absent: "not-fitted"` + `reason` declares a part the real car lacks; `empty: "<reason>"`
  leaves a slot empty on purpose (audio-check still fails it).

## Electric cars

An EV is recognised from what the package says the car is: `physics.engine.cylinders` 0, an electric engine/motor
declaration, or (for a bare `audio.json`) a motor ladder: blend provenance with `motor: true` or `pitchAutomation`. Never from
`audio.drivetrain: "electric"`: that switches the runtime to its synthesised motor voice and ignores recorded ladders,
so audio-check fails it as `AUDIO_SYNTHESISED`.

- The motor is still a recorded engine ladder (`AUDIO_ENGINE_UNSOURCED` otherwise). BeamNG's electric motors name a
  stock blend with no rung samples (`ElectricMotor_02` -> `event:>Engine>Bands>Real>electric_eng_02`, one loop re-pitched
  by an `RPM` pitch automation on the event's master bus). audio-import builds the ladder from that event: rungs at
  1,000 rpm then every 2,000 rpm up to the motor's `maxRPM` (or `ladder.rungs` / `ladder.maxRpm` / the automation's
  span), each the recording at the rate the automation plays it there (normalised pitch -1..1 = -24..+24 semitones),
  recorded as `fmod-pitch-automation-varispeed`; the blend provenance keeps the curve. A map can name the event
  directly: `{"slots": {"engineLadder": {"event": "event:/Engine/Bands/Real/electric_eng_02"}}}`. An event with a second
  simultaneous loop puts it on the exhaust layer.
- A recorded blend taken from an electric car (its selected parts' powertrain has an `electricMotor`) is a motor ladder
  too: no cylinder count is asked for (`sampleCylinderCount` 1; the playback rate is rpm / rung rpm either way) and its
  blend provenance says `motor: true`.
- `not-fitted` is allowed for every combustion slot (exhaustLadder, idle, startup, shutdown, clutch, turboSpool,
  blowOff, intake, revLimiter, backfire) and, on a single-speed drive (one forward ratio), shiftUp / shiftDown.
  transmissionWhine stays required: the reduction gear whines.
- The firing-fundamental pitch gate does not apply to a motor ladder. Rungs the source itself re-pitched from one take
  (FMOD auto-pitch, an event's pitch automation) are not called resampled copies (`AUDIO_LADDER_RUNG_COPY`,
  `AUDIO_NEAR_DUPLICATE_RUNGS`). The near-pure-tone gate is unchanged: the stock BeamNG whine and 12 real Model S
  clips pass it as they are.

## The rung pitch gate

`AUDIO_RUNG_PITCH_OCTAVE_OFF` used to come from a periodicity tracker alone, which locks onto the engine-cycle
sub-harmonic that real flat-plane V8 and flat-six recordings carry: it failed every real F40 ladder. It now decides on a
comb cross-check first (`firingCombRatio`, the f40-r8 owner-proxy's `firing_xcheck.py`): summed spectral peaks on the
labelled firing series k × f — or on its half-order series k × f/2, which each bank's collector puts into a real
recording — over the comb between the teeth. >= 3: pitched at its label; < 1.5: off its label (error); between:
ambiguous (warning). Measured on 130 real F40 rungs (Kunos AC, euan and Gabry BeamNG mods): 0 below 1.5, 11 between.
Two-octaves-down copies of the same rungs fall below 1.5 on 128 of 130, one-octave-down copies on 74; round 7's
crank-order synthetic rung measures about 0.6.

## Known limits

- Real Assetto Corsa recordings clip and carry DC offset (the F40's `F40_ex_on_low_2`: 18% of samples clipped, -0.19 FS
  DC) and fail `AUDIO_CLIPPED` / `AUDIO_DC_OFFSET`. This command never alters a recording to pass a gate.
- The mmbng 993 PSH ladder sits about 8% below its rpm labels (its dominant series is 1.38 x crank at the labelled rpm),
  so it fails the pitch gate on its own labels.
- The portable runtime plays a recorded gear whine only with a declared native pitch and has no player for a
  package's idle or intake take (idle comes from the ladder's bottom rung), so those recordings are kept unconsumed —
  and still uploaded and sealed with the package.
- FMOD metadata layouts other than FMT `0x50` (Assetto Corsa) and `0x92` (BeamNG 0.3x) are refused by version number.
