Skip to content

Latest commit

 

History

History
628 lines (525 loc) · 34.4 KB

core.md

File metadata and controls

628 lines (525 loc) · 34.4 KB

The native core

The XGrid core began from xemu 0.8.139 and is now maintained directly in xemu/. It is a custom enhanced and patched core that evolves separately from the original xemu codebase. For the historical comparison with pristine xemu, see xemu baseline differences.

Tree structure

xemu/
  <xemu 0.8.139 lineage and its QEMU base, maintained as XGrid's core>
  xgrid-core/          XGrid-owned native code
  hw/xbox/chihiro/     ported Sega Chihiro machine and cabinet devices
  block/blkmemory.c    memory-backed block driver for the Chihiro DIMM
  xemu-patches/        patch record for upstream edits
  XGrid.Xemu.Tree.csproj
  dist/                build output (git-ignored)

xgrid-core/

File Role
block/xgrid-iso.c Shared XDVDFS game-partition detection for the XISO, CHD and ZArchive drivers.
block/xgridiso.c ISO/XISO block driver; maps the detected game partition (optimized XISO or full Redump) to LBA 0.
block/xgridcci.c CCI block driver; LZ4 sectors through vendored libCCI, with split-part discovery and game-partition mapping.
block/xgridchd.c CHD block driver; decodes hunks on demand through libchdr and maps the detected game partition.
block/xgridzar.c ZArchive block driver; decodes zstd blocks, exposes an entry-form .iso, and synthesizes XDVDFS for file-tree archives.
media/xgrid-media.c, media/xgrid-media-block.c, media/xgrid-media-cache.c, media/xgrid-media-fatx.c Media probe and browser: XDVDFS root/XBE certificate identity over any disc driver plus FATX directory listings, returned as JSON. Successful probes are cached by size, timestamp and a 64 KiB header hash.
display/xgrid-display.c Presentation filter/overlay selection plus the headless frame sink (Windows named section or POSIX shared memory).
ui/xemu-overlay.cc Core-side frame-rate and diagnostics overlay: present counters, the text and the rasterised RGBA panel both presenters composite. Not part of the emulated picture.
audio/xgrid-host-audio.c Host audio stream interface for the APU monitor pacing clock and the Xbox Live Communicator headset; SDL stays out of hw/.
audio/xgrid-host-audio-device.c Host output-device interface over the selected QEMU audio backend; the APU monitor uses it instead of QEMU audio types.
window/xgrid-host-window.h Host window contract: native handles, size, visibility, fullscreen and focus; ui/xemu.c implements it for SDL, the presenters consume it, and the shell only locates/focuses the separate game window.
gl/xgrid-host-gl.h Host GL entry-point contract used by the macOS debug loader; ui/xemu-gl-context.c implements it and owns the SDL offscreen context behind gloffscreen.h.
input/xgrid-host-input.c One pad record and source interface: the XGD shared sink is built in, SDL registers as a fallback, and controller/rumble dispatch no longer branches in the sink.
input/xgrid-input.c Input sink; reads one 48-byte pad record per Xbox port, writes the rumble tail for the shell, and feeds the input recorder/replayer.
input/xgrid-input-record.c, .h Core-side .xgin input recorder and virtual-time replayer.
control/xgrid-control.c, .h Token-authenticated loopback control channel for the separate-process host.
control/xgrid-http.c, .h Optional HTTP listener beside the line channel: POST /command, GET /events and GET /health, sharing the same token and command decoder.
record/xgrid-record-mp4.c, record/xgrid-mp4.c, .h Core-side H.264 MP4 writer with x264, PCM audio and the in-memory instant-replay ring.
record/xgrid-record-avi.c MJPEG AVI 1.0 fallback writer with PCM audio and the replay ring used when x264 is not available.
record/xgrid-record-queue.c, .h Bounded encode queue and one worker; the render thread only copies the frame.
abi/xgrid-core.c Core operations behind the command handlers: playback, save states, disc changes, memory units, host audio, guest-memory access and statistics. The loopback and HTTP transports share the command dispatcher.
thirdparty/libchdr/ Vendored libchdr 0.3.0 (BSD-3-Clause).
thirdparty/libcci/ Vendored libCCI (GPL-2.0-or-later), built against the host LZ4.
thirdparty/stb_image_write/ Vendored stb_image_write 1.16 (public domain or MIT) for the AVI fallback encoder.
host x264 Optional H.264 encoder detected by pkg-config; the MP4 recorder is built when it is available.
meson.build Wires the additions into the xemu build.

