Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

fix(miles): shared room on xaudio2 and a fresh voice per sound

Olcay Seygan6f642b906728
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4d5d36789..c491e05e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,7 @@ found and fixed — EA's own, not port damage.**
- Every map has an echo of its own, worked out from how much of it is built over. A city rings for nearly two seconds with a slap straight back off the buildings. Open desert answers a quarter of a second late from the hills, a distinct second crack and then a long, thin, dark tail. Snow kills it: a short dead tail, no echo, and air that takes the top end off a sound sooner. Far sounds carry more of the room than near ones. Unit replies take none of this, no muffling, no pitch bend and no echo: a tank answering from across the map sounds like a radio in your ear, as it always has.
- A nuke, a Particle Cannon sweep, a Daisy Cutter, a MOAB or a Nuke Cannon shell that lands within earshot leaves you half deaf. The rest of the battle drops to a sixth of its volume and is muffled down to a few hundred hertz for a second, then comes back over three more, all of it by how close the blast was.
- Nothing clips any more. A dense tank fight in a city used to drive one sample in twenty past full scale, and the city's echo made it worse; a limiter at the end of the mix now looks two milliseconds ahead and turns the whole mix down just enough, so the loudest moment is as loud as the speakers go and no louder.
+- On Windows the echo was nearly lost. Windows played it through its own built-in reverb, which answered a shell 12 decibels quieter than intended on open ground, 20 in a city and 31 in snow, with its top end gone. A sound card set to 96 kHz got no echo at all. Windows now plays the very echo macOS, Linux and the recorded videos do, sample for sample.
- macOS and Linux hear the same, and so does the sound the game records for a video, in step with the picture frame for frame. A mod can retune any of it, or switch a part off, from its audio settings.
## Ukrainian and Russian
@@ -1784,6 +1785,7 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same
## It does not crash
- A sound cut off in the middle no longer takes the game down a moment later. The game stopped the sound and freed it, but Windows' audio mixer only stops reading on its next pass, a hundredth of a second on, and two players' games died with the mixer reading what had just been freed. Every sound now plays from a copy the mixer gives back itself when it is done. A load screen movie skipped to its last frame threw its sound away the same way, and now leaves it to the mixer too.
+- That copy did not end the mixer crash: two 3.3.0 players still met it. Each sound channel was reused for the next sound by stopping it, emptying it and handing it new audio, and now and then Windows' mixer carried its place in the old sound over as one step before the start of the new one, then read eight gigabytes past it. Every sound now gets a fresh channel that nothing has played before, which is how Windows' mixer is normally used.
- The game no longer crashes now and then as a match starts or a new unit comes on the field. Since 3.2.0 the battle runs beside the picture, and both sides ask the game's files whether a model or a texture is there. The answers go into one shared list, and two answers written at once tore it, which took the game down later in some unrelated place. Two reads from the same game archive at once could also hand one of them the other's bytes. Each now waits its turn.
- Text on the screen, a message line or a unit's label, no longer crashes the game with the Direct3D 11 picture on. Three players met it on 3.2.0 in the same spot. The picture keeps a note of every texture it has copied, and a texture thrown away on the battle's side struck its note off while the picture was writing a new one in. The battle's side now leaves the striking off to the picture, which does it before its next look.
- A tank or helicopter carrying an add-on on its back, an Overlord's Gattling Cannon or a Helix's bunker, no longer crashes the game now and then. Since 3.2.0 the battle runs beside the picture, and the picture, seating the add-on on its carrier, finished the carrier's waiting model changes while the battle was still adding to that same list. The picture now takes the carrier as the last step between pictures left it.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore
index 2c4a2296d..b6b717a1e 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore
@@ -14,6 +14,8 @@
!include/MSS/MSS.h
# mss_ex_pcm.h: miniaudio's pushed-PCM voice for the movies (V1), declared beside it.
!include/MSS/mss_ex_pcm.h
+# mss_ex_room.h: the room both backends play, so the two cannot drift.
+!include/MSS/mss_ex_room.h
# Windows links both backends: each under its own prefix (mss_backend_names.h), miles_dispatch.cpp
# owning the plain names.
!include/MSS/mss_backend_names.h
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
index 743270195..ef7c5ca67 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
@@ -275,7 +275,9 @@ void AILCALL AIL_ex_stop_capture(void);
device: the mix moves only when AIL_ex_mix_to_frame asks it to, logicFrame * rate / 60 frames from
the start, so a capture holds exactly the sound of the logic frames it spans however fast or slow
the run went. Nothing is heard meanwhile. AIL_ex_capture_length reports what the last finished
- capture wrote, in frames at its rate; the XAudio2 backend does not count and says zero. */
+ capture wrote, in frames at its rate; the XAudio2 backend does not count and says zero.
+ ZH_WAV_XAUDIO2 in the environment leaves the run on XAudio2 instead, recording its master in real
+ time (miles_dispatch.cpp). */
void AILCALL AIL_ex_offline_mix(void);
void AILCALL AIL_ex_mix_to_frame(S32 logicFrame);
void AILCALL AIL_ex_capture_length(S32 *frames, S32 *rate);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_ex_room.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_ex_room.h
new file mode 100644
index 000000000..027110991
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_ex_room.h
@@ -0,0 +1,134 @@
+/*
+ * The room (AIL_ex_set_reverb): the reverb every 3D sample sends to, shared by both backends so that
+ * what a player hears on Windows and what a -wav run records are the same room.
+ *
+ * Not Miles. A small reverb of Freeverb's shape, cut to four combs and two all-passes a side. The
+ * send goes through the echo first, a delay that is also heard once on its own (a street of
+ * buildings answering), then into the combs, damped in their feedback, and out through the
+ * all-passes that smear them. Mono in, stereo out; the right side's lines are 23 samples longer
+ * than the left's, Freeverb's spread, for width.
+ *
+ * XAudio2's own reverb was the Windows room until 2026-10-25, through an I3DL2 mapping of these
+ * five numbers. Driven offline against this one it answered an impulse 12 dB quieter on open
+ * ground, 20 dB in a town and 31 dB in snow, with the top end of its tail 19 dB further down, so a
+ * player heard next to no room at all; and it takes 20 to 48 kHz only, so a device at 96 kHz had
+ * none. miles_xaudio2 runs this as an effect on its room submix instead.
+ *
+ * C++ only: the two backends are. The caller keeps it to one thread at a time.
+ */
+
+#ifndef MSS_EX_ROOM_H
+#define MSS_EX_ROOM_H
+
+#include <math.h>
+#include <stddef.h>
+#include <vector>
+
+const unsigned ROOM_COMBS = 4;
+const unsigned ROOM_ALLPASSES = 2;
+const unsigned ROOM_COMB_LENGTHS[ROOM_COMBS] = { 1116, 1188, 1277, 1356 }; // Freeverb's, at 44.1 kHz
+const unsigned ROOM_ALLPASS_LENGTHS[ROOM_ALLPASSES] = { 556, 441 };
+const unsigned ROOM_STEREO_SPREAD = 23;
+const unsigned ROOM_OUTPUT_CHANNELS = 2;
+const float ROOM_TUNING_RATE = 44100.0f;
+const float ROOM_ALLPASS_FEEDBACK = 0.5f;
+const float ROOM_INPUT_GAIN = 0.25f; // four combs at a second-long decay answer at about the send's level
+const float ROOM_MAX_DAMPING = 0.7f;
+const float ROOM_MAX_ECHO_SECONDS = 0.3f; // the longest echo MilesAudioManager asks for is 0.26
+const float ROOM_DENORMAL_GUARD = 1e-18f; // keeps a dying tail out of the denormals, which x64 does slowly
+
+struct DelayLine
+{
+ DelayLine() : at(0), feedback(0.0f), store(0.0f) {}
+
+ std::vector<float> line;
+ size_t at;
+ float feedback;
+ float store; // a comb's damping filter
+};
+
+struct Room
+{
+ Room() : ready(false), rate(0), damping(0.0f), slap(0.0f), echoLength(0) {}
+
+ bool ready;
+ unsigned rate;
+ float damping;
+ float slap; // the echo's own level, AIL_ex_set_reverb
+ DelayLine echo;
+ size_t echoLength;
+ DelayLine combs[2][ROOM_COMBS];
+ DelayLine allpasses[2][ROOM_ALLPASSES];
+};
+
+inline void initRoom(Room *room, unsigned rate)
+{
+ const float scale = (float)rate / ROOM_TUNING_RATE;
+ for (unsigned side = 0; side < 2; ++side) {
+ for (unsigned i = 0; i < ROOM_COMBS; ++i) {
+ room->combs[side][i].line.assign((size_t)((ROOM_COMB_LENGTHS[i] + side * ROOM_STEREO_SPREAD) * scale), 0.0f);
+ }
+ for (unsigned i = 0; i < ROOM_ALLPASSES; ++i) {
+ room->allpasses[side][i].line.assign((size_t)((ROOM_ALLPASS_LENGTHS[i] + side * ROOM_STEREO_SPREAD) * scale), 0.0f);
+ }
+ }
+ room->echo.line.assign((size_t)(ROOM_MAX_ECHO_SECONDS * rate) + 1, 0.0f);
+ room->rate = rate;
+ room->ready = true;
+}
+
+inline void setRoom(Room *room, float decay, float damping, float echo, float slap)
+{
+ if (!room->ready) {
+ return;
+ }
+ // each comb loses 60 dB in `decay` seconds: a gain per trip of 0.001 to the power of trips that long
+ for (unsigned side = 0; side < 2; ++side) {
+ for (unsigned i = 0; i < ROOM_COMBS; ++i) {
+ DelayLine &comb = room->combs[side][i];
+ comb.feedback = powf(0.001f, (float)comb.line.size() / (decay * (float)room->rate));
+ }
+ }
+ room->damping = damping * ROOM_MAX_DAMPING;
+ room->slap = slap;
+ const size_t echoLength = echo > 0.0f ? (size_t)(echo * (float)room->rate) : 0;
+ room->echoLength = echoLength < room->echo.line.size() ? echoLength : room->echo.line.size() - 1;
+ room->echo.at = room->echoLength > 0 ? room->echo.at % room->echoLength : 0;
+}
+
+// Adds the room's answer to `input` (mono, the sends of one mix pass) into the stereo `output`.
+inline void processRoom(Room *room, const float *input, float *output, unsigned frames)
+{
+ for (unsigned frame = 0; frame < frames; ++frame) {
+ float in = input[frame];
+ float echoed = 0.0f;
+ if (room->echoLength > 0) {
+ DelayLine &echo = room->echo;
+ echoed = echo.line[echo.at];
+ echo.line[echo.at] = in;
+ echo.at = (echo.at + 1) % room->echoLength;
+ in = echoed;
+ }
+ for (unsigned side = 0; side < 2; ++side) {
+ float sum = 0.0f;
+ for (unsigned i = 0; i < ROOM_COMBS; ++i) {
+ DelayLine &comb = room->combs[side][i];
+ const float out = comb.line[comb.at];
+ comb.store = out + room->damping * (comb.store - out);
+ comb.line[comb.at] = in * ROOM_INPUT_GAIN + comb.store * comb.feedback + ROOM_DENORMAL_GUARD;
+ comb.at = (comb.at + 1) % comb.line.size();
+ sum += out;
+ }
+ for (unsigned i = 0; i < ROOM_ALLPASSES; ++i) {
+ DelayLine &pass = room->allpasses[side][i];
+ const float held = pass.line[pass.at];
+ pass.line[pass.at] = sum + held * ROOM_ALLPASS_FEEDBACK;
+ pass.at = (pass.at + 1) % pass.line.size();
+ sum = held - sum;
+ }
+ output[frame * ROOM_OUTPUT_CHANNELS + side] += sum + echoed * room->slap;
+ }
+ }
+}
+
+#endif /* MSS_EX_ROOM_H */
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp
index 1dd41c2aa..ab5a599f5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp
@@ -10,6 +10,8 @@
* sound opens its own XAudio2 on Windows and goes through neither.
*/
+#include <stdlib.h>
+
#include "MSS/MSS.h"
#define MSS_API_LIST \
@@ -107,6 +109,12 @@ MSS_API_LIST
void AILCALL AIL_ex_offline_mix(void)
{
+ // ZH_WAV_XAUDIO2 keeps a -wav run on XAudio2, recording through the master's tap what a player
+ // hears. The mix then runs on the device's clock: it needs an audio device, plays aloud, and the
+ // file is as long as the wall clock the run took, so the run has to go at the speed of play.
+ if (getenv("ZH_WAV_XAUDIO2") != NULL) {
+ return;
+ }
g_offline = true;
MA_AIL_ex_offline_mix();
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp
index bd091a172..290e26a03 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp
@@ -34,8 +34,8 @@
* 3D positioning -> the same distance attenuation and stereo pan miles_xaudio2 computes,
* not miniaudio's spatializer. The air, room and duck of MSS.h too, by the
* same helpers: a one-pole low-pass where XAudio2 sets the voice's filter,
- * the resampler's rate for doppler, and a small reverb of its own (Room
- * below) where XAudio2 has a submix running its built-in one.
+ * the resampler's rate for doppler, and the room of MSS/mss_ex_room.h,
+ * which miles_xaudio2 runs as an effect on a submix.
* the mix -> done here, in miniaudio's device callback, so that the output matrix is
* exactly XAudio2's: every source channel summed into left and right at
* the pan's two gains.
@@ -70,6 +70,7 @@
#include "MSS/MSS.h"
#include "MSS/mss_ex_pcm.h"
+#include "MSS/mss_ex_room.h" // the room (AIL_ex_set_reverb), miles_xaudio2's as well; under mixLock here
#ifndef WAVE_FORMAT_IMA_ADPCM
#define WAVE_FORMAT_IMA_ADPCM 0x0011
@@ -536,121 +537,6 @@ struct Capture
unsigned int sizesWrittenAt;
};
-// ---------------------------------------------------------------------------------------------
-// The room (AIL_ex_set_reverb): the reverb every 3D sample sends to. XAudio2 has one built in and
-// miniaudio has none, so this is a small one of Freeverb's shape, cut to four combs and two
-// all-passes a side. The send goes through the echo first, a delay that is also heard once on its
-// own (a street of buildings answering), then into the combs, damped in their feedback, and out
-// through the all-passes that smear them. Mono in; the right side's lines are 23 samples longer than
-// the left's, Freeverb's spread, for width. Under mixLock.
-// ---------------------------------------------------------------------------------------------
-
-const unsigned ROOM_COMBS = 4;
-const unsigned ROOM_ALLPASSES = 2;
-const unsigned ROOM_COMB_LENGTHS[ROOM_COMBS] = { 1116, 1188, 1277, 1356 }; // Freeverb's, at 44.1 kHz
-const unsigned ROOM_ALLPASS_LENGTHS[ROOM_ALLPASSES] = { 556, 441 };
-const unsigned ROOM_STEREO_SPREAD = 23;
-const float ROOM_TUNING_RATE = 44100.0f;
-const float ROOM_ALLPASS_FEEDBACK = 0.5f;
-const float ROOM_INPUT_GAIN = 0.25f; // four combs at a second-long decay answer at about the send's level
-const float ROOM_MAX_DAMPING = 0.7f;
-const float ROOM_MAX_ECHO_SECONDS = 0.3f; // I3DL2's ReflectionsDelay limit, where miles_xaudio2 puts the echo
-const float ROOM_DENORMAL_GUARD = 1e-18f; // keeps a dying tail out of the denormals, which x64 does slowly
-
-struct DelayLine
-{
- DelayLine() : at(0), feedback(0.0f), store(0.0f) {}
-
- std::vector<float> line;
- size_t at;
- float feedback;
- float store; // a comb's damping filter
-};
-
-struct Room
-{
- Room() : ready(false), rate(0), damping(0.0f), slap(0.0f), echoLength(0) {}
-
- bool ready;
- unsigned rate;
- float damping;
- float slap; // the echo's own level, AIL_ex_set_reverb
- DelayLine echo;
- size_t echoLength;
- DelayLine combs[2][ROOM_COMBS];
- DelayLine allpasses[2][ROOM_ALLPASSES];
-};
-
-void initRoom(Room *room, unsigned rate)
-{
- const float scale = (float)rate / ROOM_TUNING_RATE;
- for (unsigned side = 0; side < 2; ++side) {
- for (unsigned i = 0; i < ROOM_COMBS; ++i) {
- room->combs[side][i].line.assign((size_t)((ROOM_COMB_LENGTHS[i] + side * ROOM_STEREO_SPREAD) * scale), 0.0f);
- }
- for (unsigned i = 0; i < ROOM_ALLPASSES; ++i) {
- room->allpasses[side][i].line.assign((size_t)((ROOM_ALLPASS_LENGTHS[i] + side * ROOM_STEREO_SPREAD) * scale), 0.0f);
- }
- }
- room->echo.line.assign((size_t)(ROOM_MAX_ECHO_SECONDS * rate) + 1, 0.0f);
- room->rate = rate;
- room->ready = true;
-}
-
-void setRoom(Room *room, float decay, float damping, float echo, float slap)
-{
- if (!room->ready) {
- return;
- }
- // each comb loses 60 dB in `decay` seconds: a gain per trip of 0.001 to the power of trips that long
- for (unsigned side = 0; side < 2; ++side) {
- for (unsigned i = 0; i < ROOM_COMBS; ++i) {
- DelayLine &comb = room->combs[side][i];
- comb.feedback = powf(0.001f, (float)comb.line.size() / (decay * (float)room->rate));
- }
- }
- room->damping = damping * ROOM_MAX_DAMPING;
- room->slap = slap;
- const size_t echoLength = echo > 0.0f ? (size_t)(echo * (float)room->rate) : 0;
- room->echoLength = echoLength < room->echo.line.size() ? echoLength : room->echo.line.size() - 1;
- room->echo.at = room->echoLength > 0 ? room->echo.at % room->echoLength : 0;
-}
-
-// Adds the room's answer to `input` (mono, the sends of one mix pass) into the stereo `output`.
-void processRoom(Room *room, const float *input, float *output, unsigned frames)
-{
- for (unsigned frame = 0; frame < frames; ++frame) {
- float in = input[frame];
- float echoed = 0.0f;
- if (room->echoLength > 0) {
- DelayLine &echo = room->echo;
- echoed = echo.line[echo.at];
- echo.line[echo.at] = in;
- echo.at = (echo.at + 1) % room->echoLength;
- in = echoed;
- }
- for (unsigned side = 0; side < 2; ++side) {
- float sum = 0.0f;
- for (unsigned i = 0; i < ROOM_COMBS; ++i) {
- DelayLine &comb = room->combs[side][i];
- const float out = comb.line[comb.at];
- comb.store = out + room->damping * (comb.store - out);
- comb.line[comb.at] = in * ROOM_INPUT_GAIN + comb.store * comb.feedback + ROOM_DENORMAL_GUARD;
- comb.at = (comb.at + 1) % comb.line.size();
- sum += out;
- }
- for (unsigned i = 0; i < ROOM_ALLPASSES; ++i) {
- DelayLine &pass = room->allpasses[side][i];
- const float held = pass.line[pass.at];
- pass.line[pass.at] = sum + held * ROOM_ALLPASS_FEEDBACK;
- pass.at = (pass.at + 1) % pass.line.size();
- sum = held - sum;
- }
- output[frame * OUTPUT_CHANNELS + side] += sum + echoed * room->slap;
- }
- }
-}
-
struct Engine
{
Engine() : contextReady(false), deviceReady(false), serviceRunning(false), started(false), deviceRate(0),
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
index 91d2cde98..cf2ecfdc8 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
@@ -15,7 +15,7 @@
* pair and an occlusion scalar. On top of those (MSS.h's AIL_ex_ air,
* room and duck): the voice's own one-pole filter for air and occlusion,
* its frequency ratio for doppler, and a second send into one submix
- * running XAudio2's reverb.
+ * running mss_ex_room.h's room, miles_miniaudio's own.
* EOS callbacks -> the service thread notices a voice run dry and calls back from there,
* which is the thread context Miles used (MilesAudioManager locks for it).
*/
@@ -23,7 +23,6 @@
#include <windows.h>
#include <mmreg.h>
#include <xaudio2.h>
-#include <xaudio2fx.h>
#include <xapo.h>
#include <math.h>
#include <stdio.h>
@@ -41,6 +40,7 @@ extern "C" {
}
#include "MSS/MSS.h"
+#include "MSS/mss_ex_room.h"
namespace {
@@ -293,6 +293,7 @@ struct Sample
AILSAMPLECB endOfSample;
AIL3DSAMPLECB endOf3DSample;
bool playing;
+ bool started; // the voice has been started once, and gets no second buffer (freshVoice)
float positionX, positionY, positionZ;
float minDistance, maxDistance;
float occlusion;
@@ -352,7 +353,7 @@ struct Engine
IXAudio2 *xaudio;
IXAudio2MasteringVoice *master;
unsigned int masterRate;
- IXAudio2SubmixVoice *room; // XAudio2's reverb, AIL_ex_set_reverb; NULL where it could not be made
+ IXAudio2SubmixVoice *room; // RoomTap, AIL_ex_set_reverb; NULL where it could not be made
CRITICAL_SECTION lock;
HANDLE serviceThread;
volatile LONG serviceRunning;
@@ -546,22 +547,23 @@ void retireVoice(IXAudio2SourceVoice **voice)
}
}
-bool ensureVoice(Sample *sample, const WAVEFORMATEX &format)
+// Every sound gets a voice nobody has played before, and a voice is never fed again once it has
+// been started. Crash reports 890, 1254, 1724 and 1748 are xaudio2_9.dll's resampler reading a
+// source buffer at frame -1 as an unsigned 32-bit index, 8 GB past the buffer (1748, on the same
+// build of the DLL as Windows 10 19041: the int16 reader at +0x56760 handed base - 2 + 0xFFFFFFFF * 2
+// by its caller at +0x56B14). Its history path covers frame -1 only when the index is signed. The voices
+// were reused, Stop, FlushSourceBuffers and a new buffer for each sound on a pooled handle,
+// carrying the resampler's position from the cut-off sound into the new one; the PCM copy above
+// (v3.3.0) did not stop the crash, 1724 and 1748 are v3.3.0. A fresh voice starts at frame 0 with
+// no position to carry, the way every fire-and-forget XAudio2 sound starts.
+bool freshVoice(Sample *sample, const WAVEFORMATEX &format)
{
if (g_engine.xaudio == NULL) {
return false;
}
- if (sample->voice != NULL &&
- sample->format.nChannels == format.nChannels &&
- sample->format.nSamplesPerSec == format.nSamplesPerSec &&
- sample->format.wBitsPerSample == format.wBitsPerSample) {
- sample->voice->Stop(0);
- sample->voice->FlushSourceBuffers();
- return true;
- }
-
retireVoice(&sample->voice);
+ sample->started = false;
sample->format = format;
if (!sample->is3D) {
return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, 0, 4.0f, &g_sampleCallback));
@@ -574,22 +576,6 @@ bool ensureVoice(Sample *sample, const WAVEFORMATEX &format)
&g_sampleCallback, &sendList));
}
-// The room every 3D sample sends to: XAudio2's own reverb, on a stereo submix into the master. The
-// reverb takes 20 to 48 kHz only, and a device outside that plays with no room at all.
-void createRoom()
-{
- IUnknown *reverb = NULL;
- if (FAILED(XAudio2CreateReverb(&reverb, 0))) {
- return;
- }
- XAUDIO2_EFFECT_DESCRIPTOR descriptor = { reverb, TRUE, 2 };
- XAUDIO2_EFFECT_CHAIN chain = { 1, &descriptor };
- if (FAILED(g_engine.xaudio->CreateSubmixVoice(&g_engine.room, 2, g_engine.masterRate, 0, 0, NULL, &chain))) {
- g_engine.room = NULL;
- }
- reverb->Release();
-}
-
// ---------------------------------------------------------------------------------------------
// Streams, decoded by FFmpeg through the game's file callbacks
// ---------------------------------------------------------------------------------------------
@@ -841,13 +827,14 @@ DWORD WINAPI serviceThreadMain(LPVOID)
std::vector<H3DSAMPLE> sample3DHandles;
std::vector<AILSTREAMCB> streamCallbacks;
std::vector<HSTREAM> streamHandles;
+ std::vector<IXAudio2SourceVoice *> spentVoices;
EnterCriticalSection(&g_engine.lock);
for (size_t i = 0; i < g_engine.retiredVoices.size(); ) {
XAUDIO2_VOICE_STATE state;
g_engine.retiredVoices[i]->GetState(&state);
if (state.BuffersQueued == 0) {
- g_engine.retiredVoices[i]->DestroyVoice();
+ spentVoices.push_back(g_engine.retiredVoices[i]);
g_engine.retiredVoices.erase(g_engine.retiredVoices.begin() + i);
} else {
++i;
@@ -903,6 +890,12 @@ DWORD WINAPI serviceThreadMain(LPVOID)
}
LeaveCriticalSection(&g_engine.lock);
+ // DestroyVoice waits for the mixer's pass to end, and with a voice retired for every sound
+ // played that is too long to hold the game's AIL calls up; nothing names these voices any more.
+ for (size_t i = 0; i < spentVoices.size(); ++i) {
+ spentVoices[i]->DestroyVoice();
+ }
+
// Callbacks run outside the lock: the game takes its own locks in them.
for (size_t i = 0; i < sampleCallbacks.size(); ++i) {
sampleCallbacks[i](sampleHandles[i]);
@@ -969,20 +962,12 @@ void writeWaveHeader(FILE *file, unsigned int channels, unsigned int samplesPerS
writeLittleU32(file, dataBytes);
}
-// The master voice's one effect: MSS.h's limiter on everything, then, while AIL_ex_start_capture has
-// a file open, the recording of what the limiter let out.
-class MasterTap : public IXAPO
+// An effect of our own on a voice, working on the voice's float mix in place, with the format the
+// voice has. XAudio2 holds a reference while the voice has it in its chain.
+class InPlaceEffect : public IXAPO
{
public:
- MasterTap(FILE *file, unsigned int channels, unsigned int samplesPerSecond)
- : m_references(1), m_file(file), m_channels(channels),
- m_samplesPerSecond(samplesPerSecond), m_dataBytes(0), m_sizesWrittenAt(0)
- {
- AIL_ex_limiter_init(&m_limiter, (S32)channels, (F32)samplesPerSecond);
- if (m_file != NULL) {
- writeWaveHeader(m_file, m_channels, m_samplesPerSecond, 0);
- }
- }
+ InPlaceEffect() : m_references(1) {}
STDMETHOD(QueryInterface)(REFIID riid, void **object)
{
@@ -1034,21 +1019,16 @@ public:
return S_OK;
}
- STDMETHOD(IsInputFormatSupported)(const WAVEFORMATEX *, const WAVEFORMATEX *requested,
- WAVEFORMATEX **supported)
+ // Any format is taken. The out pointer is for the nearest format to one refused, allocated with
+ // XAPOAlloc for the caller to free, so a yes leaves it alone, as CXAPOBase does: handing back the
+ // caller's own pointer gives it something of its own to free.
+ STDMETHOD(IsInputFormatSupported)(const WAVEFORMATEX *, const WAVEFORMATEX *, WAVEFORMATEX **)
{
- if (supported != NULL) {
- *supported = const_cast<WAVEFORMATEX *>(requested);
- }
return S_OK;
}
- STDMETHOD(IsOutputFormatSupported)(const WAVEFORMATEX *, const WAVEFORMATEX *requested,
- WAVEFORMATEX **supported)
+ STDMETHOD(IsOutputFormatSupported)(const WAVEFORMATEX *, const WAVEFORMATEX *, WAVEFORMATEX **)
{
- if (supported != NULL) {
- *supported = const_cast<WAVEFORMATEX *>(requested);
- }
return S_OK;
}
@@ -1071,6 +1051,38 @@ public:
{
}
+ STDMETHOD_(UINT32, CalcInputFrames)(UINT32 outputFrameCount)
+ {
+ return outputFrameCount;
+ }
+
+ STDMETHOD_(UINT32, CalcOutputFrames)(UINT32 inputFrameCount)
+ {
+ return inputFrameCount;
+ }
+
+protected:
+ virtual ~InPlaceEffect() {}
+
+private:
+ volatile LONG m_references;
+};
+
+// The master voice's one effect: MSS.h's limiter on everything, then, while AIL_ex_start_capture has
+// a file open, the recording of what the limiter let out.
+class MasterTap : public InPlaceEffect
+{
+public:
+ MasterTap(FILE *file, unsigned int channels, unsigned int samplesPerSecond)
+ : m_file(file), m_channels(channels), m_samplesPerSecond(samplesPerSecond), m_dataBytes(0),
+ m_sizesWrittenAt(0)
+ {
+ AIL_ex_limiter_init(&m_limiter, (S32)channels, (F32)samplesPerSecond);
+ if (m_file != NULL) {
+ writeWaveHeader(m_file, m_channels, m_samplesPerSecond, 0);
+ }
+ }
+
STDMETHOD_(void, Process)(UINT32, const XAPO_PROCESS_BUFFER_PARAMETERS *input, UINT32,
XAPO_PROCESS_BUFFER_PARAMETERS *output, BOOL)
{
@@ -1103,16 +1115,6 @@ public:
}
}
- STDMETHOD_(UINT32, CalcInputFrames)(UINT32 outputFrameCount)
- {
- return outputFrameCount;
- }
-
- STDMETHOD_(UINT32, CalcOutputFrames)(UINT32 inputFrameCount)
- {
- return inputFrameCount;
- }
-
private:
~MasterTap()
{
@@ -1146,7 +1148,6 @@ private:
writeLittleU32(m_file, m_dataBytes);
}
- volatile LONG m_references;
AIL_EX_LIMITER m_limiter;
FILE *m_file; // NULL when nothing is being recorded
unsigned int m_channels;
@@ -1175,6 +1176,95 @@ bool installMasterTap(FILE *file)
return SUCCEEDED(result);
}
+// The room submix's effect: the send, which every voice puts on both channels alike, through
+// mss_ex_room.h's room, the one miles_miniaudio mixes, so a player and a -wav run hear one room.
+class RoomTap : public InPlaceEffect
+{
+public:
+ explicit RoomTap(unsigned int samplesPerSecond)
+ : m_pending(false), m_decay(0.0f), m_damping(0.0f), m_echo(0.0f), m_slap(0.0f)
+ {
+ InitializeCriticalSection(&m_settingsLock);
+ initRoom(&m_room, samplesPerSecond);
+ }
+
+ // AIL_ex_set_reverb's, from the game's thread: the mixer takes them up at its next pass.
+ void set(float decay, float damping, float echo, float slap)
+ {
+ EnterCriticalSection(&m_settingsLock);
+ m_decay = decay;
+ m_damping = damping;
+ m_echo = echo;
+ m_slap = slap;
+ m_pending = true;
+ LeaveCriticalSection(&m_settingsLock);
+ }
+
+ STDMETHOD(LockForProcess)(UINT32, const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS *input, UINT32,
+ const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS *)
+ {
+ m_send.resize(input[0].MaxFrameCount);
+ return S_OK;
+ }
+
+ STDMETHOD_(void, Process)(UINT32, const XAPO_PROCESS_BUFFER_PARAMETERS *input, UINT32,
+ XAPO_PROCESS_BUFFER_PARAMETERS *output, BOOL)
+ {
+ EnterCriticalSection(&m_settingsLock);
+ if (m_pending) {
+ setRoom(&m_room, m_decay, m_damping, m_echo, m_slap);
+ m_pending = false;
+ }
+ LeaveCriticalSection(&m_settingsLock);
+
+ // in place: the send read off the left channel, then the buffer is the room's answer alone; a
+ // silent pass is no send, and the tail still rings
+ const UINT32 frames = input[0].ValidFrameCount;
+ float *mix = (float *)input[0].pBuffer;
+ const bool silent = input[0].BufferFlags == XAPO_BUFFER_SILENT;
+ for (UINT32 frame = 0; frame < frames; ++frame) {
+ m_send[frame] = silent ? 0.0f : mix[frame * ROOM_OUTPUT_CHANNELS];
+ }
+ memset(mix, 0, (size_t)frames * ROOM_OUTPUT_CHANNELS * sizeof(float));
+ processRoom(&m_room, &m_send[0], mix, frames);
+ if (output != NULL) {
+ output[0].ValidFrameCount = frames;
+ output[0].BufferFlags = XAPO_BUFFER_VALID;
+ }
+ }
+
+private:
+ ~RoomTap()
+ {
+ DeleteCriticalSection(&m_settingsLock);
+ }
+
+ Room m_room; // the mixer thread's alone
+ std::vector<float> m_send;
+ CRITICAL_SECTION m_settingsLock;
+ bool m_pending;
+ float m_decay;
+ float m_damping;
+ float m_echo;
+ float m_slap;
+};
+
+RoomTap *g_roomTap; // our reference, for AIL_ex_set_reverb; the room voice holds XAudio2's
+
+// The room every 3D sample sends to: RoomTap on a stereo submix into the master, at the master's rate.
+void createRoom()
+{
+ RoomTap *tap = new RoomTap(g_engine.masterRate);
+ XAUDIO2_EFFECT_DESCRIPTOR descriptor = { static_cast<IXAPO *>(tap), TRUE, 2 };
+ XAUDIO2_EFFECT_CHAIN chain = { 1, &descriptor };
+ if (FAILED(g_engine.xaudio->CreateSubmixVoice(&g_engine.room, 2, g_engine.masterRate, 0, 0, NULL, &chain))) {
+ g_engine.room = NULL;
+ tap->Release();
+ return;
+ }
+ g_roomTap = tap;
+}
+
} // namespace
// =================================================================================================
@@ -1277,6 +1367,8 @@ void AILCALL AIL_shutdown(void)
if (g_engine.room != NULL) {
g_engine.room->DestroyVoice();
g_engine.room = NULL;
+ g_roomTap->Release();
+ g_roomTap = NULL;
}
if (g_engine.master != NULL) {
g_engine.master->DestroyVoice();
@@ -1430,10 +1522,7 @@ void AILCALL AIL_init_sample(HSAMPLE handle)
}
EnterCriticalSection(&g_engine.lock);
- if (sample->voice != NULL) {
- sample->voice->Stop(0);
- sample->voice->FlushSourceBuffers();
- }
+ retireVoice(&sample->voice);
sample->playing = false;
sample->volume = 1.0f;
sample->pan = DEFAULT_PAN;
@@ -1453,7 +1542,7 @@ S32 AILCALL AIL_set_sample_file(HSAMPLE handle, const void *file_image, S32)
EnterCriticalSection(&g_engine.lock);
sample->playing = false;
- const bool ready = ensureVoice(sample, wave.format);
+ const bool ready = freshVoice(sample, wave.format);
if (ready) {
releaseSampleData(sample->data);
sample->data = copySampleData(wave.data, wave.dataBytes);
@@ -1473,8 +1562,11 @@ void AILCALL AIL_start_sample(HSAMPLE handle)
}
EnterCriticalSection(&g_engine.lock);
- sample->voice->Stop(0);
- sample->voice->FlushSourceBuffers();
+ // a second start of the same sound: a voice of its own again, as freshVoice says why
+ if (sample->started && !freshVoice(sample, sample->format)) {
+ LeaveCriticalSection(&g_engine.lock);
+ return;
+ }
XAUDIO2_BUFFER buffer;
memset(&buffer, 0, sizeof(buffer));
@@ -1487,6 +1579,7 @@ void AILCALL AIL_start_sample(HSAMPLE handle)
refreshSampleOutput(sample);
sample->voice->Start(0);
sample->playing = true;
+ sample->started = true;
} else {
releaseSampleData(sample->data);
}
@@ -1721,36 +1814,9 @@ void AILCALL AIL_ex_set_3D_air(F32 speed_of_sound, F32 absorption_distance)
void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo, F32 slap)
{
g_roomSend.store(wet);
- if (g_engine.room == NULL) {
- return;
+ if (g_roomTap != NULL) {
+ g_roomTap->set(decay, damping, echo, slap);
}
-
- // I3DL2's terms, from its open-air preset: the top end loses up to 30 dB and dies sooner as the
- // damping rises, and an echo is an early reflection that late, less smeared, at the slap's level
- // in millibels against the reverb's: -200 for a slap of 0.35, as miles_miniaudio hears it.
- const float REFERENCE_SLAP = 0.35f;
- const INT32 MILLIBELS_PER_DECADE = 2000;
- const INT32 REFLECTIONS_AT_REFERENCE = -200;
- const float MAX_REVERB_DELAY = 0.1f; // I3DL2's ReverbDelay limit
- const INT32 MIN_REFLECTIONS = -10000; // I3DL2's Reflections range, millibels
- const INT32 MAX_REFLECTIONS = 1000;
- XAUDIO2FX_REVERB_I3DL2_PARAMETERS room = XAUDIO2FX_I3DL2_PRESET_PLAIN;
- room.WetDryMix = 100.0f;
- room.Room = 0;
- room.RoomHF = -(INT32)(damping * 3000.0f);
- room.DecayTime = decay;
- room.DecayHFRatio = 1.0f - 0.9f * damping;
- const INT32 reflections = echo > 0.0f && slap > 0.0f
- ? REFLECTIONS_AT_REFERENCE + (INT32)(MILLIBELS_PER_DECADE * log10f(slap / REFERENCE_SLAP))
- : MIN_REFLECTIONS;
- room.Reflections = reflections > MAX_REFLECTIONS ? MAX_REFLECTIONS : (reflections < MIN_REFLECTIONS ? MIN_REFLECTIONS : reflections);
- room.ReflectionsDelay = echo;
- room.Reverb = -600;
- room.ReverbDelay = echo * 0.5f + 0.01f < MAX_REVERB_DELAY ? echo * 0.5f + 0.01f : MAX_REVERB_DELAY;
- room.Diffusion = echo > 0.0f ? 60.0f : 100.0f;
- XAUDIO2FX_REVERB_PARAMETERS native;
- ReverbConvertI3DL2ToNative(&room, &native);
- g_engine.room->SetEffectParameters(0, &native, sizeof(native));
}
void AILCALL AIL_ex_duck(H3DSAMPLE trigger, F32 gain, F32 seconds)
diff --git a/GeneralsMD/Code/Tests/test_miles_effects.cpp b/GeneralsMD/Code/Tests/test_miles_effects.cpp
index 5cf23f581..943fc45e6 100644
--- a/GeneralsMD/Code/Tests/test_miles_effects.cpp
+++ b/GeneralsMD/Code/Tests/test_miles_effects.cpp
@@ -8,8 +8,10 @@
* back through AIL_ex_start_capture, the tap -wav writes its file from. The expected numbers are the
* physics the helpers in MSS.h claim, worked out here, not read back from them.
*
- * Not covered: XAudio2's own filter, reverb and duck, which only a player on Windows hears, and the
- * delay a world sound starts with, which is the game's request list and not this library.
+ * The room is MSS/mss_ex_room.h, which miles_xaudio2 runs too, so the room tests hold for what a
+ * player on Windows hears. Not covered: XAudio2's own filter and its wall-clock duck, which need an
+ * audio device, and the delay a world sound starts with, which is the game's request list and not
+ * this library.
*/
#include "test_harness.h"