squadreplay 0.1.0-alpha.1

Library-first Rust parser and CLI for Squad UE5 replay files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
use clap::{Parser, Subcommand};
use serde::Serialize;
use squadreplay::bundle::Bundle;
use squadreplay::{Error, ParseOptions, Result, compat, parse_file, read_bundle, sqrb, sqrj};
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};

const ROOT_AFTER_HELP: &str = "\
Examples:
  squadreplay parse match.replay --format sqrj,sqrb --output out/match
  squadreplay parse match.replay --compat-json
  squadreplay inspect match.replay
  squadreplay show out/match.sqrb
  squadreplay unpack out/match.sqrb --output out/unpacked

Use --json to keep machine-readable output for scripts.
";

const PARSE_AFTER_HELP: &str = "\
Examples:
  squadreplay parse match.replay --format sqrj,sqrb
  squadreplay parse match.replay --output out/match --compat-json --json
";

const INSPECT_AFTER_HELP: &str = "\
Examples:
  squadreplay inspect match.replay
  squadreplay inspect match.replay --json
";

const SHOW_AFTER_HELP: &str = "\
Examples:
  squadreplay show out/match.sqrb
  squadreplay show out/match.sqrj.json --json
";

const UNPACK_AFTER_HELP: &str = "\
Examples:
  squadreplay unpack out/match.sqrb --output out/unpacked
  squadreplay unpack out/match.sqrb --output out/unpacked --json
";

#[derive(Debug, Parser)]
#[command(name = "squadreplay")]
#[command(about = "Parse and inspect Squad UE5 replay bundles")]
#[command(after_help = ROOT_AFTER_HELP)]
#[command(arg_required_else_help = true)]
pub struct Cli {
    #[command(subcommand)]
    command: Command,

    #[arg(
        long,
        global = true,
        help = "Print machine-readable JSON instead of the default terminal summary"
    )]
    json: bool,
}

#[derive(Debug, Subcommand)]
enum Command {
    #[command(about = "Parse a .replay file and write one or more bundle outputs")]
    #[command(after_help = PARSE_AFTER_HELP)]
    Parse {
        #[arg(value_name = "REPLAY", help = "Path to the .replay file to parse")]
        input: PathBuf,
        #[arg(
            long,
            short = 'f',
            default_value = "sqrj",
            value_name = "FORMATS",
            help = "Formats to write: sqrj, sqrb, or a comma-separated list"
        )]
        format: String,
        #[arg(
            long,
            short = 'o',
            value_name = "OUTPUT_BASE",
            help = "Output path prefix. Defaults to the input path without the .replay suffix"
        )]
        output: Option<PathBuf>,
        #[arg(
            long,
            help = "Also write a compatibility JSON file for older downstream consumers"
        )]
        compat_json: bool,
        #[arg(
            long,
            help = "Skip raw property events to keep output smaller and easier to inspect"
        )]
        no_properties: bool,
    },
    #[command(about = "Read a .replay file and print a summary")]
    #[command(after_help = INSPECT_AFTER_HELP)]
    Inspect {
        #[arg(value_name = "REPLAY", help = "Path to the .replay file to inspect")]
        input: PathBuf,
        #[arg(
            long,
            help = "Skip raw property events to keep output smaller and easier to inspect"
        )]
        no_properties: bool,
    },
    #[command(about = "Read an existing sqrj or sqrb bundle and print a summary")]
    #[command(after_help = SHOW_AFTER_HELP)]
    Show {
        #[arg(value_name = "BUNDLE", help = "Path to a .sqrj.json or .sqrb bundle")]
        input: PathBuf,
    },
    #[command(about = "Expand an sqrb bundle into section JSON files")]
    #[command(after_help = UNPACK_AFTER_HELP)]
    Unpack {
        #[arg(value_name = "BUNDLE", help = "Path to the .sqrb bundle to unpack")]
        input: PathBuf,
        #[arg(
            long,
            short = 'o',
            value_name = "OUTPUT_DIR",
            help = "Directory to write the unpacked JSON sections into"
        )]
        output: PathBuf,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputFormat {
    Sqrj,
    Sqrb,
}

#[derive(Debug, Clone, Default)]
struct OutputSelection {
    sqrj: bool,
    sqrb: bool,
}

impl OutputSelection {
    fn parse_csv(input: &str) -> std::result::Result<Self, String> {
        let mut out = Self::default();
        for part in input.split(',').map(|s| s.trim().to_ascii_lowercase()) {
            match part.as_str() {
                "" => {}
                "sqrj" => out.sqrj = true,
                "sqrb" => out.sqrb = true,
                other => return Err(format!("unsupported format `{other}`")),
            }
        }
        if !out.sqrj && !out.sqrb {
            return Err("at least one format must be selected".to_string());
        }
        Ok(out)
    }

