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(w3ddevice): pipe -video pictures into ffmpeg, no bitmaps
Olcay Seygandd437f82dfa6
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex c2783e6b5..393980312 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -41,6 +41,8 @@ static void drawFramerateBar(void);#include "Lib/Clock.h"#if defined(_WIN32)#include <windows.h>+#include <condition_variable>+#include <mutex>#endif#if defined(_WIN32)#include <io.h>@@ -4082,8 +4084,8 @@ static void saveScreenShot(void)}//=============================================================================-// -video <from> <to> [name]: one picture per logic frame across the range, written as numbered-// .bmp files under Videos\<name>\ and then handed to ffmpeg for Videos\<name>.mp4. GameEngine runs+// -video <from> <to> [name]: one picture per logic frame across the range, piped raw into ffmpeg for+// Videos\<name>.mp4 (numbered .bmp files under Videos\<name>\ where there is no ffmpeg). GameEngine runs// one logic frame a pass over the range, so a picture is a logic frame and a second of video is// LOGICFRAMES_PER_SECOND of them. -recordfps 60 draws each frame twice before the next one runs, and// a second is twice as many pictures; a picture is numbered by its logic frame times the pictures a@@ -4142,14 +4144,26 @@ static VideoPaneShape s_videoPaneRunsShape;static std::vector<ObserverPaneRun> s_videoPaneRuns;static std::vector<IRegion2D> s_videoRowKept;#if defined(_WIN32)-/* -directorrecord writes no frames to disk: they go down a pipe into ffmpeg as they are drawn, which a- whole match of 1080p bitmaps would need tens of gigabytes for. With no ffmpeg it records nothing- and quits. */+/* A recording writes no frames to disk: they go down a pipe into ffmpeg as they are drawn. A whole+ match of 1080p bitmaps needs tens of gigabytes, and -video writing a 1440p bitmap a picture to the+ disk and reading them all back at the end cost 0.85 s a picture against a 26 ms draw. A thread of+ its own writes the pipe, so the draw waits on the encoder only once VIDEO_QUEUED_FRAMES pictures are+ waiting for it. With no ffmpeg -directorrecord records nothing and quits, and -video falls back to+ numbered bitmaps it leaves where they are. */static Bool s_videoPipeTried = FALSE;static HANDLE s_videoPipe = NULL;static HANDLE s_videoEncoder = NULL;static Int s_videoPipeWidth = 0;static Int s_videoPipeHeight = 0;+enum { VIDEO_QUEUED_FRAMES = 8 };+static std::vector<UnsignedByte> s_videoQueue[VIDEO_QUEUED_FRAMES];+static Int s_videoQueueHead = 0; ///< the oldest picture still to go down the pipe+static Int s_videoQueueCount = 0;+static Bool s_videoQueueClosed = FALSE; ///< the recording is over: the writer empties the queue and stops+static Bool s_videoPipeBroken = FALSE; ///< ffmpeg stopped taking pictures+static std::mutex s_videoQueueLock;+static std::condition_variable s_videoQueueChanged;+static HANDLE s_videoWriter = NULL;// the directory with its trailing backslash taken off is the movie's own namestatic void buildVideoMoviePath(char *moviePath, size_t size)@@ -4235,6 +4249,16 @@ static void finishVideo(void)// the end of the pipe is the end of the stream: ffmpeg finishes the movie and exitsif (s_videoEncoder != NULL){+ {+ std::lock_guard<std::mutex> lock(s_videoQueueLock);+ s_videoQueueClosed = TRUE;+ }+ s_videoQueueChanged.notify_all();+ WaitForSingleObject(s_videoWriter, INFINITE);+ CloseHandle(s_videoWriter);+ s_videoWriter = NULL;+ for (Int index = 0; index < VIDEO_QUEUED_FRAMES; ++index)+ std::vector<UnsignedByte>().swap(s_videoQueue[index]);CloseHandle(s_videoPipe);s_videoPipe = NULL;WaitForSingleObject(s_videoEncoder, INFINITE);@@ -4258,72 +4282,85 @@ static void finishVideo(void)if (s_videoFramesWritten == 0)return;-#if !defined(_WIN32)- // Off Windows the encoder is not started for you: the frames stay, and this is how to make the movie.+ // No ffmpeg was there to pipe into, so the frames stay, and this is how to make the movie.DEBUG_LOG(("VIDEO: encode with: ffmpeg -framerate %d -i \"%s%s\" -c:v libx264 -pix_fmt yuv420p out.mp4\n",videoFramesPerSecond(), s_videoDirectory, VIDEO_FRAME_PATTERN));-#else- char encoderPath[_MAX_PATH];- if (!findVideoEncoder(encoderPath, ARRAY_SIZE(encoderPath)))- {- DEBUG_LOG(("VIDEO: no %s beside the game or on the PATH, so the frames stay where they are\n", VIDEO_ENCODER));- return;- }+}- char moviePath[_MAX_PATH];- buildVideoMoviePath(moviePath, ARRAY_SIZE(moviePath));+/** A -video range is being recorded and this logic frame is inside it. */+static Bool videoRecordingFrame(void)+{+ if (TheGlobalData->m_videoEndFrame <= 0 || s_videoFinished || TheGameLogic == NULL+ || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())+ return FALSE;+ const UnsignedInt frame = TheGameLogic->getFrame();+ return frame >= (UnsignedInt)TheGlobalData->m_videoStartFrame && frame <= (UnsignedInt)TheGlobalData->m_videoEndFrame;+}- // yuv420p is what every player opens and it wants even dimensions, which a window need not have- char commandLine[4 * _MAX_PATH];- snprintf(commandLine, ARRAY_SIZE(commandLine),- "\"%s\" -y -loglevel error -framerate %d -i \"%s%s\" -vf pad=ceil(iw/2)*2:ceil(ih/2)*2 "- "-c:v libx264 -pix_fmt yuv420p -crf 18 \"%s\"",- encoderPath, videoFramesPerSecond(), s_videoDirectory, VIDEO_FRAME_PATTERN, moviePath);+#if defined(_WIN32)+/** -video is footage for an edit, so it is encoded close to lossless: on NVIDIA's encoder where the card+ * has one, which costs the machine next to nothing, and on x264 everywhere else. -directorrecord's+ * whole match keeps x264 at a size a match can be kept at. The probe opens the encoder with these+ * very arguments, so a card or an ffmpeg that refuses one of them falls back here and not after the+ * first picture has gone down the pipe. */+static const char *videoCodecArguments(const char *encoderPath)+{+ static const char NVENC[] = "-c:v h264_nvenc -preset p5 -tune hq -profile:v high -rc vbr -cq 17 -b:v 0";+ static const char X264[] = "-c:v libx264 -preset fast -crf 16";+ if (TheGlobalData->m_directorRecord)+ return "-c:v libx264 -crf 18";+ char commandLine[2 * _MAX_PATH];+ snprintf(commandLine, ARRAY_SIZE(commandLine),+ "\"%s\" -hide_banner -loglevel quiet -nostdin -f lavfi -i nullsrc=s=256x256 -frames:v 1 %s "+ "-pix_fmt yuv420p -f null -", encoderPath, NVENC);STARTUPINFOA startup;memset(&startup, 0, sizeof(startup));startup.cb = sizeof(startup);PROCESS_INFORMATION process;if (!CreateProcessA(encoderPath, commandLine, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL,&startup, &process))- {- DEBUG_LOG(("VIDEO: %s would not start (error %u), so the frames stay where they are\n",- encoderPath, (unsigned)GetLastError()));- return;- }-+ return X264;WaitForSingleObject(process.hProcess, INFINITE);- DWORD exitCode = 0;+ DWORD exitCode = 1;GetExitCodeProcess(process.hProcess, &exitCode);CloseHandle(process.hThread);CloseHandle(process.hProcess);-- if (exitCode != 0)- {- DEBUG_LOG(("VIDEO: %s exited with %u, so the frames stay where they are\n",- encoderPath, (unsigned)exitCode));- return;- }-- deleteVideoFrames();- RemoveDirectoryA(s_videoDirectory);- DEBUG_LOG(("VIDEO: wrote %s\n", moviePath));-#endif+ return exitCode == 0 ? NVENC : X264;}-/** A -video range is being recorded and this logic frame is inside it. */-static Bool videoRecordingFrame(void)+/** The pipe's writer: every queued picture down to ffmpeg in turn, until the queue is closed and empty+ * or ffmpeg stops taking them. */+static DWORD WINAPI writeVideoQueue(LPVOID){- if (TheGlobalData->m_videoEndFrame <= 0 || s_videoFinished || TheGameLogic == NULL- || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())- return FALSE;- const UnsignedInt frame = TheGameLogic->getFrame();- return frame >= (UnsignedInt)TheGlobalData->m_videoStartFrame && frame <= (UnsignedInt)TheGlobalData->m_videoEndFrame;+ std::unique_lock<std::mutex> lock(s_videoQueueLock);+ for (;;)+ {+ s_videoQueueChanged.wait(lock, [] { return s_videoQueueCount > 0 || s_videoQueueClosed; });+ if (s_videoQueueCount == 0)+ return 0;+ const std::vector<UnsignedByte> &frame = s_videoQueue[s_videoQueueHead];+ lock.unlock();+ DWORD written = 0;+ const Bool wrote = WriteFile(s_videoPipe, &frame[0], (DWORD)frame.size(), &written, NULL)+ && written == frame.size();+ const DWORD error = GetLastError();+ lock.lock();+ if (!wrote)+ {+ DEBUG_LOG(("VIDEO: %s stopped taking frames (error %u)\n", VIDEO_ENCODER, (unsigned)error));+ s_videoPipeBroken = TRUE;+ s_videoQueueChanged.notify_all();+ return 0;+ }+ s_videoQueueHead = (s_videoQueueHead + 1) % VIDEO_QUEUED_FRAMES;+ --s_videoQueueCount;+ s_videoQueueChanged.notify_all();+ }}-#if defined(_WIN32)-/** ffmpeg started with its stdin a pipe this end writes raw frames of this size into. FALSE when- * there is no ffmpeg or it would not start. */+/** ffmpeg started with its stdin a pipe this end writes raw frames of this size into, and the thread+ * that writes them. FALSE when there is no ffmpeg or it would not start. */static Bool openVideoPipe(Int width, Int height){char encoderPath[_MAX_PATH];@@ -4332,6 +4369,7 @@ static Bool openVideoPipe(Int width, Int height)DEBUG_LOG(("VIDEO: no %s beside the game or on the PATH\n", VIDEO_ENCODER));return FALSE;}+ const char *codec = videoCodecArguments(encoderPath);SECURITY_ATTRIBUTES inherited;memset(&inherited, 0, sizeof(inherited));@@ -4352,8 +4390,8 @@ static Bool openVideoPipe(Int width, Int height)char commandLine[4 * _MAX_PATH];snprintf(commandLine, ARRAY_SIZE(commandLine),"\"%s\" -y -loglevel error -f rawvideo -pix_fmt bgr0 -s %dx%d -framerate %d -i - "- "-vf pad=ceil(iw/2)*2:ceil(ih/2)*2 -c:v libx264 -pix_fmt yuv420p -crf 18 \"%s\"",- encoderPath, width, height, videoFramesPerSecond(), moviePath);+ "-vf pad=ceil(iw/2)*2:ceil(ih/2)*2 %s -pix_fmt yuv420p \"%s\"",+ encoderPath, width, height, videoFramesPerSecond(), codec, moviePath);STARTUPINFOA startup;memset(&startup, 0, sizeof(startup));@@ -4377,7 +4415,8 @@ static Bool openVideoPipe(Int width, Int height)s_videoEncoder = process.hProcess;s_videoPipeWidth = width;s_videoPipeHeight = height;- DEBUG_LOG(("VIDEO: %dx%d frames go straight into %s for %s\n", width, height, encoderPath, moviePath));+ s_videoWriter = CreateThread(NULL, 0, writeVideoQueue, NULL, 0, NULL);+ DEBUG_LOG(("VIDEO: %dx%d frames go straight into %s (%s) for %s\n", width, height, encoderPath, codec, moviePath));return TRUE;}#endif@@ -4524,12 +4563,13 @@ static void joinVideoPanes(const VideoRecord &record, Int recordIndex, UnsignedB}}-/** One picture of the recording, VIDEO_PIXEL_BYTES a pixel with no gap between rows, into ffmpeg's pipe- * under -directorrecord, as the next numbered .bmp otherwise. */-static Bool writeVideoFrame(const UnsignedByte *pixels, Int width, Int height, UnsignedInt picture)+/** One picture of the recording, VIDEO_PIXEL_BYTES a pixel with no gap between rows, queued for ffmpeg's+ * pipe, or as the next numbered .bmp where there is no ffmpeg. The picture is copied, so pixels may go+ * as soon as this returns. */+static Bool writeVideoFrame(const UnsignedByte *pixels, Int width, Int height){#if defined(_WIN32)- if (TheGlobalData->m_directorRecord && !s_videoPipeTried)+ if (!s_videoPipeTried){s_videoPipeTried = TRUE;openVideoPipe(width, height);@@ -4539,13 +4579,18 @@ static Bool writeVideoFrame(const UnsignedByte *pixels, Int width, Int height, U// ffmpeg was told one size; a picture of another would shear every frame after itif (width != s_videoPipeWidth || height != s_videoPipeHeight)return FALSE;- const DWORD bytes = (DWORD)(VIDEO_PIXEL_BYTES * width * height);- DWORD written = 0;- if (WriteFile(s_videoPipe, pixels, bytes, &written, NULL) && written == bytes)- return TRUE;- DEBUG_LOG(("VIDEO: %s stopped taking frames (error %u) at logic frame %u\n", VIDEO_ENCODER,- (unsigned)GetLastError(), picture * LOGICFRAMES_PER_SECOND / videoFramesPerSecond()));- return FALSE;+ std::unique_lock<std::mutex> lock(s_videoQueueLock);+ s_videoQueueChanged.wait(lock, [] { return s_videoQueueCount < VIDEO_QUEUED_FRAMES || s_videoPipeBroken; });+ if (s_videoPipeBroken)+ return FALSE;+ // the writer reads only the pictures already counted, so the free one is filled without the lock+ std::vector<UnsignedByte> &frame = s_videoQueue[(s_videoQueueHead + s_videoQueueCount) % VIDEO_QUEUED_FRAMES];+ lock.unlock();+ frame.assign(pixels, pixels + (size_t)VIDEO_PIXEL_BYTES * width * height);+ lock.lock();+ ++s_videoQueueCount;+ s_videoQueueChanged.notify_all();+ return TRUE;}#endif// a whole match as bitmaps is tens of gigabytes, and one run filled a disk with 13 GB before it@@ -4603,7 +4648,7 @@ static void writeVideoRecord(Int recordIndex)pixels = &s_videoJoined[0];}- if (writeVideoFrame(pixels, width, height, record.picture))+ if (writeVideoFrame(pixels, width, height))++s_videoFramesWritten;else++s_videoFramesMissed;