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(milesaudio): record the finished mix with -wav
Olcay Seygan06737cf86d88
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex dea984bca..5649fbb7a 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -427,6 +427,9 @@ public:Int m_videoStartFrame; ///< -video <from> <to> [name]: the first logic frame recordedInt m_videoEndFrame; ///< -video: the last logic frame recorded (0 = no video)AsciiString m_videoName; ///< -video: the recording is Videos\<name>.mp4 next to the save games+ Int m_wavStartFrame; ///< -wav <from> <to> [name]: the first logic frame of the sound recording+ Int m_wavEndFrame; ///< -wav: the last logic frame recorded (0 = no sound recording)+ AsciiString m_wavName; ///< -wav: the recording is Videos\<name>.wav next to the save gamesInt m_autoCameraSeconds; ///< -autocamera <n>: every n seconds, move the camera to wherever the fighting is (0 = off)Bool m_cameraLookSet; ///< -camera <x> <y>: point the camera at one map position once the match startsCoord2D m_cameraLook; ///< where -camera pointed itdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 36a0277b2..95920f851 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1489,6 +1489,60 @@ Int parseVideo(char *args[], int num)return consumed;}+/* -wav <from> <to> [name]: record what the game sounds like over logic frames <from> to <to>.+ *+ * A movie made by -video has no sound in it: the picture comes from a frame dump and the frames are+ * saved as fast as the disk takes them, which is nothing like the speed the mixer plays at. Sound+ * has to come off a second run at the pace a player would hear it, and the two runs line up because+ * the same seed and the same shot list play the same match twice. Everything the game plays goes+ * through one mastering voice, so the recording is the finished mix - music, effects, speech, the+ * 3D positioning, the lot - written to Videos\<name>.wav next to the save games. Mux it onto the+ * picture afterwards: ffmpeg -i <name>.mp4 -i <name>.wav -c:v copy -shortest <name>_sound.mp4.+ *+ * The run logs how long the recording took against how long the frames say it should have, which is+ * the only thing that can go wrong here: a run that cannot hold 30 frames a second drifts away from+ * the picture, and the AUDIO line says by how much before anyone edits with it. */+Int parseWav(char *args[], int num)+{+ if (num < 3)+ {+ DEBUG_LOG(("-wav: wants the first and the last logic frame to record, got %d arguments\n", num - 1));+ return num;+ }++ Int from = atoi(args[1]);+ if (from < 1)+ from = 1;+ const Int to = atoi(args[2]);++ AsciiString name;+ name.format("video_%d_%d", from, to);+ Int consumed = 3;+ if (num > 3 && args[3][0] != '-')+ {+ consumed = 4;+ if (isVideoNameUsable(args[3]))+ name = args[3];+ else+ DEBUG_LOG(("-wav: '%s' is not a usable name (letters, digits, '-' and '_'), recording as %s\n",+ args[3], name.str()));+ }++ if (to < from)+ {+ DEBUG_LOG(("-wav: the last frame %d comes before the first frame %d, so nothing is recorded\n", to, from));+ return consumed;+ }++ if (TheWritableGlobalData)+ {+ TheWritableGlobalData->m_wavStartFrame = from;+ TheWritableGlobalData->m_wavEndFrame = to;+ TheWritableGlobalData->m_wavName = name;+ }+ return consumed;+}+/* -autocamera [seconds]: every so often, put the camera wherever the fighting is.** A soak run watches from a free camera that never moves, and a camera that never moves is the@@ -2307,6 +2361,7 @@ static CommandLineParam params[] ={ "-maxframes", parseMaxGameFrames },{ "-screenshot", parseScreenShot },{ "-video", parseVideo },+ { "-wav", parseWav },{ "-msaa", parseMSAA },{ "-d3d9", parseDirect3D9 },{ "-language", parseTextLanguage },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 78c874d41..b0ba1623c 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -704,6 +704,9 @@ GlobalData::GlobalData()m_videoStartFrame = 0;m_videoEndFrame = 0; // record nothing unless -video asks for a rangem_videoName.clear();+ m_wavStartFrame = 0;+ m_wavEndFrame = 0; // record no sound unless -wav asks for a range+ m_wavName.clear();m_autoCameraSeconds = 0; // the camera stays where it was putm_cameraLookSet = FALSE; // -camera not given: the map decides where the view startsm_cameraLook.x = m_cameraLook.y = 0.0f;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cppindex ca00c68c2..3523b2bd5 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp@@ -496,10 +496,83 @@ void MilesAudioManager::reset()removeLevelSpecificAudioEventInfos();}+//-------------------------------------------------------------------------------------------------+/** -wav <from> <to> [name]: record the finished mix over a range of logic frames.+ *+ * The mixer plays at the speed a person hears, and -video saves frames at the speed the disk takes+ * them, so one run cannot make both halves of a film. This is the other run: the same seed and the+ * same shot list play the same match, and what comes out lines up with the picture as long as the+ * run held 30 logic frames a second. That is the one thing worth checking, so the closing line says+ * how much sound was recorded against how much the picture is going to be.+ *+ * A run that is not pacing itself cannot be recorded from at all, which is why -headless and a+ * lifted frame limit are refused here rather than producing something quietly wrong. */+static void updateSoundCapture( void )+{+ static Bool recording = FALSE;+ static Bool finished = FALSE;+ static __int64 startTicks = 0;++ if (TheGlobalData->m_wavEndFrame <= 0 || finished)+ return;+ if (TheGameLogic == NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())+ return;++ if (TheGlobalData->m_headless || !TheGlobalData->m_useFpsLimit)+ {+ finished = TRUE;+ DEBUG_LOG(("AUDIO: -wav needs a run that plays at the speed a person hears it, so -headless "+ "and -noFPSLimit record nothing\n"));+ return;+ }++ const UnsignedInt frame = TheGameLogic->getFrame();+ if (frame < (UnsignedInt)TheGlobalData->m_wavStartFrame)+ return;++ if (!recording)+ {+ char directory[_MAX_PATH];+ snprintf(directory, ARRAY_SIZE(directory), "%sVideos", TheGlobalData->getPath_UserData().str());+ CreateDirectoryA(directory, NULL);++ char pathname[_MAX_PATH];+ snprintf(pathname, ARRAY_SIZE(pathname), "%s\\%s.wav", directory, TheGlobalData->m_wavName.str());+ if (!AIL_ex_start_capture(pathname))+ {+ finished = TRUE;+ DEBUG_LOG(("AUDIO: nothing could be recorded into %s\n", pathname));+ return;+ }++ recording = TRUE;+ QueryPerformanceCounter((LARGE_INTEGER *)&startTicks);+ DEBUG_LOG(("AUDIO: recording logic frames %d to %d into %s\n",+ TheGlobalData->m_wavStartFrame, TheGlobalData->m_wavEndFrame, pathname));+ return;+ }++ if (frame <= (UnsignedInt)TheGlobalData->m_wavEndFrame)+ return;++ finished = TRUE;+ AIL_ex_stop_capture();++ __int64 nowTicks = 0;+ __int64 ticksPerSecond = 0;+ QueryPerformanceCounter((LARGE_INTEGER *)&nowTicks);+ QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond);+ const Real recordedSeconds = (Real)(nowTicks - startTicks) / (Real)ticksPerSecond;+ const Real pictureSeconds = (Real)(frame - TheGlobalData->m_wavStartFrame) / LOGICFRAMES_PER_SECONDS_REAL;+ DEBUG_LOG(("AUDIO: recorded %.2f seconds of sound for %.2f seconds of picture, %.2f adrift\n",+ recordedSeconds, pictureSeconds, recordedSeconds - pictureSeconds));+}+//-------------------------------------------------------------------------------------------------void MilesAudioManager::update(){AudioManager::update();+ updateSoundCapture();setDeviceListenerPosition();processRequestList();processPlayingList();diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.hindex 5ffe3d2d5..4cb463cc6 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h@@ -224,6 +224,13 @@ HAUDIO AILCALL AIL_quick_load_and_play(const char *filename, U32 loop_count,void AILCALL AIL_quick_unload(HAUDIO audio);void AILCALL AIL_quick_set_volume(HAUDIO audio, F32 volume, F32 extravol);+/* ---- capture ----------------------------------------------------------- */+/* Not Miles. The fork's own pair: everything the game plays is mixed into one mastering voice, so+ an effect on that voice is the whole soundtrack and nothing else on the machine. The caller+ decides when the recording starts, because only the caller knows what logic frame it is. */+S32 AILCALL AIL_ex_start_capture(const char *pathname);+void AILCALL AIL_ex_stop_capture(void);+/* ---- file format helpers ---------------------------------------------- */S32 AILCALL AIL_WAV_info(const void *data, AILSOUNDINFO *info);S32 AILCALL AIL_decompress_ADPCM(const AILSOUNDINFO *info, void **outdata, U32 *outsize);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cppindex 3f868a44d..33886cd1d 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp@@ -19,6 +19,7 @@#include <windows.h>#include <mmreg.h>#include <xaudio2.h>+#include <xapo.h>#include <math.h>#include <stdio.h>#include <stdlib.h>@@ -737,6 +738,236 @@ DWORD WINAPI serviceThreadMain(LPVOID)return 0;}+// ---------------------------------------------------------------------------------------------+// Capture+//+// Everything the game plays ends up in the one mastering voice, so an effect sitting on that voice+// is the whole soundtrack and nothing else on the machine. The effect passes the mix through+// untouched and writes a copy to a WAV file.+//+// The file is the tap's own: XAudio2 holds the only other reference, so the destructor runs after+// the last Process call and there is no window where one thread is writing a file the other has+// closed. Nothing is buffered off to another thread either - a write that blocks makes the live+// output stutter, and nobody is listening to a capture run.+// ---------------------------------------------------------------------------------------------++const int WAVE_HEADER_BYTES = 44;+const int WAVE_RIFF_SIZE_OFFSET = 4;+const int WAVE_DATA_SIZE_OFFSET = 40;+const int WAVE_FMT_CHUNK_BYTES = 16;+const int WAVE_PCM_TAG = 1;+const int CAPTURE_BITS_PER_SAMPLE = 16;+const float CAPTURE_SAMPLE_SCALE = 32767.0f;+const int CAPTURE_CONVERSION_SAMPLES = 4096;++void writeLittleU32(FILE *file, unsigned int value)+{+ fwrite(&value, sizeof(value), 1, file);+}++void writeLittleU16(FILE *file, unsigned short value)+{+ fwrite(&value, sizeof(value), 1, file);+}++void writeWaveHeader(FILE *file, unsigned int channels, unsigned int samplesPerSecond,+ unsigned int dataBytes)+{+ const unsigned int blockAlign = channels * (CAPTURE_BITS_PER_SAMPLE / 8);+ fwrite("RIFF", 1, 4, file);+ writeLittleU32(file, WAVE_HEADER_BYTES - 8 + dataBytes);+ fwrite("WAVEfmt ", 1, 8, file);+ writeLittleU32(file, WAVE_FMT_CHUNK_BYTES);+ writeLittleU16(file, WAVE_PCM_TAG);+ writeLittleU16(file, (unsigned short)channels);+ writeLittleU32(file, samplesPerSecond);+ writeLittleU32(file, samplesPerSecond * blockAlign);+ writeLittleU16(file, (unsigned short)blockAlign);+ writeLittleU16(file, CAPTURE_BITS_PER_SAMPLE);+ fwrite("data", 1, 4, file);+ writeLittleU32(file, dataBytes);+}++class CaptureTap : public IXAPO+{+public:+ CaptureTap(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);+ }++ STDMETHOD(QueryInterface)(REFIID riid, void **object)+ {+ if (object == NULL) {+ return E_POINTER;+ }+ if (riid == __uuidof(IXAPO) || riid == __uuidof(IUnknown)) {+ *object = static_cast<IXAPO *>(this);+ AddRef();+ return S_OK;+ }+ *object = NULL;+ return E_NOINTERFACE;+ }++ STDMETHOD_(ULONG, AddRef)()+ {+ return (ULONG)InterlockedIncrement(&m_references);+ }++ STDMETHOD_(ULONG, Release)()+ {+ const LONG left = InterlockedDecrement(&m_references);+ if (left == 0) {+ delete this;+ }+ return (ULONG)left;+ }++ STDMETHOD(GetRegistrationProperties)(XAPO_REGISTRATION_PROPERTIES **properties)+ {+ XAPO_REGISTRATION_PROPERTIES *copy = (XAPO_REGISTRATION_PROPERTIES *)+ CoTaskMemAlloc(sizeof(XAPO_REGISTRATION_PROPERTIES));+ if (copy == NULL) {+ return E_OUTOFMEMORY;+ }+ memset(copy, 0, sizeof(*copy));+ wcscpy_s(copy->FriendlyName, L"capture");+ wcscpy_s(copy->CopyrightInfo, L"");+ copy->MajorVersion = 1;+ copy->Flags = XAPO_FLAG_CHANNELS_MUST_MATCH | XAPO_FLAG_FRAMERATE_MUST_MATCH+ | XAPO_FLAG_BITSPERSAMPLE_MUST_MATCH | XAPO_FLAG_BUFFERCOUNT_MUST_MATCH+ | XAPO_FLAG_INPLACE_SUPPORTED | XAPO_FLAG_INPLACE_REQUIRED;+ copy->MinInputBufferCount = 1;+ copy->MaxInputBufferCount = 1;+ copy->MinOutputBufferCount = 1;+ copy->MaxOutputBufferCount = 1;+ *properties = copy;+ return S_OK;+ }++ STDMETHOD(IsInputFormatSupported)(const WAVEFORMATEX *, const WAVEFORMATEX *requested,+ WAVEFORMATEX **supported)+ {+ if (supported != NULL) {+ *supported = const_cast<WAVEFORMATEX *>(requested);+ }+ return S_OK;+ }++ STDMETHOD(IsOutputFormatSupported)(const WAVEFORMATEX *, const WAVEFORMATEX *requested,+ WAVEFORMATEX **supported)+ {+ if (supported != NULL) {+ *supported = const_cast<WAVEFORMATEX *>(requested);+ }+ return S_OK;+ }++ STDMETHOD(Initialize)(const void *, UINT32)+ {+ return S_OK;+ }++ STDMETHOD_(void, Reset)()+ {+ }++ STDMETHOD(LockForProcess)(UINT32, const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS *, UINT32,+ const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS *)+ {+ return S_OK;+ }++ STDMETHOD_(void, UnlockForProcess)()+ {+ }++ 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];++ if (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;+ }+ return;+ }++ const float *mix = (const float *)input[0].pBuffer;+ for (UINT32 read = 0; read < samples; ) {+ const UINT32 batch = min(samples - read, (UINT32)CAPTURE_CONVERSION_SAMPLES);+ for (UINT32 index = 0; index < batch; ++index) {+ const float value = mix[read + index];+ const float clamped = value > 1.0f ? 1.0f : (value < -1.0f ? -1.0f : value);+ converted[index] = (short)(clamped * CAPTURE_SAMPLE_SCALE);+ }+ writeSamples(converted, batch);+ read += batch;+ }+ }++ STDMETHOD_(UINT32, CalcInputFrames)(UINT32 outputFrameCount)+ {+ return outputFrameCount;+ }++ STDMETHOD_(UINT32, CalcOutputFrames)(UINT32 inputFrameCount)+ {+ return inputFrameCount;+ }++private:+ ~CaptureTap()+ {+ writeSizes();+ fclose(m_file);+ }++ void writeSamples(const short *samples, UINT32 count)+ {+ m_dataBytes += (unsigned int)fwrite(samples, sizeof(short), count, m_file) * sizeof(short);++ // A recording run is usually killed from the script that started it rather than left to shut+ // down, and a file whose header still says nothing was written is one no editor will open.+ // Writing the two sizes back once a second costs two seeks and makes a killed run usable.+ const unsigned int refreshEvery = m_samplesPerSecond * m_channels * sizeof(short);+ if (m_dataBytes - m_sizesWrittenAt < refreshEvery) {+ return;+ }+ m_sizesWrittenAt = m_dataBytes;+ writeSizes();+ fseek(m_file, 0, SEEK_END);+ }++ void writeSizes()+ {+ fseek(m_file, WAVE_RIFF_SIZE_OFFSET, SEEK_SET);+ writeLittleU32(m_file, WAVE_HEADER_BYTES - 8 + m_dataBytes);+ fseek(m_file, WAVE_DATA_SIZE_OFFSET, SEEK_SET);+ writeLittleU32(m_file, m_dataBytes);+ }++ volatile LONG m_references;+ FILE *m_file;+ unsigned int m_channels;+ unsigned int m_samplesPerSecond;+ unsigned int m_dataBytes;+ unsigned int m_sizesWrittenAt;+};+} // namespace// =================================================================================================@@ -790,8 +1021,48 @@ void AILCALL AIL_quick_handles(HDIGDRIVER *pdig, HMDIDRIVER *pmdi, HDLSDEVICE *pif (pdls != NULL) *pdls = NULL;}+S32 AILCALL AIL_ex_start_capture(const char *pathname)+{+ if (g_engine.master == NULL || pathname == NULL) {+ 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;+}++void AILCALL AIL_ex_stop_capture(void)+{+ if (g_engine.master != NULL) {+ g_engine.master->SetEffectChain(NULL);+ }+}+void AILCALL AIL_shutdown(void){+ AIL_ex_stop_capture();+if (g_engine.serviceThread != NULL) {InterlockedExchange(&g_engine.serviceRunning, 0);WaitForSingleObject(g_engine.serviceThread, 2000);