    fn iter(&self) -> std::vec::IntoIter<OutputFormat> {
        let mut formats = Vec::new();
        if self.sqrj {
            formats.push(OutputFormat::Sqrj);
        }
        if self.sqrb {
            formats.push(OutputFormat::Sqrb);
        }
        formats.into_iter()
    }
}

#[derive(Debug, Clone, Default)]
struct WrittenOutputs {
    sqrj: Option<PathBuf>,
    sqrb: Option<PathBuf>,
    compat_json: Option<PathBuf>,
}

#[derive(Debug, Serialize)]
struct BundleSummary<'a> {
    input: &'a str,
    map_name: Option<&'a str>,
    squad_version: Option<&'a str>,
    duration_ms: u64,
    teams: usize,
    squads: usize,
    players: usize,
    vehicles: usize,
    helicopters: usize,
    deployables: usize,
    components: usize,
    player_tracks: usize,
    vehicle_tracks: usize,
    helicopter_tracks: usize,
    kills: usize,
    deployments: usize,
    seat_changes: usize,
    component_states: usize,
    vehicle_states: usize,
    weapon_states: usize,
    property_events: usize,
    frames_processed: u64,
    packets_processed: u64,
    actor_opens: u64,
}

fn default_output_base(input: &Path) -> PathBuf {
    match (input.parent(), input.file_stem()) {
        (Some(parent), Some(stem)) => parent.join(stem),
        _ => input.with_extension(""),
    }
}

fn output_path_with_suffix(base: impl AsRef<Path>, suffix: &str) -> PathBuf {
    let mut path = base.as_ref().as_os_str().to_os_string();
    path.push(suffix);
    PathBuf::from(path)
}