xemu-patches/

xemu/xemu-patches/ is the provenance record for upstream edits. It includes the shell-pad binding in ui/xemu-input.c that gives players 1–4 a controller to feed, the core-side presentation filter/overlay, the exit-time GL guard in the Windows DXGI presenter, the WGL interop attachment fix, the guest-clock part of fast-forward, the disc-driver selection in system/vl.c, the DirectSound device option plus the -audio-drivers probe, and the Sega Chihiro machine and its Xbox integration. The historical in-process DLL record is retained, but the tree it described has been reverted: the Windows sigsetjmp shim, the configurable QEMU thread stack and the library-mode run entry point are gone.

XGrid-native additions live in xemu/xgrid-core/; new changes are ordinary commits in this repository. Upstream xemu is a reference and a source of selective fixes, not a release-for-release merge obligation. See Core lineage and upstream for the upstream revision markers and the weekly report, and Native dependencies for the dependency manifest, the Windows host lock and the update policy.

Host boundary

hw/ and system/ are compiled on Windows, Linux and macOS. Their code must not include <windows.h>, <X11/...>, <Cocoa/...> or SDL directly; platform calls belong behind a host interface. The gate scans both trees:

python .github/scripts/host_include_check.py

It fails on a new include and on a baseline entry that no longer exists; its unit test is .github/scripts/test_host_include_check.py. The recorded exception list is empty: the SDL GL context lives in ui/xemu-gl-context.c behind gloffscreen.h, the macOS GL entry-point lookup goes through xgrid-core/gl/xgrid-host-gl.h, and the APU monitor, USB headset and process entry point no longer include SDL. The native-core CI job runs the same check.

Renderers

The NV2A has three renderer backends:

Backend Path Host
OpenGL hw/xbox/nv2a/pgraph/gl/, shaders in pgraph/glsl/ All
Vulkan hw/xbox/nv2a/pgraph/vk/, shaders in pgraph/glsl/ Builds with Vulkan
NULL hw/xbox/nv2a/pgraph/null/ All

Each backend is one entry in PGRAPH's static PGRAPHRenderer table; PGRAPH owns state extraction and calls the selected backend's operations. The build runs XGridCore -renderers, which prints the table ids, and writes that list into xgrid-core.json. A build therefore lists exactly the backends it compiled. Direct3D 11 was a Windows-only development backend and has been removed; Vulkan covers Windows on the same source as the other platforms.

Every presented frame is published as an XGridFrameSurface (xgrid-core/display/xgrid-frame.h): a versioned, pointer-free description with a kind (GL texture, Vulkan image or CPU memory), format, size, native handle, memory pointer and a fence slot. nv2a_get_framebuffer_surface() fills it and the display path reads only that contract. OpenGL publishes its display texture; Vulkan publishes the VkImage directly and presents it through the Vulkan sink, so the display path never receives a copied frame.

Vulkan applies the Xbox texture component swizzle with VkImageViewCreateInfo::components where the device supports it. When VK_KHR_portability_subset reports imageViewFormatSwizzle as unavailable (MoltenVK), the image view keeps the identity mapping and the generated pixel shader remaps the fetched texel; the depth-texture format markers are preserved on the same path.

A renderer switch is a four-phase handoff in PGRAPH. The request waits until the display loop has released its framebuffer claim and the frame mailbox is clear, then parks the guest CPU, finalizes the old backend, discards any frame that backend published, and initializes the new one. The display loop claims the framebuffer before checking the phase, so it either gets a live surface or waits for renderer_switch_complete; the switch never finalizes a backend under a surface the display loop is still using.

