Record, upload and watch replays¶
In a peer-hosted match (transport: p2p_host) there is no game server, so the host player's
game is the only place a replay exists. This guide is how a game records one, uploads it,
shows it back, and keeps a hostile file from hurting anybody. It has two audiences: the game
programmer (the contract below) and the person who runs otomo (moderation, limits, retention).
If you only read one thing: otomo stores a replay's bytes and never looks inside them. Your game's replay reader is the only thing between a hostile file and another player's game. The section "Replay format contract for clients" is a requirement on that reader.
How it fits together¶
- The match ends. The host's game writes the replay to a file under
user://. - The host uploads it with
RecordingsClient.UploadAsync(the SDK checks the file, hashes it, sends it and retries). Patch asks the Allocator whether this player hosted that match and the Matchmaker who was in it, and refuses anything that does not fit. - The replay is private: its participants can list it and download it. Nobody else can.
- The host may ask for it to be shown publicly (
SetVisibilityAsync(..., PublicPending)). Staff review it in a moderation queue (the API is in place; the admin website page is built separately). When they approve it, every player can list and watch it, and it can be added to a curated list. - Any player who can see a recording can report it. Reports queue for staff.
- Player recordings expire after 30 days unless staff pinned them, a curated list names them, or an unresolved report is under review. Recordings from a game server are not expired unless the operator turns that on.
Recordings are served by Patch with the player's token, by id. They are not release content, they are never addressed by a public hash, and the content mirror (the CDN) does not carry them.
What the game does¶
var rec = otomo.CreateRecordings(httpClient); // once; the same HttpClient the SDK uses
// 1. After the match, on the host: upload.
var result = await rec.UploadAsync(matchId, "/path/to/match.otrp", new UploadOptions
{
Kind = "replay.v1", // the format your reader parses
ReleaseId = currentReleaseId, // from the Patch manifest this client ran
Players = rosterPlayerIds, // a subset of the match roster; the host is added
Tags = new[] { "arena" }, // stored as "u:arena"
Meta = new JsonObject { ["map"] = "arena", ["duration_s"] = 412 },
});
if (!result.Success)
{
switch (result.Failure)
{
case RecordingFailure.QuotaExceeded: // tomorrow: result.RetryAfter
case RecordingFailure.Network:
case RecordingFailure.Unavailable:
QueueForLater(path); // keep the file; try again at next start
break;
default: // not the host, too large, invalid, ...
Discard(path);
break;
}
}
// 2. Watch: list, download (verified), then hand the file to YOUR reader.
var mine = await rec.ListMineAsync();
var info = mine[0];
if (info.Kind != "replay.v1" || info.ReleaseId != currentReleaseId) return; // refuse, do not try
var dl = await rec.DownloadAsync(info, RecordingsClient.DefaultPath(config, info));
if (dl.Success) ReplayReader.Open(dl.Path!); // see the contract below
// 3. Report, or ask for a public listing.
await rec.ReportAsync(info.Id, ReportReason.Cheating);
await rec.SetVisibilityAsync(info.Id, RecordingVisibility.PublicPending);
Things the game must do around the SDK:
- Keep the file until the upload succeeds. A host can lose the connection at the end of a
match.
UploadAsyncis idempotent per match: uploading the same bytes again after a success is a free200, so a retry queue is safe. - Only the host uploads. A peer that tries gets
NotHost. Do not offer it. - Respect the quota. The default is 20 uploads and 64 MiB per player per day, and 8 MiB per
file.
QuotaExceededcarriesRetryAfter. - Never trust
Meta,TagsorPlayerson a listing. They are whatever the uploader wrote. Show them as plain text in aLabel, never in BBCode; do not use them to grant anything. A score inMetais a claim, not a result. - Name files by digest.
RecordingsClient.DefaultPathdoes. Never build a path from an id, a tag or a name from the server.
Replay format contract for clients¶
A replay is untrusted input from another player, parsed by your game with your game's privileges. The recording service cannot check that it is well-formed, and a replay format that can express "load this resource" or "run this" is a remote code execution hole delivered by a friendly looking download. Hold your format to this contract.
The format
- Plain data, strict schema. A fixed header and length-prefixed or fixed-layout records, read
with explicit bounds (a
BinaryReaderorSystem.Buffers.Binaryover a span that you check before every read). Not an object graph. - No Godot
Variantdecoding at all, anywhere in the reader, not even "without objects": noGD.BytesToVar/bytes_to_var/bytes_to_var_with_objects, noFileAccess.get_var, nostr_to_var, noConfigFileorJSON.parse_stringinto untypedVariants of file data. A Variant decoder will allocate whatever size the bytes claim and can construct objects; there is no safe flag to set, so the only safe use is none. Read the fixed fields yourself. Likewise noResourceLoader.Loadon a path from the file, noPackedScenefrom bytes, noResourcesaved as.tres, no .NETBinaryFormatter,Type.GetType, polymorphic or$typeJSON. If you use JSON for a small part, useJsonDocumentwith aMaxDepth, read only the keys you expect, and ignore the rest. - No scene, script or resource paths. A replay refers to things by numeric id (a
character, an effect, a spell, a map), and the reader checks every id against a fixed list built
into this release. An id outside the list rejects the file. A string from the file is never used
as a path, a node path, a class name or an input to
load. - Everything is bounded, and nothing is preallocated from a number in the file. Cap the file
size (the service already refuses more than 8 MiB), the number of players (at most 64), entities
per snapshot, events per snapshot, snapshots, the total duration, and the decompressed size.
Never size an array, list or buffer from a count you just read. First check
count * record_size <= remaining_bytes(with the multiplication done in 64 bits, and the count already under its cap); only then allocate. If the payload is compressed, inflate with an output limit checked while inflating and reject past it. In Godot usePackedByteArray.decompresswith the exact expected size ordecompress_dynamicwith an explicitmax_output_size, never an unbounded one: a few kilobytes can decompress to gigabytes. - Tagged with the release, refused on mismatch. The header carries the
release_idof the build that recorded it, and the format version. The player reads the same two values from the listing (RecordingInfo.ReleaseId,RecordingInfo.Kind); a replay from another release is not opened (a replay is only meaningful against the content that produced it). Check before downloading, and again from the header after. - Reject, do not repair. The first violation of any rule ends the parse and discards the file. No partial playback of a file that failed a check, and no "best effort" for unknown record types.
- The parser has no side effects. It builds a plain in-memory description of what to show. Playback then drives your own game objects from that description; the file never names which objects.
- A replay must never be passed to
LoadResourcePack(ProjectSettings.load_resource_pack), toResourceLoader, toImage.loadfrom an extension in the file, or mounted in any way. A resource pack runs scripts. Patch's own blobs are release content and are the only thing the game mounts. - No parse on the main thread without a budget. Parse on a worker with a time limit, or in steps; a file that takes too long is refused.
- Show listing text as plain text, never as markup.
RecordingInfo.Metastrings,TagsandUploadercome from a player. Put them in a plainLabel(orLineEdit), never in aRichTextLabelwithbbcode_enabled:metamay contain[and](BBCode, including[url]and[img]), bidirectional controls that reorder what the player reads, and zero-width characters that make two different names look the same. Cap the displayed length, and strip or visibly escape control and format characters before showing them. - Do not carry names. A display name is not in the replay: show names from the roster the
platform signs (
/api/player/match/{id}/roster). A string you did not write is a string that can contain bidi controls or markup.
Staff tools that open a replay (the admin website downloads one only as an opaque attachment) must follow the same contract. Do not double-click a downloaded replay in an editor that could open it.
A replay is host-authored and is not evidence. The host's game wrote every byte of it, so a replay shows what the host says happened, not what happened. Do not use one as proof in a cheat report, a dispute or an outcome, and never pay, rank or reward from one. (Reports on a replay are about the replay itself, such as abuse in a name or a message; staff cannot confirm cheating from it.)
A recommended minimal format (replay.v1)¶
This is documentation, not code the platform ships. It is small, fixed-layout and easy to bound. Little-endian, no padding.
Header (64 bytes)
magic "OTRP" 4
version u16 = 1 2
flags u16 (0; bit0 = payload is deflate) 2
release_id u64 8 the build that recorded it; must equal the viewer's
match_id 16 bytes (UUID) 16
tick_hz u16 (<= 60) 2
keyframe_every_ticks u16 2
duration_ticks u32 (<= tick_hz*3600) 4
player_count u8 (<= 64) 1
_reserved u8 = 0 1
snapshot_count u32 (<= 1,000,000) 4
raw_len u32 (<= 24 MiB) 4 decompressed payload length; checked while inflating
payload_len u32 4 length of what follows
reserved 6 bytes, zero 6
crc32 u32 4 of the payload; detects damage, proves nothing
Payload (raw_len bytes after inflate)
players[player_count]: player_id 16 bytes, slot u8, character_id u16 (id from the release's fixed list)
snapshots[snapshot_count]:
tick_delta varint (<= 2^16)
kind u8 0 = keyframe (every entity), 1 = delta (changed entities only)
entity_count u16 (<= 512)
entities[]: entity_id u16, type_id u16 (fixed list), flags u16,
x i16, y i16, z i16 (position in 1/64 m, room-local), yaw u8 (1.4 degree steps),
hp u16, anim_id u16 (fixed list)
event_count u16 (<= 256)
events[]: type u8 (fixed list), actor u16, target u16, value i32
Every *_id, type and anim_id is validated against a list the release ships. Positions are
integers, so there is no float parsing to go wrong.
Estimated sizes. An entity record is 17 bytes. A host snapshot stream at 10 Hz with 64 live entities, about 40% changing per snapshot, is around 4.5 KB per second before events (64 x 0.4 x 17 x 10, plus a 1.1 KB keyframe every 5 seconds):
| Match length | Raw stream | Deflated (about 2.5x) | Fits the 8 MiB cap |
|---|---|---|---|
| 5 minutes | 1.4 MB | 0.5 MB | yes |
| 15 minutes | 4.1 MB | 1.6 MB | yes |
| 30 minutes | 8.1 MB | 3.2 MB | only deflated |
| 60 minutes | 16 MB | 6.5 MB | barely, deflated |
These are worst-ish cases with all 64 entities live; a typical match has far fewer. At 20 Hz double the first column. The 8 MiB cap is the server's; if you need more, quantise harder or lower the snapshot rate before you ask for a larger cap, because every replay is stored for 30 days and counted against each player's daily 64 MiB.
Run it (operators)¶
- Turn it on. Re-run
deploy/scripts/generate-secrets.sh(three new keys) and restartallocator,matchmakerandpatch. Until the keys exist, Patch answers uploads with503 host_check_unavailablerather than accepting an unchecked one. - Limits (all in the Patch README): per-upload cap, per-player daily uploads and bytes, interval, window after the match, disk cap, allowed formats.
- Moderation: a queue of reported and publicly-requested recordings, with hide, approve,
dismiss, unpublish, download and delete, under
/api/admin/patch/moderation(the admin website page is a separate piece of work; the routes and the screen it needs are in the Patch README).viewerreads,live_opsdecides,admindeletes. Approving pins the recording against the 30-day sweep unless you untick it. - What a host claims is untrusted.
Metacan feed a curated list's order (for example "highest score first") on recordings you approved. It must never feed a reward, a rank or an achievement: a peer-hosted match is paid from the economy's own match record, not from a replay. See Pay rewards for peer-hosted matches. - Erasure. When a player erases their account, their recordings should go too. Patch has the endpoint, but account erasure does not reach Patch until Auth calls it (a follow-up; see the Patch README), so for now they leave with the 30-day sweep. Even then, other participants' ids are inside the replay bytes that another player uploaded, and stay there until that recording expires; Patch never opens the bytes. A public listing shows strangers neither the player list nor the uploader.
- A match has one replay. A host who uploads again must send exactly the same bytes, format, meta, tags and players (a free retry); anything different is refused. If staff delete a recording, the host cannot upload it again.