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
perf(milesaudiodevice): read a sound's first play off the frame
Olcay Seyganed97b29a0fb4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6dde8dcb..7efdab447 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -504,6 +504,7 @@ found and fixed, EA's own, not port damage.**## The frame rate cap is gone- The picture now runs uncapped; the rules keep their own steady clock.+- A sound's first play no longer freezes the battle. The whole game stopped while the hard disk found the file: up to 187 ms at the worst moment of a two minute fight with eight computer players here, and seconds with anything else busy on the same drive. Files now load beside the game, and the worst frame of that fight fell to 19 ms on Classic from 68 to 140, and to about 42 on the full Reforged look from 111 to 187. The sound starts a little late instead: over a whole match off a cold disk, more than half within 5 ms, 95 in 100 within 100 ms, a third of a second at the very worst. A shot still waiting after half a second is skipped, because by then it is the wrong shot, while replies jump the queue and always play. The rings under a veteran's aura had the same fault, up to 125 ms the first time each kind lit, and now load with the map. The game also kept only 4 MB of sound in memory, the figure from 2003, so sounds pushed each other out and came back off the disk 3,508 times in those two minutes. It keeps 64 MB now, a whole match fits in 39, and the same fight reads about 35 files.- On a machine with two graphics chips, the game used to draw on the first one it found, which was the slow one. It now uses the dedicated card, and a match holds about 260 frames a second with the trees, the shadows and the filtering left on.- Display options has a vertical sync box. Off, the picture still runs free. On, it waits for the monitor so the frame does not tear. The box takes effect when you Accept.- With vertical sync off, the picture really is free again. Ever since the game started drawing through Direct3D 11, fullscreen and windowed games were still held to the monitor's refresh: 164 frames a second on a 164 Hz screen, and a 60 Hz screen sat at 60 and sank into the fifties in a fight, where the old renderer had given players over 450. The same match now takes 2.3ms a frame, over 400 a second, where it was pinned at 6.1ms. Every picture is the same one it was. Vertical sync on still waits for the monitor.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 9e1a3d80d..267df68e6 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -1765,6 +1765,7 @@ GameEngine/Source/GameNetwork/WOLBrowser/WebBrowserPosix.cppGameEngine/Source/GameNetwork/udp.cppGameEngine/Source/Precompiled/PreRTS.cppGameEngineDevice/GameEngineDevice.dsp+GameEngineDevice/Include/MilesAudioDevice/AudioFileLoader.hGameEngineDevice/Include/MilesAudioDevice/AudioMixPolicy.hGameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.hGameEngineDevice/Include/PosixDevice/Common/PosixFileResolutionDump.hdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex ad692dde1..81b82b127 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -2522,7 +2522,7 @@ add_test(NAME miles_smoke COMMAND miles_smoke# the test calls it by the same names.add_executable(test_miles_effects ${TESTS}/test_miles_effects.cpp ${WW}/Miles6/miniaudio/miles_miniaudio.cpp)set_source_files_properties(${TESTS}/test_miles_effects.cpp PROPERTIES COMPILE_DEFINITIONS MSS_BACKEND_PREFIX=MA_)-target_include_directories(test_miles_effects PRIVATE ${WW}/Miles6/include ${WW}/WWLib)+target_include_directories(test_miles_effects PRIVATE ${WW}/Miles6/include ${WW}/WWLib ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Include)target_link_libraries(test_miles_effects PRIVATE test_harness miniaudio)add_test(NAME test_miles_effects COMMAND test_miles_effects)endif() # ZH_PLATFORM_WINDOWS - device and codec smoke tests@@ -2554,7 +2554,7 @@ else()endif()# The same file Windows runs: the air, room and duck in the offline mix.add_executable(test_miles_effects ${TESTS}/test_miles_effects.cpp)-target_include_directories(test_miles_effects PRIVATE ${WW}/Miles6/include)+target_include_directories(test_miles_effects PRIVATE ${WW}/Miles6/include ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Include)target_link_libraries(test_miles_effects PRIVATE test_harness milesaudio)add_test(NAME test_miles_effects COMMAND test_miles_effects)diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/AudioFileLoader.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/AudioFileLoader.hnew file mode 100644index 000000000..7402c21ed--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/AudioFileLoader.h@@ -0,0 +1,284 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/+// Modified 2026 by Olcay Seygan for Zero Hour Reforged; see the git history.++// FILE: AudioFileLoader.h+// The disk half of a sound's first play, on a thread of its own, so the frame that asked for the+// sound does not wait on a hard disk: 137 ms once in a two minute window on a quiet machine, 9806 ms+// beside a build on the same drive. The main thread asks by name and looks again next pass; the+// thread reads the file through a function it was given and decompresses it. Which files stay in+// memory and for how long is AudioFileCache's business and stays on the main thread, so all this+// shares with anyone is the job list under its own lock. The engine is reached only through that+// function, so a test can hold it.++#pragma once++#include <chrono>+#include <condition_variable>+#include <deque>+#include <map>+#include <mutex>+#include <string>+#include <thread>++#include <string.h>++#include "MSS/MSS.h"++class AudioFileLoader+{+public:+ /// A sound file as the mixer wants it: a WAV image of PCM.+ struct Loaded+ {+ void *file; ///< NULL when the file is missing or in a format the mixer does not play+ unsigned size; ///< bytes of file+ bool compressed; ///< made by AIL_decompress_ADPCM, and so freed by AIL_mem_free_lock+ AILSOUNDINFO info;+ float readMs;+ float decodeMs;+ float askedToDoneMs;+ };++ /// All of a file in a new[] buffer, or NULL. Called on the thread.+ typedef char *(*ReadFile)(const char *name, unsigned *size);++ enum { LATE_BUCKETS = 6 };+ static float lateBucketMs(int bucket)+ {+ static const float limits[LATE_BUCKETS - 1] = { 5.0f, 16.7f, 33.3f, 100.0f, 500.0f };+ return limits[bucket];+ }++ /// What the thread has done since it started, for the log.+ struct Stats+ {+ unsigned files;+ double readMs, readWorstMs;+ double decodeMs, decodeWorstMs;+ double askedToDoneMs, askedToDoneWorstMs;+ unsigned doneWithin[LATE_BUCKETS]; ///< files by asked to done, up to each of lateBucketMs and past the last+ };++ explicit AudioFileLoader(ReadFile read) :+ m_read(read),+ m_stopping(false),+ m_working(false),+ m_thread(&AudioFileLoader::run, this)+ {+ memset(&m_stats, 0, sizeof(m_stats));+ }++ /** Waits for the file in hand, if there is one, so nothing outlives the file system it reads. */+ ~AudioFileLoader()+ {+ {+ std::lock_guard<std::mutex> lock(m_lock);+ m_stopping = true;+ }+ m_wake.notify_all();+ m_thread.join();+ for (Jobs::iterator it = m_jobs.begin(); it != m_jobs.end(); ++it) {+ if (it->second.done) {+ release(&it->second.loaded);+ }+ }+ }++ /** Is this file read and decoded? The first ask queues it, and a false means ask again later.+ * An urgent one goes to the front. `read` is for a file that wants another way to the disk than+ * the loader's own. */+ bool ready(const char *name, bool urgent = false, ReadFile read = NULL)+ {+ std::lock_guard<std::mutex> lock(m_lock);+ Jobs::iterator it = m_jobs.find(name);+ if (it != m_jobs.end()) {+ return it->second.done;+ }+ Job &job = m_jobs[name];+ job.done = false;+ job.read = read != NULL ? read : m_read;+ job.askedAt = Clock::now();+ if (urgent) {+ m_queue.push_front(name);+ } else {+ m_queue.push_back(name);+ }+ m_wake.notify_one();+ return false;+ }++ /** How long a file asked for and not yet finished has been waited for, in milliseconds. */+ float waitedMs(const char *name)+ {+ std::lock_guard<std::mutex> lock(m_lock);+ Jobs::iterator it = m_jobs.find(name);+ return it != m_jobs.end() && !it->second.done ? milliseconds(Clock::now() - it->second.askedAt) : 0.0f;+ }++ /** Hands over what ready said was there, which is then the caller's to release. False if the+ * thread has not finished it. */+ bool take(const char *name, Loaded *loaded)+ {+ std::lock_guard<std::mutex> lock(m_lock);+ Jobs::iterator it = m_jobs.find(name);+ if (it == m_jobs.end() || !it->second.done) {+ return false;+ }+ *loaded = it->second.loaded;+ m_jobs.erase(it);+ return true;+ }++ /** Until every file asked for so far has been read. A test's way of not racing the disk. */+ void waitUntilIdle()+ {+ std::unique_lock<std::mutex> lock(m_lock);+ m_idle.wait(lock, [this] { return m_queue.empty() && !m_working; });+ }++ Stats stats()+ {+ std::lock_guard<std::mutex> lock(m_lock);+ return m_stats;+ }++ /** Reading and decompressing one file, on whichever thread calls it. */+ static void load(ReadFile read, const char *name, Loaded *loaded)+ {+ memset(loaded, 0, sizeof(*loaded));+ const Clock::time_point start = Clock::now();+ unsigned size = 0;+ char *buffer = read(name, &size);+ const Clock::time_point afterRead = Clock::now();+ loaded->readMs = milliseconds(afterRead - start);+ if (buffer == NULL) {+ return;+ }++ AILSOUNDINFO info;+ memset(&info, 0, sizeof(info));+ AIL_WAV_info(buffer, &info);+ if (info.format == WAVE_FORMAT_IMA_ADPCM) {+ void *decompressed = NULL;+ U32 decompressedSize = 0;+ if (AIL_decompress_ADPCM(&info, &decompressed, &decompressedSize)) {+ loaded->file = decompressed;+ loaded->size = decompressedSize;+ loaded->compressed = true;+ loaded->info = info;+ }+ delete [] buffer;+ } else if (info.format == WAVE_FORMAT_PCM) {+ loaded->file = buffer;+ loaded->size = size;+ loaded->info = info;+ } else {+ delete [] buffer;+ }+ loaded->decodeMs = milliseconds(Clock::now() - afterRead);+ }++ static void release(Loaded *loaded)+ {+ if (loaded->compressed) {+ AIL_mem_free_lock(loaded->file);+ } else {+ delete [] (char *)loaded->file;+ }+ loaded->file = NULL;+ }++private:+ typedef std::chrono::steady_clock Clock;++ struct Job+ {+ bool done;+ ReadFile read;+ Clock::time_point askedAt;+ Loaded loaded;+ };+ typedef std::map<std::string, Job> Jobs;++ static float milliseconds(Clock::duration span)+ {+ return std::chrono::duration<float, std::milli>(span).count();+ }++ void run()+ {+ std::unique_lock<std::mutex> lock(m_lock);+ for (;;) {+ m_wake.wait(lock, [this] { return m_stopping || !m_queue.empty(); });+ if (m_stopping) {+ return;+ }+ const std::string name = m_queue.front();+ m_queue.pop_front();+ m_working = true;+ const ReadFile read = m_jobs[name].read;++ lock.unlock();+ Loaded loaded;+ load(read, name.c_str(), &loaded);+ lock.lock();++ m_working = false;+ Job &job = m_jobs[name];+ job.loaded = loaded;+ job.done = true;+ job.loaded.askedToDoneMs = milliseconds(Clock::now() - job.askedAt);+ note(job.loaded);+ m_idle.notify_all();+ }+ }++ void note(const Loaded &loaded)+ {+ ++m_stats.files;+ m_stats.readMs += loaded.readMs;+ m_stats.decodeMs += loaded.decodeMs;+ m_stats.askedToDoneMs += loaded.askedToDoneMs;+ if (loaded.readMs > m_stats.readWorstMs) {+ m_stats.readWorstMs = loaded.readMs;+ }+ if (loaded.decodeMs > m_stats.decodeWorstMs) {+ m_stats.decodeWorstMs = loaded.decodeMs;+ }+ if (loaded.askedToDoneMs > m_stats.askedToDoneWorstMs) {+ m_stats.askedToDoneWorstMs = loaded.askedToDoneMs;+ }+ int bucket = 0;+ while (bucket < LATE_BUCKETS - 1 && loaded.askedToDoneMs > lateBucketMs(bucket)) {+ ++bucket;+ }+ ++m_stats.doneWithin[bucket];+ }++ ReadFile m_read;+ std::mutex m_lock;+ std::condition_variable m_wake;+ std::condition_variable m_idle;+ std::deque<std::string> m_queue;+ Jobs m_jobs;+ Stats m_stats;+ bool m_stopping;+ bool m_working;+ std::thread m_thread; ///< last, so it starts with everything above it made+};diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.hindex 2ecd008ed..0330dffd0 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h@@ -26,6 +26,7 @@#include "Common/AudioSettings.h"#include "Common/GameAudio.h"#include "MSS/MSS.h"+#include "MilesAudioDevice/AudioFileLoader.h"#include "mutex.h"#include <list>#include <map>@@ -160,8 +161,19 @@ class AudioFileCachevoid *openFile( AudioEventRTS *eventToOpenFrom );void closeFile( void *fileToClose );void setMaxSize( UnsignedInt size );+ /// Can openFile give this event its next file without the disk? A no starts the read, off the frame.+ Bool fileIsReady( AudioEventRTS *eventToOpenFrom, Bool urgent );+ /// Has this one waited past the point of being heard as what it was? A yes is counted as dropped.+ Bool fileComesTooLate( AudioEventRTS *eventToOpenFrom );// End Protected by mutex+ /// A stream opens its own file, on the main thread: this reads its start and end ahead of that.+ Bool streamIsWarm( const AsciiString &name ) { return m_loader.ready(name.str(), false, warmStreamFile); }+ void streamOpened( const AsciiString &name );++ void waitForLoads() { m_loader.waitUntilIdle(); }+ void logLoads();+// Note: These functions should be used for informational purposes only. For speed reasons,// they are not protected by the mutex, so they are not guarenteed to be valid if called from// outside the audio cache. They should be used as a rough estimate only.@@ -180,9 +192,14 @@ class AudioFileCache#if defined(_WIN32)HANDLE m_mutex;#else- std::timed_mutex *m_mutex; ///< Windows' named mutex, as a process's own (C4): ScopedMutex.h+ std::timed_mutex *m_mutex; ///< Windows' mutex, as a process's own (C4): ScopedMutex.h#endif- const char *m_mutexName;+ AudioFileLoader m_loader;+ UnsignedInt m_readsOnTheFrame; ///< files read where they were asked for: -wav, the forced briefing voice+ UnsignedInt m_droppedLate;++ private:+ static char *warmStreamFile( const char *name, unsigned *size );};class MilesAudioManager : public AudioManager@@ -308,6 +325,9 @@ class MilesAudioManager : public AudioManager// Looping functionsBool startNextLoop( PlayingAudio *looping );+ Bool fileIsReady( AudioEventRTS *event );+ Bool fileComesTooLate( AudioRequest *req );+ void continueFromRequestList( PlayingAudio *playing );void endLoopPassNow( PlayingAudio *audio );void playStream( AudioEventRTS *event, HSTREAM stream );diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cppindex 344a1e556..dca1142ce 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp@@ -104,6 +104,8 @@ static inline PlayingStatus playingStatusCompareExchange( volatile PlayingStatus#endifenum { INFINITE_LOOP_COUNT = 1000000 };+static const UnsignedInt MIN_AUDIO_CACHE_BYTES = 64 * 1024 * 1024;+static const Real LATE_SOUND_MS = 500.0f;// Callback functions useful for Miles ////////////////////////////////////////////////////////////static void AILCALLBACK setSampleCompleted( HSAMPLE sampleCompleted );@@ -166,6 +168,7 @@ MilesAudioManager::~MilesAudioManager()DEBUG_ASSERTCRASH(m_binkHandle == NULL, ("Leaked a Bink handle. Chuybregts"));releaseHandleForBink();closeDevice();+ m_audioCache->logLoads();delete m_audioCache;DEBUG_ASSERTCRASH(this == TheAudio, ("Umm...\n"));@@ -512,7 +515,10 @@ void MilesAudioManager::init()// We should now know how many samples we want to loadopenDevice();- m_audioCache->setMaxSize(getAudioSettings()->m_maxCacheSize);+ // The shipped 4 MB held about a tenth of what one match plays, so sounds pushed each other out and+ // came back from the disk all the time: 3508 reads of 338 files in two minutes of eight AIs, 314 MB.+ // All 474 files of a whole 17 minute match come to 39 MB. A bigger figure in the INI still stands.+ m_audioCache->setMaxSize(max(getAudioSettings()->m_maxCacheSize, MIN_AUDIO_CACHE_BYTES));// Now, set the file callbacks to load the streams from Biggie filesAIL_set_file_callbacks(streamingFileOpen, streamingFileClose, streamingFileSeek, streamingFileRead);@@ -535,6 +541,10 @@ void MilesAudioManager::reset()AudioManager::reset();stopAllAudioImmediately();removeAllAudioRequests();+ // A file read past this point would read the file system's mod list through a GlobalData that+ // its own reset, which comes after this one, is about to free.+ m_audioCache->waitForLoads();+ m_audioCache->logLoads();m_recentShots.clear();m_replyAtMs.clear();// the bed went with everything else; the next map, the same one again included, chooses anew@@ -737,7 +747,8 @@ void MilesAudioManager::pauseAudio( AudioAffect which )for (ait = m_audioRequests.begin(); ait != m_audioRequests.end(); /* empty */){AudioRequest *req = (*ait);- if( req && req->m_request == AR_Play )+ // a track that waits for its file while the music plays on through this pause is not paused+ if( req && req->m_request == AR_Play && (BitTest(which, AudioAffect_Music) || !audioIsType(req->m_pendingEvent, AT_Music)) ){req->deleteInstance();ait = m_audioRequests.erase(ait);@@ -814,7 +825,8 @@ void MilesAudioManager::playAudioEvent( AudioEventRTS *event, Bool requestStop,delete event; // nothing downstream will take it nowreturn;}- if (!event->getIsLogicalAudio() && refuseReply(event)) {+ // a line's next portion, come round by the request list for its file, is that line going on+ if (!nextLoop && !event->getIsLogicalAudio() && refuseReply(event)) {delete event;return;}@@ -880,6 +892,7 @@ void MilesAudioManager::playAudioEvent( AudioEventRTS *event, Bool requestStop,HSTREAM stream;if (!handleToKill || foundSoundToReplace) {stream = AIL_open_stream(m_digitalHandle, fileToPlay.str(), 0);+ m_audioCache->streamOpened(fileToPlay);} else {stream = NULL;}@@ -1100,6 +1113,17 @@ void MilesAudioManager::stopAudioEvent( AudioHandle handle )}}}++ // A track asked for ahead of this stop and still waiting for its file would start after it.+ std::list<AudioRequest*>::iterator waiting = m_audioRequests.begin();+ while (waiting != m_audioRequests.end() && !((*waiting)->m_request == AR_Stop && (*waiting)->m_handleToInteractOn == handle)) {+ if ((*waiting)->m_usePendingEvent && audioIsType((*waiting)->m_pendingEvent, AT_Music)) {+ (*waiting)->deleteInstance();+ waiting = m_audioRequests.erase(waiting);+ } else {+ ++waiting;+ }+ }}//@@ -1585,6 +1609,17 @@ void MilesAudioManager::stopAllSpeech( void )}releasePlayingAudioInListIfStopped(m_playingStreams, m_playingStreamsCS);++ // and a line still waiting for its file, which would talk over the one that asked for this+ std::list<AudioRequest*>::iterator waiting = m_audioRequests.begin();+ while (waiting != m_audioRequests.end()) {+ if ((*waiting)->m_usePendingEvent && audioIsType((*waiting)->m_pendingEvent, AT_Streaming)) {+ (*waiting)->deleteInstance();+ waiting = m_audioRequests.erase(waiting);+ } else {+ ++waiting;+ }+ }}//-------------------------------------------------------------------------------------------------@@ -2006,6 +2041,10 @@ void MilesAudioManager::notifyOfAudioCompletion( UnsignedIntPtr audioCompleted,// middle of this call, and close that file a second time.closeFile(playing->m_file);playing->m_file = NULL;+ if (playing->m_type != PAT_Stream && !fileIsReady(playing->m_audioEventRTS)) {+ continueFromRequestList(playing);+ return;+ }if (playing->m_type == PAT_Sample) {playing->m_file = playSample(playing->m_audioEventRTS, playing->m_sample);@@ -2999,12 +3038,34 @@ void MilesAudioManager::processRequestList( void )continue;}+ // Asked first: a sound waiting out its distance reads its file in the meantime.+ const Bool fileReady = !req->m_usePendingEvent || fileIsReady(req->m_pendingEvent);+if (!shouldProcessRequestThisFrame(req)) {adjustRequest(req);++it;continue;}+ if (!fileReady && fileComesTooLate(req)) {+ req->deleteInstance();+ it = m_audioRequests.erase(it);+ continue;+ }++ if (!fileReady) {+ // It stays, as one waiting for its distance does, so a stop still finds it, and is asked+ // again as it lands. The sound it was to replace may have ended by then, and a replacement+ // that finds nothing to replace does not play, so the question of who gives way is open+ // again (checkForSample, for a sound effect; a stream keeps its victim and is not asked).+ if (req->m_pendingEvent->getAudioEventInfo()->m_soundType == AT_SoundEffect) {+ req->m_pendingEvent->setHandleToKill(0);+ req->m_requiresCheckForSample = true;+ }+ ++it;+ continue;+ }+if (!req->m_requiresCheckForSample || checkForSample(req)) {processRequest(req);}@@ -3803,6 +3864,69 @@ Real MilesAudioManager::getEffectiveVolume(AudioEventRTS *event) constreturn volume;}+//-------------------------------------------------------------------------------------------------+/** This pass is done, and the next waits on the request list, for its delay or its file, with a copy+ * of the event. EA handed over the event itself and kept pointing at it until the sweep, so a stop+ * that dropped the request in the same update freed it under this entry, and the next walk of the+ * list (stopAudioEvent, the sweep's stopPlayingAudio) read freed memory. */+void MilesAudioManager::continueFromRequestList( PlayingAudio *playing )+{+#if defined(_WIN32)+ InterlockedCompareExchange( (volatile long *)&playing->m_status, PS_Stopping, PS_Playing );+#else+ playingStatusCompareExchange( &playing->m_status, PS_Stopping, PS_Playing );+#endif++ AudioRequest *req = allocateAudioRequest(true);+ req->m_pendingEvent = MSGNEW("AudioEventRTS") AudioEventRTS(*playing->m_audioEventRTS);+ req->m_pendingEvent->setHandleToKill(0); // it made room when it started, and a replacement that finds nothing to replace does not play+ req->m_requiresCheckForSample = true;+ req->m_nextLoop = true;+ req->m_requestStop = playing->m_requestStop; // a stop's decay portion, which plays and ends there+ appendAudioRequest(req);+}++//-------------------------------------------------------------------------------------------------+/** The sound effects' files are the ones the cache reads. Streams open their own, and a -wav run+ * moves the mix by the logic clock, where a late sound would be late in the film for good, and the+ * wall clock does not matter: its files are read where they are asked for. */+Bool MilesAudioManager::fileIsReady( AudioEventRTS *event )+{+ if (event->getAudioEventInfo() == NULL) {+ getInfoForAudioEvent(event);+ }+ const AudioEventInfo *info = event->getAudioEventInfo();+ if (info == NULL || TheGlobalData->m_wavEndFrame > 0) {+ return TRUE;+ }+ // Loading a map with mod factions turns the file system's focus to each mod in turn, which would+ // send a read on another thread into the wrong mod's files. Nobody is watching frames then.+ if (TheGlobalData->m_modFactions && TheGameLogic->isLoadingMap()) {+ return TRUE;+ }+ if (info->m_soundType != AT_SoundEffect) {+ return m_audioCache->streamIsWarm(event->getFilename());+ }+ // a reply answers a click, so it goes past the battle's first plays in the queue+ return m_audioCache->fileIsReady(event, BitTest(info->m_type, ST_VOICE));+}++//-------------------------------------------------------------------------------------------------+/** A shot half a second behind its muzzle flash reads as a different shot, and in a fight the next+ * one is coming anyway, so a one-shot world or interface sound gives up there. The file still+ * lands in the cache for the next one. A reply is still the answer to the click, a script may be+ * waiting on its sound, and a loop's next pass would otherwise end it for good: those play late. */+Bool MilesAudioManager::fileComesTooLate( AudioRequest *req )+{+ AudioEventRTS *event = req->m_pendingEvent;+ const AudioEventInfo *info = event->getAudioEventInfo();+ if (info == NULL || info->m_soundType != AT_SoundEffect || (info->m_control & AC_LOOP) || BitTest(info->m_type, ST_VOICE)+ || event->getIsLogicalAudio() || req->m_nextLoop) {+ return FALSE;+ }+ return m_audioCache->fileComesTooLate(event);+}+//-------------------------------------------------------------------------------------------------Bool MilesAudioManager::startNextLoop( PlayingAudio *looping ){@@ -3817,23 +3941,8 @@ Bool MilesAudioManager::startNextLoop( PlayingAudio *looping )// generate a new filename, and test to see whether we can play with it nowlooping->m_audioEventRTS->generateFilename();- if (looping->m_audioEventRTS->getDelay() > MSEC_PER_LOGICFRAME_REAL) {- // This pass is done, and the next waits on the request list for its delay with a copy of- // the event. EA handed over the event itself and kept pointing at it until the sweep, so a- // stop that dropped the request in the same update freed it under this entry, and the next- // walk of the list (stopAudioEvent, the sweep's stopPlayingAudio) read freed memory.-#if defined(_WIN32)- InterlockedCompareExchange( (volatile long *)&looping->m_status, PS_Stopping, PS_Playing );-#else- playingStatusCompareExchange( &looping->m_status, PS_Stopping, PS_Playing );-#endif--- AudioRequest *req = allocateAudioRequest(true);- req->m_pendingEvent = MSGNEW("AudioEventRTS") AudioEventRTS(*looping->m_audioEventRTS);- req->m_requiresCheckForSample = true;- req->m_nextLoop = true;- appendAudioRequest(req);+ if (looping->m_audioEventRTS->getDelay() > MSEC_PER_LOGICFRAME_REAL || !fileIsReady(looping->m_audioEventRTS)) {+ continueFromRequestList(looping);return true;}@@ -4171,12 +4280,27 @@ U32 AILCALLBACK streamingFileRead(AILFILEHANDLE file_handle, void *buffer, U32 b//-------------------------------------------------------------------------------------------------//-------------------------------------------------------------------------------------------------//--------------------------------------------------------------------------------------------------AudioFileCache::AudioFileCache() : m_maxSize(0), m_currentlyUsedSize(0), m_mutexName("AudioFileCacheMutex")+/** AudioFileLoader's way to the files, on its thread. What it reads is the same open and read any+ * other reader off the main thread makes: the archive's read has its own lock. */+static char *readAudioFile( const char *name, unsigned *size )+{+ File *file = TheFileSystem->openFile(name);+ if (!file) {+ return NULL;+ }+ *size = file->size();+ return file->readEntireAndClose();+}++//-------------------------------------------------------------------------------------------------+/** The mutex had a name, which made it every process's: a second copy of the game on the machine+ * waited on this one's disk reads, up to the 500 ms ScopedMutex gives up after. */+AudioFileCache::AudioFileCache() : m_maxSize(0), m_currentlyUsedSize(0), m_loader(readAudioFile), m_readsOnTheFrame(0), m_droppedLate(0){#if defined(_WIN32)- m_mutex = CreateMutex(NULL, FALSE, m_mutexName);+ m_mutex = CreateMutex(NULL, FALSE, NULL);#else- m_mutex = new std::timed_mutex; // the process's own: Windows' name made it every process's, by accident+ m_mutex = new std::timed_mutex;#endif}@@ -4207,25 +4331,94 @@ AudioFileCache::~AudioFileCache()}//--------------------------------------------------------------------------------------------------void *AudioFileCache::openFile( AudioEventRTS *eventToOpenFrom )+static AsciiString nextFileOf( AudioEventRTS *event ){- // Protect the entire openFile function- ScopedMutex mut(m_mutex);-- AsciiString strToFind;- switch (eventToOpenFrom->getNextPlayPortion())+ switch (event->getNextPlayPortion()){case PP_Attack:- strToFind = eventToOpenFrom->getAttackFilename();- break;+ return event->getAttackFilename();case PP_Sound:- strToFind = eventToOpenFrom->getFilename();- break;+ return event->getFilename();case PP_Decay:- strToFind = eventToOpenFrom->getDecayFilename();- break;- case PP_Done:- return NULL;+ return event->getDecayFilename();+ }+ return AsciiString::TheEmptyString;+}++//-------------------------------------------------------------------------------------------------+Bool AudioFileCache::fileIsReady( AudioEventRTS *eventToOpenFrom, Bool urgent )+{+ ScopedMutex mut(m_mutex);++ const AsciiString name = nextFileOf(eventToOpenFrom);+ return name.isEmpty() || m_openFiles.find(name) != m_openFiles.end() || m_loader.ready(name.str(), urgent != FALSE);+}++//-------------------------------------------------------------------------------------------------+Bool AudioFileCache::fileComesTooLate( AudioEventRTS *eventToOpenFrom )+{+ ScopedMutex mut(m_mutex);++ if (m_loader.waitedMs(nextFileOf(eventToOpenFrom).str()) < LATE_SOUND_MS) {+ return FALSE;+ }+ ++m_droppedLate;+ return TRUE;+}++//-------------------------------------------------------------------------------------------------+/** A stream's file is opened on the main thread, and that was 277 ms for a music track on a hard disk,+ * against 2 ms with its sectors in the OS's cache, so this reads them first and throws them away. An+ * archived track is read whole by the open here, as by the one that follows (FileSystem::openFile+ * does not pass File::STREAMING on to the archive); a loose one takes the start, where FFmpeg learns+ * the format, and the end, where it looks for tags. */+char *AudioFileCache::warmStreamFile( const char *name, unsigned *size )+{+ static const Int START_BYTES = 1024 * 1024;+ static const Int END_BYTES = 64 * 1024;+ File *file = TheFileSystem->openFile(name, File::READ | File::STREAMING);+ if (file) {+ char *buffer = NEW char[START_BYTES];+ file->read(buffer, START_BYTES);+ file->seek(-END_BYTES, File::END);+ file->read(buffer, END_BYTES);+ delete [] buffer;+ file->close();+ }+ return NULL;+}++//-------------------------------------------------------------------------------------------------+void AudioFileCache::streamOpened( const AsciiString &name )+{+ AudioFileLoader::Loaded nothing;+ m_loader.take(name.str(), ¬hing); // so the next play of it warms it again+}++//-------------------------------------------------------------------------------------------------+void AudioFileCache::logLoads()+{+ const AudioFileLoader::Stats stats = m_loader.stats();+ if (stats.files == 0 && m_readsOnTheFrame == 0) {+ return;+ }+ const double files = stats.files > 0 ? stats.files : 1;+ DEBUG_LOG(("AUDIO FILES: %u off the frame, %u on it, %u sounds dropped as too late | read %.2f/%.2f decode %.2f/%.2f asked to done "+ "%.2f/%.2f ms mean/worst, %u/%u/%u/%u/%u/%u of them within 5/17/33/100/500/more | %u of %u bytes held\n", stats.files,+ m_readsOnTheFrame, m_droppedLate, stats.readMs / files, stats.readWorstMs, stats.decodeMs / files, stats.decodeWorstMs,+ stats.askedToDoneMs / files, stats.askedToDoneWorstMs, stats.doneWithin[0], stats.doneWithin[1], stats.doneWithin[2],+ stats.doneWithin[3], stats.doneWithin[4], stats.doneWithin[5], m_currentlyUsedSize, m_maxSize));+}++//-------------------------------------------------------------------------------------------------+void *AudioFileCache::openFile( AudioEventRTS *eventToOpenFrom )+{+ // Protect the entire openFile function+ ScopedMutex mut(m_mutex);++ const AsciiString strToFind = nextFileOf(eventToOpenFrom);+ if (strToFind.isEmpty()) {+ return NULL;}OpenFilesHash::iterator it;@@ -4241,53 +4434,31 @@ void *AudioFileCache::openFile( AudioEventRTS *eventToOpenFrom )return it->second.m_file;}- // Couldn't find the file, so actually open it.- File *file = TheFileSystem->openFile(strToFind.str());- if (!file) {- DEBUG_ASSERTLOG(strToFind.isEmpty(), ("Missing Audio File: '%s'\n", strToFind.str()));+ // Not in memory. A sound in a match waited on the request list for the loader to finish this+ // (fileIsReady); what comes here unasked is read here, a -wav run and the forced briefing voice.+ AudioFileLoader::Loaded loaded;+ if (!m_loader.take(strToFind.str(), &loaded)) {+ AudioFileLoader::load(readAudioFile, strToFind.str(), &loaded);+ ++m_readsOnTheFrame;+ }+ if (!loaded.file) {+ DEBUG_ASSERTLOG(FALSE, ("Missing or unreadable Audio File: '%s'\n", strToFind.str()));return NULL;}- UnsignedInt fileSize = file->size();- char* buffer = file->readEntireAndClose();-- OpenAudioFile openedAudioFile;- openedAudioFile.m_eventInfo = eventToOpenFrom->getAudioEventInfo();-- AILSOUNDINFO soundInfo;- AIL_WAV_info(buffer, &soundInfo);-- if (eventToOpenFrom->isPositionalAudio()) {- if (soundInfo.channels > 1) {- DEBUG_CRASH(("Requested Positional Play of audio '%s', but it is in stereo.", strToFind.str()));- delete [] buffer;- return NULL;- }- }-- if (soundInfo.format == WAVE_FORMAT_IMA_ADPCM) {- void *decompressFileBuffer;- U32 newFileSize;- AIL_decompress_ADPCM(&soundInfo, &decompressFileBuffer, &newFileSize);- fileSize = newFileSize;- openedAudioFile.m_compressed = TRUE;- delete [] buffer;- openedAudioFile.m_file = decompressFileBuffer;- openedAudioFile.m_soundInfo = soundInfo;- openedAudioFile.m_openCount = 1;- } else if (soundInfo.format == WAVE_FORMAT_PCM) {- openedAudioFile.m_compressed = FALSE;- openedAudioFile.m_file = buffer;- openedAudioFile.m_soundInfo = soundInfo;- openedAudioFile.m_openCount = 1;- } else {- DEBUG_CRASH(("Unexpected compression type in '%s'\n", strToFind.str()));- // prevent leaks- delete [] buffer;+ if (eventToOpenFrom->isPositionalAudio() && loaded.info.channels > 1) {+ DEBUG_CRASH(("Requested Positional Play of audio '%s', but it is in stereo.", strToFind.str()));+ AudioFileLoader::release(&loaded);return NULL;}- openedAudioFile.m_fileSize = fileSize;+ OpenAudioFile openedAudioFile;+ openedAudioFile.m_eventInfo = eventToOpenFrom->getAudioEventInfo();+ openedAudioFile.m_compressed = loaded.compressed ? TRUE : FALSE;+ openedAudioFile.m_file = loaded.file;+ openedAudioFile.m_soundInfo = loaded.info;+ openedAudioFile.m_openCount = 1;+ openedAudioFile.m_fileSize = loaded.size;m_currentlyUsedSize += openedAudioFile.m_fileSize;if (m_currentlyUsedSize > m_maxSize) {// We need to free some samples, or we're not going to be able to play this sound.diff --git a/GeneralsMD/Code/Tests/test_miles_effects.cpp b/GeneralsMD/Code/Tests/test_miles_effects.cppindex 813c7a664..43fb4fdc9 100644--- a/GeneralsMD/Code/Tests/test_miles_effects.cpp+++ b/GeneralsMD/Code/Tests/test_miles_effects.cpp@@ -10,6 +10,9 @@* 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.*+ * Also the read of a sound's file off the frame (AudioFileLoader.h), against a disk the test holds,+ * and through this backend's decompress and mix.+ ** Not covered: XAudio2's own filter, which needs an audio device.*/#include "test_harness.h"@@ -18,10 +21,15 @@#include <stdio.h>#include <string.h>+#include <chrono>+#include <condition_variable>+#include <mutex>#include <string>+#include <thread>#include <vector>#include "MSS/MSS.h"+#include "MilesAudioDevice/AudioFileLoader.h"static const unsigned TONE_RATE = 22050;static const double TONE_PI = 3.14159265358979323846; // MSVC's math.h gives M_PI only on request@@ -268,6 +276,231 @@ TEST(a_loud_mix_never_reaches_full_scale)CHECK(rms(capture, 1.1, 1.2) < 0.0002);}+// ---- A sound's file off the frame (AudioFileLoader) ----------------------------------------------++// A disk that holds every read until the test lets it go, so "the asker did not wait" is no race.+static std::mutex g_diskLock;+static std::condition_variable g_diskMoved;+static bool g_diskOpen = false;+static int g_diskReads = 0;+static std::vector<unsigned char> g_diskImage;++static char *readFromHeldDisk(const char *name, unsigned *size)+{+ std::unique_lock<std::mutex> lock(g_diskLock);+ ++g_diskReads;+ g_diskMoved.wait(lock, [] { return g_diskOpen; });+ if (strcmp(name, "missing.wav") == 0) {+ return NULL;+ }+ char *buffer = new char[g_diskImage.size()];+ memcpy(buffer, &g_diskImage[0], g_diskImage.size());+ *size = (unsigned)g_diskImage.size();+ return buffer;+}++static void holdDisk(const std::vector<unsigned char> &image)+{+ std::lock_guard<std::mutex> lock(g_diskLock);+ g_diskImage = image;+ g_diskOpen = false;+ g_diskReads = 0;+}++static void openDisk()+{+ std::lock_guard<std::mutex> lock(g_diskLock);+ g_diskOpen = true;+ g_diskMoved.notify_all();+}++static int diskReads()+{+ std::lock_guard<std::mutex> lock(g_diskLock);+ return g_diskReads;+}++// A WAV image of IMA ADPCM, the shape of the game's voices: runs of one nibble up and one down, a+// triangle wave and so a sound, with no encoder here to get wrong.+static std::vector<unsigned char> makeAdpcm(unsigned blocks)+{+ const unsigned BLOCK = 256;+ const unsigned dataBytes = blocks * BLOCK;+ std::vector<unsigned char> image(60 + dataBytes);+ memcpy(&image[0], "RIFF", 4);+ put32(&image[4], (unsigned)image.size() - 8);+ memcpy(&image[8], "WAVEfmt ", 8);+ put32(&image[16], 20);+ put16(&image[20], 0x11);+ put16(&image[22], 1);+ put32(&image[24], TONE_RATE);+ put32(&image[28], TONE_RATE / 2);+ put16(&image[32], BLOCK);+ put16(&image[34], 4);+ put16(&image[36], 2);+ put16(&image[38], 1 + (BLOCK - 4) * 2);+ memcpy(&image[40], "fact", 4);+ put32(&image[44], 4);+ put32(&image[48], blocks * (1 + (BLOCK - 4) * 2));+ memcpy(&image[52], "data", 4);+ put32(&image[56], dataBytes);+ for (unsigned i = 0; i < dataBytes; ++i) {+ image[60 + i] = (i % BLOCK) < 4 ? 0 : ((i % 80) < 40 ? 0x44 : 0xCC);+ }+ return image;+}++TEST(a_file_on_a_stuck_disk_leaves_the_asker_free_and_is_read_once)+{+ startAudio();+ const std::vector<unsigned char> image = makeAdpcm(40);+ holdDisk(image);+ {+ AudioFileLoader loader(readFromHeldDisk);+ AudioFileLoader::Loaded loaded;++ // every call comes straight back while the read sits on the disk: one held under the lock+ // would hang here+ CHECK(!loader.ready("voice.wav"));+ CHECK(!loader.ready("voice.wav"));+ CHECK(!loader.take("voice.wav", &loaded));+ CHECK(!loader.take("never asked.wav", &loaded));+ std::this_thread::sleep_for(std::chrono::milliseconds(20));+ CHECK(loader.waitedMs("voice.wav") >= 10.0f);+ CHECK_EQ(loader.waitedMs("never asked.wav"), 0.0f);++ openDisk();+ loader.waitUntilIdle();+ CHECK(loader.ready("voice.wav"));+ CHECK_EQ(loader.waitedMs("voice.wav"), 0.0f);+ CHECK_EQ(diskReads(), 1);+ CHECK(loader.take("voice.wav", &loaded));+ CHECK(!loader.take("voice.wav", &loaded)); // handed over once++ // what comes back is what the mixer's own decompress makes of the file+ AILSOUNDINFO info;+ AIL_WAV_info(&image[0], &info);+ void *direct = NULL;+ U32 directSize = 0;+ CHECK(AIL_decompress_ADPCM(&info, &direct, &directSize) != 0);+ CHECK(loaded.compressed);+ CHECK_EQ(loaded.size, (unsigned)directSize);+ CHECK_EQ(memcmp(loaded.file, direct, directSize), 0);+ CHECK_EQ((int)loaded.info.format, 0x11);+ AIL_mem_free_lock(direct);++ // and it plays+ const std::vector<unsigned char> decoded((unsigned char *)loaded.file, (unsigned char *)loaded.file + loaded.size);+ std::vector<H3DSAMPLE> sound(1, place(decoded, -20.0f, 0.0f, 1.0f));+ const Capture capture = listen(sound, 0.4);+ CHECK(rms(capture, 0.0, 0.3) > 0.01);+ AudioFileLoader::release(&loaded);+ CHECK(loaded.file == NULL);++ const AudioFileLoader::Stats stats = loader.stats();+ CHECK_EQ(stats.files, 1u);+ }+}++TEST(an_urgent_file_goes_past_the_queue_but_not_the_one_on_the_disk)+{+ static std::vector<std::string> order;+ order.clear();+ struct Recording+ {+ static char *read(const char *name, unsigned *size)+ {+ char *buffer = readFromHeldDisk(name, size);+ std::lock_guard<std::mutex> lock(g_diskLock);+ order.push_back(name);+ return buffer;+ }+ };+ holdDisk(makeTone(440.0, 50));+ AudioFileLoader loader(Recording::read);+ loader.ready("in hand.wav");+ while (diskReads() == 0) {+ std::this_thread::yield();+ }+ loader.ready("shot.wav");+ loader.ready("reply.wav", true);+ openDisk();+ loader.waitUntilIdle();+ CHECK_EQ((int)order.size(), 3);+ CHECK_STR(order[0].c_str(), "in hand.wav");+ CHECK_STR(order[1].c_str(), "reply.wav");+ CHECK_STR(order[2].c_str(), "shot.wav");+ const char *names[3] = { "in hand.wav", "reply.wav", "shot.wav" };+ for (int i = 0; i < 3; ++i) {+ AudioFileLoader::Loaded loaded;+ CHECK(loader.take(names[i], &loaded));+ AudioFileLoader::release(&loaded);+ }+}++TEST(a_plain_pcm_file_comes_through_untouched)+{+ const std::vector<unsigned char> image = makeTone(440.0, 100);+ holdDisk(image);+ openDisk();+ AudioFileLoader loader(readFromHeldDisk);+ loader.ready("shot.wav");+ loader.waitUntilIdle();+ AudioFileLoader::Loaded loaded;+ CHECK(loader.take("shot.wav", &loaded));+ CHECK(!loaded.compressed);+ CHECK_EQ(loaded.size, (unsigned)image.size());+ CHECK_EQ(memcmp(loaded.file, &image[0], image.size()), 0);+ AudioFileLoader::release(&loaded);+}++TEST(a_missing_file_comes_back_empty_and_the_next_ask_looks_again)+{+ holdDisk(std::vector<unsigned char>(1, 0));+ openDisk();+ AudioFileLoader loader(readFromHeldDisk);+ AudioFileLoader::Loaded loaded;+ loader.ready("missing.wav");+ loader.waitUntilIdle();+ CHECK(loader.take("missing.wav", &loaded));+ CHECK(loaded.file == NULL);+ CHECK(!loader.ready("missing.wav"));+ loader.waitUntilIdle();+ CHECK_EQ(diskReads(), 2);+}++TEST(closing_waits_for_the_file_in_hand_and_reads_no_more)+{+ const std::vector<unsigned char> image = makeTone(440.0, 50);+ holdDisk(image);+ {+ AudioFileLoader loader(readFromHeldDisk);+ loader.ready("first.wav");+ loader.ready("second.wav");+ loader.ready("third.wav");+ // the thread is on the disk with the first before the disk opens, and the close starts behind it+ while (diskReads() == 0) {+ std::this_thread::yield();+ }+ std::thread opener([] {+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ openDisk();+ });+ opener.detach();+ }+ CHECK_EQ(diskReads(), 1);++ // a finished file nobody took goes with the loader+ holdDisk(image);+ openDisk();+ {+ AudioFileLoader loader(readFromHeldDisk);+ loader.ready("not taken.wav");+ loader.waitUntilIdle();+ }+ CHECK_EQ(diskReads(), 1);+}+TEST(headphones_hear_a_sound_on_the_right_later_quieter_and_duller_in_the_left_ear){// MSS.h's ears alone, both backends' code. A click straight to the right of a listener facing +ydiff --git a/GeneralsMD/Code/Tests/test_milesaudiomanager.cpp b/GeneralsMD/Code/Tests/test_milesaudiomanager.cppindex b09738de7..b6c34c278 100644--- a/GeneralsMD/Code/Tests/test_milesaudiomanager.cpp+++ b/GeneralsMD/Code/Tests/test_milesaudiomanager.cpp@@ -165,6 +165,7 @@ public:processCompletedAudio();setDeviceListenerPosition();processRequestList();+ m_audioCache->waitForLoads(); // the next tick plays what this one asked the disk for, however slow the diskprocessPlayingList();processFadingList();}@@ -522,11 +523,11 @@ TEST(two_track_changes_in_one_update_leave_one_track_playing)TheAudio->removeAudioEvent( AHSV_StopTheMusicFade );play( pick );}- audio->tick();+ audio->runFor( 20 ); // one tick for the stops and to warm the file, one to start the last trackCHECK_EQ( audio->musicPlaying(), 1 );// a track started with no stop in front of it replaces the one playingplay( pick );- audio->tick();+ audio->runFor( 20 );CHECK_EQ( audio->musicPlaying(), 1 );TheAudio->removeAudioEvent( AHSV_StopTheMusic );audio->runFor( 100 );