Shell cover art

The shell resolves cover art without touching the emulated picture:

File Role
Services/Covers/CoverMatcher.cs Annotation stripping, normalization, Jaro-Winkler scoring, alias and sequel-number rules.
Services/Covers/LocalCoverIndex.cs Read-only index of a local cover folder; exact, token, no-space and fuzzy lookups.
Services/Covers/CoverCatalog.cs catalog.json validation, title/game-id indexes and image URI resolution.
Services/Covers/CoverStore.cs Content-addressed image cache and catalog sidecar.
Services/Covers/CoverDownloader.cs Conditional catalog GETs, retries and image downloads.
Services/Covers/CoverService.cs Local/catalog resolution order, metadata and automatic downloads.

The matching behavior follows Simple Launcher and 5DO (annotation groups, token/no-space forms, subtitle aliases, Jaro-Winkler and sequel-number protection) but is a separate XGrid implementation, not a copy of those projects. The catalog uses SHA-256-named WebP images and a sidecar ETag, and every downloaded image is verified before it enters the cache. The default catalog is https://assets.purelogiccode.com/xgrid/v1/catalog.json; it is configurable and may be a file:// catalog for offline use.

scripts/package-covers.ps1 builds the local pack with ffmpeg and scripts/publish-covers.ps1 mirrors it to R2 with rclone. See Cover catalog packaging.

Host command contract

The command dispatcher is the only host contract. The core is a standalone process and exports no C entry points; the loopback channel and the optional HTTP listener decode their own framing and call the same registry. The validation scripts drive the core through that channel.

The dispatcher (xgrid-core/command/xgrid-command.h) validates and runs one request:

int xgrid_command_registry_dispatch(XGridCommandRegistry *registry,
                                    void *opaque,
                                    const XGridCommand *request,
                                    XGridCommandResult *result);

A command carries a protocol version, an id, up to four integer arguments and an optional text argument. The result carries a dispatcher status, an integer value and owned data/text. The handler keeps ownership until the transport calls xgrid_command_result_release(); the loopback transport releases it after writing the line. A command declares CALLER or MAIN; a MAIN command is scheduled on the core main loop when the caller is another thread. A MAIN command called after the machine has stopped returns not running instead of queueing work with no loop to run it. The channel covers playback, snapshot, disc, memory-card, media, statistics, recording, replay, input-recording and presentation operations. Fullscreen is a command-only operation: it sets an atomic request that the window loop applies on the window thread, so SDL is never called off-thread.

The process context (xgrid-core/context/xgrid-context.h) owns the command registry, the event ring, the settings resolver, the display and input sinks, the active machine, the default host audio backend and the one-machine-per-process claim. The loopback channel and the HTTP listener dispatch through the context's registry; event producers and settings use its ring and resolver. The core operations in abi/xgrid-core.c attach their snapshot, disc, XMU, pause, statistics and audio state to the context as private state; the context destructor releases it.

xemu_run() is a thin adapter over xgrid-core/lifecycle/: parse, configure, create, run and stop. The runner enforces the order, emits one state event with code 10 when a phase fails, and still calls stop so a partially created machine is released. The host callbacks stay in ui/xemu.c because they own the SDL window and the display loop.

Runtime settings resolve through five layers, highest first:

  1. launch arguments (-xgrid-config key=value);
  2. the command layer (CONFIG SET or the DISPLAY commands);
  3. the environment (XGRID_PRESENT_FILTER, XGRID_FPS_LIMIT, ...);
  4. the TOML feed from xemu-settings (filtering, colour, geometry);
  5. built-in defaults.

CONFIG returns the effective configuration as JSON with the winning source for every key, and each key emits one config event. The resolver lives in xgrid-core/settings/xgrid-settings.c; display code reads it instead of keeping parallel atomics.

The event ring is the other half of the contract. Producers call xgrid_event_emit() or xgrid_event_log(); xgrid-core/events/xgrid-events.h exposes the sequence, a copy by sequence and an optional in-process callback.

