Skip to content

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

  1. The match ends. The host's game writes the replay to a file under user://.
  2. 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.
  3. The replay is private: its participants can list it and download it. Nobody else can.
  4. 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.
  5. Any player who can see a recording can report it. Reports queue for staff.
  6. 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. UploadAsync is idempotent per match: uploading the same bytes again after a success is a free 200, 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. QuotaExceeded carries RetryAfter.
  • Never trust Meta, Tags or Players on a listing. They are whatever the uploader wrote. Show them as plain text in a Label, never in BBCode; do not use them to grant anything. A score in Meta is a claim, not a result.
  • Name files by digest. RecordingsClient.DefaultPath does. 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

  1. Plain data, strict schema. A fixed header and length-prefixed or fixed-layout records, read with explicit bounds (a BinaryReader or System.Buffers.Binary over a span that you check before every read). Not an object graph.
  2. No Godot Variant decoding at all, anywhere in the reader, not even "without objects": no GD.BytesToVar / bytes_to_var / bytes_to_var_with_objects, no FileAccess.get_var, no str_to_var, no ConfigFile or JSON.parse_string into untyped Variants 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 no ResourceLoader.Load on a path from the file, no PackedScene from bytes, no Resource saved as .tres, no .NET BinaryFormatter, Type.GetType, polymorphic or $type JSON. If you use JSON for a small part, use JsonDocument with a MaxDepth, read only the keys you expect, and ignore the rest.
  3. 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.
  4. 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 use PackedByteArray.decompress with the exact expected size or decompress_dynamic with an explicit max_output_size, never an unbounded one: a few kilobytes can decompress to gigabytes.
  5. Tagged with the release, refused on mismatch. The header carries the release_id of 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.
  6. 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.
  7. 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.
  8. A replay must never be passed to LoadResourcePack (ProjectSettings.load_resource_pack), to ResourceLoader, to Image.load from 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.
  9. 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.
  10. Show listing text as plain text, never as markup. RecordingInfo.Meta strings, Tags and Uploader come from a player. Put them in a plain Label (or LineEdit), never in a RichTextLabel with bbcode_enabled: meta may 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.
  11. 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.)

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 restart allocator, matchmaker and patch. Until the keys exist, Patch answers uploads with 503 host_check_unavailable rather 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). viewer reads, live_ops decides, admin deletes. Approving pins the recording against the 30-day sweep unless you untick it.
  • What a host claims is untrusted. Meta can 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.