Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Start frozen launcher workers suspended instead of through PowerShell (#20)
Bowen Xue4f9acd306d37
diff --git a/freevideo_engine/processes.py b/freevideo_engine/processes.pyindex e638c85..934bf1e 100644--- a/freevideo_engine/processes.py+++ b/freevideo_engine/processes.py@@ -1,5 +1,4 @@"""Worker creation, inherited leases and bounded cleanup on Linux and Windows."""-import jsonimport osfrom pathlib import Pathimport signal@@ -11,20 +10,10 @@ from contextlib import contextmanagerfrom .system import windowsHANDLE_ENV = 'FREEVIDEO_RUNTIME_LOCK_HANDLE'-COMMAND_ENV = 'FREEVIDEO_WINDOWS_CHILD_COMMAND'+CREATE_SUSPENDED = 0x4_spawn_lock = threading.Lock()-def windows_child_command(command):- """Data for the frozen Job gate; never ask PowerShell to reparse argv."""- if isinstance(command, (str, bytes)) or not command:- raise ValueError('Windows workers require a nonempty argument list')- values = list(map(str, command))- if not values[0] or any('\0' in value for value in values):- raise ValueError('Windows worker arguments cannot contain NUL or an empty executable')- return json.dumps(dict(executable=values[0], arguments=subprocess.list2cmdline(values[1:])), ensure_ascii=True)--def inherited_fd():"""Adopt a Windows handle once; CRT descriptor numbers are process-local."""value = os.environ.get(HANDLE_ENV)@@ -56,28 +45,30 @@ class WindowsPopen(subprocess.Popen):def __init__(self, command, *, pass_fds=(), env=None, **kwargs):import ctypesimport msvcrt- from .win32 import Job, HANDLE, checked, kernel32+ from .win32 import Job, HANDLE, checked, kernel32, resume_suspendedlib = kernel32()self.job = Job()handles = []environment = dict(os.environ if env is None else env)- # A worker waits for assignment before it is allowed to spawn anything.- # This closes the launch/kill race without suspended-thread internals.+ # A worker must belong to the Job before it can spawn anything; this+ # closes the launch/kill race. The frozen GUI starts the worker itself+ # suspended, assigns it and resumes it. It used to start a hidden+ # PowerShell gate with -ExecutionPolicy Bypass, the pattern behind a+ # Defender Trojan:Script/Wacatac.B!ml verdict on the unsigned EXE.+ # Managed Python keeps its Python gate, which waits for assignment.+ frozen = getattr(sys, 'frozen', False)try:- gate = checked(lib.CreateEventW(None, True, False, None))- handles.append(gate)- if getattr(sys, 'frozen', False):+ if frozen:if pass_fds:raise ValueError('The desktop launcher delegates runtime leases to managed Python')- environment[COMMAND_ENV] = windows_child_command(command)- host = [str(Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'),- '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',- str(Path(__file__).with_name('windows_process_host.ps1')), str(gate)]+ host, flags = list(command), subprocess.CREATE_NEW_PROCESS_GROUP | CREATE_SUSPENDEDelse:- environment.pop(COMMAND_ENV, None)- host = module_command('freevideo_engine.process_host', gate, *command)+ gate = checked(lib.CreateEventW(None, True, False, None))+ handles.append(gate)+ host, flags = module_command('freevideo_engine.process_host', gate, *command), subprocess.CREATE_NEW_PROCESS_GROUPwith _spawn_lock:- checked(lib.SetHandleInformation(gate, 1, 1))+ if not frozen:+ checked(lib.SetHandleInformation(gate, 1, 1))if len(pass_fds) > 1:raise ValueError('Only the runtime lease may be inherited by a Windows worker')for fd in pass_fds:@@ -99,9 +90,12 @@ class WindowsPopen(subprocess.Popen):kwargs.pop('start_new_session', None)kwargs.pop('close_fds', None)super().__init__(host, env=environment, startupinfo=info, close_fds=True,- creationflags=subprocess.CREATE_NEW_PROCESS_GROUP, **kwargs)+ creationflags=flags, **kwargs)self.job.assign(self._handle)- checked(lib.SetEvent(gate))+ if frozen:+ resume_suspended(self.pid)+ else:+ checked(lib.SetEvent(gate))except BaseException:if getattr(self, '_child_created', False):super().kill()diff --git a/freevideo_engine/win32.py b/freevideo_engine/win32.pyindex fd3ffc7..3781ab5 100644--- a/freevideo_engine/win32.py+++ b/freevideo_engine/win32.py@@ -18,6 +18,10 @@ def kernel32():'CreateToolhelp32Snapshot': (HANDLE, [DWORD, DWORD]),'Process32FirstW': (BOOL, [HANDLE, C.c_void_p]),'Process32NextW': (BOOL, [HANDLE, C.c_void_p]),+ 'Thread32First': (BOOL, [HANDLE, C.c_void_p]),+ 'Thread32Next': (BOOL, [HANDLE, C.c_void_p]),+ 'OpenThread': (HANDLE, [DWORD, BOOL, DWORD]),+ 'ResumeThread': (DWORD, [HANDLE]),'GetProcessIoCounters': (BOOL, [HANDLE, C.c_void_p]),'GetProcessTimes': (BOOL, [HANDLE, C.c_void_p, C.c_void_p, C.c_void_p, C.c_void_p]),'GlobalMemoryStatusEx': (BOOL, [C.c_void_p]),@@ -144,6 +148,39 @@ class ProcessEntry(C.Structure):('priority', C.c_int32), ('flags', DWORD), ('exe', C.c_wchar * 260)]+class ThreadEntry(C.Structure):+ _fields_ = [('dwSize', DWORD), ('cntUsage', DWORD), ('tid', DWORD), ('pid', DWORD),+ ('base_priority', C.c_long), ('delta_priority', C.c_long), ('flags', DWORD)]+++def resume_suspended(pid):+ """Resume the one initial thread of a process created with CREATE_SUSPENDED."""+ lib = kernel32()+ snapshot = lib.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD+ if snapshot == C.c_void_p(-1).value:+ raise C.WinError(C.get_last_error())+ threads = []+ try:+ entry = ThreadEntry()+ entry.dwSize = C.sizeof(entry)+ more = lib.Thread32First(snapshot, C.byref(entry))+ while more:+ if entry.pid == pid:+ threads.append(entry.tid)+ more = lib.Thread32Next(snapshot, C.byref(entry))+ finally:+ lib.CloseHandle(snapshot)+ # A process that has not run yet has exactly its initial thread.+ if len(threads) != 1:+ raise OSError('Expected one suspended thread in process %d, found %d' % (pid, len(threads)))+ thread = checked(lib.OpenThread(0x0002, False, threads[0])) # THREAD_SUSPEND_RESUME+ try:+ if lib.ResumeThread(thread) == 0xFFFFFFFF:+ raise C.WinError(C.get_last_error())+ finally:+ lib.CloseHandle(thread)++class ProcessCounters(C.Structure):_fields_ = [('cb', DWORD), ('faults', DWORD)] + [(n, SIZE_T) for n in('peak_working_set', 'working_set', 'peak_paged_pool', 'paged_pool',diff --git a/freevideo_engine/windows_process_host.ps1 b/freevideo_engine/windows_process_host.ps1deleted file mode 100644index 8b270dc..0000000--- a/freevideo_engine/windows_process_host.ps1+++ /dev/null@@ -1,48 +0,0 @@-# The one-file GUI must not relaunch its unpacking bootloader as a job gate.-# PowerShell waits before spawning any child; all descendants then inherit the Job.-$ErrorActionPreference = 'Stop'-$event = [Threading.EventWaitHandle]::new($false, [Threading.EventResetMode]::ManualReset)-try {- $event.SafeWaitHandle = [Microsoft.Win32.SafeHandles.SafeWaitHandle]::new([IntPtr]([long]$args[0]), $true)- if (-not $event.WaitOne(30000)) { throw 'Worker was not assigned to its Windows Job Object in time.' }-} finally {- $event.Dispose()-}-# Windows PowerShell 5.1's native argument binder removes embedded quotes and-# empty arguments. The Python controller already produced a Win32 command line;-# hand it directly to ProcessStartInfo, without shell invocation or evaluation.-$command = $env:FREEVIDEO_WINDOWS_CHILD_COMMAND | ConvertFrom-Json-Remove-Item Env:FREEVIDEO_WINDOWS_CHILD_COMMAND-if (-not $command.executable) { throw 'Missing worker executable.' }-$info = [Diagnostics.ProcessStartInfo]::new()-$info.FileName = $command.executable-$info.Arguments = $command.arguments-$info.UseShellExecute = $false-# Inherit the gate's hidden console so native helpers cannot create a new one.-$info.CreateNoWindow = $false-$info.WindowStyle = [Diagnostics.ProcessWindowStyle]::Hidden-# stdout/stderr redirection makes .NET set STARTF_USESTDHANDLES. With stdin-# redirection disabled it passes GetStdHandle(STD_INPUT_HANDLE) to the child:-# the controller's pipe (or NUL) itself, without another buffered pipe/pump.-# This delivers short writes and EOF directly and creates no StreamWriter/BOM.-$info.RedirectStandardInput = $false-$info.RedirectStandardOutput = $true-$info.RedirectStandardError = $true-$process = [Diagnostics.Process]::new()-$process.StartInfo = $info-try {- if (-not $process.Start()) { throw 'Worker did not start.' }- # Copy raw bytes continuously; do not buffer the whole log, translate its- # encoding, or wait for a full line before forwarding progress to the GUI.- $output = $process.StandardOutput.BaseStream.CopyToAsync([Console]::OpenStandardOutput())- $errorOutput = $process.StandardError.BaseStream.CopyToAsync([Console]::OpenStandardError())- $process.WaitForExit()- # Windows PowerShell exposes the internal VoidTaskResult of CopyToAsync.- # Consume completion without printing that value into the worker's stdout.- [void]$output.GetAwaiter().GetResult()- [void]$errorOutput.GetAwaiter().GetResult()- $code = $process.ExitCode-} finally {- $process.Dispose()-}-exit $codediff --git a/pyproject.toml b/pyproject.tomlindex 5efe342..4dc39f5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -31,4 +31,4 @@ freevideo = "freevideo_engine.cli:main"include = ["freevideo_engine*"][tool.setuptools.package-data]-freevideo_engine = ["build-version.txt", "build-identity.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "bootstrap_versions.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_process_host.ps1", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt"]+freevideo_engine = ["build-version.txt", "build-identity.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "bootstrap_versions.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt"]