Events are fixed width (XGridEvent) and carry a type, level, stable code, sequence, timestamp, integer value, subsystem and message. The callback runs on the emitting thread; the ring keeps the last 256 events for polling. Start/stop, notification/error and one config event per effective setting emit today. The channel exposes the ring as EVENTS <after-sequence>, which returns a base64 JSON array so a host can poll without a second protocol. The shell polls that command and mirrors events into Serilog and Activity. Warning and error events also become shell toasts; the event level and code decide both. A crash event is written beside the dump because the ring dies with the process.

code is a stable wire value; value carries the code-specific integer:

Code Meaning
0 none
1 renderer device lost
2 renderer fallback
3 firmware missing
4 disc invalid
5 snapshot mismatch
6 control authentication rejected
7 invalid configuration
8 crash
9 machine already claimed in this process
10 lifecycle phase failed

New codes are appended, never renumbered.

xgrid_event_log(level, subsystem, format, ...) is the core's log entry point. It emits a log event with that level and writes the same line to stderr when no in-process subscriber is registered, so the standalone core leaves a log file.

The run entry point is xemu_run(int argc, char **argv) in ui/xemu-run.h. The standalone binary calls it once; there is no exported start, stop, join or version surface. The process exit status is the run status, and QEMU's global state is single-use.

Save states use the SNAPSHOT command family. SNAPSHOT_SAVE, SNAPSHOT_LOAD and SNAPSHOT_DELETE carry the snapshot name in the text argument, SNAPSHOT_REFRESH rescans the list, and SNAPSHOT_STATUS, SNAPSHOT_ERROR, SNAPSHOT_COUNT and SNAPSHOT_NAME return the request state, the last error, the count and one name. Status values are idle (0), pending (1), completed (2) and failed (3). The control channel spells them SNAPSHOT SAVE|LOAD|DELETE|REFRESH|STATUS|ERROR|COUNT|NAME.

Guest memory uses the MEMORY command family: MEMORY_SIZE, MEMORY_READ, MEMORY_WRITE and MEMORY_HASH. The address is a guest physical address below the reported size. Reads and writes are limited to 1 MiB per request and reject any range outside RAM, so MMIO and device windows are never reachable. Requests run on the core's main loop. MEMORY_HASH computes a 32-bit FNV-1a hash; poll it and compare successive values to detect changes. It is a polling watch, not a CPU watchpoint. Status values are 0 success, -1 machine not ready, -2 bad range, -3 bad argument, -4 transaction fault and -5 timeout.

scripts/memory-abi-check.ps1 round-trips a pattern through high RAM over the control channel, verifies the hash changes, restores the original bytes and confirms an out-of-range request fails.

Playback uses PAUSE (one argument, non-zero pauses), STEP, SPEED_GET and SPEED_SET (multiplier 1..8). A request is queued and applied as a bottom half on the core's main loop. A pause stops the machine on the next published frame; a frame step resumes from that frame boundary and stops the same way after the next one. When no frame is published (the display sink is off), a short timer stops the machine instead. The shell keeps the paused state it asked for and reports it in the status bar, the toolbar and a badge over the picture.

Disc change uses DISC_LOAD (path in the text argument), DISC_EJECT, DISC_STATUS and DISC_ERROR. A disc load opens the medium through the block layer with the format the file extension names: .chd uses xgridchd, .cci uses xgridcci, .zar uses xgridzar, and .iso/.xiso use xgridiso. The tray is cycled so Xbox software notices the change; no power cycle is involved.

Media probe

MEDIA PROBE <path> is a MAIN command that reads a disc or a loose executable without starting or changing the machine. It opens ISO/XISO as a raw stream so the parser can report the retail XGD game-partition offset, and CHD/CCI/ZArchive through their drivers, which map the game partition to LBA 0. It then reads the XDVDFS root table, finds the root default.xbe and parses the certificate. A failed probe still returns one JSON object and does not raise an event:

