From 56871fdebfdbc0819da41f3fb5ea1f63aa419e7d Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Tue, 20 Oct 2026 06:45:02 -0500 Subject: [PATCH] feat(sound): mute every sound, add StopSound, and map channels MuteSoundFile hooked Sound::Play2D, which only interface sounds and files reach. Positional sounds (Play3D: creature voices, spell impacts, server sounds) and loops (PlayLooped: ambience, emitters) open through other routes, so they could not be muted and never reached GetRecentSoundFiles. The hooks now sit on Sound::Play (0x007A5290, behind both Play2D and Play3D) and Sound::PlayLooped (0x007A54D0). StopSound(handle [, fadeoutTime]) calls Sound::Stop2 (0x007A5A10). It stops only handles our play functions returned, because releasing a record the engine holds in a slot would free it under that slot. PlaySoundFile makes the engine's own Play2D(3, file) call, adds the channel's category flag, and returns willPlay, soundHandle. The channel argument now picks the volume category by name, as 4.3.4's _PickScriptSoundBus does. This replaces the numeric bus, which exposed the engine's per-bus concurrency caps. forceNoDuplicates sets the sound definition's own duplicate bit for the call. SoundKit plays now respect the interface-sound suppression count, as PlaySound(name) does. --- docs/API.md | 51 ++++++- src/Offsets.h | 89 +++++++---- src/sound/Mute.cpp | 66 ++++---- src/sound/Play.cpp | 364 +++++++++++++++++++++++++++------------------ 4 files changed, 364 insertions(+), 206 deletions(-) diff --git a/docs/API.md b/docs/API.md index 62ee1c92..5c7fc6bb 100644 --- a/docs/API.md +++ b/docs/API.md @@ -658,6 +658,8 @@ build instructions. - [`C_Sound.PlaySoundWithOptions(params)`](#c_soundplaysoundwithoptionsparams) - [`C_Sound.GetSoundScaledVolume(soundHandle)`](#c_soundgetsoundscaledvolumesoundhandle) - [`C_Sound.IsPlaying(soundHandle)`](#c_soundisplayingsoundhandle) + - [`StopSound(soundHandle [, fadeoutTime])`](#stopsoundsoundhandle--fadeouttime) + - [`PlaySoundFile(file [, channel])`](#playsoundfilefile--channel) - [`C_Sound.PlayItemSound(soundType, item)`](#c_soundplayitemsoundsoundtype-item) - [`C_Sound.PlayVocalErrorSound(vocalErrorSoundID)`](#c_soundplayvocalerrorsoundvocalerrorsoundid) - [`MuteSoundFile(file)` / `UnmuteSoundFile(file)`](#mutesoundfilefile--unmutesoundfilefile) @@ -4926,6 +4928,9 @@ C_Sound.PlaySound(8959, nil, nil, true) |---|---| | `arg1` | `soundHandle` — the handle [`C_Sound.PlaySound`](#c_soundplaysoundsoundkitid--channel-forcenoduplicates-runfinishcallback) returned for the sound that just ended. | +A sound stopped with [`StopSound`](#stopsoundsoundhandle--fadeouttime) +also sends the event. + It fires **only** for sounds played with `runFinishCallback` set to `true`. Sounds played any other way report nothing — every footstep and button click would otherwise raise an event. @@ -15578,16 +15583,18 @@ local willPlay, handle = C_Sound.PlaySound(8959) ``` `willPlay` is `false` when the sound cannot start. That happens when the -file is muted, when the id names no entry, or when the category already -has as many sounds as it allows. +file is muted, when the id names no entry, or when a duplicate is +refused. It is also `false` while the interface loads, and while you +enter or leave the world. `PlaySound` with a sound name is silent at +those times too. An entry can hold several files. The client picks one of them, with the same weighting it uses for its own sounds. | Argument | Meaning | |---|---| -| `channel` | The sound category, `0` to `12`. Leave it out for `0`, which is what the client uses for interface sounds and music. A channel **name** such as `"SFX"` is accepted and ignored: the categories here do not match those names. | -| `forceNoDuplicates` | Accepted and ignored. | +| `channel` | The volume slider that applies: `"SFX"`, `"Music"`, `"Ambience"` or `"Master"`. Upper and lower case do not matter. Leave it out, or give another value, for `"SFX"`. `"Master"` uses only the master volume. `"Ambience"` uses the sound volume for a SoundKitID. | +| `forceNoDuplicates` | Pass `true` to play nothing while the same file is already playing. An entry with several files can still play a second copy if the client picks a different file. | | `runFinishCallback` | Pass `true` to get the [`SOUNDKIT_FINISHED`](#soundkit_finished-event) event when this sound ends. | ### `C_Sound.PlaySoundWithOptions(params)` @@ -15608,8 +15615,8 @@ local ok, handle = C_Sound.PlaySoundWithOptions({ | `soundKitID` | The sound to play. | | `volumeOverride` | Scales the sound's volume. `1` leaves it alone, `0` is silent. Leave it out to play at the sound's own volume. | | `runFinishCallback` | Pass `true` to get the [`SOUNDKIT_FINISHED`](#soundkit_finished-event) event when this sound ends. | +| `forceNoDuplicates` | Pass `true` to play nothing while the same file is already playing. | | `uiSoundSubType` | Accepted and ignored. | -| `forceNoDuplicates` | Accepted and ignored. | | `overridePriority` | Accepted and ignored. | ### `C_Sound.GetSoundScaledVolume(soundHandle)` @@ -15636,6 +15643,40 @@ the client can give the same handle value to a later sound, so a handle you have held for a while can report `true` for a different sound. Read it soon after you get it. +### `StopSound(soundHandle [, fadeoutTime])` + +Stops a sound that one of the play functions on this page started. + +```lua +local _, handle = C_Sound.PlaySound(8959) +StopSound(handle) -- stops at once +StopSound(handle, 1500) -- fades out over 1.5 seconds +``` + +`fadeoutTime` is in milliseconds. A fade shorter than 100 ms stops the +sound at once. `StopSound` does nothing when the sound has already ended. +It also does nothing for a sound that the client started itself, such as +music or ambience. + +A stopped sound with `runFinishCallback` set sends +[`SOUNDKIT_FINISHED`](#soundkit_finished-event) when it ends. + +### `PlaySoundFile(file [, channel])` + +Plays an audio file by its path. Returns `willPlay, soundHandle`. + +```lua +local willPlay, handle = PlaySoundFile("Sound\\Interface\\RaidWarning.wav", "Master") +``` + +`channel` takes the same values as in +[`C_Sound.PlaySound`](#c_soundplaysoundsoundkitid--channel-forcenoduplicates-runfinishcallback). +For a file, `"Ambience"` uses the ambience volume. + +Only two files from `PlaySoundFile` can play at the same time. While two +play, a third returns `false`. Give the handle to +[`StopSound`](#stopsoundsoundhandle--fadeouttime) to stop the file before it ends. + ### `C_Sound.PlayItemSound(soundType, item)` Plays the noise an item makes when you handle it, without doing the action. diff --git a/src/Offsets.h b/src/Offsets.h index 540bf81b..7053aa25 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -7680,37 +7680,68 @@ enum Offsets { // ---- Sound playback ------------------------------------------------ // - // `FUN_007A5450` is the ONE funnel every sound in this client passes - // through: `int *__fastcall(int category /*ecx*/, const char *path - // /*edx*/, uint flags, char deferStart)`. It returns the stream object, - // or NULL when the sound did not start — the engine's own "didn't - // play" answer, produced by its pre-play gate `FUN_007A66A0` (per - // category active-count limit, plus a by-path-hash dedup when - // `flags & 1`). Every caller already handles NULL, which is what makes - // muting expressible here: return NULL and nothing else changes. + // Every sound in this client is an FMOD stream opened by path (the + // binary links only FSOUND_Stream_*), and every open ends in one of + // TWO engine functions (benilla-re sound/engine, xrefs confirmed in + // Ghidra): + // Sound::Play `int *__fastcall(int bus, const char *path, + // uint mode, char held, uint flags)`, RET 0xC. + // Reached only from Play2D (`FUN_SOUND_PLAY_2D`) + // and Play3D (`0x007A5490`, every positional sound: + // creature voices, spell impacts, server sounds). + // Sound::PlayLooped `int *__fastcall(int bus, const char *path, + // int loopCount, uint mode, char held, uint flags)`, + // RET 0x10. Ambience, emitters, 2D/3D loops. + // Both return the Sound record, or NULL when nothing started — the + // engine's own "didn't play" answer (Play2D/Play3D also return NULL + // from their pre-play gate `0x007A66A0`: the bus cap, and the by-path + // duplicate check when `flags & 1`), which every caller handles. That + // is what makes muting expressible: return NULL and nothing else + // changes. Play2D alone is NOT a funnel — it misses every 3D and + // looped sound. // - // Six callers, and they are the whole surface: Script_PlaySoundFile - // (`FUN_00458780`, category 3), the SoundEntries player - // `FUN_SOUND_PLAY_ENTRY` (which is where `PlaySound` and every - // DBC-driven spell/creature/UI sound lands), and four music/ambience - // paths (`FUN_0045AE50`, `FUN_00460240`, `FUN_00461290`, - // `FUN_007A5620`, all category 0). There is no second route: the - // binary links only FMOD's FSOUND_Stream_* API — no - // FSOUND_Sample_Load, no FSOUND_PlaySound — so every sound, however - // short, is a stream opened by path. - // - // `category` indexes per-category state (`0x00CF553C[c]` active count - // against the cap at `0x0087CE60[c]`), and `FUN_007A66A0` rejects - // `c > 0xC`, so the valid range is 0..12. - FUN_SOUND_PLAY_BY_PATH = 0x007A5450, - SOUND_CATEGORY_MAX = 0x0C, + // `flags` low byte picks the volume category: 0x2 Music (also exempt + // from the sound-effects switch), 0x8 Ambience, 0x10 Master only, + // otherwise Sound. `bus` is one of 13 concurrency buses (caps at + // `0x0087CE60`: 2^31-1, 1, 2, 2, 1, 1, 2, 2, 1, 6, 4, 1, 2); bus 3 is + // the one Script_PlaySoundFile (`0x00458780`) uses. + FUN_SOUND_OPEN = 0x007A5290, + FUN_SOUND_OPEN_LOOPED = 0x007A54D0, + // Sound::Play2D — `int *__fastcall(int bus, const char *path, uint + // flags, char held)`, RET 0x8: the pre-play gate, then FUN_SOUND_OPEN + // with mode 0x82000. + FUN_SOUND_PLAY_2D = 0x007A5450, + SOUND_BUS_PLAY_SOUND_FILE = 3, + SOUND_FLAG_MUSIC = 0x02, + SOUND_FLAG_AMBIENCE = 0x08, + SOUND_FLAG_NO_CATEGORY = 0x10, - // SoundEntries player — `void *__fastcall(char orFlag4 /*ecx*/, char - // orFlag10 /*edx*/, int category, int soundEntryID, int variantIndex, - // int orFlag2)`, RET 0x10, returning the stream object or NULL. - // Resolves the row (`FUN_0045CDA0`), picks one of its up-to-10 file - // variants (`FUN_0045BB70`; `variantIndex = -1` takes the weighted - // random pick the engine uses), then calls FUN_SOUND_PLAY_BY_PATH. + // Sound::Stop2 — `void __thiscall(Sound *, float seconds)`, RET 0x4. + // Fades the sound out and releases it at silence, or releases it at + // once below 0.1 s (benilla-re sound/engine#fades). Releasing frees + // the record, so only a sound no engine slot holds may be stopped. + FUN_SOUND_STOP = 0x007A5A10, + + // Interface-sound suppression count: `PlaySound(name)` + // (SndInterfacePlayInterfaceSound `0x00458030`) plays nothing while it + // is above 0. The UI load and the world enter/leave paths raise it + // around themselves (`0x00458F50` / `0x00458F60`). + VAR_INTERFACE_SOUND_SUPPRESS = 0x00B05FA0, + + // Sound definition (`FUN_SOUND_ENTRY_FOR_ID`'s result) flags, copied + // from the SoundEntries row. Bit 0x20 asks the play for the by-path + // duplicate check (`0x00458F40`: `([def+0x7C] >> 5) & 1`). + OFF_SOUND_DEFINITION_FLAGS = 0x7C, + SOUND_DEFINITION_FLAG_NO_DUPLICATES = 0x20, + + // SoundEntries player (InternalPlaySound) — `void *__fastcall(char keep + // /*ecx, flag 0x4*/, char noCategory /*edx, flag 0x10*/, int bus, int + // soundEntryID, int variantIndex, int music /*flag 0x2*/)`, RET 0x10, + // returning the Sound record or NULL. Resolves the definition + // (`FUN_0045CDA0`), picks one of its up-to-10 file variants + // (`FUN_0045BB70`; `variantIndex = -1` takes the weighted random pick + // the engine uses), then calls FUN_SOUND_PLAY_2D with the definition's + // duplicate bit as flag 0x1. // // ABI verified by disassembly, NOT the decompile — Ghidra maps the // arguments inconsistently against the call site. `FUN_00458850`, the diff --git a/src/sound/Mute.cpp b/src/sound/Mute.cpp index b92dd65d..70509f0f 100644 --- a/src/sound/Mute.cpp +++ b/src/sound/Mute.cpp @@ -19,19 +19,18 @@ // meaningful here, since file ids are a later scheme. The path is the one // the engine itself uses, e.g. "Sound\Creature\Ragnaros\RagnarosAggro01.wav". // -// HOW: one co-hook on FUN_SOUND_PLAY_BY_PATH, the single funnel every sound -// passes through (see Offsets.h for why there is no second route — this -// client links only FMOD's streaming API, so even a one-shot UI click is a -// stream opened by path). A muted path returns NULL, which is the engine's -// OWN "this did not play" answer: its pre-play gate `FUN_007A66A0` already -// produces NULL for a category that is at its concurrency cap, so every -// caller in the binary already handles it, and `PlaySoundFile` already -// reports it to Lua as nil. Muting therefore needs no new failure path. +// HOW: co-hooks on the two engine functions every sound open ends in — +// Sound::Play (FUN_SOUND_OPEN, behind both the 2D and the 3D opener) and +// Sound::PlayLooped (FUN_SOUND_OPEN_LOOPED, ambience and emitters). See +// Offsets.h for why there is no third route. A muted path returns NULL, +// which is the engine's OWN "this did not play" answer: its pre-play gate +// `0x007A66A0` already produces NULL for a bus at its cap, and a failed +// stream open does the same in both functions, so every caller in the +// binary already handles it. Muting therefore needs no new failure path. // // Suppressing the open rather than muting the opened stream is deliberate: // nothing is decoded for a sound nobody hears. The one visible difference -// from a true mute is that `PlaySoundFile` returns nil for a muted file -// instead of 1. +// from a true mute is that a play call reports a muted file as not played. // // WHY THE RECENT LIST IS ALWAYS ON: the hook exists for muting regardless, // and recording costs one bounded copy into a preallocated slot on a call @@ -147,19 +146,33 @@ void Record(const char *path, bool muted) { r.muted = muted; } -using PlayByPath_t = void *(__fastcall *)(int category, const char *path, - unsigned flags, char deferStart); -PlayByPath_t g_playByPath = nullptr; +// Records the open and answers whether it must be refused. +bool Refuse(const char *path) { + if (path == nullptr || *path == '\0') + return false; + const bool muted = IsMuted(path); + Record(path, muted); + return muted; +} -void *__fastcall PlayByPath_h(int category, const char *path, unsigned flags, - char deferStart) { - if (path != nullptr && *path != '\0') { - const bool muted = IsMuted(path); - Record(path, muted); - if (muted) - return nullptr; // exactly what the engine's own gate returns - } - return g_playByPath(category, path, flags, deferStart); +using Open_t = void *(__fastcall *)(int bus, const char *path, unsigned mode, char held, + unsigned flags); +using OpenLooped_t = void *(__fastcall *)(int bus, const char *path, int loopCount, + unsigned mode, char held, unsigned flags); +Open_t g_open = nullptr; +OpenLooped_t g_openLooped = nullptr; + +void *__fastcall Open_h(int bus, const char *path, unsigned mode, char held, unsigned flags) { + if (Refuse(path)) + return nullptr; // exactly what the engine's own failures return + return g_open(bus, path, mode, held, flags); +} + +void *__fastcall OpenLooped_h(int bus, const char *path, int loopCount, unsigned mode, + char held, unsigned flags) { + if (Refuse(path)) + return nullptr; + return g_openLooped(bus, path, loopCount, mode, held, flags); } // MuteSoundFile(path) -> true when the path is now muted, false for a bad @@ -233,9 +246,12 @@ void RegisterLuaFunctions() { } const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; -const Game::HookAutoRegister _hook{Offsets::FUN_SOUND_PLAY_BY_PATH, - reinterpret_cast(&PlayByPath_h), - reinterpret_cast(&g_playByPath)}; +const Game::HookAutoRegister _openHook{Offsets::FUN_SOUND_OPEN, + reinterpret_cast(&Open_h), + reinterpret_cast(&g_open)}; +const Game::HookAutoRegister _openLoopedHook{Offsets::FUN_SOUND_OPEN_LOOPED, + reinterpret_cast(&OpenLooped_h), + reinterpret_cast(&g_openLooped)}; } // namespace diff --git a/src/sound/Play.cpp b/src/sound/Play.cpp index 501333c7..89a2c94a 100644 --- a/src/sound/Play.cpp +++ b/src/sound/Play.cpp @@ -12,9 +12,11 @@ // ClassicAPI. If not, see . // `C_Sound.PlaySound(soundKitID [, channel [, forceNoDuplicates -// [, runFinishCallback]]])`, `C_Sound.IsPlaying(soundHandle)`, the -// `SOUNDKIT_FINISHED` event, and the global `PlaySound` widened to take a -// SoundKitID as well as the row name it has always taken. +// [, runFinishCallback]]])`, `C_Sound.PlaySoundWithOptions`, +// `C_Sound.IsPlaying`, `C_Sound.GetSoundScaledVolume`, `StopSound`, the +// `SOUNDKIT_FINISHED` event, the global `PlaySound` widened to take a +// SoundKitID as well as the row name it has always taken, and +// `PlaySoundFile` widened to take a channel and return a handle. // // A SoundKitID is a SoundEntries.dbc row id — the same ids the modern // client's SOUNDKIT constants carry, because it is the same table under a @@ -28,13 +30,20 @@ // SOUNDKIT ids could not play a single sound here, even though every id was // already valid. // -// `FUN_SOUND_PLAY_ENTRY` does the work and returns the stream object, which -// is the handle. See Offsets.h for its ABI, which was taken from the -// disassembly rather than the decompile (Ghidra maps its arguments -// inconsistently against the call site). We pass variantIndex -1 so a row -// with several files picks one the same weighted-random way the engine does -// for its own sounds, and leave all three flag bytes clear, matching -// `PlaySound`. +// `FUN_SOUND_PLAY_ENTRY` (InternalPlaySound) does the work and returns the +// Sound record, which is the handle. See Offsets.h for its ABI, which was +// taken from the disassembly rather than the decompile. We pass +// variantIndex -1 so a row with several files picks one the same +// weighted-random way the engine does for its own sounds. +// +// CHANNELS are the volume categories, picked the way 4.3.4's +// `_PickScriptSoundBus` picks them: "Master", "Music" and "Ambience" +// (case-insensitive), anything else or nothing is "SFX". Here a category +// is a flag on the sound (Offsets.h, SOUND_FLAG_*), not the bus, which only +// caps concurrency. InternalPlaySound takes the Music and Master flags as +// arguments but has no Ambience argument, so a SoundKit on "Ambience" +// plays on the Sound slider; a FILE on "Ambience" is exact, because +// Play2D takes the flags whole. #include "Game.h" #include "Offsets.h" @@ -42,22 +51,24 @@ #include "tick/WorldTick.h" #include +#include #include namespace Sound::Play { namespace { -// `void *__fastcall(char orFlag4, char orFlag10, int category, -// int soundEntryID, int variantIndex, int orFlag2)` -using PlaySoundEntry_t = void *(__fastcall *)(char, char, int, int, int, int); +using PlaySoundEntry_t = void *(__fastcall *)(char keep, char noCategory, int bus, + int soundEntryID, int variantIndex, int music); +using Play2D_t = void *(__fastcall *)(int bus, const char *path, unsigned flags, char held); +using Stop_t = void(__thiscall *)(void *sound, float seconds); using ScriptFn_t = int(__fastcall *)(void *L); constexpr int kVariantRandom = -1; // the engine's own weighted pick -// A stream object is freed once the sound ends, so a stale handle must -// never be dereferenced. Membership of the engine's live stream list is the -// safe test — the same list its dedup pass walks (`FUN_007A66A0`): an +// A Sound record is freed once the sound ends, so a stale handle must +// never be dereferenced. Membership of the engine's live list is the safe +// test — the same list its dedup pass walks (`FUN_007A66A0`): an // intrusive list whose `next` sits at +0x04, ended by a null or a // low-bit-tagged sentinel. Returns the node so a caller that needs a field // off it reads only a node that is provably still there. @@ -77,152 +88,172 @@ uintptr_t FindStreamNode(uintptr_t handle) { return 0; // cycle or corruption — never spin inside a Lua call } -bool HandleAlive(uintptr_t handle) { return FindStreamNode(handle) != 0; } - uint32_t PathHash(uintptr_t node) { return *reinterpret_cast( node + Offsets::OFF_SOUND_STREAM_PATH_HASH); } -// Re-apply a row's volume to a already-started stream at `scale`. The by-id -// player runs this with 1.0 as it starts the sound, and the setter writes -// rather than accumulates, so a second call simply replaces the volume. -using SoundEntryForID_t = void *(__fastcall *)(unsigned soundEntryID); -using ApplyRowVolume_t = void(__thiscall *)(void *row, void *stream, float scale); - -void ApplyVolumeScale(int soundKitID, void *handle, float scale) { - void *row = reinterpret_cast(Offsets::FUN_SOUND_ENTRY_FOR_ID)( - static_cast(soundKitID)); - if (row == nullptr) - return; - reinterpret_cast(Offsets::FUN_SOUND_APPLY_ROW_VOLUME)(row, handle, scale); -} - -// ---- SOUNDKIT_FINISHED ------------------------------------------------ +// ---- Sounds we started ------------------------------------------------- // -// Fires with the sound handle once that sound stops, and ONLY for sounds -// started with `runFinishCallback` — which is both the documented contract -// and the reason this is affordable. Without the opt-in every footstep and -// UI click would dispatch a Lua event. +// Every sound one of our play functions starts is remembered with its +// path hash until it ends. Two things need it: // -// Detected on the world tick rather than from FMOD's end callback: that -// callback (`FUN_007A53C0`) runs on the STREAMER thread and only defers the -// stream onto a list under a critical section. Firing a Lua event from -// there would call into the VM off the main thread. The engine notices -// completion on its own side in `FUN_007A4B60`, from the per-frame sound -// update — so a main-thread check is what the engine itself does. +// - StopSound may only stop these. Stopping releases the Sound record, and +// the engine keeps records of its own in slots (music, ambience, kept +// sounds with flag 0x4); freeing one of those under its slot would be a +// use-after-free. A handle we returned was started with no keep flag and +// is held by nobody but the caller. +// - SOUNDKIT_FINISHED fires for the ones started with `runFinishCallback`. // -// A tracked entry keeps the stream's path hash alongside the handle. -// Stream objects are pooled and their addresses reused, so "the handle is +// Sound records are pooled and their addresses reused, so "the handle is // still in the list" is not enough on its own: a later sound can land on -// the same address. Comparing the hash too means only the same file -// replaying at the same address can be mistaken for the original, and that -// costs one extra dword read of a node we have already found alive. -const Event::Custom::AutoReserve _soundkitFinished{"SOUNDKIT_FINISHED"}; - -struct Tracked { +// the same address. Comparing the path hash too means only the same file +// replaying at the same address can be mistaken for the original. +// +// Ends are detected on the world tick rather than from FMOD's end +// callback: that callback (`FUN_007A53C0`) runs on the STREAMER thread and +// only defers the stream onto a list under a critical section. The engine +// notices completion in `FUN_007A4B60`, from the per-frame sound update — +// so a main-thread check is what the engine itself does. +struct Owned { uintptr_t handle; uint32_t pathHash; + bool notifyFinish; }; -// Only ever holds sounds a caller opted in for, so it is empty almost -// always and never needs a cap. -std::vector g_tracked; +// Holds only sounds an addon started that are still playing, so it is a +// handful of entries at most. +std::vector g_owned; -void TrackForFinish(uintptr_t handle) { - const uintptr_t node = FindStreamNode(handle); +void Own(void *sound, bool notifyFinish) { + const uintptr_t node = FindStreamNode(reinterpret_cast(sound)); if (node == 0) - return; // already over, or never started — nothing to report - g_tracked.push_back({handle, PathHash(node)}); + return; // already over — nothing to stop or report + g_owned.push_back({node, PathHash(node), notifyFinish}); } +bool StillPlaying(const Owned &o) { + const uintptr_t node = FindStreamNode(o.handle); + return node != 0 && PathHash(node) == o.pathHash; +} + +const Event::Custom::AutoReserve _soundkitFinished{"SOUNDKIT_FINISHED"}; + void OnWorldTick() { - if (g_tracked.empty()) + if (g_owned.empty()) return; const int slot = _soundkitFinished.Slot(); size_t keep = 0; - for (size_t i = 0; i < g_tracked.size(); ++i) { - const Tracked &t = g_tracked[i]; - const uintptr_t node = FindStreamNode(t.handle); - if (node != 0 && PathHash(node) == t.pathHash) { - g_tracked[keep++] = t; // still playing + for (size_t i = 0; i < g_owned.size(); ++i) { + const Owned &o = g_owned[i]; + if (StillPlaying(o)) { + g_owned[keep++] = o; continue; } - if (slot >= 0) - Event::Custom::Fire(slot, "%u", static_cast(t.handle)); + if (o.notifyFinish && slot >= 0) + Event::Custom::Fire(slot, "%u", static_cast(o.handle)); } - g_tracked.resize(keep); + g_owned.resize(keep); } const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick}; -// Play a row by id and push `willPlay, soundHandle`. -// -// `optionalBase` is the 1-based stack index of the `channel` argument, with -// `forceNoDuplicates` and `runFinishCallback` after it — or 0 for a caller -// that takes none of them. The global `PlaySound` passes 0: it gains only -// the id form, and the fuller argument list belongs to `C_Sound.PlaySound`. -// -// `channel` is the engine's sound category (0..12; 0 is what the engine -// itself uses for UI sounds and music, 3 for a file played by path). A -// channel NAME is accepted and ignored, so code written against the modern -// string form still runs — the categories here do not correspond to it. -// -// `forceNoDuplicates` is likewise accepted and does nothing. The engine -// does have a by-path dedup, but it is bit 0 of a flag word the row itself -// supplies; the by-id player ORs in only bits 1, 2 and 4 from its -// arguments, so there is no way to ask for it without bypassing that -// player and re-deriving its weighted file pick, which would be a worse -// trade than the missing flag. -// -// `runFinishCallback` opts the sound in to SOUNDKIT_FINISHED. +// ---- Channels ---------------------------------------------------------- + +enum class Channel { SFX, Master, Music, Ambience }; + +// 4.3.4 `_PickScriptSoundBus`: a string argument picks by name, anything +// else is SFX. +Channel ChannelArg(void *L, int idx) { + if (Game::Lua::Type(L, idx) != Game::Lua::TYPE_STRING) + return Channel::SFX; + const char *name = Game::Lua::ToString(L, idx); + if (name == nullptr) + return Channel::SFX; + if (_stricmp(name, "Master") == 0) + return Channel::Master; + if (_stricmp(name, "Music") == 0) + return Channel::Music; + if (_stricmp(name, "Ambience") == 0) + return Channel::Ambience; + return Channel::SFX; +} + +unsigned ChannelFlags(Channel c) { + switch (c) { + case Channel::Master: + return Offsets::SOUND_FLAG_NO_CATEGORY; + case Channel::Music: + return Offsets::SOUND_FLAG_MUSIC; + case Channel::Ambience: + return Offsets::SOUND_FLAG_AMBIENCE; + default: + return 0; + } +} + +// ---- Playing a SoundKit ------------------------------------------------ + +using SoundEntryForID_t = void *(__fastcall *)(unsigned soundEntryID); +using ApplyRowVolume_t = void(__thiscall *)(void *def, void *sound, float scale); + // The options every play path shares, however they were spelled at the -// Lua edge. `volumeScale < 0` means "leave the row's own volume alone". +// Lua edge. `volumeScale < 0` means "leave the definition's own volume". struct PlayOptions { - int category = 0; + Channel channel = Channel::SFX; + bool noDuplicates = false; bool runFinishCallback = false; float volumeScale = -1.0f; }; -// Start `soundKitID` with `opts` and push `willPlay, soundHandle`. -int PlayWithOptions(void *L, int soundKitID, const PlayOptions &opts) { - if (soundKitID <= 0) { - Game::Lua::PushBool(L, false); - Game::Lua::PushNil(L); - return 2; - } +void *PlayKit(int soundKitID, const PlayOptions &opts) { + if (soundKitID <= 0) + return nullptr; + // `PlaySound(name)` plays nothing while the UI loads or the world is + // entered or left; the id form keeps the same quiet. + if (Game::Read(static_cast(Offsets::VAR_INTERFACE_SOUND_SUPPRESS)) > 0) + return nullptr; + auto *def = static_cast(reinterpret_cast( + Offsets::FUN_SOUND_ENTRY_FOR_ID)(static_cast(soundKitID))); + if (def == nullptr) + return nullptr; - auto play = reinterpret_cast(Offsets::FUN_SOUND_PLAY_ENTRY); - void *handle = play(0, 0, opts.category, soundKitID, kVariantRandom, 0); + // The duplicate check is the definition's own bit, which the player + // turns into the open's flag 0x1. Lend it for this one call. The check + // compares the picked FILE, so a kit with several files can still + // start a second copy on a different pick. + auto &defFlags = *reinterpret_cast(def + Offsets::OFF_SOUND_DEFINITION_FLAGS); + const uint32_t savedFlags = defFlags; + if (opts.noDuplicates) + defFlags |= Offsets::SOUND_DEFINITION_FLAG_NO_DUPLICATES; - if (handle != nullptr) { - if (opts.volumeScale >= 0.0f) - ApplyVolumeScale(soundKitID, handle, opts.volumeScale); - if (opts.runFinishCallback) - TrackForFinish(reinterpret_cast(handle)); - } + void *sound = reinterpret_cast(Offsets::FUN_SOUND_PLAY_ENTRY)( + 0, opts.channel == Channel::Master ? 1 : 0, 0, soundKitID, kVariantRandom, + opts.channel == Channel::Music ? 1 : 0); + defFlags = savedFlags; - Game::Lua::PushBool(L, handle != nullptr); - if (handle != nullptr) - Game::Lua::PushNumber(L, static_cast(reinterpret_cast(handle))); + if (sound == nullptr) + return nullptr; + // The player applies the definition's volume at scale 1.0 as it + // starts; the applicator writes rather than accumulates, so a second + // call replaces it. + if (opts.volumeScale >= 0.0f) + reinterpret_cast(Offsets::FUN_SOUND_APPLY_ROW_VOLUME)( + def, sound, opts.volumeScale); + Own(sound, opts.runFinishCallback); + return sound; +} + +// Push `willPlay, soundHandle`. +int PushResult(void *L, void *sound) { + Game::Lua::PushBool(L, sound != nullptr); + if (sound != nullptr) + Game::Lua::PushNumber(L, static_cast(reinterpret_cast(sound))); else Game::Lua::PushNil(L); return 2; } -int PlayById(void *L, int soundKitID, int optionalBase) { - PlayOptions opts; - if (optionalBase > 0) { - if (Game::Lua::Type(L, optionalBase) == Game::Lua::TYPE_NUMBER) { - opts.category = static_cast(Game::Lua::ToNumber(L, optionalBase)); - if (opts.category < 0 || opts.category > Offsets::SOUND_CATEGORY_MAX) - opts.category = 0; // the engine rejects the rest outright - } - opts.runFinishCallback = Game::Lua::ToBoolean(L, optionalBase + 2) != 0; - } - return PlayWithOptions(L, soundKitID, opts); -} - // C_Sound.PlaySound(soundKitID [, channel [, forceNoDuplicates // [, runFinishCallback]]]) -> willPlay, soundHandle int __fastcall Script_C_Sound_PlaySound(void *L) { @@ -232,7 +263,11 @@ int __fastcall Script_C_Sound_PlaySound(void *L) { "[, runFinishCallback]]])"); return 0; } - return PlayById(L, static_cast(Game::Lua::ToNumber(L, 1)), 2); + PlayOptions opts; + opts.channel = ChannelArg(L, 2); + opts.noDuplicates = Game::Lua::ToBoolean(L, 3) != 0; + opts.runFinishCallback = Game::Lua::ToBoolean(L, 4) != 0; + return PushResult(L, PlayKit(static_cast(Game::Lua::ToNumber(L, 1)), opts)); } // The global `PlaySound(soundKitID | soundName)`. @@ -243,32 +278,25 @@ int __fastcall Script_C_Sound_PlaySound(void *L) { // else tail-calls the engine with the stack untouched, so the name form // behaves exactly as it always has (it pushes no return values). // -// The id form is the ONLY thing added here — the optional channel / -// forceNoDuplicates / runFinishCallback arguments live on -// `C_Sound.PlaySound` instead, which keeps this global as close to the +// The id form is the ONLY thing added here — the optional arguments live +// on `C_Sound.PlaySound` instead, which keeps this global as close to the // one it replaces as the extension allows. // // Discriminating on `lua_type`, not `lua_isnumber`: the latter also // accepts a numeric STRING, which would quietly reroute `PlaySound("123")` -// away from the name lookup. No row in this table is named with digits, so -// nothing real is lost, but the type test is the honest rule. +// away from the name lookup. int __fastcall Script_PlaySound(void *L) { if (Game::Lua::Type(L, 1) == Game::Lua::TYPE_NUMBER) - return PlayById(L, static_cast(Game::Lua::ToNumber(L, 1)), 0); + return PushResult(L, PlayKit(static_cast(Game::Lua::ToNumber(L, 1)), {})); return reinterpret_cast(Offsets::FUN_SCRIPT_PLAY_SOUND)(L); } // Read `name` from the params table at stack index `idx`. Uses GetTable // rather than a raw read so a params table built from a mixin still works. // Leaves the stack as it found it. -bool Field(void *L, int idx, const char *name) { +double FieldNumber(void *L, int idx, const char *name, double fallback) { Game::Lua::PushString(L, name); Game::Lua::GetTable(L, idx); - return true; // value is on the stack; caller pops -} - -double FieldNumber(void *L, int idx, const char *name, double fallback) { - Field(L, idx, name); const double v = (Game::Lua::Type(L, -1) == Game::Lua::TYPE_NUMBER) ? Game::Lua::ToNumber(L, -1) : fallback; @@ -277,7 +305,8 @@ double FieldNumber(void *L, int idx, const char *name, double fallback) { } bool FieldBool(void *L, int idx, const char *name) { - Field(L, idx, name); + Game::Lua::PushString(L, name); + Game::Lua::GetTable(L, idx); const bool v = Game::Lua::ToBoolean(L, -1) != 0; Game::Lua::SetTop(L, -2); return v; @@ -285,34 +314,73 @@ bool FieldBool(void *L, int idx, const char *name) { // C_Sound.PlaySoundWithOptions(params) -> success, soundHandle // -// The table form of PlaySound. Honors `soundKitID`, `runFinishCallback` -// and `volumeOverride`; accepts and ignores `uiSoundSubType`, -// `forceNoDuplicates` and `overridePriority`, which have nothing behind -// them here (see PlayById for why forceNoDuplicates cannot be asked for). -// -// `volumeOverride` scales the sound's own volume, so 1.0 is unchanged and -// 0 is silent. +// The table form of PlaySound. Honors `soundKitID`, `forceNoDuplicates`, +// `runFinishCallback` and `volumeOverride`; accepts and ignores +// `uiSoundSubType` and `overridePriority`, which have nothing behind them +// here. `volumeOverride` scales the sound's own volume, so 1.0 is +// unchanged and 0 is silent. int __fastcall Script_PlaySoundWithOptions(void *L) { if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE) { Game::Lua::Error(L, "Usage: C_Sound.PlaySoundWithOptions(params)"); return 0; } const int soundKitID = static_cast(FieldNumber(L, 1, "soundKitID", 0)); - PlayOptions opts; + opts.noDuplicates = FieldBool(L, 1, "forceNoDuplicates"); opts.runFinishCallback = FieldBool(L, 1, "runFinishCallback"); const double volume = FieldNumber(L, 1, "volumeOverride", -1.0); if (volume >= 0.0) opts.volumeScale = static_cast(volume); + return PushResult(L, PlayKit(soundKitID, opts)); +} - return PlayWithOptions(L, soundKitID, opts); +// PlaySoundFile(file [, channel]) -> willPlay, soundHandle +// +// The engine's own (`0x00458780`) is `Play2D(3, file, 0, 0)` returning +// 1 or nil. This is the same open on the same bus (its cap of 2 still +// refuses a third file at once), with the channel's category flag and +// the handle returned so StopSound can end it. +int __fastcall Script_PlaySoundFile(void *L) { + if (!Game::Lua::IsString(L, 1)) { + Game::Lua::Error(L, + "Usage: PlaySoundFile(\"soundfile\", optional[\"SFX\",\"Music\",\"Ambience\" " + "or \"Master\"])"); + return 0; + } + const unsigned flags = ChannelFlags(ChannelArg(L, 2)); + void *sound = reinterpret_cast(Offsets::FUN_SOUND_PLAY_2D)( + Offsets::SOUND_BUS_PLAY_SOUND_FILE, Game::Lua::ToString(L, 1), flags, 0); + if (sound != nullptr) + Own(sound, false); + return PushResult(L, sound); +} + +// StopSound(soundHandle [, fadeoutTime]) +// +// `fadeoutTime` is in milliseconds. Sound::Stop2 fades the sound out and +// releases it at silence, or releases it at once below 0.1 s. Only a +// handle one of our play functions returned is stopped (see Owned). +int __fastcall Script_StopSound(void *L) { + if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_NUMBER) + return 0; + const auto handle = static_cast(Game::Lua::ToNumber(L, 1)); + const double fadeMs = + Game::Lua::Type(L, 2) == Game::Lua::TYPE_NUMBER ? Game::Lua::ToNumber(L, 2) : 0.0; + for (const Owned &o : g_owned) { + if (o.handle != handle || !StillPlaying(o)) + continue; + reinterpret_cast(Offsets::FUN_SOUND_STOP)( + reinterpret_cast(handle), static_cast(fadeMs * 0.001)); + break; + } + return 0; } // C_Sound.GetSoundScaledVolume(soundHandle) -> number // // The volume the sound is playing at: the sound's own volume after any -// scaling. Reads the field only off a stream still in the live list, since -// a finished stream's memory goes back to a pool. +// scaling. Reads the field only off a sound still in the live list, since +// a finished sound's memory goes back to a pool. int __fastcall Script_GetSoundScaledVolume(void *L) { if (!Game::Lua::IsNumber(L, 1)) { Game::Lua::PushNil(L); @@ -338,7 +406,7 @@ int __fastcall Script_IsPlaying(void *L) { } const uintptr_t handle = static_cast(Game::Lua::ToNumber(L, 1)); - Game::Lua::PushBool(L, HandleAlive(handle)); + Game::Lua::PushBool(L, FindStreamNode(handle) != 0); return 1; } @@ -349,8 +417,10 @@ void RegisterLuaFunctions() { Game::Lua::RegisterTableFunction("C_Sound", "GetSoundScaledVolume", &Script_GetSoundScaledVolume); Game::Lua::RegisterTableFunction("C_Sound", "IsPlaying", &Script_IsPlaying); - // A strict superset of the engine's own global — see Script_PlaySound. + // Strict supersets of the engine's own globals — see each Script_*. Game::Lua::RegisterGlobalFunction("PlaySound", &Script_PlaySound); + Game::Lua::RegisterGlobalFunction("PlaySoundFile", &Script_PlaySoundFile); + Game::Lua::RegisterGlobalFunction("StopSound", &Script_StopSound); } const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};