# Replay media runtime Achievements invokes FFmpeg as a separate, hidden process to read and remux an existing NVIDIA/AMD replay. It does not use FFmpeg to capture a screen, run a rolling buffer or encode video. The default native recorder has its own existing pipeline. ## Build and verify On Windows x64, run `npm run prepare:replay-media`. It downloads the pinned FFmpeg 8.1.3 source archive and w64devkit 2.11.0 compiler into the OS temporary folder, verifies SHA-256, and builds without installing a system compiler. Subsequent builds verify and reuse the generated runtime. Internet access is needed only for the initial preparation. Build switches, source/compiler URLs and hashes are in `prepare-replay-media.js` and the generated manifest. No upstream sources are modified. `npm run verify:replay-media` validates the generated binaries, license texts, build configuration and matching source archive. Packaging checks run before and after Windows packaging; Linux excludes this Windows runtime. Builds fail if preparation or verification fails, rather than silently relying on tools in PATH. The generated `utils/vendor/replay-media` directory is ignored by Git and is populated during build preparation. ## Distribution The installer includes these files in `resources/app.asar.unpacked/utils/vendor/replay-media`: - `ffmpeg.exe` and `ffprobe.exe`, built with file input, MP4 demuxing/muxing, the concat demuxer for successive replay segments, H.264/HEVC/AV1/AAC parsers, and the necessary bitstream filters. - `COPYING.LGPLv2.1`, its referenced `COPYING.GPLv2`, and MinGW runtime notices. The FFmpeg build is **LGPL-2.1-or-later**, without `--enable-gpl`, `--enable-nonfree`, external codec libraries, network input, hardware capture or encoders. - The matching original `ffmpeg-8.1.3-source.tar.xz`, `manifest.json` and configuration log, so the corresponding FFmpeg sources accompany the binaries. The two executables currently total approximately **4.5 MiB**. Matching sources add approximately **11.2 MiB**, plus notices and the configuration log. The compiler, complete third-party shared builds, FFplay, development headers and compiler libraries are not shipped. This is an external command-line dependency; application code does not link FFmpeg libraries. Sources: [FFmpeg releases](https://ffmpeg.org/releases/), [FFmpeg licensing](https://ffmpeg.org/legal.html), [w64devkit source/build system](https://github.com/skeeto/w64devkit/tree/v2.11.0). The packaged corresponding source and configure flags allow FFmpeg to be rebuilt or replaced, subject to the documented input/output interface. ## Validation boundaries Run `node tests/verify-external-replay.js` for isolated queue, cancellation, migration, settings and cleanup regressions; it does not invoke GPU capture. Live NVIDIA/AMD tests must additionally verify movement, notification inclusion, monitor selection and foreground focus. MP4 structural/metadata validation does not establish smooth gameplay or guarantee every HDR/player combination. A replay command that times out is not sent again automatically. Failed jobs retain their source recordings, and interruption recovery never executes another replay command or deletes a source. `node tests/verify-pending-external-replay.js` additionally checks the first-notification/auto-selection boundary using the production main-process functions: correct config/platform, original visibility timestamp/preferences, expiry, duplicate suppression, backend changes and notification closure. Waiting for auto-selection does not start native capture and does not depend on screenshots being enabled. `node tests/verify-replay-batches.js` exercises both GPU backends with a simulated transport: shared saves, arrivals after a save command, incremental and rolling sources, missing intervals, dynamic batching, buffer deadlines, cancellation, source mutation and deferred cleanup. `node tests/verify-replay-safety.js` adds the review regressions: manual-source protection, capture-response receipts, stable shutdown while new accepted jobs enter, a valid 120-second post-roll and bounded handling of a stalled shutdown. `node tests/verify-nvidia-session.js` covers session recovery, concurrency, cancellation, transport errors and an end-to-end simulated replay across two expirations. `node tests/verify-partial-replay.js` checks complete/partial intervals and early saves for both backends. `node tests/verify-replay-queues.js` covers uncertain-save observation, capture/processing overlap, source leases and two-worker shutdown. `node tests/verify-replay-hotkey-ui.js` checks localized AMD diagnostic messages and renderer transitions. `node tests/verify-replay-readiness.js` checks prerequisite diagnostics and notification suppression. `node tests/verify-replay-hotkeys.js` checks parser compatibility and keyboard-event traces. `node tests/verify-amd-registry-fallback.js` checks user/machine shortcut precedence, explicit disabled/invalid values, view conflicts, fresh reads and the PowerShell helper with in-memory registry fixtures. `npm run test:external-replay` runs all eleven suites. Raw sources remain in the active history for at least 145 seconds after their capture end and until pending jobs no longer depend on them. Automatic deletion additionally requires an exact source path supplied by the capture command's machine-readable response and a successful unchanged source. A shortcut, success acknowledgement or filename/time match alone does not authorize deletion. AMD shortcuts and NVIDIA responses without a path therefore leave the GPU original in place; finished unconfirmed entries retire from active history so they do not permanently exhaust the history limit. `source-retained` with `ownership-unconfirmed` records this normal outcome. Errors pin their sources for diagnosis. Internal source journals are not trusted as timing information after a process restart. Graceful shutdown waits for all accepted jobs, including jobs accepted while a preceding drain was finishing. Its timeout accounts for remaining post-roll plus bounded settings, save, detection and media work, capped at 30 minutes; completion resumes quit immediately. The native-only fallback remains 75 seconds. The calculated budget and pending count appear in the `shutdown-draining` stage. A forced/deadline exit preserves incomplete or uncertain sources. For media integration, run `node tests/verify-replay-segments.js `. The explicitly supplied full test FFmpeg creates moving H.264/HEVC/AV1 fixtures, including B-frames, and independently decodes the production runtime's joined output. Decoded video frame hashes must match the original sequence across two/three-segment joins, with both audio tracks preserved. The H.264 fixture with an approximately 21ms AAC overlap must publish successfully with audio warnings; a separate 100ms audio offset must still be rejected. Ordinary single-source H.264 with audio is also checked. The full test binary is never used by production or included in the installer. Production continues to copy compressed streams without encoders or capture support. Concat outpoints use decoding timestamps. Joins therefore check independent starting frames, compatible stream formats and safe overlap boundaries; arbitrary B-frame overlaps are rejected when they cannot be cut safely. Every output audio track is checked around visible joins for missing/overlapping packet intervals. Minor audio gaps/overlaps up to **25ms per discontinuity** are allowed: the final clip is published with `audioWarnings`, and `external-replay:audio-warning` records the affected tracks, boundaries and maximum overlap/gap in `records.log`. No audio is removed or re-encoded. Larger audio discontinuities, missing coverage or invalid timing still prevent publication and retain originals; detection also checks AAC packet-duration stretching that could conceal a large gap. A real video-history gap is not concealed by padding or repeating frames: interval selection uses one continuous available portion and reports partial coverage. Strict media joins still reject uncovered gaps as `replay-history-gap`. Batch identifiers/sizes and trimming source lists distinguish shared saves from multi-source processing. ## Partial replay intervals Before and After are desired lengths, not required minimum coverage. Validation still requires a positive, finite GPU buffer, active replay/Desktop Capture and the existing monitor/output checks. There is no hard 60-second minimum and no rejection solely because the configured buffer is shorter than Before + After. The native recorder and screenshots retain their existing behavior. The ordinary full-coverage path still selects the complete requested interval. When the actual files lack part of it, selection uses the continuous available interval containing the notification where possible, clipping the requested start/end to that interval. It never joins across a real gap. If the notification has already fallen outside all available intervals, the nearest remaining material is saved, limited to the requested total duration, with `notificationIncluded:false`. Valid retained segments can still provide a full clip even when the current GPU buffer is shorter than the requested total. Invalid/changed sources or unsafe video/audio joins remain errors rather than being silently accepted. For scheduling, the desired save time remains the requested After plus the existing 1s settling interval when safe. The history-protection deadline is the first uncovered requested timestamp plus the configured buffer length, minus a safety margin of up to 3s (one quarter of the buffer for very short buffers). The earlier of the desired time and deadline wins. This prioritizes the requested action before the notification over a long After; later notifications cannot extend a shared save beyond that deadline. Already expired/late requests save immediately instead of being rejected before capture. Settings/observation/provider I/O can still overrun a deadline; actual file coverage is then used for the partial cut. This does not guarantee preservation of frames the GPU has already overwritten. Capture/detection remain serialized; media processing now has an independent single worker as described below. | Requested | Available | Selected interval | | --- | --- | --- | | 20s before + 20s after | Complete interval | 40s | | 20s before + 20s after | 8s before + 20s after | 28s | | 20s before + 20s after | 30s buffer, no earlier source | About 20s before + 7s after, with the 3s safety margin | | 20s before + 20s after | 20s before + 8s after | 28s | `saving` stages include `bufferSeconds`, requested timing and `earlySave`. `trimming`/`saved` include `partial`, `partialReasons`, `requestedBeforeSeconds`, `requestedAfterSeconds`, `selectedBeforeSeconds`, `selectedAfterSeconds` and `notificationIncluded`; `duration` is the media result's duration. `external-replay:partial` records the shortened result separately. Selected timing comes from the source interval; stream-copy/keyframe rounding can slightly change the actual published duration. Successful partial clips use the same output paths and ownership/retention rules as complete clips, without additional sidecar files or automatic capture retries. Optional integration: `node tests/verify-partial-replay.js ` creates moving H.264 fixtures with audio, then runs the production controller/planner and bundled stream-copy runtime. The complete/short-before/30s-buffer/short-after outputs are independently decoded and their video frame hashes compared with the selected source interval. On 2026-11-02 the four outputs were approximately 40.067s, 28.133s, 27.067s and 28.067s, with audio preserved and no re-encoding. These disposable-media checks do not invoke real NVIDIA/AMD capture or establish driver behavior under load. ## AMD hotkey diagnostics AMD settings checks reread both registry sources through the read-only PowerShell helper. `HKCU\Software\AMD\DVR` has priority separately for each setting; an absent value can use `HKLM\SOFTWARE\AMD\DVR`. This applies to `CaptureFileOutput`, `SaveInstantReplayHotkey`, `InstantReplayEnabled`, `InstantReplayDuration`, `DesktopRecordingEnabled`, `DvrEnabled`, `HotkeysDisabled`, `DvrDesktops`, `FileEncoderType` and `FileCustomFrameRate`. A missing entire user key is supported. Explicit user values, including `0`, `false`, `None`, empty strings and unsupported representations, are preserved. Conflicting explicit user values block that setting. Machine conflicts are checked only for fields requiring fallback, so overridden machine differences do not block a valid user profile. No value is written or hardcoded. Machine read errors block a required fallback or an available but uncertain optional fallback. Absent optional metadata (hotkeys-enabled flag, monitor, codec/FPS) retains its previous unknown-state behavior if no readable fallback exists; successful checks include any `registryReadErrors`. Required values still undergo normal enabled/buffer/path/monitor validation. The live AMD recording service check cannot be replaced by registry settings. User registry read errors are not interpreted as a missing key. The affected-user log confirmed an absent HKCU shortcut after factory reset, then `None` after clearing it, then readiness after reassignment. The older diagnostic contained the same valid shortcut in HKCU and HKLM; actual AMD default precedence after reset still needs live verification. Successful checks log `registrySources` for each resolved value and retain `hotkeySource` for the shortcut. Each source contains `registryPath`, `registryValue`, `fallback` and available source views. Conflicts/read failures name the affected setting and source; registry-read failures include `fallbackRegistryErrors`. Validation failures retain the resolved source map. `replay-hotkey-invalid` also includes `hotkeyIssue`, `hotkeyType` and a bounded `hotkeyValue` for strings in `records.log`. `missing` identifies an absent/empty value; `unsupported-format`, `unsupported-key` and `unsupported-modifiers` identify rejected representations. Source/read-error metadata is excluded from the recording fingerprint, so materializing an identical HKCU profile does not cancel a pending replay. Settings displays separate localized messages for missing and unreadable shortcuts, followed by reassignment/check instructions. "Unreadable" means Achievements cannot interpret the representation it read, not that Adrenalin rejects the combination. Automatic recording-failure warnings use the same formatter and readiness-warning suppression described below. All 30 locales include the texts; unknown older hotkey diagnostics keep the generic replay message. Raw registry values remain diagnostic data and are not inserted into the renderer's message. No default shortcut is assumed and no registry setting is changed. Legacy mappings are preserved while additional explicit representations are supported below. `node tests/verify-replay-hotkey-ui.js` checks actual parser diagnostics, all locale keys, missing/unsupported/ready renderer transitions, generic fallback, stale-response suppression and zero preference writes. `node build/run-electron-script.js tests/verify-replay-hotkey-ui.js` additionally loads the production message formatter and replay controls into an isolated hidden Electron renderer with simulated IPC and English text, verifies the same visible status transitions and writes a report under the OS temporary folder. It does not contact AMD or change the application profile. ## AMD hotkey compatibility The parser keeps the verified AMD `modifiers,key` form (`Ctrl+Shift,S`) and accepts explicit `modifier+modifier+key` text (`Ctrl+Shift+S`), case/whitespace variations, `Control`/`Ctrl` aliases, left/right modifier names and `VK_` key names. Existing string-array representations still join to their text form. Bare configured keys such as `F10` and `Space` are supported; this does not imply that every Adrenalin version permits assigning every combination. No modifier is added automatically and order is retained. Supported main keys include letters/digits, F1–F24, arrows, Home/End/PageUp/PageDown, Insert/Delete/Backspace/Tab/Enter/Escape/Space, Pause/PrintScreen/lock keys, numpad digits/operators and explicit Windows OEM names. Examples include `Ctrl,VK_UP`, `Alt+Page Down`, `RControl+Up`, `Ctrl+Numpad0`, `Ctrl,OEM_PLUS` and `Ctrl,VK_OEM_102`. The Windows-defined plus/comma/minus/period keys also accept their names or glyphs; the comma-separated form distinguishes the comma key (`Ctrl+Shift,,`), and `Ctrl++` denotes Ctrl plus the plus key. Layout-dependent OEM punctuation should use its explicit OEM key identifier; no US-layout character conversion or inferred extra Shift/AltGr is applied. Modifiers-only, duplicate modifier families, malformed/unknown input and unverified binary/numeric encodings remain diagnostic failures. An absent user value can use the explicit machine shortcut under the precedence rules above; if both sources lack it, the check still fails. No hardcoded key combination is supplied. The shortcut sender accepts the resulting configured key(s), sets KEYEVENTF_EXTENDEDKEY for extended navigation/right-modifier/Windows/numpad-divide keys, preserves key-up flags, and releases only successfully injected keys in reverse order. Validation precedes native API creation; the held-key wait and cancellation rules remain in place. NVIDIA's API save path is untouched; its older shortcut fallback shares the sender and is checked for equivalent ordinary Alt+F10 events. `node tests/verify-replay-hotkeys.js` exhaustively checks all previously supported non-duplicate Ctrl/Shift/Alt permutations with letters, digits and F1–F24, plus equivalent text forms and new named-key examples. Stubbed INPUT traces cover extended flags, single keys, ordinary NVIDIA fallback, cancellation, rejected input and physical held-key protection, without real keyboard events. Primary references: [Windows virtual-key codes](https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes), [KEYBDINPUT flags](https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput), and [AMD's configurable hotkey behavior](https://www.amd.com/en/resources/support-articles/faqs/DH3-038.html). These sources document keys/behavior, not every AMD registry serialization; a live AMD test is still needed for a newly reported representation. ## Readiness warnings When external GPU recording is enabled, one read-only preflight runs when the selected backend becomes active, including startup and enabling recording. Repeated config selection does not repeat this activation check. The existing Check replay settings action also reads current state; normal save attempts retain their own validation. There is no periodic polling, GPU-option toggle, automatic shortcut assignment or extra capture command. Providers attach diagnostic `prerequisites` outside the recording settings fingerprint. Values are true, false or null (unknown). AMD reports Instant Replay, desktop recording, its DVR feature/service and the hotkeys-enabled flag. NVIDIA reports Instant Replay and Desktop Capture from its existing config/API checks; `overlay_not_available` has its own message. Conflicting/absent state is reported as unverified rather than disabled. Optional missing AMD HotkeysDisabled metadata does not newly block otherwise working configurations. Hotkey errors can include other confirmed inactive prerequisites in the same warning. Capture eligibility rules remain unchanged. Settings and in-app warnings share the localized formatter. With external recording enabled, identical recognized readiness warnings from activation, manual checks and job failures are suppressed for 60 seconds. A successful check resets suppression; a different condition can warn immediately. Other recording failures retain their existing generic notification/throttle. Warnings do not show/focus the app or use achievement notifications. If the main window is loading, the pending warning is reconsidered after load, using the current backend. Stale replies after disabling, switching away/back, newer checks or quitting do not notify. `external-replay:settings-check` records `reason: activation` or `manual` as well as the result and available prerequisites. `node tests/verify-replay-readiness.js` checks confirmed inactive states, unknown vs disabled, combined diagnostics, optional metadata compatibility, all locale keys, one activation check, cooldown/recovery, native/disabled/quit guards, stale replies and deferred window delivery. The isolated Electron renderer check additionally verifies AMD/NVIDIA disabled-option text without changing GPU settings. A local read-only NVIDIA check on 2026-11-02 confirmed active Instant Replay/Desktop Capture through the production reader; AMD inactive states are covered with fixtures, not live AMD hardware. ## Independent capture and processing queues The capture worker serializes settings checks, scheduling, one save command and file detection. After association, it closes that observer, adds the source to history, freezes each job's selected sources/coverage and queues media processing. It can then handle the next capture without waiting for FFmpeg. The media worker serializes output preparation, trimming, validation and publication: there is still at most one FFmpeg trim at a time. Neither worker starts a second GPU capture to retry an earlier result. Both queues share the existing 16-job limit, source limits and original visibility timestamps/preferences. Each processing job protects explicit source references, including the capture source and any retained segment required for its selected interval. Cleanup respects these leases even if a partial/salvage source lies outside the job's requested timing. Source selection, addition, marking and cleanup run through one history critical section to avoid competing journal writes or deletion during selection. A closed observer ignores later filesystem callbacks, so the next GPU file cannot retroactively invalidate an already sealed association. File mutation, monitor changes and media validation are still checked before publication. Graceful stop waits until capture, processing and history operations have drained, including processing enqueued while shutdown was awaiting an older worker promise. Cancellation aborts active and queued jobs in both workers; force-stop also closes the provider. Incomplete/failed sources remain pinned. Final cleanup happens only after both queues finish. Slow settings/API/detection can still hold the capture worker; the separation removes media-processing delay without introducing ambiguous concurrent saves. ## Uncertain NVIDIA save results The provider records `captureSentAt` immediately before a save attempt. Transport timeouts/disconnections, unreadable transport responses and the NVIDIA `overlay_timeout` outcome are marked `outcomeUncertain`; known pre-send failures such as connection refusal are not. The controller keeps the already-open observer and uses that original timestamp, not the later time the error arrived. No save is resent and no shortcut fallback is attempted. Detection keeps its existing bounded wait (up to 60s after the API call returns). A single stable, valid new candidate proceeds through the normal source/monitor/media checks. The stages `save-outcome-uncertain`, `detecting` and `save-file-recovered` explain the attempt; a published result carries `saveOutcomeUncertain:true`. The failed API response supplies no trusted path receipt, so the GPU original remains unconfirmed and is not automatically deleted. This is file-based recovery, not proof that the API acknowledged the save. Explicit access/readiness/validation rejections and HTTP failures, errors before a request could be sent, and user cancellation do not enter this recovery. Missing or ambiguous candidates remain failures; diagnostics also retain `originalApiCode` and `originalApiError`. `overlay_timeout` permits observation because execution may be uncertain, regardless of its retryability flag; it never permits an automatic resend. The isolated queue suite verifies delayed-file recovery with the original timestamp, one save command only, no recovery for explicit rejections or refused connections, capture/processing overlap for NVIDIA and AMD, one worker per stage, protected sources and serialized history operations, cancellation while waiting for a file, graceful/forced shutdown, and real filesystem watchers handing off two distinct files. The GPU commands and probes in these watcher fixtures are simulated; this does not establish real driver behavior under game load. ## NVIDIA API connection and recovery The HTTP adapter reads discovery afresh, accepts `/mcp` and `/mcp/`, validates loopback-only endpoints, and shares one client for the discovered endpoint/host PID. Replacement and shutdown are serialized. Initialization is shared; cancelling one settings check does not cancel another check's initialization. Closing a client aborts its outstanding requests, waits for initialization cleanup, and attempts DELETE of its last known session exactly once. Failed initialization also releases an assigned session. For a session-bound status read returning HTTP 404, the adapter discards the expired ID, initializes without it, discovers the required tools, and retries the read once. Concurrent and late responses from the expired generation share that renewal and cannot restore its old ID. A second failure, an HTTP 500, a backend error, or a 404 without an assigned session is returned without another renewal. The status checks before waiting and before saving use the same policy. Renewal counters are diagnostic only and do not change the recording settings fingerprint or requested clip timing. `external-replay:stage` logs `api-session-renewing`, `api-session-renewed` and `api-session-renewal-failed`. Settings checks include `apiProtocol` and `apiSessionRenewals`; failure diagnostics preserve `operation`, `httpStatus`, `apiCode`, `rpcCode`, `retriable`, or `missingStatusFields` where applicable. The detecting stage retains the capture's text as `providerMessage`; that acknowledgement is not treated as proof of a saved file. Session IDs are not logged. A timeout/connection loss/capture error never resends `save_instant_replay` and never switches to a shortcut. An uncertain save, including `overlay_timeout`, can still be recovered from one observed valid file as documented above; it is not reported as successful merely because the provider marks the error retriable. Official references: [NVIDIA connection/lifecycle](https://github.com/NVIDIA/nvidia-app-skills/blob/main/skills/nvidia-app/references/connection.md), [NVIDIA Overlay contract](https://github.com/NVIDIA/nvidia-app-skills/blob/main/skills/nvidia-app/references/mcp-tool-contract.md), [NVIDIA capture semantics](https://github.com/NVIDIA/nvidia-app-skills/blob/main/skills/nvidia-app/references/overlay-capture.md), and [MCP session management](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management). The adapter retains the supported `2025-11-25` legacy negotiation (including session cleanup) rather than switching to NVIDIA's newer stateless protocol. HTTP pipe-only/degraded installations are reported as unavailable; no stdio bridge process is spawned. MCP connection readiness does not establish Overlay readiness. Status fields may be omitted; missing Desktop Capture/Instant Replay fields are reported as unknown instead of guessing. The API saves the configured buffer and normally returns human-readable capture output, without a guaranteed output path, duration override or monitor identity. Existing file observation, stream-copy trimming, monitor confirmation and original-file ownership rules therefore remain necessary. The isolated regression suite includes 20 scenarios: six simultaneous expired reads and late old responses, bounded/no-session recovery, initialization failures, HTTP/transport/JSON-RPC errors, capture timeouts with one command only, structured/text error codes, SSE priming/multi-line frames, paginated tool discovery, independent cancellation, shutdown during renewal, endpoint/PID replacement and complete simulated replay publication. A live status-only check on 2026-11-02 invalidated only its own test session, renewed once for four simultaneous reads, and closed the replacement; no capture command was sent. This validates connection recovery, not live game footage, driver smoothness or AMD hardware behavior.