{"version":1,"ok":true,"format":"iso","streamSize":123456789,
 "partitionOffset":0,"leadingPartition":false,"titleId":1263882244,
 "titleName":"Halo","gameRegion":1,"certificateVersion":1,"discNumber":0,
 "multiDisc":false,"allowedMedia":2,"imageTimestamp":287454020,
 "imageSize":65536}

streamSize is the probed stream length. partitionOffset is the byte offset of the game partition in that stream; leadingPartition is true when a retail XGD video/update area precedes it. ISO/XISO report the real offset; CHD/CCI/ZArchive report 0 because their drivers already map the game partition to LBA 0. discNumber and multiDisc are the certificate's multi-disc hint. A loose .xbe reports format xbe, and an unreadable image reports {"version":1,"ok":false,"error":"..."}. The command runs on the core main loop because it opens a block backend; the main loop and block layer must already exist. The control channel spells it MEDIA PROBE <base64 path>.

A successful result is cached in the per-user cache directory under xgrid/media, keyed by the file size, modification time and a SHA-256 of the first 64 KiB. A repeated probe returns the stored JSON without reopening the block backend; a size, timestamp or header change invalidates the entry. Failed probes are not cached.

Media browse

MEDIA BROWSE <path> [index...] lists one directory of a disc image or a FATX memory-unit image. It is a MAIN command for the same reason as a probe and never changes the inserted disc or the machine. The reader checks for the FATX superblock first and otherwise searches the XDVDFS game-partition offsets, so a memory-unit .bin and an ISO/XISO/CHD/CCI/ZArchive disc use one command.

Each optional index selects a directory entry from the previous listing; zero indices list the volume root. The indices let the shell walk a tree one UI click at a time without re-encoding paths, and at most four levels fit one request. The result is one JSON object:

{"version":1,"ok":true,"format":"iso","fileSystem":"xdvdfs",
 "streamSize":123456789,"partitionOffset":0,"leadingPartition":false,
 "count":2,"truncated":false,
 "entries":[{"name":"Media","attributes":16,"size":2048,"start":44,
             "directory":true},
            {"name":"default.xbe","attributes":0,"size":4096,"start":40,
             "directory":false}]}

start is the first data sector for XDVDFS and the first data cluster for FATX; a directory's size is its table size. At most 4096 entries are returned and truncated reports a longer directory. Invalid indices, a selected file and a corrupt table still return JSON with "ok":false and an error string. The control channel spells it MEDIA BROWSE <base64 path> [index...].

Presentation uses the DISPLAY commands: PRESENT_FILTER, PRESENT_FPS_LIMIT, PRESENT_FPS_OVERLAY, PRESENT_DIAGNOSTIC_OVERLAY, PRESENT_FRAME_SKIP, PRESENT_COLOR and PRESENT_GEOMETRY. Host audio uses AUDIO: no argument returns the active backend name, AUDIO BACKEND <name> and AUDIO DEVICE <name> record a choice for the next launch, and AUDIO REOPEN re-resolves the running WASAPI endpoint. PRESENT_FPS_LIMIT accepts 0 for the historical unlimited pace or a 1..1000 frames-per-second cap. Frame skipping drops missed presentation deadlines instead of presenting a catch-up burst and only applies with a limit. The core draws the frame-rate and diagnostics overlays itself when the shell selects them; they are presentation features and never reach the recorded or captured picture. The shell reads the guest flip rate, the presentation-loop rate, frame times, draw calls, VRAM, the renderer and the audio pipeline counters from the STATS command and shows them in its own Activity page. Colour values are percentages: brightness/contrast/saturation in -100..100 and gamma in 50..300. Geometry selects whole-multiple scaling and an overscan crop of 0..20% per edge. All of these live in the core's final blit; the guest clock and the emulated picture are unchanged.

A headless benchmark sets present.sink-mode=1 (the launch argument -xgrid-config present.sink-mode=1). The display sink then publishes only the 32-byte header and frame counter, so the core skips the GPU readback, the RGBA-to-BGRA conversion and the shared-memory pixel copy. The full-pixel sink remains the default for tests and tools that actually read a frame. On the Vulkan path, screenshots and recording use a three-slot host-visible readback ring with one fence per slot; on the GL path they reuse one capture framebuffer and a two-buffer pixel-pack ring. Neither path allocates a target per capture.

