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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(audio): master limiter, steeper air, open and snow rooms, deafening duck
Olcay Seygan3de96804dd86
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 75f1d10c5..7ed631ded 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,10 +11,11 @@ found and fixed — EA's own, not port damage.**## Sound that travels- Sound takes time to cross the battlefield now. An explosion at the edge of the screen is heard about a quarter of a second after it is seen, one at the far end of a long view half a second after, at the speed of sound on the scale the units are drawn at. The wait never runs past a second, and unit replies, the interface, music, speech and every sound a mission script waits on still play the moment they are asked for.-- Distance takes the top off a sound as air does. Fighting near the middle of the screen keeps its crack, a battle across the map arrives as a dull rumble, and a nuke on the far side is mostly low thunder. The muffling EA gave sixteen explosions for when they go off out of view used to be only a drop in volume; it is a real muffling now, so those blasts are no quieter off screen than on it, only duller.-- Jets, helicopters and the Nuke Cannon's shell rise in pitch as they come in and drop as they pass, by how fast they move towards you. A Raptor run is two semitones up and down; an Aurora at full speed twice that.-- Every map has an echo of its own, worked out from how much of it is built over. A city map rings for nearly two seconds and throws a slap back off the buildings, open desert gives a faint short tail, and snow deadens whatever the map has. Far sounds carry more of it 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 pushes the rest of the battle down for a couple of seconds, by how close it is, and lets it back up.+- Distance takes the top off a sound as air does, twelve decibels an octave. Fighting in the middle of the screen keeps its crack, a blast across a long view arrives with its crack gone, mostly thump, and a nuke across the map is low thunder and nothing else. The muffling EA gave sixteen explosions for when they go off out of view used to be only a drop in volume; it is a real muffling now, so those blasts are no quieter off screen than on it, only duller.+- Jets, helicopters and the Nuke Cannon's shell rise in pitch as they come in and drop as they pass, by how fast they move towards you. Units cross the map far slower than the real machines would, so the bend is worked out at three times their speed: a Raptor run comes in six semitones high and leaves five low, and an Aurora screams in a full octave up.+- 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.- 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 Russiandiff --git a/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h b/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.hindex 3e599a49f..cea033924 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h@@ -47,11 +47,11 @@ struct AudioSettingsm_rangeVolumeFade( FALSE ),m_speedOfSound( 1700.0f ),m_maxSoundDelay( 1000.0f ),- m_dopplerScale( 1.0f ),- m_airAbsorptionDistance( 400.0f ),+ m_dopplerScale( 3.0f ),+ m_airAbsorptionDistance( 300.0f ),m_reverbLevel( 1.0f ),- m_duckVolume( 0.35f ),- m_duckTime( 2500.0f )+ m_duckVolume( 0.15f ),+ m_duckTime( 4000.0f ){m_duckSounds.push_back( "ExplosionNeutron" );m_duckSounds.push_back( "ExplosionDaisyCutter" );@@ -90,9 +90,11 @@ struct AudioSettings* microphone over it, never more than `MaxSoundDelay` milliseconds, and a moving one is pitched* by doppler. The ground is drawn at about 0.2 m a unit (a Ranger stands 13 units, a Crusader* is 30 long), so 343 m/s is 1700. Zero is neither. `DopplerScale` multiplies the speed doppler- * hears, zero switching doppler alone off.+ * hears, zero switching doppler alone off: 3, since a Raptor crosses the map at 35 m/s on that+ * scale and a real jet's pitch bend needs it about ten times faster.* `AirAbsorptionDistance`, game units: where air has taken the top end down from 20 kHz to 10,- * falling with the square of the distance past it. Zero is no air.+ * falling with the square of the distance past it, through two stages. Zero is no air. A snow+ * map takes it at 60%.* `ReverbLevel`: the room's send, as a share of what the map asks for. Zero is no room.* `DuckVolume` and `DuckTime` (milliseconds): when one of `DuckSounds` starts within earshot,* everything else dips to that volume and comes back over that time. 100% is no duck. */diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.hindex 637ca7ca3..efc9560fa 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h@@ -343,6 +343,7 @@ class MilesAudioManager : public AudioManager/// picture at any render rate and in a -wav run. Out of a game a pass counts as one frame.UnsignedInt m_clockFrame;Real m_clockElapsedMs;+ UnsignedInt m_clockMovedAt; ///< Clock_Milliseconds when the logic clock last moved onAsciiString m_roomMap; ///< the map setRoomFromMap last set the room for// LOGIC-THREAD.md M7: what the tick asks, as captureForLogic found it at the sync pointdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cppindex c3f0e9f85..11f2d0890 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp@@ -141,6 +141,7 @@ MilesAudioManager::MilesAudioManager() :m_delayFilter(NULL),m_clockFrame(0),m_clockElapsedMs(MSEC_PER_LOGICFRAME_REAL),+ m_clockMovedAt(0),m_binkHandle(NULL),m_pref3DProvider(AsciiString::TheEmptyString),m_prefSpeaker(AsciiString::TheEmptyString)@@ -1084,14 +1085,19 @@ void MilesAudioManager::stopAudioEvent( AudioHandle handle )// loop outlives the thing that asked for it. A one-shot sound effect still plays the one pass// it was waiting for, the same as one caught mid-play below; a loop is dropped, as one playing// below ends its pass, which matters since the distance delay holds nearly every world loop here.+ // A loop already heard and waiting between passes plays its decay now, as a playing one would.//std::list<AudioRequest*>::iterator ait;for ( ait = m_audioRequests.begin(); ait != m_audioRequests.end(); ++ait ) {AudioRequest *req = (*ait);if (req && req->m_usePendingEvent && req->m_pendingEvent&& req->m_pendingEvent->getPlayingHandle() == handle) {- if (audioIsType(req->m_pendingEvent, AT_SoundEffect)- && !(req->m_pendingEvent->getAudioEventInfo()->m_control & AC_LOOP)) {+ const Bool loop = (req->m_pendingEvent->getAudioEventInfo()->m_control & AC_LOOP) != 0;+ if (audioIsType(req->m_pendingEvent, AT_SoundEffect) && !loop) {+ req->m_requestStop = true;+ } else if (loop && req->m_nextLoop && req->m_pendingEvent->getDecayFilename().isNotEmpty()) {+ req->m_pendingEvent->setNextPlayPortion(PP_Decay);+ req->m_pendingEvent->setDelay(0.0f);req->m_requestStop = true;} else {req->deleteInstance();@@ -1298,7 +1304,7 @@ void MilesAudioManager::releaseMilesHandles( PlayingAudio *release ){if (release->m_3DSample) {AIL_register_3D_EOS_callback(release->m_3DSample, NULL);- AIL_stop_3D_sample(release->m_3DSample);+ AIL_end_3D_sample(release->m_3DSample); // an end, not a stop: the handle is done withm_available3DSamples.push_back(release->m_3DSample);release->m_3DSample = 0;}@@ -2904,6 +2910,7 @@ void MilesAudioManager::advanceAudioClock( void )if (!TheGameLogic->isInGame()){m_clockElapsedMs = MSEC_PER_LOGICFRAME_REAL;+ m_clockMovedAt = Clock_Milliseconds();return;}@@ -2911,6 +2918,8 @@ void MilesAudioManager::advanceAudioClock( void )const UnsignedInt frame = TheGameLogic->getFrame();m_clockElapsedMs = frame > m_clockFrame ? (Real)(frame - m_clockFrame) * MSEC_PER_LOGICFRAME_REAL : 0.0f;m_clockFrame = frame;+ if (m_clockElapsedMs > 0.0f)+ m_clockMovedAt = Clock_Milliseconds();}//-------------------------------------------------------------------------------------------------@@ -2922,8 +2931,10 @@ void MilesAudioManager::trackVelocity( PlayingAudio *playing, const Coord3D *pos{if (m_clockElapsedMs <= 0.0f){- // a pass between two logic frames keeps the velocity; a paused game stands still, pitch too- if (playing->m_tracked && TheGameLogic->isGamePaused())+ // A pass between two logic frames keeps the velocity. A clock standing longer than a few frames+ // is a pause or a network stall, where nothing moves and no pitch may hang.+ const UnsignedInt CLOCK_STALL_MS = 100;+ if (playing->m_tracked && Clock_Milliseconds() - m_clockMovedAt > CLOCK_STALL_MS){playing->m_velocity.zero();AIL_set_3D_velocity_vector( playing->m_3DSample, 0.0f, 0.0f, 0.0f );@@ -2950,9 +2961,10 @@ void MilesAudioManager::trackVelocity( PlayingAudio *playing, const Coord3D *pos* its playable ground the placed structures cover. Supply docks are left out, being on every map at* a third to a full percent of it. The shipped maps measured that way run from about 0.1% (Twilight* Flame, Tournament Tundra) to near 3% (Tournament Urban, El Scorcho), and the room goes from open- * ground at 0.3%, a faint, short, dark tail, to a town at 1.9%, a longer and brighter one with an- * echo off the walls. Snow takes half the room away and most of its top end. The object list is- * the map file's, which the terrain keeps until the next map, so nothing in logic is asked. */+ * ground at 0.3%, a loud late slap and a long thin tail, to a town at 1.9%, a strong early echo off+ * the walls and a brighter tail. Snow leaves a third of the send, no echo, a short dead tail and+ * air that takes the top end off sooner. The object list is the map file's, which the terrain+ * keeps until the next map, so nothing in logic is asked. */void MilesAudioManager::setRoomFromMap( void ){Real built = 0.0f;@@ -2972,20 +2984,33 @@ void MilesAudioManager::setRoomFromMap( void )Real town = (cover - OPEN_COVER) / (TOWN_COVER - OPEN_COVER);town = town < 0.0f ? 0.0f : (town > 1.0f ? 1.0f : town);- Real wet = 0.06f + 0.24f * town;- Real decay = 0.7f + 1.1f * town;- Real damping = 0.6f - 0.3f * town;- const Real echo = town >= 0.3f ? 0.04f + 0.05f * town : 0.0f;- if (TheGlobalData->m_weather == WEATHER_SNOWY)+ // Open ground answers late and thin: a ridge's slap a quarter second on, then a long dark tail. A+ // town answers at once off the walls across the street, brighter and stronger.+ Real wet = 0.14f + 0.16f * town;+ Real decay = 2.6f - 0.8f * town;+ Real damping = 0.8f - 0.5f * town;+ Real echo = 0.26f - 0.17f * town;+ Real slap = 1.2f - 0.85f * town;+ Real absorption = m_audioSettings->m_airAbsorptionDistance;+ const Bool snowy = TheGlobalData->m_weather == WEATHER_SNOWY;+ if (snowy){- wet *= 0.5f;- decay *= 0.7f;- damping = damping > 0.85f ? damping : 0.85f;- }- AIL_ex_set_reverb(wet * m_audioSettings->m_reverbLevel, decay, damping, echo);- DEBUG_LOG(("AUDIO: room for %s: %.2f%% built over, town %.2f%s, send %.2f, decay %.2f s, damping %.2f, echo %d ms\n",- m_roomMap.str(), cover * 100.0f, town, TheGlobalData->m_weather == WEATHER_SNOWY ? " in snow" : "",- wet * m_audioSettings->m_reverbLevel, decay, damping, (Int)(echo * 1000.0f)));+ // snow swallows the echo and the top end, of the sound itself as well as the room's+ const Real SNOW_SEND_SHARE = 0.35f;+ const Real SNOW_DECAY_SECONDS = 0.4f;+ const Real SNOW_AIR_SHARE = 0.6f;+ wet *= SNOW_SEND_SHARE;+ decay = SNOW_DECAY_SECONDS;+ damping = 1.0f;+ echo = 0.0f;+ slap = 0.0f;+ absorption *= SNOW_AIR_SHARE;+ }+ AIL_ex_set_3D_air(m_audioSettings->m_speedOfSound, absorption);+ AIL_ex_set_reverb(wet * m_audioSettings->m_reverbLevel, decay, damping, echo, slap);+ DEBUG_LOG(("AUDIO: room for %s: %.2f%% built over, town %.2f%s, send %.2f, decay %.2f s, damping %.2f, "+ "echo %d ms at %.2f, air %.0f\n", m_roomMap.str(), cover * 100.0f, town, snowy ? " in snow" : "",+ wet * m_audioSettings->m_reverbLevel, decay, damping, (Int)(echo * 1000.0f), slap, absorption));}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.hindex 025185c26..743270195 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h@@ -295,17 +295,22 @@ void AILCALL AIL_ex_set_3D_linear_falloff(S32 linear);** AIL_ex_set_reverb: the one room every 3D sample sends to. wet is the send of a sample at full* volume (zero takes the room away), decay the seconds its tail takes to fall 60 dB, damping (0 to 1)- * how much sooner the top end dies, echo the seconds before the first reflection comes back.+ * how much sooner the top end dies, echo the seconds before the first reflection comes back, and+ * slap that reflection's level against the send: the wall across a street, or a ridge far off.** AIL_ex_duck: everything but the trigger, and any earlier trigger still sounding, dips to gain and- * comes back over seconds, AIL_ex_duck_gain's shape. miniaudio counts that time in frames mixed, so- * a -wav run ducks on the picture's clock; XAudio2 counts it on the wall clock it plays on. The- * movies' voice (mss_ex_pcm.h) is never ducked.+ * comes back over seconds, AIL_ex_duck_gain's shape, and the other 3D samples are muffled with it+ * (AIL_ex_duck_cutoff). miniaudio counts that time in frames mixed, so a -wav run ducks on the+ * picture's clock; XAudio2 counts it on the wall clock it plays on. The movies' voice+ * (mss_ex_pcm.h) is never ducked.+ *+ * Both backends hold the mix under AIL_EX_LIMITER_CEILING with the same limiter (AIL_ex_limit), so+ * nothing they play or record clips.** AIL_ex_set_3D_sample_dry: a 3D sample that takes no air, no doppler and no room, only its distance* gain, pan and occlusion; a unit's reply stays clean. Set on each play; a fresh handle is wet. */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);+void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo, F32 slap);void AILCALL AIL_ex_duck(H3DSAMPLE trigger, F32 gain, F32 seconds);void AILCALL AIL_ex_set_3D_sample_dry(H3DSAMPLE handle, S32 dry);@@ -342,7 +347,8 @@ static inline F32 AIL_ex_3D_distance_gain(F32 distance, F32 min_dist, F32 max_diabsorption_distance and falling with the square of the distance past it, so a blast across the mapis a rumble. Occlusion is EA's LowPassCutoff, which MilesAudioManager hands down as 1 - cutoff fora sound off screen; it used to be a cut in volume and is a ceiling now, 20 kHz times (1 - occlusion)- squared: 5 kHz for the shipped 50%. */+ squared: 5 kHz for the shipped 50%. Both backends run the cutoff through two one-pole stages, 12 dB+ an octave, steep enough to take the crack off a blast that is mostly bass. */static inline F32 AIL_ex_3D_cutoff(F32 distance, F32 absorption_distance, F32 occlusion){F32 cutoff = AIL_EX_OPEN_CUTOFF;@@ -403,4 +409,80 @@ static inline F32 AIL_ex_duck_gain(F32 elapsed, F32 gain, F32 seconds)return gain + (1.0f - gain) * (elapsed - hold) / (seconds - hold);}+/* The muffle a duck puts on the other 3D samples, a cutoff falling with the square of the duck's+ gain: a duck to 15% is a 450 Hz ceiling, one to 70% still 10 kHz, and the duck's end opens it. */+static inline F32 AIL_ex_duck_cutoff(F32 duck)+{+ return AIL_EX_OPEN_CUTOFF * duck * duck;+}++/* The master limiter both backends run last. A frame comes out AIL_EX_LIMITER_LOOKAHEAD - 1 frames+ late, at a gain already down to what the loudest frame of the window needs, so no sample passes the+ ceiling and none is cut flat. The gain falls along the average of the window's floors, a fade of+ two milliseconds rather than a step, and comes back over AIL_EX_LIMITER_RELEASE_SECONDS. */+#define AIL_EX_LIMITER_LOOKAHEAD 96+#define AIL_EX_LIMITER_MAX_CHANNELS 16+#define AIL_EX_LIMITER_CEILING 0.89f /* -1 dBFS */+#define AIL_EX_LIMITER_RELEASE_SECONDS 0.3f++typedef struct+{+ F32 delayed[AIL_EX_LIMITER_LOOKAHEAD * AIL_EX_LIMITER_MAX_CHANNELS];+ F32 needs[AIL_EX_LIMITER_LOOKAHEAD]; /* the gain each frame of the window asks for */+ F32 floors[AIL_EX_LIMITER_LOOKAHEAD]; /* the least of the window's needs, as it stood at each frame */+ double floorSum;+ F32 gain;+ F32 release;+ S32 channels;+ S32 at;+} AIL_EX_LIMITER;++static inline void AIL_ex_limiter_init(AIL_EX_LIMITER *limiter, S32 channels, F32 rate)+{+ S32 i;+ for (i = 0; i < AIL_EX_LIMITER_LOOKAHEAD * AIL_EX_LIMITER_MAX_CHANNELS; ++i)+ limiter->delayed[i] = 0.0f;+ for (i = 0; i < AIL_EX_LIMITER_LOOKAHEAD; ++i) {+ limiter->needs[i] = 1.0f;+ limiter->floors[i] = 1.0f;+ }+ limiter->floorSum = AIL_EX_LIMITER_LOOKAHEAD;+ limiter->gain = 1.0f;+ limiter->release = 1.0f - expf(-1.0f / (AIL_EX_LIMITER_RELEASE_SECONDS * rate));+ limiter->channels = channels;+ limiter->at = 0;+}++/* In place, `count` interleaved frames of the channel count the limiter was made for. */+static inline void AIL_ex_limit(AIL_EX_LIMITER *limiter, F32 *frames, S32 count)+{+ const S32 channels = limiter->channels;+ S32 frame, channel, i;+ for (frame = 0; frame < count; ++frame) {+ F32 *sample = frames + frame * channels;+ const S32 at = limiter->at;+ const S32 oldest = (at + 1) % AIL_EX_LIMITER_LOOKAHEAD;+ F32 peak = 0.0f;+ F32 floor = 1.0f;+ F32 target;+ for (channel = 0; channel < channels; ++channel) {+ const F32 level = fabsf(sample[channel]);+ if (level > peak) peak = level;+ }+ limiter->needs[at] = peak > AIL_EX_LIMITER_CEILING ? AIL_EX_LIMITER_CEILING / peak : 1.0f;+ for (i = 0; i < AIL_EX_LIMITER_LOOKAHEAD; ++i) {+ if (limiter->needs[i] < floor) floor = limiter->needs[i];+ }+ limiter->floorSum += floor - limiter->floors[at];+ limiter->floors[at] = floor;+ target = (F32)(limiter->floorSum / AIL_EX_LIMITER_LOOKAHEAD);+ limiter->gain = target < limiter->gain ? target : limiter->gain + (target - limiter->gain) * limiter->release;+ for (channel = 0; channel < channels; ++channel) {+ limiter->delayed[at * channels + channel] = sample[channel];+ sample[channel] = limiter->delayed[oldest * channels + channel] * limiter->gain;+ }+ limiter->at = oldest;+ }+}+#endif /* MSS_H */diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cppindex 114fd7d64..1dd41c2aa 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp@@ -82,7 +82,7 @@MSS_API(void, AIL_ex_stop_capture, (void), ()) \MSS_API(void, AIL_ex_set_3D_linear_falloff, (S32 linear), (linear)) \MSS_API(void, AIL_ex_set_3D_air, (F32 speed_of_sound, F32 absorption_distance), (speed_of_sound, absorption_distance)) \- MSS_API(void, AIL_ex_set_reverb, (F32 wet, F32 decay, F32 damping, F32 echo), (wet, decay, damping, echo)) \+ MSS_API(void, AIL_ex_set_reverb, (F32 wet, F32 decay, F32 damping, F32 echo, F32 slap), (wet, decay, damping, echo, slap)) \MSS_API(void, AIL_ex_duck, (H3DSAMPLE trigger, F32 gain, F32 seconds), (trigger, gain, seconds)) \MSS_API(void, AIL_ex_set_3D_sample_dry, (H3DSAMPLE handle, S32 dry), (handle, dry)) \MSS_API(S32, AIL_WAV_info, (const void *data, AILSOUNDINFO *info), (data, info)) \diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cppindex e1a50311a..6133f5131 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp@@ -305,17 +305,18 @@ const float LOW_PASS_DENORMAL_GUARD = 1e-18f; // a filter left ringing on silencstruct VoiceMix{VoiceMix() : resamplerReady(false), channels(0), gainLeft(0.0f), gainRight(0.0f), lowPass(1.0f), lowPassState(0.0f),- roomSend(0.0f), passThrough(false), pending(0), pendingAt(0) {}+ lowPassSecond(0.0f), roomSend(0.0f), passThrough(false), pending(0), pendingAt(0) {}ma_resampler resampler;bool resamplerReady;unsigned channels;float gainLeft;float gainRight;- // A 3D sample's air and occlusion, XAudio2's LowPassOnePoleFilter on the resampled sum: y += a(x - y),- // a = 1 passing it untouched. And its share into the room.+ // A 3D sample's air and occlusion, XAudio2's LowPassOnePoleFilter on the resampled sum, y += a(x - y),+ // a = 1 passing it untouched, and again after it as XAudio2's output filter. And its share into the room.float lowPass;float lowPassState;+ float lowPassSecond;float roomSend;// An XAudio2 voice with the default matrix rather than a panned Miles one: left to left and right// to right (a mono source to both), each at its gain. The movies' voice (mss_ex_pcm.h).@@ -362,20 +363,23 @@ void resetResampler(VoiceMix *mix)mix->pending = 0;mix->pendingAt = 0;mix->lowPassState = 0.0f;+ mix->lowPassSecond = 0.0f;}// Fills up to maxFrames of float source frames. Returns how many it gave; 0 means the source is dry.typedef unsigned (*SourceRead)(void *source, float *out, unsigned maxFrames);// Mixes up to `frames` output frames of one voice into `output`, at `duck` (AIL_ex_duck) on top of its-// gains, and its send into `room` when there is one. Returns true once the source is dry and nothing-// is left in flight, which is XAudio2's BuffersQueued == 0.+// gains with `muffle` (the duck's low-pass coefficient, 1 for none) as a ceiling on its own, and its+// send into `room` when there is one. Returns true once the source is dry and nothing is left in+// flight, which is XAudio2's BuffersQueued == 0.bool mixVoice(VoiceMix *mix, SourceRead read, void *source, float *output, unsigned frames, bool *sourceDry,- float duck, float *room)+ float duck, float muffle, float *room){const float left = mix->gainLeft * duck;const float right = mix->gainRight * duck;const float send = mix->roomSend * duck;+ const float lowPass = mix->lowPass < muffle ? mix->lowPass : muffle;float resampled[MIX_CHUNK_FRAMES * 2];unsigned done = 0;@@ -409,8 +413,9 @@ bool mixVoice(VoiceMix *mix, SourceRead read, void *source, float *output, unsigfor (unsigned channel = 0; channel < mix->channels; ++channel) {sum += resampled[frame * mix->channels + channel];}- mix->lowPassState += mix->lowPass * (sum - mix->lowPassState) + LOW_PASS_DENORMAL_GUARD;- sum = mix->lowPassState;+ mix->lowPassState += lowPass * (sum - mix->lowPassState) + LOW_PASS_DENORMAL_GUARD;+ mix->lowPassSecond += lowPass * (mix->lowPassState - mix->lowPassSecond) + LOW_PASS_DENORMAL_GUARD;+ sum = mix->lowPassSecond;output[(done + frame) * OUTPUT_CHANNELS + 0] += left * sum;output[(done + frame) * OUTPUT_CHANNELS + 1] += right * sum;if (room != NULL) {@@ -548,7 +553,6 @@ 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_ECHO_GAIN = 0.35f;const float ROOM_MAX_DAMPING = 0.7f;const float ROOM_MAX_ECHO_SECONDS = 0.3f; // I3DL2's ReflectionsDelay limit, where miles_xaudio2 puts the echoconst float ROOM_DENORMAL_GUARD = 1e-18f; // keeps a dying tail out of the denormals, which x64 does slowly@@ -565,11 +569,12 @@ struct DelayLinestruct Room{- Room() : ready(false), rate(0), damping(0.0f), echoLength(0) {}+ 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_reverbDelayLine echo;size_t echoLength;DelayLine combs[2][ROOM_COMBS];@@ -592,7 +597,7 @@ void initRoom(Room *room, unsigned rate)room->ready = true;}-void setRoom(Room *room, float decay, float damping, float echo)+void setRoom(Room *room, float decay, float damping, float echo, float slap){if (!room->ready) {return;@@ -605,6 +610,7 @@ void setRoom(Room *room, float decay, float damping, float echo)}}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;@@ -640,7 +646,7 @@ void processRoom(Room *room, const float *input, float *output, unsigned frames)pass.at = (pass.at + 1) % pass.line.size();sum = held - sum;}- output[frame * OUTPUT_CHANNELS + side] += sum + echoed * ROOM_ECHO_GAIN;+ output[frame * OUTPUT_CHANNELS + side] += sum + echoed * room->slap;}}}@@ -690,6 +696,7 @@ struct Engine// mixed so that a -wav run ducks on the logic clock.Room room;std::vector<float> roomInput;+ AIL_EX_LIMITER limiter; // the last thing the mix goes through, MSS.h'sbool duckActive;long long duckFrames;float duckGain;@@ -1263,13 +1270,15 @@ void dataCallback(ma_device *, void *output, const void *, ma_uint32 frameCount)float *room = &g_engine.roomInput[0];memset(room, 0, (size_t)frameCount * sizeof(float));+ const float muffle = AIL_ex_one_pole_coefficient(AIL_ex_duck_cutoff(duck), (float)g_engine.deviceRate);for (size_t i = 0; i < g_engine.samples.size(); ++i) {Sample *sample = g_engine.samples[i];if (!sample->running || !sample->queued || !sample->mix.resamplerReady) {continue;}+ const bool ducked = !sample->unducked;if (mixVoice(&sample->mix, readSampleSource, sample, out, frameCount, &sample->sourceDry,- sample->unducked ? 1.0f : duck, sample->is3D ? room : NULL)) {+ ducked ? duck : 1.0f, ducked && sample->is3D ? muffle : 1.0f, sample->is3D ? room : NULL)) {sample->queued = false;}}@@ -1280,18 +1289,19 @@ void dataCallback(ma_device *, void *output, const void *, ma_uint32 frameCount)continue;}stream->sourceDry = false;- mixVoice(&stream->mix, readStreamSource, stream, out, frameCount, &stream->sourceDry, duck, NULL);+ mixVoice(&stream->mix, readStreamSource, stream, out, frameCount, &stream->sourceDry, duck, 1.0f, NULL);}for (size_t i = 0; i < g_engine.pcmVoices.size(); ++i) {PcmVoice *voice = g_engine.pcmVoices[i];// Dry is only until the owner queues more, so it is asked afresh each pass, as a stream's is.// A movie is not ducked, as XAudio2's movie voice is not: -wav has to sound like the game.voice->sourceDry = false;- mixVoice(&voice->mix, readPcmSource, voice, out, frameCount, &voice->sourceDry, 1.0f, NULL);+ mixVoice(&voice->mix, readPcmSource, voice, out, frameCount, &voice->sourceDry, 1.0f, 1.0f, NULL);}if (g_engine.room.ready) {processRoom(&g_engine.room, room, out, frameCount);}+ AIL_ex_limit(&g_engine.limiter, out, (S32)frameCount);if (g_engine.capture != NULL) {writeCapture(g_engine.capture, out, frameCount);@@ -1356,6 +1366,7 @@ S32 AILCALL AIL_quick_startup(S32 use_digital, S32, U32, S32, S32)}g_engine.deviceRate = g_engine.device.sampleRate;initRoom(&g_engine.room, g_engine.deviceRate);+ AIL_ex_limiter_init(&g_engine.limiter, OUTPUT_CHANNELS, (float)g_engine.deviceRate);g_engine.deviceReady = true;if (!g_engine.offline && ma_device_start(&g_engine.device) != MA_SUCCESS) {ma_device_uninit(&g_engine.device);@@ -1951,9 +1962,6 @@ void AILCALL AIL_start_3D_sample(H3DSAMPLE handle)void AILCALL AIL_stop_3D_sample(H3DSAMPLE handle){AIL_stop_sample((HSAMPLE)handle);- // the manager stops every handle it takes back, and the next sound on it ducks like the rest- std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);- ((Sample *)handle)->unducked = false;}void AILCALL AIL_resume_3D_sample(H3DSAMPLE handle)@@ -1964,6 +1972,10 @@ void AILCALL AIL_resume_3D_sample(H3DSAMPLE handle)void AILCALL AIL_end_3D_sample(H3DSAMPLE handle){AIL_stop_sample((HSAMPLE)handle);+ // the manager ends every handle it takes back, and the next sound on it ducks like the rest; a+ // stop is also a pause, which keeps the exemption+ std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);+ ((Sample *)handle)->unducked = false;}void AILCALL AIL_set_3D_sample_volume(H3DSAMPLE handle, F32 volume)@@ -2013,11 +2025,11 @@ void AILCALL AIL_ex_set_3D_air(F32 speed_of_sound, F32 absorption_distance)g_absorptionDistance.store(absorption_distance);}-void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo)+void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo, F32 slap){g_roomSend.store(wet);std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);- setRoom(&g_engine.room, decay, damping, echo);+ setRoom(&g_engine.room, decay, damping, echo, slap);}void AILCALL AIL_ex_duck(H3DSAMPLE trigger, F32 gain, F32 seconds)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cppindex 62c96e91a..386726b61 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp@@ -469,15 +469,18 @@ Spatial computeSpatial(const Sample &sample)Spatial spatial;spatial.volume = clampUnit(sample.volume) * attenuation;spatial.pan = pan;+ // a duck muffles everything but its trigger, as miles_miniaudio's mix does+ const float muffle = sample.unducked ? AIL_EX_OPEN_CUTOFF : AIL_ex_duck_cutoff(g_duck.duckNow);if (sample.dry) {spatial.cutoff = AIL_ex_3D_cutoff(distance, 0.0f, sample.occlusion);spatial.send = 0.0f;spatial.doppler = 1.0f;- return spatial;+ } else {+ spatial.cutoff = AIL_ex_3D_cutoff(distance, g_absorptionDistance.load(), sample.occlusion);+ spatial.send = AIL_ex_3D_send(clampUnit(sample.volume), attenuation, g_roomSend.load());+ spatial.doppler = AIL_ex_doppler_ratio(dx, dy, dz, sample.velocityX, sample.velocityY, sample.velocityZ, g_speedOfSound.load());}- spatial.cutoff = AIL_ex_3D_cutoff(distance, g_absorptionDistance.load(), sample.occlusion);- spatial.send = AIL_ex_3D_send(clampUnit(sample.volume), attenuation, g_roomSend.load());- spatial.doppler = AIL_ex_doppler_ratio(dx, dy, dz, sample.velocityX, sample.velocityY, sample.velocityZ, g_speedOfSound.load());+ spatial.cutoff = spatial.cutoff < muffle ? spatial.cutoff : muffle;return spatial;}@@ -498,8 +501,10 @@ void refreshSampleOutput(Sample *sample)const XAUDIO2_FILTER_PARAMETERS filter = { LowPassOnePoleFilter,AIL_ex_one_pole_coefficient(spatial.cutoff, (float)g_engine.masterRate), 1.0f };sample->voice->SetFilterParameters(&filter);+ sample->voice->SetOutputFilterParameters(g_engine.master, &filter);// the voice's volume scales both sends, so the room's is given relative to itif (g_engine.room != NULL) {+ sample->voice->SetOutputFilterParameters(g_engine.room, &filter);applyRoomSend(sample->voice, sample->format.nChannels, volume > 0.0f ? spatial.send / volume : 0.0f);}}@@ -561,8 +566,9 @@ bool ensureVoice(Sample *sample, const WAVEFORMATEX &format)if (!sample->is3D) {return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, 0, 4.0f, &g_sampleCallback));}- // A 3D sample's voice has the filter for air and occlusion, and sends into the room as well.- XAUDIO2_SEND_DESCRIPTOR sends[2] = { { 0, g_engine.master }, { 0, g_engine.room } };+ // A 3D sample's voice has the filter for air and occlusion, and sends into the room as well. Each+ // send filters again, which makes the two one-pole stages miles_miniaudio runs.+ XAUDIO2_SEND_DESCRIPTOR sends[2] = { { XAUDIO2_SEND_USEFILTER, g_engine.master }, { XAUDIO2_SEND_USEFILTER, g_engine.room } };XAUDIO2_VOICE_SENDS sendList = { g_engine.room != NULL ? 2u : 1u, sends };return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, XAUDIO2_VOICE_USEFILTER, 4.0f,&g_sampleCallback, &sendList));@@ -963,14 +969,19 @@ void writeWaveHeader(FILE *file, unsigned int channels, unsigned int samplesPerSwriteLittleU32(file, dataBytes);}-class CaptureTap : public IXAPO+// 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{public:- CaptureTap(FILE *file, unsigned int channels, unsigned int samplesPerSecond)+ 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){- writeWaveHeader(m_file, m_channels, m_samplesPerSecond, 0);+ AIL_ex_limiter_init(&m_limiter, (S32)channels, (F32)samplesPerSecond);+ if (m_file != NULL) {+ writeWaveHeader(m_file, m_channels, m_samplesPerSecond, 0);+ }}STDMETHOD(QueryInterface)(REFIID riid, void **object)@@ -1009,7 +1020,7 @@ public:return E_OUTOFMEMORY;}memset(copy, 0, sizeof(*copy));- wcscpy_s(copy->FriendlyName, L"capture");+ wcscpy_s(copy->FriendlyName, L"master");wcscpy_s(copy->CopyrightInfo, L"");copy->MajorVersion = 1;copy->Flags = XAPO_FLAG_CHANNELS_MUST_MATCH | XAPO_FLAG_FRAMERATE_MUST_MATCH@@ -1063,25 +1074,23 @@ public:STDMETHOD_(void, Process)(UINT32, const XAPO_PROCESS_BUFFER_PARAMETERS *input, UINT32,XAPO_PROCESS_BUFFER_PARAMETERS *output, BOOL){- if (output != NULL) {- output[0].ValidFrameCount = input[0].ValidFrameCount;- output[0].BufferFlags = input[0].BufferFlags;- }-const UINT32 samples = input[0].ValidFrameCount * m_channels;- short converted[CAPTURE_CONVERSION_SAMPLES];+ float *mix = (float *)input[0].pBuffer;+ // in place: a silent pass is zeros through the limiter, which still has a tail to give outif (input[0].BufferFlags == XAPO_BUFFER_SILENT) {- memset(converted, 0, sizeof(converted));- for (UINT32 written = 0; written < samples; ) {- const UINT32 batch = min(samples - written, (UINT32)CAPTURE_CONVERSION_SAMPLES);- writeSamples(converted, batch);- written += batch;- }+ memset(mix, 0, samples * sizeof(float));+ }+ AIL_ex_limit(&m_limiter, mix, (S32)input[0].ValidFrameCount);+ if (output != NULL) {+ output[0].ValidFrameCount = input[0].ValidFrameCount;+ output[0].BufferFlags = XAPO_BUFFER_VALID;+ }+ if (m_file == NULL) {return;}- const float *mix = (const float *)input[0].pBuffer;+ short converted[CAPTURE_CONVERSION_SAMPLES];for (UINT32 read = 0; read < samples; ) {const UINT32 batch = min(samples - read, (UINT32)CAPTURE_CONVERSION_SAMPLES);for (UINT32 index = 0; index < batch; ++index) {@@ -1105,10 +1114,12 @@ public:}private:- ~CaptureTap()+ ~MasterTap(){- writeSizes();- fclose(m_file);+ if (m_file != NULL) {+ writeSizes();+ fclose(m_file);+ }}void writeSamples(const short *samples, UINT32 count)@@ -1136,13 +1147,34 @@ private:}volatile LONG m_references;- FILE *m_file;+ AIL_EX_LIMITER m_limiter;+ FILE *m_file; // NULL when nothing is being recordedunsigned int m_channels;unsigned int m_samplesPerSecond;unsigned int m_dataBytes;unsigned int m_sizesWrittenAt;};+// A fresh tap on the master, recording into `file` unless it is NULL. The chain holds the reference+// that matters from here; ours goes, and on a refusal that is the last one, so the tap closes its own+// file on the way out.+bool installMasterTap(FILE *file)+{+ XAUDIO2_VOICE_DETAILS details;+ g_engine.master->GetVoiceDetails(&details);+ MasterTap *tap = new MasterTap(file, details.InputChannels, details.InputSampleRate);+ XAUDIO2_EFFECT_DESCRIPTOR descriptor;+ descriptor.pEffect = static_cast<IXAPO *>(tap);+ descriptor.InitialState = TRUE;+ descriptor.OutputChannels = details.InputChannels;+ XAUDIO2_EFFECT_CHAIN chain;+ chain.EffectCount = 1;+ chain.pEffectDescriptors = &descriptor;+ const HRESULT result = g_engine.master->SetEffectChain(&chain);+ tap->Release();+ return SUCCEEDED(result);+}+} // namespace// =================================================================================================@@ -1187,6 +1219,7 @@ S32 AILCALL AIL_quick_startup(S32 use_digital, S32, U32, S32, S32)g_engine.master->GetVoiceDetails(&masterDetails);g_engine.masterRate = masterDetails.InputSampleRate;createRoom();+ installMasterTap(NULL);InterlockedExchange(&g_engine.serviceRunning, 1);g_engine.serviceThread = CreateThread(NULL, 0, serviceThreadMain, NULL, 0, NULL);@@ -1206,41 +1239,25 @@ S32 AILCALL AIL_ex_start_capture(const char *pathname)return 0;}- XAUDIO2_VOICE_DETAILS details;- g_engine.master->GetVoiceDetails(&details);-FILE *file = NULL;if (fopen_s(&file, pathname, "wb") != 0 || file == NULL) {return 0;}-- CaptureTap *tap = new CaptureTap(file, details.InputChannels, details.InputSampleRate);- XAUDIO2_EFFECT_DESCRIPTOR descriptor;- descriptor.pEffect = static_cast<IXAPO *>(tap);- descriptor.InitialState = TRUE;- descriptor.OutputChannels = details.InputChannels;- XAUDIO2_EFFECT_CHAIN chain;- chain.EffectCount = 1;- chain.pEffectDescriptors = &descriptor;-- const HRESULT result = g_engine.master->SetEffectChain(&chain);-- // the chain holds the reference that matters from here; ours goes, and on a refusal that is- // the last one, so the tap closes its own file on the way out- tap->Release();- return SUCCEEDED(result) ? 1 : 0;+ return installMasterTap(file) ? 1 : 0;}void AILCALL AIL_ex_stop_capture(void){if (g_engine.master != NULL) {- g_engine.master->SetEffectChain(NULL);+ installMasterTap(NULL);}}void AILCALL AIL_shutdown(void){- AIL_ex_stop_capture();+ if (g_engine.master != NULL) {+ g_engine.master->SetEffectChain(NULL);+ }if (g_engine.serviceThread != NULL) {InterlockedExchange(&g_engine.serviceRunning, 0);@@ -1632,10 +1649,6 @@ void AILCALL AIL_start_3D_sample(H3DSAMPLE handle)void AILCALL AIL_stop_3D_sample(H3DSAMPLE handle){AIL_stop_sample((HSAMPLE)handle);- // the manager stops every handle it takes back, and the next sound on it ducks like the rest- EnterCriticalSection(&g_engine.lock);- ((Sample *)handle)->unducked = false;- LeaveCriticalSection(&g_engine.lock);}void AILCALL AIL_resume_3D_sample(H3DSAMPLE handle)@@ -1646,6 +1659,11 @@ void AILCALL AIL_resume_3D_sample(H3DSAMPLE handle)void AILCALL AIL_end_3D_sample(H3DSAMPLE handle){AIL_stop_sample((HSAMPLE)handle);+ // the manager ends every handle it takes back, and the next sound on it ducks like the rest; a+ // stop is also a pause, which keeps the exemption+ EnterCriticalSection(&g_engine.lock);+ ((Sample *)handle)->unducked = false;+ LeaveCriticalSection(&g_engine.lock);}void AILCALL AIL_set_3D_sample_volume(H3DSAMPLE handle, F32 volume)@@ -1699,7 +1717,7 @@ void AILCALL AIL_ex_set_3D_air(F32 speed_of_sound, F32 absorption_distance)g_absorptionDistance.store(absorption_distance);}-void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo)+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) {@@ -1707,17 +1725,27 @@ void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo)}// 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 a strong early reflection that late, less smeared.+ // 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;- room.Reflections = echo > 0.0f ? -200 : -2000;+ 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;+ 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);diff --git a/GeneralsMD/Code/Tests/test_miles_effects.cpp b/GeneralsMD/Code/Tests/test_miles_effects.cppindex cc22128a6..5cf23f581 100644--- a/GeneralsMD/Code/Tests/test_miles_effects.cpp+++ b/GeneralsMD/Code/Tests/test_miles_effects.cpp@@ -1,6 +1,6 @@/*- * The air, room and duck of the Miles surface on miniaudio (MSS.h's AIL_ex_set_3D_air,- * AIL_ex_set_reverb and AIL_ex_duck), measured in the mix a -wav run records.+ * The air, room, duck and limiter of the Miles surface on miniaudio (MSS.h's AIL_ex_set_3D_air,+ * AIL_ex_set_reverb, AIL_ex_duck and AIL_ex_limit), measured in the mix a -wav run records.** miles_miniaudio.cpp is compiled into this test on its own, without the XAudio2 half, and run on its* offline mix: AIL_ex_offline_mix, then AIL_ex_mix_to_frame moves the mix by logic frames, so every@@ -103,12 +103,14 @@ struct Capture{std::vector<double> mono; // left plus right over twounsigned rate;+ double peak; // the loudest sample of either side, full scale 1};static Capture readCapture(){Capture capture;capture.rate = 0;+ capture.peak = 0.0;FILE *file = fopen(CAPTURE_PATH, "rb");if (file == NULL) {return capture;@@ -128,7 +130,11 @@ static Capture readCapture()const size_t frames = (bytes.size() - 44) / 4;capture.mono.resize(frames);for (size_t i = 0; i < frames; ++i) {- capture.mono[i] = ((double)(short)get16(&bytes[44 + i * 4]) + (double)(short)get16(&bytes[44 + i * 4 + 2])) / 2.0 / 32767.0;+ const double left = (double)(short)get16(&bytes[44 + i * 4]) / 32767.0;+ const double right = (double)(short)get16(&bytes[44 + i * 4 + 2]) / 32767.0;+ capture.mono[i] = (left + right) / 2.0;+ capture.peak = fabs(left) > capture.peak ? fabs(left) : capture.peak;+ capture.peak = fabs(right) > capture.peak ? fabs(right) : capture.peak;}return capture;}@@ -227,11 +233,11 @@ TEST(the_room_rings_on_after_the_sound_has_stopped)startAudio();// A tenth of a second of tone, then listen past it: dry is silence, a room is a tail.std::vector<unsigned char> tone = makeTone(440.0, 100);- AIL_ex_set_reverb(0.0f, 1.5f, 0.3f, 0.0f);+ AIL_ex_set_reverb(0.0f, 1.5f, 0.3f, 0.0f, 0.0f);std::vector<H3DSAMPLE> dry(1, place(tone, -20.0f, 0.0f, 1.0f));const Capture dryCapture = listen(dry, 1.0);- AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.0f);+ AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.0f, 0.0f);std::vector<H3DSAMPLE> wet(1, place(tone, -20.0f, 0.0f, 1.0f));const Capture wetCapture = listen(wet, 1.0);@@ -243,10 +249,10 @@ TEST(the_room_rings_on_after_the_sound_has_stopped)std::vector<H3DSAMPLE> prompt(1, place(blip, -20.0f, 0.0f, 1.0f));const Capture promptCapture = listen(prompt, 0.3);runSeconds(4.0);- AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.09f);+ AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.09f, 0.35f);std::vector<H3DSAMPLE> echoed(1, place(blip, -20.0f, 0.0f, 1.0f));const Capture echoCapture = listen(echoed, 0.3);- AIL_ex_set_reverb(0.0f, 1.0f, 0.0f, 0.0f);+ AIL_ex_set_reverb(0.0f, 1.0f, 0.0f, 0.0f, 0.0f);runSeconds(3.0); // let the tail die before the next test listensCHECK(rms(dryCapture, 0.0, 0.1) > 0.02);@@ -263,7 +269,7 @@ TEST(a_dry_sample_takes_no_air_and_no_room)startAudio();// A unit's reply: 1600 out with air at 400 keeps its 8 kHz, and a room at half send adds no tail.AIL_ex_set_3D_air(0.0f, 400.0f);- AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.0f);+ AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.0f, 0.0f);std::vector<unsigned char> bright = makeTone(8000.0, 500);std::vector<H3DSAMPLE> farReply(1, place(bright, -1600.0f, 0.0f, 1.0f));AIL_ex_set_3D_sample_dry(farReply[0], 1);@@ -277,7 +283,7 @@ TEST(a_dry_sample_takes_no_air_and_no_room)AIL_ex_set_3D_sample_dry(reply[0], 1);const Capture replyCapture = listen(reply, 1.0);AIL_ex_set_3D_air(0.0f, 0.0f);- AIL_ex_set_reverb(0.0f, 1.0f, 0.0f, 0.0f);+ AIL_ex_set_reverb(0.0f, 1.0f, 0.0f, 0.0f, 0.0f);runSeconds(3.0);CHECK(nearLevel > 0.05);@@ -289,8 +295,9 @@ TEST(a_dry_sample_takes_no_air_and_no_room)TEST(a_duck_dips_the_rest_and_spares_the_blast){startAudio();- // The rest is a steady tone; the blast is a silent sample, since only its exemption matters.- std::vector<unsigned char> steady = makeTone(440.0, 4000);+ // The rest is a steady tone, low enough that the duck's muffle leaves it be; the blast is a silent+ // sample, since only its exemption matters.+ std::vector<unsigned char> steady = makeTone(110.0, 4000);std::vector<unsigned char> blastTone = makeTone(880.0, 4000);std::vector<H3DSAMPLE> samples;samples.push_back(place(steady, -20.0f, 0.0f, 1.0f));@@ -305,3 +312,40 @@ TEST(a_duck_dips_the_rest_and_spares_the_blast)CHECK(rms(capture, 1.2, 1.3) / full > 0.4);CHECK(rms(capture, 1.2, 1.3) / full < 0.9);}++TEST(a_duck_muffles_what_it_dips)+{+ startAudio();+ // A duck to a quarter is a 1250 Hz ceiling, AIL_ex_duck_cutoff: an 8 kHz tone under it loses far+ // more than the quarter the gain takes.+ std::vector<unsigned char> bright = makeTone(8000.0, 3000);+ std::vector<unsigned char> blastTone = makeTone(880.0, 3000);+ std::vector<H3DSAMPLE> samples;+ samples.push_back(place(bright, -20.0f, 0.0f, 1.0f));+ samples.push_back(place(blastTone, -20.0f, 0.0f, 0.0f));+ AIL_ex_duck(samples[1], 0.25f, 2.0f);+ const Capture capture = listen(samples, 2.5);++ const double full = rms(capture, 2.1, 2.4);+ CHECK(full > 0.02);+ CHECK(rms(capture, 0.1, 0.45) / full < 0.1);+}++TEST(a_loud_mix_never_reaches_full_scale)+{+ startAudio();+ // Eight tones at full volume inside their minimum distance, all on the right: four times full+ // scale before the limiter, and nothing past its ceiling after it.+ const unsigned TONES = 8;+ std::vector<unsigned char> tones[TONES];+ std::vector<H3DSAMPLE> samples;+ for (unsigned i = 0; i < TONES; ++i) {+ tones[i] = makeTone(110.0 * (i + 1), 1000);+ samples.push_back(place(tones[i], -5.0f, 0.0f, 1.0f));+ }+ const Capture capture = listen(samples, 1.2);++ CHECK(capture.peak <= AIL_EX_LIMITER_CEILING + 0.001);+ CHECK(capture.peak > AIL_EX_LIMITER_CEILING - 0.05);+ CHECK(rms(capture, 1.1, 1.2) < 0.0002);+}