fn path_text(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

fn written_outputs_json(written: &WrittenOutputs) -> serde_json::Value {
    serde_json::json!({
        "sqrj": written.sqrj.as_deref().map(path_text),
        "sqrb": written.sqrb.as_deref().map(path_text),
        "compat_json": written.compat_json.as_deref().map(path_text),
    })
}

fn io_err(path: impl AsRef<Path>, source: std::io::Error) -> Error {
    Error::Io {
        path: path.as_ref().to_path_buf(),
        source,
    }
}

fn write_outputs(
    bundle: &Bundle,
    formats: &OutputSelection,
    output_base: &Path,
    write_compat: bool,
) -> Result<WrittenOutputs> {
    if let Some(parent) = output_base.parent() {
        fs::create_dir_all(parent).map_err(|source| io_err(parent, source))?;
    }

    let mut written = WrittenOutputs::default();
    for format in formats.iter() {
        match format {
            OutputFormat::Sqrj => {
                let path = output_path_with_suffix(output_base, ".sqrj.json");
                sqrj::write(bundle, &path)?;
                written.sqrj = Some(path);
            }
            OutputFormat::Sqrb => {
                let path = output_path_with_suffix(output_base, ".sqrb");
                sqrb::write(bundle, &path)?;
                written.sqrb = Some(path);
            }
        }
    }

    if write_compat {
        let path = output_path_with_suffix(output_base, ".compat-match.json");
        let file = File::create(&path).map_err(|source| io_err(&path, source))?;
        let mut writer = BufWriter::new(file);
        serde_json::to_writer_pretty(&mut writer, &compat::from_bundle(bundle))?;
        // Explicit flush: `BufWriter::drop` swallows flush errors; without
        // this we could report success while leaving a truncated file.
        writer.flush().map_err(|source| io_err(&path, source))?;
        written.compat_json = Some(path);
    }

    Ok(written)
}

fn summarize<'a>(input: &'a str, bundle: &'a Bundle) -> BundleSummary<'a> {
    BundleSummary {
        input,
        map_name: bundle.replay.map_name.as_deref(),
        squad_version: bundle.replay.squad_version.as_deref(),
        duration_ms: bundle.replay.duration_ms,
        teams: bundle.teams.len(),
        squads: bundle.squads.len(),
        players: bundle.players.len(),
        vehicles: bundle.actors.vehicles.len(),
        helicopters: bundle.actors.helicopters.len(),
        deployables: bundle.actors.deployables.len(),
        components: bundle.actors.components.len(),
        player_tracks: bundle.tracks.players.len(),
        vehicle_tracks: bundle.tracks.vehicles.len(),
        helicopter_tracks: bundle.tracks.helicopters.len(),
        kills: bundle.events.kills.len(),
        deployments: bundle.events.deployments.len(),
        seat_changes: bundle.events.seat_changes.len(),
        component_states: bundle.events.component_states.len(),
        vehicle_states: bundle.events.vehicle_states.len(),
        weapon_states: bundle.events.weapon_states.len(),
        property_events: bundle.events.properties.len(),
        frames_processed: bundle.diagnostics.frames_processed,
        packets_processed: bundle.diagnostics.packets_processed,
        actor_opens: bundle.diagnostics.actor_opens,
    }
}

fn option_text(value: Option<&str>) -> &str {
    value.unwrap_or("unknown")
}

fn format_duration(duration_ms: u64) -> String {
    let total_seconds = duration_ms / 1000;
    let hours = total_seconds / 3600;
    let minutes = (total_seconds % 3600) / 60;
    let seconds = total_seconds % 60;

    if hours > 0 {
        format!("{hours}:{minutes:02}:{seconds:02}")
    } else {
        format!("{minutes}:{seconds:02}")
    }
}

fn render_summary_text(title: &str, summary: &BundleSummary<'_>) -> String {
    [
        title.to_string(),
        format!("Input: {}", summary.input),
        format!("Map: {}", option_text(summary.map_name)),
        format!("Squad version: {}", option_text(summary.squad_version)),
        format!("Duration: {}", format_duration(summary.duration_ms)),
        format!(
            "Entities: {} teams, {} squads, {} players",
            summary.teams, summary.squads, summary.players
        ),
        format!(
            "Actors: {} vehicles, {} helicopters, {} deployables, {} components",
            summary.vehicles, summary.helicopters, summary.deployables, summary.components
        ),
        format!(
            "Tracks: {} player, {} vehicle, {} helicopter",
            summary.player_tracks, summary.vehicle_tracks, summary.helicopter_tracks
        ),
        format!(
            "Events: {} kills, {} deployments, {} seat changes, {} property events",
            summary.kills, summary.deployments, summary.seat_changes, summary.property_events
        ),
        format!(
            "Diagnostics: {} frames, {} packets, {} actor opens",
            summary.frames_processed, summary.packets_processed, summary.actor_opens
        ),
    ]
    .join("\n")
}

fn render_written_outputs(written: &WrittenOutputs) -> Vec<String> {
    let mut lines = Vec::new();

    if let Some(path) = written.sqrj.as_ref() {
        lines.push(format!("  - {}", path_text(path)));
    }
    if let Some(path) = written.sqrb.as_ref() {
        lines.push(format!("  - {}", path_text(path)));
    }
    if let Some(path) = written.compat_json.as_ref() {
        lines.push(format!("  - {}", path_text(path)));
    }

    lines
}

fn render_parse_text(
    input: &Path,
    output_base: &Path,
    written: &WrittenOutputs,
    bundle: &Bundle,
) -> String {
    let input_display = path_text(input);
    let summary = summarize(&input_display, bundle);
    let mut lines = vec![
        "Replay converted".to_string(),
        format!("Input: {}", path_text(input)),
        format!("Output base: {}", path_text(output_base)),
        format!("Map: {}", option_text(summary.map_name)),
        format!("Squad version: {}", option_text(summary.squad_version)),
        format!("Duration: {}", format_duration(summary.duration_ms)),
        format!(
            "Entities: {} teams, {} squads, {} players",
            summary.teams, summary.squads, summary.players
        ),
        format!(
            "Events: {} kills, {} deployments, {} seat changes, {} property events",
            summary.kills, summary.deployments, summary.seat_changes, summary.property_events
        ),
        "Wrote:".to_string(),
    ];
    lines.extend(render_written_outputs(written));
    lines.join("\n")
}

fn render_unpack_text(input: &Path, output: &Path) -> String {
    [
        "Bundle unpacked".to_string(),
        format!("Input: {}", path_text(input)),
        format!("Output directory: {}", path_text(output)),
    ]
    .join("\n")
}

fn print_json<T: Serialize>(value: &T) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

fn print_parse_result_json(
    input: &Path,
    output_base: &Path,
    written: &WrittenOutputs,
    bundle: &Bundle,
) -> Result<()> {
    let compat_preview = compat::from_bundle(bundle);
    let input_display = path_text(input);
    print_json(&serde_json::json!({
        "input": path_text(input),
        "outputBase": path_text(output_base),
        "written": written_outputs_json(written),
        "summary": summarize(&input_display, bundle),
        "compatPreview": {
            "mapName": compat_preview.map_name,
            "squadVersion": compat_preview.squad_version,
            "matchDurationSeconds": compat_preview.match_duration_seconds,
            "kills": compat_preview.kills.len(),
            "positionsPerSecond": compat_preview.positions_per_second.len(),
            "vehiclePositionsPerSecond": compat_preview.vehicle_positions_per_second.len(),
            "deployableEvents": compat_preview.deployable_events.len(),
        }
    }))
}

pub fn run() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Command::Parse {
            input,
            format,
            output,
            compat_json,
            no_properties,
        } => {
            let formats = OutputSelection::parse_csv(&format).map_err(Error::Message)?;
            let output_base = output.unwrap_or_else(|| default_output_base(&input));
            let options = ParseOptions {
                include_property_events: !no_properties,
            };
            let bundle = parse_file(&input, &options)?;
            let written = write_outputs(&bundle, &formats, &output_base, compat_json)?;

            if cli.json {
                print_parse_result_json(&input, &output_base, &written, &bundle)
            } else {
                println!(
                    "{}",
                    render_parse_text(&input, &output_base, &written, &bundle)
                );
                Ok(())
            }
        }
        Command::Inspect {
            input,
            no_properties,
        } => {
            let options = ParseOptions {
                include_property_events: !no_properties,
            };
            let bundle = parse_file(&input, &options)?;
            let input_display = path_text(&input);
            let summary = summarize(&input_display, &bundle);

            if cli.json {
                print_json(&summary)
            } else {
                println!("{}", render_summary_text("Replay summary", &summary));
                Ok(())
            }
        }
        Command::Show { input } => {
            let bundle = read_bundle(&input)?;
            let input_display = path_text(&input);
            let summary = summarize(&input_display, &bundle);

            if cli.json {
                print_json(&summary)
            } else {
                println!("{}", render_summary_text("Bundle summary", &summary));
                Ok(())
            }
        }
        Command::Unpack { input, output } => {
            sqrb::unpack(&input, &output)?;

            if cli.json {
                print_json(&serde_json::json!({
                    "input": path_text(&input),
                    "output": path_text(&output),
                    "status": "ok"
                }))
            } else {
                println!("{}", render_unpack_text(&input, &output));
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use squadreplay::bundle::{
        ActorEntity, ActorGroups, ComponentEntity, ComponentStateEvent, DeploymentEvent,
        Diagnostics, EventGroups, KillEvent, ReplayInfoSection, SeatChangeEvent, Track3,
        TrackGroups, VehicleStateEvent, WeaponStateEvent,
    };

    fn sample_bundle() -> Bundle {
        Bundle {
            replay: ReplayInfoSection {
                map_name: Some("Jensen's Range".to_string()),
                squad_version: Some("8.1.0".to_string()),
                duration_ms: 2_146_000,
                ..ReplayInfoSection::default()
            },
            teams: vec![Default::default(), Default::default()],
            squads: vec![Default::default(); 6],
            players: vec![Default::default(); 72],
            actors: ActorGroups {
                vehicles: vec![ActorEntity::default(); 12],
                helicopters: vec![ActorEntity::default(); 2],
                deployables: vec![ActorEntity::default(); 18],
                components: vec![ComponentEntity::default(); 44],
            },
            tracks: TrackGroups {
                players: vec![Track3::default(); 40],
                vehicles: vec![Track3::default(); 11],
                helicopters: vec![Track3::default(); 2],
            },
            events: EventGroups {
                kills: vec![KillEvent::default(); 15],
                deployments: vec![DeploymentEvent::default(); 9],
                seat_changes: vec![SeatChangeEvent::default(); 6],
                component_states: vec![ComponentStateEvent::default(); 5],
                vehicle_states: vec![VehicleStateEvent::default(); 7],
                weapon_states: vec![WeaponStateEvent::default(); 4],
                properties: vec![Default::default(); 125],
            },
            diagnostics: Diagnostics {
                frames_processed: 3_220,
                packets_processed: 8_441,
                actor_opens: 381,
                ..Diagnostics::default()
            },
            ..Bundle::default()
        }
    }

    #[test]
    fn summary_rendering_stays_readable() {
        let bundle = sample_bundle();
        let summary = summarize("match.replay", &bundle);
        let rendered = render_summary_text("Replay summary", &summary);

        assert!(rendered.contains("Replay summary"));
        assert!(rendered.contains("Input: match.replay"));
        assert!(rendered.contains("Map: Jensen's Range"));
        assert!(rendered.contains("Duration: 35:46"));
        assert!(rendered.contains("Entities: 2 teams, 6 squads, 72 players"));
        assert!(
            rendered
                .contains("Events: 15 kills, 9 deployments, 6 seat changes, 125 property events")
        );
    }

    #[cfg(unix)]
    #[test]
    fn output_suffix_preserves_non_utf8_paths() {
        use std::ffi::OsString;
        use std::os::unix::ffi::{OsStrExt, OsStringExt};

        let base = PathBuf::from(OsString::from_vec(b"match-\xFF".to_vec()));
        let output = output_path_with_suffix(&base, ".sqrb");

        assert_eq!(
            output
                .file_name()
                .expect("path should have a file name")
                .as_bytes(),
            b"match-\xFF.sqrb"
        );
    }
}