SCREENSHOT queues a capture on the core's render loop. The core writes the PNG into general.screenshot_dir; the shell never receives the pixels.

Crash reports are written by the core itself, because only the crashing process can describe its own exit. The standalone core reads XGRID_CRASH_DIR (falling back to dumps in its working directory); there is no C setter. Windows writes a minidump through MiniDumpWriteDump and a .txt summary; Linux and macOS write a backtrace summary and re-raise the signal so the OS core-dump policy still applies. The shell only names the folder and logs the newest file. Setting XGRID_CRASH_TEST=1 faults before the machine starts, which is what scripts/crash-report-check.ps1 uses.

STATS returns the running machine's counters without touching the picture or the renderer. STATS_SUBSCRIBE selects the tick interval in milliseconds; xgrid_internal_stats_tick() is the core-side display hook that emits the tick.

The original 56-byte snapshot carries guest flips, flip rate, last frame time, draw calls, VRAM size, the running XBE title ID and the WASAPI mode, buffer size, frequency, queued frames and underrun count. The extended snapshot keeps those fields and adds p50/p95/p99/max guest frame times, a p99-derived 1% low, present-late count and worst lateness, the last capture path's total, readback and encode time, the last GL shader/program compile and Vulkan pipeline creation time, the recording queue depth and dropped frames, the negotiated WASAPI shared-mode engine period, the monitor refresh rate, the active Vulkan presentation and HDR modes, texture uploads, surface downloads/uploads, surface-to-texture fallbacks, shader generations, pipeline binds and inline draws. The caller passes its buffer size; the core writes the filled size and layout version. The endpoint is written to the core log. The Activity page and the headless reports read the same snapshot. Compiles over 16 ms also emit a core warning.

Recording and instant replay use the same core-owned picture. After presentation, when xgrid_record_wants_frame() is due, the render loop asks the frame sink for a top-down RGB copy (xgrid_frame_sink_read_rgb) and passes it to xgrid_record_add_frame(). That call copies the frame into a bounded encode queue and returns; one worker encodes and writes the container, so x264/JPEG work and disk writes never block presentation. GL reads through xemu_present_read_rgb() (RenderFramebufferToRgb); Vulkan reads the display image through xemu_vk_present_read_rgb(). The shell never receives a pixel. A build with x264 converts the frame to I420, encodes H.264 and appends the sample to an MP4; a build without x264 encodes JPEG with stb_image_write and appends it to an MJPEG AVI. Stop drains the queue before finalizing; a full queue drops the newest frame and increments the dropped counter in STATS. The replay ring stores encoded samples from the same encoder:

Command Arguments / text Result
RECORD_START text path, fps, quality 0 started
RECORD_STOP - finalizes the file
RECORD_STATUS - 1 while recording
RECORD_ERROR - last error text
RECORD_EXTENSION - mp4 or avi
REPLAY_START seconds, fps, quality 0 started
REPLAY_STOP - drops the ring
REPLAY_STATUS - 1 while collecting
REPLAY_COUNT - buffered frames
REPLAY_SAVE text path 0 written

MP4 stores 64-bit chunk offsets, so the container is not limited by the AVI 1.0 4 GiB boundary. The AVI fallback keeps its 32-bit size limit and stops a file cleanly. The replay ring keeps encoded samples, not raw pictures, and caps at 7,200 frames. The shell only supplies paths and options.

The APU's mixed frame buffer feeds the recorder as 48 kHz stereo S16LE. Live audio is spooled beside the video and resampled while it is muxed, so long recordings do not need a full copy in memory. The replay ring keeps its audio alongside the encoded frames. MP4 writes a QuickTime sowt PCM track; AVI writes an auds PCM stream. scripts/recording-audio-check.ps1 verifies the track and A/V duration against a booted core.

