From 27277b11aa752ec29f0eccd371c8a243d5186831 Mon Sep 17 00:00:00 2001
From: Brues <5278969+brues-code@users.noreply.github.com>
Date: Sat, 12 Sep 2026 07:40:51 -0500
Subject: [PATCH] feat(sound): fire SOUNDKIT_FINISHED when an opted-in sound
ends
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Reports the handle of a finished sound, and only for sounds played with
`runFinishCallback` — the documented contract, and what makes it
affordable: without the opt-in every footstep and UI click would dispatch
a Lua event.
Detected on the world tick, NOT from FMOD's end callback. That callback
(FUN_007A53C0) runs on the STREAMER thread — it opens with
EnterCriticalSection and only moves the stream onto a deferred list — so
firing an event there would call into the Lua VM off the main thread. The
engine reclaims those streams in FUN_007A4B60, from the per-frame sound
update that ends in FSOUND_Update, so noticing completion on the main
thread is what the engine itself does.
A tracked entry keeps the stream's path hash (+0x80, stamped at creation
by FUN_007A51D0) beside the handle. Stream objects come from a pool and
their addresses are reused, so "still in the live list" is not enough on
its own — a later sound can land on the same address and the event would
be deferred to the wrong one. Comparing the hash narrows that to the same
file replaying at the same address, for one extra dword read of a node
already found alive.
C_Sound.PlaySound takes the remaining modern arguments: channel,
forceNoDuplicates and runFinishCallback. forceNoDuplicates is accepted
and ignored — the engine's by-path dedup is bit 0 of a flag word the row
itself supplies, and the by-id player ORs in only bits 1, 2 and 4 from
its arguments, so asking for it would mean bypassing that player and
re-deriving its weighted file pick.
The global PlaySound deliberately does NOT take those: it gains the
SoundKitID form and nothing else, staying as close to the global it
replaces as the extension allows.
---
README.md | 1 +
docs/API.md | 48 ++++++++++++---
src/Offsets.h | 16 +++++
src/sound/Play.cpp | 146 ++++++++++++++++++++++++++++++++++++++-------
4 files changed, 179 insertions(+), 32 deletions(-)
diff --git a/README.md b/README.md
index aa61a6f1..e2705823 100644
--- a/README.md
+++ b/README.md
@@ -232,6 +232,7 @@ when launching with `-console`), not as Lua functions. See the
| `QUEST_DATA_LOAD_RESULT` | `questID, success` |
| `QUEST_REMOVED` | `questID` |
| `QUEST_TURNED_IN` | `questID, xpReward, moneyReward` |
+| `SOUNDKIT_FINISHED` | `soundHandle` (only for sounds played with `runFinishCallback`) |
| `UNIT_SPELLCAST_SENT` | `"player", target, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_START` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_STOP` | `unit, castGUID, spellID, spellName, rank` |
diff --git a/docs/API.md b/docs/API.md
index 509e5d60..3c7dc531 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -169,6 +169,7 @@ build instructions.
- [`QUEST_ACCEPTED` event](#quest_accepted-event)
- [`QUEST_REMOVED` event](#quest_removed-event)
- [`QUEST_TURNED_IN` event](#quest_turned_in-event)
+ - [`SOUNDKIT_FINISHED` event](#soundkit_finished-event)
- [`UNIT_FACTION` event (fire-coverage fix)](#unit_faction-event-fire-coverage-fix)
- [`UPDATE_MOUSEOVER_UNIT` event (loss-fire fix)](#update_mouseover_unit-event-loss-fire-fix)
- [`UPDATE_SHAPESHIFT_FORM` event](#update_shapeshift_form-event)
@@ -558,8 +559,8 @@ build instructions.
- [`GetQuestLogLeaderBoardID(objectiveIndex [, questIndex])`](#getquestlogleaderboardidobjectiveindex--questindex)
- [Sound](#sound)
- - [`PlaySound(soundKitID [, channel])` / `PlaySound(soundName)`](#playsoundsoundkitid--channel--playsoundsoundname)
- - [`C_Sound.PlaySound(soundKitID [, channel])`](#c_soundplaysoundsoundkitid--channel)
+ - [`PlaySound(soundKitID)` / `PlaySound(soundName)`](#playsoundsoundkitid--playsoundsoundname)
+ - [`C_Sound.PlaySound(soundKitID [, channel, forceNoDuplicates, runFinishCallback])`](#c_soundplaysoundsoundkitid--channel-forcenoduplicates-runfinishcallback)
- [`C_Sound.IsPlaying(soundHandle)`](#c_soundisplayingsoundhandle)
- [`C_Sound.PlayItemSound(soundType, item)`](#c_soundplayitemsoundsoundtype-item)
- [`MuteSoundFile(file)` / `UnmuteSoundFile(file)`](#mutesoundfilefile--unmutesoundfilefile)
@@ -4242,6 +4243,31 @@ quest invalidated, etc.). Only fires on a real successful turn-in.
> done, quest removed from log). Hooking the packet handler gives
> us a clean turn-in signal.
+### `SOUNDKIT_FINISHED` event
+
+Fires when a sound finishes playing.
+
+```lua
+local f = CreateFrame("Frame")
+f:RegisterEvent("SOUNDKIT_FINISHED")
+f:SetScript("OnEvent", function()
+ print("finished:", arg1) -- the handle of the sound that ended
+end)
+
+C_Sound.PlaySound(8959, nil, nil, true)
+```
+
+| Argument | Meaning |
+|---|---|
+| `arg1` | `soundHandle` — the handle [`C_Sound.PlaySound`](#c_soundplaysoundsoundkitid--channel-forcenoduplicates-runfinishcallback) returned for the sound that just ended. |
+
+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.
+
+The event arrives on the frame after the sound ends, which is when the
+client releases it.
+
### `UNIT_FACTION` event (fire-coverage fix)
`UNIT_FACTION` already exists in the event table — addons can register
@@ -13645,7 +13671,7 @@ To see the file paths, extract them with the
[`ExportSoundFiles`](#exportsoundfiles-subpath-console-command) console
command.
-### `PlaySound(soundKitID [, channel])` / `PlaySound(soundName)`
+### `PlaySound(soundKitID)` / `PlaySound(soundName)`
Plays a sound.
@@ -13659,14 +13685,12 @@ PlaySound(8959) -- true, 394043692
PlaySound("igMainMenuOpen") -- plays, returns nothing
```
-`channel` selects 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, so code written for the
-modern client still runs. The categories here do not match those names.
+The id is the only thing added here. For a channel, or to be told when the
+sound ends, use `C_Sound.PlaySound` below.
-### `C_Sound.PlaySound(soundKitID [, channel])`
+### `C_Sound.PlaySound(soundKitID [, channel, forceNoDuplicates, runFinishCallback])`
-The same as the numeric form above, and it takes only a number. Returns
+Plays a SoundKitID, and takes only a number. Returns
`willPlay, soundHandle`.
```lua
@@ -13680,6 +13704,12 @@ has as many sounds as it allows.
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. |
+| `runFinishCallback` | Pass `true` to get the [`SOUNDKIT_FINISHED`](#soundkit_finished-event) event when this sound ends. |
+
### `C_Sound.IsPlaying(soundHandle)`
Returns `true` while the sound for that handle is still playing.
diff --git a/src/Offsets.h b/src/Offsets.h
index 7f71fcdd..f3f053a0 100644
--- a/src/Offsets.h
+++ b/src/Offsets.h
@@ -6147,6 +6147,22 @@ enum Offsets {
// when it finishes, so the handle must never be dereferenced directly.
VAR_SOUND_STREAM_LIST_HEAD = 0x00CF557C,
OFF_SOUND_STREAM_NEXT = 0x04,
+ // Hash of the path the stream was opened with, stamped at creation
+ // (`FUN_007A51D0`: `obj[0x20] = FUN_0064AF90(path)`) and compared by
+ // the dedup pass. Stream objects come from a pool and their addresses
+ // are reused, so this is what tells one instance from another at the
+ // same address — see `Sound::Play`'s finish tracking.
+ OFF_SOUND_STREAM_PATH_HASH = 0x80,
+
+ // Per-frame sound update, main thread: drains finished streams
+ // (`FUN_007A4B60`), updates the 3D listener, then calls FSOUND_Update.
+ // The drain matters for anything reporting completion: FMOD's own end
+ // callback (`FUN_007A53C0`) runs on the STREAMER thread and only moves
+ // the stream onto a deferred list under a critical section
+ // (`0x00CF55B4`) — so a finished sound must never be reported from
+ // there. `FUN_007A4B60` is where the engine reclaims those, on the main
+ // thread, which is the only safe side to notice completion from.
+ FUN_SOUND_UPDATE_FRAME = 0x007A4AD0,
// `Script_PlaySound` — the engine's `PlaySound(soundName)`: hashes the
// name to a SoundEntries row and calls `FUN_00458850`, whose tail is
diff --git a/src/sound/Play.cpp b/src/sound/Play.cpp
index d3ffa0b2..ce757099 100644
--- a/src/sound/Play.cpp
+++ b/src/sound/Play.cpp
@@ -11,9 +11,10 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see .
-// `C_Sound.PlaySound(soundKitID [, channel])`,
-// `C_Sound.IsPlaying(soundHandle)`, and the global `PlaySound` widened to
-// take a SoundKitID as well as the row name it has always taken.
+// `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.
//
// 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
@@ -37,8 +38,11 @@
#include "Game.h"
#include "Offsets.h"
+#include "event/Custom.h"
+#include "tick/WorldTick.h"
#include
+#include
namespace Sound::Play {
@@ -55,29 +59,110 @@ constexpr int kVariantRandom = -1; // the engine's own weighted pick
// 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
// intrusive list whose `next` sits at +0x04, ended by a null or a
-// low-bit-tagged sentinel.
-bool HandleAlive(uintptr_t handle) {
+// 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.
+uintptr_t FindStreamNode(uintptr_t handle) {
if (handle == 0)
- return false;
+ return 0;
uintptr_t node = *reinterpret_cast(
static_cast(Offsets::VAR_SOUND_STREAM_LIST_HEAD));
for (int guard = 0; guard < 4096; ++guard) {
if (node == 0 || (node & 1) != 0)
- return false;
+ return 0;
if (node == handle)
- return true;
+ return node;
node = *reinterpret_cast(
node + Offsets::OFF_SOUND_STREAM_NEXT);
}
- return false; // cycle or corruption — never spin inside a Lua call
+ return 0; // cycle or corruption — never spin inside a Lua call
}
-// Play a row by id and push `willPlay, soundHandle`. `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.
-int PlayById(void *L, int soundKitID, int argChannel) {
+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);
+}
+
+// ---- SOUNDKIT_FINISHED ------------------------------------------------
+//
+// 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.
+//
+// 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.
+//
+// A tracked entry keeps the stream's path hash alongside the handle.
+// Stream objects 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 {
+ uintptr_t handle;
+ uint32_t pathHash;
+};
+
+// Only ever holds sounds a caller opted in for, so it is empty almost
+// always and never needs a cap.
+std::vector g_tracked;
+
+void TrackForFinish(uintptr_t handle) {
+ const uintptr_t node = FindStreamNode(handle);
+ if (node == 0)
+ return; // already over, or never started — nothing to report
+ g_tracked.push_back({handle, PathHash(node)});
+}
+
+void OnWorldTick() {
+ if (g_tracked.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
+ continue;
+ }
+ if (slot >= 0)
+ Event::Custom::Fire(slot, "%u", static_cast(t.handle));
+ }
+ g_tracked.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.
+int PlayById(void *L, int soundKitID, int optionalBase) {
if (soundKitID <= 0) {
Game::Lua::PushBool(L, false);
Game::Lua::PushNil(L);
@@ -85,15 +170,22 @@ int PlayById(void *L, int soundKitID, int argChannel) {
}
int category = 0;
- if (Game::Lua::Type(L, argChannel) == Game::Lua::TYPE_NUMBER) {
- category = static_cast(Game::Lua::ToNumber(L, argChannel));
- if (category < 0 || category > Offsets::SOUND_CATEGORY_MAX)
- category = 0; // the engine rejects the rest outright
+ bool runFinishCallback = false;
+ if (optionalBase > 0) {
+ if (Game::Lua::Type(L, optionalBase) == Game::Lua::TYPE_NUMBER) {
+ category = static_cast(Game::Lua::ToNumber(L, optionalBase));
+ if (category < 0 || category > Offsets::SOUND_CATEGORY_MAX)
+ category = 0; // the engine rejects the rest outright
+ }
+ runFinishCallback = Game::Lua::ToBoolean(L, optionalBase + 2) != 0;
}
auto play = reinterpret_cast(Offsets::FUN_SOUND_PLAY_ENTRY);
void *handle = play(0, 0, category, soundKitID, kVariantRandom, 0);
+ if (handle != nullptr && runFinishCallback)
+ TrackForFinish(reinterpret_cast(handle));
+
Game::Lua::PushBool(L, handle != nullptr);
if (handle != nullptr)
Game::Lua::PushNumber(L, static_cast(reinterpret_cast(handle)));
@@ -102,16 +194,19 @@ int PlayById(void *L, int soundKitID, int argChannel) {
return 2;
}
-// C_Sound.PlaySound(soundKitID [, channel]) -> willPlay, soundHandle
+// C_Sound.PlaySound(soundKitID [, channel [, forceNoDuplicates
+// [, runFinishCallback]]]) -> willPlay, soundHandle
int __fastcall Script_C_Sound_PlaySound(void *L) {
if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_NUMBER) {
- Game::Lua::Error(L, "Usage: C_Sound.PlaySound(soundKitID [, channel])");
+ Game::Lua::Error(L,
+ "Usage: C_Sound.PlaySound(soundKitID [, channel [, forceNoDuplicates "
+ "[, runFinishCallback]]])");
return 0;
}
return PlayById(L, static_cast(Game::Lua::ToNumber(L, 1)), 2);
}
-// The global `PlaySound(soundKitID | soundName [, channel])`.
+// The global `PlaySound(soundKitID | soundName)`.
//
// The engine's own `PlaySound` takes a SoundEntries row NAME
// ("igMainMenuOpen"); the modern one takes that row's id. Both now work:
@@ -119,13 +214,18 @@ 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
+// 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.
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)), 2);
+ return PlayById(L, static_cast(Game::Lua::ToNumber(L, 1)), 0);
return reinterpret_cast(Offsets::FUN_SCRIPT_PLAY_SOUND)(L);
}