Input recording and replay are separate from the picture and use the INPUT command family: INPUT_RECORD_START (text path), INPUT_RECORD_STOP, INPUT_RECORD_STATE, INPUT_PLAY_START (text path), INPUT_PLAY_STOP, INPUT_PLAY_STATE (0 idle, 1 applying, 2 finished) and INPUT_ERROR.

xgrid-input-record.c samples the four XGDI pad records the core actually reads. It writes a sample only when a pad changes, with a QEMU virtual-time offset and the guest frame number. Replay applies those samples at the same virtual times, so pause, frame step and fast-forward stay aligned. Playback holds the final sample until stopped. The .xgin header and sample layout are documented in Input recording and replay; the shell inspects the header before starting a replay. A matching save state supplies the machine state; the input file does not contain RAM or devices.

Separate-process control channel

control/xgrid-control.c is started from xemu_run() when the shell sets XGRID_CONTROL_FILE and XGRID_CONTROL_TOKEN. It binds a random port on 127.0.0.1, writes the port to the file and accepts one authenticated client. Commands are LF-terminated text lines; string arguments and error text use base64 so paths and names need no escaping. The channel decodes each line into the shared command dispatcher for pause/resume, frame step, speed, snapshot save/load/delete/refresh/status/list, disc load/eject/status, MEDIA PROBE/ MEDIA BROWSE, RECORD, REPLAY, INPUT, MEMORY, DISPLAY, CONFIG and EVENTS. It is not a second emulation path and never carries the picture; recording and screenshots sample the core's own frame, and guest-memory reads and writes are chunked into 8 KiB requests. CONFIG returns the effective settings JSON; CONFIG SET key=value selects the command layer and CONFIG RESET [key] clears it, falling back to the environment, TOML or default.

The standalone run calls xgrid_internal_machine_started() once the machine is ready and xgrid_internal_machine_stopped() at shutdown. That state gates the core operations and installs the display frame hook. The shell's XemuCoreProcess maps the channel onto ICorePlayback, ISaveStateService, ICoreDiscs, ICoreMemoryCards, ICoreRecorder, ICoreInputRecording and ICoreMemory, so MainWindowViewModel uses one implementation.

An optional HTTP listener starts beside the line channel and writes its port to <port_file>.http. It binds only 127.0.0.1 and requires Authorization: Bearer <token>. POST /command takes one text command as the body and returns a JSON envelope (ok, value, json, text or data); GET /events?after=N returns the event array, GET /stats and GET /config return their normal JSON, and GET /health is a liveness check. One request is handled per connection, the request and body are capped at 16 KiB and 8 KiB, and both transports call xgrid_control_execute_line() so they cannot drift. The shell keeps using the line channel; the HTTP listener is for external tools and diagnostics.

system/vl.c builds an XboxEEPROMProfile from sys.eeprom.region, sys.eeprom.language and sys.eeprom.video_standard. A new EEPROM is generated with those fields; an existing file is patched in place by xbox_eeprom_apply_profile() in hw/xbox/eeprom_generation.c. That function detects the key version already used by the file, decrypts the security block, updates the profile fields, recomputes the covered checksums and re-encrypts the block. The serial, MAC, HDD key and online key are preserved.

Zero-valued profile fields mean "keep the existing value". The shell resolves auto before launch: region from the game's XBE certificate, language from the UI locale and video standard from the region. The AV pack remains the existing sys.avpack SMC setting.

Pause and frame step are queued like the save-state requests and applied on the core's main loop. A pause stops the machine on the next published frame, and a step resumes from that boundary and stops after the next frame. A 50 ms timer is the fallback when the display sink is off, because then no frame is published.

The speed multiplier scales the guest's QEMU_CLOCK_VIRTUAL and the vblank pace together, so the vCPU timers, the Xbox TSC and the presented frame rate all run at the same faster pace. The scale update is queued on the core's main loop, and system/cpus.c publishes the scale/base/anchor triple through a seqlock so the timer and vCPU readers never see a torn value. The shell returns to 1× on the next toggle, pause or session end.

A separate core process receives pause/step, speed, snapshots and disc changes over the loopback control channel. The registered XGrid.SetSpeed window message remains as a fallback for a direct window message.

The standalone process hosts one machine. QEMU's global state is single-use, so xemu_run() is called once and there is no exported start, join or version surface.

Build and validation

Windows:

pwsh -File scripts/build-native-xemu.ps1

Output: xemu/dist/XGridCore.exe, xemu/dist/xgrid-core.json and the runtime DLLs. The core's -renderers probe supplies the renderer list and -audio-drivers the audio list; the shell offers only those backends.

Linux:

bash scripts/build-native-xemu.sh

Output: xemu/dist/XGridCore, xemu/dist/xgrid-core.json and xemu/dist/LICENSE.txt. This is the standalone core; there is no separate validation library.

For the sanitizer gate, build in a separate checkout or worktree:

bash scripts/build-native-xemu.sh --sanitize
ASAN_OPTIONS=detect_leaks=0:abort_on_error=1 \
UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 \
XGRID_TEST_TIMEOUT_MULTIPLIER=5 \
  bash scripts/native-test.sh

--sanitize adds -Dasan=true -Dubsan=true and disables Vulkan; the test timeout multiplier covers the slower fuzz pass. The CI native-sanitize job runs the same sequence.

A release-style link-time-optimized build uses --lto:

bash scripts/build-native-xemu.sh -j4 --lto

The nightly native-lto job builds and tests the same configuration.

Upstream baseline

Each deliberate upstream re-base is checked against a tracked baseline:

pwsh -File scripts/core-baseline.ps1

It compares xemu/XEMU_VERSION and xemu/XEMU_COMMIT with xemu/xgrid-core/abi-baseline.json and checks the staged manifest version. There is no export list: the core has no native host ABI. A deliberate upstream re-base updates the baseline with -Refresh, then re-runs the media boot checks and the test suite.

Media boot checks

The disc drivers are checked end to end by booting a disc with the standalone core:

pwsh -File scripts/chd-boot-check.ps1 -Disc path\to\optimized.iso -Shot wt-data\xiso-boot.png
pwsh -File scripts/chd-boot-check.ps1 -Disc path\to\redump.iso -Shot wt-data\redump-boot.png
pwsh -File scripts/chd-boot-check.ps1 -Disc path\to\game.chd -Shot wt-data\chd-boot.png
pwsh -File scripts/chd-boot-check.ps1 -Disc path\to\game.cci -Shot wt-data\cci-boot.png
pwsh -File scripts/chd-boot-check.ps1 -Disc path\to\game.1.cci -Shot wt-data\cci-split-boot.png
pwsh -File scripts/chd-boot-check.ps1 -Disc data\test-samples\zar\007-entry.zar -Shot wt-data\zar-boot.png
pwsh -File scripts/chd-boot-check.ps1 -Disc data\test-samples\zar\hello.zar -Shot wt-data\zar-tree-boot.png

RESULT: PASS means the core stayed alive and presented a non-blank frame. A full Redump ISO must show the game, not the dashboard's video tray; the xgridiso driver maps the XGD game partition to LBA 0. The file-tree check exercises the XDVDFS synthesizer. For CCI, check both a single file and the first part of a split set; qemu-img compare can validate the decoded stream against the source ISO.

Adding an enhancement

  1. Prefer xemu/xgrid-core/ for new files.
  2. If an upstream file must change, keep the change minimal and record it in xemu/xemu-patches/.
  3. Keep the original copyright/license notice on derived files; add SPDX and a Ported from line when porting.
  4. Update THIRD_PARTY_NOTICES.md and docs/legal/licensing.md.
  5. Build the core and run the shell tests.
  6. Update the relevant documentation page in the same change.

Licensing

XGrid's additions are GPL-2.0-or-later. libchdr is BSD-3-Clause; libCCI is GPL-2.0-or-later. The vendored xemu/QEMU files keep their original notices. See Licensing and Porting and provenance.